| 1 | //! Public `EngineHandle` methods. |
| 2 | //! |
| 3 | //! The struct itself lives next door in `engine.rs` because two |
| 4 | //! construction sites (`Engine::new` and the test-only |
| 5 | //! `mock_engine_handle`) need access to its private mpsc channels. |
| 6 | //! The method surface — `send`, `cancel*`, `is_cancelled`, |
| 7 | //! `approve_tool_call` / `deny_tool_call` / `retry_tool_with_policy`, |
| 8 | //! `submit_user_input` / `cancel_user_input`, and `steer` — moves here |
| 9 | //! so the agent loop's mailbox API is reviewable on its own. |
| 10 | |
| 11 | use anyhow::Result; |
| 12 | use std::collections::VecDeque; |
| 13 | use std::sync::{Arc, Mutex as StdMutex}; |
| 14 | use tokio::sync::{mpsc, oneshot}; |
| 15 | use tokio_util::sync::CancellationToken; |
| 16 | |
| 17 | use codewhale_config::AppMode; |
| 18 | use codewhale_execpolicy::ApprovalMode; |
| 19 | |
| 20 | use super::approval::{ApprovalDecision, SubmittedApproval, UserInputDecision}; |
| 21 | use super::{ |
| 22 | CancelReason, EngineHandle, EngineRunCompletion, LiveRuntimeAuthority, Op, |
| 23 | RuntimePermissionAuthority, UserInputResponse, |
| 24 | }; |
| 25 | use crate::approval_log::ApprovalDecider; |
| 26 | use crate::core::authority::auto_review::{AutoReviewBlockedAction, AutoReviewRetryGrant}; |
| 27 | |
| 28 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 29 | pub enum AutoReviewRetryApprovalError { |
| 30 | OwnerRequired, |
| 31 | NotInAutoReview, |
| 32 | InvalidTarget(String), |
| 33 | } |
| 34 | |
| 35 | impl std::fmt::Display for AutoReviewRetryApprovalError { |
| 36 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 37 | match self { |
| 38 | Self::OwnerRequired => { |
| 39 | f.write_str("owner surface is required to approve Auto-Review retry") |
| 40 | } |
| 41 | Self::NotInAutoReview => { |
| 42 | f.write_str("Auto-Review retry can only be approved while Auto-Review is active") |
| 43 | } |
| 44 | Self::InvalidTarget(msg) => f.write_str(msg), |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | impl std::error::Error for AutoReviewRetryApprovalError {} |
| 50 | |
| 51 | // This bounds host delivery/acknowledgement, never the person's time to |
| 52 | // answer. No active waiter may consume a reply after its caller abandoned it. |
| 53 | const USER_INPUT_ACK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5); |
| 54 | |
| 55 | impl EngineHandle { |
| 56 | pub fn replace_user_permission_ruleset(&self, ruleset: codewhale_execpolicy::Ruleset) { |
| 57 | self.exec_policy.clone().set_ruleset(ruleset); |
| 58 | } |
| 59 | |
| 60 | #[must_use] |
| 61 | pub fn exec_policy(&self) -> &codewhale_execpolicy::ExecPolicyEngine { |
| 62 | &self.exec_policy |
| 63 | } |
| 64 | |
| 65 | #[cfg(any(test, feature = "test-support"))] |
| 66 | pub fn set_exec_policy(&mut self, exec_policy: codewhale_execpolicy::ExecPolicyEngine) { |
| 67 | self.exec_policy = exec_policy; |
| 68 | } |
| 69 | |
| 70 | /// Wait for this exact background run to return or terminate abnormally. |
| 71 | /// Cancelling a wait does not stop the engine or consume another waiter's result. |
| 72 | /// Directly constructed handles return `NotObserved`; completion does not prove |
| 73 | /// persistence succeeded or detached children and blocking writers stopped. |
| 74 | pub async fn wait_run_completion(&self) -> EngineRunCompletion { |
| 75 | let Some(mut completion) = self.run_completion.clone() else { |
| 76 | return EngineRunCompletion::NotObserved; |
| 77 | }; |
| 78 | loop { |
| 79 | let outcome = *completion.borrow_and_update(); |
| 80 | if let Some(outcome) = outcome { |
| 81 | return outcome; |
| 82 | } |
| 83 | if completion.changed().await.is_err() { |
| 84 | return EngineRunCompletion::AbnormalTermination; |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | async fn await_user_input_acceptance( |
| 91 | sender: &mpsc::Sender<UserInputDecision>, |
| 92 | decision: UserInputDecision, |
| 93 | mut accepted: oneshot::Receiver<bool>, |
| 94 | timeout: std::time::Duration, |
| 95 | ) -> Result<()> { |
| 96 | let delivery = tokio::time::timeout(timeout, async { |
| 97 | sender |
| 98 | .send(decision) |
| 99 | .await |
| 100 | .map_err(|_| anyhow::anyhow!("Engine is not accepting user input"))?; |
| 101 | (&mut accepted).await.map_err(|_| { |
| 102 | anyhow::anyhow!("Engine ended the user input request before accepting this decision") |
| 103 | }) |
| 104 | }) |
| 105 | .await; |
| 106 | let accepted = match delivery { |
| 107 | Ok(result) => result?, |
| 108 | Err(_) => { |
| 109 | // Close first: after this point Engine's verdict send cannot |
| 110 | // succeed. A verdict already delivered before the bound wins |
| 111 | // over the timeout, so a consumed answer is never called rejected. |
| 112 | accepted.close(); |
| 113 | accepted.try_recv().unwrap_or(false) |
| 114 | } |
| 115 | }; |
| 116 | anyhow::ensure!( |
| 117 | accepted, |
| 118 | "User input request is no longer accepting this decision" |
| 119 | ); |
| 120 | Ok(()) |
| 121 | } |
| 122 | |
| 123 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 124 | pub(super) struct RustTurnOrigin { |
| 125 | pub run_origin: crate::core::authority::auto_review::RunOrigin, |
| 126 | pub owner_present: bool, |
| 127 | } |
| 128 | |
| 129 | #[derive(Clone)] |
| 130 | pub(super) struct TurnControl { |
| 131 | pub id: u64, |
| 132 | pub narrowing: super::host_profile::TurnNarrowing, |
| 133 | pub origin: Option<RustTurnOrigin>, |
| 134 | pub cancel: CancellationToken, |
| 135 | pub reason: Arc<StdMutex<Option<CancelReason>>>, |
| 136 | } |
| 137 | |
| 138 | #[derive(Default)] |
| 139 | pub(super) struct TurnControls { |
| 140 | next_id: u64, |
| 141 | pub active: Option<TurnControl>, |
| 142 | pub pending: VecDeque<TurnControl>, |
| 143 | } |
| 144 | |
| 145 | impl TurnControls { |
| 146 | pub fn fresh(&mut self) -> TurnControl { |
| 147 | self.next_id = self |
| 148 | .next_id |
| 149 | .checked_add(1) |
| 150 | .expect("turn control id exhausted"); |
| 151 | TurnControl { |
| 152 | id: self.next_id, |
| 153 | narrowing: super::host_profile::TurnNarrowing::Inherit, |
| 154 | origin: None, |
| 155 | cancel: CancellationToken::new(), |
| 156 | reason: Arc::new(StdMutex::new(None)), |
| 157 | } |
| 158 | } |
| 159 | |
| 160 | fn target(&self) -> Option<&TurnControl> { |
| 161 | self.active.as_ref().or_else(|| self.pending.front()) |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | pub(super) struct TurnControlGuard { |
| 166 | pub controls: Arc<StdMutex<TurnControls>>, |
| 167 | pub id: u64, |
| 168 | pub narrowing: super::host_profile::TurnNarrowing, |
| 169 | pub origin: Option<RustTurnOrigin>, |
| 170 | } |
| 171 | |
| 172 | impl Drop for TurnControlGuard { |
| 173 | fn drop(&mut self) { |
| 174 | let mut controls = self |
| 175 | .controls |
| 176 | .lock() |
| 177 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 178 | if controls |
| 179 | .active |
| 180 | .as_ref() |
| 181 | .is_some_and(|active| active.id == self.id) |
| 182 | { |
| 183 | controls.active = None; |
| 184 | } |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | #[derive(Debug)] |
| 189 | pub struct SteerInput { |
| 190 | pub(super) turn_id: Option<u64>, |
| 191 | pub(super) replace_pending: bool, |
| 192 | pub content: String, |
| 193 | pub(super) person_text: Option<String>, |
| 194 | pub(super) outcome: Option<oneshot::Sender<SteerOutcome>>, |
| 195 | pub(super) owner_steer: bool, |
| 196 | } |
| 197 | |
| 198 | /// The engine's verdict on one steer. A steer whose turn had already moved |
| 199 | /// on is discarded by `next_turn_steer`; the verdict tells the sender which |
| 200 | /// happened, because "the channel accepted the text" is not "the model saw |
| 201 | /// it" (#6276). |
| 202 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 203 | pub enum SteerOutcome { |
| 204 | /// The steer's text was committed into the session record inside the |
| 205 | /// turn it was sent to; the model received it. |
| 206 | Accepted, |
| 207 | /// The turn had already moved on (or ended) before the steer reached a |
| 208 | /// commit boundary. The model never saw the text. |
| 209 | Dropped, |
| 210 | } |
| 211 | |
| 212 | /// A steer the engine has taken ownership of. Committing it reports |
| 213 | /// [`SteerOutcome::Accepted`]; any other exit — interrupt, failure, early |
| 214 | /// return, silent drop of the pending queue — reports `Dropped` from `Drop`, |
| 215 | /// so no path can lose a verdict. |
| 216 | pub struct PendingSteer { |
| 217 | pub replace_pending: bool, |
| 218 | pub content: String, |
| 219 | person_text: Option<String>, |
| 220 | outcome: Option<oneshot::Sender<SteerOutcome>>, |
| 221 | owner_steer: bool, |
| 222 | } |
| 223 | |
| 224 | impl PendingSteer { |
| 225 | pub fn new(content: String, outcome: Option<oneshot::Sender<SteerOutcome>>) -> Self { |
| 226 | Self { |
| 227 | content, |
| 228 | person_text: None, |
| 229 | outcome, |
| 230 | replace_pending: false, |
| 231 | owner_steer: false, |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | #[cfg(test)] |
| 236 | pub(super) const fn is_owner_steer(&self) -> bool { |
| 237 | self.owner_steer |
| 238 | } |
| 239 | |
| 240 | /// Commit the steer into the turn's record: report `Accepted`, then hand |
| 241 | /// back the text. Consuming `self` without calling this reports |
| 242 | /// `Dropped` via `Drop`. |
| 243 | pub fn commit(mut self) -> String { |
| 244 | if let Some(outcome) = self.outcome.take() { |
| 245 | let _ = outcome.send(SteerOutcome::Accepted); |
| 246 | } |
| 247 | // `Drop` runs after this returns and finds `outcome` already taken, |
| 248 | // so the verdict stays exactly one `Accepted`. |
| 249 | std::mem::take(&mut self.content) |
| 250 | } |
| 251 | |
| 252 | pub(super) fn commit_with_owner_intent(mut self) -> (String, bool, Option<String>) { |
| 253 | let owner_steer = self.owner_steer; |
| 254 | let person_text = self.person_text.take(); |
| 255 | (self.commit(), owner_steer, person_text) |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | impl Drop for PendingSteer { |
| 260 | fn drop(&mut self) { |
| 261 | if let Some(outcome) = self.outcome.take() { |
| 262 | let _ = outcome.send(SteerOutcome::Dropped); |
| 263 | } |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | impl SteerInput { |
| 268 | /// Take ownership of this steer as an unsettled [`PendingSteer`]. |
| 269 | /// |
| 270 | /// This is the only way to claim a steer off the channel. Whatever the |
| 271 | /// claimant then does — `commit()` or drop — settles it exactly once, so |
| 272 | /// there is one settlement mechanism rather than two (#6276). |
| 273 | pub fn into_pending(mut self) -> PendingSteer { |
| 274 | // Both fields are taken, so the `Drop` below finds nothing left to |
| 275 | // settle and the verdict travels with the `PendingSteer`. |
| 276 | let mut pending = PendingSteer::new(std::mem::take(&mut self.content), self.outcome.take()); |
| 277 | pending.replace_pending = self.replace_pending; |
| 278 | pending.person_text = self.person_text.take(); |
| 279 | pending.owner_steer = self.owner_steer; |
| 280 | pending |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | impl Drop for SteerInput { |
| 285 | fn drop(&mut self) { |
| 286 | if let Some(outcome) = self.outcome.take() { |
| 287 | let _ = outcome.send(SteerOutcome::Dropped); |
| 288 | } |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | impl std::ops::Deref for SteerInput { |
| 293 | type Target = str; |
| 294 | fn deref(&self) -> &str { |
| 295 | &self.content |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | impl std::fmt::Display for SteerInput { |
| 300 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 301 | self.content.fmt(f) |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | pub struct SteerPermit { |
| 306 | permit: mpsc::OwnedPermit<SteerInput>, |
| 307 | turn_id: Option<u64>, |
| 308 | owner_steer: bool, |
| 309 | } |
| 310 | |
| 311 | impl SteerPermit { |
| 312 | pub fn send(self, content: String) { |
| 313 | self.permit.send(SteerInput { |
| 314 | turn_id: self.turn_id, |
| 315 | replace_pending: false, |
| 316 | content, |
| 317 | person_text: None, |
| 318 | outcome: None, |
| 319 | owner_steer: self.owner_steer, |
| 320 | }); |
| 321 | } |
| 322 | |
| 323 | pub fn send_with_person_text(self, content: String, person_text: Option<String>) { |
| 324 | self.permit.send(SteerInput { |
| 325 | turn_id: self.turn_id, |
| 326 | replace_pending: false, |
| 327 | content, |
| 328 | person_text, |
| 329 | outcome: None, |
| 330 | owner_steer: self.owner_steer, |
| 331 | }); |
| 332 | } |
| 333 | |
| 334 | /// Send a steer and receive the engine's verdict on it. The receiver |
| 335 | /// resolves to [`SteerOutcome::Accepted`] when the turn commits the text |
| 336 | /// into its record, [`SteerOutcome::Dropped`] when the turn moved on |
| 337 | /// first, and closes without a verdict only if the engine itself is gone |
| 338 | /// (#6276). |
| 339 | pub fn send_with_outcome(self, content: String) -> oneshot::Receiver<SteerOutcome> { |
| 340 | let owner_steer = self.owner_steer; |
| 341 | self.send_with_replacement_outcome(content, None, false, owner_steer) |
| 342 | } |
| 343 | |
| 344 | pub fn send_with_outcome_and_authorship( |
| 345 | self, |
| 346 | content: String, |
| 347 | owner_steer: bool, |
| 348 | person_text: Option<String>, |
| 349 | ) -> oneshot::Receiver<SteerOutcome> { |
| 350 | let allowed_owner_steer = self.owner_steer && owner_steer; |
| 351 | self.send_with_replacement_outcome(content, person_text, false, allowed_owner_steer) |
| 352 | } |
| 353 | |
| 354 | pub fn send_replacing_with_outcome(self, content: String) -> oneshot::Receiver<SteerOutcome> { |
| 355 | let owner_steer = self.owner_steer; |
| 356 | self.send_with_replacement_outcome(content, None, true, owner_steer) |
| 357 | } |
| 358 | |
| 359 | fn send_with_replacement_outcome( |
| 360 | self, |
| 361 | content: String, |
| 362 | person_text: Option<String>, |
| 363 | replace_pending: bool, |
| 364 | owner_steer: bool, |
| 365 | ) -> oneshot::Receiver<SteerOutcome> { |
| 366 | let (outcome_tx, outcome_rx) = oneshot::channel(); |
| 367 | self.permit.send(SteerInput { |
| 368 | turn_id: self.turn_id, |
| 369 | replace_pending, |
| 370 | content, |
| 371 | person_text, |
| 372 | outcome: Some(outcome_tx), |
| 373 | owner_steer, |
| 374 | }); |
| 375 | outcome_rx |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | impl EngineHandle { |
| 380 | /// The engine's turn-phase heartbeat (#6184). Hosts read it to tell a |
| 381 | /// bounded model wait from a wedged turn without inferring liveness from |
| 382 | /// the stream-chunk timeout. |
| 383 | #[must_use] |
| 384 | pub fn turn_heartbeat(&self) -> &Arc<super::turn_heartbeat::TurnHeartbeat> { |
| 385 | &self.turn_heartbeat |
| 386 | } |
| 387 | |
| 388 | /// Called only while Runtime holds the idle turn admission claim. The |
| 389 | /// following SendMessage refreshes the existing prompt/config projection. |
| 390 | pub fn restore_runtime_goal( |
| 391 | &self, |
| 392 | goal: Option<&codewhale_protocol::ThreadGoal>, |
| 393 | ) -> Result<()> { |
| 394 | let mut state = self |
| 395 | .goal_state |
| 396 | .lock() |
| 397 | .map_err(|_| anyhow::anyhow!("goal state lock poisoned"))?; |
| 398 | let current = state.snapshot(); |
| 399 | if current.goal_id.as_deref() != goal.map(|goal| goal.goal_id.as_str()) { |
| 400 | *state = goal.map_or_else(crate::tools::goal::GoalState::default, |goal| { |
| 401 | crate::tools::goal::GoalState::from_snapshot( |
| 402 | &crate::tools::goal::GoalSnapshot::from_thread_goal(goal), |
| 403 | ) |
| 404 | }); |
| 405 | } |
| 406 | Ok(()) |
| 407 | } |
| 408 | |
| 409 | /// Apply the host's latest durable goal control to the live continuation |
| 410 | /// gate. The mailbox drains only between turns, so it cannot carry stop |
| 411 | /// controls. A replacement parks the old goal until normal turn admission |
| 412 | /// restores the new revision; it never starts a second turn here. |
| 413 | pub fn sync_runtime_goal_control( |
| 414 | &self, |
| 415 | goal: Option<&codewhale_protocol::ThreadGoal>, |
| 416 | ) -> Result<()> { |
| 417 | let mut state = self |
| 418 | .goal_state |
| 419 | .lock() |
| 420 | .map_err(|_| anyhow::anyhow!("goal state lock poisoned"))?; |
| 421 | let current = state.snapshot(); |
| 422 | let Some(goal) = goal else { |
| 423 | state.clear(); |
| 424 | return Ok(()); |
| 425 | }; |
| 426 | if current.goal_id.as_deref() != Some(goal.goal_id.as_str()) { |
| 427 | if state.is_active() { |
| 428 | state.sync_from_host_status( |
| 429 | current.objective.as_deref(), |
| 430 | current.token_budget, |
| 431 | crate::tools::goal::GoalStatus::Paused, |
| 432 | ); |
| 433 | } |
| 434 | } else { |
| 435 | let (status, pause_reason) = crate::tools::goal::thread_goal_status_projection( |
| 436 | goal.status.clone(), |
| 437 | goal.pause_reason, |
| 438 | ); |
| 439 | if status != crate::tools::goal::GoalStatus::Active { |
| 440 | state.sync_from_host_status_with_reason( |
| 441 | current.objective.as_deref(), |
| 442 | current.token_budget, |
| 443 | status, |
| 444 | pause_reason, |
| 445 | ); |
| 446 | } |
| 447 | } |
| 448 | Ok(()) |
| 449 | } |
| 450 | |
| 451 | /// True when the caller must preflight a concrete provider client before |
| 452 | /// committing UI/runtime turn state. Test and embedding handles with an |
| 453 | /// injected model client return false because that client owns model I/O. |
| 454 | #[must_use] |
| 455 | pub fn client_preflight_required(&self) -> bool { |
| 456 | self.client_preflight_required |
| 457 | } |
| 458 | |
| 459 | pub fn retire_mcp_for_handoff(&self) -> Option<crate::mcp::McpHandoff> { |
| 460 | let mut slot = self |
| 461 | .mcp_pool_slot |
| 462 | .lock() |
| 463 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 464 | slot.handed_off = true; |
| 465 | if let Some(handoff) = slot.handoff.take() { |
| 466 | return Some(handoff); |
| 467 | } |
| 468 | let pool = slot.pool.upgrade()?; |
| 469 | let mut pool = pool.try_lock().ok()?; |
| 470 | Some(pool.retire_for_handoff()) |
| 471 | } |
| 472 | |
| 473 | /// Send an operation to the engine |
| 474 | /// |
| 475 | /// This awaits channel capacity, and the engine drains `rx_op` only |
| 476 | /// between turns — so on the UI event loop an awaited send into a |
| 477 | /// saturated mailbox freezes input for the rest of the turn (#6150). |
| 478 | /// Input-path callers instead either `try_send` a droppable op (report |
| 479 | /// the rejection) or `try_reserve_owned` before committing UI state and |
| 480 | /// hand off with `send_reserved_op`. An awaited `send` remains correct |
| 481 | /// only where the operation is part of a committed, ordered transition |
| 482 | /// (session/provider reload) whose drop would desync engine and UI. |
| 483 | pub async fn send(&self, op: Op) -> Result<()> { |
| 484 | let authority = Self::change_mode_authority(&op); |
| 485 | let permit = self.tx_op.clone().reserve_owned().await?; |
| 486 | if let Some(authority) = authority { |
| 487 | self.publish_runtime_authority(authority); |
| 488 | } |
| 489 | self.send_reserved_op(permit, op); |
| 490 | Ok(()) |
| 491 | } |
| 492 | |
| 493 | /// Try to send an operation without blocking. |
| 494 | /// |
| 495 | /// Returns `Err` if the channel is full or closed. Use this for |
| 496 | /// non-critical, refresh-type ops (e.g. `Op::ListSubAgents`) that can |
| 497 | /// safely be dropped and re-requested on the next drain cycle. |
| 498 | pub fn try_send(&self, op: Op) -> Result<()> { |
| 499 | let authority = Self::change_mode_authority(&op); |
| 500 | let result = self.tx_op.clone().try_reserve_owned(); |
| 501 | // A full channel already guarantees that the engine will wake and |
| 502 | // drain an operation. Publish the typed authority anyway: the drain |
| 503 | // applies pending authority before handling that queued operation, so |
| 504 | // a posture edit never blocks behind refresh traffic. A closed |
| 505 | // channel has no engine left to observe the update. |
| 506 | if !matches!(&result, Err(mpsc::error::TrySendError::Closed(_))) |
| 507 | && let Some(authority) = authority |
| 508 | { |
| 509 | self.publish_runtime_authority(authority); |
| 510 | } |
| 511 | // Keep the public error bound to the rejected operation. Callers use |
| 512 | // TrySendError<Op> to distinguish a retryable full mailbox from a |
| 513 | // stopped engine; reservation errors otherwise carry a Sender<Op>. |
| 514 | match result { |
| 515 | Ok(permit) => { |
| 516 | self.send_reserved_op(permit, op); |
| 517 | Ok(()) |
| 518 | } |
| 519 | Err(mpsc::error::TrySendError::Full(_)) => { |
| 520 | Err(mpsc::error::TrySendError::Full(op).into()) |
| 521 | } |
| 522 | Err(mpsc::error::TrySendError::Closed(_)) => { |
| 523 | Err(mpsc::error::TrySendError::Closed(op).into()) |
| 524 | } |
| 525 | } |
| 526 | } |
| 527 | |
| 528 | pub(crate) fn set_owner_surface_attached(&mut self, attached: bool) { |
| 529 | self.owner_surface_attached = attached; |
| 530 | } |
| 531 | |
| 532 | pub(crate) fn set_host_profile( |
| 533 | &mut self, |
| 534 | host_profile: super::host_profile::EngineHostProfile, |
| 535 | ) { |
| 536 | self.host_profile = host_profile; |
| 537 | } |
| 538 | |
| 539 | /// Bind controls and enqueue under one lock, preserving the same FIFO as |
| 540 | /// the operation mailbox even when several senders hold reserved slots. |
| 541 | pub fn send_reserved_op(&self, permit: mpsc::OwnedPermit<Op>, op: Op) { |
| 542 | self.send_reserved_narrowed_op( |
| 543 | permit, |
| 544 | op, |
| 545 | super::host_profile::TurnNarrowing::Inherit, |
| 546 | None, |
| 547 | ); |
| 548 | } |
| 549 | |
| 550 | /// Called only by the captured ACP Runtime admission. One lock retains the |
| 551 | /// exact control/mailbox FIFO; no profile is added to the public operation. |
| 552 | pub fn send_reserved_acp_op(&self, permit: mpsc::OwnedPermit<Op>, op: Op) { |
| 553 | self.send_reserved_narrowed_op( |
| 554 | permit, |
| 555 | op, |
| 556 | super::host_profile::TurnNarrowing::Acp, |
| 557 | Some(RustTurnOrigin { |
| 558 | run_origin: crate::core::authority::auto_review::RunOrigin::Headless, |
| 559 | owner_present: false, |
| 560 | }), |
| 561 | ); |
| 562 | } |
| 563 | |
| 564 | pub(crate) fn send_reserved_op_with_origin( |
| 565 | &self, |
| 566 | permit: mpsc::OwnedPermit<Op>, |
| 567 | op: Op, |
| 568 | narrowing: super::host_profile::TurnNarrowing, |
| 569 | run_origin: crate::core::authority::auto_review::RunOrigin, |
| 570 | owner_present: bool, |
| 571 | ) { |
| 572 | use crate::core::authority::auto_review::RunOrigin; |
| 573 | let origin = if matches!(narrowing, super::host_profile::TurnNarrowing::Acp) |
| 574 | || self.host_profile.is_acp() |
| 575 | || self.host_profile.is_headless() |
| 576 | { |
| 577 | RustTurnOrigin { |
| 578 | run_origin: RunOrigin::Headless, |
| 579 | owner_present: false, |
| 580 | } |
| 581 | } else { |
| 582 | let owner_present = run_origin == RunOrigin::Interactive |
| 583 | && owner_present |
| 584 | && self.owner_surface_attached; |
| 585 | let run_origin = if run_origin == RunOrigin::Interactive && !owner_present { |
| 586 | RunOrigin::Background |
| 587 | } else { |
| 588 | run_origin |
| 589 | }; |
| 590 | RustTurnOrigin { |
| 591 | run_origin, |
| 592 | owner_present, |
| 593 | } |
| 594 | }; |
| 595 | self.send_reserved_narrowed_op(permit, op, narrowing, Some(origin)); |
| 596 | } |
| 597 | |
| 598 | fn send_reserved_narrowed_op( |
| 599 | &self, |
| 600 | permit: mpsc::OwnedPermit<Op>, |
| 601 | op: Op, |
| 602 | narrowing: super::host_profile::TurnNarrowing, |
| 603 | origin: Option<RustTurnOrigin>, |
| 604 | ) { |
| 605 | let mut controls = self |
| 606 | .turn_controls |
| 607 | .lock() |
| 608 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 609 | if matches!(&op, Op::SendMessage(_) | Op::Review { .. }) { |
| 610 | let mut control = controls.fresh(); |
| 611 | control.narrowing = narrowing; |
| 612 | control.origin = origin; |
| 613 | controls.pending.push_back(control); |
| 614 | } |
| 615 | permit.send(op); |
| 616 | } |
| 617 | |
| 618 | fn change_mode_authority(op: &Op) -> Option<LiveRuntimeAuthority> { |
| 619 | let Op::ChangeMode { |
| 620 | mode, |
| 621 | allow_shell, |
| 622 | trust_mode, |
| 623 | auto_approve, |
| 624 | approval_mode, |
| 625 | configured_sandbox_mode, |
| 626 | } = op |
| 627 | else { |
| 628 | return None; |
| 629 | }; |
| 630 | Some(LiveRuntimeAuthority::from_fields( |
| 631 | *mode, |
| 632 | *allow_shell, |
| 633 | *trust_mode, |
| 634 | *auto_approve, |
| 635 | *approval_mode, |
| 636 | configured_sandbox_mode.clone(), |
| 637 | )) |
| 638 | } |
| 639 | |
| 640 | fn publish_runtime_authority(&self, authority: LiveRuntimeAuthority) { |
| 641 | let mut state = self |
| 642 | .live_runtime_authority |
| 643 | .lock() |
| 644 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 645 | let approval_changed = state.authority.approval_mode != authority.approval_mode; |
| 646 | let mode_changed = state.authority.mode != authority.mode; |
| 647 | state.revision = state.revision.wrapping_add(1).max(1); |
| 648 | state.authority = authority; |
| 649 | if (approval_changed && state.authority.approval_mode != ApprovalMode::Auto) || mode_changed |
| 650 | { |
| 651 | self.auto_review_state.lock().revoke_retry_grants(); |
| 652 | } |
| 653 | } |
| 654 | |
| 655 | pub fn publish_turn_authority( |
| 656 | &self, |
| 657 | mode: AppMode, |
| 658 | allow_shell: bool, |
| 659 | trust_mode: bool, |
| 660 | auto_approve: bool, |
| 661 | approval_mode: ApprovalMode, |
| 662 | configured_sandbox_mode: Option<String>, |
| 663 | ) { |
| 664 | self.publish_runtime_authority(LiveRuntimeAuthority::from_fields( |
| 665 | mode, |
| 666 | allow_shell, |
| 667 | trust_mode, |
| 668 | auto_approve, |
| 669 | approval_mode, |
| 670 | configured_sandbox_mode, |
| 671 | )); |
| 672 | } |
| 673 | |
| 674 | /// Exact live permission authority for runtime approval and elevation |
| 675 | /// gates. This is the same typed state the active engine turn drains. |
| 676 | #[must_use] |
| 677 | pub fn runtime_permission_authority(&self) -> RuntimePermissionAuthority { |
| 678 | self.live_runtime_authority |
| 679 | .lock() |
| 680 | .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 681 | .authority |
| 682 | .permission_snapshot() |
| 683 | } |
| 684 | |
| 685 | /// Reserve capacity for a runtime steer before it mutates durable state. |
| 686 | /// The owned permit lets the caller persist and dispatch synchronously, |
| 687 | /// without a cancellation point between those two operations. |
| 688 | pub async fn reserve_steer(&self) -> Result<SteerPermit> { |
| 689 | let permit = self.tx_steer.clone().reserve_owned().await?; |
| 690 | let (turn_id, owner_steer) = self.steer_target(); |
| 691 | Ok(SteerPermit { |
| 692 | permit, |
| 693 | turn_id, |
| 694 | owner_steer, |
| 695 | }) |
| 696 | } |
| 697 | |
| 698 | pub fn reserve_current_steer( |
| 699 | &self, |
| 700 | ) -> impl Future<Output = Result<SteerPermit>> + Send + 'static { |
| 701 | let sender = self.tx_steer.clone(); |
| 702 | let (turn_id, owner_steer) = self.steer_target(); |
| 703 | async move { |
| 704 | let permit = sender.reserve_owned().await?; |
| 705 | Ok(SteerPermit { |
| 706 | permit, |
| 707 | turn_id, |
| 708 | owner_steer, |
| 709 | }) |
| 710 | } |
| 711 | } |
| 712 | |
| 713 | fn steer_target(&self) -> (Option<u64>, bool) { |
| 714 | let controls = self |
| 715 | .turn_controls |
| 716 | .lock() |
| 717 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 718 | let target = controls.target(); |
| 719 | let turn_id = target.map(|control| control.id); |
| 720 | let target_acp = target.is_some_and(|control| { |
| 721 | matches!(control.narrowing, super::host_profile::TurnNarrowing::Acp) |
| 722 | }); |
| 723 | let owner_steer = self.owner_surface_attached |
| 724 | && matches!( |
| 725 | self.host_profile, |
| 726 | super::host_profile::EngineHostProfile::Normal |
| 727 | ) |
| 728 | && !target_acp; |
| 729 | (turn_id, owner_steer) |
| 730 | } |
| 731 | |
| 732 | /// Cancel the current request (user-initiated path — keeps the |
| 733 | /// public `cancel()` signature stable). Equivalent to |
| 734 | /// `cancel_with_reason(CancelReason::User)`. |
| 735 | pub fn cancel(&self) { |
| 736 | self.cancel_with_reason(CancelReason::User); |
| 737 | } |
| 738 | |
| 739 | /// Cancel the current request and latch the reason so downstream |
| 740 | /// "request cancelled" error messages can name a cause. |
| 741 | pub fn cancel_with_reason(&self, reason: CancelReason) { |
| 742 | // Keep turn activation excluded until both the admitted control and |
| 743 | // the legacy shared token have been canceled. |
| 744 | let controls = self |
| 745 | .turn_controls |
| 746 | .lock() |
| 747 | .unwrap_or_else(std::sync::PoisonError::into_inner); |
| 748 | if let Some(control) = controls.target() { |
| 749 | *control |
| 750 | .reason |
| 751 | .lock() |
| 752 | .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(reason); |
| 753 | control.cancel.cancel(); |
| 754 | } |
| 755 | match self.cancel_reason.lock() { |
| 756 | Ok(mut slot) => *slot = Some(reason), |
| 757 | Err(poisoned) => *poisoned.into_inner() = Some(reason), |
| 758 | } |
| 759 | match self.cancel_token.lock() { |
| 760 | Ok(token) => token.cancel(), |
| 761 | Err(poisoned) => poisoned.into_inner().cancel(), |
| 762 | } |
| 763 | codewhale_runtime::retry_status::clear(); |
| 764 | #[cfg(any(test, feature = "test-support"))] |
| 765 | if let Some(sources) = self.mock_approval_publications.as_ref() { |
| 766 | let pending = sources.lock().drain().collect::<Vec<_>>(); |
| 767 | let runtime = tokio::runtime::Handle::try_current().ok(); |
| 768 | for (id, (source, producer)) in pending { |
| 769 | let receipt = crate::approval_log::ApprovalReceipt::decided_with( |
| 770 | id, |
| 771 | crate::approval_log::ApprovalOutcome::Cancelled, |
| 772 | Some(ApprovalDecider::Host), |
| 773 | ); |
| 774 | let committed = source.commit_mock_outcome(receipt).unwrap_or(false); |
| 775 | if let Some(runtime) = runtime.as_ref() { |
| 776 | runtime.spawn(async move { |
| 777 | let _producer = producer; |
| 778 | if committed { |
| 779 | let _ = source.published().await; |
| 780 | } |
| 781 | }); |
| 782 | } |
| 783 | } |
| 784 | } |
| 785 | } |
| 786 | |
| 787 | /// Snapshot the exact existing target control for one captured transport |
| 788 | /// wait. It cannot follow a later turn or reset the admitted token. |
| 789 | pub fn captured_turn_cancel(&self) -> CancellationToken { |
| 790 | self.turn_controls |
| 791 | .lock() |
| 792 | .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 793 | .target() |
| 794 | .map(|control| control.cancel.clone()) |
| 795 | .unwrap_or_else(|| { |
| 796 | self.cancel_token |
| 797 | .lock() |
| 798 | .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 799 | .clone() |
| 800 | }) |
| 801 | } |
| 802 | |
| 803 | /// Check if a request is currently cancelled |
| 804 | #[must_use] |
| 805 | pub fn is_cancelled(&self) -> bool { |
| 806 | if let Some(control) = self |
| 807 | .turn_controls |
| 808 | .lock() |
| 809 | .unwrap_or_else(std::sync::PoisonError::into_inner) |
| 810 | .target() |
| 811 | { |
| 812 | return control.cancel.is_cancelled(); |
| 813 | } |
| 814 | match self.cancel_token.lock() { |
| 815 | Ok(token) => token.is_cancelled(), |
| 816 | Err(poisoned) => poisoned.into_inner().is_cancelled(), |
| 817 | } |
| 818 | } |
| 819 | |
| 820 | /// Pause or resume the current pausable command. |
| 821 | pub fn set_paused(&self, paused: bool) { |
| 822 | match self.shared_paused.lock() { |
| 823 | Ok(mut slot) => *slot = paused, |
| 824 | Err(poisoned) => *poisoned.into_inner() = paused, |
| 825 | } |
| 826 | } |
| 827 | |
| 828 | /// Check whether the engine pause gate is set. |
| 829 | #[cfg(any(test, feature = "test-support"))] |
| 830 | #[must_use] |
| 831 | pub fn is_paused(&self) -> bool { |
| 832 | match self.shared_paused.lock() { |
| 833 | Ok(slot) => *slot, |
| 834 | Err(poisoned) => *poisoned.into_inner(), |
| 835 | } |
| 836 | } |
| 837 | |
| 838 | async fn send_approval(&self, decision: ApprovalDecision) -> Result<()> { |
| 839 | let current = self |
| 840 | .current_approval |
| 841 | .lock() |
| 842 | .as_ref() |
| 843 | .filter(|source| source.is_for(decision.id())) |
| 844 | .cloned(); |
| 845 | if let Some(source) = current { |
| 846 | return self.deliver_source_approval(decision, source).await; |
| 847 | } |
| 848 | if crate::tools::subagent::SubAgentManager::is_child_approval_id(decision.id()) { |
| 849 | use crate::tools::subagent::ChildApprovalOutcome; |
| 850 | let (outcome, grant) = match &decision { |
| 851 | ApprovalDecision::Approved { by, grant, .. } => { |
| 852 | (ChildApprovalOutcome::Approved { by: *by }, grant.clone()) |
| 853 | } |
| 854 | ApprovalDecision::Denied { by, grant, .. } => { |
| 855 | (ChildApprovalOutcome::Denied { by: *by }, grant.clone()) |
| 856 | } |
| 857 | ApprovalDecision::TimedOut { .. } => (ChildApprovalOutcome::TimedOut, None), |
| 858 | ApprovalDecision::Unavailable { .. } => (ChildApprovalOutcome::Unavailable, None), |
| 859 | ApprovalDecision::RetryWithPolicy { .. } => { |
| 860 | anyhow::bail!("child approval does not offer a sandbox retry") |
| 861 | } |
| 862 | }; |
| 863 | let submission = self.subagent_manager.write().await.submit_child_approval( |
| 864 | decision.id(), |
| 865 | outcome, |
| 866 | grant, |
| 867 | ); |
| 868 | if submission.wait().await? { |
| 869 | return Ok(()); |
| 870 | } |
| 871 | #[cfg(any(test, feature = "test-support"))] |
| 872 | anyhow::ensure!( |
| 873 | self.mock_approval_publications.is_some(), |
| 874 | "child approval is no longer pending or resolved differently" |
| 875 | ); |
| 876 | #[cfg(not(any(test, feature = "test-support")))] |
| 877 | anyhow::bail!("child approval is no longer pending or resolved differently"); |
| 878 | } |
| 879 | #[cfg(any(test, feature = "test-support"))] |
| 880 | if let Some(sources) = self.mock_approval_publications.as_ref() { |
| 881 | let mock = sources |
| 882 | .lock() |
| 883 | .get(decision.id()) |
| 884 | .map(|(source, _)| source.clone()); |
| 885 | if let Some(source) = mock { |
| 886 | let receipt = decision.receipt(); |
| 887 | if source.commit_mock_outcome(receipt)? { |
| 888 | let actual = source.actual().await?; |
| 889 | let observed = if decision.require_actual(&actual).is_ok() { |
| 890 | Some(decision.clone()) |
| 891 | } else if matches!( |
| 892 | actual, |
| 893 | crate::approval_log::ApprovalReceipt::Decided { |
| 894 | outcome: crate::approval_log::ApprovalOutcome::Timeout, |
| 895 | .. |
| 896 | } |
| 897 | ) { |
| 898 | Some(ApprovalDecision::TimedOut { |
| 899 | id: decision.id().to_owned(), |
| 900 | }) |
| 901 | } else { |
| 902 | None |
| 903 | }; |
| 904 | if let Some(observed) = observed { |
| 905 | self.tx_approval |
| 906 | .send(SubmittedApproval { |
| 907 | decision: observed, |
| 908 | publication: Some(source.clone()), |
| 909 | }) |
| 910 | .await?; |
| 911 | } |
| 912 | } |
| 913 | return decision.require_actual(&source.published().await?); |
| 914 | } |
| 915 | let (source, _producer) = super::NativeApprovalPublication::new(decision.id()); |
| 916 | source.set_mock_controls(self.captured_turn_cancel(), None); |
| 917 | source.commit_mock_outcome(decision.receipt())?; |
| 918 | decision.require_actual(&source.published().await?)?; |
| 919 | self.tx_approval |
| 920 | .send(SubmittedApproval { |
| 921 | decision, |
| 922 | publication: Some(source), |
| 923 | }) |
| 924 | .await?; |
| 925 | return Ok(()); |
| 926 | } |
| 927 | anyhow::bail!("approval has no current held Core request") |
| 928 | } |
| 929 | |
| 930 | async fn deliver_source_approval( |
| 931 | &self, |
| 932 | decision: ApprovalDecision, |
| 933 | publication: super::NativeApprovalPublication, |
| 934 | ) -> Result<()> { |
| 935 | anyhow::ensure!( |
| 936 | publication.is_for(decision.id()), |
| 937 | "approval source belongs to another Core request" |
| 938 | ); |
| 939 | let current = self |
| 940 | .current_approval |
| 941 | .lock() |
| 942 | .as_ref() |
| 943 | .is_some_and(|source| source.same_request(&publication)); |
| 944 | if !current { |
| 945 | return decision.require_actual(&publication.published().await?); |
| 946 | } |
| 947 | if matches!(decision, ApprovalDecision::TimedOut { .. }) { |
| 948 | anyhow::ensure!( |
| 949 | publication.timeout_seconds().is_some(), |
| 950 | "Core approval has no configured deadline" |
| 951 | ); |
| 952 | return decision.require_actual(&publication.published().await?); |
| 953 | } |
| 954 | let submitted = SubmittedApproval { |
| 955 | decision: decision.clone(), |
| 956 | publication: Some(publication.clone()), |
| 957 | }; |
| 958 | let receipt = tokio::select! { |
| 959 | biased; |
| 960 | receipt = publication.published() => receipt?, |
| 961 | sent = self.tx_approval.send(submitted) => { |
| 962 | sent?; |
| 963 | publication.published().await? |
| 964 | } |
| 965 | }; |
| 966 | decision.require_actual(&receipt) |
| 967 | } |
| 968 | |
| 969 | pub(crate) async fn accept_child_approval( |
| 970 | &self, |
| 971 | id: String, |
| 972 | reply: crate::tools::subagent::ChildApprovalReply, |
| 973 | ) -> Result<()> { |
| 974 | use crate::tools::subagent::ChildApprovalOutcome; |
| 975 | let decision = match reply.outcome { |
| 976 | ChildApprovalOutcome::Approved { by } => ApprovalDecision::Approved { |
| 977 | id, |
| 978 | by, |
| 979 | grant: reply.grant, |
| 980 | }, |
| 981 | ChildApprovalOutcome::Denied { by } => ApprovalDecision::Denied { |
| 982 | id, |
| 983 | by, |
| 984 | grant: reply.grant, |
| 985 | }, |
| 986 | ChildApprovalOutcome::TimedOut => ApprovalDecision::TimedOut { id }, |
| 987 | ChildApprovalOutcome::Unavailable => ApprovalDecision::Unavailable { id }, |
| 988 | }; |
| 989 | if let Some(publication) = reply.publication { |
| 990 | self.deliver_source_approval(decision, publication).await |
| 991 | } else { |
| 992 | anyhow::bail!("child approval reply has no captured Core source") |
| 993 | } |
| 994 | } |
| 995 | |
| 996 | #[cfg(any(test, feature = "test-support"))] |
| 997 | pub(crate) fn has_mock_approval_publications(&self) -> bool { |
| 998 | self.mock_approval_publications.is_some() |
| 999 | } |
| 1000 | |
| 1001 | #[cfg(any(test, feature = "test-support"))] |
| 1002 | pub(crate) fn mock_approval_publication( |
| 1003 | &self, |
| 1004 | tool_id: &str, |
| 1005 | timeout: Option<std::time::Duration>, |
| 1006 | ) -> Option<super::NativeApprovalPublication> { |
| 1007 | let sources = self.mock_approval_publications.as_ref()?.clone(); |
| 1008 | let (source, producer) = super::NativeApprovalPublication::new(tool_id); |
| 1009 | source.set_mock_controls(self.captured_turn_cancel(), timeout); |
| 1010 | { |
| 1011 | let mut pending = sources.lock(); |
| 1012 | if pending.contains_key(tool_id) { |
| 1013 | return None; |
| 1014 | } |
| 1015 | pending.insert(tool_id.to_owned(), (source.clone(), producer)); |
| 1016 | } |
| 1017 | if let Some(timeout) = timeout { |
| 1018 | let source = source.clone(); |
| 1019 | let tool_id = tool_id.to_owned(); |
| 1020 | let approvals = self.tx_approval.clone(); |
| 1021 | tokio::spawn(async move { |
| 1022 | tokio::time::sleep(timeout).await; |
| 1023 | let receipt = crate::approval_log::ApprovalReceipt::decided_with( |
| 1024 | &tool_id, |
| 1025 | crate::approval_log::ApprovalOutcome::Timeout, |
| 1026 | None, |
| 1027 | ); |
| 1028 | if source.commit_mock_outcome(receipt).unwrap_or(false) { |
| 1029 | let _ = source.published().await; |
| 1030 | if matches!( |
| 1031 | source.actual().await, |
| 1032 | Ok(crate::approval_log::ApprovalReceipt::Decided { |
| 1033 | outcome: crate::approval_log::ApprovalOutcome::Timeout, |
| 1034 | .. |
| 1035 | }) |
| 1036 | ) { |
| 1037 | let _ = approvals |
| 1038 | .send(SubmittedApproval { |
| 1039 | decision: ApprovalDecision::TimedOut { |
| 1040 | id: tool_id.clone(), |
| 1041 | }, |
| 1042 | publication: Some(source.clone()), |
| 1043 | }) |
| 1044 | .await; |
| 1045 | } |
| 1046 | let mut pending = sources.lock(); |
| 1047 | if pending |
| 1048 | .get(&tool_id) |
| 1049 | .is_some_and(|(current, _)| current.same_request(&source)) |
| 1050 | { |
| 1051 | pending.remove(&tool_id); |
| 1052 | } |
| 1053 | } |
| 1054 | }); |
| 1055 | } |
| 1056 | Some(source) |
| 1057 | } |
| 1058 | |
| 1059 | #[cfg(any(test, feature = "test-support"))] |
| 1060 | pub(crate) fn retire_mock_approval_publication( |
| 1061 | &self, |
| 1062 | tool_id: &str, |
| 1063 | source: &super::NativeApprovalPublication, |
| 1064 | ) { |
| 1065 | if let Some(sources) = self.mock_approval_publications.as_ref() { |
| 1066 | let mut pending = sources.lock(); |
| 1067 | if pending |
| 1068 | .get(tool_id) |
| 1069 | .is_some_and(|(current, _)| current.same_request(source)) |
| 1070 | { |
| 1071 | pending.remove(tool_id); |
| 1072 | } |
| 1073 | } |
| 1074 | } |
| 1075 | |
| 1076 | #[must_use] |
| 1077 | pub fn approval_is_pending(&self, id: &str) -> bool { |
| 1078 | if self |
| 1079 | .current_approval |
| 1080 | .lock() |
| 1081 | .as_ref() |
| 1082 | .is_some_and(|source| source.is_for(id)) |
| 1083 | { |
| 1084 | return true; |
| 1085 | } |
| 1086 | #[cfg(any(test, feature = "test-support"))] |
| 1087 | if self.mock_approval_publications.is_some() { |
| 1088 | return true; |
| 1089 | } |
| 1090 | false |
| 1091 | } |
| 1092 | |
| 1093 | /// Approve a pending tool call because a person said yes. |
| 1094 | pub async fn approve_tool_call(&self, id: impl Into<String>) -> Result<()> { |
| 1095 | self.approve_tool_call_by(id, ApprovalDecider::User).await |
| 1096 | } |
| 1097 | |
| 1098 | /// Approve a pending tool call, recording who answered: a person, a |
| 1099 | /// session rule, or the active posture. The approval receipt keeps it. |
| 1100 | pub async fn approve_tool_call_by( |
| 1101 | &self, |
| 1102 | id: impl Into<String>, |
| 1103 | by: ApprovalDecider, |
| 1104 | ) -> Result<()> { |
| 1105 | self.send_approval(ApprovalDecision::Approved { |
| 1106 | id: id.into(), |
| 1107 | by, |
| 1108 | grant: None, |
| 1109 | }) |
| 1110 | .await |
| 1111 | } |
| 1112 | |
| 1113 | /// Approve a pending tool call because a standing grant matched; the |
| 1114 | /// approval receipt names the grant. |
| 1115 | pub async fn approve_tool_call_by_grant( |
| 1116 | &self, |
| 1117 | id: impl Into<String>, |
| 1118 | by: ApprovalDecider, |
| 1119 | grant: crate::core::authority::grants::GrantRef, |
| 1120 | ) -> Result<()> { |
| 1121 | self.send_approval(ApprovalDecision::Approved { |
| 1122 | id: id.into(), |
| 1123 | by, |
| 1124 | grant: Some(grant), |
| 1125 | }) |
| 1126 | .await |
| 1127 | } |
| 1128 | |
| 1129 | /// Deny a pending tool call because a person said no. |
| 1130 | pub async fn deny_tool_call(&self, id: impl Into<String>) -> Result<()> { |
| 1131 | self.deny_tool_call_by(id, ApprovalDecider::User).await |
| 1132 | } |
| 1133 | |
| 1134 | /// Deny a pending tool call, recording who answered. |
| 1135 | pub async fn deny_tool_call_by( |
| 1136 | &self, |
| 1137 | id: impl Into<String>, |
| 1138 | by: ApprovalDecider, |
| 1139 | ) -> Result<()> { |
| 1140 | self.send_approval(ApprovalDecision::Denied { |
| 1141 | id: id.into(), |
| 1142 | by, |
| 1143 | grant: None, |
| 1144 | }) |
| 1145 | .await |
| 1146 | } |
| 1147 | |
| 1148 | /// Deny a pending tool call because a standing deny grant matched. |
| 1149 | pub async fn deny_tool_call_by_grant( |
| 1150 | &self, |
| 1151 | id: impl Into<String>, |
| 1152 | by: ApprovalDecider, |
| 1153 | grant: crate::core::authority::grants::GrantRef, |
| 1154 | ) -> Result<()> { |
| 1155 | self.send_approval(ApprovalDecision::Denied { |
| 1156 | id: id.into(), |
| 1157 | by, |
| 1158 | grant: Some(grant), |
| 1159 | }) |
| 1160 | .await |
| 1161 | } |
| 1162 | |
| 1163 | /// Deny a pending tool call because its interactive approval card |
| 1164 | /// expired (#6101). Kept distinct from [`Self::deny_tool_call`] so the |
| 1165 | /// receipt records a timeout instead of an operator denial. |
| 1166 | pub async fn deny_tool_call_timed_out(&self, id: impl Into<String>) -> Result<()> { |
| 1167 | self.send_approval(ApprovalDecision::TimedOut { id: id.into() }) |
| 1168 | .await |
| 1169 | } |
| 1170 | |
| 1171 | /// Resolve a pending tool call whose request could not be put in front |
| 1172 | /// of a person (a stale turn's request, or a child from another |
| 1173 | /// conversation). Kept distinct from [`Self::deny_tool_call`] so neither |
| 1174 | /// the receipt nor the model message claims the person denied it. |
| 1175 | pub async fn deny_tool_call_unavailable(&self, id: impl Into<String>) -> Result<()> { |
| 1176 | self.send_approval(ApprovalDecision::Unavailable { id: id.into() }) |
| 1177 | .await |
| 1178 | } |
| 1179 | |
| 1180 | /// Retry a tool call with an elevated sandbox policy a person chose. |
| 1181 | pub async fn retry_tool_with_policy( |
| 1182 | &self, |
| 1183 | id: impl Into<String>, |
| 1184 | policy: codewhale_sandbox::SandboxPolicy, |
| 1185 | ) -> Result<()> { |
| 1186 | self.retry_tool_with_policy_by(id, policy, ApprovalDecider::User) |
| 1187 | .await |
| 1188 | } |
| 1189 | |
| 1190 | /// Retry a tool call with an elevated sandbox policy, recording who chose it. |
| 1191 | pub async fn retry_tool_with_policy_by( |
| 1192 | &self, |
| 1193 | id: impl Into<String>, |
| 1194 | policy: codewhale_sandbox::SandboxPolicy, |
| 1195 | by: ApprovalDecider, |
| 1196 | ) -> Result<()> { |
| 1197 | self.send_approval(ApprovalDecision::RetryWithPolicy { |
| 1198 | id: id.into(), |
| 1199 | policy, |
| 1200 | by, |
| 1201 | }) |
| 1202 | .await |
| 1203 | } |
| 1204 | |
| 1205 | /// Submit a response for request_user_input. Success means Engine accepted |
| 1206 | /// it for the live exact request, rather than merely queuing the response. |
| 1207 | pub async fn submit_user_input( |
| 1208 | &self, |
| 1209 | id: impl Into<String>, |
| 1210 | response: UserInputResponse, |
| 1211 | ) -> Result<()> { |
| 1212 | let (accepted_tx, accepted_rx) = oneshot::channel(); |
| 1213 | await_user_input_acceptance( |
| 1214 | &self.tx_user_input, |
| 1215 | UserInputDecision::Submitted { |
| 1216 | id: id.into(), |
| 1217 | response, |
| 1218 | accepted: accepted_tx, |
| 1219 | }, |
| 1220 | accepted_rx, |
| 1221 | USER_INPUT_ACK_TIMEOUT, |
| 1222 | ) |
| 1223 | .await |
| 1224 | } |
| 1225 | |
| 1226 | /// Cancel a request_user_input prompt. |
| 1227 | pub async fn cancel_user_input(&self, id: impl Into<String>) -> Result<()> { |
| 1228 | let (accepted_tx, accepted_rx) = oneshot::channel(); |
| 1229 | await_user_input_acceptance( |
| 1230 | &self.tx_user_input, |
| 1231 | UserInputDecision::Cancelled { |
| 1232 | id: id.into(), |
| 1233 | accepted: accepted_tx, |
| 1234 | }, |
| 1235 | accepted_rx, |
| 1236 | USER_INPUT_ACK_TIMEOUT, |
| 1237 | ) |
| 1238 | .await |
| 1239 | } |
| 1240 | |
| 1241 | /// Steer an in-flight turn with additional user input. |
| 1242 | pub async fn steer(&self, content: impl Into<String>) -> Result<()> { |
| 1243 | self.reserve_steer().await?.send(content.into()); |
| 1244 | Ok(()) |
| 1245 | } |
| 1246 | |
| 1247 | pub async fn steer_with_person_text( |
| 1248 | &self, |
| 1249 | content: impl Into<String>, |
| 1250 | person_text: Option<String>, |
| 1251 | ) -> Result<()> { |
| 1252 | self.reserve_steer() |
| 1253 | .await? |
| 1254 | .send_with_person_text(content.into(), person_text); |
| 1255 | Ok(()) |
| 1256 | } |
| 1257 | |
| 1258 | /// Request the live context-window budget for this session's route. |
| 1259 | /// `None` means the route cannot express a bounded window (e.g. an |
| 1260 | /// unknown model with no catalog or configured limits) — callers should |
| 1261 | /// surface "unavailable" rather than inventing a number. |
| 1262 | pub async fn get_context_budget( |
| 1263 | &self, |
| 1264 | ) -> Result<Option<crate::core::ops::SessionContextBudget>> { |
| 1265 | let (tx, rx) = tokio::sync::oneshot::channel(); |
| 1266 | let tx = std::sync::Arc::new(std::sync::Mutex::new(Some(tx))); |
| 1267 | self.send(Op::GetContextBudget { tx }).await?; |
| 1268 | rx.await |
| 1269 | .map_err(|_| anyhow::anyhow!("Engine dropped context budget oneshot")) |
| 1270 | } |
| 1271 | |
| 1272 | /// Request a snapshot of the current session state. |
| 1273 | /// Returns the snapshot directly via a oneshot channel, avoiding |
| 1274 | /// competition with the SSE event stream on the mpsc receiver. |
| 1275 | pub async fn get_session_snapshot(&self) -> Result<crate::core::ops::SessionSnapshot> { |
| 1276 | let (tx, rx) = tokio::sync::oneshot::channel(); |
| 1277 | let tx = std::sync::Arc::new(std::sync::Mutex::new(Some(tx))); |
| 1278 | self.send(Op::GetSessionSnapshot { tx }).await?; |
| 1279 | rx.await |
| 1280 | .map_err(|_| anyhow::anyhow!("Engine dropped session snapshot oneshot")) |
| 1281 | } |
| 1282 | |
| 1283 | /// Query after the active turn settles, without competing with events. |
| 1284 | /// The caller must keep draining events and bound this future: an active |
| 1285 | /// turn can be awaiting provider/tool work or a full event channel. |
| 1286 | pub async fn get_subagent_settlement(&self) -> Result<crate::core::ops::SubAgentSettlement> { |
| 1287 | let (tx, rx) = tokio::sync::oneshot::channel(); |
| 1288 | let tx = Arc::new(StdMutex::new(Some(tx))); |
| 1289 | self.send(Op::GetSubAgentSettlement { tx }).await?; |
| 1290 | rx.await |
| 1291 | .map_err(|_| anyhow::anyhow!("Engine dropped child settlement receipt")) |
| 1292 | } |
| 1293 | |
| 1294 | /// Request active provider request concurrency state. |
| 1295 | pub async fn get_provider_runtime_status( |
| 1296 | &self, |
| 1297 | ) -> Result<crate::core::ops::ProviderRuntimeStatus> { |
| 1298 | let (tx, rx) = tokio::sync::oneshot::channel(); |
| 1299 | let tx = std::sync::Arc::new(std::sync::Mutex::new(Some(tx))); |
| 1300 | self.send(Op::GetProviderRuntimeStatus { tx }).await?; |
| 1301 | rx.await |
| 1302 | .map_err(|_| anyhow::anyhow!("Engine dropped provider runtime status oneshot")) |
| 1303 | } |
| 1304 | |
| 1305 | /// Run the bounded initial connection pass on the engine-owned MCP pool. |
| 1306 | /// |
| 1307 | /// The returned manager snapshot and every later tool call therefore see |
| 1308 | /// the same connections and catalog generation. Unlike `reload_mcp`, this |
| 1309 | /// does not force a config re-read or drop ready transports. Optional |
| 1310 | /// servers are connected in the background at engine spawn; this waits |
| 1311 | /// only if the caller explicitly asked for the settled receipt. |
| 1312 | pub async fn bootstrap_mcp(&self) -> Result<crate::core::ops::McpManagerUpdate> { |
| 1313 | let (tx, rx) = tokio::sync::oneshot::channel(); |
| 1314 | let tx = std::sync::Arc::new(std::sync::Mutex::new(Some(tx))); |
| 1315 | self.send(Op::BootstrapMcp { tx }).await?; |
| 1316 | rx.await |
| 1317 | .map_err(|_| anyhow::anyhow!("Engine dropped MCP bootstrap oneshot"))? |
| 1318 | .map_err(anyhow::Error::msg) |
| 1319 | } |
| 1320 | |
| 1321 | /// Retry one failed server through the existing engine-owned pool. |
| 1322 | pub async fn retry_mcp_server( |
| 1323 | &self, |
| 1324 | name: impl Into<String>, |
| 1325 | ) -> Result<crate::core::ops::McpManagerUpdate> { |
| 1326 | let (tx, rx) = tokio::sync::oneshot::channel(); |
| 1327 | let tx = std::sync::Arc::new(std::sync::Mutex::new(Some(tx))); |
| 1328 | self.send(Op::RetryMcpServer { |
| 1329 | name: name.into(), |
| 1330 | tx, |
| 1331 | }) |
| 1332 | .await?; |
| 1333 | rx.await |
| 1334 | .map_err(|_| anyhow::anyhow!("Engine dropped MCP retry oneshot"))? |
| 1335 | .map_err(anyhow::Error::msg) |
| 1336 | } |
| 1337 | |
| 1338 | /// Force the engine-owned MCP pool to reload and reconnect, returning a |
| 1339 | /// snapshot from the exact live pool that supplies the next model turn. |
| 1340 | pub async fn reload_mcp( |
| 1341 | &self, |
| 1342 | config_path: std::path::PathBuf, |
| 1343 | ) -> Result<crate::core::ops::McpManagerUpdate> { |
| 1344 | let (tx, rx) = tokio::sync::oneshot::channel(); |
| 1345 | let tx = std::sync::Arc::new(std::sync::Mutex::new(Some(tx))); |
| 1346 | self.send(Op::ReloadMcp { config_path, tx }).await?; |
| 1347 | rx.await |
| 1348 | .map_err(|_| anyhow::anyhow!("Engine dropped MCP reload oneshot"))? |
| 1349 | .map_err(anyhow::Error::msg) |
| 1350 | } |
| 1351 | |
| 1352 | #[must_use] |
| 1353 | pub fn list_auto_review_blocks(&self) -> Vec<AutoReviewBlockedAction> { |
| 1354 | self.auto_review_state.lock().blocked_actions() |
| 1355 | } |
| 1356 | |
| 1357 | pub fn approve_auto_review_retry( |
| 1358 | &self, |
| 1359 | target: &str, |
| 1360 | ) -> std::result::Result<AutoReviewRetryGrant, AutoReviewRetryApprovalError> { |
| 1361 | if !self.owner_surface_attached |
| 1362 | || !matches!( |
| 1363 | self.host_profile, |
| 1364 | super::host_profile::EngineHostProfile::Normal |
| 1365 | ) |
| 1366 | { |
| 1367 | return Err(AutoReviewRetryApprovalError::OwnerRequired); |
| 1368 | } |
| 1369 | if self.runtime_permission_authority().approval_mode != ApprovalMode::Auto { |
| 1370 | return Err(AutoReviewRetryApprovalError::NotInAutoReview); |
| 1371 | } |
| 1372 | self.auto_review_state |
| 1373 | .lock() |
| 1374 | .approve_retry(target) |
| 1375 | .map_err(AutoReviewRetryApprovalError::InvalidTarget) |
| 1376 | } |
| 1377 | |
| 1378 | pub fn reset_auto_review_state_for_boundary(&self) { |
| 1379 | self.auto_review_state |
| 1380 | .lock() |
| 1381 | .reset_for_conversation_boundary(); |
| 1382 | } |
| 1383 | |
| 1384 | #[cfg(any(test, feature = "test-support"))] |
| 1385 | pub fn set_auto_review_authority_for_test(&self, approval_mode: ApprovalMode) { |
| 1386 | self.publish_turn_authority( |
| 1387 | AppMode::Agent, |
| 1388 | true, |
| 1389 | false, |
| 1390 | approval_mode == ApprovalMode::Bypass, |
| 1391 | approval_mode, |
| 1392 | None, |
| 1393 | ); |
| 1394 | } |
| 1395 | |
| 1396 | #[cfg(any(test, feature = "test-support"))] |
| 1397 | #[allow(clippy::too_many_arguments)] |
| 1398 | pub fn record_auto_review_block_for_test( |
| 1399 | &self, |
| 1400 | tool_id: &str, |
| 1401 | tool_name: &str, |
| 1402 | tool_input: &serde_json::Value, |
| 1403 | rule: Option<&str>, |
| 1404 | reason: &str, |
| 1405 | gate: &str, |
| 1406 | verdict: &str, |
| 1407 | approvable: bool, |
| 1408 | ) -> Option<String> { |
| 1409 | let recorded = self.auto_review_state.lock().record_block( |
| 1410 | true, |
| 1411 | self.owner_surface_attached, |
| 1412 | false, |
| 1413 | approvable, |
| 1414 | tool_id, |
| 1415 | tool_name, |
| 1416 | tool_input, |
| 1417 | rule, |
| 1418 | reason, |
| 1419 | gate, |
| 1420 | verdict, |
| 1421 | ); |
| 1422 | recorded.receipt_id |
| 1423 | } |
| 1424 | } |
| 1425 | |
| 1426 | #[cfg(test)] |
| 1427 | mod user_input_ack_tests { |
| 1428 | use super::*; |
| 1429 | |
| 1430 | #[tokio::test] |
| 1431 | async fn user_input_delivery_bound_rejects_abandoned_reply_and_full_mailbox() { |
| 1432 | for full in [false, true] { |
| 1433 | let (sender, mut mailbox) = mpsc::channel(1); |
| 1434 | if full { |
| 1435 | let (accepted, receiver) = oneshot::channel(); |
| 1436 | drop(receiver); |
| 1437 | sender |
| 1438 | .send(UserInputDecision::Cancelled { |
| 1439 | id: "blocker".into(), |
| 1440 | accepted, |
| 1441 | }) |
| 1442 | .await |
| 1443 | .unwrap(); |
| 1444 | } |
| 1445 | let (accepted, verdict) = oneshot::channel(); |
| 1446 | let result = await_user_input_acceptance( |
| 1447 | &sender, |
| 1448 | UserInputDecision::Submitted { |
| 1449 | id: "late-reply".into(), |
| 1450 | response: UserInputResponse { |
| 1451 | answers: Vec::new(), |
| 1452 | }, |
| 1453 | accepted, |
| 1454 | }, |
| 1455 | verdict, |
| 1456 | std::time::Duration::from_millis(10), |
| 1457 | ) |
| 1458 | .await; |
| 1459 | assert!(result.is_err()); |
| 1460 | match mailbox.try_recv().unwrap() { |
| 1461 | UserInputDecision::Submitted { id, accepted, .. } => { |
| 1462 | assert!(!full); |
| 1463 | assert_eq!(id, "late-reply"); |
| 1464 | assert!( |
| 1465 | accepted.send(true).is_err(), |
| 1466 | "timed-out reply cannot be accepted later" |
| 1467 | ); |
| 1468 | } |
| 1469 | UserInputDecision::Cancelled { id, .. } => { |
| 1470 | assert!(full); |
| 1471 | assert_eq!(id, "blocker"); |
| 1472 | } |
| 1473 | } |
| 1474 | assert!( |
| 1475 | mailbox.try_recv().is_err(), |
| 1476 | "a full mailbox must not receive the abandoned reply" |
| 1477 | ); |
| 1478 | } |
| 1479 | } |
| 1480 | } |
| 1481 |