返回 CodeWhale
protocol_parity.rs
根目录 / crates / engine / src / core / protocol_parity.rs
1 //! Compile-enforced parity between the engine's internal `Op` / `Event` and
2 //! the protocol's `Op` / `EventMsg` (core/protocol extraction spec, Phase A1).
3 //!
4 //! Every function here is one exhaustive `match` with **no wildcard arm**.
5 //! Adding an engine `Event` or `Op` variant without a protocol twin fails to
6 //! compile right here — that is the `protocol_covers_engine_events` /
7 //! `protocol_covers_engine_ops` guard from spec §7. The `#[cfg(any(test, feature = "test-support"))]`
8 //! block below only proves the projections agree with the protocol's own
9 //! wire-tag tables and that this file keeps its no-wildcard discipline.
10 //!
11 //! The reverse direction (protocol `Op` -> engine `Op`) is not total — engine
12 //! ops carry resolved routes, reply channels, and hook executors that the
13 //! host must supply — so it lands with the engine handle in Phase C/D, not
14 //! here.
15 //!
16 //! The foreground pet observer consumes the event projection, retaining only
17 //! lifecycle metadata. Other projections remain compile-time parity guards.
18
19 use std::collections::BTreeMap;
20
21 use codewhale_protocol::event_msg as wire;
22 use codewhale_protocol::ids::{SessionId, ThreadId};
23 use codewhale_protocol::op as wire_op;
24 use serde::Serialize;
25 use serde_json::Value;
26
27 use crate::agent_roster::{AgentRosterRow, RosterState};
28 use crate::compaction::CompactionConfig;
29 use crate::core::engine::preview::PreviewUnresolved;
30 use crate::core::events::{
31 Event, RouteBillingEnvelope, ToolGate, ToolGateVerdict, TurnOutcomeStatus, TurnRoute,
32 };
33 use crate::core::ops::Op;
34 use crate::cost_status::RouteBillingMode;
35 use crate::mcp::{McpManagerSnapshot, McpServerCapabilityMetadata};
36 use crate::model_profile::SupportState;
37 use crate::route_billing::RouteProduct;
38 use crate::tools::spec::ToolError;
39 use crate::tools::subagent::AgentWorkerStatus;
40 use crate::tools::user_input::UserInputRequest;
41 use codewhale_config::AppMode;
42 use codewhale_config::ProviderKind;
43 use codewhale_execpolicy::ApprovalMode;
44 use codewhale_models::Usage;
45 use codewhale_protocol::ResponseChannel;
46
47 /// Routing ids the engine does not carry on each event; the emitter supplies
48 /// them once per session.
49 #[derive(Debug, Clone)]
50 pub struct ProtocolIds {
51 pub thread_id: ThreadId,
52 pub session_id: SessionId,
53 }
54
55 fn to_value<T: Serialize>(value: &T) -> Value {
56 serde_json::to_value(value).unwrap_or(Value::Null)
57 }
58
59 fn count(value: usize) -> u64 {
60 u64::try_from(value).unwrap_or(u64::MAX)
61 }
62
63 /// Lossless mode label; round-trips through `AppMode::parse`.
64 #[must_use]
65 pub fn app_mode_str(mode: AppMode) -> &'static str {
66 match mode {
67 AppMode::Agent => "agent",
68 AppMode::Plan => "plan",
69 }
70 }
71
72 #[must_use]
73 pub fn approval_mode_str(mode: ApprovalMode) -> &'static str {
74 match mode {
75 ApprovalMode::Auto => "auto",
76 ApprovalMode::Bypass => "bypass",
77 ApprovalMode::Suggest => "suggest",
78 ApprovalMode::AcceptEdits => "accept_edits",
79 ApprovalMode::Never => "never",
80 }
81 }
82
83 #[must_use]
84 pub fn worker_status_str(status: AgentWorkerStatus) -> &'static str {
85 match status {
86 AgentWorkerStatus::Queued => "queued",
87 AgentWorkerStatus::Starting => "starting",
88 AgentWorkerStatus::Running => "running",
89 AgentWorkerStatus::WaitingForUser => "waiting_for_user",
90 AgentWorkerStatus::ModelWait => "model_wait",
91 AgentWorkerStatus::RunningTool => "running_tool",
92 AgentWorkerStatus::Completed => "completed",
93 AgentWorkerStatus::Failed => "failed",
94 AgentWorkerStatus::Cancelled => "cancelled",
95 AgentWorkerStatus::Interrupted => "interrupted",
96 }
97 }
98
99 fn roster_state_str(state: RosterState) -> &'static str {
100 match state {
101 RosterState::Running => "running",
102 RosterState::Waiting => "waiting",
103 RosterState::Parked => "parked",
104 RosterState::Done => "done",
105 RosterState::Failed => "failed",
106 RosterState::Cancelled => "cancelled",
107 }
108 }
109
110 fn billing_mode_str(mode: RouteBillingMode) -> &'static str {
111 match mode {
112 RouteBillingMode::Metered => "metered",
113 RouteBillingMode::Subscription => "subscription",
114 RouteBillingMode::Local => "local",
115 RouteBillingMode::Unknown => "unknown",
116 }
117 }
118
119 fn support_state_str(state: SupportState) -> &'static str {
120 match state {
121 SupportState::Supported => "supported",
122 SupportState::Unsupported => "unsupported",
123 SupportState::Unknown => "unknown",
124 }
125 }
126
127 fn capability_metadata_str(metadata: McpServerCapabilityMetadata) -> &'static str {
128 match metadata {
129 McpServerCapabilityMetadata::Advertised(_) => "advertised",
130 McpServerCapabilityMetadata::LegacyFallback => "legacy_fallback",
131 McpServerCapabilityMetadata::NotObserved => "not_observed",
132 }
133 }
134
135 fn provider_str(provider: ProviderKind) -> String {
136 provider.as_str().to_string()
137 }
138
139 fn usage_to_wire(usage: &Usage) -> wire::TokenUsage {
140 wire::TokenUsage {
141 input_tokens: usage.input_tokens,
142 output_tokens: usage.output_tokens,
143 prompt_cache_hit_tokens: usage.prompt_cache_hit_tokens,
144 prompt_cache_miss_tokens: usage.prompt_cache_miss_tokens,
145 prompt_cache_write_tokens: usage.prompt_cache_write_tokens,
146 reasoning_tokens: usage.reasoning_tokens,
147 reasoning_replay_tokens: usage.reasoning_replay_tokens,
148 code_execution_requests: usage
149 .server_tool_use
150 .as_ref()
151 .and_then(|server| server.code_execution_requests),
152 tool_search_requests: usage
153 .server_tool_use
154 .as_ref()
155 .and_then(|server| server.tool_search_requests),
156 }
157 }
158
159 fn route_product_to_wire(product: RouteProduct) -> wire::RouteProduct {
160 match product {
161 RouteProduct::Unproven => wire::RouteProduct::Unproven,
162 RouteProduct::Subscription(label) => wire::RouteProduct::Subscription {
163 label: label.to_string(),
164 },
165 RouteProduct::Metered => wire::RouteProduct::Metered,
166 }
167 }
168
169 fn billing_to_wire(billing: &RouteBillingEnvelope) -> wire::RouteBillingEnvelope {
170 wire::RouteBillingEnvelope {
171 openrouter_vendor: billing
172 .openrouter_vendor
173 .as_deref()
174 .map(codewhale_runtime::safe_label::sanitize_persisted_route_label),
175 billing_surface: billing.billing_surface.clone(),
176 endpoint_fingerprint: billing.endpoint_fingerprint.clone(),
177 provider_live_pricing: billing
178 .provider_live_pricing
179 .as_ref()
180 .map(to_value)
181 .filter(|v| !v.is_null()),
182 billing_mode: billing_mode_str(billing.billing_mode).to_string(),
183 dispatched_at: billing.dispatched_at,
184 }
185 }
186
187 fn route_to_wire(route: &TurnRoute) -> wire::TurnRoute {
188 wire::TurnRoute {
189 provider: provider_str(route.provider),
190 provider_identity: route.provider_identity.clone(),
191 model: route.model.clone(),
192 auto_model: route.auto_model,
193 receipt: route
194 .receipt
195 .as_ref()
196 .map(|receipt| wire::TurnRouteReceipt {
197 provider: provider_str(receipt.provider()),
198 provider_identity: receipt.provider_identity().to_string(),
199 wire_model: receipt.wire_model().to_string(),
200 endpoint_identity: receipt.endpoint_identity().to_string(),
201 credential_generation_present: !receipt.credential_generation().is_empty(),
202 }),
203 billing: route.billing.as_ref().map(billing_to_wire),
204 base_url: route.base_url.clone(),
205 billing_product: route_product_to_wire(route.billing_product),
206 }
207 }
208
209 fn tool_error_to_wire(error: &ToolError) -> wire::ToolCallError {
210 match error {
211 ToolError::InvalidInput { message } => wire::ToolCallError::InvalidInput {
212 message: message.clone(),
213 },
214 ToolError::MissingField { field } => wire::ToolCallError::MissingField {
215 field: field.clone(),
216 },
217 ToolError::PathEscape { path } => wire::ToolCallError::PathEscape { path: path.clone() },
218 ToolError::ExecutionFailed { message, .. } => wire::ToolCallError::ExecutionFailed {
219 message: message.clone(),
220 },
221 ToolError::Timeout { seconds } => wire::ToolCallError::Timeout { seconds: *seconds },
222 ToolError::Cancelled { message } => wire::ToolCallError::Cancelled {
223 message: message.clone(),
224 },
225 ToolError::NotAvailable { message } => wire::ToolCallError::NotAvailable {
226 message: message.clone(),
227 },
228 ToolError::PermissionDenied { message } => wire::ToolCallError::PermissionDenied {
229 message: message.clone(),
230 },
231 }
232 }
233
234 fn gate_to_wire(gate: ToolGate) -> wire::ToolGate {
235 match gate {
236 ToolGate::AutoReviewDeterministic => wire::ToolGate::AutoReviewDeterministic,
237 ToolGate::AutoReviewGuardian => wire::ToolGate::AutoReviewGuardian,
238 }
239 }
240
241 fn verdict_to_wire(verdict: ToolGateVerdict) -> wire::ToolGateVerdict {
242 match verdict {
243 ToolGateVerdict::Allowed => wire::ToolGateVerdict::Allowed,
244 ToolGateVerdict::Denied => wire::ToolGateVerdict::Denied,
245 ToolGateVerdict::Unavailable => wire::ToolGateVerdict::Unavailable,
246 }
247 }
248
249 fn outcome_status_to_wire(status: TurnOutcomeStatus) -> wire::TurnOutcomeStatus {
250 match status {
251 TurnOutcomeStatus::Completed => wire::TurnOutcomeStatus::Completed,
252 TurnOutcomeStatus::Interrupted => wire::TurnOutcomeStatus::Interrupted,
253 TurnOutcomeStatus::Failed => wire::TurnOutcomeStatus::Failed,
254 }
255 }
256
257 fn mcp_snapshot_to_wire(snapshot: &McpManagerSnapshot) -> wire::McpManagerSnapshot {
258 let item = |item: &crate::mcp::McpDiscoveredItem| wire::McpDiscoveredItem {
259 name: item.name.clone(),
260 model_name: item.model_name.clone(),
261 description: item.description.clone(),
262 };
263 wire::McpManagerSnapshot {
264 config_path: snapshot.config_path.clone(),
265 config_exists: snapshot.config_exists,
266 reload_required: snapshot.reload_required,
267 servers: snapshot
268 .servers
269 .iter()
270 .map(|server| wire::McpServerSnapshot {
271 name: server.name.clone(),
272 enabled: server.enabled,
273 required: server.required,
274 transport: server.transport.clone(),
275 command_or_url: redacted_command_or_url(&server.command_or_url),
276 connect_timeout: server.connect_timeout,
277 execute_timeout: server.execute_timeout,
278 read_timeout: server.read_timeout,
279 connected: server.connected,
280 error: server.error.clone(),
281 capability_metadata: capability_metadata_str(server.capability_metadata)
282 .to_string(),
283 tools: server.tools.iter().map(item).collect(),
284 resources: server.resources.iter().map(item).collect(),
285 prompts: server.prompts.iter().map(item).collect(),
286 })
287 .collect(),
288 }
289 }
290
291 /// Sanitize an MCP server's configured target before it goes on the wire.
292 ///
293 /// `command_or_url` is the raw configuration: either the configured URL, which
294 /// can carry userinfo (`https://user:token@host`) or query credentials, or a
295 /// stdio command line built as `command + " " + args.join(" ")`, whose args can
296 /// carry a token. That is acceptable in the local picker, where the only reader
297 /// is the person who configured it. This projection is not local -- it feeds
298 /// `EventMsg::McpSessionBoot`, which every SSE and stream-JSON consumer
299 /// receives and any frame-retaining log keeps.
300 ///
301 /// URLs reuse the existing masking in `codewhale_sanitize::sanitize::redact_url_for_display`. Stdio
302 /// keeps the program name and elides the arguments, because a secret there can
303 /// be positional and is not reliably recognizable by key.
304 fn redacted_command_or_url(raw: &str) -> String {
305 // No `match` here on purpose: `projections_have_no_wildcard_arms` scans
306 // this whole file for wildcard arms, and a `_ =>` would trip it even in a
307 // helper that projects no engine variant.
308 let trimmed = raw.trim();
309 // A URL never contains whitespace; an argv line does. `://` alone is not
310 // enough to route here: `redact_url_for_display` returns its input
311 // verbatim when `Url::parse` fails, so a stdio command that merely
312 // mentions a URL — `docker run -e TOKEN=… img --url https://…` — would
313 // reach the wire with its positional secret intact.
314 if !trimmed.is_empty() && !trimmed.contains(char::is_whitespace) && trimmed.contains("://") {
315 return codewhale_sanitize::sanitize::redact_url_for_display(trimmed);
316 }
317 if let Some((program, rest)) = trimmed.split_once(char::is_whitespace)
318 && !rest.trim().is_empty()
319 {
320 return format!("{program} …");
321 }
322 trimmed.to_string()
323 }
324
325 fn roster_row_to_wire(row: &AgentRosterRow) -> wire::AgentRosterRow {
326 wire::AgentRosterRow {
327 worker_id: row.worker_id.clone(),
328 display_name: row.display_name.clone(),
329 model: row.model.clone(),
330 state: roster_state_str(row.state).to_string(),
331 status: worker_status_str(row.status).to_string(),
332 activity: row.activity.clone(),
333 millis: row.millis,
334 input_tokens: row.input_tokens,
335 output_tokens: row.output_tokens,
336 cost_microusd: row.cost_microusd,
337 steps_taken: row.steps_taken,
338 parent_run_id: row.parent_run_id.clone(),
339 run_id: row.run_id.clone(),
340 }
341 }
342
343 fn user_input_to_wire(request: &UserInputRequest) -> wire::UserInputRequest {
344 wire::UserInputRequest {
345 require_typed_answers: request.require_typed_answers,
346 questions: request
347 .questions
348 .iter()
349 .map(|question| codewhale_protocol::UserInputQuestionEvent {
350 header: question.header.clone(),
351 id: question.id.clone(),
352 question: question.question.clone(),
353 detail: question.detail.clone(),
354 intent: question.intent.as_ref().map(|intent| match intent {
355 crate::tools::user_input::UserInputIntent::PlanReview { approve, call_id } => {
356 codewhale_protocol::UserInputIntentEvent::PlanReview {
357 approve: approve.clone(),
358 call_id: call_id.clone(),
359 }
360 }
361 }),
362 options: question
363 .options
364 .iter()
365 .map(|option| codewhale_protocol::UserInputOptionEvent {
366 label: option.label.clone(),
367 description: option.description.clone(),
368 })
369 .collect(),
370 allow_free_text: question.allow_free_text,
371 multi_select: question.multi_select,
372 })
373 .collect(),
374 }
375 }
376
377 fn compaction_to_wire(config: &CompactionConfig) -> wire_op::CompactionPolicy {
378 wire_op::CompactionPolicy {
379 enabled: config.enabled,
380 token_threshold: count(config.token_threshold),
381 model: config.model.clone(),
382 image_input: support_state_str(config.image_input).to_string(),
383 effective_context_window: config.effective_context_window,
384 cache_summary: config.cache_summary,
385 focus: config.focus.clone(),
386 runtime_cost_owner: config.runtime_cost_owner.clone(),
387 workspace: config.workspace.clone(),
388 }
389 }
390
391 /// Project the engine's per-turn authority onto the wire `TurnSpec`. Host-only
392 /// fields (`initial_routed_usage`, `hook_executor`) and resolved routes are
393 /// stripped; only their non-secret receipts cross.
394 fn turn_spec_to_wire(spec: &crate::core::ops::TurnSpec) -> wire_op::TurnSpec {
395 // `spec.submission_id` is deliberately not projected: the token is
396 // host-process-local by design and the wire op has no correlation twin,
397 // so wire submitters observe `TurnStarted.submission_id` always absent
398 // and cannot correlate submissions on that channel.
399 wire_op::TurnSpec {
400 profile_constitution: spec
401 .profile_constitution
402 .as_ref()
403 .map(|snapshot| serde_json::json!(snapshot)),
404 max_output_tokens: spec.max_output_tokens,
405 content: spec.content.clone(),
406 images: spec.images.clone(),
407 mode: app_mode_str(spec.mode).to_string(),
408 model: Some(spec.route.model.clone()),
409 model_provider: Some(spec.route.identity.key.to_string()),
410 allowed_tools: spec.allowed_tools.clone(),
411 dynamic_tools: spec.dynamic_tools.clone(),
412 provenance: spec.provenance.as_str().to_string(),
413 compaction: Some(Box::new(compaction_to_wire(&spec.compaction))),
414 goal_objective: spec.goal_objective.clone(),
415 goal_token_budget: spec.goal_token_budget,
416 goal_status: spec.goal_status.as_str().to_string(),
417 reasoning_effort: spec.reasoning_effort.clone(),
418 reasoning_effort_auto: spec.reasoning_effort_auto,
419 auto_model: spec.auto_model,
420 allow_shell: spec.allow_shell,
421 trust_mode: spec.trust_mode,
422 auto_approve: spec.auto_approve,
423 approval_mode: approval_mode_str(spec.approval_mode).to_string(),
424 translation_enabled: spec.translation_enabled,
425 verbosity: spec.verbosity.clone(),
426 }
427 }
428
429 fn preview_unresolved_str(unresolved: &PreviewUnresolved) -> String {
430 match unresolved {
431 PreviewUnresolved::AutoRouteNeedsPrompt => "auto_route_needs_prompt".to_string(),
432 PreviewUnresolved::AutoRouteClassificationNotExecuted => {
433 "auto_route_classification_not_executed".to_string()
434 }
435 PreviewUnresolved::NoPrompt => "no_prompt".to_string(),
436 PreviewUnresolved::PlanFailed(error) => format!("plan_failed: {error}"),
437 PreviewUnresolved::MessageSubmitHooksConfigured => {
438 "message_submit_hooks_configured".to_string()
439 }
440 PreviewUnresolved::PromptResolutionFailed(error) => {
441 format!("prompt_resolution_failed: {error}")
442 }
443 }
444 }
445
446 /// Project one engine event onto the protocol. Exhaustive: a new engine
447 /// variant without a protocol twin does not compile.
448 #[must_use]
449 pub fn event_to_protocol(event: &Event, ids: &ProtocolIds) -> wire::EventMsg {
450 let thread_id = ids.thread_id.clone();
451 let session_id = ids.session_id.clone();
452 match event {
453 Event::ToolProjectionWarning {
454 provider,
455 omitted_tool_names,
456 omitted_tool_count,
457 } => wire::EventMsg::ToolProjectionWarning {
458 thread_id,
459 session_id,
460 provider: provider.clone(),
461 omitted_tool_names: omitted_tool_names.clone(),
462 omitted_tool_count: count(*omitted_tool_count),
463 },
464 Event::RequestImageWindow {
465 provider,
466 model,
467 total,
468 elided,
469 cap,
470 cap_source,
471 message,
472 } => wire::EventMsg::RequestImageWindow {
473 thread_id,
474 session_id,
475 provider: provider.clone(),
476 model: model.clone(),
477 total: count(*total),
478 elided: count(*elided),
479 cap: count(*cap),
480 cap_source: cap_source.clone(),
481 message: message.clone(),
482 },
483 Event::SnapshotsDisabled { workspace, reason } => wire::EventMsg::SnapshotsDisabled {
484 thread_id,
485 session_id,
486 workspace: workspace.clone(),
487 reason: reason.clone(),
488 },
489 Event::MessageStarted { index } => wire::EventMsg::MessageStarted {
490 thread_id,
491 session_id,
492 index: count(*index),
493 },
494 Event::MessageDelta { index, content } => wire::EventMsg::ResponseDelta {
495 thread_id,
496 session_id,
497 index: count(*index),
498 delta: content.clone(),
499 channel: ResponseChannel::Text,
500 },
501 Event::MessageComplete { index } => wire::EventMsg::MessageComplete {
502 thread_id,
503 session_id,
504 index: count(*index),
505 },
506 Event::ThinkingStarted { index } => wire::EventMsg::ThinkingStarted {
507 thread_id,
508 session_id,
509 index: count(*index),
510 },
511 Event::ThinkingDelta { index, content } => wire::EventMsg::ResponseDelta {
512 thread_id,
513 session_id,
514 index: count(*index),
515 delta: content.clone(),
516 channel: ResponseChannel::Reasoning,
517 },
518 Event::ThinkingComplete { index } => wire::EventMsg::ThinkingComplete {
519 thread_id,
520 session_id,
521 index: count(*index),
522 },
523 Event::ToolExecutionStarted { id } => wire::EventMsg::ToolExecutionStarted {
524 thread_id,
525 session_id,
526 tool_call_id: id.clone(),
527 },
528 Event::ToolResultContent { id, blocks } => wire::EventMsg::ToolResultContent {
529 thread_id,
530 session_id,
531 tool_call_id: id.clone(),
532 blocks: to_value(blocks),
533 },
534 Event::ToolCallStarted {
535 id, name, input, ..
536 } => wire::EventMsg::ToolCallStarted {
537 thread_id,
538 session_id,
539 tool_call_id: id.clone(),
540 tool_name: name.clone(),
541 input: input.clone(),
542 },
543 Event::ToolCallHeartbeat => wire::EventMsg::ToolCallHeartbeat {
544 thread_id,
545 session_id,
546 },
547 Event::ToolCallComplete {
548 id, name, result, ..
549 } => wire::EventMsg::ToolCallComplete {
550 thread_id,
551 session_id,
552 tool_call_id: id.clone(),
553 tool_name: name.clone(),
554 result: match result {
555 Ok(result) => wire::ToolCallOutcome::Ok {
556 content: result.content.clone(),
557 success: result.success,
558 metadata: result.metadata.clone(),
559 },
560 Err(error) => wire::ToolCallOutcome::Err {
561 error: tool_error_to_wire(error),
562 },
563 },
564 },
565 Event::OperationActivityStarted {
566 span_id,
567 activity_kind,
568 action_id,
569 } => wire::EventMsg::OperationActivityStarted {
570 thread_id,
571 session_id,
572 span_id: span_id.clone(),
573 activity_kind: *activity_kind,
574 action_id: action_id.clone(),
575 },
576 Event::OperationActivityCompleted {
577 span_id,
578 activity_kind,
579 action_id,
580 outcome,
581 } => wire::EventMsg::OperationActivityCompleted {
582 thread_id,
583 session_id,
584 span_id: span_id.clone(),
585 activity_kind: *activity_kind,
586 action_id: action_id.clone(),
587 outcome: *outcome,
588 },
589 Event::TurnStarted {
590 turn_id,
591 created_at,
592 route,
593 submission_id,
594 ..
595 } => wire::EventMsg::TurnStarted {
596 thread_id,
597 session_id,
598 turn_id: turn_id.clone(),
599 created_at: *created_at,
600 route: route.as_ref().map(route_to_wire),
601 submission_id: submission_id.clone(),
602 },
603 Event::ToolRequestSnapshot { snapshot } => wire::EventMsg::ToolRequestSnapshot {
604 thread_id,
605 session_id,
606 snapshot: to_value(snapshot),
607 },
608 Event::WorkspaceSnapshotTaken { snapshot } => wire::EventMsg::WorkspaceSnapshotTaken {
609 thread_id,
610 session_id,
611 snapshot: to_value(snapshot),
612 },
613 Event::RouteDispatched { turn_id, route } => wire::EventMsg::RouteDispatched {
614 thread_id,
615 session_id,
616 turn_id: turn_id.clone(),
617 route: route_to_wire(route),
618 },
619 Event::TurnComplete {
620 turn_id,
621 submission_id,
622 compaction_id,
623 usage,
624 parent_route_usage,
625 routed_usage_dropped_records,
626 status,
627 error,
628 tool_catalog,
629 base_url,
630 ..
631 } => wire::EventMsg::TurnComplete {
632 thread_id,
633 session_id,
634 turn_id: turn_id.clone(),
635 submission_id: submission_id.clone(),
636 compaction_id: compaction_id.clone(),
637 status: outcome_status_to_wire(*status),
638 error: error.clone(),
639 usage: usage_to_wire(usage),
640 parent_route_usage: Some(usage_to_wire(parent_route_usage)),
641 routed_usage_dropped_records: *routed_usage_dropped_records,
642 tool_catalog: tool_catalog
643 .as_ref()
644 .map(|tools| tools.iter().map(to_value).collect()),
645 base_url: base_url.clone(),
646 },
647 Event::ProviderRequestReceipt { receipt } => wire::EventMsg::ProviderRequestReceipt {
648 thread_id,
649 session_id,
650 receipt: receipt.clone(),
651 },
652 Event::TurnUsage {
653 max_output_tokens,
654 usage,
655 duration_ms,
656 first_token_ms,
657 request_ms,
658 ..
659 } => wire::EventMsg::TurnUsage {
660 max_output_tokens: *max_output_tokens,
661 thread_id,
662 session_id,
663 usage: usage_to_wire(usage),
664 duration_ms: *duration_ms,
665 first_token_ms: *first_token_ms,
666 request_ms: *request_ms,
667 },
668 Event::RoutedTurnUsage {
669 usage,
670 duration_ms,
671 first_token_ms,
672 request_ms,
673 } => wire::EventMsg::RoutedTurnUsage {
674 thread_id,
675 session_id,
676 usage: usage_to_wire(usage),
677 duration_ms: *duration_ms,
678 first_token_ms: *first_token_ms,
679 request_ms: *request_ms,
680 },
681 Event::GoalUpdated { snapshot } => wire::EventMsg::GoalUpdated {
682 thread_id,
683 session_id,
684 snapshot: to_value(snapshot),
685 },
686 Event::GoalContinuationWaiting { delay_seconds } => {
687 wire::EventMsg::GoalContinuationWaiting {
688 thread_id,
689 session_id,
690 delay_seconds: *delay_seconds,
691 }
692 }
693 Event::GoalContinuationWaitEnded { interrupted } => {
694 wire::EventMsg::GoalContinuationWaitEnded {
695 thread_id,
696 session_id,
697 interrupted: *interrupted,
698 }
699 }
700 Event::CompactionStarted {
701 id, auto, message, ..
702 } => wire::EventMsg::CompactionStarted {
703 thread_id,
704 session_id,
705 id: id.clone(),
706 auto: *auto,
707 message: message.clone(),
708 },
709 Event::CompactionCompleted {
710 id,
711 auto,
712 message,
713 messages_before,
714 messages_after,
715 summary_prompt,
716 post_input_tokens,
717 } => wire::EventMsg::CompactionCompleted {
718 thread_id,
719 session_id,
720 id: id.clone(),
721 auto: *auto,
722 message: message.clone(),
723 messages_before: messages_before.map(count),
724 messages_after: messages_after.map(count),
725 summary_prompt: summary_prompt.clone(),
726 post_input_tokens: *post_input_tokens,
727 },
728 Event::CompactionCancelled { id, auto, message } => wire::EventMsg::CompactionCancelled {
729 thread_id,
730 session_id,
731 id: id.clone(),
732 auto: *auto,
733 message: message.clone(),
734 },
735 Event::PurgeStarted { message } => wire::EventMsg::PurgeStarted {
736 thread_id,
737 session_id,
738 message: message.clone(),
739 },
740 Event::PurgeCompleted {
741 messages_before,
742 messages_after,
743 removed_count,
744 replaced_count,
745 message,
746 } => wire::EventMsg::PurgeCompleted {
747 thread_id,
748 session_id,
749 messages_before: count(*messages_before),
750 messages_after: count(*messages_after),
751 removed_count: count(*removed_count),
752 replaced_count: count(*replaced_count),
753 message: message.clone(),
754 },
755 Event::PurgeFailed { message } => wire::EventMsg::PurgeFailed {
756 thread_id,
757 session_id,
758 message: message.clone(),
759 },
760 Event::CompactionFailed { id, auto, message } => wire::EventMsg::CompactionFailed {
761 thread_id,
762 session_id,
763 id: id.clone(),
764 auto: *auto,
765 message: message.clone(),
766 },
767 Event::AgentSpawned {
768 owner_session_id,
769 id,
770 prompt,
771 worker_status,
772 parent_run_id,
773 spawn_depth,
774 model,
775 route_source,
776 display_name,
777 } => wire::EventMsg::AgentSpawned {
778 thread_id,
779 session_id,
780 owner_session_id: owner_session_id.clone(),
781 id: id.clone(),
782 prompt: prompt.clone(),
783 worker_status: worker_status.map(|status| worker_status_str(status).to_string()),
784 parent_run_id: parent_run_id.clone(),
785 spawn_depth: *spawn_depth,
786 model: model.clone(),
787 route_source: route_source.clone(),
788 display_name: display_name.clone(),
789 },
790 Event::AgentProgress {
791 owner_session_id,
792 id,
793 status,
794 activity,
795 parent_run_id,
796 spawn_depth,
797 } => wire::EventMsg::AgentProgress {
798 thread_id,
799 session_id,
800 owner_session_id: owner_session_id.clone(),
801 id: id.clone(),
802 status: status.clone(),
803 activity: wire::AgentProgressActivity {
804 worker_status: worker_status_str(activity.worker_status).to_string(),
805 step: activity.step,
806 tool_name: activity.tool_name.clone(),
807 },
808 parent_run_id: parent_run_id.clone(),
809 spawn_depth: *spawn_depth,
810 },
811 Event::AgentComplete {
812 limit_kind,
813 owner_session_id,
814 id,
815 result,
816 outcome,
817 parent_run_id,
818 spawn_depth,
819 continuable,
820 // Child usage stays off the wire: no protocol client consumes
821 // it, and metrics reads the persisted runtime payload (#6315).
822 usage: _,
823 display_name,
824 } => wire::EventMsg::AgentComplete {
825 limit_kind: *limit_kind,
826 thread_id,
827 session_id,
828 owner_session_id: owner_session_id.clone(),
829 id: id.clone(),
830 result: result.clone(),
831 worker_status: outcome
832 .as_ref()
833 .map(|status| crate::tools::subagent::subagent_status_name(status).to_string()),
834 parent_run_id: parent_run_id.clone(),
835 spawn_depth: *spawn_depth,
836 continuable: *continuable,
837 display_name: display_name.clone(),
838 },
839 Event::SubAgentFollowUp {
840 owner_session_id,
841 agent_id,
842 outcome,
843 } => wire::EventMsg::SubAgentFollowUp {
844 thread_id,
845 session_id,
846 owner_session_id: owner_session_id.clone(),
847 agent_id: agent_id.clone(),
848 outcome: match outcome {
849 Ok(outcome) => wire::SubAgentFollowUpOutcome::Ok {
850 agent_id: outcome.agent_id.clone(),
851 target_agent_id: outcome.target_agent_id.clone(),
852 delivered: outcome.delivered,
853 resumed: outcome.resumed,
854 note: outcome.note.clone(),
855 },
856 Err(reason) => wire::SubAgentFollowUpOutcome::Err {
857 reason: reason.clone(),
858 },
859 },
860 },
861 Event::AgentList {
862 owner_session_id,
863 agents,
864 coordination,
865 queued_follow_ups,
866 roster,
867 } => wire::EventMsg::AgentList {
868 thread_id,
869 session_id,
870 owner_session_id: owner_session_id.clone(),
871 agents: agents.iter().map(to_value).collect(),
872 coordination: to_value(coordination),
873 queued_follow_ups: queued_follow_ups
874 .iter()
875 .map(|(agent_id, queued)| (agent_id.clone(), count(*queued)))
876 .collect::<BTreeMap<_, _>>(),
877 roster: roster.iter().map(roster_row_to_wire).collect(),
878 },
879 Event::SubAgentMailbox {
880 owner_session_id,
881 turn_id,
882 seq,
883 message,
884 } => wire::EventMsg::SubAgentMailbox {
885 thread_id,
886 session_id,
887 owner_session_id: owner_session_id.clone(),
888 turn_id: turn_id.clone(),
889 seq: *seq,
890 message: to_value(message),
891 },
892 Event::WorkflowUi {
893 owner_session_id,
894 run_id,
895 event,
896 } => wire::EventMsg::WorkflowUi {
897 thread_id,
898 session_id,
899 owner_session_id: owner_session_id.clone(),
900 run_id: run_id.clone(),
901 ui_event: event.clone(),
902 },
903 Event::Error {
904 envelope,
905 recoverable,
906 } => wire::EventMsg::Error {
907 thread_id,
908 session_id,
909 category: envelope.category.to_string(),
910 severity: envelope.severity.to_string(),
911 recoverable: *recoverable,
912 code: envelope.code.clone(),
913 message: envelope.message.clone(),
914 },
915 Event::Status { message } => wire::EventMsg::Status {
916 thread_id,
917 session_id,
918 message: message.clone(),
919 },
920 Event::McpSessionBoot {
921 generation,
922 snapshot,
923 connecting,
924 finished,
925 } => wire::EventMsg::McpSessionBoot {
926 thread_id,
927 session_id,
928 generation: *generation,
929 snapshot: mcp_snapshot_to_wire(snapshot),
930 connecting: connecting.clone(),
931 finished: *finished,
932 },
933 Event::RequestManifestReady { rendered } => wire::EventMsg::RequestManifestReady {
934 thread_id,
935 session_id,
936 rendered: rendered.clone(),
937 },
938 // The in-process `ack` notifier is an engine handle, not wire data.
939 Event::PauseEvents { ack: _ } => wire::EventMsg::PauseEvents {
940 thread_id,
941 session_id,
942 },
943 Event::ResumeEvents => wire::EventMsg::ResumeEvents {
944 thread_id,
945 session_id,
946 },
947 Event::ApprovalRequired {
948 publication: _,
949 id,
950 tool_name,
951 description,
952 input,
953 approval_key,
954 approval_grouping_key,
955 intent_summary,
956 approval_force_prompt,
957 } => wire::EventMsg::ApprovalRequired {
958 thread_id,
959 session_id,
960 id: id.clone(),
961 tool_name: tool_name.clone(),
962 description: description.clone(),
963 input: input.clone(),
964 approval_key: approval_key.clone(),
965 approval_grouping_key: approval_grouping_key.clone(),
966 intent_summary: intent_summary.clone(),
967 approval_force_prompt: *approval_force_prompt,
968 },
969 Event::ApprovalWithdrawn { id } => wire::EventMsg::ApprovalWithdrawn {
970 thread_id,
971 session_id,
972 id: id.clone(),
973 },
974 Event::UserInputRequired { id, request } => wire::EventMsg::UserInputRequired {
975 thread_id,
976 session_id,
977 id: id.clone(),
978 request: user_input_to_wire(request),
979 },
980 Event::UserInputClosed { id, outcome } => wire::EventMsg::UserInputClosed {
981 thread_id,
982 session_id,
983 id: id.clone(),
984 outcome: match outcome {
985 crate::core::events::UserInputClosedOutcome::Answered => {
986 wire::UserInputClosedOutcome::Answered
987 }
988 crate::core::events::UserInputClosedOutcome::Cancelled => {
989 wire::UserInputClosedOutcome::Cancelled
990 }
991 crate::core::events::UserInputClosedOutcome::TimedOut => {
992 wire::UserInputClosedOutcome::TimedOut
993 }
994 crate::core::events::UserInputClosedOutcome::Unavailable => {
995 wire::UserInputClosedOutcome::Unavailable
996 }
997 },
998 },
999 Event::SessionUpdated {
1000 source: _,
1001 checkpoint: _,
1002 session_id: engine_session_id,
1003 messages,
1004 system_prompt,
1005 instruction_assembly,
1006 model,
1007 workspace,
1008 } => wire::EventMsg::SessionUpdated {
1009 thread_id,
1010 session_id,
1011 engine_session_id: engine_session_id.clone(),
1012 messages: messages.iter().map(to_value).collect(),
1013 system_prompt: system_prompt.as_ref().map(to_value),
1014 instruction_assembly: instruction_assembly
1015 .as_deref()
1016 .map(crate::project_context::InstructionAssembly::receipt_json),
1017 model: model.clone(),
1018 workspace: workspace.clone(),
1019 },
1020 Event::ElevationRequired {
1021 tool_id,
1022 tool_name,
1023 command,
1024 denial_reason,
1025 blocked_network,
1026 blocked_write,
1027 } => wire::EventMsg::ElevationRequired {
1028 thread_id,
1029 session_id,
1030 tool_id: tool_id.clone(),
1031 tool_name: tool_name.clone(),
1032 command: command.clone(),
1033 denial_reason: denial_reason.clone(),
1034 blocked_network: *blocked_network,
1035 blocked_write: *blocked_write,
1036 },
1037 Event::LspRepairUpdate {
1038 diagnostics_found,
1039 files,
1040 injected,
1041 } => wire::EventMsg::LspRepairUpdate {
1042 thread_id,
1043 session_id,
1044 diagnostics_found: count(*diagnostics_found),
1045 files: count(*files),
1046 injected: *injected,
1047 },
1048 Event::ToolGateDecision {
1049 agent_id,
1050 tool_id,
1051 tool_name,
1052 gate,
1053 decision,
1054 risk,
1055 reviewer_model,
1056 reason,
1057 rule,
1058 receipt_id,
1059 call_digest,
1060 action_summary,
1061 } => wire::EventMsg::ToolGateDecision {
1062 thread_id,
1063 session_id,
1064 agent_id: agent_id.clone(),
1065 tool_id: tool_id.clone(),
1066 tool_name: tool_name.clone(),
1067 gate: gate_to_wire(*gate),
1068 decision: verdict_to_wire(*decision),
1069 risk: risk.clone(),
1070 reviewer_model: reviewer_model.clone(),
1071 reason: reason.clone(),
1072 rule: rule.clone(),
1073 receipt_id: receipt_id.clone(),
1074 call_digest: call_digest.clone(),
1075 action_summary: action_summary.clone(),
1076 },
1077 Event::AutoReviewPaused {
1078 reason,
1079 approval_mode,
1080 } => wire::EventMsg::AutoReviewPaused {
1081 thread_id,
1082 session_id,
1083 reason: reason.clone(),
1084 approval_mode: approval_mode_str(*approval_mode).to_string(),
1085 },
1086 Event::AdvisoryNote {
1087 turn_id,
1088 note,
1089 tool_call_count,
1090 } => wire::EventMsg::AdvisoryNote {
1091 thread_id,
1092 session_id,
1093 turn_id: turn_id.clone(),
1094 note: note.clone(),
1095 tool_call_count: *tool_call_count,
1096 },
1097 Event::PrefixCacheChange {
1098 description,
1099 system_prompt_changed,
1100 tools_changed,
1101 stability_pct,
1102 changed,
1103 pinned_combined_hash,
1104 pin_reason,
1105 last_miss_reason,
1106 context_updates,
1107 } => wire::EventMsg::PrefixCacheChange {
1108 thread_id,
1109 session_id,
1110 description: description.clone(),
1111 system_prompt_changed: *system_prompt_changed,
1112 tools_changed: *tools_changed,
1113 stability_pct: *stability_pct,
1114 changed: *changed,
1115 pinned_combined_hash: pinned_combined_hash.clone(),
1116 pin_reason: pin_reason.clone(),
1117 last_miss_reason: last_miss_reason.clone(),
1118 context_updates: *context_updates,
1119 },
1120 Event::ConversationTitle { title } => wire::EventMsg::ConversationTitle {
1121 thread_id,
1122 session_id,
1123 title: title.clone(),
1124 },
1125 Event::ContentFilterRefusal { reason, refusal } => wire::EventMsg::ContentFilterRefusal {
1126 thread_id,
1127 session_id,
1128 reason: reason.clone(),
1129 refusal: refusal.clone(),
1130 },
1131 Event::PluginChanged {
1132 plugin,
1133 action,
1134 content_hash,
1135 decided_by,
1136 services,
1137 tools_added,
1138 tools_removed,
1139 } => wire::EventMsg::PluginChanged {
1140 thread_id,
1141 session_id,
1142 plugin: plugin.clone(),
1143 action: action.clone(),
1144 content_hash: content_hash.clone(),
1145 decided_by: decided_by.clone(),
1146 services: services.clone(),
1147 tools_added: tools_added.clone(),
1148 tools_removed: tools_removed.clone(),
1149 },
1150 }
1151 }
1152
1153 /// Project one engine op onto the protocol. Exhaustive: a new engine variant
1154 /// without a protocol twin does not compile. Reply channels, hook executors,
1155 /// and resolved clients are stripped; only their non-secret receipts cross.
1156 #[must_use]
1157 pub fn op_to_protocol(op: &Op) -> wire_op::Op {
1158 match op {
1159 Op::Review { turn, request } => wire_op::Op::Review {
1160 turn: Box::new(turn_spec_to_wire(turn)),
1161 request: request.clone(),
1162 },
1163 Op::SendMessage(spec) => wire_op::Op::SendMessage(turn_spec_to_wire(spec)),
1164 Op::ContinueGoal {
1165 dynamic_tools,
1166 engine_schedule_id,
1167 } => wire_op::Op::ContinueGoal {
1168 dynamic_tools: dynamic_tools.clone(),
1169 engine_schedule_id: *engine_schedule_id,
1170 },
1171 Op::RunShellCommand {
1172 command,
1173 mode,
1174 allow_shell,
1175 trust_mode,
1176 auto_approve,
1177 approval_mode,
1178 } => wire_op::Op::RunShellCommand {
1179 command: command.clone(),
1180 mode: app_mode_str(*mode).to_string(),
1181 allow_shell: *allow_shell,
1182 trust_mode: *trust_mode,
1183 auto_approve: *auto_approve,
1184 approval_mode: approval_mode_str(*approval_mode).to_string(),
1185 },
1186 Op::SetGoalStatus {
1187 status,
1188 clear,
1189 goal_id,
1190 } => wire_op::Op::SetGoalStatus {
1191 goal_id: goal_id.clone(),
1192 status: status.as_str().to_string(),
1193 clear: *clear,
1194 },
1195 Op::SetGoalObjective {
1196 objective,
1197 token_budget,
1198 goal_id,
1199 } => wire_op::Op::SetGoalObjective {
1200 goal_id: goal_id.clone(),
1201 objective: objective.clone(),
1202 token_budget: *token_budget,
1203 },
1204 Op::PreviewOutboundRequest {
1205 inputs,
1206 json,
1207 base_prompt_only,
1208 } => wire_op::Op::PreviewOutboundRequest {
1209 json: *json,
1210 base_prompt_only: *base_prompt_only,
1211 mode: app_mode_str(inputs.mode).to_string(),
1212 allow_shell: inputs.allow_shell,
1213 trust_mode: inputs.trust_mode,
1214 auto_approve: inputs.auto_approve,
1215 approval_mode: approval_mode_str(inputs.approval_mode).to_string(),
1216 allowed_tools: inputs.allowed_tools.clone(),
1217 dynamic_tools: inputs.dynamic_tools.clone(),
1218 provenance: inputs.provenance.as_str().to_string(),
1219 requested_model: inputs.requested_model.clone(),
1220 requested_reasoning: inputs.requested_reasoning.clone(),
1221 auto_model: inputs.auto_model,
1222 hypothetical_prompt_supplied: inputs.hypothetical_prompt_supplied,
1223 hypothetical_prompt: inputs.next_turn.as_ref().map(|turn| turn.content.clone()),
1224 unresolved: if inputs.next_turn.is_some() {
1225 None
1226 } else {
1227 Some(preview_unresolved_str(&inputs.unresolved))
1228 },
1229 },
1230 Op::ListSubAgents => wire_op::Op::ListSubAgents,
1231 Op::GetSubAgentSettlement { tx: _ } => wire_op::Op::GetSubAgentSettlement,
1232 Op::CancelSubAgent { agent_id } => wire_op::Op::CancelSubAgent {
1233 agent_id: agent_id.clone(),
1234 },
1235 Op::FollowUpSubAgent { agent_id, text } => wire_op::Op::FollowUpSubAgent {
1236 agent_id: agent_id.clone(),
1237 text: text.clone(),
1238 },
1239 Op::StartFleetMember { start, tx: _ } => wire_op::Op::StartFleetMember {
1240 member_id: start.member_id.clone(),
1241 },
1242 Op::ChangeMode {
1243 mode,
1244 allow_shell,
1245 trust_mode,
1246 auto_approve,
1247 approval_mode,
1248 configured_sandbox_mode,
1249 } => wire_op::Op::ChangeMode {
1250 mode: app_mode_str(*mode).to_string(),
1251 allow_shell: *allow_shell,
1252 trust_mode: *trust_mode,
1253 auto_approve: *auto_approve,
1254 approval_mode: approval_mode_str(*approval_mode).to_string(),
1255 configured_sandbox_mode: configured_sandbox_mode.clone(),
1256 },
1257 Op::SetModel {
1258 model,
1259 mode,
1260 route_limits,
1261 } => wire_op::Op::SetModel {
1262 model: model.clone(),
1263 mode: app_mode_str(*mode).to_string(),
1264 route_limits: route_limits.map(|limits| wire_op::RouteLimits {
1265 context_tokens: limits.context_tokens,
1266 input_tokens: limits.input_tokens,
1267 output_tokens: limits.output_tokens,
1268 }),
1269 },
1270 Op::SetRoute { route, mode } => {
1271 let route_limits = crate::route_budget::known_route_limits(route.candidate.limits());
1272 wire_op::Op::SetModel {
1273 model: route.model.clone(),
1274 mode: app_mode_str(*mode).to_string(),
1275 route_limits: route_limits.map(|limits| wire_op::RouteLimits {
1276 context_tokens: limits.context_tokens,
1277 input_tokens: limits.input_tokens,
1278 output_tokens: limits.output_tokens,
1279 }),
1280 }
1281 }
1282 Op::SetCompaction { config } => wire_op::Op::SetCompaction {
1283 config: compaction_to_wire(config),
1284 },
1285 Op::SetStreamChunkTimeout { timeout_secs } => wire_op::Op::SetStreamChunkTimeout {
1286 timeout_secs: *timeout_secs,
1287 },
1288 Op::SetAutoReviewReviewerModel { reviewer_model } => {
1289 wire_op::Op::SetAutoReviewReviewerModel {
1290 reviewer_model: reviewer_model.clone(),
1291 }
1292 }
1293 Op::SetSubagentRuntimeConfig {
1294 enabled,
1295 max_subagents,
1296 launch_concurrency,
1297 max_spawn_depth,
1298 api_timeout_secs,
1299 heartbeat_timeout_secs,
1300 } => wire_op::Op::SetSubagentRuntimeConfig {
1301 enabled: *enabled,
1302 max_subagents: count(*max_subagents),
1303 launch_concurrency: count(*launch_concurrency),
1304 max_spawn_depth: *max_spawn_depth,
1305 api_timeout_secs: *api_timeout_secs,
1306 heartbeat_timeout_secs: *heartbeat_timeout_secs,
1307 },
1308 Op::SetSearchProvider { provider } => wire_op::Op::SetSearchProvider {
1309 provider: provider.as_str().to_string(),
1310 },
1311 Op::SetFleetRoster { roster } => wire_op::Op::SetFleetRoster {
1312 member_ids: roster
1313 .members()
1314 .iter()
1315 .map(|member| member.id.clone())
1316 .collect(),
1317 exact_selection: roster.is_exact_selection(),
1318 load_error: roster.load_error().map(str::to_string),
1319 },
1320 Op::SyncSession {
1321 expected,
1322 session_id,
1323 messages,
1324 system_prompt,
1325 system_prompt_override,
1326 model,
1327 workspace,
1328 mode,
1329 agent_preset,
1330 ..
1331 } => wire_op::Op::SyncSession {
1332 expected: expected.as_ref().map(to_value),
1333 engine_session_id: session_id.clone(),
1334 messages: messages.iter().map(to_value).collect(),
1335 system_prompt: system_prompt.as_ref().map(to_value),
1336 system_prompt_override: *system_prompt_override,
1337 model: model.clone(),
1338 workspace: workspace.clone(),
1339 mode: app_mode_str(*mode).to_string(),
1340 agent_preset: agent_preset.clone(),
1341 },
1342 Op::RewindConversation {
1343 expected, messages, ..
1344 } => wire_op::Op::RewindConversation {
1345 expected: to_value(expected),
1346 messages: messages.iter().map(to_value).collect(),
1347 },
1348 Op::CompactContext {
1349 id,
1350 route,
1351 compaction,
1352 } => wire_op::Op::CompactContext {
1353 id: id.clone(),
1354 model: route.model.clone(),
1355 model_provider: route.identity.key.to_string(),
1356 compaction: compaction_to_wire(compaction),
1357 },
1358 Op::CancelCompaction { id } => wire_op::Op::CancelCompaction { id: id.clone() },
1359 // Reply channels never cross the wire: the answer is a frame.
1360 Op::GetSessionSnapshot { tx: _ } => wire_op::Op::GetSessionSnapshot,
1361 Op::GetContextBudget { tx: _ } => wire_op::Op::GetContextBudget,
1362 Op::GetProviderRuntimeStatus { tx: _ } => wire_op::Op::GetProviderRuntimeStatus,
1363 Op::BootstrapMcp { tx: _ } => wire_op::Op::BootstrapMcp,
1364 Op::RetryMcpServer { name, tx: _ } => wire_op::Op::RetryMcpServer { name: name.clone() },
1365 Op::ReloadMcp { config_path, tx: _ } => wire_op::Op::ReloadMcp {
1366 config_path: config_path.clone(),
1367 },
1368 Op::PurgeContext => wire_op::Op::PurgeContext,
1369 Op::EditLastTurn {
1370 new_message,
1371 submission_id: _,
1372 } => wire_op::Op::EditLastTurn {
1373 new_message: new_message.clone(),
1374 },
1375 Op::SetAdvisorEnabled { enabled } => wire_op::Op::SetAdvisorEnabled { enabled: *enabled },
1376 Op::Shutdown => wire_op::Op::Shutdown,
1377 }
1378 }
1379
1380 impl Event {
1381 /// Protocol projection of this event. See [`event_to_protocol`].
1382 #[must_use]
1383 pub fn to_protocol(&self, ids: &ProtocolIds) -> wire::EventMsg {
1384 event_to_protocol(self, ids)
1385 }
1386 }
1387
1388 impl Op {
1389 /// Protocol projection of this op. See [`op_to_protocol`].
1390 #[must_use]
1391 pub fn to_protocol(&self) -> wire_op::Op {
1392 op_to_protocol(self)
1393 }
1394 }
1395
1396 #[cfg(test)]
1397 mod tests {
1398 #[test]
1399 fn mcp_command_or_url_is_redacted_before_it_reaches_the_wire() {
1400 // Local display may show the configured value; this projection feeds
1401 // EventMsg::McpSessionBoot, which every SSE/stream-JSON consumer sees.
1402 assert_eq!(
1403 redacted_command_or_url("https://user:tok@mcp.example.com/sse"),
1404 "https://***:***@mcp.example.com/sse"
1405 );
1406 let masked = redacted_command_or_url("https://mcp.example.com/sse?api_key=SECRET");
1407 assert!(!masked.contains("SECRET"), "{masked}");
1408 // stdio: keep the program, drop the args -- a token there can be
1409 // positional, so key-based masking is not enough.
1410 assert_eq!(
1411 redacted_command_or_url("npx -y server --token SECRET"),
1412 "npx …"
1413 );
1414 // Nothing to hide, nothing changed.
1415 assert_eq!(redacted_command_or_url("npx"), "npx");
1416 // A stdio command that merely mentions a URL must still collapse to
1417 // the program name. Routing it to the URL redactor returns it verbatim
1418 // (`Url::parse` rejects the spaces), leaking the positional token.
1419 let mentions_url = redacted_command_or_url(
1420 "docker run -e TOKEN=sk-live-abc img --url https://mcp.example.com",
1421 );
1422 assert_eq!(mentions_url, "docker …");
1423 assert!(
1424 !mentions_url.contains("sk-live-abc"),
1425 "argv secret reached the wire: {mentions_url}"
1426 );
1427 }
1428
1429 use super::*;
1430 use crate::tools::goal::GoalStatus;
1431 use crate::tools::spec::ToolResult;
1432 use codewhale_error_taxonomy::{ErrorCategory, ErrorEnvelope, ErrorSeverity};
1433 use serde_json::json;
1434
1435 const SOURCE: &str = include_str!("protocol_parity.rs");
1436
1437 fn ids() -> ProtocolIds {
1438 ProtocolIds {
1439 thread_id: ThreadId::new(),
1440 session_id: SessionId::new(),
1441 }
1442 }
1443
1444 #[test]
1445 fn worker_lifecycle_wire_preserves_typed_outcomes_without_parsing_result_text() {
1446 use crate::tools::subagent::SubAgentStatus;
1447 let ids = ids();
1448 for (outcome, expected) in [
1449 (Some(SubAgentStatus::Completed), Some("completed")),
1450 (
1451 Some(SubAgentStatus::Failed("private failure".into())),
1452 Some("failed"),
1453 ),
1454 (
1455 Some(SubAgentStatus::Interrupted("private reason".into())),
1456 Some("interrupted"),
1457 ),
1458 (Some(SubAgentStatus::Cancelled), Some("cancelled")),
1459 (
1460 Some(SubAgentStatus::BudgetExhausted),
1461 Some("budget_exhausted"),
1462 ),
1463 (None, None),
1464 ] {
1465 let event = Event::AgentComplete {
1466 limit_kind: None,
1467 display_name: None,
1468 owner_session_id: "owner".into(),
1469 id: "worker".into(),
1470 result: "Completed successfully".into(),
1471 outcome,
1472 parent_run_id: Some("parent".into()),
1473 spawn_depth: Some(2),
1474 continuable: Some(false),
1475 usage: None,
1476 };
1477 let wire = serde_json::to_value(event_to_protocol(&event, &ids)).unwrap();
1478 assert_eq!(wire["worker_status"].as_str(), expected);
1479 assert_eq!(wire["parent_run_id"], "parent");
1480 assert_eq!(wire["spawn_depth"], 2);
1481 assert_eq!(wire["continuable"], false);
1482 assert!(!wire.to_string().contains("private"));
1483 }
1484 for status in [
1485 AgentWorkerStatus::Queued,
1486 AgentWorkerStatus::Starting,
1487 AgentWorkerStatus::Running,
1488 AgentWorkerStatus::WaitingForUser,
1489 AgentWorkerStatus::ModelWait,
1490 AgentWorkerStatus::RunningTool,
1491 AgentWorkerStatus::Completed,
1492 AgentWorkerStatus::Failed,
1493 AgentWorkerStatus::Cancelled,
1494 AgentWorkerStatus::Interrupted,
1495 ] {
1496 // Runtime serializes the producer enum; stream-json uses this
1497 // exhaustive adapter. Their discriminants must remain identical.
1498 assert_eq!(
1499 serde_json::to_value(status).unwrap(),
1500 worker_status_str(status)
1501 );
1502 }
1503 }
1504
1505 #[test]
1506 fn wire_accounting_preserves_parent_total_and_distinct_routed_telemetry() {
1507 let ids = ids();
1508 let total = Usage {
1509 input_tokens: 49,
1510 output_tokens: 19,
1511 ..Usage::default()
1512 };
1513 let parent = Usage {
1514 input_tokens: 7,
1515 output_tokens: 5,
1516 ..Usage::default()
1517 };
1518 let complete = event_to_protocol(
1519 &Event::TurnComplete {
1520 source_accounting: false,
1521
1522 turn_id: None,
1523 submission_id: None,
1524 compaction_id: None,
1525 usage: total.clone(),
1526 parent_route_usage: parent.clone(),
1527 routed_usage_dropped_records: 3,
1528 status: TurnOutcomeStatus::Completed,
1529 error: None,
1530 tool_catalog: None,
1531 base_url: None,
1532 },
1533 &ids,
1534 );
1535 let json = serde_json::to_value(&complete).unwrap();
1536 assert_eq!(json["usage"]["input_tokens"], 49);
1537 assert_eq!(json["usage"]["output_tokens"], 19);
1538 assert_eq!(json["parent_route_usage"]["input_tokens"], 7);
1539 assert_eq!(json["parent_route_usage"]["output_tokens"], 5);
1540 assert_eq!(json["routed_usage_dropped_records"], 3);
1541 assert_eq!(
1542 serde_json::from_value::<wire::EventMsg>(json.clone()).unwrap(),
1543 complete
1544 );
1545
1546 // A legacy terminal receipt has no parent subset, which differs from
1547 // an explicitly reported zero parent on a compaction-only turn.
1548 let mut legacy = json;
1549 legacy.as_object_mut().unwrap().remove("parent_route_usage");
1550 legacy
1551 .as_object_mut()
1552 .unwrap()
1553 .remove("routed_usage_dropped_records");
1554 assert!(matches!(
1555 serde_json::from_value::<wire::EventMsg>(legacy).unwrap(),
1556 wire::EventMsg::TurnComplete {
1557 parent_route_usage: None,
1558 routed_usage_dropped_records: 0,
1559 ..
1560 }
1561 ));
1562
1563 for (event, tag) in [
1564 (
1565 Event::TurnUsage {
1566 accounting: None,
1567 max_output_tokens: None,
1568 usage: parent,
1569 duration_ms: 12,
1570 first_token_ms: Some(2),
1571 request_ms: Some(10),
1572 finish_reason: None,
1573 },
1574 "turn_usage",
1575 ),
1576 (
1577 Event::RoutedTurnUsage {
1578 usage: total,
1579 duration_ms: 27,
1580 first_token_ms: None,
1581 request_ms: None,
1582 },
1583 "routed_turn_usage",
1584 ),
1585 ] {
1586 let projected = event_to_protocol(&event, &ids);
1587 let json = serde_json::to_value(&projected).unwrap();
1588 assert_eq!(json["event"], tag);
1589 assert_eq!(
1590 serde_json::from_value::<wire::EventMsg>(json).unwrap(),
1591 projected
1592 );
1593 }
1594 }
1595
1596 #[test]
1597 fn manual_compaction_terminal_keeps_its_operation_id_in_projection() {
1598 let event = Event::TurnComplete {
1599 source_accounting: false,
1600
1601 turn_id: None,
1602 submission_id: None,
1603 compaction_id: Some("compact-1".into()),
1604 usage: Usage::default(),
1605 parent_route_usage: Usage::default(),
1606 routed_usage_dropped_records: 0,
1607 status: TurnOutcomeStatus::Failed,
1608 error: Some("route rejected".into()),
1609 tool_catalog: None,
1610 base_url: None,
1611 };
1612 let value = serde_json::to_value(event.to_protocol(&ids())).unwrap();
1613 assert_eq!(value["compaction_id"], "compact-1");
1614 assert!(value.get("turn_id").is_none());
1615 assert!(value.get("submission_id").is_none());
1616 }
1617
1618 /// The guard is the exhaustive `match` in `event_to_protocol`: this test
1619 /// exists so the guard has a name in the test log and so the projection
1620 /// is proven to agree with the protocol's wire-tag table.
1621 #[test]
1622 fn protocol_covers_engine_events() {
1623 let ids = ids();
1624 let usage = Usage {
1625 input_tokens: 3,
1626 output_tokens: 4,
1627 ..Usage::default()
1628 };
1629 let events = vec![
1630 Event::MessageStarted { index: 0 },
1631 Event::MessageDelta {
1632 index: 0,
1633 content: "hello".into(),
1634 },
1635 Event::ThinkingDelta {
1636 index: 1,
1637 content: "hmm".into(),
1638 },
1639 Event::ToolCallStarted {
1640 model_call: None,
1641 id: "c1".into(),
1642 name: "read_file".into(),
1643 input: json!({"path": "x"}),
1644 },
1645 Event::ToolCallHeartbeat,
1646 Event::ToolCallComplete {
1647 model_call: None,
1648 id: "c1".into(),
1649 name: "read_file".into(),
1650 result: Ok(ToolResult::success("ok")),
1651 },
1652 Event::ToolCallComplete {
1653 model_call: None,
1654 id: "c2".into(),
1655 name: "bash".into(),
1656 result: Err(ToolError::Timeout { seconds: 9 }),
1657 },
1658 Event::TurnStarted {
1659 previous_source: None,
1660 turn_id: "turn-1".into(),
1661 created_at: chrono::Utc::now(),
1662 route: None,
1663 // A host-stamped token, not `None`: the projection must carry
1664 // it verbatim or the assertion on `events[7]` below fails.
1665 submission_id: Some("sub-host-1".into()),
1666 },
1667 Event::TurnComplete {
1668 source_accounting: false,
1669
1670 turn_id: Some("turn-1".into()),
1671 submission_id: Some("sub-host-1".into()),
1672 compaction_id: None,
1673 usage: usage.clone(),
1674 parent_route_usage: usage.clone(),
1675 routed_usage_dropped_records: 0,
1676 status: TurnOutcomeStatus::Interrupted,
1677 error: Some("stopped".into()),
1678 tool_catalog: None,
1679 base_url: Some("https://example.invalid".into()),
1680 },
1681 Event::WorkspaceSnapshotTaken {
1682 snapshot: codewhale_snapshot::WorkspaceSnapshotRef {
1683 kind: codewhale_snapshot::WorkspaceSnapshotKind::Tool,
1684 snapshot_id: "a".repeat(40),
1685 tree_id: "b".repeat(40),
1686 session_id: "thr_1".into(),
1687 tool_call_id: Some("c1".into()),
1688 write_paths: Some(vec!["src/lib.rs".into()]),
1689 changed_paths: Some(Vec::new()),
1690 },
1691 },
1692 Event::RoutedTurnUsage {
1693 usage: usage.clone(),
1694 duration_ms: 12,
1695 first_token_ms: Some(3),
1696 request_ms: None,
1697 },
1698 Event::TurnUsage {
1699 accounting: None,
1700 max_output_tokens: None,
1701 usage,
1702 duration_ms: 12,
1703 first_token_ms: Some(3),
1704 request_ms: None,
1705 finish_reason: None,
1706 },
1707 Event::Error {
1708 envelope: ErrorEnvelope {
1709 category: ErrorCategory::RateLimit,
1710 severity: ErrorSeverity::Warning,
1711 recoverable: true,
1712 code: "E429".into(),
1713 message: "slow down".into(),
1714 request_transmission: None,
1715 },
1716 recoverable: true,
1717 },
1718 Event::status("ready"),
1719 Event::PauseEvents { ack: None },
1720 Event::ResumeEvents,
1721 Event::ToolGateDecision {
1722 agent_id: None,
1723 tool_id: "c3".into(),
1724 tool_name: "bash".into(),
1725 gate: ToolGate::AutoReviewGuardian,
1726 decision: ToolGateVerdict::Unavailable,
1727 risk: None,
1728 reviewer_model: None,
1729 reason: "timeout".into(),
1730 rule: Some("guardian-unavailable".into()),
1731 receipt_id: Some("ar-1".into()),
1732 call_digest: Some("d1".into()),
1733 action_summary: Some("bash: ls".into()),
1734 },
1735 Event::AutoReviewPaused {
1736 reason: "Auto-Review paused after 3 blocked calls in a row; Shift+Tab or /auto to resume".into(),
1737 approval_mode: ApprovalMode::Suggest,
1738 },
1739 Event::WorkflowUi {
1740 owner_session_id: "owner".into(),
1741 run_id: "run".into(),
1742 event: json!({"type": "task_started"}),
1743 },
1744 ];
1745
1746 for event in &events {
1747 let msg = event.to_protocol(&ids);
1748 assert!(
1749 wire::EVENT_KINDS.contains(&msg.kind_str()),
1750 "{} is not in EVENT_KINDS",
1751 msg.kind_str()
1752 );
1753 assert_eq!(msg.thread_id(), &ids.thread_id);
1754 assert_eq!(msg.session_id(), &ids.session_id);
1755 let value = serde_json::to_value(&msg).unwrap();
1756 assert_eq!(value["event"], msg.kind_str());
1757 let back: wire::EventMsg = serde_json::from_value(value).unwrap();
1758 assert_eq!(back, msg);
1759 }
1760
1761 let delta = events[1].to_protocol(&ids);
1762 let thinking = events[2].to_protocol(&ids);
1763 assert!(matches!(
1764 delta,
1765 wire::EventMsg::ResponseDelta {
1766 channel: ResponseChannel::Text,
1767 ..
1768 }
1769 ));
1770 assert!(matches!(
1771 thinking,
1772 wire::EventMsg::ResponseDelta {
1773 channel: ResponseChannel::Reasoning,
1774 ..
1775 }
1776 ));
1777 assert_eq!(
1778 serde_json::to_value(events[6].to_protocol(&ids)).unwrap()["result"],
1779 json!({"outcome": "err", "error": {"kind": "timeout", "seconds": 9}})
1780 );
1781 // The host correlation token must cross the projection verbatim: the
1782 // app forwarder binds its submit-window actions to this echo, so a
1783 // silently dropped mapping would defeat the contract.
1784 assert_eq!(
1785 serde_json::to_value(events[7].to_protocol(&ids)).unwrap()["submission_id"],
1786 json!("sub-host-1")
1787 );
1788 assert_eq!(
1789 serde_json::to_value(events[8].to_protocol(&ids)).unwrap()["status"],
1790 "interrupted"
1791 );
1792 let terminal = serde_json::to_value(events[8].to_protocol(&ids)).unwrap();
1793 assert_eq!(terminal["turn_id"], "turn-1");
1794 assert_eq!(terminal["submission_id"], "sub-host-1");
1795 assert!(terminal.get("compaction_id").is_none());
1796 let error = events
1797 .iter()
1798 .find(|event| matches!(event, Event::Error { .. }))
1799 .unwrap();
1800 let error = serde_json::to_value(error.to_protocol(&ids)).unwrap();
1801 assert_eq!(error["category"], "rate_limit");
1802 assert_eq!(error["severity"], "warning");
1803 }
1804
1805 #[test]
1806 fn plugin_changed_projection_round_trips_and_preserves_fields() {
1807 let ids = ids();
1808 let event = Event::PluginChanged {
1809 plugin: "alpha".into(),
1810 action: "installed".into(),
1811 content_hash: Some("sha256:abc".into()),
1812 decided_by: Some("approved by you".into()),
1813 services: vec!["workspace".into()],
1814 tools_added: vec!["alpha_tool".into()],
1815 tools_removed: vec!["legacy_tool".into()],
1816 };
1817 let wire_msg = event.to_protocol(&ids);
1818 let value = serde_json::to_value(&wire_msg).unwrap();
1819 assert_eq!(value["event"], "plugin_changed");
1820 assert_eq!(value["plugin"], "alpha");
1821 assert_eq!(value["action"], "installed");
1822 assert_eq!(value["content_hash"], "sha256:abc");
1823 assert_eq!(value["decided_by"], "approved by you");
1824 assert_eq!(value["services"], json!(["workspace"]));
1825 assert_eq!(value["tools_added"], json!(["alpha_tool"]));
1826 assert_eq!(value["tools_removed"], json!(["legacy_tool"]));
1827 let back: wire::EventMsg = serde_json::from_value(value).unwrap();
1828 assert_eq!(back, wire_msg);
1829 }
1830
1831 #[test]
1832 fn conditional_rewind_projection_preserves_expected_state_and_reply_owner() {
1833 let expected = crate::core::ops::SessionSnapshot {
1834 source: None,
1835
1836 session_id: "observed-conversation".into(),
1837 messages: vec![],
1838 total_tokens: 9,
1839 model: "observed-model".into(),
1840 model_provider: "deepseek".into(),
1841 model_provider_id: Some("configured-provider".into()),
1842 workspace: std::path::PathBuf::from("/observed/workspace"),
1843 system_prompt: None,
1844 instruction_assembly: None,
1845 mode: "agent".into(),
1846 agent_preset: None,
1847 };
1848 let (tx, mut receive) = tokio::sync::oneshot::channel();
1849 let op = Op::RewindConversation {
1850 control: crate::core::ops::SessionControlId::new(),
1851 expected: Box::new(expected.clone()),
1852 messages: vec![],
1853 tx,
1854 };
1855 let value = serde_json::to_value(op.to_protocol()).unwrap();
1856 assert_eq!(value["kind"], "rewind_conversation");
1857 assert!(value["expected"] == to_value(&expected));
1858 assert!(value.get("tx").is_none());
1859 assert!(matches!(
1860 receive.try_recv(),
1861 Err(tokio::sync::oneshot::error::TryRecvError::Empty)
1862 ));
1863 }
1864
1865 #[test]
1866 fn protocol_covers_engine_ops() {
1867 let (tx, _rx) = tokio::sync::oneshot::channel();
1868 let settlement_reply = std::sync::Arc::new(std::sync::Mutex::new(Some(tx)));
1869 let ops = vec![
1870 Op::SetGoalStatus {
1871 goal_id: None,
1872 status: GoalStatus::Paused,
1873 clear: false,
1874 },
1875 Op::SetGoalObjective {
1876 goal_id: None,
1877 objective: "ship".into(),
1878 token_budget: Some(7),
1879 },
1880 Op::ListSubAgents,
1881 Op::CancelSubAgent {
1882 agent_id: "a1".into(),
1883 },
1884 Op::FollowUpSubAgent {
1885 agent_id: "a1".into(),
1886 text: "go".into(),
1887 },
1888 Op::SetStreamChunkTimeout { timeout_secs: 30 },
1889 Op::SetAutoReviewReviewerModel {
1890 reviewer_model: Some("claude-sonnet-5-5".into()),
1891 },
1892 Op::SetSubagentRuntimeConfig {
1893 enabled: true,
1894 max_subagents: 4,
1895 launch_concurrency: 2,
1896 max_spawn_depth: 1,
1897 api_timeout_secs: 60,
1898 heartbeat_timeout_secs: 10,
1899 },
1900 Op::CancelCompaction { id: "cmp".into() },
1901 Op::GetSessionSnapshot {
1902 tx: std::sync::Arc::new(std::sync::Mutex::new(None)),
1903 },
1904 Op::GetContextBudget {
1905 tx: std::sync::Arc::new(std::sync::Mutex::new(None)),
1906 },
1907 Op::GetProviderRuntimeStatus {
1908 tx: std::sync::Arc::new(std::sync::Mutex::new(None)),
1909 },
1910 Op::BootstrapMcp {
1911 tx: std::sync::Arc::new(std::sync::Mutex::new(None)),
1912 },
1913 Op::RetryMcpServer {
1914 name: "fs".into(),
1915 tx: std::sync::Arc::new(std::sync::Mutex::new(None)),
1916 },
1917 Op::ReloadMcp {
1918 config_path: std::path::PathBuf::from("/tmp/mcp.json"),
1919 tx: std::sync::Arc::new(std::sync::Mutex::new(None)),
1920 },
1921 Op::PurgeContext,
1922 Op::EditLastTurn {
1923 new_message: "again".into(),
1924 submission_id: None,
1925 },
1926 Op::SetAdvisorEnabled { enabled: true },
1927 Op::GetSubAgentSettlement {
1928 tx: std::sync::Arc::clone(&settlement_reply),
1929 },
1930 Op::Shutdown,
1931 ];
1932
1933 for op in &ops {
1934 let msg = op.to_protocol();
1935 assert!(
1936 wire_op::OP_KINDS.contains(&msg.kind_str()),
1937 "{} is not in OP_KINDS",
1938 msg.kind_str()
1939 );
1940 let value = serde_json::to_value(&msg).unwrap();
1941 assert_eq!(value["kind"], msg.kind_str());
1942 let back: wire_op::Op = serde_json::from_value(value).unwrap();
1943 assert_eq!(back, msg);
1944 }
1945
1946 assert_eq!(
1947 serde_json::to_value(ops[0].to_protocol()).unwrap(),
1948 json!({"kind": "set_goal_status", "status": "paused", "clear": false})
1949 );
1950 let snapshot = ops
1951 .iter()
1952 .find(|op| matches!(op, Op::GetSessionSnapshot { .. }))
1953 .unwrap();
1954 assert_eq!(
1955 serde_json::to_value(snapshot.to_protocol()).unwrap(),
1956 json!({"kind": "get_session_snapshot"}),
1957 "reply channels must not leak onto the wire"
1958 );
1959 let settlement = ops
1960 .iter()
1961 .find(|op| matches!(op, Op::GetSubAgentSettlement { .. }))
1962 .unwrap();
1963 assert_eq!(
1964 serde_json::to_value(settlement.to_protocol()).unwrap(),
1965 json!({"kind": "get_sub_agent_settlement"}),
1966 "the settlement operation must retain its own channel-free protocol twin"
1967 );
1968 assert!(
1969 settlement_reply.lock().unwrap().is_some(),
1970 "projection must not consume the host's live response sender"
1971 );
1972 }
1973
1974 #[test]
1975 fn mode_labels_round_trip_through_app_mode_parse() {
1976 for mode in [AppMode::Agent, AppMode::Plan] {
1977 assert_eq!(AppMode::parse(app_mode_str(mode)), Some(mode), "{mode:?}");
1978 }
1979 for mode in [
1980 ApprovalMode::Auto,
1981 ApprovalMode::Bypass,
1982 ApprovalMode::Suggest,
1983 ApprovalMode::AcceptEdits,
1984 ApprovalMode::Never,
1985 ] {
1986 assert_eq!(
1987 ApprovalMode::from_config_value(approval_mode_str(mode)),
1988 Some(mode)
1989 );
1990 }
1991 }
1992
1993 /// The projections are only a guard while they stay exhaustive. A
1994 /// wildcard arm would let a new engine variant slip through unmapped.
1995 #[test]
1996 fn projections_have_no_wildcard_arms() {
1997 let wildcard_arms: Vec<&str> = SOURCE
1998 .lines()
1999 .filter(|line| {
2000 let trimmed = line.trim_start();
2001 trimmed.starts_with("_ =>")
2002 || trimmed.starts_with("_=>")
2003 || trimmed.starts_with("Event::_")
2004 || trimmed.starts_with("Op::_")
2005 || (trimmed.contains(" => ") && trimmed.starts_with("other =>"))
2006 })
2007 .collect();
2008 assert!(
2009 wildcard_arms.is_empty(),
2010 "protocol_parity.rs must match engine variants exhaustively; found {wildcard_arms:?}"
2011 );
2012 }
2013 #[test]
2014 fn acp_optional_tool_facts_round_trip_with_core_routing_identity() {
2015 let ids = ids();
2016 for event in [
2017 Event::ToolExecutionStarted {
2018 id: "core-call".into(),
2019 },
2020 Event::ToolResultContent {
2021 id: "core-call".into(),
2022 blocks: vec![codewhale_tools::ToolResultContentBlock::Image {
2023 mime_type: "image/png".into(),
2024 data: "QUJD".into(),
2025 }],
2026 },
2027 ] {
2028 let projected = event_to_protocol(&event, &ids);
2029 assert_eq!(projected.thread_id(), &ids.thread_id);
2030 assert_eq!(projected.session_id(), &ids.session_id);
2031 let value = serde_json::to_value(&projected).unwrap();
2032 assert_eq!(
2033 serde_json::from_value::<wire::EventMsg>(value).unwrap(),
2034 projected
2035 );
2036 }
2037 }
2038 }
2039
2039 lines RUST