返回 CodeWhale
event_msg.rs
根目录 / crates / protocol / src / 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
28 use std::collections::BTreeMap;
29 use std::path::PathBuf;
30
31 use chrono::{DateTime, Utc};
32 use serde::{Deserialize, Serialize};
33 use serde_json::Value;
34
35 use crate::ResponseChannel;
36 use crate::UserInputQuestionEvent;
37 use 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")]
42 pub enum TurnOutcomeStatus {
43 Completed,
44 Interrupted,
45 Failed,
46 }
47
48 impl 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)]
63 pub 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)]
86 pub 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")]
97 pub 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)]
109 pub 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)]
126 pub 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")]
145 pub 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")]
159 pub 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)]
173 pub 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")]
185 pub 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)]
200 pub 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)]
227 pub 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)]
236 pub 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)]
257 pub 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)]
266 pub 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")]
274 pub 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")]
284 pub 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")]
292 pub 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")]
304 pub 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 limit_kind: Option<crate::agent_run::AgentLimitKind>,
644 #[serde(default, skip_serializing_if = "Option::is_none")]
645 parent_run_id: Option<String>,
646 #[serde(default, skip_serializing_if = "Option::is_none")]
647 spawn_depth: Option<u32>,
648 #[serde(default, skip_serializing_if = "Option::is_none")]
649 continuable: Option<bool>,
650 #[serde(default, skip_serializing_if = "Option::is_none")]
651 display_name: Option<String>,
652 },
653 SubAgentFollowUp {
654 thread_id: ThreadId,
655 session_id: SessionId,
656 owner_session_id: String,
657 agent_id: String,
658 outcome: SubAgentFollowUpOutcome,
659 },
660 /// Sub-agent listing. `agents` are `SubAgentResult`s and `coordination`
661 /// is the `CoordinationDetailProjection`, both serialized.
662 AgentList {
663 thread_id: ThreadId,
664 session_id: SessionId,
665 owner_session_id: String,
666 agents: Vec<Value>,
667 coordination: Value,
668 /// `agent_id` -> queued follow-up count; only non-zero entries.
669 #[serde(default)]
670 queued_follow_ups: BTreeMap<String, u64>,
671 roster: Vec<AgentRosterRow>,
672 },
673 /// Structured sub-agent mailbox envelope (`MailboxMessage` serialized).
674 /// Deduplicate on `(turn_id, seq)`, never `seq` alone.
675 SubAgentMailbox {
676 thread_id: ThreadId,
677 session_id: SessionId,
678 owner_session_id: String,
679 turn_id: String,
680 seq: u64,
681 message: Value,
682 },
683 /// Live workflow UI event. `ui_event` is the flattened
684 /// `{"type": ..., "at_ms": ..., ...}` object (named `event` on the
685 /// engine side; renamed here because `event` is the wire tag).
686 WorkflowUi {
687 thread_id: ThreadId,
688 session_id: SessionId,
689 owner_session_id: String,
690 run_id: String,
691 ui_event: Value,
692 },
693
694 // === System ===
695 Error {
696 thread_id: ThreadId,
697 session_id: SessionId,
698 /// `ErrorCategory` in snake_case.
699 category: String,
700 /// `ErrorSeverity` in snake_case.
701 severity: String,
702 recoverable: bool,
703 code: String,
704 message: String,
705 },
706 Status {
707 thread_id: ThreadId,
708 session_id: SessionId,
709 message: String,
710 },
711 McpSessionBoot {
712 thread_id: ThreadId,
713 session_id: SessionId,
714 generation: u64,
715 snapshot: McpManagerSnapshot,
716 connecting: Vec<String>,
717 finished: bool,
718 },
719 /// Rendered `/preview-request` manifest.
720 RequestManifestReady {
721 thread_id: ThreadId,
722 session_id: SessionId,
723 rendered: String,
724 },
725 /// Pause terminal input events for an interactive subprocess. The engine's
726 /// in-process acknowledgement handle does not cross the wire.
727 PauseEvents {
728 thread_id: ThreadId,
729 session_id: SessionId,
730 },
731 ResumeEvents {
732 thread_id: ThreadId,
733 session_id: SessionId,
734 },
735 ApprovalRequired {
736 thread_id: ThreadId,
737 session_id: SessionId,
738 id: String,
739 tool_name: String,
740 description: String,
741 input: Value,
742 approval_key: String,
743 approval_grouping_key: String,
744 #[serde(default, skip_serializing_if = "Option::is_none")]
745 intent_summary: Option<String>,
746 approval_force_prompt: bool,
747 },
748 ApprovalWithdrawn {
749 thread_id: ThreadId,
750 session_id: SessionId,
751 id: String,
752 },
753 UserInputRequired {
754 thread_id: ThreadId,
755 session_id: SessionId,
756 id: String,
757 request: UserInputRequest,
758 },
759 UserInputClosed {
760 thread_id: ThreadId,
761 session_id: SessionId,
762 id: String,
763 outcome: UserInputClosedOutcome,
764 },
765 /// Authoritative API conversation state (`Message`s / `SystemPrompt`
766 /// serialized).
767 SessionUpdated {
768 thread_id: ThreadId,
769 session_id: SessionId,
770 engine_session_id: String,
771 messages: Vec<Value>,
772 #[serde(default, skip_serializing_if = "Option::is_none")]
773 system_prompt: Option<Value>,
774 #[serde(default, skip_serializing_if = "Option::is_none")]
775 instruction_assembly: Option<Value>,
776 model: String,
777 workspace: PathBuf,
778 },
779 ElevationRequired {
780 thread_id: ThreadId,
781 session_id: SessionId,
782 tool_id: String,
783 tool_name: String,
784 #[serde(default, skip_serializing_if = "Option::is_none")]
785 command: Option<String>,
786 denial_reason: String,
787 blocked_network: bool,
788 blocked_write: bool,
789 },
790 LspRepairUpdate {
791 thread_id: ThreadId,
792 session_id: SessionId,
793 diagnostics_found: u64,
794 files: u64,
795 injected: bool,
796 },
797 ToolGateDecision {
798 thread_id: ThreadId,
799 session_id: SessionId,
800 #[serde(default, skip_serializing_if = "Option::is_none")]
801 agent_id: Option<String>,
802 tool_id: String,
803 tool_name: String,
804 gate: ToolGate,
805 decision: ToolGateVerdict,
806 #[serde(default, skip_serializing_if = "Option::is_none")]
807 risk: Option<String>,
808 #[serde(default, skip_serializing_if = "Option::is_none")]
809 reviewer_model: Option<String>,
810 reason: String,
811 #[serde(default, skip_serializing_if = "Option::is_none")]
812 rule: Option<String>,
813 #[serde(default, skip_serializing_if = "Option::is_none")]
814 receipt_id: Option<String>,
815 #[serde(default, skip_serializing_if = "Option::is_none")]
816 call_digest: Option<String>,
817 #[serde(default, skip_serializing_if = "Option::is_none")]
818 action_summary: Option<String>,
819 },
820 AutoReviewPaused {
821 thread_id: ThreadId,
822 session_id: SessionId,
823 reason: String,
824 approval_mode: String,
825 },
826 AdvisoryNote {
827 thread_id: ThreadId,
828 session_id: SessionId,
829 turn_id: String,
830 note: String,
831 tool_call_count: u32,
832 },
833
834 // === Prefix cache ===
835 PrefixCacheChange {
836 thread_id: ThreadId,
837 session_id: SessionId,
838 description: String,
839 system_prompt_changed: bool,
840 tools_changed: bool,
841 stability_pct: u32,
842 changed: bool,
843 pinned_combined_hash: String,
844 pin_reason: String,
845 last_miss_reason: String,
846 context_updates: u64,
847 },
848 ConversationTitle {
849 thread_id: ThreadId,
850 session_id: SessionId,
851 title: String,
852 },
853 ContentFilterRefusal {
854 thread_id: ThreadId,
855 session_id: SessionId,
856 reason: String,
857 #[serde(default, skip_serializing_if = "Option::is_none")]
858 refusal: Option<String>,
859 },
860 PluginChanged {
861 thread_id: ThreadId,
862 session_id: SessionId,
863 plugin: String,
864 action: String,
865 #[serde(default, skip_serializing_if = "Option::is_none")]
866 content_hash: Option<String>,
867 #[serde(default, skip_serializing_if = "Option::is_none")]
868 decided_by: Option<String>,
869 #[serde(default, skip_serializing_if = "Vec::is_empty")]
870 services: Vec<String>,
871 #[serde(default, skip_serializing_if = "Vec::is_empty")]
872 tools_added: Vec<String>,
873 #[serde(default, skip_serializing_if = "Vec::is_empty")]
874 tools_removed: Vec<String>,
875 },
876 }
877
878 /// Envelope that carries an `EventMsg` over the wire / channel with a
879 /// monotonic seq so consumers can detect drops. Mirrors the existing
880 /// `RuntimeEventEnvelope` but typed to `EventMsg`.
881 #[derive(Debug, Clone, Serialize, Deserialize)]
882 pub struct EventEnvelope {
883 pub seq: u64,
884 pub thread_id: ThreadId,
885 pub session_id: SessionId,
886 pub turn_id: Option<String>,
887 pub event: EventMsg,
888 }
889
890 /// Every wire tag `EventMsg` can carry, in declaration order. Kept next to
891 /// the enum so a new variant is added here in the same edit; the test below
892 /// proves the list and `kind_str` agree.
893 pub const EVENT_KINDS: &[&str] = &[
894 "tool_projection_warning",
895 "request_image_window",
896 "message_started",
897 "response_delta",
898 "message_complete",
899 "thinking_started",
900 "thinking_complete",
901 "tool_call_started",
902 "tool_call_heartbeat",
903 "tool_call_complete",
904 "operation_activity_started",
905 "operation_activity_completed",
906 "turn_started",
907 "tool_request_snapshot",
908 "workspace_snapshot_taken",
909 "route_dispatched",
910 "turn_complete",
911 "turn_usage",
912 "routed_turn_usage",
913 "goal_updated",
914 "goal_continuation_waiting",
915 "goal_continuation_wait_ended",
916 "compaction_started",
917 "compaction_completed",
918 "compaction_cancelled",
919 "compaction_failed",
920 "purge_started",
921 "purge_completed",
922 "purge_failed",
923 "agent_spawned",
924 "agent_progress",
925 "agent_complete",
926 "sub_agent_follow_up",
927 "agent_list",
928 "sub_agent_mailbox",
929 "workflow_ui",
930 "error",
931 "status",
932 "mcp_session_boot",
933 "request_manifest_ready",
934 "pause_events",
935 "resume_events",
936 "approval_required",
937 "approval_withdrawn",
938 "user_input_required",
939 "user_input_closed",
940 "session_updated",
941 "elevation_required",
942 "lsp_repair_update",
943 "tool_gate_decision",
944 "auto_review_paused",
945 "advisory_note",
946 "prefix_cache_change",
947 "conversation_title",
948 "content_filter_refusal",
949 "plugin_changed",
950 ];
951
952 impl EventMsg {
953 #[must_use]
954 pub fn kind_str(&self) -> &'static str {
955 match self {
956 Self::ToolProjectionWarning { .. } => "tool_projection_warning",
957 Self::RequestImageWindow { .. } => "request_image_window",
958 Self::SnapshotsDisabled { .. } => "snapshots_disabled",
959 Self::MessageStarted { .. } => "message_started",
960 Self::ResponseDelta { .. } => "response_delta",
961 Self::MessageComplete { .. } => "message_complete",
962 Self::ThinkingStarted { .. } => "thinking_started",
963 Self::ThinkingComplete { .. } => "thinking_complete",
964 Self::ToolCallStarted { .. } => "tool_call_started",
965 Self::ToolCallHeartbeat { .. } => "tool_call_heartbeat",
966 Self::ToolExecutionStarted { .. } => "tool_execution_started",
967 Self::ToolResultContent { .. } => "tool_result_content",
968 Self::ToolCallComplete { .. } => "tool_call_complete",
969 Self::OperationActivityStarted { .. } => "operation_activity_started",
970 Self::OperationActivityCompleted { .. } => "operation_activity_completed",
971 Self::TurnStarted { .. } => "turn_started",
972 Self::ToolRequestSnapshot { .. } => "tool_request_snapshot",
973 Self::WorkspaceSnapshotTaken { .. } => "workspace_snapshot_taken",
974 Self::RouteDispatched { .. } => "route_dispatched",
975 Self::TurnComplete { .. } => "turn_complete",
976 Self::ProviderRequestReceipt { .. } => "provider_request_receipt",
977 Self::TurnUsage { .. } => "turn_usage",
978 Self::RoutedTurnUsage { .. } => "routed_turn_usage",
979 Self::GoalUpdated { .. } => "goal_updated",
980 Self::GoalContinuationWaiting { .. } => "goal_continuation_waiting",
981 Self::GoalContinuationWaitEnded { .. } => "goal_continuation_wait_ended",
982 Self::CompactionStarted { .. } => "compaction_started",
983 Self::CompactionCompleted { .. } => "compaction_completed",
984 Self::CompactionCancelled { .. } => "compaction_cancelled",
985 Self::CompactionFailed { .. } => "compaction_failed",
986 Self::PurgeStarted { .. } => "purge_started",
987 Self::PurgeCompleted { .. } => "purge_completed",
988 Self::PurgeFailed { .. } => "purge_failed",
989 Self::AgentSpawned { .. } => "agent_spawned",
990 Self::AgentProgress { .. } => "agent_progress",
991 Self::AgentComplete { .. } => "agent_complete",
992 Self::SubAgentFollowUp { .. } => "sub_agent_follow_up",
993 Self::AgentList { .. } => "agent_list",
994 Self::SubAgentMailbox { .. } => "sub_agent_mailbox",
995 Self::WorkflowUi { .. } => "workflow_ui",
996 Self::Error { .. } => "error",
997 Self::Status { .. } => "status",
998 Self::McpSessionBoot { .. } => "mcp_session_boot",
999 Self::RequestManifestReady { .. } => "request_manifest_ready",
1000 Self::PauseEvents { .. } => "pause_events",
1001 Self::ResumeEvents { .. } => "resume_events",
1002 Self::ApprovalRequired { .. } => "approval_required",
1003 Self::ApprovalWithdrawn { .. } => "approval_withdrawn",
1004 Self::UserInputRequired { .. } => "user_input_required",
1005 Self::UserInputClosed { .. } => "user_input_closed",
1006 Self::SessionUpdated { .. } => "session_updated",
1007 Self::ElevationRequired { .. } => "elevation_required",
1008 Self::LspRepairUpdate { .. } => "lsp_repair_update",
1009 Self::ToolGateDecision { .. } => "tool_gate_decision",
1010 Self::AutoReviewPaused { .. } => "auto_review_paused",
1011 Self::AdvisoryNote { .. } => "advisory_note",
1012 Self::PrefixCacheChange { .. } => "prefix_cache_change",
1013 Self::ConversationTitle { .. } => "conversation_title",
1014 Self::ContentFilterRefusal { .. } => "content_filter_refusal",
1015 Self::PluginChanged { .. } => "plugin_changed",
1016 }
1017 }
1018
1019 #[must_use]
1020 pub fn thread_id(&self) -> &ThreadId {
1021 match self {
1022 Self::ToolProjectionWarning { thread_id, .. }
1023 | Self::RequestImageWindow { thread_id, .. }
1024 | Self::SnapshotsDisabled { thread_id, .. }
1025 | Self::MessageStarted { thread_id, .. }
1026 | Self::ResponseDelta { thread_id, .. }
1027 | Self::MessageComplete { thread_id, .. }
1028 | Self::ThinkingStarted { thread_id, .. }
1029 | Self::ThinkingComplete { thread_id, .. }
1030 | Self::ToolCallStarted { thread_id, .. }
1031 | Self::ToolCallHeartbeat { thread_id, .. }
1032 | Self::ToolExecutionStarted { thread_id, .. }
1033 | Self::ToolResultContent { thread_id, .. }
1034 | Self::ToolCallComplete { thread_id, .. }
1035 | Self::OperationActivityStarted { thread_id, .. }
1036 | Self::OperationActivityCompleted { thread_id, .. }
1037 | Self::TurnStarted { thread_id, .. }
1038 | Self::ToolRequestSnapshot { thread_id, .. }
1039 | Self::WorkspaceSnapshotTaken { thread_id, .. }
1040 | Self::RouteDispatched { thread_id, .. }
1041 | Self::TurnComplete { thread_id, .. }
1042 | Self::ProviderRequestReceipt { thread_id, .. }
1043 | Self::TurnUsage { thread_id, .. }
1044 | Self::RoutedTurnUsage { thread_id, .. }
1045 | Self::GoalUpdated { thread_id, .. }
1046 | Self::GoalContinuationWaiting { thread_id, .. }
1047 | Self::GoalContinuationWaitEnded { thread_id, .. }
1048 | Self::CompactionStarted { thread_id, .. }
1049 | Self::CompactionCompleted { thread_id, .. }
1050 | Self::CompactionCancelled { thread_id, .. }
1051 | Self::CompactionFailed { thread_id, .. }
1052 | Self::PurgeStarted { thread_id, .. }
1053 | Self::PurgeCompleted { thread_id, .. }
1054 | Self::PurgeFailed { thread_id, .. }
1055 | Self::AgentSpawned { thread_id, .. }
1056 | Self::AgentProgress { thread_id, .. }
1057 | Self::AgentComplete { thread_id, .. }
1058 | Self::SubAgentFollowUp { thread_id, .. }
1059 | Self::AgentList { thread_id, .. }
1060 | Self::SubAgentMailbox { thread_id, .. }
1061 | Self::WorkflowUi { thread_id, .. }
1062 | Self::Error { thread_id, .. }
1063 | Self::Status { thread_id, .. }
1064 | Self::McpSessionBoot { thread_id, .. }
1065 | Self::RequestManifestReady { thread_id, .. }
1066 | Self::PauseEvents { thread_id, .. }
1067 | Self::ResumeEvents { thread_id, .. }
1068 | Self::ApprovalRequired { thread_id, .. }
1069 | Self::ApprovalWithdrawn { thread_id, .. }
1070 | Self::UserInputRequired { thread_id, .. }
1071 | Self::UserInputClosed { thread_id, .. }
1072 | Self::SessionUpdated { thread_id, .. }
1073 | Self::ElevationRequired { thread_id, .. }
1074 | Self::LspRepairUpdate { thread_id, .. }
1075 | Self::ToolGateDecision { thread_id, .. }
1076 | Self::AutoReviewPaused { thread_id, .. }
1077 | Self::AdvisoryNote { thread_id, .. }
1078 | Self::PrefixCacheChange { thread_id, .. }
1079 | Self::ConversationTitle { thread_id, .. }
1080 | Self::ContentFilterRefusal { thread_id, .. }
1081 | Self::PluginChanged { thread_id, .. } => thread_id,
1082 }
1083 }
1084
1085 #[must_use]
1086 pub fn session_id(&self) -> &SessionId {
1087 match self {
1088 Self::ToolProjectionWarning { session_id, .. }
1089 | Self::RequestImageWindow { session_id, .. }
1090 | Self::SnapshotsDisabled { session_id, .. }
1091 | Self::MessageStarted { session_id, .. }
1092 | Self::ResponseDelta { session_id, .. }
1093 | Self::MessageComplete { session_id, .. }
1094 | Self::ThinkingStarted { session_id, .. }
1095 | Self::ThinkingComplete { session_id, .. }
1096 | Self::ToolCallStarted { session_id, .. }
1097 | Self::ToolCallHeartbeat { session_id, .. }
1098 | Self::ToolExecutionStarted { session_id, .. }
1099 | Self::ToolResultContent { session_id, .. }
1100 | Self::ToolCallComplete { session_id, .. }
1101 | Self::OperationActivityStarted { session_id, .. }
1102 | Self::OperationActivityCompleted { session_id, .. }
1103 | Self::TurnStarted { session_id, .. }
1104 | Self::ToolRequestSnapshot { session_id, .. }
1105 | Self::WorkspaceSnapshotTaken { session_id, .. }
1106 | Self::RouteDispatched { session_id, .. }
1107 | Self::TurnComplete { session_id, .. }
1108 | Self::ProviderRequestReceipt { session_id, .. }
1109 | Self::TurnUsage { session_id, .. }
1110 | Self::RoutedTurnUsage { session_id, .. }
1111 | Self::GoalUpdated { session_id, .. }
1112 | Self::GoalContinuationWaiting { session_id, .. }
1113 | Self::GoalContinuationWaitEnded { session_id, .. }
1114 | Self::CompactionStarted { session_id, .. }
1115 | Self::CompactionCompleted { session_id, .. }
1116 | Self::CompactionCancelled { session_id, .. }
1117 | Self::CompactionFailed { session_id, .. }
1118 | Self::PurgeStarted { session_id, .. }
1119 | Self::PurgeCompleted { session_id, .. }
1120 | Self::PurgeFailed { session_id, .. }
1121 | Self::AgentSpawned { session_id, .. }
1122 | Self::AgentProgress { session_id, .. }
1123 | Self::AgentComplete { session_id, .. }
1124 | Self::SubAgentFollowUp { session_id, .. }
1125 | Self::AgentList { session_id, .. }
1126 | Self::SubAgentMailbox { session_id, .. }
1127 | Self::WorkflowUi { session_id, .. }
1128 | Self::Error { session_id, .. }
1129 | Self::Status { session_id, .. }
1130 | Self::McpSessionBoot { session_id, .. }
1131 | Self::RequestManifestReady { session_id, .. }
1132 | Self::PauseEvents { session_id, .. }
1133 | Self::ResumeEvents { session_id, .. }
1134 | Self::ApprovalRequired { session_id, .. }
1135 | Self::ApprovalWithdrawn { session_id, .. }
1136 | Self::UserInputRequired { session_id, .. }
1137 | Self::UserInputClosed { session_id, .. }
1138 | Self::SessionUpdated { session_id, .. }
1139 | Self::ElevationRequired { session_id, .. }
1140 | Self::LspRepairUpdate { session_id, .. }
1141 | Self::ToolGateDecision { session_id, .. }
1142 | Self::AutoReviewPaused { session_id, .. }
1143 | Self::AdvisoryNote { session_id, .. }
1144 | Self::PrefixCacheChange { session_id, .. }
1145 | Self::ConversationTitle { session_id, .. }
1146 | Self::ContentFilterRefusal { session_id, .. }
1147 | Self::PluginChanged { session_id, .. } => session_id,
1148 }
1149 }
1150 }
1151
1152 #[cfg(test)]
1153 mod tests {
1154 use super::*;
1155 use serde_json::json;
1156
1157 fn ids() -> (ThreadId, SessionId) {
1158 (ThreadId::new(), SessionId::new())
1159 }
1160
1161 /// One instance of every variant, in declaration order. A new variant
1162 /// must be added here too, or `every_variant_is_listed_once` fails.
1163 fn every_variant() -> Vec<EventMsg> {
1164 let (t, s) = ids();
1165 let usage = TokenUsage {
1166 input_tokens: 1,
1167 output_tokens: 2,
1168 ..TokenUsage::default()
1169 };
1170 let route = TurnRoute {
1171 provider: "deepseek".into(),
1172 provider_identity: "deepseek".into(),
1173 model: "deepseek-chat".into(),
1174 auto_model: false,
1175 receipt: Some(TurnRouteReceipt {
1176 provider: "deepseek".into(),
1177 provider_identity: "deepseek".into(),
1178 wire_model: "deepseek-chat".into(),
1179 endpoint_identity: "api.deepseek.com".into(),
1180 credential_generation_present: true,
1181 }),
1182 billing: Some(RouteBillingEnvelope {
1183 openrouter_vendor: None,
1184 billing_surface: None,
1185 endpoint_fingerprint: Some("fp".into()),
1186 provider_live_pricing: None,
1187 billing_mode: "metered".into(),
1188 dispatched_at: DateTime::<Utc>::from_timestamp(0, 0).unwrap(),
1189 }),
1190 base_url: "https://api.deepseek.com".into(),
1191 billing_product: RouteProduct::Subscription {
1192 label: "pro".into(),
1193 },
1194 };
1195 vec![
1196 EventMsg::ToolProjectionWarning {
1197 thread_id: t.clone(),
1198 session_id: s.clone(),
1199 provider: "openai".into(),
1200 omitted_tool_names: vec!["a".into()],
1201 omitted_tool_count: 3,
1202 },
1203 EventMsg::RequestImageWindow {
1204 thread_id: t.clone(),
1205 session_id: s.clone(),
1206 provider: "vllm".into(),
1207 model: "m".into(),
1208 total: 6,
1209 elided: 3,
1210 cap: 3,
1211 cap_source: "provider_rejection".into(),
1212 message: "m".into(),
1213 },
1214 EventMsg::MessageStarted {
1215 thread_id: t.clone(),
1216 session_id: s.clone(),
1217 index: 0,
1218 },
1219 EventMsg::ResponseDelta {
1220 thread_id: t.clone(),
1221 session_id: s.clone(),
1222 index: 0,
1223 delta: "hi".into(),
1224 channel: ResponseChannel::Reasoning,
1225 },
1226 EventMsg::MessageComplete {
1227 thread_id: t.clone(),
1228 session_id: s.clone(),
1229 index: 0,
1230 },
1231 EventMsg::ThinkingStarted {
1232 thread_id: t.clone(),
1233 session_id: s.clone(),
1234 index: 1,
1235 },
1236 EventMsg::ThinkingComplete {
1237 thread_id: t.clone(),
1238 session_id: s.clone(),
1239 index: 1,
1240 },
1241 EventMsg::ToolCallStarted {
1242 thread_id: t.clone(),
1243 session_id: s.clone(),
1244 tool_call_id: "c1".into(),
1245 tool_name: "read_file".into(),
1246 input: json!({"path": "x"}),
1247 },
1248 EventMsg::ToolCallHeartbeat {
1249 thread_id: t.clone(),
1250 session_id: s.clone(),
1251 },
1252 EventMsg::ToolCallComplete {
1253 thread_id: t.clone(),
1254 session_id: s.clone(),
1255 tool_call_id: "c1".into(),
1256 tool_name: "read_file".into(),
1257 result: ToolCallOutcome::Err {
1258 error: ToolCallError::Timeout { seconds: 3 },
1259 },
1260 },
1261 EventMsg::OperationActivityStarted {
1262 thread_id: t.clone(),
1263 session_id: s.clone(),
1264 span_id: "span-1".into(),
1265 activity_kind: crate::engine_owner::OwnerActivityKind::Reading,
1266 action_id: Some("read_file".into()),
1267 },
1268 EventMsg::OperationActivityCompleted {
1269 thread_id: t.clone(),
1270 session_id: s.clone(),
1271 span_id: "span-1".into(),
1272 activity_kind: crate::engine_owner::OwnerActivityKind::Reading,
1273 action_id: Some("read_file".into()),
1274 outcome: crate::engine_owner::OwnerOperationOutcome::Succeeded,
1275 },
1276 EventMsg::TurnStarted {
1277 thread_id: t.clone(),
1278 session_id: s.clone(),
1279 turn_id: "turn-1".into(),
1280 created_at: DateTime::<Utc>::from_timestamp(1, 0).unwrap(),
1281 route: Some(route.clone()),
1282 submission_id: None,
1283 },
1284 EventMsg::ToolRequestSnapshot {
1285 thread_id: t.clone(),
1286 session_id: s.clone(),
1287 snapshot: json!({"tool_count": 2}),
1288 },
1289 EventMsg::WorkspaceSnapshotTaken {
1290 thread_id: t.clone(),
1291 session_id: s.clone(),
1292 snapshot: json!({"kind": "pre_turn", "tree_id": "t"}),
1293 },
1294 EventMsg::RouteDispatched {
1295 thread_id: t.clone(),
1296 session_id: s.clone(),
1297 turn_id: "turn-1".into(),
1298 route,
1299 },
1300 EventMsg::TurnComplete {
1301 submission_id: None,
1302 compaction_id: None,
1303 thread_id: t.clone(),
1304 session_id: s.clone(),
1305 turn_id: None,
1306 status: TurnOutcomeStatus::Failed,
1307 error: Some("boom".into()),
1308 usage: usage.clone(),
1309 parent_route_usage: Some(usage.clone()),
1310 routed_usage_dropped_records: 0,
1311 tool_catalog: Some(vec![json!({"name": "read_file"})]),
1312 base_url: None,
1313 },
1314 EventMsg::TurnUsage {
1315 max_output_tokens: None,
1316 thread_id: t.clone(),
1317 session_id: s.clone(),
1318 usage: usage.clone(),
1319 duration_ms: 10,
1320 first_token_ms: Some(2),
1321 request_ms: None,
1322 },
1323 EventMsg::RoutedTurnUsage {
1324 thread_id: t.clone(),
1325 session_id: s.clone(),
1326 usage,
1327 duration_ms: 10,
1328 first_token_ms: Some(2),
1329 request_ms: None,
1330 },
1331 EventMsg::GoalUpdated {
1332 thread_id: t.clone(),
1333 session_id: s.clone(),
1334 snapshot: json!({"status": "active"}),
1335 },
1336 EventMsg::GoalContinuationWaiting {
1337 thread_id: t.clone(),
1338 session_id: s.clone(),
1339 delay_seconds: 5,
1340 },
1341 EventMsg::GoalContinuationWaitEnded {
1342 thread_id: t.clone(),
1343 session_id: s.clone(),
1344 interrupted: true,
1345 },
1346 EventMsg::CompactionStarted {
1347 thread_id: t.clone(),
1348 session_id: s.clone(),
1349 id: "cmp-1".into(),
1350 auto: true,
1351 message: "m".into(),
1352 },
1353 EventMsg::CompactionCompleted {
1354 thread_id: t.clone(),
1355 session_id: s.clone(),
1356 id: "cmp-1".into(),
1357 auto: true,
1358 message: "m".into(),
1359 messages_before: Some(10),
1360 messages_after: Some(2),
1361 summary_prompt: None,
1362 post_input_tokens: Some(100),
1363 },
1364 EventMsg::CompactionCancelled {
1365 thread_id: t.clone(),
1366 session_id: s.clone(),
1367 id: "cmp-1".into(),
1368 auto: false,
1369 message: "m".into(),
1370 },
1371 EventMsg::CompactionFailed {
1372 thread_id: t.clone(),
1373 session_id: s.clone(),
1374 id: "cmp-1".into(),
1375 auto: false,
1376 message: "m".into(),
1377 },
1378 EventMsg::PurgeStarted {
1379 thread_id: t.clone(),
1380 session_id: s.clone(),
1381 message: "m".into(),
1382 },
1383 EventMsg::PurgeCompleted {
1384 thread_id: t.clone(),
1385 session_id: s.clone(),
1386 messages_before: 4,
1387 messages_after: 2,
1388 removed_count: 2,
1389 replaced_count: 0,
1390 message: "m".into(),
1391 },
1392 EventMsg::PurgeFailed {
1393 thread_id: t.clone(),
1394 session_id: s.clone(),
1395 message: "m".into(),
1396 },
1397 EventMsg::AgentSpawned {
1398 thread_id: t.clone(),
1399 session_id: s.clone(),
1400 owner_session_id: "owner".into(),
1401 id: "a1".into(),
1402 prompt: "p".into(),
1403 worker_status: Some("starting".into()),
1404 parent_run_id: None,
1405 spawn_depth: 1,
1406 model: "m".into(),
1407 route_source: Some("task.model".into()),
1408 display_name: Some("audit docs".into()),
1409 },
1410 EventMsg::AgentProgress {
1411 thread_id: t.clone(),
1412 session_id: s.clone(),
1413 owner_session_id: "owner".into(),
1414 id: "a1".into(),
1415 status: "running".into(),
1416 activity: AgentProgressActivity {
1417 worker_status: "running_tool".into(),
1418 step: Some(2),
1419 tool_name: Some("bash".into()),
1420 },
1421 parent_run_id: None,
1422 spawn_depth: 1,
1423 },
1424 EventMsg::AgentComplete {
1425 limit_kind: None,
1426 thread_id: t.clone(),
1427 session_id: s.clone(),
1428 owner_session_id: "owner".into(),
1429 id: "a1".into(),
1430 result: "done".into(),
1431 worker_status: Some("completed".into()),
1432 parent_run_id: None,
1433 spawn_depth: Some(1),
1434 continuable: Some(false),
1435 display_name: Some("audit docs".into()),
1436 },
1437 EventMsg::SubAgentFollowUp {
1438 thread_id: t.clone(),
1439 session_id: s.clone(),
1440 owner_session_id: "owner".into(),
1441 agent_id: "a1".into(),
1442 outcome: SubAgentFollowUpOutcome::Ok {
1443 agent_id: "a1".into(),
1444 target_agent_id: "a2".into(),
1445 delivered: false,
1446 resumed: true,
1447 note: "resumed".into(),
1448 },
1449 },
1450 EventMsg::AgentList {
1451 thread_id: t.clone(),
1452 session_id: s.clone(),
1453 owner_session_id: "owner".into(),
1454 agents: vec![json!({"id": "a1"})],
1455 coordination: json!({}),
1456 queued_follow_ups: BTreeMap::from([("a1".to_string(), 1)]),
1457 roster: vec![AgentRosterRow {
1458 worker_id: "w1".into(),
1459 display_name: "scout".into(),
1460 model: "m".into(),
1461 state: "running".into(),
1462 status: "running".into(),
1463 activity: None,
1464 millis: Some(5),
1465 input_tokens: None,
1466 output_tokens: None,
1467 cost_microusd: None,
1468 steps_taken: 1,
1469 parent_run_id: None,
1470 run_id: "r1".into(),
1471 }],
1472 },
1473 EventMsg::SubAgentMailbox {
1474 thread_id: t.clone(),
1475 session_id: s.clone(),
1476 owner_session_id: "owner".into(),
1477 turn_id: "turn-1".into(),
1478 seq: 7,
1479 message: json!({"kind": "spawned"}),
1480 },
1481 EventMsg::WorkflowUi {
1482 thread_id: t.clone(),
1483 session_id: s.clone(),
1484 owner_session_id: "owner".into(),
1485 run_id: "run-1".into(),
1486 ui_event: json!({"type": "task_started"}),
1487 },
1488 EventMsg::Error {
1489 thread_id: t.clone(),
1490 session_id: s.clone(),
1491 category: "network".into(),
1492 severity: "error".into(),
1493 recoverable: true,
1494 code: "E1".into(),
1495 message: "m".into(),
1496 },
1497 EventMsg::Status {
1498 thread_id: t.clone(),
1499 session_id: s.clone(),
1500 message: "m".into(),
1501 },
1502 EventMsg::McpSessionBoot {
1503 thread_id: t.clone(),
1504 session_id: s.clone(),
1505 generation: 1,
1506 snapshot: McpManagerSnapshot {
1507 config_path: PathBuf::from("/tmp/mcp.json"),
1508 config_exists: true,
1509 reload_required: false,
1510 servers: vec![McpServerSnapshot {
1511 name: "fs".into(),
1512 enabled: true,
1513 required: false,
1514 transport: "stdio".into(),
1515 command_or_url: "npx".into(),
1516 connect_timeout: 1,
1517 execute_timeout: 2,
1518 read_timeout: 3,
1519 connected: true,
1520 error: None,
1521 capability_metadata: "advertised".into(),
1522 tools: vec![McpDiscoveredItem {
1523 name: "read".into(),
1524 model_name: "fs__read".into(),
1525 description: None,
1526 }],
1527 resources: vec![],
1528 prompts: vec![],
1529 }],
1530 },
1531 connecting: vec!["slow".into()],
1532 finished: false,
1533 },
1534 EventMsg::RequestManifestReady {
1535 thread_id: t.clone(),
1536 session_id: s.clone(),
1537 rendered: "manifest".into(),
1538 },
1539 EventMsg::PauseEvents {
1540 thread_id: t.clone(),
1541 session_id: s.clone(),
1542 },
1543 EventMsg::ResumeEvents {
1544 thread_id: t.clone(),
1545 session_id: s.clone(),
1546 },
1547 EventMsg::ApprovalRequired {
1548 thread_id: t.clone(),
1549 session_id: s.clone(),
1550 id: "c1".into(),
1551 tool_name: "bash".into(),
1552 description: "rm".into(),
1553 input: json!({"command": "rm"}),
1554 approval_key: "k".into(),
1555 approval_grouping_key: "g".into(),
1556 intent_summary: None,
1557 approval_force_prompt: true,
1558 },
1559 EventMsg::ApprovalWithdrawn {
1560 thread_id: t.clone(),
1561 session_id: s.clone(),
1562 id: "c1".into(),
1563 },
1564 EventMsg::UserInputRequired {
1565 thread_id: t.clone(),
1566 session_id: s.clone(),
1567 id: "c2".into(),
1568 request: UserInputRequest {
1569 require_typed_answers: true,
1570 questions: vec![UserInputQuestionEvent {
1571 header: "h".into(),
1572 id: "q1".into(),
1573 question: "?".into(),
1574 detail: Some("Exact detail".into()),
1575 intent: Some(crate::UserInputIntentEvent::PlanReview {
1576 approve: "Proceed".into(),
1577 call_id: Some("plan-1".into()),
1578 }),
1579 options: vec![],
1580 allow_free_text: true,
1581 multi_select: false,
1582 }],
1583 },
1584 },
1585 EventMsg::UserInputClosed {
1586 thread_id: t.clone(),
1587 session_id: s.clone(),
1588 id: "c2".into(),
1589 outcome: UserInputClosedOutcome::TimedOut,
1590 },
1591 EventMsg::SessionUpdated {
1592 thread_id: t.clone(),
1593 session_id: s.clone(),
1594 engine_session_id: "sess".into(),
1595 messages: vec![json!({"role": "user", "content": []})],
1596 system_prompt: Some(json!("sys")),
1597 instruction_assembly: None,
1598 model: "m".into(),
1599 workspace: PathBuf::from("/ws"),
1600 },
1601 EventMsg::ElevationRequired {
1602 thread_id: t.clone(),
1603 session_id: s.clone(),
1604 tool_id: "c3".into(),
1605 tool_name: "bash".into(),
1606 command: Some("curl".into()),
1607 denial_reason: "net".into(),
1608 blocked_network: true,
1609 blocked_write: false,
1610 },
1611 EventMsg::LspRepairUpdate {
1612 thread_id: t.clone(),
1613 session_id: s.clone(),
1614 diagnostics_found: 1,
1615 files: 1,
1616 injected: true,
1617 },
1618 EventMsg::ToolGateDecision {
1619 thread_id: t.clone(),
1620 session_id: s.clone(),
1621 agent_id: None,
1622 tool_id: "c4".into(),
1623 tool_name: "bash".into(),
1624 gate: ToolGate::AutoReviewGuardian,
1625 decision: ToolGateVerdict::Denied,
1626 risk: Some("high".into()),
1627 reviewer_model: Some("claude-sonnet-5-5".into()),
1628 reason: "no".into(),
1629 rule: Some("guardian".into()),
1630 receipt_id: Some("ar-1".into()),
1631 call_digest: Some("d1".into()),
1632 action_summary: Some("bash: rm -rf /tmp".into()),
1633 },
1634 EventMsg::AutoReviewPaused {
1635 thread_id: t.clone(),
1636 session_id: s.clone(),
1637 reason: "Auto-Review paused after 3 blocked calls in a row; Shift+Tab or /auto to resume".into(),
1638 approval_mode: "suggest".into(),
1639 },
1640 EventMsg::AdvisoryNote {
1641 thread_id: t.clone(),
1642 session_id: s.clone(),
1643 turn_id: "turn-1".into(),
1644 note: "n".into(),
1645 tool_call_count: 2,
1646 },
1647 EventMsg::PrefixCacheChange {
1648 thread_id: t.clone(),
1649 session_id: s.clone(),
1650 description: "d".into(),
1651 system_prompt_changed: false,
1652 tools_changed: true,
1653 stability_pct: 90,
1654 changed: true,
1655 pinned_combined_hash: "h".into(),
1656 pin_reason: "initial".into(),
1657 last_miss_reason: String::new(),
1658 context_updates: 0,
1659 },
1660 EventMsg::ConversationTitle {
1661 thread_id: t.clone(),
1662 session_id: s.clone(),
1663 title: "Conversation".into(),
1664 },
1665 EventMsg::ContentFilterRefusal {
1666 thread_id: t.clone(),
1667 session_id: s.clone(),
1668 reason: "content_filter".into(),
1669 refusal: Some("Blocked by safety policy".into()),
1670 },
1671 EventMsg::PluginChanged {
1672 thread_id: t,
1673 session_id: s,
1674 plugin: "alpha".into(),
1675 action: "installed".into(),
1676 content_hash: Some("sha256:abc".into()),
1677 decided_by: Some("approved by you".into()),
1678 services: vec!["workspace".into()],
1679 tools_added: vec!["alpha_tool".into()],
1680 tools_removed: Vec::new(),
1681 },
1682 ]
1683 }
1684
1685 #[test]
1686 fn every_variant_is_listed_once() {
1687 let kinds: Vec<&str> = every_variant().iter().map(EventMsg::kind_str).collect();
1688 assert_eq!(
1689 kinds, EVENT_KINDS,
1690 "EVENT_KINDS must list every variant in order"
1691 );
1692 }
1693
1694 #[test]
1695 fn every_variant_round_trips_and_tags_by_event() {
1696 for msg in every_variant() {
1697 let value = serde_json::to_value(&msg).unwrap();
1698 assert_eq!(value["event"], msg.kind_str(), "{msg:?}");
1699 assert_eq!(value["thread_id"], msg.thread_id().to_string(), "{msg:?}");
1700 assert_eq!(value["session_id"], msg.session_id().to_string(), "{msg:?}");
1701 let back: EventMsg = serde_json::from_value(value).unwrap();
1702 assert_eq!(back, msg);
1703 }
1704 }
1705
1706 #[test]
1707 fn agent_events_from_producers_without_a_display_name_still_load() {
1708 // #6565 added `display_name`; payloads written before it omit it.
1709 let mut every = every_variant();
1710 every.retain(|msg| {
1711 matches!(
1712 msg,
1713 EventMsg::AgentSpawned { .. } | EventMsg::AgentComplete { .. }
1714 )
1715 });
1716 assert_eq!(every.len(), 2);
1717 for msg in every {
1718 let mut value = serde_json::to_value(&msg).unwrap();
1719 assert_eq!(value["display_name"], "audit docs");
1720 value.as_object_mut().unwrap().remove("display_name");
1721 let back: EventMsg = serde_json::from_value(value.clone()).unwrap();
1722 match &back {
1723 EventMsg::AgentSpawned { display_name, .. }
1724 | EventMsg::AgentComplete { display_name, .. } => assert_eq!(*display_name, None),
1725 other => panic!("unexpected {other:?}"),
1726 }
1727 assert!(
1728 serde_json::to_value(&back)
1729 .unwrap()
1730 .get("display_name")
1731 .is_none()
1732 );
1733 }
1734 }
1735
1736 #[test]
1737 fn event_msg_roundtrip() {
1738 let msg = EventMsg::TurnComplete {
1739 submission_id: None,
1740 compaction_id: None,
1741 thread_id: ThreadId::new(),
1742 session_id: SessionId::new(),
1743 turn_id: Some("turn-1".into()),
1744 status: TurnOutcomeStatus::Completed,
1745 error: None,
1746 usage: TokenUsage::default(),
1747 parent_route_usage: None,
1748 routed_usage_dropped_records: 0,
1749 tool_catalog: None,
1750 base_url: None,
1751 };
1752 let json = serde_json::to_string(&msg).unwrap();
1753 let back: EventMsg = serde_json::from_str(&json).unwrap();
1754 assert_eq!(back.kind_str(), "turn_complete");
1755 assert!(json.contains(r#""status":"completed""#));
1756 }
1757
1758 #[test]
1759 fn turn_complete_ownership_is_additive_and_round_trips() {
1760 for (turn_id, submission_id, compaction_id) in [
1761 (Some("turn-1"), Some("sub-host-1"), None),
1762 (None, Some("sub-rejected"), None),
1763 (Some("autonomous-turn"), None, None),
1764 (None, None, Some("compact-1")),
1765 (None, None, None),
1766 ] {
1767 let msg = EventMsg::TurnComplete {
1768 thread_id: ThreadId::new(),
1769 session_id: SessionId::new(),
1770 turn_id: turn_id.map(str::to_string),
1771 submission_id: submission_id.map(str::to_string),
1772 compaction_id: compaction_id.map(str::to_string),
1773 status: TurnOutcomeStatus::Failed,
1774 error: Some("fixture rejection".into()),
1775 usage: TokenUsage::default(),
1776 parent_route_usage: None,
1777 routed_usage_dropped_records: 0,
1778 tool_catalog: None,
1779 base_url: None,
1780 };
1781 let value = serde_json::to_value(&msg).unwrap();
1782 for (key, expected) in [
1783 ("turn_id", turn_id),
1784 ("submission_id", submission_id),
1785 ("compaction_id", compaction_id),
1786 ] {
1787 if let Some(expected) = expected {
1788 assert_eq!(value[key], expected);
1789 } else {
1790 assert!(value.get(key).is_none(), "{key} must stay absent");
1791 }
1792 }
1793 let back: EventMsg = serde_json::from_value(value).unwrap();
1794 assert_eq!(
1795 back, msg,
1796 "legacy absent fields and owned receipts round-trip"
1797 );
1798 }
1799 }
1800
1801 #[test]
1802 fn text_channel_is_elided_on_the_wire() {
1803 let msg = EventMsg::ResponseDelta {
1804 thread_id: ThreadId::new(),
1805 session_id: SessionId::new(),
1806 index: 0,
1807 delta: "x".into(),
1808 channel: ResponseChannel::Text,
1809 };
1810 let json = serde_json::to_string(&msg).unwrap();
1811 assert!(!json.contains("channel"), "{json}");
1812 let back: EventMsg = serde_json::from_str(&json).unwrap();
1813 assert_eq!(back, msg);
1814 }
1815
1816 /// A host-stamped `submission_id` crosses the wire verbatim, a `None`
1817 /// token stays absent, and a payload from a producer that predates the
1818 /// field still deserializes (`serde(default)`).
1819 #[test]
1820 fn turn_started_submission_id_is_additive_and_default_absent() {
1821 let msg = EventMsg::TurnStarted {
1822 thread_id: ThreadId::new(),
1823 session_id: SessionId::new(),
1824 turn_id: "turn-1".into(),
1825 created_at: DateTime::<Utc>::from_timestamp(1, 0).unwrap(),
1826 route: None,
1827 submission_id: Some("sub-host-1".into()),
1828 };
1829 let json = serde_json::to_string(&msg).unwrap();
1830 assert!(
1831 json.contains(r#""submission_id":"sub-host-1""#),
1832 "a host-stamped token must be serialized: {json}"
1833 );
1834 let back: EventMsg = serde_json::from_str(&json).unwrap();
1835 assert_eq!(back, msg);
1836
1837 let none = EventMsg::TurnStarted {
1838 thread_id: ThreadId::new(),
1839 session_id: SessionId::new(),
1840 turn_id: "turn-2".into(),
1841 created_at: DateTime::<Utc>::from_timestamp(2, 0).unwrap(),
1842 route: None,
1843 submission_id: None,
1844 };
1845 let value = serde_json::to_value(&none).unwrap();
1846 assert!(
1847 value.get("submission_id").is_none(),
1848 "a self-started turn's None token must stay absent on the wire: {value}"
1849 );
1850 // An older producer that predates the field: the absent key defaults.
1851 let back: EventMsg = serde_json::from_value(value).unwrap();
1852 assert_eq!(back, none);
1853 }
1854 }
1855
1855 lines RUST