Skip to main content

codewhale_protocol/
event_msg.rs

1//! `EventMsg`-out API in `crates/protocol` (issue #5261, Phase A1 of the
2//! core/protocol extraction spec).
3//!
4//! Mirrors `crates/engine/src/core/events::Event` variant-by-variant as a
5//! serializable protocol. The TUI's `rx_event` / `Event` channel, the
6//! app-server's SSE stream, and the CLI's `stream-json` output all speak this
7//! one type so headless and TUI observe byte-identical event shapes for the
8//! same `Op`.
9//!
10//! Parity is compile-enforced from the engine side:
11//! `crates/engine/src/core/protocol_parity.rs` matches every engine `Event`
12//! variant exhaustively into an `EventMsg` (`protocol_covers_engine_events`).
13//! Adding an engine variant without a twin here fails to compile.
14//!
15//! Payload fidelity rules for this phase:
16//!
17//! - Scalars, ids, lifecycle enums, route/billing receipts, tool outcomes,
18//!   MCP snapshots, approvals, and gate decisions are typed here.
19//! - Deep domain payloads whose canonical serde type still lives above this
20//!   crate (goal snapshots, sub-agent results, coordination projections,
21//!   mailbox messages, transcript messages, tool catalogs, tool inspection
22//!   snapshots, workflow UI events) cross as `serde_json::Value` produced by
23//!   that type's own `Serialize`. They are typed in later phases; the variant
24//!   and its field names are already stable.
25//! - Engine-only handles (`oneshot`/`Notify`, `Arc<HookExecutor>`) never
26//!   cross. A variant that carried one is projected without it.
27
28use 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/// Final status for a turn (`TurnComplete.status`).
40#[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/// Token usage reported by a provider for one model call or one whole turn.
60/// Field-for-field twin of the engine's `Usage`; `None` means the provider
61/// did not report the fact, never zero.
62#[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/// Secret-free proof of the base route a turn's client was installed on.
83/// The credential generation digest is redacted by design on the engine side
84/// and never crosses; only its presence does.
85#[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/// Credential/pay-mode product truth captured at the client-freeze boundary.
95#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
96#[serde(tag = "kind", rename_all = "snake_case")]
97pub enum RouteProduct {
98    /// No product fact was captured. Not a licence to guess.
99    Unproven,
100    /// Subscription-backed with this user-facing quota label.
101    Subscription { label: String },
102    /// Bills per token.
103    Metered,
104}
105
106/// Billing evidence captured at application admission before the provider permit.
107/// This does not attest network delivery. Absent before admission.
108#[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    /// Validated frozen provider-live quote serialized by the runtime owner.
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub provider_live_pricing: Option<Value>,
119    /// `RouteBillingMode` in snake_case.
120    pub billing_mode: String,
121    pub dispatched_at: DateTime<Utc>,
122}
123
124/// Provider/model route resolved for a model-backed turn.
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct TurnRoute {
127    /// `ProviderKind` key (`deepseek`, `openai`, `custom`, ...).
128    pub provider: String,
129    /// Exact non-secret configured route key.
130    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    /// Endpoint the client was frozen against, verbatim. Empty when unknown.
138    pub base_url: String,
139    pub billing_product: RouteProduct,
140}
141
142/// Structured error surfaced by a tool execution.
143#[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/// Outcome of a tool call: the engine's `Result<ToolResult, ToolError>`.
157#[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/// Lifecycle metadata paired with a human-readable `AgentProgress` message.
172#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
173pub struct AgentProgressActivity {
174    /// `AgentWorkerStatus` in snake_case.
175    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/// Receipt for an operator follow-up to a child agent.
183#[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/// One row of the receipts-only agent roster.
199#[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    /// Coarse rail state:
205    /// `running | waiting | parked | done | failed | cancelled`.
206    pub state: String,
207    /// `AgentWorkerStatus` in snake_case.
208    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/// One discovered MCP tool / resource / prompt.
226#[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/// One configured MCP server as seen by the engine-owned pool.
235#[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    /// `advertised | legacy_fallback | not_observed`.
249    pub capability_metadata: String,
250    pub tools: Vec<McpDiscoveredItem>,
251    pub resources: Vec<McpDiscoveredItem>,
252    pub prompts: Vec<McpDiscoveredItem>,
253}
254
255/// Engine-owned MCP pool snapshot.
256#[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/// Structured clarification request (`request_user_input`).
265#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
266pub struct UserInputRequest {
267    #[serde(default)]
268    pub require_typed_answers: bool,
269    pub questions: Vec<UserInputQuestionEvent>,
270}
271
272#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
273#[serde(rename_all = "snake_case")]
274pub enum UserInputClosedOutcome {
275    Answered,
276    Cancelled,
277    TimedOut,
278    Unavailable,
279}
280
281/// Which permission gate produced a `ToolGateDecision`.
282#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
283#[serde(rename_all = "snake_case")]
284pub enum ToolGate {
285    AutoReviewDeterministic,
286    AutoReviewGuardian,
287}
288
289/// What a permission gate decided for one proposed tool call.
290#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
291#[serde(rename_all = "snake_case")]
292pub enum ToolGateVerdict {
293    Allowed,
294    Denied,
295    Unavailable,
296}
297
298/// One event emitted by the core engine to every consumer (TUI, CLI,
299/// app-server, tests). This is the `EventMsg`-out half of the `Op`-in /
300/// `EventMsg`-out contract: a projection of every internal engine `Event`
301/// variant plus the thread/session ids that route it.
302#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
303#[serde(tag = "event", rename_all = "snake_case")]
304pub enum EventMsg {
305    /// A route compatibility check omitted tools from the provider request.
306    ToolProjectionWarning {
307        thread_id: ThreadId,
308        session_id: SessionId,
309        provider: String,
310        omitted_tool_names: Vec<String>,
311        omitted_tool_count: u64,
312    },
313
314    RequestImageWindow {
315        thread_id: ThreadId,
316        session_id: SessionId,
317        provider: String,
318        model: String,
319        total: u64,
320        elided: u64,
321        cap: u64,
322        cap_source: String,
323        message: String,
324    },
325
326    /// Workspace snapshots (undo) are off for this workspace. `reason` is one
327    /// rendered, localized line: the consequence, the gate that refused, and
328    /// the recovery that actually lifts *that* gate (the size cap's config key
329    /// appears only for the size gate).
330    SnapshotsDisabled {
331        thread_id: ThreadId,
332        session_id: SessionId,
333        workspace: String,
334        reason: String,
335    },
336
337    // === Streaming ===
338    MessageStarted {
339        thread_id: ThreadId,
340        session_id: SessionId,
341        index: u64,
342    },
343    /// Incremental content delta on the `text` (message) or `reasoning`
344    /// (thinking) channel.
345    ResponseDelta {
346        thread_id: ThreadId,
347        session_id: SessionId,
348        index: u64,
349        delta: String,
350        #[serde(default, skip_serializing_if = "ResponseChannel::is_text")]
351        channel: ResponseChannel,
352    },
353    MessageComplete {
354        thread_id: ThreadId,
355        session_id: SessionId,
356        index: u64,
357    },
358    ThinkingStarted {
359        thread_id: ThreadId,
360        session_id: SessionId,
361        index: u64,
362    },
363    ThinkingComplete {
364        thread_id: ThreadId,
365        session_id: SessionId,
366        index: u64,
367    },
368
369    // === Tools ===
370    ToolCallStarted {
371        thread_id: ThreadId,
372        session_id: SessionId,
373        tool_call_id: String,
374        tool_name: String,
375        input: Value,
376    },
377    /// Liveness pulse while a tool future remains pending. Carries no output.
378    ToolCallHeartbeat {
379        thread_id: ThreadId,
380        session_id: SessionId,
381    },
382    ToolExecutionStarted {
383        thread_id: ThreadId,
384        session_id: SessionId,
385        tool_call_id: String,
386    },
387    ToolResultContent {
388        thread_id: ThreadId,
389        session_id: SessionId,
390        tool_call_id: String,
391        blocks: Value,
392    },
393    ToolCallComplete {
394        thread_id: ThreadId,
395        session_id: SessionId,
396        tool_call_id: String,
397        tool_name: String,
398        result: ToolCallOutcome,
399    },
400    /// Trusted Engine-owned activity for an operation that passed dispatch
401    /// and authority checks. No arguments, command, or result is
402    /// included in the pet-facing activity contract.
403    OperationActivityStarted {
404        thread_id: ThreadId,
405        session_id: SessionId,
406        span_id: String,
407        activity_kind: crate::engine_owner::OwnerActivityKind,
408        #[serde(default, skip_serializing_if = "Option::is_none")]
409        action_id: Option<String>,
410    },
411    OperationActivityCompleted {
412        thread_id: ThreadId,
413        session_id: SessionId,
414        span_id: String,
415        activity_kind: crate::engine_owner::OwnerActivityKind,
416        outcome: crate::engine_owner::OwnerOperationOutcome,
417        #[serde(default, skip_serializing_if = "Option::is_none")]
418        action_id: Option<String>,
419    },
420
421    // === Turn lifecycle ===
422    TurnStarted {
423        thread_id: ThreadId,
424        session_id: SessionId,
425        turn_id: String,
426        created_at: DateTime<Utc>,
427        #[serde(default, skip_serializing_if = "Option::is_none")]
428        route: Option<TurnRoute>,
429        /// Host submission correlation echo: the token an in-process host
430        /// stamped on its `SendMessage`/`EditLastTurn` op, echoed verbatim by
431        /// that turn's start; `None` for every engine self-started turn.
432        /// Additive and default-absent on the wire. Only in-process engine
433        /// handles can stamp a token — the wire `Op` carries no correlation
434        /// field — so wire submitters only ever observe `None` here.
435        #[serde(default, skip_serializing_if = "Option::is_none")]
436        submission_id: Option<String>,
437    },
438    /// Bounded tool-field projection from a prepared model-client request
439    /// (`ToolInspectionSnapshot` serialized).
440    ToolRequestSnapshot {
441        thread_id: ThreadId,
442        session_id: SessionId,
443        snapshot: Value,
444    },
445    /// A workspace snapshot the engine took for the running turn
446    /// (`WorkspaceSnapshotRef` serialized: `kind`, `snapshot_id`, `tree_id`,
447    /// `session_id`, optional `tool_call_id`, `write_paths` and
448    /// `changed_paths`).
449    WorkspaceSnapshotTaken {
450        thread_id: ThreadId,
451        session_id: SessionId,
452        snapshot: Value,
453    },
454    /// Immutable billing route captured at application admission.
455    RouteDispatched {
456        thread_id: ThreadId,
457        session_id: SessionId,
458        turn_id: String,
459        route: TurnRoute,
460    },
461    TurnComplete {
462        thread_id: ThreadId,
463        session_id: SessionId,
464        /// Actual started turn; absent when a submitted operation fails
465        /// before starting.
466        #[serde(default, skip_serializing_if = "Option::is_none")]
467        turn_id: Option<String>,
468        /// Host submission correlation, including preflight rejection. Runtime
469        /// self-starts do not carry a host token. Older producers default to
470        /// absent.
471        #[serde(default, skip_serializing_if = "Option::is_none")]
472        submission_id: Option<String>,
473        /// Manual compaction operation identity, never the surrounding host
474        /// submission.
475        #[serde(default, skip_serializing_if = "Option::is_none")]
476        compaction_id: Option<String>,
477        status: TurnOutcomeStatus,
478        #[serde(default, skip_serializing_if = "Option::is_none")]
479        error: Option<String>,
480        usage: TokenUsage,
481        /// Parent-route subset; absent in legacy events, whose split is unknown.
482        #[serde(default, skip_serializing_if = "Option::is_none")]
483        parent_route_usage: Option<TokenUsage>,
484        #[serde(default)]
485        routed_usage_dropped_records: u64,
486        /// Tool catalog sent with this turn's model request (`Tool` serialized).
487        #[serde(default, skip_serializing_if = "Option::is_none")]
488        tool_catalog: Option<Vec<Value>>,
489        #[serde(default, skip_serializing_if = "Option::is_none")]
490        base_url: Option<String>,
491    },
492    ProviderRequestReceipt {
493        thread_id: ThreadId,
494        session_id: SessionId,
495        receipt: Value,
496    },
497
498    /// Usage for one model call within the turn.
499    TurnUsage {
500        #[serde(
501            default,
502            rename = "maxOutputTokens",
503            skip_serializing_if = "Option::is_none"
504        )]
505        max_output_tokens: Option<u32>,
506        thread_id: ThreadId,
507        session_id: SessionId,
508        usage: TokenUsage,
509        duration_ms: u64,
510        #[serde(default, skip_serializing_if = "Option::is_none")]
511        first_token_ms: Option<u64>,
512        #[serde(default, skip_serializing_if = "Option::is_none")]
513        request_ms: Option<u64>,
514    },
515
516    /// Child-call telemetry; cost belongs to its own routed receipt.
517    RoutedTurnUsage {
518        thread_id: ThreadId,
519        session_id: SessionId,
520        usage: TokenUsage,
521        duration_ms: u64,
522        #[serde(default, skip_serializing_if = "Option::is_none")]
523        first_token_ms: Option<u64>,
524        #[serde(default, skip_serializing_if = "Option::is_none")]
525        request_ms: Option<u64>,
526    },
527
528    // === Goals ===
529    /// Runtime goal state changed (`GoalSnapshot` serialized).
530    GoalUpdated {
531        thread_id: ThreadId,
532        session_id: SessionId,
533        snapshot: Value,
534    },
535    GoalContinuationWaiting {
536        thread_id: ThreadId,
537        session_id: SessionId,
538        delay_seconds: u64,
539    },
540    GoalContinuationWaitEnded {
541        thread_id: ThreadId,
542        session_id: SessionId,
543        interrupted: bool,
544    },
545
546    // === Compaction / purge ===
547    CompactionStarted {
548        thread_id: ThreadId,
549        session_id: SessionId,
550        id: String,
551        auto: bool,
552        message: String,
553    },
554    CompactionCompleted {
555        thread_id: ThreadId,
556        session_id: SessionId,
557        id: String,
558        auto: bool,
559        message: String,
560        #[serde(default, skip_serializing_if = "Option::is_none")]
561        messages_before: Option<u64>,
562        #[serde(default, skip_serializing_if = "Option::is_none")]
563        messages_after: Option<u64>,
564        #[serde(default, skip_serializing_if = "Option::is_none")]
565        summary_prompt: Option<String>,
566        #[serde(default, skip_serializing_if = "Option::is_none")]
567        post_input_tokens: Option<u64>,
568    },
569    CompactionCancelled {
570        thread_id: ThreadId,
571        session_id: SessionId,
572        id: String,
573        auto: bool,
574        message: String,
575    },
576    CompactionFailed {
577        thread_id: ThreadId,
578        session_id: SessionId,
579        id: String,
580        auto: bool,
581        message: String,
582    },
583    PurgeStarted {
584        thread_id: ThreadId,
585        session_id: SessionId,
586        message: String,
587    },
588    PurgeCompleted {
589        thread_id: ThreadId,
590        session_id: SessionId,
591        messages_before: u64,
592        messages_after: u64,
593        removed_count: u64,
594        replaced_count: u64,
595        message: String,
596    },
597    PurgeFailed {
598        thread_id: ThreadId,
599        session_id: SessionId,
600        message: String,
601    },
602
603    // === Sub-agents ===
604    AgentSpawned {
605        thread_id: ThreadId,
606        session_id: SessionId,
607        owner_session_id: String,
608        id: String,
609        prompt: String,
610        #[serde(default, skip_serializing_if = "Option::is_none")]
611        worker_status: Option<String>,
612        #[serde(default, skip_serializing_if = "Option::is_none")]
613        parent_run_id: Option<String>,
614        spawn_depth: u32,
615        model: String,
616        #[serde(default, skip_serializing_if = "Option::is_none")]
617        route_source: Option<String>,
618        /// The name the agent goes by (workflow task label, dispatch name, or
619        /// role). Absent from older producers; never the raw id.
620        #[serde(default, skip_serializing_if = "Option::is_none")]
621        display_name: Option<String>,
622    },
623    AgentProgress {
624        thread_id: ThreadId,
625        session_id: SessionId,
626        owner_session_id: String,
627        id: String,
628        status: String,
629        activity: AgentProgressActivity,
630        #[serde(default, skip_serializing_if = "Option::is_none")]
631        parent_run_id: Option<String>,
632        spawn_depth: u32,
633    },
634    AgentComplete {
635        thread_id: ThreadId,
636        session_id: SessionId,
637        owner_session_id: String,
638        id: String,
639        result: String,
640        #[serde(default, skip_serializing_if = "Option::is_none")]
641        worker_status: Option<String>,
642        #[serde(default, skip_serializing_if = "Option::is_none")]
643        parent_run_id: Option<String>,
644        #[serde(default, skip_serializing_if = "Option::is_none")]
645        spawn_depth: Option<u32>,
646        #[serde(default, skip_serializing_if = "Option::is_none")]
647        continuable: Option<bool>,
648        #[serde(default, skip_serializing_if = "Option::is_none")]
649        display_name: Option<String>,
650    },
651    SubAgentFollowUp {
652        thread_id: ThreadId,
653        session_id: SessionId,
654        owner_session_id: String,
655        agent_id: String,
656        outcome: SubAgentFollowUpOutcome,
657    },
658    /// Sub-agent listing. `agents` are `SubAgentResult`s and `coordination`
659    /// is the `CoordinationDetailProjection`, both serialized.
660    AgentList {
661        thread_id: ThreadId,
662        session_id: SessionId,
663        owner_session_id: String,
664        agents: Vec<Value>,
665        coordination: Value,
666        /// `agent_id` -> queued follow-up count; only non-zero entries.
667        #[serde(default)]
668        queued_follow_ups: BTreeMap<String, u64>,
669        roster: Vec<AgentRosterRow>,
670    },
671    /// Structured sub-agent mailbox envelope (`MailboxMessage` serialized).
672    /// Deduplicate on `(turn_id, seq)`, never `seq` alone.
673    SubAgentMailbox {
674        thread_id: ThreadId,
675        session_id: SessionId,
676        owner_session_id: String,
677        turn_id: String,
678        seq: u64,
679        message: Value,
680    },
681    /// Live workflow UI event. `ui_event` is the flattened
682    /// `{"type": ..., "at_ms": ..., ...}` object (named `event` on the
683    /// engine side; renamed here because `event` is the wire tag).
684    WorkflowUi {
685        thread_id: ThreadId,
686        session_id: SessionId,
687        owner_session_id: String,
688        run_id: String,
689        ui_event: Value,
690    },
691
692    // === System ===
693    Error {
694        thread_id: ThreadId,
695        session_id: SessionId,
696        /// `ErrorCategory` in snake_case.
697        category: String,
698        /// `ErrorSeverity` in snake_case.
699        severity: String,
700        recoverable: bool,
701        code: String,
702        message: String,
703    },
704    Status {
705        thread_id: ThreadId,
706        session_id: SessionId,
707        message: String,
708    },
709    McpSessionBoot {
710        thread_id: ThreadId,
711        session_id: SessionId,
712        generation: u64,
713        snapshot: McpManagerSnapshot,
714        connecting: Vec<String>,
715        finished: bool,
716    },
717    /// Rendered `/preview-request` manifest.
718    RequestManifestReady {
719        thread_id: ThreadId,
720        session_id: SessionId,
721        rendered: String,
722    },
723    /// Pause terminal input events for an interactive subprocess. The engine's
724    /// in-process acknowledgement handle does not cross the wire.
725    PauseEvents {
726        thread_id: ThreadId,
727        session_id: SessionId,
728    },
729    ResumeEvents {
730        thread_id: ThreadId,
731        session_id: SessionId,
732    },
733    ApprovalRequired {
734        thread_id: ThreadId,
735        session_id: SessionId,
736        id: String,
737        tool_name: String,
738        description: String,
739        input: Value,
740        approval_key: String,
741        approval_grouping_key: String,
742        #[serde(default, skip_serializing_if = "Option::is_none")]
743        intent_summary: Option<String>,
744        approval_force_prompt: bool,
745    },
746    ApprovalWithdrawn {
747        thread_id: ThreadId,
748        session_id: SessionId,
749        id: String,
750    },
751    UserInputRequired {
752        thread_id: ThreadId,
753        session_id: SessionId,
754        id: String,
755        request: UserInputRequest,
756    },
757    UserInputClosed {
758        thread_id: ThreadId,
759        session_id: SessionId,
760        id: String,
761        outcome: UserInputClosedOutcome,
762    },
763    /// Authoritative API conversation state (`Message`s / `SystemPrompt`
764    /// serialized).
765    SessionUpdated {
766        thread_id: ThreadId,
767        session_id: SessionId,
768        engine_session_id: String,
769        messages: Vec<Value>,
770        #[serde(default, skip_serializing_if = "Option::is_none")]
771        system_prompt: Option<Value>,
772        #[serde(default, skip_serializing_if = "Option::is_none")]
773        instruction_assembly: Option<Value>,
774        model: String,
775        workspace: PathBuf,
776    },
777    ElevationRequired {
778        thread_id: ThreadId,
779        session_id: SessionId,
780        tool_id: String,
781        tool_name: String,
782        #[serde(default, skip_serializing_if = "Option::is_none")]
783        command: Option<String>,
784        denial_reason: String,
785        blocked_network: bool,
786        blocked_write: bool,
787    },
788    LspRepairUpdate {
789        thread_id: ThreadId,
790        session_id: SessionId,
791        diagnostics_found: u64,
792        files: u64,
793        injected: bool,
794    },
795    ToolGateDecision {
796        thread_id: ThreadId,
797        session_id: SessionId,
798        #[serde(default, skip_serializing_if = "Option::is_none")]
799        agent_id: Option<String>,
800        tool_id: String,
801        tool_name: String,
802        gate: ToolGate,
803        decision: ToolGateVerdict,
804        #[serde(default, skip_serializing_if = "Option::is_none")]
805        risk: Option<String>,
806        #[serde(default, skip_serializing_if = "Option::is_none")]
807        reviewer_model: Option<String>,
808        reason: String,
809        #[serde(default, skip_serializing_if = "Option::is_none")]
810        rule: Option<String>,
811        #[serde(default, skip_serializing_if = "Option::is_none")]
812        receipt_id: Option<String>,
813        #[serde(default, skip_serializing_if = "Option::is_none")]
814        call_digest: Option<String>,
815        #[serde(default, skip_serializing_if = "Option::is_none")]
816        action_summary: Option<String>,
817    },
818    AutoReviewPaused {
819        thread_id: ThreadId,
820        session_id: SessionId,
821        reason: String,
822        approval_mode: String,
823    },
824    AdvisoryNote {
825        thread_id: ThreadId,
826        session_id: SessionId,
827        turn_id: String,
828        note: String,
829        tool_call_count: u32,
830    },
831
832    // === Prefix cache ===
833    PrefixCacheChange {
834        thread_id: ThreadId,
835        session_id: SessionId,
836        description: String,
837        system_prompt_changed: bool,
838        tools_changed: bool,
839        stability_pct: u32,
840        changed: bool,
841        pinned_combined_hash: String,
842        pin_reason: String,
843        last_miss_reason: String,
844        context_updates: u64,
845    },
846    ConversationTitle {
847        thread_id: ThreadId,
848        session_id: SessionId,
849        title: String,
850    },
851    ContentFilterRefusal {
852        thread_id: ThreadId,
853        session_id: SessionId,
854        reason: String,
855        #[serde(default, skip_serializing_if = "Option::is_none")]
856        refusal: Option<String>,
857    },
858    PluginChanged {
859        thread_id: ThreadId,
860        session_id: SessionId,
861        plugin: String,
862        action: String,
863        #[serde(default, skip_serializing_if = "Option::is_none")]
864        content_hash: Option<String>,
865        #[serde(default, skip_serializing_if = "Option::is_none")]
866        decided_by: Option<String>,
867        #[serde(default, skip_serializing_if = "Vec::is_empty")]
868        services: Vec<String>,
869        #[serde(default, skip_serializing_if = "Vec::is_empty")]
870        tools_added: Vec<String>,
871        #[serde(default, skip_serializing_if = "Vec::is_empty")]
872        tools_removed: Vec<String>,
873    },
874}
875
876/// Envelope that carries an `EventMsg` over the wire / channel with a
877/// monotonic seq so consumers can detect drops. Mirrors the existing
878/// `RuntimeEventEnvelope` but typed to `EventMsg`.
879#[derive(Debug, Clone, Serialize, Deserialize)]
880pub struct EventEnvelope {
881    pub seq: u64,
882    pub thread_id: ThreadId,
883    pub session_id: SessionId,
884    pub turn_id: Option<String>,
885    pub event: EventMsg,
886}
887
888/// Every wire tag `EventMsg` can carry, in declaration order. Kept next to
889/// the enum so a new variant is added here in the same edit; the test below
890/// proves the list and `kind_str` agree.
891pub const EVENT_KINDS: &[&str] = &[
892    "tool_projection_warning",
893    "request_image_window",
894    "message_started",
895    "response_delta",
896    "message_complete",
897    "thinking_started",
898    "thinking_complete",
899    "tool_call_started",
900    "tool_call_heartbeat",
901    "tool_call_complete",
902    "operation_activity_started",
903    "operation_activity_completed",
904    "turn_started",
905    "tool_request_snapshot",
906    "workspace_snapshot_taken",
907    "route_dispatched",
908    "turn_complete",
909    "turn_usage",
910    "routed_turn_usage",
911    "goal_updated",
912    "goal_continuation_waiting",
913    "goal_continuation_wait_ended",
914    "compaction_started",
915    "compaction_completed",
916    "compaction_cancelled",
917    "compaction_failed",
918    "purge_started",
919    "purge_completed",
920    "purge_failed",
921    "agent_spawned",
922    "agent_progress",
923    "agent_complete",
924    "sub_agent_follow_up",
925    "agent_list",
926    "sub_agent_mailbox",
927    "workflow_ui",
928    "error",
929    "status",
930    "mcp_session_boot",
931    "request_manifest_ready",
932    "pause_events",
933    "resume_events",
934    "approval_required",
935    "approval_withdrawn",
936    "user_input_required",
937    "user_input_closed",
938    "session_updated",
939    "elevation_required",
940    "lsp_repair_update",
941    "tool_gate_decision",
942    "auto_review_paused",
943    "advisory_note",
944    "prefix_cache_change",
945    "conversation_title",
946    "content_filter_refusal",
947    "plugin_changed",
948];
949
950impl EventMsg {
951    #[must_use]
952    pub fn kind_str(&self) -> &'static str {
953        match self {
954            Self::ToolProjectionWarning { .. } => "tool_projection_warning",
955            Self::RequestImageWindow { .. } => "request_image_window",
956            Self::SnapshotsDisabled { .. } => "snapshots_disabled",
957            Self::MessageStarted { .. } => "message_started",
958            Self::ResponseDelta { .. } => "response_delta",
959            Self::MessageComplete { .. } => "message_complete",
960            Self::ThinkingStarted { .. } => "thinking_started",
961            Self::ThinkingComplete { .. } => "thinking_complete",
962            Self::ToolCallStarted { .. } => "tool_call_started",
963            Self::ToolCallHeartbeat { .. } => "tool_call_heartbeat",
964            Self::ToolExecutionStarted { .. } => "tool_execution_started",
965            Self::ToolResultContent { .. } => "tool_result_content",
966            Self::ToolCallComplete { .. } => "tool_call_complete",
967            Self::OperationActivityStarted { .. } => "operation_activity_started",
968            Self::OperationActivityCompleted { .. } => "operation_activity_completed",
969            Self::TurnStarted { .. } => "turn_started",
970            Self::ToolRequestSnapshot { .. } => "tool_request_snapshot",
971            Self::WorkspaceSnapshotTaken { .. } => "workspace_snapshot_taken",
972            Self::RouteDispatched { .. } => "route_dispatched",
973            Self::TurnComplete { .. } => "turn_complete",
974            Self::ProviderRequestReceipt { .. } => "provider_request_receipt",
975            Self::TurnUsage { .. } => "turn_usage",
976            Self::RoutedTurnUsage { .. } => "routed_turn_usage",
977            Self::GoalUpdated { .. } => "goal_updated",
978            Self::GoalContinuationWaiting { .. } => "goal_continuation_waiting",
979            Self::GoalContinuationWaitEnded { .. } => "goal_continuation_wait_ended",
980            Self::CompactionStarted { .. } => "compaction_started",
981            Self::CompactionCompleted { .. } => "compaction_completed",
982            Self::CompactionCancelled { .. } => "compaction_cancelled",
983            Self::CompactionFailed { .. } => "compaction_failed",
984            Self::PurgeStarted { .. } => "purge_started",
985            Self::PurgeCompleted { .. } => "purge_completed",
986            Self::PurgeFailed { .. } => "purge_failed",
987            Self::AgentSpawned { .. } => "agent_spawned",
988            Self::AgentProgress { .. } => "agent_progress",
989            Self::AgentComplete { .. } => "agent_complete",
990            Self::SubAgentFollowUp { .. } => "sub_agent_follow_up",
991            Self::AgentList { .. } => "agent_list",
992            Self::SubAgentMailbox { .. } => "sub_agent_mailbox",
993            Self::WorkflowUi { .. } => "workflow_ui",
994            Self::Error { .. } => "error",
995            Self::Status { .. } => "status",
996            Self::McpSessionBoot { .. } => "mcp_session_boot",
997            Self::RequestManifestReady { .. } => "request_manifest_ready",
998            Self::PauseEvents { .. } => "pause_events",
999            Self::ResumeEvents { .. } => "resume_events",
1000            Self::ApprovalRequired { .. } => "approval_required",
1001            Self::ApprovalWithdrawn { .. } => "approval_withdrawn",
1002            Self::UserInputRequired { .. } => "user_input_required",
1003            Self::UserInputClosed { .. } => "user_input_closed",
1004            Self::SessionUpdated { .. } => "session_updated",
1005            Self::ElevationRequired { .. } => "elevation_required",
1006            Self::LspRepairUpdate { .. } => "lsp_repair_update",
1007            Self::ToolGateDecision { .. } => "tool_gate_decision",
1008            Self::AutoReviewPaused { .. } => "auto_review_paused",
1009            Self::AdvisoryNote { .. } => "advisory_note",
1010            Self::PrefixCacheChange { .. } => "prefix_cache_change",
1011            Self::ConversationTitle { .. } => "conversation_title",
1012            Self::ContentFilterRefusal { .. } => "content_filter_refusal",
1013            Self::PluginChanged { .. } => "plugin_changed",
1014        }
1015    }
1016
1017    #[must_use]
1018    pub fn thread_id(&self) -> &ThreadId {
1019        match self {
1020            Self::ToolProjectionWarning { thread_id, .. }
1021            | Self::RequestImageWindow { thread_id, .. }
1022            | Self::SnapshotsDisabled { thread_id, .. }
1023            | Self::MessageStarted { thread_id, .. }
1024            | Self::ResponseDelta { thread_id, .. }
1025            | Self::MessageComplete { thread_id, .. }
1026            | Self::ThinkingStarted { thread_id, .. }
1027            | Self::ThinkingComplete { thread_id, .. }
1028            | Self::ToolCallStarted { thread_id, .. }
1029            | Self::ToolCallHeartbeat { thread_id, .. }
1030            | Self::ToolExecutionStarted { thread_id, .. }
1031            | Self::ToolResultContent { thread_id, .. }
1032            | Self::ToolCallComplete { thread_id, .. }
1033            | Self::OperationActivityStarted { thread_id, .. }
1034            | Self::OperationActivityCompleted { thread_id, .. }
1035            | Self::TurnStarted { thread_id, .. }
1036            | Self::ToolRequestSnapshot { thread_id, .. }
1037            | Self::WorkspaceSnapshotTaken { thread_id, .. }
1038            | Self::RouteDispatched { thread_id, .. }
1039            | Self::TurnComplete { thread_id, .. }
1040            | Self::ProviderRequestReceipt { thread_id, .. }
1041            | Self::TurnUsage { thread_id, .. }
1042            | Self::RoutedTurnUsage { thread_id, .. }
1043            | Self::GoalUpdated { thread_id, .. }
1044            | Self::GoalContinuationWaiting { thread_id, .. }
1045            | Self::GoalContinuationWaitEnded { thread_id, .. }
1046            | Self::CompactionStarted { thread_id, .. }
1047            | Self::CompactionCompleted { thread_id, .. }
1048            | Self::CompactionCancelled { thread_id, .. }
1049            | Self::CompactionFailed { thread_id, .. }
1050            | Self::PurgeStarted { thread_id, .. }
1051            | Self::PurgeCompleted { thread_id, .. }
1052            | Self::PurgeFailed { thread_id, .. }
1053            | Self::AgentSpawned { thread_id, .. }
1054            | Self::AgentProgress { thread_id, .. }
1055            | Self::AgentComplete { thread_id, .. }
1056            | Self::SubAgentFollowUp { thread_id, .. }
1057            | Self::AgentList { thread_id, .. }
1058            | Self::SubAgentMailbox { thread_id, .. }
1059            | Self::WorkflowUi { thread_id, .. }
1060            | Self::Error { thread_id, .. }
1061            | Self::Status { thread_id, .. }
1062            | Self::McpSessionBoot { thread_id, .. }
1063            | Self::RequestManifestReady { thread_id, .. }
1064            | Self::PauseEvents { thread_id, .. }
1065            | Self::ResumeEvents { thread_id, .. }
1066            | Self::ApprovalRequired { thread_id, .. }
1067            | Self::ApprovalWithdrawn { thread_id, .. }
1068            | Self::UserInputRequired { thread_id, .. }
1069            | Self::UserInputClosed { thread_id, .. }
1070            | Self::SessionUpdated { thread_id, .. }
1071            | Self::ElevationRequired { thread_id, .. }
1072            | Self::LspRepairUpdate { thread_id, .. }
1073            | Self::ToolGateDecision { thread_id, .. }
1074            | Self::AutoReviewPaused { thread_id, .. }
1075            | Self::AdvisoryNote { thread_id, .. }
1076            | Self::PrefixCacheChange { thread_id, .. }
1077            | Self::ConversationTitle { thread_id, .. }
1078            | Self::ContentFilterRefusal { thread_id, .. }
1079            | Self::PluginChanged { thread_id, .. } => thread_id,
1080        }
1081    }
1082
1083    #[must_use]
1084    pub fn session_id(&self) -> &SessionId {
1085        match self {
1086            Self::ToolProjectionWarning { session_id, .. }
1087            | Self::RequestImageWindow { session_id, .. }
1088            | Self::SnapshotsDisabled { session_id, .. }
1089            | Self::MessageStarted { session_id, .. }
1090            | Self::ResponseDelta { session_id, .. }
1091            | Self::MessageComplete { session_id, .. }
1092            | Self::ThinkingStarted { session_id, .. }
1093            | Self::ThinkingComplete { session_id, .. }
1094            | Self::ToolCallStarted { session_id, .. }
1095            | Self::ToolCallHeartbeat { session_id, .. }
1096            | Self::ToolExecutionStarted { session_id, .. }
1097            | Self::ToolResultContent { session_id, .. }
1098            | Self::ToolCallComplete { session_id, .. }
1099            | Self::OperationActivityStarted { session_id, .. }
1100            | Self::OperationActivityCompleted { session_id, .. }
1101            | Self::TurnStarted { session_id, .. }
1102            | Self::ToolRequestSnapshot { session_id, .. }
1103            | Self::WorkspaceSnapshotTaken { session_id, .. }
1104            | Self::RouteDispatched { session_id, .. }
1105            | Self::TurnComplete { session_id, .. }
1106            | Self::ProviderRequestReceipt { session_id, .. }
1107            | Self::TurnUsage { session_id, .. }
1108            | Self::RoutedTurnUsage { session_id, .. }
1109            | Self::GoalUpdated { session_id, .. }
1110            | Self::GoalContinuationWaiting { session_id, .. }
1111            | Self::GoalContinuationWaitEnded { session_id, .. }
1112            | Self::CompactionStarted { session_id, .. }
1113            | Self::CompactionCompleted { session_id, .. }
1114            | Self::CompactionCancelled { session_id, .. }
1115            | Self::CompactionFailed { session_id, .. }
1116            | Self::PurgeStarted { session_id, .. }
1117            | Self::PurgeCompleted { session_id, .. }
1118            | Self::PurgeFailed { session_id, .. }
1119            | Self::AgentSpawned { session_id, .. }
1120            | Self::AgentProgress { session_id, .. }
1121            | Self::AgentComplete { session_id, .. }
1122            | Self::SubAgentFollowUp { session_id, .. }
1123            | Self::AgentList { session_id, .. }
1124            | Self::SubAgentMailbox { session_id, .. }
1125            | Self::WorkflowUi { session_id, .. }
1126            | Self::Error { session_id, .. }
1127            | Self::Status { session_id, .. }
1128            | Self::McpSessionBoot { session_id, .. }
1129            | Self::RequestManifestReady { session_id, .. }
1130            | Self::PauseEvents { session_id, .. }
1131            | Self::ResumeEvents { session_id, .. }
1132            | Self::ApprovalRequired { session_id, .. }
1133            | Self::ApprovalWithdrawn { session_id, .. }
1134            | Self::UserInputRequired { session_id, .. }
1135            | Self::UserInputClosed { session_id, .. }
1136            | Self::SessionUpdated { session_id, .. }
1137            | Self::ElevationRequired { session_id, .. }
1138            | Self::LspRepairUpdate { session_id, .. }
1139            | Self::ToolGateDecision { session_id, .. }
1140            | Self::AutoReviewPaused { session_id, .. }
1141            | Self::AdvisoryNote { session_id, .. }
1142            | Self::PrefixCacheChange { session_id, .. }
1143            | Self::ConversationTitle { session_id, .. }
1144            | Self::ContentFilterRefusal { session_id, .. }
1145            | Self::PluginChanged { session_id, .. } => session_id,
1146        }
1147    }
1148}
1149
1150#[cfg(test)]
1151mod tests {
1152    use super::*;
1153    use serde_json::json;
1154
1155    fn ids() -> (ThreadId, SessionId) {
1156        (ThreadId::new(), SessionId::new())
1157    }
1158
1159    /// One instance of every variant, in declaration order. A new variant
1160    /// must be added here too, or `every_variant_is_listed_once` fails.
1161    fn every_variant() -> Vec<EventMsg> {
1162        let (t, s) = ids();
1163        let usage = TokenUsage {
1164            input_tokens: 1,
1165            output_tokens: 2,
1166            ..TokenUsage::default()
1167        };
1168        let route = TurnRoute {
1169            provider: "deepseek".into(),
1170            provider_identity: "deepseek".into(),
1171            model: "deepseek-chat".into(),
1172            auto_model: false,
1173            receipt: Some(TurnRouteReceipt {
1174                provider: "deepseek".into(),
1175                provider_identity: "deepseek".into(),
1176                wire_model: "deepseek-chat".into(),
1177                endpoint_identity: "api.deepseek.com".into(),
1178                credential_generation_present: true,
1179            }),
1180            billing: Some(RouteBillingEnvelope {
1181                openrouter_vendor: None,
1182                billing_surface: None,
1183                endpoint_fingerprint: Some("fp".into()),
1184                provider_live_pricing: None,
1185                billing_mode: "metered".into(),
1186                dispatched_at: DateTime::<Utc>::from_timestamp(0, 0).unwrap(),
1187            }),
1188            base_url: "https://api.deepseek.com".into(),
1189            billing_product: RouteProduct::Subscription {
1190                label: "pro".into(),
1191            },
1192        };
1193        vec![
1194            EventMsg::ToolProjectionWarning {
1195                thread_id: t.clone(),
1196                session_id: s.clone(),
1197                provider: "openai".into(),
1198                omitted_tool_names: vec!["a".into()],
1199                omitted_tool_count: 3,
1200            },
1201            EventMsg::RequestImageWindow {
1202                thread_id: t.clone(),
1203                session_id: s.clone(),
1204                provider: "vllm".into(),
1205                model: "m".into(),
1206                total: 6,
1207                elided: 3,
1208                cap: 3,
1209                cap_source: "provider_rejection".into(),
1210                message: "m".into(),
1211            },
1212            EventMsg::MessageStarted {
1213                thread_id: t.clone(),
1214                session_id: s.clone(),
1215                index: 0,
1216            },
1217            EventMsg::ResponseDelta {
1218                thread_id: t.clone(),
1219                session_id: s.clone(),
1220                index: 0,
1221                delta: "hi".into(),
1222                channel: ResponseChannel::Reasoning,
1223            },
1224            EventMsg::MessageComplete {
1225                thread_id: t.clone(),
1226                session_id: s.clone(),
1227                index: 0,
1228            },
1229            EventMsg::ThinkingStarted {
1230                thread_id: t.clone(),
1231                session_id: s.clone(),
1232                index: 1,
1233            },
1234            EventMsg::ThinkingComplete {
1235                thread_id: t.clone(),
1236                session_id: s.clone(),
1237                index: 1,
1238            },
1239            EventMsg::ToolCallStarted {
1240                thread_id: t.clone(),
1241                session_id: s.clone(),
1242                tool_call_id: "c1".into(),
1243                tool_name: "read_file".into(),
1244                input: json!({"path": "x"}),
1245            },
1246            EventMsg::ToolCallHeartbeat {
1247                thread_id: t.clone(),
1248                session_id: s.clone(),
1249            },
1250            EventMsg::ToolCallComplete {
1251                thread_id: t.clone(),
1252                session_id: s.clone(),
1253                tool_call_id: "c1".into(),
1254                tool_name: "read_file".into(),
1255                result: ToolCallOutcome::Err {
1256                    error: ToolCallError::Timeout { seconds: 3 },
1257                },
1258            },
1259            EventMsg::OperationActivityStarted {
1260                thread_id: t.clone(),
1261                session_id: s.clone(),
1262                span_id: "span-1".into(),
1263                activity_kind: crate::engine_owner::OwnerActivityKind::Reading,
1264                action_id: Some("read_file".into()),
1265            },
1266            EventMsg::OperationActivityCompleted {
1267                thread_id: t.clone(),
1268                session_id: s.clone(),
1269                span_id: "span-1".into(),
1270                activity_kind: crate::engine_owner::OwnerActivityKind::Reading,
1271                action_id: Some("read_file".into()),
1272                outcome: crate::engine_owner::OwnerOperationOutcome::Succeeded,
1273            },
1274            EventMsg::TurnStarted {
1275                thread_id: t.clone(),
1276                session_id: s.clone(),
1277                turn_id: "turn-1".into(),
1278                created_at: DateTime::<Utc>::from_timestamp(1, 0).unwrap(),
1279                route: Some(route.clone()),
1280                submission_id: None,
1281            },
1282            EventMsg::ToolRequestSnapshot {
1283                thread_id: t.clone(),
1284                session_id: s.clone(),
1285                snapshot: json!({"tool_count": 2}),
1286            },
1287            EventMsg::WorkspaceSnapshotTaken {
1288                thread_id: t.clone(),
1289                session_id: s.clone(),
1290                snapshot: json!({"kind": "pre_turn", "tree_id": "t"}),
1291            },
1292            EventMsg::RouteDispatched {
1293                thread_id: t.clone(),
1294                session_id: s.clone(),
1295                turn_id: "turn-1".into(),
1296                route,
1297            },
1298            EventMsg::TurnComplete {
1299                submission_id: None,
1300                compaction_id: None,
1301                thread_id: t.clone(),
1302                session_id: s.clone(),
1303                turn_id: None,
1304                status: TurnOutcomeStatus::Failed,
1305                error: Some("boom".into()),
1306                usage: usage.clone(),
1307                parent_route_usage: Some(usage.clone()),
1308                routed_usage_dropped_records: 0,
1309                tool_catalog: Some(vec![json!({"name": "read_file"})]),
1310                base_url: None,
1311            },
1312            EventMsg::TurnUsage {
1313                max_output_tokens: None,
1314                thread_id: t.clone(),
1315                session_id: s.clone(),
1316                usage: usage.clone(),
1317                duration_ms: 10,
1318                first_token_ms: Some(2),
1319                request_ms: None,
1320            },
1321            EventMsg::RoutedTurnUsage {
1322                thread_id: t.clone(),
1323                session_id: s.clone(),
1324                usage,
1325                duration_ms: 10,
1326                first_token_ms: Some(2),
1327                request_ms: None,
1328            },
1329            EventMsg::GoalUpdated {
1330                thread_id: t.clone(),
1331                session_id: s.clone(),
1332                snapshot: json!({"status": "active"}),
1333            },
1334            EventMsg::GoalContinuationWaiting {
1335                thread_id: t.clone(),
1336                session_id: s.clone(),
1337                delay_seconds: 5,
1338            },
1339            EventMsg::GoalContinuationWaitEnded {
1340                thread_id: t.clone(),
1341                session_id: s.clone(),
1342                interrupted: true,
1343            },
1344            EventMsg::CompactionStarted {
1345                thread_id: t.clone(),
1346                session_id: s.clone(),
1347                id: "cmp-1".into(),
1348                auto: true,
1349                message: "m".into(),
1350            },
1351            EventMsg::CompactionCompleted {
1352                thread_id: t.clone(),
1353                session_id: s.clone(),
1354                id: "cmp-1".into(),
1355                auto: true,
1356                message: "m".into(),
1357                messages_before: Some(10),
1358                messages_after: Some(2),
1359                summary_prompt: None,
1360                post_input_tokens: Some(100),
1361            },
1362            EventMsg::CompactionCancelled {
1363                thread_id: t.clone(),
1364                session_id: s.clone(),
1365                id: "cmp-1".into(),
1366                auto: false,
1367                message: "m".into(),
1368            },
1369            EventMsg::CompactionFailed {
1370                thread_id: t.clone(),
1371                session_id: s.clone(),
1372                id: "cmp-1".into(),
1373                auto: false,
1374                message: "m".into(),
1375            },
1376            EventMsg::PurgeStarted {
1377                thread_id: t.clone(),
1378                session_id: s.clone(),
1379                message: "m".into(),
1380            },
1381            EventMsg::PurgeCompleted {
1382                thread_id: t.clone(),
1383                session_id: s.clone(),
1384                messages_before: 4,
1385                messages_after: 2,
1386                removed_count: 2,
1387                replaced_count: 0,
1388                message: "m".into(),
1389            },
1390            EventMsg::PurgeFailed {
1391                thread_id: t.clone(),
1392                session_id: s.clone(),
1393                message: "m".into(),
1394            },
1395            EventMsg::AgentSpawned {
1396                thread_id: t.clone(),
1397                session_id: s.clone(),
1398                owner_session_id: "owner".into(),
1399                id: "a1".into(),
1400                prompt: "p".into(),
1401                worker_status: Some("starting".into()),
1402                parent_run_id: None,
1403                spawn_depth: 1,
1404                model: "m".into(),
1405                route_source: Some("task.model".into()),
1406                display_name: Some("audit docs".into()),
1407            },
1408            EventMsg::AgentProgress {
1409                thread_id: t.clone(),
1410                session_id: s.clone(),
1411                owner_session_id: "owner".into(),
1412                id: "a1".into(),
1413                status: "running".into(),
1414                activity: AgentProgressActivity {
1415                    worker_status: "running_tool".into(),
1416                    step: Some(2),
1417                    tool_name: Some("bash".into()),
1418                },
1419                parent_run_id: None,
1420                spawn_depth: 1,
1421            },
1422            EventMsg::AgentComplete {
1423                thread_id: t.clone(),
1424                session_id: s.clone(),
1425                owner_session_id: "owner".into(),
1426                id: "a1".into(),
1427                result: "done".into(),
1428                worker_status: Some("completed".into()),
1429                parent_run_id: None,
1430                spawn_depth: Some(1),
1431                continuable: Some(false),
1432                display_name: Some("audit docs".into()),
1433            },
1434            EventMsg::SubAgentFollowUp {
1435                thread_id: t.clone(),
1436                session_id: s.clone(),
1437                owner_session_id: "owner".into(),
1438                agent_id: "a1".into(),
1439                outcome: SubAgentFollowUpOutcome::Ok {
1440                    agent_id: "a1".into(),
1441                    target_agent_id: "a2".into(),
1442                    delivered: false,
1443                    resumed: true,
1444                    note: "resumed".into(),
1445                },
1446            },
1447            EventMsg::AgentList {
1448                thread_id: t.clone(),
1449                session_id: s.clone(),
1450                owner_session_id: "owner".into(),
1451                agents: vec![json!({"id": "a1"})],
1452                coordination: json!({}),
1453                queued_follow_ups: BTreeMap::from([("a1".to_string(), 1)]),
1454                roster: vec![AgentRosterRow {
1455                    worker_id: "w1".into(),
1456                    display_name: "scout".into(),
1457                    model: "m".into(),
1458                    state: "running".into(),
1459                    status: "running".into(),
1460                    activity: None,
1461                    millis: Some(5),
1462                    input_tokens: None,
1463                    output_tokens: None,
1464                    cost_microusd: None,
1465                    steps_taken: 1,
1466                    parent_run_id: None,
1467                    run_id: "r1".into(),
1468                }],
1469            },
1470            EventMsg::SubAgentMailbox {
1471                thread_id: t.clone(),
1472                session_id: s.clone(),
1473                owner_session_id: "owner".into(),
1474                turn_id: "turn-1".into(),
1475                seq: 7,
1476                message: json!({"kind": "spawned"}),
1477            },
1478            EventMsg::WorkflowUi {
1479                thread_id: t.clone(),
1480                session_id: s.clone(),
1481                owner_session_id: "owner".into(),
1482                run_id: "run-1".into(),
1483                ui_event: json!({"type": "task_started"}),
1484            },
1485            EventMsg::Error {
1486                thread_id: t.clone(),
1487                session_id: s.clone(),
1488                category: "network".into(),
1489                severity: "error".into(),
1490                recoverable: true,
1491                code: "E1".into(),
1492                message: "m".into(),
1493            },
1494            EventMsg::Status {
1495                thread_id: t.clone(),
1496                session_id: s.clone(),
1497                message: "m".into(),
1498            },
1499            EventMsg::McpSessionBoot {
1500                thread_id: t.clone(),
1501                session_id: s.clone(),
1502                generation: 1,
1503                snapshot: McpManagerSnapshot {
1504                    config_path: PathBuf::from("/tmp/mcp.json"),
1505                    config_exists: true,
1506                    reload_required: false,
1507                    servers: vec![McpServerSnapshot {
1508                        name: "fs".into(),
1509                        enabled: true,
1510                        required: false,
1511                        transport: "stdio".into(),
1512                        command_or_url: "npx".into(),
1513                        connect_timeout: 1,
1514                        execute_timeout: 2,
1515                        read_timeout: 3,
1516                        connected: true,
1517                        error: None,
1518                        capability_metadata: "advertised".into(),
1519                        tools: vec![McpDiscoveredItem {
1520                            name: "read".into(),
1521                            model_name: "fs__read".into(),
1522                            description: None,
1523                        }],
1524                        resources: vec![],
1525                        prompts: vec![],
1526                    }],
1527                },
1528                connecting: vec!["slow".into()],
1529                finished: false,
1530            },
1531            EventMsg::RequestManifestReady {
1532                thread_id: t.clone(),
1533                session_id: s.clone(),
1534                rendered: "manifest".into(),
1535            },
1536            EventMsg::PauseEvents {
1537                thread_id: t.clone(),
1538                session_id: s.clone(),
1539            },
1540            EventMsg::ResumeEvents {
1541                thread_id: t.clone(),
1542                session_id: s.clone(),
1543            },
1544            EventMsg::ApprovalRequired {
1545                thread_id: t.clone(),
1546                session_id: s.clone(),
1547                id: "c1".into(),
1548                tool_name: "bash".into(),
1549                description: "rm".into(),
1550                input: json!({"command": "rm"}),
1551                approval_key: "k".into(),
1552                approval_grouping_key: "g".into(),
1553                intent_summary: None,
1554                approval_force_prompt: true,
1555            },
1556            EventMsg::ApprovalWithdrawn {
1557                thread_id: t.clone(),
1558                session_id: s.clone(),
1559                id: "c1".into(),
1560            },
1561            EventMsg::UserInputRequired {
1562                thread_id: t.clone(),
1563                session_id: s.clone(),
1564                id: "c2".into(),
1565                request: UserInputRequest {
1566                    require_typed_answers: true,
1567                    questions: vec![UserInputQuestionEvent {
1568                        header: "h".into(),
1569                        id: "q1".into(),
1570                        question: "?".into(),
1571                        detail: Some("Exact detail".into()),
1572                        intent: Some(crate::UserInputIntentEvent::PlanReview {
1573                            approve: "Proceed".into(),
1574                            call_id: Some("plan-1".into()),
1575                        }),
1576                        options: vec![],
1577                        allow_free_text: true,
1578                        multi_select: false,
1579                    }],
1580                },
1581            },
1582            EventMsg::UserInputClosed {
1583                thread_id: t.clone(),
1584                session_id: s.clone(),
1585                id: "c2".into(),
1586                outcome: UserInputClosedOutcome::TimedOut,
1587            },
1588            EventMsg::SessionUpdated {
1589                thread_id: t.clone(),
1590                session_id: s.clone(),
1591                engine_session_id: "sess".into(),
1592                messages: vec![json!({"role": "user", "content": []})],
1593                system_prompt: Some(json!("sys")),
1594                instruction_assembly: None,
1595                model: "m".into(),
1596                workspace: PathBuf::from("/ws"),
1597            },
1598            EventMsg::ElevationRequired {
1599                thread_id: t.clone(),
1600                session_id: s.clone(),
1601                tool_id: "c3".into(),
1602                tool_name: "bash".into(),
1603                command: Some("curl".into()),
1604                denial_reason: "net".into(),
1605                blocked_network: true,
1606                blocked_write: false,
1607            },
1608            EventMsg::LspRepairUpdate {
1609                thread_id: t.clone(),
1610                session_id: s.clone(),
1611                diagnostics_found: 1,
1612                files: 1,
1613                injected: true,
1614            },
1615            EventMsg::ToolGateDecision {
1616                thread_id: t.clone(),
1617                session_id: s.clone(),
1618                agent_id: None,
1619                tool_id: "c4".into(),
1620                tool_name: "bash".into(),
1621                gate: ToolGate::AutoReviewGuardian,
1622                decision: ToolGateVerdict::Denied,
1623                risk: Some("high".into()),
1624                reviewer_model: Some("claude-sonnet-5-5".into()),
1625                reason: "no".into(),
1626                rule: Some("guardian".into()),
1627                receipt_id: Some("ar-1".into()),
1628                call_digest: Some("d1".into()),
1629                action_summary: Some("bash: rm -rf /tmp".into()),
1630            },
1631            EventMsg::AutoReviewPaused {
1632                thread_id: t.clone(),
1633                session_id: s.clone(),
1634                reason: "Auto-Review paused after 3 blocked calls in a row; Shift+Tab or /auto to resume".into(),
1635                approval_mode: "suggest".into(),
1636            },
1637            EventMsg::AdvisoryNote {
1638                thread_id: t.clone(),
1639                session_id: s.clone(),
1640                turn_id: "turn-1".into(),
1641                note: "n".into(),
1642                tool_call_count: 2,
1643            },
1644            EventMsg::PrefixCacheChange {
1645                thread_id: t.clone(),
1646                session_id: s.clone(),
1647                description: "d".into(),
1648                system_prompt_changed: false,
1649                tools_changed: true,
1650                stability_pct: 90,
1651                changed: true,
1652                pinned_combined_hash: "h".into(),
1653                pin_reason: "initial".into(),
1654                last_miss_reason: String::new(),
1655                context_updates: 0,
1656            },
1657            EventMsg::ConversationTitle {
1658                thread_id: t.clone(),
1659                session_id: s.clone(),
1660                title: "Conversation".into(),
1661            },
1662            EventMsg::ContentFilterRefusal {
1663                thread_id: t.clone(),
1664                session_id: s.clone(),
1665                reason: "content_filter".into(),
1666                refusal: Some("Blocked by safety policy".into()),
1667            },
1668            EventMsg::PluginChanged {
1669                thread_id: t,
1670                session_id: s,
1671                plugin: "alpha".into(),
1672                action: "installed".into(),
1673                content_hash: Some("sha256:abc".into()),
1674                decided_by: Some("approved by you".into()),
1675                services: vec!["workspace".into()],
1676                tools_added: vec!["alpha_tool".into()],
1677                tools_removed: Vec::new(),
1678            },
1679        ]
1680    }
1681
1682    #[test]
1683    fn every_variant_is_listed_once() {
1684        let kinds: Vec<&str> = every_variant().iter().map(EventMsg::kind_str).collect();
1685        assert_eq!(
1686            kinds, EVENT_KINDS,
1687            "EVENT_KINDS must list every variant in order"
1688        );
1689    }
1690
1691    #[test]
1692    fn every_variant_round_trips_and_tags_by_event() {
1693        for msg in every_variant() {
1694            let value = serde_json::to_value(&msg).unwrap();
1695            assert_eq!(value["event"], msg.kind_str(), "{msg:?}");
1696            assert_eq!(value["thread_id"], msg.thread_id().to_string(), "{msg:?}");
1697            assert_eq!(value["session_id"], msg.session_id().to_string(), "{msg:?}");
1698            let back: EventMsg = serde_json::from_value(value).unwrap();
1699            assert_eq!(back, msg);
1700        }
1701    }
1702
1703    #[test]
1704    fn agent_events_from_producers_without_a_display_name_still_load() {
1705        // #6565 added `display_name`; payloads written before it omit it.
1706        let mut every = every_variant();
1707        every.retain(|msg| {
1708            matches!(
1709                msg,
1710                EventMsg::AgentSpawned { .. } | EventMsg::AgentComplete { .. }
1711            )
1712        });
1713        assert_eq!(every.len(), 2);
1714        for msg in every {
1715            let mut value = serde_json::to_value(&msg).unwrap();
1716            assert_eq!(value["display_name"], "audit docs");
1717            value.as_object_mut().unwrap().remove("display_name");
1718            let back: EventMsg = serde_json::from_value(value.clone()).unwrap();
1719            match &back {
1720                EventMsg::AgentSpawned { display_name, .. }
1721                | EventMsg::AgentComplete { display_name, .. } => assert_eq!(*display_name, None),
1722                other => panic!("unexpected {other:?}"),
1723            }
1724            assert!(
1725                serde_json::to_value(&back)
1726                    .unwrap()
1727                    .get("display_name")
1728                    .is_none()
1729            );
1730        }
1731    }
1732
1733    #[test]
1734    fn event_msg_roundtrip() {
1735        let msg = EventMsg::TurnComplete {
1736            submission_id: None,
1737            compaction_id: None,
1738            thread_id: ThreadId::new(),
1739            session_id: SessionId::new(),
1740            turn_id: Some("turn-1".into()),
1741            status: TurnOutcomeStatus::Completed,
1742            error: None,
1743            usage: TokenUsage::default(),
1744            parent_route_usage: None,
1745            routed_usage_dropped_records: 0,
1746            tool_catalog: None,
1747            base_url: None,
1748        };
1749        let json = serde_json::to_string(&msg).unwrap();
1750        let back: EventMsg = serde_json::from_str(&json).unwrap();
1751        assert_eq!(back.kind_str(), "turn_complete");
1752        assert!(json.contains(r#""status":"completed""#));
1753    }
1754
1755    #[test]
1756    fn turn_complete_ownership_is_additive_and_round_trips() {
1757        for (turn_id, submission_id, compaction_id) in [
1758            (Some("turn-1"), Some("sub-host-1"), None),
1759            (None, Some("sub-rejected"), None),
1760            (Some("autonomous-turn"), None, None),
1761            (None, None, Some("compact-1")),
1762            (None, None, None),
1763        ] {
1764            let msg = EventMsg::TurnComplete {
1765                thread_id: ThreadId::new(),
1766                session_id: SessionId::new(),
1767                turn_id: turn_id.map(str::to_string),
1768                submission_id: submission_id.map(str::to_string),
1769                compaction_id: compaction_id.map(str::to_string),
1770                status: TurnOutcomeStatus::Failed,
1771                error: Some("fixture rejection".into()),
1772                usage: TokenUsage::default(),
1773                parent_route_usage: None,
1774                routed_usage_dropped_records: 0,
1775                tool_catalog: None,
1776                base_url: None,
1777            };
1778            let value = serde_json::to_value(&msg).unwrap();
1779            for (key, expected) in [
1780                ("turn_id", turn_id),
1781                ("submission_id", submission_id),
1782                ("compaction_id", compaction_id),
1783            ] {
1784                if let Some(expected) = expected {
1785                    assert_eq!(value[key], expected);
1786                } else {
1787                    assert!(value.get(key).is_none(), "{key} must stay absent");
1788                }
1789            }
1790            let back: EventMsg = serde_json::from_value(value).unwrap();
1791            assert_eq!(
1792                back, msg,
1793                "legacy absent fields and owned receipts round-trip"
1794            );
1795        }
1796    }
1797
1798    #[test]
1799    fn text_channel_is_elided_on_the_wire() {
1800        let msg = EventMsg::ResponseDelta {
1801            thread_id: ThreadId::new(),
1802            session_id: SessionId::new(),
1803            index: 0,
1804            delta: "x".into(),
1805            channel: ResponseChannel::Text,
1806        };
1807        let json = serde_json::to_string(&msg).unwrap();
1808        assert!(!json.contains("channel"), "{json}");
1809        let back: EventMsg = serde_json::from_str(&json).unwrap();
1810        assert_eq!(back, msg);
1811    }
1812
1813    /// A host-stamped `submission_id` crosses the wire verbatim, a `None`
1814    /// token stays absent, and a payload from a producer that predates the
1815    /// field still deserializes (`serde(default)`).
1816    #[test]
1817    fn turn_started_submission_id_is_additive_and_default_absent() {
1818        let msg = EventMsg::TurnStarted {
1819            thread_id: ThreadId::new(),
1820            session_id: SessionId::new(),
1821            turn_id: "turn-1".into(),
1822            created_at: DateTime::<Utc>::from_timestamp(1, 0).unwrap(),
1823            route: None,
1824            submission_id: Some("sub-host-1".into()),
1825        };
1826        let json = serde_json::to_string(&msg).unwrap();
1827        assert!(
1828            json.contains(r#""submission_id":"sub-host-1""#),
1829            "a host-stamped token must be serialized: {json}"
1830        );
1831        let back: EventMsg = serde_json::from_str(&json).unwrap();
1832        assert_eq!(back, msg);
1833
1834        let none = EventMsg::TurnStarted {
1835            thread_id: ThreadId::new(),
1836            session_id: SessionId::new(),
1837            turn_id: "turn-2".into(),
1838            created_at: DateTime::<Utc>::from_timestamp(2, 0).unwrap(),
1839            route: None,
1840            submission_id: None,
1841        };
1842        let value = serde_json::to_value(&none).unwrap();
1843        assert!(
1844            value.get("submission_id").is_none(),
1845            "a self-started turn's None token must stay absent on the wire: {value}"
1846        );
1847        // An older producer that predates the field: the absent key defaults.
1848        let back: EventMsg = serde_json::from_value(value).unwrap();
1849        assert_eq!(back, none);
1850    }
1851}