| 1 | //! Non-interactive exec agent assembly: the `run_exec_agent` pipeline |
| 2 | //! that resolves the CLI route, builds the engine configuration, spawns |
| 3 | //! the engine, and drives the exec output stream to completion. |
| 4 | //! |
| 5 | |
| 6 | use anyhow::Context; |
| 7 | use anyhow::Result; |
| 8 | use anyhow::bail; |
| 9 | use clap::ValueEnum; |
| 10 | use codewhale_engine::core::ops::TurnSpec; |
| 11 | use codewhale_engine::exec_events::ExecAgentEvents; |
| 12 | use codewhale_engine::exec_events::exec_error_event_is_fatal; |
| 13 | use codewhale_engine::fleet::executor::exec_stream_final_answer_excerpt; |
| 14 | use codewhale_engine::model_routing; |
| 15 | use codewhale_engine::route_receipt::ExecRouteBinding; |
| 16 | use codewhale_engine::session_manager; |
| 17 | use codewhale_engine::session_manager::SessionManager; |
| 18 | use codewhale_engine::session_manager::truncate_id; |
| 19 | use codewhale_models::ContentBlock; |
| 20 | use codewhale_models::Message; |
| 21 | use codewhale_models::Role; |
| 22 | use codewhale_models::SystemPrompt; |
| 23 | use codewhale_runtime::config::Config; |
| 24 | use codewhale_runtime::config::MAX_SUBAGENTS; |
| 25 | use serde_json::Value; |
| 26 | use std::collections::HashMap; |
| 27 | use std::io; |
| 28 | use std::io::Write; |
| 29 | use std::path::Path; |
| 30 | use std::path::PathBuf; |
| 31 | use std::sync::Arc; |
| 32 | use std::sync::atomic::AtomicBool; |
| 33 | use std::sync::atomic::Ordering; |
| 34 | use std::time::Duration; |
| 35 | use std::time::Instant; |
| 36 | |
| 37 | /// Resolve the headless `exec` model-step ceiling. |
| 38 | /// |
| 39 | /// Omission leaves model steps uncapped. Clap rejects `--max-turns 0`; |
| 40 | /// explicit positive values retain the documented finite range. |
| 41 | pub fn exec_max_steps(max_turns: Option<u32>) -> u32 { |
| 42 | codewhale_runtime::turn_budget::resolve_max_model_steps(max_turns) |
| 43 | } |
| 44 | |
| 45 | /// Model-step ceiling for a plain (zero-tool) `exec` run without |
| 46 | /// `--max-turns`. Its only extra steps are output-limit continuations, which |
| 47 | /// have no progress signal of their own; without this a model stuck at the |
| 48 | /// output limit would be re-asked, with growing history, until the turn wall |
| 49 | /// clock (#6510 review). |
| 50 | pub const ONE_SHOT_DEFAULT_MAX_STEPS: u32 = 8; |
| 51 | |
| 52 | /// Default-denied tools for headless `exec`, on top of the operator's own |
| 53 | /// `--disallowed-tools` flag. |
| 54 | /// |
| 55 | /// A headless run has no responder for `request_user_input`, so offering the |
| 56 | /// tool can only stall the run until the turn wall clock, or forever with |
| 57 | /// `[tools] user_input_timeout_seconds = 0`. Withholding it is the default |
| 58 | /// form of the operator workaround (`--disallowed-tools request_user_input`): |
| 59 | /// the model reports the tool absent and finishes instead of parking. This |
| 60 | /// stays unconditional: there is no channel on which a one-shot CLI run |
| 61 | /// could answer, so advertising the tool cannot work. |
| 62 | pub(crate) fn exec_disallowed_tools(disallowed_tools: Option<Vec<String>>) -> Option<Vec<String>> { |
| 63 | use codewhale_tools::names::REQUEST_USER_INPUT_NAME; |
| 64 | let mut disallowed = disallowed_tools.unwrap_or_default(); |
| 65 | if !disallowed |
| 66 | .iter() |
| 67 | .any(|tool| tool.as_str() == REQUEST_USER_INPUT_NAME) |
| 68 | { |
| 69 | disallowed.push(REQUEST_USER_INPUT_NAME.to_string()); |
| 70 | } |
| 71 | Some(disallowed) |
| 72 | } |
| 73 | |
| 74 | async fn shutdown_exec_engine( |
| 75 | handle: &codewhale_engine::core::engine::EngineHandle, |
| 76 | deadline: tokio::time::Instant, |
| 77 | ) -> Option<codewhale_engine::core::engine::EngineRunCompletion> { |
| 78 | tokio::time::timeout_at(deadline, async { |
| 79 | let _ = handle.send(codewhale_engine::core::ops::Op::Shutdown).await; |
| 80 | handle.wait_run_completion().await |
| 81 | }) |
| 82 | .await |
| 83 | .ok() |
| 84 | } |
| 85 | |
| 86 | /// Attach the durable automation store headless `exec` inspects. |
| 87 | /// |
| 88 | /// Headless exec builds its catalog from the same tool surface the TUI and the |
| 89 | /// Runtime host do, so it advertises `automation` and `send_later` whether or |
| 90 | /// not the store behind them is attached. Left unattached, every call failed |
| 91 | /// "AutomationManager is not attached" — the tool was real and the service was |
| 92 | /// missing. This opens the same store those two hosts open: a shared directory |
| 93 | /// guarded per transaction by its own file locks (`AutomationManager::open`), |
| 94 | /// so it adds no second store, no scheduler, and no second scheduling |
| 95 | /// authority. |
| 96 | /// |
| 97 | /// What exec deliberately does not take is the Runtime's task-execution lease. |
| 98 | /// That lease is exclusive (`TaskExecutionLease::new`) and a one-shot host must |
| 99 | /// neither contend with it nor recover work from the process that holds it. So |
| 100 | /// the manager returned here is *unbound*: inspection works, and everything |
| 101 | /// that would promise dispatch is refused by the tool's own admission check |
| 102 | /// (`tools::automation::require_dispatch_owner`) rather than persisting a |
| 103 | /// schedule nothing would honor. |
| 104 | /// |
| 105 | /// Fleet worker subprocesses get nothing, keeping the narrowed envelope they |
| 106 | /// were launched with alongside the empty plugin registry and disabled |
| 107 | /// subagents. A store that cannot be opened is reported, never swallowed: |
| 108 | /// both other hosts fail startup on it, so exec does too instead of |
| 109 | /// advertising an automation surface it silently cannot serve. |
| 110 | pub(crate) fn exec_automation_services( |
| 111 | fleet_authority_active: bool, |
| 112 | ) -> Result<Option<codewhale_engine::automation_manager::SharedAutomationManager>> { |
| 113 | if fleet_authority_active { |
| 114 | return Ok(None); |
| 115 | } |
| 116 | let service = codewhale_engine::automation_manager::AutomationManager::default_location() |
| 117 | .context("open the automation store for headless exec")?; |
| 118 | Ok(Some(std::sync::Arc::new(tokio::sync::Mutex::new(service)))) |
| 119 | } |
| 120 | |
| 121 | /// Printed to stderr when a tool-less one-shot `exec` answer contained |
| 122 | /// tool-call markup that the engine stripped from the visible output. |
| 123 | pub(crate) const ONE_SHOT_TOOL_CALL_NOTICE: &str = "codewhale exec: the model tried to call a tool, but this run offers none, so the tool call was removed from the answer. Re-run with --auto (or --allowed-tools) to let it use tools."; |
| 124 | |
| 125 | async fn persist_exec_checkpoint( |
| 126 | request: Arc<codewhale_engine::core::events::SessionCheckpointRequest>, |
| 127 | manager: Option<Arc<SessionManager>>, |
| 128 | session_id: &str, |
| 129 | workspace: &Path, |
| 130 | turn_id: Option<&str>, |
| 131 | engine: &codewhale_engine::core::engine::EngineHandle, |
| 132 | deadline: Instant, |
| 133 | source: &mut Option<codewhale_engine::session_manager::SessionWriteReceipt>, |
| 134 | binding: Option<&ExecRouteBinding>, |
| 135 | ) { |
| 136 | if turn_id != Some(request.caller.turn_id.as_str()) { |
| 137 | request.fail("exec session checkpoint does not match its active turn"); |
| 138 | return; |
| 139 | } |
| 140 | if let Err(error) = request.validate_prefix(session_id, workspace, &request.snapshot.messages) { |
| 141 | request.fail(error); |
| 142 | return; |
| 143 | } |
| 144 | let turn_cancel = engine.captured_turn_cancel(); |
| 145 | if turn_cancel.is_cancelled() { |
| 146 | request.fail("exec session checkpoint cancelled before persistence"); |
| 147 | return; |
| 148 | } |
| 149 | if Instant::now() >= deadline { |
| 150 | request.fail("exec session checkpoint deadline expired before persistence"); |
| 151 | engine.cancel_with_reason(codewhale_engine::core::engine::CancelReason::External); |
| 152 | return; |
| 153 | } |
| 154 | let Some(manager) = manager else { |
| 155 | request.no_backend(); |
| 156 | return; |
| 157 | }; |
| 158 | let Some(captured_source) = source.clone() else { |
| 159 | request.fail("exec checkpoint has no admitted original session source"); |
| 160 | return; |
| 161 | }; |
| 162 | let Some(captured_owner) = request.snapshot.source.clone() else { |
| 163 | request.fail("exec checkpoint has no native Engine source"); |
| 164 | return; |
| 165 | }; |
| 166 | let write_request = Arc::clone(&request); |
| 167 | let binding = binding.cloned(); |
| 168 | let mut writer = tokio::task::spawn_blocking( |
| 169 | move || -> Result<codewhale_engine::session_manager::SessionPublication> { |
| 170 | let snapshot = &write_request.snapshot; |
| 171 | let publication = persist_exec_session( |
| 172 | &snapshot.messages, |
| 173 | &snapshot.model, |
| 174 | PersistedProviderRoute { |
| 175 | kind: &snapshot.model_provider, |
| 176 | id: snapshot.model_provider_id.as_deref(), |
| 177 | binding: binding.as_ref(), |
| 178 | }, |
| 179 | &snapshot.workspace, |
| 180 | &snapshot.system_prompt, |
| 181 | Some(&snapshot.session_id), |
| 182 | snapshot.total_tokens, |
| 183 | None, |
| 184 | manager.as_ref(), |
| 185 | &[], |
| 186 | Some(write_request.as_ref()), |
| 187 | &captured_source, |
| 188 | &captured_owner, |
| 189 | snapshot.agent_preset.as_deref(), |
| 190 | )?; |
| 191 | Ok(publication) |
| 192 | }, |
| 193 | ); |
| 194 | let result = tokio::select! { |
| 195 | biased; |
| 196 | () = request.withdraw.cancelled() => { |
| 197 | request.fail("exec session checkpoint was withdrawn; its write may have completed"); |
| 198 | writer.await |
| 199 | } |
| 200 | () = turn_cancel.cancelled() => { |
| 201 | request.fail("exec session checkpoint was cancelled; its write may have completed"); |
| 202 | request.withdraw.cancel(); |
| 203 | writer.await |
| 204 | } |
| 205 | () = tokio::time::sleep_until(deadline.into()) => { |
| 206 | request.fail("exec session checkpoint deadline expired; its write may have completed"); |
| 207 | request.withdraw.cancel(); |
| 208 | engine.cancel_with_reason(codewhale_engine::core::engine::CancelReason::External); |
| 209 | writer.await |
| 210 | } |
| 211 | result = &mut writer => result, |
| 212 | }; |
| 213 | match result { |
| 214 | Ok(Ok(publication)) => { |
| 215 | *source = Some(publication.write_receipt()); |
| 216 | request.succeed(publication.checkpoint_receipt); |
| 217 | } |
| 218 | Ok(Err(error)) => request.fail(format!("exec session checkpoint failed: {error:#}")), |
| 219 | Err(error) => request.fail(format!("exec session checkpoint writer failed: {error}")), |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | pub struct ExecJsonSchema { |
| 224 | pub schema: serde_json::Value, |
| 225 | pub validator: codewhale_engine::ResponseSchemaValidator, |
| 226 | } |
| 227 | |
| 228 | pub async fn parse_exec_json_schema(raw: &str) -> Result<ExecJsonSchema> { |
| 229 | use anyhow::Context as _; |
| 230 | let text = match raw.strip_prefix('@') { |
| 231 | Some(path) if path.trim().is_empty() => { |
| 232 | anyhow::bail!("exec --json-schema: `@` requires a file path"); |
| 233 | } |
| 234 | Some(path) => tokio::fs::read_to_string(path) |
| 235 | .await |
| 236 | .with_context(|| format!("failed to read --json-schema file `{path}`"))?, |
| 237 | None => raw.to_string(), |
| 238 | }; |
| 239 | let schema: serde_json::Value = serde_json::from_str(&text) |
| 240 | .map_err(|err| anyhow::anyhow!("exec --json-schema: invalid JSON: {err}"))?; |
| 241 | let validator = codewhale_engine::compile_response_schema("exec --json-schema", &schema) |
| 242 | .map_err(anyhow::Error::msg)?; |
| 243 | Ok(ExecJsonSchema { schema, validator }) |
| 244 | } |
| 245 | |
| 246 | #[allow(clippy::too_many_arguments)] |
| 247 | pub async fn run_exec_agent( |
| 248 | config: &Config, |
| 249 | model: &str, |
| 250 | prompt: &str, |
| 251 | workspace: PathBuf, |
| 252 | max_subagents: usize, |
| 253 | auto_approve: bool, |
| 254 | allow_sandbox_elevation: bool, |
| 255 | explicit_sandbox: Option<&str>, |
| 256 | json_output: bool, |
| 257 | resume_session: Option<codewhale_engine::session_manager::SavedSession>, |
| 258 | explicitly_reselected_route: bool, |
| 259 | force_configured_route: bool, |
| 260 | output_format: ExecOutputFormat, |
| 261 | max_turns: u32, |
| 262 | max_tool_calls: Option<u32>, |
| 263 | allowed_tools: Option<Vec<String>>, |
| 264 | disallowed_tools: Option<Vec<String>>, |
| 265 | append_system_prompt: Option<String>, |
| 266 | tool_authority_json: Option<String>, |
| 267 | exec_hooks_enabled: bool, |
| 268 | plugin_registry: std::sync::Arc<codewhale_plugins::PluginRegistry>, |
| 269 | permission_mode: Option<codewhale_engine::runtime_options::PermissionMode>, |
| 270 | // #6510: plain `exec` (no tool-surface flag). The caller passes an empty |
| 271 | // allowlist; this also skips workspace snapshots, LSP and the automation |
| 272 | // store. |
| 273 | one_shot: bool, |
| 274 | conversation_mode: Option<String>, |
| 275 | receipt_written: &AtomicBool, |
| 276 | json_schema: Option<ExecJsonSchema>, |
| 277 | ) -> Result<()> { |
| 278 | use codewhale_config::AppMode; |
| 279 | use codewhale_engine::compaction::CompactionConfig; |
| 280 | use codewhale_engine::core::engine::{EngineConfig, spawn_headless_engine}; |
| 281 | use codewhale_engine::core::events::Event; |
| 282 | use codewhale_engine::core::ops::Op; |
| 283 | use codewhale_engine::tools::plan::new_shared_plan_state; |
| 284 | use codewhale_engine::tools::todo::new_shared_todo_list; |
| 285 | use codewhale_execpolicy::ApprovalMode; |
| 286 | |
| 287 | let _timing = codewhale_runtime::logging::PhaseTimer::start("exec_total"); |
| 288 | let startup_timing = codewhale_runtime::logging::PhaseTimer::start("exec_startup"); |
| 289 | ignore_sigpipe_for_headless_exec(); |
| 290 | |
| 291 | // Withhold `request_user_input`; a headless run has no responder. |
| 292 | let disallowed_tools = exec_disallowed_tools(disallowed_tools); |
| 293 | |
| 294 | // Headless exec registers the model-facing notify tool too. Project the |
| 295 | // final merged config before tool setup so `off`, quiet/category gates, |
| 296 | // and explicit `always` are truthful outside the interactive TUI. With no |
| 297 | // focus-reporting channel, fail closed to focused; only explicit `always` |
| 298 | // may authorize a headless desktop notification. |
| 299 | let terminal = codewhale_runtime::host_terminal::host(); |
| 300 | terminal.set_terminal_focused(true); |
| 301 | terminal.apply_notification_settings(&config.notifications_config()); |
| 302 | |
| 303 | validate_exec_tool_authority_resume(tool_authority_json.as_deref(), resume_session.is_some())?; |
| 304 | let fleet_authority = tool_authority_json |
| 305 | .as_deref() |
| 306 | .map(codewhale_engine::tools::spec::ToolAuthorityEnvelope::from_json) |
| 307 | .transpose() |
| 308 | .map_err(anyhow::Error::msg)?; |
| 309 | let fleet_authority_active = fleet_authority.is_some(); |
| 310 | let outer_network_access = fleet_authority |
| 311 | .as_ref() |
| 312 | .and_then(|authority| authority.network_access); |
| 313 | let outer_shell_authority = fleet_authority |
| 314 | .as_ref() |
| 315 | .map(|authority| authority.shell) |
| 316 | .unwrap_or_default(); |
| 317 | if let Some(envelope) = fleet_authority { |
| 318 | codewhale_engine::tools::spec::install_process_tool_authority(envelope) |
| 319 | .map_err(anyhow::Error::msg)?; |
| 320 | } |
| 321 | |
| 322 | let fleet_capture = match ( |
| 323 | std::env::var("CODEWHALE_FLEET_CAPTURE_ID").ok(), |
| 324 | std::env::var_os("CODEWHALE_FLEET_CAPTURE_DIR"), |
| 325 | ) { |
| 326 | (Some(id), Some(dir)) => { |
| 327 | uuid::Uuid::parse_str(&id).context("invalid Fleet session capture id")?; |
| 328 | anyhow::ensure!( |
| 329 | resume_session.is_none(), |
| 330 | "Fleet capture cannot resume a session" |
| 331 | ); |
| 332 | let manager = SessionManager::new(PathBuf::from(dir))?; |
| 333 | match manager.load_session(&id) { |
| 334 | Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} |
| 335 | _ => anyhow::bail!("Fleet session capture id is already in use or unavailable"), |
| 336 | } |
| 337 | Some((id, manager)) |
| 338 | } |
| 339 | (None, None) => None, |
| 340 | _ => anyhow::bail!("incomplete Fleet session capture destination"), |
| 341 | }; |
| 342 | |
| 343 | let mut exec_write_receipt = resume_session |
| 344 | .as_ref() |
| 345 | .and_then(|saved| saved.write_receipt.clone()); |
| 346 | let exec_agent_preset = resume_session.as_ref().map_or_else( |
| 347 | || conversation_mode.clone(), |
| 348 | |saved| saved.agent_preset.clone(), |
| 349 | ); |
| 350 | let exec_is_fresh = resume_session.is_none(); |
| 351 | |
| 352 | let exec_session_id = fleet_capture |
| 353 | .as_ref() |
| 354 | .map(|(id, _)| id.clone()) |
| 355 | .or_else(|| { |
| 356 | resume_session |
| 357 | .as_ref() |
| 358 | .map(|saved| saved.metadata.id.clone()) |
| 359 | }) |
| 360 | .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); |
| 361 | let exec_session_workspace = resume_session |
| 362 | .as_ref() |
| 363 | .map(|saved| saved.metadata.workspace.clone()) |
| 364 | .unwrap_or_else(|| workspace.clone()); |
| 365 | let mut should_persist_session = !one_shot |
| 366 | || resume_session.is_some() |
| 367 | || fleet_capture.is_some() |
| 368 | || output_format == ExecOutputFormat::StreamJson; |
| 369 | let is_fleet_worker = fleet_authority_active || fleet_capture.is_some(); |
| 370 | let mut exec_session_manager = fleet_capture.map(|(_, manager)| Arc::new(manager)); |
| 371 | let _exec_operation_lease = if exec_is_fresh { |
| 372 | match admit_cli_saved_operation( |
| 373 | exec_session_manager.clone(), |
| 374 | exec_session_id.clone(), |
| 375 | exec_session_workspace.clone(), |
| 376 | model.to_string(), |
| 377 | config |
| 378 | .active_provider_identity() |
| 379 | .map_err(anyhow::Error::msg)?, |
| 380 | prompt.to_string(), |
| 381 | ) |
| 382 | .await |
| 383 | { |
| 384 | Ok((manager, source, lease)) => { |
| 385 | exec_session_manager = Some(manager); |
| 386 | exec_write_receipt = Some(source); |
| 387 | Some(lease) |
| 388 | } |
| 389 | Err(error) => { |
| 390 | tracing::warn!(%error, "could not admit exec's saved accounting operation; continuing with unknown cost"); |
| 391 | None |
| 392 | } |
| 393 | } |
| 394 | } else { |
| 395 | None |
| 396 | }; |
| 397 | let mut open_exec_session_manager = || -> Result<Arc<SessionManager>> { |
| 398 | if exec_session_manager.is_none() { |
| 399 | exec_session_manager = Some(Arc::new( |
| 400 | SessionManager::default_location().context("could not open exec session store")?, |
| 401 | )); |
| 402 | } |
| 403 | Ok(Arc::clone( |
| 404 | exec_session_manager |
| 405 | .as_ref() |
| 406 | .expect("opened exec session store"), |
| 407 | )) |
| 408 | }; |
| 409 | if should_persist_session { |
| 410 | open_exec_session_manager()?; |
| 411 | } |
| 412 | let required_binding = |
| 413 | required_exec_resume_binding(resume_session.as_ref(), explicitly_reselected_route); |
| 414 | let binding_key = if required_binding.is_some() || should_persist_session { |
| 415 | load_exec_route_binding_key(open_exec_session_manager(), required_binding.is_none()).await |
| 416 | } else { |
| 417 | None |
| 418 | }; |
| 419 | check_exec_resume_endpoint( |
| 420 | required_binding, |
| 421 | binding_key.as_ref(), |
| 422 | &config.active_route_base_url(), |
| 423 | )?; |
| 424 | |
| 425 | let bound_go = required_binding.filter(|binding| binding.go_dispatch.is_some()); |
| 426 | if let Some(saved) = bound_go { |
| 427 | let key = binding_key |
| 428 | .as_ref() |
| 429 | .ok_or_else(|| anyhow::anyhow!(EXEC_RESUME_RESELECT))?; |
| 430 | anyhow::ensure!( |
| 431 | force_configured_route |
| 432 | && !model.trim().eq_ignore_ascii_case("auto") |
| 433 | && config |
| 434 | .active_provider_identity() |
| 435 | .is_ok_and(|id| id.provider == codewhale_config::ProviderKind::OpencodeGo), |
| 436 | "{EXEC_RESUME_RESELECT}" |
| 437 | ); |
| 438 | let config = config.clone(); |
| 439 | let key = *key; |
| 440 | let discovery = codewhale_runtime::runtime_control::owner_work(move || { |
| 441 | codewhale_engine::client::CodewhaleClient::for_catalog_refresh(&config)? |
| 442 | .go_discovery_binding(&key, &config) |
| 443 | }) |
| 444 | .await?; |
| 445 | anyhow::ensure!( |
| 446 | discovery.authority == saved.authority && discovery.endpoint == saved.endpoint, |
| 447 | "{EXEC_RESUME_RESELECT}" |
| 448 | ); |
| 449 | } |
| 450 | |
| 451 | let accounting_origin = exec_write_receipt.as_ref().and_then(|receipt| { |
| 452 | match receipt.usage_origin(codewhale_engine::cost_status::scope_token()) { |
| 453 | Ok(origin) => Some(origin), |
| 454 | Err(error) => { |
| 455 | tracing::warn!(%error, "exec accounting origin unavailable; continuing with unknown cost"); |
| 456 | None |
| 457 | } |
| 458 | } |
| 459 | }); |
| 460 | let preselected_go = config.active_provider_identity().ok().filter(|identity| { |
| 461 | required_binding.is_none() |
| 462 | && !force_configured_route |
| 463 | && !model.trim().eq_ignore_ascii_case("auto") |
| 464 | && identity.provider == codewhale_config::ProviderKind::OpencodeGo |
| 465 | }); |
| 466 | if let Some(identity) = &preselected_go { |
| 467 | codewhale_engine::provider_lake::refresh_account_catalog_before_first_request(config).await; |
| 468 | anyhow::ensure!( |
| 469 | matches!( |
| 470 | codewhale_engine::provider_catalog_live::status_for_route( |
| 471 | identity.provider, |
| 472 | identity.key.as_str(), |
| 473 | &config.active_route_base_url() |
| 474 | ), |
| 475 | codewhale_config::catalog::CatalogStatus::Fresh |
| 476 | ), |
| 477 | "Go inventory is unavailable. Reselect an explicit provider to run this model." |
| 478 | ); |
| 479 | } |
| 480 | let route = resolve_cli_exec_route( |
| 481 | config, |
| 482 | model, |
| 483 | prompt, |
| 484 | force_configured_route, |
| 485 | accounting_origin.clone(), |
| 486 | ) |
| 487 | .await?; |
| 488 | let execution_config = config_for_cli_route(config, &route)?; |
| 489 | let account_refresh_attempted = if (required_binding.is_none() || bound_go.is_some()) |
| 490 | && preselected_go.as_ref() != Some(&route.provider) |
| 491 | { |
| 492 | codewhale_engine::provider_lake::refresh_account_catalog_before_first_request( |
| 493 | &execution_config, |
| 494 | ) |
| 495 | .await |
| 496 | } else { |
| 497 | false |
| 498 | }; |
| 499 | let auto_model = route.auto_model; |
| 500 | let effective_identity = execution_config |
| 501 | .active_provider_identity() |
| 502 | .map_err(anyhow::Error::msg)?; |
| 503 | let effective_provider = effective_identity.provider; |
| 504 | if is_fleet_worker |
| 505 | && effective_provider != codewhale_config::ProviderKind::OpencodeGo |
| 506 | && !account_refresh_attempted |
| 507 | { |
| 508 | let config = execution_config.clone(); |
| 509 | let identity = effective_identity.clone(); |
| 510 | let refresh = codewhale_runtime::runtime_control::owner_work(move || { |
| 511 | codewhale_engine::worker_model_pool::requires_inventory(&config, &identity) |
| 512 | }) |
| 513 | .await?; |
| 514 | if refresh { |
| 515 | codewhale_engine::provider_lake::update_provider_catalog( |
| 516 | &execution_config, |
| 517 | &effective_identity, |
| 518 | ) |
| 519 | .await; |
| 520 | } |
| 521 | } |
| 522 | let effective_model = route.model; |
| 523 | let mut validated_route = codewhale_engine::route_runtime::resolve_runtime_route_for_identity( |
| 524 | &execution_config, |
| 525 | &effective_identity, |
| 526 | Some(&effective_model), |
| 527 | ) |
| 528 | .map_err(anyhow::Error::msg)? |
| 529 | .validate_for_async(codewhale_engine::route_runtime::RouteErrorSurface::Headless) |
| 530 | .await |
| 531 | .map_err(anyhow::Error::msg)?; |
| 532 | if is_fleet_worker { |
| 533 | let config = validated_route.config.clone(); |
| 534 | let identity = validated_route.identity.clone(); |
| 535 | let model = validated_route |
| 536 | .candidate |
| 537 | .wire_model_id() |
| 538 | .as_str() |
| 539 | .to_owned(); |
| 540 | codewhale_runtime::runtime_control::owner_work(move || { |
| 541 | codewhale_engine::worker_model_pool::require_worker(&config, &identity, &model) |
| 542 | }) |
| 543 | .await?; |
| 544 | } |
| 545 | validated_route.client.pin_exec_auth_scope().await?; |
| 546 | let mut deferred_binding = (!should_persist_session).then(|| { |
| 547 | ( |
| 548 | validated_route.client.clone(), |
| 549 | validated_route.config.clone(), |
| 550 | ) |
| 551 | }); |
| 552 | let mut route_binding = match binding_key.as_ref() { |
| 553 | Some(key) => validated_route |
| 554 | .client |
| 555 | .exec_route_binding(key, &validated_route.config)?, |
| 556 | None => ExecRouteBinding::default(), |
| 557 | }; |
| 558 | check_exec_resume_authority(required_binding, &route_binding)?; |
| 559 | if required_binding.is_some() && bound_go.is_none() { |
| 560 | codewhale_engine::provider_lake::refresh_account_catalog_before_first_request( |
| 561 | &execution_config, |
| 562 | ) |
| 563 | .await; |
| 564 | } |
| 565 | let effective_identity = validated_route.identity.clone(); |
| 566 | let effective_provider_name = effective_identity.key.to_string(); |
| 567 | let (effective_provider_kind, effective_stream_provider_id) = |
| 568 | exec_stream_provider_route(&validated_route.identity); |
| 569 | let route_source = if auto_model { |
| 570 | "auto_resolver" |
| 571 | } else { |
| 572 | "explicit_or_configured" |
| 573 | } |
| 574 | .to_string(); |
| 575 | let exec_started = Instant::now(); |
| 576 | let prompt_sha256 = format!( |
| 577 | "sha256:{}", |
| 578 | codewhale_runtime::hashing::sha256_hex(prompt.as_bytes()) |
| 579 | ); |
| 580 | let mut binary_identity = |
| 581 | (output_format == ExecOutputFormat::StreamJson).then(start_binary_sha256); |
| 582 | let approval_posture = if auto_approve { "auto_tools" } else { "ask" }.to_string(); |
| 583 | // The Full Access posture travels in the op's auto_approve/approval_mode |
| 584 | // fields; modes no longer carry permission. |
| 585 | let mode = match permission_mode { |
| 586 | Some(codewhale_engine::runtime_options::PermissionMode::Plan) => AppMode::Plan, |
| 587 | _ => AppMode::Agent, |
| 588 | }; |
| 589 | let turn_approval_mode = if auto_approve { |
| 590 | ApprovalMode::Bypass |
| 591 | } else if let Some(explicit_mode) = |
| 592 | permission_mode.and_then(codewhale_engine::runtime_options::PermissionMode::approval_mode) |
| 593 | { |
| 594 | explicit_mode |
| 595 | } else { |
| 596 | execution_config |
| 597 | .approval_policy |
| 598 | .as_deref() |
| 599 | .and_then(ApprovalMode::from_config_value) |
| 600 | .unwrap_or_default() |
| 601 | }; |
| 602 | let turn_sandbox_policy = codewhale_engine::core::authority::sandbox_policy_for_turn( |
| 603 | mode, |
| 604 | turn_approval_mode, |
| 605 | execution_config.sandbox_mode.as_deref(), |
| 606 | &workspace, |
| 607 | codewhale_engine::core::authority::SandboxNetworkAccess::from_config( |
| 608 | execution_config.sandbox_network_access, |
| 609 | ), |
| 610 | ); |
| 611 | let trust_mode = auto_approve |
| 612 | && matches!( |
| 613 | turn_sandbox_policy, |
| 614 | codewhale_sandbox::SandboxPolicy::DangerFullAccess |
| 615 | ); |
| 616 | let active_route_limits = |
| 617 | codewhale_engine::route_budget::known_route_limits(validated_route.candidate.limits()); |
| 618 | let effective_context_window = validated_route.context_window; |
| 619 | let max_subagents = if max_subagents |
| 620 | == config.max_subagents_for_provider( |
| 621 | &config |
| 622 | .active_provider_identity() |
| 623 | .map_err(anyhow::Error::msg)?, |
| 624 | ) { |
| 625 | execution_config |
| 626 | .max_subagents_for_provider(&effective_identity) |
| 627 | .clamp(1, MAX_SUBAGENTS) |
| 628 | } else { |
| 629 | max_subagents |
| 630 | }; |
| 631 | // A FIXED model with `--reasoning-effort auto` (the exact shape a Fleet |
| 632 | // worker subprocess launches with: `--model <exact> --reasoning-effort |
| 633 | // auto`) is still Auto. `auto_model` is a *model* decision and is false |
| 634 | // here, so deriving the auto flag from it left this path both raw and |
| 635 | // non-auto: the literal string `"auto"` travelled to the engine while the |
| 636 | // receipt claimed no Auto was in play. |
| 637 | let reasoning_effort_auto = route.auto_controls_reasoning; |
| 638 | // Resolve Auto against this run's prompt at the CLI boundary, exactly like |
| 639 | // the interactive launch path does, so the tier the engine (and the |
| 640 | // receipt below) sees is concrete. |
| 641 | let effective_reasoning_effort = route.reasoning_effort.and_then(|effort| { |
| 642 | cli_reasoning_effort_value_for_prompt(&execution_config, &effective_model, effort) |
| 643 | }); |
| 644 | |
| 645 | let settings = codewhale_runtime::settings::Settings::load().unwrap_or_default(); |
| 646 | let auto_compact_enabled = |
| 647 | if codewhale_runtime::settings::Settings::auto_compact_explicitly_configured() { |
| 648 | settings.auto_compact |
| 649 | } else { |
| 650 | codewhale_engine::route_budget::auto_compact_default_for_route( |
| 651 | effective_provider, |
| 652 | &effective_model, |
| 653 | active_route_limits, |
| 654 | ) |
| 655 | }; |
| 656 | let compaction = CompactionConfig { |
| 657 | enabled: auto_compact_enabled, |
| 658 | model: effective_model.clone(), |
| 659 | effective_context_window: Some(validated_route.context_window.tokens), |
| 660 | token_threshold: |
| 661 | codewhale_engine::route_budget::compaction_threshold_for_route_at_percent_with_window( |
| 662 | effective_provider, |
| 663 | &effective_model, |
| 664 | active_route_limits, |
| 665 | Some(validated_route.context_window.tokens), |
| 666 | settings.auto_compact_threshold_percent, |
| 667 | ), |
| 668 | summary_instructions: execution_config.compaction_summary_instructions(), |
| 669 | retained_user_message_tokens: execution_config.compaction_retained_user_message_tokens(), |
| 670 | ..Default::default() |
| 671 | }; |
| 672 | |
| 673 | let network_policy = exec_network_policy(&execution_config, outer_network_access); |
| 674 | |
| 675 | let lsp_config = (!fleet_authority_active && !one_shot) |
| 676 | .then(|| { |
| 677 | execution_config |
| 678 | .lsp |
| 679 | .clone() |
| 680 | .map(codewhale_lsp::LspConfig::from) |
| 681 | }) |
| 682 | .flatten(); |
| 683 | let mut engine_features = execution_config.features(); |
| 684 | apply_fleet_engine_feature_caps( |
| 685 | &mut engine_features, |
| 686 | fleet_authority_active, |
| 687 | outer_network_access, |
| 688 | outer_shell_authority, |
| 689 | ); |
| 690 | if codewhale_engine::core::engine::tool_catalog::allowlist_is_native_file_and_shell_only( |
| 691 | allowed_tools.as_deref(), |
| 692 | ) { |
| 693 | engine_features.disable(codewhale_runtime::features::Feature::Mcp); |
| 694 | } |
| 695 | let engine_plugin_registry = if fleet_authority_active { |
| 696 | std::sync::Arc::new(codewhale_plugins::PluginRegistry::empty(&workspace)) |
| 697 | } else { |
| 698 | plugin_registry |
| 699 | }; |
| 700 | // `exec --hooks` (#6099) is the operator's explicit opt-in: headless runs |
| 701 | // fire no hooks by default. When armed, the executor is the same one the |
| 702 | // TUI builds — global config, reviewed plugin snapshots, then trusted |
| 703 | // project `.codewhale/hooks.toml` — so `tool_call_before` can still deny |
| 704 | // and `shell_env` still applies. It is shared with the engine config, the |
| 705 | // turn's SendMessage op (which re-installs it into the engine), and the |
| 706 | // tool runtime services. Fleet workers never opt in: the narrowed |
| 707 | // authority envelope does not carry the operator's hook set into a child. |
| 708 | let exec_hook_executor = (exec_hooks_enabled && !fleet_authority_active).then(|| { |
| 709 | let hooks_config = codewhale_engine::hooks::config::load_with_project_and_plugins( |
| 710 | execution_config.hooks_config(), |
| 711 | &workspace, |
| 712 | Some(engine_plugin_registry.as_ref()), |
| 713 | ); |
| 714 | std::sync::Arc::new(codewhale_engine::hooks::HookExecutor::new( |
| 715 | hooks_config, |
| 716 | workspace.clone(), |
| 717 | )) |
| 718 | }); |
| 719 | let exec_allow_shell = codewhale_engine::tools::spec::fleet_exec_shell_enabled( |
| 720 | fleet_authority_active, |
| 721 | outer_shell_authority, |
| 722 | disallowed_tools.as_deref(), |
| 723 | ) || (!fleet_authority_active |
| 724 | && (auto_approve || execution_config.allow_shell())); |
| 725 | let persist_services_enabled = cfg!(unix) |
| 726 | && !fleet_authority_active |
| 727 | && exec_allow_shell |
| 728 | && explicit_sandbox |
| 729 | .is_some_and(|sandbox| sandbox.eq_ignore_ascii_case("danger-full-access")); |
| 730 | let exec_shell_manager = |
| 731 | codewhale_engine::tools::shell::new_shared_shell_manager(workspace.clone()); |
| 732 | let exec_automations = exec_automation_services(fleet_authority_active || one_shot)?; |
| 733 | let runtime_services = codewhale_engine::tools::spec::RuntimeToolServices { |
| 734 | accounting_origin, |
| 735 | shell_manager: Some(exec_shell_manager.clone()), |
| 736 | persist_services_enabled, |
| 737 | automations: exec_automations, |
| 738 | media_originals_dir: codewhale_runtime::media_originals::default_store_dir(), |
| 739 | hook_executor: exec_hook_executor.clone(), |
| 740 | ..codewhale_engine::tools::spec::RuntimeToolServices::default() |
| 741 | }; |
| 742 | |
| 743 | let engine_config = EngineConfig { |
| 744 | model: effective_model.clone(), |
| 745 | active_route_limits, |
| 746 | workspace: workspace.clone(), |
| 747 | session_id: Some(exec_session_id.clone()), |
| 748 | session_checkpoint_backend: Some( |
| 749 | codewhale_engine::core::events::SessionCheckpointProjection::Exact, |
| 750 | ), |
| 751 | subagent_state_root: None, |
| 752 | child_posture: None, |
| 753 | plugin_registry: Some(std::sync::Arc::clone(&engine_plugin_registry)), |
| 754 | allow_shell: exec_allow_shell, |
| 755 | trust_mode, |
| 756 | mcp_config_path: execution_config.mcp_config_path(), |
| 757 | mcp_auth_context: Default::default(), |
| 758 | // Non-interactive exec has no user-level MCP OAuth callback |
| 759 | // overrides; the loopback default applies. |
| 760 | mcp_oauth_callback_port: None, |
| 761 | mcp_oauth_callback_url: None, |
| 762 | skills_dir: execution_config.skills_dir(), |
| 763 | skills_config: std::sync::Arc::new(execution_config.skills_config()), |
| 764 | agent_preset: exec_agent_preset.clone(), |
| 765 | instructions: { |
| 766 | let mut instrs: Vec<codewhale_engine::prompts::InstructionSource> = execution_config |
| 767 | .instructions_paths() |
| 768 | .into_iter() |
| 769 | .map(Into::into) |
| 770 | .collect(); |
| 771 | instrs.push(codewhale_engine::prompts::InstructionSource::Inline { |
| 772 | name: "exec:no-user-present".into(), |
| 773 | content: |
| 774 | "No user is present; choose the recommended default and state the assumption." |
| 775 | .into(), |
| 776 | }); |
| 777 | if let Some(ref extra) = append_system_prompt { |
| 778 | instrs.push(codewhale_engine::prompts::InstructionSource::Inline { |
| 779 | name: "cli:append-system-prompt".into(), |
| 780 | content: extra.clone(), |
| 781 | }); |
| 782 | } |
| 783 | instrs |
| 784 | }, |
| 785 | project_context_pack_enabled: execution_config.project_context_pack_enabled(), |
| 786 | translation_enabled: false, |
| 787 | max_steps: max_turns, |
| 788 | max_subagents, |
| 789 | max_admitted_subagents: execution_config |
| 790 | .max_admitted_subagents_for_provider(&effective_identity) |
| 791 | .max(max_subagents), |
| 792 | launch_concurrency: execution_config.launch_concurrency_for_provider(&effective_identity), |
| 793 | subagents_enabled: !fleet_authority_active |
| 794 | && execution_config.subagents_enabled_for_provider(&effective_identity), |
| 795 | features: engine_features, |
| 796 | auto_review_policy: |
| 797 | codewhale_engine::core::authority::auto_review::AutoReviewPolicy::from_config( |
| 798 | &execution_config, |
| 799 | ), |
| 800 | compaction: compaction.clone(), |
| 801 | todos: new_shared_todo_list(), |
| 802 | plan_state: new_shared_plan_state(), |
| 803 | goal_state: codewhale_engine::tools::goal::new_shared_goal_state(), |
| 804 | goal_complete_judge: execution_config.goal_complete_judge(), |
| 805 | goal_blocked_judge: execution_config.goal_blocked_judge(), |
| 806 | max_spawn_depth: if fleet_authority_active { |
| 807 | 0 |
| 808 | } else { |
| 809 | execution_config.subagent_max_spawn_depth_for_provider(&effective_identity) |
| 810 | }, |
| 811 | network_policy, |
| 812 | snapshots_enabled: !fleet_authority_active |
| 813 | && !one_shot |
| 814 | && execution_config.snapshots_config().enabled, |
| 815 | snapshots_max_workspace_bytes: execution_config |
| 816 | .snapshots_config() |
| 817 | .max_workspace_gb |
| 818 | .saturating_mul(1024 * 1024 * 1024), |
| 819 | record_restore_points: true, |
| 820 | lsp_config, |
| 821 | runtime_services, |
| 822 | subagent_model_overrides: execution_config.subagent_model_overrides(), |
| 823 | fleet_roster: std::sync::Arc::new( |
| 824 | codewhale_engine::fleet::identity::load_effective_roster( |
| 825 | &execution_config.fleet_config(), |
| 826 | &workspace, |
| 827 | Some(engine_plugin_registry.as_ref()), |
| 828 | ), |
| 829 | ), |
| 830 | subagent_api_timeout: std::time::Duration::from_secs( |
| 831 | execution_config.subagent_api_timeout_secs_for_provider(&effective_identity), |
| 832 | ), |
| 833 | stream_chunk_timeout: std::time::Duration::from_secs( |
| 834 | execution_config.stream_chunk_timeout_secs(), |
| 835 | ), |
| 836 | turn_wall_clock: execution_config.turn_wall_clock(), |
| 837 | stream_max_content_bytes: execution_config.stream_max_content_bytes(), |
| 838 | stream_max_duration: execution_config.stream_max_duration(), |
| 839 | stream_retry_limits: execution_config.stream_retry_limits(), |
| 840 | stream_open_timeout: execution_config.stream_open_timeout(), |
| 841 | subagent_heartbeat_timeout: std::time::Duration::from_secs( |
| 842 | execution_config.subagent_heartbeat_timeout_secs_for_provider(&effective_identity), |
| 843 | ), |
| 844 | prefer_bwrap: execution_config.prefers_bwrap(), |
| 845 | tool_launcher: execution_config.tool_launcher.clone(), |
| 846 | bwrap_extensions: codewhale_sandbox::BwrapMountExtensions { |
| 847 | read_only_roots: execution_config.bwrap_ro_roots.clone(), |
| 848 | device_roots: execution_config.bwrap_dev_roots.clone(), |
| 849 | }, |
| 850 | read_denylist: codewhale_sandbox::read_guard::ReadDenylist::from_config(&execution_config), |
| 851 | memory_enabled: execution_config.memory_enabled(), |
| 852 | memory_path: execution_config.memory_path(), |
| 853 | speech_output_dir: execution_config.speech_output_dir(), |
| 854 | vision_config: execution_config.vision_model_config(), |
| 855 | strict_tool_mode: execution_config.strict_tool_mode.unwrap_or(false), |
| 856 | goal_objective: None, |
| 857 | goal_token_budget: None, |
| 858 | goal_status: codewhale_engine::tools::goal::GoalStatus::Active, |
| 859 | goal_max_continuations: execution_config.goal_max_continuations(), |
| 860 | goal_continuation_delay_seconds: execution_config.goal_continuation_delay_seconds(), |
| 861 | goal_enforce_token_budget: execution_config.goal_enforce_token_budget(), |
| 862 | reasoning_only_max_reprompts: execution_config.reasoning_only_max_reprompts(), |
| 863 | reasoning_only_on_output_limit: execution_config.reasoning_only_on_output_limit(), |
| 864 | reasoning_only_reprompt_message: Some( |
| 865 | execution_config |
| 866 | .reasoning_only_reprompt_message() |
| 867 | .to_string(), |
| 868 | ), |
| 869 | allowed_tools: allowed_tools.clone(), |
| 870 | disallowed_tools: disallowed_tools.clone(), |
| 871 | max_tool_calls, |
| 872 | hook_executor: exec_hook_executor.clone(), |
| 873 | locale_tag: codewhale_localization::resolve_locale(&settings.locale) |
| 874 | .tag() |
| 875 | .to_string(), |
| 876 | workshop: { |
| 877 | codewhale_runtime::active_workshop::install_active_workshop(config.workshop.as_ref()); |
| 878 | config.workshop.clone() |
| 879 | }, |
| 880 | search_provider: execution_config.search_provider(), |
| 881 | search_api_key: execution_config |
| 882 | .search |
| 883 | .as_ref() |
| 884 | .and_then(|s| s.api_key.clone()), |
| 885 | search_native: execution_config.search_native(), |
| 886 | search_third_party: execution_config |
| 887 | .search |
| 888 | .as_ref() |
| 889 | .and_then(|search| search.third_party), |
| 890 | search_consent_implied: execution_config.search_consent_implied(), |
| 891 | search_base_url: execution_config |
| 892 | .search |
| 893 | .as_ref() |
| 894 | .and_then(|s| s.base_url.clone()), |
| 895 | tools_always_load: if fleet_authority_active { |
| 896 | std::collections::HashSet::new() |
| 897 | } else { |
| 898 | execution_config.tools_always_load() |
| 899 | }, |
| 900 | user_input_limits: codewhale_engine::tools::user_input::UserInputLimits::from_config( |
| 901 | &execution_config, |
| 902 | ), |
| 903 | user_input_timeout: execution_config.user_input_timeout(), |
| 904 | user_input_responder: false, |
| 905 | goal_max_steps: None, |
| 906 | tools: if fleet_authority_active { |
| 907 | None |
| 908 | } else { |
| 909 | execution_config.tools.clone() |
| 910 | }, |
| 911 | verbosity: execution_config.verbosity.clone(), |
| 912 | workspace_follow_symlinks: settings.workspace_follow_symlinks, |
| 913 | extra_trusted_paths: execution_config.extra_trusted_paths.clone(), |
| 914 | exec_policy_engine: execution_config.exec_policy_engine.clone(), |
| 915 | terminal_chrome_enabled: false, |
| 916 | advisor_config: execution_config |
| 917 | .advisor |
| 918 | .as_ref() |
| 919 | .map(codewhale_engine::tools::subagent::AdvisorConfig::from_toml) |
| 920 | .unwrap_or_else(codewhale_engine::tools::subagent::AdvisorConfig::disabled), |
| 921 | }; |
| 922 | |
| 923 | let engine_handle = spawn_headless_engine(engine_config, &execution_config, None).await; |
| 924 | // A restricted posture that resolves to no enforcing sandbox must reach |
| 925 | // the person running exec, not only the model's posture line: policy-only |
| 926 | // is accepted (read-only already fails closed in the shell tool), but it |
| 927 | // is never silent. Uses the enforcement pinned by `Engine::new`. |
| 928 | let sandbox_enforcement = engine_handle.sandbox_enforcement; |
| 929 | let sandbox_posture = turn_sandbox_policy.posture_label_with_enforcement(sandbox_enforcement); |
| 930 | if sandbox_enforcement == codewhale_sandbox::policy::SandboxEnforcement::Unavailable |
| 931 | && turn_sandbox_policy.should_sandbox() |
| 932 | { |
| 933 | eprintln!("warning: {sandbox_posture} — shell commands will run unrestricted"); |
| 934 | } |
| 935 | |
| 936 | let mut loaded_session_id = None; |
| 937 | if let Some(saved) = resume_session { |
| 938 | let saved_id = saved.metadata.id.clone(); |
| 939 | let saved_workspace = tokio::fs::canonicalize(&saved.metadata.workspace) |
| 940 | .await |
| 941 | .unwrap_or_else(|_| saved.metadata.workspace.clone()); |
| 942 | let launch_workspace = tokio::fs::canonicalize(&workspace) |
| 943 | .await |
| 944 | .unwrap_or_else(|_| workspace.clone()); |
| 945 | if !paths_equal_for_config(&saved_workspace, &launch_workspace) |
| 946 | && output_format == ExecOutputFormat::Text |
| 947 | { |
| 948 | eprintln!( |
| 949 | "Warning: session {} was created in a different workspace ({}). Resuming anyway.", |
| 950 | truncate_id(&saved_id), |
| 951 | saved.metadata.workspace.display(), |
| 952 | ); |
| 953 | } |
| 954 | |
| 955 | engine_handle |
| 956 | .send(Op::SyncSession { |
| 957 | expected: None, |
| 958 | control: codewhale_engine::core::ops::SessionControlId::new(), |
| 959 | session_id: Some(saved_id.clone()), |
| 960 | messages: saved.messages, |
| 961 | system_prompt: saved.system_prompt.map(SystemPrompt::Text), |
| 962 | system_prompt_override: false, |
| 963 | model: saved.metadata.model, |
| 964 | workspace: saved.metadata.workspace, |
| 965 | mode, |
| 966 | agent_preset: saved.agent_preset, |
| 967 | }) |
| 968 | .await?; |
| 969 | loaded_session_id = Some(saved_id.clone()); |
| 970 | if output_format == ExecOutputFormat::Text && !json_output { |
| 971 | eprintln!("{}", exec_resumed_session_line(&saved_id)); |
| 972 | } |
| 973 | } |
| 974 | |
| 975 | if loaded_session_id.is_none() && exec_agent_preset.is_some() { |
| 976 | let snapshot = engine_handle.get_session_snapshot().await?; |
| 977 | engine_handle |
| 978 | .send(Op::SyncSession { |
| 979 | expected: None, |
| 980 | control: codewhale_engine::core::ops::SessionControlId::new(), |
| 981 | session_id: Some(snapshot.session_id), |
| 982 | messages: Vec::new(), |
| 983 | system_prompt: None, |
| 984 | system_prompt_override: false, |
| 985 | model: snapshot.model, |
| 986 | workspace: snapshot.workspace, |
| 987 | mode, |
| 988 | agent_preset: exec_agent_preset.clone(), |
| 989 | }) |
| 990 | .await?; |
| 991 | } |
| 992 | |
| 993 | // Lifecycle outbox (`[lifecycle_outbox]`): headless `codewhale exec` |
| 994 | // gets the same turn boundaries as the interactive TUI. Disabled |
| 995 | // (all emits no-op) when the config has no path. |
| 996 | let lifecycle_outbox = config |
| 997 | .lifecycle_outbox |
| 998 | .as_ref() |
| 999 | .map(|outbox| { |
| 1000 | codewhale_hooks::LifecycleOutbox::new( |
| 1001 | outbox.path.clone(), |
| 1002 | outbox.webhook_url.clone(), |
| 1003 | outbox.webhook_token.clone(), |
| 1004 | ) |
| 1005 | }) |
| 1006 | .unwrap_or_else(codewhale_hooks::LifecycleOutbox::disabled); |
| 1007 | // Wall clock for the outbox `turn_end` duration starts at the same |
| 1008 | // `Op::SendMessage` boundary where `turn_start` is emitted below. |
| 1009 | drop(startup_timing); |
| 1010 | let exec_turn_started_at = Instant::now(); |
| 1011 | |
| 1012 | let user_content = match json_schema.as_ref() { |
| 1013 | Some(js) => { |
| 1014 | let schema_text = |
| 1015 | serde_json::to_string_pretty(&js.schema).unwrap_or_else(|_| js.schema.to_string()); |
| 1016 | format!( |
| 1017 | "{prompt}\n\nReturn ONLY a JSON value matching this JSON Schema. No prose, no explanation:\n```json\n{schema_text}\n```" |
| 1018 | ) |
| 1019 | } |
| 1020 | None => prompt.to_string(), |
| 1021 | }; |
| 1022 | |
| 1023 | engine_handle |
| 1024 | .send(Op::SendMessage(TurnSpec { |
| 1025 | profile_constitution: None, |
| 1026 | max_output_tokens: None, |
| 1027 | content: user_content, |
| 1028 | images: Vec::new(), |
| 1029 | mode, |
| 1030 | route: Box::new(validated_route.into_resolved()), |
| 1031 | compaction: Box::new(compaction.clone()), |
| 1032 | initial_routed_usage: Box::default(), |
| 1033 | goal_objective: None, |
| 1034 | goal_token_budget: None, |
| 1035 | goal_status: codewhale_engine::tools::goal::GoalStatus::Active, |
| 1036 | allowed_tools: allowed_tools.clone(), |
| 1037 | dynamic_tools: Vec::new(), |
| 1038 | hook_executor: exec_hook_executor.clone(), |
| 1039 | reasoning_effort: effective_reasoning_effort, |
| 1040 | reasoning_effort_auto, |
| 1041 | auto_model, |
| 1042 | allow_shell: auto_approve || execution_config.allow_shell(), |
| 1043 | trust_mode, |
| 1044 | auto_approve, |
| 1045 | translation_enabled: false, |
| 1046 | approval_mode: turn_approval_mode, |
| 1047 | verbosity: execution_config.verbosity.clone(), |
| 1048 | provenance: codewhale_engine::core::ops::UserInputProvenance::ExternalUser, |
| 1049 | input_authorship: if fleet_authority_active |
| 1050 | || std::env::var_os("CODEWHALE_FLEET_CAPTURE_ID").is_some() |
| 1051 | { |
| 1052 | codewhale_engine::core::ops::TurnInputAuthorship::NotPerson |
| 1053 | } else { |
| 1054 | codewhale_engine::core::ops::TurnInputAuthorship::Person(prompt.to_owned()) |
| 1055 | }, |
| 1056 | // Headless exec does not correlate submissions. |
| 1057 | submission_id: None, |
| 1058 | })) |
| 1059 | .await?; |
| 1060 | |
| 1061 | // Lifecycle outbox: the headless submission boundary, before the Engine |
| 1062 | // reports TurnStarted. No-op when the feature is disabled. |
| 1063 | lifecycle_outbox.emit(codewhale_hooks::LifecycleEvent { |
| 1064 | event: "turn_start".to_string(), |
| 1065 | kind: "turn.started".to_string(), |
| 1066 | thread_id: loaded_session_id.clone().unwrap_or_default(), |
| 1067 | turn_id: None, |
| 1068 | item_id: None, |
| 1069 | payload: serde_json::json!({ |
| 1070 | "model": codewhale_hooks::bounded_text( |
| 1071 | &effective_model, |
| 1072 | codewhale_hooks::OUTBOX_DETAIL_MAX_CHARS, |
| 1073 | ), |
| 1074 | "workspace": workspace.display().to_string(), |
| 1075 | }), |
| 1076 | }); |
| 1077 | |
| 1078 | let mut summary = ExecSummary { |
| 1079 | mode: if one_shot { "one-shot" } else { "agent" }.to_string(), |
| 1080 | provider: effective_provider_name.clone(), |
| 1081 | model: effective_model.clone(), |
| 1082 | prompt: prompt.to_string(), |
| 1083 | ..ExecSummary::default() |
| 1084 | }; |
| 1085 | let can_elevate_sandbox = |
| 1086 | exec_sandbox_elevation_authorized(allow_sandbox_elevation, explicit_sandbox); |
| 1087 | let mut sandbox_denied = false; |
| 1088 | let mut approval_required = false; |
| 1089 | let mut tool_error_seen = false; |
| 1090 | let mut last_error_category = None; |
| 1091 | let mut reported_sandbox_contract = false; |
| 1092 | |
| 1093 | let mut active_turn_id = None; |
| 1094 | let mut provider_request_receipts = Vec::new(); |
| 1095 | let mut latest_session_id = loaded_session_id; |
| 1096 | let mut latest_messages: Arc<Vec<Message>> = Arc::new(Vec::new()); |
| 1097 | let mut latest_source: Option<codewhale_engine::core::ops::SessionSnapshotSource> = None; |
| 1098 | let mut latest_system_prompt: Option<SystemPrompt> = None; |
| 1099 | let mut latest_model = effective_model.clone(); |
| 1100 | let mut latest_workspace = workspace.clone(); |
| 1101 | let mut tool_starts: HashMap<String, (Instant, String)> = HashMap::new(); |
| 1102 | let mut turn_usage_seq: u32 = 0; |
| 1103 | // None means no actual terminal request snapshot was observed. A known |
| 1104 | // zero must remain distinguishable from that missing receipt. |
| 1105 | let mut observed_retry_count = None; |
| 1106 | let mut settled_usage: Option<codewhale_models::Usage> = None; |
| 1107 | let mut routed_usage_dropped_records = 0_u64; |
| 1108 | let mut usage_coverage_gap = false; |
| 1109 | let mut saved_session_id: Option<String> = None; |
| 1110 | let mut tool_catalog_sha256: Option<String> = None; |
| 1111 | |
| 1112 | let mut ends_with_newline = false; |
| 1113 | // One absolute host deadline includes every autonomous child fan-in turn; |
| 1114 | // child-specific shorter deadlines remain enforced by their runtime. |
| 1115 | // The default wall clock is unbounded (`Duration::MAX`); a century |
| 1116 | // stands in for "never" without overflowing `Instant`. |
| 1117 | let exec_deadline = exec_turn_started_at |
| 1118 | .checked_add(execution_config.turn_wall_clock()) |
| 1119 | .unwrap_or_else(|| exec_turn_started_at + Duration::from_secs(100 * 365 * 86_400)); |
| 1120 | let mut events = ExecAgentEvents::new(engine_handle.clone(), exec_deadline); |
| 1121 | loop { |
| 1122 | let Some(event) = events.next().await else { |
| 1123 | break; |
| 1124 | }; |
| 1125 | |
| 1126 | if should_persist_session |
| 1127 | && let Some((client, config)) = deferred_binding.take() |
| 1128 | && let Some(key) = load_exec_route_binding_key(open_exec_session_manager(), true).await |
| 1129 | { |
| 1130 | route_binding = client.exec_route_binding(&key, &config)?; |
| 1131 | } |
| 1132 | |
| 1133 | codewhale_engine::tools::subagent::log_subagent_lifecycle_audit(&event); |
| 1134 | summary.record_agent_event(&event); |
| 1135 | match event { |
| 1136 | Event::TurnStarted { turn_id, .. } => { |
| 1137 | active_turn_id = Some(turn_id); |
| 1138 | } |
| 1139 | Event::MessageDelta { content, .. } => { |
| 1140 | summary.output.push_str(&content); |
| 1141 | if output_format == ExecOutputFormat::StreamJson { |
| 1142 | emit_exec_stream_event(&ExecStreamEvent::Content { content })?; |
| 1143 | } else if !json_output && json_schema.is_none() { |
| 1144 | write_exec_stdout(&content)?; |
| 1145 | } |
| 1146 | ends_with_newline = summary.output.ends_with('\n'); |
| 1147 | } |
| 1148 | Event::MessageComplete { .. } |
| 1149 | if output_format == ExecOutputFormat::Text |
| 1150 | && !json_output |
| 1151 | && json_schema.is_none() |
| 1152 | && !ends_with_newline => |
| 1153 | { |
| 1154 | write_exec_stdout("\n")?; |
| 1155 | } |
| 1156 | Event::ThinkingDelta { .. } => { |
| 1157 | // Exec stream-json intentionally omits reasoning deltas; the |
| 1158 | // TUI transcript retains its existing Activity Detail surface. |
| 1159 | } |
| 1160 | Event::ToolProjectionWarning { |
| 1161 | provider, |
| 1162 | omitted_tool_names, |
| 1163 | omitted_tool_count, |
| 1164 | } if !json_output => { |
| 1165 | eprintln!( |
| 1166 | "{}", |
| 1167 | codewhale_engine::core::events::tool_projection_warning_message( |
| 1168 | &provider, |
| 1169 | &omitted_tool_names, |
| 1170 | omitted_tool_count, |
| 1171 | ) |
| 1172 | ); |
| 1173 | } |
| 1174 | Event::SnapshotsDisabled { reason, .. } => { |
| 1175 | eprintln!("warning: {reason}"); |
| 1176 | } |
| 1177 | Event::RequestImageWindow { |
| 1178 | provider, |
| 1179 | model, |
| 1180 | total, |
| 1181 | elided, |
| 1182 | cap, |
| 1183 | cap_source, |
| 1184 | message, |
| 1185 | } => { |
| 1186 | if output_format == ExecOutputFormat::StreamJson { |
| 1187 | emit_exec_stream_event(&ExecStreamEvent::RequestImageWindow { |
| 1188 | provider, |
| 1189 | model, |
| 1190 | total, |
| 1191 | elided, |
| 1192 | cap, |
| 1193 | cap_source, |
| 1194 | message, |
| 1195 | })?; |
| 1196 | } else if !json_output { |
| 1197 | eprintln!("{message}"); |
| 1198 | } |
| 1199 | } |
| 1200 | Event::ToolCallStarted { |
| 1201 | id, name, input, .. |
| 1202 | } => { |
| 1203 | let started_at = chrono::Utc::now().to_rfc3339(); |
| 1204 | tool_starts.insert(id.clone(), (Instant::now(), started_at.clone())); |
| 1205 | if output_format == ExecOutputFormat::StreamJson { |
| 1206 | emit_exec_stream_event(&ExecStreamEvent::ToolUse { |
| 1207 | name, |
| 1208 | id, |
| 1209 | input, |
| 1210 | started_at, |
| 1211 | })?; |
| 1212 | } else if !json_output { |
| 1213 | let summary = summarize_tool_args(&input); |
| 1214 | if let Some(summary) = summary { |
| 1215 | eprintln!("tool: {name} ({summary})"); |
| 1216 | } else { |
| 1217 | eprintln!("tool: {name}"); |
| 1218 | } |
| 1219 | } |
| 1220 | } |
| 1221 | Event::ToolExecutionStarted { id } => { |
| 1222 | if let Some(start) = tool_starts.get_mut(&id) { |
| 1223 | *start = (Instant::now(), chrono::Utc::now().to_rfc3339()); |
| 1224 | } |
| 1225 | } |
| 1226 | Event::ToolCallComplete { |
| 1227 | id, name, result, .. |
| 1228 | } => { |
| 1229 | let (duration_ms, started_at) = tool_starts |
| 1230 | .remove(&id) |
| 1231 | .map(|(started, timestamp)| { |
| 1232 | ( |
| 1233 | u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX), |
| 1234 | timestamp, |
| 1235 | ) |
| 1236 | }) |
| 1237 | .unwrap_or_else(|| (0, chrono::Utc::now().to_rfc3339())); |
| 1238 | let receipt_name = name.clone(); |
| 1239 | match result { |
| 1240 | Ok(output) => { |
| 1241 | tool_error_seen |= !output.success; |
| 1242 | summary.tools.push(ExecToolEntry { |
| 1243 | name: name.clone(), |
| 1244 | success: output.success, |
| 1245 | output: output.content.clone(), |
| 1246 | }); |
| 1247 | if output_format == ExecOutputFormat::StreamJson { |
| 1248 | emit_exec_stream_event(&ExecStreamEvent::ToolResult { |
| 1249 | id, |
| 1250 | name: receipt_name, |
| 1251 | output: output.content, |
| 1252 | status: if output.success { |
| 1253 | "success".to_string() |
| 1254 | } else { |
| 1255 | "error".to_string() |
| 1256 | }, |
| 1257 | started_at, |
| 1258 | completed_at: chrono::Utc::now().to_rfc3339(), |
| 1259 | duration_ms, |
| 1260 | side_effect_status: output |
| 1261 | .metadata |
| 1262 | .as_ref() |
| 1263 | .and_then(|metadata| metadata.get("side_effect_status")) |
| 1264 | .and_then(serde_json::Value::as_str) |
| 1265 | .unwrap_or("unknown") |
| 1266 | .to_string(), |
| 1267 | error_category: (!output.success).then(|| { |
| 1268 | output |
| 1269 | .metadata |
| 1270 | .as_ref() |
| 1271 | .and_then(|metadata| metadata.get("error_category")) |
| 1272 | .and_then(serde_json::Value::as_str) |
| 1273 | .unwrap_or("tool_reported_failure") |
| 1274 | .to_string() |
| 1275 | }), |
| 1276 | truncated: output |
| 1277 | .metadata |
| 1278 | .as_ref() |
| 1279 | .and_then(|metadata| metadata.get("truncated")) |
| 1280 | .and_then(serde_json::Value::as_bool), |
| 1281 | artifact: tool_artifact_receipt(output.metadata.as_ref()), |
| 1282 | result_metadata: output.metadata, |
| 1283 | })?; |
| 1284 | } else if !json_output { |
| 1285 | eprintln!( |
| 1286 | "tool {name} completed: {}", |
| 1287 | summarize_tool_output(&output.content) |
| 1288 | ); |
| 1289 | } |
| 1290 | } |
| 1291 | Err(err) => { |
| 1292 | tool_error_seen = true; |
| 1293 | let error_text = err.to_string(); |
| 1294 | summary.tools.push(ExecToolEntry { |
| 1295 | name: name.clone(), |
| 1296 | success: false, |
| 1297 | output: error_text.clone(), |
| 1298 | }); |
| 1299 | if output_format == ExecOutputFormat::StreamJson { |
| 1300 | emit_exec_stream_event(&ExecStreamEvent::ToolResult { |
| 1301 | id, |
| 1302 | name: receipt_name, |
| 1303 | output: error_text, |
| 1304 | status: "error".to_string(), |
| 1305 | started_at, |
| 1306 | completed_at: chrono::Utc::now().to_rfc3339(), |
| 1307 | duration_ms, |
| 1308 | side_effect_status: "not_started_or_unknown".to_string(), |
| 1309 | error_category: Some(tool_error_receipt_category(&err).to_string()), |
| 1310 | truncated: err |
| 1311 | .metadata() |
| 1312 | .and_then(|metadata| metadata.get("truncated")) |
| 1313 | .and_then(serde_json::Value::as_bool), |
| 1314 | artifact: tool_artifact_receipt(err.metadata()), |
| 1315 | result_metadata: err.metadata().cloned(), |
| 1316 | })?; |
| 1317 | } else if !json_output { |
| 1318 | eprintln!("tool {name} failed: {err}"); |
| 1319 | } |
| 1320 | } |
| 1321 | } |
| 1322 | } |
| 1323 | Event::AgentSpawned { id, prompt, .. } |
| 1324 | if output_format == ExecOutputFormat::Text && !json_output => |
| 1325 | { |
| 1326 | eprintln!("sub-agent {id} spawned: {}", summarize_tool_output(&prompt)); |
| 1327 | } |
| 1328 | Event::AgentProgress { id, status, .. } |
| 1329 | if output_format == ExecOutputFormat::Text && !json_output => |
| 1330 | { |
| 1331 | eprintln!("sub-agent {id}: {status}"); |
| 1332 | } |
| 1333 | Event::AgentComplete { |
| 1334 | id, |
| 1335 | result, |
| 1336 | outcome, |
| 1337 | .. |
| 1338 | } if output_format == ExecOutputFormat::Text && !json_output => { |
| 1339 | eprintln!( |
| 1340 | "sub-agent {id} {}: {}", |
| 1341 | outcome |
| 1342 | .as_ref() |
| 1343 | .map(codewhale_engine::tools::subagent::subagent_status_name) |
| 1344 | .unwrap_or("settled (outcome unconfirmed)"), |
| 1345 | summarize_tool_output(&result) |
| 1346 | ); |
| 1347 | } |
| 1348 | Event::AgentSpawned { |
| 1349 | id, |
| 1350 | parent_run_id, |
| 1351 | spawn_depth, |
| 1352 | model, |
| 1353 | route_source, |
| 1354 | .. |
| 1355 | } if output_format == ExecOutputFormat::StreamJson => { |
| 1356 | emit_exec_stream_event(&ExecStreamEvent::AgentSpawned { |
| 1357 | id, |
| 1358 | model, |
| 1359 | spawn_depth, |
| 1360 | parent_run_id, |
| 1361 | route_source, |
| 1362 | })?; |
| 1363 | } |
| 1364 | Event::AgentSpawned { .. } |
| 1365 | | Event::AgentProgress { .. } |
| 1366 | | Event::AgentComplete { .. } => {} |
| 1367 | Event::WorkflowUi { run_id, event, .. } |
| 1368 | if output_format == ExecOutputFormat::StreamJson => |
| 1369 | { |
| 1370 | emit_exec_stream_event(&ExecStreamEvent::WorkflowEvent { run_id, event })?; |
| 1371 | } |
| 1372 | // Headless runs have no person at the prompt: the run's flags |
| 1373 | // (the posture) answer every request. |
| 1374 | Event::ApprovalRequired { |
| 1375 | id, |
| 1376 | approval_force_prompt, |
| 1377 | .. |
| 1378 | } => { |
| 1379 | // An exact user decision (including extension-sourced shell |
| 1380 | // and network calls) cannot be supplied by a headless posture. |
| 1381 | if auto_approve && !approval_force_prompt { |
| 1382 | let _ = engine_handle |
| 1383 | .approve_tool_call_by( |
| 1384 | id, |
| 1385 | codewhale_engine::approval_log::ApprovalDecider::Posture, |
| 1386 | ) |
| 1387 | .await; |
| 1388 | } else { |
| 1389 | approval_required = true; |
| 1390 | let _ = engine_handle |
| 1391 | .deny_tool_call_by( |
| 1392 | id, |
| 1393 | codewhale_engine::approval_log::ApprovalDecider::Posture, |
| 1394 | ) |
| 1395 | .await; |
| 1396 | } |
| 1397 | } |
| 1398 | Event::ElevationRequired { |
| 1399 | tool_id, |
| 1400 | tool_name, |
| 1401 | denial_reason, |
| 1402 | .. |
| 1403 | } => { |
| 1404 | if can_elevate_sandbox { |
| 1405 | let policy = codewhale_sandbox::SandboxPolicy::DangerFullAccess; |
| 1406 | let _ = engine_handle |
| 1407 | .retry_tool_with_policy_by( |
| 1408 | tool_id, |
| 1409 | policy, |
| 1410 | codewhale_engine::approval_log::ApprovalDecider::Posture, |
| 1411 | ) |
| 1412 | .await; |
| 1413 | } else { |
| 1414 | sandbox_denied = true; |
| 1415 | approval_required = true; |
| 1416 | summary.outcomes.push(ExecOutcome { |
| 1417 | kind: "sandbox_denied".to_string(), |
| 1418 | outcome: "approval_required".to_string(), |
| 1419 | tool_name: tool_name.clone(), |
| 1420 | reason: denial_reason.clone(), |
| 1421 | }); |
| 1422 | if !reported_sandbox_contract { |
| 1423 | eprintln!( |
| 1424 | "sandbox denied {tool_name}: {denial_reason}; --auto approves tools but does not elevate sandbox access — use --sandbox danger-full-access or --allow-sandbox-elevation to opt in" |
| 1425 | ); |
| 1426 | reported_sandbox_contract = true; |
| 1427 | } |
| 1428 | if output_format == ExecOutputFormat::StreamJson { |
| 1429 | emit_exec_stream_event(&ExecStreamEvent::SandboxDenied { |
| 1430 | tool_id: tool_id.clone(), |
| 1431 | tool_name, |
| 1432 | reason: denial_reason, |
| 1433 | outcome: "approval_required".to_string(), |
| 1434 | })?; |
| 1435 | } |
| 1436 | let _ = engine_handle |
| 1437 | .deny_tool_call_by( |
| 1438 | tool_id, |
| 1439 | codewhale_engine::approval_log::ApprovalDecider::Posture, |
| 1440 | ) |
| 1441 | .await; |
| 1442 | } |
| 1443 | } |
| 1444 | Event::Error { |
| 1445 | envelope, |
| 1446 | recoverable: _, |
| 1447 | } => { |
| 1448 | // Only a non-recoverable envelope may force the run summary |
| 1449 | // into failure. Recoverable warnings (stream-stall notices, |
| 1450 | // transient retry noise) are still streamed for visibility, |
| 1451 | // but the terminal TurnComplete event carries the |
| 1452 | // authoritative turn outcome — letting a warning set |
| 1453 | // `summary.error` here would exit an otherwise-successful |
| 1454 | // `exec` run non-zero. |
| 1455 | if exec_error_event_is_fatal(&envelope) { |
| 1456 | last_error_category = Some(envelope.category); |
| 1457 | summary.error_category = Some(envelope.category.to_string()); |
| 1458 | summary.error = Some(envelope.message.clone()); |
| 1459 | } |
| 1460 | if output_format == ExecOutputFormat::StreamJson { |
| 1461 | emit_exec_stream_event(&ExecStreamEvent::Error { |
| 1462 | error: envelope.message, |
| 1463 | })?; |
| 1464 | } else if !json_output { |
| 1465 | eprintln!("error: {}", envelope.message); |
| 1466 | } |
| 1467 | } |
| 1468 | Event::ProviderRequestReceipt { receipt } => { |
| 1469 | let image_projection = receipt |
| 1470 | .get("wire_observations") |
| 1471 | .and_then(serde_json::Value::as_array) |
| 1472 | .is_some_and(|observations| { |
| 1473 | observations |
| 1474 | .iter() |
| 1475 | .any(|observation| observation.get("image_projection").is_some()) |
| 1476 | }); |
| 1477 | let coverage = receipt.get("coverage").cloned().and_then(|value| { |
| 1478 | serde_json::from_value::<codewhale_engine::llm_client::ProviderUsageCoverage>( |
| 1479 | value, |
| 1480 | ) |
| 1481 | .ok() |
| 1482 | }); |
| 1483 | let coverage_gap = matches!( |
| 1484 | coverage, |
| 1485 | Some( |
| 1486 | codewhale_engine::llm_client::ProviderUsageCoverage::Missing |
| 1487 | | codewhale_engine::llm_client::ProviderUsageCoverage::Incomplete |
| 1488 | ) |
| 1489 | ); |
| 1490 | usage_coverage_gap |= coverage_gap; |
| 1491 | let unknown_primary = receipt["primary"].as_bool() == Some(true) && coverage_gap; |
| 1492 | if image_projection || unknown_primary { |
| 1493 | should_persist_session = true; |
| 1494 | provider_request_receipts.push(receipt.clone()); |
| 1495 | } |
| 1496 | if output_format == ExecOutputFormat::StreamJson { |
| 1497 | emit_exec_stream_event(&ExecStreamEvent::ProviderRequestReceipt { receipt })?; |
| 1498 | } |
| 1499 | } |
| 1500 | Event::TurnUsage { |
| 1501 | usage, |
| 1502 | duration_ms, |
| 1503 | finish_reason, |
| 1504 | .. |
| 1505 | } => { |
| 1506 | if output_format == ExecOutputFormat::StreamJson { |
| 1507 | turn_usage_seq = turn_usage_seq.saturating_add(1); |
| 1508 | emit_exec_stream_event(&ExecStreamEvent::TurnUsage { |
| 1509 | turn: turn_usage_seq, |
| 1510 | input_tokens: usage.input_tokens, |
| 1511 | output_tokens: usage.output_tokens, |
| 1512 | reasoning_tokens: usage.reasoning_tokens, |
| 1513 | prompt_cache_hit_tokens: usage.prompt_cache_hit_tokens, |
| 1514 | prompt_cache_miss_tokens: usage.prompt_cache_miss_tokens, |
| 1515 | prompt_cache_write_tokens: usage.prompt_cache_write_tokens, |
| 1516 | reasoning_replay_tokens: usage.reasoning_replay_tokens, |
| 1517 | duration_ms, |
| 1518 | finish_reason, |
| 1519 | })?; |
| 1520 | } |
| 1521 | } |
| 1522 | Event::TurnComplete { |
| 1523 | turn_id, |
| 1524 | submission_id, |
| 1525 | compaction_id, |
| 1526 | status, |
| 1527 | error, |
| 1528 | usage, |
| 1529 | routed_usage_dropped_records: dropped_records, |
| 1530 | tool_catalog, |
| 1531 | .. |
| 1532 | } => { |
| 1533 | let _timing = codewhale_runtime::logging::PhaseTimer::start("exec_postprocessing"); |
| 1534 | routed_usage_dropped_records = dropped_records; |
| 1535 | tool_catalog_sha256 = tool_catalog.as_ref().and_then(|catalog| { |
| 1536 | serde_json::to_vec(catalog).ok().map(|bytes| { |
| 1537 | format!("sha256:{}", codewhale_runtime::hashing::sha256_hex(&bytes)) |
| 1538 | }) |
| 1539 | }); |
| 1540 | let terminal_source = codewhale_engine::core::ops::SessionSnapshotSource::terminal( |
| 1541 | turn_id, |
| 1542 | submission_id, |
| 1543 | compaction_id, |
| 1544 | ); |
| 1545 | let terminal_snapshot = match engine_handle.get_session_snapshot().await { |
| 1546 | Ok(snapshot) => Some(snapshot), |
| 1547 | Err(error) => { |
| 1548 | tracing::warn!(%error, "exec terminal session snapshot could not be read; checkpoint retained"); |
| 1549 | None |
| 1550 | } |
| 1551 | }.filter(|snapshot| { |
| 1552 | snapshot.source.as_ref() == terminal_source.as_ref() |
| 1553 | && terminal_source.is_some() |
| 1554 | && snapshot.session_id == exec_session_id |
| 1555 | && snapshot.workspace == exec_session_workspace |
| 1556 | && latest_source.as_ref() == terminal_source.as_ref() |
| 1557 | && snapshot.messages.as_slice() == latest_messages.as_slice() |
| 1558 | }); |
| 1559 | let mut terminal_status = status; |
| 1560 | let terminal_error = error; |
| 1561 | #[cfg(unix)] |
| 1562 | let mut terminal_error = terminal_error; |
| 1563 | settled_usage = Some(usage.clone()); |
| 1564 | if matches!( |
| 1565 | terminal_status, |
| 1566 | codewhale_engine::core::events::TurnOutcomeStatus::Completed |
| 1567 | ) && terminal_error.is_none() |
| 1568 | { |
| 1569 | #[cfg(unix)] |
| 1570 | match exec_shell_manager.lock() { |
| 1571 | Ok(mut manager) => match manager.commit_persistent_services() { |
| 1572 | Ok(receipts) => { |
| 1573 | for receipt in &receipts { |
| 1574 | if output_format == ExecOutputFormat::StreamJson { |
| 1575 | emit_exec_stream_event( |
| 1576 | &ExecStreamEvent::ServiceReleased { |
| 1577 | task_id: receipt.task_id.clone(), |
| 1578 | pid: receipt.pid, |
| 1579 | process_group_id: receipt.process_group_id, |
| 1580 | ownership: receipt.ownership.clone(), |
| 1581 | }, |
| 1582 | )?; |
| 1583 | } else if !json_output { |
| 1584 | eprintln!( |
| 1585 | "persistent service released: {} pid={} pgid={} ownership={}", |
| 1586 | receipt.task_id, |
| 1587 | receipt.pid, |
| 1588 | receipt.process_group_id, |
| 1589 | receipt.ownership |
| 1590 | ); |
| 1591 | } |
| 1592 | } |
| 1593 | summary.released_services.extend(receipts); |
| 1594 | } |
| 1595 | Err(error) => { |
| 1596 | manager.abort_persistent_services(); |
| 1597 | terminal_status = |
| 1598 | codewhale_engine::core::events::TurnOutcomeStatus::Failed; |
| 1599 | terminal_error = Some(format!( |
| 1600 | "Persistent service ownership transfer failed: {error}" |
| 1601 | )); |
| 1602 | } |
| 1603 | }, |
| 1604 | Err(_) => { |
| 1605 | terminal_status = |
| 1606 | codewhale_engine::core::events::TurnOutcomeStatus::Failed; |
| 1607 | terminal_error = Some( |
| 1608 | "Persistent service ownership transfer failed: shell manager lock poisoned" |
| 1609 | .to_string(), |
| 1610 | ); |
| 1611 | } |
| 1612 | } |
| 1613 | } else if let Ok(mut manager) = exec_shell_manager.lock() { |
| 1614 | manager.abort_persistent_services(); |
| 1615 | } |
| 1616 | summary.apply_turn_complete_error_summary( |
| 1617 | terminal_status, |
| 1618 | terminal_error, |
| 1619 | sandbox_denied, |
| 1620 | &mut last_error_category, |
| 1621 | ); |
| 1622 | let mut schema_decode_failed = false; |
| 1623 | if let Some(js) = json_schema.as_ref() |
| 1624 | && terminal_status |
| 1625 | == codewhale_engine::core::events::TurnOutcomeStatus::Completed |
| 1626 | && summary.error.is_none() |
| 1627 | { |
| 1628 | let final_answer = exec_stream_final_answer_text( |
| 1629 | &latest_messages, |
| 1630 | !summary.output.trim().is_empty(), |
| 1631 | ) |
| 1632 | .unwrap_or_default(); |
| 1633 | match codewhale_engine::decode_schema_reply( |
| 1634 | "exec --json-schema", |
| 1635 | &final_answer, |
| 1636 | &js.validator, |
| 1637 | ) { |
| 1638 | Ok(value) => { |
| 1639 | summary.structured_output = Some(value.clone()); |
| 1640 | if output_format == ExecOutputFormat::Text && !json_output { |
| 1641 | write_exec_stdout(&format!( |
| 1642 | "{}\n", |
| 1643 | serde_json::to_string(&value)? |
| 1644 | ))?; |
| 1645 | } |
| 1646 | } |
| 1647 | Err(err) => { |
| 1648 | let error = err.message().to_string(); |
| 1649 | terminal_status = |
| 1650 | codewhale_engine::core::events::TurnOutcomeStatus::Failed; |
| 1651 | summary.status = Some("failed".to_string()); |
| 1652 | summary.error = Some(error.clone()); |
| 1653 | last_error_category = None; |
| 1654 | schema_decode_failed = true; |
| 1655 | if output_format == ExecOutputFormat::StreamJson { |
| 1656 | emit_exec_stream_event(&ExecStreamEvent::Error { error })?; |
| 1657 | } |
| 1658 | } |
| 1659 | } |
| 1660 | } |
| 1661 | saved_session_id = if should_persist_session && !latest_messages.is_empty() { |
| 1662 | let saved = open_exec_session_manager().and_then(|manager| { |
| 1663 | if exec_write_receipt.is_none() && exec_is_fresh { |
| 1664 | exec_write_receipt = |
| 1665 | Some(manager.expect_absent_session(&exec_session_id)?); |
| 1666 | } |
| 1667 | let source = exec_write_receipt.as_ref().ok_or_else(|| { |
| 1668 | anyhow::anyhow!("exec original source was not admitted") |
| 1669 | })?; |
| 1670 | let owner = terminal_snapshot |
| 1671 | .as_ref() |
| 1672 | .and_then(|snapshot| snapshot.source.as_ref()) |
| 1673 | .ok_or_else(|| { |
| 1674 | anyhow::anyhow!( |
| 1675 | "exec terminal snapshot belongs to another native turn" |
| 1676 | ) |
| 1677 | })?; |
| 1678 | persist_exec_session( |
| 1679 | &latest_messages, |
| 1680 | &latest_model, |
| 1681 | PersistedProviderRoute { |
| 1682 | kind: effective_identity.persisted_kind(), |
| 1683 | id: effective_identity.persisted_id(), |
| 1684 | binding: Some(&route_binding), |
| 1685 | }, |
| 1686 | &latest_workspace, |
| 1687 | &latest_system_prompt, |
| 1688 | latest_session_id.as_deref(), |
| 1689 | u64::from(usage.input_tokens) + u64::from(usage.output_tokens), |
| 1690 | (terminal_status |
| 1691 | == codewhale_engine::core::events::TurnOutcomeStatus::Failed) |
| 1692 | .then_some(summary.error.as_deref().unwrap_or_else(|| { |
| 1693 | codewhale_engine::core::termination::classify_turn_termination( |
| 1694 | terminal_status, |
| 1695 | last_error_category, |
| 1696 | tool_error_seen, |
| 1697 | approval_required, |
| 1698 | ) |
| 1699 | .as_str() |
| 1700 | })), |
| 1701 | manager.as_ref(), |
| 1702 | &provider_request_receipts, |
| 1703 | None, |
| 1704 | source, |
| 1705 | owner, |
| 1706 | exec_agent_preset.as_deref(), |
| 1707 | ) |
| 1708 | }); |
| 1709 | match saved { |
| 1710 | Ok(publication) => { |
| 1711 | let id = publication.metadata.id.clone(); |
| 1712 | if output_format == ExecOutputFormat::Text && !json_output { |
| 1713 | eprintln!("{}", exec_saved_session_line(&id)); |
| 1714 | } |
| 1715 | Some(id) |
| 1716 | } |
| 1717 | Err(err) => { |
| 1718 | let error = format!( |
| 1719 | "Failed to save exec session: {err:#}. The task may already have run; do not retry automatically." |
| 1720 | ); |
| 1721 | terminal_status = |
| 1722 | codewhale_engine::core::events::TurnOutcomeStatus::Failed; |
| 1723 | summary.status = Some("failed".to_string()); |
| 1724 | summary.error = Some(match summary.error.take() { |
| 1725 | Some(previous) => format!("{previous}; {error}"), |
| 1726 | None => error.clone(), |
| 1727 | }); |
| 1728 | last_error_category = |
| 1729 | Some(codewhale_error_taxonomy::ErrorCategory::State); |
| 1730 | summary.error_category = |
| 1731 | last_error_category.map(|category| category.to_string()); |
| 1732 | if output_format == ExecOutputFormat::StreamJson { |
| 1733 | emit_exec_stream_event(&ExecStreamEvent::Error { error })?; |
| 1734 | } |
| 1735 | None |
| 1736 | } |
| 1737 | } |
| 1738 | } else { |
| 1739 | None |
| 1740 | }; |
| 1741 | // Lifecycle outbox: the clean headless turn-end boundary. |
| 1742 | // `terminal_status` includes persistent-service handoff and |
| 1743 | // session-save failures above, and |
| 1744 | // `summary.error` includes the sandbox-denial augmentation. |
| 1745 | // No-op when the feature is disabled. |
| 1746 | { |
| 1747 | let outbox_status = format!("{terminal_status:?}").to_lowercase(); |
| 1748 | let kind = match terminal_status { |
| 1749 | codewhale_engine::core::events::TurnOutcomeStatus::Completed => { |
| 1750 | "turn.completed" |
| 1751 | } |
| 1752 | codewhale_engine::core::events::TurnOutcomeStatus::Failed => "turn.failed", |
| 1753 | codewhale_engine::core::events::TurnOutcomeStatus::Interrupted => { |
| 1754 | "turn.interrupted" |
| 1755 | } |
| 1756 | }; |
| 1757 | lifecycle_outbox.emit(codewhale_hooks::LifecycleEvent { |
| 1758 | event: "turn_end".to_string(), |
| 1759 | kind: kind.to_string(), |
| 1760 | thread_id: latest_session_id.clone().unwrap_or_default(), |
| 1761 | turn_id: None, |
| 1762 | item_id: None, |
| 1763 | payload: serde_json::json!({ |
| 1764 | "status": outbox_status, |
| 1765 | "duration_ms": exec_turn_started_at.elapsed().as_millis() as u64, |
| 1766 | "workspace": latest_workspace.display().to_string(), |
| 1767 | "error": summary.error.as_deref().map(|message| { |
| 1768 | codewhale_hooks::bounded_text( |
| 1769 | message, |
| 1770 | codewhale_hooks::OUTBOX_DETAIL_MAX_CHARS, |
| 1771 | ) |
| 1772 | }), |
| 1773 | }), |
| 1774 | }); |
| 1775 | } |
| 1776 | let termination_reason = if schema_decode_failed { |
| 1777 | codewhale_engine::core::termination::RunTerminationReason::Unresolved |
| 1778 | } else { |
| 1779 | codewhale_engine::core::termination::classify_turn_termination( |
| 1780 | terminal_status, |
| 1781 | last_error_category, |
| 1782 | tool_error_seen, |
| 1783 | approval_required, |
| 1784 | ) |
| 1785 | }; |
| 1786 | summary.termination_reason = Some(termination_reason.as_str().to_string()); |
| 1787 | // State the exit class here rather than inferring it later |
| 1788 | // from the process exit code. A no-op unless this process was |
| 1789 | // armed. |
| 1790 | if !termination_reason.is_success() { |
| 1791 | codewhale_telemetry::set_exit_class(codewhale_telemetry::ExitClass::Error); |
| 1792 | } |
| 1793 | break; |
| 1794 | } |
| 1795 | Event::CompactionStarted { .. } => { |
| 1796 | // The Engine writes recovery artifacts under its session ID. |
| 1797 | // Keep the owning session discoverable even in text output. |
| 1798 | should_persist_session = true; |
| 1799 | } |
| 1800 | Event::SessionUpdated { |
| 1801 | source, |
| 1802 | session_id, |
| 1803 | messages, |
| 1804 | system_prompt, |
| 1805 | instruction_assembly: _, |
| 1806 | model, |
| 1807 | workspace, |
| 1808 | checkpoint, |
| 1809 | } => { |
| 1810 | if let Some(checkpoint) = checkpoint { |
| 1811 | if session_id != exec_session_id |
| 1812 | || workspace != exec_session_workspace |
| 1813 | || active_turn_id.as_deref() != Some(checkpoint.caller.turn_id.as_str()) |
| 1814 | || model != checkpoint.snapshot.model |
| 1815 | || system_prompt != checkpoint.snapshot.system_prompt |
| 1816 | { |
| 1817 | checkpoint |
| 1818 | .fail("exec checkpoint event does not match its captured root turn"); |
| 1819 | continue; |
| 1820 | } |
| 1821 | if let Err(error) = |
| 1822 | checkpoint.validate_prefix(&session_id, &workspace, &messages) |
| 1823 | { |
| 1824 | checkpoint.fail(error); |
| 1825 | continue; |
| 1826 | } |
| 1827 | let manager = if should_persist_session { |
| 1828 | open_exec_session_manager().and_then(|manager| { |
| 1829 | if exec_write_receipt.is_none() && exec_is_fresh { |
| 1830 | exec_write_receipt = |
| 1831 | Some(manager.expect_absent_session(&exec_session_id)?); |
| 1832 | } |
| 1833 | Ok(Some(manager)) |
| 1834 | }) |
| 1835 | } else { |
| 1836 | Ok(None) |
| 1837 | }; |
| 1838 | match manager { |
| 1839 | Ok(manager) => { |
| 1840 | persist_exec_checkpoint( |
| 1841 | checkpoint, |
| 1842 | manager, |
| 1843 | &exec_session_id, |
| 1844 | &exec_session_workspace, |
| 1845 | active_turn_id.as_deref(), |
| 1846 | &engine_handle, |
| 1847 | exec_deadline, |
| 1848 | &mut exec_write_receipt, |
| 1849 | Some(&route_binding), |
| 1850 | ) |
| 1851 | .await |
| 1852 | } |
| 1853 | Err(error) => checkpoint |
| 1854 | .fail(format!("could not open exec checkpoint store: {error:#}")), |
| 1855 | } |
| 1856 | } |
| 1857 | latest_source = source; |
| 1858 | latest_session_id = Some(session_id); |
| 1859 | latest_messages = messages; |
| 1860 | latest_system_prompt = system_prompt; |
| 1861 | latest_model = model; |
| 1862 | latest_workspace = workspace; |
| 1863 | } |
| 1864 | // A tool-less one-shot run has no tool channel, so a model that |
| 1865 | // still tries to call a tool writes the call as text. The engine |
| 1866 | // strips that markup from the answer; say why the answer is short |
| 1867 | // and how to give the model tools, instead of exiting on nothing. |
| 1868 | Event::Status { message } |
| 1869 | if one_shot && message == codewhale_engine::core::engine::FAKE_WRAPPER_NOTICE => |
| 1870 | { |
| 1871 | eprintln!("{ONE_SHOT_TOOL_CALL_NOTICE}"); |
| 1872 | } |
| 1873 | // #3027: surface the engine's max-steps notice in text mode so a |
| 1874 | // --max-turns run that stops early says why instead of going quiet. |
| 1875 | Event::Status { message } |
| 1876 | if output_format == ExecOutputFormat::Text |
| 1877 | && !json_output |
| 1878 | && message.contains("Maximum model steps") => |
| 1879 | { |
| 1880 | eprintln!("{message}"); |
| 1881 | } |
| 1882 | Event::ToolRequestSnapshot { snapshot } => { |
| 1883 | if let Some(reason) = snapshot.terminal.as_ref().and_then(|facts| facts.reason) { |
| 1884 | summary.stop_reason = Some(reason.into()); |
| 1885 | } |
| 1886 | observed_retry_count = |
| 1887 | accumulate_exec_retry_count(observed_retry_count, snapshot.terminal.as_ref()); |
| 1888 | } |
| 1889 | Event::Status { message } => { |
| 1890 | if let Some(receipt) = exec_retry_status(&message) { |
| 1891 | if output_format == ExecOutputFormat::StreamJson { |
| 1892 | emit_exec_stream_event(&receipt)?; |
| 1893 | } else if output_format == ExecOutputFormat::Text && !json_output { |
| 1894 | eprintln!("{message}"); |
| 1895 | } |
| 1896 | } |
| 1897 | } |
| 1898 | _ => {} |
| 1899 | } |
| 1900 | } |
| 1901 | |
| 1902 | let run_duration_ms = u64::try_from(exec_started.elapsed().as_millis()).unwrap_or(u64::MAX); |
| 1903 | let shutdown_deadline = tokio::time::Instant::now() + Duration::from_secs(2); |
| 1904 | let completion = shutdown_exec_engine(&engine_handle, shutdown_deadline).await; |
| 1905 | if completion != Some(codewhale_engine::core::engine::EngineRunCompletion::NormalReturn) { |
| 1906 | tracing::warn!(target: "engine", ?completion, "exec engine run completion was not confirmed"); |
| 1907 | } |
| 1908 | |
| 1909 | if summary.status.is_none() { |
| 1910 | if let Ok(mut manager) = exec_shell_manager.lock() { |
| 1911 | manager.abort_persistent_services(); |
| 1912 | } |
| 1913 | let error = summary.error.clone().unwrap_or_else(|| { |
| 1914 | "Engine event channel closed before a terminal turn receipt".to_string() |
| 1915 | }); |
| 1916 | let category = last_error_category |
| 1917 | .unwrap_or_else(|| codewhale_error_taxonomy::classify_error_message(&error)); |
| 1918 | let termination_reason = codewhale_engine::core::termination::classify_turn_termination( |
| 1919 | codewhale_engine::core::events::TurnOutcomeStatus::Failed, |
| 1920 | Some(category), |
| 1921 | tool_error_seen, |
| 1922 | approval_required, |
| 1923 | ); |
| 1924 | summary.status = Some("failed".to_string()); |
| 1925 | summary.error_category = Some(category.to_string()); |
| 1926 | summary.termination_reason = Some(termination_reason.as_str().to_string()); |
| 1927 | summary.error = Some(error.clone()); |
| 1928 | // Lifecycle outbox: the engine channel closed before a terminal |
| 1929 | // turn receipt. Every emitted `turn_start` still gets its matching |
| 1930 | // `turn_end` so a supervisor never sees an orphaned in-progress |
| 1931 | // turn. No-op when the feature is disabled. |
| 1932 | lifecycle_outbox.emit(codewhale_hooks::LifecycleEvent { |
| 1933 | event: "turn_end".to_string(), |
| 1934 | kind: "turn.failed".to_string(), |
| 1935 | thread_id: latest_session_id.clone().unwrap_or_default(), |
| 1936 | turn_id: None, |
| 1937 | item_id: None, |
| 1938 | payload: serde_json::json!({ |
| 1939 | "status": "failed", |
| 1940 | "duration_ms": exec_turn_started_at.elapsed().as_millis() as u64, |
| 1941 | "workspace": latest_workspace.display().to_string(), |
| 1942 | "error": codewhale_hooks::bounded_text( |
| 1943 | &error, |
| 1944 | codewhale_hooks::OUTBOX_DETAIL_MAX_CHARS, |
| 1945 | ), |
| 1946 | }), |
| 1947 | }); |
| 1948 | if output_format == ExecOutputFormat::StreamJson { |
| 1949 | emit_exec_stream_event(&ExecStreamEvent::Error { error })?; |
| 1950 | } |
| 1951 | } |
| 1952 | |
| 1953 | summary.settle( |
| 1954 | settled_usage, |
| 1955 | routed_usage_dropped_records, |
| 1956 | usage_coverage_gap, |
| 1957 | ); |
| 1958 | if output_format == ExecOutputFormat::StreamJson { |
| 1959 | let reported_usage = summary.usage.as_ref(); |
| 1960 | if let Some(id) = saved_session_id.as_ref() { |
| 1961 | emit_exec_stream_event(&ExecStreamEvent::SessionCapture { |
| 1962 | content: exec_stream_session_ref(id), |
| 1963 | saved_session_id: id.clone(), |
| 1964 | })?; |
| 1965 | } |
| 1966 | // Resolved output ceiling and its provenance, surfaced so a |
| 1967 | // wrong ceiling is visible in the receipt rather than |
| 1968 | // requiring packet capture. |
| 1969 | let codewhale_max_output_tokens = |
| 1970 | codewhale_engine::route_budget::effective_max_output_tokens_for_turn_with_window( |
| 1971 | effective_provider, |
| 1972 | &latest_model, |
| 1973 | active_route_limits, |
| 1974 | (latest_model == effective_model).then_some(effective_context_window.tokens), |
| 1975 | None, |
| 1976 | None, |
| 1977 | ); |
| 1978 | let codewhale_max_output_tokens_source = |
| 1979 | codewhale_engine::route_budget::output_ceiling_source( |
| 1980 | effective_provider, |
| 1981 | &latest_model, |
| 1982 | ) |
| 1983 | .as_str(); |
| 1984 | // The deliverable is the final assistant reply of the |
| 1985 | // session, not the cumulative stream output: a |
| 1986 | // multi-step turn streams pre-tool commentary first, |
| 1987 | // and that commentary is not part of the answer. |
| 1988 | let final_answer = |
| 1989 | exec_stream_final_answer_text(&latest_messages, !summary.output.trim().is_empty()) |
| 1990 | .unwrap_or_default(); |
| 1991 | let binary_sha256 = match binary_identity.take() { |
| 1992 | Some(worker) => worker.await.ok().flatten(), |
| 1993 | None => None, |
| 1994 | }; |
| 1995 | emit_exec_stream_event(&ExecStreamEvent::Metadata { |
| 1996 | meta: Box::new(ExecStreamMeta { |
| 1997 | receipt_kind: "terminal", |
| 1998 | provider: effective_provider_kind.clone(), |
| 1999 | provider_id: effective_stream_provider_id.clone(), |
| 2000 | model: latest_model.clone(), |
| 2001 | route_source: route_source.clone(), |
| 2002 | input_tokens: reported_usage.map(|usage| usage.input_tokens), |
| 2003 | output_tokens: reported_usage.map(|usage| usage.output_tokens), |
| 2004 | prompt_cache_hit_tokens: reported_usage |
| 2005 | .and_then(|usage| usage.prompt_cache_hit_tokens), |
| 2006 | prompt_cache_miss_tokens: reported_usage |
| 2007 | .and_then(|usage| usage.prompt_cache_miss_tokens), |
| 2008 | prompt_cache_write_tokens: reported_usage |
| 2009 | .and_then(|usage| usage.prompt_cache_write_tokens), |
| 2010 | reasoning_tokens: reported_usage.and_then(|usage| usage.reasoning_tokens), |
| 2011 | usage_status: summary.usage_status, |
| 2012 | stop_reason: summary.stop_reason, |
| 2013 | codewhale_max_output_tokens: Some(codewhale_max_output_tokens), |
| 2014 | codewhale_max_output_tokens_source: Some(codewhale_max_output_tokens_source), |
| 2015 | duration_ms: run_duration_ms, |
| 2016 | retry_count: observed_retry_count, |
| 2017 | approval_posture: approval_posture.clone(), |
| 2018 | sandbox_posture: sandbox_posture.clone(), |
| 2019 | binary_sha256, |
| 2020 | config_sha256: None, |
| 2021 | prompt_sha256: prompt_sha256.clone(), |
| 2022 | tool_catalog_sha256, |
| 2023 | input_analysis: exec_stream_input_analysis( |
| 2024 | &latest_messages, |
| 2025 | latest_system_prompt.as_ref(), |
| 2026 | ), |
| 2027 | visible_final_answer_chars: final_answer.chars().count(), |
| 2028 | visible_final_answer_excerpt: exec_stream_final_answer_excerpt(&final_answer), |
| 2029 | resume_command: saved_session_id |
| 2030 | .as_deref() |
| 2031 | .map(exec_stream_resume_hint) |
| 2032 | .unwrap_or_default(), |
| 2033 | session_id: saved_session_id |
| 2034 | .as_deref() |
| 2035 | .map(exec_stream_session_ref) |
| 2036 | .unwrap_or_default(), |
| 2037 | workspace: latest_workspace.display().to_string(), |
| 2038 | message_count: latest_messages.len(), |
| 2039 | status: summary.status.clone(), |
| 2040 | termination_reason: summary.termination_reason.clone(), |
| 2041 | error_category: summary.error_category.clone(), |
| 2042 | error: summary.error.clone(), |
| 2043 | structured_output: summary.structured_output.clone(), |
| 2044 | }), |
| 2045 | })?; |
| 2046 | receipt_written.store(true, Ordering::SeqCst); |
| 2047 | emit_exec_stream_event(&ExecStreamEvent::Done)?; |
| 2048 | } |
| 2049 | |
| 2050 | // Drain the terminal receipt before returning. Outbox failures cannot change the |
| 2051 | // authoritative turn outcome. |
| 2052 | if let Err(error) = lifecycle_outbox.flush(Duration::from_secs(2)).await { |
| 2053 | tracing::warn!(target: "lifecycle_outbox", %error, "exec lifecycle outbox did not drain before exit"); |
| 2054 | } |
| 2055 | |
| 2056 | if json_output { |
| 2057 | write_exec_json_receipt(&summary, receipt_written)?; |
| 2058 | } |
| 2059 | |
| 2060 | if let Some(error) = summary.error.as_ref() |
| 2061 | && !error.trim().is_empty() |
| 2062 | { |
| 2063 | bail!("exec turn failed: {error}"); |
| 2064 | } |
| 2065 | |
| 2066 | if matches!( |
| 2067 | summary.status.as_deref(), |
| 2068 | Some("failed" | "canceled" | "interrupted") |
| 2069 | ) { |
| 2070 | let status = summary.status.as_deref().unwrap_or("unknown"); |
| 2071 | bail!("exec turn ended with status {status}"); |
| 2072 | } |
| 2073 | |
| 2074 | Ok(()) |
| 2075 | } |
| 2076 | |
| 2077 | fn exec_retry_status(message: &str) -> Option<ExecStreamEvent> { |
| 2078 | (codewhale_engine::core::events::is_retry_status_receipt(message) |
| 2079 | || codewhale_engine::core::events::is_request_image_status_receipt(message)) |
| 2080 | .then(|| ExecStreamEvent::Status { |
| 2081 | message: message.to_string(), |
| 2082 | }) |
| 2083 | } |
| 2084 | |
| 2085 | fn accumulate_exec_retry_count( |
| 2086 | previous: Option<u32>, |
| 2087 | terminal: Option<&codewhale_engine::tool_inspection::TurnStopDiagnostics>, |
| 2088 | ) -> Option<u32> { |
| 2089 | let Some(terminal) = terminal.filter(|facts| facts.status.is_some()) else { |
| 2090 | return previous; |
| 2091 | }; |
| 2092 | let retries = terminal |
| 2093 | .transport_retries |
| 2094 | .saturating_add(terminal.transparent_stream_retries) |
| 2095 | .saturating_add(terminal.stream_resumes) |
| 2096 | .saturating_add(terminal.empty_stop_retries) |
| 2097 | .saturating_add(terminal.reasoning_only_reprompts); |
| 2098 | Some(previous.unwrap_or(0).saturating_add(retries)) |
| 2099 | } |
| 2100 | |
| 2101 | #[cfg(test)] |
| 2102 | mod tests { |
| 2103 | use super::{ |
| 2104 | ExecAgentEvents, ExecRouteBinding, exec_automation_services, exec_disallowed_tools, |
| 2105 | shutdown_exec_engine, |
| 2106 | }; |
| 2107 | |
| 2108 | use codewhale_engine::core::engine::mock_engine_handle; |
| 2109 | use codewhale_engine::core::events::{Event, TurnOutcomeStatus}; |
| 2110 | use codewhale_engine::core::ops::{Op, SubAgentSettlement}; |
| 2111 | use codewhale_models::Usage; |
| 2112 | use codewhale_tools::names::REQUEST_USER_INPUT_NAME; |
| 2113 | use std::time::{Duration, Instant}; |
| 2114 | |
| 2115 | #[tokio::test] |
| 2116 | async fn run_completion_exec_shutdown_waits_after_mailbox_delivery() { |
| 2117 | let mut engine = mock_engine_handle(); |
| 2118 | let (release, receiver) = tokio::sync::oneshot::channel(); |
| 2119 | let run = engine.observe_run_for_test(async move { |
| 2120 | receiver.await.unwrap(); |
| 2121 | }); |
| 2122 | let task = tokio::spawn(run); |
| 2123 | let deadline = tokio::time::Instant::now() + Duration::from_secs(2); |
| 2124 | let wait = shutdown_exec_engine(&engine.handle, deadline); |
| 2125 | tokio::pin!(wait); |
| 2126 | tokio::select! { |
| 2127 | biased; |
| 2128 | result = &mut wait => panic!("send alone is not completion: {result:?}"), |
| 2129 | op = engine.rx_op.recv() => assert!(matches!(op, Some(Op::Shutdown))), |
| 2130 | } |
| 2131 | assert!( |
| 2132 | tokio::time::timeout_at(tokio::time::Instant::now(), &mut wait) |
| 2133 | .await |
| 2134 | .is_err() |
| 2135 | ); |
| 2136 | release.send(()).unwrap(); |
| 2137 | assert_eq!( |
| 2138 | wait.await, |
| 2139 | Some(codewhale_engine::core::engine::EngineRunCompletion::NormalReturn) |
| 2140 | ); |
| 2141 | task.await.unwrap(); |
| 2142 | } |
| 2143 | |
| 2144 | #[tokio::test] |
| 2145 | async fn run_completion_exec_shutdown_has_one_deadline_for_send_and_wait() { |
| 2146 | let mut engine = mock_engine_handle(); |
| 2147 | let _run = engine.observe_run_for_test(std::future::pending()); |
| 2148 | let deadline = tokio::time::Instant::now() - Duration::from_secs(1); |
| 2149 | tokio::time::sleep_until(deadline).await; |
| 2150 | { |
| 2151 | let mut shutdown = Box::pin(shutdown_exec_engine(&engine.handle, deadline)); |
| 2152 | std::future::poll_fn(|cx| { |
| 2153 | assert!(matches!( |
| 2154 | std::future::Future::poll(shutdown.as_mut(), cx), |
| 2155 | std::task::Poll::Ready(None) |
| 2156 | )); |
| 2157 | std::task::Poll::Ready(()) |
| 2158 | }) |
| 2159 | .await; |
| 2160 | } |
| 2161 | assert!(matches!(engine.rx_op.recv().await, Some(Op::Shutdown))); |
| 2162 | while engine.handle.try_send(Op::Shutdown).is_ok() {} |
| 2163 | let mut shutdown = Box::pin(shutdown_exec_engine(&engine.handle, deadline)); |
| 2164 | std::future::poll_fn(|cx| { |
| 2165 | assert!(matches!( |
| 2166 | std::future::Future::poll(shutdown.as_mut(), cx), |
| 2167 | std::task::Poll::Ready(None) |
| 2168 | )); |
| 2169 | std::task::Poll::Ready(()) |
| 2170 | }) |
| 2171 | .await; |
| 2172 | } |
| 2173 | |
| 2174 | #[tokio::test] |
| 2175 | async fn run_completion_exec_shutdown_uses_observed_exit_when_mailbox_closed() { |
| 2176 | use codewhale_engine::core::engine::EngineRunCompletion; |
| 2177 | for normal in [true, false] { |
| 2178 | let mut engine = mock_engine_handle(); |
| 2179 | let run = engine.observe_run_for_test(async {}); |
| 2180 | let expected = if normal { |
| 2181 | run.await; |
| 2182 | EngineRunCompletion::NormalReturn |
| 2183 | } else { |
| 2184 | drop(run); |
| 2185 | EngineRunCompletion::AbnormalTermination |
| 2186 | }; |
| 2187 | engine.rx_op.close(); |
| 2188 | assert_eq!( |
| 2189 | shutdown_exec_engine( |
| 2190 | &engine.handle, |
| 2191 | tokio::time::Instant::now() + Duration::from_secs(2) |
| 2192 | ) |
| 2193 | .await, |
| 2194 | Some(expected) |
| 2195 | ); |
| 2196 | } |
| 2197 | } |
| 2198 | |
| 2199 | #[test] |
| 2200 | fn run_completion_exec_shutdown_consumes_real_spawned_engine() { |
| 2201 | let _env = codewhale_engine::test_support::lock_test_env(); |
| 2202 | let home = tempfile::tempdir().unwrap(); |
| 2203 | let _home = codewhale_engine::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path()); |
| 2204 | let runtime = tokio::runtime::Builder::new_current_thread() |
| 2205 | .enable_all() |
| 2206 | .build() |
| 2207 | .unwrap(); |
| 2208 | runtime.block_on(async { |
| 2209 | let mut config = codewhale_engine::core::engine::EngineConfig { |
| 2210 | workspace: home.path().into(), |
| 2211 | snapshots_enabled: false, |
| 2212 | memory_enabled: false, |
| 2213 | subagents_enabled: false, |
| 2214 | ..Default::default() |
| 2215 | }; |
| 2216 | config |
| 2217 | .features |
| 2218 | .disable(codewhale_runtime::features::Feature::Mcp); |
| 2219 | let handle = codewhale_engine::core::engine::spawn_headless_engine( |
| 2220 | config, |
| 2221 | &codewhale_runtime::config::Config::default(), |
| 2222 | None, |
| 2223 | ) |
| 2224 | .await; |
| 2225 | assert_eq!( |
| 2226 | shutdown_exec_engine( |
| 2227 | &handle, |
| 2228 | tokio::time::Instant::now() + Duration::from_secs(5) |
| 2229 | ) |
| 2230 | .await, |
| 2231 | Some(codewhale_engine::core::engine::EngineRunCompletion::NormalReturn) |
| 2232 | ); |
| 2233 | }); |
| 2234 | } |
| 2235 | |
| 2236 | fn completed_parent(input_tokens: u32) -> Event { |
| 2237 | let usage = Usage { |
| 2238 | input_tokens, |
| 2239 | ..Usage::default() |
| 2240 | }; |
| 2241 | Event::TurnComplete { |
| 2242 | source_accounting: false, |
| 2243 | |
| 2244 | turn_id: None, |
| 2245 | submission_id: None, |
| 2246 | compaction_id: None, |
| 2247 | usage: usage.clone(), |
| 2248 | parent_route_usage: usage, |
| 2249 | routed_usage_dropped_records: 0, |
| 2250 | status: TurnOutcomeStatus::Completed, |
| 2251 | error: None, |
| 2252 | tool_catalog: None, |
| 2253 | base_url: None, |
| 2254 | } |
| 2255 | } |
| 2256 | |
| 2257 | async fn reply_to_probe( |
| 2258 | operations: &mut tokio::sync::mpsc::Receiver<Op>, |
| 2259 | snapshot: SubAgentSettlement, |
| 2260 | ) { |
| 2261 | let Op::GetSubAgentSettlement { tx } = operations.recv().await.expect("host probe") else { |
| 2262 | panic!("host must not shut down while child work remains"); |
| 2263 | }; |
| 2264 | tx.lock().unwrap().take().unwrap().send(snapshot).unwrap(); |
| 2265 | } |
| 2266 | |
| 2267 | #[test] |
| 2268 | fn headless_exec_withholds_request_user_input_without_a_responder() { |
| 2269 | // No responder exists on a one-shot CLI run, so the tool is |
| 2270 | // withheld by default rather than offered and stalled on. |
| 2271 | let disallowed = exec_disallowed_tools(None).expect("withhold list"); |
| 2272 | assert!( |
| 2273 | disallowed |
| 2274 | .iter() |
| 2275 | .any(|tool| tool.as_str() == REQUEST_USER_INPUT_NAME), |
| 2276 | "request_user_input must be withheld by default: {disallowed:?}" |
| 2277 | ); |
| 2278 | // An operator-passed entry is kept exactly once, not duplicated. |
| 2279 | let disallowed = exec_disallowed_tools(Some(vec![REQUEST_USER_INPUT_NAME.to_string()])) |
| 2280 | .expect("withhold list"); |
| 2281 | assert_eq!( |
| 2282 | disallowed |
| 2283 | .iter() |
| 2284 | .filter(|tool| tool.as_str() == REQUEST_USER_INPUT_NAME) |
| 2285 | .count(), |
| 2286 | 1 |
| 2287 | ); |
| 2288 | } |
| 2289 | |
| 2290 | #[tokio::test] |
| 2291 | async fn headless_success_waits_for_children_workflow_phases_and_parent_fan_in() { |
| 2292 | let mut engine = mock_engine_handle(); |
| 2293 | let mut events = ExecAgentEvents::new( |
| 2294 | engine.handle.clone(), |
| 2295 | Instant::now() + Duration::from_secs(3), |
| 2296 | ); |
| 2297 | engine.tx_event.send(completed_parent(11)).await.unwrap(); |
| 2298 | let actor = async { |
| 2299 | reply_to_probe( |
| 2300 | &mut engine.rx_op, |
| 2301 | SubAgentSettlement { |
| 2302 | running_children: 1, |
| 2303 | running_workflows: 1, |
| 2304 | pending_completions: 0, |
| 2305 | }, |
| 2306 | ) |
| 2307 | .await; |
| 2308 | reply_to_probe( |
| 2309 | &mut engine.rx_op, |
| 2310 | SubAgentSettlement { |
| 2311 | running_children: 0, |
| 2312 | running_workflows: 1, |
| 2313 | pending_completions: 0, |
| 2314 | }, |
| 2315 | ) |
| 2316 | .await; |
| 2317 | reply_to_probe( |
| 2318 | &mut engine.rx_op, |
| 2319 | SubAgentSettlement { |
| 2320 | running_children: 0, |
| 2321 | running_workflows: 0, |
| 2322 | pending_completions: 1, |
| 2323 | }, |
| 2324 | ) |
| 2325 | .await; |
| 2326 | engine |
| 2327 | .tx_event |
| 2328 | .send(Event::MessageDelta { |
| 2329 | content: "child findings reviewed".into(), |
| 2330 | index: 0, |
| 2331 | }) |
| 2332 | .await |
| 2333 | .unwrap(); |
| 2334 | engine.tx_event.send(completed_parent(7)).await.unwrap(); |
| 2335 | reply_to_probe(&mut engine.rx_op, SubAgentSettlement::default()).await; |
| 2336 | }; |
| 2337 | let host = async { |
| 2338 | assert!( |
| 2339 | matches!(events.next().await, Some(Event::MessageDelta { content, .. }) if content == "child findings reviewed") |
| 2340 | ); |
| 2341 | let Some(Event::TurnComplete { usage, status, .. }) = events.next().await else { |
| 2342 | panic!("settled parent receipt") |
| 2343 | }; |
| 2344 | assert_eq!(status, TurnOutcomeStatus::Completed); |
| 2345 | assert_eq!( |
| 2346 | usage.input_tokens, 18, |
| 2347 | "both parent turns are accounted once" |
| 2348 | ); |
| 2349 | }; |
| 2350 | tokio::time::timeout(Duration::from_secs(4), async { tokio::join!(actor, host) }) |
| 2351 | .await |
| 2352 | .unwrap(); |
| 2353 | assert!( |
| 2354 | !engine.handle.is_cancelled(), |
| 2355 | "ordinary success must not cancel children" |
| 2356 | ); |
| 2357 | assert!( |
| 2358 | engine.rx_op.try_recv().is_err(), |
| 2359 | "the event reader does not send early Shutdown" |
| 2360 | ); |
| 2361 | |
| 2362 | use codewhale_engine::core::events::{ |
| 2363 | SessionCheckpointCaller, SessionCheckpointProjection, SessionCheckpointRequest, |
| 2364 | }; |
| 2365 | use codewhale_engine::core::ops::SessionSnapshot; |
| 2366 | use std::sync::Arc; |
| 2367 | use tokio_util::sync::CancellationToken; |
| 2368 | |
| 2369 | let tmp = tempfile::tempdir().unwrap(); |
| 2370 | let manager = Arc::new( |
| 2371 | codewhale_engine::session_manager::SessionManager::new( |
| 2372 | tmp.path().join("fleet-capture"), |
| 2373 | ) |
| 2374 | .unwrap(), |
| 2375 | ); |
| 2376 | let workspace = tmp.path().join("workspace"); |
| 2377 | let messages: Vec<codewhale_models::Message> = serde_json::from_value(serde_json::json!([ |
| 2378 | {"role":"user","content":[{"type":"text","text":"review the changes"}]}, |
| 2379 | {"role":"assistant","content":[{"type":"tool_use","id":"provider-call","execution_id":"exec-call","name":"review","input":{}}]} |
| 2380 | ])).unwrap(); |
| 2381 | let snapshot = Arc::new(SessionSnapshot { |
| 2382 | source: Some(codewhale_engine::core::ops::SessionSnapshotSource::turn( |
| 2383 | "exec-turn".into(), |
| 2384 | None, |
| 2385 | )), |
| 2386 | |
| 2387 | session_id: "exec-checkpoint".into(), |
| 2388 | messages: messages.clone(), |
| 2389 | total_tokens: 23, |
| 2390 | model: "review-model".into(), |
| 2391 | model_provider: "custom".into(), |
| 2392 | model_provider_id: Some("review-route".into()), |
| 2393 | workspace: workspace.clone(), |
| 2394 | system_prompt: None, |
| 2395 | instruction_assembly: None, |
| 2396 | mode: "exec".into(), |
| 2397 | agent_preset: None, |
| 2398 | }); |
| 2399 | let caller = SessionCheckpointCaller { |
| 2400 | session_id: snapshot.session_id.clone(), |
| 2401 | agent_id: None, |
| 2402 | turn_id: "exec-turn".into(), |
| 2403 | call_id: "exec-call".into(), |
| 2404 | workspace: workspace.clone(), |
| 2405 | }; |
| 2406 | let checkpoint = |caller: SessionCheckpointCaller, snapshot: Arc<SessionSnapshot>| { |
| 2407 | let (reply, receive) = tokio::sync::oneshot::channel(); |
| 2408 | let hash = SessionCheckpointRequest::prefix_hash(&snapshot.messages).unwrap(); |
| 2409 | ( |
| 2410 | SessionCheckpointRequest::new( |
| 2411 | caller, |
| 2412 | snapshot, |
| 2413 | hash, |
| 2414 | SessionCheckpointProjection::Exact, |
| 2415 | CancellationToken::new(), |
| 2416 | reply, |
| 2417 | ), |
| 2418 | receive, |
| 2419 | ) |
| 2420 | }; |
| 2421 | let mut source = Some(manager.expect_absent_session(&snapshot.session_id).unwrap()); |
| 2422 | let binding = ExecRouteBinding { |
| 2423 | go_dispatch: None, |
| 2424 | endpoint: Some("fixture-endpoint-tag".into()), |
| 2425 | authority: Some("fixture-authority-tag".into()), |
| 2426 | }; |
| 2427 | let (request, receive) = checkpoint(caller.clone(), Arc::clone(&snapshot)); |
| 2428 | super::persist_exec_checkpoint( |
| 2429 | Arc::clone(&request), |
| 2430 | Some(Arc::clone(&manager)), |
| 2431 | &snapshot.session_id, |
| 2432 | &workspace, |
| 2433 | Some("exec-turn"), |
| 2434 | &engine.handle, |
| 2435 | Instant::now() + Duration::from_secs(3), |
| 2436 | &mut source, |
| 2437 | Some(&binding), |
| 2438 | ) |
| 2439 | .await; |
| 2440 | assert!(receive.await.unwrap().unwrap()); |
| 2441 | let persisted = manager.load_session_snapshot(&snapshot.session_id).unwrap(); |
| 2442 | assert_eq!(persisted.messages, messages); |
| 2443 | assert_eq!(persisted.metadata.total_tokens, 23); |
| 2444 | assert_eq!( |
| 2445 | persisted.metadata.exec_route_binding.as_ref(), |
| 2446 | Some(&binding) |
| 2447 | ); |
| 2448 | assert_eq!( |
| 2449 | persisted.metadata.model_provider_id.as_deref(), |
| 2450 | Some("review-route") |
| 2451 | ); |
| 2452 | assert_eq!(persisted.metadata.workspace, workspace); |
| 2453 | assert_eq!(persisted.metadata.mode.as_deref(), Some("exec")); |
| 2454 | |
| 2455 | let mut completed = messages.clone(); |
| 2456 | completed.push(serde_json::from_value(serde_json::json!({ |
| 2457 | "role":"user","content":[{"type":"tool_result","tool_use_id":"provider-call","execution_id":"exec-call","content":"review complete"}] |
| 2458 | })).unwrap()); |
| 2459 | let publication = crate::exec_agent::persist_exec_session( |
| 2460 | &completed, |
| 2461 | &snapshot.model, |
| 2462 | crate::exec_agent::PersistedProviderRoute { |
| 2463 | kind: "custom", |
| 2464 | id: Some("review-route"), |
| 2465 | binding: None, |
| 2466 | }, |
| 2467 | &workspace, |
| 2468 | &None, |
| 2469 | Some(&snapshot.session_id), |
| 2470 | 42, |
| 2471 | None, |
| 2472 | manager.as_ref(), |
| 2473 | &[], |
| 2474 | None, |
| 2475 | source.as_ref().unwrap(), |
| 2476 | snapshot.source.as_ref().unwrap(), |
| 2477 | None, |
| 2478 | ) |
| 2479 | .unwrap(); |
| 2480 | source = Some(publication.write_receipt()); |
| 2481 | super::persist_exec_checkpoint( |
| 2482 | request, |
| 2483 | Some(Arc::clone(&manager)), |
| 2484 | &snapshot.session_id, |
| 2485 | &workspace, |
| 2486 | Some("exec-turn"), |
| 2487 | &engine.handle, |
| 2488 | Instant::now() + Duration::from_secs(3), |
| 2489 | &mut source, |
| 2490 | None, |
| 2491 | ) |
| 2492 | .await; |
| 2493 | assert_eq!( |
| 2494 | manager |
| 2495 | .load_session_snapshot(&snapshot.session_id) |
| 2496 | .unwrap() |
| 2497 | .messages, |
| 2498 | completed |
| 2499 | ); |
| 2500 | |
| 2501 | for mismatch in ["session", "workspace", "child", "turn"] { |
| 2502 | let mut foreign = caller.clone(); |
| 2503 | match mismatch { |
| 2504 | "session" => foreign.session_id = "foreign-session".into(), |
| 2505 | "workspace" => foreign.workspace = tmp.path().join("foreign-workspace"), |
| 2506 | "child" => foreign.agent_id = Some("child-agent".into()), |
| 2507 | "turn" => foreign.turn_id = "foreign-turn".into(), |
| 2508 | _ => unreachable!(), |
| 2509 | } |
| 2510 | let (request, receive) = checkpoint(foreign, Arc::clone(&snapshot)); |
| 2511 | super::persist_exec_checkpoint( |
| 2512 | request, |
| 2513 | Some(Arc::clone(&manager)), |
| 2514 | &snapshot.session_id, |
| 2515 | &workspace, |
| 2516 | Some("exec-turn"), |
| 2517 | &engine.handle, |
| 2518 | Instant::now() + Duration::from_secs(3), |
| 2519 | &mut source, |
| 2520 | None, |
| 2521 | ) |
| 2522 | .await; |
| 2523 | assert!(receive.await.unwrap().is_err(), "{mismatch}"); |
| 2524 | } |
| 2525 | assert_eq!( |
| 2526 | manager |
| 2527 | .load_session_snapshot(&snapshot.session_id) |
| 2528 | .unwrap() |
| 2529 | .messages, |
| 2530 | completed |
| 2531 | ); |
| 2532 | assert!(!manager.sessions_dir().join("foreign-session.json").exists()); |
| 2533 | |
| 2534 | let (request, receive) = checkpoint(caller.clone(), Arc::clone(&snapshot)); |
| 2535 | request.withdraw.cancel(); |
| 2536 | super::persist_exec_checkpoint( |
| 2537 | request, |
| 2538 | Some(Arc::clone(&manager)), |
| 2539 | &snapshot.session_id, |
| 2540 | &workspace, |
| 2541 | Some("exec-turn"), |
| 2542 | &engine.handle, |
| 2543 | Instant::now() + Duration::from_secs(3), |
| 2544 | &mut source, |
| 2545 | None, |
| 2546 | ) |
| 2547 | .await; |
| 2548 | assert!(receive.await.unwrap().is_err()); |
| 2549 | let (request, receive) = checkpoint(caller.clone(), Arc::clone(&snapshot)); |
| 2550 | super::persist_exec_checkpoint( |
| 2551 | request, |
| 2552 | None, |
| 2553 | &snapshot.session_id, |
| 2554 | &workspace, |
| 2555 | Some("exec-turn"), |
| 2556 | &engine.handle, |
| 2557 | Instant::now() + Duration::from_secs(3), |
| 2558 | &mut source, |
| 2559 | None, |
| 2560 | ) |
| 2561 | .await; |
| 2562 | assert!(!receive.await.unwrap().unwrap()); |
| 2563 | |
| 2564 | let failed_store = Arc::new( |
| 2565 | codewhale_engine::session_manager::SessionManager::new(tmp.path().join("failed-store")) |
| 2566 | .unwrap(), |
| 2567 | ); |
| 2568 | std::fs::create_dir(failed_store.sessions_dir().join("exec-checkpoint.json")).unwrap(); |
| 2569 | let (request, receive) = checkpoint(caller.clone(), Arc::clone(&snapshot)); |
| 2570 | super::persist_exec_checkpoint( |
| 2571 | request, |
| 2572 | Some(failed_store), |
| 2573 | &snapshot.session_id, |
| 2574 | &workspace, |
| 2575 | Some("exec-turn"), |
| 2576 | &engine.handle, |
| 2577 | Instant::now() + Duration::from_secs(3), |
| 2578 | &mut source, |
| 2579 | None, |
| 2580 | ) |
| 2581 | .await; |
| 2582 | assert!(receive.await.unwrap().is_err()); |
| 2583 | let (request, receive) = checkpoint(caller, Arc::clone(&snapshot)); |
| 2584 | super::persist_exec_checkpoint( |
| 2585 | request, |
| 2586 | Some(Arc::clone(&manager)), |
| 2587 | &snapshot.session_id, |
| 2588 | &workspace, |
| 2589 | Some("exec-turn"), |
| 2590 | &engine.handle, |
| 2591 | Instant::now(), |
| 2592 | &mut source, |
| 2593 | None, |
| 2594 | ) |
| 2595 | .await; |
| 2596 | assert!(receive.await.unwrap().is_err()); |
| 2597 | assert!(engine.handle.is_cancelled()); |
| 2598 | assert_eq!( |
| 2599 | manager |
| 2600 | .load_session_snapshot(&snapshot.session_id) |
| 2601 | .unwrap() |
| 2602 | .messages, |
| 2603 | completed |
| 2604 | ); |
| 2605 | } |
| 2606 | |
| 2607 | #[test] |
| 2608 | fn exec_session_file_keeps_the_conversation_mode_it_was_started_in() { |
| 2609 | let tmp = tempfile::tempdir().unwrap(); |
| 2610 | let manager = |
| 2611 | codewhale_engine::session_manager::SessionManager::new(tmp.path().join("exec-mode")) |
| 2612 | .unwrap(); |
| 2613 | let workspace = tmp.path().join("workspace"); |
| 2614 | let messages: Vec<codewhale_models::Message> = serde_json::from_value(serde_json::json!([ |
| 2615 | {"role":"user","content":[{"type":"text","text":"hello"}]} |
| 2616 | ])) |
| 2617 | .unwrap(); |
| 2618 | let owner = |
| 2619 | codewhale_engine::core::ops::SessionSnapshotSource::turn("exec-turn".into(), None); |
| 2620 | let save = |source: &codewhale_engine::session_manager::SessionWriteReceipt, |
| 2621 | preset: Option<&str>| { |
| 2622 | crate::exec_agent::persist_exec_session( |
| 2623 | &messages, |
| 2624 | "model", |
| 2625 | crate::exec_agent::PersistedProviderRoute { |
| 2626 | kind: "custom", |
| 2627 | id: None, |
| 2628 | binding: None, |
| 2629 | }, |
| 2630 | &workspace, |
| 2631 | &None, |
| 2632 | Some("exec-mode-session"), |
| 2633 | 1, |
| 2634 | None, |
| 2635 | &manager, |
| 2636 | &[], |
| 2637 | None, |
| 2638 | source, |
| 2639 | &owner, |
| 2640 | preset, |
| 2641 | ) |
| 2642 | .unwrap() |
| 2643 | }; |
| 2644 | let first = save( |
| 2645 | &manager.expect_absent_session("exec-mode-session").unwrap(), |
| 2646 | Some("creator"), |
| 2647 | ); |
| 2648 | let saved = manager.load_session_snapshot("exec-mode-session").unwrap(); |
| 2649 | assert_eq!(saved.agent_preset.as_deref(), Some("creator")); |
| 2650 | |
| 2651 | save(&first.write_receipt(), None); |
| 2652 | let saved = manager.load_session_snapshot("exec-mode-session").unwrap(); |
| 2653 | assert_eq!( |
| 2654 | saved.agent_preset.as_deref(), |
| 2655 | Some("creator"), |
| 2656 | "a later save without the mode does not turn the conversation into Standard" |
| 2657 | ); |
| 2658 | } |
| 2659 | |
| 2660 | #[tokio::test] |
| 2661 | async fn headless_child_settlement_deadline_bounds_a_stalled_engine_probe() { |
| 2662 | let mut engine = mock_engine_handle(); |
| 2663 | let mut events = ExecAgentEvents::new( |
| 2664 | engine.handle.clone(), |
| 2665 | Instant::now() + Duration::from_millis(30), |
| 2666 | ); |
| 2667 | engine.tx_event.send(completed_parent(13)).await.unwrap(); |
| 2668 | let event = tokio::time::timeout(Duration::from_secs(1), events.next()) |
| 2669 | .await |
| 2670 | .unwrap(); |
| 2671 | let Some(Event::TurnComplete { |
| 2672 | status, |
| 2673 | error, |
| 2674 | usage, |
| 2675 | routed_usage_dropped_records, |
| 2676 | .. |
| 2677 | }) = event |
| 2678 | else { |
| 2679 | panic!("bounded failure receipt") |
| 2680 | }; |
| 2681 | assert_eq!(status, TurnOutcomeStatus::Failed); |
| 2682 | assert!(error.unwrap().contains("wall-clock budget exhausted")); |
| 2683 | assert_eq!(usage.input_tokens, 13); |
| 2684 | assert_eq!(routed_usage_dropped_records, 1); |
| 2685 | assert!(engine.handle.is_cancelled()); |
| 2686 | let mut shutdown = false; |
| 2687 | while let Ok(op) = engine.rx_op.try_recv() { |
| 2688 | shutdown |= matches!(op, Op::Shutdown); |
| 2689 | } |
| 2690 | assert!(shutdown, "shutdown must also cancel detached session tasks"); |
| 2691 | } |
| 2692 | |
| 2693 | #[tokio::test] |
| 2694 | async fn headless_failed_or_interrupted_parent_skips_child_settlement() { |
| 2695 | for terminal_status in [TurnOutcomeStatus::Failed, TurnOutcomeStatus::Interrupted] { |
| 2696 | let mut engine = mock_engine_handle(); |
| 2697 | let mut events = ExecAgentEvents::new( |
| 2698 | engine.handle.clone(), |
| 2699 | Instant::now() + Duration::from_secs(30), |
| 2700 | ); |
| 2701 | let mut terminal = completed_parent(3); |
| 2702 | if let Event::TurnComplete { status, .. } = &mut terminal { |
| 2703 | *status = terminal_status; |
| 2704 | } |
| 2705 | engine.tx_event.send(terminal).await.unwrap(); |
| 2706 | assert!( |
| 2707 | matches!(events.next().await, Some(Event::TurnComplete { status, .. }) if status == terminal_status) |
| 2708 | ); |
| 2709 | assert!( |
| 2710 | engine.rx_op.try_recv().is_err(), |
| 2711 | "failure cannot admit another settling turn" |
| 2712 | ); |
| 2713 | } |
| 2714 | } |
| 2715 | |
| 2716 | #[tokio::test] |
| 2717 | async fn headless_fatal_fan_in_error_cancels_before_releasing_terminal_receipt() { |
| 2718 | let engine = mock_engine_handle(); |
| 2719 | let mut events = ExecAgentEvents::new( |
| 2720 | engine.handle.clone(), |
| 2721 | Instant::now() + Duration::from_secs(30), |
| 2722 | ); |
| 2723 | engine.tx_event.send(completed_parent(5)).await.unwrap(); |
| 2724 | engine |
| 2725 | .tx_event |
| 2726 | .send(Event::error( |
| 2727 | codewhale_error_taxonomy::ErrorEnvelope::fatal("fan-in route unavailable"), |
| 2728 | )) |
| 2729 | .await |
| 2730 | .unwrap(); |
| 2731 | assert!(matches!(events.next().await, Some(Event::Error { .. }))); |
| 2732 | assert!(engine.handle.is_cancelled()); |
| 2733 | assert!( |
| 2734 | matches!(events.next().await, Some(Event::TurnComplete { status: TurnOutcomeStatus::Failed, error: Some(error), .. }) if error.contains("fan-in route unavailable")) |
| 2735 | ); |
| 2736 | } |
| 2737 | |
| 2738 | #[tokio::test] |
| 2739 | async fn headless_cancel_during_child_wait_returns_interrupted() { |
| 2740 | let mut engine = mock_engine_handle(); |
| 2741 | let mut events = ExecAgentEvents::new( |
| 2742 | engine.handle.clone(), |
| 2743 | Instant::now() + Duration::from_secs(30), |
| 2744 | ); |
| 2745 | engine.tx_event.send(completed_parent(5)).await.unwrap(); |
| 2746 | let cancel = async { |
| 2747 | reply_to_probe( |
| 2748 | &mut engine.rx_op, |
| 2749 | SubAgentSettlement { |
| 2750 | running_children: 1, |
| 2751 | running_workflows: 0, |
| 2752 | pending_completions: 0, |
| 2753 | }, |
| 2754 | ) |
| 2755 | .await; |
| 2756 | engine.handle.cancel(); |
| 2757 | }; |
| 2758 | let host = async { |
| 2759 | assert!(matches!( |
| 2760 | events.next().await, |
| 2761 | Some(Event::TurnComplete { |
| 2762 | status: TurnOutcomeStatus::Interrupted, |
| 2763 | .. |
| 2764 | }) |
| 2765 | )); |
| 2766 | }; |
| 2767 | tokio::time::timeout(Duration::from_secs(1), async { tokio::join!(cancel, host) }) |
| 2768 | .await |
| 2769 | .unwrap(); |
| 2770 | } |
| 2771 | |
| 2772 | #[tokio::test] |
| 2773 | async fn headless_closed_engine_cannot_reuse_an_earlier_success_receipt() { |
| 2774 | let mut engine = mock_engine_handle(); |
| 2775 | let mut events = ExecAgentEvents::new( |
| 2776 | engine.handle.clone(), |
| 2777 | Instant::now() + Duration::from_secs(30), |
| 2778 | ); |
| 2779 | engine.tx_event.send(completed_parent(5)).await.unwrap(); |
| 2780 | engine.close_event_stream(); |
| 2781 | assert!( |
| 2782 | matches!(events.next().await, Some(Event::TurnComplete { status: TurnOutcomeStatus::Failed, error: Some(error), .. }) if error.contains("channel closed")) |
| 2783 | ); |
| 2784 | } |
| 2785 | |
| 2786 | /// The reproduced defect: headless exec advertised `automation` while |
| 2787 | /// attaching no store, so every call — including the read-only `list` and |
| 2788 | /// `read` — failed "AutomationManager is not attached". Exec must attach |
| 2789 | /// the same durable store the TUI and the Runtime open. |
| 2790 | #[test] |
| 2791 | fn headless_exec_attaches_the_shared_automation_store() { |
| 2792 | let _lock = codewhale_engine::test_support::lock_test_env(); |
| 2793 | let tmp = tempfile::TempDir::new().expect("tempdir"); |
| 2794 | // SAFETY: serialised by lock_test_env. |
| 2795 | unsafe { |
| 2796 | std::env::set_var("CODEWHALE_AUTOMATIONS_DIR", tmp.path()); |
| 2797 | } |
| 2798 | let attached = exec_automation_services(false).expect("open store"); |
| 2799 | // SAFETY: cleanup under the same lock. |
| 2800 | unsafe { |
| 2801 | std::env::remove_var("CODEWHALE_AUTOMATIONS_DIR"); |
| 2802 | } |
| 2803 | let attached = attached.expect("exec attaches the automation store"); |
| 2804 | let manager = attached.blocking_lock(); |
| 2805 | // Reads work against the shared store... |
| 2806 | assert!( |
| 2807 | manager.list_automations().is_ok(), |
| 2808 | "an attached store must serve inspection" |
| 2809 | ); |
| 2810 | // ...while the exec host stays outside the Runtime's exclusive |
| 2811 | // task-execution lease, so it claims no dispatch ownership. |
| 2812 | assert!( |
| 2813 | manager.execution_scope().is_none(), |
| 2814 | "a one-shot host must not claim an execution scope" |
| 2815 | ); |
| 2816 | } |
| 2817 | |
| 2818 | /// A Fleet worker keeps the narrowed envelope it was launched with. |
| 2819 | #[test] |
| 2820 | fn fleet_workers_get_no_automation_store() { |
| 2821 | assert!( |
| 2822 | exec_automation_services(true) |
| 2823 | .expect("no store to open") |
| 2824 | .is_none() |
| 2825 | ); |
| 2826 | } |
| 2827 | |
| 2828 | /// A store that cannot be opened is reported, not swallowed into a silent |
| 2829 | /// "not attached" at the first tool call. |
| 2830 | #[test] |
| 2831 | fn an_unopenable_store_fails_loudly() { |
| 2832 | let _lock = codewhale_engine::test_support::lock_test_env(); |
| 2833 | let tmp = tempfile::NamedTempFile::new().expect("temp file"); |
| 2834 | // A regular file cannot host the store's directories. |
| 2835 | let blocked = tmp.path().join("automations"); |
| 2836 | // SAFETY: serialised by lock_test_env. |
| 2837 | unsafe { |
| 2838 | std::env::set_var("CODEWHALE_AUTOMATIONS_DIR", &blocked); |
| 2839 | } |
| 2840 | let result = exec_automation_services(false); |
| 2841 | // SAFETY: cleanup under the same lock. |
| 2842 | unsafe { |
| 2843 | std::env::remove_var("CODEWHALE_AUTOMATIONS_DIR"); |
| 2844 | } |
| 2845 | let err = result.expect_err("opening the store must fail"); |
| 2846 | assert!( |
| 2847 | format!("{err:#}").contains("automation store for headless exec"), |
| 2848 | "the failure must name what could not be opened: {err:#}" |
| 2849 | ); |
| 2850 | } |
| 2851 | |
| 2852 | #[test] |
| 2853 | fn exec_retry_receipts_keep_the_existing_jsonl_schema_and_text() { |
| 2854 | for message in [ |
| 2855 | "Retry attempt: transport 1/2; upstream 503; waiting 0.00s", |
| 2856 | "Retry recovery: transport request recovered after 1 retries", |
| 2857 | "Retry exhaustion: stream-resume stopped after 2 retries; stream interrupted", |
| 2858 | "Retry stopped: transparent stream completion was not observed", |
| 2859 | "Image request budget: omitted 4 older image-bearing blocks; retained 12 newest blocks.", |
| 2860 | "HTTP 413 recovery: retrying once without image attachments.", |
| 2861 | ] { |
| 2862 | let event = super::exec_retry_status(message).expect("request receipt projection"); |
| 2863 | let value = crate::exec_agent::exec_stream_value(&event).unwrap(); |
| 2864 | assert_eq!(value["type"], "status"); |
| 2865 | assert_eq!(value["message"], message); |
| 2866 | assert_eq!(value["schema"], "codewhale.exec-stream"); |
| 2867 | assert_eq!(value["schema_version"], 1); |
| 2868 | } |
| 2869 | assert!(super::exec_retry_status("Executing tools sequentially").is_none()); |
| 2870 | assert!(super::exec_retry_status("Goal set; starting goal work.").is_none()); |
| 2871 | } |
| 2872 | |
| 2873 | #[test] |
| 2874 | fn exec_retry_count_requires_terminal_facts_and_keeps_unknown_distinct_from_zero() { |
| 2875 | use codewhale_engine::tool_inspection::TurnStopDiagnostics; |
| 2876 | assert_eq!(super::accumulate_exec_retry_count(None, None), None); |
| 2877 | assert_eq!( |
| 2878 | super::accumulate_exec_retry_count(None, Some(&TurnStopDiagnostics::default())), |
| 2879 | None |
| 2880 | ); |
| 2881 | let zero = TurnStopDiagnostics { |
| 2882 | status: Some(TurnOutcomeStatus::Completed), |
| 2883 | ..Default::default() |
| 2884 | }; |
| 2885 | assert_eq!( |
| 2886 | super::accumulate_exec_retry_count(None, Some(&zero)), |
| 2887 | Some(0) |
| 2888 | ); |
| 2889 | let retries = TurnStopDiagnostics { |
| 2890 | status: Some(TurnOutcomeStatus::Failed), |
| 2891 | transport_retries: 2, |
| 2892 | stream_resumes: 3, |
| 2893 | transparent_stream_retries: 1, |
| 2894 | empty_stop_retries: 1, |
| 2895 | reasoning_only_reprompts: 2, |
| 2896 | ..Default::default() |
| 2897 | }; |
| 2898 | assert_eq!( |
| 2899 | super::accumulate_exec_retry_count(Some(0), Some(&retries)), |
| 2900 | Some(9) |
| 2901 | ); |
| 2902 | assert_eq!(super::accumulate_exec_retry_count(Some(9), None), Some(9)); |
| 2903 | assert_eq!( |
| 2904 | super::accumulate_exec_retry_count(Some(u32::MAX), Some(&retries)), |
| 2905 | Some(u32::MAX) |
| 2906 | ); |
| 2907 | } |
| 2908 | } |
| 2909 | |
| 2910 | #[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] |
| 2911 | pub enum ExecOutputFormat { |
| 2912 | Text, |
| 2913 | #[value(name = "stream-json")] |
| 2914 | StreamJson, |
| 2915 | } |
| 2916 | |
| 2917 | pub async fn admit_cli_saved_operation( |
| 2918 | manager: Option<std::sync::Arc<session_manager::SessionManager>>, |
| 2919 | id: String, |
| 2920 | workspace: PathBuf, |
| 2921 | model: String, |
| 2922 | provider: codewhale_runtime::config::ProviderIdentity, |
| 2923 | prompt: String, |
| 2924 | ) -> Result<( |
| 2925 | std::sync::Arc<session_manager::SessionManager>, |
| 2926 | session_manager::SessionWriteReceipt, |
| 2927 | session_manager::SessionLease, |
| 2928 | )> { |
| 2929 | codewhale_runtime::runtime_control::owner_work(move || { |
| 2930 | let manager = match manager { |
| 2931 | Some(manager) => manager, |
| 2932 | None => std::sync::Arc::new(session_manager::SessionManager::default_location()?), |
| 2933 | }; |
| 2934 | let lease = manager.reserve_session_for_external_write(&id)?; |
| 2935 | let source = manager.expect_absent_session(&id)?; |
| 2936 | let messages = vec![codewhale_models::Message { |
| 2937 | role: codewhale_models::Role::User, |
| 2938 | content: vec![codewhale_models::ContentBlock::Text { |
| 2939 | text: prompt, |
| 2940 | cache_control: None, |
| 2941 | }], |
| 2942 | }]; |
| 2943 | let mut saved = session_manager::create_saved_session_with_id_and_mode( |
| 2944 | id, |
| 2945 | &messages, |
| 2946 | &model, |
| 2947 | &workspace, |
| 2948 | 0, |
| 2949 | None, |
| 2950 | Some("exec"), |
| 2951 | ); |
| 2952 | let (kind, provider_id) = exec_stream_provider_route(&provider); |
| 2953 | saved.metadata.model_provider = kind; |
| 2954 | saved.metadata.model_provider_id = provider_id; |
| 2955 | saved.metadata.cost.coverage_recorded = true; |
| 2956 | saved.write_receipt = Some(source); |
| 2957 | saved.capture_publication(session_manager::SessionWriteOwner::control())?; |
| 2958 | let publication = manager.publish_session(&saved)?; |
| 2959 | Ok((manager, publication.write_receipt(), lease)) |
| 2960 | }) |
| 2961 | .await |
| 2962 | } |
| 2963 | |
| 2964 | #[cfg(windows)] |
| 2965 | pub fn paths_equal_for_config(left: &Path, right: &Path) -> bool { |
| 2966 | normalize_windows_config_path_for_compare(left) |
| 2967 | == normalize_windows_config_path_for_compare(right) |
| 2968 | } |
| 2969 | |
| 2970 | #[cfg(not(windows))] |
| 2971 | pub fn paths_equal_for_config(left: &Path, right: &Path) -> bool { |
| 2972 | left == right |
| 2973 | } |
| 2974 | |
| 2975 | #[cfg(windows)] |
| 2976 | fn normalize_windows_config_path_for_compare(path: &Path) -> String { |
| 2977 | normalize_windows_config_path_str(&path.to_string_lossy()) |
| 2978 | } |
| 2979 | |
| 2980 | #[cfg(any(windows, test))] |
| 2981 | fn normalize_windows_config_path_str(path: &str) -> String { |
| 2982 | let mut normalized = path.replace('/', "\\"); |
| 2983 | if let Some(rest) = normalized.strip_prefix(r"\\?\UNC\") { |
| 2984 | normalized = format!("\\\\{rest}"); |
| 2985 | } else if let Some(rest) = normalized.strip_prefix(r"\\?\") { |
| 2986 | normalized = rest.to_string(); |
| 2987 | } |
| 2988 | while normalized.len() > 3 && normalized.ends_with('\\') { |
| 2989 | normalized.pop(); |
| 2990 | } |
| 2991 | normalized.to_ascii_lowercase() |
| 2992 | } |
| 2993 | |
| 2994 | #[derive(Debug)] |
| 2995 | pub struct CliAutoRoute { |
| 2996 | pub provider: codewhale_runtime::config::ProviderIdentity, |
| 2997 | pub model: String, |
| 2998 | pub reasoning_effort: Option<codewhale_engine::reasoning_preference::ReasoningEffort>, |
| 2999 | /// Whether the runtime should continue resolving reasoning per prompt. |
| 3000 | /// |
| 3001 | /// This is independent from `auto_model`: an Auto model can carry a fixed |
| 3002 | /// saved effort, while a fixed Fleet model can still request Auto effort. |
| 3003 | pub auto_controls_reasoning: bool, |
| 3004 | pub auto_model: bool, |
| 3005 | } |
| 3006 | |
| 3007 | pub fn cli_reasoning_effort_value( |
| 3008 | config: &Config, |
| 3009 | model: &str, |
| 3010 | effort: codewhale_engine::reasoning_preference::ReasoningEffort, |
| 3011 | ) -> Option<String> { |
| 3012 | let identity = config.active_provider_identity().ok()?; |
| 3013 | effort |
| 3014 | .normalize_for_route_identity( |
| 3015 | identity.provider, |
| 3016 | identity.key.as_str(), |
| 3017 | &config.base_url_for_route(&identity), |
| 3018 | model, |
| 3019 | ) |
| 3020 | .api_value_for_provider(identity.provider) |
| 3021 | .map(str::to_string) |
| 3022 | } |
| 3023 | |
| 3024 | fn cli_reasoning_effort_value_for_prompt( |
| 3025 | config: &Config, |
| 3026 | model: &str, |
| 3027 | effort: codewhale_engine::reasoning_preference::ReasoningEffort, |
| 3028 | ) -> Option<String> { |
| 3029 | let resolved = if effort == codewhale_engine::reasoning_preference::ReasoningEffort::Auto { |
| 3030 | codewhale_engine::auto_reasoning::select() |
| 3031 | } else { |
| 3032 | effort |
| 3033 | }; |
| 3034 | cli_reasoning_effort_value(config, model, resolved) |
| 3035 | } |
| 3036 | |
| 3037 | pub fn config_for_cli_route(config: &Config, route: &CliAutoRoute) -> Result<Config> { |
| 3038 | let mut execution_config = config.clone(); |
| 3039 | execution_config |
| 3040 | .scope_to_provider_identity(&route.provider) |
| 3041 | .map_err(anyhow::Error::msg)?; |
| 3042 | execution_config.set_provider_model_override(&route.provider, Some(route.model.clone()))?; |
| 3043 | if route.provider.provider == codewhale_config::ProviderKind::Deepseek { |
| 3044 | execution_config.default_text_model = Some(route.model.clone()); |
| 3045 | } |
| 3046 | Ok(execution_config) |
| 3047 | } |
| 3048 | |
| 3049 | async fn resolve_cli_auto_route( |
| 3050 | config: &Config, |
| 3051 | model: &str, |
| 3052 | prompt: &str, |
| 3053 | accounting_origin: Option<codewhale_engine::cost_status::NativeUsageOrigin>, |
| 3054 | ) -> Result<CliAutoRoute> { |
| 3055 | let active = config |
| 3056 | .active_provider_identity() |
| 3057 | .map_err(anyhow::Error::msg)?; |
| 3058 | if model.trim().eq_ignore_ascii_case("auto") { |
| 3059 | let selection = |
| 3060 | model_routing::resolve_auto_route_with_inventory_for_session_and_cache_policy( |
| 3061 | config, |
| 3062 | prompt, |
| 3063 | "", |
| 3064 | "agent", |
| 3065 | "auto", |
| 3066 | "auto", |
| 3067 | true, |
| 3068 | accounting_origin.map(|origin| { |
| 3069 | codewhale_engine::cost_status::NativeUsageSource::capture_with_origin( |
| 3070 | format!("cli-auto-router:{}", uuid::Uuid::new_v4()), |
| 3071 | codewhale_engine::cost_status::UsageSpendOwner::Auxiliary, |
| 3072 | Some(origin), |
| 3073 | ) |
| 3074 | }), |
| 3075 | ) |
| 3076 | .await?; |
| 3077 | let preference = config |
| 3078 | .reasoning_effort() |
| 3079 | .filter(|_| config.reasoning_effort_is_explicit()) |
| 3080 | .map(codewhale_engine::reasoning_preference::ReasoningEffort::from_setting); |
| 3081 | let (reasoning_effort, auto_controls_reasoning) = |
| 3082 | model_routing::resolve_auto_model_reasoning(preference, selection.reasoning_effort); |
| 3083 | Ok(CliAutoRoute { |
| 3084 | provider: selection.provider, |
| 3085 | model: selection.model, |
| 3086 | reasoning_effort, |
| 3087 | auto_controls_reasoning, |
| 3088 | auto_model: true, |
| 3089 | }) |
| 3090 | } else { |
| 3091 | if let Some(selection) = model_routing::resolve_explicit_route_with_inventory(config, model) |
| 3092 | { |
| 3093 | let auto_controls_reasoning = matches!( |
| 3094 | selection.reasoning_effort, |
| 3095 | Some(codewhale_engine::reasoning_preference::ReasoningEffort::Auto) |
| 3096 | ); |
| 3097 | return Ok(CliAutoRoute { |
| 3098 | provider: selection.provider, |
| 3099 | model: selection.model, |
| 3100 | reasoning_effort: selection.reasoning_effort, |
| 3101 | auto_controls_reasoning, |
| 3102 | auto_model: false, |
| 3103 | }); |
| 3104 | } |
| 3105 | |
| 3106 | let candidate_providers = model_routing::explicit_route_candidate_providers(config, model); |
| 3107 | if !candidate_providers.is_empty() && !candidate_providers.contains(&active) { |
| 3108 | let providers = candidate_providers |
| 3109 | .iter() |
| 3110 | .map(|provider| provider.key.as_str()) |
| 3111 | .collect::<Vec<_>>() |
| 3112 | .join(", "); |
| 3113 | bail!( |
| 3114 | "model `{model}` is available from configured provider route(s): {providers}. \ |
| 3115 | Pass `--provider <provider>` with `--model {model}` to choose one explicitly. \ |
| 3116 | In the TUI, use `/provider`, `/model`, or `/setup` to resolve the route before sending." |
| 3117 | ); |
| 3118 | } |
| 3119 | |
| 3120 | // When --model is not `auto`, fall back to the reasoning_effort |
| 3121 | // declared in the user's config.toml. The previous hard-coded `None` |
| 3122 | // silently dropped the user's setting on every non-auto-route exec |
| 3123 | // call, which (for example) prevented vllm + Qwen3 users from |
| 3124 | // disabling thinking via `reasoning_effort = "off"` and caused |
| 3125 | // 30+ second SSE idle timeouts on trivial prompts. |
| 3126 | let reasoning_effort = config |
| 3127 | .reasoning_effort() |
| 3128 | .map(codewhale_engine::reasoning_preference::ReasoningEffort::from_setting); |
| 3129 | Ok(CliAutoRoute { |
| 3130 | provider: active, |
| 3131 | model: model.to_string(), |
| 3132 | auto_controls_reasoning: matches!( |
| 3133 | reasoning_effort, |
| 3134 | Some(codewhale_engine::reasoning_preference::ReasoningEffort::Auto) |
| 3135 | ), |
| 3136 | reasoning_effort, |
| 3137 | auto_model: false, |
| 3138 | }) |
| 3139 | } |
| 3140 | } |
| 3141 | |
| 3142 | pub async fn resolve_cli_exec_route( |
| 3143 | config: &Config, |
| 3144 | model: &str, |
| 3145 | prompt: &str, |
| 3146 | force_configured_route: bool, |
| 3147 | accounting_origin: Option<codewhale_engine::cost_status::NativeUsageOrigin>, |
| 3148 | ) -> Result<CliAutoRoute> { |
| 3149 | let mut local_default = None; |
| 3150 | if let Ok(identity) = config.active_provider_identity() |
| 3151 | && identity.provider == codewhale_config::ProviderKind::Ollama |
| 3152 | { |
| 3153 | codewhale_engine::provider_lake::refresh_local_ollama_catalog(config, &identity).await; |
| 3154 | if codewhale_runtime::config::is_unresolved_local_ollama_model(model) |
| 3155 | || (force_configured_route && model.trim().eq_ignore_ascii_case("auto")) |
| 3156 | { |
| 3157 | local_default = Some( |
| 3158 | codewhale_engine::route_runtime::resolve_runtime_route_for_identity( |
| 3159 | config, &identity, None, |
| 3160 | ) |
| 3161 | .map_err(anyhow::Error::msg)? |
| 3162 | .model, |
| 3163 | ); |
| 3164 | } |
| 3165 | } |
| 3166 | let model = local_default.as_deref().unwrap_or(model); |
| 3167 | if force_configured_route && !model.trim().eq_ignore_ascii_case("auto") { |
| 3168 | let reasoning_effort = config |
| 3169 | .reasoning_effort() |
| 3170 | .map(codewhale_engine::reasoning_preference::ReasoningEffort::from_setting); |
| 3171 | return Ok(CliAutoRoute { |
| 3172 | provider: config |
| 3173 | .active_provider_identity() |
| 3174 | .map_err(anyhow::Error::msg)?, |
| 3175 | model: model.to_string(), |
| 3176 | auto_controls_reasoning: matches!( |
| 3177 | reasoning_effort, |
| 3178 | Some(codewhale_engine::reasoning_preference::ReasoningEffort::Auto) |
| 3179 | ), |
| 3180 | reasoning_effort, |
| 3181 | auto_model: false, |
| 3182 | }); |
| 3183 | } |
| 3184 | resolve_cli_auto_route(config, model, prompt, accounting_origin).await |
| 3185 | } |
| 3186 | |
| 3187 | pub fn exec_stream_provider_route( |
| 3188 | identity: &codewhale_runtime::config::ProviderIdentity, |
| 3189 | ) -> (String, Option<String>) { |
| 3190 | let provider = identity.persisted_kind().to_string(); |
| 3191 | let provider_id = if identity.provider == codewhale_config::ProviderKind::Custom { |
| 3192 | identity.persisted_id().map(str::to_string) |
| 3193 | } else { |
| 3194 | None |
| 3195 | }; |
| 3196 | (provider, provider_id) |
| 3197 | } |
| 3198 | |
| 3199 | #[derive(serde::Serialize)] |
| 3200 | pub struct ExecStreamMeta { |
| 3201 | pub receipt_kind: &'static str, |
| 3202 | pub provider: String, |
| 3203 | /// Exact configured provider-table id, when one selected the route. |
| 3204 | /// `None` deliberately distinguishes the legacy idless root custom route |
| 3205 | /// from literal `[providers.custom]`, whose exact id is `"custom"`. |
| 3206 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3207 | pub provider_id: Option<String>, |
| 3208 | pub model: String, |
| 3209 | pub route_source: String, |
| 3210 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3211 | pub input_tokens: Option<u32>, |
| 3212 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3213 | pub output_tokens: Option<u32>, |
| 3214 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3215 | pub prompt_cache_hit_tokens: Option<u32>, |
| 3216 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3217 | pub prompt_cache_miss_tokens: Option<u32>, |
| 3218 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3219 | pub prompt_cache_write_tokens: Option<u32>, |
| 3220 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3221 | pub reasoning_tokens: Option<u32>, |
| 3222 | pub usage_status: ExecUsageStatus, |
| 3223 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3224 | pub stop_reason: Option<codewhale_engine::runtime_threads::RuntimeTurnStopReason>, |
| 3225 | /// Resolved output ceiling the route actually requested (post-catalogue). |
| 3226 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3227 | pub codewhale_max_output_tokens: Option<u32>, |
| 3228 | /// Provenance of that ceiling: `documented`, `uncatalogued`, or |
| 3229 | /// `route-declared`. |
| 3230 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3231 | pub codewhale_max_output_tokens_source: Option<&'static str>, |
| 3232 | pub duration_ms: u64, |
| 3233 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3234 | pub retry_count: Option<u32>, |
| 3235 | pub approval_posture: String, |
| 3236 | pub sandbox_posture: String, |
| 3237 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3238 | pub binary_sha256: Option<String>, |
| 3239 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3240 | pub config_sha256: Option<String>, |
| 3241 | pub prompt_sha256: String, |
| 3242 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3243 | pub tool_catalog_sha256: Option<String>, |
| 3244 | pub input_analysis: ExecStreamInputAnalysis, |
| 3245 | /// Real character count of the visible final answer, before any bound. |
| 3246 | pub visible_final_answer_chars: usize, |
| 3247 | /// Bounded, secret-redacted excerpt of the visible final answer (see |
| 3248 | /// [`exec_stream_final_answer_excerpt`]). Omitted when the run produced |
| 3249 | /// no visible answer. |
| 3250 | #[serde(skip_serializing_if = "String::is_empty")] |
| 3251 | pub visible_final_answer_excerpt: String, |
| 3252 | pub session_id: String, |
| 3253 | pub resume_command: String, |
| 3254 | pub workspace: String, |
| 3255 | pub message_count: usize, |
| 3256 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3257 | pub status: Option<String>, |
| 3258 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3259 | pub termination_reason: Option<String>, |
| 3260 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3261 | pub error_category: Option<String>, |
| 3262 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3263 | pub error: Option<String>, |
| 3264 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3265 | pub structured_output: Option<serde_json::Value>, |
| 3266 | } |
| 3267 | |
| 3268 | #[derive(Debug, Default, Clone, serde::Serialize, PartialEq, Eq)] |
| 3269 | pub struct ExecStreamInputAnalysis { |
| 3270 | estimated_request_tokens: usize, |
| 3271 | estimated_message_content_tokens: usize, |
| 3272 | estimated_system_tokens: usize, |
| 3273 | estimated_framing_tokens: usize, |
| 3274 | user_message_count: usize, |
| 3275 | assistant_message_count: usize, |
| 3276 | tool_message_count: usize, |
| 3277 | tool_use_count: usize, |
| 3278 | tool_result_count: usize, |
| 3279 | text_chars: usize, |
| 3280 | thinking_chars: usize, |
| 3281 | tool_use_input_chars: usize, |
| 3282 | tool_result_chars: usize, |
| 3283 | text_estimated_tokens: usize, |
| 3284 | thinking_estimated_tokens: usize, |
| 3285 | tool_use_input_estimated_tokens: usize, |
| 3286 | tool_result_estimated_tokens: usize, |
| 3287 | } |
| 3288 | |
| 3289 | #[derive(serde::Serialize)] |
| 3290 | #[serde(tag = "type")] |
| 3291 | // Keep receipts flat for stable JSONL consumers. Boxing the whole tool_result |
| 3292 | // payload would introduce a nested object and break the stream schema. |
| 3293 | #[allow(clippy::large_enum_variant)] |
| 3294 | pub enum ExecStreamEvent { |
| 3295 | #[serde(rename = "status")] |
| 3296 | Status { message: String }, |
| 3297 | #[serde(rename = "request_image_window")] |
| 3298 | RequestImageWindow { |
| 3299 | provider: String, |
| 3300 | model: String, |
| 3301 | total: usize, |
| 3302 | elided: usize, |
| 3303 | cap: usize, |
| 3304 | cap_source: String, |
| 3305 | message: String, |
| 3306 | }, |
| 3307 | #[serde(rename = "content")] |
| 3308 | Content { content: String }, |
| 3309 | #[serde(rename = "tool_use")] |
| 3310 | ToolUse { |
| 3311 | name: String, |
| 3312 | id: String, |
| 3313 | input: serde_json::Value, |
| 3314 | started_at: String, |
| 3315 | }, |
| 3316 | #[serde(rename = "tool_result")] |
| 3317 | ToolResult { |
| 3318 | id: String, |
| 3319 | name: String, |
| 3320 | output: String, |
| 3321 | status: String, |
| 3322 | started_at: String, |
| 3323 | completed_at: String, |
| 3324 | duration_ms: u64, |
| 3325 | side_effect_status: String, |
| 3326 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3327 | error_category: Option<String>, |
| 3328 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3329 | truncated: Option<bool>, |
| 3330 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3331 | artifact: Option<serde_json::Value>, |
| 3332 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3333 | result_metadata: Option<serde_json::Value>, |
| 3334 | }, |
| 3335 | /// A sub-agent was launched, and the model it was launched on. |
| 3336 | /// |
| 3337 | /// Without this, a delegated child is invisible to anything reading the |
| 3338 | /// stream: a parent turn on one route could spawn children billed on |
| 3339 | /// another and the only place it surfaced was the invoice. That is not |
| 3340 | /// hypothetical — the `Fast` loadout re-priced scout children onto a |
| 3341 | /// cheaper sibling until it was fixed, and nothing in the output said so. |
| 3342 | #[serde(rename = "agent_spawned")] |
| 3343 | AgentSpawned { |
| 3344 | id: String, |
| 3345 | model: String, |
| 3346 | spawn_depth: u32, |
| 3347 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3348 | parent_run_id: Option<String>, |
| 3349 | /// Why the child got this route, when the spawn path resolved one. |
| 3350 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3351 | route_source: Option<String>, |
| 3352 | }, |
| 3353 | #[serde(rename = "sandbox_denied")] |
| 3354 | SandboxDenied { |
| 3355 | tool_id: String, |
| 3356 | tool_name: String, |
| 3357 | reason: String, |
| 3358 | outcome: String, |
| 3359 | }, |
| 3360 | #[serde(rename = "workflow_event")] |
| 3361 | WorkflowEvent { |
| 3362 | run_id: String, |
| 3363 | event: serde_json::Value, |
| 3364 | }, |
| 3365 | #[serde(rename = "session_capture")] |
| 3366 | SessionCapture { |
| 3367 | /// Redacted fingerprint for logs/forensics, the same value the |
| 3368 | /// terminal `metadata.session_id` carries; never the recoverable id. |
| 3369 | content: String, |
| 3370 | /// The real saved-session id a caller can resolve via |
| 3371 | /// `GET /v1/sessions/{id}` to read the worker's full transcript. This |
| 3372 | /// is the only place the exec stream carries the raw id: `metadata` |
| 3373 | /// stays fingerprint-only so a captured terminal receipt is safe to |
| 3374 | /// log on its own. |
| 3375 | saved_session_id: String, |
| 3376 | }, |
| 3377 | #[serde(rename = "service_released")] |
| 3378 | #[cfg(unix)] |
| 3379 | ServiceReleased { |
| 3380 | task_id: String, |
| 3381 | pid: u32, |
| 3382 | process_group_id: u32, |
| 3383 | ownership: String, |
| 3384 | }, |
| 3385 | #[serde(rename = "provider_request_receipt")] |
| 3386 | ProviderRequestReceipt { receipt: serde_json::Value }, |
| 3387 | /// Per-model-call usage receipt. Field names mirror the terminal |
| 3388 | /// `metadata` receipt (`prompt_cache_hit_tokens` is the provider's |
| 3389 | /// cache-read count, `prompt_cache_write_tokens` the cache-creation |
| 3390 | /// count). Optional fields are omitted — never emitted as null or zero — |
| 3391 | /// when the provider does not report them; the whole event is skipped |
| 3392 | /// for model calls whose provider reported no usage at all. |
| 3393 | #[serde(rename = "turn_usage")] |
| 3394 | TurnUsage { |
| 3395 | /// 1-based index of the model call within this exec run. |
| 3396 | turn: u32, |
| 3397 | input_tokens: u32, |
| 3398 | output_tokens: u32, |
| 3399 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3400 | reasoning_tokens: Option<u32>, |
| 3401 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3402 | prompt_cache_hit_tokens: Option<u32>, |
| 3403 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3404 | prompt_cache_miss_tokens: Option<u32>, |
| 3405 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3406 | prompt_cache_write_tokens: Option<u32>, |
| 3407 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3408 | reasoning_replay_tokens: Option<u32>, |
| 3409 | duration_ms: u64, |
| 3410 | #[serde(skip_serializing_if = "Option::is_none")] |
| 3411 | finish_reason: Option<String>, |
| 3412 | }, |
| 3413 | #[serde(rename = "metadata")] |
| 3414 | Metadata { meta: Box<ExecStreamMeta> }, |
| 3415 | #[serde(rename = "done")] |
| 3416 | Done, |
| 3417 | #[serde(rename = "error")] |
| 3418 | Error { error: String }, |
| 3419 | } |
| 3420 | |
| 3421 | pub fn exec_sandbox_elevation_authorized( |
| 3422 | allow_sandbox_elevation: bool, |
| 3423 | explicit_sandbox: Option<&str>, |
| 3424 | ) -> bool { |
| 3425 | allow_sandbox_elevation |
| 3426 | || explicit_sandbox.is_some_and(|policy| policy.eq_ignore_ascii_case("danger-full-access")) |
| 3427 | } |
| 3428 | |
| 3429 | pub fn emit_exec_stream_event(event: &ExecStreamEvent) -> Result<()> { |
| 3430 | let mut line = serde_json::to_string(&exec_stream_value(event)?)?; |
| 3431 | line.push('\n'); |
| 3432 | write_exec_stdout(&line) |
| 3433 | } |
| 3434 | |
| 3435 | pub fn write_exec_json_receipt(summary: &ExecSummary, receipt_written: &AtomicBool) -> Result<()> { |
| 3436 | receipt_written.store(true, Ordering::SeqCst); |
| 3437 | write_exec_stdout(&format!("{}\n", serde_json::to_string_pretty(summary)?)) |
| 3438 | } |
| 3439 | |
| 3440 | pub fn write_exec_failure_receipt( |
| 3441 | receipt_written: &AtomicBool, |
| 3442 | json_output: bool, |
| 3443 | output_format: ExecOutputFormat, |
| 3444 | mode: &str, |
| 3445 | provider: &str, |
| 3446 | error: &str, |
| 3447 | ) -> Result<()> { |
| 3448 | if receipt_written.load(Ordering::SeqCst) { |
| 3449 | return Ok(()); |
| 3450 | } |
| 3451 | if json_output { |
| 3452 | let mut summary = |
| 3453 | ExecSummary::new(mode, provider.to_string(), String::new(), String::new()); |
| 3454 | summary.record_turn_outcome( |
| 3455 | codewhale_engine::core::events::TurnOutcomeStatus::Failed, |
| 3456 | Some(error.to_string()), |
| 3457 | ); |
| 3458 | summary.settle(None, 0, false); |
| 3459 | return write_exec_json_receipt(&summary, receipt_written); |
| 3460 | } |
| 3461 | if output_format == ExecOutputFormat::StreamJson { |
| 3462 | receipt_written.store(true, Ordering::SeqCst); |
| 3463 | return emit_exec_stream_event(&ExecStreamEvent::Error { |
| 3464 | error: error.to_string(), |
| 3465 | }); |
| 3466 | } |
| 3467 | Ok(()) |
| 3468 | } |
| 3469 | |
| 3470 | /// Headless `exec` ignores SIGPIPE while it runs, because it writes to pipes |
| 3471 | /// it does not own: a stdio MCP server, LSP, hook or shell child that exits |
| 3472 | /// early must fail that one write with `EPIPE`, not kill the run with no |
| 3473 | /// output. Under the default disposition, an MCP server whose interpreter |
| 3474 | /// could not start (a broken `node` on PATH for the built-in Computer Use |
| 3475 | /// plugin) made `exec --auto` exit 141 before printing anything. |
| 3476 | fn ignore_sigpipe_for_headless_exec() { |
| 3477 | // SAFETY: a plain disposition change with no handler. Children still start |
| 3478 | // with SIGPIPE at SIG_DFL: the standard library resets it before exec. |
| 3479 | #[cfg(unix)] |
| 3480 | unsafe { |
| 3481 | libc::signal(libc::SIGPIPE, libc::SIG_IGN); |
| 3482 | } |
| 3483 | } |
| 3484 | |
| 3485 | /// Write exec output to stdout. SIGPIPE is ignored during exec (see |
| 3486 | /// [`ignore_sigpipe_for_headless_exec`]), so a reader that closed stdout |
| 3487 | /// (`codewhale exec ... | head -1`) surfaces here as `BrokenPipe`. End the |
| 3488 | /// process the way the default disposition would have (#4030) instead of |
| 3489 | /// panicking inside `print!`. |
| 3490 | fn write_exec_stdout(text: &str) -> Result<()> { |
| 3491 | let mut stdout = io::stdout().lock(); |
| 3492 | match stdout |
| 3493 | .write_all(text.as_bytes()) |
| 3494 | .and_then(|()| stdout.flush()) |
| 3495 | { |
| 3496 | Err(err) if err.kind() == io::ErrorKind::BrokenPipe => { |
| 3497 | let _ = codewhale_telemetry::report_termination( |
| 3498 | codewhale_telemetry::ExitClass::Signal, |
| 3499 | codewhale_telemetry::SIGNAL_FLUSH_TIMEOUT, |
| 3500 | ); |
| 3501 | // SAFETY: restores the default disposition and re-raises the |
| 3502 | // signal the write would have delivered without SIG_IGN. |
| 3503 | #[cfg(unix)] |
| 3504 | unsafe { |
| 3505 | libc::signal(libc::SIGPIPE, libc::SIG_DFL); |
| 3506 | libc::raise(libc::SIGPIPE); |
| 3507 | } |
| 3508 | std::process::exit(141); |
| 3509 | } |
| 3510 | result => result.map_err(Into::into), |
| 3511 | } |
| 3512 | } |
| 3513 | |
| 3514 | fn exec_stream_value(event: &ExecStreamEvent) -> Result<serde_json::Value> { |
| 3515 | let mut value = serde_json::to_value(event)?; |
| 3516 | if let Some(object) = value.as_object_mut() { |
| 3517 | object.insert("schema_version".to_string(), serde_json::json!(1)); |
| 3518 | object.insert( |
| 3519 | "schema".to_string(), |
| 3520 | serde_json::json!("codewhale.exec-stream"), |
| 3521 | ); |
| 3522 | } |
| 3523 | Ok(value) |
| 3524 | } |
| 3525 | |
| 3526 | fn tool_error_receipt_category(error: &codewhale_engine::tools::spec::ToolError) -> &'static str { |
| 3527 | use codewhale_engine::tools::spec::ToolError; |
| 3528 | match error { |
| 3529 | ToolError::InvalidInput { .. } => "invalid_input", |
| 3530 | ToolError::MissingField { .. } => "missing_field", |
| 3531 | ToolError::PathEscape { .. } => "path_escape", |
| 3532 | ToolError::ExecutionFailed { .. } => "execution_failed", |
| 3533 | ToolError::Timeout { .. } => "timeout", |
| 3534 | ToolError::Cancelled { .. } => "cancelled", |
| 3535 | ToolError::NotAvailable { .. } => "not_available", |
| 3536 | ToolError::PermissionDenied { .. } => "permission_denied", |
| 3537 | } |
| 3538 | } |
| 3539 | |
| 3540 | pub fn tool_artifact_receipt(metadata: Option<&serde_json::Value>) -> Option<serde_json::Value> { |
| 3541 | let object = metadata?.as_object()?; |
| 3542 | let mut artifact = serde_json::Map::new(); |
| 3543 | for key in [ |
| 3544 | "artifact_id", |
| 3545 | "artifact_path", |
| 3546 | "artifact_relative_path", |
| 3547 | "artifact_byte_size", |
| 3548 | "spillover_path", |
| 3549 | "content_digest", |
| 3550 | "original_byte_count", |
| 3551 | "retained_head_bytes", |
| 3552 | "retained_tail_bytes", |
| 3553 | ] { |
| 3554 | if let Some(value) = object.get(key) { |
| 3555 | artifact.insert(key.to_string(), value.clone()); |
| 3556 | } |
| 3557 | } |
| 3558 | (!artifact.is_empty()).then_some(serde_json::Value::Object(artifact)) |
| 3559 | } |
| 3560 | |
| 3561 | pub fn start_binary_sha256() -> tokio::task::JoinHandle<Option<String>> { |
| 3562 | let file = std::env::current_exe().and_then(std::fs::File::open); |
| 3563 | tokio::task::spawn_blocking(move || { |
| 3564 | let _timing = codewhale_runtime::logging::PhaseTimer::start("binary_identity"); |
| 3565 | let hash = codewhale_release::installs::reader_sha256(file.ok()?).ok()?; |
| 3566 | Some(format!("sha256:{hash}")) |
| 3567 | }) |
| 3568 | } |
| 3569 | |
| 3570 | fn exec_stream_input_analysis( |
| 3571 | messages: &[Message], |
| 3572 | system: Option<&SystemPrompt>, |
| 3573 | ) -> ExecStreamInputAnalysis { |
| 3574 | let mut analysis = ExecStreamInputAnalysis { |
| 3575 | estimated_request_tokens: codewhale_engine::compaction::estimate_input_tokens_conservative( |
| 3576 | messages, system, |
| 3577 | ), |
| 3578 | estimated_message_content_tokens: codewhale_engine::compaction::estimate_tokens(messages), |
| 3579 | estimated_system_tokens: exec_stream_estimate_system_tokens(system), |
| 3580 | estimated_framing_tokens: messages.len().saturating_mul(12).saturating_add(48), |
| 3581 | ..ExecStreamInputAnalysis::default() |
| 3582 | }; |
| 3583 | |
| 3584 | for message in messages { |
| 3585 | match message.role.as_str() { |
| 3586 | "user" => analysis.user_message_count += 1, |
| 3587 | "assistant" => analysis.assistant_message_count += 1, |
| 3588 | "tool" => analysis.tool_message_count += 1, |
| 3589 | _ => {} |
| 3590 | } |
| 3591 | |
| 3592 | for block in &message.content { |
| 3593 | match block { |
| 3594 | ContentBlock::Text { text, .. } => { |
| 3595 | exec_stream_add_text_estimate( |
| 3596 | text, |
| 3597 | &mut analysis.text_chars, |
| 3598 | &mut analysis.text_estimated_tokens, |
| 3599 | ); |
| 3600 | } |
| 3601 | ContentBlock::Thinking { thinking, .. } => { |
| 3602 | exec_stream_add_text_estimate( |
| 3603 | thinking, |
| 3604 | &mut analysis.thinking_chars, |
| 3605 | &mut analysis.thinking_estimated_tokens, |
| 3606 | ); |
| 3607 | } |
| 3608 | ContentBlock::ToolUse { input, .. } | ContentBlock::ServerToolUse { input, .. } => { |
| 3609 | analysis.tool_use_count += 1; |
| 3610 | exec_stream_add_json_estimate( |
| 3611 | input, |
| 3612 | &mut analysis.tool_use_input_chars, |
| 3613 | &mut analysis.tool_use_input_estimated_tokens, |
| 3614 | ); |
| 3615 | } |
| 3616 | ContentBlock::ToolResult { |
| 3617 | content, |
| 3618 | content_blocks, |
| 3619 | .. |
| 3620 | } => { |
| 3621 | analysis.tool_result_count += 1; |
| 3622 | exec_stream_add_text_estimate( |
| 3623 | content, |
| 3624 | &mut analysis.tool_result_chars, |
| 3625 | &mut analysis.tool_result_estimated_tokens, |
| 3626 | ); |
| 3627 | if let Some(blocks) = content_blocks { |
| 3628 | exec_stream_add_json_estimate( |
| 3629 | blocks, |
| 3630 | &mut analysis.tool_result_chars, |
| 3631 | &mut analysis.tool_result_estimated_tokens, |
| 3632 | ); |
| 3633 | } |
| 3634 | } |
| 3635 | ContentBlock::ToolSearchToolResult { content, .. } |
| 3636 | | ContentBlock::CodeExecutionToolResult { content, .. } |
| 3637 | | ContentBlock::WebSearchToolResult { content, .. } |
| 3638 | | ContentBlock::WebFetchToolResult { content, .. } => { |
| 3639 | analysis.tool_result_count += 1; |
| 3640 | exec_stream_add_json_estimate( |
| 3641 | content, |
| 3642 | &mut analysis.tool_result_chars, |
| 3643 | &mut analysis.tool_result_estimated_tokens, |
| 3644 | ); |
| 3645 | } |
| 3646 | ContentBlock::WebSearchCall { .. } | ContentBlock::ServerToolCalls { .. } => { |
| 3647 | analysis.tool_use_count += 1; |
| 3648 | } |
| 3649 | ContentBlock::File { .. } | ContentBlock::ImageUrl { .. } => {} |
| 3650 | } |
| 3651 | } |
| 3652 | } |
| 3653 | |
| 3654 | analysis |
| 3655 | } |
| 3656 | |
| 3657 | fn exec_stream_add_text_estimate(text: &str, chars: &mut usize, tokens: &mut usize) { |
| 3658 | *chars = chars.saturating_add(text.chars().count()); |
| 3659 | *tokens = tokens |
| 3660 | .saturating_add(codewhale_engine::compaction::estimate_text_tokens_conservative(text)); |
| 3661 | } |
| 3662 | |
| 3663 | fn exec_stream_add_json_estimate<T: serde::Serialize>( |
| 3664 | value: &T, |
| 3665 | chars: &mut usize, |
| 3666 | tokens: &mut usize, |
| 3667 | ) { |
| 3668 | let text = serde_json::to_string(value).unwrap_or_default(); |
| 3669 | exec_stream_add_text_estimate(&text, chars, tokens); |
| 3670 | } |
| 3671 | |
| 3672 | fn exec_stream_estimate_system_tokens(system: Option<&SystemPrompt>) -> usize { |
| 3673 | match system { |
| 3674 | Some(SystemPrompt::Text(text)) => { |
| 3675 | codewhale_engine::compaction::estimate_text_tokens_conservative(text) |
| 3676 | } |
| 3677 | Some(SystemPrompt::Blocks(blocks)) => blocks |
| 3678 | .iter() |
| 3679 | .map(|block| { |
| 3680 | codewhale_engine::compaction::estimate_text_tokens_conservative(&block.text) |
| 3681 | }) |
| 3682 | .sum(), |
| 3683 | None => 0, |
| 3684 | } |
| 3685 | } |
| 3686 | |
| 3687 | fn exec_saved_session_line(session_id: &str) -> String { |
| 3688 | format!("session: {}", truncate_id(session_id)) |
| 3689 | } |
| 3690 | |
| 3691 | fn exec_resumed_session_line(session_id: &str) -> String { |
| 3692 | format!("resumed session: {}", truncate_id(session_id)) |
| 3693 | } |
| 3694 | |
| 3695 | pub fn exec_stream_session_ref(session_id: &str) -> String { |
| 3696 | codewhale_util::utils::redacted_identifier_for_log(session_id) |
| 3697 | } |
| 3698 | |
| 3699 | /// Resume hint for the terminal `metadata` receipt. `metadata` carries only |
| 3700 | /// the session fingerprint, so the hint names the `session_capture` field |
| 3701 | /// that holds the recoverable id instead of pretending to redact one. |
| 3702 | fn exec_stream_resume_hint(session_id: &str) -> String { |
| 3703 | if session_id.trim().is_empty() { |
| 3704 | String::new() |
| 3705 | } else { |
| 3706 | "codewhale exec --resume <session_capture.saved_session_id>".to_string() |
| 3707 | } |
| 3708 | } |
| 3709 | |
| 3710 | /// The final visible assistant reply for the terminal receipt: the text |
| 3711 | /// blocks of the last assistant-like message after the current user prompt. |
| 3712 | /// Tool results also use the user role, so they must not start a new turn. |
| 3713 | /// A resumed session can be synchronized before its new prompt is accepted; |
| 3714 | /// without current output its old answer must never become a new deliverable. |
| 3715 | fn exec_stream_final_answer_text( |
| 3716 | messages: &[Message], |
| 3717 | current_turn_has_output: bool, |
| 3718 | ) -> Option<String> { |
| 3719 | if !current_turn_has_output { |
| 3720 | return None; |
| 3721 | } |
| 3722 | let turn_start = messages.iter().rposition(|message| { |
| 3723 | message.role == Role::User |
| 3724 | && !codewhale_models::turn_classify::is_runtime_owned_user_message(message) |
| 3725 | && !message |
| 3726 | .content |
| 3727 | .iter() |
| 3728 | .any(|block| matches!(block, ContentBlock::ToolResult { .. })) |
| 3729 | })?; |
| 3730 | let text = messages |
| 3731 | .iter() |
| 3732 | .skip(turn_start + 1) |
| 3733 | .rev() |
| 3734 | .find(|message| message.role.is_assistant_like())? |
| 3735 | .content |
| 3736 | .iter() |
| 3737 | .filter_map(|block| match block { |
| 3738 | ContentBlock::Text { text, .. } => Some(text.as_str()), |
| 3739 | _ => None, |
| 3740 | }) |
| 3741 | .collect::<Vec<_>>() |
| 3742 | .join("\n") |
| 3743 | .trim() |
| 3744 | .to_string(); |
| 3745 | (!text.is_empty()).then_some(text) |
| 3746 | } |
| 3747 | |
| 3748 | async fn load_exec_route_binding_key( |
| 3749 | manager: Result<Arc<SessionManager>>, |
| 3750 | create: bool, |
| 3751 | ) -> Option<[u8; 32]> { |
| 3752 | let result = async { |
| 3753 | let sessions_dir = tokio::fs::canonicalize(manager?.sessions_dir()).await?; |
| 3754 | codewhale_runtime::runtime_control::owner_work(move || { |
| 3755 | SessionManager::exec_route_binding_key(&sessions_dir, create) |
| 3756 | }) |
| 3757 | .await |
| 3758 | } |
| 3759 | .await; |
| 3760 | match result { |
| 3761 | Ok(key) => Some(key), |
| 3762 | Err(error) => { |
| 3763 | tracing::debug!(%error, "exec route binding key unavailable"); |
| 3764 | None |
| 3765 | } |
| 3766 | } |
| 3767 | } |
| 3768 | |
| 3769 | fn required_exec_resume_binding( |
| 3770 | saved: Option<&session_manager::SavedSession>, |
| 3771 | explicitly_reselected_route: bool, |
| 3772 | ) -> Option<&ExecRouteBinding> { |
| 3773 | saved |
| 3774 | .filter(|_| !explicitly_reselected_route) |
| 3775 | .and_then(|saved| saved.metadata.exec_route_binding.as_ref()) |
| 3776 | } |
| 3777 | |
| 3778 | const EXEC_RESUME_RESELECT: &str = "The saved provider binding changed or could not be verified. Re-run with an explicit --provider or --model to confirm the current route."; |
| 3779 | |
| 3780 | fn check_exec_resume_endpoint( |
| 3781 | required: Option<&ExecRouteBinding>, |
| 3782 | key: Option<&[u8; 32]>, |
| 3783 | base_url: &str, |
| 3784 | ) -> Result<()> { |
| 3785 | if let Some(required) = required { |
| 3786 | anyhow::ensure!( |
| 3787 | required.authority.is_some() |
| 3788 | && key.is_some_and(|key| { |
| 3789 | required.endpoint.as_deref() |
| 3790 | == Some(ExecRouteBinding::endpoint_tag(key, base_url).as_str()) |
| 3791 | }), |
| 3792 | "{EXEC_RESUME_RESELECT}" |
| 3793 | ); |
| 3794 | } |
| 3795 | Ok(()) |
| 3796 | } |
| 3797 | |
| 3798 | fn check_exec_resume_authority( |
| 3799 | required: Option<&ExecRouteBinding>, |
| 3800 | current: &ExecRouteBinding, |
| 3801 | ) -> Result<()> { |
| 3802 | anyhow::ensure!( |
| 3803 | required.is_none_or(|required| required.matches(current)), |
| 3804 | "{EXEC_RESUME_RESELECT}" |
| 3805 | ); |
| 3806 | Ok(()) |
| 3807 | } |
| 3808 | |
| 3809 | #[derive(Clone, Copy)] |
| 3810 | struct PersistedProviderRoute<'a> { |
| 3811 | kind: &'a str, |
| 3812 | id: Option<&'a str>, |
| 3813 | binding: Option<&'a ExecRouteBinding>, |
| 3814 | } |
| 3815 | |
| 3816 | fn persist_exec_session( |
| 3817 | messages: &[Message], |
| 3818 | model: &str, |
| 3819 | provider_route: PersistedProviderRoute<'_>, |
| 3820 | workspace: &Path, |
| 3821 | system_prompt: &Option<SystemPrompt>, |
| 3822 | session_id: Option<&str>, |
| 3823 | total_tokens: u64, |
| 3824 | turn_failure: Option<&str>, |
| 3825 | manager: &SessionManager, |
| 3826 | provider_request_receipts: &[serde_json::Value], |
| 3827 | checkpoint: Option<&codewhale_engine::core::events::SessionCheckpointRequest>, |
| 3828 | source: &session_manager::SessionWriteReceipt, |
| 3829 | owner: &codewhale_engine::core::ops::SessionSnapshotSource, |
| 3830 | agent_preset: Option<&str>, |
| 3831 | ) -> Result<session_manager::SessionPublication> { |
| 3832 | let captured = source.capture(session_manager::SessionWriteOwner::Engine(owner.clone()))?; |
| 3833 | if checkpoint.is_some() { |
| 3834 | captured.require_checkpoint_acknowledgement(); |
| 3835 | } |
| 3836 | let native_accounting = session_id |
| 3837 | .map(|id| manager.has_native_usage_records(id)) |
| 3838 | .transpose()? |
| 3839 | .unwrap_or(false) |
| 3840 | || provider_request_receipts |
| 3841 | .iter() |
| 3842 | .any(|receipt| receipt["source_accounting"].as_bool() == Some(true)); |
| 3843 | let mut saved = if let Some(id) = session_id.filter(|id| !id.trim().is_empty()) { |
| 3844 | match manager.load_session_snapshot(id) { |
| 3845 | Ok(existing) => { |
| 3846 | let tokens = if native_accounting { |
| 3847 | existing.metadata.total_tokens |
| 3848 | } else { |
| 3849 | total_tokens |
| 3850 | }; |
| 3851 | session_manager::update_session(existing, messages, tokens, system_prompt.as_ref()) |
| 3852 | } |
| 3853 | Err(err) if err.kind() == std::io::ErrorKind::NotFound => { |
| 3854 | session_manager::create_saved_session_with_id_and_mode( |
| 3855 | id.to_string(), |
| 3856 | messages, |
| 3857 | model, |
| 3858 | workspace, |
| 3859 | if native_accounting { 0 } else { total_tokens }, |
| 3860 | system_prompt.as_ref(), |
| 3861 | Some("exec"), |
| 3862 | ) |
| 3863 | } |
| 3864 | Err(err) => return Err(err).context("could not load existing exec session"), |
| 3865 | } |
| 3866 | } else { |
| 3867 | session_manager::create_saved_session_with_mode( |
| 3868 | messages, |
| 3869 | model, |
| 3870 | workspace, |
| 3871 | total_tokens, |
| 3872 | system_prompt.as_ref(), |
| 3873 | Some("exec"), |
| 3874 | ) |
| 3875 | }; |
| 3876 | if saved.agent_preset.is_none() { |
| 3877 | saved.agent_preset = agent_preset.map(str::to_string); |
| 3878 | } |
| 3879 | saved.write_receipt = Some(captured); |
| 3880 | stamp_exec_session_metadata( |
| 3881 | &mut saved, |
| 3882 | model, |
| 3883 | provider_route.kind, |
| 3884 | provider_route.id, |
| 3885 | workspace, |
| 3886 | ); |
| 3887 | if let Some(binding) = provider_route.binding { |
| 3888 | saved.metadata.exec_route_binding = Some(binding.clone()); |
| 3889 | } |
| 3890 | if let Some(error) = turn_failure { |
| 3891 | session_manager::push_turn_outcome( |
| 3892 | &mut saved.turn_outcomes, |
| 3893 | session_manager::SavedTurnOutcome::failed(error, messages.len()), |
| 3894 | ); |
| 3895 | } |
| 3896 | if !provider_request_receipts.is_empty() { |
| 3897 | saved.ensure_journal(); |
| 3898 | if let Some(journal) = saved.journal.as_mut() { |
| 3899 | let leaf = journal.leaf_id.clone(); |
| 3900 | for receipt in provider_request_receipts { |
| 3901 | let label = if receipt |
| 3902 | .get("wire_observations") |
| 3903 | .and_then(serde_json::Value::as_array) |
| 3904 | .is_some_and(|values| { |
| 3905 | values |
| 3906 | .iter() |
| 3907 | .any(|value| value.get("image_projection").is_some()) |
| 3908 | }) { |
| 3909 | "Provider request image projection" |
| 3910 | } else { |
| 3911 | "Provider request receipt" |
| 3912 | }; |
| 3913 | journal.append(codewhale_runtime::session_tree::SessionEntryKind::System { |
| 3914 | content: format!("{label}: {receipt}"), |
| 3915 | }); |
| 3916 | journal.leaf_id.clone_from(&leaf); |
| 3917 | } |
| 3918 | } |
| 3919 | } |
| 3920 | for receipt in provider_request_receipts.iter().filter(|receipt| { |
| 3921 | receipt["primary"].as_bool() == Some(true) |
| 3922 | && receipt["source_accounting"].as_bool() != Some(true) |
| 3923 | }) { |
| 3924 | let Some(source) = receipt["source_id"].as_str() else { |
| 3925 | continue; |
| 3926 | }; |
| 3927 | let coverage = receipt.get("coverage").cloned().and_then(|value| { |
| 3928 | serde_json::from_value::<codewhale_engine::llm_client::ProviderUsageCoverage>(value) |
| 3929 | .ok() |
| 3930 | }); |
| 3931 | let missing_coverage = matches!( |
| 3932 | coverage, |
| 3933 | Some( |
| 3934 | codewhale_engine::llm_client::ProviderUsageCoverage::Missing |
| 3935 | | codewhale_engine::llm_client::ProviderUsageCoverage::Incomplete |
| 3936 | ) |
| 3937 | ); |
| 3938 | if missing_coverage |
| 3939 | && let Some(route) = receipt.get("route").cloned().and_then(|value| { |
| 3940 | serde_json::from_value::<codewhale_engine::cost_status::EffectiveRouteEnvelope>( |
| 3941 | value, |
| 3942 | ) |
| 3943 | .ok() |
| 3944 | }) |
| 3945 | { |
| 3946 | let reason = |
| 3947 | if receipt["outcome"] == "completed" || receipt["outcome"] == "review_response" { |
| 3948 | codewhale_engine::cost_status::RuntimeUsageMissingReason::SuccessWithoutUsage |
| 3949 | } else { |
| 3950 | codewhale_engine::cost_status::RuntimeUsageMissingReason::RequestOutcomeUnknown |
| 3951 | }; |
| 3952 | let drop_record = codewhale_engine::cost_status::RuntimeUsageDropRecord { |
| 3953 | source_id: source.to_string(), |
| 3954 | route, |
| 3955 | reason, |
| 3956 | }; |
| 3957 | if let Err(error) = saved |
| 3958 | .metadata |
| 3959 | .cost |
| 3960 | .project_usage_record(&drop_record.as_usage_record()) |
| 3961 | { |
| 3962 | tracing::warn!(%error, source_id = %source, "agent missing usage projection skipped"); |
| 3963 | } |
| 3964 | } else if receipt["usage_reported"].as_bool() == Some(true) { |
| 3965 | saved.metadata.cost.usage_source_fingerprints.insert( |
| 3966 | codewhale_engine::cost_status::usage_source_fingerprint(source), |
| 3967 | ); |
| 3968 | } |
| 3969 | } |
| 3970 | saved.make_storage_compatible(); |
| 3971 | if let Some(checkpoint) = checkpoint { |
| 3972 | checkpoint |
| 3973 | .validate_prefix( |
| 3974 | &saved.metadata.id, |
| 3975 | &saved.metadata.workspace, |
| 3976 | &saved.messages, |
| 3977 | ) |
| 3978 | .map_err(anyhow::Error::msg)?; |
| 3979 | } |
| 3980 | manager |
| 3981 | .publish_session(&saved) |
| 3982 | .context("could not save exec session") |
| 3983 | } |
| 3984 | |
| 3985 | pub fn stamp_exec_session_metadata( |
| 3986 | saved: &mut session_manager::SavedSession, |
| 3987 | model: &str, |
| 3988 | model_provider_kind: &str, |
| 3989 | model_provider_id: Option<&str>, |
| 3990 | workspace: &Path, |
| 3991 | ) { |
| 3992 | saved.metadata.model = model.to_string(); |
| 3993 | saved |
| 3994 | .metadata |
| 3995 | .set_model_provider_route(model_provider_kind, model_provider_id); |
| 3996 | saved.metadata.workspace = workspace.to_path_buf(); |
| 3997 | saved.metadata.mode = Some("exec".to_string()); |
| 3998 | } |
| 3999 | |
| 4000 | #[derive(serde::Serialize)] |
| 4001 | struct ExecToolEntry { |
| 4002 | name: String, |
| 4003 | success: bool, |
| 4004 | output: String, |
| 4005 | } |
| 4006 | |
| 4007 | #[derive(serde::Serialize)] |
| 4008 | struct ExecOutcome { |
| 4009 | kind: String, |
| 4010 | outcome: String, |
| 4011 | tool_name: String, |
| 4012 | reason: String, |
| 4013 | } |
| 4014 | |
| 4015 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize)] |
| 4016 | #[serde(rename_all = "snake_case")] |
| 4017 | pub enum ExecUsageStatus { |
| 4018 | Complete, |
| 4019 | Partial, |
| 4020 | #[default] |
| 4021 | Unreported, |
| 4022 | } |
| 4023 | |
| 4024 | #[derive(serde::Serialize)] |
| 4025 | struct ExecAgentReceipt { |
| 4026 | id: String, |
| 4027 | model: Option<String>, |
| 4028 | usage: Option<codewhale_engine::tools::subagent::AgentRunUsage>, |
| 4029 | } |
| 4030 | |
| 4031 | #[derive(serde::Serialize, Default)] |
| 4032 | pub struct ExecSummary { |
| 4033 | mode: String, |
| 4034 | provider: String, |
| 4035 | model: String, |
| 4036 | prompt: String, |
| 4037 | pub output: String, |
| 4038 | tools: Vec<ExecToolEntry>, |
| 4039 | outcomes: Vec<ExecOutcome>, |
| 4040 | status: Option<String>, |
| 4041 | termination_reason: Option<String>, |
| 4042 | stop_reason: Option<codewhale_engine::runtime_threads::RuntimeTurnStopReason>, |
| 4043 | error_category: Option<String>, |
| 4044 | error: Option<String>, |
| 4045 | #[serde(skip_serializing_if = "Vec::is_empty")] |
| 4046 | released_services: Vec<codewhale_engine::tools::shell::PersistentServiceReceipt>, |
| 4047 | success: bool, |
| 4048 | pub usage: Option<codewhale_models::Usage>, |
| 4049 | pub usage_status: ExecUsageStatus, |
| 4050 | agents: Vec<ExecAgentReceipt>, |
| 4051 | #[serde(skip_serializing_if = "Option::is_none")] |
| 4052 | pub agent_id: Option<String>, |
| 4053 | #[serde(skip_serializing_if = "Option::is_none")] |
| 4054 | pub thread_id: Option<String>, |
| 4055 | #[serde(skip_serializing_if = "Option::is_none")] |
| 4056 | pub turn_id: Option<String>, |
| 4057 | #[serde(skip_serializing_if = "Option::is_none")] |
| 4058 | structured_output: Option<serde_json::Value>, |
| 4059 | } |
| 4060 | |
| 4061 | impl ExecSummary { |
| 4062 | pub fn new(mode: &str, provider: String, model: String, prompt: String) -> Self { |
| 4063 | Self { |
| 4064 | mode: mode.to_string(), |
| 4065 | provider, |
| 4066 | model, |
| 4067 | prompt, |
| 4068 | ..Self::default() |
| 4069 | } |
| 4070 | } |
| 4071 | |
| 4072 | pub fn record_turn_outcome( |
| 4073 | &mut self, |
| 4074 | status: codewhale_engine::core::events::TurnOutcomeStatus, |
| 4075 | error: Option<String>, |
| 4076 | ) { |
| 4077 | let mut category = None; |
| 4078 | self.apply_turn_complete_error_summary(status, error, false, &mut category); |
| 4079 | self.termination_reason = Some( |
| 4080 | codewhale_engine::core::termination::classify_turn_termination( |
| 4081 | status, category, false, false, |
| 4082 | ) |
| 4083 | .as_str() |
| 4084 | .to_string(), |
| 4085 | ); |
| 4086 | } |
| 4087 | |
| 4088 | pub fn settle( |
| 4089 | &mut self, |
| 4090 | usage: Option<codewhale_models::Usage>, |
| 4091 | routed_usage_dropped_records: u64, |
| 4092 | coverage_gap: bool, |
| 4093 | ) { |
| 4094 | self.success = self.error.is_none() && self.status.as_deref() == Some("completed"); |
| 4095 | self.usage = |
| 4096 | usage.filter(codewhale_engine::core::engine::turn_loop::usage_has_reported_data); |
| 4097 | let gap = routed_usage_dropped_records > 0 |
| 4098 | || coverage_gap |
| 4099 | || self.agents.iter().any(|agent| agent.usage.is_none()); |
| 4100 | self.usage_status = if self.usage.is_some() && !gap { |
| 4101 | ExecUsageStatus::Complete |
| 4102 | } else if self.usage.is_some() || self.agents.iter().any(|agent| agent.usage.is_some()) { |
| 4103 | ExecUsageStatus::Partial |
| 4104 | } else { |
| 4105 | ExecUsageStatus::Unreported |
| 4106 | }; |
| 4107 | } |
| 4108 | |
| 4109 | fn record_agent_event(&mut self, event: &codewhale_engine::core::events::Event) { |
| 4110 | match event { |
| 4111 | codewhale_engine::core::events::Event::AgentSpawned { id, model, .. } => { |
| 4112 | let agent = self.agent_entry(id); |
| 4113 | agent.model = Some(model.clone()); |
| 4114 | agent.usage = None; |
| 4115 | } |
| 4116 | codewhale_engine::core::events::Event::AgentComplete { id, usage, .. } => { |
| 4117 | self.agent_entry(id).usage = usage |
| 4118 | .clone() |
| 4119 | .filter(codewhale_engine::tools::subagent::AgentRunUsage::has_measured_values); |
| 4120 | } |
| 4121 | _ => {} |
| 4122 | } |
| 4123 | } |
| 4124 | |
| 4125 | fn agent_entry(&mut self, id: &str) -> &mut ExecAgentReceipt { |
| 4126 | let index = match self.agents.iter().position(|agent| agent.id == id) { |
| 4127 | Some(index) => index, |
| 4128 | None => { |
| 4129 | self.agents.push(ExecAgentReceipt { |
| 4130 | id: id.to_string(), |
| 4131 | model: None, |
| 4132 | usage: None, |
| 4133 | }); |
| 4134 | self.agents.len() - 1 |
| 4135 | } |
| 4136 | }; |
| 4137 | &mut self.agents[index] |
| 4138 | } |
| 4139 | |
| 4140 | fn apply_turn_complete_error_summary( |
| 4141 | &mut self, |
| 4142 | terminal_status: codewhale_engine::core::events::TurnOutcomeStatus, |
| 4143 | terminal_error: Option<String>, |
| 4144 | sandbox_denied: bool, |
| 4145 | last_error_category: &mut Option<codewhale_error_taxonomy::ErrorCategory>, |
| 4146 | ) { |
| 4147 | self.status = Some(format!("{terminal_status:?}").to_lowercase()); |
| 4148 | if terminal_error.is_some() { |
| 4149 | self.error = terminal_error; |
| 4150 | } |
| 4151 | let synthesized_sandbox_denial = if sandbox_denied |
| 4152 | && self.error.is_none() |
| 4153 | && matches!( |
| 4154 | terminal_status, |
| 4155 | codewhale_engine::core::events::TurnOutcomeStatus::Failed |
| 4156 | ) { |
| 4157 | self.error = Some( |
| 4158 | "exec turn failed after sandbox denial; explicit sandbox elevation was not authorized" |
| 4159 | .to_string(), |
| 4160 | ); |
| 4161 | true |
| 4162 | } else { |
| 4163 | false |
| 4164 | }; |
| 4165 | if last_error_category.is_none() && !synthesized_sandbox_denial { |
| 4166 | *last_error_category = self |
| 4167 | .error |
| 4168 | .as_deref() |
| 4169 | .map(codewhale_error_taxonomy::classify_error_message); |
| 4170 | self.error_category = last_error_category.map(|category| category.to_string()); |
| 4171 | } |
| 4172 | } |
| 4173 | } |
| 4174 | |
| 4175 | pub fn validate_exec_tool_authority_resume( |
| 4176 | tool_authority_json: Option<&str>, |
| 4177 | resuming: bool, |
| 4178 | ) -> Result<()> { |
| 4179 | if tool_authority_json.is_some() && resuming { |
| 4180 | bail!( |
| 4181 | "Fleet tool authority cannot be combined with exec --resume, --session-id, or --continue" |
| 4182 | ); |
| 4183 | } |
| 4184 | Ok(()) |
| 4185 | } |
| 4186 | |
| 4187 | fn exec_network_policy( |
| 4188 | config: &Config, |
| 4189 | outer_network_access: Option<bool>, |
| 4190 | ) -> Option<codewhale_net::network_policy::NetworkPolicyDecider> { |
| 4191 | // Fleet caps are an outer authority boundary: user configuration may |
| 4192 | // narrow them further, but it may never widen an explicit network denial. |
| 4193 | if outer_network_access == Some(false) { |
| 4194 | // A Fleet denial is an outer authority the user's document may never |
| 4195 | // widen, so mark the decider authoritative: a mid-session re-read of |
| 4196 | // that document folds onto it instead of replacing it. |
| 4197 | return Some( |
| 4198 | codewhale_net::network_policy::NetworkPolicyDecider::new( |
| 4199 | codewhale_net::network_policy::NetworkPolicy { |
| 4200 | default: codewhale_net::network_policy::DecisionToml::Deny, |
| 4201 | ..codewhale_net::network_policy::NetworkPolicy::default() |
| 4202 | }, |
| 4203 | None, |
| 4204 | ) |
| 4205 | .with_authoritative(), |
| 4206 | ); |
| 4207 | } |
| 4208 | config.network.clone().map(|toml_cfg| { |
| 4209 | codewhale_net::network_policy::NetworkPolicyDecider::with_default_audit( |
| 4210 | codewhale_net::network_policy::NetworkPolicy::from(toml_cfg), |
| 4211 | ) |
| 4212 | }) |
| 4213 | } |
| 4214 | |
| 4215 | fn apply_fleet_engine_feature_caps( |
| 4216 | features: &mut codewhale_runtime::features::Features, |
| 4217 | fleet_authority_active: bool, |
| 4218 | outer_network_access: Option<bool>, |
| 4219 | shell_authority: codewhale_engine::tools::spec::ToolShellAuthority, |
| 4220 | ) { |
| 4221 | if fleet_authority_active { |
| 4222 | features.disable(codewhale_runtime::features::Feature::Subagents); |
| 4223 | features.disable(codewhale_runtime::features::Feature::Mcp); |
| 4224 | features.disable(codewhale_runtime::features::Feature::PluginCreator); |
| 4225 | if shell_authority != codewhale_engine::tools::spec::ToolShellAuthority::ReadOnly { |
| 4226 | features.disable(codewhale_runtime::features::Feature::ShellTool); |
| 4227 | } |
| 4228 | } |
| 4229 | if outer_network_access == Some(false) { |
| 4230 | features.disable(codewhale_runtime::features::Feature::WebSearch); |
| 4231 | } |
| 4232 | } |
| 4233 | |
| 4234 | #[cfg(any(test, feature = "test-support"))] |
| 4235 | pub fn custom_exec_config(active: &str) -> Config { |
| 4236 | let mut custom = std::collections::HashMap::new(); |
| 4237 | for (name, base_url, model) in [ |
| 4238 | ( |
| 4239 | "custom-a", |
| 4240 | "http://127.0.0.1:18181/v1", |
| 4241 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL, |
| 4242 | ), |
| 4243 | ("custom-b", "http://127.0.0.1:18182/v1", "model-b"), |
| 4244 | ] { |
| 4245 | custom.insert( |
| 4246 | name.to_string(), |
| 4247 | codewhale_runtime::config::ProviderConfig { |
| 4248 | kind: Some("openai-compatible".to_string()), |
| 4249 | base_url: Some(base_url.to_string()), |
| 4250 | model: Some(model.to_string()), |
| 4251 | api_key: Some("local-test-key".to_string()), |
| 4252 | ..Default::default() |
| 4253 | }, |
| 4254 | ); |
| 4255 | } |
| 4256 | { |
| 4257 | let __cw_config_init_1_0 = Some(active.to_string()); |
| 4258 | let __cw_config_init_1_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 4259 | custom, |
| 4260 | ..Default::default() |
| 4261 | }); |
| 4262 | let mut __cw_config_init_1_value: Config = Default::default(); |
| 4263 | __cw_config_init_1_value.provider = __cw_config_init_1_0; |
| 4264 | __cw_config_init_1_value.providers = __cw_config_init_1_1; |
| 4265 | __cw_config_init_1_value |
| 4266 | } |
| 4267 | } |
| 4268 | |
| 4269 | const TOOL_TEXT_LIMIT: usize = 300; |
| 4270 | |
| 4271 | fn summarize_string_value(text: &str, max_len: usize, count_only: bool) -> String { |
| 4272 | let trimmed = text.trim(); |
| 4273 | let len = trimmed.chars().count(); |
| 4274 | if count_only || len > max_len { |
| 4275 | return format!("<{len} chars>"); |
| 4276 | } |
| 4277 | codewhale_tui_kit::ui_text::truncate_line_to_width(trimmed, max_len) |
| 4278 | } |
| 4279 | |
| 4280 | fn summarize_inline_value(value: &Value, max_len: usize, count_only: bool) -> String { |
| 4281 | match value { |
| 4282 | Value::String(s) => summarize_string_value(s, max_len, count_only), |
| 4283 | Value::Array(items) => format!("<{} items>", items.len()), |
| 4284 | Value::Object(map) => format!("<{} keys>", map.len()), |
| 4285 | Value::Bool(b) => b.to_string(), |
| 4286 | Value::Number(num) => num.to_string(), |
| 4287 | Value::Null => "null".to_string(), |
| 4288 | } |
| 4289 | } |
| 4290 | |
| 4291 | fn is_noisy_tool_arg_key(key: &str) -> bool { |
| 4292 | matches!( |
| 4293 | key, |
| 4294 | "limit" |
| 4295 | | "max_count" |
| 4296 | | "max_output_tokens" |
| 4297 | | "offset" |
| 4298 | | "page" |
| 4299 | | "page_size" |
| 4300 | | "per_page" |
| 4301 | | "response_length" |
| 4302 | | "timeout_ms" |
| 4303 | | "yield_time_ms" |
| 4304 | ) |
| 4305 | } |
| 4306 | |
| 4307 | #[must_use] |
| 4308 | pub fn summarize_tool_args(input: &Value) -> Option<String> { |
| 4309 | let obj = input.as_object()?; |
| 4310 | if obj.is_empty() { |
| 4311 | return None; |
| 4312 | } |
| 4313 | |
| 4314 | let mut parts = Vec::new(); |
| 4315 | |
| 4316 | if let Some(value) = obj.get("path") { |
| 4317 | parts.push(format!( |
| 4318 | "path: {}", |
| 4319 | summarize_inline_value(value, 80, false) |
| 4320 | )); |
| 4321 | } |
| 4322 | if let Some(value) = obj.get("command") { |
| 4323 | parts.push(format!( |
| 4324 | "command: {}", |
| 4325 | summarize_inline_value(value, 80, false) |
| 4326 | )); |
| 4327 | } |
| 4328 | if let Some(value) = obj.get("query") { |
| 4329 | parts.push(format!( |
| 4330 | "query: {}", |
| 4331 | summarize_inline_value(value, 80, false) |
| 4332 | )); |
| 4333 | } |
| 4334 | if let Some(value) = obj.get("prompt") { |
| 4335 | parts.push(format!( |
| 4336 | "prompt: {}", |
| 4337 | summarize_inline_value(value, 80, false) |
| 4338 | )); |
| 4339 | } |
| 4340 | if let Some(value) = obj.get("text") { |
| 4341 | parts.push(format!( |
| 4342 | "text: {}", |
| 4343 | summarize_inline_value(value, 80, false) |
| 4344 | )); |
| 4345 | } |
| 4346 | if let Some(value) = obj.get("pattern") { |
| 4347 | parts.push(format!( |
| 4348 | "pattern: {}", |
| 4349 | summarize_inline_value(value, 80, false) |
| 4350 | )); |
| 4351 | } |
| 4352 | if let Some(value) = obj.get("model") { |
| 4353 | parts.push(format!( |
| 4354 | "model: {}", |
| 4355 | summarize_inline_value(value, 40, false) |
| 4356 | )); |
| 4357 | } |
| 4358 | if let Some(value) = obj.get("profile") { |
| 4359 | parts.push(format!( |
| 4360 | "profile: {}", |
| 4361 | summarize_inline_value(value, 40, false) |
| 4362 | )); |
| 4363 | } |
| 4364 | if let Some(value) = obj.get("level") { |
| 4365 | parts.push(format!( |
| 4366 | "level: {}", |
| 4367 | summarize_inline_value(value, 40, false) |
| 4368 | )); |
| 4369 | } |
| 4370 | if let Some(value) = obj.get("file_id") { |
| 4371 | parts.push(format!( |
| 4372 | "file_id: {}", |
| 4373 | summarize_inline_value(value, 40, false) |
| 4374 | )); |
| 4375 | } |
| 4376 | if let Some(value) = obj.get("task_id") { |
| 4377 | parts.push(format!( |
| 4378 | "task_id: {}", |
| 4379 | summarize_inline_value(value, 40, false) |
| 4380 | )); |
| 4381 | } |
| 4382 | if let Some(value) = obj.get("voice_id") { |
| 4383 | parts.push(format!( |
| 4384 | "voice_id: {}", |
| 4385 | summarize_inline_value(value, 40, false) |
| 4386 | )); |
| 4387 | } |
| 4388 | if let Some(value) = obj.get("content") { |
| 4389 | parts.push(format!( |
| 4390 | "content: {}", |
| 4391 | summarize_inline_value(value, 0, true) |
| 4392 | )); |
| 4393 | } |
| 4394 | |
| 4395 | if parts.is_empty() |
| 4396 | && let Some((key, value)) = obj |
| 4397 | .iter() |
| 4398 | .find(|(key, _)| !is_noisy_tool_arg_key(key.as_str())) |
| 4399 | { |
| 4400 | return Some(format!( |
| 4401 | "{}: {}", |
| 4402 | key, |
| 4403 | summarize_inline_value(value, 80, false) |
| 4404 | )); |
| 4405 | } |
| 4406 | |
| 4407 | if parts.is_empty() { |
| 4408 | None |
| 4409 | } else { |
| 4410 | Some(parts.join(", ")) |
| 4411 | } |
| 4412 | } |
| 4413 | |
| 4414 | #[must_use] |
| 4415 | pub fn summarize_tool_output(output: &str) -> String { |
| 4416 | if let Ok(json) = serde_json::from_str::<Value>(output) { |
| 4417 | if let Some(obj) = json.as_object() { |
| 4418 | if let Some(error) = obj.get("error").or(obj.get("status_msg")) { |
| 4419 | return format!("Error: {}", summarize_inline_value(error, 120, false)); |
| 4420 | } |
| 4421 | |
| 4422 | let mut parts = Vec::new(); |
| 4423 | |
| 4424 | if let Some(status) = obj.get("status").and_then(|v| v.as_str()) { |
| 4425 | parts.push(format!("status: {status}")); |
| 4426 | } |
| 4427 | if let Some(message) = obj.get("message").and_then(|v| v.as_str()) { |
| 4428 | parts.push(codewhale_tui_kit::ui_text::truncate_line_to_width( |
| 4429 | message, |
| 4430 | TOOL_TEXT_LIMIT, |
| 4431 | )); |
| 4432 | } |
| 4433 | if let Some(task_id) = obj.get("task_id").and_then(|v| v.as_str()) { |
| 4434 | parts.push(format!("task_id: {task_id}")); |
| 4435 | } |
| 4436 | if let Some(file_id) = obj.get("file_id").and_then(|v| v.as_str()) { |
| 4437 | parts.push(format!("file_id: {file_id}")); |
| 4438 | } |
| 4439 | if let Some(url) = obj |
| 4440 | .get("file_url") |
| 4441 | .or_else(|| obj.get("url")) |
| 4442 | .and_then(|v| v.as_str()) |
| 4443 | { |
| 4444 | parts.push(format!( |
| 4445 | "url: {}", |
| 4446 | codewhale_tui_kit::ui_text::truncate_line_to_width(url, 120) |
| 4447 | )); |
| 4448 | } |
| 4449 | if let Some(data) = obj.get("data") { |
| 4450 | parts.push(format!("data: {}", summarize_inline_value(data, 80, true))); |
| 4451 | } |
| 4452 | |
| 4453 | if !parts.is_empty() { |
| 4454 | return parts.join(" | "); |
| 4455 | } |
| 4456 | |
| 4457 | if let Some(content) = obj |
| 4458 | .get("content") |
| 4459 | .or(obj.get("result")) |
| 4460 | .or(obj.get("output")) |
| 4461 | { |
| 4462 | return summarize_inline_value(content, TOOL_TEXT_LIMIT, false); |
| 4463 | } |
| 4464 | } |
| 4465 | |
| 4466 | return summarize_inline_value(&json, TOOL_TEXT_LIMIT, true); |
| 4467 | } |
| 4468 | |
| 4469 | codewhale_tui_kit::ui_text::truncate_line_to_width(output, TOOL_TEXT_LIMIT) |
| 4470 | } |
| 4471 | |
| 4472 | #[cfg(test)] |
| 4473 | mod route_tests { |
| 4474 | use super::*; |
| 4475 | |
| 4476 | #[test] |
| 4477 | fn exec_resume_checks_saved_endpoint_and_credential_after_reopen() -> Result<()> { |
| 4478 | let _env = codewhale_engine::test_support::lock_test_env(); |
| 4479 | let _override_key = |
| 4480 | codewhale_engine::test_support::EnvVarGuard::remove(codewhale_config::CLI_API_KEY_ENV); |
| 4481 | let temporary = tempfile::tempdir()?; |
| 4482 | let store = temporary.path().join("sessions"); |
| 4483 | let binding = |key, base_url, api_key, wire: &str| -> Result<ExecRouteBinding> { |
| 4484 | let profile = if wire == "responses" { |
| 4485 | "responses_profile = \"standard\"" |
| 4486 | } else { |
| 4487 | "" |
| 4488 | }; |
| 4489 | let config: Config = toml::from_str(&format!( |
| 4490 | r#" |
| 4491 | provider = "resume-fixture" |
| 4492 | [providers.resume-fixture] |
| 4493 | kind = "openai-compatible" |
| 4494 | base_url = "{base_url}" |
| 4495 | model = "fixture-model" |
| 4496 | api_key = "{api_key}" |
| 4497 | wire = "{wire}" |
| 4498 | {profile} |
| 4499 | "# |
| 4500 | ))?; |
| 4501 | codewhale_engine::client::CodewhaleClient::new(&config)? |
| 4502 | .exec_route_binding(key, &config) |
| 4503 | }; |
| 4504 | const ORIGINAL: &str = "https://one.example.test/v1"; |
| 4505 | const REBOUND: &str = "https://two.example.test/v1"; |
| 4506 | const ORIGINAL_KEY: &str = "fixture-account-one"; |
| 4507 | const REBOUND_KEY: &str = "fixture-account-two"; |
| 4508 | let manager = SessionManager::new(store.clone())?; |
| 4509 | let key = |
| 4510 | SessionManager::exec_route_binding_key(&manager.sessions_dir().canonicalize()?, true)?; |
| 4511 | let current = binding(&key, ORIGINAL, ORIGINAL_KEY, "chat")?; |
| 4512 | let mut saved = session_manager::create_saved_session_with_mode( |
| 4513 | &[], |
| 4514 | "fixture-model", |
| 4515 | temporary.path(), |
| 4516 | 0, |
| 4517 | None, |
| 4518 | Some("exec"), |
| 4519 | ); |
| 4520 | saved |
| 4521 | .metadata |
| 4522 | .set_model_provider_route("custom", Some("resume-fixture")); |
| 4523 | assert!(required_exec_resume_binding(Some(&saved), false).is_none()); |
| 4524 | saved.metadata.exec_route_binding = Some(current.clone()); |
| 4525 | let json = serde_json::to_string(&saved.metadata)?; |
| 4526 | assert!(!json.contains(ORIGINAL)); |
| 4527 | assert!(!json.contains(ORIGINAL_KEY)); |
| 4528 | saved.metadata = serde_json::from_str(&json)?; |
| 4529 | drop(manager); |
| 4530 | |
| 4531 | let manager = SessionManager::new(store)?; |
| 4532 | let reopened_key = |
| 4533 | SessionManager::exec_route_binding_key(&manager.sessions_dir().canonicalize()?, false)?; |
| 4534 | let required = required_exec_resume_binding(Some(&saved), false); |
| 4535 | check_exec_resume_endpoint(required, Some(&reopened_key), ORIGINAL)?; |
| 4536 | check_exec_resume_authority( |
| 4537 | required, |
| 4538 | &binding(&reopened_key, ORIGINAL, ORIGINAL_KEY, "chat")?, |
| 4539 | )?; |
| 4540 | assert!( |
| 4541 | check_exec_resume_authority( |
| 4542 | required, |
| 4543 | &binding(&reopened_key, ORIGINAL, ORIGINAL_KEY, "responses")?, |
| 4544 | ) |
| 4545 | .is_err() |
| 4546 | ); |
| 4547 | |
| 4548 | let changed_endpoint = |
| 4549 | check_exec_resume_endpoint(required, Some(&reopened_key), REBOUND).unwrap_err(); |
| 4550 | assert!( |
| 4551 | changed_endpoint |
| 4552 | .to_string() |
| 4553 | .contains("--provider or --model") |
| 4554 | ); |
| 4555 | assert!(!changed_endpoint.to_string().contains(REBOUND)); |
| 4556 | assert!(check_exec_resume_endpoint(required, None, ORIGINAL).is_err()); |
| 4557 | let rebound_account = binding(&reopened_key, ORIGINAL, REBOUND_KEY, "chat")?; |
| 4558 | let changed_account = check_exec_resume_authority(required, &rebound_account).unwrap_err(); |
| 4559 | assert!( |
| 4560 | changed_account |
| 4561 | .to_string() |
| 4562 | .contains("--provider or --model") |
| 4563 | ); |
| 4564 | assert!(!changed_account.to_string().contains(REBOUND_KEY)); |
| 4565 | |
| 4566 | let required = required_exec_resume_binding(Some(&saved), true); |
| 4567 | check_exec_resume_endpoint(required, Some(&reopened_key), REBOUND)?; |
| 4568 | check_exec_resume_authority( |
| 4569 | required, |
| 4570 | &binding(&reopened_key, REBOUND, REBOUND_KEY, "chat")?, |
| 4571 | )?; |
| 4572 | Ok(()) |
| 4573 | } |
| 4574 | #[test] |
| 4575 | fn windows_config_path_compare_normalizes_mixed_separators() { |
| 4576 | assert_eq!( |
| 4577 | normalize_windows_config_path_str(r"C:\Users\me\repo"), |
| 4578 | normalize_windows_config_path_str(r"C:/Users/me/repo/") |
| 4579 | ); |
| 4580 | } |
| 4581 | |
| 4582 | #[test] |
| 4583 | fn windows_config_path_compare_normalizes_verbatim_and_unc_prefixes() { |
| 4584 | assert_eq!( |
| 4585 | normalize_windows_config_path_str(r"\\?\C:\Users\me\repo"), |
| 4586 | normalize_windows_config_path_str(r"C:/Users/me/repo") |
| 4587 | ); |
| 4588 | assert_eq!( |
| 4589 | normalize_windows_config_path_str(r"\\?\UNC\server\share\repo"), |
| 4590 | normalize_windows_config_path_str(r"\\server/share/repo/") |
| 4591 | ); |
| 4592 | } |
| 4593 | |
| 4594 | #[test] |
| 4595 | fn headless_consultant_authority_overrides_network_allow_and_disables_web_search() { |
| 4596 | let config = { |
| 4597 | let __cw_config_init_0_0 = Some(codewhale_config::NetworkPolicyToml { |
| 4598 | default: "allow".to_string(), |
| 4599 | audit: false, |
| 4600 | ..codewhale_config::NetworkPolicyToml::default() |
| 4601 | }); |
| 4602 | let mut __cw_config_init_0_value: Config = Config::default(); |
| 4603 | __cw_config_init_0_value.network = __cw_config_init_0_0; |
| 4604 | __cw_config_init_0_value |
| 4605 | }; |
| 4606 | let authority = codewhale_engine::tools::spec::ToolAuthorityEnvelope { |
| 4607 | schema_version: 1, |
| 4608 | owner: "consultant-1".to_string(), |
| 4609 | authority: codewhale_engine::tools::spec::ToolMutationAuthority::ReadOnly, |
| 4610 | network_access: Some(false), |
| 4611 | shell: codewhale_engine::tools::spec::ToolShellAuthority::None, |
| 4612 | verification: codewhale_engine::tools::spec::ToolVerificationAuthority::None, |
| 4613 | writable_roots: Vec::new(), |
| 4614 | writable_files: Vec::new(), |
| 4615 | coordination_contracts: Vec::new(), |
| 4616 | } |
| 4617 | .normalized() |
| 4618 | .expect("Consultant authority"); |
| 4619 | |
| 4620 | let policy = exec_network_policy(&config, authority.network_access) |
| 4621 | .expect("explicit network=false always installs a policy"); |
| 4622 | assert_eq!( |
| 4623 | policy.evaluate("example.com", "web_search"), |
| 4624 | codewhale_net::network_policy::Decision::Deny, |
| 4625 | "the permissive user config must not widen Consultant network authority" |
| 4626 | ); |
| 4627 | let mut features = codewhale_runtime::features::Features::default(); |
| 4628 | features.enable(codewhale_runtime::features::Feature::ShellTool); |
| 4629 | features.enable(codewhale_runtime::features::Feature::WebSearch); |
| 4630 | apply_fleet_engine_feature_caps( |
| 4631 | &mut features, |
| 4632 | true, |
| 4633 | authority.network_access, |
| 4634 | authority.shell, |
| 4635 | ); |
| 4636 | assert!(!features.enabled(codewhale_runtime::features::Feature::WebSearch)); |
| 4637 | assert!(!features.enabled(codewhale_runtime::features::Feature::ShellTool)); |
| 4638 | |
| 4639 | let worker_policy = exec_network_policy(&config, Some(true)).expect("configured policy"); |
| 4640 | assert_eq!( |
| 4641 | worker_policy.evaluate("example.com", "web_search"), |
| 4642 | codewhale_net::network_policy::Decision::Allow, |
| 4643 | "a network-capable role keeps the configured policy" |
| 4644 | ); |
| 4645 | } |
| 4646 | |
| 4647 | #[tokio::test] |
| 4648 | #[allow(clippy::await_holding_lock)] |
| 4649 | async fn explicit_exec_model_routes_to_unique_authenticated_provider_candidate() { |
| 4650 | let _env_lock = codewhale_engine::test_support::lock_test_env(); |
| 4651 | let _zai = codewhale_engine::test_support::EnvVarGuard::set("ZAI_API_KEY", "zai-key"); |
| 4652 | let _openrouter = codewhale_engine::test_support::EnvVarGuard::remove("OPENROUTER_API_KEY"); |
| 4653 | let config = { |
| 4654 | let __cw_config_init_11_0 = Some("deepseek".to_string()); |
| 4655 | let __cw_config_init_11_1 = |
| 4656 | Some(codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string()); |
| 4657 | let mut __cw_config_init_11_value: Config = Default::default(); |
| 4658 | __cw_config_init_11_value.provider = __cw_config_init_11_0; |
| 4659 | __cw_config_init_11_value.default_text_model = __cw_config_init_11_1; |
| 4660 | __cw_config_init_11_value |
| 4661 | }; |
| 4662 | |
| 4663 | let route = resolve_cli_auto_route( |
| 4664 | &config, |
| 4665 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL, |
| 4666 | "pong", |
| 4667 | None, |
| 4668 | ) |
| 4669 | .await |
| 4670 | .expect("explicit GLM should route to the configured Z.ai provider"); |
| 4671 | |
| 4672 | assert_eq!(route.provider.provider, codewhale_config::ProviderKind::Zai); |
| 4673 | assert_eq!( |
| 4674 | route.model, |
| 4675 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL |
| 4676 | ); |
| 4677 | assert!(!route.auto_model); |
| 4678 | } |
| 4679 | |
| 4680 | #[tokio::test] |
| 4681 | #[allow(clippy::await_holding_lock)] |
| 4682 | async fn explicit_exec_model_reports_ambiguous_authenticated_provider_candidates() { |
| 4683 | let _env_lock = codewhale_engine::test_support::lock_test_env(); |
| 4684 | let _zai = codewhale_engine::test_support::EnvVarGuard::set("ZAI_API_KEY", "zai-key"); |
| 4685 | let _openrouter = |
| 4686 | codewhale_engine::test_support::EnvVarGuard::set("OPENROUTER_API_KEY", "or-key"); |
| 4687 | let config = { |
| 4688 | let __cw_config_init_12_0 = Some("deepseek".to_string()); |
| 4689 | let __cw_config_init_12_1 = |
| 4690 | Some(codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string()); |
| 4691 | let mut __cw_config_init_12_value: Config = Default::default(); |
| 4692 | __cw_config_init_12_value.provider = __cw_config_init_12_0; |
| 4693 | __cw_config_init_12_value.default_text_model = __cw_config_init_12_1; |
| 4694 | __cw_config_init_12_value |
| 4695 | }; |
| 4696 | |
| 4697 | let err = resolve_cli_auto_route( |
| 4698 | &config, |
| 4699 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL, |
| 4700 | "pong", |
| 4701 | None, |
| 4702 | ) |
| 4703 | .await |
| 4704 | .expect_err("ambiguous GLM route should ask for an explicit provider"); |
| 4705 | let message = err.to_string(); |
| 4706 | |
| 4707 | assert!(message.contains("model `GLM-5.2` is available")); |
| 4708 | assert!(message.contains("openrouter")); |
| 4709 | assert!(message.contains("zai")); |
| 4710 | assert!(message.contains("--provider")); |
| 4711 | assert!(message.contains("/provider")); |
| 4712 | assert!(message.contains("/model")); |
| 4713 | assert!(message.contains("/setup")); |
| 4714 | } |
| 4715 | |
| 4716 | #[tokio::test] |
| 4717 | async fn cli_auto_model_honors_a_fixed_reasoning_preference() { |
| 4718 | let config = { |
| 4719 | let __cw_config_init_13_0 = Some("vllm".to_string()); |
| 4720 | let __cw_config_init_13_1 = Some("low".to_string()); |
| 4721 | let __cw_config_init_13_2 = Some(codewhale_runtime::config::ProvidersConfig { |
| 4722 | vllm: codewhale_runtime::config::ProviderConfig { |
| 4723 | base_url: Some("http://127.0.0.1:18190/v1".to_string()), |
| 4724 | model: Some("local-auto-model".to_string()), |
| 4725 | ..Default::default() |
| 4726 | }, |
| 4727 | ..Default::default() |
| 4728 | }); |
| 4729 | let mut __cw_config_init_13_value: Config = Default::default(); |
| 4730 | __cw_config_init_13_value.provider = __cw_config_init_13_0; |
| 4731 | __cw_config_init_13_value.reasoning_effort = __cw_config_init_13_1; |
| 4732 | __cw_config_init_13_value.providers = __cw_config_init_13_2; |
| 4733 | __cw_config_init_13_value |
| 4734 | }; |
| 4735 | |
| 4736 | let route = resolve_cli_auto_route(&config, "auto", "debug a failing test", None) |
| 4737 | .await |
| 4738 | .expect("Auto model route"); |
| 4739 | |
| 4740 | assert!(route.auto_model); |
| 4741 | assert_eq!( |
| 4742 | route.reasoning_effort, |
| 4743 | Some(codewhale_engine::reasoning_preference::ReasoningEffort::Low) |
| 4744 | ); |
| 4745 | assert!( |
| 4746 | !route.auto_controls_reasoning, |
| 4747 | "a fixed saved tier must not be replaced per prompt" |
| 4748 | ); |
| 4749 | } |
| 4750 | |
| 4751 | #[test] |
| 4752 | fn cli_route_execution_config_stamps_routed_model_into_provider_slot() { |
| 4753 | let mut providers = codewhale_runtime::config::ProvidersConfig::default(); |
| 4754 | providers.deepseek.model = Some("deepseek-v4-pro".to_string()); |
| 4755 | let config = { |
| 4756 | let __cw_config_init_14_0 = Some("deepseek".to_string()); |
| 4757 | let __cw_config_init_14_1 = Some(providers); |
| 4758 | let mut __cw_config_init_14_value: Config = Default::default(); |
| 4759 | __cw_config_init_14_value.provider = __cw_config_init_14_0; |
| 4760 | __cw_config_init_14_value.providers = __cw_config_init_14_1; |
| 4761 | __cw_config_init_14_value |
| 4762 | }; |
| 4763 | let route = CliAutoRoute { |
| 4764 | provider: Config::default() |
| 4765 | .test_identity_for_kind(codewhale_config::ProviderKind::Deepseek), |
| 4766 | model: "deepseek-v4-flash".to_string(), |
| 4767 | reasoning_effort: None, |
| 4768 | auto_controls_reasoning: true, |
| 4769 | auto_model: true, |
| 4770 | }; |
| 4771 | |
| 4772 | let execution_config = |
| 4773 | config_for_cli_route(&config, &route).expect("admitted execution route"); |
| 4774 | |
| 4775 | assert_eq!(execution_config.default_model(), "deepseek-v4-flash"); |
| 4776 | assert_eq!( |
| 4777 | execution_config |
| 4778 | .provider_config_for( |
| 4779 | &execution_config |
| 4780 | .test_identity_for_kind(codewhale_config::ProviderKind::Deepseek) |
| 4781 | ) |
| 4782 | .and_then(|entry| entry.model.as_deref()), |
| 4783 | Some("deepseek-v4-flash") |
| 4784 | ); |
| 4785 | } |
| 4786 | |
| 4787 | #[test] |
| 4788 | fn cli_route_execution_config_preserves_the_legacy_literal_custom_route() { |
| 4789 | let _lock = codewhale_engine::test_support::lock_test_env(); |
| 4790 | let _source = |
| 4791 | codewhale_engine::test_support::EnvVarGuard::remove("DEEPSEEK_API_KEY_SOURCE"); |
| 4792 | let _cli_key = codewhale_engine::test_support::EnvVarGuard::remove("CODEWHALE_CLI_API_KEY"); |
| 4793 | let config = { |
| 4794 | let __cw_config_init_15_0 = Some("custom".to_string()); |
| 4795 | let __cw_config_init_15_1 = Some("legacy-model".to_string()); |
| 4796 | let mut __cw_config_init_15_value: Config = Default::default(); |
| 4797 | __cw_config_init_15_value.provider = __cw_config_init_15_0; |
| 4798 | __cw_config_init_15_value.default_text_model = __cw_config_init_15_1; |
| 4799 | __cw_config_init_15_value |
| 4800 | } |
| 4801 | .with_legacy_root( |
| 4802 | Some("legacy-root-key".to_string()), |
| 4803 | Some("http://127.0.0.1:18183/v1".to_string()), |
| 4804 | ); |
| 4805 | let route = CliAutoRoute { |
| 4806 | provider: config |
| 4807 | .active_provider_identity() |
| 4808 | .expect("captured literal root identity"), |
| 4809 | model: "routed-legacy-model".to_string(), |
| 4810 | reasoning_effort: None, |
| 4811 | auto_controls_reasoning: false, |
| 4812 | auto_model: false, |
| 4813 | }; |
| 4814 | |
| 4815 | let execution = config_for_cli_route(&config, &route).expect("admitted execution route"); |
| 4816 | |
| 4817 | // The literal route's top-level fields live in `[providers.custom]` |
| 4818 | // (#6394), and the routed model lands there too. |
| 4819 | assert!(execution.selects_literal_custom_provider()); |
| 4820 | assert_eq!(execution.provider.as_deref(), Some("custom")); |
| 4821 | assert_eq!(execution.default_model(), "routed-legacy-model"); |
| 4822 | assert_eq!( |
| 4823 | execution.active_route_base_url(), |
| 4824 | "http://127.0.0.1:18183/v1" |
| 4825 | ); |
| 4826 | assert_eq!(execution.active_route_api_key().unwrap(), "legacy-root-key"); |
| 4827 | for _ in 0..2 { |
| 4828 | let identity = execution |
| 4829 | .resolve_provider_identity("custom") |
| 4830 | .expect("legacy identity remains repeatedly resolvable"); |
| 4831 | assert_eq!(identity.key.as_str(), "custom"); |
| 4832 | } |
| 4833 | let client = codewhale_engine::client::CodewhaleClient::new(&execution) |
| 4834 | .expect("legacy execution client"); |
| 4835 | assert_eq!(client.base_url(), "http://127.0.0.1:18183/v1"); |
| 4836 | } |
| 4837 | |
| 4838 | #[tokio::test] |
| 4839 | async fn forced_exec_route_keeps_custom_provider_when_model_matches_builtin_catalog() { |
| 4840 | let config = custom_exec_config("custom-a"); |
| 4841 | |
| 4842 | let route = resolve_cli_exec_route( |
| 4843 | &config, |
| 4844 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL, |
| 4845 | "audit", |
| 4846 | true, |
| 4847 | None, |
| 4848 | ) |
| 4849 | .await |
| 4850 | .expect("forced route"); |
| 4851 | let execution = config_for_cli_route(&config, &route).expect("admitted execution route"); |
| 4852 | |
| 4853 | assert_eq!( |
| 4854 | route.provider.provider, |
| 4855 | codewhale_config::ProviderKind::Custom |
| 4856 | ); |
| 4857 | assert_eq!( |
| 4858 | route.model, |
| 4859 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL |
| 4860 | ); |
| 4861 | assert_eq!(execution.provider.as_deref(), Some("custom-a")); |
| 4862 | } |
| 4863 | |
| 4864 | #[tokio::test] |
| 4865 | async fn configured_workflow_default_keeps_named_custom_route() { |
| 4866 | let config = custom_exec_config("custom-a"); |
| 4867 | let model = config.default_model(); |
| 4868 | |
| 4869 | let route = resolve_cli_exec_route( |
| 4870 | &config, |
| 4871 | &model, |
| 4872 | "Run a checked-in Workflow through the host runtime", |
| 4873 | true, |
| 4874 | None, |
| 4875 | ) |
| 4876 | .await |
| 4877 | .expect("configured workflow route"); |
| 4878 | let execution = config_for_cli_route(&config, &route).expect("admitted execution route"); |
| 4879 | |
| 4880 | assert_eq!( |
| 4881 | route.provider.provider, |
| 4882 | codewhale_config::ProviderKind::Custom |
| 4883 | ); |
| 4884 | assert_eq!( |
| 4885 | execution.active_provider_identity().unwrap().key.as_str(), |
| 4886 | "custom-a" |
| 4887 | ); |
| 4888 | assert_eq!( |
| 4889 | execution.active_route_base_url(), |
| 4890 | "http://127.0.0.1:18181/v1" |
| 4891 | ); |
| 4892 | let client = |
| 4893 | codewhale_engine::client::CodewhaleClient::new(&execution).expect("workflow client"); |
| 4894 | assert_eq!(client.base_url(), "http://127.0.0.1:18181/v1"); |
| 4895 | } |
| 4896 | |
| 4897 | #[test] |
| 4898 | fn exec_json_receipts_keep_exact_named_custom_provider() { |
| 4899 | let config = custom_exec_config("custom-a"); |
| 4900 | let identity = config.active_provider_identity().unwrap(); |
| 4901 | let provider = identity.key.as_str(); |
| 4902 | let mut one_shot = ExecSummary { |
| 4903 | mode: "one-shot".to_string(), |
| 4904 | provider: provider.to_string(), |
| 4905 | model: "model-a".to_string(), |
| 4906 | output: "done".to_string(), |
| 4907 | status: Some("completed".to_string()), |
| 4908 | ..ExecSummary::default() |
| 4909 | }; |
| 4910 | one_shot.settle( |
| 4911 | Some(codewhale_models::Usage { |
| 4912 | input_tokens: 12, |
| 4913 | output_tokens: 3, |
| 4914 | ..Default::default() |
| 4915 | }), |
| 4916 | 0, |
| 4917 | false, |
| 4918 | ); |
| 4919 | let one_shot = serde_json::to_value(&one_shot).expect("one-shot receipt"); |
| 4920 | assert_eq!(one_shot["mode"], "one-shot"); |
| 4921 | assert_eq!(one_shot["provider"], "custom-a"); |
| 4922 | assert_eq!(one_shot["model"], "model-a"); |
| 4923 | assert_eq!(one_shot["output"], "done"); |
| 4924 | assert_eq!(one_shot["success"], true); |
| 4925 | assert_eq!(one_shot["usage"]["input_tokens"], 12); |
| 4926 | assert_eq!(one_shot["usage"]["output_tokens"], 3); |
| 4927 | assert_eq!(one_shot["usage_status"], "complete"); |
| 4928 | assert!(one_shot["stop_reason"].is_null()); |
| 4929 | |
| 4930 | let mut failed = ExecSummary::new( |
| 4931 | "one-shot", |
| 4932 | provider.to_string(), |
| 4933 | "model-a".to_string(), |
| 4934 | String::new(), |
| 4935 | ); |
| 4936 | failed.record_turn_outcome( |
| 4937 | codewhale_engine::core::events::TurnOutcomeStatus::Failed, |
| 4938 | Some("Model response incomplete".to_string()), |
| 4939 | ); |
| 4940 | failed.settle(Some(codewhale_models::Usage::default()), 0, false); |
| 4941 | let failed = serde_json::to_value(&failed).expect("failed one-shot receipt"); |
| 4942 | assert_eq!(failed["success"], false); |
| 4943 | assert_eq!(failed["status"], "failed"); |
| 4944 | assert!(failed["termination_reason"].is_string(), "{failed}"); |
| 4945 | assert!(failed["usage"].is_null(), "no usage is never zero usage"); |
| 4946 | assert_eq!(failed["usage_status"], "unreported"); |
| 4947 | |
| 4948 | let mut agent = ExecSummary::new( |
| 4949 | "agent", |
| 4950 | provider.to_string(), |
| 4951 | "model-a".to_string(), |
| 4952 | String::new(), |
| 4953 | ); |
| 4954 | agent.record_agent_event(&codewhale_engine::core::events::Event::AgentSpawned { |
| 4955 | owner_session_id: "exec-sess-1".to_string(), |
| 4956 | id: "child-1".to_string(), |
| 4957 | prompt: String::new(), |
| 4958 | worker_status: None, |
| 4959 | parent_run_id: None, |
| 4960 | spawn_depth: 1, |
| 4961 | model: "child-model".to_string(), |
| 4962 | route_source: None, |
| 4963 | display_name: None, |
| 4964 | }); |
| 4965 | agent.record_turn_outcome( |
| 4966 | codewhale_engine::core::events::TurnOutcomeStatus::Completed, |
| 4967 | None, |
| 4968 | ); |
| 4969 | agent.settle( |
| 4970 | Some(codewhale_models::Usage { |
| 4971 | input_tokens: 40, |
| 4972 | output_tokens: 5, |
| 4973 | ..Default::default() |
| 4974 | }), |
| 4975 | 0, |
| 4976 | false, |
| 4977 | ); |
| 4978 | let agent = serde_json::to_value(&agent).expect("agent exec JSON receipt"); |
| 4979 | assert_eq!(agent["provider"], "custom-a"); |
| 4980 | assert_eq!(agent["success"], true); |
| 4981 | assert_eq!(agent["usage"]["input_tokens"], 40); |
| 4982 | assert_eq!( |
| 4983 | agent["usage_status"], "partial", |
| 4984 | "a child without a usage receipt keeps the total partial" |
| 4985 | ); |
| 4986 | assert_eq!(agent["agents"][0]["id"], "child-1"); |
| 4987 | assert_eq!(agent["agents"][0]["model"], "child-model"); |
| 4988 | assert!(agent["agents"][0]["usage"].is_null()); |
| 4989 | let serialized = serde_json::to_string(&agent).expect("serialize receipt"); |
| 4990 | assert!(!serialized.contains("127.0.0.1")); |
| 4991 | assert!(!serialized.contains("local-test-key")); |
| 4992 | } |
| 4993 | |
| 4994 | #[test] |
| 4995 | fn exec_stream_provider_pair_preserves_named_literal_and_root_custom_provenance() { |
| 4996 | let mut config = Config::default(); |
| 4997 | for key in ["lm-studio", "custom"] { |
| 4998 | config |
| 4999 | .providers |
| 5000 | .get_or_insert_with(Default::default) |
| 5001 | .custom |
| 5002 | .insert( |
| 5003 | key.to_string(), |
| 5004 | codewhale_runtime::config::ProviderConfig { |
| 5005 | kind: Some("openai-compatible".to_string()), |
| 5006 | base_url: Some("http://localhost:1234/v1".to_string()), |
| 5007 | ..Default::default() |
| 5008 | }, |
| 5009 | ); |
| 5010 | } |
| 5011 | let named = config |
| 5012 | .resolve_provider_identity("lm-studio") |
| 5013 | .expect("exact named table"); |
| 5014 | let literal = config |
| 5015 | .resolve_provider_identity("custom") |
| 5016 | .expect("exact literal table"); |
| 5017 | let root_config = { |
| 5018 | let __cw_config_init_1_0 = Some("custom".to_string()); |
| 5019 | let mut __cw_config_init_1_value: Config = Config::default(); |
| 5020 | __cw_config_init_1_value.provider = __cw_config_init_1_0; |
| 5021 | __cw_config_init_1_value |
| 5022 | } |
| 5023 | .with_legacy_root(None, Some("http://localhost:1234/v1".to_string())); |
| 5024 | let root = root_config |
| 5025 | .active_provider_identity() |
| 5026 | .expect("captured root migration"); |
| 5027 | let built_in = Config::default() |
| 5028 | .active_provider_identity() |
| 5029 | .expect("built-in fixture"); |
| 5030 | |
| 5031 | assert_eq!( |
| 5032 | exec_stream_provider_route(&named), |
| 5033 | ("custom".to_string(), Some("lm-studio".to_string())) |
| 5034 | ); |
| 5035 | assert_eq!( |
| 5036 | exec_stream_provider_route(&literal), |
| 5037 | ("custom".to_string(), Some("custom".to_string())) |
| 5038 | ); |
| 5039 | assert_eq!( |
| 5040 | exec_stream_provider_route(&root), |
| 5041 | ("custom".to_string(), None) |
| 5042 | ); |
| 5043 | assert_eq!( |
| 5044 | exec_stream_provider_route(&built_in), |
| 5045 | ("deepseek".to_string(), None) |
| 5046 | ); |
| 5047 | } |
| 5048 | |
| 5049 | #[test] |
| 5050 | fn exec_persistence_omits_id_for_legacy_root_custom_route() { |
| 5051 | let mut saved = session_manager::create_saved_session_with_mode( |
| 5052 | &[], |
| 5053 | "legacy-root-model", |
| 5054 | Path::new("/tmp/exec-root"), |
| 5055 | 0, |
| 5056 | None, |
| 5057 | Some("exec"), |
| 5058 | ); |
| 5059 | stamp_exec_session_metadata( |
| 5060 | &mut saved, |
| 5061 | "legacy-root-model", |
| 5062 | codewhale_config::ProviderKind::Custom.as_str(), |
| 5063 | None, |
| 5064 | Path::new("/tmp/exec-root"), |
| 5065 | ); |
| 5066 | |
| 5067 | assert_eq!(saved.metadata.model_provider, "custom"); |
| 5068 | assert_eq!(saved.metadata.model_provider_id, None); |
| 5069 | assert!( |
| 5070 | !serde_json::to_string(&saved) |
| 5071 | .expect("serialize exec session") |
| 5072 | .contains("model_provider_id") |
| 5073 | ); |
| 5074 | } |
| 5075 | |
| 5076 | #[test] |
| 5077 | fn cli_auto_resolves_to_the_declared_default_before_k3_route_normalization() { |
| 5078 | let config = { |
| 5079 | let __cw_config_init_2_0 = Some("moonshot".to_string()); |
| 5080 | let __cw_config_init_2_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 5081 | moonshot: codewhale_runtime::config::ProviderConfig { |
| 5082 | base_url: Some( |
| 5083 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL |
| 5084 | .to_string(), |
| 5085 | ), |
| 5086 | model: Some( |
| 5087 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL |
| 5088 | .to_string(), |
| 5089 | ), |
| 5090 | ..Default::default() |
| 5091 | }, |
| 5092 | ..Default::default() |
| 5093 | }); |
| 5094 | let mut __cw_config_init_2_value: Config = Default::default(); |
| 5095 | __cw_config_init_2_value.provider = __cw_config_init_2_0; |
| 5096 | __cw_config_init_2_value.providers = __cw_config_init_2_1; |
| 5097 | __cw_config_init_2_value |
| 5098 | }; |
| 5099 | |
| 5100 | // #6290 rework: Auto no longer classifies the prompt. Any wording |
| 5101 | // resolves the declared policy tier, normalized for the K3 route. |
| 5102 | assert_eq!( |
| 5103 | cli_reasoning_effort_value_for_prompt( |
| 5104 | &config, |
| 5105 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL, |
| 5106 | codewhale_engine::reasoning_preference::ReasoningEffort::Auto, |
| 5107 | ) |
| 5108 | .as_deref(), |
| 5109 | Some("high"), |
| 5110 | "Auto resolves the declared default, not a classification" |
| 5111 | ); |
| 5112 | |
| 5113 | assert_eq!( |
| 5114 | cli_reasoning_effort_value_for_prompt( |
| 5115 | &config, |
| 5116 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL, |
| 5117 | codewhale_engine::reasoning_preference::ReasoningEffort::Off, |
| 5118 | ) |
| 5119 | .as_deref(), |
| 5120 | Some("low"), |
| 5121 | "membership K3 still applies its exact-route always-thinking floor" |
| 5122 | ); |
| 5123 | } |
| 5124 | |
| 5125 | #[test] |
| 5126 | fn cli_route_tracks_auto_reasoning_independently_from_auto_model() { |
| 5127 | use codewhale_engine::reasoning_preference::ReasoningEffort; |
| 5128 | |
| 5129 | let fixed_model_auto_reasoning = CliAutoRoute { |
| 5130 | provider: Config::default() |
| 5131 | .test_identity_for_kind(codewhale_config::ProviderKind::Deepseek), |
| 5132 | model: codewhale_config::descriptors::defaults::DEFAULT_TEXT_MODEL.to_string(), |
| 5133 | reasoning_effort: Some(ReasoningEffort::Auto), |
| 5134 | auto_controls_reasoning: true, |
| 5135 | auto_model: false, |
| 5136 | }; |
| 5137 | let auto_model_fixed_reasoning = CliAutoRoute { |
| 5138 | provider: Config::default() |
| 5139 | .test_identity_for_kind(codewhale_config::ProviderKind::OpenaiCodex), |
| 5140 | model: codewhale_config::descriptors::defaults::DEFAULT_OPENAI_CODEX_MODEL.to_string(), |
| 5141 | reasoning_effort: Some(ReasoningEffort::High), |
| 5142 | auto_controls_reasoning: false, |
| 5143 | auto_model: true, |
| 5144 | }; |
| 5145 | |
| 5146 | assert!(fixed_model_auto_reasoning.auto_controls_reasoning); |
| 5147 | assert!(!fixed_model_auto_reasoning.auto_model); |
| 5148 | assert!(!auto_model_fixed_reasoning.auto_controls_reasoning); |
| 5149 | assert!(auto_model_fixed_reasoning.auto_model); |
| 5150 | } |
| 5151 | |
| 5152 | /// `run_exec_agent` must hand the engine a concrete tier, never the literal |
| 5153 | /// `"auto"` sentinel, for a fixed-model Auto launch. |
| 5154 | #[test] |
| 5155 | fn fixed_model_exec_auto_resolves_to_a_concrete_tier_not_the_auto_sentinel() { |
| 5156 | let config = { |
| 5157 | let __cw_config_init_5_0 = Some("zai".to_string()); |
| 5158 | let mut __cw_config_init_5_value: Config = Default::default(); |
| 5159 | __cw_config_init_5_value.provider = __cw_config_init_5_0; |
| 5160 | __cw_config_init_5_value |
| 5161 | }; |
| 5162 | |
| 5163 | let resolved = cli_reasoning_effort_value_for_prompt( |
| 5164 | &config, |
| 5165 | codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL, |
| 5166 | codewhale_engine::reasoning_preference::ReasoningEffort::Auto, |
| 5167 | ) |
| 5168 | .expect("Auto must resolve to a concrete tier"); |
| 5169 | |
| 5170 | assert_ne!( |
| 5171 | resolved, "auto", |
| 5172 | "the literal auto sentinel must never reach a provider" |
| 5173 | ); |
| 5174 | assert!( |
| 5175 | matches!(resolved.as_str(), "off" | "low" | "medium" | "high" | "max"), |
| 5176 | "unexpected resolved tier: {resolved}" |
| 5177 | ); |
| 5178 | } |
| 5179 | |
| 5180 | #[test] |
| 5181 | fn fleet_tool_authority_cannot_cross_an_exec_resume_boundary() { |
| 5182 | assert!(validate_exec_tool_authority_resume(None, true).is_ok()); |
| 5183 | assert!(validate_exec_tool_authority_resume(Some("{}"), false).is_ok()); |
| 5184 | let error = validate_exec_tool_authority_resume(Some("{}"), true) |
| 5185 | .expect_err("authority must remain bound to its fresh Fleet launch") |
| 5186 | .to_string(); |
| 5187 | assert!(error.contains("cannot be combined with exec --resume")); |
| 5188 | } |
| 5189 | |
| 5190 | #[test] |
| 5191 | fn exec_sandbox_denial_stream_event_is_typed() { |
| 5192 | let event = ExecStreamEvent::SandboxDenied { |
| 5193 | tool_id: "call_1".to_string(), |
| 5194 | tool_name: "exec_shell".to_string(), |
| 5195 | reason: "write blocked".to_string(), |
| 5196 | outcome: "approval_required".to_string(), |
| 5197 | }; |
| 5198 | let value: serde_json::Value = |
| 5199 | serde_json::from_str(&serde_json::to_string(&event).expect("serializes")) |
| 5200 | .expect("valid json"); |
| 5201 | assert_eq!(value["type"], "sandbox_denied"); |
| 5202 | assert_eq!(value["outcome"], "approval_required"); |
| 5203 | } |
| 5204 | |
| 5205 | #[test] |
| 5206 | fn exec_stream_turn_usage_event_serializes_reported_fields() { |
| 5207 | let event = ExecStreamEvent::TurnUsage { |
| 5208 | turn: 2, |
| 5209 | input_tokens: 1200, |
| 5210 | output_tokens: 180, |
| 5211 | reasoning_tokens: Some(90), |
| 5212 | prompt_cache_hit_tokens: Some(900), |
| 5213 | prompt_cache_miss_tokens: Some(300), |
| 5214 | prompt_cache_write_tokens: Some(0), |
| 5215 | reasoning_replay_tokens: Some(40), |
| 5216 | duration_ms: 1834, |
| 5217 | finish_reason: None, |
| 5218 | }; |
| 5219 | |
| 5220 | let value = exec_stream_value(&event).expect("serializes"); |
| 5221 | let json = serde_json::to_string(&value).expect("serializes"); |
| 5222 | assert!(!json.contains('\n')); |
| 5223 | let parsed: serde_json::Value = serde_json::from_str(&json).expect("valid json"); |
| 5224 | assert_eq!(parsed["type"], "turn_usage"); |
| 5225 | assert_eq!(parsed["schema"], "codewhale.exec-stream"); |
| 5226 | assert_eq!(parsed["schema_version"], 1); |
| 5227 | assert_eq!(parsed["turn"], 2); |
| 5228 | assert_eq!(parsed["input_tokens"], 1200); |
| 5229 | assert_eq!(parsed["output_tokens"], 180); |
| 5230 | assert_eq!(parsed["reasoning_tokens"], 90); |
| 5231 | assert_eq!(parsed["prompt_cache_hit_tokens"], 900); |
| 5232 | assert_eq!(parsed["prompt_cache_miss_tokens"], 300); |
| 5233 | assert_eq!(parsed["prompt_cache_write_tokens"], 0); |
| 5234 | assert_eq!(parsed["reasoning_replay_tokens"], 40); |
| 5235 | assert_eq!(parsed["duration_ms"], 1834); |
| 5236 | } |
| 5237 | |
| 5238 | #[test] |
| 5239 | fn exec_stream_turn_usage_event_omits_unreported_fields() { |
| 5240 | // Honest absence: optional token fields the provider did not report |
| 5241 | // are dropped from the object entirely — never emitted as null and |
| 5242 | // never backfilled with fabricated zeros. |
| 5243 | let event = ExecStreamEvent::TurnUsage { |
| 5244 | turn: 1, |
| 5245 | input_tokens: 11, |
| 5246 | output_tokens: 3, |
| 5247 | reasoning_tokens: None, |
| 5248 | prompt_cache_hit_tokens: None, |
| 5249 | prompt_cache_miss_tokens: None, |
| 5250 | prompt_cache_write_tokens: None, |
| 5251 | reasoning_replay_tokens: None, |
| 5252 | duration_ms: 250, |
| 5253 | finish_reason: None, |
| 5254 | }; |
| 5255 | |
| 5256 | let value = exec_stream_value(&event).expect("serializes"); |
| 5257 | let parsed = value; |
| 5258 | assert_eq!(parsed["type"], "turn_usage"); |
| 5259 | assert_eq!(parsed["input_tokens"], 11); |
| 5260 | assert_eq!(parsed["output_tokens"], 3); |
| 5261 | assert_eq!(parsed["duration_ms"], 250); |
| 5262 | let object = parsed.as_object().expect("event object"); |
| 5263 | for absent in [ |
| 5264 | "reasoning_tokens", |
| 5265 | "prompt_cache_hit_tokens", |
| 5266 | "prompt_cache_miss_tokens", |
| 5267 | "prompt_cache_write_tokens", |
| 5268 | "reasoning_replay_tokens", |
| 5269 | ] { |
| 5270 | assert!(!object.contains_key(absent), "{absent} leaked: {parsed}"); |
| 5271 | } |
| 5272 | } |
| 5273 | |
| 5274 | #[test] |
| 5275 | fn exec_stream_pre_existing_event_type_tags_are_unchanged() { |
| 5276 | // Contract guard for existing stream consumers (bench harness, fleet |
| 5277 | // ledger): the pre-turn_usage event vocabulary keeps its exact tags. |
| 5278 | let cases: Vec<(ExecStreamEvent, &str)> = vec![ |
| 5279 | ( |
| 5280 | ExecStreamEvent::Content { |
| 5281 | content: "hi".to_string(), |
| 5282 | }, |
| 5283 | "content", |
| 5284 | ), |
| 5285 | ( |
| 5286 | ExecStreamEvent::ToolUse { |
| 5287 | name: "read_file".to_string(), |
| 5288 | id: "call_1".to_string(), |
| 5289 | input: serde_json::json!({}), |
| 5290 | started_at: "2026-08-03T00:00:00Z".to_string(), |
| 5291 | }, |
| 5292 | "tool_use", |
| 5293 | ), |
| 5294 | ( |
| 5295 | ExecStreamEvent::ToolResult { |
| 5296 | id: "call_1".to_string(), |
| 5297 | name: "read_file".to_string(), |
| 5298 | output: "ok".to_string(), |
| 5299 | status: "success".to_string(), |
| 5300 | started_at: "2026-08-03T00:00:00Z".to_string(), |
| 5301 | completed_at: "2026-08-03T00:00:01Z".to_string(), |
| 5302 | duration_ms: 1, |
| 5303 | side_effect_status: "unknown".to_string(), |
| 5304 | error_category: None, |
| 5305 | truncated: None, |
| 5306 | artifact: None, |
| 5307 | result_metadata: None, |
| 5308 | }, |
| 5309 | "tool_result", |
| 5310 | ), |
| 5311 | ( |
| 5312 | ExecStreamEvent::SandboxDenied { |
| 5313 | tool_id: "call_1".to_string(), |
| 5314 | tool_name: "exec_shell".to_string(), |
| 5315 | reason: "denied".to_string(), |
| 5316 | outcome: "approval_required".to_string(), |
| 5317 | }, |
| 5318 | "sandbox_denied", |
| 5319 | ), |
| 5320 | ( |
| 5321 | ExecStreamEvent::WorkflowEvent { |
| 5322 | run_id: "workflow_1".to_string(), |
| 5323 | event: serde_json::json!({"type": "task_completed"}), |
| 5324 | }, |
| 5325 | "workflow_event", |
| 5326 | ), |
| 5327 | ( |
| 5328 | ExecStreamEvent::SessionCapture { |
| 5329 | content: "x".to_string(), |
| 5330 | saved_session_id: "session-x".to_string(), |
| 5331 | }, |
| 5332 | "session_capture", |
| 5333 | ), |
| 5334 | ( |
| 5335 | ExecStreamEvent::Error { |
| 5336 | error: "boom".to_string(), |
| 5337 | }, |
| 5338 | "error", |
| 5339 | ), |
| 5340 | (ExecStreamEvent::Done, "done"), |
| 5341 | ]; |
| 5342 | |
| 5343 | for (event, expected_type) in cases { |
| 5344 | let value = exec_stream_value(&event).expect("serializes"); |
| 5345 | assert_eq!(value["type"], expected_type, "event tag drifted"); |
| 5346 | assert_eq!(value["schema"], "codewhale.exec-stream"); |
| 5347 | assert_eq!(value["schema_version"], 1); |
| 5348 | } |
| 5349 | } |
| 5350 | |
| 5351 | #[test] |
| 5352 | fn exec_stream_events_are_json_lines() { |
| 5353 | let event = ExecStreamEvent::ToolResult { |
| 5354 | id: "call_1".to_string(), |
| 5355 | name: "read_file".to_string(), |
| 5356 | output: "line 1\nline 2".to_string(), |
| 5357 | status: "success".to_string(), |
| 5358 | started_at: "2026-07-13T00:00:00Z".to_string(), |
| 5359 | completed_at: "2026-07-13T00:00:01Z".to_string(), |
| 5360 | duration_ms: 1000, |
| 5361 | side_effect_status: "not_started".to_string(), |
| 5362 | error_category: None, |
| 5363 | truncated: Some(false), |
| 5364 | artifact: None, |
| 5365 | result_metadata: None, |
| 5366 | }; |
| 5367 | |
| 5368 | let value = exec_stream_value(&event).expect("serializes"); |
| 5369 | let json = serde_json::to_string(&value).expect("serializes"); |
| 5370 | assert!(!json.contains('\n')); |
| 5371 | let parsed: serde_json::Value = serde_json::from_str(&json).expect("valid json"); |
| 5372 | assert_eq!(parsed["type"], "tool_result"); |
| 5373 | assert_eq!(parsed["schema"], "codewhale.exec-stream"); |
| 5374 | assert_eq!(parsed["schema_version"], 1); |
| 5375 | assert_eq!(parsed["duration_ms"], 1000); |
| 5376 | assert_eq!(parsed["side_effect_status"], "not_started"); |
| 5377 | } |
| 5378 | |
| 5379 | #[test] |
| 5380 | fn workflow_receipt_stream_event_is_one_json_line() { |
| 5381 | let event = ExecStreamEvent::WorkflowEvent { |
| 5382 | run_id: "workflow_1234".to_string(), |
| 5383 | event: serde_json::json!({ |
| 5384 | "type": "handoff_promoted", |
| 5385 | "artifact_id": "workflow_1234:agent_1:review-gate:review_report", |
| 5386 | "gate_id": "review-gate", |
| 5387 | "kind": "review_report", |
| 5388 | "from_role": "reviewer", |
| 5389 | "to_role": "verifier", |
| 5390 | "producer_task_id": "agent_1" |
| 5391 | }), |
| 5392 | }; |
| 5393 | |
| 5394 | let value = exec_stream_value(&event).expect("serializes"); |
| 5395 | let json = serde_json::to_string(&value).expect("serializes"); |
| 5396 | assert!(!json.contains('\n')); |
| 5397 | let parsed: serde_json::Value = serde_json::from_str(&json).expect("valid json"); |
| 5398 | assert_eq!(parsed["type"], "workflow_event"); |
| 5399 | assert_eq!(parsed["schema"], "codewhale.exec-stream"); |
| 5400 | assert_eq!(parsed["schema_version"], 1); |
| 5401 | assert_eq!(parsed["run_id"], "workflow_1234"); |
| 5402 | assert_eq!(parsed["event"]["type"], "handoff_promoted"); |
| 5403 | assert_eq!( |
| 5404 | parsed["event"]["artifact_id"], |
| 5405 | "workflow_1234:agent_1:review-gate:review_report" |
| 5406 | ); |
| 5407 | assert_eq!(parsed["event"]["gate_id"], "review-gate"); |
| 5408 | assert_eq!(parsed["event"]["kind"], "review_report"); |
| 5409 | assert_eq!(parsed["event"]["from_role"], "reviewer"); |
| 5410 | assert_eq!(parsed["event"]["to_role"], "verifier"); |
| 5411 | assert_eq!(parsed["event"]["producer_task_id"], "agent_1"); |
| 5412 | assert!(parsed["event"].get("payload").is_none(), "{parsed}"); |
| 5413 | |
| 5414 | let consumed = ExecStreamEvent::WorkflowEvent { |
| 5415 | run_id: "workflow_1234".to_string(), |
| 5416 | event: serde_json::json!({ |
| 5417 | "type": "handoff_consumed", |
| 5418 | "artifact_id": "workflow_1234:agent_1:review-gate:review_report", |
| 5419 | "kind": "review_report", |
| 5420 | "from_role": "reviewer", |
| 5421 | "to_role": "verifier", |
| 5422 | "consumer_task_id": "agent_2" |
| 5423 | }), |
| 5424 | }; |
| 5425 | let consumed = exec_stream_value(&consumed).expect("serializes consumed receipt"); |
| 5426 | assert_eq!(consumed["type"], "workflow_event"); |
| 5427 | assert_eq!(consumed["schema"], "codewhale.exec-stream"); |
| 5428 | assert_eq!(consumed["schema_version"], 1); |
| 5429 | assert_eq!(consumed["event"]["type"], "handoff_consumed"); |
| 5430 | assert_eq!( |
| 5431 | consumed["event"]["artifact_id"], |
| 5432 | "workflow_1234:agent_1:review-gate:review_report" |
| 5433 | ); |
| 5434 | assert_eq!(consumed["event"]["consumer_task_id"], "agent_2"); |
| 5435 | assert!(consumed["event"].get("payload").is_none(), "{consumed}"); |
| 5436 | } |
| 5437 | |
| 5438 | #[test] |
| 5439 | fn exec_stream_metadata_redacts_resume_breadcrumbs() { |
| 5440 | let raw_session_id = "abc123fullsecret"; |
| 5441 | let event = ExecStreamEvent::Metadata { |
| 5442 | meta: Box::new(ExecStreamMeta { |
| 5443 | receipt_kind: "terminal", |
| 5444 | provider: "deepseek".to_string(), |
| 5445 | provider_id: None, |
| 5446 | model: "deepseek-v4-flash".to_string(), |
| 5447 | route_source: "explicit_or_configured".to_string(), |
| 5448 | input_tokens: Some(123), |
| 5449 | output_tokens: Some(45), |
| 5450 | prompt_cache_hit_tokens: Some(10), |
| 5451 | prompt_cache_miss_tokens: None, |
| 5452 | prompt_cache_write_tokens: None, |
| 5453 | reasoning_tokens: Some(3), |
| 5454 | usage_status: ExecUsageStatus::Complete, |
| 5455 | stop_reason: None, |
| 5456 | codewhale_max_output_tokens: Some(384_000), |
| 5457 | codewhale_max_output_tokens_source: Some("documented"), |
| 5458 | duration_ms: 2500, |
| 5459 | retry_count: None, |
| 5460 | approval_posture: "ask".to_string(), |
| 5461 | sandbox_posture: "workspace-write".to_string(), |
| 5462 | binary_sha256: Some("sha256:binary".to_string()), |
| 5463 | config_sha256: None, |
| 5464 | prompt_sha256: "sha256:prompt".to_string(), |
| 5465 | tool_catalog_sha256: Some("sha256:tools".to_string()), |
| 5466 | input_analysis: ExecStreamInputAnalysis::default(), |
| 5467 | visible_final_answer_chars: 17, |
| 5468 | visible_final_answer_excerpt: "the visible reply".to_string(), |
| 5469 | session_id: exec_stream_session_ref(raw_session_id), |
| 5470 | resume_command: exec_stream_resume_hint(raw_session_id), |
| 5471 | workspace: "/tmp/work".to_string(), |
| 5472 | message_count: 4, |
| 5473 | status: Some("completed".to_string()), |
| 5474 | termination_reason: Some("resolved".to_string()), |
| 5475 | error_category: None, |
| 5476 | error: None, |
| 5477 | structured_output: None, |
| 5478 | }), |
| 5479 | }; |
| 5480 | |
| 5481 | let json = serde_json::to_string(&event).expect("serializes"); |
| 5482 | assert!(!json.contains('\n')); |
| 5483 | assert!(!json.contains(raw_session_id)); |
| 5484 | let parsed: serde_json::Value = serde_json::from_str(&json).expect("valid json"); |
| 5485 | assert_eq!(parsed["type"], "metadata"); |
| 5486 | assert_ne!(parsed["meta"]["session_id"], raw_session_id); |
| 5487 | assert!( |
| 5488 | parsed["meta"]["session_id"] |
| 5489 | .as_str() |
| 5490 | .unwrap() |
| 5491 | .starts_with("<redacted:") |
| 5492 | ); |
| 5493 | assert_eq!( |
| 5494 | parsed["meta"]["resume_command"], |
| 5495 | "codewhale exec --resume <session_capture.saved_session_id>" |
| 5496 | ); |
| 5497 | assert_eq!(parsed["meta"]["workspace"], "/tmp/work"); |
| 5498 | assert_eq!(parsed["meta"]["message_count"], 4); |
| 5499 | assert_eq!(parsed["meta"]["visible_final_answer_chars"], 17); |
| 5500 | assert_eq!( |
| 5501 | parsed["meta"]["visible_final_answer_excerpt"], |
| 5502 | "the visible reply" |
| 5503 | ); |
| 5504 | |
| 5505 | // Contract (#5946): the raw saved-session id is carried by exactly one |
| 5506 | // field, `session_capture.saved_session_id`. The `metadata` receipt |
| 5507 | // above stays fingerprint-only, and the capture's own `content` keeps |
| 5508 | // the same fingerprint so both surfaces can be correlated in a log. |
| 5509 | let capture = ExecStreamEvent::SessionCapture { |
| 5510 | content: exec_stream_session_ref(raw_session_id), |
| 5511 | saved_session_id: raw_session_id.to_string(), |
| 5512 | }; |
| 5513 | let capture_json = serde_json::to_string(&capture).expect("serializes"); |
| 5514 | let parsed_capture: serde_json::Value = |
| 5515 | serde_json::from_str(&capture_json).expect("valid json"); |
| 5516 | assert_eq!(parsed_capture["type"], "session_capture"); |
| 5517 | assert_eq!(parsed_capture["content"], parsed["meta"]["session_id"]); |
| 5518 | assert_ne!(parsed_capture["content"], raw_session_id); |
| 5519 | assert_eq!(parsed_capture["saved_session_id"], raw_session_id); |
| 5520 | assert!(parsed_capture.get("session_id").is_none(), "{capture_json}"); |
| 5521 | } |
| 5522 | |
| 5523 | #[test] |
| 5524 | fn exec_stream_final_answer_text_is_the_last_assistant_reply() { |
| 5525 | // Multi-step turn: pre-tool commentary, a tool result, then a |
| 5526 | // distinct final answer. The receipt must carry only the final |
| 5527 | // reply, not the cumulative stream output. |
| 5528 | let messages = vec![ |
| 5529 | Message { |
| 5530 | role: Role::User, |
| 5531 | content: vec![ContentBlock::Text { |
| 5532 | text: "write the report".to_string(), |
| 5533 | cache_control: None, |
| 5534 | }], |
| 5535 | }, |
| 5536 | Message { |
| 5537 | role: Role::Assistant, |
| 5538 | content: vec![ContentBlock::Text { |
| 5539 | text: "let me check the workspace first".to_string(), |
| 5540 | cache_control: None, |
| 5541 | }], |
| 5542 | }, |
| 5543 | Message { |
| 5544 | role: Role::User, |
| 5545 | content: vec![ContentBlock::ToolResult { |
| 5546 | execution_id: None, |
| 5547 | tool_use_id: "call-1".to_string(), |
| 5548 | content: "listed files".to_string(), |
| 5549 | is_error: Some(false), |
| 5550 | content_blocks: None, |
| 5551 | }], |
| 5552 | }, |
| 5553 | Message { |
| 5554 | role: Role::Assistant, |
| 5555 | content: vec![ |
| 5556 | ContentBlock::thinking("final reasoning"), |
| 5557 | ContentBlock::Text { |
| 5558 | text: "the final report".to_string(), |
| 5559 | cache_control: None, |
| 5560 | }, |
| 5561 | ], |
| 5562 | }, |
| 5563 | ]; |
| 5564 | assert_eq!( |
| 5565 | exec_stream_final_answer_text(&messages, true), |
| 5566 | Some("the final report".to_string()) |
| 5567 | ); |
| 5568 | } |
| 5569 | |
| 5570 | #[test] |
| 5571 | fn exec_stream_final_answer_text_never_reuses_a_resumed_turn_reply() { |
| 5572 | let mut messages = vec![ |
| 5573 | Message { |
| 5574 | role: Role::User, |
| 5575 | content: vec![ContentBlock::Text { |
| 5576 | text: "old prompt".into(), |
| 5577 | cache_control: None, |
| 5578 | }], |
| 5579 | }, |
| 5580 | Message { |
| 5581 | role: Role::Assistant, |
| 5582 | content: vec![ContentBlock::Text { |
| 5583 | text: "old reply must not be delivered again".into(), |
| 5584 | cache_control: None, |
| 5585 | }], |
| 5586 | }, |
| 5587 | ]; |
| 5588 | // The synchronization event can precede acceptance of the new prompt. |
| 5589 | assert_eq!(exec_stream_final_answer_text(&messages, false), None); |
| 5590 | messages.push(Message { |
| 5591 | role: Role::User, |
| 5592 | content: vec![ContentBlock::Text { |
| 5593 | text: "new prompt that fails before an answer".into(), |
| 5594 | cache_control: None, |
| 5595 | }], |
| 5596 | }); |
| 5597 | assert_eq!(exec_stream_final_answer_text(&messages, true), None); |
| 5598 | messages.push(Message { |
| 5599 | role: Role::InterruptedAssistant, |
| 5600 | content: vec![ContentBlock::Text { |
| 5601 | text: "current partial reply".into(), |
| 5602 | cache_control: None, |
| 5603 | }], |
| 5604 | }); |
| 5605 | assert_eq!( |
| 5606 | exec_stream_final_answer_text(&messages, true).as_deref(), |
| 5607 | Some("current partial reply") |
| 5608 | ); |
| 5609 | // Tool results are user-role records inside this same turn. |
| 5610 | messages.push(Message { |
| 5611 | role: Role::User, |
| 5612 | content: vec![ContentBlock::ToolResult { |
| 5613 | execution_id: None, |
| 5614 | tool_use_id: "call-current".into(), |
| 5615 | content: "result".into(), |
| 5616 | is_error: None, |
| 5617 | content_blocks: None, |
| 5618 | }], |
| 5619 | }); |
| 5620 | assert_eq!( |
| 5621 | exec_stream_final_answer_text(&messages, true).as_deref(), |
| 5622 | Some("current partial reply") |
| 5623 | ); |
| 5624 | } |
| 5625 | |
| 5626 | #[test] |
| 5627 | fn exec_stream_final_answer_text_requires_assistant_text() { |
| 5628 | assert_eq!(exec_stream_final_answer_text(&[], true), None); |
| 5629 | let user_only = vec![Message { |
| 5630 | role: Role::User, |
| 5631 | content: vec![ContentBlock::Text { |
| 5632 | text: "prompt".to_string(), |
| 5633 | cache_control: None, |
| 5634 | }], |
| 5635 | }]; |
| 5636 | assert_eq!(exec_stream_final_answer_text(&user_only, true), None); |
| 5637 | let textless_assistant = vec![Message { |
| 5638 | role: Role::Assistant, |
| 5639 | content: vec![ContentBlock::thinking("reasoning only")], |
| 5640 | }]; |
| 5641 | assert_eq!( |
| 5642 | exec_stream_final_answer_text(&textless_assistant, true), |
| 5643 | None |
| 5644 | ); |
| 5645 | } |
| 5646 | |
| 5647 | #[test] |
| 5648 | fn exec_stream_input_analysis_reports_prompt_composition() { |
| 5649 | let system = SystemPrompt::Text("system rules".to_string()); |
| 5650 | let messages = vec![ |
| 5651 | Message { |
| 5652 | role: Role::User, |
| 5653 | content: vec![ContentBlock::Text { |
| 5654 | text: "run tests".to_string(), |
| 5655 | cache_control: None, |
| 5656 | }], |
| 5657 | }, |
| 5658 | Message { |
| 5659 | role: Role::Assistant, |
| 5660 | content: vec![ |
| 5661 | ContentBlock::thinking("checking context"), |
| 5662 | ContentBlock::Text { |
| 5663 | text: "working".to_string(), |
| 5664 | cache_control: None, |
| 5665 | }, |
| 5666 | ContentBlock::ToolUse { |
| 5667 | execution_id: None, |
| 5668 | id: "call-1".to_string(), |
| 5669 | name: "exec_shell".to_string(), |
| 5670 | input: serde_json::json!({"command": "cargo test"}), |
| 5671 | caller: None, |
| 5672 | thought_signature: None, |
| 5673 | }, |
| 5674 | ], |
| 5675 | }, |
| 5676 | Message { |
| 5677 | role: Role::User, |
| 5678 | content: vec![ContentBlock::ToolResult { |
| 5679 | execution_id: None, |
| 5680 | tool_use_id: "call-1".to_string(), |
| 5681 | content: "stdout line\nstderr line".to_string(), |
| 5682 | is_error: Some(false), |
| 5683 | content_blocks: Some(vec![serde_json::json!({ |
| 5684 | "type": "text", |
| 5685 | "text": "structured output" |
| 5686 | })]), |
| 5687 | }], |
| 5688 | }, |
| 5689 | ]; |
| 5690 | |
| 5691 | let analysis = exec_stream_input_analysis(&messages, Some(&system)); |
| 5692 | |
| 5693 | assert_eq!(analysis.user_message_count, 2); |
| 5694 | assert_eq!(analysis.assistant_message_count, 1); |
| 5695 | assert_eq!(analysis.tool_message_count, 0); |
| 5696 | assert_eq!(analysis.tool_use_count, 1); |
| 5697 | assert_eq!(analysis.tool_result_count, 1); |
| 5698 | assert_eq!(analysis.thinking_chars, "checking context".chars().count()); |
| 5699 | assert!(analysis.text_chars >= "run testsworking".chars().count()); |
| 5700 | assert!(analysis.tool_use_input_chars > 0); |
| 5701 | assert!(analysis.tool_result_chars >= "stdout line\nstderr line".chars().count()); |
| 5702 | assert!(analysis.estimated_system_tokens > 0); |
| 5703 | assert!(analysis.estimated_message_content_tokens > 0); |
| 5704 | assert!( |
| 5705 | analysis.estimated_request_tokens |
| 5706 | >= analysis.estimated_system_tokens |
| 5707 | + analysis.estimated_message_content_tokens |
| 5708 | + analysis.estimated_framing_tokens |
| 5709 | ); |
| 5710 | } |
| 5711 | |
| 5712 | #[test] |
| 5713 | fn exec_text_session_breadcrumbs_use_compact_ids() { |
| 5714 | let session_id = "1234567890abcdef"; |
| 5715 | |
| 5716 | assert_eq!(exec_saved_session_line(session_id), "session: 12345678"); |
| 5717 | assert_eq!( |
| 5718 | exec_resumed_session_line(session_id), |
| 5719 | "resumed session: 12345678" |
| 5720 | ); |
| 5721 | assert!(!exec_saved_session_line(session_id).contains(session_id)); |
| 5722 | assert!(!exec_resumed_session_line(session_id).contains(session_id)); |
| 5723 | } |
| 5724 | |
| 5725 | #[test] |
| 5726 | fn sandbox_denial_fallback_preserves_approval_required_termination() { |
| 5727 | let mut summary = ExecSummary::default(); |
| 5728 | let mut last_error_category = None; |
| 5729 | summary.apply_turn_complete_error_summary( |
| 5730 | codewhale_engine::core::events::TurnOutcomeStatus::Failed, |
| 5731 | None, |
| 5732 | true, |
| 5733 | &mut last_error_category, |
| 5734 | ); |
| 5735 | assert_eq!( |
| 5736 | summary.error.as_deref(), |
| 5737 | Some( |
| 5738 | "exec turn failed after sandbox denial; explicit sandbox elevation was not authorized" |
| 5739 | ) |
| 5740 | ); |
| 5741 | assert_eq!(last_error_category, None); |
| 5742 | assert_eq!(summary.error_category, None); |
| 5743 | let termination = codewhale_engine::core::termination::classify_turn_termination( |
| 5744 | codewhale_engine::core::events::TurnOutcomeStatus::Failed, |
| 5745 | last_error_category, |
| 5746 | false, |
| 5747 | true, |
| 5748 | ); |
| 5749 | assert_eq!( |
| 5750 | termination, |
| 5751 | codewhale_engine::core::termination::RunTerminationReason::ApprovalRequired |
| 5752 | ); |
| 5753 | |
| 5754 | let mut timed_out_summary = ExecSummary::default(); |
| 5755 | let mut timed_out_category = None; |
| 5756 | timed_out_summary.apply_turn_complete_error_summary( |
| 5757 | codewhale_engine::core::events::TurnOutcomeStatus::Failed, |
| 5758 | Some("upstream request timed out".to_string()), |
| 5759 | true, |
| 5760 | &mut timed_out_category, |
| 5761 | ); |
| 5762 | assert_eq!( |
| 5763 | timed_out_category, |
| 5764 | Some(codewhale_error_taxonomy::ErrorCategory::Timeout) |
| 5765 | ); |
| 5766 | let timed_out_termination = codewhale_engine::core::termination::classify_turn_termination( |
| 5767 | codewhale_engine::core::events::TurnOutcomeStatus::Failed, |
| 5768 | timed_out_category, |
| 5769 | false, |
| 5770 | true, |
| 5771 | ); |
| 5772 | assert_eq!( |
| 5773 | timed_out_termination, |
| 5774 | codewhale_engine::core::termination::RunTerminationReason::Timeout |
| 5775 | ); |
| 5776 | } |
| 5777 | |
| 5778 | #[test] |
| 5779 | fn exec_subagent_lifecycle_events_persist_to_audit_log() { |
| 5780 | let _lock = codewhale_runtime::test_support::lock_test_env(); |
| 5781 | let temp = tempfile::TempDir::new().expect("tempdir"); |
| 5782 | let home = temp.path().join("codewhale-home"); |
| 5783 | let _guard = codewhale_runtime::test_support::EnvVarGuard::set("CODEWHALE_HOME", &home); |
| 5784 | |
| 5785 | let spawned = codewhale_engine::core::events::Event::AgentSpawned { |
| 5786 | owner_session_id: "exec-sess-1".to_string(), |
| 5787 | id: "exec-agent-1".to_string(), |
| 5788 | prompt: "secret prompt must not be logged".to_string(), |
| 5789 | worker_status: Some(codewhale_engine::tools::subagent::AgentWorkerStatus::Running), |
| 5790 | parent_run_id: Some("run-1".to_string()), |
| 5791 | spawn_depth: 1, |
| 5792 | model: "deepseek-chat".to_string(), |
| 5793 | route_source: None, |
| 5794 | display_name: Some("reviewer".to_string()), |
| 5795 | }; |
| 5796 | let completed = codewhale_engine::core::events::Event::AgentComplete { |
| 5797 | owner_session_id: "exec-sess-1".to_string(), |
| 5798 | id: "exec-agent-1".to_string(), |
| 5799 | result: "secret result must not be logged".to_string(), |
| 5800 | outcome: Some(codewhale_engine::tools::subagent::SubAgentStatus::Completed), |
| 5801 | limit_kind: None, |
| 5802 | parent_run_id: Some("run-1".to_string()), |
| 5803 | spawn_depth: Some(1), |
| 5804 | continuable: Some(false), |
| 5805 | usage: Some(codewhale_engine::tools::subagent::AgentRunUsage { |
| 5806 | status: "reported".to_string(), |
| 5807 | input_tokens: Some(400), |
| 5808 | output_tokens: Some(120), |
| 5809 | total_tokens: Some(520), |
| 5810 | cost_microusd: Some(85), |
| 5811 | note: String::new(), |
| 5812 | }), |
| 5813 | display_name: Some("reviewer".to_string()), |
| 5814 | }; |
| 5815 | |
| 5816 | assert!(codewhale_engine::tools::subagent::log_subagent_lifecycle_audit(&spawned)); |
| 5817 | assert!(codewhale_engine::tools::subagent::log_subagent_lifecycle_audit(&completed)); |
| 5818 | |
| 5819 | let log = std::fs::read_to_string(home.join("audit.log")).expect("audit.log"); |
| 5820 | let lines: Vec<serde_json::Value> = log |
| 5821 | .lines() |
| 5822 | .map(|line| serde_json::from_str(line).expect("audit json")) |
| 5823 | .collect(); |
| 5824 | assert_eq!(lines.len(), 2); |
| 5825 | assert_eq!(lines[0]["event"], "agent.spawned"); |
| 5826 | assert_eq!(lines[0]["details"]["agent_id"], "exec-agent-1"); |
| 5827 | assert_eq!(lines[0]["details"]["session_id"], "exec-sess-1"); |
| 5828 | assert_eq!(lines[0]["details"]["model"], "deepseek-chat"); |
| 5829 | assert_eq!(lines[0]["details"]["worker_status"], "running"); |
| 5830 | assert_eq!(lines[1]["event"], "agent.completed"); |
| 5831 | assert_eq!(lines[1]["details"]["agent_id"], "exec-agent-1"); |
| 5832 | assert_eq!(lines[1]["details"]["worker_status"], "completed"); |
| 5833 | assert_eq!(lines[1]["details"]["usage"]["input_tokens"], 400); |
| 5834 | assert_eq!(lines[1]["details"]["usage"]["output_tokens"], 120); |
| 5835 | assert_eq!(lines[1]["details"]["usage"]["total_tokens"], 520); |
| 5836 | assert!(!log.contains("secret prompt")); |
| 5837 | assert!(!log.contains("secret result")); |
| 5838 | } |
| 5839 | } |
| 5840 |