| 1 | //! Events emitted by the core engine to the UI. |
| 2 | //! |
| 3 | //! These events flow from the engine to the TUI via a channel, |
| 4 | //! enabling non-blocking, real-time updates. |
| 5 | |
| 6 | use sha2::{Digest, Sha256}; |
| 7 | use std::{ |
| 8 | path::{Path, PathBuf}, |
| 9 | sync::{Arc, Mutex}, |
| 10 | }; |
| 11 | use tokio::sync::oneshot; |
| 12 | use tokio_util::sync::CancellationToken; |
| 13 | |
| 14 | use chrono::{DateTime, Utc}; |
| 15 | use serde_json::Value; |
| 16 | |
| 17 | use crate::tools::goal::GoalSnapshot; |
| 18 | use crate::tools::spec::{ToolError, ToolResult}; |
| 19 | use crate::tools::subagent::{AgentWorkerStatus, CoordinationDetailProjection, SubAgentResult}; |
| 20 | use crate::tools::user_input::UserInputRequest; |
| 21 | use codewhale_config::ProviderKind; |
| 22 | use codewhale_error_taxonomy::ErrorEnvelope; |
| 23 | use codewhale_models::{Message, SystemPrompt, Tool, Usage}; |
| 24 | |
| 25 | #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] |
| 26 | #[serde(rename_all = "snake_case")] |
| 27 | pub enum UserInputClosedOutcome { |
| 28 | Answered, |
| 29 | Cancelled, |
| 30 | TimedOut, |
| 31 | Unavailable, |
| 32 | } |
| 33 | |
| 34 | /// Status receipt carried by the one request a reasoning-only / empty-stop |
| 35 | /// nudge rides (C02-04). The nudge itself never joins the session. |
| 36 | pub const REQUEST_NUDGE_RECEIPT_PREFIX: &str = |
| 37 | "Continuing — this retry carries a request-scoped nudge (not saved to the conversation): "; |
| 38 | |
| 39 | /// Provider correlation retained only for model-history reconstruction. |
| 40 | /// Event ids remain host execution ids; this is not approval authority. |
| 41 | #[derive(Debug, Clone, PartialEq)] |
| 42 | pub struct ModelToolCall { |
| 43 | pub provider_id: String, |
| 44 | pub caller: Option<codewhale_models::ToolCaller>, |
| 45 | pub thought_signature: Option<String>, |
| 46 | } |
| 47 | |
| 48 | /// Final status for a turn. |
| 49 | #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] |
| 50 | #[serde(rename_all = "snake_case")] |
| 51 | pub enum TurnOutcomeStatus { |
| 52 | Completed, |
| 53 | Interrupted, |
| 54 | Failed, |
| 55 | } |
| 56 | |
| 57 | /// Provider/model route resolved for a model-backed turn. |
| 58 | /// |
| 59 | /// Emitted at `RouteDispatched` so hosts retain provenance until the matching |
| 60 | /// `TurnComplete` without relying on mutable global selection state. Non-model |
| 61 | /// turns such as composer `!` shell commands use no route. |
| 62 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 63 | pub struct TurnRoute { |
| 64 | pub provider: ProviderKind, |
| 65 | /// Exact non-secret configured route key. Named custom providers all map |
| 66 | /// to [`ProviderKind::Custom`], so the enum alone is not provenance. |
| 67 | pub provider_identity: String, |
| 68 | pub model: String, |
| 69 | pub auto_model: bool, |
| 70 | /// Secret-free proof of the endpoint and credential generation the turn's |
| 71 | /// client was *installed* on, minted from that client rather than re-read |
| 72 | /// from config later. |
| 73 | /// |
| 74 | /// Hosts that dispatch follow-up work derived from this turn's context must |
| 75 | /// authorize it against this receipt: config is mutable and web config |
| 76 | /// events are drained ahead of engine events, so anything a host resolves |
| 77 | /// while handling `TurnStarted` may already describe a different route. |
| 78 | /// `None` when no concrete client was installed (injected-client engines, |
| 79 | /// or a client that failed to construct). |
| 80 | pub receipt: Option<crate::route_receipt::TurnRouteReceipt>, |
| 81 | /// Billing evidence for a request admitted to application dispatch. |
| 82 | /// |
| 83 | /// `None` at `TurnStarted`: a lifecycle start is not a dispatch, and a |
| 84 | /// route that has not reached admission has no billing time, no metering |
| 85 | /// surface, and no endpoint to attest. Populated exactly once at the |
| 86 | /// pre-permit application-dispatch boundary and delivered on |
| 87 | /// `RouteDispatched`. This does not attest network delivery or a provider |
| 88 | /// invoice-time rate. Consumers that price a turn must treat `None` as |
| 89 | /// *unknown*, never as a zero-cost turn. |
| 90 | pub billing: Option<RouteBillingEnvelope>, |
| 91 | /// Endpoint this turn's client was frozen against, verbatim. |
| 92 | /// |
| 93 | /// [`crate::route_receipt::TurnRouteReceipt`] deliberately keeps only a |
| 94 | /// redacted endpoint identity, which billing cannot classify from, so the |
| 95 | /// non-secret URL travels here. Captured from the resolved route candidate |
| 96 | /// at the client-freeze boundary, before any ambient selection state can |
| 97 | /// move. Empty only when no endpoint was captured, which bills Unknown |
| 98 | /// rather than guessing. |
| 99 | pub base_url: String, |
| 100 | /// Credential/pay-mode product truth captured from the route-scoped config |
| 101 | /// at the same instant. |
| 102 | /// |
| 103 | /// Together with `provider_identity` and `base_url` this is a complete |
| 104 | /// [`crate::route_billing::DispatchedReceipt`]: every fact billing needs, |
| 105 | /// frozen at the client-freeze boundary. Consumers must classify from |
| 106 | /// these fields and must never re-read an ambient `Config` after the turn |
| 107 | /// starts — by `TurnComplete` a provider switch, an auto-router hop, or a |
| 108 | /// `/provider` change can have moved it elsewhere. |
| 109 | pub billing_product: crate::route_billing::RouteProduct, |
| 110 | } |
| 111 | |
| 112 | /// Dispatch-time billing evidence. Separate from [`TurnRoute`] so the type |
| 113 | /// system — not a convention — enforces that no caller can read a billing |
| 114 | /// surface, endpoint fingerprint, or dispatch instant off a route that was |
| 115 | /// only *planned*. |
| 116 | /// |
| 117 | /// This is deliberately *not* the same thing as the classification receipt |
| 118 | /// carried by [`TurnRoute::base_url`] / [`TurnRoute::billing_product`], and |
| 119 | /// the two are not merged. They are captured at different instants and answer |
| 120 | /// different questions: |
| 121 | /// |
| 122 | /// - `base_url` + `billing_product` + `provider_identity` are frozen at the |
| 123 | /// **client-freeze** boundary and answer *which route is this and how does |
| 124 | /// it bill* — a [`crate::route_billing::DispatchedReceipt`]. They must be |
| 125 | /// readable from `TurnStarted` onward so a child turn arriving mid-flight |
| 126 | /// can be billed against the parent's frozen route. |
| 127 | /// - This envelope is stamped at the **pre-permit application-dispatch** |
| 128 | /// boundary and answers *what CodeWhale admitted for provider execution, |
| 129 | /// when*. It does not claim network delivery or provider invoice-time |
| 130 | /// pricing. A merely planned route has no metering surface or dispatch |
| 131 | /// instant, so it must be structurally absent rather than defaulted. |
| 132 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 133 | pub struct RouteBillingEnvelope { |
| 134 | pub openrouter_vendor: Option<String>, |
| 135 | pub billing_surface: Option<String>, |
| 136 | pub endpoint_fingerprint: Option<String>, |
| 137 | pub provider_live_pricing: Option<crate::provider_catalog_live::ProviderLivePricingQuote>, |
| 138 | pub billing_mode: crate::cost_status::RouteBillingMode, |
| 139 | pub dispatched_at: DateTime<Utc>, |
| 140 | } |
| 141 | |
| 142 | impl TurnRoute { |
| 143 | /// Priceable envelope for this route, or `None` when the route was never |
| 144 | /// dispatched. Deliberately not a `Default`-filled envelope: an undispatched |
| 145 | /// route has no cost, and "no cost" is not "zero cost". |
| 146 | #[must_use] |
| 147 | pub fn cost_envelope(&self) -> Option<crate::cost_status::EffectiveRouteEnvelope> { |
| 148 | let billing = self.billing.as_ref()?; |
| 149 | Some(crate::cost_status::EffectiveRouteEnvelope { |
| 150 | provider: self.provider, |
| 151 | provider_identity: self.provider_identity.clone(), |
| 152 | model: self.model.clone(), |
| 153 | openrouter_vendor: billing.openrouter_vendor.clone(), |
| 154 | billing_surface: billing.billing_surface.clone(), |
| 155 | endpoint_fingerprint: billing.endpoint_fingerprint.clone(), |
| 156 | provider_live_pricing: billing.provider_live_pricing.clone(), |
| 157 | billing_mode: billing.billing_mode, |
| 158 | dispatched_at: billing.dispatched_at, |
| 159 | }) |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | /// Structured lifecycle metadata paired with a human-readable |
| 164 | /// [`Event::AgentProgress`] message. |
| 165 | /// |
| 166 | /// Producers own this classification. UI consumers may bound the display |
| 167 | /// message, but must never recover lifecycle state by parsing it. |
| 168 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 169 | pub struct AgentProgressEventMeta { |
| 170 | pub worker_status: AgentWorkerStatus, |
| 171 | pub step: Option<u32>, |
| 172 | /// Canonical action/tool name. Presentation aliases are applied by the UI |
| 173 | /// when it creates the bounded current-activity projection. |
| 174 | pub tool_name: Option<String>, |
| 175 | /// True when this progress is the routine per-step wait heartbeat |
| 176 | /// ("requesting model response"). Retry/timeout waits share the |
| 177 | /// `ModelWait` status but carry informative text, so the status alone |
| 178 | /// cannot tell them apart — the producer sets this instead, and UI |
| 179 | /// consumers rewrite on it rather than sniffing the message (#6290). |
| 180 | pub routine_wait: bool, |
| 181 | /// The child approval id this progress reports on: set while the agent |
| 182 | /// waits on a person and on the first progress after that wait ends, so |
| 183 | /// hosts can retire the matching card and pending entry by identity |
| 184 | /// (approvals C1) instead of by parsing the message. |
| 185 | pub approval_id: Option<String>, |
| 186 | } |
| 187 | |
| 188 | impl AgentProgressEventMeta { |
| 189 | #[must_use] |
| 190 | pub const fn new(worker_status: AgentWorkerStatus) -> Self { |
| 191 | Self { |
| 192 | worker_status, |
| 193 | step: None, |
| 194 | tool_name: None, |
| 195 | routine_wait: false, |
| 196 | approval_id: None, |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | #[must_use] |
| 201 | pub const fn with_step(mut self, step: u32) -> Self { |
| 202 | self.step = Some(step); |
| 203 | self |
| 204 | } |
| 205 | |
| 206 | #[must_use] |
| 207 | pub fn with_tool(mut self, tool_name: impl Into<String>) -> Self { |
| 208 | self.tool_name = Some(tool_name.into()); |
| 209 | self |
| 210 | } |
| 211 | |
| 212 | #[must_use] |
| 213 | pub fn with_approval_id(mut self, approval_id: impl Into<String>) -> Self { |
| 214 | self.approval_id = Some(approval_id.into()); |
| 215 | self |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 220 | pub struct SessionCheckpointCaller { |
| 221 | pub session_id: String, |
| 222 | pub agent_id: Option<String>, |
| 223 | pub turn_id: String, |
| 224 | pub call_id: String, |
| 225 | pub workspace: PathBuf, |
| 226 | } |
| 227 | |
| 228 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 229 | pub enum SessionCheckpointProjection { |
| 230 | Exact, |
| 231 | RuntimeReceiptRedacted, |
| 232 | } |
| 233 | |
| 234 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 235 | pub struct SessionCheckpointReceipt { |
| 236 | pub persisted_sha256: String, |
| 237 | pub messages_len: usize, |
| 238 | pub projection: SessionCheckpointProjection, |
| 239 | } |
| 240 | |
| 241 | #[derive(Debug)] |
| 242 | pub struct SessionCheckpointRequest { |
| 243 | pub checkpoint_id: String, |
| 244 | pub caller: SessionCheckpointCaller, |
| 245 | pub prefix_sha256: String, |
| 246 | pub snapshot: Arc<crate::core::ops::SessionSnapshot>, |
| 247 | pub withdraw: CancellationToken, |
| 248 | projection: SessionCheckpointProjection, |
| 249 | reply: Mutex<Option<oneshot::Sender<Result<bool, ToolError>>>>, |
| 250 | } |
| 251 | |
| 252 | impl SessionCheckpointRequest { |
| 253 | pub fn new( |
| 254 | caller: SessionCheckpointCaller, |
| 255 | snapshot: Arc<crate::core::ops::SessionSnapshot>, |
| 256 | prefix_sha256: String, |
| 257 | projection: SessionCheckpointProjection, |
| 258 | withdraw: CancellationToken, |
| 259 | reply: oneshot::Sender<Result<bool, ToolError>>, |
| 260 | ) -> Arc<Self> { |
| 261 | Arc::new(Self { |
| 262 | checkpoint_id: uuid::Uuid::new_v4().to_string(), |
| 263 | caller, |
| 264 | prefix_sha256, |
| 265 | snapshot, |
| 266 | withdraw, |
| 267 | projection, |
| 268 | reply: Mutex::new(Some(reply)), |
| 269 | }) |
| 270 | } |
| 271 | |
| 272 | pub fn prefix_hash(messages: &[Message]) -> Result<String, String> { |
| 273 | serde_json::to_vec(messages) |
| 274 | .map(|bytes| { |
| 275 | Sha256::digest(bytes) |
| 276 | .iter() |
| 277 | .map(|byte| format!("{byte:02x}")) |
| 278 | .collect() |
| 279 | }) |
| 280 | .map_err(|error| format!("session checkpoint could not encode its prefix: {error}")) |
| 281 | } |
| 282 | |
| 283 | pub fn validate_prefix( |
| 284 | &self, |
| 285 | session_id: &str, |
| 286 | workspace: &Path, |
| 287 | messages: &[Message], |
| 288 | ) -> Result<(), String> { |
| 289 | if self.is_stale() { |
| 290 | return Err("session checkpoint was withdrawn".into()); |
| 291 | } |
| 292 | if self.caller.agent_id.is_some() |
| 293 | || self |
| 294 | .snapshot |
| 295 | .source |
| 296 | .as_ref() |
| 297 | .and_then(|source| source.turn_id.as_deref()) |
| 298 | != Some(self.caller.turn_id.as_str()) |
| 299 | || session_id != self.caller.session_id |
| 300 | || session_id != self.snapshot.session_id |
| 301 | || workspace != self.caller.workspace |
| 302 | || workspace != self.snapshot.workspace |
| 303 | || messages.len() != self.snapshot.messages.len() |
| 304 | || Self::prefix_hash(messages)? != self.prefix_sha256 |
| 305 | { |
| 306 | return Err("session checkpoint does not match its captured owner and prefix".into()); |
| 307 | } |
| 308 | Ok(()) |
| 309 | } |
| 310 | |
| 311 | pub fn is_stale(&self) -> bool { |
| 312 | self.withdraw.is_cancelled() |
| 313 | || self |
| 314 | .reply |
| 315 | .lock() |
| 316 | .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 317 | .as_ref() |
| 318 | .is_none_or(oneshot::Sender::is_closed) |
| 319 | } |
| 320 | |
| 321 | fn finish(&self, result: Result<bool, ToolError>) { |
| 322 | let result = if self.withdraw.is_cancelled() { |
| 323 | Err(ToolError::cancelled("session checkpoint was withdrawn")) |
| 324 | } else { |
| 325 | result |
| 326 | }; |
| 327 | if let Some(reply) = self |
| 328 | .reply |
| 329 | .lock() |
| 330 | .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 331 | .take() |
| 332 | { |
| 333 | let _ = reply.send(result); |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | pub fn succeed(&self, receipt: SessionCheckpointReceipt) { |
| 338 | let valid_hash = receipt.persisted_sha256.len() == 64 |
| 339 | && receipt |
| 340 | .persisted_sha256 |
| 341 | .bytes() |
| 342 | .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)); |
| 343 | let allowed = match receipt.projection { |
| 344 | SessionCheckpointProjection::Exact => receipt.persisted_sha256 == self.prefix_sha256, |
| 345 | SessionCheckpointProjection::RuntimeReceiptRedacted => { |
| 346 | self.projection == SessionCheckpointProjection::RuntimeReceiptRedacted |
| 347 | } |
| 348 | }; |
| 349 | if !valid_hash || !allowed || receipt.messages_len != self.snapshot.messages.len() { |
| 350 | self.fail( |
| 351 | "session checkpoint persistence receipt does not match its captured projection", |
| 352 | ); |
| 353 | return; |
| 354 | } |
| 355 | self.finish(Ok(true)); |
| 356 | } |
| 357 | |
| 358 | pub fn fail(&self, reason: impl Into<String>) { |
| 359 | self.finish(Err(ToolError::not_available(reason.into()))); |
| 360 | } |
| 361 | |
| 362 | pub fn no_backend(&self) { |
| 363 | self.finish(Ok(false)); |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | impl Drop for SessionCheckpointRequest { |
| 368 | fn drop(&mut self) { |
| 369 | if let Some(reply) = self |
| 370 | .reply |
| 371 | .get_mut() |
| 372 | .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 373 | .take() |
| 374 | { |
| 375 | let _ = reply.send(Err(ToolError::not_available( |
| 376 | "owning host did not acknowledge the session checkpoint", |
| 377 | ))); |
| 378 | } |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | /// Events emitted by the engine to update the UI. |
| 383 | #[derive(Debug, Clone)] |
| 384 | pub enum Event { |
| 385 | /// A route compatibility check omitted tools from the provider request. |
| 386 | /// Names are wire-safe and bounded by the request catalog; schemas and |
| 387 | /// validator details never cross this user-visible boundary. |
| 388 | ToolProjectionWarning { |
| 389 | provider: String, |
| 390 | omitted_tool_names: Vec<String>, |
| 391 | omitted_tool_count: usize, |
| 392 | }, |
| 393 | |
| 394 | RequestImageWindow { |
| 395 | provider: String, |
| 396 | model: String, |
| 397 | total: usize, |
| 398 | elided: usize, |
| 399 | cap: usize, |
| 400 | cap_source: String, |
| 401 | message: String, |
| 402 | }, |
| 403 | |
| 404 | /// Workspace snapshots (undo) could not be enabled for this workspace. |
| 405 | /// Emitted once per session/workspace so another session cannot consume |
| 406 | /// its notice. The disabled state also remains visible in `/status` (#5930). |
| 407 | /// `reason` is the single localized line rendered from the gate, so every |
| 408 | /// surface states the workspace, the limit, and the recovery exactly once. |
| 409 | SnapshotsDisabled { |
| 410 | workspace: String, |
| 411 | reason: String, |
| 412 | }, |
| 413 | // === Streaming Events === |
| 414 | /// A new message block has started |
| 415 | MessageStarted { |
| 416 | index: usize, |
| 417 | }, |
| 418 | |
| 419 | /// Incremental text content delta |
| 420 | MessageDelta { |
| 421 | index: usize, |
| 422 | content: String, |
| 423 | }, |
| 424 | |
| 425 | /// Message block completed |
| 426 | MessageComplete { |
| 427 | index: usize, |
| 428 | }, |
| 429 | |
| 430 | /// Thinking block started |
| 431 | ThinkingStarted { |
| 432 | index: usize, |
| 433 | }, |
| 434 | |
| 435 | /// Incremental thinking content delta |
| 436 | ThinkingDelta { |
| 437 | index: usize, |
| 438 | content: String, |
| 439 | }, |
| 440 | |
| 441 | /// Thinking block completed |
| 442 | ThinkingComplete { |
| 443 | index: usize, |
| 444 | }, |
| 445 | |
| 446 | // === Tool Events === |
| 447 | /// Tool call initiated |
| 448 | ToolCallStarted { |
| 449 | id: String, |
| 450 | model_call: Option<ModelToolCall>, |
| 451 | name: String, |
| 452 | input: Value, |
| 453 | }, |
| 454 | |
| 455 | /// Best-effort liveness pulse while a tool future remains pending. |
| 456 | /// |
| 457 | /// This carries no output and must not change user-visible status or the |
| 458 | /// transcript. It only prevents the TUI from declaring a healthy, |
| 459 | /// deliberately long-running tool turn stale. |
| 460 | ToolCallHeartbeat, |
| 461 | |
| 462 | /// The call passed its gates and started running; until then an announced |
| 463 | /// call is only queued. |
| 464 | ToolExecutionStarted { |
| 465 | id: String, |
| 466 | }, |
| 467 | /// Canonical rich result after existing output/media preservation. |
| 468 | ToolResultContent { |
| 469 | id: String, |
| 470 | blocks: Vec<codewhale_tools::ToolResultContentBlock>, |
| 471 | }, |
| 472 | |
| 473 | /// Tool call completed |
| 474 | ToolCallComplete { |
| 475 | id: String, |
| 476 | model_call: Option<ModelToolCall>, |
| 477 | name: String, |
| 478 | result: Result<ToolResult, ToolError>, |
| 479 | }, |
| 480 | |
| 481 | /// Trusted operation activity emitted only after dispatch and authority |
| 482 | /// gates resolve the underlying operation. The payload deliberately |
| 483 | /// excludes arguments, commands, and results. |
| 484 | OperationActivityStarted { |
| 485 | span_id: String, |
| 486 | activity_kind: codewhale_protocol::engine_owner::OwnerActivityKind, |
| 487 | action_id: Option<String>, |
| 488 | }, |
| 489 | OperationActivityCompleted { |
| 490 | span_id: String, |
| 491 | activity_kind: codewhale_protocol::engine_owner::OwnerActivityKind, |
| 492 | outcome: codewhale_protocol::engine_owner::OwnerOperationOutcome, |
| 493 | action_id: Option<String>, |
| 494 | }, |
| 495 | |
| 496 | // === Turn Lifecycle === |
| 497 | /// A new turn has started (user sent a message) |
| 498 | TurnStarted { |
| 499 | previous_source: Option<super::ops::SessionSnapshotSource>, |
| 500 | turn_id: String, |
| 501 | created_at: DateTime<Utc>, |
| 502 | /// Legacy/non-model hosts may still attach a route at start. Model |
| 503 | /// turns emit it separately at the application dispatch boundary. |
| 504 | route: Option<TurnRoute>, |
| 505 | /// Correlation with the host submission that produced this turn: the |
| 506 | /// verbatim echo of the `submission_id` the host stamped on its |
| 507 | /// `SendMessage`/`EditLastTurn` op, `None` for every runtime |
| 508 | /// self-started turn (idle sub-agent completion, background shell |
| 509 | /// wake, goal continuation) and for the composer shell command turn. |
| 510 | /// Hosts use the echo to tell their own pending submission's |
| 511 | /// `TurnStarted` apart from an autonomous follow-up whose start event |
| 512 | /// overtook it in the stream, so a deferred submit-window action is |
| 513 | /// only ever consumed by the turn it targets. |
| 514 | submission_id: Option<String>, |
| 515 | }, |
| 516 | |
| 517 | /// Bounded tool-field projection from a prepared model-client request. |
| 518 | /// Delivery remains unknown; this event is emitted before connection setup. |
| 519 | ToolRequestSnapshot { |
| 520 | snapshot: crate::tool_inspection::ToolInspectionSnapshot, |
| 521 | }, |
| 522 | |
| 523 | /// The engine took a workspace snapshot for the running turn: before it |
| 524 | /// (`pre_turn`), before one file-modifying tool call (`tool`), after that |
| 525 | /// call (`post_tool`, recording hosts only), or after the turn |
| 526 | /// (`post_turn`). A host that records these on its turn records owns |
| 527 | /// exactly those restore points (see `codewhale_snapshot::WorkspaceSnapshotRef`). |
| 528 | /// With `EngineConfig::record_restore_points` every receipt of a turn |
| 529 | /// arrives before its `TurnComplete`. |
| 530 | WorkspaceSnapshotTaken { |
| 531 | snapshot: codewhale_snapshot::WorkspaceSnapshotRef, |
| 532 | }, |
| 533 | |
| 534 | /// Immutable billing route captured at CodeWhale's pre-permit application |
| 535 | /// dispatch boundary, after request preparation. This is admission-time |
| 536 | /// evidence, not proof of network delivery or provider invoice-time rates. |
| 537 | RouteDispatched { |
| 538 | turn_id: String, |
| 539 | route: TurnRoute, |
| 540 | }, |
| 541 | |
| 542 | /// The turn is complete (no more tool calls) |
| 543 | TurnComplete { |
| 544 | /// Actual started turn, captured by its producer; absent on preflight |
| 545 | /// rejection. |
| 546 | turn_id: Option<String>, |
| 547 | /// Original host submission, also echoed when it fails before |
| 548 | /// `TurnStarted`. Runtime self-starts and non-message operations never |
| 549 | /// borrow a pending host id. |
| 550 | submission_id: Option<String>, |
| 551 | /// Manual compaction operation id. Mutually exclusive with the two |
| 552 | /// fields above; auto compaction closes its enclosing model turn |
| 553 | /// instead. |
| 554 | compaction_id: Option<String>, |
| 555 | /// Total usage for session/goal/token metrics, including programmatic |
| 556 | /// child calls performed inline during this turn. |
| 557 | usage: Usage, |
| 558 | /// Usage served by the parent turn's frozen route only. Consumers |
| 559 | /// price this under the parent quote and price routed children from |
| 560 | /// their own receipts, avoiding double billing without subtraction. |
| 561 | parent_route_usage: Usage, |
| 562 | source_accounting: bool, |
| 563 | /// Provider calls whose execution/usage could not be receipted. |
| 564 | /// Non-zero makes cost coverage explicitly incomplete. |
| 565 | routed_usage_dropped_records: u64, |
| 566 | status: TurnOutcomeStatus, |
| 567 | error: Option<String>, |
| 568 | /// Tool catalog sent with this turn's model request. |
| 569 | tool_catalog: Option<Vec<Tool>>, |
| 570 | /// API base URL used by this turn's client. |
| 571 | base_url: Option<String>, |
| 572 | }, |
| 573 | |
| 574 | ProviderRequestReceipt { |
| 575 | receipt: serde_json::Value, |
| 576 | }, |
| 577 | |
| 578 | /// A single model call (turn-step) within the turn completed and the |
| 579 | /// provider reported usage for it. Unlike `TurnComplete`, which fires |
| 580 | /// once per turn with the cumulative usage, this fires once per model |
| 581 | /// request so consumers can attribute tokens (including reasoning and |
| 582 | /// cache behavior) to individual steps. It is not emitted when the |
| 583 | /// provider never reported usage for the call — absence is honest, and |
| 584 | /// fields inside `usage` stay `None` when the provider omits them. |
| 585 | TurnUsage { |
| 586 | accounting: Option<crate::cost_status::RuntimeUsageRecord>, |
| 587 | /// Primary request allowance; not a claim of provider-reported usage. |
| 588 | max_output_tokens: Option<u32>, |
| 589 | usage: Usage, |
| 590 | /// Wall-clock duration of this model call's stream. |
| 591 | duration_ms: u64, |
| 592 | /// Wall-clock time from the moment the request was dispatched to the |
| 593 | /// provider until the first content-bearing stream event arrived |
| 594 | /// (time to first token). `None` when the call produced no content |
| 595 | /// or the emitting path does not measure the first content event |
| 596 | /// (non-streaming reviewer / REPL consults). |
| 597 | first_token_ms: Option<u64>, |
| 598 | /// Wall-clock time from request dispatch to the usage receipt for |
| 599 | /// this model call — the whole call including connection setup, not |
| 600 | /// only the stream. `None` where an individual request is not |
| 601 | /// measured (for example an aggregate REPL child receipt). This is |
| 602 | /// the denominator for effective session-average throughput. |
| 603 | request_ms: Option<u64>, |
| 604 | finish_reason: Option<String>, |
| 605 | }, |
| 606 | |
| 607 | /// Usage telemetry for a programmatic provider call whose cost is carried |
| 608 | /// by its own routed receipt rather than the active parent route. TUI |
| 609 | /// consumers fold this into model-call metrics only; `TurnComplete.usage` |
| 610 | /// remains the authoritative total-token reconciliation. |
| 611 | RoutedTurnUsage { |
| 612 | usage: Usage, |
| 613 | duration_ms: u64, |
| 614 | first_token_ms: Option<u64>, |
| 615 | request_ms: Option<u64>, |
| 616 | }, |
| 617 | |
| 618 | /// Runtime goal state changed inside the engine, usually from model-visible |
| 619 | /// `create_goal` or `update_goal` tool calls. |
| 620 | GoalUpdated { |
| 621 | snapshot: GoalSnapshot, |
| 622 | }, |
| 623 | |
| 624 | /// The interactive engine is in the configured quiet period before one |
| 625 | /// already-authorized goal continuation. This is lifecycle state, not a |
| 626 | /// status string: Esc/Ctrl+C can cancel it without pretending a provider |
| 627 | /// turn is still in flight. |
| 628 | GoalContinuationWaiting { |
| 629 | delay_seconds: u64, |
| 630 | }, |
| 631 | |
| 632 | /// The between-turn quiet period ended. `interrupted` distinguishes a |
| 633 | /// user/external cancel from normal expiry or a goal status control. |
| 634 | GoalContinuationWaitEnded { |
| 635 | interrupted: bool, |
| 636 | }, |
| 637 | |
| 638 | /// Context compaction started. |
| 639 | CompactionStarted { |
| 640 | previous_source: Option<super::ops::SessionSnapshotSource>, |
| 641 | id: String, |
| 642 | auto: bool, |
| 643 | message: String, |
| 644 | }, |
| 645 | |
| 646 | /// Context compaction completed. |
| 647 | CompactionCompleted { |
| 648 | id: String, |
| 649 | auto: bool, |
| 650 | message: String, |
| 651 | /// Number of messages before compaction. |
| 652 | messages_before: Option<usize>, |
| 653 | /// Number of messages after compaction. |
| 654 | messages_after: Option<usize>, |
| 655 | /// Rendered text of the accumulated compaction summary prompt, if any. |
| 656 | /// Host layers (e.g. the /v1 runtime) persist this into the thread |
| 657 | /// record so the summary survives engine reloads — without it the |
| 658 | /// summary lives only in engine memory and is lost on LRU eviction |
| 659 | /// or restart (SyncSession re-extracts it from the record prompt). |
| 660 | summary_prompt: Option<String>, |
| 661 | /// Conservative input-token estimate for the complete post-compaction |
| 662 | /// request, including its system prompt. Hosts can use this until the |
| 663 | /// next provider-reported usage arrives. |
| 664 | post_input_tokens: Option<u64>, |
| 665 | }, |
| 666 | |
| 667 | /// Context compaction was canceled before it could commit a checkpoint. |
| 668 | /// |
| 669 | /// The stable id makes cancellation idempotent and lets host layers settle |
| 670 | /// the exact durable item without inferring lifecycle from status prose. |
| 671 | CompactionCancelled { |
| 672 | id: String, |
| 673 | auto: bool, |
| 674 | message: String, |
| 675 | }, |
| 676 | |
| 677 | /// Context purge started. |
| 678 | PurgeStarted { |
| 679 | /// Status message for display. |
| 680 | message: String, |
| 681 | }, |
| 682 | |
| 683 | /// Context purge completed. |
| 684 | PurgeCompleted { |
| 685 | /// Number of messages before purge. |
| 686 | messages_before: usize, |
| 687 | /// Number of messages after purge. |
| 688 | messages_after: usize, |
| 689 | /// How many messages were removed. |
| 690 | removed_count: usize, |
| 691 | /// How many replace operations were applied. |
| 692 | replaced_count: usize, |
| 693 | /// Summary message for display. |
| 694 | message: String, |
| 695 | }, |
| 696 | |
| 697 | /// Context purge failed. |
| 698 | PurgeFailed { |
| 699 | message: String, |
| 700 | }, |
| 701 | |
| 702 | /// Context compaction failed. |
| 703 | CompactionFailed { |
| 704 | id: String, |
| 705 | auto: bool, |
| 706 | message: String, |
| 707 | }, |
| 708 | |
| 709 | // === Sub-Agent Events === |
| 710 | /// A sub-agent has been spawned |
| 711 | AgentSpawned { |
| 712 | owner_session_id: String, |
| 713 | id: String, |
| 714 | prompt: String, |
| 715 | worker_status: Option<AgentWorkerStatus>, |
| 716 | parent_run_id: Option<String>, |
| 717 | spawn_depth: u32, |
| 718 | /// Model the child runtime was actually installed with, after route |
| 719 | /// resolution. Structured-output hosts surface this so child billing |
| 720 | /// attribution never depends on reading source or an invoice. |
| 721 | model: String, |
| 722 | /// Why the child got that route (`task.model`, `agent_profile.loadout`, |
| 723 | /// `run.model`, …). `None` for spawn paths that bypass route |
| 724 | /// resolution (checkpoint resume, engine-internal spawns). |
| 725 | route_source: Option<String>, |
| 726 | /// The name this agent goes by on every surface: its workflow task |
| 727 | /// label, dispatch name, or role, resolved once by the engine |
| 728 | /// (`subagent_display_name`). Never the raw id. |
| 729 | display_name: Option<String>, |
| 730 | }, |
| 731 | |
| 732 | /// Sub-agent progress update |
| 733 | AgentProgress { |
| 734 | owner_session_id: String, |
| 735 | id: String, |
| 736 | status: String, |
| 737 | activity: AgentProgressEventMeta, |
| 738 | parent_run_id: Option<String>, |
| 739 | spawn_depth: u32, |
| 740 | }, |
| 741 | |
| 742 | /// Sub-agent completed |
| 743 | AgentComplete { |
| 744 | owner_session_id: String, |
| 745 | id: String, |
| 746 | result: String, |
| 747 | /// Producer-owned outcome. None is a legacy receipt, never success. |
| 748 | outcome: Option<crate::tools::subagent::SubAgentStatus>, |
| 749 | limit_kind: Option<codewhale_protocol::agent_run::AgentLimitKind>, |
| 750 | parent_run_id: Option<String>, |
| 751 | spawn_depth: Option<u32>, |
| 752 | continuable: Option<bool>, |
| 753 | /// Provider-reported child usage from the durable ledger (#6315). |
| 754 | /// None means the worker has no usage receipt, never zero tokens. |
| 755 | usage: Option<crate::tools::subagent::AgentRunUsage>, |
| 756 | /// Same resolved name as `AgentSpawned::display_name`. |
| 757 | display_name: Option<String>, |
| 758 | }, |
| 759 | |
| 760 | /// Receipt for an operator follow-up sent to a child (`Op::FollowUpSubAgent`). |
| 761 | /// `Ok` carries the delivery outcome (the target id may differ from the |
| 762 | /// addressed id when a fork was continued from a checkpoint); `Err` is the |
| 763 | /// exact reason nothing was delivered. |
| 764 | SubAgentFollowUp { |
| 765 | owner_session_id: String, |
| 766 | agent_id: String, |
| 767 | outcome: Result<crate::tools::subagent::UserFollowUpOutcome, String>, |
| 768 | }, |
| 769 | |
| 770 | /// Sub-agent listing plus the same bounded typed coordination projection |
| 771 | /// used by machine-readable `agents/coordinate inspect`. |
| 772 | AgentList { |
| 773 | owner_session_id: String, |
| 774 | agents: Vec<SubAgentResult>, |
| 775 | coordination: CoordinationDetailProjection, |
| 776 | /// Follow-ups handed to a running child that it has not yet taken at |
| 777 | /// its next round boundary (`agent_id` → count). Only non-zero entries. |
| 778 | queued_follow_ups: std::collections::HashMap<String, usize>, |
| 779 | /// Receipts-only roster of every agent that ran this session (#5479): |
| 780 | /// status, current step, elapsed and token usage per row, built from |
| 781 | /// the retained worker records rather than from live agent state, so a |
| 782 | /// finished agent keeps the numbers it finished with. |
| 783 | roster: Vec<crate::agent_roster::AgentRosterRow>, |
| 784 | }, |
| 785 | |
| 786 | /// Structured sub-agent mailbox envelope (issue #128). Carries the |
| 787 | /// monotonic seq + the typed `MailboxMessage` so the UI can route each |
| 788 | /// envelope to the correct in-transcript card. |
| 789 | SubAgentMailbox { |
| 790 | owner_session_id: String, |
| 791 | /// Engine turn identity. Sequence numbers restart for every mailbox, |
| 792 | /// so consumers must deduplicate on `(turn_id, seq)`, never `seq` |
| 793 | /// alone. |
| 794 | turn_id: String, |
| 795 | seq: u64, |
| 796 | message: crate::tools::subagent::MailboxMessage, |
| 797 | }, |
| 798 | |
| 799 | /// Live workflow UI event (#4122). Mirrors a typed `WorkflowUiEvent` JSON |
| 800 | /// object so the TUI can advance the WorkflowPanel and the compact history |
| 801 | /// card while a run is still in flight (not only on tool complete). |
| 802 | WorkflowUi { |
| 803 | /// Immutable conversation owner. Consumers must compare this before |
| 804 | /// revealing or applying any workflow state. |
| 805 | owner_session_id: String, |
| 806 | run_id: String, |
| 807 | /// Flattened event JSON: `{"type":"task_started", "at_ms":…, …}`. |
| 808 | /// Callers inject `run_id` on the object when available. |
| 809 | event: Value, |
| 810 | }, |
| 811 | |
| 812 | // === System Events === |
| 813 | /// An error occurred |
| 814 | Error { |
| 815 | envelope: ErrorEnvelope, |
| 816 | recoverable: bool, |
| 817 | }, |
| 818 | |
| 819 | /// Status message for UI display |
| 820 | Status { |
| 821 | message: String, |
| 822 | }, |
| 823 | |
| 824 | /// Session-owned MCP + plugin boot progress. |
| 825 | /// |
| 826 | /// Failures stay on this event (and therefore on the session page) until |
| 827 | /// retry succeeds. They are not `Status` toasts. `connecting` names the |
| 828 | /// enabled servers that have not settled yet; `finished` is the terminal |
| 829 | /// receipt for this boot pass. |
| 830 | McpSessionBoot { |
| 831 | /// Monotonic engine-owned event generation. A direct `/mcp` snapshot |
| 832 | /// may supersede one generation without suppressing later passes. |
| 833 | generation: u64, |
| 834 | snapshot: crate::mcp::McpManagerSnapshot, |
| 835 | connecting: Vec<String>, |
| 836 | finished: bool, |
| 837 | }, |
| 838 | |
| 839 | /// Rendered `/preview-request` manifest (#1004). |
| 840 | /// |
| 841 | /// The engine is the only authority that can rebuild the exact next-turn |
| 842 | /// request, so the manifest is rendered there and delivered as text. The |
| 843 | /// payload is normally a redacted, typed manifest — never a request body. |
| 844 | /// The explicit `base-prompt` mode may instead carry only the exact base |
| 845 | /// prompt; it never carries runtime/system additions. There is no error |
| 846 | /// variant: a manifest that cannot describe something says so in a typed |
| 847 | /// unavailable section instead. |
| 848 | RequestManifestReady { |
| 849 | rendered: String, |
| 850 | }, |
| 851 | |
| 852 | /// Pause terminal input events (for interactive subprocesses). |
| 853 | PauseEvents { |
| 854 | /// Optional one-shot notification fired after the UI has actually |
| 855 | /// released the terminal to the child process. |
| 856 | ack: Option<Arc<tokio::sync::Notify>>, |
| 857 | }, |
| 858 | |
| 859 | /// Resume terminal input events after subprocess completion |
| 860 | ResumeEvents, |
| 861 | |
| 862 | /// Request user approval for a tool call |
| 863 | ApprovalRequired { |
| 864 | publication: Option<crate::core::engine::NativeApprovalPublication>, |
| 865 | id: String, |
| 866 | tool_name: String, |
| 867 | description: String, |
| 868 | /// Tool parameters for approval display. Carried on the event so the |
| 869 | /// TUI does not need to reconstruct them from `pending_tool_uses`. |
| 870 | input: Value, |
| 871 | /// Exact-argument fingerprint, used to scope *denials* (#1617). |
| 872 | approval_key: String, |
| 873 | /// Lossy / arity-aware fingerprint, used to scope *approvals* so an |
| 874 | /// "approve for session" covers later flag variants (v0.8.37). |
| 875 | approval_grouping_key: String, |
| 876 | /// The model's explanation of intent before invoking write tools (#2381). |
| 877 | /// Displayed in the approval view so users understand *why* the change |
| 878 | /// is being made before reviewing *what* will change. |
| 879 | intent_summary: Option<String>, |
| 880 | /// When true, the UI must show the prompt instead of consuming |
| 881 | /// session/auto approval shortcuts. |
| 882 | approval_force_prompt: bool, |
| 883 | }, |
| 884 | |
| 885 | /// The engine no longer waits for this approval. Every decision surface |
| 886 | /// must retire the request by identity without sending a user decision. |
| 887 | ApprovalWithdrawn { |
| 888 | id: String, |
| 889 | }, |
| 890 | |
| 891 | /// Request user input for a tool call |
| 892 | UserInputRequired { |
| 893 | id: String, |
| 894 | request: UserInputRequest, |
| 895 | }, |
| 896 | |
| 897 | UserInputClosed { |
| 898 | id: String, |
| 899 | outcome: UserInputClosedOutcome, |
| 900 | }, |
| 901 | |
| 902 | /// Authoritative API conversation state from the engine session. |
| 903 | /// |
| 904 | /// The UI receives granular display events, but those are not always a |
| 905 | /// lossless representation of the API transcript. DeepSeek can emit |
| 906 | /// reasoning directly followed by tool calls without a visible assistant |
| 907 | /// text block, and that assistant message still has to be persisted for |
| 908 | /// later `reasoning_content` replay. |
| 909 | SessionUpdated { |
| 910 | source: Option<crate::core::ops::SessionSnapshotSource>, |
| 911 | checkpoint: Option<Arc<SessionCheckpointRequest>>, |
| 912 | session_id: String, |
| 913 | /// Shared history snapshot (#6214 T2): the engine hands out an `Arc` |
| 914 | /// instead of deep-copying the transcript per event. |
| 915 | messages: Arc<Vec<Message>>, |
| 916 | system_prompt: Option<SystemPrompt>, |
| 917 | instruction_assembly: Option<Arc<crate::project_context::InstructionAssembly>>, |
| 918 | model: String, |
| 919 | workspace: PathBuf, |
| 920 | }, |
| 921 | |
| 922 | /// Request user decision after sandbox denial |
| 923 | // Consumers (TUI, runtime threads, exec agent, protocol parity) handle |
| 924 | // this, but the engine never emits it. It stayed "live" only because the |
| 925 | // deleted public `rlm::run_rlm_turn` put `Event` in the crate's public |
| 926 | // API (#6511). Whether to wire the emitter or drop the elevation flow is |
| 927 | // a separate product decision. |
| 928 | ElevationRequired { |
| 929 | tool_id: String, |
| 930 | tool_name: String, |
| 931 | command: Option<String>, |
| 932 | denial_reason: String, |
| 933 | blocked_network: bool, |
| 934 | blocked_write: bool, |
| 935 | }, |
| 936 | |
| 937 | /// Observable LSP repair-loop update for the Turn Inspector (#4107). |
| 938 | /// Carries only summary counts/state — never raw prompt internals. |
| 939 | LspRepairUpdate { |
| 940 | diagnostics_found: usize, |
| 941 | files: usize, |
| 942 | injected: bool, |
| 943 | }, |
| 944 | |
| 945 | /// Advisory note emitted by the background advisor watcher (#3982). |
| 946 | /// |
| 947 | /// A permission decision the runtime made for one proposed tool call |
| 948 | /// without a user prompt, so the transcript can carry a visible receipt |
| 949 | /// of who decided and why (the audit log keeps the full record). |
| 950 | /// |
| 951 | /// Only decisions a person would otherwise never see are emitted: |
| 952 | /// Auto-Review guardian verdicts, guardian failures (which deny, fail |
| 953 | /// closed), and deterministic Auto-Review blocks. Proven-safe |
| 954 | /// deterministic allows stay silent, like rule-based auto-approvals in |
| 955 | /// other harnesses, so a routine read does not spam the transcript. |
| 956 | ToolGateDecision { |
| 957 | /// The child (sub-agent / Fleet worker) whose call was gated, or |
| 958 | /// `None` for the parent turn. Hosts route a child's receipt into that |
| 959 | /// child's transcript. |
| 960 | agent_id: Option<String>, |
| 961 | /// Tool-call id the decision applies to. |
| 962 | tool_id: String, |
| 963 | /// Tool name as the model called it. |
| 964 | tool_name: String, |
| 965 | /// Which gate decided. |
| 966 | gate: ToolGate, |
| 967 | /// What it decided. |
| 968 | decision: ToolGateVerdict, |
| 969 | /// Reviewer risk tier when a guardian answered (`low`, `medium`, |
| 970 | /// `high`, `critical`); `None` for deterministic gates and failures. |
| 971 | risk: Option<String>, |
| 972 | reviewer_model: Option<String>, |
| 973 | /// Bounded, control-stripped rationale safe to render as one line. |
| 974 | reason: String, |
| 975 | rule: Option<String>, |
| 976 | receipt_id: Option<String>, |
| 977 | call_digest: Option<String>, |
| 978 | action_summary: Option<String>, |
| 979 | }, |
| 980 | |
| 981 | AutoReviewPaused { |
| 982 | reason: String, |
| 983 | approval_mode: codewhale_execpolicy::ApprovalMode, |
| 984 | }, |
| 985 | |
| 986 | /// Fired fire-and-forget after `TurnComplete` when the advisor is enabled |
| 987 | /// and the completed turn contained at least one tool call. The note is |
| 988 | /// a concise LLM-generated summary of concerns observed in the bounded |
| 989 | /// tool-call slice; it never blocks or fails the parent turn. |
| 990 | AdvisoryNote { |
| 991 | /// The turn whose tool calls were reviewed. |
| 992 | turn_id: String, |
| 993 | /// Concise advisory text (one to three sentences). May be suppressed |
| 994 | /// by the emission guard's rate-limit or dedup window. |
| 995 | note: String, |
| 996 | /// Number of tool-call pairs that were included in the review slice. |
| 997 | tool_call_count: u32, |
| 998 | }, |
| 999 | |
| 1000 | // === Prefix-Cache Stability Events === |
| 1001 | /// The prefix (system prompt + tool specs) changed between turns, |
| 1002 | /// which invalidates DeepSeek's KV prefix cache. Carries diagnostics |
| 1003 | /// for the TUI to surface. |
| 1004 | PrefixCacheChange { |
| 1005 | /// Human-readable description of what changed. |
| 1006 | description: String, |
| 1007 | /// Whether the system prompt component changed. |
| 1008 | system_prompt_changed: bool, |
| 1009 | /// Whether the tool set component changed. |
| 1010 | tools_changed: bool, |
| 1011 | /// Overall prefix stability percentage (100 = fully stable). |
| 1012 | stability_pct: u32, |
| 1013 | /// True when the prefix actually changed (cache invalidated). |
| 1014 | /// False for routine stable-check heartbeats. |
| 1015 | changed: bool, |
| 1016 | /// Current pinned prefix combined hash (SHA-256, 64 hex chars). |
| 1017 | /// Carried so `/cache stats` can surface it without reaching |
| 1018 | /// into the engine's PrefixStabilityManager. |
| 1019 | pinned_combined_hash: String, |
| 1020 | /// Why the current pin exists: `initial`, `resume`, or |
| 1021 | /// `change:<what>`. Empty when unknown. |
| 1022 | pin_reason: String, |
| 1023 | /// Explanation of the most recent expected miss (declared header |
| 1024 | /// change, history reset, or undeclared drift). Empty when none. |
| 1025 | last_miss_reason: String, |
| 1026 | /// `<context_update>` snapshots appended this session. |
| 1027 | context_updates: u64, |
| 1028 | }, |
| 1029 | |
| 1030 | ConversationTitle { |
| 1031 | title: String, |
| 1032 | }, |
| 1033 | |
| 1034 | ContentFilterRefusal { |
| 1035 | reason: String, |
| 1036 | refusal: Option<String>, |
| 1037 | }, |
| 1038 | |
| 1039 | PluginChanged { |
| 1040 | plugin: String, |
| 1041 | action: String, |
| 1042 | content_hash: Option<String>, |
| 1043 | decided_by: Option<String>, |
| 1044 | services: Vec<String>, |
| 1045 | tools_added: Vec<String>, |
| 1046 | tools_removed: Vec<String>, |
| 1047 | }, |
| 1048 | } |
| 1049 | |
| 1050 | /// Render the already-bounded name sample, marking an incomplete sample with |
| 1051 | /// a language-neutral ellipsis. The exact total remains available in typed |
| 1052 | /// runtime metadata. |
| 1053 | #[must_use] |
| 1054 | pub fn tool_projection_warning_tool_list( |
| 1055 | omitted_tool_names: &[String], |
| 1056 | omitted_tool_count: usize, |
| 1057 | ) -> String { |
| 1058 | let mut rendered = omitted_tool_names.join(", "); |
| 1059 | if omitted_tool_count > omitted_tool_names.len() { |
| 1060 | if !rendered.is_empty() { |
| 1061 | rendered.push_str(", "); |
| 1062 | } |
| 1063 | rendered.push('…'); |
| 1064 | } |
| 1065 | if rendered.is_empty() { |
| 1066 | rendered.push_str("<unnamed>"); |
| 1067 | } |
| 1068 | rendered |
| 1069 | } |
| 1070 | |
| 1071 | #[must_use] |
| 1072 | pub fn tool_projection_warning_message( |
| 1073 | provider: &str, |
| 1074 | omitted_tool_names: &[String], |
| 1075 | omitted_tool_count: usize, |
| 1076 | ) -> String { |
| 1077 | format!( |
| 1078 | "Warning: {provider} omitted tools for this request: {}. A tool is omitted when its input schema is incompatible with this route or when its encoded name is longer than the provider's tool-name limit (64 characters on OpenAI-style routes, 128 on Anthropic-style routes and DeepSeek); a name ending in … is cut for display. Shorten the tool's name (dots, hyphens and other special characters each add characters) or remove it.", |
| 1079 | tool_projection_warning_tool_list(omitted_tool_names, omitted_tool_count) |
| 1080 | ) |
| 1081 | } |
| 1082 | |
| 1083 | impl From<codewhale_models::ToolProjectionWarning> for Event { |
| 1084 | fn from(warning: codewhale_models::ToolProjectionWarning) -> Self { |
| 1085 | Self::ToolProjectionWarning { |
| 1086 | provider: warning.provider, |
| 1087 | omitted_tool_names: warning.omitted_tool_names, |
| 1088 | omitted_tool_count: warning.omitted_tool_count, |
| 1089 | } |
| 1090 | } |
| 1091 | } |
| 1092 | |
| 1093 | pub fn render_tool_projection_warning(warning: &codewhale_models::ToolProjectionWarning) -> String { |
| 1094 | tool_projection_warning_message( |
| 1095 | &warning.provider, |
| 1096 | &warning.omitted_tool_names, |
| 1097 | warning.omitted_tool_count, |
| 1098 | ) |
| 1099 | } |
| 1100 | |
| 1101 | impl Event { |
| 1102 | /// Create an error event from a categorized envelope. The envelope's own |
| 1103 | /// `recoverable` flag controls whether the UI flips into offline mode. |
| 1104 | pub fn error(envelope: ErrorEnvelope) -> Self { |
| 1105 | let recoverable = envelope.recoverable; |
| 1106 | Event::Error { |
| 1107 | envelope, |
| 1108 | recoverable, |
| 1109 | } |
| 1110 | } |
| 1111 | |
| 1112 | /// Create a new status event |
| 1113 | pub fn status(message: impl Into<String>) -> Self { |
| 1114 | Event::Status { |
| 1115 | message: message.into(), |
| 1116 | } |
| 1117 | } |
| 1118 | } |
| 1119 | |
| 1120 | /// Who a [`Event::Status`] line is for once it leaves the engine. |
| 1121 | /// |
| 1122 | /// The TUI shows every status in its transient footer, so it needs no |
| 1123 | /// classification. Durable clients (the runtime thread store and anything |
| 1124 | /// that renders its items) do: scheduler, continuation and schema-hydration |
| 1125 | /// lines are engine plumbing, and rendering them as transcript rows buries |
| 1126 | /// the user's actual conversation. |
| 1127 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1128 | pub enum StatusVisibility { |
| 1129 | /// Worth a transcript row. |
| 1130 | User, |
| 1131 | /// Engine plumbing: keep the receipt, but clients collapse it by default. |
| 1132 | Internal, |
| 1133 | /// Addressed to the model, which already receives it in a tool result. |
| 1134 | /// Never persist it as a user-facing item. |
| 1135 | ModelOnly, |
| 1136 | } |
| 1137 | |
| 1138 | impl StatusVisibility { |
| 1139 | /// Wire value carried in runtime item metadata (`metadata.visibility`). |
| 1140 | #[must_use] |
| 1141 | pub fn as_str(self) -> &'static str { |
| 1142 | match self { |
| 1143 | Self::User => "user", |
| 1144 | Self::Internal => "internal", |
| 1145 | Self::ModelOnly => "model_only", |
| 1146 | } |
| 1147 | } |
| 1148 | } |
| 1149 | |
| 1150 | /// Engine-owned retry status wording. Retain these observations in the TUI |
| 1151 | /// transcript without turning unrelated scheduler/footer updates into rows. |
| 1152 | #[must_use] |
| 1153 | pub fn is_retry_status_receipt(message: &str) -> bool { |
| 1154 | [ |
| 1155 | "Retry attempt: ", |
| 1156 | "Retry recovery: ", |
| 1157 | "Retry exhaustion: ", |
| 1158 | "Retry interrupted: ", |
| 1159 | "Retry stopped: ", |
| 1160 | ] |
| 1161 | .iter() |
| 1162 | .any(|prefix| message.starts_with(prefix)) |
| 1163 | } |
| 1164 | |
| 1165 | #[must_use] |
| 1166 | pub fn is_request_image_status_receipt(message: &str) -> bool { |
| 1167 | message.starts_with("Image request budget: ") || message.starts_with("HTTP 413 recovery: ") |
| 1168 | } |
| 1169 | |
| 1170 | /// Classify an engine status line for durable clients. Unknown lines stay |
| 1171 | /// user-visible; internal scheduler and model-only notices retain their scope. |
| 1172 | #[must_use] |
| 1173 | pub fn status_visibility(message: &str) -> StatusVisibility { |
| 1174 | let message = message.trim(); |
| 1175 | if message.starts_with("Loaded deferred tool '") |
| 1176 | && message.contains("Retry the call with its visible schema") |
| 1177 | { |
| 1178 | return StatusVisibility::ModelOnly; |
| 1179 | } |
| 1180 | let scheduler_row = message.starts_with("Executing tools sequentially") |
| 1181 | || (message.starts_with("Executing ") && message.ends_with(" parallel chunk(s)")); |
| 1182 | let continuation_row = message.starts_with("Continuing — ") |
| 1183 | || message.starts_with("Continuing active goal (pass "); |
| 1184 | // Successful agent completions already have their own durable receipts. |
| 1185 | // Keep failure-bearing or unknown resumption notices visible. |
| 1186 | let agent_resume_row = message |
| 1187 | .strip_prefix("Resuming turn with ") |
| 1188 | .and_then(|rest| rest.strip_suffix(" sub-agent completion(s)")) |
| 1189 | .is_some_and(|count| { |
| 1190 | let count = [" idle", " queued", " late"] |
| 1191 | .iter() |
| 1192 | .find_map(|suffix| count.strip_suffix(suffix)) |
| 1193 | .unwrap_or(count); |
| 1194 | count.parse::<usize>().is_ok_and(|count| count > 0) |
| 1195 | }); |
| 1196 | let approval_wait_row = (message.starts_with("Still waiting for tool approval on `") |
| 1197 | || message.starts_with("Still waiting for user input on `")) |
| 1198 | && message.ends_with("s — the turn is parked here until it is answered"); |
| 1199 | // #6511: a nested sub-RLM's forwarded rounds are the record of model |
| 1200 | // calls the parent never saw; keep them, collapsed. |
| 1201 | let nested_rlm_row = message.starts_with(crate::rlm::bridge::NESTED_RLM_STATUS_PREFIX); |
| 1202 | let mcp_guidance_row = message.starts_with("MCP server guidance added to context") |
| 1203 | || message == "MCP server guidance withdrawn from context"; |
| 1204 | if scheduler_row |
| 1205 | || continuation_row |
| 1206 | || agent_resume_row |
| 1207 | || approval_wait_row |
| 1208 | || nested_rlm_row |
| 1209 | || mcp_guidance_row |
| 1210 | { |
| 1211 | StatusVisibility::Internal |
| 1212 | } else { |
| 1213 | StatusVisibility::User |
| 1214 | } |
| 1215 | } |
| 1216 | |
| 1217 | /// The tool call named by the engine's tool-approval wait heartbeat |
| 1218 | /// ("Still waiting for tool approval on `<id>` after Ns — ..."), if `message` |
| 1219 | /// is one. The runtime uses it to drop a heartbeat for an approval it has |
| 1220 | /// already settled. |
| 1221 | #[must_use] |
| 1222 | pub fn approval_wait_tool_call(message: &str) -> Option<&str> { |
| 1223 | let message = message.trim(); |
| 1224 | if status_visibility(message) != StatusVisibility::Internal { |
| 1225 | return None; |
| 1226 | } |
| 1227 | message |
| 1228 | .strip_prefix("Still waiting for tool approval on `")? |
| 1229 | .rsplit_once("` after ") |
| 1230 | .map(|(call, _)| call) |
| 1231 | } |
| 1232 | |
| 1233 | /// Which permission gate produced a [`Event::ToolGateDecision`]. |
| 1234 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1235 | pub enum ToolGate { |
| 1236 | /// The deterministic Auto-Review policy engine (configured rules plus |
| 1237 | /// the built-in safety floor); never model-reviewed. |
| 1238 | AutoReviewDeterministic, |
| 1239 | /// The one-shot Auto-Review model guardian consulted for a fallback hold. |
| 1240 | AutoReviewGuardian, |
| 1241 | } |
| 1242 | |
| 1243 | impl ToolGate { |
| 1244 | #[must_use] |
| 1245 | pub fn as_str(self) -> &'static str { |
| 1246 | match self { |
| 1247 | Self::AutoReviewDeterministic => "auto_review_deterministic", |
| 1248 | Self::AutoReviewGuardian => "auto_review_guardian", |
| 1249 | } |
| 1250 | } |
| 1251 | } |
| 1252 | |
| 1253 | /// What a permission gate decided for one proposed tool call. |
| 1254 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1255 | pub enum ToolGateVerdict { |
| 1256 | /// The call may run without a user prompt. |
| 1257 | Allowed, |
| 1258 | /// The call was refused with a stated rationale. |
| 1259 | Denied, |
| 1260 | /// The gate could not produce a verdict (timeout, transport error, |
| 1261 | /// unparseable answer) and the call was denied, fail closed. |
| 1262 | Unavailable, |
| 1263 | } |
| 1264 | |
| 1265 | impl ToolGateVerdict { |
| 1266 | #[must_use] |
| 1267 | pub fn as_str(self) -> &'static str { |
| 1268 | match self { |
| 1269 | Self::Allowed => "allowed", |
| 1270 | Self::Denied => "denied", |
| 1271 | Self::Unavailable => "unavailable", |
| 1272 | } |
| 1273 | } |
| 1274 | } |
| 1275 | |
| 1276 | /// Bound a gate rationale to one safe transcript line: control and bidi |
| 1277 | /// format characters are dropped, whitespace is collapsed, and the text is |
| 1278 | /// capped so a verbose reviewer cannot flood the transcript. |
| 1279 | #[must_use] |
| 1280 | pub fn bounded_gate_reason(reason: &str) -> String { |
| 1281 | const MAX_CHARS: usize = 220; |
| 1282 | let cleaned: String = reason |
| 1283 | .chars() |
| 1284 | .filter(|c| !c.is_control() && !codewhale_sanitize::sanitize::is_bidi_control(*c)) |
| 1285 | .collect(); |
| 1286 | let collapsed = cleaned.split_whitespace().collect::<Vec<_>>().join(" "); |
| 1287 | if collapsed.chars().count() <= MAX_CHARS { |
| 1288 | return collapsed; |
| 1289 | } |
| 1290 | let mut out: String = collapsed.chars().take(MAX_CHARS - 1).collect(); |
| 1291 | out.push('…'); |
| 1292 | out |
| 1293 | } |
| 1294 | |
| 1295 | #[cfg(test)] |
| 1296 | mod tool_projection_warning_tests { |
| 1297 | use super::*; |
| 1298 | use codewhale_models::tool_projection::{ |
| 1299 | TOOL_PROJECTION_WARNING_MAX_NAME_CHARS, TOOL_PROJECTION_WARNING_MAX_NAMES, |
| 1300 | bounded_tool_projection_warning_names, |
| 1301 | }; |
| 1302 | |
| 1303 | #[test] |
| 1304 | fn projection_warning_message_names_the_tool_and_the_name_limit() { |
| 1305 | let names = vec!["web-x00002E-run".to_string()]; |
| 1306 | let message = tool_projection_warning_message("OpenAI", &names, 1); |
| 1307 | assert!(message.contains("web-x00002E-run"), "{message}"); |
| 1308 | assert!(message.contains("64 characters"), "{message}"); |
| 1309 | assert!(message.contains("128 on Anthropic-style"), "{message}"); |
| 1310 | } |
| 1311 | |
| 1312 | #[test] |
| 1313 | fn projection_warning_names_are_count_and_length_bounded() { |
| 1314 | let names: Vec<String> = (0..12) |
| 1315 | .map(|index| format!("tool-{index}-{}\nspoof", "x".repeat(100))) |
| 1316 | .collect(); |
| 1317 | |
| 1318 | let bounded = bounded_tool_projection_warning_names(&names); |
| 1319 | |
| 1320 | assert_eq!(bounded.len(), TOOL_PROJECTION_WARNING_MAX_NAMES); |
| 1321 | assert!( |
| 1322 | bounded |
| 1323 | .iter() |
| 1324 | .all(|name| name.chars().count() <= TOOL_PROJECTION_WARNING_MAX_NAME_CHARS) |
| 1325 | ); |
| 1326 | assert!(bounded.iter().all(|name| !name.contains('\n'))); |
| 1327 | assert!(tool_projection_warning_tool_list(&bounded, names.len()).ends_with(", …")); |
| 1328 | } |
| 1329 | } |
| 1330 | |
| 1331 | #[cfg(test)] |
| 1332 | mod status_visibility_tests { |
| 1333 | use super::{StatusVisibility, approval_wait_tool_call, status_visibility}; |
| 1334 | |
| 1335 | #[test] |
| 1336 | fn engine_plumbing_statuses_are_not_user_rows() { |
| 1337 | for internal in [ |
| 1338 | "Executing tools sequentially (writes, approvals, or non-parallel tools detected)", |
| 1339 | "Executing 3 read-only tools in 2 parallel chunk(s)", |
| 1340 | "Continuing — tool results", |
| 1341 | "Continuing — queued steer input", |
| 1342 | "Continuing active goal (pass 2 this turn, 5 total)", |
| 1343 | "Resuming turn with 1 sub-agent completion(s)", |
| 1344 | "Resuming turn with 2 idle sub-agent completion(s)", |
| 1345 | "Resuming turn with 3 queued sub-agent completion(s)", |
| 1346 | "Resuming turn with 4 late sub-agent completion(s)", |
| 1347 | "Still waiting for tool approval on `call-1` after 60s — the turn is parked here until it is answered", |
| 1348 | "Still waiting for user input on `call-2` after 120s — the turn is parked here until it is answered", |
| 1349 | ] { |
| 1350 | assert_eq!( |
| 1351 | status_visibility(internal), |
| 1352 | StatusVisibility::Internal, |
| 1353 | "{internal}" |
| 1354 | ); |
| 1355 | } |
| 1356 | for model_only in [ |
| 1357 | "Loaded deferred tool 'load_skill'. Retry the call with its visible schema.", |
| 1358 | "Loaded deferred tool 'load_skill' after resolving 'skill'. Retry the call with its visible schema.", |
| 1359 | ] { |
| 1360 | assert_eq!( |
| 1361 | status_visibility(model_only), |
| 1362 | StatusVisibility::ModelOnly, |
| 1363 | "{model_only}" |
| 1364 | ); |
| 1365 | } |
| 1366 | for user in [ |
| 1367 | "Request cancelled", |
| 1368 | "Reconnecting…", |
| 1369 | "Goal set; starting goal work.", |
| 1370 | "Still waiting for the service to reconnect; retry in a moment.", |
| 1371 | "Still waiting for tool approval on `call-1` after an unexpected failure", |
| 1372 | "Resuming turn with 1 sub-agent completion(s) (1 failed)", |
| 1373 | "Resuming turn with 2 idle sub-agent completion(s) (1 failed)", |
| 1374 | "Resuming turn with unexpected sub-agent completion(s)", |
| 1375 | "Resuming turn with 1 unknown sub-agent completion(s)", |
| 1376 | "Turn ending with 1 detached sub-agent(s) still running in the background; they'll report when done.", |
| 1377 | ] { |
| 1378 | assert_eq!(status_visibility(user), StatusVisibility::User, "{user}"); |
| 1379 | } |
| 1380 | assert_eq!(StatusVisibility::Internal.as_str(), "internal"); |
| 1381 | } |
| 1382 | |
| 1383 | #[test] |
| 1384 | fn retry_status_receipts_classify_every_closing_kind_without_footer_noise() { |
| 1385 | for message in [ |
| 1386 | "Retry attempt: transport 1/2; upstream 503; waiting 0.00s", |
| 1387 | "Retry recovery: stream recovered after 1 retries", |
| 1388 | "Retry exhaustion: stream stopped after 2 retries", |
| 1389 | "Retry interrupted: request cancelled", |
| 1390 | "Retry stopped: transparent stream completion was not observed", |
| 1391 | ] { |
| 1392 | assert!(super::is_retry_status_receipt(message), "{message}"); |
| 1393 | assert_eq!(status_visibility(message), StatusVisibility::User); |
| 1394 | } |
| 1395 | for message in [ |
| 1396 | "Executing tools sequentially", |
| 1397 | "Loaded deferred tool 'load_skill'. Retry the call with its visible schema.", |
| 1398 | "Goal set; starting goal work.", |
| 1399 | "Retry stopped", |
| 1400 | ] { |
| 1401 | assert!(!super::is_retry_status_receipt(message), "{message}"); |
| 1402 | } |
| 1403 | } |
| 1404 | |
| 1405 | #[test] |
| 1406 | fn approval_wait_tool_call_names_the_raw_call_id() { |
| 1407 | assert_eq!( |
| 1408 | approval_wait_tool_call( |
| 1409 | "Still waiting for tool approval on `call_00_x|99765c30-c427` after 60s — the turn is parked here until it is answered" |
| 1410 | ), |
| 1411 | Some("call_00_x|99765c30-c427") |
| 1412 | ); |
| 1413 | for not_a_heartbeat in [ |
| 1414 | "Still waiting for user input on `call-2` after 120s — the turn is parked here until it is answered", |
| 1415 | "Still waiting for tool approval on `call-1` after an unexpected failure", |
| 1416 | "Continuing — tool results", |
| 1417 | ] { |
| 1418 | assert_eq!( |
| 1419 | approval_wait_tool_call(not_a_heartbeat), |
| 1420 | None, |
| 1421 | "{not_a_heartbeat}" |
| 1422 | ); |
| 1423 | } |
| 1424 | } |
| 1425 | } |
| 1426 |