| 1 | //! Low-level tool execution helpers for the engine turn loop. |
| 2 | //! |
| 3 | //! This module keeps the mechanics of MCP dispatch, execution locking, and |
| 4 | //! parallel-tool fanout out of `engine.rs`; the turn loop still owns planning, |
| 5 | //! approval, and how tool results are written back into session state. |
| 6 | |
| 7 | use std::{ |
| 8 | fs::OpenOptions, |
| 9 | io::Write, |
| 10 | path::{Path, PathBuf}, |
| 11 | sync::Arc, |
| 12 | time::Duration, |
| 13 | }; |
| 14 | |
| 15 | use super::*; |
| 16 | |
| 17 | const TOOL_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(10); |
| 18 | |
| 19 | fn inherited_interactive_shell_refusal(tool_name: &str, interactive: bool) -> Option<ToolError> { |
| 20 | if !interactive || !matches!(tool_name, "bash" | "Bash" | "exec_shell") { |
| 21 | return None; |
| 22 | } |
| 23 | crate::tools::shell::inherited_interactive_terminal_refusal() |
| 24 | .map(|message| ToolError::execution_failed(message.to_string())) |
| 25 | } |
| 26 | |
| 27 | #[cfg(all(any(test, feature = "test-support"), unix))] |
| 28 | thread_local! { |
| 29 | static REPLAY_SPAN_SEQ: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) }; |
| 30 | } |
| 31 | |
| 32 | /// Number operation spans on this thread from 1 until the guard drops, the |
| 33 | /// way an otherwise idle process would (see [`OperationSpanGuard::span_id`]). |
| 34 | #[cfg(all(any(test, feature = "test-support"), unix))] |
| 35 | pub fn pin_replay_span_sequence() -> ReplaySpanSequenceGuard { |
| 36 | REPLAY_SPAN_SEQ.with(|cell| cell.set(Some(1))); |
| 37 | ReplaySpanSequenceGuard |
| 38 | } |
| 39 | |
| 40 | #[cfg(all(any(test, feature = "test-support"), unix))] |
| 41 | pub struct ReplaySpanSequenceGuard; |
| 42 | |
| 43 | #[cfg(all(any(test, feature = "test-support"), unix))] |
| 44 | impl Drop for ReplaySpanSequenceGuard { |
| 45 | fn drop(&mut self) { |
| 46 | REPLAY_SPAN_SEQ.with(|cell| cell.set(None)); |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | /// Pairs an observed `OperationActivityStarted` with at most one completion. |
| 51 | /// |
| 52 | /// The turn loop drops an in-flight tool future when the user cancels. |
| 53 | /// Capacity reserved before admission keeps completion synchronous even when |
| 54 | /// a nested call is withdrawn while its parent continues. |
| 55 | pub struct OperationSpanGuard<'a> { |
| 56 | start: Option<mpsc::Permit<'a, Event>>, |
| 57 | span: Option<( |
| 58 | mpsc::Permit<'a, Event>, |
| 59 | String, |
| 60 | codewhale_protocol::engine_owner::OwnerActivityKind, |
| 61 | Option<String>, |
| 62 | )>, |
| 63 | } |
| 64 | |
| 65 | impl<'a> OperationSpanGuard<'a> { |
| 66 | /// A process-unique span id. The model's tool-call id is not unique: |
| 67 | /// gateways that elide ids fall back to `call_{block_index}`, which |
| 68 | /// repeats every step, and a consumer deduplicates completed spans. |
| 69 | fn span_id(call_id: &str) -> String { |
| 70 | static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); |
| 71 | // A conformance replay numbers its own spans. The process-wide |
| 72 | // counter also counts every span another test starts in a shared |
| 73 | // process, so a golden recorded in isolation drifted there (#6698). |
| 74 | #[cfg(all(any(test, feature = "test-support"), unix))] |
| 75 | if let Some(seq) = REPLAY_SPAN_SEQ.with(|cell| { |
| 76 | let seq = cell.get()?; |
| 77 | cell.set(Some(seq + 1)); |
| 78 | Some(seq) |
| 79 | }) { |
| 80 | return format!("{call_id}#{seq}"); |
| 81 | } |
| 82 | let seq = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); |
| 83 | format!("{call_id}#{seq}") |
| 84 | } |
| 85 | |
| 86 | pub async fn reserve( |
| 87 | tx: &'a mpsc::Sender<Event>, |
| 88 | call_id: &str, |
| 89 | activity_kind: codewhale_protocol::engine_owner::OwnerActivityKind, |
| 90 | action_id: Option<String>, |
| 91 | cancel: Option<CancellationToken>, |
| 92 | ) -> Self { |
| 93 | let reserve = tx.reserve_many(2); |
| 94 | let permits = match cancel.as_ref() { |
| 95 | Some(cancel) => tokio::select! { |
| 96 | biased; |
| 97 | () = cancel.cancelled() => None, |
| 98 | result = reserve => result.ok(), |
| 99 | }, |
| 100 | None => reserve.await.ok(), |
| 101 | }; |
| 102 | let Some(mut permits) = permits else { |
| 103 | return Self { |
| 104 | start: None, |
| 105 | span: None, |
| 106 | }; |
| 107 | }; |
| 108 | let start = permits.next().expect("reserved activity start"); |
| 109 | let completion = permits.next().expect("reserved activity completion"); |
| 110 | Self { |
| 111 | start: Some(start), |
| 112 | span: Some((completion, Self::span_id(call_id), activity_kind, action_id)), |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | pub fn activate(mut self) -> Self { |
| 117 | if let Some(start) = self.start.take() |
| 118 | && let Some((_, span_id, activity_kind, action_id)) = &self.span |
| 119 | { |
| 120 | start.send(Event::OperationActivityStarted { |
| 121 | span_id: span_id.clone(), |
| 122 | activity_kind: *activity_kind, |
| 123 | action_id: action_id.clone(), |
| 124 | }); |
| 125 | } |
| 126 | self |
| 127 | } |
| 128 | |
| 129 | pub async fn start( |
| 130 | tx: &'a mpsc::Sender<Event>, |
| 131 | call_id: &str, |
| 132 | activity_kind: codewhale_protocol::engine_owner::OwnerActivityKind, |
| 133 | action_id: Option<String>, |
| 134 | cancel: Option<CancellationToken>, |
| 135 | ) -> Self { |
| 136 | Self::reserve(tx, call_id, activity_kind, action_id, cancel) |
| 137 | .await |
| 138 | .activate() |
| 139 | } |
| 140 | |
| 141 | pub async fn complete( |
| 142 | mut self, |
| 143 | outcome: codewhale_protocol::engine_owner::OwnerOperationOutcome, |
| 144 | ) { |
| 145 | if self.start.is_none() |
| 146 | && let Some((permit, span_id, activity_kind, action_id)) = self.span.take() |
| 147 | { |
| 148 | permit.send(Event::OperationActivityCompleted { |
| 149 | span_id, |
| 150 | activity_kind, |
| 151 | action_id, |
| 152 | outcome, |
| 153 | }); |
| 154 | } |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | impl Drop for OperationSpanGuard<'_> { |
| 159 | fn drop(&mut self) { |
| 160 | if self.start.is_none() |
| 161 | && let Some((permit, span_id, activity_kind, action_id)) = self.span.take() |
| 162 | { |
| 163 | permit.send(Event::OperationActivityCompleted { |
| 164 | span_id, |
| 165 | activity_kind, |
| 166 | action_id, |
| 167 | outcome: codewhale_protocol::engine_owner::OwnerOperationOutcome::Cancelled, |
| 168 | }); |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | /// Emits delayed, best-effort liveness pulses for one running tool. |
| 174 | /// |
| 175 | /// Keep the ticker in its own task instead of embedding `tokio::time::Interval` |
| 176 | /// in the already-large engine turn future. Besides keeping the turn future |
| 177 | /// compact, this leaves pre-execution MCP discovery and approval scheduling |
| 178 | /// untouched. Dropping the guard cancels and aborts the ticker synchronously. |
| 179 | struct ToolHeartbeatGuard { |
| 180 | cancel: tokio_util::sync::CancellationToken, |
| 181 | task: tokio::task::JoinHandle<()>, |
| 182 | } |
| 183 | |
| 184 | impl ToolHeartbeatGuard { |
| 185 | fn start(tx_event: mpsc::Sender<Event>, interval: Duration) -> Self { |
| 186 | let cancel = tokio_util::sync::CancellationToken::new(); |
| 187 | let task_cancel = cancel.clone(); |
| 188 | let task = tokio::spawn(async move { |
| 189 | let mut ticker = tokio::time::interval(interval); |
| 190 | ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); |
| 191 | // Tokio intervals tick immediately once. Consume that tick so fast |
| 192 | // tools do not produce a pulse and the first heartbeat is delayed. |
| 193 | ticker.tick().await; |
| 194 | |
| 195 | loop { |
| 196 | tokio::select! { |
| 197 | biased; |
| 198 | |
| 199 | () = task_cancel.cancelled() => break, |
| 200 | _ = ticker.tick() => { |
| 201 | match tx_event.try_send(Event::ToolCallHeartbeat) { |
| 202 | Ok(()) | Err(tokio::sync::mpsc::error::TrySendError::Full(_)) => {} |
| 203 | Err(tokio::sync::mpsc::error::TrySendError::Closed(_)) => break, |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | } |
| 208 | }); |
| 209 | Self { cancel, task } |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | impl Drop for ToolHeartbeatGuard { |
| 214 | fn drop(&mut self) { |
| 215 | self.cancel.cancel(); |
| 216 | self.task.abort(); |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | /// RAII guard that pauses the TUI's terminal-state ownership for the duration |
| 221 | /// of an interactive tool, then restores it on drop. |
| 222 | /// |
| 223 | /// Background: interactive tools (anything that needs the raw TTY — external |
| 224 | /// editor, `exec_shell` with stdin, etc.) need the TUI to leave alt-screen, |
| 225 | /// disable raw mode, and release mouse capture so the child sees a normal |
| 226 | /// terminal. The TUI listens for `Event::PauseEvents` / `Event::ResumeEvents` |
| 227 | /// and runs `pause_terminal` / `resume_terminal` in response. |
| 228 | /// |
| 229 | /// Earlier code sent `PauseEvents` before tool execution and `ResumeEvents` |
| 230 | /// after. That worked on the happy path, but if the tool's future was dropped |
| 231 | /// — Ctrl+C cancellation, sub-agent abort, parent task cancelled while the |
| 232 | /// tool was awaiting — the second `await` never reached and `ResumeEvents` |
| 233 | /// was never sent. It also let interactive children start before the UI had |
| 234 | /// actually left alt-screen/raw mode. Both failures strand the TUI in a |
| 235 | /// regular shell scrollback: the parent shell scrollbar takes over, mouse |
| 236 | /// wheel scrolls the host terminal instead of the transcript, and the TUI |
| 237 | /// renders at the bottom of cooked-mode output. |
| 238 | /// |
| 239 | /// Reserve the matching resume before pausing. `Drop` consumes that permit |
| 240 | /// synchronously, including on cancellation and a full channel. No detached |
| 241 | /// sender can outlive the tool or compete with the turn's terminal event. |
| 242 | pub(super) struct InteractiveTerminalGuard { |
| 243 | resume: Option<(mpsc::Sender<Event>, mpsc::OwnedPermit<Event>)>, |
| 244 | } |
| 245 | |
| 246 | impl InteractiveTerminalGuard { |
| 247 | /// Send `PauseEvents` and arm the guard. If `interactive` is false the |
| 248 | /// guard is a no-op — `Drop` will skip the resume. |
| 249 | pub(super) async fn engage( |
| 250 | tx: mpsc::Sender<Event>, |
| 251 | interactive: bool, |
| 252 | cancel: Option<CancellationToken>, |
| 253 | ) -> Result<Self, ToolError> { |
| 254 | if !interactive { |
| 255 | return Ok(Self { resume: None }); |
| 256 | } |
| 257 | let resume = super::streaming::reserve_event_capacity( |
| 258 | &tx, |
| 259 | cancel.as_ref(), |
| 260 | super::streaming::EventReservationPolicy::Strict, |
| 261 | ) |
| 262 | .await |
| 263 | .map_err(terminal_handoff_send_error)?; |
| 264 | let ack = Arc::new(tokio::sync::Notify::new()); |
| 265 | let pause = super::streaming::reserve_event_capacity( |
| 266 | &tx, |
| 267 | cancel.as_ref(), |
| 268 | super::streaming::EventReservationPolicy::Strict, |
| 269 | ) |
| 270 | .await |
| 271 | .map_err(terminal_handoff_send_error)?; |
| 272 | // No await separates the pause send and guard installation. A |
| 273 | // cancelled reservation above never paused and needs no resume. |
| 274 | pause.send(Event::PauseEvents { |
| 275 | ack: Some(ack.clone()), |
| 276 | }); |
| 277 | let guard = Self { |
| 278 | resume: Some((tx, resume)), |
| 279 | }; |
| 280 | let acknowledged = match cancel.as_ref() { |
| 281 | Some(cancel) => tokio::select! { |
| 282 | biased; |
| 283 | () = cancel.cancelled() => { |
| 284 | return Err(ToolError::cancelled("Terminal handoff cancelled; interactive tool was not launched.")); |
| 285 | } |
| 286 | result = tokio::time::timeout(Duration::from_millis(750), ack.notified()) => result, |
| 287 | }, |
| 288 | None => tokio::time::timeout(Duration::from_millis(750), ack.notified()).await, |
| 289 | }; |
| 290 | if acknowledged.is_err() { |
| 291 | return Err(ToolError::execution_failed( |
| 292 | "Terminal handoff was not acknowledged; interactive tool was not launched.", |
| 293 | )); |
| 294 | } |
| 295 | Ok(guard) |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | fn terminal_handoff_send_error(reason: super::streaming::EventSendError) -> ToolError { |
| 300 | match reason { |
| 301 | super::streaming::EventSendError::Cancelled => { |
| 302 | ToolError::cancelled("Terminal handoff cancelled; interactive tool was not launched.") |
| 303 | } |
| 304 | super::streaming::EventSendError::Closed => ToolError::execution_failed( |
| 305 | "Terminal handoff channel closed; interactive tool was not launched.", |
| 306 | ), |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | impl Drop for InteractiveTerminalGuard { |
| 311 | fn drop(&mut self) { |
| 312 | if let Some((tx, resume)) = self.resume.take() |
| 313 | && !tx.is_closed() |
| 314 | { |
| 315 | resume.send(Event::ResumeEvents); |
| 316 | } |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | pub async fn emit_tool_audit(event: serde_json::Value) { |
| 321 | let Some(path) = std::env::var_os("CODEWHALE_TOOL_AUDIT_LOG") |
| 322 | .or_else(|| std::env::var_os("DEEPSEEK_TOOL_AUDIT_LOG")) |
| 323 | else { |
| 324 | return; |
| 325 | }; |
| 326 | let path = PathBuf::from(path); |
| 327 | if let Err(error) = codewhale_runtime::runtime_control::owner_work(move || { |
| 328 | emit_tool_audit_to_path(&path, event); |
| 329 | Ok(()) |
| 330 | }) |
| 331 | .await |
| 332 | { |
| 333 | tracing::error!("Failed to run the tool audit writer: {error}"); |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | fn emit_tool_audit_to_path(path: &Path, event: serde_json::Value) { |
| 338 | let line = match serde_json::to_string(&event) { |
| 339 | Ok(line) => line, |
| 340 | Err(e) => { |
| 341 | tracing::error!("Failed to serialize tool audit event: {e}"); |
| 342 | return; |
| 343 | } |
| 344 | }; |
| 345 | if let Some(parent) = path.parent() |
| 346 | && let Err(e) = std::fs::create_dir_all(parent) |
| 347 | { |
| 348 | tracing::error!( |
| 349 | "Failed to create audit log directory {}: {e}", |
| 350 | parent.display() |
| 351 | ); |
| 352 | return; |
| 353 | } |
| 354 | match OpenOptions::new().create(true).append(true).open(path) { |
| 355 | Ok(mut file) => { |
| 356 | if let Err(e) = writeln!(file, "{line}") { |
| 357 | tracing::error!("Failed to write to audit log {}: {e}", path.display()); |
| 358 | } |
| 359 | } |
| 360 | Err(e) => { |
| 361 | tracing::error!("Failed to open audit log {}: {e}", path.display()); |
| 362 | } |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | impl Engine { |
| 367 | #[allow(clippy::too_many_arguments)] |
| 368 | pub async fn execute_mcp_tool_with_pool( |
| 369 | pool: Arc<AsyncMutex<McpPool>>, |
| 370 | tx_event: &mpsc::Sender<Event>, |
| 371 | name: &str, |
| 372 | input: serde_json::Value, |
| 373 | disallowed_tools: &[String], |
| 374 | decision: Option<&super::HumanDecision>, |
| 375 | account_fence: Option<&crate::profile_constitution::AccountFence>, |
| 376 | always_binding: Option<u64>, |
| 377 | delegated: Option<Arc<crate::mcp::DelegatedMcpRead>>, |
| 378 | ) -> Result<RichToolResult, ToolError> { |
| 379 | McpPool::authorize_call(disallowed_tools, name, &input) |
| 380 | .map_err(|error| ToolError::not_available(error.to_string()))?; |
| 381 | if let Some(grant) = delegated { |
| 382 | crate::profile_constitution::admit_desktop_browser_call(name, account_fence).await?; |
| 383 | let result = crate::mcp::call_delegated_read_unlocked( |
| 384 | &pool, |
| 385 | &grant, |
| 386 | name, |
| 387 | input, |
| 388 | disallowed_tools, |
| 389 | |_| Ok(()), |
| 390 | ) |
| 391 | .await |
| 392 | .map_err(|error| ToolError::permission_denied(error.to_string()))?; |
| 393 | return Ok(crate::tools::registry::mcp_result_to_bounded_rich_tool_result(result)); |
| 394 | } |
| 395 | // A synthetic `mcp_<server>_authenticate` call runs the shared OAuth |
| 396 | // login flow with the pool lock released during the browser wait, so |
| 397 | // parallel MCP tools and the `/mcp` manager keep working while the |
| 398 | // user signs in. On success it changes the callable MCP surface (the |
| 399 | // server's real tools replace the synthetic one); flag that so the |
| 400 | // turn loop merges the refreshed catalog before the next model |
| 401 | // request instead of leaving the model with names it cannot legally |
| 402 | // call yet. |
| 403 | let auth_target = pool.lock().await.authenticate_tool_target(name); |
| 404 | if let Some(server) = auth_target { |
| 405 | let mut notice_task = None; |
| 406 | let mut result = crate::mcp::authenticate_tool_via_pool(&pool, &server, |url| { |
| 407 | // The model cannot relay the URL until the call returns, and |
| 408 | // the call returns only after the sign-in completes — so the |
| 409 | // user must see it now. This status is the only copy of the |
| 410 | // URL: `try_send` drops it on a full channel, so the send |
| 411 | // waits for room on its own task instead of failing the |
| 412 | // login. |
| 413 | let server = server.clone(); |
| 414 | let url = url.to_string(); |
| 415 | let tx = tx_event.clone(); |
| 416 | notice_task = Some(super::turn_heartbeat::AbortOnDrop(tokio::spawn(async move { |
| 417 | if let Ok(permit) = super::streaming::reserve_event_capacity( |
| 418 | &tx, |
| 419 | None, |
| 420 | super::streaming::EventReservationPolicy::Receipt, |
| 421 | ) |
| 422 | .await |
| 423 | { |
| 424 | permit.send(Event::status(format!( |
| 425 | "◆ auth required: sign in to MCP server '{server}' in your browser — {url}" |
| 426 | ))); |
| 427 | } |
| 428 | }))); |
| 429 | }) |
| 430 | .await |
| 431 | .map_err(|e| ToolError::execution_failed(format!("MCP tool failed: {e}")))?; |
| 432 | if let Some(task) = notice_task.as_mut() { |
| 433 | let _ = (&mut task.0).await; |
| 434 | } |
| 435 | McpPool::filter_authenticate_result(&mut result, disallowed_tools); |
| 436 | let mut rich = crate::tools::registry::mcp_result_to_bounded_rich_tool_result(result); |
| 437 | if rich.result.success { |
| 438 | rich.result.metadata = Some(serde_json::json!({ "mcp_catalog_changed": true })); |
| 439 | } |
| 440 | return Ok(rich); |
| 441 | } |
| 442 | crate::profile_constitution::admit_desktop_browser_call(name, account_fence).await?; |
| 443 | let mut needs_auth_generation_before = None; |
| 444 | let mut binding_changed = false; |
| 445 | let mut reload_error = None; |
| 446 | let result = crate::mcp::call_tool_unlocked( |
| 447 | &pool, |
| 448 | name, |
| 449 | input, |
| 450 | disallowed_tools, |
| 451 | decision, |
| 452 | |pool| { |
| 453 | if let Some(expected) = always_binding { |
| 454 | if let Err(error) = pool.refresh_config_if_changed() { |
| 455 | reload_error = Some(error.to_string()); |
| 456 | anyhow::bail!("MCP configuration could not be reloaded"); |
| 457 | } |
| 458 | if pool.always_allow_binding(name) != Some(expected) { |
| 459 | binding_changed = true; |
| 460 | anyhow::bail!("The connector permission changed. Try the call again."); |
| 461 | } |
| 462 | } |
| 463 | needs_auth_generation_before.get_or_insert(pool.needs_auth_generation()); |
| 464 | Ok(()) |
| 465 | }, |
| 466 | ) |
| 467 | .await; |
| 468 | if binding_changed { |
| 469 | return Err(ToolError::permission_denied( |
| 470 | "The connector permission changed. Try the call again.", |
| 471 | )); |
| 472 | } |
| 473 | if let Some(error) = reload_error { |
| 474 | return Err(ToolError::execution_failed(error)); |
| 475 | } |
| 476 | match result { |
| 477 | Ok(result) => { |
| 478 | Ok(crate::tools::registry::mcp_result_to_bounded_rich_tool_result(result)) |
| 479 | } |
| 480 | Err(error) => { |
| 481 | // A credential the server stopped accepting mid-session |
| 482 | // flips it into the typed needs-auth state and drops its |
| 483 | // connection — the callable surface changed. For THAT |
| 484 | // transition only, return the failure as a result (not an |
| 485 | // Err) carrying `mcp_catalog_changed`, so the turn loop |
| 486 | // replaces the pool's catalog slice: dead tools leave, the |
| 487 | // synthetic login tool arrives, and the error's own hint |
| 488 | // stays model-readable. Every other failure keeps the Err |
| 489 | // contract. |
| 490 | let auth_surface_changed = match needs_auth_generation_before { |
| 491 | Some(before) => pool.lock().await.needs_auth_generation() != before, |
| 492 | None => false, |
| 493 | }; |
| 494 | if !auth_surface_changed { |
| 495 | return Err(ToolError::execution_failed(format!( |
| 496 | "MCP tool failed: {error}" |
| 497 | ))); |
| 498 | } |
| 499 | let tool_result = |
| 500 | crate::tools::spec::ToolResult::error(format!("MCP tool failed: {error}")) |
| 501 | .with_metadata(serde_json::json!({ "mcp_catalog_changed": true })); |
| 502 | Ok(RichToolResult::plain(tool_result)) |
| 503 | } |
| 504 | } |
| 505 | } |
| 506 | |
| 507 | #[allow(clippy::too_many_arguments)] |
| 508 | pub(super) async fn execute_tool_with_lock( |
| 509 | lock: Arc<RwLock<()>>, |
| 510 | supports_parallel: bool, |
| 511 | interactive: bool, |
| 512 | tx_event: mpsc::Sender<Event>, |
| 513 | cancel_token: Option<CancellationToken>, |
| 514 | tool_name: String, |
| 515 | activity_call_id: Option<String>, |
| 516 | tool_input: serde_json::Value, |
| 517 | workspace: PathBuf, |
| 518 | registry: Option<&crate::tools::ToolRegistry>, |
| 519 | mcp_pool: Option<Arc<AsyncMutex<McpPool>>>, |
| 520 | context_override: Option<crate::tools::ToolContext>, |
| 521 | ) -> Result<RichToolResult, ToolError> { |
| 522 | let child = context_override |
| 523 | .as_ref() |
| 524 | .or_else(|| registry.map(|registry| registry.context())) |
| 525 | .and_then(|context| context.child_host.clone()) |
| 526 | .filter(|_| tool_name != EXECUTE_TOOLS_TOOL_NAME); |
| 527 | let execution = Self::execute_tool_admitted( |
| 528 | lock, |
| 529 | supports_parallel, |
| 530 | interactive, |
| 531 | tx_event, |
| 532 | cancel_token, |
| 533 | tool_name, |
| 534 | activity_call_id, |
| 535 | tool_input, |
| 536 | workspace, |
| 537 | registry, |
| 538 | mcp_pool, |
| 539 | context_override, |
| 540 | ); |
| 541 | match child { |
| 542 | Some(child) => child.run_tool_bounded(execution).await, |
| 543 | None => execution.await, |
| 544 | } |
| 545 | } |
| 546 | |
| 547 | #[allow(clippy::too_many_arguments)] |
| 548 | async fn execute_tool_admitted( |
| 549 | lock: Arc<RwLock<()>>, |
| 550 | supports_parallel: bool, |
| 551 | interactive: bool, |
| 552 | tx_event: mpsc::Sender<Event>, |
| 553 | cancel_token: Option<CancellationToken>, |
| 554 | tool_name: String, |
| 555 | activity_call_id: Option<String>, |
| 556 | tool_input: serde_json::Value, |
| 557 | workspace: PathBuf, |
| 558 | registry: Option<&crate::tools::ToolRegistry>, |
| 559 | mcp_pool: Option<Arc<AsyncMutex<McpPool>>>, |
| 560 | context_override: Option<crate::tools::ToolContext>, |
| 561 | ) -> Result<RichToolResult, ToolError> { |
| 562 | if cancel_token |
| 563 | .as_ref() |
| 564 | .is_some_and(CancellationToken::is_cancelled) |
| 565 | { |
| 566 | return Err(ToolError::permission_denied( |
| 567 | "Turn stopped by user. Tool call blocked.", |
| 568 | )); |
| 569 | } |
| 570 | // Unix inherited-terminal shell calls are impossible without a full |
| 571 | // POSIX job-control lease. Refuse them before the terminal guard so a |
| 572 | // known-invalid call cannot flash host scrollback or drain input. |
| 573 | if let Some(error) = inherited_interactive_shell_refusal(&tool_name, interactive) { |
| 574 | return Err(error); |
| 575 | } |
| 576 | // This guard starts before lock acquisition, so contention as well as |
| 577 | // registry/MCP/interpreter execution remains visibly live. |
| 578 | let _heartbeat = ToolHeartbeatGuard::start(tx_event.clone(), TOOL_HEARTBEAT_INTERVAL); |
| 579 | let started_at = std::time::Instant::now(); |
| 580 | let dispatch = if McpPool::is_mcp_tool(&tool_name) { |
| 581 | "mcp" |
| 582 | } else if matches!( |
| 583 | tool_name.as_str(), |
| 584 | CODE_EXECUTION_TOOL_NAME | EXECUTE_TOOLS_TOOL_NAME |
| 585 | ) { |
| 586 | "interpreter" |
| 587 | } else if registry.is_some() { |
| 588 | "registry" |
| 589 | } else { |
| 590 | "missing" |
| 591 | }; |
| 592 | let input_bytes = serde_json::to_string(&tool_input) |
| 593 | .map(|s| s.len()) |
| 594 | .unwrap_or(0); |
| 595 | tracing::debug!( |
| 596 | target: "engine.tool_execution", |
| 597 | tool = %tool_name, |
| 598 | dispatch, |
| 599 | interactive, |
| 600 | supports_parallel, |
| 601 | input_bytes, |
| 602 | "tool.exec.start", |
| 603 | ); |
| 604 | |
| 605 | let acquire = async { |
| 606 | if supports_parallel { |
| 607 | ToolExecGuard::Read { |
| 608 | _guard: lock.read().await, |
| 609 | } |
| 610 | } else { |
| 611 | ToolExecGuard::Write { |
| 612 | _guard: lock.write().await, |
| 613 | } |
| 614 | } |
| 615 | }; |
| 616 | let _guard = match cancel_token.as_ref() { |
| 617 | Some(cancel) => tokio::select! { |
| 618 | biased; |
| 619 | () = cancel.cancelled() => return Err(ToolError::cancelled("Tool lock wait cancelled.")), |
| 620 | guard = acquire => guard, |
| 621 | }, |
| 622 | None => acquire.await, |
| 623 | }; |
| 624 | |
| 625 | // RAII pause/resume: ensures `Event::ResumeEvents` always fires on |
| 626 | // drop, even if the tool future is cancelled mid-await. See |
| 627 | // `InteractiveTerminalGuard` doc-comment for the regression this |
| 628 | // closes (parent terminal scrollback hijacking the TUI after a |
| 629 | // cancelled interactive tool). |
| 630 | let _terminal = |
| 631 | InteractiveTerminalGuard::engage(tx_event.clone(), interactive, cancel_token.clone()) |
| 632 | .await?; |
| 633 | |
| 634 | if cancel_token |
| 635 | .as_ref() |
| 636 | .is_some_and(CancellationToken::is_cancelled) |
| 637 | { |
| 638 | return Err(ToolError::permission_denied( |
| 639 | "Turn stopped by user. Tool call blocked.", |
| 640 | )); |
| 641 | } |
| 642 | |
| 643 | if let Some(context) = context_override |
| 644 | .as_ref() |
| 645 | .or_else(|| registry.map(|registry| registry.context())) |
| 646 | { |
| 647 | crate::tools::execution_envelope::enforce_tool_denial( |
| 648 | context, |
| 649 | &tool_name, |
| 650 | &tool_input, |
| 651 | )?; |
| 652 | } |
| 653 | |
| 654 | let tool_authority = context_override |
| 655 | .as_ref() |
| 656 | .and_then(|context| context.tool_authority.as_ref()) |
| 657 | .or_else(|| registry.and_then(|registry| registry.context().tool_authority.as_ref())); |
| 658 | if let Some(authority) = tool_authority { |
| 659 | if McpPool::is_mcp_tool(&tool_name) |
| 660 | && !super::dispatch::mcp_tool_is_read_only(&tool_name) |
| 661 | && !registry |
| 662 | .filter(|tools| tools.context().child_host.is_some()) |
| 663 | .and_then(|tools| tools.delegated_mcp_read(&tool_name)) |
| 664 | .is_some_and(|grant| grant.permits_arguments(&tool_input)) |
| 665 | { |
| 666 | return Err(ToolError::permission_denied(format!( |
| 667 | "worker '{}' cannot run mutating MCP tool {tool_name}: it has no authorized file target", |
| 668 | authority.owner |
| 669 | ))); |
| 670 | } |
| 671 | if matches!( |
| 672 | tool_name.as_str(), |
| 673 | CODE_EXECUTION_TOOL_NAME | EXECUTE_TOOLS_TOOL_NAME |
| 674 | ) { |
| 675 | return Err(ToolError::permission_denied(format!( |
| 676 | "worker '{}' cannot run {tool_name}: arbitrary code execution is outside its machine-readable authority envelope", |
| 677 | authority.owner |
| 678 | ))); |
| 679 | } |
| 680 | } |
| 681 | |
| 682 | // Typed owner activity: classified only after every gate above has |
| 683 | // passed, from the same authority that dispatches the call (the MCP |
| 684 | // pool's resolved server map, the interpreter, or the registry plus |
| 685 | // the canonical action alias). Arguments never leave here. |
| 686 | let activity_kind = match activity_call_id.as_ref() { |
| 687 | None => None, |
| 688 | Some(_) if McpPool::is_mcp_tool(&tool_name) => match mcp_pool.as_ref() { |
| 689 | Some(pool) => pool |
| 690 | .lock() |
| 691 | .await |
| 692 | .resolved_tool_servers() |
| 693 | .get(&tool_name) |
| 694 | .map(|server| crate::tools::activity::mcp_activity_kind(server)), |
| 695 | None => None, |
| 696 | }, |
| 697 | Some(_) if tool_name == CODE_EXECUTION_TOOL_NAME => { |
| 698 | Some(codewhale_protocol::engine_owner::OwnerActivityKind::Executing) |
| 699 | } |
| 700 | Some(_) => registry |
| 701 | .filter(|registry| registry.get(&tool_name).is_some()) |
| 702 | .and_then(|_| { |
| 703 | crate::tools::activity::registry_activity_kind(&tool_name, &tool_input) |
| 704 | }), |
| 705 | }; |
| 706 | if cancel_token |
| 707 | .as_ref() |
| 708 | .is_some_and(CancellationToken::is_cancelled) |
| 709 | { |
| 710 | return Err(ToolError::cancelled("Tool activity admission cancelled.")); |
| 711 | } |
| 712 | |
| 713 | let child_mcp_call = if McpPool::is_mcp_tool(&tool_name) { |
| 714 | let context = context_override |
| 715 | .as_ref() |
| 716 | .or_else(|| registry.map(|registry| registry.context())); |
| 717 | if context.is_some_and(|context| context.child_host.is_some()) { |
| 718 | let registry = registry.ok_or_else(|| { |
| 719 | ToolError::permission_denied( |
| 720 | "child MCP call has no canonical registered capability", |
| 721 | ) |
| 722 | })?; |
| 723 | registry |
| 724 | .admit_child_call( |
| 725 | &tool_name, |
| 726 | &tool_input, |
| 727 | context.expect("captured child context"), |
| 728 | ) |
| 729 | .await? |
| 730 | } else { |
| 731 | None |
| 732 | } |
| 733 | } else { |
| 734 | None |
| 735 | }; |
| 736 | let context = context_override |
| 737 | .as_ref() |
| 738 | .or_else(|| registry.map(|registry| registry.context())); |
| 739 | let protocol_host = context |
| 740 | .is_some_and(|context| context.acp_host.is_some() || context.child_host.is_some()); |
| 741 | let execution_receipt = match activity_call_id { |
| 742 | Some(_) => match super::streaming::reserve_event_capacity( |
| 743 | &tx_event, |
| 744 | cancel_token.as_ref(), |
| 745 | super::streaming::EventReservationPolicy::Receipt, |
| 746 | ) |
| 747 | .await |
| 748 | { |
| 749 | Ok(permit) => Some(permit), |
| 750 | Err(_) if protocol_host => { |
| 751 | return Err(ToolError::cancelled("ACP dispatch observation unavailable")); |
| 752 | } |
| 753 | Err(_) => None, |
| 754 | }, |
| 755 | None => None, |
| 756 | }; |
| 757 | let operation_span = match (activity_call_id.as_deref(), activity_kind) { |
| 758 | (Some(call_id), Some(kind)) => Some( |
| 759 | OperationSpanGuard::reserve( |
| 760 | &tx_event, |
| 761 | call_id, |
| 762 | kind, |
| 763 | Some(crate::tools::activity::action_id(&tool_name, &tool_input)), |
| 764 | cancel_token.clone(), |
| 765 | ) |
| 766 | .await, |
| 767 | ), |
| 768 | _ => None, |
| 769 | }; |
| 770 | let on_admitted = || { |
| 771 | if cancel_token |
| 772 | .as_ref() |
| 773 | .is_some_and(CancellationToken::is_cancelled) |
| 774 | { |
| 775 | return Err(ToolError::cancelled("Tool activity admission cancelled.")); |
| 776 | } |
| 777 | if let Some(context) = context |
| 778 | && (context.acp_host.is_some() || context.child_host.is_some()) |
| 779 | { |
| 780 | let acp_mcp_call = context.acp_host.is_some() && McpPool::is_mcp_tool(&tool_name); |
| 781 | if !acp_mcp_call |
| 782 | && (context.acp_host.is_some() || tool_name != EXECUTE_TOOLS_TOOL_NAME) |
| 783 | { |
| 784 | let spec = registry |
| 785 | .and_then(|registry| registry.get(&tool_name)) |
| 786 | .ok_or_else(|| { |
| 787 | ToolError::not_available("ACP call has no admitted registered tool") |
| 788 | })?; |
| 789 | crate::tools::registry::enforce_tool_authority( |
| 790 | &tool_name, |
| 791 | &tool_input, |
| 792 | spec.as_ref(), |
| 793 | context, |
| 794 | )?; |
| 795 | } |
| 796 | crate::extension_host::validate_caller_plugins(context.plugin_registry.as_deref()) |
| 797 | .map_err(ToolError::not_available)?; |
| 798 | } |
| 799 | if let Some(permit) = execution_receipt { |
| 800 | permit.send(Event::ToolExecutionStarted { |
| 801 | id: activity_call_id |
| 802 | .as_ref() |
| 803 | .expect("reserved execution identity") |
| 804 | .clone(), |
| 805 | }); |
| 806 | } |
| 807 | Ok(operation_span.map(OperationSpanGuard::activate)) |
| 808 | }; |
| 809 | let telemetry_tool_name = if codewhale_telemetry::event::TOOL_NAMES |
| 810 | .contains(&tool_name.as_str()) |
| 811 | { |
| 812 | tool_name.as_str() |
| 813 | } else { |
| 814 | codewhale_execpolicy::canonical_action::canonical_action_alias(&tool_name, &tool_input) |
| 815 | }; |
| 816 | let registry_dispatch = !McpPool::is_mcp_tool(&tool_name) |
| 817 | && !matches!( |
| 818 | tool_name.as_str(), |
| 819 | CODE_EXECUTION_TOOL_NAME | EXECUTE_TOOLS_TOOL_NAME |
| 820 | ); |
| 821 | let outcome = if registry_dispatch { |
| 822 | match registry { |
| 823 | Some(registry) => { |
| 824 | registry |
| 825 | .execute_rich_full_with_context( |
| 826 | &tool_name, |
| 827 | tool_input.clone(), |
| 828 | context_override.as_ref(), |
| 829 | on_admitted, |
| 830 | ) |
| 831 | .await |
| 832 | } |
| 833 | None => Err(ToolError::not_available(format!( |
| 834 | "tool '{tool_name}' is not registered" |
| 835 | ))), |
| 836 | } |
| 837 | } else { |
| 838 | let operation_span = on_admitted()?; |
| 839 | let outcome: Result<RichToolResult, ToolError> = if McpPool::is_mcp_tool(&tool_name) { |
| 840 | if let Some(pool) = mcp_pool { |
| 841 | let disallowed_tools = context_override |
| 842 | .as_ref() |
| 843 | .or_else(|| registry.map(|registry| registry.context())) |
| 844 | .map(|context| context.disallowed_tools.as_slice()) |
| 845 | .unwrap_or_default(); |
| 846 | // Only a per-call override can carry a person's decision; the |
| 847 | // registry's shared context never does. |
| 848 | let decision = context_override |
| 849 | .as_ref() |
| 850 | .and_then(|context| context.human_decision.as_ref()); |
| 851 | let account_fence = context_override |
| 852 | .as_ref() |
| 853 | .or_else(|| registry.map(|registry| registry.context())) |
| 854 | .and_then(|context| context.account_fence.as_deref()); |
| 855 | Engine::execute_mcp_tool_with_pool( |
| 856 | pool, |
| 857 | &tx_event, |
| 858 | &tool_name, |
| 859 | tool_input, |
| 860 | disallowed_tools, |
| 861 | decision, |
| 862 | account_fence, |
| 863 | context_override |
| 864 | .as_ref() |
| 865 | .and_then(|context| context.mcp_always_binding), |
| 866 | child_mcp_call |
| 867 | .as_ref() |
| 868 | .and_then(|_| registry?.delegated_mcp_read(&tool_name)), |
| 869 | ) |
| 870 | .await |
| 871 | } else { |
| 872 | Err(ToolError::not_available(format!( |
| 873 | "tool '{tool_name}' is not registered" |
| 874 | ))) |
| 875 | } |
| 876 | } else if tool_name == CODE_EXECUTION_TOOL_NAME { |
| 877 | if let Some(context) = context_override |
| 878 | .as_ref() |
| 879 | .or_else(|| registry.map(|registry| registry.context())) |
| 880 | { |
| 881 | execute_code_execution_tool(&tool_input, &workspace, context) |
| 882 | .await |
| 883 | .map(RichToolResult::plain) |
| 884 | } else { |
| 885 | Err(ToolError::not_available( |
| 886 | "local code execution requires an effective tool context", |
| 887 | )) |
| 888 | } |
| 889 | } else if tool_name == EXECUTE_TOOLS_TOOL_NAME { |
| 890 | if let Some(registry) = registry { |
| 891 | let context = context_override |
| 892 | .as_ref() |
| 893 | .cloned() |
| 894 | .unwrap_or_else(|| registry.context().clone()); |
| 895 | crate::tools::codemode::execute_tools_tool(&tool_input, registry, &context) |
| 896 | .await |
| 897 | .map(RichToolResult::plain) |
| 898 | } else { |
| 899 | Err(ToolError::not_available(format!( |
| 900 | "tool '{tool_name}' is not registered" |
| 901 | ))) |
| 902 | } |
| 903 | } else { |
| 904 | Err(ToolError::not_available(format!( |
| 905 | "tool '{tool_name}' is not registered" |
| 906 | ))) |
| 907 | }; |
| 908 | if let Some(operation_span) = operation_span { |
| 909 | operation_span |
| 910 | .complete(crate::tools::activity::operation_outcome( |
| 911 | &outcome, |
| 912 | cancel_token |
| 913 | .as_ref() |
| 914 | .is_some_and(CancellationToken::is_cancelled), |
| 915 | )) |
| 916 | .await; |
| 917 | } |
| 918 | outcome |
| 919 | }; |
| 920 | |
| 921 | if outcome.as_ref().is_ok_and(|result| result.result.success) |
| 922 | && let Some((authority, writes)) = child_mcp_call |
| 923 | { |
| 924 | authority.record_settled_writes(writes).await; |
| 925 | } |
| 926 | let duration_ms = started_at.elapsed().as_millis() as u64; |
| 927 | // The surface-agnostic choke point for every tool call, so this one |
| 928 | // bump covers exec and the CLI as well as the TUI. `memory_search` is |
| 929 | // counted here for the same reason — one site, not one per tool. |
| 930 | let telemetry = codewhale_telemetry::session_counters(); |
| 931 | telemetry.bump(codewhale_telemetry::Counter::ToolCalls); |
| 932 | telemetry.record_tool_call( |
| 933 | telemetry_tool_name, |
| 934 | dispatch == "mcp", |
| 935 | !outcome.as_ref().is_ok_and(|result| result.result.success), |
| 936 | ); |
| 937 | if tool_name == "memory_search" { |
| 938 | telemetry.bump(codewhale_telemetry::Counter::MemorySearch); |
| 939 | } |
| 940 | match &outcome { |
| 941 | Ok(result) => { |
| 942 | tracing::debug!( |
| 943 | target: "engine.tool_execution", |
| 944 | tool = %tool_name, |
| 945 | dispatch, |
| 946 | duration_ms, |
| 947 | success = result.result.success, |
| 948 | output_bytes = result.result.content.len(), |
| 949 | "tool.exec.end", |
| 950 | ); |
| 951 | } |
| 952 | Err(err) => { |
| 953 | let kind = match err { |
| 954 | ToolError::InvalidInput { .. } => "invalid_input", |
| 955 | ToolError::MissingField { .. } => "missing_field", |
| 956 | ToolError::PathEscape { .. } => "path_escape", |
| 957 | ToolError::ExecutionFailed { .. } => "execution_failed", |
| 958 | ToolError::Timeout { .. } => "timeout", |
| 959 | ToolError::Cancelled { .. } => "cancelled", |
| 960 | ToolError::NotAvailable { .. } => "not_available", |
| 961 | ToolError::PermissionDenied { .. } => "permission_denied", |
| 962 | }; |
| 963 | // The discriminant and nothing else. `ToolError::PathEscape`'s |
| 964 | // `Display` *is* an absolute path, and several sibling |
| 965 | // variants render a literal source fragment the model emitted. |
| 966 | match err { |
| 967 | ToolError::PermissionDenied { .. } => { |
| 968 | telemetry.bump_error(codewhale_telemetry::ErrorCounter::ToolDeniedByPolicy) |
| 969 | } |
| 970 | ToolError::Timeout { .. } => { |
| 971 | telemetry.bump_error(codewhale_telemetry::ErrorCounter::ToolTimeout); |
| 972 | } |
| 973 | _ => {} |
| 974 | } |
| 975 | tracing::warn!( |
| 976 | target: "engine.tool_execution", |
| 977 | tool = %tool_name, |
| 978 | dispatch, |
| 979 | duration_ms, |
| 980 | error_kind = kind, |
| 981 | "tool.exec.end", |
| 982 | ); |
| 983 | } |
| 984 | } |
| 985 | outcome |
| 986 | } |
| 987 | } |
| 988 | |
| 989 | #[cfg(test)] |
| 990 | mod tests { |
| 991 | use super::*; |
| 992 | use serde_json::json; |
| 993 | use std::time::Duration; |
| 994 | |
| 995 | const TEST_HEARTBEAT_INTERVAL: Duration = Duration::from_millis(10); |
| 996 | |
| 997 | #[tokio::test] |
| 998 | async fn tool_heartbeat_emits_for_slow_tool() { |
| 999 | let (tx, mut rx) = mpsc::channel(4); |
| 1000 | let guard = ToolHeartbeatGuard::start(tx, TEST_HEARTBEAT_INTERVAL); |
| 1001 | |
| 1002 | let event = tokio::time::timeout(Duration::from_secs(1), rx.recv()) |
| 1003 | .await |
| 1004 | .expect("heartbeat before slow tool completes") |
| 1005 | .expect("event channel stays open"); |
| 1006 | |
| 1007 | assert!(matches!(event, Event::ToolCallHeartbeat)); |
| 1008 | drop(guard); |
| 1009 | } |
| 1010 | |
| 1011 | #[tokio::test] |
| 1012 | async fn event_capacity_cancelled_activity_preserves_exact_outcomes_and_releases_full_queue() { |
| 1013 | use codewhale_protocol::engine_owner::{OwnerActivityKind, OwnerOperationOutcome}; |
| 1014 | for outcome in [ |
| 1015 | OwnerOperationOutcome::Succeeded, |
| 1016 | OwnerOperationOutcome::Failed, |
| 1017 | OwnerOperationOutcome::Denied, |
| 1018 | OwnerOperationOutcome::Cancelled, |
| 1019 | ] { |
| 1020 | let (tx, mut rx) = mpsc::channel(2); |
| 1021 | let cancel = CancellationToken::new(); |
| 1022 | let span = OperationSpanGuard::start( |
| 1023 | &tx, |
| 1024 | "completed-call", |
| 1025 | OwnerActivityKind::Tool, |
| 1026 | Some("tool".into()), |
| 1027 | Some(cancel.clone()), |
| 1028 | ) |
| 1029 | .await; |
| 1030 | cancel.cancel(); |
| 1031 | tokio::time::timeout(Duration::from_millis(100), span.complete(outcome)) |
| 1032 | .await |
| 1033 | .expect("completed activity preserves available capacity after cancellation"); |
| 1034 | let Event::OperationActivityStarted { |
| 1035 | span_id, |
| 1036 | activity_kind, |
| 1037 | action_id, |
| 1038 | } = rx.try_recv().unwrap() |
| 1039 | else { |
| 1040 | panic!("activity start"); |
| 1041 | }; |
| 1042 | let Event::OperationActivityCompleted { |
| 1043 | span_id: completed_span, |
| 1044 | activity_kind: completed_kind, |
| 1045 | outcome: completed_outcome, |
| 1046 | action_id: completed_action, |
| 1047 | } = rx |
| 1048 | .try_recv() |
| 1049 | .expect("cancellation must not discard the completion") |
| 1050 | else { |
| 1051 | panic!("activity completion"); |
| 1052 | }; |
| 1053 | assert_eq!(completed_span, span_id); |
| 1054 | assert_eq!(completed_kind, activity_kind); |
| 1055 | assert_eq!(completed_action, action_id); |
| 1056 | assert_eq!( |
| 1057 | completed_outcome, outcome, |
| 1058 | "retain the observed outcome exactly" |
| 1059 | ); |
| 1060 | assert!(rx.try_recv().is_err(), "exactly one completion"); |
| 1061 | } |
| 1062 | |
| 1063 | let (tx, mut rx) = mpsc::channel(512); |
| 1064 | let mut spans = Vec::new(); |
| 1065 | for i in 0..256 { |
| 1066 | spans.push( |
| 1067 | OperationSpanGuard::start( |
| 1068 | &tx, |
| 1069 | &format!("full-call-{i}"), |
| 1070 | OwnerActivityKind::Tool, |
| 1071 | Some("tool".into()), |
| 1072 | None, |
| 1073 | ) |
| 1074 | .await, |
| 1075 | ); |
| 1076 | } |
| 1077 | assert_eq!(tx.capacity(), 0); |
| 1078 | drop(spans); |
| 1079 | let mut starts = 0; |
| 1080 | let mut cancelled = 0; |
| 1081 | while let Ok(event) = rx.try_recv() { |
| 1082 | match event { |
| 1083 | Event::OperationActivityStarted { .. } => starts += 1, |
| 1084 | Event::OperationActivityCompleted { |
| 1085 | outcome: OwnerOperationOutcome::Cancelled, |
| 1086 | .. |
| 1087 | } => cancelled += 1, |
| 1088 | other => panic!("unexpected activity receipt: {other:?}"), |
| 1089 | } |
| 1090 | } |
| 1091 | assert_eq!((starts, cancelled), (256, 256)); |
| 1092 | assert_eq!(tx.capacity(), 512); |
| 1093 | let (tx, mut rx) = mpsc::channel(1); |
| 1094 | let span = |
| 1095 | OperationSpanGuard::start(&tx, "too-small", OwnerActivityKind::Tool, None, None).await; |
| 1096 | drop(span); |
| 1097 | assert!(rx.try_recv().is_err(), "never publish an unpaired start"); |
| 1098 | } |
| 1099 | |
| 1100 | #[tokio::test] |
| 1101 | async fn tool_heartbeat_is_delayed_for_fast_tool() { |
| 1102 | let (tx, mut rx) = mpsc::channel(4); |
| 1103 | |
| 1104 | let guard = ToolHeartbeatGuard::start(tx, TEST_HEARTBEAT_INTERVAL); |
| 1105 | drop(guard); |
| 1106 | tokio::time::sleep(TEST_HEARTBEAT_INTERVAL * 2).await; |
| 1107 | |
| 1108 | assert!(rx.try_recv().is_err(), "fast tool emitted a heartbeat"); |
| 1109 | } |
| 1110 | |
| 1111 | #[tokio::test] |
| 1112 | async fn tool_heartbeat_stops_after_tool_completes() { |
| 1113 | let (tx, mut rx) = mpsc::channel(8); |
| 1114 | let guard = ToolHeartbeatGuard::start(tx, TEST_HEARTBEAT_INTERVAL); |
| 1115 | |
| 1116 | let event = tokio::time::timeout(Duration::from_secs(1), rx.recv()) |
| 1117 | .await |
| 1118 | .expect("heartbeat before slow tool completes") |
| 1119 | .expect("event channel stays open"); |
| 1120 | assert!(matches!(event, Event::ToolCallHeartbeat)); |
| 1121 | |
| 1122 | drop(guard); |
| 1123 | tokio::task::yield_now().await; |
| 1124 | while rx.try_recv().is_ok() {} |
| 1125 | tokio::time::sleep(TEST_HEARTBEAT_INTERVAL * 2).await; |
| 1126 | assert!( |
| 1127 | rx.try_recv().is_err(), |
| 1128 | "heartbeat continued after tool completion" |
| 1129 | ); |
| 1130 | } |
| 1131 | |
| 1132 | #[tokio::test] |
| 1133 | async fn full_event_channel_never_blocks_tool_heartbeat() { |
| 1134 | let (tx, mut rx) = mpsc::channel(1); |
| 1135 | tx.try_send(Event::status("filler")).expect("fill channel"); |
| 1136 | |
| 1137 | let result = tokio::time::timeout(Duration::from_secs(1), async { |
| 1138 | let guard = ToolHeartbeatGuard::start(tx, TEST_HEARTBEAT_INTERVAL); |
| 1139 | tokio::time::sleep(TEST_HEARTBEAT_INTERVAL * 3).await; |
| 1140 | drop(guard); |
| 1141 | "done" |
| 1142 | }) |
| 1143 | .await |
| 1144 | .expect("full event channel must not block tool completion"); |
| 1145 | |
| 1146 | assert_eq!(result, "done"); |
| 1147 | assert!(matches!(rx.recv().await, Some(Event::Status { .. }))); |
| 1148 | assert!(rx.try_recv().is_err(), "heartbeat displaced queued event"); |
| 1149 | } |
| 1150 | |
| 1151 | #[tokio::test] |
| 1152 | async fn terminal_guard_queues_resume_when_event_channel_is_full() { |
| 1153 | let (tx, mut rx) = mpsc::channel(2); |
| 1154 | let resume = tx.clone().reserve_owned().await.expect("resume capacity"); |
| 1155 | tx.try_send(Event::status("filler")).expect("fill channel"); |
| 1156 | |
| 1157 | drop(InteractiveTerminalGuard { |
| 1158 | resume: Some((tx, resume)), |
| 1159 | }); |
| 1160 | |
| 1161 | assert!(matches!(rx.recv().await, Some(Event::Status { .. }))); |
| 1162 | let resumed = tokio::time::timeout(Duration::from_secs(1), rx.recv()) |
| 1163 | .await |
| 1164 | .expect("queued resume event") |
| 1165 | .expect("event channel still open"); |
| 1166 | assert!(matches!(resumed, Event::ResumeEvents)); |
| 1167 | assert!(rx.try_recv().is_err(), "restoration is exactly once"); |
| 1168 | } |
| 1169 | |
| 1170 | #[tokio::test] |
| 1171 | async fn terminal_guard_waits_for_pause_ack_before_returning() { |
| 1172 | let (tx, mut rx) = mpsc::channel(4); |
| 1173 | let task = tokio::spawn(InteractiveTerminalGuard::engage(tx, true, None)); |
| 1174 | |
| 1175 | let event = tokio::time::timeout(Duration::from_secs(1), rx.recv()) |
| 1176 | .await |
| 1177 | .expect("pause event") |
| 1178 | .expect("event channel still open"); |
| 1179 | let ack = match event { |
| 1180 | Event::PauseEvents { ack: Some(ack) } => ack, |
| 1181 | other => panic!("expected PauseEvents with ack, got {other:?}"), |
| 1182 | }; |
| 1183 | |
| 1184 | tokio::task::yield_now().await; |
| 1185 | assert!(!task.is_finished(), "guard returned before pause ack"); |
| 1186 | |
| 1187 | ack.notify_one(); |
| 1188 | let guard = tokio::time::timeout(Duration::from_secs(1), task) |
| 1189 | .await |
| 1190 | .expect("guard returned after ack") |
| 1191 | .expect("guard task joined") |
| 1192 | .expect("terminal handoff acknowledged"); |
| 1193 | |
| 1194 | drop(guard); |
| 1195 | let resumed = tokio::time::timeout(Duration::from_secs(1), rx.recv()) |
| 1196 | .await |
| 1197 | .expect("resume event") |
| 1198 | .expect("event channel still open"); |
| 1199 | assert!(matches!(resumed, Event::ResumeEvents)); |
| 1200 | } |
| 1201 | |
| 1202 | #[tokio::test] |
| 1203 | async fn terminal_guard_refuses_child_and_queues_resume_when_pause_is_not_acknowledged() { |
| 1204 | let (tx, mut rx) = mpsc::channel(4); |
| 1205 | let task = tokio::spawn(InteractiveTerminalGuard::engage(tx, true, None)); |
| 1206 | |
| 1207 | let event = tokio::time::timeout(Duration::from_secs(1), rx.recv()) |
| 1208 | .await |
| 1209 | .expect("pause event") |
| 1210 | .expect("event channel still open"); |
| 1211 | let _unacknowledged_pause = match event { |
| 1212 | Event::PauseEvents { ack: Some(ack) } => ack, |
| 1213 | other => panic!("expected PauseEvents with ack, got {other:?}"), |
| 1214 | }; |
| 1215 | |
| 1216 | let handoff = tokio::time::timeout(Duration::from_secs(2), task) |
| 1217 | .await |
| 1218 | .expect("guard refused child after pause timeout") |
| 1219 | .expect("guard task joined"); |
| 1220 | let err = match handoff { |
| 1221 | Ok(_) => panic!("unacknowledged terminal handoff must fail closed"), |
| 1222 | Err(err) => err, |
| 1223 | }; |
| 1224 | assert!( |
| 1225 | err.to_string().contains("was not acknowledged"), |
| 1226 | "unexpected handoff error: {err}" |
| 1227 | ); |
| 1228 | |
| 1229 | let resumed = tokio::time::timeout(Duration::from_secs(1), rx.recv()) |
| 1230 | .await |
| 1231 | .expect("queued resume event") |
| 1232 | .expect("event channel still open"); |
| 1233 | assert!(matches!(resumed, Event::ResumeEvents)); |
| 1234 | } |
| 1235 | |
| 1236 | #[tokio::test] |
| 1237 | async fn terminal_guard_cancellation_during_pause_ack_still_queues_resume() { |
| 1238 | let (tx, mut rx) = mpsc::channel(4); |
| 1239 | let task = tokio::spawn(InteractiveTerminalGuard::engage(tx, true, None)); |
| 1240 | |
| 1241 | let event = tokio::time::timeout(Duration::from_secs(1), rx.recv()) |
| 1242 | .await |
| 1243 | .expect("pause event") |
| 1244 | .expect("event channel still open"); |
| 1245 | let _unacknowledged_pause = match event { |
| 1246 | Event::PauseEvents { ack: Some(ack) } => ack, |
| 1247 | other => panic!("expected PauseEvents with ack, got {other:?}"), |
| 1248 | }; |
| 1249 | |
| 1250 | task.abort(); |
| 1251 | let cancelled = match task.await { |
| 1252 | Ok(_) => panic!("engage future should be cancelled"), |
| 1253 | Err(cancelled) => cancelled, |
| 1254 | }; |
| 1255 | assert!(cancelled.is_cancelled()); |
| 1256 | |
| 1257 | let resumed = tokio::time::timeout(Duration::from_secs(1), rx.recv()) |
| 1258 | .await |
| 1259 | .expect("queued resume event") |
| 1260 | .expect("event channel still open"); |
| 1261 | assert!(matches!(resumed, Event::ResumeEvents)); |
| 1262 | } |
| 1263 | |
| 1264 | #[tokio::test] |
| 1265 | async fn terminal_guard_cancelled_capacity_reservations_never_pause_or_restore() { |
| 1266 | for capacity in [1, 2] { |
| 1267 | let (tx, mut rx) = mpsc::channel(capacity); |
| 1268 | tx.try_send(Event::status("occupied")).unwrap(); |
| 1269 | let cancel = CancellationToken::new(); |
| 1270 | let mut engage = Box::pin(InteractiveTerminalGuard::engage( |
| 1271 | tx.clone(), |
| 1272 | true, |
| 1273 | Some(cancel.clone()), |
| 1274 | )); |
| 1275 | assert!( |
| 1276 | tokio::time::timeout(Duration::from_millis(20), &mut engage) |
| 1277 | .await |
| 1278 | .is_err() |
| 1279 | ); |
| 1280 | // Capacity 1 stalls the resume reservation; capacity 2 stalls |
| 1281 | // the pause reservation while the first permit is held. |
| 1282 | cancel.cancel(); |
| 1283 | assert!( |
| 1284 | tokio::time::timeout(Duration::from_secs(1), &mut engage) |
| 1285 | .await |
| 1286 | .unwrap() |
| 1287 | .is_err() |
| 1288 | ); |
| 1289 | drop(engage); |
| 1290 | assert!(matches!(rx.try_recv(), Ok(Event::Status { .. }))); |
| 1291 | assert!( |
| 1292 | rx.try_recv().is_err(), |
| 1293 | "a pause that never entered needs no resume" |
| 1294 | ); |
| 1295 | assert_eq!( |
| 1296 | tx.capacity(), |
| 1297 | capacity, |
| 1298 | "cancelled waits release every permit" |
| 1299 | ); |
| 1300 | } |
| 1301 | } |
| 1302 | |
| 1303 | #[tokio::test] |
| 1304 | async fn terminal_guard_cancelled_ack_restores_once_without_detached_sender() { |
| 1305 | let (tx, mut rx) = mpsc::channel(3); |
| 1306 | let cancel = CancellationToken::new(); |
| 1307 | let task = tokio::spawn(InteractiveTerminalGuard::engage( |
| 1308 | tx.clone(), |
| 1309 | true, |
| 1310 | Some(cancel.clone()), |
| 1311 | )); |
| 1312 | assert!(matches!(rx.recv().await, Some(Event::PauseEvents { .. }))); |
| 1313 | tx.try_send(Event::status("fill after pause")).unwrap(); |
| 1314 | cancel.cancel(); |
| 1315 | assert!( |
| 1316 | tokio::time::timeout(Duration::from_secs(1), task) |
| 1317 | .await |
| 1318 | .unwrap() |
| 1319 | .unwrap() |
| 1320 | .is_err() |
| 1321 | ); |
| 1322 | assert!(matches!(rx.try_recv(), Ok(Event::Status { .. }))); |
| 1323 | assert!(matches!(rx.try_recv(), Ok(Event::ResumeEvents))); |
| 1324 | assert!(rx.try_recv().is_err()); |
| 1325 | assert_eq!(tx.capacity(), 3); |
| 1326 | } |
| 1327 | |
| 1328 | #[tokio::test] |
| 1329 | async fn terminal_guard_closed_receiver_refuses_or_releases_held_restoration() { |
| 1330 | let (tx, rx) = mpsc::channel(3); |
| 1331 | drop(rx); |
| 1332 | assert!( |
| 1333 | InteractiveTerminalGuard::engage(tx, true, None) |
| 1334 | .await |
| 1335 | .is_err() |
| 1336 | ); |
| 1337 | |
| 1338 | let (tx, mut rx) = mpsc::channel(3); |
| 1339 | let task = tokio::spawn(InteractiveTerminalGuard::engage(tx.clone(), true, None)); |
| 1340 | let Some(Event::PauseEvents { ack: Some(ack) }) = rx.recv().await else { |
| 1341 | panic!("pause with acknowledgement"); |
| 1342 | }; |
| 1343 | ack.notify_one(); |
| 1344 | let guard = task.await.unwrap().unwrap(); |
| 1345 | drop(rx); |
| 1346 | drop(guard); |
| 1347 | assert!(tx.is_closed()); |
| 1348 | assert_eq!( |
| 1349 | tx.capacity(), |
| 1350 | 3, |
| 1351 | "receiver closure cannot strand restoration capacity" |
| 1352 | ); |
| 1353 | } |
| 1354 | |
| 1355 | #[cfg(unix)] |
| 1356 | #[test] |
| 1357 | fn inherited_interactive_shell_is_refused_before_terminal_handoff() { |
| 1358 | for tool_name in ["bash", "Bash", "exec_shell"] { |
| 1359 | let err = inherited_interactive_shell_refusal(tool_name, true) |
| 1360 | .expect("Unix inherited-interactive shell must fail preflight"); |
| 1361 | assert!( |
| 1362 | err.to_string().contains("foreground TTY ownership"), |
| 1363 | "{tool_name}: {err}" |
| 1364 | ); |
| 1365 | } |
| 1366 | assert!(inherited_interactive_shell_refusal("Bash", false).is_none()); |
| 1367 | assert!( |
| 1368 | inherited_interactive_shell_refusal(REQUEST_USER_INPUT_NAME, true).is_none(), |
| 1369 | "user-input modal keeps its own terminal handoff" |
| 1370 | ); |
| 1371 | } |
| 1372 | |
| 1373 | #[test] |
| 1374 | fn emit_tool_audit_to_path_writes_jsonl_lines() { |
| 1375 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1376 | let path = tmp.path().join("audit.log"); |
| 1377 | let marker = path.display().to_string(); |
| 1378 | |
| 1379 | emit_tool_audit_to_path( |
| 1380 | &path, |
| 1381 | json!({ |
| 1382 | "event": "tool.spillover", |
| 1383 | "test_marker": marker, |
| 1384 | "tool_id": "call-abc", |
| 1385 | "tool_name": "exec_shell", |
| 1386 | "path": "/tmp/foo.txt", |
| 1387 | }), |
| 1388 | ); |
| 1389 | emit_tool_audit_to_path( |
| 1390 | &path, |
| 1391 | json!({ |
| 1392 | "event": "tool.result", |
| 1393 | "test_marker": marker, |
| 1394 | "tool_id": "call-xyz", |
| 1395 | "success": true, |
| 1396 | }), |
| 1397 | ); |
| 1398 | |
| 1399 | let body = std::fs::read_to_string(&path).expect("audit log written"); |
| 1400 | let entries: Vec<serde_json::Value> = body |
| 1401 | .lines() |
| 1402 | .map(|line| serde_json::from_str(line).expect("audit line is JSON")) |
| 1403 | .filter(|entry: &serde_json::Value| { |
| 1404 | entry.get("test_marker").and_then(|v| v.as_str()) == Some(marker.as_str()) |
| 1405 | }) |
| 1406 | .collect(); |
| 1407 | assert_eq!(entries.len(), 2, "two marked emits -> two lines"); |
| 1408 | |
| 1409 | // Each line round-trips as JSON, has the expected event key. |
| 1410 | let first = &entries[0]; |
| 1411 | assert_eq!( |
| 1412 | first.get("event").and_then(|v| v.as_str()), |
| 1413 | Some("tool.spillover") |
| 1414 | ); |
| 1415 | assert_eq!( |
| 1416 | first.get("tool_id").and_then(|v| v.as_str()), |
| 1417 | Some("call-abc") |
| 1418 | ); |
| 1419 | |
| 1420 | let second = &entries[1]; |
| 1421 | assert_eq!( |
| 1422 | second.get("event").and_then(|v| v.as_str()), |
| 1423 | Some("tool.result") |
| 1424 | ); |
| 1425 | } |
| 1426 | |
| 1427 | #[test] |
| 1428 | fn emit_tool_audit_creates_parent_directory() { |
| 1429 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1430 | // Path with a parent that doesn't exist yet — the writer |
| 1431 | // should create it. |
| 1432 | let nested = tmp.path().join("nested").join("dir").join("audit.log"); |
| 1433 | emit_tool_audit_to_path(&nested, json!({"event": "test"})); |
| 1434 | assert!(nested.exists(), "writer should mkdir -p the parent chain"); |
| 1435 | } |
| 1436 | } |
| 1437 |