| 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 | //! Extracted verbatim from `lib.rs` (#5586, the issue's prescribed |
| 6 | //! engine-config-assembly cut). The two functions were crate-private in |
| 7 | //! the root and are `pub(crate)` here purely so the root's glob re-export |
| 8 | //! keeps the dispatch site and tests resolving unchanged. |
| 9 | |
| 10 | use super::*; |
| 11 | use crate::core::ops::TurnSpec; |
| 12 | |
| 13 | /// Resolve the headless `exec` model-step ceiling. |
| 14 | /// |
| 15 | /// Omission leaves model steps uncapped. Clap rejects `--max-turns 0`; |
| 16 | /// explicit positive values retain the documented finite range. |
| 17 | pub(crate) fn exec_max_steps(max_turns: Option<u32>) -> u32 { |
| 18 | crate::core::engine::turn_budget::resolve_max_model_steps(max_turns) |
| 19 | } |
| 20 | |
| 21 | /// Default-denied tools for headless `exec`, on top of the operator's own |
| 22 | /// `--disallowed-tools` flag. |
| 23 | /// |
| 24 | /// A headless run has no responder for `request_user_input`, so offering the |
| 25 | /// tool can only stall the run until the turn wall clock, or forever with |
| 26 | /// `[tools] user_input_timeout_seconds = 0`. Withholding it is the default |
| 27 | /// form of the operator workaround (`--disallowed-tools request_user_input`): |
| 28 | /// the model reports the tool absent and finishes instead of parking. This |
| 29 | /// stays unconditional: there is no channel on which a one-shot CLI run |
| 30 | /// could answer, so advertising the tool cannot work. |
| 31 | pub(crate) fn exec_disallowed_tools(disallowed_tools: Option<Vec<String>>) -> Option<Vec<String>> { |
| 32 | use crate::core::engine::tool_catalog::REQUEST_USER_INPUT_NAME; |
| 33 | let mut disallowed = disallowed_tools.unwrap_or_default(); |
| 34 | if !disallowed |
| 35 | .iter() |
| 36 | .any(|tool| tool.as_str() == REQUEST_USER_INPUT_NAME) |
| 37 | { |
| 38 | disallowed.push(REQUEST_USER_INPUT_NAME.to_string()); |
| 39 | } |
| 40 | Some(disallowed) |
| 41 | } |
| 42 | |
| 43 | type ExecSettlementProbe = std::pin::Pin< |
| 44 | Box<dyn std::future::Future<Output = Result<crate::core::ops::SubAgentSettlement>> + Send>, |
| 45 | >; |
| 46 | |
| 47 | /// Read the existing Engine stream through the one-shot host's final boundary. |
| 48 | /// Successful parent receipts remain pending while admitted children or their |
| 49 | /// completion inbox can still produce another normal Engine turn. This owns |
| 50 | /// only the deferred output receipt, never child execution or a turn loop. |
| 51 | pub(crate) struct ExecAgentEvents { |
| 52 | handle: crate::core::engine::EngineHandle, |
| 53 | deadline: tokio::time::Instant, |
| 54 | terminal: Option<crate::core::events::Event>, |
| 55 | probe: Option<ExecSettlementProbe>, |
| 56 | next_probe_at: tokio::time::Instant, |
| 57 | in_flight_usage: codewhale_models::Usage, |
| 58 | } |
| 59 | |
| 60 | impl ExecAgentEvents { |
| 61 | pub(crate) fn new(handle: crate::core::engine::EngineHandle, deadline: Instant) -> Self { |
| 62 | Self { |
| 63 | handle, |
| 64 | deadline: deadline.into(), |
| 65 | terminal: None, |
| 66 | probe: None, |
| 67 | next_probe_at: tokio::time::Instant::now(), |
| 68 | in_flight_usage: codewhale_models::Usage::default(), |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | fn stop_settlement( |
| 73 | &mut self, |
| 74 | status: crate::core::events::TurnOutcomeStatus, |
| 75 | error: String, |
| 76 | ) -> crate::core::events::Event { |
| 77 | use crate::core::events::Event; |
| 78 | self.handle |
| 79 | .cancel_with_reason(crate::core::engine::CancelReason::External); |
| 80 | // Cancellation is out of band; shutdown remains in the existing |
| 81 | // Engine mailbox so it also cancels detached session children. |
| 82 | let _ = self.handle.try_send(crate::core::ops::Op::Shutdown); |
| 83 | self.probe = None; |
| 84 | let mut terminal = self.terminal.take().expect("pending parent receipt"); |
| 85 | if let Event::TurnComplete { |
| 86 | status: terminal_status, |
| 87 | error: terminal_error, |
| 88 | usage, |
| 89 | parent_route_usage, |
| 90 | routed_usage_dropped_records, |
| 91 | .. |
| 92 | } = &mut terminal |
| 93 | { |
| 94 | *terminal_status = status; |
| 95 | *terminal_error = Some(error); |
| 96 | crate::core::turn::add_usage_to(usage, &self.in_flight_usage); |
| 97 | crate::core::turn::add_usage_to(parent_route_usage, &self.in_flight_usage); |
| 98 | // The host cannot prove usage settlement after abandoning the |
| 99 | // inbox. Keep reported usage and explicitly mark coverage partial. |
| 100 | *routed_usage_dropped_records = routed_usage_dropped_records.saturating_add(1); |
| 101 | } |
| 102 | self.in_flight_usage = codewhale_models::Usage::default(); |
| 103 | terminal |
| 104 | } |
| 105 | |
| 106 | pub(crate) async fn next(&mut self) -> Option<crate::core::events::Event> { |
| 107 | use crate::core::events::{Event, TurnOutcomeStatus}; |
| 108 | // Keep the streamed event on the stack instead of allocating another |
| 109 | // box for every token merely to equalize the two small control arms. |
| 110 | #[allow(clippy::large_enum_variant)] |
| 111 | enum Input { |
| 112 | Event(Option<Event>), |
| 113 | Probe(Result<crate::core::ops::SubAgentSettlement>), |
| 114 | Poll, |
| 115 | } |
| 116 | loop { |
| 117 | if matches!( |
| 118 | self.terminal, |
| 119 | Some(Event::TurnComplete { status, .. }) if status != TurnOutcomeStatus::Completed |
| 120 | ) { |
| 121 | return self.terminal.take(); |
| 122 | } |
| 123 | let settling = self.terminal.is_some(); |
| 124 | if settling && self.handle.is_cancelled() { |
| 125 | return Some(self.stop_settlement( |
| 126 | TurnOutcomeStatus::Interrupted, |
| 127 | "Headless exec cancelled while settling children; recorded usage is partial." |
| 128 | .to_string(), |
| 129 | )); |
| 130 | } |
| 131 | if settling && tokio::time::Instant::now() >= self.deadline { |
| 132 | return Some(self.stop_settlement( |
| 133 | TurnOutcomeStatus::Failed, |
| 134 | "Headless exec wall-clock budget exhausted while settling children; recorded usage is partial." |
| 135 | .to_string(), |
| 136 | )); |
| 137 | } |
| 138 | if settling && self.probe.is_none() && tokio::time::Instant::now() >= self.next_probe_at |
| 139 | { |
| 140 | let handle = self.handle.clone(); |
| 141 | self.probe = Some(Box::pin( |
| 142 | async move { handle.get_subagent_settlement().await }, |
| 143 | )); |
| 144 | } |
| 145 | let probing = self.probe.is_some(); |
| 146 | let wake_at = self.deadline.min(if probing { |
| 147 | tokio::time::Instant::now() + Duration::from_millis(250) |
| 148 | } else { |
| 149 | self.next_probe_at |
| 150 | }); |
| 151 | let input = { |
| 152 | let mut events = self.handle.rx_event.write().await; |
| 153 | tokio::select! { |
| 154 | biased; |
| 155 | // Drain queued SessionUpdated/TurnComplete events before |
| 156 | // accepting the later actor-owned idle receipt. |
| 157 | event = events.recv() => Input::Event(event), |
| 158 | result = async { self.probe.as_mut().expect("active probe").await }, if probing => Input::Probe(result), |
| 159 | () = tokio::time::sleep_until(wake_at), if settling => Input::Poll, |
| 160 | } |
| 161 | }; |
| 162 | match input { |
| 163 | Input::Poll => {} |
| 164 | Input::Probe(Ok(snapshot)) if snapshot.is_settled() => { |
| 165 | self.probe = None; |
| 166 | return self.terminal.take(); |
| 167 | } |
| 168 | Input::Probe(Ok(_)) => { |
| 169 | self.probe = None; |
| 170 | self.next_probe_at = tokio::time::Instant::now() + Duration::from_millis(250); |
| 171 | } |
| 172 | Input::Probe(Err(error)) => { |
| 173 | return Some(self.stop_settlement( |
| 174 | TurnOutcomeStatus::Failed, |
| 175 | format!( |
| 176 | "Cannot verify child settlement: {error}; recorded usage is partial." |
| 177 | ), |
| 178 | )); |
| 179 | } |
| 180 | Input::Event(None) if settling => { |
| 181 | return Some(self.stop_settlement( |
| 182 | TurnOutcomeStatus::Failed, |
| 183 | "Engine event channel closed before child settlement; recorded usage is partial." |
| 184 | .to_string(), |
| 185 | )); |
| 186 | } |
| 187 | Input::Event(None) => return None, |
| 188 | Input::Event(Some(mut event)) => { |
| 189 | match &mut event { |
| 190 | Event::TurnComplete { |
| 191 | usage, |
| 192 | parent_route_usage, |
| 193 | routed_usage_dropped_records, |
| 194 | status, |
| 195 | error, |
| 196 | .. |
| 197 | } => { |
| 198 | if let Some(Event::TurnComplete { |
| 199 | usage: prior_usage, |
| 200 | parent_route_usage: prior_parent_usage, |
| 201 | routed_usage_dropped_records: prior_dropped, |
| 202 | .. |
| 203 | }) = self.terminal.take() |
| 204 | { |
| 205 | crate::core::turn::add_usage_to(usage, &prior_usage); |
| 206 | crate::core::turn::add_usage_to( |
| 207 | parent_route_usage, |
| 208 | &prior_parent_usage, |
| 209 | ); |
| 210 | *routed_usage_dropped_records = |
| 211 | routed_usage_dropped_records.saturating_add(prior_dropped); |
| 212 | } |
| 213 | self.in_flight_usage = codewhale_models::Usage::default(); |
| 214 | if *status == TurnOutcomeStatus::Completed && error.is_none() { |
| 215 | self.terminal = Some(event); |
| 216 | self.next_probe_at = tokio::time::Instant::now(); |
| 217 | continue; |
| 218 | } |
| 219 | } |
| 220 | Event::TurnUsage { usage, .. } => { |
| 221 | crate::core::turn::add_usage_to(&mut self.in_flight_usage, usage); |
| 222 | } |
| 223 | Event::Error { envelope, .. } |
| 224 | if settling && exec_error_event_is_fatal(envelope) => |
| 225 | { |
| 226 | let terminal = self.stop_settlement( |
| 227 | TurnOutcomeStatus::Failed, |
| 228 | format!( |
| 229 | "{}; child settlement stopped and recorded usage is partial.", |
| 230 | envelope.message |
| 231 | ), |
| 232 | ); |
| 233 | self.terminal = Some(terminal); |
| 234 | } |
| 235 | _ => {} |
| 236 | } |
| 237 | return Some(event); |
| 238 | } |
| 239 | } |
| 240 | } |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | /// Attach the durable automation store headless `exec` inspects. |
| 245 | /// |
| 246 | /// Headless exec builds its catalog from the same tool surface the TUI and the |
| 247 | /// Runtime host do, so it advertises `automation` and `send_later` whether or |
| 248 | /// not the store behind them is attached. Left unattached, every call failed |
| 249 | /// "AutomationManager is not attached" — the tool was real and the service was |
| 250 | /// missing. This opens the same store those two hosts open: a shared directory |
| 251 | /// guarded per transaction by its own file locks (`AutomationManager::open`), |
| 252 | /// so it adds no second store, no scheduler, and no second scheduling |
| 253 | /// authority. |
| 254 | /// |
| 255 | /// What exec deliberately does not take is the Runtime's task-execution lease. |
| 256 | /// That lease is exclusive (`TaskExecutionLease::new`) and a one-shot host must |
| 257 | /// neither contend with it nor recover work from the process that holds it. So |
| 258 | /// the manager returned here is *unbound*: inspection works, and everything |
| 259 | /// that would promise dispatch is refused by the tool's own admission check |
| 260 | /// (`tools::automation::require_dispatch_owner`) rather than persisting a |
| 261 | /// schedule nothing would honor. |
| 262 | /// |
| 263 | /// Fleet worker subprocesses get nothing, keeping the narrowed envelope they |
| 264 | /// were launched with alongside the empty plugin registry and disabled |
| 265 | /// subagents. A store that cannot be opened is reported, never swallowed: |
| 266 | /// both other hosts fail startup on it, so exec does too instead of |
| 267 | /// advertising an automation surface it silently cannot serve. |
| 268 | pub(crate) fn exec_automation_services( |
| 269 | fleet_authority_active: bool, |
| 270 | ) -> Result<Option<crate::automation_manager::SharedAutomationManager>> { |
| 271 | if fleet_authority_active { |
| 272 | return Ok(None); |
| 273 | } |
| 274 | let service = crate::automation_manager::AutomationManager::default_location() |
| 275 | .context("open the automation store for headless exec")?; |
| 276 | Ok(Some(std::sync::Arc::new(tokio::sync::Mutex::new(service)))) |
| 277 | } |
| 278 | |
| 279 | #[allow(clippy::too_many_arguments)] |
| 280 | pub(crate) async fn run_exec_agent( |
| 281 | config: &Config, |
| 282 | model: &str, |
| 283 | prompt: &str, |
| 284 | workspace: PathBuf, |
| 285 | max_subagents: usize, |
| 286 | auto_approve: bool, |
| 287 | allow_sandbox_elevation: bool, |
| 288 | explicit_sandbox: Option<&str>, |
| 289 | trust_mode: bool, |
| 290 | json_output: bool, |
| 291 | resume_session: Option<session_manager::SavedSession>, |
| 292 | force_configured_route: bool, |
| 293 | output_format: ExecOutputFormat, |
| 294 | max_turns: u32, |
| 295 | max_tool_calls: Option<u32>, |
| 296 | allowed_tools: Option<Vec<String>>, |
| 297 | disallowed_tools: Option<Vec<String>>, |
| 298 | append_system_prompt: Option<String>, |
| 299 | tool_authority_json: Option<String>, |
| 300 | exec_hooks_enabled: bool, |
| 301 | plugin_registry: std::sync::Arc<crate::plugins::PluginRegistry>, |
| 302 | ) -> Result<()> { |
| 303 | use crate::compaction::CompactionConfig; |
| 304 | use crate::core::engine::{EngineConfig, spawn_engine}; |
| 305 | use crate::core::events::Event; |
| 306 | use crate::core::ops::Op; |
| 307 | use crate::tools::plan::new_shared_plan_state; |
| 308 | use crate::tools::todo::new_shared_todo_list; |
| 309 | use codewhale_config::AppMode; |
| 310 | use codewhale_execpolicy::ApprovalMode; |
| 311 | |
| 312 | // Withhold `request_user_input`; a headless run has no responder. |
| 313 | let disallowed_tools = exec_disallowed_tools(disallowed_tools); |
| 314 | |
| 315 | // Headless exec registers the model-facing notify tool too. Project the |
| 316 | // final merged config before tool setup so `off`, quiet/category gates, |
| 317 | // and explicit `always` are truthful outside the interactive TUI. With no |
| 318 | // focus-reporting channel, fail closed to focused; only explicit `always` |
| 319 | // may authorize a headless desktop notification. |
| 320 | crate::tui::notifications::set_terminal_focused(true); |
| 321 | let _ = crate::tui::notifications::settings(config); |
| 322 | |
| 323 | validate_exec_tool_authority_resume(tool_authority_json.as_deref(), resume_session.is_some())?; |
| 324 | let fleet_authority = tool_authority_json |
| 325 | .as_deref() |
| 326 | .map(crate::tools::spec::ToolAuthorityEnvelope::from_json) |
| 327 | .transpose() |
| 328 | .map_err(anyhow::Error::msg)?; |
| 329 | let fleet_authority_active = fleet_authority.is_some(); |
| 330 | let outer_network_access = fleet_authority |
| 331 | .as_ref() |
| 332 | .and_then(|authority| authority.network_access); |
| 333 | let outer_shell_authority = fleet_authority |
| 334 | .as_ref() |
| 335 | .map(|authority| authority.shell) |
| 336 | .unwrap_or_default(); |
| 337 | if let Some(envelope) = fleet_authority { |
| 338 | crate::tools::spec::install_process_tool_authority(envelope).map_err(anyhow::Error::msg)?; |
| 339 | } |
| 340 | |
| 341 | let fleet_capture = match ( |
| 342 | std::env::var("CODEWHALE_FLEET_CAPTURE_ID").ok(), |
| 343 | std::env::var_os("CODEWHALE_FLEET_CAPTURE_DIR"), |
| 344 | ) { |
| 345 | (Some(id), Some(dir)) => { |
| 346 | uuid::Uuid::parse_str(&id).context("invalid Fleet session capture id")?; |
| 347 | anyhow::ensure!( |
| 348 | resume_session.is_none(), |
| 349 | "Fleet capture cannot resume a session" |
| 350 | ); |
| 351 | let manager = SessionManager::new(PathBuf::from(dir))?; |
| 352 | match manager.load_session(&id) { |
| 353 | Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} |
| 354 | _ => anyhow::bail!("Fleet session capture id is already in use or unavailable"), |
| 355 | } |
| 356 | Some((id, manager)) |
| 357 | } |
| 358 | (None, None) => None, |
| 359 | _ => anyhow::bail!("incomplete Fleet session capture destination"), |
| 360 | }; |
| 361 | |
| 362 | let route = resolve_cli_exec_route(config, model, prompt, force_configured_route).await?; |
| 363 | let execution_config = config_for_cli_route(config, &route); |
| 364 | let auto_model = route.auto_model; |
| 365 | let effective_provider = route.provider; |
| 366 | let effective_model = route.model; |
| 367 | let validated_route = crate::route_runtime::resolve_runtime_route( |
| 368 | &execution_config, |
| 369 | effective_provider, |
| 370 | Some(&effective_model), |
| 371 | ) |
| 372 | .map_err(anyhow::Error::msg)? |
| 373 | .validate() |
| 374 | .map_err(anyhow::Error::msg)?; |
| 375 | let effective_provider_name = validated_route.identity.key.clone(); |
| 376 | let effective_provider_id = validated_route.identity.exact_id.clone(); |
| 377 | let (effective_provider_kind, effective_stream_provider_id) = |
| 378 | exec_stream_provider_route(&validated_route.identity); |
| 379 | let route_source = if auto_model { |
| 380 | "auto_resolver" |
| 381 | } else { |
| 382 | "explicit_or_configured" |
| 383 | } |
| 384 | .to_string(); |
| 385 | let exec_started = Instant::now(); |
| 386 | let prompt_sha256 = format!("sha256:{}", crate::hashing::sha256_hex(prompt.as_bytes())); |
| 387 | let binary_sha256 = current_binary_sha256(); |
| 388 | let approval_posture = if auto_approve { "auto_tools" } else { "ask" }.to_string(); |
| 389 | let sandbox_posture = explicit_sandbox.unwrap_or("configured_default").to_string(); |
| 390 | let active_route_limits = |
| 391 | crate::route_budget::known_route_limits(validated_route.candidate.limits()); |
| 392 | let max_subagents = if max_subagents == config.max_subagents_for_provider(config.api_provider()) |
| 393 | { |
| 394 | execution_config |
| 395 | .max_subagents_for_provider(effective_provider) |
| 396 | .clamp(1, MAX_SUBAGENTS) |
| 397 | } else { |
| 398 | max_subagents |
| 399 | }; |
| 400 | // A FIXED model with `--reasoning-effort auto` (the exact shape a Fleet |
| 401 | // worker subprocess launches with: `--model <exact> --reasoning-effort |
| 402 | // auto`) is still Auto. `auto_model` is a *model* decision and is false |
| 403 | // here, so deriving the auto flag from it left this path both raw and |
| 404 | // non-auto: the literal string `"auto"` travelled to the engine while the |
| 405 | // receipt claimed no Auto was in play. |
| 406 | let reasoning_effort_auto = route.auto_controls_reasoning; |
| 407 | // Resolve Auto against this run's prompt at the CLI boundary, exactly like |
| 408 | // `run_one_shot`/`run_one_shot_json` and the interactive launch path do, |
| 409 | // so the tier the engine (and the receipt below) sees is concrete. |
| 410 | let effective_reasoning_effort = route.reasoning_effort.and_then(|effort| { |
| 411 | cli_reasoning_effort_value_for_prompt(&execution_config, &effective_model, effort) |
| 412 | }); |
| 413 | |
| 414 | let settings = crate::settings::Settings::load().unwrap_or_default(); |
| 415 | let auto_compact_enabled = if crate::settings::Settings::auto_compact_explicitly_configured() { |
| 416 | settings.auto_compact |
| 417 | } else { |
| 418 | crate::route_budget::auto_compact_default_for_route( |
| 419 | effective_provider, |
| 420 | &effective_model, |
| 421 | active_route_limits, |
| 422 | ) |
| 423 | }; |
| 424 | let compaction = CompactionConfig { |
| 425 | enabled: auto_compact_enabled, |
| 426 | model: effective_model.clone(), |
| 427 | effective_context_window: Some(crate::route_budget::route_context_window_tokens( |
| 428 | effective_provider, |
| 429 | &effective_model, |
| 430 | active_route_limits, |
| 431 | )), |
| 432 | token_threshold: crate::route_budget::compaction_threshold_for_route_at_percent( |
| 433 | effective_provider, |
| 434 | &effective_model, |
| 435 | active_route_limits, |
| 436 | settings.auto_compact_threshold_percent, |
| 437 | ), |
| 438 | summary_instructions: execution_config.compaction_summary_instructions(), |
| 439 | retained_user_message_tokens: execution_config.compaction_retained_user_message_tokens(), |
| 440 | ..Default::default() |
| 441 | }; |
| 442 | |
| 443 | let network_policy = exec_network_policy(&execution_config, outer_network_access); |
| 444 | |
| 445 | let lsp_config = (!fleet_authority_active) |
| 446 | .then(|| { |
| 447 | execution_config |
| 448 | .lsp |
| 449 | .clone() |
| 450 | .map(crate::config::LspConfigToml::into_runtime) |
| 451 | }) |
| 452 | .flatten(); |
| 453 | let mut engine_features = execution_config.features(); |
| 454 | apply_fleet_engine_feature_caps( |
| 455 | &mut engine_features, |
| 456 | fleet_authority_active, |
| 457 | outer_network_access, |
| 458 | outer_shell_authority, |
| 459 | ); |
| 460 | if crate::core::allowlist_is_native_file_and_shell_only(allowed_tools.as_deref()) { |
| 461 | engine_features.disable(crate::features::Feature::Mcp); |
| 462 | } |
| 463 | let engine_plugin_registry = if fleet_authority_active { |
| 464 | std::sync::Arc::new(crate::plugins::PluginRegistry::empty(&workspace)) |
| 465 | } else { |
| 466 | plugin_registry |
| 467 | }; |
| 468 | // `exec --hooks` (#6099) is the operator's explicit opt-in: headless runs |
| 469 | // fire no hooks by default. When armed, the executor is the same one the |
| 470 | // TUI builds — global config, reviewed plugin snapshots, then trusted |
| 471 | // project `.codewhale/hooks.toml` — so `tool_call_before` can still deny |
| 472 | // and `shell_env` still applies. It is shared with the engine config, the |
| 473 | // turn's SendMessage op (which re-installs it into the engine), and the |
| 474 | // tool runtime services. Fleet workers never opt in: the narrowed |
| 475 | // authority envelope does not carry the operator's hook set into a child. |
| 476 | let exec_hook_executor = (exec_hooks_enabled && !fleet_authority_active).then(|| { |
| 477 | let hooks_config = crate::hooks::HooksConfig::load_with_project_and_plugins( |
| 478 | execution_config.hooks_config(), |
| 479 | &workspace, |
| 480 | Some(engine_plugin_registry.as_ref()), |
| 481 | ); |
| 482 | std::sync::Arc::new(crate::hooks::HookExecutor::new( |
| 483 | hooks_config, |
| 484 | workspace.clone(), |
| 485 | )) |
| 486 | }); |
| 487 | let exec_allow_shell = crate::tools::spec::fleet_exec_shell_enabled( |
| 488 | fleet_authority_active, |
| 489 | outer_shell_authority, |
| 490 | disallowed_tools.as_deref(), |
| 491 | ) || (!fleet_authority_active |
| 492 | && (auto_approve || execution_config.allow_shell())); |
| 493 | let persist_services_enabled = cfg!(unix) |
| 494 | && !fleet_authority_active |
| 495 | && exec_allow_shell |
| 496 | && explicit_sandbox |
| 497 | .is_some_and(|sandbox| sandbox.eq_ignore_ascii_case("danger-full-access")); |
| 498 | let exec_shell_manager = crate::tools::shell::new_shared_shell_manager(workspace.clone()); |
| 499 | let exec_automations = exec_automation_services(fleet_authority_active)?; |
| 500 | let runtime_services = crate::tools::spec::RuntimeToolServices { |
| 501 | shell_manager: Some(exec_shell_manager.clone()), |
| 502 | persist_services_enabled, |
| 503 | automations: exec_automations, |
| 504 | media_originals_dir: crate::media_originals::default_store_dir(), |
| 505 | hook_executor: exec_hook_executor.clone(), |
| 506 | ..crate::tools::spec::RuntimeToolServices::default() |
| 507 | }; |
| 508 | |
| 509 | let engine_config = EngineConfig { |
| 510 | model: effective_model.clone(), |
| 511 | active_route_limits, |
| 512 | workspace: workspace.clone(), |
| 513 | session_id: fleet_capture.as_ref().map(|(id, _)| id.clone()), |
| 514 | subagent_state_root: None, |
| 515 | plugin_registry: Some(std::sync::Arc::clone(&engine_plugin_registry)), |
| 516 | allow_shell: exec_allow_shell, |
| 517 | trust_mode, |
| 518 | notes_path: execution_config.notes_path(), |
| 519 | mcp_config_path: execution_config.mcp_config_path(), |
| 520 | // Non-interactive exec has no user-level MCP OAuth callback |
| 521 | // overrides; the loopback default applies. |
| 522 | mcp_oauth_callback_port: None, |
| 523 | mcp_oauth_callback_url: None, |
| 524 | skills_dir: execution_config.skills_dir(), |
| 525 | skills_scan_codewhale_only: execution_config.skills_config().scan_codewhale_only(), |
| 526 | instructions: { |
| 527 | let mut instrs: Vec<crate::prompts::InstructionSource> = execution_config |
| 528 | .instructions_paths() |
| 529 | .into_iter() |
| 530 | .map(Into::into) |
| 531 | .collect(); |
| 532 | if let Some(ref extra) = append_system_prompt { |
| 533 | instrs.push(crate::prompts::InstructionSource::Inline { |
| 534 | name: "cli:append-system-prompt".into(), |
| 535 | content: extra.clone(), |
| 536 | }); |
| 537 | } |
| 538 | instrs |
| 539 | }, |
| 540 | project_context_pack_enabled: execution_config.project_context_pack_enabled(), |
| 541 | translation_enabled: false, |
| 542 | max_steps: max_turns, |
| 543 | max_subagents, |
| 544 | max_admitted_subagents: execution_config |
| 545 | .max_admitted_subagents_for_provider(effective_provider) |
| 546 | .max(max_subagents), |
| 547 | launch_concurrency: execution_config.launch_concurrency_for_provider(effective_provider), |
| 548 | subagents_enabled: !fleet_authority_active |
| 549 | && execution_config.subagents_enabled_for_provider(effective_provider), |
| 550 | features: engine_features, |
| 551 | auto_review_policy: execution_config.auto_review_policy(), |
| 552 | compaction: compaction.clone(), |
| 553 | todos: new_shared_todo_list(), |
| 554 | plan_state: new_shared_plan_state(), |
| 555 | goal_state: crate::tools::goal::new_shared_goal_state(), |
| 556 | max_spawn_depth: if fleet_authority_active { |
| 557 | 0 |
| 558 | } else { |
| 559 | execution_config.subagent_max_spawn_depth_for_provider(effective_provider) |
| 560 | }, |
| 561 | network_policy, |
| 562 | snapshots_enabled: !fleet_authority_active && execution_config.snapshots_config().enabled, |
| 563 | snapshots_max_workspace_bytes: execution_config |
| 564 | .snapshots_config() |
| 565 | .max_workspace_gb |
| 566 | .saturating_mul(1024 * 1024 * 1024), |
| 567 | lsp_config, |
| 568 | runtime_services, |
| 569 | subagent_model_overrides: execution_config.subagent_model_overrides(), |
| 570 | fleet_roster: std::sync::Arc::new(crate::fleet::identity::load_effective_roster( |
| 571 | &execution_config.fleet_config(), |
| 572 | &workspace, |
| 573 | Some(engine_plugin_registry.as_ref()), |
| 574 | )), |
| 575 | subagent_api_timeout: std::time::Duration::from_secs( |
| 576 | execution_config.subagent_api_timeout_secs_for_provider(effective_provider), |
| 577 | ), |
| 578 | stream_chunk_timeout: std::time::Duration::from_secs( |
| 579 | execution_config.stream_chunk_timeout_secs(), |
| 580 | ), |
| 581 | turn_wall_clock: execution_config.turn_wall_clock(), |
| 582 | stream_max_content_bytes: execution_config.stream_max_content_bytes(), |
| 583 | stream_max_duration: execution_config.stream_max_duration(), |
| 584 | subagent_heartbeat_timeout: std::time::Duration::from_secs( |
| 585 | execution_config.subagent_heartbeat_timeout_secs_for_provider(effective_provider), |
| 586 | ), |
| 587 | prefer_bwrap: execution_config.prefer_bwrap.unwrap_or(false), |
| 588 | bwrap_extensions: crate::sandbox::BwrapMountExtensions { |
| 589 | read_only_roots: execution_config.bwrap_ro_roots.clone(), |
| 590 | device_roots: execution_config.bwrap_dev_roots.clone(), |
| 591 | }, |
| 592 | read_denylist: execution_config.read_denylist(), |
| 593 | memory_enabled: execution_config.memory_enabled(), |
| 594 | memory_path: execution_config.memory_path(), |
| 595 | speech_output_dir: execution_config.speech_output_dir(), |
| 596 | vision_config: execution_config.vision_model_config(), |
| 597 | strict_tool_mode: execution_config.strict_tool_mode.unwrap_or(false), |
| 598 | goal_objective: None, |
| 599 | goal_token_budget: None, |
| 600 | goal_status: crate::tools::goal::GoalStatus::Active, |
| 601 | goal_max_continuations: execution_config.goal_max_continuations(), |
| 602 | goal_continuation_delay_seconds: execution_config.goal_continuation_delay_seconds(), |
| 603 | goal_enforce_token_budget: execution_config.goal_enforce_token_budget(), |
| 604 | reasoning_only_max_reprompts: execution_config.reasoning_only_max_reprompts(), |
| 605 | reasoning_only_reprompt_message: Some( |
| 606 | execution_config |
| 607 | .reasoning_only_reprompt_message() |
| 608 | .to_string(), |
| 609 | ), |
| 610 | allowed_tools: allowed_tools.clone(), |
| 611 | disallowed_tools: disallowed_tools.clone(), |
| 612 | max_tool_calls, |
| 613 | hook_executor: exec_hook_executor.clone(), |
| 614 | locale_tag: codewhale_localization::resolve_locale(&settings.locale) |
| 615 | .tag() |
| 616 | .to_string(), |
| 617 | workshop: { |
| 618 | crate::tools::large_output_router::WorkshopConfig::install_active( |
| 619 | config.workshop.as_ref(), |
| 620 | ); |
| 621 | config.workshop.clone() |
| 622 | }, |
| 623 | search_provider: execution_config.search_provider(), |
| 624 | search_api_key: execution_config |
| 625 | .search |
| 626 | .as_ref() |
| 627 | .and_then(|s| s.api_key.clone()), |
| 628 | search_base_url: execution_config |
| 629 | .search |
| 630 | .as_ref() |
| 631 | .and_then(|s| s.base_url.clone()), |
| 632 | tools_always_load: if fleet_authority_active { |
| 633 | std::collections::HashSet::new() |
| 634 | } else { |
| 635 | execution_config.tools_always_load() |
| 636 | }, |
| 637 | user_input_limits: execution_config.user_input_limits(), |
| 638 | user_input_timeout: execution_config.user_input_timeout(), |
| 639 | goal_max_steps: None, |
| 640 | tools: if fleet_authority_active { |
| 641 | None |
| 642 | } else { |
| 643 | execution_config.tools.clone() |
| 644 | }, |
| 645 | verbosity: execution_config.verbosity.clone(), |
| 646 | workspace_follow_symlinks: settings.workspace_follow_symlinks, |
| 647 | exec_policy_engine: execution_config.exec_policy_engine.clone(), |
| 648 | terminal_chrome_enabled: false, |
| 649 | advisor_config: execution_config |
| 650 | .advisor |
| 651 | .as_ref() |
| 652 | .map(crate::tools::subagent::AdvisorConfig::from_toml) |
| 653 | .unwrap_or_else(crate::tools::subagent::AdvisorConfig::disabled), |
| 654 | }; |
| 655 | |
| 656 | let engine_handle = spawn_engine(engine_config, &execution_config); |
| 657 | // The Full Access posture travels in the op's auto_approve/approval_mode |
| 658 | // fields; modes no longer carry permission. |
| 659 | let mode = AppMode::Agent; |
| 660 | |
| 661 | let resuming_session = resume_session.is_some(); |
| 662 | let mut loaded_session_id = None; |
| 663 | if let Some(saved) = resume_session { |
| 664 | let saved_id = saved.metadata.id.clone(); |
| 665 | if saved.metadata.workspace != workspace && output_format == ExecOutputFormat::Text { |
| 666 | eprintln!( |
| 667 | "Warning: session {} was created in a different workspace ({}). Resuming anyway.", |
| 668 | truncate_id(&saved_id), |
| 669 | saved.metadata.workspace.display(), |
| 670 | ); |
| 671 | } |
| 672 | |
| 673 | engine_handle |
| 674 | .send(Op::SyncSession { |
| 675 | session_id: Some(saved_id.clone()), |
| 676 | messages: saved.messages, |
| 677 | system_prompt: saved.system_prompt.map(SystemPrompt::Text), |
| 678 | system_prompt_override: false, |
| 679 | model: saved.metadata.model, |
| 680 | workspace: saved.metadata.workspace, |
| 681 | mode, |
| 682 | }) |
| 683 | .await?; |
| 684 | loaded_session_id = Some(saved_id.clone()); |
| 685 | if output_format == ExecOutputFormat::Text && !json_output { |
| 686 | eprintln!("{}", exec_resumed_session_line(&saved_id)); |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | // Lifecycle outbox (`[lifecycle_outbox]`): headless `codewhale exec` |
| 691 | // gets the same turn boundaries as the interactive TUI. Disabled |
| 692 | // (all emits no-op) when the config has no path. |
| 693 | let lifecycle_outbox = config |
| 694 | .lifecycle_outbox |
| 695 | .as_ref() |
| 696 | .map(|outbox| { |
| 697 | codewhale_hooks::LifecycleOutbox::new( |
| 698 | outbox.path.clone(), |
| 699 | outbox.webhook_url.clone(), |
| 700 | outbox.webhook_token.clone(), |
| 701 | ) |
| 702 | }) |
| 703 | .unwrap_or_else(codewhale_hooks::LifecycleOutbox::disabled); |
| 704 | // Wall clock for the outbox `turn_end` duration. `exec` never receives |
| 705 | // a TurnStarted engine event, so the start is marked at the same |
| 706 | // `Op::SendMessage` boundary where `turn_start` is emitted below. |
| 707 | let exec_turn_started_at = Instant::now(); |
| 708 | |
| 709 | engine_handle |
| 710 | .send(Op::SendMessage(TurnSpec { |
| 711 | max_output_tokens: None, |
| 712 | content: prompt.to_string(), |
| 713 | images: Vec::new(), |
| 714 | mode, |
| 715 | route: Box::new(validated_route.into_resolved()), |
| 716 | compaction: Box::new(compaction.clone()), |
| 717 | initial_routed_usage: Box::default(), |
| 718 | goal_objective: None, |
| 719 | goal_token_budget: None, |
| 720 | goal_status: crate::tools::goal::GoalStatus::Active, |
| 721 | allowed_tools: allowed_tools.clone(), |
| 722 | dynamic_tools: Vec::new(), |
| 723 | hook_executor: exec_hook_executor.clone(), |
| 724 | reasoning_effort: effective_reasoning_effort, |
| 725 | reasoning_effort_auto, |
| 726 | auto_model, |
| 727 | allow_shell: auto_approve || execution_config.allow_shell(), |
| 728 | trust_mode, |
| 729 | auto_approve, |
| 730 | translation_enabled: false, |
| 731 | approval_mode: if auto_approve { |
| 732 | ApprovalMode::Bypass |
| 733 | } else { |
| 734 | execution_config |
| 735 | .approval_policy |
| 736 | .as_deref() |
| 737 | .and_then(ApprovalMode::from_config_value) |
| 738 | .unwrap_or_default() |
| 739 | }, |
| 740 | verbosity: execution_config.verbosity.clone(), |
| 741 | provenance: crate::core::ops::UserInputProvenance::ExternalUser, |
| 742 | })) |
| 743 | .await?; |
| 744 | |
| 745 | // Lifecycle outbox: the clean headless turn-start boundary. `exec` has |
| 746 | // no TurnStarted engine event; the message submission above is exactly |
| 747 | // where the engine begins the turn. No-op when the feature is disabled. |
| 748 | lifecycle_outbox.emit(codewhale_hooks::LifecycleEvent { |
| 749 | event: "turn_start".to_string(), |
| 750 | kind: "turn.started".to_string(), |
| 751 | thread_id: loaded_session_id.clone().unwrap_or_default(), |
| 752 | turn_id: None, |
| 753 | item_id: None, |
| 754 | payload: serde_json::json!({ |
| 755 | "model": codewhale_hooks::bounded_text( |
| 756 | &effective_model, |
| 757 | codewhale_hooks::OUTBOX_DETAIL_MAX_CHARS, |
| 758 | ), |
| 759 | "workspace": workspace.display().to_string(), |
| 760 | }), |
| 761 | }); |
| 762 | |
| 763 | let mut summary = ExecSummary { |
| 764 | mode: "agent".to_string(), |
| 765 | provider: effective_provider_name.clone(), |
| 766 | model: effective_model.clone(), |
| 767 | prompt: prompt.to_string(), |
| 768 | ..ExecSummary::default() |
| 769 | }; |
| 770 | let can_elevate_sandbox = |
| 771 | exec_sandbox_elevation_authorized(allow_sandbox_elevation, explicit_sandbox); |
| 772 | let mut sandbox_denied = false; |
| 773 | let mut approval_required = false; |
| 774 | let mut tool_error_seen = false; |
| 775 | let mut last_error_category = None; |
| 776 | let mut reported_sandbox_contract = false; |
| 777 | |
| 778 | let mut should_persist_session = |
| 779 | resuming_session || output_format == ExecOutputFormat::StreamJson; |
| 780 | let mut latest_session_id = loaded_session_id; |
| 781 | let mut latest_messages: Arc<Vec<Message>> = Arc::new(Vec::new()); |
| 782 | let mut latest_system_prompt: Option<SystemPrompt> = None; |
| 783 | let mut latest_model = effective_model; |
| 784 | let mut latest_workspace = workspace.clone(); |
| 785 | let mut tool_starts: HashMap<String, (Instant, String)> = HashMap::new(); |
| 786 | let mut turn_usage_seq: u32 = 0; |
| 787 | |
| 788 | let mut stdout = io::stdout(); |
| 789 | let mut ends_with_newline = false; |
| 790 | // One absolute host deadline includes every autonomous child fan-in turn; |
| 791 | // child-specific shorter deadlines remain enforced by their runtime. |
| 792 | let mut events = ExecAgentEvents::new( |
| 793 | engine_handle.clone(), |
| 794 | exec_turn_started_at + execution_config.turn_wall_clock(), |
| 795 | ); |
| 796 | loop { |
| 797 | let Some(event) = events.next().await else { |
| 798 | break; |
| 799 | }; |
| 800 | |
| 801 | match event { |
| 802 | Event::MessageDelta { content, .. } => { |
| 803 | summary.output.push_str(&content); |
| 804 | if output_format == ExecOutputFormat::StreamJson { |
| 805 | emit_exec_stream_event(&ExecStreamEvent::Content { content })?; |
| 806 | } else if !json_output { |
| 807 | print!("{content}"); |
| 808 | stdout.flush()?; |
| 809 | } |
| 810 | ends_with_newline = summary.output.ends_with('\n'); |
| 811 | } |
| 812 | Event::MessageComplete { .. } |
| 813 | if output_format == ExecOutputFormat::Text |
| 814 | && !json_output |
| 815 | && !ends_with_newline => |
| 816 | { |
| 817 | println!(); |
| 818 | } |
| 819 | Event::ThinkingDelta { .. } => { |
| 820 | // Exec stream-json intentionally omits reasoning deltas; the |
| 821 | // TUI transcript retains its existing Activity Detail surface. |
| 822 | } |
| 823 | Event::ToolProjectionWarning { |
| 824 | provider, |
| 825 | omitted_tool_names, |
| 826 | omitted_tool_count, |
| 827 | } if !json_output => { |
| 828 | eprintln!( |
| 829 | "{}", |
| 830 | crate::core::events::tool_projection_warning_message( |
| 831 | &provider, |
| 832 | &omitted_tool_names, |
| 833 | omitted_tool_count, |
| 834 | ) |
| 835 | ); |
| 836 | } |
| 837 | Event::ToolCallStarted { id, name, input } => { |
| 838 | let started_at = chrono::Utc::now().to_rfc3339(); |
| 839 | tool_starts.insert(id.clone(), (Instant::now(), started_at.clone())); |
| 840 | if output_format == ExecOutputFormat::StreamJson { |
| 841 | emit_exec_stream_event(&ExecStreamEvent::ToolUse { |
| 842 | name, |
| 843 | id, |
| 844 | input, |
| 845 | started_at, |
| 846 | })?; |
| 847 | } else if !json_output { |
| 848 | let summary = summarize_tool_args(&input); |
| 849 | if let Some(summary) = summary { |
| 850 | eprintln!("tool: {name} ({summary})"); |
| 851 | } else { |
| 852 | eprintln!("tool: {name}"); |
| 853 | } |
| 854 | } |
| 855 | } |
| 856 | Event::ToolCallComplete { |
| 857 | id, name, result, .. |
| 858 | } => { |
| 859 | let (duration_ms, started_at) = tool_starts |
| 860 | .remove(&id) |
| 861 | .map(|(started, timestamp)| { |
| 862 | ( |
| 863 | u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX), |
| 864 | timestamp, |
| 865 | ) |
| 866 | }) |
| 867 | .unwrap_or_else(|| (0, chrono::Utc::now().to_rfc3339())); |
| 868 | let receipt_name = name.clone(); |
| 869 | match result { |
| 870 | Ok(output) => { |
| 871 | tool_error_seen |= !output.success; |
| 872 | summary.tools.push(ExecToolEntry { |
| 873 | name: name.clone(), |
| 874 | success: output.success, |
| 875 | output: output.content.clone(), |
| 876 | }); |
| 877 | if output_format == ExecOutputFormat::StreamJson { |
| 878 | emit_exec_stream_event(&ExecStreamEvent::ToolResult { |
| 879 | id, |
| 880 | name: receipt_name, |
| 881 | output: output.content, |
| 882 | status: if output.success { |
| 883 | "success".to_string() |
| 884 | } else { |
| 885 | "error".to_string() |
| 886 | }, |
| 887 | started_at, |
| 888 | completed_at: chrono::Utc::now().to_rfc3339(), |
| 889 | duration_ms, |
| 890 | side_effect_status: output |
| 891 | .metadata |
| 892 | .as_ref() |
| 893 | .and_then(|metadata| metadata.get("side_effect_status")) |
| 894 | .and_then(serde_json::Value::as_str) |
| 895 | .unwrap_or("unknown") |
| 896 | .to_string(), |
| 897 | error_category: (!output.success).then(|| { |
| 898 | output |
| 899 | .metadata |
| 900 | .as_ref() |
| 901 | .and_then(|metadata| metadata.get("error_category")) |
| 902 | .and_then(serde_json::Value::as_str) |
| 903 | .unwrap_or("tool_reported_failure") |
| 904 | .to_string() |
| 905 | }), |
| 906 | truncated: output |
| 907 | .metadata |
| 908 | .as_ref() |
| 909 | .and_then(|metadata| metadata.get("truncated")) |
| 910 | .and_then(serde_json::Value::as_bool), |
| 911 | artifact: tool_artifact_receipt(output.metadata.as_ref()), |
| 912 | result_metadata: output.metadata, |
| 913 | })?; |
| 914 | } else if !json_output { |
| 915 | if name == "exec_shell" && !output.content.trim().is_empty() { |
| 916 | eprintln!("tool {name} completed"); |
| 917 | eprintln!( |
| 918 | "--- stdout/stderr ---\n{}\n---------------------", |
| 919 | output.content |
| 920 | ); |
| 921 | } else { |
| 922 | eprintln!( |
| 923 | "tool {name} completed: {}", |
| 924 | summarize_tool_output(&output.content) |
| 925 | ); |
| 926 | } |
| 927 | } |
| 928 | } |
| 929 | Err(err) => { |
| 930 | tool_error_seen = true; |
| 931 | let error_text = err.to_string(); |
| 932 | summary.tools.push(ExecToolEntry { |
| 933 | name: name.clone(), |
| 934 | success: false, |
| 935 | output: error_text.clone(), |
| 936 | }); |
| 937 | if output_format == ExecOutputFormat::StreamJson { |
| 938 | emit_exec_stream_event(&ExecStreamEvent::ToolResult { |
| 939 | id, |
| 940 | name: receipt_name, |
| 941 | output: error_text, |
| 942 | status: "error".to_string(), |
| 943 | started_at, |
| 944 | completed_at: chrono::Utc::now().to_rfc3339(), |
| 945 | duration_ms, |
| 946 | side_effect_status: "not_started_or_unknown".to_string(), |
| 947 | error_category: Some(tool_error_receipt_category(&err).to_string()), |
| 948 | truncated: None, |
| 949 | artifact: None, |
| 950 | result_metadata: None, |
| 951 | })?; |
| 952 | } else if !json_output { |
| 953 | eprintln!("tool {name} failed: {err}"); |
| 954 | } |
| 955 | } |
| 956 | } |
| 957 | } |
| 958 | Event::AgentSpawned { id, prompt, .. } |
| 959 | if output_format == ExecOutputFormat::Text && !json_output => |
| 960 | { |
| 961 | eprintln!("sub-agent {id} spawned: {}", summarize_tool_output(&prompt)); |
| 962 | } |
| 963 | Event::AgentProgress { id, status, .. } |
| 964 | if output_format == ExecOutputFormat::Text && !json_output => |
| 965 | { |
| 966 | eprintln!("sub-agent {id}: {status}"); |
| 967 | } |
| 968 | Event::AgentComplete { |
| 969 | id, |
| 970 | result, |
| 971 | outcome, |
| 972 | .. |
| 973 | } if output_format == ExecOutputFormat::Text && !json_output => { |
| 974 | eprintln!( |
| 975 | "sub-agent {id} {}: {}", |
| 976 | outcome |
| 977 | .as_ref() |
| 978 | .map(crate::tools::subagent::subagent_status_name) |
| 979 | .unwrap_or("settled (outcome unconfirmed)"), |
| 980 | summarize_tool_output(&result) |
| 981 | ); |
| 982 | } |
| 983 | Event::AgentSpawned { |
| 984 | id, |
| 985 | parent_run_id, |
| 986 | spawn_depth, |
| 987 | model, |
| 988 | route_source, |
| 989 | .. |
| 990 | } if output_format == ExecOutputFormat::StreamJson => { |
| 991 | emit_exec_stream_event(&ExecStreamEvent::AgentSpawned { |
| 992 | id, |
| 993 | model, |
| 994 | spawn_depth, |
| 995 | parent_run_id, |
| 996 | route_source, |
| 997 | })?; |
| 998 | } |
| 999 | Event::AgentSpawned { .. } |
| 1000 | | Event::AgentProgress { .. } |
| 1001 | | Event::AgentComplete { .. } => {} |
| 1002 | Event::WorkflowUi { run_id, event, .. } |
| 1003 | if output_format == ExecOutputFormat::StreamJson => |
| 1004 | { |
| 1005 | emit_exec_stream_event(&ExecStreamEvent::WorkflowEvent { run_id, event })?; |
| 1006 | } |
| 1007 | Event::ApprovalRequired { id, .. } => { |
| 1008 | if auto_approve { |
| 1009 | let _ = engine_handle.approve_tool_call(id).await; |
| 1010 | } else { |
| 1011 | approval_required = true; |
| 1012 | let _ = engine_handle.deny_tool_call(id).await; |
| 1013 | } |
| 1014 | } |
| 1015 | Event::ElevationRequired { |
| 1016 | tool_id, |
| 1017 | tool_name, |
| 1018 | denial_reason, |
| 1019 | .. |
| 1020 | } => { |
| 1021 | if can_elevate_sandbox { |
| 1022 | let policy = crate::sandbox::SandboxPolicy::DangerFullAccess; |
| 1023 | let _ = engine_handle.retry_tool_with_policy(tool_id, policy).await; |
| 1024 | } else { |
| 1025 | sandbox_denied = true; |
| 1026 | approval_required = true; |
| 1027 | summary.outcomes.push(ExecOutcome { |
| 1028 | kind: "sandbox_denied".to_string(), |
| 1029 | outcome: "approval_required".to_string(), |
| 1030 | tool_name: tool_name.clone(), |
| 1031 | reason: denial_reason.clone(), |
| 1032 | }); |
| 1033 | if !reported_sandbox_contract { |
| 1034 | eprintln!( |
| 1035 | "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" |
| 1036 | ); |
| 1037 | reported_sandbox_contract = true; |
| 1038 | } |
| 1039 | if output_format == ExecOutputFormat::StreamJson { |
| 1040 | emit_exec_stream_event(&ExecStreamEvent::SandboxDenied { |
| 1041 | tool_id: tool_id.clone(), |
| 1042 | tool_name, |
| 1043 | reason: denial_reason, |
| 1044 | outcome: "approval_required".to_string(), |
| 1045 | })?; |
| 1046 | } |
| 1047 | let _ = engine_handle.deny_tool_call(tool_id).await; |
| 1048 | } |
| 1049 | } |
| 1050 | Event::Error { |
| 1051 | envelope, |
| 1052 | recoverable: _, |
| 1053 | } => { |
| 1054 | // Only a non-recoverable envelope may force the run summary |
| 1055 | // into failure. Recoverable warnings (stream-stall notices, |
| 1056 | // transient retry noise) are still streamed for visibility, |
| 1057 | // but the terminal TurnComplete event carries the |
| 1058 | // authoritative turn outcome — letting a warning set |
| 1059 | // `summary.error` here would exit an otherwise-successful |
| 1060 | // `exec` run non-zero. |
| 1061 | if exec_error_event_is_fatal(&envelope) { |
| 1062 | last_error_category = Some(envelope.category); |
| 1063 | summary.error_category = Some(envelope.category.to_string()); |
| 1064 | summary.error = Some(envelope.message.clone()); |
| 1065 | } |
| 1066 | if output_format == ExecOutputFormat::StreamJson { |
| 1067 | emit_exec_stream_event(&ExecStreamEvent::Error { |
| 1068 | error: envelope.message, |
| 1069 | })?; |
| 1070 | } else if !json_output { |
| 1071 | eprintln!("error: {}", envelope.message); |
| 1072 | } |
| 1073 | } |
| 1074 | Event::TurnUsage { |
| 1075 | usage, duration_ms, .. |
| 1076 | } => { |
| 1077 | if output_format == ExecOutputFormat::StreamJson { |
| 1078 | turn_usage_seq = turn_usage_seq.saturating_add(1); |
| 1079 | emit_exec_stream_event(&ExecStreamEvent::TurnUsage { |
| 1080 | turn: turn_usage_seq, |
| 1081 | input_tokens: usage.input_tokens, |
| 1082 | output_tokens: usage.output_tokens, |
| 1083 | reasoning_tokens: usage.reasoning_tokens, |
| 1084 | prompt_cache_hit_tokens: usage.prompt_cache_hit_tokens, |
| 1085 | prompt_cache_miss_tokens: usage.prompt_cache_miss_tokens, |
| 1086 | prompt_cache_write_tokens: usage.prompt_cache_write_tokens, |
| 1087 | reasoning_replay_tokens: usage.reasoning_replay_tokens, |
| 1088 | duration_ms, |
| 1089 | })?; |
| 1090 | } |
| 1091 | } |
| 1092 | Event::TurnComplete { |
| 1093 | status, |
| 1094 | error, |
| 1095 | usage, |
| 1096 | tool_catalog, |
| 1097 | .. |
| 1098 | } => { |
| 1099 | let (terminal_status, terminal_error) = (status, error); |
| 1100 | #[cfg(unix)] |
| 1101 | let (mut terminal_status, mut terminal_error) = (terminal_status, terminal_error); |
| 1102 | if matches!( |
| 1103 | terminal_status, |
| 1104 | crate::core::events::TurnOutcomeStatus::Completed |
| 1105 | ) && terminal_error.is_none() |
| 1106 | { |
| 1107 | #[cfg(unix)] |
| 1108 | match exec_shell_manager.lock() { |
| 1109 | Ok(mut manager) => match manager.commit_persistent_services() { |
| 1110 | Ok(receipts) => { |
| 1111 | for receipt in &receipts { |
| 1112 | if output_format == ExecOutputFormat::StreamJson { |
| 1113 | emit_exec_stream_event( |
| 1114 | &ExecStreamEvent::ServiceReleased { |
| 1115 | task_id: receipt.task_id.clone(), |
| 1116 | pid: receipt.pid, |
| 1117 | process_group_id: receipt.process_group_id, |
| 1118 | ownership: receipt.ownership.clone(), |
| 1119 | }, |
| 1120 | )?; |
| 1121 | } else if !json_output { |
| 1122 | eprintln!( |
| 1123 | "persistent service released: {} pid={} pgid={} ownership={}", |
| 1124 | receipt.task_id, |
| 1125 | receipt.pid, |
| 1126 | receipt.process_group_id, |
| 1127 | receipt.ownership |
| 1128 | ); |
| 1129 | } |
| 1130 | } |
| 1131 | summary.released_services.extend(receipts); |
| 1132 | } |
| 1133 | Err(error) => { |
| 1134 | manager.abort_persistent_services(); |
| 1135 | terminal_status = crate::core::events::TurnOutcomeStatus::Failed; |
| 1136 | terminal_error = Some(format!( |
| 1137 | "Persistent service ownership transfer failed: {error}" |
| 1138 | )); |
| 1139 | } |
| 1140 | }, |
| 1141 | Err(_) => { |
| 1142 | terminal_status = crate::core::events::TurnOutcomeStatus::Failed; |
| 1143 | terminal_error = Some( |
| 1144 | "Persistent service ownership transfer failed: shell manager lock poisoned" |
| 1145 | .to_string(), |
| 1146 | ); |
| 1147 | } |
| 1148 | } |
| 1149 | } else if let Ok(mut manager) = exec_shell_manager.lock() { |
| 1150 | manager.abort_persistent_services(); |
| 1151 | } |
| 1152 | summary.status = Some(format!("{terminal_status:?}").to_lowercase()); |
| 1153 | if terminal_error.is_some() { |
| 1154 | summary.error = terminal_error; |
| 1155 | } |
| 1156 | if sandbox_denied |
| 1157 | && summary.error.is_none() |
| 1158 | && matches!( |
| 1159 | terminal_status, |
| 1160 | crate::core::events::TurnOutcomeStatus::Failed |
| 1161 | ) |
| 1162 | { |
| 1163 | summary.error = Some( |
| 1164 | "exec turn failed after sandbox denial; explicit sandbox elevation was not authorized" |
| 1165 | .to_string(), |
| 1166 | ); |
| 1167 | } |
| 1168 | // Lifecycle outbox: the clean headless turn-end boundary. |
| 1169 | // `terminal_status` is authoritative here — persistent-service |
| 1170 | // handoff failures above already demoted it to Failed, and |
| 1171 | // `summary.error` includes the sandbox-denial augmentation. |
| 1172 | // No-op when the feature is disabled. |
| 1173 | { |
| 1174 | let outbox_status = format!("{terminal_status:?}").to_lowercase(); |
| 1175 | let kind = match terminal_status { |
| 1176 | crate::core::events::TurnOutcomeStatus::Completed => "turn.completed", |
| 1177 | crate::core::events::TurnOutcomeStatus::Failed => "turn.failed", |
| 1178 | crate::core::events::TurnOutcomeStatus::Interrupted => "turn.interrupted", |
| 1179 | }; |
| 1180 | lifecycle_outbox.emit(codewhale_hooks::LifecycleEvent { |
| 1181 | event: "turn_end".to_string(), |
| 1182 | kind: kind.to_string(), |
| 1183 | thread_id: latest_session_id.clone().unwrap_or_default(), |
| 1184 | turn_id: None, |
| 1185 | item_id: None, |
| 1186 | payload: serde_json::json!({ |
| 1187 | "status": outbox_status, |
| 1188 | "duration_ms": exec_turn_started_at.elapsed().as_millis() as u64, |
| 1189 | "workspace": latest_workspace.display().to_string(), |
| 1190 | "error": summary.error.as_deref().map(|message| { |
| 1191 | codewhale_hooks::bounded_text( |
| 1192 | message, |
| 1193 | codewhale_hooks::OUTBOX_DETAIL_MAX_CHARS, |
| 1194 | ) |
| 1195 | }), |
| 1196 | }), |
| 1197 | }); |
| 1198 | } |
| 1199 | if last_error_category.is_none() { |
| 1200 | last_error_category = summary |
| 1201 | .error |
| 1202 | .as_deref() |
| 1203 | .map(crate::error_taxonomy::classify_error_message); |
| 1204 | summary.error_category = |
| 1205 | last_error_category.map(|category| category.to_string()); |
| 1206 | } |
| 1207 | let termination_reason = crate::core::termination::classify_turn_termination( |
| 1208 | terminal_status, |
| 1209 | last_error_category, |
| 1210 | tool_error_seen, |
| 1211 | approval_required, |
| 1212 | ); |
| 1213 | summary.termination_reason = Some(termination_reason.as_str().to_string()); |
| 1214 | // State the exit class here rather than inferring it later |
| 1215 | // from the process exit code: `Canceled` exits 130, the same |
| 1216 | // value the SIGINT path uses, so a code-based derivation would |
| 1217 | // report every Esc-cancelled turn as a signal. A no-op unless |
| 1218 | // this process was armed. |
| 1219 | if !termination_reason.is_success() { |
| 1220 | codewhale_telemetry::set_exit_class(codewhale_telemetry::ExitClass::Error); |
| 1221 | } |
| 1222 | let saved_session_id = if should_persist_session && !latest_messages.is_empty() { |
| 1223 | match persist_exec_session( |
| 1224 | &latest_messages, |
| 1225 | &latest_model, |
| 1226 | PersistedProviderRoute { |
| 1227 | kind: effective_provider.as_str(), |
| 1228 | id: effective_provider_id.as_deref(), |
| 1229 | }, |
| 1230 | &latest_workspace, |
| 1231 | &latest_system_prompt, |
| 1232 | latest_session_id.as_deref(), |
| 1233 | u64::from(usage.input_tokens) + u64::from(usage.output_tokens), |
| 1234 | fleet_capture.as_ref().map(|(_, manager)| manager), |
| 1235 | ) { |
| 1236 | Ok(id) => { |
| 1237 | if output_format == ExecOutputFormat::Text && !json_output { |
| 1238 | eprintln!("{}", exec_saved_session_line(&id)); |
| 1239 | } |
| 1240 | Some(id) |
| 1241 | } |
| 1242 | Err(err) => { |
| 1243 | if output_format == ExecOutputFormat::Text && !json_output { |
| 1244 | eprintln!("warning: failed to save exec session: {err}"); |
| 1245 | } |
| 1246 | None |
| 1247 | } |
| 1248 | } |
| 1249 | } else { |
| 1250 | None |
| 1251 | }; |
| 1252 | if output_format == ExecOutputFormat::StreamJson { |
| 1253 | if let Some(id) = saved_session_id.as_ref() { |
| 1254 | emit_exec_stream_event(&ExecStreamEvent::SessionCapture { |
| 1255 | content: exec_stream_session_ref(id), |
| 1256 | saved_session_id: id.clone(), |
| 1257 | })?; |
| 1258 | } |
| 1259 | // Resolved output ceiling and its provenance, surfaced so a |
| 1260 | // wrong ceiling is visible in the receipt rather than |
| 1261 | // requiring packet capture. |
| 1262 | let codewhale_max_output_tokens = |
| 1263 | crate::route_budget::effective_max_output_tokens_for_route( |
| 1264 | effective_provider, |
| 1265 | &latest_model, |
| 1266 | active_route_limits, |
| 1267 | ); |
| 1268 | let codewhale_max_output_tokens_source = |
| 1269 | crate::route_budget::output_ceiling_source( |
| 1270 | effective_provider, |
| 1271 | &latest_model, |
| 1272 | ) |
| 1273 | .as_str(); |
| 1274 | // The deliverable is the final assistant reply of the |
| 1275 | // session, not the cumulative stream output: a |
| 1276 | // multi-step turn streams pre-tool commentary first, |
| 1277 | // and that commentary is not part of the answer. |
| 1278 | let final_answer = exec_stream_final_answer_text( |
| 1279 | &latest_messages, |
| 1280 | !summary.output.trim().is_empty(), |
| 1281 | ) |
| 1282 | .unwrap_or_default(); |
| 1283 | emit_exec_stream_event(&ExecStreamEvent::Metadata { |
| 1284 | meta: Box::new(ExecStreamMeta { |
| 1285 | receipt_kind: "terminal", |
| 1286 | provider: effective_provider_kind.clone(), |
| 1287 | provider_id: effective_stream_provider_id.clone(), |
| 1288 | model: latest_model.clone(), |
| 1289 | route_source: route_source.clone(), |
| 1290 | input_tokens: Some(usage.input_tokens), |
| 1291 | output_tokens: Some(usage.output_tokens), |
| 1292 | prompt_cache_hit_tokens: usage.prompt_cache_hit_tokens, |
| 1293 | prompt_cache_miss_tokens: usage.prompt_cache_miss_tokens, |
| 1294 | prompt_cache_write_tokens: usage.prompt_cache_write_tokens, |
| 1295 | reasoning_tokens: usage.reasoning_tokens, |
| 1296 | codewhale_max_output_tokens: Some(codewhale_max_output_tokens), |
| 1297 | codewhale_max_output_tokens_source: Some( |
| 1298 | codewhale_max_output_tokens_source, |
| 1299 | ), |
| 1300 | duration_ms: u64::try_from(exec_started.elapsed().as_millis()) |
| 1301 | .unwrap_or(u64::MAX), |
| 1302 | retry_count: None, |
| 1303 | approval_posture: approval_posture.clone(), |
| 1304 | sandbox_posture: sandbox_posture.clone(), |
| 1305 | binary_sha256: binary_sha256.clone(), |
| 1306 | config_sha256: None, |
| 1307 | prompt_sha256: prompt_sha256.clone(), |
| 1308 | tool_catalog_sha256: tool_catalog.as_ref().and_then(|catalog| { |
| 1309 | serde_json::to_vec(catalog).ok().map(|bytes| { |
| 1310 | format!("sha256:{}", crate::hashing::sha256_hex(&bytes)) |
| 1311 | }) |
| 1312 | }), |
| 1313 | input_analysis: exec_stream_input_analysis( |
| 1314 | &latest_messages, |
| 1315 | latest_system_prompt.as_ref(), |
| 1316 | ), |
| 1317 | visible_final_answer_chars: final_answer.chars().count(), |
| 1318 | visible_final_answer_excerpt: exec_stream_final_answer_excerpt( |
| 1319 | &final_answer, |
| 1320 | ), |
| 1321 | resume_command: saved_session_id |
| 1322 | .as_deref() |
| 1323 | .map(exec_stream_resume_hint) |
| 1324 | .unwrap_or_default(), |
| 1325 | session_id: saved_session_id |
| 1326 | .as_deref() |
| 1327 | .map(exec_stream_session_ref) |
| 1328 | .unwrap_or_default(), |
| 1329 | workspace: latest_workspace.display().to_string(), |
| 1330 | message_count: latest_messages.len(), |
| 1331 | status: summary.status.clone(), |
| 1332 | termination_reason: summary.termination_reason.clone(), |
| 1333 | error_category: summary.error_category.clone(), |
| 1334 | error: summary.error.clone(), |
| 1335 | }), |
| 1336 | })?; |
| 1337 | emit_exec_stream_event(&ExecStreamEvent::Done)?; |
| 1338 | } |
| 1339 | let _ = |
| 1340 | tokio::time::timeout(Duration::from_secs(2), engine_handle.send(Op::Shutdown)) |
| 1341 | .await; |
| 1342 | break; |
| 1343 | } |
| 1344 | Event::CompactionStarted { .. } => { |
| 1345 | // The Engine writes recovery artifacts under its session ID. |
| 1346 | // Keep the owning session discoverable even in text output. |
| 1347 | should_persist_session = true; |
| 1348 | } |
| 1349 | Event::SessionUpdated { |
| 1350 | session_id, |
| 1351 | messages, |
| 1352 | system_prompt, |
| 1353 | model, |
| 1354 | workspace, |
| 1355 | } => { |
| 1356 | latest_session_id = Some(session_id); |
| 1357 | latest_messages = messages; |
| 1358 | latest_system_prompt = system_prompt; |
| 1359 | latest_model = model; |
| 1360 | latest_workspace = workspace; |
| 1361 | } |
| 1362 | // #3027: surface the engine's max-steps notice in text mode so a |
| 1363 | // --max-turns run that stops early says why instead of going quiet. |
| 1364 | Event::Status { message } |
| 1365 | if output_format == ExecOutputFormat::Text |
| 1366 | && !json_output |
| 1367 | && message.contains("Maximum model steps") => |
| 1368 | { |
| 1369 | eprintln!("{message}"); |
| 1370 | } |
| 1371 | _ => {} |
| 1372 | } |
| 1373 | } |
| 1374 | |
| 1375 | if summary.status.is_none() { |
| 1376 | if let Ok(mut manager) = exec_shell_manager.lock() { |
| 1377 | manager.abort_persistent_services(); |
| 1378 | } |
| 1379 | let error = summary.error.clone().unwrap_or_else(|| { |
| 1380 | "Engine event channel closed before a terminal turn receipt".to_string() |
| 1381 | }); |
| 1382 | let category = last_error_category |
| 1383 | .unwrap_or_else(|| crate::error_taxonomy::classify_error_message(&error)); |
| 1384 | let termination_reason = crate::core::termination::classify_turn_termination( |
| 1385 | crate::core::events::TurnOutcomeStatus::Failed, |
| 1386 | Some(category), |
| 1387 | tool_error_seen, |
| 1388 | approval_required, |
| 1389 | ); |
| 1390 | summary.status = Some("failed".to_string()); |
| 1391 | summary.error_category = Some(category.to_string()); |
| 1392 | summary.termination_reason = Some(termination_reason.as_str().to_string()); |
| 1393 | summary.error = Some(error.clone()); |
| 1394 | // Lifecycle outbox: the engine channel closed before a terminal |
| 1395 | // turn receipt. Every emitted `turn_start` still gets its matching |
| 1396 | // `turn_end` so a supervisor never sees an orphaned in-progress |
| 1397 | // turn. No-op when the feature is disabled. |
| 1398 | lifecycle_outbox.emit(codewhale_hooks::LifecycleEvent { |
| 1399 | event: "turn_end".to_string(), |
| 1400 | kind: "turn.failed".to_string(), |
| 1401 | thread_id: latest_session_id.clone().unwrap_or_default(), |
| 1402 | turn_id: None, |
| 1403 | item_id: None, |
| 1404 | payload: serde_json::json!({ |
| 1405 | "status": "failed", |
| 1406 | "duration_ms": exec_turn_started_at.elapsed().as_millis() as u64, |
| 1407 | "workspace": latest_workspace.display().to_string(), |
| 1408 | "error": codewhale_hooks::bounded_text( |
| 1409 | &error, |
| 1410 | codewhale_hooks::OUTBOX_DETAIL_MAX_CHARS, |
| 1411 | ), |
| 1412 | }), |
| 1413 | }); |
| 1414 | if output_format == ExecOutputFormat::StreamJson { |
| 1415 | emit_exec_stream_event(&ExecStreamEvent::Error { error })?; |
| 1416 | } |
| 1417 | } |
| 1418 | |
| 1419 | // Drain the terminal receipt before either returning or taking the explicit |
| 1420 | // retryable-failure process exit below. Outbox failures cannot change the |
| 1421 | // authoritative turn outcome. |
| 1422 | if let Err(error) = lifecycle_outbox.flush(Duration::from_secs(2)).await { |
| 1423 | tracing::warn!(target: "lifecycle_outbox", %error, "exec lifecycle outbox did not drain before exit"); |
| 1424 | } |
| 1425 | |
| 1426 | if json_output { |
| 1427 | println!("{}", serde_json::to_string_pretty(&summary)?); |
| 1428 | } |
| 1429 | |
| 1430 | if let Some(error) = summary.error.as_ref() |
| 1431 | && !error.trim().is_empty() |
| 1432 | { |
| 1433 | // Distinguish retryable infrastructure failures (provider/transport, |
| 1434 | // after all in-session retries are exhausted) from genuine task |
| 1435 | // failures so supervisors and bench harnesses can tell them apart at |
| 1436 | // the process level without parsing the stream. Genuine failures |
| 1437 | // keep the historical `bail!` → exit 1 path. |
| 1438 | let exit_code = exec_failure_exit_code(summary.error_category.as_deref()); |
| 1439 | if exit_code != 1 { |
| 1440 | eprintln!("Error: exec turn failed: {error}"); |
| 1441 | let _ = io::stdout().flush(); |
| 1442 | std::process::exit(exit_code); |
| 1443 | } |
| 1444 | bail!("exec turn failed: {error}"); |
| 1445 | } |
| 1446 | |
| 1447 | if matches!( |
| 1448 | summary.status.as_deref(), |
| 1449 | Some("failed" | "canceled" | "interrupted") |
| 1450 | ) { |
| 1451 | let status = summary.status.as_deref().unwrap_or("unknown"); |
| 1452 | bail!("exec turn ended with status {status}"); |
| 1453 | } |
| 1454 | |
| 1455 | Ok(()) |
| 1456 | } |
| 1457 | |
| 1458 | #[cfg(test)] |
| 1459 | mod tests { |
| 1460 | use super::{ExecAgentEvents, exec_automation_services, exec_disallowed_tools}; |
| 1461 | use crate::core::engine::mock_engine_handle; |
| 1462 | use crate::core::engine::tool_catalog::REQUEST_USER_INPUT_NAME; |
| 1463 | use crate::core::events::{Event, TurnOutcomeStatus}; |
| 1464 | use crate::core::ops::{Op, SubAgentSettlement}; |
| 1465 | use codewhale_models::Usage; |
| 1466 | use std::time::{Duration, Instant}; |
| 1467 | |
| 1468 | fn completed_parent(input_tokens: u32) -> Event { |
| 1469 | let usage = Usage { |
| 1470 | input_tokens, |
| 1471 | ..Usage::default() |
| 1472 | }; |
| 1473 | Event::TurnComplete { |
| 1474 | usage: usage.clone(), |
| 1475 | parent_route_usage: usage, |
| 1476 | routed_usage_dropped_records: 0, |
| 1477 | status: TurnOutcomeStatus::Completed, |
| 1478 | error: None, |
| 1479 | tool_catalog: None, |
| 1480 | base_url: None, |
| 1481 | } |
| 1482 | } |
| 1483 | |
| 1484 | async fn reply_to_probe( |
| 1485 | operations: &mut tokio::sync::mpsc::Receiver<Op>, |
| 1486 | snapshot: SubAgentSettlement, |
| 1487 | ) { |
| 1488 | let Op::GetSubAgentSettlement { tx } = operations.recv().await.expect("host probe") else { |
| 1489 | panic!("host must not shut down while child work remains"); |
| 1490 | }; |
| 1491 | tx.lock().unwrap().take().unwrap().send(snapshot).unwrap(); |
| 1492 | } |
| 1493 | |
| 1494 | #[test] |
| 1495 | fn headless_exec_withholds_request_user_input_without_a_responder() { |
| 1496 | // No responder exists on a one-shot CLI run, so the tool is |
| 1497 | // withheld by default rather than offered and stalled on. |
| 1498 | let disallowed = exec_disallowed_tools(None).expect("withhold list"); |
| 1499 | assert!( |
| 1500 | disallowed |
| 1501 | .iter() |
| 1502 | .any(|tool| tool.as_str() == REQUEST_USER_INPUT_NAME), |
| 1503 | "request_user_input must be withheld by default: {disallowed:?}" |
| 1504 | ); |
| 1505 | // An operator-passed entry is kept exactly once, not duplicated. |
| 1506 | let disallowed = exec_disallowed_tools(Some(vec![REQUEST_USER_INPUT_NAME.to_string()])) |
| 1507 | .expect("withhold list"); |
| 1508 | assert_eq!( |
| 1509 | disallowed |
| 1510 | .iter() |
| 1511 | .filter(|tool| tool.as_str() == REQUEST_USER_INPUT_NAME) |
| 1512 | .count(), |
| 1513 | 1 |
| 1514 | ); |
| 1515 | } |
| 1516 | |
| 1517 | #[tokio::test] |
| 1518 | async fn headless_success_waits_for_children_workflow_phases_and_parent_fan_in() { |
| 1519 | let mut engine = mock_engine_handle(); |
| 1520 | let mut events = ExecAgentEvents::new( |
| 1521 | engine.handle.clone(), |
| 1522 | Instant::now() + Duration::from_secs(3), |
| 1523 | ); |
| 1524 | engine.tx_event.send(completed_parent(11)).await.unwrap(); |
| 1525 | let actor = async { |
| 1526 | reply_to_probe( |
| 1527 | &mut engine.rx_op, |
| 1528 | SubAgentSettlement { |
| 1529 | running_children: 1, |
| 1530 | running_workflows: 1, |
| 1531 | pending_completions: 0, |
| 1532 | }, |
| 1533 | ) |
| 1534 | .await; |
| 1535 | reply_to_probe( |
| 1536 | &mut engine.rx_op, |
| 1537 | SubAgentSettlement { |
| 1538 | running_children: 0, |
| 1539 | running_workflows: 1, |
| 1540 | pending_completions: 0, |
| 1541 | }, |
| 1542 | ) |
| 1543 | .await; |
| 1544 | reply_to_probe( |
| 1545 | &mut engine.rx_op, |
| 1546 | SubAgentSettlement { |
| 1547 | running_children: 0, |
| 1548 | running_workflows: 0, |
| 1549 | pending_completions: 1, |
| 1550 | }, |
| 1551 | ) |
| 1552 | .await; |
| 1553 | engine |
| 1554 | .tx_event |
| 1555 | .send(Event::MessageDelta { |
| 1556 | content: "child findings reviewed".into(), |
| 1557 | index: 0, |
| 1558 | }) |
| 1559 | .await |
| 1560 | .unwrap(); |
| 1561 | engine.tx_event.send(completed_parent(7)).await.unwrap(); |
| 1562 | reply_to_probe(&mut engine.rx_op, SubAgentSettlement::default()).await; |
| 1563 | }; |
| 1564 | let host = async { |
| 1565 | assert!( |
| 1566 | matches!(events.next().await, Some(Event::MessageDelta { content, .. }) if content == "child findings reviewed") |
| 1567 | ); |
| 1568 | let Some(Event::TurnComplete { usage, status, .. }) = events.next().await else { |
| 1569 | panic!("settled parent receipt") |
| 1570 | }; |
| 1571 | assert_eq!(status, TurnOutcomeStatus::Completed); |
| 1572 | assert_eq!( |
| 1573 | usage.input_tokens, 18, |
| 1574 | "both parent turns are accounted once" |
| 1575 | ); |
| 1576 | }; |
| 1577 | tokio::time::timeout(Duration::from_secs(4), async { tokio::join!(actor, host) }) |
| 1578 | .await |
| 1579 | .unwrap(); |
| 1580 | assert!( |
| 1581 | !engine.handle.is_cancelled(), |
| 1582 | "ordinary success must not cancel children" |
| 1583 | ); |
| 1584 | assert!( |
| 1585 | engine.rx_op.try_recv().is_err(), |
| 1586 | "the event reader does not send early Shutdown" |
| 1587 | ); |
| 1588 | } |
| 1589 | |
| 1590 | #[tokio::test] |
| 1591 | async fn headless_child_settlement_deadline_bounds_a_stalled_engine_probe() { |
| 1592 | let mut engine = mock_engine_handle(); |
| 1593 | let mut events = ExecAgentEvents::new( |
| 1594 | engine.handle.clone(), |
| 1595 | Instant::now() + Duration::from_millis(30), |
| 1596 | ); |
| 1597 | engine.tx_event.send(completed_parent(13)).await.unwrap(); |
| 1598 | let event = tokio::time::timeout(Duration::from_secs(1), events.next()) |
| 1599 | .await |
| 1600 | .unwrap(); |
| 1601 | let Some(Event::TurnComplete { |
| 1602 | status, |
| 1603 | error, |
| 1604 | usage, |
| 1605 | routed_usage_dropped_records, |
| 1606 | .. |
| 1607 | }) = event |
| 1608 | else { |
| 1609 | panic!("bounded failure receipt") |
| 1610 | }; |
| 1611 | assert_eq!(status, TurnOutcomeStatus::Failed); |
| 1612 | assert!(error.unwrap().contains("wall-clock budget exhausted")); |
| 1613 | assert_eq!(usage.input_tokens, 13); |
| 1614 | assert_eq!(routed_usage_dropped_records, 1); |
| 1615 | assert!(engine.handle.is_cancelled()); |
| 1616 | let mut shutdown = false; |
| 1617 | while let Ok(op) = engine.rx_op.try_recv() { |
| 1618 | shutdown |= matches!(op, Op::Shutdown); |
| 1619 | } |
| 1620 | assert!(shutdown, "shutdown must also cancel detached session tasks"); |
| 1621 | } |
| 1622 | |
| 1623 | #[tokio::test] |
| 1624 | async fn headless_failed_or_interrupted_parent_skips_child_settlement() { |
| 1625 | for terminal_status in [TurnOutcomeStatus::Failed, TurnOutcomeStatus::Interrupted] { |
| 1626 | let mut engine = mock_engine_handle(); |
| 1627 | let mut events = ExecAgentEvents::new( |
| 1628 | engine.handle.clone(), |
| 1629 | Instant::now() + Duration::from_secs(30), |
| 1630 | ); |
| 1631 | let mut terminal = completed_parent(3); |
| 1632 | if let Event::TurnComplete { status, .. } = &mut terminal { |
| 1633 | *status = terminal_status; |
| 1634 | } |
| 1635 | engine.tx_event.send(terminal).await.unwrap(); |
| 1636 | assert!( |
| 1637 | matches!(events.next().await, Some(Event::TurnComplete { status, .. }) if status == terminal_status) |
| 1638 | ); |
| 1639 | assert!( |
| 1640 | engine.rx_op.try_recv().is_err(), |
| 1641 | "failure cannot admit another settling turn" |
| 1642 | ); |
| 1643 | } |
| 1644 | } |
| 1645 | |
| 1646 | #[tokio::test] |
| 1647 | async fn headless_fatal_fan_in_error_cancels_before_releasing_terminal_receipt() { |
| 1648 | let engine = mock_engine_handle(); |
| 1649 | let mut events = ExecAgentEvents::new( |
| 1650 | engine.handle.clone(), |
| 1651 | Instant::now() + Duration::from_secs(30), |
| 1652 | ); |
| 1653 | engine.tx_event.send(completed_parent(5)).await.unwrap(); |
| 1654 | engine |
| 1655 | .tx_event |
| 1656 | .send(Event::error(crate::error_taxonomy::ErrorEnvelope::fatal( |
| 1657 | "fan-in route unavailable", |
| 1658 | ))) |
| 1659 | .await |
| 1660 | .unwrap(); |
| 1661 | assert!(matches!(events.next().await, Some(Event::Error { .. }))); |
| 1662 | assert!(engine.handle.is_cancelled()); |
| 1663 | assert!( |
| 1664 | matches!(events.next().await, Some(Event::TurnComplete { status: TurnOutcomeStatus::Failed, error: Some(error), .. }) if error.contains("fan-in route unavailable")) |
| 1665 | ); |
| 1666 | } |
| 1667 | |
| 1668 | #[tokio::test] |
| 1669 | async fn headless_cancel_during_child_wait_returns_interrupted() { |
| 1670 | let mut engine = mock_engine_handle(); |
| 1671 | let mut events = ExecAgentEvents::new( |
| 1672 | engine.handle.clone(), |
| 1673 | Instant::now() + Duration::from_secs(30), |
| 1674 | ); |
| 1675 | engine.tx_event.send(completed_parent(5)).await.unwrap(); |
| 1676 | let cancel = async { |
| 1677 | reply_to_probe( |
| 1678 | &mut engine.rx_op, |
| 1679 | SubAgentSettlement { |
| 1680 | running_children: 1, |
| 1681 | running_workflows: 0, |
| 1682 | pending_completions: 0, |
| 1683 | }, |
| 1684 | ) |
| 1685 | .await; |
| 1686 | engine.handle.cancel(); |
| 1687 | }; |
| 1688 | let host = async { |
| 1689 | assert!(matches!( |
| 1690 | events.next().await, |
| 1691 | Some(Event::TurnComplete { |
| 1692 | status: TurnOutcomeStatus::Interrupted, |
| 1693 | .. |
| 1694 | }) |
| 1695 | )); |
| 1696 | }; |
| 1697 | tokio::time::timeout(Duration::from_secs(1), async { tokio::join!(cancel, host) }) |
| 1698 | .await |
| 1699 | .unwrap(); |
| 1700 | } |
| 1701 | |
| 1702 | #[tokio::test] |
| 1703 | async fn headless_closed_engine_cannot_reuse_an_earlier_success_receipt() { |
| 1704 | let mut engine = mock_engine_handle(); |
| 1705 | let mut events = ExecAgentEvents::new( |
| 1706 | engine.handle.clone(), |
| 1707 | Instant::now() + Duration::from_secs(30), |
| 1708 | ); |
| 1709 | engine.tx_event.send(completed_parent(5)).await.unwrap(); |
| 1710 | engine.close_event_stream(); |
| 1711 | assert!( |
| 1712 | matches!(events.next().await, Some(Event::TurnComplete { status: TurnOutcomeStatus::Failed, error: Some(error), .. }) if error.contains("channel closed")) |
| 1713 | ); |
| 1714 | } |
| 1715 | |
| 1716 | /// The reproduced defect: headless exec advertised `automation` while |
| 1717 | /// attaching no store, so every call — including the read-only `list` and |
| 1718 | /// `read` — failed "AutomationManager is not attached". Exec must attach |
| 1719 | /// the same durable store the TUI and the Runtime open. |
| 1720 | #[test] |
| 1721 | fn headless_exec_attaches_the_shared_automation_store() { |
| 1722 | let _lock = crate::test_support::lock_test_env(); |
| 1723 | let tmp = tempfile::TempDir::new().expect("tempdir"); |
| 1724 | // SAFETY: serialised by lock_test_env. |
| 1725 | unsafe { |
| 1726 | std::env::set_var("CODEWHALE_AUTOMATIONS_DIR", tmp.path()); |
| 1727 | } |
| 1728 | let attached = exec_automation_services(false).expect("open store"); |
| 1729 | // SAFETY: cleanup under the same lock. |
| 1730 | unsafe { |
| 1731 | std::env::remove_var("CODEWHALE_AUTOMATIONS_DIR"); |
| 1732 | } |
| 1733 | let attached = attached.expect("exec attaches the automation store"); |
| 1734 | let manager = attached.blocking_lock(); |
| 1735 | // Reads work against the shared store... |
| 1736 | assert!( |
| 1737 | manager.list_automations().is_ok(), |
| 1738 | "an attached store must serve inspection" |
| 1739 | ); |
| 1740 | // ...while the exec host stays outside the Runtime's exclusive |
| 1741 | // task-execution lease, so it claims no dispatch ownership. |
| 1742 | assert!( |
| 1743 | manager.execution_scope().is_none(), |
| 1744 | "a one-shot host must not claim an execution scope" |
| 1745 | ); |
| 1746 | } |
| 1747 | |
| 1748 | /// A Fleet worker keeps the narrowed envelope it was launched with. |
| 1749 | #[test] |
| 1750 | fn fleet_workers_get_no_automation_store() { |
| 1751 | assert!( |
| 1752 | exec_automation_services(true) |
| 1753 | .expect("no store to open") |
| 1754 | .is_none() |
| 1755 | ); |
| 1756 | } |
| 1757 | |
| 1758 | /// A store that cannot be opened is reported, not swallowed into a silent |
| 1759 | /// "not attached" at the first tool call. |
| 1760 | #[test] |
| 1761 | fn an_unopenable_store_fails_loudly() { |
| 1762 | let _lock = crate::test_support::lock_test_env(); |
| 1763 | let tmp = tempfile::NamedTempFile::new().expect("temp file"); |
| 1764 | // A regular file cannot host the store's directories. |
| 1765 | let blocked = tmp.path().join("automations"); |
| 1766 | // SAFETY: serialised by lock_test_env. |
| 1767 | unsafe { |
| 1768 | std::env::set_var("CODEWHALE_AUTOMATIONS_DIR", &blocked); |
| 1769 | } |
| 1770 | let result = exec_automation_services(false); |
| 1771 | // SAFETY: cleanup under the same lock. |
| 1772 | unsafe { |
| 1773 | std::env::remove_var("CODEWHALE_AUTOMATIONS_DIR"); |
| 1774 | } |
| 1775 | let err = result.expect_err("opening the store must fail"); |
| 1776 | assert!( |
| 1777 | format!("{err:#}").contains("automation store for headless exec"), |
| 1778 | "the failure must name what could not be opened: {err:#}" |
| 1779 | ); |
| 1780 | } |
| 1781 | } |
| 1782 |