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 UiFocus,
62 UiInvalidate,
63 UiLog,
64 UiNotify,
65 UiNotifyCancel,
66 UiPanes,
67 UiPlaced,
68 UiScroll,
69 UiStatus,
70 UiToast,
71 Unknown(String),
73}
74
75impl SystemSubtype {
76 pub fn as_str(&self) -> &str {
77 match self {
78 Self::Init => "init",
79 Self::Status => "status",
80 Self::CompactBoundary => "compact_boundary",
81 Self::ThinkingTokens => "thinking_tokens",
82 Self::TaskStarted => "task_started",
83 Self::TaskProgress => "task_progress",
84 Self::TaskUpdated => "task_updated",
85 Self::TaskNotification => "task_notification",
86 Self::ApiRetry => "api_retry",
87 Self::ControlRequestProgress => "control_request_progress",
88 Self::ModelRefusalFallback => "model_refusal_fallback",
89 Self::ModelRefusalNoFallback => "model_refusal_no_fallback",
90 Self::LocalCommandOutput => "local_command_output",
91 Self::HookStarted => "hook_started",
92 Self::HookProgress => "hook_progress",
93 Self::HookResponse => "hook_response",
94 Self::PluginInstall => "plugin_install",
95 Self::BackgroundTasksChanged => "background_tasks_changed",
96 Self::SessionStateChanged => "session_state_changed",
97 Self::WorkerShuttingDown => "worker_shutting_down",
98 Self::CommandsChanged => "commands_changed",
99 Self::Notification => "notification",
100 Self::FilesPersisted => "files_persisted",
101 Self::MemoryRecall => "memory_recall",
102 Self::ElicitationComplete => "elicitation_complete",
103 Self::PermissionDenied => "permission_denied",
104 Self::MirrorError => "mirror_error",
105 Self::Informational => "informational",
106 Self::CodeChangePublished => "code_change_published",
107 Self::VcsStateChanged => "vcs_state_changed",
108 Self::FeedbackDraftQueued => "feedback_draft_queued",
109 Self::CloudSessionDelta => "cloud_session_delta",
110 Self::DevIntent => "dev_intent",
111 Self::TurnHandoffAvailable => "turn_handoff_available",
112 Self::TurnPreempted => "turn_preempted",
113 Self::PeerMessageHold => "peer_message_hold",
114 Self::PerTurnEffortChanged => "per_turn_effort_changed",
115 Self::SessionTitleChanged => "session_title_changed",
116 Self::SessionWritesLost => "session_writes_lost",
117 Self::InstructionSizeWarning => "instruction_size_warning",
118 Self::FileAttachmentsMissing => "file_attachments_missing",
119 Self::PermissionCheckStatus => "permission_check_status",
120 Self::InheritedAsksSettled => "inherited_asks_settled",
121 Self::LateAllowNotRun => "late_allow_not_run",
122 Self::UiFocus => "ui_focus",
123 Self::UiInvalidate => "ui_invalidate",
124 Self::UiLog => "ui_log",
125 Self::UiNotify => "ui_notify",
126 Self::UiNotifyCancel => "ui_notify_cancel",
127 Self::UiPanes => "ui_panes",
128 Self::UiPlaced => "ui_placed",
129 Self::UiScroll => "ui_scroll",
130 Self::UiStatus => "ui_status",
131 Self::UiToast => "ui_toast",
132 Self::Unknown(s) => s.as_str(),
133 }
134 }
135}
136
137impl fmt::Display for SystemSubtype {
138 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139 f.write_str(self.as_str())
140 }
141}
142
143impl From<&str> for SystemSubtype {
144 fn from(s: &str) -> Self {
145 match s {
146 "init" => Self::Init,
147 "status" => Self::Status,
148 "compact_boundary" => Self::CompactBoundary,
149 "thinking_tokens" => Self::ThinkingTokens,
150 "task_started" => Self::TaskStarted,
151 "task_progress" => Self::TaskProgress,
152 "task_updated" => Self::TaskUpdated,
153 "task_notification" => Self::TaskNotification,
154 "api_retry" => Self::ApiRetry,
155 "control_request_progress" => Self::ControlRequestProgress,
156 "model_refusal_fallback" => Self::ModelRefusalFallback,
157 "model_refusal_no_fallback" => Self::ModelRefusalNoFallback,
158 "local_command_output" => Self::LocalCommandOutput,
159 "hook_started" => Self::HookStarted,
160 "hook_progress" => Self::HookProgress,
161 "hook_response" => Self::HookResponse,
162 "plugin_install" => Self::PluginInstall,
163 "background_tasks_changed" => Self::BackgroundTasksChanged,
164 "session_state_changed" => Self::SessionStateChanged,
165 "worker_shutting_down" => Self::WorkerShuttingDown,
166 "commands_changed" => Self::CommandsChanged,
167 "notification" => Self::Notification,
168 "files_persisted" => Self::FilesPersisted,
169 "memory_recall" => Self::MemoryRecall,
170 "elicitation_complete" => Self::ElicitationComplete,
171 "permission_denied" => Self::PermissionDenied,
172 "mirror_error" => Self::MirrorError,
173 "informational" => Self::Informational,
174 "code_change_published" => Self::CodeChangePublished,
175 "vcs_state_changed" => Self::VcsStateChanged,
176 "feedback_draft_queued" => Self::FeedbackDraftQueued,
177 "cloud_session_delta" => Self::CloudSessionDelta,
178 "dev_intent" => Self::DevIntent,
179 "turn_handoff_available" => Self::TurnHandoffAvailable,
180 "turn_preempted" => Self::TurnPreempted,
181 "peer_message_hold" => Self::PeerMessageHold,
182 "per_turn_effort_changed" => Self::PerTurnEffortChanged,
183 "session_title_changed" => Self::SessionTitleChanged,
184 "session_writes_lost" => Self::SessionWritesLost,
185 "instruction_size_warning" => Self::InstructionSizeWarning,
186 "file_attachments_missing" => Self::FileAttachmentsMissing,
187 "permission_check_status" => Self::PermissionCheckStatus,
188 "inherited_asks_settled" => Self::InheritedAsksSettled,
189 "late_allow_not_run" => Self::LateAllowNotRun,
190 "ui_focus" => Self::UiFocus,
191 "ui_invalidate" => Self::UiInvalidate,
192 "ui_log" => Self::UiLog,
193 "ui_notify" => Self::UiNotify,
194 "ui_notify_cancel" => Self::UiNotifyCancel,
195 "ui_panes" => Self::UiPanes,
196 "ui_placed" => Self::UiPlaced,
197 "ui_scroll" => Self::UiScroll,
198 "ui_status" => Self::UiStatus,
199 "ui_toast" => Self::UiToast,
200 other => Self::Unknown(other.to_string()),
201 }
202 }
203}
204
205impl Serialize for SystemSubtype {
206 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
207 serializer.serialize_str(self.as_str())
208 }
209}
210
211impl<'de> Deserialize<'de> for SystemSubtype {
212 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
213 let s = String::deserialize(deserializer)?;
214 Ok(Self::from(s.as_str()))
215 }
216}
217
218#[derive(Debug, Clone, PartialEq, Eq, Hash)]
223pub enum MessageRole {
224 User,
225 Assistant,
226 Unknown(String),
228}
229
230impl MessageRole {
231 pub fn as_str(&self) -> &str {
232 match self {
233 Self::User => "user",
234 Self::Assistant => "assistant",
235 Self::Unknown(s) => s.as_str(),
236 }
237 }
238}
239
240impl fmt::Display for MessageRole {
241 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
242 f.write_str(self.as_str())
243 }
244}
245
246impl From<&str> for MessageRole {
247 fn from(s: &str) -> Self {
248 match s {
249 "user" => Self::User,
250 "assistant" => Self::Assistant,
251 other => Self::Unknown(other.to_string()),
252 }
253 }
254}
255
256impl Serialize for MessageRole {
257 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
258 serializer.serialize_str(self.as_str())
259 }
260}
261
262impl<'de> Deserialize<'de> for MessageRole {
263 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
264 let s = String::deserialize(deserializer)?;
265 Ok(Self::from(s.as_str()))
266 }
267}
268
269#[derive(Debug, Clone, PartialEq, Eq, Hash)]
271pub enum CompactionTrigger {
272 Auto,
274 Manual,
276 Unknown(String),
278}
279
280impl CompactionTrigger {
281 pub fn as_str(&self) -> &str {
282 match self {
283 Self::Auto => "auto",
284 Self::Manual => "manual",
285 Self::Unknown(s) => s.as_str(),
286 }
287 }
288}
289
290impl fmt::Display for CompactionTrigger {
291 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
292 f.write_str(self.as_str())
293 }
294}
295
296impl From<&str> for CompactionTrigger {
297 fn from(s: &str) -> Self {
298 match s {
299 "auto" => Self::Auto,
300 "manual" => Self::Manual,
301 other => Self::Unknown(other.to_string()),
302 }
303 }
304}
305
306impl Serialize for CompactionTrigger {
307 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
308 serializer.serialize_str(self.as_str())
309 }
310}
311
312impl<'de> Deserialize<'de> for CompactionTrigger {
313 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
314 let s = String::deserialize(deserializer)?;
315 Ok(Self::from(s.as_str()))
316 }
317}
318
319#[derive(Debug, Clone, PartialEq, Eq, Hash)]
321pub enum StopReason {
322 EndTurn,
324 MaxTokens,
326 ToolUse,
328 Unknown(String),
330}
331
332impl StopReason {
333 pub fn as_str(&self) -> &str {
334 match self {
335 Self::EndTurn => "end_turn",
336 Self::MaxTokens => "max_tokens",
337 Self::ToolUse => "tool_use",
338 Self::Unknown(s) => s.as_str(),
339 }
340 }
341}
342
343impl fmt::Display for StopReason {
344 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
345 f.write_str(self.as_str())
346 }
347}
348
349impl From<&str> for StopReason {
350 fn from(s: &str) -> Self {
351 match s {
352 "end_turn" => Self::EndTurn,
353 "max_tokens" => Self::MaxTokens,
354 "tool_use" => Self::ToolUse,
355 other => Self::Unknown(other.to_string()),
356 }
357 }
358}
359
360impl Serialize for StopReason {
361 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
362 serializer.serialize_str(self.as_str())
363 }
364}
365
366impl<'de> Deserialize<'de> for StopReason {
367 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
368 let s = String::deserialize(deserializer)?;
369 Ok(Self::from(s.as_str()))
370 }
371}
372
373#[derive(Debug, Clone, PartialEq, Eq, Hash)]
375pub enum ApiKeySource {
376 None,
378 User,
379 Project,
380 Org,
381 Temporary,
382 Oauth,
383 Unknown(String),
385}
386
387impl ApiKeySource {
388 pub fn as_str(&self) -> &str {
389 match self {
390 Self::None => "none",
391 Self::User => "user",
392 Self::Project => "project",
393 Self::Org => "org",
394 Self::Temporary => "temporary",
395 Self::Oauth => "oauth",
396 Self::Unknown(s) => s.as_str(),
397 }
398 }
399}
400
401impl fmt::Display for ApiKeySource {
402 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
403 f.write_str(self.as_str())
404 }
405}
406
407impl From<&str> for ApiKeySource {
408 fn from(s: &str) -> Self {
409 match s {
410 "none" => Self::None,
411 "user" => Self::User,
412 "project" => Self::Project,
413 "org" => Self::Org,
414 "temporary" => Self::Temporary,
415 "oauth" => Self::Oauth,
416 other => Self::Unknown(other.to_string()),
417 }
418 }
419}
420
421impl Serialize for ApiKeySource {
422 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
423 serializer.serialize_str(self.as_str())
424 }
425}
426
427impl<'de> Deserialize<'de> for ApiKeySource {
428 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
429 let s = String::deserialize(deserializer)?;
430 Ok(Self::from(s.as_str()))
431 }
432}
433
434#[derive(Debug, Clone, PartialEq, Eq, Hash)]
436pub enum OutputStyle {
437 Default,
439 Unknown(String),
441}
442
443impl OutputStyle {
444 pub fn as_str(&self) -> &str {
445 match self {
446 Self::Default => "default",
447 Self::Unknown(s) => s.as_str(),
448 }
449 }
450}
451
452impl fmt::Display for OutputStyle {
453 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
454 f.write_str(self.as_str())
455 }
456}
457
458impl From<&str> for OutputStyle {
459 fn from(s: &str) -> Self {
460 match s {
461 "default" => Self::Default,
462 other => Self::Unknown(other.to_string()),
463 }
464 }
465}
466
467impl Serialize for OutputStyle {
468 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
469 serializer.serialize_str(self.as_str())
470 }
471}
472
473impl<'de> Deserialize<'de> for OutputStyle {
474 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
475 let s = String::deserialize(deserializer)?;
476 Ok(Self::from(s.as_str()))
477 }
478}
479
480#[derive(Debug, Clone, PartialEq, Eq, Hash)]
482pub enum InitPermissionMode {
483 Default,
485 AcceptEdits,
486 BypassPermissions,
487 Plan,
488 DontAsk,
489 Auto,
490 Unknown(String),
492}
493
494impl InitPermissionMode {
495 pub fn as_str(&self) -> &str {
496 match self {
497 Self::Default => "default",
498 Self::AcceptEdits => "acceptEdits",
499 Self::BypassPermissions => "bypassPermissions",
500 Self::Plan => "plan",
501 Self::DontAsk => "dontAsk",
502 Self::Auto => "auto",
503 Self::Unknown(s) => s.as_str(),
504 }
505 }
506}
507
508impl fmt::Display for InitPermissionMode {
509 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
510 f.write_str(self.as_str())
511 }
512}
513
514impl From<&str> for InitPermissionMode {
515 fn from(s: &str) -> Self {
516 match s {
517 "default" => Self::Default,
518 "acceptEdits" => Self::AcceptEdits,
519 "bypassPermissions" => Self::BypassPermissions,
520 "plan" => Self::Plan,
521 "dontAsk" => Self::DontAsk,
522 "auto" => Self::Auto,
523 other => Self::Unknown(other.to_string()),
524 }
525 }
526}
527
528impl Serialize for InitPermissionMode {
529 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
530 serializer.serialize_str(self.as_str())
531 }
532}
533
534impl<'de> Deserialize<'de> for InitPermissionMode {
535 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
536 let s = String::deserialize(deserializer)?;
537 Ok(Self::from(s.as_str()))
538 }
539}
540
541#[derive(Debug, Clone, PartialEq, Eq, Hash)]
543pub enum StatusMessageStatus {
544 Compacting,
546 Requesting,
548 Unknown(String),
550}
551
552impl StatusMessageStatus {
553 pub fn as_str(&self) -> &str {
554 match self {
555 Self::Compacting => "compacting",
556 Self::Requesting => "requesting",
557 Self::Unknown(s) => s.as_str(),
558 }
559 }
560}
561
562impl fmt::Display for StatusMessageStatus {
563 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
564 f.write_str(self.as_str())
565 }
566}
567
568impl From<&str> for StatusMessageStatus {
569 fn from(s: &str) -> Self {
570 match s {
571 "compacting" => Self::Compacting,
572 "requesting" => Self::Requesting,
573 other => Self::Unknown(other.to_string()),
574 }
575 }
576}
577
578impl Serialize for StatusMessageStatus {
579 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
580 serializer.serialize_str(self.as_str())
581 }
582}
583
584impl<'de> Deserialize<'de> for StatusMessageStatus {
585 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
586 let s = String::deserialize(deserializer)?;
587 Ok(Self::from(s.as_str()))
588 }
589}
590
591pub(crate) fn serialize_optional_uuid<S>(
593 uuid: &Option<Uuid>,
594 serializer: S,
595) -> Result<S::Ok, S::Error>
596where
597 S: Serializer,
598{
599 match uuid {
600 Some(id) => serializer.serialize_str(&id.to_string()),
601 None => serializer.serialize_none(),
602 }
603}
604
605pub(crate) fn deserialize_optional_uuid<'de, D>(deserializer: D) -> Result<Option<Uuid>, D::Error>
607where
608 D: Deserializer<'de>,
609{
610 let opt_str: Option<String> = Option::deserialize(deserializer)?;
611 match opt_str {
612 Some(s) => Uuid::parse_str(&s)
613 .map(Some)
614 .map_err(serde::de::Error::custom),
615 None => Ok(None),
616 }
617}
618
619#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
622pub struct MessageOrigin {
623 pub kind: String,
624 #[serde(flatten)]
625 pub extra: serde_json::Map<String, Value>,
626}
627
628#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
630pub struct SummarizeMetadata {
631 pub messages_summarized: u64,
632 #[serde(default, skip_serializing_if = "Option::is_none")]
633 pub user_context: Option<String>,
634 #[serde(default, skip_serializing_if = "Option::is_none")]
635 pub direction: Option<String>,
636}
637
638#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
640pub struct McpMeta {
641 #[serde(default, skip_serializing_if = "Option::is_none", rename = "_meta")]
642 pub meta: Option<Value>,
643 #[serde(default, skip_serializing_if = "Option::is_none")]
644 pub structured_content: Option<Value>,
645 #[serde(default, skip_serializing_if = "Vec::is_empty")]
650 pub resource_links: Vec<ResourceLink>,
651}
652
653#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
657pub struct ResourceLink {
658 pub uri: String,
659 pub name: String,
660 #[serde(default, skip_serializing_if = "Option::is_none")]
661 pub title: Option<String>,
662 #[serde(default, skip_serializing_if = "Option::is_none")]
663 pub description: Option<String>,
664 #[serde(default, skip_serializing_if = "Option::is_none", rename = "mimeType")]
665 pub mime_type: Option<String>,
666 #[serde(default, skip_serializing_if = "Option::is_none")]
667 pub size: Option<u64>,
668 #[serde(default, skip_serializing_if = "Option::is_none")]
669 pub annotations: Option<Value>,
670}
671
672#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
674pub struct ToolResultMeta {
675 pub id: String,
677 #[serde(default, skip_serializing_if = "Option::is_none")]
684 pub non_execution_kind: Option<String>,
685 #[serde(default, skip_serializing_if = "Option::is_none")]
687 pub user_feedback: Option<String>,
688 #[serde(default, skip_serializing_if = "Option::is_none")]
693 pub remedy: Option<ToolResultRemedy>,
694 #[serde(default, skip_serializing_if = "Option::is_none")]
701 pub permission_decision: Option<ToolPermissionDecision>,
702 #[serde(default, skip_serializing_if = "Option::is_none")]
709 pub built_in_tool: Option<String>,
710 #[serde(default, skip_serializing_if = "Option::is_none")]
717 pub run_input: Option<String>,
718}
719
720#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
724pub struct ToolPermissionDecision {
725 pub decision: PermissionDecisionOutcome,
727 pub source: String,
735 #[serde(default, skip_serializing_if = "Option::is_none")]
741 pub reason_type: Option<PermissionDecisionReasonType>,
742 #[serde(default, skip_serializing_if = "Option::is_none")]
748 pub auto_mode_rule: Option<AutoModeRule>,
749}
750
751#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
754pub struct AutoModeRule {
755 pub list: AutoModeRuleList,
757 pub name: String,
759}
760
761#[derive(Debug, Clone, PartialEq, Eq, Hash)]
763pub enum AutoModeRuleList {
764 Allow,
766 SoftDeny,
768 Unknown(String),
770}
771
772impl AutoModeRuleList {
773 pub fn as_str(&self) -> &str {
774 match self {
775 Self::Allow => "allow",
776 Self::SoftDeny => "soft_deny",
777 Self::Unknown(s) => s.as_str(),
778 }
779 }
780}
781
782impl fmt::Display for AutoModeRuleList {
783 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
784 f.write_str(self.as_str())
785 }
786}
787
788impl From<&str> for AutoModeRuleList {
789 fn from(s: &str) -> Self {
790 match s {
791 "allow" => Self::Allow,
792 "soft_deny" => Self::SoftDeny,
793 other => Self::Unknown(other.to_string()),
794 }
795 }
796}
797
798impl Serialize for AutoModeRuleList {
799 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
800 serializer.serialize_str(self.as_str())
801 }
802}
803
804impl<'de> Deserialize<'de> for AutoModeRuleList {
805 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
806 let s = String::deserialize(deserializer)?;
807 Ok(Self::from(s.as_str()))
808 }
809}
810
811#[derive(Debug, Clone, PartialEq, Eq, Hash)]
813pub enum PermissionDecisionOutcome {
814 Accept,
816 Reject,
818 Cancelled,
820 Unknown(String),
822}
823
824impl PermissionDecisionOutcome {
825 pub fn as_str(&self) -> &str {
826 match self {
827 Self::Accept => "accept",
828 Self::Reject => "reject",
829 Self::Cancelled => "cancelled",
830 Self::Unknown(s) => s.as_str(),
831 }
832 }
833}
834
835impl fmt::Display for PermissionDecisionOutcome {
836 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
837 f.write_str(self.as_str())
838 }
839}
840
841impl From<&str> for PermissionDecisionOutcome {
842 fn from(s: &str) -> Self {
843 match s {
844 "accept" => Self::Accept,
845 "reject" => Self::Reject,
846 "cancelled" => Self::Cancelled,
847 other => Self::Unknown(other.to_string()),
848 }
849 }
850}
851
852impl Serialize for PermissionDecisionOutcome {
853 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
854 serializer.serialize_str(self.as_str())
855 }
856}
857
858impl<'de> Deserialize<'de> for PermissionDecisionOutcome {
859 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
860 let s = String::deserialize(deserializer)?;
861 Ok(Self::from(s.as_str()))
862 }
863}
864
865#[derive(Debug, Clone, PartialEq, Eq, Hash)]
868pub enum PermissionDecisionReasonType {
869 Rule,
871 Mode,
873 SubcommandResults,
875 PermissionPromptTool,
877 Hook,
879 AsyncAgent,
881 SandboxOverride,
883 WorkingDir,
885 SafetyCheck,
887 Classifier,
889 Other,
891 Unknown(String),
893}
894
895impl PermissionDecisionReasonType {
896 pub fn as_str(&self) -> &str {
897 match self {
898 Self::Rule => "rule",
899 Self::Mode => "mode",
900 Self::SubcommandResults => "subcommandResults",
901 Self::PermissionPromptTool => "permissionPromptTool",
902 Self::Hook => "hook",
903 Self::AsyncAgent => "asyncAgent",
904 Self::SandboxOverride => "sandboxOverride",
905 Self::WorkingDir => "workingDir",
906 Self::SafetyCheck => "safetyCheck",
907 Self::Classifier => "classifier",
908 Self::Other => "other",
909 Self::Unknown(s) => s.as_str(),
910 }
911 }
912}
913
914impl fmt::Display for PermissionDecisionReasonType {
915 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
916 f.write_str(self.as_str())
917 }
918}
919
920impl From<&str> for PermissionDecisionReasonType {
921 fn from(s: &str) -> Self {
922 match s {
923 "rule" => Self::Rule,
924 "mode" => Self::Mode,
925 "subcommandResults" => Self::SubcommandResults,
926 "permissionPromptTool" => Self::PermissionPromptTool,
927 "hook" => Self::Hook,
928 "asyncAgent" => Self::AsyncAgent,
929 "sandboxOverride" => Self::SandboxOverride,
930 "workingDir" => Self::WorkingDir,
931 "safetyCheck" => Self::SafetyCheck,
932 "classifier" => Self::Classifier,
933 "other" => Self::Other,
934 other => Self::Unknown(other.to_string()),
935 }
936 }
937}
938
939impl Serialize for PermissionDecisionReasonType {
940 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
941 serializer.serialize_str(self.as_str())
942 }
943}
944
945impl<'de> Deserialize<'de> for PermissionDecisionReasonType {
946 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
947 let s = String::deserialize(deserializer)?;
948 Ok(Self::from(s.as_str()))
949 }
950}
951
952#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
957pub struct ToolResultRemedy {
958 pub kind: ToolResultRemedyKind,
961 #[serde(default, skip_serializing_if = "Option::is_none")]
965 pub servers: Option<Vec<String>>,
966 #[serde(default, skip_serializing_if = "Option::is_none")]
969 pub provider: Option<RemedyLoginProvider>,
970 #[serde(default, skip_serializing_if = "Option::is_none")]
974 pub path: Option<String>,
975 #[serde(default, skip_serializing_if = "Option::is_none")]
980 pub managed: Option<bool>,
981 #[serde(default, skip_serializing_if = "Option::is_none")]
983 pub feature: Option<RemedyFeature>,
984 #[serde(default, skip_serializing_if = "Option::is_none")]
986 pub cause: Option<RemedyFeatureCause>,
987 #[serde(default, skip_serializing_if = "Option::is_none")]
989 pub policy_kind: Option<RemedyPolicyKind>,
990}
991
992#[derive(Debug, Clone, PartialEq, Eq, Hash)]
994pub enum ToolResultRemedyKind {
995 McpNeedsAuth,
997 McpDisabled,
999 McpRequiredMissing,
1001 AuthExpired,
1003 AuthOverridden,
1005 AuthMissingScope,
1007 DesignNeedsAuthorization,
1009 SandboxViolation,
1011 OutsideReadsBlocked,
1013 MemoryPaused,
1015 FeatureDisabled,
1017 PolicyDenied,
1020 SpawnArgLimit,
1022 StagedForReview,
1024 Unknown(String),
1026}
1027
1028impl ToolResultRemedyKind {
1029 pub fn as_str(&self) -> &str {
1030 match self {
1031 Self::McpNeedsAuth => "mcp_needs_auth",
1032 Self::McpDisabled => "mcp_disabled",
1033 Self::McpRequiredMissing => "mcp_required_missing",
1034 Self::AuthExpired => "auth_expired",
1035 Self::AuthOverridden => "auth_overridden",
1036 Self::AuthMissingScope => "auth_missing_scope",
1037 Self::DesignNeedsAuthorization => "design_needs_authorization",
1038 Self::SandboxViolation => "sandbox_violation",
1039 Self::OutsideReadsBlocked => "outside_reads_blocked",
1040 Self::MemoryPaused => "memory_paused",
1041 Self::FeatureDisabled => "feature_disabled",
1042 Self::PolicyDenied => "policy_denied",
1043 Self::SpawnArgLimit => "spawn_arg_limit",
1044 Self::StagedForReview => "staged_for_review",
1045 Self::Unknown(s) => s.as_str(),
1046 }
1047 }
1048}
1049
1050impl fmt::Display for ToolResultRemedyKind {
1051 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1052 f.write_str(self.as_str())
1053 }
1054}
1055
1056impl From<&str> for ToolResultRemedyKind {
1057 fn from(s: &str) -> Self {
1058 match s {
1059 "mcp_needs_auth" => Self::McpNeedsAuth,
1060 "mcp_disabled" => Self::McpDisabled,
1061 "mcp_required_missing" => Self::McpRequiredMissing,
1062 "auth_expired" => Self::AuthExpired,
1063 "auth_overridden" => Self::AuthOverridden,
1064 "auth_missing_scope" => Self::AuthMissingScope,
1065 "design_needs_authorization" => Self::DesignNeedsAuthorization,
1066 "sandbox_violation" => Self::SandboxViolation,
1067 "outside_reads_blocked" => Self::OutsideReadsBlocked,
1068 "memory_paused" => Self::MemoryPaused,
1069 "feature_disabled" => Self::FeatureDisabled,
1070 "policy_denied" => Self::PolicyDenied,
1071 "spawn_arg_limit" => Self::SpawnArgLimit,
1072 "staged_for_review" => Self::StagedForReview,
1073 other => Self::Unknown(other.to_string()),
1074 }
1075 }
1076}
1077
1078impl Serialize for ToolResultRemedyKind {
1079 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1080 serializer.serialize_str(self.as_str())
1081 }
1082}
1083
1084impl<'de> Deserialize<'de> for ToolResultRemedyKind {
1085 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1086 let s = String::deserialize(deserializer)?;
1087 Ok(Self::from(s.as_str()))
1088 }
1089}
1090
1091#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1093pub enum RemedyLoginProvider {
1094 ClaudeAi,
1096 ClaudeDesign,
1098 Unknown(String),
1100}
1101
1102impl RemedyLoginProvider {
1103 pub fn as_str(&self) -> &str {
1104 match self {
1105 Self::ClaudeAi => "claude_ai",
1106 Self::ClaudeDesign => "claude_design",
1107 Self::Unknown(s) => s.as_str(),
1108 }
1109 }
1110}
1111
1112impl fmt::Display for RemedyLoginProvider {
1113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1114 f.write_str(self.as_str())
1115 }
1116}
1117
1118impl From<&str> for RemedyLoginProvider {
1119 fn from(s: &str) -> Self {
1120 match s {
1121 "claude_ai" => Self::ClaudeAi,
1122 "claude_design" => Self::ClaudeDesign,
1123 other => Self::Unknown(other.to_string()),
1124 }
1125 }
1126}
1127
1128impl Serialize for RemedyLoginProvider {
1129 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1130 serializer.serialize_str(self.as_str())
1131 }
1132}
1133
1134impl<'de> Deserialize<'de> for RemedyLoginProvider {
1135 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1136 let s = String::deserialize(deserializer)?;
1137 Ok(Self::from(s.as_str()))
1138 }
1139}
1140
1141#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1144pub enum RemedyFeature {
1145 Workflows,
1146 Artifacts,
1147 Unknown(String),
1149}
1150
1151impl RemedyFeature {
1152 pub fn as_str(&self) -> &str {
1153 match self {
1154 Self::Workflows => "workflows",
1155 Self::Artifacts => "artifacts",
1156 Self::Unknown(s) => s.as_str(),
1157 }
1158 }
1159}
1160
1161impl fmt::Display for RemedyFeature {
1162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1163 f.write_str(self.as_str())
1164 }
1165}
1166
1167impl From<&str> for RemedyFeature {
1168 fn from(s: &str) -> Self {
1169 match s {
1170 "workflows" => Self::Workflows,
1171 "artifacts" => Self::Artifacts,
1172 other => Self::Unknown(other.to_string()),
1173 }
1174 }
1175}
1176
1177impl Serialize for RemedyFeature {
1178 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1179 serializer.serialize_str(self.as_str())
1180 }
1181}
1182
1183impl<'de> Deserialize<'de> for RemedyFeature {
1184 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1185 let s = String::deserialize(deserializer)?;
1186 Ok(Self::from(s.as_str()))
1187 }
1188}
1189
1190#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1193pub enum RemedyFeatureCause {
1194 ManagedSettings,
1197 OrgPolicy,
1199 Unavailable,
1201 UserSetting,
1204 UnsupportedRuntime,
1208 Unknown(String),
1210}
1211
1212impl RemedyFeatureCause {
1213 pub fn as_str(&self) -> &str {
1214 match self {
1215 Self::ManagedSettings => "managed_settings",
1216 Self::OrgPolicy => "org_policy",
1217 Self::Unavailable => "unavailable",
1218 Self::UserSetting => "user_setting",
1219 Self::UnsupportedRuntime => "unsupported_runtime",
1220 Self::Unknown(s) => s.as_str(),
1221 }
1222 }
1223}
1224
1225impl fmt::Display for RemedyFeatureCause {
1226 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1227 f.write_str(self.as_str())
1228 }
1229}
1230
1231impl From<&str> for RemedyFeatureCause {
1232 fn from(s: &str) -> Self {
1233 match s {
1234 "managed_settings" => Self::ManagedSettings,
1235 "org_policy" => Self::OrgPolicy,
1236 "unavailable" => Self::Unavailable,
1237 "user_setting" => Self::UserSetting,
1238 "unsupported_runtime" => Self::UnsupportedRuntime,
1239 other => Self::Unknown(other.to_string()),
1240 }
1241 }
1242}
1243
1244impl Serialize for RemedyFeatureCause {
1245 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1246 serializer.serialize_str(self.as_str())
1247 }
1248}
1249
1250impl<'de> Deserialize<'de> for RemedyFeatureCause {
1251 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1252 let s = String::deserialize(deserializer)?;
1253 Ok(Self::from(s.as_str()))
1254 }
1255}
1256
1257#[derive(Debug, Clone, PartialEq, Eq, Hash)]
1260pub enum RemedyPolicyKind {
1261 OrgDenied,
1263 Latched,
1266 Unknown(String),
1268}
1269
1270impl RemedyPolicyKind {
1271 pub fn as_str(&self) -> &str {
1272 match self {
1273 Self::OrgDenied => "org_denied",
1274 Self::Latched => "latched",
1275 Self::Unknown(s) => s.as_str(),
1276 }
1277 }
1278}
1279
1280impl fmt::Display for RemedyPolicyKind {
1281 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1282 f.write_str(self.as_str())
1283 }
1284}
1285
1286impl From<&str> for RemedyPolicyKind {
1287 fn from(s: &str) -> Self {
1288 match s {
1289 "org_denied" => Self::OrgDenied,
1290 "latched" => Self::Latched,
1291 other => Self::Unknown(other.to_string()),
1292 }
1293 }
1294}
1295
1296impl Serialize for RemedyPolicyKind {
1297 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1298 serializer.serialize_str(self.as_str())
1299 }
1300}
1301
1302impl<'de> Deserialize<'de> for RemedyPolicyKind {
1303 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1304 let s = String::deserialize(deserializer)?;
1305 Ok(Self::from(s.as_str()))
1306 }
1307}
1308
1309#[derive(Debug, Clone, Serialize, Deserialize)]
1311pub struct UserMessage {
1312 pub message: MessageContent,
1313 #[serde(skip_serializing_if = "Option::is_none", alias = "sessionId")]
1314 #[serde(
1315 serialize_with = "serialize_optional_uuid",
1316 deserialize_with = "deserialize_optional_uuid"
1317 )]
1318 pub session_id: Option<Uuid>,
1319 #[serde(skip_serializing_if = "Option::is_none")]
1321 pub parent_tool_use_id: Option<String>,
1322 #[serde(skip_serializing_if = "Option::is_none")]
1324 pub uuid: Option<String>,
1325 #[serde(skip_serializing_if = "Option::is_none")]
1327 pub timestamp: Option<String>,
1328 #[serde(skip_serializing_if = "Option::is_none")]
1335 pub tool_use_result: Option<serde_json::Value>,
1336 #[serde(default, skip_serializing_if = "Option::is_none")]
1341 pub agent_id: Option<String>,
1342 #[serde(skip_serializing_if = "Option::is_none")]
1345 pub subagent_type: Option<String>,
1346 #[serde(skip_serializing_if = "Option::is_none")]
1348 pub task_description: Option<String>,
1349 #[serde(skip_serializing_if = "Option::is_none")]
1350 pub origin: Option<MessageOrigin>,
1351 #[serde(skip_serializing_if = "Option::is_none")]
1352 pub priority: Option<String>,
1353 #[serde(skip_serializing_if = "Option::is_none", rename = "isSynthetic")]
1354 pub is_synthetic: Option<bool>,
1355 #[serde(skip_serializing_if = "Option::is_none", rename = "shouldQuery")]
1356 pub should_query: Option<bool>,
1357 #[serde(default, skip_serializing_if = "Option::is_none")]
1358 pub is_meta: Option<bool>,
1359 #[serde(default, skip_serializing_if = "Option::is_none")]
1360 pub is_visible_in_transcript_only: Option<bool>,
1361 #[serde(default, skip_serializing_if = "Option::is_none")]
1362 pub is_virtual: Option<bool>,
1363 #[serde(default, skip_serializing_if = "Option::is_none")]
1364 pub is_compact_summary: Option<bool>,
1365 #[serde(skip_serializing_if = "Option::is_none")]
1366 pub summarize_metadata: Option<SummarizeMetadata>,
1367 #[serde(skip_serializing_if = "Option::is_none")]
1368 pub mcp_meta: Option<McpMeta>,
1369 #[serde(skip_serializing_if = "Option::is_none")]
1372 pub tool_result_meta: Option<Vec<ToolResultMeta>>,
1373 #[serde(skip_serializing_if = "Option::is_none")]
1374 pub source_tool_use_id: Option<String>,
1375 #[serde(skip_serializing_if = "Option::is_none")]
1376 pub source_tool_assistant_uuid: Option<String>,
1377 #[serde(skip_serializing_if = "Option::is_none")]
1378 pub image_paste_ids: Option<Vec<u64>>,
1379 #[serde(skip_serializing_if = "Option::is_none")]
1380 pub client_platform: Option<String>,
1381 #[serde(skip_serializing_if = "Option::is_none")]
1382 pub inbound_origin: Option<String>,
1383 #[serde(default, skip_serializing_if = "Option::is_none")]
1388 pub keeps_request_id: Option<String>,
1389 #[serde(skip_serializing_if = "Option::is_none", rename = "isReplay")]
1390 pub is_replay: Option<bool>,
1391 #[serde(skip_serializing_if = "Option::is_none")]
1392 pub file_attachments: Option<Vec<Value>>,
1393 #[serde(default, skip_serializing_if = "Option::is_none")]
1395 pub seeded_summon: Option<bool>,
1396 #[serde(default, skip_serializing_if = "Option::is_none")]
1399 pub client_composed: Option<bool>,
1400 #[serde(default, skip_serializing_if = "Option::is_none")]
1409 pub text_not_typed: Option<bool>,
1410 #[serde(default, skip_serializing_if = "Option::is_none")]
1417 pub initiator: Option<String>,
1418 #[serde(default, skip_serializing_if = "Option::is_none")]
1424 pub pasted_content: Option<Vec<Value>>,
1425 #[serde(default, skip_serializing_if = "Option::is_none")]
1429 pub historical: Option<bool>,
1430 #[serde(default, skip_serializing_if = "Option::is_none")]
1436 pub server_received_wall_ms: Option<f64>,
1437 #[serde(default, skip_serializing_if = "Option::is_none")]
1441 pub refused_message_id: Option<String>,
1442 #[serde(default, skip_serializing_if = "Option::is_none")]
1449 pub requeue_if_interrupted_within_ms: Option<u64>,
1450 #[serde(default, skip_serializing_if = "Option::is_none")]
1459 pub ultrathink_typed: Option<bool>,
1460 #[serde(default, skip_serializing_if = "Option::is_none")]
1464 pub tool_states: Option<Vec<Value>>,
1465 #[serde(default, skip_serializing_if = "Option::is_none")]
1471 pub plugin_prompt: Option<PluginPrompt>,
1472 #[serde(default, skip_serializing_if = "Option::is_none")]
1483 pub retracted_message_uuids: Option<Vec<String>>,
1484}
1485
1486#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
1489pub struct PluginPrompt {
1490 pub name: String,
1493 pub text: String,
1499}
1500
1501impl UserMessage {
1502 pub fn tool_use_result_as<T: serde::de::DeserializeOwned>(
1510 &self,
1511 ) -> Option<Result<T, serde_json::Error>> {
1512 self.tool_use_result
1513 .as_ref()
1514 .map(|v| serde_json::from_value(v.clone()))
1515 }
1516
1517 pub fn subagent_result(&self) -> Option<SubagentResult> {
1528 self.tool_use_result
1529 .as_ref()
1530 .and_then(|v| serde_json::from_value(v.clone()).ok())
1531 }
1532}
1533
1534#[derive(Debug, Clone, Serialize, Deserialize)]
1545pub struct SubagentResult {
1546 #[serde(skip_serializing_if = "Option::is_none")]
1548 pub status: Option<String>,
1549 #[serde(skip_serializing_if = "Option::is_none")]
1551 pub prompt: Option<String>,
1552 #[serde(rename = "agentId", skip_serializing_if = "Option::is_none")]
1554 pub agent_id: Option<String>,
1555 #[serde(rename = "agentType", skip_serializing_if = "Option::is_none")]
1557 pub agent_type: Option<String>,
1558 #[serde(
1560 default,
1561 deserialize_with = "deserialize_content_blocks",
1562 skip_serializing_if = "Vec::is_empty"
1563 )]
1564 pub content: Vec<ContentBlock>,
1565 #[serde(rename = "resolvedModel", skip_serializing_if = "Option::is_none")]
1567 pub resolved_model: Option<String>,
1568 #[serde(rename = "totalDurationMs", skip_serializing_if = "Option::is_none")]
1570 pub total_duration_ms: Option<u64>,
1571 #[serde(rename = "totalTokens", skip_serializing_if = "Option::is_none")]
1573 pub total_tokens: Option<u64>,
1574 #[serde(rename = "totalToolUseCount", skip_serializing_if = "Option::is_none")]
1576 pub total_tool_use_count: Option<u64>,
1577 #[serde(skip_serializing_if = "Option::is_none")]
1579 pub usage: Option<super::result::UsageInfo>,
1580 #[serde(rename = "toolStats", skip_serializing_if = "Option::is_none")]
1582 pub tool_stats: Option<SubagentToolStats>,
1583}
1584
1585#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1590#[serde(rename_all = "camelCase")]
1591pub struct SubagentToolStats {
1592 #[serde(default)]
1593 pub read_count: u64,
1594 #[serde(default)]
1595 pub search_count: u64,
1596 #[serde(default)]
1597 pub bash_count: u64,
1598 #[serde(default)]
1599 pub edit_file_count: u64,
1600 #[serde(default)]
1601 pub lines_added: u64,
1602 #[serde(default)]
1603 pub lines_removed: u64,
1604 #[serde(default)]
1605 pub other_tool_count: u64,
1606 #[serde(flatten)]
1607 pub extra: serde_json::Map<String, Value>,
1608}
1609
1610#[derive(Debug, Clone, Default, PartialEq, Eq)]
1637pub struct SubagentUsageRollup {
1638 pub subagent_tokens: u64,
1641 pub agent_count: u32,
1643 pub tool_uses: u64,
1645 pub duration_ms: u64,
1647 seen_agent_ids: std::collections::BTreeSet<String>,
1648}
1649
1650impl SubagentUsageRollup {
1651 pub fn observe(&mut self, output: &ClaudeOutput) -> bool {
1657 match output {
1658 ClaudeOutput::User(user) => self.observe_user(user),
1659 _ => false,
1660 }
1661 }
1662
1663 pub fn observe_user(&mut self, user: &UserMessage) -> bool {
1670 let Some(result) = user.subagent_result() else {
1671 return false;
1672 };
1673 if result.total_tokens.is_none() && result.agent_id.is_none() {
1674 return false;
1675 }
1676 if let Some(agent_id) = &result.agent_id {
1677 if !self.seen_agent_ids.insert(agent_id.clone()) {
1678 return false;
1679 }
1680 }
1681 self.agent_count += 1;
1682 self.subagent_tokens += result.total_tokens.unwrap_or(0);
1683 self.tool_uses += result.total_tool_use_count.unwrap_or(0);
1684 self.duration_ms += result.total_duration_ms.unwrap_or(0);
1685 true
1686 }
1687}
1688
1689#[derive(Debug, Clone, Serialize, Deserialize)]
1691pub struct MessageContent {
1692 pub role: MessageRole,
1693 #[serde(deserialize_with = "deserialize_content_blocks")]
1694 pub content: Vec<ContentBlock>,
1695}
1696
1697#[derive(Debug, Clone, Serialize, Deserialize)]
1699pub struct SystemMessage {
1700 pub subtype: SystemSubtype,
1701 #[serde(flatten)]
1702 pub data: Value, }
1704
1705impl SystemMessage {
1706 pub fn is_init(&self) -> bool {
1708 self.subtype == SystemSubtype::Init
1709 }
1710
1711 pub fn is_status(&self) -> bool {
1713 self.subtype == SystemSubtype::Status
1714 }
1715
1716 pub fn is_compact_boundary(&self) -> bool {
1718 self.subtype == SystemSubtype::CompactBoundary
1719 }
1720
1721 pub fn as_init(&self) -> Option<InitMessage> {
1723 if self.subtype != SystemSubtype::Init {
1724 return None;
1725 }
1726 serde_json::from_value(self.data.clone()).ok()
1727 }
1728
1729 pub fn as_status(&self) -> Option<StatusMessage> {
1731 if self.subtype != SystemSubtype::Status {
1732 return None;
1733 }
1734 serde_json::from_value(self.data.clone()).ok()
1735 }
1736
1737 pub fn as_compact_boundary(&self) -> Option<CompactBoundaryMessage> {
1739 if self.subtype != SystemSubtype::CompactBoundary {
1740 return None;
1741 }
1742 serde_json::from_value(self.data.clone()).ok()
1743 }
1744
1745 pub fn is_task_started(&self) -> bool {
1747 self.subtype == SystemSubtype::TaskStarted
1748 }
1749
1750 pub fn is_task_progress(&self) -> bool {
1752 self.subtype == SystemSubtype::TaskProgress
1753 }
1754
1755 pub fn is_task_notification(&self) -> bool {
1757 self.subtype == SystemSubtype::TaskNotification
1758 }
1759
1760 pub fn as_task_started(&self) -> Option<TaskStartedMessage> {
1762 if self.subtype != SystemSubtype::TaskStarted {
1763 return None;
1764 }
1765 serde_json::from_value(self.data.clone()).ok()
1766 }
1767
1768 pub fn as_task_progress(&self) -> Option<TaskProgressMessage> {
1770 if self.subtype != SystemSubtype::TaskProgress {
1771 return None;
1772 }
1773 serde_json::from_value(self.data.clone()).ok()
1774 }
1775
1776 pub fn as_task_notification(&self) -> Option<TaskNotificationMessage> {
1778 if self.subtype != SystemSubtype::TaskNotification {
1779 return None;
1780 }
1781 serde_json::from_value(self.data.clone()).ok()
1782 }
1783
1784 pub fn is_task_updated(&self) -> bool {
1786 self.subtype == SystemSubtype::TaskUpdated
1787 }
1788
1789 pub fn as_task_updated(&self) -> Option<TaskUpdatedMessage> {
1791 if self.subtype != SystemSubtype::TaskUpdated {
1792 return None;
1793 }
1794 serde_json::from_value(self.data.clone()).ok()
1795 }
1796
1797 pub fn is_thinking_tokens(&self) -> bool {
1799 self.subtype == SystemSubtype::ThinkingTokens
1800 }
1801
1802 pub fn as_thinking_tokens(&self) -> Option<ThinkingTokensMessage> {
1804 if self.subtype != SystemSubtype::ThinkingTokens {
1805 return None;
1806 }
1807 serde_json::from_value(self.data.clone()).ok()
1808 }
1809
1810 pub fn is_code_change_published(&self) -> bool {
1812 self.subtype == SystemSubtype::CodeChangePublished
1813 }
1814
1815 pub fn as_code_change_published(&self) -> Option<CodeChangePublishedMessage> {
1817 if self.subtype != SystemSubtype::CodeChangePublished {
1818 return None;
1819 }
1820 serde_json::from_value(self.data.clone()).ok()
1821 }
1822
1823 pub fn is_vcs_state_changed(&self) -> bool {
1825 self.subtype == SystemSubtype::VcsStateChanged
1826 }
1827
1828 pub fn as_vcs_state_changed(&self) -> Option<VcsStateChangedMessage> {
1830 if self.subtype != SystemSubtype::VcsStateChanged {
1831 return None;
1832 }
1833 serde_json::from_value(self.data.clone()).ok()
1834 }
1835
1836 pub fn is_feedback_draft_queued(&self) -> bool {
1838 self.subtype == SystemSubtype::FeedbackDraftQueued
1839 }
1840
1841 pub fn as_feedback_draft_queued(&self) -> Option<FeedbackDraftQueuedMessage> {
1843 if self.subtype != SystemSubtype::FeedbackDraftQueued {
1844 return None;
1845 }
1846 serde_json::from_value(self.data.clone()).ok()
1847 }
1848
1849 pub fn is_cloud_session_delta(&self) -> bool {
1851 self.subtype == SystemSubtype::CloudSessionDelta
1852 }
1853
1854 pub fn as_cloud_session_delta(&self) -> Option<CloudSessionDeltaMessage> {
1856 if self.subtype != SystemSubtype::CloudSessionDelta {
1857 return None;
1858 }
1859 serde_json::from_value(self.data.clone()).ok()
1860 }
1861
1862 pub fn is_dev_intent(&self) -> bool {
1864 self.subtype == SystemSubtype::DevIntent
1865 }
1866
1867 pub fn as_dev_intent(&self) -> Option<DevIntentMessage> {
1869 if self.subtype != SystemSubtype::DevIntent {
1870 return None;
1871 }
1872 serde_json::from_value(self.data.clone()).ok()
1873 }
1874
1875 pub fn is_turn_handoff_available(&self) -> bool {
1877 self.subtype == SystemSubtype::TurnHandoffAvailable
1878 }
1879
1880 pub fn as_turn_handoff_available(&self) -> Option<TurnHandoffAvailableMessage> {
1882 if self.subtype != SystemSubtype::TurnHandoffAvailable {
1883 return None;
1884 }
1885 serde_json::from_value(self.data.clone()).ok()
1886 }
1887
1888 pub fn is_turn_preempted(&self) -> bool {
1890 self.subtype == SystemSubtype::TurnPreempted
1891 }
1892
1893 pub fn as_turn_preempted(&self) -> Option<TurnPreemptedMessage> {
1895 if self.subtype != SystemSubtype::TurnPreempted {
1896 return None;
1897 }
1898 serde_json::from_value(self.data.clone()).ok()
1899 }
1900
1901 pub fn is_peer_message_hold(&self) -> bool {
1903 self.subtype == SystemSubtype::PeerMessageHold
1904 }
1905
1906 pub fn as_peer_message_hold(&self) -> Option<PeerMessageHoldMessage> {
1908 if self.subtype != SystemSubtype::PeerMessageHold {
1909 return None;
1910 }
1911 serde_json::from_value(self.data.clone()).ok()
1912 }
1913
1914 pub fn is_per_turn_effort_changed(&self) -> bool {
1916 self.subtype == SystemSubtype::PerTurnEffortChanged
1917 }
1918
1919 pub fn as_per_turn_effort_changed(&self) -> Option<PerTurnEffortChangedMessage> {
1921 if self.subtype != SystemSubtype::PerTurnEffortChanged {
1922 return None;
1923 }
1924 serde_json::from_value(self.data.clone()).ok()
1925 }
1926
1927 pub fn is_session_title_changed(&self) -> bool {
1929 self.subtype == SystemSubtype::SessionTitleChanged
1930 }
1931
1932 pub fn as_session_title_changed(&self) -> Option<SessionTitleChangedMessage> {
1934 if self.subtype != SystemSubtype::SessionTitleChanged {
1935 return None;
1936 }
1937 serde_json::from_value(self.data.clone()).ok()
1938 }
1939
1940 pub fn is_session_writes_lost(&self) -> bool {
1942 self.subtype == SystemSubtype::SessionWritesLost
1943 }
1944
1945 pub fn as_session_writes_lost(&self) -> Option<SessionWritesLostMessage> {
1947 if self.subtype != SystemSubtype::SessionWritesLost {
1948 return None;
1949 }
1950 serde_json::from_value(self.data.clone()).ok()
1951 }
1952
1953 pub fn is_instruction_size_warning(&self) -> bool {
1955 self.subtype == SystemSubtype::InstructionSizeWarning
1956 }
1957
1958 pub fn as_instruction_size_warning(&self) -> Option<InstructionSizeWarningMessage> {
1960 if self.subtype != SystemSubtype::InstructionSizeWarning {
1961 return None;
1962 }
1963 serde_json::from_value(self.data.clone()).ok()
1964 }
1965
1966 pub fn is_permission_check_status(&self) -> bool {
1968 self.subtype == SystemSubtype::PermissionCheckStatus
1969 }
1970
1971 pub fn as_permission_check_status(&self) -> Option<PermissionCheckStatusMessage> {
1973 if self.subtype != SystemSubtype::PermissionCheckStatus {
1974 return None;
1975 }
1976 serde_json::from_value(self.data.clone()).ok()
1977 }
1978
1979 pub fn is_inherited_asks_settled(&self) -> bool {
1981 self.subtype == SystemSubtype::InheritedAsksSettled
1982 }
1983
1984 pub fn as_inherited_asks_settled(&self) -> Option<InheritedAsksSettledMessage> {
1986 if self.subtype != SystemSubtype::InheritedAsksSettled {
1987 return None;
1988 }
1989 serde_json::from_value(self.data.clone()).ok()
1990 }
1991
1992 pub fn is_late_allow_not_run(&self) -> bool {
1994 self.subtype == SystemSubtype::LateAllowNotRun
1995 }
1996
1997 pub fn as_late_allow_not_run(&self) -> Option<LateAllowNotRunMessage> {
1999 if self.subtype != SystemSubtype::LateAllowNotRun {
2000 return None;
2001 }
2002 serde_json::from_value(self.data.clone()).ok()
2003 }
2004
2005 pub fn is_file_attachments_missing(&self) -> bool {
2007 self.subtype == SystemSubtype::FileAttachmentsMissing
2008 }
2009
2010 pub fn as_file_attachments_missing(&self) -> Option<FileAttachmentsMissingMessage> {
2012 if self.subtype != SystemSubtype::FileAttachmentsMissing {
2013 return None;
2014 }
2015 serde_json::from_value(self.data.clone()).ok()
2016 }
2017
2018 pub fn is_ui_focus(&self) -> bool {
2020 self.subtype == SystemSubtype::UiFocus
2021 }
2022
2023 pub fn as_ui_focus(&self) -> Option<UiFocusMessage> {
2025 if self.subtype != SystemSubtype::UiFocus {
2026 return None;
2027 }
2028 serde_json::from_value(self.data.clone()).ok()
2029 }
2030
2031 pub fn is_ui_invalidate(&self) -> bool {
2033 self.subtype == SystemSubtype::UiInvalidate
2034 }
2035
2036 pub fn as_ui_invalidate(&self) -> Option<UiInvalidateMessage> {
2038 if self.subtype != SystemSubtype::UiInvalidate {
2039 return None;
2040 }
2041 serde_json::from_value(self.data.clone()).ok()
2042 }
2043
2044 pub fn is_ui_log(&self) -> bool {
2046 self.subtype == SystemSubtype::UiLog
2047 }
2048
2049 pub fn as_ui_log(&self) -> Option<UiLogMessage> {
2051 if self.subtype != SystemSubtype::UiLog {
2052 return None;
2053 }
2054 serde_json::from_value(self.data.clone()).ok()
2055 }
2056
2057 pub fn is_ui_notify(&self) -> bool {
2059 self.subtype == SystemSubtype::UiNotify
2060 }
2061
2062 pub fn as_ui_notify(&self) -> Option<UiNotifyMessage> {
2064 if self.subtype != SystemSubtype::UiNotify {
2065 return None;
2066 }
2067 serde_json::from_value(self.data.clone()).ok()
2068 }
2069
2070 pub fn is_ui_notify_cancel(&self) -> bool {
2072 self.subtype == SystemSubtype::UiNotifyCancel
2073 }
2074
2075 pub fn as_ui_notify_cancel(&self) -> Option<UiNotifyCancelMessage> {
2077 if self.subtype != SystemSubtype::UiNotifyCancel {
2078 return None;
2079 }
2080 serde_json::from_value(self.data.clone()).ok()
2081 }
2082
2083 pub fn is_ui_panes(&self) -> bool {
2085 self.subtype == SystemSubtype::UiPanes
2086 }
2087
2088 pub fn as_ui_panes(&self) -> Option<UiPanesMessage> {
2090 if self.subtype != SystemSubtype::UiPanes {
2091 return None;
2092 }
2093 serde_json::from_value(self.data.clone()).ok()
2094 }
2095
2096 pub fn is_ui_placed(&self) -> bool {
2098 self.subtype == SystemSubtype::UiPlaced
2099 }
2100
2101 pub fn as_ui_placed(&self) -> Option<UiPlacedMessage> {
2103 if self.subtype != SystemSubtype::UiPlaced {
2104 return None;
2105 }
2106 serde_json::from_value(self.data.clone()).ok()
2107 }
2108
2109 pub fn is_ui_scroll(&self) -> bool {
2111 self.subtype == SystemSubtype::UiScroll
2112 }
2113
2114 pub fn as_ui_scroll(&self) -> Option<UiScrollMessage> {
2116 if self.subtype != SystemSubtype::UiScroll {
2117 return None;
2118 }
2119 serde_json::from_value(self.data.clone()).ok()
2120 }
2121
2122 pub fn is_ui_status(&self) -> bool {
2124 self.subtype == SystemSubtype::UiStatus
2125 }
2126
2127 pub fn as_ui_status(&self) -> Option<UiStatusMessage> {
2129 if self.subtype != SystemSubtype::UiStatus {
2130 return None;
2131 }
2132 serde_json::from_value(self.data.clone()).ok()
2133 }
2134
2135 pub fn is_ui_toast(&self) -> bool {
2137 self.subtype == SystemSubtype::UiToast
2138 }
2139
2140 pub fn as_ui_toast(&self) -> Option<UiToastMessage> {
2142 if self.subtype != SystemSubtype::UiToast {
2143 return None;
2144 }
2145 serde_json::from_value(self.data.clone()).ok()
2146 }
2147
2148 pub fn as_known_system_event(&self) -> Option<KnownSystemEvent> {
2150 macro_rules! parse {
2151 ($variant:ident, $ty:ty) => {
2152 serde_json::from_value::<$ty>(self.data.clone())
2153 .ok()
2154 .map(KnownSystemEvent::$variant)
2155 };
2156 }
2157
2158 match self.subtype {
2159 SystemSubtype::Init => parse!(Init, InitMessage),
2160 SystemSubtype::Status => parse!(Status, StatusMessage),
2161 SystemSubtype::CompactBoundary => parse!(CompactBoundary, CompactBoundaryMessage),
2162 SystemSubtype::ThinkingTokens => parse!(ThinkingTokens, ThinkingTokensMessage),
2163 SystemSubtype::TaskStarted => parse!(TaskStarted, TaskStartedMessage),
2164 SystemSubtype::TaskProgress => parse!(TaskProgress, TaskProgressMessage),
2165 SystemSubtype::TaskUpdated => parse!(TaskUpdated, TaskUpdatedMessage),
2166 SystemSubtype::TaskNotification => parse!(TaskNotification, TaskNotificationMessage),
2167 SystemSubtype::ApiRetry => parse!(ApiRetry, ApiRetryMessage),
2168 SystemSubtype::ControlRequestProgress => {
2169 parse!(ControlRequestProgress, ControlRequestProgressMessage)
2170 }
2171 SystemSubtype::ModelRefusalFallback => {
2172 parse!(ModelRefusalFallback, ModelRefusalFallbackMessage)
2173 }
2174 SystemSubtype::ModelRefusalNoFallback => {
2175 parse!(ModelRefusalNoFallback, ModelRefusalNoFallbackMessage)
2176 }
2177 SystemSubtype::LocalCommandOutput => {
2178 parse!(LocalCommandOutput, LocalCommandOutputMessage)
2179 }
2180 SystemSubtype::HookStarted => parse!(HookStarted, HookStartedMessage),
2181 SystemSubtype::HookProgress => parse!(HookProgress, HookProgressMessage),
2182 SystemSubtype::HookResponse => parse!(HookResponse, HookResponseMessage),
2183 SystemSubtype::PluginInstall => parse!(PluginInstall, PluginInstallMessage),
2184 SystemSubtype::BackgroundTasksChanged => {
2185 parse!(BackgroundTasksChanged, BackgroundTasksChangedMessage)
2186 }
2187 SystemSubtype::SessionStateChanged => {
2188 parse!(SessionStateChanged, SessionStateChangedMessage)
2189 }
2190 SystemSubtype::WorkerShuttingDown => {
2191 parse!(WorkerShuttingDown, WorkerShuttingDownMessage)
2192 }
2193 SystemSubtype::CommandsChanged => parse!(CommandsChanged, CommandsChangedMessage),
2194 SystemSubtype::Notification => parse!(Notification, NotificationMessage),
2195 SystemSubtype::FilesPersisted => parse!(FilesPersisted, FilesPersistedMessage),
2196 SystemSubtype::MemoryRecall => parse!(MemoryRecall, MemoryRecallMessage),
2197 SystemSubtype::ElicitationComplete => {
2198 parse!(ElicitationComplete, ElicitationCompleteMessage)
2199 }
2200 SystemSubtype::PermissionDenied => parse!(PermissionDenied, PermissionDeniedMessage),
2201 SystemSubtype::MirrorError => parse!(MirrorError, MirrorErrorMessage),
2202 SystemSubtype::Informational => parse!(Informational, InformationalMessage),
2203 SystemSubtype::CodeChangePublished => {
2204 parse!(CodeChangePublished, CodeChangePublishedMessage)
2205 }
2206 SystemSubtype::VcsStateChanged => parse!(VcsStateChanged, VcsStateChangedMessage),
2207 SystemSubtype::FeedbackDraftQueued => {
2208 parse!(FeedbackDraftQueued, FeedbackDraftQueuedMessage)
2209 }
2210 SystemSubtype::CloudSessionDelta => {
2211 parse!(CloudSessionDelta, CloudSessionDeltaMessage)
2212 }
2213 SystemSubtype::DevIntent => parse!(DevIntent, DevIntentMessage),
2214 SystemSubtype::TurnHandoffAvailable => {
2215 parse!(TurnHandoffAvailable, TurnHandoffAvailableMessage)
2216 }
2217 SystemSubtype::TurnPreempted => parse!(TurnPreempted, TurnPreemptedMessage),
2218 SystemSubtype::PeerMessageHold => parse!(PeerMessageHold, PeerMessageHoldMessage),
2219 SystemSubtype::PerTurnEffortChanged => {
2220 parse!(PerTurnEffortChanged, PerTurnEffortChangedMessage)
2221 }
2222 SystemSubtype::SessionTitleChanged => {
2223 parse!(SessionTitleChanged, SessionTitleChangedMessage)
2224 }
2225 SystemSubtype::SessionWritesLost => {
2226 parse!(SessionWritesLost, SessionWritesLostMessage)
2227 }
2228 SystemSubtype::InstructionSizeWarning => {
2229 parse!(InstructionSizeWarning, InstructionSizeWarningMessage)
2230 }
2231 SystemSubtype::FileAttachmentsMissing => {
2232 parse!(FileAttachmentsMissing, FileAttachmentsMissingMessage)
2233 }
2234 SystemSubtype::PermissionCheckStatus => {
2235 parse!(PermissionCheckStatus, PermissionCheckStatusMessage)
2236 }
2237 SystemSubtype::InheritedAsksSettled => {
2238 parse!(InheritedAsksSettled, InheritedAsksSettledMessage)
2239 }
2240 SystemSubtype::LateAllowNotRun => parse!(LateAllowNotRun, LateAllowNotRunMessage),
2241 SystemSubtype::UiFocus => parse!(UiFocus, UiFocusMessage),
2242 SystemSubtype::UiInvalidate => parse!(UiInvalidate, UiInvalidateMessage),
2243 SystemSubtype::UiLog => parse!(UiLog, UiLogMessage),
2244 SystemSubtype::UiNotify => parse!(UiNotify, UiNotifyMessage),
2245 SystemSubtype::UiNotifyCancel => parse!(UiNotifyCancel, UiNotifyCancelMessage),
2246 SystemSubtype::UiPanes => parse!(UiPanes, UiPanesMessage),
2247 SystemSubtype::UiPlaced => parse!(UiPlaced, UiPlacedMessage),
2248 SystemSubtype::UiScroll => parse!(UiScroll, UiScrollMessage),
2249 SystemSubtype::UiStatus => parse!(UiStatus, UiStatusMessage),
2250 SystemSubtype::UiToast => parse!(UiToast, UiToastMessage),
2251 SystemSubtype::Unknown(_) => None,
2252 }
2253 }
2254
2255 pub fn typed_value(&self) -> Option<Value> {
2264 fn reserialize<T: Serialize>(parsed: Option<T>) -> Option<Value> {
2265 parsed.and_then(|v| serde_json::to_value(v).ok())
2266 }
2267 match self.subtype {
2268 SystemSubtype::Init => reserialize(self.as_init()),
2269 SystemSubtype::Status => reserialize(self.as_status()),
2270 SystemSubtype::CompactBoundary => reserialize(self.as_compact_boundary()),
2271 SystemSubtype::ThinkingTokens => reserialize(self.as_thinking_tokens()),
2272 SystemSubtype::TaskStarted => reserialize(self.as_task_started()),
2273 SystemSubtype::TaskProgress => reserialize(self.as_task_progress()),
2274 SystemSubtype::TaskUpdated => reserialize(self.as_task_updated()),
2275 SystemSubtype::TaskNotification => reserialize(self.as_task_notification()),
2276 SystemSubtype::ApiRetry => reserialize(parse_system::<ApiRetryMessage>(self)),
2277 SystemSubtype::ControlRequestProgress => {
2278 reserialize(parse_system::<ControlRequestProgressMessage>(self))
2279 }
2280 SystemSubtype::ModelRefusalFallback => {
2281 reserialize(parse_system::<ModelRefusalFallbackMessage>(self))
2282 }
2283 SystemSubtype::ModelRefusalNoFallback => {
2284 reserialize(parse_system::<ModelRefusalNoFallbackMessage>(self))
2285 }
2286 SystemSubtype::LocalCommandOutput => {
2287 reserialize(parse_system::<LocalCommandOutputMessage>(self))
2288 }
2289 SystemSubtype::HookStarted => reserialize(parse_system::<HookStartedMessage>(self)),
2290 SystemSubtype::HookProgress => reserialize(parse_system::<HookProgressMessage>(self)),
2291 SystemSubtype::HookResponse => reserialize(parse_system::<HookResponseMessage>(self)),
2292 SystemSubtype::PluginInstall => reserialize(parse_system::<PluginInstallMessage>(self)),
2293 SystemSubtype::BackgroundTasksChanged => {
2294 reserialize(parse_system::<BackgroundTasksChangedMessage>(self))
2295 }
2296 SystemSubtype::SessionStateChanged => {
2297 reserialize(parse_system::<SessionStateChangedMessage>(self))
2298 }
2299 SystemSubtype::WorkerShuttingDown => {
2300 reserialize(parse_system::<WorkerShuttingDownMessage>(self))
2301 }
2302 SystemSubtype::CommandsChanged => {
2303 reserialize(parse_system::<CommandsChangedMessage>(self))
2304 }
2305 SystemSubtype::Notification => reserialize(parse_system::<NotificationMessage>(self)),
2306 SystemSubtype::FilesPersisted => {
2307 reserialize(parse_system::<FilesPersistedMessage>(self))
2308 }
2309 SystemSubtype::MemoryRecall => reserialize(parse_system::<MemoryRecallMessage>(self)),
2310 SystemSubtype::ElicitationComplete => {
2311 reserialize(parse_system::<ElicitationCompleteMessage>(self))
2312 }
2313 SystemSubtype::PermissionDenied => {
2314 reserialize(parse_system::<PermissionDeniedMessage>(self))
2315 }
2316 SystemSubtype::MirrorError => reserialize(parse_system::<MirrorErrorMessage>(self)),
2317 SystemSubtype::Informational => reserialize(parse_system::<InformationalMessage>(self)),
2318 SystemSubtype::CodeChangePublished => {
2319 reserialize(parse_system::<CodeChangePublishedMessage>(self))
2320 }
2321 SystemSubtype::VcsStateChanged => {
2322 reserialize(parse_system::<VcsStateChangedMessage>(self))
2323 }
2324 SystemSubtype::FeedbackDraftQueued => {
2325 reserialize(parse_system::<FeedbackDraftQueuedMessage>(self))
2326 }
2327 SystemSubtype::CloudSessionDelta => {
2328 reserialize(parse_system::<CloudSessionDeltaMessage>(self))
2329 }
2330 SystemSubtype::DevIntent => reserialize(parse_system::<DevIntentMessage>(self)),
2331 SystemSubtype::TurnHandoffAvailable => {
2332 reserialize(parse_system::<TurnHandoffAvailableMessage>(self))
2333 }
2334 SystemSubtype::TurnPreempted => reserialize(parse_system::<TurnPreemptedMessage>(self)),
2335 SystemSubtype::PeerMessageHold => {
2336 reserialize(parse_system::<PeerMessageHoldMessage>(self))
2337 }
2338 SystemSubtype::PerTurnEffortChanged => {
2339 reserialize(parse_system::<PerTurnEffortChangedMessage>(self))
2340 }
2341 SystemSubtype::SessionTitleChanged => {
2342 reserialize(parse_system::<SessionTitleChangedMessage>(self))
2343 }
2344 SystemSubtype::SessionWritesLost => {
2345 reserialize(parse_system::<SessionWritesLostMessage>(self))
2346 }
2347 SystemSubtype::InstructionSizeWarning => {
2348 reserialize(parse_system::<InstructionSizeWarningMessage>(self))
2349 }
2350 SystemSubtype::FileAttachmentsMissing => {
2351 reserialize(parse_system::<FileAttachmentsMissingMessage>(self))
2352 }
2353 SystemSubtype::PermissionCheckStatus => {
2354 reserialize(parse_system::<PermissionCheckStatusMessage>(self))
2355 }
2356 SystemSubtype::InheritedAsksSettled => {
2357 reserialize(parse_system::<InheritedAsksSettledMessage>(self))
2358 }
2359 SystemSubtype::LateAllowNotRun => {
2360 reserialize(parse_system::<LateAllowNotRunMessage>(self))
2361 }
2362 SystemSubtype::UiFocus => reserialize(parse_system::<UiFocusMessage>(self)),
2363 SystemSubtype::UiInvalidate => reserialize(parse_system::<UiInvalidateMessage>(self)),
2364 SystemSubtype::UiLog => reserialize(parse_system::<UiLogMessage>(self)),
2365 SystemSubtype::UiNotify => reserialize(parse_system::<UiNotifyMessage>(self)),
2366 SystemSubtype::UiNotifyCancel => {
2367 reserialize(parse_system::<UiNotifyCancelMessage>(self))
2368 }
2369 SystemSubtype::UiPanes => reserialize(parse_system::<UiPanesMessage>(self)),
2370 SystemSubtype::UiPlaced => reserialize(parse_system::<UiPlacedMessage>(self)),
2371 SystemSubtype::UiScroll => reserialize(parse_system::<UiScrollMessage>(self)),
2372 SystemSubtype::UiStatus => reserialize(parse_system::<UiStatusMessage>(self)),
2373 SystemSubtype::UiToast => reserialize(parse_system::<UiToastMessage>(self)),
2374 SystemSubtype::Unknown(_) => None,
2375 }
2376 }
2377}
2378
2379fn parse_system<T: serde::de::DeserializeOwned>(message: &SystemMessage) -> Option<T> {
2380 serde_json::from_value(message.data.clone()).ok()
2381}
2382
2383#[allow(clippy::large_enum_variant)]
2389#[derive(Debug, Clone, Serialize, Deserialize)]
2390pub enum KnownSystemEvent {
2391 Init(InitMessage),
2392 Status(StatusMessage),
2393 CompactBoundary(CompactBoundaryMessage),
2394 ThinkingTokens(ThinkingTokensMessage),
2395 TaskStarted(TaskStartedMessage),
2396 TaskProgress(TaskProgressMessage),
2397 TaskUpdated(TaskUpdatedMessage),
2398 TaskNotification(TaskNotificationMessage),
2399 ApiRetry(ApiRetryMessage),
2400 ControlRequestProgress(ControlRequestProgressMessage),
2401 ModelRefusalFallback(ModelRefusalFallbackMessage),
2402 ModelRefusalNoFallback(ModelRefusalNoFallbackMessage),
2403 LocalCommandOutput(LocalCommandOutputMessage),
2404 HookStarted(HookStartedMessage),
2405 HookProgress(HookProgressMessage),
2406 HookResponse(HookResponseMessage),
2407 PluginInstall(PluginInstallMessage),
2408 BackgroundTasksChanged(BackgroundTasksChangedMessage),
2409 SessionStateChanged(SessionStateChangedMessage),
2410 WorkerShuttingDown(WorkerShuttingDownMessage),
2411 CommandsChanged(CommandsChangedMessage),
2412 Notification(NotificationMessage),
2413 FilesPersisted(FilesPersistedMessage),
2414 MemoryRecall(MemoryRecallMessage),
2415 ElicitationComplete(ElicitationCompleteMessage),
2416 PermissionDenied(PermissionDeniedMessage),
2417 MirrorError(MirrorErrorMessage),
2418 Informational(InformationalMessage),
2419 CodeChangePublished(CodeChangePublishedMessage),
2420 VcsStateChanged(VcsStateChangedMessage),
2421 FeedbackDraftQueued(FeedbackDraftQueuedMessage),
2422 CloudSessionDelta(CloudSessionDeltaMessage),
2423 DevIntent(DevIntentMessage),
2424 TurnHandoffAvailable(TurnHandoffAvailableMessage),
2425 TurnPreempted(TurnPreemptedMessage),
2426 PeerMessageHold(PeerMessageHoldMessage),
2427 PerTurnEffortChanged(PerTurnEffortChangedMessage),
2428 SessionTitleChanged(SessionTitleChangedMessage),
2429 SessionWritesLost(SessionWritesLostMessage),
2430 InstructionSizeWarning(InstructionSizeWarningMessage),
2431 FileAttachmentsMissing(FileAttachmentsMissingMessage),
2432 PermissionCheckStatus(PermissionCheckStatusMessage),
2433 InheritedAsksSettled(InheritedAsksSettledMessage),
2434 LateAllowNotRun(LateAllowNotRunMessage),
2435 UiFocus(UiFocusMessage),
2436 UiInvalidate(UiInvalidateMessage),
2437 UiLog(UiLogMessage),
2438 UiNotify(UiNotifyMessage),
2439 UiNotifyCancel(UiNotifyCancelMessage),
2440 UiPanes(UiPanesMessage),
2441 UiPlaced(UiPlacedMessage),
2442 UiScroll(UiScrollMessage),
2443 UiStatus(UiStatusMessage),
2444 UiToast(UiToastMessage),
2445}
2446
2447#[derive(Debug, Clone, Serialize, Deserialize)]
2448pub struct ApiRetryMessage {
2449 pub attempt: u64,
2450 pub max_retries: u64,
2451 pub retry_delay_ms: u64,
2452 pub error_status: Option<u16>,
2453 pub error: String,
2454 #[serde(default, skip_serializing_if = "Option::is_none")]
2459 pub no_response: Option<ApiRetryNoResponse>,
2460 #[serde(default, skip_serializing_if = "Option::is_none")]
2461 pub uuid: Option<String>,
2462 #[serde(default, skip_serializing_if = "Option::is_none")]
2463 pub session_id: Option<String>,
2464}
2465
2466#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2469pub struct ApiRetryNoResponse {
2470 pub waited_ms: u64,
2472 pub retry_wait_ms: u64,
2474}
2475
2476#[derive(Debug, Clone, Serialize, Deserialize)]
2477pub struct ControlRequestProgressMessage {
2478 pub request_id: String,
2479 pub status: String,
2480 #[serde(default, skip_serializing_if = "Option::is_none")]
2481 pub attempt: Option<u64>,
2482 #[serde(default, skip_serializing_if = "Option::is_none")]
2483 pub max_retries: Option<u64>,
2484 #[serde(default, skip_serializing_if = "Option::is_none")]
2485 pub retry_delay_ms: Option<u64>,
2486 #[serde(default, skip_serializing_if = "Option::is_none")]
2487 pub error_status: Option<u16>,
2488 #[serde(default, skip_serializing_if = "Option::is_none")]
2489 pub error: Option<String>,
2490 #[serde(default, skip_serializing_if = "Option::is_none")]
2491 pub uuid: Option<String>,
2492 #[serde(default, skip_serializing_if = "Option::is_none")]
2493 pub session_id: Option<String>,
2494}
2495
2496#[derive(Debug, Clone, Serialize, Deserialize)]
2497pub struct ModelRefusalFallbackMessage {
2498 pub trigger: String,
2499 pub direction: String,
2500 #[serde(default, skip_serializing_if = "Option::is_none")]
2506 pub scope: Option<RefusalFallbackScope>,
2507 pub original_model: String,
2508 pub fallback_model: String,
2509 pub request_id: Option<String>,
2510 #[serde(default, skip_serializing_if = "Option::is_none")]
2511 pub api_refusal_category: Option<String>,
2512 #[serde(default, skip_serializing_if = "Option::is_none")]
2517 pub saw_cyber_refusal: Option<bool>,
2518 #[serde(default, skip_serializing_if = "Option::is_none")]
2519 pub api_refusal_explanation: Option<String>,
2520 #[serde(default, skip_serializing_if = "Option::is_none")]
2528 pub api_refusal_cyber_verification: Option<CyberVerificationStatus>,
2529 #[serde(default, skip_serializing_if = "Option::is_none")]
2530 pub retracted_message_uuids: Option<Vec<String>>,
2531 #[serde(default, skip_serializing_if = "Option::is_none")]
2532 pub refused_user_message_uuid: Option<String>,
2533 pub content: Value,
2534 #[serde(default, skip_serializing_if = "Option::is_none")]
2535 pub uuid: Option<String>,
2536 #[serde(default, skip_serializing_if = "Option::is_none")]
2537 pub session_id: Option<String>,
2538}
2539
2540#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
2544pub struct CyberVerificationStatus {
2545 #[serde(rename = "type")]
2546 pub verification_type: String,
2547 #[serde(default, skip_serializing_if = "Option::is_none")]
2548 pub tier: Option<String>,
2549 #[serde(default, skip_serializing_if = "Option::is_none")]
2550 pub reason: Option<String>,
2551}
2552
2553#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2557pub enum RefusalFallbackScope {
2558 Session,
2560 Local,
2563 Unknown(String),
2565}
2566
2567impl RefusalFallbackScope {
2568 pub fn as_str(&self) -> &str {
2569 match self {
2570 Self::Session => "session",
2571 Self::Local => "local",
2572 Self::Unknown(s) => s.as_str(),
2573 }
2574 }
2575}
2576
2577impl fmt::Display for RefusalFallbackScope {
2578 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2579 f.write_str(self.as_str())
2580 }
2581}
2582
2583impl From<&str> for RefusalFallbackScope {
2584 fn from(s: &str) -> Self {
2585 match s {
2586 "session" => Self::Session,
2587 "local" => Self::Local,
2588 other => Self::Unknown(other.to_string()),
2589 }
2590 }
2591}
2592
2593impl Serialize for RefusalFallbackScope {
2594 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2595 serializer.serialize_str(self.as_str())
2596 }
2597}
2598
2599impl<'de> Deserialize<'de> for RefusalFallbackScope {
2600 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2601 let s = String::deserialize(deserializer)?;
2602 Ok(Self::from(s.as_str()))
2603 }
2604}
2605
2606#[derive(Debug, Clone, Serialize, Deserialize)]
2607pub struct ModelRefusalNoFallbackMessage {
2608 pub original_model: String,
2609 pub request_id: Option<String>,
2610 #[serde(default, skip_serializing_if = "Option::is_none")]
2611 pub api_refusal_category: Option<String>,
2612 #[serde(default, skip_serializing_if = "Option::is_none")]
2613 pub api_refusal_explanation: Option<String>,
2614 pub content: Value,
2615 #[serde(default, skip_serializing_if = "Option::is_none")]
2616 pub uuid: Option<String>,
2617 #[serde(default, skip_serializing_if = "Option::is_none")]
2618 pub session_id: Option<String>,
2619}
2620
2621#[derive(Debug, Clone, Serialize, Deserialize)]
2622pub struct LocalCommandOutputMessage {
2623 pub content: String,
2624 #[serde(default, skip_serializing_if = "Option::is_none")]
2625 pub uuid: Option<String>,
2626 #[serde(default, skip_serializing_if = "Option::is_none")]
2627 pub session_id: Option<String>,
2628}
2629
2630#[derive(Debug, Clone, Serialize, Deserialize)]
2631pub struct HookStartedMessage {
2632 pub hook_id: String,
2633 pub hook_name: String,
2634 pub hook_event: String,
2635 #[serde(default, skip_serializing_if = "Option::is_none")]
2640 pub origin: Option<String>,
2641 #[serde(default, skip_serializing_if = "Option::is_none")]
2645 pub label: Option<String>,
2646 #[serde(default, skip_serializing_if = "Option::is_none")]
2649 pub plugin_name: Option<String>,
2650 #[serde(default, skip_serializing_if = "Option::is_none")]
2651 pub uuid: Option<String>,
2652 #[serde(default, skip_serializing_if = "Option::is_none")]
2653 pub session_id: Option<String>,
2654}
2655
2656#[derive(Debug, Clone, Serialize, Deserialize)]
2657pub struct HookProgressMessage {
2658 pub hook_id: String,
2659 pub hook_name: String,
2660 pub hook_event: String,
2661 #[serde(default, skip_serializing_if = "Option::is_none")]
2662 pub stdout: Option<String>,
2663 #[serde(default, skip_serializing_if = "Option::is_none")]
2664 pub stderr: Option<String>,
2665 #[serde(default, skip_serializing_if = "Option::is_none")]
2666 pub output: Option<String>,
2667 #[serde(default, skip_serializing_if = "Option::is_none")]
2671 pub backgrounded: Option<bool>,
2672 #[serde(default, skip_serializing_if = "Option::is_none")]
2673 pub uuid: Option<String>,
2674 #[serde(default, skip_serializing_if = "Option::is_none")]
2675 pub session_id: Option<String>,
2676}
2677
2678#[derive(Debug, Clone, Serialize, Deserialize)]
2679pub struct HookResponseMessage {
2680 pub hook_id: String,
2681 pub hook_name: String,
2682 pub hook_event: String,
2683 #[serde(default, skip_serializing_if = "Option::is_none")]
2684 pub stdout: Option<String>,
2685 #[serde(default, skip_serializing_if = "Option::is_none")]
2686 pub stderr: Option<String>,
2687 #[serde(default, skip_serializing_if = "Option::is_none")]
2688 pub output: Option<String>,
2689 #[serde(default, skip_serializing_if = "Option::is_none")]
2690 pub exit_code: Option<i32>,
2691 pub outcome: String,
2692 #[serde(default, skip_serializing_if = "Option::is_none")]
2693 pub uuid: Option<String>,
2694 #[serde(default, skip_serializing_if = "Option::is_none")]
2695 pub session_id: Option<String>,
2696}
2697
2698#[derive(Debug, Clone, Serialize, Deserialize)]
2699pub struct PluginInstallMessage {
2700 pub status: String,
2701 #[serde(default, skip_serializing_if = "Option::is_none")]
2702 pub name: Option<String>,
2703 #[serde(default, skip_serializing_if = "Option::is_none")]
2704 pub error: Option<String>,
2705 #[serde(default, skip_serializing_if = "Option::is_none")]
2706 pub uuid: Option<String>,
2707 #[serde(default, skip_serializing_if = "Option::is_none")]
2708 pub session_id: Option<String>,
2709}
2710
2711#[derive(Debug, Clone, Serialize, Deserialize)]
2712pub struct BackgroundTasksChangedMessage {
2713 pub tasks: Vec<BackgroundTaskInfo>,
2714 #[serde(default, skip_serializing_if = "Option::is_none")]
2715 pub uuid: Option<String>,
2716 #[serde(default, skip_serializing_if = "Option::is_none")]
2717 pub session_id: Option<String>,
2718}
2719
2720#[derive(Debug, Clone, Serialize, Deserialize)]
2721pub struct BackgroundTaskInfo {
2722 pub task_id: String,
2723 #[serde(default, skip_serializing_if = "Option::is_none")]
2726 pub run_id: Option<String>,
2727 pub task_type: String,
2728 #[serde(default, skip_serializing_if = "Option::is_none")]
2732 pub subagent_type: Option<String>,
2733 pub description: String,
2734 #[serde(default, skip_serializing_if = "Option::is_none")]
2737 pub parent_task_id: Option<String>,
2738 #[serde(default, skip_serializing_if = "Option::is_none")]
2741 pub ambient: Option<bool>,
2742 #[serde(default, skip_serializing_if = "Option::is_none")]
2745 pub awaited: Option<bool>,
2746 #[serde(default, skip_serializing_if = "Option::is_none")]
2750 pub off_host: Option<bool>,
2751}
2752
2753#[derive(Debug, Clone, Serialize, Deserialize)]
2754pub struct SessionStateChangedMessage {
2755 pub state: String,
2756 #[serde(default, skip_serializing_if = "Option::is_none")]
2757 pub uuid: Option<String>,
2758 #[serde(default, skip_serializing_if = "Option::is_none")]
2759 pub session_id: Option<String>,
2760}
2761
2762#[derive(Debug, Clone, Serialize, Deserialize)]
2763pub struct WorkerShuttingDownMessage {
2764 pub reason: String,
2765 #[serde(default, skip_serializing_if = "Option::is_none")]
2766 pub uuid: Option<String>,
2767 #[serde(default, skip_serializing_if = "Option::is_none")]
2768 pub session_id: Option<String>,
2769}
2770
2771#[derive(Debug, Clone, Serialize, Deserialize)]
2772pub struct CommandsChangedMessage {
2773 pub commands: Vec<CommandInfo>,
2774 #[serde(default, skip_serializing_if = "Option::is_none")]
2775 pub uuid: Option<String>,
2776 #[serde(default, skip_serializing_if = "Option::is_none")]
2777 pub session_id: Option<String>,
2778}
2779
2780#[derive(Debug, Clone, Serialize, Deserialize)]
2781pub struct CommandInfo {
2782 pub name: String,
2783 pub description: String,
2784 #[serde(rename = "argumentHint")]
2785 pub argument_hint: String,
2786 #[serde(default, skip_serializing_if = "Option::is_none")]
2787 pub aliases: Option<Vec<String>>,
2788 #[serde(default, skip_serializing_if = "Option::is_none")]
2794 pub builtin: Option<bool>,
2795}
2796
2797#[derive(Debug, Clone, Serialize, Deserialize)]
2798pub struct NotificationMessage {
2799 pub key: String,
2800 pub text: String,
2801 pub priority: String,
2802 #[serde(default, skip_serializing_if = "Option::is_none")]
2803 pub color: Option<String>,
2804 #[serde(default, skip_serializing_if = "Option::is_none")]
2805 pub timeout_ms: Option<u64>,
2806 #[serde(default, skip_serializing_if = "Option::is_none")]
2807 pub uuid: Option<String>,
2808 #[serde(default, skip_serializing_if = "Option::is_none")]
2809 pub session_id: Option<String>,
2810}
2811
2812#[derive(Debug, Clone, Serialize, Deserialize)]
2813pub struct FilesPersistedMessage {
2814 pub files: Vec<PersistedFile>,
2815 pub failed: Vec<FailedPersistedFile>,
2816 pub processed_at: String,
2817 #[serde(default, skip_serializing_if = "Option::is_none")]
2818 pub uuid: Option<String>,
2819 #[serde(default, skip_serializing_if = "Option::is_none")]
2820 pub session_id: Option<String>,
2821}
2822
2823#[derive(Debug, Clone, Serialize, Deserialize)]
2824pub struct PersistedFile {
2825 pub filename: String,
2826 pub file_id: String,
2827}
2828
2829#[derive(Debug, Clone, Serialize, Deserialize)]
2830pub struct FailedPersistedFile {
2831 pub filename: String,
2832 pub error: String,
2833}
2834
2835#[derive(Debug, Clone, Serialize, Deserialize)]
2836pub struct MemoryRecallMessage {
2837 pub mode: String,
2838 pub memories: Vec<MemoryRecallItem>,
2839 #[serde(default, skip_serializing_if = "Option::is_none")]
2840 pub uuid: Option<String>,
2841 #[serde(default, skip_serializing_if = "Option::is_none")]
2842 pub session_id: Option<String>,
2843}
2844
2845#[derive(Debug, Clone, Serialize, Deserialize)]
2846pub struct MemoryRecallItem {
2847 pub path: String,
2848 pub scope: String,
2849 #[serde(default, skip_serializing_if = "Option::is_none")]
2850 pub content: Option<String>,
2851}
2852
2853#[derive(Debug, Clone, Serialize, Deserialize)]
2854pub struct ElicitationCompleteMessage {
2855 pub mcp_server_name: String,
2856 pub elicitation_id: String,
2857 #[serde(default, skip_serializing_if = "Option::is_none")]
2858 pub uuid: Option<String>,
2859 #[serde(default, skip_serializing_if = "Option::is_none")]
2860 pub session_id: Option<String>,
2861}
2862
2863#[derive(Debug, Clone, Serialize, Deserialize)]
2864pub struct PermissionDeniedMessage {
2865 pub tool_name: String,
2866 pub tool_use_id: String,
2867 #[serde(default, skip_serializing_if = "Option::is_none")]
2868 pub agent_id: Option<String>,
2869 #[serde(default, skip_serializing_if = "Option::is_none")]
2870 pub decision_reason_type: Option<String>,
2871 #[serde(default, skip_serializing_if = "Option::is_none")]
2875 pub decision_reason_code: Option<PermissionDeniedReasonCode>,
2876 #[serde(default, skip_serializing_if = "Option::is_none")]
2877 pub decision_reason: Option<String>,
2878 pub message: String,
2879 #[serde(default, skip_serializing_if = "Option::is_none")]
2880 pub uuid: Option<String>,
2881 #[serde(default, skip_serializing_if = "Option::is_none")]
2882 pub session_id: Option<String>,
2883}
2884
2885#[derive(Debug, Clone, PartialEq, Eq, Hash)]
2888pub enum PermissionDeniedReasonCode {
2889 ClassifierTranscriptTooLong,
2891 OutsideReadsBlocked,
2893 MemoryPaused,
2895 AutoModeNoCheckInSession,
2900 AutoModeStopNoCheckInSession,
2904 AutoModeStopNoResultForCalls,
2907 AutoModeStopNoVerdict,
2911 Unknown(String),
2913}
2914
2915impl PermissionDeniedReasonCode {
2916 pub fn as_str(&self) -> &str {
2917 match self {
2918 Self::ClassifierTranscriptTooLong => "classifier_transcript_too_long",
2919 Self::OutsideReadsBlocked => "outside_reads_blocked",
2920 Self::MemoryPaused => "memory_paused",
2921 Self::AutoModeNoCheckInSession => "auto_mode_no_check_in_session",
2922 Self::AutoModeStopNoCheckInSession => "auto_mode_stop_no_check_in_session",
2923 Self::AutoModeStopNoResultForCalls => "auto_mode_stop_no_result_for_calls",
2924 Self::AutoModeStopNoVerdict => "auto_mode_stop_no_verdict",
2925 Self::Unknown(s) => s.as_str(),
2926 }
2927 }
2928}
2929
2930impl fmt::Display for PermissionDeniedReasonCode {
2931 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2932 f.write_str(self.as_str())
2933 }
2934}
2935
2936impl From<&str> for PermissionDeniedReasonCode {
2937 fn from(s: &str) -> Self {
2938 match s {
2939 "classifier_transcript_too_long" => Self::ClassifierTranscriptTooLong,
2940 "outside_reads_blocked" => Self::OutsideReadsBlocked,
2941 "memory_paused" => Self::MemoryPaused,
2942 "auto_mode_no_check_in_session" => Self::AutoModeNoCheckInSession,
2943 "auto_mode_stop_no_check_in_session" => Self::AutoModeStopNoCheckInSession,
2944 "auto_mode_stop_no_result_for_calls" => Self::AutoModeStopNoResultForCalls,
2945 "auto_mode_stop_no_verdict" => Self::AutoModeStopNoVerdict,
2946 other => Self::Unknown(other.to_string()),
2947 }
2948 }
2949}
2950
2951impl Serialize for PermissionDeniedReasonCode {
2952 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2953 serializer.serialize_str(self.as_str())
2954 }
2955}
2956
2957impl<'de> Deserialize<'de> for PermissionDeniedReasonCode {
2958 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2959 let s = String::deserialize(deserializer)?;
2960 Ok(Self::from(s.as_str()))
2961 }
2962}
2963
2964#[derive(Debug, Clone, Serialize, Deserialize)]
2965pub struct MirrorErrorMessage {
2966 pub error: String,
2967 pub key: MirrorErrorKey,
2968 #[serde(default, skip_serializing_if = "Option::is_none")]
2969 pub uuid: Option<String>,
2970 #[serde(default, skip_serializing_if = "Option::is_none")]
2971 pub session_id: Option<String>,
2972}
2973
2974#[derive(Debug, Clone, Serialize, Deserialize)]
2975pub struct MirrorErrorKey {
2976 #[serde(rename = "projectKey")]
2977 pub project_key: String,
2978 #[serde(rename = "sessionId")]
2979 pub session_id: String,
2980 #[serde(default, skip_serializing_if = "Option::is_none")]
2981 pub subpath: Option<String>,
2982}
2983
2984#[derive(Debug, Clone, Serialize, Deserialize)]
2985pub struct InformationalMessage {
2986 pub content: String,
2987 pub level: String,
2988 #[serde(default, skip_serializing_if = "Option::is_none")]
2989 pub tool_use_id: Option<String>,
2990 #[serde(default, skip_serializing_if = "Option::is_none")]
2991 pub prevent_continuation: Option<bool>,
2992 #[serde(default, skip_serializing_if = "Option::is_none")]
2995 pub tag: Option<String>,
2996 #[serde(default, skip_serializing_if = "Option::is_none")]
3002 pub prompt_submit_outcome: Option<PromptSubmitOutcome>,
3003 #[serde(default, skip_serializing_if = "Option::is_none")]
3007 pub model_restriction: Option<ModelRestriction>,
3008 #[serde(default, skip_serializing_if = "Option::is_none")]
3014 pub hook_no_verdict: Option<HookNoVerdict>,
3015 #[serde(default, skip_serializing_if = "Option::is_none")]
3016 pub uuid: Option<String>,
3017 #[serde(default, skip_serializing_if = "Option::is_none")]
3018 pub session_id: Option<String>,
3019}
3020
3021#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3027pub struct HookNoVerdict {
3028 pub hook_event: String,
3030 pub tool_use_id: String,
3032 pub timed_out: bool,
3034 #[serde(default, skip_serializing_if = "Option::is_none")]
3036 pub plugin_id: Option<String>,
3037 #[serde(default, skip_serializing_if = "Option::is_none")]
3039 pub plugin_root: Option<String>,
3040}
3041
3042#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3048pub struct ModelRestriction {
3049 pub requested_model: String,
3052 pub effective_model: String,
3055 #[serde(default, skip_serializing_if = "Option::is_none")]
3060 pub at: Option<String>,
3061}
3062
3063#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3066pub struct PromptSubmitOutcome {
3067 #[serde(default, skip_serializing_if = "Option::is_none")]
3071 pub kind: Option<PromptSubmitOutcomeKind>,
3072 #[serde(default, skip_serializing_if = "Option::is_none")]
3079 pub no_verdict_kind: Option<String>,
3080 pub prompt_kept: bool,
3083 #[serde(default, skip_serializing_if = "Option::is_none")]
3087 pub reason: Option<String>,
3088}
3089
3090#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3092pub enum PromptSubmitOutcomeKind {
3093 BlockedByHook,
3095 StoppedByHook,
3097 DroppedByHook,
3099 NotPassedOn,
3101 NoVerdict,
3104 Other(String),
3106}
3107
3108impl PromptSubmitOutcomeKind {
3109 pub fn as_str(&self) -> &str {
3110 match self {
3111 Self::BlockedByHook => "blocked_by_hook",
3112 Self::StoppedByHook => "stopped_by_hook",
3113 Self::DroppedByHook => "dropped_by_hook",
3114 Self::NotPassedOn => "not_passed_on",
3115 Self::NoVerdict => "no_verdict",
3116 Self::Other(s) => s.as_str(),
3117 }
3118 }
3119}
3120
3121impl fmt::Display for PromptSubmitOutcomeKind {
3122 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3123 f.write_str(self.as_str())
3124 }
3125}
3126
3127impl From<&str> for PromptSubmitOutcomeKind {
3128 fn from(s: &str) -> Self {
3129 match s {
3130 "blocked_by_hook" => Self::BlockedByHook,
3131 "stopped_by_hook" => Self::StoppedByHook,
3132 "dropped_by_hook" => Self::DroppedByHook,
3133 "not_passed_on" => Self::NotPassedOn,
3134 "no_verdict" => Self::NoVerdict,
3135 other => Self::Other(other.to_string()),
3136 }
3137 }
3138}
3139
3140impl Serialize for PromptSubmitOutcomeKind {
3141 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3142 serializer.serialize_str(self.as_str())
3143 }
3144}
3145
3146impl<'de> Deserialize<'de> for PromptSubmitOutcomeKind {
3147 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3148 let s = String::deserialize(deserializer)?;
3149 Ok(Self::from(s.as_str()))
3150 }
3151}
3152
3153#[derive(Debug, Clone, Serialize, Deserialize)]
3155pub struct PluginInfo {
3156 pub name: String,
3158 pub path: String,
3160 #[serde(skip_serializing_if = "Option::is_none")]
3162 pub source: Option<String>,
3163 #[serde(default, skip_serializing_if = "Option::is_none")]
3165 pub version: Option<String>,
3166}
3167
3168#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3170pub struct PluginDiagnostic {
3171 pub plugin: String,
3172 #[serde(rename = "type")]
3173 pub diagnostic_type: String,
3174 pub message: String,
3175 #[serde(default, skip_serializing_if = "Option::is_none")]
3181 pub path: Option<String>,
3182 #[serde(default, skip_serializing_if = "Option::is_none")]
3185 pub managed_lock: Option<PluginManagedLock>,
3186}
3187
3188#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3195pub struct PluginManagedLock {
3196 pub plugin_enabled: bool,
3200 pub name: String,
3203 #[serde(default, skip_serializing_if = "Option::is_none")]
3206 pub marketplace: Option<String>,
3207}
3208
3209#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3211pub struct MemoryPaths {
3212 #[serde(default, skip_serializing_if = "Option::is_none")]
3213 pub auto: Option<String>,
3214 #[serde(default, skip_serializing_if = "Option::is_none")]
3215 pub team: Option<String>,
3216 #[serde(flatten)]
3217 pub extra: serde_json::Map<String, Value>,
3218}
3219
3220#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3224pub struct McpServerError {
3225 pub name: String,
3226 #[serde(rename = "type")]
3228 pub error_type: String,
3229 pub message: String,
3230}
3231
3232#[derive(Debug, Clone, Serialize, Deserialize)]
3234pub struct InitMessage {
3235 pub session_id: String,
3237 #[serde(skip_serializing_if = "Option::is_none")]
3239 pub cwd: Option<String>,
3240 #[serde(skip_serializing_if = "Option::is_none")]
3242 pub model: Option<String>,
3243 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3245 pub tools: Vec<String>,
3246 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3248 pub mcp_servers: Vec<Value>,
3249 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3251 pub slash_commands: Vec<String>,
3252 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3255 pub terminal_slash_commands: Vec<String>,
3256 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3258 pub agents: Vec<String>,
3259 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3261 pub plugins: Vec<PluginInfo>,
3262 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3264 pub skills: Vec<Value>,
3265 #[serde(skip_serializing_if = "Option::is_none")]
3267 pub claude_code_version: Option<String>,
3268 #[serde(skip_serializing_if = "Option::is_none")]
3271 pub messaging_socket_path: Option<String>,
3272 #[serde(skip_serializing_if = "Option::is_none", rename = "apiKeySource")]
3274 pub api_key_source: Option<ApiKeySource>,
3275 #[serde(skip_serializing_if = "Option::is_none")]
3277 pub output_style: Option<OutputStyle>,
3278 #[serde(skip_serializing_if = "Option::is_none", rename = "permissionMode")]
3280 pub permission_mode: Option<InitPermissionMode>,
3281
3282 #[serde(skip_serializing_if = "Option::is_none")]
3284 pub uuid: Option<String>,
3285
3286 #[serde(skip_serializing_if = "Option::is_none")]
3288 pub memory_paths: Option<MemoryPaths>,
3289
3290 #[serde(default, skip_serializing_if = "Option::is_none")]
3295 pub scratchpad_path: Option<String>,
3296
3297 #[serde(skip_serializing_if = "Option::is_none")]
3299 pub fast_mode_state: Option<String>,
3300
3301 #[serde(default, skip_serializing_if = "Option::is_none")]
3303 pub fast_mode_disabled_reason: Option<super::result::FastModeDisabledReason>,
3304
3305 #[serde(default, skip_serializing_if = "Option::is_none")]
3308 pub mcp_server_errors: Option<Vec<McpServerError>>,
3309
3310 #[serde(default, skip_serializing_if = "Option::is_none")]
3312 pub analytics_disabled: Option<bool>,
3313
3314 #[serde(default, skip_serializing_if = "Option::is_none")]
3316 pub product_feedback_disabled: Option<bool>,
3317
3318 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3320 pub betas: Vec<String>,
3321
3322 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3324 pub capabilities: Vec<String>,
3325
3326 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3328 pub plugin_errors: Vec<PluginDiagnostic>,
3329
3330 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3332 pub plugin_warnings: Vec<PluginDiagnostic>,
3333
3334 #[serde(default, skip_serializing_if = "Option::is_none")]
3339 pub effort: Option<String>,
3340
3341 #[serde(default, skip_serializing_if = "Option::is_none")]
3346 pub cloud_session: Option<Value>,
3347
3348 #[serde(default, skip_serializing_if = "Option::is_none")]
3352 pub footer_indicator: Option<FooterIndicator>,
3353
3354 #[serde(default, skip_serializing_if = "Option::is_none")]
3358 pub worker_epoch: Option<u64>,
3359
3360 #[serde(default, skip_serializing_if = "Option::is_none")]
3364 pub powershell_path: Option<Option<String>>,
3365
3366 #[serde(default, skip_serializing_if = "Option::is_none")]
3370 pub startup_timing: Option<serde_json::Map<String, Value>>,
3371
3372 #[serde(default, skip_serializing_if = "Option::is_none")]
3382 pub per_turn_effort_active: Option<bool>,
3383
3384 #[serde(default, skip_serializing_if = "Option::is_none")]
3392 pub ultrathink_available: Option<bool>,
3393
3394 #[serde(default, skip_serializing_if = "Option::is_none")]
3404 pub ultrathink_typed_raises: Option<bool>,
3405
3406 #[serde(default, skip_serializing_if = "Option::is_none")]
3411 pub client_thinking: Option<ClientThinking>,
3412
3413 #[serde(default, skip_serializing_if = "Option::is_none")]
3418 pub flag_restate_noop: Option<bool>,
3419
3420 #[serde(default, skip_serializing_if = "Option::is_none")]
3428 pub synced_skills_path: Option<String>,
3429
3430 #[serde(default, skip_serializing_if = "Option::is_none")]
3437 pub view_mode: Option<ViewMode>,
3438
3439 #[serde(default, skip_serializing_if = "Option::is_none")]
3446 pub original_cwd: Option<String>,
3447
3448 #[serde(default, skip_serializing_if = "Option::is_none")]
3457 pub additional_directories: Option<Vec<String>>,
3458}
3459
3460#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3463pub struct ClientThinking {
3464 #[serde(default)]
3467 pub max_thinking_tokens: Option<u64>,
3468 #[serde(default)]
3472 pub thinking_display: Option<String>,
3473}
3474
3475#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3479pub struct FooterIndicator {
3480 pub text: String,
3483}
3484
3485#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3488pub enum ViewMode {
3489 Focus,
3492 Default,
3494 Unknown(String),
3496}
3497
3498impl ViewMode {
3499 pub fn as_str(&self) -> &str {
3500 match self {
3501 Self::Focus => "focus",
3502 Self::Default => "default",
3503 Self::Unknown(s) => s.as_str(),
3504 }
3505 }
3506}
3507
3508impl fmt::Display for ViewMode {
3509 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3510 f.write_str(self.as_str())
3511 }
3512}
3513
3514impl From<&str> for ViewMode {
3515 fn from(s: &str) -> Self {
3516 match s {
3517 "focus" => Self::Focus,
3518 "default" => Self::Default,
3519 other => Self::Unknown(other.to_string()),
3520 }
3521 }
3522}
3523
3524impl Serialize for ViewMode {
3525 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3526 serializer.serialize_str(self.as_str())
3527 }
3528}
3529
3530impl<'de> Deserialize<'de> for ViewMode {
3531 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3532 let s = String::deserialize(deserializer)?;
3533 Ok(Self::from(s.as_str()))
3534 }
3535}
3536
3537#[derive(Debug, Clone, Serialize, Deserialize)]
3539pub struct StatusMessage {
3540 pub session_id: String,
3542 pub status: Option<StatusMessageStatus>,
3544 #[serde(skip_serializing_if = "Option::is_none")]
3546 pub uuid: Option<String>,
3547 #[serde(skip_serializing_if = "Option::is_none", rename = "permissionMode")]
3549 pub permission_mode: Option<InitPermissionMode>,
3550 #[serde(skip_serializing_if = "Option::is_none")]
3551 pub compact_result: Option<String>,
3552 #[serde(skip_serializing_if = "Option::is_none")]
3553 pub compact_error: Option<String>,
3554 #[serde(default, skip_serializing_if = "Option::is_none")]
3561 pub compact_output_chars: Option<u64>,
3562 #[serde(default, skip_serializing_if = "Option::is_none")]
3569 pub resume_held_for_plan: Option<bool>,
3570}
3571
3572#[derive(Debug, Clone, Serialize, Deserialize)]
3574pub struct CompactBoundaryMessage {
3575 pub session_id: String,
3577 pub compact_metadata: CompactMetadata,
3579 #[serde(
3583 default,
3584 skip_serializing_if = "Option::is_none",
3585 alias = "content",
3586 alias = "text"
3587 )]
3588 pub summary: Option<String>,
3589 #[serde(
3593 default,
3594 skip_serializing_if = "Option::is_none",
3595 alias = "message_count"
3596 )]
3597 pub leaf_message_count: Option<u32>,
3598 #[serde(default, skip_serializing_if = "Option::is_none")]
3600 pub duration_ms: Option<u64>,
3601 #[serde(skip_serializing_if = "Option::is_none")]
3603 pub uuid: Option<String>,
3604 #[serde(skip_serializing_if = "Option::is_none")]
3606 pub logical_parent_uuid: Option<Option<String>>,
3607 #[serde(default, skip_serializing_if = "Option::is_none")]
3611 pub historical: Option<bool>,
3612}
3613
3614#[derive(Debug, Clone, Serialize, Deserialize)]
3616pub struct CompactMetadata {
3617 pub pre_tokens: u64,
3619 pub trigger: CompactionTrigger,
3621 #[serde(default, skip_serializing_if = "Option::is_none")]
3622 pub post_tokens: Option<u64>,
3623 #[serde(default, skip_serializing_if = "Option::is_none")]
3624 pub cumulative_dropped_tokens: Option<u64>,
3625 #[serde(default, skip_serializing_if = "Option::is_none")]
3626 pub duration_ms: Option<u64>,
3627 #[serde(default, skip_serializing_if = "Option::is_none")]
3628 pub user_context: Option<String>,
3629 #[serde(default, skip_serializing_if = "Option::is_none")]
3630 pub messages_summarized: Option<u64>,
3631 #[serde(default, skip_serializing_if = "Option::is_none")]
3632 pub precomputed: Option<bool>,
3633 #[serde(default, skip_serializing_if = "Option::is_none")]
3634 pub pre_compact_discovered_tools: Option<Vec<String>>,
3635 #[serde(default, skip_serializing_if = "Option::is_none")]
3640 pub pre_compact_artifact_read_versions: Option<Vec<ArtifactReadVersion>>,
3641 #[serde(default, skip_serializing_if = "Option::is_none")]
3642 pub preserved_segment: Option<PreservedSegment>,
3643 #[serde(default, skip_serializing_if = "Option::is_none")]
3644 pub preserved_messages: Option<PreservedMessages>,
3645}
3646
3647#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
3650pub struct ArtifactReadVersion {
3651 pub slug: String,
3653 pub ver: String,
3655}
3656
3657#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3658pub struct PreservedSegment {
3659 pub head_uuid: String,
3660 pub anchor_uuid: String,
3661 pub tail_uuid: String,
3662}
3663
3664#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
3665pub struct PreservedMessages {
3666 pub anchor_uuid: String,
3667 pub uuids: Vec<String>,
3668 #[serde(default, skip_serializing_if = "Option::is_none")]
3669 pub all_uuids: Option<Vec<String>>,
3670}
3671
3672#[derive(Debug, Clone, Serialize, Deserialize)]
3678pub struct TaskUsage {
3679 pub duration_ms: u64,
3681 pub tool_uses: u64,
3683 pub total_tokens: u64,
3685}
3686
3687#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3689pub enum TaskType {
3690 LocalAgent,
3692 LocalBash,
3694 LocalWorkflow,
3696 Unknown(String),
3698}
3699
3700impl TaskType {
3701 pub fn as_str(&self) -> &str {
3702 match self {
3703 Self::LocalAgent => "local_agent",
3704 Self::LocalBash => "local_bash",
3705 Self::LocalWorkflow => "local_workflow",
3706 Self::Unknown(s) => s.as_str(),
3707 }
3708 }
3709}
3710
3711impl fmt::Display for TaskType {
3712 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3713 f.write_str(self.as_str())
3714 }
3715}
3716
3717impl From<&str> for TaskType {
3718 fn from(s: &str) -> Self {
3719 match s {
3720 "local_agent" => Self::LocalAgent,
3721 "local_bash" => Self::LocalBash,
3722 "local_workflow" => Self::LocalWorkflow,
3723 other => Self::Unknown(other.to_string()),
3724 }
3725 }
3726}
3727
3728impl Serialize for TaskType {
3729 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3730 serializer.serialize_str(self.as_str())
3731 }
3732}
3733
3734impl<'de> Deserialize<'de> for TaskType {
3735 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3736 let s = String::deserialize(deserializer)?;
3737 Ok(Self::from(s.as_str()))
3738 }
3739}
3740
3741#[derive(Debug, Clone, PartialEq, Eq, Hash)]
3743pub enum TaskStatus {
3744 Pending,
3745 Running,
3746 Completed,
3747 Failed,
3748 Killed,
3749 Paused,
3750 Stopped,
3751 Unknown(String),
3752}
3753
3754impl TaskStatus {
3755 pub fn as_str(&self) -> &str {
3756 match self {
3757 Self::Pending => "pending",
3758 Self::Running => "running",
3759 Self::Completed => "completed",
3760 Self::Failed => "failed",
3761 Self::Killed => "killed",
3762 Self::Paused => "paused",
3763 Self::Stopped => "stopped",
3764 Self::Unknown(s) => s.as_str(),
3765 }
3766 }
3767}
3768
3769impl fmt::Display for TaskStatus {
3770 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3771 f.write_str(self.as_str())
3772 }
3773}
3774
3775impl From<&str> for TaskStatus {
3776 fn from(s: &str) -> Self {
3777 match s {
3778 "pending" => Self::Pending,
3779 "running" => Self::Running,
3780 "completed" => Self::Completed,
3781 "failed" => Self::Failed,
3782 "killed" => Self::Killed,
3783 "paused" => Self::Paused,
3784 "stopped" => Self::Stopped,
3785 other => Self::Unknown(other.to_string()),
3786 }
3787 }
3788}
3789
3790impl Serialize for TaskStatus {
3791 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
3792 serializer.serialize_str(self.as_str())
3793 }
3794}
3795
3796impl<'de> Deserialize<'de> for TaskStatus {
3797 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
3798 let s = String::deserialize(deserializer)?;
3799 Ok(Self::from(s.as_str()))
3800 }
3801}
3802
3803#[derive(Debug, Clone, Serialize, Deserialize)]
3805pub struct TaskStartedMessage {
3806 pub session_id: String,
3807 pub task_id: String,
3808 #[serde(default, skip_serializing_if = "Option::is_none")]
3814 pub run_id: Option<String>,
3815 #[serde(default, skip_serializing_if = "Option::is_none")]
3821 pub parent_task_id: Option<String>,
3822 #[serde(default, skip_serializing_if = "Option::is_none")]
3823 pub task_type: Option<TaskType>,
3824 #[serde(default, skip_serializing_if = "Option::is_none")]
3825 pub tool_use_id: Option<String>,
3826 pub description: String,
3827 #[serde(default, skip_serializing_if = "Option::is_none")]
3830 pub subagent_type: Option<String>,
3831 #[serde(default, skip_serializing_if = "Option::is_none")]
3837 pub is_backgrounded: Option<bool>,
3838 #[serde(default, skip_serializing_if = "Option::is_none")]
3846 pub awaited: Option<bool>,
3847 #[serde(default, skip_serializing_if = "Option::is_none")]
3851 pub spawn_depth: Option<u32>,
3852 #[serde(default, skip_serializing_if = "Option::is_none")]
3854 pub prompt: Option<String>,
3855 #[serde(default, skip_serializing_if = "Option::is_none")]
3856 pub workflow_name: Option<String>,
3857 #[serde(default, skip_serializing_if = "Option::is_none")]
3858 pub skip_transcript: Option<bool>,
3859 #[serde(default, skip_serializing_if = "Option::is_none")]
3864 pub ambient: Option<bool>,
3865 pub uuid: String,
3866}
3867
3868#[derive(Debug, Clone, Serialize, Deserialize)]
3872pub struct TaskUpdatedMessage {
3873 pub session_id: String,
3874 pub task_id: String,
3875 #[serde(default, skip_serializing_if = "Option::is_none")]
3878 pub run_id: Option<String>,
3879 pub patch: TaskPatch,
3880 pub uuid: String,
3881}
3882
3883#[derive(Debug, Clone, Default, Serialize, Deserialize)]
3886pub struct TaskPatch {
3887 #[serde(default, skip_serializing_if = "Option::is_none")]
3888 pub status: Option<TaskStatus>,
3889 #[serde(default, skip_serializing_if = "Option::is_none")]
3892 pub end_time: Option<u64>,
3893 #[serde(default, skip_serializing_if = "Option::is_none")]
3894 pub description: Option<String>,
3895 #[serde(default, skip_serializing_if = "Option::is_none")]
3896 pub total_paused_ms: Option<u64>,
3897 #[serde(default, skip_serializing_if = "Option::is_none")]
3898 pub error: Option<String>,
3899 #[serde(default, skip_serializing_if = "Option::is_none")]
3900 pub is_backgrounded: Option<bool>,
3901}
3902
3903#[derive(Debug, Clone, Serialize, Deserialize)]
3906pub struct ThinkingTokensMessage {
3907 pub session_id: String,
3908 pub estimated_tokens: u64,
3910 pub estimated_tokens_delta: u64,
3912 #[serde(default, skip_serializing_if = "Option::is_none")]
3919 pub user_message_uuid: Option<String>,
3920 pub uuid: String,
3921}
3922
3923#[derive(Debug, Clone, Serialize, Deserialize)]
3926pub struct TaskProgressMessage {
3927 pub session_id: String,
3928 pub task_id: String,
3929 #[serde(default, skip_serializing_if = "Option::is_none")]
3932 pub run_id: Option<String>,
3933 #[serde(default, skip_serializing_if = "Option::is_none")]
3934 pub tool_use_id: Option<String>,
3935 pub description: String,
3936 #[serde(default, skip_serializing_if = "Option::is_none")]
3937 pub last_tool_name: Option<String>,
3938 pub usage: TaskUsage,
3939 #[serde(default, skip_serializing_if = "Option::is_none")]
3941 pub subagent_type: Option<String>,
3942 #[serde(default, skip_serializing_if = "Option::is_none")]
3943 pub summary: Option<String>,
3944 pub uuid: String,
3945}
3946
3947#[derive(Debug, Clone, Serialize, Deserialize)]
3950pub struct TaskNotificationMessage {
3951 pub session_id: String,
3952 pub task_id: String,
3953 #[serde(default, skip_serializing_if = "Option::is_none")]
3956 pub run_id: Option<String>,
3957 pub status: TaskStatus,
3958 #[serde(default, skip_serializing_if = "Option::is_none")]
3961 pub reason: Option<TaskEndReason>,
3962 pub summary: String,
3963 #[serde(default, skip_serializing_if = "Option::is_none")]
3969 pub summary_is_report: Option<bool>,
3970 pub output_file: Option<String>,
3971 #[serde(skip_serializing_if = "Option::is_none")]
3972 pub tool_use_id: Option<String>,
3973 #[serde(skip_serializing_if = "Option::is_none")]
3974 pub usage: Option<TaskUsage>,
3975 #[serde(default, skip_serializing_if = "Vec::is_empty")]
3981 pub resource_links: Vec<ResourceLink>,
3982 #[serde(default, skip_serializing_if = "Option::is_none")]
3989 pub handback: Option<TaskHandback>,
3990 #[serde(default, skip_serializing_if = "Option::is_none")]
3994 pub handback_report: Option<HandbackReport>,
3995 #[serde(default, skip_serializing_if = "Option::is_none")]
3996 pub skip_transcript: Option<bool>,
3997 #[serde(default, skip_serializing_if = "Option::is_none")]
4000 pub ambient: Option<bool>,
4001 #[serde(skip_serializing_if = "Option::is_none")]
4002 pub uuid: Option<String>,
4003}
4004
4005#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4008pub enum TaskHandback {
4009 Send,
4011 Flagged,
4013 Withheld,
4015 Unknown(String),
4017}
4018
4019impl TaskHandback {
4020 pub fn as_str(&self) -> &str {
4021 match self {
4022 Self::Send => "send",
4023 Self::Flagged => "flagged",
4024 Self::Withheld => "withheld",
4025 Self::Unknown(s) => s.as_str(),
4026 }
4027 }
4028}
4029
4030impl fmt::Display for TaskHandback {
4031 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4032 f.write_str(self.as_str())
4033 }
4034}
4035
4036impl From<&str> for TaskHandback {
4037 fn from(s: &str) -> Self {
4038 match s {
4039 "send" => Self::Send,
4040 "flagged" => Self::Flagged,
4041 "withheld" => Self::Withheld,
4042 other => Self::Unknown(other.to_string()),
4043 }
4044 }
4045}
4046
4047impl Serialize for TaskHandback {
4048 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4049 serializer.serialize_str(self.as_str())
4050 }
4051}
4052
4053impl<'de> Deserialize<'de> for TaskHandback {
4054 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4055 let s = String::deserialize(deserializer)?;
4056 Ok(Self::from(s.as_str()))
4057 }
4058}
4059
4060#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
4063pub struct HandbackReport {
4064 pub text: String,
4067 #[serde(default, skip_serializing_if = "Option::is_none")]
4070 pub warning: Option<String>,
4071}
4072
4073#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4075pub enum AssistantErrorKind {
4076 AuthenticationFailed,
4077 OauthOrgNotAllowed,
4078 AccountOnHold,
4079 BillingError,
4080 RateLimit,
4081 Overloaded,
4082 InvalidRequest,
4083 ModelNotFound,
4084 ServerError,
4085 UnknownError,
4086 MaxOutputTokens,
4087 Unknown(String),
4088}
4089
4090impl AssistantErrorKind {
4091 pub fn as_str(&self) -> &str {
4092 match self {
4093 Self::AuthenticationFailed => "authentication_failed",
4094 Self::OauthOrgNotAllowed => "oauth_org_not_allowed",
4095 Self::AccountOnHold => "account_on_hold",
4096 Self::BillingError => "billing_error",
4097 Self::RateLimit => "rate_limit",
4098 Self::Overloaded => "overloaded",
4099 Self::InvalidRequest => "invalid_request",
4100 Self::ModelNotFound => "model_not_found",
4101 Self::ServerError => "server_error",
4102 Self::UnknownError => "unknown",
4103 Self::MaxOutputTokens => "max_output_tokens",
4104 Self::Unknown(s) => s.as_str(),
4105 }
4106 }
4107}
4108
4109impl fmt::Display for AssistantErrorKind {
4110 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4111 f.write_str(self.as_str())
4112 }
4113}
4114
4115impl From<&str> for AssistantErrorKind {
4116 fn from(s: &str) -> Self {
4117 match s {
4118 "authentication_failed" => Self::AuthenticationFailed,
4119 "oauth_org_not_allowed" => Self::OauthOrgNotAllowed,
4120 "account_on_hold" => Self::AccountOnHold,
4121 "billing_error" => Self::BillingError,
4122 "rate_limit" => Self::RateLimit,
4123 "overloaded" => Self::Overloaded,
4124 "invalid_request" => Self::InvalidRequest,
4125 "model_not_found" => Self::ModelNotFound,
4126 "server_error" => Self::ServerError,
4127 "unknown" => Self::UnknownError,
4128 "max_output_tokens" => Self::MaxOutputTokens,
4129 other => Self::Unknown(other.to_string()),
4130 }
4131 }
4132}
4133
4134impl Serialize for AssistantErrorKind {
4135 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4136 serializer.serialize_str(self.as_str())
4137 }
4138}
4139
4140impl<'de> Deserialize<'de> for AssistantErrorKind {
4141 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4142 let s = String::deserialize(deserializer)?;
4143 Ok(Self::from(s.as_str()))
4144 }
4145}
4146
4147#[derive(Debug, Clone, Serialize, Deserialize)]
4154pub struct CodeChangePublishedMessage {
4155 pub provider: String,
4159 pub url: String,
4161 pub repo: String,
4164 pub identifier: String,
4166 #[serde(default, skip_serializing_if = "Option::is_none")]
4175 pub action: Option<String>,
4176 #[serde(default, skip_serializing_if = "Option::is_none")]
4184 pub branch: Option<String>,
4185 pub uuid: String,
4186 pub session_id: String,
4187}
4188
4189#[derive(Debug, Clone, Serialize, Deserialize)]
4194pub struct VcsStateChangedMessage {
4195 pub kind: VcsMutationKind,
4198 pub cwd: String,
4201 #[serde(default, skip_serializing_if = "Option::is_none")]
4206 pub branch: Option<String>,
4207 pub uuid: String,
4208 pub session_id: String,
4209}
4210
4211#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4213pub enum VcsMutationKind {
4214 Commit,
4215 Push,
4216 Merge,
4217 Rebase,
4218 Unknown(String),
4220}
4221
4222impl VcsMutationKind {
4223 pub fn as_str(&self) -> &str {
4224 match self {
4225 Self::Commit => "commit",
4226 Self::Push => "push",
4227 Self::Merge => "merge",
4228 Self::Rebase => "rebase",
4229 Self::Unknown(s) => s.as_str(),
4230 }
4231 }
4232}
4233
4234impl fmt::Display for VcsMutationKind {
4235 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4236 f.write_str(self.as_str())
4237 }
4238}
4239
4240impl From<&str> for VcsMutationKind {
4241 fn from(s: &str) -> Self {
4242 match s {
4243 "commit" => Self::Commit,
4244 "push" => Self::Push,
4245 "merge" => Self::Merge,
4246 "rebase" => Self::Rebase,
4247 other => Self::Unknown(other.to_string()),
4248 }
4249 }
4250}
4251
4252impl Serialize for VcsMutationKind {
4253 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4254 serializer.serialize_str(self.as_str())
4255 }
4256}
4257
4258impl<'de> Deserialize<'de> for VcsMutationKind {
4259 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4260 let s = String::deserialize(deserializer)?;
4261 Ok(Self::from(s.as_str()))
4262 }
4263}
4264
4265#[derive(Debug, Clone, Serialize, Deserialize)]
4267pub struct FeedbackDraftQueuedMessage {
4268 pub draft_id: String,
4269 pub draft_type: String,
4270 pub title: String,
4271 pub details_preview: String,
4272 #[serde(default, skip_serializing_if = "Option::is_none")]
4273 pub uuid: Option<String>,
4274 #[serde(default, skip_serializing_if = "Option::is_none")]
4275 pub session_id: Option<String>,
4276 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4277 pub extra: serde_json::Map<String, Value>,
4278}
4279
4280#[derive(Debug, Clone, Serialize, Deserialize)]
4288pub struct CloudSessionDeltaMessage {
4289 pub seq: u64,
4293 pub changed: Vec<String>,
4297 pub cloud_session: Value,
4301 pub uuid: String,
4302 pub session_id: String,
4303 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4304 pub extra: serde_json::Map<String, Value>,
4305}
4306
4307#[derive(Debug, Clone, Serialize, Deserialize)]
4323pub struct DevIntentMessage {
4324 pub kind: DevIntentKind,
4326 #[serde(default, skip_serializing_if = "Option::is_none")]
4332 pub trigger: Option<DevIntentTrigger>,
4333 pub uuid: String,
4334 pub session_id: String,
4335 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4336 pub extra: serde_json::Map<String, Value>,
4337}
4338
4339#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4343pub enum DevIntentKind {
4344 IosApp,
4350 AndroidApp,
4357 Unknown(String),
4359}
4360
4361impl DevIntentKind {
4362 pub fn as_str(&self) -> &str {
4363 match self {
4364 Self::IosApp => "ios_app",
4365 Self::AndroidApp => "android_app",
4366 Self::Unknown(s) => s.as_str(),
4367 }
4368 }
4369}
4370
4371impl fmt::Display for DevIntentKind {
4372 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4373 f.write_str(self.as_str())
4374 }
4375}
4376
4377impl From<&str> for DevIntentKind {
4378 fn from(s: &str) -> Self {
4379 match s {
4380 "ios_app" => Self::IosApp,
4381 "android_app" => Self::AndroidApp,
4382 other => Self::Unknown(other.to_string()),
4383 }
4384 }
4385}
4386
4387impl Serialize for DevIntentKind {
4388 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4389 serializer.serialize_str(self.as_str())
4390 }
4391}
4392
4393impl<'de> Deserialize<'de> for DevIntentKind {
4394 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4395 let s = String::deserialize(deserializer)?;
4396 Ok(Self::from(s.as_str()))
4397 }
4398}
4399
4400#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4404pub enum DevIntentTrigger {
4405 SwiftEdit,
4407 UikitImport,
4409 XcodeProject,
4412 IosCommand,
4415 KotlinEdit,
4417 JavaEdit,
4419 AndroidImport,
4421 AndroidManifest,
4423 GradlePlugin,
4425 AndroidCommand,
4428 ProjectScan,
4431 Unknown(String),
4433}
4434
4435impl DevIntentTrigger {
4436 pub fn as_str(&self) -> &str {
4437 match self {
4438 Self::SwiftEdit => "swift_edit",
4439 Self::UikitImport => "uikit_import",
4440 Self::XcodeProject => "xcode_project",
4441 Self::IosCommand => "ios_command",
4442 Self::KotlinEdit => "kotlin_edit",
4443 Self::JavaEdit => "java_edit",
4444 Self::AndroidImport => "android_import",
4445 Self::AndroidManifest => "android_manifest",
4446 Self::GradlePlugin => "gradle_plugin",
4447 Self::AndroidCommand => "android_command",
4448 Self::ProjectScan => "project_scan",
4449 Self::Unknown(s) => s.as_str(),
4450 }
4451 }
4452}
4453
4454impl fmt::Display for DevIntentTrigger {
4455 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4456 f.write_str(self.as_str())
4457 }
4458}
4459
4460impl From<&str> for DevIntentTrigger {
4461 fn from(s: &str) -> Self {
4462 match s {
4463 "swift_edit" => Self::SwiftEdit,
4464 "uikit_import" => Self::UikitImport,
4465 "xcode_project" => Self::XcodeProject,
4466 "ios_command" => Self::IosCommand,
4467 "kotlin_edit" => Self::KotlinEdit,
4468 "java_edit" => Self::JavaEdit,
4469 "android_import" => Self::AndroidImport,
4470 "android_manifest" => Self::AndroidManifest,
4471 "gradle_plugin" => Self::GradlePlugin,
4472 "android_command" => Self::AndroidCommand,
4473 "project_scan" => Self::ProjectScan,
4474 other => Self::Unknown(other.to_string()),
4475 }
4476 }
4477}
4478
4479impl Serialize for DevIntentTrigger {
4480 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4481 serializer.serialize_str(self.as_str())
4482 }
4483}
4484
4485impl<'de> Deserialize<'de> for DevIntentTrigger {
4486 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4487 let s = String::deserialize(deserializer)?;
4488 Ok(Self::from(s.as_str()))
4489 }
4490}
4491
4492#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4496pub enum TaskEndReason {
4497 WorkerRestart,
4500 Unknown(String),
4502}
4503
4504impl TaskEndReason {
4505 pub fn as_str(&self) -> &str {
4506 match self {
4507 Self::WorkerRestart => "worker_restart",
4508 Self::Unknown(s) => s.as_str(),
4509 }
4510 }
4511}
4512
4513impl fmt::Display for TaskEndReason {
4514 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4515 f.write_str(self.as_str())
4516 }
4517}
4518
4519impl From<&str> for TaskEndReason {
4520 fn from(s: &str) -> Self {
4521 match s {
4522 "worker_restart" => Self::WorkerRestart,
4523 other => Self::Unknown(other.to_string()),
4524 }
4525 }
4526}
4527
4528impl Serialize for TaskEndReason {
4529 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4530 serializer.serialize_str(self.as_str())
4531 }
4532}
4533
4534impl<'de> Deserialize<'de> for TaskEndReason {
4535 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4536 let s = String::deserialize(deserializer)?;
4537 Ok(Self::from(s.as_str()))
4538 }
4539}
4540
4541#[derive(Debug, Clone, Serialize, Deserialize)]
4550pub struct TurnHandoffAvailableMessage {
4551 pub v: u64,
4553 pub tools: Vec<String>,
4555 pub worker_epoch: u64,
4557 #[serde(default, skip_serializing_if = "Option::is_none")]
4561 pub relay_marker: Option<bool>,
4562 #[serde(default, skip_serializing_if = "Option::is_none")]
4570 pub staged_files: Option<bool>,
4571 #[serde(default, skip_serializing_if = "Option::is_none")]
4578 pub no_query_first: Option<bool>,
4579 #[serde(default, skip_serializing_if = "Option::is_none")]
4587 pub home_files: Option<bool>,
4588 #[serde(default, skip_serializing_if = "Option::is_none")]
4592 pub file_names: Option<bool>,
4593 #[serde(default, skip_serializing_if = "Option::is_none")]
4603 pub carried_writes: Option<bool>,
4604 #[serde(default, skip_serializing_if = "Option::is_none")]
4618 pub hydrates_carried_lines: Option<bool>,
4619 #[serde(default, skip_serializing_if = "Option::is_none")]
4625 pub shared_message_id: Option<bool>,
4626 #[serde(default, skip_serializing_if = "Option::is_none")]
4631 pub requires_rewind_request_id: Option<bool>,
4632 pub uuid: String,
4633 pub session_id: String,
4634 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4635 pub extra: serde_json::Map<String, Value>,
4636}
4637
4638#[derive(Debug, Clone, Serialize, Deserialize)]
4650pub struct TurnPreemptedMessage {
4651 pub reason: String,
4655 pub preempted_by_uuid: String,
4659 #[serde(default)]
4662 pub preempted_message_uuids: Vec<String>,
4663 pub uuid: String,
4664 pub session_id: String,
4665 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4666 pub extra: serde_json::Map<String, Value>,
4667}
4668
4669#[derive(Debug, Clone, Serialize, Deserialize)]
4677pub struct PeerMessageHoldMessage {
4678 pub state: PeerMessageHoldState,
4684 #[serde(default, skip_serializing_if = "Option::is_none")]
4691 pub message_uuid: Option<String>,
4692 pub lane: PeerMessageLane,
4694 pub from: String,
4699 #[serde(default, skip_serializing_if = "Option::is_none")]
4702 pub from_name: Option<String>,
4703 #[serde(default, skip_serializing_if = "Option::is_none")]
4705 pub cause: Option<PeerMessageHoldCause>,
4706 #[serde(default, skip_serializing_if = "Option::is_none")]
4708 pub outcome: Option<PeerMessageHoldOutcome>,
4709 pub uuid: String,
4710 pub session_id: String,
4711 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
4712 pub extra: serde_json::Map<String, Value>,
4713}
4714
4715#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4717pub enum PeerMessageHoldState {
4718 Held,
4720 Released,
4722 Dropped,
4724 Unknown(String),
4726}
4727
4728impl PeerMessageHoldState {
4729 pub fn as_str(&self) -> &str {
4730 match self {
4731 Self::Held => "held",
4732 Self::Released => "released",
4733 Self::Dropped => "dropped",
4734 Self::Unknown(s) => s.as_str(),
4735 }
4736 }
4737}
4738
4739impl fmt::Display for PeerMessageHoldState {
4740 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4741 f.write_str(self.as_str())
4742 }
4743}
4744
4745impl From<&str> for PeerMessageHoldState {
4746 fn from(s: &str) -> Self {
4747 match s {
4748 "held" => Self::Held,
4749 "released" => Self::Released,
4750 "dropped" => Self::Dropped,
4751 other => Self::Unknown(other.to_string()),
4752 }
4753 }
4754}
4755
4756impl Serialize for PeerMessageHoldState {
4757 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4758 serializer.serialize_str(self.as_str())
4759 }
4760}
4761
4762impl<'de> Deserialize<'de> for PeerMessageHoldState {
4763 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4764 let s = String::deserialize(deserializer)?;
4765 Ok(Self::from(s.as_str()))
4766 }
4767}
4768
4769#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4771pub enum PeerMessageLane {
4772 Bridge,
4774 Stdin,
4776 Socket,
4778 Unknown(String),
4780}
4781
4782impl PeerMessageLane {
4783 pub fn as_str(&self) -> &str {
4784 match self {
4785 Self::Bridge => "bridge",
4786 Self::Stdin => "stdin",
4787 Self::Socket => "socket",
4788 Self::Unknown(s) => s.as_str(),
4789 }
4790 }
4791}
4792
4793impl fmt::Display for PeerMessageLane {
4794 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4795 f.write_str(self.as_str())
4796 }
4797}
4798
4799impl From<&str> for PeerMessageLane {
4800 fn from(s: &str) -> Self {
4801 match s {
4802 "bridge" => Self::Bridge,
4803 "stdin" => Self::Stdin,
4804 "socket" => Self::Socket,
4805 other => Self::Unknown(other.to_string()),
4806 }
4807 }
4808}
4809
4810impl Serialize for PeerMessageLane {
4811 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4812 serializer.serialize_str(self.as_str())
4813 }
4814}
4815
4816impl<'de> Deserialize<'de> for PeerMessageLane {
4817 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4818 let s = String::deserialize(deserializer)?;
4819 Ok(Self::from(s.as_str()))
4820 }
4821}
4822
4823#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4830pub enum PeerMessageHoldCause {
4831 ExplicitSetting,
4832 ManagedSetting,
4833 RepoSetting,
4834 InvalidSetting,
4835 BypassDefault,
4836 ModeUnknown,
4837 ModeMismatch,
4838 NoModeAsserted,
4839 Unknown(String),
4841}
4842
4843impl PeerMessageHoldCause {
4844 pub fn as_str(&self) -> &str {
4845 match self {
4846 Self::ExplicitSetting => "explicit-setting",
4847 Self::ManagedSetting => "managed-setting",
4848 Self::RepoSetting => "repo-setting",
4849 Self::InvalidSetting => "invalid-setting",
4850 Self::BypassDefault => "bypass-default",
4851 Self::ModeUnknown => "mode-unknown",
4852 Self::ModeMismatch => "mode-mismatch",
4853 Self::NoModeAsserted => "no-mode-asserted",
4854 Self::Unknown(s) => s.as_str(),
4855 }
4856 }
4857}
4858
4859impl fmt::Display for PeerMessageHoldCause {
4860 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4861 f.write_str(self.as_str())
4862 }
4863}
4864
4865impl From<&str> for PeerMessageHoldCause {
4866 fn from(s: &str) -> Self {
4867 match s {
4868 "explicit-setting" => Self::ExplicitSetting,
4869 "managed-setting" => Self::ManagedSetting,
4870 "repo-setting" => Self::RepoSetting,
4871 "invalid-setting" => Self::InvalidSetting,
4872 "bypass-default" => Self::BypassDefault,
4873 "mode-unknown" => Self::ModeUnknown,
4874 "mode-mismatch" => Self::ModeMismatch,
4875 "no-mode-asserted" => Self::NoModeAsserted,
4876 other => Self::Unknown(other.to_string()),
4877 }
4878 }
4879}
4880
4881impl Serialize for PeerMessageHoldCause {
4882 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4883 serializer.serialize_str(self.as_str())
4884 }
4885}
4886
4887impl<'de> Deserialize<'de> for PeerMessageHoldCause {
4888 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4889 let s = String::deserialize(deserializer)?;
4890 Ok(Self::from(s.as_str()))
4891 }
4892}
4893
4894#[derive(Debug, Clone, PartialEq, Eq, Hash)]
4897pub enum PeerMessageHoldOutcome {
4898 Expired,
4902 Refused,
4904 Dropped,
4907 Discarded,
4909 Unknown(String),
4911}
4912
4913impl PeerMessageHoldOutcome {
4914 pub fn as_str(&self) -> &str {
4915 match self {
4916 Self::Expired => "expired",
4917 Self::Refused => "refused",
4918 Self::Dropped => "dropped",
4919 Self::Discarded => "discarded",
4920 Self::Unknown(s) => s.as_str(),
4921 }
4922 }
4923}
4924
4925impl fmt::Display for PeerMessageHoldOutcome {
4926 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4927 f.write_str(self.as_str())
4928 }
4929}
4930
4931impl From<&str> for PeerMessageHoldOutcome {
4932 fn from(s: &str) -> Self {
4933 match s {
4934 "expired" => Self::Expired,
4935 "refused" => Self::Refused,
4936 "dropped" => Self::Dropped,
4937 "discarded" => Self::Discarded,
4938 other => Self::Unknown(other.to_string()),
4939 }
4940 }
4941}
4942
4943impl Serialize for PeerMessageHoldOutcome {
4944 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
4945 serializer.serialize_str(self.as_str())
4946 }
4947}
4948
4949impl<'de> Deserialize<'de> for PeerMessageHoldOutcome {
4950 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
4951 let s = String::deserialize(deserializer)?;
4952 Ok(Self::from(s.as_str()))
4953 }
4954}
4955
4956#[derive(Debug, Clone, Serialize, Deserialize)]
4967pub struct PerTurnEffortChangedMessage {
4968 pub per_turn_effort_active: bool,
4970 pub uuid: String,
4971 pub session_id: String,
4972}
4973
4974#[derive(Debug, Clone, Serialize, Deserialize)]
4981pub struct InstructionSizeWarningMessage {
4982 pub total_chars: u64,
4985 pub total_limit_chars: u64,
4988 pub file_count: u64,
4991 #[serde(default, skip_serializing_if = "Option::is_none")]
4995 pub largest_chars: Option<u64>,
4996 pub uuid: String,
4997 pub session_id: String,
4998}
4999
5000#[derive(Debug, Clone, Serialize, Deserialize)]
5007pub struct FileAttachmentsMissingMessage {
5008 pub message_uuid: String,
5011 pub sent_count: u64,
5013 pub missing: Vec<MissingFileAttachment>,
5015 pub uuid: String,
5016 pub session_id: String,
5017}
5018
5019#[derive(Debug, Clone, Serialize, Deserialize)]
5029pub struct PermissionCheckStatusMessage {
5030 pub tool_use_id: String,
5031 #[serde(default, skip_serializing_if = "Option::is_none")]
5034 pub agent_id: Option<String>,
5035 pub status: PermissionCheckStatus,
5036 pub uuid: String,
5037 pub session_id: String,
5038}
5039
5040#[derive(Debug, Clone, Serialize, Deserialize)]
5045pub struct InheritedAsksSettledMessage {
5046 pub kept_request_ids: Vec<String>,
5049 pub uuid: String,
5050 pub session_id: String,
5051}
5052
5053#[derive(Debug, Clone, Serialize, Deserialize)]
5060pub struct LateAllowNotRunMessage {
5061 pub request_id: String,
5064 pub tool_use_id: String,
5066 pub reason: LateAllowNotRunReason,
5068 pub uuid: String,
5069 pub session_id: String,
5070}
5071
5072#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5075pub enum LateAllowNotRunReason {
5076 TurnRunning,
5077 CardOpen,
5078 CallGone,
5079 InvalidAnswer,
5080 Limited,
5081 Stopped,
5082 Declined,
5083 AskedAgain,
5084 Withdrawn,
5085 Expired,
5086 NotRun,
5087 Unknown(String),
5089}
5090
5091impl LateAllowNotRunReason {
5092 pub fn as_str(&self) -> &str {
5093 match self {
5094 Self::TurnRunning => "turn_running",
5095 Self::CardOpen => "card_open",
5096 Self::CallGone => "call_gone",
5097 Self::InvalidAnswer => "invalid_answer",
5098 Self::Limited => "limited",
5099 Self::Stopped => "stopped",
5100 Self::Declined => "declined",
5101 Self::AskedAgain => "asked_again",
5102 Self::Withdrawn => "withdrawn",
5103 Self::Expired => "expired",
5104 Self::NotRun => "not_run",
5105 Self::Unknown(s) => s.as_str(),
5106 }
5107 }
5108}
5109
5110impl fmt::Display for LateAllowNotRunReason {
5111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5112 f.write_str(self.as_str())
5113 }
5114}
5115
5116impl From<&str> for LateAllowNotRunReason {
5117 fn from(s: &str) -> Self {
5118 match s {
5119 "turn_running" => Self::TurnRunning,
5120 "card_open" => Self::CardOpen,
5121 "call_gone" => Self::CallGone,
5122 "invalid_answer" => Self::InvalidAnswer,
5123 "limited" => Self::Limited,
5124 "stopped" => Self::Stopped,
5125 "declined" => Self::Declined,
5126 "asked_again" => Self::AskedAgain,
5127 "withdrawn" => Self::Withdrawn,
5128 "expired" => Self::Expired,
5129 "not_run" => Self::NotRun,
5130 other => Self::Unknown(other.to_string()),
5131 }
5132 }
5133}
5134
5135impl Serialize for LateAllowNotRunReason {
5136 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5137 serializer.serialize_str(self.as_str())
5138 }
5139}
5140
5141impl<'de> Deserialize<'de> for LateAllowNotRunReason {
5142 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5143 let s = String::deserialize(deserializer)?;
5144 Ok(Self::from(s.as_str()))
5145 }
5146}
5147
5148#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5150pub enum PermissionCheckStatus {
5151 Checking,
5154 Done,
5156 Unknown(String),
5158}
5159
5160impl PermissionCheckStatus {
5161 pub fn as_str(&self) -> &str {
5162 match self {
5163 Self::Checking => "checking",
5164 Self::Done => "done",
5165 Self::Unknown(s) => s.as_str(),
5166 }
5167 }
5168}
5169
5170impl fmt::Display for PermissionCheckStatus {
5171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5172 f.write_str(self.as_str())
5173 }
5174}
5175
5176impl From<&str> for PermissionCheckStatus {
5177 fn from(s: &str) -> Self {
5178 match s {
5179 "checking" => Self::Checking,
5180 "done" => Self::Done,
5181 other => Self::Unknown(other.to_string()),
5182 }
5183 }
5184}
5185
5186impl Serialize for PermissionCheckStatus {
5187 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5188 serializer.serialize_str(self.as_str())
5189 }
5190}
5191
5192impl<'de> Deserialize<'de> for PermissionCheckStatus {
5193 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5194 let s = String::deserialize(deserializer)?;
5195 Ok(Self::from(s.as_str()))
5196 }
5197}
5198
5199#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5201pub struct MissingFileAttachment {
5202 pub file_uuid: String,
5204 pub reason: String,
5209}
5210
5211#[derive(Debug, Clone, Serialize, Deserialize)]
5221pub struct SessionTitleChangedMessage {
5222 pub title: String,
5227 pub uuid: String,
5228 pub session_id: String,
5229}
5230
5231#[derive(Debug, Clone, Serialize, Deserialize)]
5241pub struct SessionWritesLostMessage {
5242 pub error_code: SessionWriteErrorCode,
5245 pub lost: Vec<LostSessionWrite>,
5247 #[serde(default, skip_serializing_if = "Option::is_none")]
5253 pub transcript_session_ids: Option<Vec<String>>,
5254 pub uuid: String,
5255 pub session_id: String,
5259}
5260
5261#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5263pub enum SessionWriteErrorCode {
5264 Enospc,
5266 Edquot,
5268 Unknown(String),
5270}
5271
5272impl SessionWriteErrorCode {
5273 pub fn as_str(&self) -> &str {
5274 match self {
5275 Self::Enospc => "ENOSPC",
5276 Self::Edquot => "EDQUOT",
5277 Self::Unknown(s) => s.as_str(),
5278 }
5279 }
5280}
5281
5282impl fmt::Display for SessionWriteErrorCode {
5283 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5284 f.write_str(self.as_str())
5285 }
5286}
5287
5288impl From<&str> for SessionWriteErrorCode {
5289 fn from(s: &str) -> Self {
5290 match s {
5291 "ENOSPC" => Self::Enospc,
5292 "EDQUOT" => Self::Edquot,
5293 other => Self::Unknown(other.to_string()),
5294 }
5295 }
5296}
5297
5298impl Serialize for SessionWriteErrorCode {
5299 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5300 serializer.serialize_str(self.as_str())
5301 }
5302}
5303
5304impl<'de> Deserialize<'de> for SessionWriteErrorCode {
5305 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5306 let s = String::deserialize(deserializer)?;
5307 Ok(Self::from(s.as_str()))
5308 }
5309}
5310
5311#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5313pub enum LostSessionWrite {
5314 Transcript,
5317 GlobalConfig,
5319 Unknown(String),
5321}
5322
5323impl LostSessionWrite {
5324 pub fn as_str(&self) -> &str {
5325 match self {
5326 Self::Transcript => "transcript",
5327 Self::GlobalConfig => "global_config",
5328 Self::Unknown(s) => s.as_str(),
5329 }
5330 }
5331}
5332
5333impl fmt::Display for LostSessionWrite {
5334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5335 f.write_str(self.as_str())
5336 }
5337}
5338
5339impl From<&str> for LostSessionWrite {
5340 fn from(s: &str) -> Self {
5341 match s {
5342 "transcript" => Self::Transcript,
5343 "global_config" => Self::GlobalConfig,
5344 other => Self::Unknown(other.to_string()),
5345 }
5346 }
5347}
5348
5349impl Serialize for LostSessionWrite {
5350 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5351 serializer.serialize_str(self.as_str())
5352 }
5353}
5354
5355impl<'de> Deserialize<'de> for LostSessionWrite {
5356 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5357 let s = String::deserialize(deserializer)?;
5358 Ok(Self::from(s.as_str()))
5359 }
5360}
5361
5362#[derive(Debug, Clone, Serialize, Deserialize)]
5366pub struct UiLogMessage {
5367 pub plugin: String,
5369 pub text: String,
5373 pub uuid: String,
5374 pub session_id: String,
5375}
5376
5377#[derive(Debug, Clone, Serialize, Deserialize)]
5382pub struct UiNotifyMessage {
5383 pub plugin: String,
5388 pub source: String,
5392 pub title: String,
5396 pub text: String,
5400 #[serde(default, skip_serializing_if = "Option::is_none")]
5404 pub key: Option<String>,
5405 #[serde(default, skip_serializing_if = "Option::is_none")]
5409 pub delay_ms: Option<u64>,
5410 #[serde(default, skip_serializing_if = "Option::is_none")]
5413 pub at: Option<u64>,
5414 #[serde(default, skip_serializing_if = "Option::is_none")]
5417 pub until_back: Option<bool>,
5418 #[serde(default)]
5423 pub rewritten: bool,
5424 pub uuid: String,
5425 pub session_id: String,
5426}
5427
5428#[derive(Debug, Clone, Serialize, Deserialize)]
5433pub struct UiNotifyCancelMessage {
5434 pub plugin: String,
5437 pub source: String,
5440 #[serde(default, skip_serializing_if = "Option::is_none")]
5445 pub key: Option<String>,
5446 pub uuid: String,
5447 pub session_id: String,
5448}
5449
5450#[derive(Debug, Clone, Serialize, Deserialize)]
5455pub struct UiToastMessage {
5456 pub plugin: String,
5458 pub text: String,
5462 pub timeout_ms: u64,
5465 pub uuid: String,
5466 pub session_id: String,
5467}
5468
5469#[derive(Debug, Clone, Serialize, Deserialize)]
5473pub struct UiStatusMessage {
5474 pub plugin: String,
5476 pub text: Option<String>,
5481 pub uuid: String,
5482 pub session_id: String,
5483}
5484
5485#[derive(Debug, Clone, Serialize, Deserialize)]
5492pub struct UiInvalidateMessage {
5493 pub event: String,
5496 #[serde(default, skip_serializing_if = "Option::is_none")]
5508 pub instances: Option<Vec<UiInvalidatedInstance>>,
5509 #[serde(default, skip_serializing_if = "Option::is_none")]
5517 pub prompts_screened: Option<bool>,
5518 pub uuid: String,
5519 pub session_id: String,
5520}
5521
5522#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5524pub struct UiInvalidatedInstance {
5525 pub surface: String,
5527 pub component: String,
5529 pub instance_id: String,
5532}
5533
5534#[derive(Debug, Clone, Serialize, Deserialize)]
5541pub struct UiPanesMessage {
5542 pub panes: Vec<UiPane>,
5545 pub shown_id: Option<String>,
5548 pub focused_id: Option<String>,
5551 pub focus_requested_id: Option<String>,
5555 pub uuid: String,
5556 pub session_id: String,
5557}
5558
5559#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5561pub struct UiPane {
5562 pub id: String,
5565 pub title: String,
5568 pub plugin: String,
5570 #[serde(default, skip_serializing_if = "Option::is_none")]
5573 pub close_on_escape: Option<bool>,
5574 #[serde(default, skip_serializing_if = "Option::is_none")]
5577 pub hold_toasts: Option<bool>,
5578 #[serde(default, skip_serializing_if = "Option::is_none")]
5583 pub background_color: Option<String>,
5584 #[serde(default, skip_serializing_if = "Option::is_none")]
5587 pub rows: Option<u64>,
5588 #[serde(default, skip_serializing_if = "Option::is_none")]
5591 pub columns: Option<u64>,
5592 #[serde(default, skip_serializing_if = "Option::is_none")]
5599 pub placement: Option<String>,
5600}
5601
5602#[derive(Debug, Clone, Serialize, Deserialize)]
5610pub struct UiPlacedMessage {
5611 pub rows: Vec<UiPlacedRow>,
5613 pub uuid: String,
5614 pub session_id: String,
5615}
5616
5617#[derive(Debug, Clone, Serialize, Deserialize)]
5619pub struct UiPlacedRow {
5620 pub plugin: String,
5622 pub id: String,
5624 pub request_id: String,
5627 #[serde(default, skip_serializing_if = "Option::is_none")]
5630 pub after_uuid: Option<String>,
5631}
5632
5633#[derive(Debug, Clone, Serialize, Deserialize)]
5637pub struct UiScrollMessage {
5638 pub client_id: String,
5640 pub component: UiSiteComponent,
5642 pub instance_id: String,
5644 pub offset: u64,
5647 #[serde(default, skip_serializing_if = "Option::is_none")]
5650 pub follow_end: Option<bool>,
5651 pub uuid: String,
5652 pub session_id: String,
5653}
5654
5655#[derive(Debug, Clone, Serialize, Deserialize)]
5660pub struct UiFocusMessage {
5661 pub client_id: String,
5663 pub component: UiSiteComponent,
5665 pub instance_id: String,
5667 pub plugin: String,
5669 pub key: String,
5671 pub uuid: String,
5672 pub session_id: String,
5673}
5674
5675#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5677pub enum UiSiteComponent {
5678 Pane,
5680 AbovePrompt,
5682 Unknown(String),
5684}
5685
5686impl UiSiteComponent {
5687 pub fn as_str(&self) -> &str {
5688 match self {
5689 Self::Pane => "Pane",
5690 Self::AbovePrompt => "AbovePrompt",
5691 Self::Unknown(s) => s.as_str(),
5692 }
5693 }
5694}
5695
5696impl fmt::Display for UiSiteComponent {
5697 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5698 f.write_str(self.as_str())
5699 }
5700}
5701
5702impl From<&str> for UiSiteComponent {
5703 fn from(s: &str) -> Self {
5704 match s {
5705 "Pane" => Self::Pane,
5706 "AbovePrompt" => Self::AbovePrompt,
5707 other => Self::Unknown(other.to_string()),
5708 }
5709 }
5710}
5711
5712impl Serialize for UiSiteComponent {
5713 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5714 serializer.serialize_str(self.as_str())
5715 }
5716}
5717
5718impl<'de> Deserialize<'de> for UiSiteComponent {
5719 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5720 let s = String::deserialize(deserializer)?;
5721 Ok(Self::from(s.as_str()))
5722 }
5723}
5724
5725#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
5728pub struct LocalCommandRun {
5729 pub command: String,
5731 pub args: String,
5734 #[serde(default, skip_serializing_if = "Option::is_none")]
5739 pub plugin: Option<String>,
5740}
5741
5742#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
5746pub struct LocalCommandOutcome {
5747 pub kind: LocalCommandOutcomeKind,
5748 #[serde(default, skip_serializing_if = "Option::is_none")]
5751 pub suggestion: Option<String>,
5752}
5753
5754#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5759pub enum LocalCommandOutcomeKind {
5760 UnavailableHeadless,
5762 Unknown,
5765 Failed,
5767 RestartRequired,
5769 Other(String),
5771}
5772
5773impl LocalCommandOutcomeKind {
5774 pub fn as_str(&self) -> &str {
5775 match self {
5776 Self::UnavailableHeadless => "unavailable_headless",
5777 Self::Unknown => "unknown",
5778 Self::Failed => "failed",
5779 Self::RestartRequired => "restart_required",
5780 Self::Other(s) => s.as_str(),
5781 }
5782 }
5783}
5784
5785impl fmt::Display for LocalCommandOutcomeKind {
5786 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5787 f.write_str(self.as_str())
5788 }
5789}
5790
5791impl From<&str> for LocalCommandOutcomeKind {
5792 fn from(s: &str) -> Self {
5793 match s {
5794 "unavailable_headless" => Self::UnavailableHeadless,
5795 "unknown" => Self::Unknown,
5796 "failed" => Self::Failed,
5797 "restart_required" => Self::RestartRequired,
5798 other => Self::Other(other.to_string()),
5799 }
5800 }
5801}
5802
5803impl Serialize for LocalCommandOutcomeKind {
5804 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
5805 serializer.serialize_str(self.as_str())
5806 }
5807}
5808
5809impl<'de> Deserialize<'de> for LocalCommandOutcomeKind {
5810 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
5811 let s = String::deserialize(deserializer)?;
5812 Ok(Self::from(s.as_str()))
5813 }
5814}
5815
5816#[derive(Debug, Clone, Serialize, Deserialize)]
5822pub struct UsageReport {
5823 pub session: super::control::UsageSession,
5825 pub rate_limits: Option<UsageReportRateLimits>,
5829 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
5830 pub extra: serde_json::Map<String, Value>,
5831}
5832
5833#[derive(Debug, Clone, Serialize, Deserialize)]
5835pub struct UsageReportRateLimits {
5836 pub limits: Option<Vec<UsageReportLimit>>,
5844 #[serde(default, skip_serializing_if = "Option::is_none")]
5847 pub extra_usage: Option<UsageReportExtraUsage>,
5848 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
5849 pub extra: serde_json::Map<String, Value>,
5850}
5851
5852#[derive(Debug, Clone, Serialize, Deserialize)]
5854pub struct UsageReportLimit {
5855 pub kind: String,
5858 pub group: String,
5861 pub percent: f64,
5863 pub resets_at: Option<String>,
5865 #[serde(default, skip_serializing_if = "Option::is_none")]
5868 pub scope: Option<UsageReportScope>,
5869 #[serde(default, skip_serializing_if = "Option::is_none")]
5873 pub severity: Option<String>,
5874 #[serde(default, skip_serializing_if = "Option::is_none")]
5876 pub is_active: Option<bool>,
5877 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
5878 pub extra: serde_json::Map<String, Value>,
5879}
5880
5881#[derive(Debug, Clone, Serialize, Deserialize)]
5883pub struct UsageReportScope {
5884 #[serde(default, skip_serializing_if = "Option::is_none")]
5885 pub model: Option<UsageReportScopeLabel>,
5886 #[serde(default, skip_serializing_if = "Option::is_none")]
5887 pub surface: Option<UsageReportScopeLabel>,
5888 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
5889 pub extra: serde_json::Map<String, Value>,
5890}
5891
5892#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
5894pub struct UsageReportScopeLabel {
5895 pub display_name: String,
5896}
5897
5898#[derive(Debug, Clone, Serialize, Deserialize)]
5902pub struct UsageReportExtraUsage {
5903 pub is_enabled: bool,
5905 pub monthly_limit: Option<f64>,
5906 pub used_credits: Option<f64>,
5907 pub utilization: Option<f64>,
5908 #[serde(default, skip_serializing_if = "Option::is_none")]
5909 pub currency: Option<String>,
5910 #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
5911 pub extra: serde_json::Map<String, Value>,
5912}
5913
5914#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
5917pub struct BatchToolUse {
5918 pub id: String,
5919 pub name: String,
5920}
5921
5922#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
5927pub struct ContextUsage {
5928 pub model: String,
5930 pub total_tokens: u64,
5933 pub raw_max_tokens: u64,
5936 pub percentage: u64,
5938 #[serde(default, skip_serializing_if = "Option::is_none")]
5940 pub over_limit: Option<ContextOverLimit>,
5941 #[serde(default)]
5943 pub categories: Vec<ContextCategory>,
5944 #[serde(default)]
5946 pub mcp_tools: Vec<ContextMcpTool>,
5947 #[serde(default)]
5949 pub memory_files: Vec<ContextMemoryFile>,
5950 #[serde(default)]
5952 pub agents: Vec<ContextAgent>,
5953 #[serde(default, skip_serializing_if = "Option::is_none")]
5955 pub skills: Option<Vec<ContextSkill>>,
5956}
5957
5958#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
5960pub struct ContextOverLimit {
5961 pub tokens_over: u64,
5962 pub kind: String,
5965}
5966
5967#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
5969pub struct ContextCategory {
5970 pub name: String,
5973 pub tokens: u64,
5974 pub kind: String,
5978}
5979
5980#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
5982pub struct ContextMcpTool {
5983 pub name: String,
5985 pub server_name: String,
5986 pub tokens: u64,
5987}
5988
5989#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
5991pub struct ContextMemoryFile {
5992 pub path: String,
5993 #[serde(rename = "type")]
5995 pub file_type: String,
5996 pub tokens: u64,
5997}
5998
5999#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6001pub struct ContextAgent {
6002 pub agent_type: String,
6003 pub source: String,
6005 pub tokens: u64,
6006}
6007
6008#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6010pub struct ContextSkill {
6011 pub name: String,
6012 pub source: String,
6014 #[serde(default, skip_serializing_if = "Option::is_none")]
6015 pub plugin_name: Option<String>,
6016 pub tokens: u64,
6017}
6018
6019#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
6021pub struct ToolUseMeta {
6022 pub id: String,
6023 pub display_name: String,
6024 #[serde(default, skip_serializing_if = "Option::is_none")]
6025 pub server_display_name: Option<String>,
6026 #[serde(default, skip_serializing_if = "Option::is_none")]
6027 pub icon_url: Option<String>,
6028 #[serde(default, skip_serializing_if = "Option::is_none")]
6033 pub server_id: Option<String>,
6034 #[serde(default, skip_serializing_if = "Option::is_none")]
6042 pub server_id_stamp: Option<String>,
6043 #[serde(default, skip_serializing_if = "Option::is_none")]
6046 pub tool_name: Option<String>,
6047 #[serde(default, skip_serializing_if = "Option::is_none")]
6056 pub artifact_publish: Option<bool>,
6057}
6058
6059#[derive(Debug, Clone, Serialize, Deserialize)]
6061pub struct AssistantMessage {
6062 pub message: AssistantMessageContent,
6063 #[serde(alias = "sessionId")]
6064 pub session_id: String,
6065 #[serde(skip_serializing_if = "Option::is_none")]
6066 pub uuid: Option<String>,
6067 #[serde(skip_serializing_if = "Option::is_none")]
6068 pub parent_tool_use_id: Option<String>,
6069 #[serde(skip_serializing_if = "Option::is_none")]
6071 pub request_id: Option<String>,
6072 #[serde(default, skip_serializing_if = "Option::is_none")]
6077 pub refused_message_id: Option<String>,
6078 #[serde(default, skip_serializing_if = "Option::is_none")]
6087 pub user_message_uuid: Option<String>,
6088 #[serde(default, skip_serializing_if = "Vec::is_empty")]
6094 pub user_message_uuids: Vec<String>,
6095 #[serde(default, skip_serializing_if = "Option::is_none")]
6099 pub agent_id: Option<String>,
6100 #[serde(skip_serializing_if = "Option::is_none")]
6103 pub subagent_type: Option<String>,
6104 #[serde(skip_serializing_if = "Option::is_none")]
6106 pub task_description: Option<String>,
6107 #[serde(skip_serializing_if = "Option::is_none")]
6108 pub error: Option<AssistantErrorKind>,
6109 #[serde(default, skip_serializing_if = "Option::is_none")]
6113 pub aborted: Option<bool>,
6114 #[serde(default, skip_serializing_if = "Option::is_none")]
6119 pub resumed_from_incomplete_thinking: Option<bool>,
6120 #[serde(default, skip_serializing_if = "Vec::is_empty")]
6127 pub supersedes: Vec<String>,
6128 #[serde(skip_serializing_if = "Option::is_none")]
6129 pub timestamp: Option<String>,
6130 #[serde(default, skip_serializing_if = "Vec::is_empty")]
6131 pub tool_use_meta: Vec<ToolUseMeta>,
6132 #[serde(default, skip_serializing_if = "Vec::is_empty")]
6137 pub batch_tool_uses: Vec<BatchToolUse>,
6138 #[serde(default, skip_serializing_if = "Option::is_none")]
6144 pub wire_tool_inputs: Option<serde_json::Map<String, Value>>,
6145 #[serde(default, skip_serializing_if = "Option::is_none")]
6151 pub wire_ingest_context: Option<serde_json::Map<String, Value>>,
6152 #[serde(default, skip_serializing_if = "Option::is_none")]
6156 pub historical: Option<bool>,
6157 #[serde(default, skip_serializing_if = "Option::is_none")]
6165 pub resume_reason: Option<String>,
6166 #[serde(default, skip_serializing_if = "Option::is_none")]
6172 pub local_command_source: Option<String>,
6173 #[serde(default, skip_serializing_if = "Vec::is_empty")]
6182 pub narration_block_indexes: Vec<usize>,
6183 #[serde(default, skip_serializing_if = "Option::is_none")]
6187 pub narration_hint: Option<String>,
6188 #[serde(default, skip_serializing_if = "Option::is_none")]
6197 pub thinking_duration_ms: Option<u64>,
6198 #[serde(default, skip_serializing_if = "Option::is_none")]
6209 pub thinking_display: Option<String>,
6210 #[serde(default, skip_serializing_if = "Option::is_none")]
6214 pub context_usage: Option<ContextUsage>,
6215 #[serde(default, skip_serializing_if = "Option::is_none")]
6223 pub usage_report: Option<Box<UsageReport>>,
6224 #[serde(default, skip_serializing_if = "Option::is_none")]
6231 pub local_command_run: Option<LocalCommandRun>,
6232 #[serde(default, skip_serializing_if = "Option::is_none")]
6238 pub local_command_outcome: Option<LocalCommandOutcome>,
6239 #[serde(default, skip_serializing_if = "Option::is_none")]
6240 pub is_meta: Option<bool>,
6241 #[serde(default, skip_serializing_if = "Option::is_none")]
6242 pub is_virtual: Option<bool>,
6243 #[serde(default, skip_serializing_if = "Option::is_none")]
6244 pub is_api_error_message: Option<bool>,
6245 #[serde(skip_serializing_if = "Option::is_none")]
6246 pub api_error_status: Option<u16>,
6247 #[serde(skip_serializing_if = "Option::is_none")]
6302 pub api_error: Option<String>,
6303 #[serde(default, skip_serializing_if = "Option::is_none")]
6310 pub api_error_code: Option<String>,
6311 #[serde(default, skip_serializing_if = "Option::is_none")]
6323 pub api_error_type: Option<String>,
6324 #[serde(default, skip_serializing_if = "Option::is_none")]
6335 pub api_error_origin: Option<String>,
6336 #[serde(default, skip_serializing_if = "Option::is_none")]
6339 pub api_error_params: Option<ApiErrorParams>,
6340 #[serde(skip_serializing_if = "Option::is_none")]
6341 pub error_details: Option<String>,
6342 #[serde(skip_serializing_if = "Option::is_none")]
6343 pub advisor_model: Option<String>,
6344 #[serde(skip_serializing_if = "Option::is_none")]
6345 pub attribution_agent: Option<String>,
6346 #[serde(skip_serializing_if = "Option::is_none")]
6347 pub attribution_skill: Option<String>,
6348 #[serde(skip_serializing_if = "Option::is_none")]
6349 pub attribution_plugin: Option<String>,
6350 #[serde(skip_serializing_if = "Option::is_none")]
6351 pub attribution_mcp_server: Option<String>,
6352 #[serde(skip_serializing_if = "Option::is_none")]
6353 pub attribution_mcp_tool: Option<String>,
6354}
6355
6356#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
6360pub struct ApiErrorParams {
6361 #[serde(default, skip_serializing_if = "Option::is_none")]
6363 pub effort: Option<String>,
6364 #[serde(default, skip_serializing_if = "Option::is_none")]
6367 pub provider: Option<ApiErrorProvider>,
6368 #[serde(default, skip_serializing_if = "Option::is_none")]
6371 pub remedy: Option<ApiErrorRemedy>,
6372 #[serde(default, skip_serializing_if = "Option::is_none")]
6375 pub media: Option<ApiErrorMedia>,
6376 #[serde(default, skip_serializing_if = "Option::is_none")]
6378 pub media_reason: Option<ApiErrorMediaReason>,
6379 #[serde(default, skip_serializing_if = "Option::is_none")]
6401 pub rate_limit_info: Option<RateLimitInfo>,
6402 #[serde(default, skip_serializing_if = "Option::is_none")]
6407 pub cut: Option<ApiErrorCut>,
6408}
6409
6410#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6412pub enum ApiErrorCut {
6413 OutputLimit,
6415 ContextWindow,
6417 Unknown(String),
6419}
6420
6421impl ApiErrorCut {
6422 pub fn as_str(&self) -> &str {
6423 match self {
6424 Self::OutputLimit => "output_limit",
6425 Self::ContextWindow => "context_window",
6426 Self::Unknown(s) => s.as_str(),
6427 }
6428 }
6429}
6430
6431impl fmt::Display for ApiErrorCut {
6432 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6433 f.write_str(self.as_str())
6434 }
6435}
6436
6437impl From<&str> for ApiErrorCut {
6438 fn from(s: &str) -> Self {
6439 match s {
6440 "output_limit" => Self::OutputLimit,
6441 "context_window" => Self::ContextWindow,
6442 other => Self::Unknown(other.to_string()),
6443 }
6444 }
6445}
6446
6447impl Serialize for ApiErrorCut {
6448 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6449 serializer.serialize_str(self.as_str())
6450 }
6451}
6452
6453impl<'de> Deserialize<'de> for ApiErrorCut {
6454 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6455 let s = String::deserialize(deserializer)?;
6456 Ok(Self::from(s.as_str()))
6457 }
6458}
6459
6460#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6462pub enum ApiErrorMedia {
6463 Image,
6464 Document,
6465 Unknown(String),
6467}
6468
6469impl ApiErrorMedia {
6470 pub fn as_str(&self) -> &str {
6471 match self {
6472 Self::Image => "image",
6473 Self::Document => "document",
6474 Self::Unknown(s) => s.as_str(),
6475 }
6476 }
6477}
6478
6479impl fmt::Display for ApiErrorMedia {
6480 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6481 f.write_str(self.as_str())
6482 }
6483}
6484
6485impl From<&str> for ApiErrorMedia {
6486 fn from(s: &str) -> Self {
6487 match s {
6488 "image" => Self::Image,
6489 "document" => Self::Document,
6490 other => Self::Unknown(other.to_string()),
6491 }
6492 }
6493}
6494
6495impl Serialize for ApiErrorMedia {
6496 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6497 serializer.serialize_str(self.as_str())
6498 }
6499}
6500
6501impl<'de> Deserialize<'de> for ApiErrorMedia {
6502 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6503 let s = String::deserialize(deserializer)?;
6504 Ok(Self::from(s.as_str()))
6505 }
6506}
6507
6508#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6511pub enum ApiErrorMediaReason {
6512 Unprocessable,
6515 UnsupportedByModel,
6517 MediaBudget,
6520 Unknown(String),
6522}
6523
6524impl ApiErrorMediaReason {
6525 pub fn as_str(&self) -> &str {
6526 match self {
6527 Self::Unprocessable => "unprocessable",
6528 Self::UnsupportedByModel => "unsupported_by_model",
6529 Self::MediaBudget => "media_budget",
6530 Self::Unknown(s) => s.as_str(),
6531 }
6532 }
6533}
6534
6535impl fmt::Display for ApiErrorMediaReason {
6536 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6537 f.write_str(self.as_str())
6538 }
6539}
6540
6541impl From<&str> for ApiErrorMediaReason {
6542 fn from(s: &str) -> Self {
6543 match s {
6544 "unprocessable" => Self::Unprocessable,
6545 "unsupported_by_model" => Self::UnsupportedByModel,
6546 "media_budget" => Self::MediaBudget,
6547 other => Self::Unknown(other.to_string()),
6548 }
6549 }
6550}
6551
6552impl Serialize for ApiErrorMediaReason {
6553 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6554 serializer.serialize_str(self.as_str())
6555 }
6556}
6557
6558impl<'de> Deserialize<'de> for ApiErrorMediaReason {
6559 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6560 let s = String::deserialize(deserializer)?;
6561 Ok(Self::from(s.as_str()))
6562 }
6563}
6564
6565#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6567pub enum ApiErrorProvider {
6568 Bedrock,
6569 AnthropicAws,
6570 Mantle,
6571 AnthropicGoogleCloud,
6572 Vertex,
6573 Foundry,
6574 Gateway,
6575 Unknown(String),
6577}
6578
6579impl ApiErrorProvider {
6580 pub fn as_str(&self) -> &str {
6581 match self {
6582 Self::Bedrock => "bedrock",
6583 Self::AnthropicAws => "anthropicAws",
6584 Self::Mantle => "mantle",
6585 Self::AnthropicGoogleCloud => "anthropicGoogleCloud",
6586 Self::Vertex => "vertex",
6587 Self::Foundry => "foundry",
6588 Self::Gateway => "gateway",
6589 Self::Unknown(s) => s.as_str(),
6590 }
6591 }
6592}
6593
6594impl fmt::Display for ApiErrorProvider {
6595 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6596 f.write_str(self.as_str())
6597 }
6598}
6599
6600impl From<&str> for ApiErrorProvider {
6601 fn from(s: &str) -> Self {
6602 match s {
6603 "bedrock" => Self::Bedrock,
6604 "anthropicAws" => Self::AnthropicAws,
6605 "mantle" => Self::Mantle,
6606 "anthropicGoogleCloud" => Self::AnthropicGoogleCloud,
6607 "vertex" => Self::Vertex,
6608 "foundry" => Self::Foundry,
6609 "gateway" => Self::Gateway,
6610 other => Self::Unknown(other.to_string()),
6611 }
6612 }
6613}
6614
6615impl Serialize for ApiErrorProvider {
6616 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6617 serializer.serialize_str(self.as_str())
6618 }
6619}
6620
6621impl<'de> Deserialize<'de> for ApiErrorProvider {
6622 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6623 let s = String::deserialize(deserializer)?;
6624 Ok(Self::from(s.as_str()))
6625 }
6626}
6627
6628#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6630pub enum ApiErrorRemedy {
6631 RefreshCommand,
6634 RefreshCredentials,
6636 Adc,
6639 GatewayToken,
6642 HostManaged,
6644 ModelAccess,
6647 Unknown(String),
6649}
6650
6651impl ApiErrorRemedy {
6652 pub fn as_str(&self) -> &str {
6653 match self {
6654 Self::RefreshCommand => "refresh_command",
6655 Self::RefreshCredentials => "refresh_credentials",
6656 Self::Adc => "adc",
6657 Self::GatewayToken => "gateway_token",
6658 Self::HostManaged => "host_managed",
6659 Self::ModelAccess => "model_access",
6660 Self::Unknown(s) => s.as_str(),
6661 }
6662 }
6663}
6664
6665impl fmt::Display for ApiErrorRemedy {
6666 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6667 f.write_str(self.as_str())
6668 }
6669}
6670
6671impl From<&str> for ApiErrorRemedy {
6672 fn from(s: &str) -> Self {
6673 match s {
6674 "refresh_command" => Self::RefreshCommand,
6675 "refresh_credentials" => Self::RefreshCredentials,
6676 "adc" => Self::Adc,
6677 "gateway_token" => Self::GatewayToken,
6678 "host_managed" => Self::HostManaged,
6679 "model_access" => Self::ModelAccess,
6680 other => Self::Unknown(other.to_string()),
6681 }
6682 }
6683}
6684
6685impl Serialize for ApiErrorRemedy {
6686 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
6687 serializer.serialize_str(self.as_str())
6688 }
6689}
6690
6691impl<'de> Deserialize<'de> for ApiErrorRemedy {
6692 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
6693 let s = String::deserialize(deserializer)?;
6694 Ok(Self::from(s.as_str()))
6695 }
6696}
6697
6698#[derive(Debug, Clone, Serialize, Deserialize)]
6700pub struct AssistantMessageContent {
6701 pub id: String,
6702 #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
6704 pub message_type: Option<String>,
6705 pub role: MessageRole,
6706 pub model: String,
6707 pub content: Vec<ContentBlock>,
6708 #[serde(skip_serializing_if = "Option::is_none")]
6709 pub stop_reason: Option<StopReason>,
6710 #[serde(skip_serializing_if = "Option::is_none")]
6711 pub stop_sequence: Option<String>,
6712 #[serde(skip_serializing_if = "Option::is_none")]
6713 pub usage: Option<AssistantUsage>,
6714 #[serde(skip_serializing_if = "Option::is_none")]
6716 pub stop_details: Option<Value>,
6717 #[serde(skip_serializing_if = "Option::is_none")]
6719 pub context_management: Option<Value>,
6720}
6721
6722#[derive(Debug, Clone, Serialize, Deserialize)]
6724pub struct AssistantUsage {
6725 #[serde(default)]
6727 pub input_tokens: u32,
6728
6729 #[serde(default)]
6731 pub output_tokens: u32,
6732
6733 #[serde(default)]
6735 pub cache_creation_input_tokens: u32,
6736
6737 #[serde(default)]
6739 pub cache_read_input_tokens: u32,
6740
6741 #[serde(skip_serializing_if = "Option::is_none")]
6743 pub service_tier: Option<String>,
6744
6745 #[serde(skip_serializing_if = "Option::is_none")]
6747 pub cache_creation: Option<CacheCreationDetails>,
6748
6749 #[serde(skip_serializing_if = "Option::is_none")]
6751 pub inference_geo: Option<String>,
6752
6753 #[serde(default, skip_serializing_if = "Option::is_none")]
6756 pub speed: Option<String>,
6757
6758 #[serde(default, skip_serializing_if = "Option::is_none")]
6761 pub fallback_credit: Option<Value>,
6762}
6763
6764#[derive(Debug, Clone, Serialize, Deserialize)]
6766pub struct CacheCreationDetails {
6767 #[serde(default)]
6769 pub ephemeral_1h_input_tokens: u32,
6770
6771 #[serde(default)]
6773 pub ephemeral_5m_input_tokens: u32,
6774}
6775
6776#[cfg(test)]
6777mod tests {
6778 use crate::io::ClaudeOutput;
6779
6780 #[test]
6781 fn test_subagent_usage_rollup_accumulates_task_results() {
6782 use super::SubagentUsageRollup;
6783
6784 let mut rollup = SubagentUsageRollup::default();
6785
6786 let task_result = r#"{"type":"user","message":{"role":"user","content":[]},"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1","tool_use_result":{"status":"completed","prompt":"Compute 6 times 7.","agentId":"ab52f22445470d454","agentType":"general-purpose","resolvedModel":"claude-sonnet-4-6","totalDurationMs":1853,"totalTokens":10201,"totalToolUseCount":3}}"#;
6787 let output: ClaudeOutput = serde_json::from_str(task_result).unwrap();
6788 assert!(rollup.observe(&output));
6789 assert_eq!(rollup.subagent_tokens, 10201);
6790 assert_eq!(rollup.agent_count, 1);
6791 assert_eq!(rollup.tool_uses, 3);
6792 assert_eq!(rollup.duration_ms, 1853);
6793
6794 assert!(!rollup.observe(&output));
6796 assert_eq!(rollup.agent_count, 1);
6797 assert_eq!(rollup.subagent_tokens, 10201);
6798
6799 let second = r#"{"type":"user","message":{"role":"user","content":[]},"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1","tool_use_result":{"status":"completed","agentId":"ffff00001111","totalDurationMs":100,"totalTokens":500,"totalToolUseCount":1}}"#;
6801 let output: ClaudeOutput = serde_json::from_str(second).unwrap();
6802 assert!(rollup.observe(&output));
6803 assert_eq!(rollup.agent_count, 2);
6804 assert_eq!(rollup.subagent_tokens, 10701);
6805 }
6806
6807 #[test]
6808 fn test_subagent_usage_rollup_ignores_non_task_results() {
6809 use super::SubagentUsageRollup;
6810
6811 let mut rollup = SubagentUsageRollup::default();
6812
6813 let tool_search = r#"{"type":"user","message":{"role":"user","content":[]},"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1","tool_use_result":{"matches":["TaskCreate"],"query":"select:TaskCreate","total_deferred_tools":27}}"#;
6816 let output: ClaudeOutput = serde_json::from_str(tool_search).unwrap();
6817 assert!(!rollup.observe(&output));
6818
6819 let plain = r#"{"type":"user","message":{"role":"user","content":[]},"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1"}"#;
6821 let output: ClaudeOutput = serde_json::from_str(plain).unwrap();
6822 assert!(!rollup.observe(&output));
6823
6824 let system = r#"{"type":"system","subtype":"status","status":null,"session_id":"7fbc568e-2bd6-45aa-b217-a1cf80004ba1"}"#;
6826 let output: ClaudeOutput = serde_json::from_str(system).unwrap();
6827 assert!(!rollup.observe(&output));
6828
6829 assert_eq!(rollup, SubagentUsageRollup::default());
6830 }
6831
6832 #[test]
6833 fn test_subagent_usage_rollup_over_captured_session() {
6834 use super::SubagentUsageRollup;
6835
6836 let mut rollup = SubagentUsageRollup::default();
6837 let fixture =
6838 include_str!("../../test_cases/subagent_sessions/general_purpose_compute.jsonl");
6839 for line in fixture.lines().filter(|l| !l.trim().is_empty()) {
6840 if let Ok(output) = serde_json::from_str::<ClaudeOutput>(line) {
6841 rollup.observe(&output);
6842 }
6843 }
6844 assert_eq!(rollup.agent_count, 1);
6845 assert_eq!(rollup.subagent_tokens, 10201);
6846 }
6847
6848 #[test]
6849 fn test_system_message_init() {
6850 let json = r#"{
6851 "type": "system",
6852 "subtype": "init",
6853 "session_id": "test-session-123",
6854 "cwd": "/home/user/project",
6855 "model": "claude-sonnet-4",
6856 "tools": ["Bash", "Read", "Write"],
6857 "mcp_servers": [],
6858 "slash_commands": ["compact", "cost", "review"],
6859 "agents": ["Bash", "Explore", "Plan"],
6860 "plugins": [{"name": "rust-analyzer-lsp", "path": "/home/user/.claude/plugins/rust-analyzer-lsp/1.0.0"}],
6861 "skills": [],
6862 "claude_code_version": "2.1.15",
6863 "apiKeySource": "none",
6864 "output_style": "default",
6865 "permissionMode": "default"
6866 }"#;
6867
6868 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
6869 if let ClaudeOutput::System(sys) = output {
6870 assert!(sys.is_init());
6871 assert!(!sys.is_status());
6872 assert!(!sys.is_compact_boundary());
6873
6874 let init = sys.as_init().expect("Should parse as init");
6875 assert_eq!(init.session_id, "test-session-123");
6876 assert_eq!(init.cwd, Some("/home/user/project".to_string()));
6877 assert_eq!(init.model, Some("claude-sonnet-4".to_string()));
6878 assert_eq!(init.tools, vec!["Bash", "Read", "Write"]);
6879 assert_eq!(init.slash_commands, vec!["compact", "cost", "review"]);
6880 assert_eq!(init.agents, vec!["Bash", "Explore", "Plan"]);
6881 assert_eq!(init.plugins.len(), 1);
6882 assert_eq!(init.plugins[0].name, "rust-analyzer-lsp");
6883 assert_eq!(init.claude_code_version, Some("2.1.15".to_string()));
6884 assert_eq!(init.api_key_source, Some(super::ApiKeySource::None));
6885 assert_eq!(init.output_style, Some(super::OutputStyle::Default));
6886 assert_eq!(
6887 init.permission_mode,
6888 Some(super::InitPermissionMode::Default)
6889 );
6890 } else {
6891 panic!("Expected System message");
6892 }
6893 }
6894
6895 #[test]
6896 fn test_system_message_init_from_real_capture() {
6897 let json = include_str!("../../test_cases/tool_use_captures/tool_msg_0.json");
6898 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
6899 if let ClaudeOutput::System(sys) = output {
6900 let init = sys.as_init().expect("Should parse real init capture");
6901 assert_eq!(init.slash_commands.len(), 8);
6902 assert!(init.slash_commands.contains(&"compact".to_string()));
6903 assert!(init.slash_commands.contains(&"review".to_string()));
6904 assert_eq!(init.agents.len(), 5);
6905 assert!(init.agents.contains(&"Bash".to_string()));
6906 assert!(init.agents.contains(&"Explore".to_string()));
6907 assert_eq!(init.plugins.len(), 1);
6908 assert_eq!(init.plugins[0].name, "rust-analyzer-lsp");
6909 assert_eq!(init.claude_code_version, Some("2.1.15".to_string()));
6910 } else {
6911 panic!("Expected System message");
6912 }
6913 }
6914
6915 #[test]
6916 fn test_system_message_status() {
6917 let json = r#"{
6918 "type": "system",
6919 "subtype": "status",
6920 "session_id": "879c1a88-3756-4092-aa95-0020c4ed9692",
6921 "status": "compacting",
6922 "uuid": "32eb9f9d-5ef7-47ff-8fce-bbe22fe7ed93"
6923 }"#;
6924
6925 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
6926 if let ClaudeOutput::System(sys) = output {
6927 assert!(sys.is_status());
6928 assert!(!sys.is_init());
6929
6930 let status = sys.as_status().expect("Should parse as status");
6931 assert_eq!(status.session_id, "879c1a88-3756-4092-aa95-0020c4ed9692");
6932 assert_eq!(status.status, Some(super::StatusMessageStatus::Compacting));
6933 assert_eq!(
6934 status.uuid,
6935 Some("32eb9f9d-5ef7-47ff-8fce-bbe22fe7ed93".to_string())
6936 );
6937 } else {
6938 panic!("Expected System message");
6939 }
6940 }
6941
6942 #[test]
6943 fn test_system_message_status_null() {
6944 let json = r#"{
6945 "type": "system",
6946 "subtype": "status",
6947 "session_id": "879c1a88-3756-4092-aa95-0020c4ed9692",
6948 "status": null,
6949 "uuid": "92d9637e-d00e-418e-acd2-a504e3861c6a"
6950 }"#;
6951
6952 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
6953 if let ClaudeOutput::System(sys) = output {
6954 let status = sys.as_status().expect("Should parse as status");
6955 assert_eq!(status.status, None);
6956 } else {
6957 panic!("Expected System message");
6958 }
6959 }
6960
6961 #[test]
6962 fn test_system_message_task_started() {
6963 let json = r#"{
6964 "type": "system",
6965 "subtype": "task_started",
6966 "session_id": "9abbc466-dad0-4b8e-b6b0-cad5eb7a16b9",
6967 "task_id": "b6daf3f",
6968 "task_type": "local_bash",
6969 "tool_use_id": "toolu_011rfSTFumpJZdCCfzeD7jaS",
6970 "description": "Wait for CI on PR #12",
6971 "uuid": "c4243261-c128-4747-b8c3-5e1c7c10eeb8"
6972 }"#;
6973
6974 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
6975 if let ClaudeOutput::System(sys) = output {
6976 assert!(sys.is_task_started());
6977 assert!(!sys.is_task_progress());
6978 assert!(!sys.is_task_notification());
6979
6980 let task = sys.as_task_started().expect("Should parse as task_started");
6981 assert_eq!(task.session_id, "9abbc466-dad0-4b8e-b6b0-cad5eb7a16b9");
6982 assert_eq!(task.task_id, "b6daf3f");
6983 assert_eq!(task.task_type, Some(super::TaskType::LocalBash));
6984 assert_eq!(
6985 task.tool_use_id.as_deref(),
6986 Some("toolu_011rfSTFumpJZdCCfzeD7jaS")
6987 );
6988 assert_eq!(task.description, "Wait for CI on PR #12");
6989 } else {
6990 panic!("Expected System message");
6991 }
6992 }
6993
6994 #[test]
6995 fn test_system_message_task_started_agent() {
6996 let json = r#"{
6997 "type": "system",
6998 "subtype": "task_started",
6999 "session_id": "bff4f716-17c1-4255-ab7b-eea9d33824e3",
7000 "task_id": "a4a7e0906e5fc64cc",
7001 "task_type": "local_agent",
7002 "tool_use_id": "toolu_01SFz9FwZ1cYgCSy8vRM7wep",
7003 "description": "Explore Scene/ArrayScene duplication",
7004 "uuid": "85a39f5a-e4d4-47f7-9a6d-1125f1a8035f"
7005 }"#;
7006
7007 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7008 if let ClaudeOutput::System(sys) = output {
7009 let task = sys.as_task_started().expect("Should parse as task_started");
7010 assert_eq!(task.task_type, Some(super::TaskType::LocalAgent));
7011 assert_eq!(task.task_id, "a4a7e0906e5fc64cc");
7012 } else {
7013 panic!("Expected System message");
7014 }
7015 }
7016
7017 #[test]
7018 fn test_system_message_task_progress() {
7019 let json = r#"{
7020 "type": "system",
7021 "subtype": "task_progress",
7022 "session_id": "bff4f716-17c1-4255-ab7b-eea9d33824e3",
7023 "task_id": "a4a7e0906e5fc64cc",
7024 "tool_use_id": "toolu_01SFz9FwZ1cYgCSy8vRM7wep",
7025 "description": "Reading src/jplephem/chebyshev.rs",
7026 "last_tool_name": "Read",
7027 "usage": {
7028 "duration_ms": 13996,
7029 "tool_uses": 9,
7030 "total_tokens": 38779
7031 },
7032 "uuid": "85a39f5a-e4d4-47f7-9a6d-1125f1a8035f"
7033 }"#;
7034
7035 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7036 if let ClaudeOutput::System(sys) = output {
7037 assert!(sys.is_task_progress());
7038 assert!(!sys.is_task_started());
7039
7040 let progress = sys
7041 .as_task_progress()
7042 .expect("Should parse as task_progress");
7043 assert_eq!(progress.task_id, "a4a7e0906e5fc64cc");
7044 assert_eq!(progress.description, "Reading src/jplephem/chebyshev.rs");
7045 assert_eq!(progress.last_tool_name.as_deref(), Some("Read"));
7046 assert_eq!(progress.usage.duration_ms, 13996);
7047 assert_eq!(progress.usage.tool_uses, 9);
7048 assert_eq!(progress.usage.total_tokens, 38779);
7049 } else {
7050 panic!("Expected System message");
7051 }
7052 }
7053
7054 #[test]
7055 fn test_system_message_task_notification_completed() {
7056 let json = r#"{
7057 "type": "system",
7058 "subtype": "task_notification",
7059 "session_id": "bff4f716-17c1-4255-ab7b-eea9d33824e3",
7060 "task_id": "a0ba761e9dc9c316f",
7061 "tool_use_id": "toolu_01Ho6XVXFLVNjTQ9YqowdBXW",
7062 "status": "completed",
7063 "summary": "Agent \"Write Hipparcos data source doc\" completed",
7064 "output_file": "",
7065 "usage": {
7066 "duration_ms": 172300,
7067 "tool_uses": 11,
7068 "total_tokens": 42005
7069 },
7070 "uuid": "269f49b9-218d-4c8d-9f7e-3a5383a0c5b2"
7071 }"#;
7072
7073 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7074 if let ClaudeOutput::System(sys) = output {
7075 assert!(sys.is_task_notification());
7076
7077 let notif = sys
7078 .as_task_notification()
7079 .expect("Should parse as task_notification");
7080 assert_eq!(notif.status, super::TaskStatus::Completed);
7081 assert_eq!(
7082 notif.summary,
7083 "Agent \"Write Hipparcos data source doc\" completed"
7084 );
7085 assert_eq!(notif.output_file, Some("".to_string()));
7086 assert_eq!(
7087 notif.tool_use_id,
7088 Some("toolu_01Ho6XVXFLVNjTQ9YqowdBXW".to_string())
7089 );
7090 let usage = notif.usage.expect("Should have usage");
7091 assert_eq!(usage.duration_ms, 172300);
7092 assert_eq!(usage.tool_uses, 11);
7093 assert_eq!(usage.total_tokens, 42005);
7094 } else {
7095 panic!("Expected System message");
7096 }
7097 }
7098
7099 #[test]
7100 fn test_system_message_task_notification_failed_no_usage() {
7101 let json = r#"{
7102 "type": "system",
7103 "subtype": "task_notification",
7104 "session_id": "ea629737-3c36-48a8-a1c4-ad761ad35784",
7105 "task_id": "b98f6a3",
7106 "status": "failed",
7107 "summary": "Background command \"Run FSM calibration\" failed with exit code 1",
7108 "output_file": "/tmp/claude-1000/tasks/b98f6a3.output"
7109 }"#;
7110
7111 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7112 if let ClaudeOutput::System(sys) = output {
7113 let notif = sys
7114 .as_task_notification()
7115 .expect("Should parse as task_notification");
7116 assert_eq!(notif.status, super::TaskStatus::Failed);
7117 assert!(notif.tool_use_id.is_none());
7118 assert!(notif.usage.is_none());
7119 assert_eq!(
7120 notif.output_file,
7121 Some("/tmp/claude-1000/tasks/b98f6a3.output".to_string())
7122 );
7123 } else {
7124 panic!("Expected System message");
7125 }
7126 }
7127
7128 #[test]
7134 fn test_task_messages_roundtrip_through_value() {
7135 let cases = [
7136 r#"{"type":"system","subtype":"task_started","session_id":"s1",
7137 "task_id":"t1","task_type":"local_bash","tool_use_id":"tu1",
7138 "description":"Sleep 3s","uuid":"u1"}"#,
7139 r#"{"type":"system","subtype":"task_progress","session_id":"s1",
7140 "task_id":"t1","tool_use_id":"tu1","description":"Running ls",
7141 "last_tool_name":"Bash",
7142 "usage":{"duration_ms":100,"tool_uses":1,"total_tokens":500},
7143 "uuid":"u2"}"#,
7144 r#"{"type":"system","subtype":"task_notification","session_id":"s1",
7145 "task_id":"t1","tool_use_id":"tu1","status":"completed",
7146 "summary":"done","output_file":"",
7147 "usage":{"duration_ms":100,"tool_uses":1,"total_tokens":500},
7148 "uuid":"u3"}"#,
7149 ];
7150
7151 for json in cases {
7152 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7153 let value = serde_json::to_value(&output).unwrap();
7154 let reparsed: ClaudeOutput = serde_json::from_value(value).unwrap();
7155
7156 let ClaudeOutput::System(sys) = reparsed else {
7157 panic!("Expected System variant after round-trip");
7158 };
7159
7160 match sys.subtype {
7161 super::SystemSubtype::TaskStarted => {
7162 assert!(
7163 sys.as_task_started().is_some(),
7164 "as_task_started failed after round-trip"
7165 );
7166 }
7167 super::SystemSubtype::TaskProgress => {
7168 assert!(
7169 sys.as_task_progress().is_some(),
7170 "as_task_progress failed after round-trip"
7171 );
7172 }
7173 super::SystemSubtype::TaskNotification => {
7174 assert!(
7175 sys.as_task_notification().is_some(),
7176 "as_task_notification failed after round-trip"
7177 );
7178 }
7179 other => panic!("unexpected subtype after round-trip: {other:?}"),
7180 }
7181 }
7182 }
7183
7184 #[test]
7185 fn test_system_message_compact_boundary() {
7186 let json = r#"{
7187 "type": "system",
7188 "subtype": "compact_boundary",
7189 "session_id": "879c1a88-3756-4092-aa95-0020c4ed9692",
7190 "compact_metadata": {
7191 "pre_tokens": 155285,
7192 "trigger": "auto"
7193 },
7194 "uuid": "a67780d5-74cb-48b1-9137-7a6e7cee45d7"
7195 }"#;
7196
7197 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7198 if let ClaudeOutput::System(sys) = output {
7199 assert!(sys.is_compact_boundary());
7200 assert!(!sys.is_init());
7201 assert!(!sys.is_status());
7202
7203 let compact = sys
7204 .as_compact_boundary()
7205 .expect("Should parse as compact_boundary");
7206 assert_eq!(compact.session_id, "879c1a88-3756-4092-aa95-0020c4ed9692");
7207 assert_eq!(compact.compact_metadata.pre_tokens, 155285);
7208 assert_eq!(
7209 compact.compact_metadata.trigger,
7210 super::CompactionTrigger::Auto
7211 );
7212 assert!(compact.summary.is_none());
7214 assert!(compact.leaf_message_count.is_none());
7215 assert!(compact.duration_ms.is_none());
7216 } else {
7217 panic!("Expected System message");
7218 }
7219 }
7220
7221 #[test]
7222 fn test_compact_boundary_with_summary_stats() {
7223 let json = r#"{
7225 "type": "system",
7226 "subtype": "compact_boundary",
7227 "session_id": "s1",
7228 "compact_metadata": { "pre_tokens": 1000, "trigger": "manual" },
7229 "summary": "Summarized the earlier exploration.",
7230 "leaf_message_count": 42,
7231 "duration_ms": 1234,
7232 "uuid": "u1"
7233 }"#;
7234 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7235 let ClaudeOutput::System(sys) = output else {
7236 panic!("Expected System message");
7237 };
7238 let compact = sys.as_compact_boundary().expect("compact_boundary");
7239 assert_eq!(
7240 compact.summary.as_deref(),
7241 Some("Summarized the earlier exploration.")
7242 );
7243 assert_eq!(compact.leaf_message_count, Some(42));
7244 assert_eq!(compact.duration_ms, Some(1234));
7245
7246 let json_alt = r#"{
7249 "type": "system",
7250 "subtype": "compact_boundary",
7251 "session_id": "s2",
7252 "compact_metadata": { "pre_tokens": 2000, "trigger": "auto" },
7253 "content": "alt-key summary",
7254 "message_count": 7
7255 }"#;
7256 let output: ClaudeOutput = serde_json::from_str(json_alt).unwrap();
7257 let ClaudeOutput::System(sys) = output else {
7258 panic!("Expected System message");
7259 };
7260 let compact = sys.as_compact_boundary().expect("compact_boundary");
7261 assert_eq!(compact.summary.as_deref(), Some("alt-key summary"));
7262 assert_eq!(compact.leaf_message_count, Some(7));
7263 }
7264
7265 #[test]
7266 fn test_init_message_with_new_fields() {
7267 let json = r#"{
7268 "type": "system",
7269 "subtype": "init",
7270 "session_id": "test-session",
7271 "cwd": "/home/user",
7272 "model": "claude-opus-4-7",
7273 "tools": ["Bash"],
7274 "mcp_servers": [],
7275 "permissionMode": "default",
7276 "apiKeySource": "none",
7277 "uuid": "44841a0d-182d-493a-86b5-79800d3d9665",
7278 "memory_paths": {"auto": "/home/user/.claude/projects/memory/"},
7279 "fast_mode_state": "off",
7280 "plugins": [{"name": "lsp", "path": "/plugins/lsp", "source": "lsp@official"}],
7281 "claude_code_version": "2.1.117"
7282 }"#;
7283
7284 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7285 if let ClaudeOutput::System(sys) = output {
7286 let init = sys.as_init().expect("Should parse as init");
7287 assert_eq!(
7288 init.uuid.as_deref(),
7289 Some("44841a0d-182d-493a-86b5-79800d3d9665")
7290 );
7291 assert!(init.memory_paths.is_some());
7292 assert_eq!(init.fast_mode_state.as_deref(), Some("off"));
7293 assert_eq!(init.plugins[0].source.as_deref(), Some("lsp@official"));
7294 assert_eq!(init.claude_code_version.as_deref(), Some("2.1.117"));
7295 } else {
7296 panic!("Expected System message");
7297 }
7298 }
7299
7300 #[test]
7301 fn test_assistant_message_with_new_fields() {
7302 let json = r#"{
7303 "type": "assistant",
7304 "message": {
7305 "id": "msg_1",
7306 "type": "message",
7307 "role": "assistant",
7308 "model": "claude-opus-4-7",
7309 "content": [{"type": "text", "text": "Hello"}],
7310 "stop_reason": "end_turn",
7311 "stop_details": null,
7312 "context_management": null,
7313 "usage": {
7314 "input_tokens": 100,
7315 "output_tokens": 10,
7316 "cache_creation_input_tokens": 50,
7317 "cache_read_input_tokens": 0,
7318 "service_tier": "standard",
7319 "inference_geo": "not_available"
7320 }
7321 },
7322 "session_id": "abc",
7323 "uuid": "msg-uuid-123"
7324 }"#;
7325
7326 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7327 if let ClaudeOutput::Assistant(asst) = output {
7328 assert_eq!(asst.message.stop_details, None);
7329 assert_eq!(asst.message.context_management, None);
7330 let usage = asst.message.usage.unwrap();
7331 assert_eq!(usage.inference_geo.as_deref(), Some("not_available"));
7332 } else {
7333 panic!("Expected Assistant message");
7334 }
7335 }
7336
7337 #[test]
7338 fn test_user_message_with_new_fields() {
7339 let json = r#"{
7340 "type": "user",
7341 "message": {
7342 "role": "user",
7343 "content": [{"type": "text", "text": "Hello"}]
7344 },
7345 "session_id": "9abbc466-dad0-4b8e-b6b0-cad5eb7a16b9",
7346 "parent_tool_use_id": "toolu_123",
7347 "uuid": "user-msg-456"
7348 }"#;
7349
7350 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7351 if let ClaudeOutput::User(user) = output {
7352 assert_eq!(user.parent_tool_use_id.as_deref(), Some("toolu_123"));
7353 assert_eq!(user.uuid.as_deref(), Some("user-msg-456"));
7354 } else {
7355 panic!("Expected User message");
7356 }
7357 }
7358
7359 #[test]
7365 fn test_user_message_preserves_tool_use_result_and_timestamp() {
7366 let json = r#"{
7367 "type":"user",
7368 "message":{"role":"user","content":[{"type":"tool_result","content":"User has answered your questions: . You can now continue with the user's answers in mind.","tool_use_id":"toolu_01331duMqP2PrRaqR2yWa8e4"}]},
7369 "parent_tool_use_id":null,
7370 "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d",
7371 "uuid":"8ef6e997-a849-4d15-bed3-2837c3d3f4cd",
7372 "timestamp":"2026-05-12T23:12:04.121Z",
7373 "tool_use_result":{"questions":[{"question":"Which color do you prefer?","header":"Color","options":[{"label":"Red","description":"A warm color"},{"label":"Blue","description":"A cool color"}],"multiSelect":false}],"answers":{"Color":"Blue"}}
7374 }"#;
7375
7376 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7377 let user = match output {
7378 ClaudeOutput::User(u) => u,
7379 other => panic!("Expected User message, got {:?}", other.message_type()),
7380 };
7381
7382 assert_eq!(user.timestamp.as_deref(), Some("2026-05-12T23:12:04.121Z"));
7383 let raw = user
7384 .tool_use_result
7385 .as_ref()
7386 .expect("tool_use_result must be captured");
7387 assert_eq!(raw["answers"]["Color"], "Blue");
7388 assert_eq!(raw["questions"][0]["header"], "Color");
7389
7390 let reser: serde_json::Value = serde_json::to_value(&user).unwrap();
7394 assert_eq!(reser["timestamp"], "2026-05-12T23:12:04.121Z");
7395 assert_eq!(reser["tool_use_result"]["answers"]["Color"], "Blue");
7396 assert_eq!(
7397 reser["tool_use_result"]["questions"][0]["question"],
7398 "Which color do you prefer?"
7399 );
7400
7401 let typed: crate::AskUserQuestionInput = user
7404 .tool_use_result_as::<crate::AskUserQuestionInput>()
7405 .expect("tool_use_result present")
7406 .expect("AskUserQuestionInput parses");
7407 assert_eq!(typed.questions.len(), 1);
7408 assert_eq!(typed.questions[0].header, "Color");
7409 let answers = typed.answers.expect("answers populated");
7410 assert_eq!(answers.get("Color").map(String::as_str), Some("Blue"));
7411 }
7412
7413 #[test]
7416 fn test_user_message_without_tool_use_result_omits_field() {
7417 let json = r#"{
7418 "type":"user",
7419 "message":{"role":"user","content":[{"type":"text","text":"hello"}]},
7420 "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d"
7421 }"#;
7422
7423 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7424 let user = match output {
7425 ClaudeOutput::User(u) => u,
7426 _ => panic!("Expected User message"),
7427 };
7428 assert!(user.tool_use_result.is_none());
7429 assert!(user.timestamp.is_none());
7430
7431 let reser = serde_json::to_value(&user).unwrap();
7432 assert!(reser.get("tool_use_result").is_none());
7433 assert!(reser.get("timestamp").is_none());
7434 }
7435
7436 #[test]
7440 fn test_subagent_result_exposes_token_accounting() {
7441 let json = r#"{
7442 "type":"user",
7443 "message":{"role":"user","content":[{"tool_use_id":"toolu_01","type":"tool_result","content":[{"type":"text","text":"21"}]}]},
7444 "session_id":"d3fc5942-75e5-4aa1-a87d-b9484a176541",
7445 "tool_use_result":{
7446 "status":"completed",
7447 "prompt":"Count the .rs files.",
7448 "agentId":"ac4f0276e9d4b6232",
7449 "agentType":"Explore",
7450 "content":[{"type":"text","text":"21"}],
7451 "resolvedModel":"claude-haiku-4-5-20251001",
7452 "totalDurationMs":6869,
7453 "totalTokens":7834,
7454 "totalToolUseCount":1,
7455 "usage":{"input_tokens":6,"cache_creation_input_tokens":125,"cache_read_input_tokens":7699,"output_tokens":4,"service_tier":"standard"},
7456 "toolStats":{"readCount":0,"searchCount":0,"bashCount":1,"editFileCount":0,"linesAdded":0,"linesRemoved":0,"otherToolCount":0}
7457 }
7458 }"#;
7459
7460 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7461 let user = match output {
7462 ClaudeOutput::User(u) => u,
7463 _ => panic!("Expected User message"),
7464 };
7465
7466 let result = user.subagent_result().expect("subagent result parses");
7467 assert_eq!(result.agent_type.as_deref(), Some("Explore"));
7468 assert_eq!(
7469 result.resolved_model.as_deref(),
7470 Some("claude-haiku-4-5-20251001")
7471 );
7472 assert_eq!(result.total_tokens, Some(7834));
7473 assert_eq!(result.total_duration_ms, Some(6869));
7474 assert_eq!(result.total_tool_use_count, Some(1));
7475
7476 let usage = result.usage.expect("nested usage present");
7477 assert_eq!(usage.input_tokens, 6);
7478 assert_eq!(usage.cache_read_input_tokens, 7699);
7479
7480 let stats = result.tool_stats.expect("toolStats present");
7481 assert_eq!(stats.bash_count, 1);
7482 }
7483
7484 #[test]
7488 fn test_subagent_result_absent_for_non_task_result() {
7489 let json = r#"{
7490 "type":"user",
7491 "message":{"role":"user","content":[{"type":"text","text":"hi"}]},
7492 "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d",
7493 "tool_use_result":{"questions":[],"answers":{"Color":"Blue"}}
7494 }"#;
7495
7496 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7497 let user = match output {
7498 ClaudeOutput::User(u) => u,
7499 _ => panic!("Expected User message"),
7500 };
7501
7502 let result = user.subagent_result().expect("lenient parse");
7503 assert_eq!(result.total_tokens, None);
7504 assert_eq!(result.agent_type, None);
7505 }
7506
7507 #[test]
7508 fn test_init_fast_mode_reason_and_mcp_server_errors_fully_wrapped() {
7509 use serde_json::Value;
7510
7511 let raw: Value = serde_json::from_str(
7512 r#"{
7513 "type":"system","subtype":"init","session_id":"s1","uuid":"u1",
7514 "fast_mode_state":"off",
7515 "fast_mode_disabled_reason":"not_first_party",
7516 "mcp_server_errors":[{"name":"broken","type":"invalid_config","message":"url entry with no type"}]
7517 }"#,
7518 )
7519 .unwrap();
7520 crate::io::assert_fully_wrapped(&raw);
7521
7522 let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7523 let ClaudeOutput::System(sys) = output else {
7524 panic!("expected System");
7525 };
7526 let init = sys.as_init().expect("parses as init");
7527 assert_eq!(
7528 init.fast_mode_disabled_reason,
7529 Some(crate::FastModeDisabledReason::NotFirstParty)
7530 );
7531 let errs = init.mcp_server_errors.unwrap();
7532 assert_eq!(errs.len(), 1);
7533 assert_eq!(errs[0].name, "broken");
7534 assert_eq!(errs[0].error_type, "invalid_config");
7535 }
7536
7537 #[test]
7538 fn test_code_change_published_fully_wrapped() {
7539 use super::{KnownSystemEvent, SystemSubtype};
7540 use serde_json::Value;
7541
7542 let raw: Value = serde_json::from_str(
7543 r#"{
7544 "type":"system","subtype":"code_change_published",
7545 "provider":"github","url":"https://github.com/owner/repo/pull/42",
7546 "repo":"owner/repo","identifier":"42",
7547 "uuid":"u1","session_id":"s1"
7548 }"#,
7549 )
7550 .unwrap();
7551 crate::io::assert_fully_wrapped(&raw);
7552
7553 let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7554 let ClaudeOutput::System(sys) = output else {
7555 panic!("expected System");
7556 };
7557 assert_eq!(sys.subtype, SystemSubtype::CodeChangePublished);
7558 let Some(KnownSystemEvent::CodeChangePublished(msg)) = sys.as_known_system_event() else {
7559 panic!("expected CodeChangePublished event");
7560 };
7561 assert_eq!(msg.provider, "github");
7562 assert_eq!(msg.repo, "owner/repo");
7563 assert_eq!(msg.identifier, "42");
7564
7565 assert!(sys.is_code_change_published());
7566 assert!(!sys.is_vcs_state_changed());
7567 let direct = sys.as_code_change_published().expect("direct accessor");
7568 assert_eq!(direct.url, "https://github.com/owner/repo/pull/42");
7569 assert!(sys.as_vcs_state_changed().is_none());
7570 }
7571
7572 #[test]
7573 fn test_feedback_draft_queued_fully_wrapped() {
7574 use super::{KnownSystemEvent, SystemSubtype};
7575 use serde_json::Value;
7576
7577 let raw: Value = serde_json::from_str(
7578 r#"{
7579 "type":"system","subtype":"feedback_draft_queued",
7580 "draft_id":"draft-1","draft_type":"bug_report",
7581 "title":"Tool output was truncated",
7582 "details_preview":"The last command omitted its final lines",
7583 "uuid":"u1","session_id":"s1","future_field":"preserved"
7584 }"#,
7585 )
7586 .unwrap();
7587 crate::io::assert_fully_wrapped(&raw);
7588
7589 let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7590 let ClaudeOutput::System(sys) = output else {
7591 panic!("expected System");
7592 };
7593 assert_eq!(sys.subtype, SystemSubtype::FeedbackDraftQueued);
7594 assert!(sys.is_feedback_draft_queued());
7595 assert!(!sys.is_vcs_state_changed());
7596
7597 let direct = sys
7598 .as_feedback_draft_queued()
7599 .expect("direct typed accessor");
7600 assert_eq!(direct.draft_id, "draft-1");
7601 assert_eq!(direct.draft_type, "bug_report");
7602 assert_eq!(direct.extra["future_field"], "preserved");
7603
7604 let Some(KnownSystemEvent::FeedbackDraftQueued(known)) = sys.as_known_system_event() else {
7605 panic!("expected FeedbackDraftQueued event");
7606 };
7607 assert_eq!(known.title, "Tool output was truncated");
7608 assert_eq!(
7609 sys.typed_value().expect("typed value")["future_field"],
7610 "preserved"
7611 );
7612 }
7613
7614 #[test]
7615 fn test_cloud_session_delta_fully_wrapped() {
7616 use super::{KnownSystemEvent, SystemSubtype};
7617 use serde_json::Value;
7618
7619 let raw: Value = serde_json::from_str(
7620 r#"{
7621 "type":"system","subtype":"cloud_session_delta",
7622 "seq":3,"changed":["serving","connection"],
7623 "cloud_session":{"id":"session_abc","view_url":"https://example.invalid/s/abc",
7624 "serving":{"state":"on"},"connection":{"state":"live"}},
7625 "uuid":"u1","session_id":"s1","future_field":"preserved"
7626 }"#,
7627 )
7628 .unwrap();
7629 crate::io::assert_fully_wrapped(&raw);
7630
7631 let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7632 let ClaudeOutput::System(sys) = output else {
7633 panic!("expected System");
7634 };
7635 assert_eq!(sys.subtype, SystemSubtype::CloudSessionDelta);
7636 assert!(sys.is_cloud_session_delta());
7637 assert!(!sys.is_feedback_draft_queued());
7638
7639 let direct = sys.as_cloud_session_delta().expect("direct typed accessor");
7640 assert_eq!(direct.seq, 3);
7641 assert_eq!(direct.changed, vec!["serving", "connection"]);
7642 assert_eq!(direct.cloud_session["id"], "session_abc");
7643 assert_eq!(direct.extra["future_field"], "preserved");
7644
7645 let Some(KnownSystemEvent::CloudSessionDelta(known)) = sys.as_known_system_event() else {
7646 panic!("expected CloudSessionDelta event");
7647 };
7648 assert_eq!(known.session_id, "s1");
7649 assert_eq!(
7650 sys.typed_value().expect("typed value")["future_field"],
7651 "preserved"
7652 );
7653 }
7654
7655 #[test]
7656 fn test_vcs_state_changed_fully_wrapped() {
7657 use super::{KnownSystemEvent, VcsMutationKind};
7658 use serde_json::Value;
7659
7660 for kind in ["commit", "push", "merge", "rebase"] {
7661 let raw: Value = serde_json::from_str(&format!(
7662 r#"{{"type":"system","subtype":"vcs_state_changed","kind":"{}","cwd":"/repo","uuid":"u1","session_id":"s1"}}"#,
7663 kind
7664 ))
7665 .unwrap();
7666 crate::io::assert_fully_wrapped(&raw);
7667
7668 let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7669 let ClaudeOutput::System(sys) = output else {
7670 panic!("expected System");
7671 };
7672 let Some(KnownSystemEvent::VcsStateChanged(msg)) = sys.as_known_system_event() else {
7673 panic!("expected VcsStateChanged event");
7674 };
7675 assert_eq!(msg.kind.as_str(), kind);
7676 assert!(!matches!(msg.kind, VcsMutationKind::Unknown(_)));
7677 }
7678
7679 let raw: Value = serde_json::from_str(
7681 r#"{"type":"system","subtype":"vcs_state_changed","kind":"tag","cwd":"/repo","uuid":"u2","session_id":"s2"}"#,
7682 )
7683 .unwrap();
7684 crate::io::assert_fully_wrapped(&raw);
7685 let output: ClaudeOutput = serde_json::from_value(raw).unwrap();
7686 let ClaudeOutput::System(sys) = output else {
7687 panic!("expected System");
7688 };
7689 let Some(KnownSystemEvent::VcsStateChanged(msg)) = sys.as_known_system_event() else {
7690 panic!("expected VcsStateChanged event");
7691 };
7692 assert_eq!(msg.kind, VcsMutationKind::Unknown("tag".to_string()));
7693
7694 assert!(sys.is_vcs_state_changed());
7695 let direct = sys.as_vcs_state_changed().expect("direct accessor");
7696 assert_eq!(direct.cwd, "/repo");
7697 assert!(sys.as_code_change_published().is_none());
7698 }
7699
7700 #[test]
7701 fn test_assistant_aborted_and_resume_flags_roundtrip() {
7702 let json = r#"{
7703 "type":"assistant",
7704 "message":{"id":"msg_1","role":"assistant","model":"claude-3","content":[{"type":"text","text":"partial"}]},
7705 "session_id":"s1",
7706 "aborted":true,
7707 "resumed_from_incomplete_thinking":true
7708 }"#;
7709 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7710 let ClaudeOutput::Assistant(msg) = &output else {
7711 panic!("expected Assistant");
7712 };
7713 assert_eq!(msg.aborted, Some(true));
7714 assert_eq!(msg.resumed_from_incomplete_thinking, Some(true));
7715 let reserialized = serde_json::to_string(&output).unwrap();
7716 assert!(reserialized.contains("\"aborted\":true"));
7717 assert!(reserialized.contains("\"resumed_from_incomplete_thinking\":true"));
7718
7719 let json = r#"{
7721 "type":"assistant",
7722 "message":{"id":"msg_2","role":"assistant","model":"claude-3","content":[]},
7723 "session_id":"s2"
7724 }"#;
7725 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7726 let reserialized = serde_json::to_string(&output).unwrap();
7727 assert!(!reserialized.contains("aborted"));
7728 assert!(!reserialized.contains("resumed_from_incomplete_thinking"));
7729 }
7730
7731 #[test]
7732 fn test_user_tool_result_meta_roundtrip() {
7733 let json = r#"{
7734 "type":"user",
7735 "message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_1","content":"denied"}]},
7736 "session_id":"622ae0c3-3d50-4fa7-9ee0-69d691238c6d",
7737 "tool_result_meta":[
7738 {"id":"toolu_1","non_execution_kind":"user-rejected","user_feedback":"use the staging db"},
7739 {"id":"toolu_2","non_execution_kind":"permission-rule"}
7740 ]
7741 }"#;
7742 let output: ClaudeOutput = serde_json::from_str(json).unwrap();
7743 let ClaudeOutput::User(user) = &output else {
7744 panic!("expected User");
7745 };
7746 let meta = user.tool_result_meta.as_ref().unwrap();
7747 assert_eq!(meta.len(), 2);
7748 assert_eq!(meta[0].non_execution_kind.as_deref(), Some("user-rejected"));
7749 assert_eq!(meta[0].user_feedback.as_deref(), Some("use the staging db"));
7750 assert_eq!(meta[1].user_feedback, None);
7751
7752 let reserialized = serde_json::to_string(&output).unwrap();
7753 assert!(reserialized.contains("\"non_execution_kind\":\"user-rejected\""));
7754 assert!(!reserialized.contains("\"user_feedback\":null"));
7755 }
7756
7757 #[test]
7761 fn model_refusal_fallback_scope_roundtrips_and_defaults() {
7762 use super::{ModelRefusalFallbackMessage, RefusalFallbackScope};
7763 let with_scope = serde_json::json!({
7764 "trigger": "refusal",
7765 "direction": "retry",
7766 "scope": "local",
7767 "original_model": "claude-fable-5",
7768 "fallback_model": "claude-opus-5",
7769 "request_id": null,
7770 "content": "Refused; retried on fallback model.",
7771 "uuid": "u1",
7772 "session_id": "s1"
7773 });
7774 let msg: ModelRefusalFallbackMessage = serde_json::from_value(with_scope.clone()).unwrap();
7775 assert_eq!(msg.scope, Some(RefusalFallbackScope::Local));
7776 assert_eq!(serde_json::to_value(&msg).unwrap(), with_scope);
7777
7778 let mut without = with_scope.clone();
7781 without.as_object_mut().unwrap().remove("scope");
7782 let msg: ModelRefusalFallbackMessage = serde_json::from_value(without.clone()).unwrap();
7783 assert_eq!(msg.scope, None);
7784 assert_eq!(serde_json::to_value(&msg).unwrap(), without);
7785
7786 assert_eq!(
7788 RefusalFallbackScope::from("workspace").as_str(),
7789 "workspace"
7790 );
7791 }
7792}