1use std::collections::BTreeMap;
29use std::path::PathBuf;
30
31use chrono::{DateTime, Utc};
32use serde::{Deserialize, Serialize};
33use serde_json::Value;
34
35use crate::ResponseChannel;
36use crate::UserInputQuestionEvent;
37use crate::ids::{SessionId, ThreadId};
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(rename_all = "snake_case")]
42pub enum TurnOutcomeStatus {
43 Completed,
44 Interrupted,
45 Failed,
46}
47
48impl TurnOutcomeStatus {
49 #[must_use]
50 pub fn as_str(self) -> &'static str {
51 match self {
52 Self::Completed => "completed",
53 Self::Interrupted => "interrupted",
54 Self::Failed => "failed",
55 }
56 }
57}
58
59#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
63pub struct TokenUsage {
64 pub input_tokens: u32,
65 pub output_tokens: u32,
66 #[serde(default, skip_serializing_if = "Option::is_none")]
67 pub prompt_cache_hit_tokens: Option<u32>,
68 #[serde(default, skip_serializing_if = "Option::is_none")]
69 pub prompt_cache_miss_tokens: Option<u32>,
70 #[serde(default, skip_serializing_if = "Option::is_none")]
71 pub prompt_cache_write_tokens: Option<u32>,
72 #[serde(default, skip_serializing_if = "Option::is_none")]
73 pub reasoning_tokens: Option<u32>,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
75 pub reasoning_replay_tokens: Option<u32>,
76 #[serde(default, skip_serializing_if = "Option::is_none")]
77 pub code_execution_requests: Option<u32>,
78 #[serde(default, skip_serializing_if = "Option::is_none")]
79 pub tool_search_requests: Option<u32>,
80}
81
82#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86pub struct TurnRouteReceipt {
87 pub provider: String,
88 pub provider_identity: String,
89 pub wire_model: String,
90 pub endpoint_identity: String,
91 pub credential_generation_present: bool,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
96#[serde(tag = "kind", rename_all = "snake_case")]
97pub enum RouteProduct {
98 Unproven,
100 Subscription { label: String },
102 Metered,
104}
105
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109pub struct RouteBillingEnvelope {
110 #[serde(default, skip_serializing_if = "Option::is_none")]
111 pub billing_surface: Option<String>,
112 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub endpoint_fingerprint: Option<String>,
114 pub billing_mode: String,
116 pub dispatched_at: DateTime<Utc>,
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121pub struct TurnRoute {
122 pub provider: String,
124 pub provider_identity: String,
126 pub model: String,
127 pub auto_model: bool,
128 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub receipt: Option<TurnRouteReceipt>,
130 #[serde(default, skip_serializing_if = "Option::is_none")]
131 pub billing: Option<RouteBillingEnvelope>,
132 pub base_url: String,
134 pub billing_product: RouteProduct,
135}
136
137#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
139#[serde(tag = "kind", rename_all = "snake_case")]
140pub enum ToolCallError {
141 InvalidInput { message: String },
142 MissingField { field: String },
143 PathEscape { path: PathBuf },
144 ExecutionFailed { message: String },
145 Timeout { seconds: u64 },
146 Cancelled { message: String },
147 NotAvailable { message: String },
148 PermissionDenied { message: String },
149}
150
151#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
153#[serde(tag = "outcome", rename_all = "snake_case")]
154pub enum ToolCallOutcome {
155 Ok {
156 content: String,
157 success: bool,
158 #[serde(default, skip_serializing_if = "Option::is_none")]
159 metadata: Option<Value>,
160 },
161 Err {
162 error: ToolCallError,
163 },
164}
165
166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
168pub struct AgentProgressActivity {
169 pub worker_status: String,
171 #[serde(default, skip_serializing_if = "Option::is_none")]
172 pub step: Option<u32>,
173 #[serde(default, skip_serializing_if = "Option::is_none")]
174 pub tool_name: Option<String>,
175}
176
177#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
179#[serde(tag = "outcome", rename_all = "snake_case")]
180pub enum SubAgentFollowUpOutcome {
181 Ok {
182 agent_id: String,
183 target_agent_id: String,
184 delivered: bool,
185 resumed: bool,
186 note: String,
187 },
188 Err {
189 reason: String,
190 },
191}
192
193#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
195pub struct AgentRosterRow {
196 pub worker_id: String,
197 pub display_name: String,
198 pub model: String,
199 pub state: String,
201 pub status: String,
203 #[serde(default, skip_serializing_if = "Option::is_none")]
204 pub activity: Option<String>,
205 #[serde(default, skip_serializing_if = "Option::is_none")]
206 pub millis: Option<u64>,
207 #[serde(default, skip_serializing_if = "Option::is_none")]
208 pub input_tokens: Option<u64>,
209 #[serde(default, skip_serializing_if = "Option::is_none")]
210 pub output_tokens: Option<u64>,
211 #[serde(default, skip_serializing_if = "Option::is_none")]
212 pub cost_microusd: Option<u64>,
213 pub steps_taken: u32,
214 #[serde(default, skip_serializing_if = "Option::is_none")]
215 pub parent_run_id: Option<String>,
216 pub run_id: String,
217}
218
219#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
221pub struct McpDiscoveredItem {
222 pub name: String,
223 pub model_name: String,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
225 pub description: Option<String>,
226}
227
228#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
230pub struct McpServerSnapshot {
231 pub name: String,
232 pub enabled: bool,
233 pub required: bool,
234 pub transport: String,
235 pub command_or_url: String,
236 pub connect_timeout: u64,
237 pub execute_timeout: u64,
238 pub read_timeout: u64,
239 pub connected: bool,
240 #[serde(default, skip_serializing_if = "Option::is_none")]
241 pub error: Option<String>,
242 pub capability_metadata: String,
244 pub tools: Vec<McpDiscoveredItem>,
245 pub resources: Vec<McpDiscoveredItem>,
246 pub prompts: Vec<McpDiscoveredItem>,
247}
248
249#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
251pub struct McpManagerSnapshot {
252 pub config_path: PathBuf,
253 pub config_exists: bool,
254 pub reload_required: bool,
255 pub servers: Vec<McpServerSnapshot>,
256}
257
258#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
260pub struct UserInputRequest {
261 pub questions: Vec<UserInputQuestionEvent>,
262}
263
264#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
266#[serde(rename_all = "snake_case")]
267pub enum ToolGate {
268 AutoReviewDeterministic,
269 AutoReviewGuardian,
270}
271
272#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
274#[serde(rename_all = "snake_case")]
275pub enum ToolGateVerdict {
276 Allowed,
277 Denied,
278 Unavailable,
279}
280
281#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
286#[serde(tag = "event", rename_all = "snake_case")]
287pub enum EventMsg {
288 ToolProjectionWarning {
290 thread_id: ThreadId,
291 session_id: SessionId,
292 provider: String,
293 omitted_tool_names: Vec<String>,
294 omitted_tool_count: u64,
295 },
296
297 MessageStarted {
299 thread_id: ThreadId,
300 session_id: SessionId,
301 index: u64,
302 },
303 ResponseDelta {
306 thread_id: ThreadId,
307 session_id: SessionId,
308 index: u64,
309 delta: String,
310 #[serde(default, skip_serializing_if = "ResponseChannel::is_text")]
311 channel: ResponseChannel,
312 },
313 MessageComplete {
314 thread_id: ThreadId,
315 session_id: SessionId,
316 index: u64,
317 },
318 ThinkingStarted {
319 thread_id: ThreadId,
320 session_id: SessionId,
321 index: u64,
322 },
323 ThinkingComplete {
324 thread_id: ThreadId,
325 session_id: SessionId,
326 index: u64,
327 },
328
329 ToolCallStarted {
331 thread_id: ThreadId,
332 session_id: SessionId,
333 tool_call_id: String,
334 tool_name: String,
335 input: Value,
336 },
337 ToolCallHeartbeat {
339 thread_id: ThreadId,
340 session_id: SessionId,
341 },
342 ToolCallComplete {
343 thread_id: ThreadId,
344 session_id: SessionId,
345 tool_call_id: String,
346 tool_name: String,
347 result: ToolCallOutcome,
348 },
349
350 TurnStarted {
352 thread_id: ThreadId,
353 session_id: SessionId,
354 turn_id: String,
355 created_at: DateTime<Utc>,
356 #[serde(default, skip_serializing_if = "Option::is_none")]
357 route: Option<TurnRoute>,
358 },
359 ToolRequestSnapshot {
362 thread_id: ThreadId,
363 session_id: SessionId,
364 snapshot: Value,
365 },
366 RouteDispatched {
368 thread_id: ThreadId,
369 session_id: SessionId,
370 turn_id: String,
371 route: TurnRoute,
372 },
373 TurnComplete {
374 thread_id: ThreadId,
375 session_id: SessionId,
376 #[serde(default, skip_serializing_if = "Option::is_none")]
379 turn_id: Option<String>,
380 status: TurnOutcomeStatus,
381 #[serde(default, skip_serializing_if = "Option::is_none")]
382 error: Option<String>,
383 usage: TokenUsage,
384 #[serde(default, skip_serializing_if = "Option::is_none")]
386 tool_catalog: Option<Vec<Value>>,
387 #[serde(default, skip_serializing_if = "Option::is_none")]
388 base_url: Option<String>,
389 },
390 TurnUsage {
392 thread_id: ThreadId,
393 session_id: SessionId,
394 usage: TokenUsage,
395 duration_ms: u64,
396 #[serde(default, skip_serializing_if = "Option::is_none")]
397 first_token_ms: Option<u64>,
398 #[serde(default, skip_serializing_if = "Option::is_none")]
399 request_ms: Option<u64>,
400 },
401
402 GoalUpdated {
405 thread_id: ThreadId,
406 session_id: SessionId,
407 snapshot: Value,
408 },
409 GoalContinuationWaiting {
410 thread_id: ThreadId,
411 session_id: SessionId,
412 delay_seconds: u64,
413 },
414 GoalContinuationWaitEnded {
415 thread_id: ThreadId,
416 session_id: SessionId,
417 interrupted: bool,
418 },
419
420 CompactionStarted {
422 thread_id: ThreadId,
423 session_id: SessionId,
424 id: String,
425 auto: bool,
426 message: String,
427 },
428 CompactionCompleted {
429 thread_id: ThreadId,
430 session_id: SessionId,
431 id: String,
432 auto: bool,
433 message: String,
434 #[serde(default, skip_serializing_if = "Option::is_none")]
435 messages_before: Option<u64>,
436 #[serde(default, skip_serializing_if = "Option::is_none")]
437 messages_after: Option<u64>,
438 #[serde(default, skip_serializing_if = "Option::is_none")]
439 summary_prompt: Option<String>,
440 #[serde(default, skip_serializing_if = "Option::is_none")]
441 post_input_tokens: Option<u64>,
442 },
443 CompactionCancelled {
444 thread_id: ThreadId,
445 session_id: SessionId,
446 id: String,
447 auto: bool,
448 message: String,
449 },
450 CompactionFailed {
451 thread_id: ThreadId,
452 session_id: SessionId,
453 id: String,
454 auto: bool,
455 message: String,
456 },
457 PurgeStarted {
458 thread_id: ThreadId,
459 session_id: SessionId,
460 message: String,
461 },
462 PurgeCompleted {
463 thread_id: ThreadId,
464 session_id: SessionId,
465 messages_before: u64,
466 messages_after: u64,
467 removed_count: u64,
468 replaced_count: u64,
469 message: String,
470 },
471 PurgeFailed {
472 thread_id: ThreadId,
473 session_id: SessionId,
474 message: String,
475 },
476
477 AgentSpawned {
479 thread_id: ThreadId,
480 session_id: SessionId,
481 owner_session_id: String,
482 id: String,
483 prompt: String,
484 #[serde(default, skip_serializing_if = "Option::is_none")]
485 parent_run_id: Option<String>,
486 spawn_depth: u32,
487 model: String,
488 #[serde(default, skip_serializing_if = "Option::is_none")]
489 route_source: Option<String>,
490 },
491 AgentProgress {
492 thread_id: ThreadId,
493 session_id: SessionId,
494 owner_session_id: String,
495 id: String,
496 status: String,
497 activity: AgentProgressActivity,
498 #[serde(default, skip_serializing_if = "Option::is_none")]
499 parent_run_id: Option<String>,
500 spawn_depth: u32,
501 },
502 AgentComplete {
503 thread_id: ThreadId,
504 session_id: SessionId,
505 owner_session_id: String,
506 id: String,
507 result: String,
508 },
509 SubAgentFollowUp {
510 thread_id: ThreadId,
511 session_id: SessionId,
512 owner_session_id: String,
513 agent_id: String,
514 outcome: SubAgentFollowUpOutcome,
515 },
516 AgentList {
519 thread_id: ThreadId,
520 session_id: SessionId,
521 owner_session_id: String,
522 agents: Vec<Value>,
523 coordination: Value,
524 #[serde(default)]
526 queued_follow_ups: BTreeMap<String, u64>,
527 roster: Vec<AgentRosterRow>,
528 },
529 SubAgentMailbox {
532 thread_id: ThreadId,
533 session_id: SessionId,
534 owner_session_id: String,
535 turn_id: String,
536 seq: u64,
537 message: Value,
538 },
539 WorkflowUi {
543 thread_id: ThreadId,
544 session_id: SessionId,
545 owner_session_id: String,
546 run_id: String,
547 ui_event: Value,
548 },
549
550 Error {
552 thread_id: ThreadId,
553 session_id: SessionId,
554 category: String,
556 severity: String,
558 recoverable: bool,
559 code: String,
560 message: String,
561 },
562 Status {
563 thread_id: ThreadId,
564 session_id: SessionId,
565 message: String,
566 },
567 McpSessionBoot {
568 thread_id: ThreadId,
569 session_id: SessionId,
570 generation: u64,
571 snapshot: McpManagerSnapshot,
572 connecting: Vec<String>,
573 finished: bool,
574 },
575 RequestManifestReady {
577 thread_id: ThreadId,
578 session_id: SessionId,
579 rendered: String,
580 },
581 PauseEvents {
584 thread_id: ThreadId,
585 session_id: SessionId,
586 },
587 ResumeEvents {
588 thread_id: ThreadId,
589 session_id: SessionId,
590 },
591 ApprovalRequired {
592 thread_id: ThreadId,
593 session_id: SessionId,
594 id: String,
595 tool_name: String,
596 description: String,
597 input: Value,
598 approval_key: String,
599 approval_grouping_key: String,
600 #[serde(default, skip_serializing_if = "Option::is_none")]
601 intent_summary: Option<String>,
602 approval_force_prompt: bool,
603 },
604 UserInputRequired {
605 thread_id: ThreadId,
606 session_id: SessionId,
607 id: String,
608 request: UserInputRequest,
609 },
610 SessionUpdated {
613 thread_id: ThreadId,
614 session_id: SessionId,
615 engine_session_id: String,
616 messages: Vec<Value>,
617 #[serde(default, skip_serializing_if = "Option::is_none")]
618 system_prompt: Option<Value>,
619 model: String,
620 workspace: PathBuf,
621 },
622 ElevationRequired {
623 thread_id: ThreadId,
624 session_id: SessionId,
625 tool_id: String,
626 tool_name: String,
627 #[serde(default, skip_serializing_if = "Option::is_none")]
628 command: Option<String>,
629 denial_reason: String,
630 blocked_network: bool,
631 blocked_write: bool,
632 },
633 LspRepairUpdate {
634 thread_id: ThreadId,
635 session_id: SessionId,
636 diagnostics_found: u64,
637 files: u64,
638 injected: bool,
639 },
640 ToolGateDecision {
641 thread_id: ThreadId,
642 session_id: SessionId,
643 #[serde(default, skip_serializing_if = "Option::is_none")]
644 agent_id: Option<String>,
645 tool_id: String,
646 tool_name: String,
647 gate: ToolGate,
648 decision: ToolGateVerdict,
649 #[serde(default, skip_serializing_if = "Option::is_none")]
650 risk: Option<String>,
651 reason: String,
652 },
653 AdvisoryNote {
654 thread_id: ThreadId,
655 session_id: SessionId,
656 turn_id: String,
657 note: String,
658 tool_call_count: u32,
659 },
660
661 PrefixCacheChange {
663 thread_id: ThreadId,
664 session_id: SessionId,
665 description: String,
666 system_prompt_changed: bool,
667 tools_changed: bool,
668 stability_pct: u32,
669 changed: bool,
670 pinned_combined_hash: String,
671 pin_reason: String,
672 last_miss_reason: String,
673 context_updates: u64,
674 },
675}
676
677#[derive(Debug, Clone, Serialize, Deserialize)]
681pub struct EventEnvelope {
682 pub seq: u64,
683 pub thread_id: ThreadId,
684 pub session_id: SessionId,
685 pub turn_id: Option<String>,
686 pub event: EventMsg,
687}
688
689pub const EVENT_KINDS: &[&str] = &[
693 "tool_projection_warning",
694 "message_started",
695 "response_delta",
696 "message_complete",
697 "thinking_started",
698 "thinking_complete",
699 "tool_call_started",
700 "tool_call_heartbeat",
701 "tool_call_complete",
702 "turn_started",
703 "tool_request_snapshot",
704 "route_dispatched",
705 "turn_complete",
706 "turn_usage",
707 "goal_updated",
708 "goal_continuation_waiting",
709 "goal_continuation_wait_ended",
710 "compaction_started",
711 "compaction_completed",
712 "compaction_cancelled",
713 "compaction_failed",
714 "purge_started",
715 "purge_completed",
716 "purge_failed",
717 "agent_spawned",
718 "agent_progress",
719 "agent_complete",
720 "sub_agent_follow_up",
721 "agent_list",
722 "sub_agent_mailbox",
723 "workflow_ui",
724 "error",
725 "status",
726 "mcp_session_boot",
727 "request_manifest_ready",
728 "pause_events",
729 "resume_events",
730 "approval_required",
731 "user_input_required",
732 "session_updated",
733 "elevation_required",
734 "lsp_repair_update",
735 "tool_gate_decision",
736 "advisory_note",
737 "prefix_cache_change",
738];
739
740impl EventMsg {
741 #[must_use]
742 pub fn kind_str(&self) -> &'static str {
743 match self {
744 Self::ToolProjectionWarning { .. } => "tool_projection_warning",
745 Self::MessageStarted { .. } => "message_started",
746 Self::ResponseDelta { .. } => "response_delta",
747 Self::MessageComplete { .. } => "message_complete",
748 Self::ThinkingStarted { .. } => "thinking_started",
749 Self::ThinkingComplete { .. } => "thinking_complete",
750 Self::ToolCallStarted { .. } => "tool_call_started",
751 Self::ToolCallHeartbeat { .. } => "tool_call_heartbeat",
752 Self::ToolCallComplete { .. } => "tool_call_complete",
753 Self::TurnStarted { .. } => "turn_started",
754 Self::ToolRequestSnapshot { .. } => "tool_request_snapshot",
755 Self::RouteDispatched { .. } => "route_dispatched",
756 Self::TurnComplete { .. } => "turn_complete",
757 Self::TurnUsage { .. } => "turn_usage",
758 Self::GoalUpdated { .. } => "goal_updated",
759 Self::GoalContinuationWaiting { .. } => "goal_continuation_waiting",
760 Self::GoalContinuationWaitEnded { .. } => "goal_continuation_wait_ended",
761 Self::CompactionStarted { .. } => "compaction_started",
762 Self::CompactionCompleted { .. } => "compaction_completed",
763 Self::CompactionCancelled { .. } => "compaction_cancelled",
764 Self::CompactionFailed { .. } => "compaction_failed",
765 Self::PurgeStarted { .. } => "purge_started",
766 Self::PurgeCompleted { .. } => "purge_completed",
767 Self::PurgeFailed { .. } => "purge_failed",
768 Self::AgentSpawned { .. } => "agent_spawned",
769 Self::AgentProgress { .. } => "agent_progress",
770 Self::AgentComplete { .. } => "agent_complete",
771 Self::SubAgentFollowUp { .. } => "sub_agent_follow_up",
772 Self::AgentList { .. } => "agent_list",
773 Self::SubAgentMailbox { .. } => "sub_agent_mailbox",
774 Self::WorkflowUi { .. } => "workflow_ui",
775 Self::Error { .. } => "error",
776 Self::Status { .. } => "status",
777 Self::McpSessionBoot { .. } => "mcp_session_boot",
778 Self::RequestManifestReady { .. } => "request_manifest_ready",
779 Self::PauseEvents { .. } => "pause_events",
780 Self::ResumeEvents { .. } => "resume_events",
781 Self::ApprovalRequired { .. } => "approval_required",
782 Self::UserInputRequired { .. } => "user_input_required",
783 Self::SessionUpdated { .. } => "session_updated",
784 Self::ElevationRequired { .. } => "elevation_required",
785 Self::LspRepairUpdate { .. } => "lsp_repair_update",
786 Self::ToolGateDecision { .. } => "tool_gate_decision",
787 Self::AdvisoryNote { .. } => "advisory_note",
788 Self::PrefixCacheChange { .. } => "prefix_cache_change",
789 }
790 }
791
792 #[must_use]
793 pub fn thread_id(&self) -> &ThreadId {
794 match self {
795 Self::ToolProjectionWarning { thread_id, .. }
796 | Self::MessageStarted { thread_id, .. }
797 | Self::ResponseDelta { thread_id, .. }
798 | Self::MessageComplete { thread_id, .. }
799 | Self::ThinkingStarted { thread_id, .. }
800 | Self::ThinkingComplete { thread_id, .. }
801 | Self::ToolCallStarted { thread_id, .. }
802 | Self::ToolCallHeartbeat { thread_id, .. }
803 | Self::ToolCallComplete { thread_id, .. }
804 | Self::TurnStarted { thread_id, .. }
805 | Self::ToolRequestSnapshot { thread_id, .. }
806 | Self::RouteDispatched { thread_id, .. }
807 | Self::TurnComplete { thread_id, .. }
808 | Self::TurnUsage { thread_id, .. }
809 | Self::GoalUpdated { thread_id, .. }
810 | Self::GoalContinuationWaiting { thread_id, .. }
811 | Self::GoalContinuationWaitEnded { thread_id, .. }
812 | Self::CompactionStarted { thread_id, .. }
813 | Self::CompactionCompleted { thread_id, .. }
814 | Self::CompactionCancelled { thread_id, .. }
815 | Self::CompactionFailed { thread_id, .. }
816 | Self::PurgeStarted { thread_id, .. }
817 | Self::PurgeCompleted { thread_id, .. }
818 | Self::PurgeFailed { thread_id, .. }
819 | Self::AgentSpawned { thread_id, .. }
820 | Self::AgentProgress { thread_id, .. }
821 | Self::AgentComplete { thread_id, .. }
822 | Self::SubAgentFollowUp { thread_id, .. }
823 | Self::AgentList { thread_id, .. }
824 | Self::SubAgentMailbox { thread_id, .. }
825 | Self::WorkflowUi { thread_id, .. }
826 | Self::Error { thread_id, .. }
827 | Self::Status { thread_id, .. }
828 | Self::McpSessionBoot { thread_id, .. }
829 | Self::RequestManifestReady { thread_id, .. }
830 | Self::PauseEvents { thread_id, .. }
831 | Self::ResumeEvents { thread_id, .. }
832 | Self::ApprovalRequired { thread_id, .. }
833 | Self::UserInputRequired { thread_id, .. }
834 | Self::SessionUpdated { thread_id, .. }
835 | Self::ElevationRequired { thread_id, .. }
836 | Self::LspRepairUpdate { thread_id, .. }
837 | Self::ToolGateDecision { thread_id, .. }
838 | Self::AdvisoryNote { thread_id, .. }
839 | Self::PrefixCacheChange { thread_id, .. } => thread_id,
840 }
841 }
842
843 #[must_use]
844 pub fn session_id(&self) -> &SessionId {
845 match self {
846 Self::ToolProjectionWarning { session_id, .. }
847 | Self::MessageStarted { session_id, .. }
848 | Self::ResponseDelta { session_id, .. }
849 | Self::MessageComplete { session_id, .. }
850 | Self::ThinkingStarted { session_id, .. }
851 | Self::ThinkingComplete { session_id, .. }
852 | Self::ToolCallStarted { session_id, .. }
853 | Self::ToolCallHeartbeat { session_id, .. }
854 | Self::ToolCallComplete { session_id, .. }
855 | Self::TurnStarted { session_id, .. }
856 | Self::ToolRequestSnapshot { session_id, .. }
857 | Self::RouteDispatched { session_id, .. }
858 | Self::TurnComplete { session_id, .. }
859 | Self::TurnUsage { session_id, .. }
860 | Self::GoalUpdated { session_id, .. }
861 | Self::GoalContinuationWaiting { session_id, .. }
862 | Self::GoalContinuationWaitEnded { session_id, .. }
863 | Self::CompactionStarted { session_id, .. }
864 | Self::CompactionCompleted { session_id, .. }
865 | Self::CompactionCancelled { session_id, .. }
866 | Self::CompactionFailed { session_id, .. }
867 | Self::PurgeStarted { session_id, .. }
868 | Self::PurgeCompleted { session_id, .. }
869 | Self::PurgeFailed { session_id, .. }
870 | Self::AgentSpawned { session_id, .. }
871 | Self::AgentProgress { session_id, .. }
872 | Self::AgentComplete { session_id, .. }
873 | Self::SubAgentFollowUp { session_id, .. }
874 | Self::AgentList { session_id, .. }
875 | Self::SubAgentMailbox { session_id, .. }
876 | Self::WorkflowUi { session_id, .. }
877 | Self::Error { session_id, .. }
878 | Self::Status { session_id, .. }
879 | Self::McpSessionBoot { session_id, .. }
880 | Self::RequestManifestReady { session_id, .. }
881 | Self::PauseEvents { session_id, .. }
882 | Self::ResumeEvents { session_id, .. }
883 | Self::ApprovalRequired { session_id, .. }
884 | Self::UserInputRequired { session_id, .. }
885 | Self::SessionUpdated { session_id, .. }
886 | Self::ElevationRequired { session_id, .. }
887 | Self::LspRepairUpdate { session_id, .. }
888 | Self::ToolGateDecision { session_id, .. }
889 | Self::AdvisoryNote { session_id, .. }
890 | Self::PrefixCacheChange { session_id, .. } => session_id,
891 }
892 }
893}
894
895#[cfg(test)]
896mod tests {
897 use super::*;
898 use serde_json::json;
899
900 fn ids() -> (ThreadId, SessionId) {
901 (ThreadId::new(), SessionId::new())
902 }
903
904 fn every_variant() -> Vec<EventMsg> {
907 let (t, s) = ids();
908 let usage = TokenUsage {
909 input_tokens: 1,
910 output_tokens: 2,
911 ..TokenUsage::default()
912 };
913 let route = TurnRoute {
914 provider: "deepseek".into(),
915 provider_identity: "deepseek".into(),
916 model: "deepseek-chat".into(),
917 auto_model: false,
918 receipt: Some(TurnRouteReceipt {
919 provider: "deepseek".into(),
920 provider_identity: "deepseek".into(),
921 wire_model: "deepseek-chat".into(),
922 endpoint_identity: "api.deepseek.com".into(),
923 credential_generation_present: true,
924 }),
925 billing: Some(RouteBillingEnvelope {
926 billing_surface: None,
927 endpoint_fingerprint: Some("fp".into()),
928 billing_mode: "metered".into(),
929 dispatched_at: DateTime::<Utc>::from_timestamp(0, 0).unwrap(),
930 }),
931 base_url: "https://api.deepseek.com".into(),
932 billing_product: RouteProduct::Subscription {
933 label: "pro".into(),
934 },
935 };
936 vec![
937 EventMsg::ToolProjectionWarning {
938 thread_id: t.clone(),
939 session_id: s.clone(),
940 provider: "openai".into(),
941 omitted_tool_names: vec!["a".into()],
942 omitted_tool_count: 3,
943 },
944 EventMsg::MessageStarted {
945 thread_id: t.clone(),
946 session_id: s.clone(),
947 index: 0,
948 },
949 EventMsg::ResponseDelta {
950 thread_id: t.clone(),
951 session_id: s.clone(),
952 index: 0,
953 delta: "hi".into(),
954 channel: ResponseChannel::Reasoning,
955 },
956 EventMsg::MessageComplete {
957 thread_id: t.clone(),
958 session_id: s.clone(),
959 index: 0,
960 },
961 EventMsg::ThinkingStarted {
962 thread_id: t.clone(),
963 session_id: s.clone(),
964 index: 1,
965 },
966 EventMsg::ThinkingComplete {
967 thread_id: t.clone(),
968 session_id: s.clone(),
969 index: 1,
970 },
971 EventMsg::ToolCallStarted {
972 thread_id: t.clone(),
973 session_id: s.clone(),
974 tool_call_id: "c1".into(),
975 tool_name: "read_file".into(),
976 input: json!({"path": "x"}),
977 },
978 EventMsg::ToolCallHeartbeat {
979 thread_id: t.clone(),
980 session_id: s.clone(),
981 },
982 EventMsg::ToolCallComplete {
983 thread_id: t.clone(),
984 session_id: s.clone(),
985 tool_call_id: "c1".into(),
986 tool_name: "read_file".into(),
987 result: ToolCallOutcome::Err {
988 error: ToolCallError::Timeout { seconds: 3 },
989 },
990 },
991 EventMsg::TurnStarted {
992 thread_id: t.clone(),
993 session_id: s.clone(),
994 turn_id: "turn-1".into(),
995 created_at: DateTime::<Utc>::from_timestamp(1, 0).unwrap(),
996 route: Some(route.clone()),
997 },
998 EventMsg::ToolRequestSnapshot {
999 thread_id: t.clone(),
1000 session_id: s.clone(),
1001 snapshot: json!({"tool_count": 2}),
1002 },
1003 EventMsg::RouteDispatched {
1004 thread_id: t.clone(),
1005 session_id: s.clone(),
1006 turn_id: "turn-1".into(),
1007 route,
1008 },
1009 EventMsg::TurnComplete {
1010 thread_id: t.clone(),
1011 session_id: s.clone(),
1012 turn_id: None,
1013 status: TurnOutcomeStatus::Failed,
1014 error: Some("boom".into()),
1015 usage: usage.clone(),
1016 tool_catalog: Some(vec![json!({"name": "read_file"})]),
1017 base_url: None,
1018 },
1019 EventMsg::TurnUsage {
1020 thread_id: t.clone(),
1021 session_id: s.clone(),
1022 usage,
1023 duration_ms: 10,
1024 first_token_ms: Some(2),
1025 request_ms: None,
1026 },
1027 EventMsg::GoalUpdated {
1028 thread_id: t.clone(),
1029 session_id: s.clone(),
1030 snapshot: json!({"status": "active"}),
1031 },
1032 EventMsg::GoalContinuationWaiting {
1033 thread_id: t.clone(),
1034 session_id: s.clone(),
1035 delay_seconds: 5,
1036 },
1037 EventMsg::GoalContinuationWaitEnded {
1038 thread_id: t.clone(),
1039 session_id: s.clone(),
1040 interrupted: true,
1041 },
1042 EventMsg::CompactionStarted {
1043 thread_id: t.clone(),
1044 session_id: s.clone(),
1045 id: "cmp-1".into(),
1046 auto: true,
1047 message: "m".into(),
1048 },
1049 EventMsg::CompactionCompleted {
1050 thread_id: t.clone(),
1051 session_id: s.clone(),
1052 id: "cmp-1".into(),
1053 auto: true,
1054 message: "m".into(),
1055 messages_before: Some(10),
1056 messages_after: Some(2),
1057 summary_prompt: None,
1058 post_input_tokens: Some(100),
1059 },
1060 EventMsg::CompactionCancelled {
1061 thread_id: t.clone(),
1062 session_id: s.clone(),
1063 id: "cmp-1".into(),
1064 auto: false,
1065 message: "m".into(),
1066 },
1067 EventMsg::CompactionFailed {
1068 thread_id: t.clone(),
1069 session_id: s.clone(),
1070 id: "cmp-1".into(),
1071 auto: false,
1072 message: "m".into(),
1073 },
1074 EventMsg::PurgeStarted {
1075 thread_id: t.clone(),
1076 session_id: s.clone(),
1077 message: "m".into(),
1078 },
1079 EventMsg::PurgeCompleted {
1080 thread_id: t.clone(),
1081 session_id: s.clone(),
1082 messages_before: 4,
1083 messages_after: 2,
1084 removed_count: 2,
1085 replaced_count: 0,
1086 message: "m".into(),
1087 },
1088 EventMsg::PurgeFailed {
1089 thread_id: t.clone(),
1090 session_id: s.clone(),
1091 message: "m".into(),
1092 },
1093 EventMsg::AgentSpawned {
1094 thread_id: t.clone(),
1095 session_id: s.clone(),
1096 owner_session_id: "owner".into(),
1097 id: "a1".into(),
1098 prompt: "p".into(),
1099 parent_run_id: None,
1100 spawn_depth: 1,
1101 model: "m".into(),
1102 route_source: Some("task.model".into()),
1103 },
1104 EventMsg::AgentProgress {
1105 thread_id: t.clone(),
1106 session_id: s.clone(),
1107 owner_session_id: "owner".into(),
1108 id: "a1".into(),
1109 status: "running".into(),
1110 activity: AgentProgressActivity {
1111 worker_status: "running_tool".into(),
1112 step: Some(2),
1113 tool_name: Some("bash".into()),
1114 },
1115 parent_run_id: None,
1116 spawn_depth: 1,
1117 },
1118 EventMsg::AgentComplete {
1119 thread_id: t.clone(),
1120 session_id: s.clone(),
1121 owner_session_id: "owner".into(),
1122 id: "a1".into(),
1123 result: "done".into(),
1124 },
1125 EventMsg::SubAgentFollowUp {
1126 thread_id: t.clone(),
1127 session_id: s.clone(),
1128 owner_session_id: "owner".into(),
1129 agent_id: "a1".into(),
1130 outcome: SubAgentFollowUpOutcome::Ok {
1131 agent_id: "a1".into(),
1132 target_agent_id: "a2".into(),
1133 delivered: false,
1134 resumed: true,
1135 note: "resumed".into(),
1136 },
1137 },
1138 EventMsg::AgentList {
1139 thread_id: t.clone(),
1140 session_id: s.clone(),
1141 owner_session_id: "owner".into(),
1142 agents: vec![json!({"id": "a1"})],
1143 coordination: json!({}),
1144 queued_follow_ups: BTreeMap::from([("a1".to_string(), 1)]),
1145 roster: vec![AgentRosterRow {
1146 worker_id: "w1".into(),
1147 display_name: "scout".into(),
1148 model: "m".into(),
1149 state: "running".into(),
1150 status: "running".into(),
1151 activity: None,
1152 millis: Some(5),
1153 input_tokens: None,
1154 output_tokens: None,
1155 cost_microusd: None,
1156 steps_taken: 1,
1157 parent_run_id: None,
1158 run_id: "r1".into(),
1159 }],
1160 },
1161 EventMsg::SubAgentMailbox {
1162 thread_id: t.clone(),
1163 session_id: s.clone(),
1164 owner_session_id: "owner".into(),
1165 turn_id: "turn-1".into(),
1166 seq: 7,
1167 message: json!({"kind": "spawned"}),
1168 },
1169 EventMsg::WorkflowUi {
1170 thread_id: t.clone(),
1171 session_id: s.clone(),
1172 owner_session_id: "owner".into(),
1173 run_id: "run-1".into(),
1174 ui_event: json!({"type": "task_started"}),
1175 },
1176 EventMsg::Error {
1177 thread_id: t.clone(),
1178 session_id: s.clone(),
1179 category: "network".into(),
1180 severity: "error".into(),
1181 recoverable: true,
1182 code: "E1".into(),
1183 message: "m".into(),
1184 },
1185 EventMsg::Status {
1186 thread_id: t.clone(),
1187 session_id: s.clone(),
1188 message: "m".into(),
1189 },
1190 EventMsg::McpSessionBoot {
1191 thread_id: t.clone(),
1192 session_id: s.clone(),
1193 generation: 1,
1194 snapshot: McpManagerSnapshot {
1195 config_path: PathBuf::from("/tmp/mcp.json"),
1196 config_exists: true,
1197 reload_required: false,
1198 servers: vec![McpServerSnapshot {
1199 name: "fs".into(),
1200 enabled: true,
1201 required: false,
1202 transport: "stdio".into(),
1203 command_or_url: "npx".into(),
1204 connect_timeout: 1,
1205 execute_timeout: 2,
1206 read_timeout: 3,
1207 connected: true,
1208 error: None,
1209 capability_metadata: "advertised".into(),
1210 tools: vec![McpDiscoveredItem {
1211 name: "read".into(),
1212 model_name: "fs__read".into(),
1213 description: None,
1214 }],
1215 resources: vec![],
1216 prompts: vec![],
1217 }],
1218 },
1219 connecting: vec!["slow".into()],
1220 finished: false,
1221 },
1222 EventMsg::RequestManifestReady {
1223 thread_id: t.clone(),
1224 session_id: s.clone(),
1225 rendered: "manifest".into(),
1226 },
1227 EventMsg::PauseEvents {
1228 thread_id: t.clone(),
1229 session_id: s.clone(),
1230 },
1231 EventMsg::ResumeEvents {
1232 thread_id: t.clone(),
1233 session_id: s.clone(),
1234 },
1235 EventMsg::ApprovalRequired {
1236 thread_id: t.clone(),
1237 session_id: s.clone(),
1238 id: "c1".into(),
1239 tool_name: "bash".into(),
1240 description: "rm".into(),
1241 input: json!({"command": "rm"}),
1242 approval_key: "k".into(),
1243 approval_grouping_key: "g".into(),
1244 intent_summary: None,
1245 approval_force_prompt: true,
1246 },
1247 EventMsg::UserInputRequired {
1248 thread_id: t.clone(),
1249 session_id: s.clone(),
1250 id: "c2".into(),
1251 request: UserInputRequest {
1252 questions: vec![UserInputQuestionEvent {
1253 header: "h".into(),
1254 id: "q1".into(),
1255 question: "?".into(),
1256 options: vec![],
1257 allow_free_text: true,
1258 multi_select: false,
1259 }],
1260 },
1261 },
1262 EventMsg::SessionUpdated {
1263 thread_id: t.clone(),
1264 session_id: s.clone(),
1265 engine_session_id: "sess".into(),
1266 messages: vec![json!({"role": "user", "content": []})],
1267 system_prompt: Some(json!("sys")),
1268 model: "m".into(),
1269 workspace: PathBuf::from("/ws"),
1270 },
1271 EventMsg::ElevationRequired {
1272 thread_id: t.clone(),
1273 session_id: s.clone(),
1274 tool_id: "c3".into(),
1275 tool_name: "bash".into(),
1276 command: Some("curl".into()),
1277 denial_reason: "net".into(),
1278 blocked_network: true,
1279 blocked_write: false,
1280 },
1281 EventMsg::LspRepairUpdate {
1282 thread_id: t.clone(),
1283 session_id: s.clone(),
1284 diagnostics_found: 1,
1285 files: 1,
1286 injected: true,
1287 },
1288 EventMsg::ToolGateDecision {
1289 thread_id: t.clone(),
1290 session_id: s.clone(),
1291 agent_id: None,
1292 tool_id: "c4".into(),
1293 tool_name: "bash".into(),
1294 gate: ToolGate::AutoReviewGuardian,
1295 decision: ToolGateVerdict::Denied,
1296 risk: Some("high".into()),
1297 reason: "no".into(),
1298 },
1299 EventMsg::AdvisoryNote {
1300 thread_id: t.clone(),
1301 session_id: s.clone(),
1302 turn_id: "turn-1".into(),
1303 note: "n".into(),
1304 tool_call_count: 2,
1305 },
1306 EventMsg::PrefixCacheChange {
1307 thread_id: t,
1308 session_id: s,
1309 description: "d".into(),
1310 system_prompt_changed: false,
1311 tools_changed: true,
1312 stability_pct: 90,
1313 changed: true,
1314 pinned_combined_hash: "h".into(),
1315 pin_reason: "initial".into(),
1316 last_miss_reason: String::new(),
1317 context_updates: 0,
1318 },
1319 ]
1320 }
1321
1322 #[test]
1323 fn every_variant_is_listed_once() {
1324 let kinds: Vec<&str> = every_variant().iter().map(EventMsg::kind_str).collect();
1325 assert_eq!(
1326 kinds, EVENT_KINDS,
1327 "EVENT_KINDS must list every variant in order"
1328 );
1329 }
1330
1331 #[test]
1332 fn every_variant_round_trips_and_tags_by_event() {
1333 for msg in every_variant() {
1334 let value = serde_json::to_value(&msg).unwrap();
1335 assert_eq!(value["event"], msg.kind_str(), "{msg:?}");
1336 assert_eq!(value["thread_id"], msg.thread_id().to_string(), "{msg:?}");
1337 assert_eq!(value["session_id"], msg.session_id().to_string(), "{msg:?}");
1338 let back: EventMsg = serde_json::from_value(value).unwrap();
1339 assert_eq!(back, msg);
1340 }
1341 }
1342
1343 #[test]
1344 fn event_msg_roundtrip() {
1345 let msg = EventMsg::TurnComplete {
1346 thread_id: ThreadId::new(),
1347 session_id: SessionId::new(),
1348 turn_id: Some("turn-1".into()),
1349 status: TurnOutcomeStatus::Completed,
1350 error: None,
1351 usage: TokenUsage::default(),
1352 tool_catalog: None,
1353 base_url: None,
1354 };
1355 let json = serde_json::to_string(&msg).unwrap();
1356 let back: EventMsg = serde_json::from_str(&json).unwrap();
1357 assert_eq!(back.kind_str(), "turn_complete");
1358 assert!(json.contains(r#""status":"completed""#));
1359 }
1360
1361 #[test]
1362 fn text_channel_is_elided_on_the_wire() {
1363 let msg = EventMsg::ResponseDelta {
1364 thread_id: ThreadId::new(),
1365 session_id: SessionId::new(),
1366 index: 0,
1367 delta: "x".into(),
1368 channel: ResponseChannel::Text,
1369 };
1370 let json = serde_json::to_string(&msg).unwrap();
1371 assert!(!json.contains("channel"), "{json}");
1372 let back: EventMsg = serde_json::from_str(&json).unwrap();
1373 assert_eq!(back, msg);
1374 }
1375}