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 openrouter_vendor: Option<String>,
112 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub billing_surface: Option<String>,
114 #[serde(default, skip_serializing_if = "Option::is_none")]
115 pub endpoint_fingerprint: Option<String>,
116 #[serde(default, skip_serializing_if = "Option::is_none")]
118 pub provider_live_pricing: Option<Value>,
119 pub billing_mode: String,
121 pub dispatched_at: DateTime<Utc>,
122}
123
124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct TurnRoute {
127 pub provider: String,
129 pub provider_identity: String,
131 pub model: String,
132 pub auto_model: bool,
133 #[serde(default, skip_serializing_if = "Option::is_none")]
134 pub receipt: Option<TurnRouteReceipt>,
135 #[serde(default, skip_serializing_if = "Option::is_none")]
136 pub billing: Option<RouteBillingEnvelope>,
137 pub base_url: String,
139 pub billing_product: RouteProduct,
140}
141
142#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
144#[serde(tag = "kind", rename_all = "snake_case")]
145pub enum ToolCallError {
146 InvalidInput { message: String },
147 MissingField { field: String },
148 PathEscape { path: PathBuf },
149 ExecutionFailed { message: String },
150 Timeout { seconds: u64 },
151 Cancelled { message: String },
152 NotAvailable { message: String },
153 PermissionDenied { message: String },
154}
155
156#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
158#[serde(tag = "outcome", rename_all = "snake_case")]
159pub enum ToolCallOutcome {
160 Ok {
161 content: String,
162 success: bool,
163 #[serde(default, skip_serializing_if = "Option::is_none")]
164 metadata: Option<Value>,
165 },
166 Err {
167 error: ToolCallError,
168 },
169}
170
171#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
173pub struct AgentProgressActivity {
174 pub worker_status: String,
176 #[serde(default, skip_serializing_if = "Option::is_none")]
177 pub step: Option<u32>,
178 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub tool_name: Option<String>,
180}
181
182#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
184#[serde(tag = "outcome", rename_all = "snake_case")]
185pub enum SubAgentFollowUpOutcome {
186 Ok {
187 agent_id: String,
188 target_agent_id: String,
189 delivered: bool,
190 resumed: bool,
191 note: String,
192 },
193 Err {
194 reason: String,
195 },
196}
197
198#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
200pub struct AgentRosterRow {
201 pub worker_id: String,
202 pub display_name: String,
203 pub model: String,
204 pub state: String,
207 pub status: String,
209 #[serde(default, skip_serializing_if = "Option::is_none")]
210 pub activity: Option<String>,
211 #[serde(default, skip_serializing_if = "Option::is_none")]
212 pub millis: Option<u64>,
213 #[serde(default, skip_serializing_if = "Option::is_none")]
214 pub input_tokens: Option<u64>,
215 #[serde(default, skip_serializing_if = "Option::is_none")]
216 pub output_tokens: Option<u64>,
217 #[serde(default, skip_serializing_if = "Option::is_none")]
218 pub cost_microusd: Option<u64>,
219 pub steps_taken: u32,
220 #[serde(default, skip_serializing_if = "Option::is_none")]
221 pub parent_run_id: Option<String>,
222 pub run_id: String,
223}
224
225#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
227pub struct McpDiscoveredItem {
228 pub name: String,
229 pub model_name: String,
230 #[serde(default, skip_serializing_if = "Option::is_none")]
231 pub description: Option<String>,
232}
233
234#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
236pub struct McpServerSnapshot {
237 pub name: String,
238 pub enabled: bool,
239 pub required: bool,
240 pub transport: String,
241 pub command_or_url: String,
242 pub connect_timeout: u64,
243 pub execute_timeout: u64,
244 pub read_timeout: u64,
245 pub connected: bool,
246 #[serde(default, skip_serializing_if = "Option::is_none")]
247 pub error: Option<String>,
248 pub capability_metadata: String,
250 pub tools: Vec<McpDiscoveredItem>,
251 pub resources: Vec<McpDiscoveredItem>,
252 pub prompts: Vec<McpDiscoveredItem>,
253}
254
255#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
257pub struct McpManagerSnapshot {
258 pub config_path: PathBuf,
259 pub config_exists: bool,
260 pub reload_required: bool,
261 pub servers: Vec<McpServerSnapshot>,
262}
263
264#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
266pub struct UserInputRequest {
267 pub questions: Vec<UserInputQuestionEvent>,
268}
269
270#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
272#[serde(rename_all = "snake_case")]
273pub enum ToolGate {
274 AutoReviewDeterministic,
275 AutoReviewGuardian,
276}
277
278#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
280#[serde(rename_all = "snake_case")]
281pub enum ToolGateVerdict {
282 Allowed,
283 Denied,
284 Unavailable,
285}
286
287#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
292#[serde(tag = "event", rename_all = "snake_case")]
293pub enum EventMsg {
294 ToolProjectionWarning {
296 thread_id: ThreadId,
297 session_id: SessionId,
298 provider: String,
299 omitted_tool_names: Vec<String>,
300 omitted_tool_count: u64,
301 },
302
303 RequestImageWindow {
304 thread_id: ThreadId,
305 session_id: SessionId,
306 provider: String,
307 model: String,
308 total: u64,
309 elided: u64,
310 cap: u64,
311 cap_source: String,
312 message: String,
313 },
314
315 SnapshotsDisabled {
320 thread_id: ThreadId,
321 session_id: SessionId,
322 workspace: String,
323 reason: String,
324 },
325
326 MessageStarted {
328 thread_id: ThreadId,
329 session_id: SessionId,
330 index: u64,
331 },
332 ResponseDelta {
335 thread_id: ThreadId,
336 session_id: SessionId,
337 index: u64,
338 delta: String,
339 #[serde(default, skip_serializing_if = "ResponseChannel::is_text")]
340 channel: ResponseChannel,
341 },
342 MessageComplete {
343 thread_id: ThreadId,
344 session_id: SessionId,
345 index: u64,
346 },
347 ThinkingStarted {
348 thread_id: ThreadId,
349 session_id: SessionId,
350 index: u64,
351 },
352 ThinkingComplete {
353 thread_id: ThreadId,
354 session_id: SessionId,
355 index: u64,
356 },
357
358 ToolCallStarted {
360 thread_id: ThreadId,
361 session_id: SessionId,
362 tool_call_id: String,
363 tool_name: String,
364 input: Value,
365 },
366 ToolCallHeartbeat {
368 thread_id: ThreadId,
369 session_id: SessionId,
370 },
371 ToolExecutionStarted {
372 thread_id: ThreadId,
373 session_id: SessionId,
374 tool_call_id: String,
375 },
376 ToolResultContent {
377 thread_id: ThreadId,
378 session_id: SessionId,
379 tool_call_id: String,
380 blocks: Value,
381 },
382 ToolCallComplete {
383 thread_id: ThreadId,
384 session_id: SessionId,
385 tool_call_id: String,
386 tool_name: String,
387 result: ToolCallOutcome,
388 },
389 OperationActivityStarted {
393 thread_id: ThreadId,
394 session_id: SessionId,
395 span_id: String,
396 activity_kind: crate::engine_owner::OwnerActivityKind,
397 #[serde(default, skip_serializing_if = "Option::is_none")]
398 action_id: Option<String>,
399 },
400 OperationActivityCompleted {
401 thread_id: ThreadId,
402 session_id: SessionId,
403 span_id: String,
404 activity_kind: crate::engine_owner::OwnerActivityKind,
405 outcome: crate::engine_owner::OwnerOperationOutcome,
406 #[serde(default, skip_serializing_if = "Option::is_none")]
407 action_id: Option<String>,
408 },
409
410 TurnStarted {
412 thread_id: ThreadId,
413 session_id: SessionId,
414 turn_id: String,
415 created_at: DateTime<Utc>,
416 #[serde(default, skip_serializing_if = "Option::is_none")]
417 route: Option<TurnRoute>,
418 #[serde(default, skip_serializing_if = "Option::is_none")]
425 submission_id: Option<String>,
426 },
427 ToolRequestSnapshot {
430 thread_id: ThreadId,
431 session_id: SessionId,
432 snapshot: Value,
433 },
434 WorkspaceSnapshotTaken {
439 thread_id: ThreadId,
440 session_id: SessionId,
441 snapshot: Value,
442 },
443 RouteDispatched {
445 thread_id: ThreadId,
446 session_id: SessionId,
447 turn_id: String,
448 route: TurnRoute,
449 },
450 TurnComplete {
451 thread_id: ThreadId,
452 session_id: SessionId,
453 #[serde(default, skip_serializing_if = "Option::is_none")]
456 turn_id: Option<String>,
457 #[serde(default, skip_serializing_if = "Option::is_none")]
461 submission_id: Option<String>,
462 #[serde(default, skip_serializing_if = "Option::is_none")]
465 compaction_id: Option<String>,
466 status: TurnOutcomeStatus,
467 #[serde(default, skip_serializing_if = "Option::is_none")]
468 error: Option<String>,
469 usage: TokenUsage,
470 #[serde(default, skip_serializing_if = "Option::is_none")]
472 parent_route_usage: Option<TokenUsage>,
473 #[serde(default)]
474 routed_usage_dropped_records: u64,
475 #[serde(default, skip_serializing_if = "Option::is_none")]
477 tool_catalog: Option<Vec<Value>>,
478 #[serde(default, skip_serializing_if = "Option::is_none")]
479 base_url: Option<String>,
480 },
481 ProviderRequestReceipt {
482 thread_id: ThreadId,
483 session_id: SessionId,
484 receipt: Value,
485 },
486
487 TurnUsage {
489 #[serde(
490 default,
491 rename = "maxOutputTokens",
492 skip_serializing_if = "Option::is_none"
493 )]
494 max_output_tokens: Option<u32>,
495 thread_id: ThreadId,
496 session_id: SessionId,
497 usage: TokenUsage,
498 duration_ms: u64,
499 #[serde(default, skip_serializing_if = "Option::is_none")]
500 first_token_ms: Option<u64>,
501 #[serde(default, skip_serializing_if = "Option::is_none")]
502 request_ms: Option<u64>,
503 },
504
505 RoutedTurnUsage {
507 thread_id: ThreadId,
508 session_id: SessionId,
509 usage: TokenUsage,
510 duration_ms: u64,
511 #[serde(default, skip_serializing_if = "Option::is_none")]
512 first_token_ms: Option<u64>,
513 #[serde(default, skip_serializing_if = "Option::is_none")]
514 request_ms: Option<u64>,
515 },
516
517 GoalUpdated {
520 thread_id: ThreadId,
521 session_id: SessionId,
522 snapshot: Value,
523 },
524 GoalContinuationWaiting {
525 thread_id: ThreadId,
526 session_id: SessionId,
527 delay_seconds: u64,
528 },
529 GoalContinuationWaitEnded {
530 thread_id: ThreadId,
531 session_id: SessionId,
532 interrupted: bool,
533 },
534
535 CompactionStarted {
537 thread_id: ThreadId,
538 session_id: SessionId,
539 id: String,
540 auto: bool,
541 message: String,
542 },
543 CompactionCompleted {
544 thread_id: ThreadId,
545 session_id: SessionId,
546 id: String,
547 auto: bool,
548 message: String,
549 #[serde(default, skip_serializing_if = "Option::is_none")]
550 messages_before: Option<u64>,
551 #[serde(default, skip_serializing_if = "Option::is_none")]
552 messages_after: Option<u64>,
553 #[serde(default, skip_serializing_if = "Option::is_none")]
554 summary_prompt: Option<String>,
555 #[serde(default, skip_serializing_if = "Option::is_none")]
556 post_input_tokens: Option<u64>,
557 },
558 CompactionCancelled {
559 thread_id: ThreadId,
560 session_id: SessionId,
561 id: String,
562 auto: bool,
563 message: String,
564 },
565 CompactionFailed {
566 thread_id: ThreadId,
567 session_id: SessionId,
568 id: String,
569 auto: bool,
570 message: String,
571 },
572 PurgeStarted {
573 thread_id: ThreadId,
574 session_id: SessionId,
575 message: String,
576 },
577 PurgeCompleted {
578 thread_id: ThreadId,
579 session_id: SessionId,
580 messages_before: u64,
581 messages_after: u64,
582 removed_count: u64,
583 replaced_count: u64,
584 message: String,
585 },
586 PurgeFailed {
587 thread_id: ThreadId,
588 session_id: SessionId,
589 message: String,
590 },
591
592 AgentSpawned {
594 thread_id: ThreadId,
595 session_id: SessionId,
596 owner_session_id: String,
597 id: String,
598 prompt: String,
599 #[serde(default, skip_serializing_if = "Option::is_none")]
600 worker_status: Option<String>,
601 #[serde(default, skip_serializing_if = "Option::is_none")]
602 parent_run_id: Option<String>,
603 spawn_depth: u32,
604 model: String,
605 #[serde(default, skip_serializing_if = "Option::is_none")]
606 route_source: Option<String>,
607 #[serde(default, skip_serializing_if = "Option::is_none")]
610 display_name: Option<String>,
611 },
612 AgentProgress {
613 thread_id: ThreadId,
614 session_id: SessionId,
615 owner_session_id: String,
616 id: String,
617 status: String,
618 activity: AgentProgressActivity,
619 #[serde(default, skip_serializing_if = "Option::is_none")]
620 parent_run_id: Option<String>,
621 spawn_depth: u32,
622 },
623 AgentComplete {
624 thread_id: ThreadId,
625 session_id: SessionId,
626 owner_session_id: String,
627 id: String,
628 result: String,
629 #[serde(default, skip_serializing_if = "Option::is_none")]
630 worker_status: Option<String>,
631 #[serde(default, skip_serializing_if = "Option::is_none")]
632 parent_run_id: Option<String>,
633 #[serde(default, skip_serializing_if = "Option::is_none")]
634 spawn_depth: Option<u32>,
635 #[serde(default, skip_serializing_if = "Option::is_none")]
636 continuable: Option<bool>,
637 #[serde(default, skip_serializing_if = "Option::is_none")]
638 display_name: Option<String>,
639 },
640 SubAgentFollowUp {
641 thread_id: ThreadId,
642 session_id: SessionId,
643 owner_session_id: String,
644 agent_id: String,
645 outcome: SubAgentFollowUpOutcome,
646 },
647 AgentList {
650 thread_id: ThreadId,
651 session_id: SessionId,
652 owner_session_id: String,
653 agents: Vec<Value>,
654 coordination: Value,
655 #[serde(default)]
657 queued_follow_ups: BTreeMap<String, u64>,
658 roster: Vec<AgentRosterRow>,
659 },
660 SubAgentMailbox {
663 thread_id: ThreadId,
664 session_id: SessionId,
665 owner_session_id: String,
666 turn_id: String,
667 seq: u64,
668 message: Value,
669 },
670 WorkflowUi {
674 thread_id: ThreadId,
675 session_id: SessionId,
676 owner_session_id: String,
677 run_id: String,
678 ui_event: Value,
679 },
680
681 Error {
683 thread_id: ThreadId,
684 session_id: SessionId,
685 category: String,
687 severity: String,
689 recoverable: bool,
690 code: String,
691 message: String,
692 },
693 Status {
694 thread_id: ThreadId,
695 session_id: SessionId,
696 message: String,
697 },
698 McpSessionBoot {
699 thread_id: ThreadId,
700 session_id: SessionId,
701 generation: u64,
702 snapshot: McpManagerSnapshot,
703 connecting: Vec<String>,
704 finished: bool,
705 },
706 RequestManifestReady {
708 thread_id: ThreadId,
709 session_id: SessionId,
710 rendered: String,
711 },
712 PauseEvents {
715 thread_id: ThreadId,
716 session_id: SessionId,
717 },
718 ResumeEvents {
719 thread_id: ThreadId,
720 session_id: SessionId,
721 },
722 ApprovalRequired {
723 thread_id: ThreadId,
724 session_id: SessionId,
725 id: String,
726 tool_name: String,
727 description: String,
728 input: Value,
729 approval_key: String,
730 approval_grouping_key: String,
731 #[serde(default, skip_serializing_if = "Option::is_none")]
732 intent_summary: Option<String>,
733 approval_force_prompt: bool,
734 },
735 ApprovalWithdrawn {
736 thread_id: ThreadId,
737 session_id: SessionId,
738 id: String,
739 },
740 UserInputRequired {
741 thread_id: ThreadId,
742 session_id: SessionId,
743 id: String,
744 request: UserInputRequest,
745 },
746 SessionUpdated {
749 thread_id: ThreadId,
750 session_id: SessionId,
751 engine_session_id: String,
752 messages: Vec<Value>,
753 #[serde(default, skip_serializing_if = "Option::is_none")]
754 system_prompt: Option<Value>,
755 model: String,
756 workspace: PathBuf,
757 },
758 ElevationRequired {
759 thread_id: ThreadId,
760 session_id: SessionId,
761 tool_id: String,
762 tool_name: String,
763 #[serde(default, skip_serializing_if = "Option::is_none")]
764 command: Option<String>,
765 denial_reason: String,
766 blocked_network: bool,
767 blocked_write: bool,
768 },
769 LspRepairUpdate {
770 thread_id: ThreadId,
771 session_id: SessionId,
772 diagnostics_found: u64,
773 files: u64,
774 injected: bool,
775 },
776 ToolGateDecision {
777 thread_id: ThreadId,
778 session_id: SessionId,
779 #[serde(default, skip_serializing_if = "Option::is_none")]
780 agent_id: Option<String>,
781 tool_id: String,
782 tool_name: String,
783 gate: ToolGate,
784 decision: ToolGateVerdict,
785 #[serde(default, skip_serializing_if = "Option::is_none")]
786 risk: Option<String>,
787 reason: String,
788 },
789 AdvisoryNote {
790 thread_id: ThreadId,
791 session_id: SessionId,
792 turn_id: String,
793 note: String,
794 tool_call_count: u32,
795 },
796
797 PrefixCacheChange {
799 thread_id: ThreadId,
800 session_id: SessionId,
801 description: String,
802 system_prompt_changed: bool,
803 tools_changed: bool,
804 stability_pct: u32,
805 changed: bool,
806 pinned_combined_hash: String,
807 pin_reason: String,
808 last_miss_reason: String,
809 context_updates: u64,
810 },
811}
812
813#[derive(Debug, Clone, Serialize, Deserialize)]
817pub struct EventEnvelope {
818 pub seq: u64,
819 pub thread_id: ThreadId,
820 pub session_id: SessionId,
821 pub turn_id: Option<String>,
822 pub event: EventMsg,
823}
824
825pub const EVENT_KINDS: &[&str] = &[
829 "tool_projection_warning",
830 "request_image_window",
831 "message_started",
832 "response_delta",
833 "message_complete",
834 "thinking_started",
835 "thinking_complete",
836 "tool_call_started",
837 "tool_call_heartbeat",
838 "tool_call_complete",
839 "operation_activity_started",
840 "operation_activity_completed",
841 "turn_started",
842 "tool_request_snapshot",
843 "workspace_snapshot_taken",
844 "route_dispatched",
845 "turn_complete",
846 "turn_usage",
847 "routed_turn_usage",
848 "goal_updated",
849 "goal_continuation_waiting",
850 "goal_continuation_wait_ended",
851 "compaction_started",
852 "compaction_completed",
853 "compaction_cancelled",
854 "compaction_failed",
855 "purge_started",
856 "purge_completed",
857 "purge_failed",
858 "agent_spawned",
859 "agent_progress",
860 "agent_complete",
861 "sub_agent_follow_up",
862 "agent_list",
863 "sub_agent_mailbox",
864 "workflow_ui",
865 "error",
866 "status",
867 "mcp_session_boot",
868 "request_manifest_ready",
869 "pause_events",
870 "resume_events",
871 "approval_required",
872 "approval_withdrawn",
873 "user_input_required",
874 "session_updated",
875 "elevation_required",
876 "lsp_repair_update",
877 "tool_gate_decision",
878 "advisory_note",
879 "prefix_cache_change",
880];
881
882impl EventMsg {
883 #[must_use]
884 pub fn kind_str(&self) -> &'static str {
885 match self {
886 Self::ToolProjectionWarning { .. } => "tool_projection_warning",
887 Self::RequestImageWindow { .. } => "request_image_window",
888 Self::SnapshotsDisabled { .. } => "snapshots_disabled",
889 Self::MessageStarted { .. } => "message_started",
890 Self::ResponseDelta { .. } => "response_delta",
891 Self::MessageComplete { .. } => "message_complete",
892 Self::ThinkingStarted { .. } => "thinking_started",
893 Self::ThinkingComplete { .. } => "thinking_complete",
894 Self::ToolCallStarted { .. } => "tool_call_started",
895 Self::ToolCallHeartbeat { .. } => "tool_call_heartbeat",
896 Self::ToolExecutionStarted { .. } => "tool_execution_started",
897 Self::ToolResultContent { .. } => "tool_result_content",
898 Self::ToolCallComplete { .. } => "tool_call_complete",
899 Self::OperationActivityStarted { .. } => "operation_activity_started",
900 Self::OperationActivityCompleted { .. } => "operation_activity_completed",
901 Self::TurnStarted { .. } => "turn_started",
902 Self::ToolRequestSnapshot { .. } => "tool_request_snapshot",
903 Self::WorkspaceSnapshotTaken { .. } => "workspace_snapshot_taken",
904 Self::RouteDispatched { .. } => "route_dispatched",
905 Self::TurnComplete { .. } => "turn_complete",
906 Self::ProviderRequestReceipt { .. } => "provider_request_receipt",
907 Self::TurnUsage { .. } => "turn_usage",
908 Self::RoutedTurnUsage { .. } => "routed_turn_usage",
909 Self::GoalUpdated { .. } => "goal_updated",
910 Self::GoalContinuationWaiting { .. } => "goal_continuation_waiting",
911 Self::GoalContinuationWaitEnded { .. } => "goal_continuation_wait_ended",
912 Self::CompactionStarted { .. } => "compaction_started",
913 Self::CompactionCompleted { .. } => "compaction_completed",
914 Self::CompactionCancelled { .. } => "compaction_cancelled",
915 Self::CompactionFailed { .. } => "compaction_failed",
916 Self::PurgeStarted { .. } => "purge_started",
917 Self::PurgeCompleted { .. } => "purge_completed",
918 Self::PurgeFailed { .. } => "purge_failed",
919 Self::AgentSpawned { .. } => "agent_spawned",
920 Self::AgentProgress { .. } => "agent_progress",
921 Self::AgentComplete { .. } => "agent_complete",
922 Self::SubAgentFollowUp { .. } => "sub_agent_follow_up",
923 Self::AgentList { .. } => "agent_list",
924 Self::SubAgentMailbox { .. } => "sub_agent_mailbox",
925 Self::WorkflowUi { .. } => "workflow_ui",
926 Self::Error { .. } => "error",
927 Self::Status { .. } => "status",
928 Self::McpSessionBoot { .. } => "mcp_session_boot",
929 Self::RequestManifestReady { .. } => "request_manifest_ready",
930 Self::PauseEvents { .. } => "pause_events",
931 Self::ResumeEvents { .. } => "resume_events",
932 Self::ApprovalRequired { .. } => "approval_required",
933 Self::ApprovalWithdrawn { .. } => "approval_withdrawn",
934 Self::UserInputRequired { .. } => "user_input_required",
935 Self::SessionUpdated { .. } => "session_updated",
936 Self::ElevationRequired { .. } => "elevation_required",
937 Self::LspRepairUpdate { .. } => "lsp_repair_update",
938 Self::ToolGateDecision { .. } => "tool_gate_decision",
939 Self::AdvisoryNote { .. } => "advisory_note",
940 Self::PrefixCacheChange { .. } => "prefix_cache_change",
941 }
942 }
943
944 #[must_use]
945 pub fn thread_id(&self) -> &ThreadId {
946 match self {
947 Self::ToolProjectionWarning { thread_id, .. }
948 | Self::RequestImageWindow { thread_id, .. }
949 | Self::SnapshotsDisabled { thread_id, .. }
950 | Self::MessageStarted { thread_id, .. }
951 | Self::ResponseDelta { thread_id, .. }
952 | Self::MessageComplete { thread_id, .. }
953 | Self::ThinkingStarted { thread_id, .. }
954 | Self::ThinkingComplete { thread_id, .. }
955 | Self::ToolCallStarted { thread_id, .. }
956 | Self::ToolCallHeartbeat { thread_id, .. }
957 | Self::ToolExecutionStarted { thread_id, .. }
958 | Self::ToolResultContent { thread_id, .. }
959 | Self::ToolCallComplete { thread_id, .. }
960 | Self::OperationActivityStarted { thread_id, .. }
961 | Self::OperationActivityCompleted { thread_id, .. }
962 | Self::TurnStarted { thread_id, .. }
963 | Self::ToolRequestSnapshot { thread_id, .. }
964 | Self::WorkspaceSnapshotTaken { thread_id, .. }
965 | Self::RouteDispatched { thread_id, .. }
966 | Self::TurnComplete { thread_id, .. }
967 | Self::ProviderRequestReceipt { thread_id, .. }
968 | Self::TurnUsage { thread_id, .. }
969 | Self::RoutedTurnUsage { thread_id, .. }
970 | Self::GoalUpdated { thread_id, .. }
971 | Self::GoalContinuationWaiting { thread_id, .. }
972 | Self::GoalContinuationWaitEnded { thread_id, .. }
973 | Self::CompactionStarted { thread_id, .. }
974 | Self::CompactionCompleted { thread_id, .. }
975 | Self::CompactionCancelled { thread_id, .. }
976 | Self::CompactionFailed { thread_id, .. }
977 | Self::PurgeStarted { thread_id, .. }
978 | Self::PurgeCompleted { thread_id, .. }
979 | Self::PurgeFailed { thread_id, .. }
980 | Self::AgentSpawned { thread_id, .. }
981 | Self::AgentProgress { thread_id, .. }
982 | Self::AgentComplete { thread_id, .. }
983 | Self::SubAgentFollowUp { thread_id, .. }
984 | Self::AgentList { thread_id, .. }
985 | Self::SubAgentMailbox { thread_id, .. }
986 | Self::WorkflowUi { thread_id, .. }
987 | Self::Error { thread_id, .. }
988 | Self::Status { thread_id, .. }
989 | Self::McpSessionBoot { thread_id, .. }
990 | Self::RequestManifestReady { thread_id, .. }
991 | Self::PauseEvents { thread_id, .. }
992 | Self::ResumeEvents { thread_id, .. }
993 | Self::ApprovalRequired { thread_id, .. }
994 | Self::ApprovalWithdrawn { thread_id, .. }
995 | Self::UserInputRequired { thread_id, .. }
996 | Self::SessionUpdated { thread_id, .. }
997 | Self::ElevationRequired { thread_id, .. }
998 | Self::LspRepairUpdate { thread_id, .. }
999 | Self::ToolGateDecision { thread_id, .. }
1000 | Self::AdvisoryNote { thread_id, .. }
1001 | Self::PrefixCacheChange { thread_id, .. } => thread_id,
1002 }
1003 }
1004
1005 #[must_use]
1006 pub fn session_id(&self) -> &SessionId {
1007 match self {
1008 Self::ToolProjectionWarning { session_id, .. }
1009 | Self::RequestImageWindow { session_id, .. }
1010 | Self::SnapshotsDisabled { session_id, .. }
1011 | Self::MessageStarted { session_id, .. }
1012 | Self::ResponseDelta { session_id, .. }
1013 | Self::MessageComplete { session_id, .. }
1014 | Self::ThinkingStarted { session_id, .. }
1015 | Self::ThinkingComplete { session_id, .. }
1016 | Self::ToolCallStarted { session_id, .. }
1017 | Self::ToolCallHeartbeat { session_id, .. }
1018 | Self::ToolExecutionStarted { session_id, .. }
1019 | Self::ToolResultContent { session_id, .. }
1020 | Self::ToolCallComplete { session_id, .. }
1021 | Self::OperationActivityStarted { session_id, .. }
1022 | Self::OperationActivityCompleted { session_id, .. }
1023 | Self::TurnStarted { session_id, .. }
1024 | Self::ToolRequestSnapshot { session_id, .. }
1025 | Self::WorkspaceSnapshotTaken { session_id, .. }
1026 | Self::RouteDispatched { session_id, .. }
1027 | Self::TurnComplete { session_id, .. }
1028 | Self::ProviderRequestReceipt { session_id, .. }
1029 | Self::TurnUsage { session_id, .. }
1030 | Self::RoutedTurnUsage { session_id, .. }
1031 | Self::GoalUpdated { session_id, .. }
1032 | Self::GoalContinuationWaiting { session_id, .. }
1033 | Self::GoalContinuationWaitEnded { session_id, .. }
1034 | Self::CompactionStarted { session_id, .. }
1035 | Self::CompactionCompleted { session_id, .. }
1036 | Self::CompactionCancelled { session_id, .. }
1037 | Self::CompactionFailed { session_id, .. }
1038 | Self::PurgeStarted { session_id, .. }
1039 | Self::PurgeCompleted { session_id, .. }
1040 | Self::PurgeFailed { session_id, .. }
1041 | Self::AgentSpawned { session_id, .. }
1042 | Self::AgentProgress { session_id, .. }
1043 | Self::AgentComplete { session_id, .. }
1044 | Self::SubAgentFollowUp { session_id, .. }
1045 | Self::AgentList { session_id, .. }
1046 | Self::SubAgentMailbox { session_id, .. }
1047 | Self::WorkflowUi { session_id, .. }
1048 | Self::Error { session_id, .. }
1049 | Self::Status { session_id, .. }
1050 | Self::McpSessionBoot { session_id, .. }
1051 | Self::RequestManifestReady { session_id, .. }
1052 | Self::PauseEvents { session_id, .. }
1053 | Self::ResumeEvents { session_id, .. }
1054 | Self::ApprovalRequired { session_id, .. }
1055 | Self::ApprovalWithdrawn { session_id, .. }
1056 | Self::UserInputRequired { session_id, .. }
1057 | Self::SessionUpdated { session_id, .. }
1058 | Self::ElevationRequired { session_id, .. }
1059 | Self::LspRepairUpdate { session_id, .. }
1060 | Self::ToolGateDecision { session_id, .. }
1061 | Self::AdvisoryNote { session_id, .. }
1062 | Self::PrefixCacheChange { session_id, .. } => session_id,
1063 }
1064 }
1065}
1066
1067#[cfg(test)]
1068mod tests {
1069 use super::*;
1070 use serde_json::json;
1071
1072 fn ids() -> (ThreadId, SessionId) {
1073 (ThreadId::new(), SessionId::new())
1074 }
1075
1076 fn every_variant() -> Vec<EventMsg> {
1079 let (t, s) = ids();
1080 let usage = TokenUsage {
1081 input_tokens: 1,
1082 output_tokens: 2,
1083 ..TokenUsage::default()
1084 };
1085 let route = TurnRoute {
1086 provider: "deepseek".into(),
1087 provider_identity: "deepseek".into(),
1088 model: "deepseek-chat".into(),
1089 auto_model: false,
1090 receipt: Some(TurnRouteReceipt {
1091 provider: "deepseek".into(),
1092 provider_identity: "deepseek".into(),
1093 wire_model: "deepseek-chat".into(),
1094 endpoint_identity: "api.deepseek.com".into(),
1095 credential_generation_present: true,
1096 }),
1097 billing: Some(RouteBillingEnvelope {
1098 openrouter_vendor: None,
1099 billing_surface: None,
1100 endpoint_fingerprint: Some("fp".into()),
1101 provider_live_pricing: None,
1102 billing_mode: "metered".into(),
1103 dispatched_at: DateTime::<Utc>::from_timestamp(0, 0).unwrap(),
1104 }),
1105 base_url: "https://api.deepseek.com".into(),
1106 billing_product: RouteProduct::Subscription {
1107 label: "pro".into(),
1108 },
1109 };
1110 vec![
1111 EventMsg::ToolProjectionWarning {
1112 thread_id: t.clone(),
1113 session_id: s.clone(),
1114 provider: "openai".into(),
1115 omitted_tool_names: vec!["a".into()],
1116 omitted_tool_count: 3,
1117 },
1118 EventMsg::RequestImageWindow {
1119 thread_id: t.clone(),
1120 session_id: s.clone(),
1121 provider: "vllm".into(),
1122 model: "m".into(),
1123 total: 6,
1124 elided: 3,
1125 cap: 3,
1126 cap_source: "provider_rejection".into(),
1127 message: "m".into(),
1128 },
1129 EventMsg::MessageStarted {
1130 thread_id: t.clone(),
1131 session_id: s.clone(),
1132 index: 0,
1133 },
1134 EventMsg::ResponseDelta {
1135 thread_id: t.clone(),
1136 session_id: s.clone(),
1137 index: 0,
1138 delta: "hi".into(),
1139 channel: ResponseChannel::Reasoning,
1140 },
1141 EventMsg::MessageComplete {
1142 thread_id: t.clone(),
1143 session_id: s.clone(),
1144 index: 0,
1145 },
1146 EventMsg::ThinkingStarted {
1147 thread_id: t.clone(),
1148 session_id: s.clone(),
1149 index: 1,
1150 },
1151 EventMsg::ThinkingComplete {
1152 thread_id: t.clone(),
1153 session_id: s.clone(),
1154 index: 1,
1155 },
1156 EventMsg::ToolCallStarted {
1157 thread_id: t.clone(),
1158 session_id: s.clone(),
1159 tool_call_id: "c1".into(),
1160 tool_name: "read_file".into(),
1161 input: json!({"path": "x"}),
1162 },
1163 EventMsg::ToolCallHeartbeat {
1164 thread_id: t.clone(),
1165 session_id: s.clone(),
1166 },
1167 EventMsg::ToolCallComplete {
1168 thread_id: t.clone(),
1169 session_id: s.clone(),
1170 tool_call_id: "c1".into(),
1171 tool_name: "read_file".into(),
1172 result: ToolCallOutcome::Err {
1173 error: ToolCallError::Timeout { seconds: 3 },
1174 },
1175 },
1176 EventMsg::OperationActivityStarted {
1177 thread_id: t.clone(),
1178 session_id: s.clone(),
1179 span_id: "span-1".into(),
1180 activity_kind: crate::engine_owner::OwnerActivityKind::Reading,
1181 action_id: Some("read_file".into()),
1182 },
1183 EventMsg::OperationActivityCompleted {
1184 thread_id: t.clone(),
1185 session_id: s.clone(),
1186 span_id: "span-1".into(),
1187 activity_kind: crate::engine_owner::OwnerActivityKind::Reading,
1188 action_id: Some("read_file".into()),
1189 outcome: crate::engine_owner::OwnerOperationOutcome::Succeeded,
1190 },
1191 EventMsg::TurnStarted {
1192 thread_id: t.clone(),
1193 session_id: s.clone(),
1194 turn_id: "turn-1".into(),
1195 created_at: DateTime::<Utc>::from_timestamp(1, 0).unwrap(),
1196 route: Some(route.clone()),
1197 submission_id: None,
1198 },
1199 EventMsg::ToolRequestSnapshot {
1200 thread_id: t.clone(),
1201 session_id: s.clone(),
1202 snapshot: json!({"tool_count": 2}),
1203 },
1204 EventMsg::WorkspaceSnapshotTaken {
1205 thread_id: t.clone(),
1206 session_id: s.clone(),
1207 snapshot: json!({"kind": "pre_turn", "tree_id": "t"}),
1208 },
1209 EventMsg::RouteDispatched {
1210 thread_id: t.clone(),
1211 session_id: s.clone(),
1212 turn_id: "turn-1".into(),
1213 route,
1214 },
1215 EventMsg::TurnComplete {
1216 submission_id: None,
1217 compaction_id: None,
1218 thread_id: t.clone(),
1219 session_id: s.clone(),
1220 turn_id: None,
1221 status: TurnOutcomeStatus::Failed,
1222 error: Some("boom".into()),
1223 usage: usage.clone(),
1224 parent_route_usage: Some(usage.clone()),
1225 routed_usage_dropped_records: 0,
1226 tool_catalog: Some(vec![json!({"name": "read_file"})]),
1227 base_url: None,
1228 },
1229 EventMsg::TurnUsage {
1230 max_output_tokens: None,
1231 thread_id: t.clone(),
1232 session_id: s.clone(),
1233 usage: usage.clone(),
1234 duration_ms: 10,
1235 first_token_ms: Some(2),
1236 request_ms: None,
1237 },
1238 EventMsg::RoutedTurnUsage {
1239 thread_id: t.clone(),
1240 session_id: s.clone(),
1241 usage,
1242 duration_ms: 10,
1243 first_token_ms: Some(2),
1244 request_ms: None,
1245 },
1246 EventMsg::GoalUpdated {
1247 thread_id: t.clone(),
1248 session_id: s.clone(),
1249 snapshot: json!({"status": "active"}),
1250 },
1251 EventMsg::GoalContinuationWaiting {
1252 thread_id: t.clone(),
1253 session_id: s.clone(),
1254 delay_seconds: 5,
1255 },
1256 EventMsg::GoalContinuationWaitEnded {
1257 thread_id: t.clone(),
1258 session_id: s.clone(),
1259 interrupted: true,
1260 },
1261 EventMsg::CompactionStarted {
1262 thread_id: t.clone(),
1263 session_id: s.clone(),
1264 id: "cmp-1".into(),
1265 auto: true,
1266 message: "m".into(),
1267 },
1268 EventMsg::CompactionCompleted {
1269 thread_id: t.clone(),
1270 session_id: s.clone(),
1271 id: "cmp-1".into(),
1272 auto: true,
1273 message: "m".into(),
1274 messages_before: Some(10),
1275 messages_after: Some(2),
1276 summary_prompt: None,
1277 post_input_tokens: Some(100),
1278 },
1279 EventMsg::CompactionCancelled {
1280 thread_id: t.clone(),
1281 session_id: s.clone(),
1282 id: "cmp-1".into(),
1283 auto: false,
1284 message: "m".into(),
1285 },
1286 EventMsg::CompactionFailed {
1287 thread_id: t.clone(),
1288 session_id: s.clone(),
1289 id: "cmp-1".into(),
1290 auto: false,
1291 message: "m".into(),
1292 },
1293 EventMsg::PurgeStarted {
1294 thread_id: t.clone(),
1295 session_id: s.clone(),
1296 message: "m".into(),
1297 },
1298 EventMsg::PurgeCompleted {
1299 thread_id: t.clone(),
1300 session_id: s.clone(),
1301 messages_before: 4,
1302 messages_after: 2,
1303 removed_count: 2,
1304 replaced_count: 0,
1305 message: "m".into(),
1306 },
1307 EventMsg::PurgeFailed {
1308 thread_id: t.clone(),
1309 session_id: s.clone(),
1310 message: "m".into(),
1311 },
1312 EventMsg::AgentSpawned {
1313 thread_id: t.clone(),
1314 session_id: s.clone(),
1315 owner_session_id: "owner".into(),
1316 id: "a1".into(),
1317 prompt: "p".into(),
1318 worker_status: Some("starting".into()),
1319 parent_run_id: None,
1320 spawn_depth: 1,
1321 model: "m".into(),
1322 route_source: Some("task.model".into()),
1323 display_name: Some("audit docs".into()),
1324 },
1325 EventMsg::AgentProgress {
1326 thread_id: t.clone(),
1327 session_id: s.clone(),
1328 owner_session_id: "owner".into(),
1329 id: "a1".into(),
1330 status: "running".into(),
1331 activity: AgentProgressActivity {
1332 worker_status: "running_tool".into(),
1333 step: Some(2),
1334 tool_name: Some("bash".into()),
1335 },
1336 parent_run_id: None,
1337 spawn_depth: 1,
1338 },
1339 EventMsg::AgentComplete {
1340 thread_id: t.clone(),
1341 session_id: s.clone(),
1342 owner_session_id: "owner".into(),
1343 id: "a1".into(),
1344 result: "done".into(),
1345 worker_status: Some("completed".into()),
1346 parent_run_id: None,
1347 spawn_depth: Some(1),
1348 continuable: Some(false),
1349 display_name: Some("audit docs".into()),
1350 },
1351 EventMsg::SubAgentFollowUp {
1352 thread_id: t.clone(),
1353 session_id: s.clone(),
1354 owner_session_id: "owner".into(),
1355 agent_id: "a1".into(),
1356 outcome: SubAgentFollowUpOutcome::Ok {
1357 agent_id: "a1".into(),
1358 target_agent_id: "a2".into(),
1359 delivered: false,
1360 resumed: true,
1361 note: "resumed".into(),
1362 },
1363 },
1364 EventMsg::AgentList {
1365 thread_id: t.clone(),
1366 session_id: s.clone(),
1367 owner_session_id: "owner".into(),
1368 agents: vec![json!({"id": "a1"})],
1369 coordination: json!({}),
1370 queued_follow_ups: BTreeMap::from([("a1".to_string(), 1)]),
1371 roster: vec![AgentRosterRow {
1372 worker_id: "w1".into(),
1373 display_name: "scout".into(),
1374 model: "m".into(),
1375 state: "running".into(),
1376 status: "running".into(),
1377 activity: None,
1378 millis: Some(5),
1379 input_tokens: None,
1380 output_tokens: None,
1381 cost_microusd: None,
1382 steps_taken: 1,
1383 parent_run_id: None,
1384 run_id: "r1".into(),
1385 }],
1386 },
1387 EventMsg::SubAgentMailbox {
1388 thread_id: t.clone(),
1389 session_id: s.clone(),
1390 owner_session_id: "owner".into(),
1391 turn_id: "turn-1".into(),
1392 seq: 7,
1393 message: json!({"kind": "spawned"}),
1394 },
1395 EventMsg::WorkflowUi {
1396 thread_id: t.clone(),
1397 session_id: s.clone(),
1398 owner_session_id: "owner".into(),
1399 run_id: "run-1".into(),
1400 ui_event: json!({"type": "task_started"}),
1401 },
1402 EventMsg::Error {
1403 thread_id: t.clone(),
1404 session_id: s.clone(),
1405 category: "network".into(),
1406 severity: "error".into(),
1407 recoverable: true,
1408 code: "E1".into(),
1409 message: "m".into(),
1410 },
1411 EventMsg::Status {
1412 thread_id: t.clone(),
1413 session_id: s.clone(),
1414 message: "m".into(),
1415 },
1416 EventMsg::McpSessionBoot {
1417 thread_id: t.clone(),
1418 session_id: s.clone(),
1419 generation: 1,
1420 snapshot: McpManagerSnapshot {
1421 config_path: PathBuf::from("/tmp/mcp.json"),
1422 config_exists: true,
1423 reload_required: false,
1424 servers: vec![McpServerSnapshot {
1425 name: "fs".into(),
1426 enabled: true,
1427 required: false,
1428 transport: "stdio".into(),
1429 command_or_url: "npx".into(),
1430 connect_timeout: 1,
1431 execute_timeout: 2,
1432 read_timeout: 3,
1433 connected: true,
1434 error: None,
1435 capability_metadata: "advertised".into(),
1436 tools: vec![McpDiscoveredItem {
1437 name: "read".into(),
1438 model_name: "fs__read".into(),
1439 description: None,
1440 }],
1441 resources: vec![],
1442 prompts: vec![],
1443 }],
1444 },
1445 connecting: vec!["slow".into()],
1446 finished: false,
1447 },
1448 EventMsg::RequestManifestReady {
1449 thread_id: t.clone(),
1450 session_id: s.clone(),
1451 rendered: "manifest".into(),
1452 },
1453 EventMsg::PauseEvents {
1454 thread_id: t.clone(),
1455 session_id: s.clone(),
1456 },
1457 EventMsg::ResumeEvents {
1458 thread_id: t.clone(),
1459 session_id: s.clone(),
1460 },
1461 EventMsg::ApprovalRequired {
1462 thread_id: t.clone(),
1463 session_id: s.clone(),
1464 id: "c1".into(),
1465 tool_name: "bash".into(),
1466 description: "rm".into(),
1467 input: json!({"command": "rm"}),
1468 approval_key: "k".into(),
1469 approval_grouping_key: "g".into(),
1470 intent_summary: None,
1471 approval_force_prompt: true,
1472 },
1473 EventMsg::ApprovalWithdrawn {
1474 thread_id: t.clone(),
1475 session_id: s.clone(),
1476 id: "c1".into(),
1477 },
1478 EventMsg::UserInputRequired {
1479 thread_id: t.clone(),
1480 session_id: s.clone(),
1481 id: "c2".into(),
1482 request: UserInputRequest {
1483 questions: vec![UserInputQuestionEvent {
1484 header: "h".into(),
1485 id: "q1".into(),
1486 question: "?".into(),
1487 options: vec![],
1488 allow_free_text: true,
1489 multi_select: false,
1490 }],
1491 },
1492 },
1493 EventMsg::SessionUpdated {
1494 thread_id: t.clone(),
1495 session_id: s.clone(),
1496 engine_session_id: "sess".into(),
1497 messages: vec![json!({"role": "user", "content": []})],
1498 system_prompt: Some(json!("sys")),
1499 model: "m".into(),
1500 workspace: PathBuf::from("/ws"),
1501 },
1502 EventMsg::ElevationRequired {
1503 thread_id: t.clone(),
1504 session_id: s.clone(),
1505 tool_id: "c3".into(),
1506 tool_name: "bash".into(),
1507 command: Some("curl".into()),
1508 denial_reason: "net".into(),
1509 blocked_network: true,
1510 blocked_write: false,
1511 },
1512 EventMsg::LspRepairUpdate {
1513 thread_id: t.clone(),
1514 session_id: s.clone(),
1515 diagnostics_found: 1,
1516 files: 1,
1517 injected: true,
1518 },
1519 EventMsg::ToolGateDecision {
1520 thread_id: t.clone(),
1521 session_id: s.clone(),
1522 agent_id: None,
1523 tool_id: "c4".into(),
1524 tool_name: "bash".into(),
1525 gate: ToolGate::AutoReviewGuardian,
1526 decision: ToolGateVerdict::Denied,
1527 risk: Some("high".into()),
1528 reason: "no".into(),
1529 },
1530 EventMsg::AdvisoryNote {
1531 thread_id: t.clone(),
1532 session_id: s.clone(),
1533 turn_id: "turn-1".into(),
1534 note: "n".into(),
1535 tool_call_count: 2,
1536 },
1537 EventMsg::PrefixCacheChange {
1538 thread_id: t,
1539 session_id: s,
1540 description: "d".into(),
1541 system_prompt_changed: false,
1542 tools_changed: true,
1543 stability_pct: 90,
1544 changed: true,
1545 pinned_combined_hash: "h".into(),
1546 pin_reason: "initial".into(),
1547 last_miss_reason: String::new(),
1548 context_updates: 0,
1549 },
1550 ]
1551 }
1552
1553 #[test]
1554 fn every_variant_is_listed_once() {
1555 let kinds: Vec<&str> = every_variant().iter().map(EventMsg::kind_str).collect();
1556 assert_eq!(
1557 kinds, EVENT_KINDS,
1558 "EVENT_KINDS must list every variant in order"
1559 );
1560 }
1561
1562 #[test]
1563 fn every_variant_round_trips_and_tags_by_event() {
1564 for msg in every_variant() {
1565 let value = serde_json::to_value(&msg).unwrap();
1566 assert_eq!(value["event"], msg.kind_str(), "{msg:?}");
1567 assert_eq!(value["thread_id"], msg.thread_id().to_string(), "{msg:?}");
1568 assert_eq!(value["session_id"], msg.session_id().to_string(), "{msg:?}");
1569 let back: EventMsg = serde_json::from_value(value).unwrap();
1570 assert_eq!(back, msg);
1571 }
1572 }
1573
1574 #[test]
1575 fn agent_events_from_producers_without_a_display_name_still_load() {
1576 let mut every = every_variant();
1578 every.retain(|msg| {
1579 matches!(
1580 msg,
1581 EventMsg::AgentSpawned { .. } | EventMsg::AgentComplete { .. }
1582 )
1583 });
1584 assert_eq!(every.len(), 2);
1585 for msg in every {
1586 let mut value = serde_json::to_value(&msg).unwrap();
1587 assert_eq!(value["display_name"], "audit docs");
1588 value.as_object_mut().unwrap().remove("display_name");
1589 let back: EventMsg = serde_json::from_value(value.clone()).unwrap();
1590 match &back {
1591 EventMsg::AgentSpawned { display_name, .. }
1592 | EventMsg::AgentComplete { display_name, .. } => assert_eq!(*display_name, None),
1593 other => panic!("unexpected {other:?}"),
1594 }
1595 assert!(
1596 serde_json::to_value(&back)
1597 .unwrap()
1598 .get("display_name")
1599 .is_none()
1600 );
1601 }
1602 }
1603
1604 #[test]
1605 fn event_msg_roundtrip() {
1606 let msg = EventMsg::TurnComplete {
1607 submission_id: None,
1608 compaction_id: None,
1609 thread_id: ThreadId::new(),
1610 session_id: SessionId::new(),
1611 turn_id: Some("turn-1".into()),
1612 status: TurnOutcomeStatus::Completed,
1613 error: None,
1614 usage: TokenUsage::default(),
1615 parent_route_usage: None,
1616 routed_usage_dropped_records: 0,
1617 tool_catalog: None,
1618 base_url: None,
1619 };
1620 let json = serde_json::to_string(&msg).unwrap();
1621 let back: EventMsg = serde_json::from_str(&json).unwrap();
1622 assert_eq!(back.kind_str(), "turn_complete");
1623 assert!(json.contains(r#""status":"completed""#));
1624 }
1625
1626 #[test]
1627 fn turn_complete_ownership_is_additive_and_round_trips() {
1628 for (turn_id, submission_id, compaction_id) in [
1629 (Some("turn-1"), Some("sub-host-1"), None),
1630 (None, Some("sub-rejected"), None),
1631 (Some("autonomous-turn"), None, None),
1632 (None, None, Some("compact-1")),
1633 (None, None, None),
1634 ] {
1635 let msg = EventMsg::TurnComplete {
1636 thread_id: ThreadId::new(),
1637 session_id: SessionId::new(),
1638 turn_id: turn_id.map(str::to_string),
1639 submission_id: submission_id.map(str::to_string),
1640 compaction_id: compaction_id.map(str::to_string),
1641 status: TurnOutcomeStatus::Failed,
1642 error: Some("fixture rejection".into()),
1643 usage: TokenUsage::default(),
1644 parent_route_usage: None,
1645 routed_usage_dropped_records: 0,
1646 tool_catalog: None,
1647 base_url: None,
1648 };
1649 let value = serde_json::to_value(&msg).unwrap();
1650 for (key, expected) in [
1651 ("turn_id", turn_id),
1652 ("submission_id", submission_id),
1653 ("compaction_id", compaction_id),
1654 ] {
1655 if let Some(expected) = expected {
1656 assert_eq!(value[key], expected);
1657 } else {
1658 assert!(value.get(key).is_none(), "{key} must stay absent");
1659 }
1660 }
1661 let back: EventMsg = serde_json::from_value(value).unwrap();
1662 assert_eq!(
1663 back, msg,
1664 "legacy absent fields and owned receipts round-trip"
1665 );
1666 }
1667 }
1668
1669 #[test]
1670 fn text_channel_is_elided_on_the_wire() {
1671 let msg = EventMsg::ResponseDelta {
1672 thread_id: ThreadId::new(),
1673 session_id: SessionId::new(),
1674 index: 0,
1675 delta: "x".into(),
1676 channel: ResponseChannel::Text,
1677 };
1678 let json = serde_json::to_string(&msg).unwrap();
1679 assert!(!json.contains("channel"), "{json}");
1680 let back: EventMsg = serde_json::from_str(&json).unwrap();
1681 assert_eq!(back, msg);
1682 }
1683
1684 #[test]
1688 fn turn_started_submission_id_is_additive_and_default_absent() {
1689 let msg = EventMsg::TurnStarted {
1690 thread_id: ThreadId::new(),
1691 session_id: SessionId::new(),
1692 turn_id: "turn-1".into(),
1693 created_at: DateTime::<Utc>::from_timestamp(1, 0).unwrap(),
1694 route: None,
1695 submission_id: Some("sub-host-1".into()),
1696 };
1697 let json = serde_json::to_string(&msg).unwrap();
1698 assert!(
1699 json.contains(r#""submission_id":"sub-host-1""#),
1700 "a host-stamped token must be serialized: {json}"
1701 );
1702 let back: EventMsg = serde_json::from_str(&json).unwrap();
1703 assert_eq!(back, msg);
1704
1705 let none = EventMsg::TurnStarted {
1706 thread_id: ThreadId::new(),
1707 session_id: SessionId::new(),
1708 turn_id: "turn-2".into(),
1709 created_at: DateTime::<Utc>::from_timestamp(2, 0).unwrap(),
1710 route: None,
1711 submission_id: None,
1712 };
1713 let value = serde_json::to_value(&none).unwrap();
1714 assert!(
1715 value.get("submission_id").is_none(),
1716 "a self-started turn's None token must stay absent on the wire: {value}"
1717 );
1718 let back: EventMsg = serde_json::from_value(value).unwrap();
1720 assert_eq!(back, none);
1721 }
1722}