| 1 | //! Projection of the existing Runtime owner; no direct provider/tool authority. |
| 2 | use super::*; |
| 3 | use codewhale_engine::runtime_threads::{ |
| 4 | RuntimeEventRecord, RuntimeTurnStatus, RuntimeTurnStopReason, TurnRecord, |
| 5 | manager::ExternalApprovalDecision, manager::StartTurnRequest, |
| 6 | }; |
| 7 | use std::time::Duration; |
| 8 | use tokio::sync::mpsc::UnboundedReceiver; |
| 9 | struct Permission { |
| 10 | thread_id: String, |
| 11 | turn_id: String, |
| 12 | approval_id: String, |
| 13 | execution_id: String, |
| 14 | } |
| 15 | pub(super) struct PromptRun { |
| 16 | pub(super) runtime: Arc<RuntimeThreadManager>, |
| 17 | pub(super) sessions_dir: PathBuf, |
| 18 | } |
| 19 | struct Projection<'a> { |
| 20 | session: &'a str, |
| 21 | thread: &'a str, |
| 22 | turn: &'a str, |
| 23 | workspace: &'a Path, |
| 24 | cursor: u64, |
| 25 | emit: bool, |
| 26 | calls: HashMap<String, PendingToolCall>, |
| 27 | permissions: HashMap<String, Permission>, |
| 28 | } |
| 29 | /// Drop interrupts only this transport's admitted turn on the current scheduler. |
| 30 | struct TurnClaim { |
| 31 | runtime: Arc<RuntimeThreadManager>, |
| 32 | thread_id: String, |
| 33 | turn_id: String, |
| 34 | armed: bool, |
| 35 | } |
| 36 | impl Drop for TurnClaim { |
| 37 | fn drop(&mut self) { |
| 38 | if !self.armed { |
| 39 | return; |
| 40 | } |
| 41 | let runtime = Arc::clone(&self.runtime); |
| 42 | let thread = self.thread_id.clone(); |
| 43 | let turn = self.turn_id.clone(); |
| 44 | if let Ok(handle) = tokio::runtime::Handle::try_current() { |
| 45 | handle.spawn(async move { |
| 46 | let _ = runtime.interrupt_turn(&thread, &turn).await; |
| 47 | }); |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | fn admitted_call<'a>( |
| 52 | calls: &'a HashMap<String, PendingToolCall>, |
| 53 | execution: &str, |
| 54 | ) -> Option<(&'a str, &'a PendingToolCall)> { |
| 55 | let mut id = execution; |
| 56 | loop { |
| 57 | if let Some((key, call)) = calls.get_key_value(id) { |
| 58 | return Some((key.as_str(), call)); |
| 59 | } |
| 60 | id = id.rsplit_once('.')?.0; |
| 61 | } |
| 62 | } |
| 63 | fn update(session: &str, update: acp::SessionUpdate) -> Outgoing { |
| 64 | Outgoing::Update(acp::SessionNotification::new(session.to_string(), update)) |
| 65 | } |
| 66 | impl PromptRun { |
| 67 | pub(super) async fn drive_prompt( |
| 68 | &self, |
| 69 | session_id: &str, |
| 70 | thread_id: &str, |
| 71 | prompt: String, |
| 72 | emit: Emit<'_>, |
| 73 | inbox: &mut UnboundedReceiver<Inbound>, |
| 74 | ) -> Result<acp::StopReason> { |
| 75 | let session_id = session_id.to_string(); |
| 76 | let thread_id = thread_id.to_string(); |
| 77 | // Subscribe before snapshot/admission; replay deduplicates by seq. |
| 78 | let mut receiver = self.runtime.subscribe_events(); |
| 79 | let detail = self.runtime.get_thread_detail(&thread_id).await?; |
| 80 | let cursor = detail.latest_seq; |
| 81 | let workspace = detail.thread.workspace; |
| 82 | let turn = self |
| 83 | .runtime |
| 84 | .start_acp_turn( |
| 85 | &thread_id, |
| 86 | StartTurnRequest { |
| 87 | prompt, |
| 88 | ..Default::default() |
| 89 | }, |
| 90 | ) |
| 91 | .await?; |
| 92 | let mut claim = TurnClaim { |
| 93 | runtime: Arc::clone(&self.runtime), |
| 94 | thread_id: thread_id.clone(), |
| 95 | turn_id: turn.id.clone(), |
| 96 | armed: true, |
| 97 | }; |
| 98 | let mut projection = Projection { |
| 99 | session: &session_id, |
| 100 | thread: &thread_id, |
| 101 | turn: &turn.id, |
| 102 | workspace: &workspace, |
| 103 | cursor, |
| 104 | emit: true, |
| 105 | calls: HashMap::new(), |
| 106 | permissions: HashMap::new(), |
| 107 | }; |
| 108 | let terminal = match self |
| 109 | .project_turn(&mut projection, &mut receiver, inbox, emit) |
| 110 | .await |
| 111 | { |
| 112 | Ok(terminal) => terminal, |
| 113 | Err(error) => { |
| 114 | if let Err(interrupt) = self.interrupt_claimed_turn(&thread_id, &turn.id).await { |
| 115 | let message = format!( |
| 116 | "ACP projection failed ({error}); Core interruption is unconfirmed ({interrupt}); inspect without replay" |
| 117 | ); |
| 118 | return Err(error.context(message)); |
| 119 | } |
| 120 | let settled = match tokio::time::timeout(Duration::from_secs(30), async { |
| 121 | loop { |
| 122 | let detail = self.runtime.get_thread_detail(&thread_id).await?; |
| 123 | if let Some(record) = detail.turns.into_iter().find(|record| { |
| 124 | record.id == turn.id |
| 125 | && !matches!( |
| 126 | record.status, |
| 127 | RuntimeTurnStatus::Queued | RuntimeTurnStatus::InProgress |
| 128 | ) |
| 129 | }) { |
| 130 | return Ok::<_, anyhow::Error>(record); |
| 131 | } |
| 132 | tokio::time::sleep(Duration::from_millis(25)).await; |
| 133 | } |
| 134 | }) |
| 135 | .await |
| 136 | { |
| 137 | Ok(Ok(settled)) => settled, |
| 138 | Ok(Err(read)) => { |
| 139 | let message = format!( |
| 140 | "ACP projection failed ({error}); Core terminal receipt unavailable ({read}); inspect without replay" |
| 141 | ); |
| 142 | return Err(error.context(message)); |
| 143 | } |
| 144 | Err(_) => { |
| 145 | let message = format!( |
| 146 | "ACP projection failed ({error}); Core cancellation is still unconfirmed, inspect its canonical receipt" |
| 147 | ); |
| 148 | return Err(error.context(message)); |
| 149 | } |
| 150 | }; |
| 151 | if let Err(checkpoint) = self.save_checkpoint(&thread_id, &session_id).await { |
| 152 | let message = format!( |
| 153 | "ACP projection failed ({error}); actual Core terminal is {:?}; checkpoint failed ({checkpoint}); inspect without replay", |
| 154 | settled.status |
| 155 | ); |
| 156 | return Err(error.context(message)); |
| 157 | } |
| 158 | claim.armed = false; |
| 159 | let message = format!( |
| 160 | "ACP projection failed ({error}); actual Core terminal is {:?}; partial receipts retained", |
| 161 | settled.status |
| 162 | ); |
| 163 | return Err(error.context(message)); |
| 164 | } |
| 165 | }; |
| 166 | claim.armed = false; |
| 167 | self.save_checkpoint(&thread_id, &session_id).await?; |
| 168 | if terminal |
| 169 | .model_request_diagnostics |
| 170 | .as_ref() |
| 171 | .and_then(|facts| facts.stop_reason) |
| 172 | == Some(RuntimeTurnStopReason::StepBudgetExhausted) |
| 173 | { |
| 174 | return Ok(acp::StopReason::MaxTurnRequests); |
| 175 | } |
| 176 | match terminal.status { |
| 177 | RuntimeTurnStatus::Completed => Ok(acp::StopReason::EndTurn), |
| 178 | RuntimeTurnStatus::Interrupted | RuntimeTurnStatus::Canceled => { |
| 179 | Ok(acp::StopReason::Cancelled) |
| 180 | } |
| 181 | _ => Err(anyhow!( |
| 182 | "{}", |
| 183 | terminal.error.unwrap_or_else( |
| 184 | || "Core turn failed; inspect its canonical receipt".to_string() |
| 185 | ) |
| 186 | )), |
| 187 | } |
| 188 | } |
| 189 | async fn interrupt_claimed_turn(&self, thread: &str, turn: &str) -> Result<()> { |
| 190 | match self.runtime.interrupt_turn(thread, turn).await { |
| 191 | Ok(_) => Ok(()), |
| 192 | Err(error) => { |
| 193 | // Completion may win the race with EOF, cancel, or a failed |
| 194 | // writer. Accept only the actual terminal of this claimed turn. |
| 195 | let detail = self.runtime.get_thread_detail(thread).await.map_err(|read| anyhow!("ACP interruption failed ({error}); Core receipt cannot be read ({read}); inspect without replay"))?; |
| 196 | if detail.turns.iter().any(|record| { |
| 197 | record.id == turn |
| 198 | && !matches!( |
| 199 | record.status, |
| 200 | RuntimeTurnStatus::Queued | RuntimeTurnStatus::InProgress |
| 201 | ) |
| 202 | }) { |
| 203 | Ok(()) |
| 204 | } else { |
| 205 | Err(anyhow!( |
| 206 | "ACP cannot confirm interruption of its claimed Core turn: {error}; inspect without replay" |
| 207 | )) |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | } |
| 212 | async fn save_checkpoint(&self, thread: &str, session: &str) -> Result<()> { |
| 213 | // The same full Engine snapshot writer as HTTP, never projected text. |
| 214 | let axum::Json(_saved_checkpoint) = crate::runtime_api::sessions::save_session_in_runtime( |
| 215 | &self.runtime, |
| 216 | &self.sessions_dir, |
| 217 | crate::runtime_api::sessions::SaveSessionRequest { |
| 218 | thread_id: Some(thread.to_string()), |
| 219 | session_id: Some(session.to_string()), |
| 220 | }, |
| 221 | ) |
| 222 | .await |
| 223 | .map_err(|error| { |
| 224 | anyhow!( |
| 225 | "Core turn finished but its checkpoint failed; do not replay: {}", |
| 226 | error.message |
| 227 | ) |
| 228 | })?; |
| 229 | Ok(()) |
| 230 | } |
| 231 | async fn project_turn( |
| 232 | &self, |
| 233 | projection: &mut Projection<'_>, |
| 234 | receiver: &mut tokio::sync::broadcast::Receiver<RuntimeEventRecord>, |
| 235 | inbox: &mut UnboundedReceiver<Inbound>, |
| 236 | emit: Emit<'_>, |
| 237 | ) -> Result<TurnRecord> { |
| 238 | let session = projection.session; |
| 239 | let thread = projection.thread; |
| 240 | let turn = projection.turn; |
| 241 | let mut eof = false; |
| 242 | let mut cancelled = false; |
| 243 | let mut cancel_deadline: Option<tokio::time::Instant> = None; |
| 244 | let mut replay: Option<codewhale_engine::runtime_threads::RuntimeEventReplay> = None; |
| 245 | let mut replay_batch = VecDeque::new(); |
| 246 | loop { |
| 247 | if cancel_deadline.is_some_and(|deadline| tokio::time::Instant::now() >= deadline) { |
| 248 | return Err(anyhow!( |
| 249 | "Core cancellation remains nonterminal; ACP cannot report a fabricated cancelled receipt" |
| 250 | )); |
| 251 | } |
| 252 | tokio::select! { |
| 253 | () = async { match cancel_deadline { Some(deadline) => tokio::time::sleep_until(deadline).await, None => std::future::pending().await } } => return Err(anyhow!("Core cancellation remains nonterminal; ACP cannot report a fabricated cancelled receipt")), |
| 254 | message = inbox.recv(), if !eof => { |
| 255 | match message { |
| 256 | Some(Inbound::Cancel { session: cancelled_session }) => { |
| 257 | if cancelled_session == session { |
| 258 | cancelled = true; projection.permissions.clear(); self.interrupt_claimed_turn(thread, turn).await?; |
| 259 | cancel_deadline.get_or_insert(tokio::time::Instant::now() + Duration::from_secs(30)); |
| 260 | } |
| 261 | } |
| 262 | Some(Inbound::Permission { key, allow }) => { |
| 263 | if !cancelled && let Some(permission) = projection.permissions.remove(&key) { self.answer_permission(&permission, allow).await?; } |
| 264 | } |
| 265 | Some(Inbound::Eof) | None => { |
| 266 | eof = true; cancelled = true; projection.permissions.clear(); self.interrupt_claimed_turn(thread, turn).await?; |
| 267 | cancel_deadline.get_or_insert(tokio::time::Instant::now() + Duration::from_secs(30)); |
| 268 | } |
| 269 | } |
| 270 | } |
| 271 | record = async { replay_batch.pop_front().expect("nonempty bounded replay batch") }, if !replay_batch.is_empty() => { |
| 272 | projection.emit = !cancelled && !eof; |
| 273 | if let Some(done) = self.project_event(projection, &record, &mut *emit).await? { return Ok(done); } |
| 274 | } |
| 275 | batch = async { replay.as_mut().expect("active replay").batches.recv().await }, if replay.is_some() && replay_batch.is_empty() => { |
| 276 | match batch { |
| 277 | Some(batch) => replay_batch.extend(batch.map_err(|error| anyhow!(error))?), |
| 278 | None => replay = None, |
| 279 | } |
| 280 | } |
| 281 | event = receiver.recv(), if replay.is_none() && replay_batch.is_empty() => { |
| 282 | match event { |
| 283 | Ok(record) => { projection.emit = !cancelled && !eof; if let Some(done) = self.project_event(projection, &record, &mut *emit).await? { return Ok(done); } }, |
| 284 | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => { |
| 285 | let captured = self.runtime.replay_events(thread, Some(projection.cursor), None).await?; |
| 286 | if captured.base_seq > projection.cursor { return Err(anyhow!("ACP replay no longer covers the cursor; projection is incomplete")); } |
| 287 | replay = Some(captured); |
| 288 | } |
| 289 | Err(tokio::sync::broadcast::error::RecvError::Closed) => return Err(anyhow!("Runtime owner closed before its terminal receipt")), |
| 290 | } |
| 291 | } |
| 292 | } |
| 293 | } |
| 294 | } |
| 295 | async fn answer_permission(&self, permission: &Permission, allow: bool) -> Result<()> { |
| 296 | let detail = self |
| 297 | .runtime |
| 298 | .get_thread_detail(&permission.thread_id) |
| 299 | .await?; |
| 300 | if !detail.pending_approvals.iter().any(|pending| { |
| 301 | pending.id == permission.approval_id |
| 302 | && pending.turn_id == permission.turn_id |
| 303 | && pending.tool_call_id.as_deref() == Some(permission.execution_id.as_str()) |
| 304 | }) { |
| 305 | return Ok(()); |
| 306 | } |
| 307 | self.runtime |
| 308 | .deliver_approval_from( |
| 309 | &permission.approval_id, |
| 310 | None, |
| 311 | if allow { |
| 312 | ExternalApprovalDecision::Allow { remember: false } |
| 313 | } else { |
| 314 | ExternalApprovalDecision::Deny { remember: false } |
| 315 | }, |
| 316 | Some(codewhale_engine::runtime_threads::manager::ApprovalResponder::Acp), |
| 317 | ) |
| 318 | .await?; |
| 319 | Ok(()) |
| 320 | } |
| 321 | async fn project_event( |
| 322 | &self, |
| 323 | projection: &mut Projection<'_>, |
| 324 | record: &RuntimeEventRecord, |
| 325 | out: Emit<'_>, |
| 326 | ) -> Result<Option<TurnRecord>> { |
| 327 | let session = projection.session; |
| 328 | let thread = projection.thread; |
| 329 | let turn = projection.turn; |
| 330 | let workspace = projection.workspace; |
| 331 | let cursor = &mut projection.cursor; |
| 332 | let calls = &mut projection.calls; |
| 333 | let permissions = &mut projection.permissions; |
| 334 | let emit = projection.emit; |
| 335 | if record.thread_id != thread || record.seq <= *cursor { |
| 336 | return Ok(None); |
| 337 | } |
| 338 | *cursor = record.seq; |
| 339 | if record.turn_id.as_deref() != Some(turn) { |
| 340 | return Ok(None); |
| 341 | } |
| 342 | let p = &record.payload; |
| 343 | match record.event.as_str() { |
| 344 | "item.delta" |
| 345 | if emit && p.get("kind").and_then(Value::as_str) == Some("agent_message") => |
| 346 | { |
| 347 | if let Some(text) = p.get("delta").and_then(Value::as_str) { |
| 348 | out(update(session, agent_text(text.to_string())))?; |
| 349 | } |
| 350 | } |
| 351 | "item.started" => { |
| 352 | if let Some(tool) = p.get("tool") { |
| 353 | let id = tool |
| 354 | .get("id") |
| 355 | .and_then(Value::as_str) |
| 356 | .ok_or_else(|| anyhow!("Tool start lacks Core identity"))? |
| 357 | .to_string(); |
| 358 | let call = PendingToolCall { |
| 359 | execution_id: id.clone(), |
| 360 | name: tool |
| 361 | .get("name") |
| 362 | .and_then(Value::as_str) |
| 363 | .unwrap_or_default() |
| 364 | .to_string(), |
| 365 | input: tool.get("input").cloned().unwrap_or(Value::Null), |
| 366 | }; |
| 367 | if emit { |
| 368 | let external = p.pointer("/item/metadata/external_agent").map(|agent| { |
| 369 | agent |
| 370 | .get("locations") |
| 371 | .and_then(external_locations) |
| 372 | .unwrap_or_default() |
| 373 | }); |
| 374 | out(update( |
| 375 | session, |
| 376 | acp::SessionUpdate::ToolCall(tool_call_start( |
| 377 | &call, workspace, external, |
| 378 | )), |
| 379 | ))?; |
| 380 | } |
| 381 | calls.insert(id, call); |
| 382 | } |
| 383 | } |
| 384 | "tool.execution_started" if emit => { |
| 385 | let id = p |
| 386 | .get("execution_id") |
| 387 | .and_then(Value::as_str) |
| 388 | .ok_or_else(|| anyhow!("Dispatch lacks Core identity"))?; |
| 389 | let call = calls |
| 390 | .get(id) |
| 391 | .ok_or_else(|| anyhow!("Dispatch projection lacks its admitted start"))?; |
| 392 | out(update( |
| 393 | session, |
| 394 | acp::SessionUpdate::ToolCallUpdate(tool_call_update( |
| 395 | call, |
| 396 | workspace, |
| 397 | acp::ToolCallStatus::InProgress, |
| 398 | None, |
| 399 | &[], |
| 400 | None, |
| 401 | )), |
| 402 | ))?; |
| 403 | } |
| 404 | "item.completed" | "item.failed" | "item.interrupted" if emit => { |
| 405 | if let Some(item) = p.get("item") |
| 406 | && let Some(id) = item |
| 407 | .pointer("/metadata/execution_id") |
| 408 | .or_else(|| item.pointer("/metadata/external_agent/tool_call_id")) |
| 409 | .and_then(Value::as_str) |
| 410 | && let Some(call) = calls.remove(id) |
| 411 | { |
| 412 | let blocks: Vec<codewhale_tools::ToolResultContentBlock> = item |
| 413 | .pointer("/metadata/acp_result_content") |
| 414 | .cloned() |
| 415 | .map(serde_json::from_value) |
| 416 | .transpose()? |
| 417 | .unwrap_or_default(); |
| 418 | let status = if item.get("status").and_then(Value::as_str) == Some("completed") |
| 419 | { |
| 420 | acp::ToolCallStatus::Completed |
| 421 | } else { |
| 422 | acp::ToolCallStatus::Failed |
| 423 | }; |
| 424 | let external = item.pointer("/metadata/external_agent").map(|agent| { |
| 425 | agent |
| 426 | .get("locations") |
| 427 | .and_then(external_locations) |
| 428 | .unwrap_or_default() |
| 429 | }); |
| 430 | out(update( |
| 431 | session, |
| 432 | acp::SessionUpdate::ToolCallUpdate(tool_call_update( |
| 433 | &call, |
| 434 | workspace, |
| 435 | status, |
| 436 | item.get("detail").and_then(Value::as_str), |
| 437 | &blocks, |
| 438 | external, |
| 439 | )), |
| 440 | ))?; |
| 441 | } |
| 442 | } |
| 443 | "approval.required" if emit => { |
| 444 | let approval = p |
| 445 | .get("approval_id") |
| 446 | .and_then(Value::as_str) |
| 447 | .ok_or_else(|| anyhow!("Approval lacks Runtime identity"))?; |
| 448 | let execution = p |
| 449 | .get("tool_call_id") |
| 450 | .and_then(Value::as_str) |
| 451 | .ok_or_else(|| anyhow!("Approval lacks Core correlator"))?; |
| 452 | let detail = self.runtime.get_thread_detail(thread).await?; |
| 453 | if detail.pending_approvals.iter().any(|pending| { |
| 454 | pending.id == approval |
| 455 | && pending.turn_id == turn |
| 456 | && pending.tool_call_id.as_deref() == Some(execution) |
| 457 | }) { |
| 458 | let (shown, call) = admitted_call(calls, execution) |
| 459 | .ok_or_else(|| anyhow!("Approval projection lacks admitted tool start"))?; |
| 460 | let id = uuid::Uuid::new_v4().to_string(); |
| 461 | let nested = shown != execution; |
| 462 | let nested_call; |
| 463 | let shown_call = if nested { |
| 464 | nested_call = PendingToolCall { |
| 465 | execution_id: execution.to_string(), |
| 466 | name: p |
| 467 | .get("tool_name") |
| 468 | .and_then(Value::as_str) |
| 469 | .unwrap_or(&call.name) |
| 470 | .to_string(), |
| 471 | input: p.get("input").cloned().unwrap_or(Value::Null), |
| 472 | }; |
| 473 | &nested_call |
| 474 | } else { |
| 475 | call |
| 476 | }; |
| 477 | let title = tool_call_title(shown_call); |
| 478 | let description = p |
| 479 | .get("description") |
| 480 | .and_then(Value::as_str) |
| 481 | .filter(|text| !text.trim().is_empty()); |
| 482 | let summary = p |
| 483 | .get("summary") |
| 484 | .and_then(Value::as_str) |
| 485 | .filter(|text| nested && !text.trim().is_empty()); |
| 486 | let text = match (summary, description) { |
| 487 | (Some(summary), Some(description)) => format!("{summary}\n{description}"), |
| 488 | (Some(text), None) | (None, Some(text)) => text.to_string(), |
| 489 | (None, None) => title.clone(), |
| 490 | }; |
| 491 | let external = p.get("external_agent").map(|_| { |
| 492 | p.get("locations") |
| 493 | .and_then(external_locations) |
| 494 | .unwrap_or_default() |
| 495 | }); |
| 496 | let mut fields = acp::ToolCallUpdateFields::new() |
| 497 | .title(title) |
| 498 | .kind(tool_call_kind(shown_call)) |
| 499 | .raw_input((!shown_call.input.is_null()).then(|| shown_call.input.clone())) |
| 500 | .content( |
| 501 | if nested || external.is_some() { |
| 502 | Vec::new() |
| 503 | } else { |
| 504 | tool_call_requested_diffs(shown_call, workspace) |
| 505 | .into_iter() |
| 506 | .map(acp::ToolCallContent::Diff) |
| 507 | .collect() |
| 508 | } |
| 509 | .into_iter() |
| 510 | .chain([acp::ToolCallContent::from(text)]) |
| 511 | .collect::<Vec<_>>(), |
| 512 | ); |
| 513 | if let Some(locations) = external { |
| 514 | fields = fields.locations(locations); |
| 515 | } |
| 516 | if !nested { |
| 517 | fields = fields.status(acp::ToolCallStatus::Pending); |
| 518 | } |
| 519 | let request = acp::RequestPermissionRequest::new( |
| 520 | session.to_string(), |
| 521 | acp::ToolCallUpdate::new(shown.to_string(), fields), |
| 522 | vec![ |
| 523 | acp::PermissionOption::new( |
| 524 | "allow-once", |
| 525 | "Allow once", |
| 526 | acp::PermissionOptionKind::AllowOnce, |
| 527 | ), |
| 528 | acp::PermissionOption::new( |
| 529 | "reject-once", |
| 530 | "Reject", |
| 531 | acp::PermissionOptionKind::RejectOnce, |
| 532 | ), |
| 533 | ], |
| 534 | ); |
| 535 | out(Outgoing::Permission { |
| 536 | key: id.clone(), |
| 537 | request, |
| 538 | })?; |
| 539 | permissions.insert( |
| 540 | id, |
| 541 | Permission { |
| 542 | thread_id: thread.to_string(), |
| 543 | turn_id: turn.to_string(), |
| 544 | approval_id: approval.to_string(), |
| 545 | execution_id: execution.to_string(), |
| 546 | }, |
| 547 | ); |
| 548 | } |
| 549 | } |
| 550 | "approval.decided" => { |
| 551 | if let Some(id) = p.get("approval_id").and_then(Value::as_str) { |
| 552 | permissions.retain(|_, permission| permission.approval_id != id); |
| 553 | } |
| 554 | } |
| 555 | codewhale_engine::runtime_threads::RUNTIME_STORE_FAILURE_EVENT |
| 556 | if p.get("terminal").and_then(Value::as_bool) == Some(true) => |
| 557 | { |
| 558 | return Err(anyhow!( |
| 559 | "Core store failure has no terminal receipt: {}; inspect without replay", |
| 560 | p.get("message") |
| 561 | .and_then(Value::as_str) |
| 562 | .unwrap_or("canonical store unavailable") |
| 563 | )); |
| 564 | } |
| 565 | "turn.completed" => { |
| 566 | permissions.clear(); |
| 567 | let terminal: TurnRecord = serde_json::from_value( |
| 568 | p.get("turn") |
| 569 | .cloned() |
| 570 | .ok_or_else(|| anyhow!("Terminal event lacks its actual record"))?, |
| 571 | )?; |
| 572 | if terminal.id != turn { |
| 573 | return Err(anyhow!("Terminal does not match admitted turn")); |
| 574 | } |
| 575 | return Ok(Some(terminal)); |
| 576 | } |
| 577 | _ => {} |
| 578 | } |
| 579 | Ok(None) |
| 580 | } |
| 581 | } |
| 582 | |
| 583 | #[cfg(test)] |
| 584 | mod tests { |
| 585 | use super::super::tests::{Rig, fixture_config}; |
| 586 | use super::*; |
| 587 | fn frame(outgoing: Outgoing) -> Value { |
| 588 | match outgoing { |
| 589 | Outgoing::Update(notification) => { |
| 590 | json!({"jsonrpc":"2.0","method":"session/update","params":serde_json::to_value(notification).unwrap()}) |
| 591 | } |
| 592 | Outgoing::Permission { key, request } => { |
| 593 | json!({"jsonrpc":"2.0","id":key,"method":"session/request_permission","params":serde_json::to_value(request).unwrap()}) |
| 594 | } |
| 595 | } |
| 596 | } |
| 597 | fn recording(out: &mut Vec<Value>) -> impl FnMut(Outgoing) -> Result<()> + Send + '_ { |
| 598 | move |outgoing| { |
| 599 | out.push(frame(outgoing)); |
| 600 | Ok(()) |
| 601 | } |
| 602 | } |
| 603 | fn event(seq: u64, thread: &str, turn: &str, name: &str, payload: Value) -> RuntimeEventRecord { |
| 604 | serde_json::from_value(json!({"seq":seq,"timestamp":chrono::Utc::now(),"thread_id":thread,"turn_id":turn,"event":name,"payload":payload})).unwrap() |
| 605 | } |
| 606 | #[tokio::test(flavor = "current_thread")] |
| 607 | async fn acp_full_access_projects_runtime_policy_holds_and_extension_permissions() -> Result<()> |
| 608 | { |
| 609 | use codewhale_engine::core::engine::{MockApprovalEvent, mock_engine_handle}; |
| 610 | use codewhale_engine::core::events::{Event, TurnOutcomeStatus}; |
| 611 | use codewhale_engine::core::ops::Op; |
| 612 | |
| 613 | for (forced, extension) in [(false, false), (true, false), (true, true)] { |
| 614 | let mut config = fixture_config(); |
| 615 | config.approval_policy = Some("full-access".into()); |
| 616 | let mut rig = Rig::new(config, vec![])?; |
| 617 | let session = rig.new_session().await; |
| 618 | let thread = rig.server.sessions[&session].thread_id.clone(); |
| 619 | let mut engine = mock_engine_handle(); |
| 620 | rig.server |
| 621 | .runtime |
| 622 | .install_test_engine(&thread, engine.handle.clone()) |
| 623 | .await?; |
| 624 | let turn = rig |
| 625 | .server |
| 626 | .runtime |
| 627 | .start_acp_turn( |
| 628 | &thread, |
| 629 | StartTurnRequest { |
| 630 | prompt: "honor the ACP approval boundary".into(), |
| 631 | ..Default::default() |
| 632 | }, |
| 633 | ) |
| 634 | .await?; |
| 635 | let Some(Op::SendMessage(spec)) = |
| 636 | tokio::time::timeout(Duration::from_secs(10), engine.rx_op.recv()).await? |
| 637 | else { |
| 638 | anyhow::bail!("ACP did not admit its canonical Engine turn") |
| 639 | }; |
| 640 | assert_eq!(spec.approval_mode, ApprovalMode::Bypass); |
| 641 | assert!(spec.auto_approve); |
| 642 | let input = json!({"path":"approval.txt","content":"bounded write","approval_key":"extcall:ext:claimed"}); |
| 643 | engine |
| 644 | .tx_event |
| 645 | .send(Event::ToolCallStarted { |
| 646 | id: "acp-policy-call".into(), |
| 647 | model_call: None, |
| 648 | name: "write".into(), |
| 649 | input: input.clone(), |
| 650 | }) |
| 651 | .await?; |
| 652 | engine |
| 653 | .tx_event |
| 654 | .send(Event::ApprovalRequired { |
| 655 | publication: None, |
| 656 | id: "acp-policy-call".into(), |
| 657 | tool_name: "write".into(), |
| 658 | description: "Requested by extension:claimed".into(), |
| 659 | input, |
| 660 | approval_key: if extension { |
| 661 | "extcall:ext:fixture" |
| 662 | } else { |
| 663 | "ordinary-policy-key" |
| 664 | } |
| 665 | .into(), |
| 666 | approval_grouping_key: "acp-policy-group".into(), |
| 667 | intent_summary: None, |
| 668 | approval_force_prompt: forced, |
| 669 | }) |
| 670 | .await?; |
| 671 | if extension { |
| 672 | tokio::time::timeout(Duration::from_secs(10), async { |
| 673 | loop { |
| 674 | if rig |
| 675 | .server |
| 676 | .runtime |
| 677 | .events_since(&thread, None)? |
| 678 | .iter() |
| 679 | .any(|record| record.event == "approval.required") |
| 680 | { |
| 681 | return Ok::<_, anyhow::Error>(()); |
| 682 | } |
| 683 | tokio::time::sleep(Duration::from_millis(10)).await; |
| 684 | } |
| 685 | }) |
| 686 | .await??; |
| 687 | assert_eq!(rig.server.runtime.pending_approvals_count(), 1); |
| 688 | } else { |
| 689 | let (decision, by) = |
| 690 | tokio::time::timeout(Duration::from_secs(10), engine.recv_approval_decision()) |
| 691 | .await? |
| 692 | .ok_or_else(|| anyhow!("Runtime approval decision missing"))?; |
| 693 | assert_eq!( |
| 694 | decision, |
| 695 | if forced { |
| 696 | MockApprovalEvent::Denied { |
| 697 | id: "acp-policy-call".into(), |
| 698 | } |
| 699 | } else { |
| 700 | MockApprovalEvent::Approved { |
| 701 | id: "acp-policy-call".into(), |
| 702 | } |
| 703 | } |
| 704 | ); |
| 705 | assert_eq!( |
| 706 | by, |
| 707 | Some(codewhale_engine::approval_log::ApprovalDecider::Posture) |
| 708 | ); |
| 709 | assert_eq!(rig.server.runtime.pending_approvals_count(), 0); |
| 710 | } |
| 711 | let mut projection = Projection { |
| 712 | session: &session, |
| 713 | thread: &thread, |
| 714 | turn: &turn.id, |
| 715 | workspace: Path::new("/"), |
| 716 | cursor: 0, |
| 717 | emit: true, |
| 718 | calls: HashMap::new(), |
| 719 | permissions: HashMap::new(), |
| 720 | }; |
| 721 | let mut output: Vec<Value> = Vec::new(); |
| 722 | // Project the actual Runtime records, not synthetic ACP frames. |
| 723 | for record in rig.server.runtime.events_since(&thread, None)? { |
| 724 | rig.server |
| 725 | .prompt_run() |
| 726 | .project_event(&mut projection, &record, &mut recording(&mut output)) |
| 727 | .await?; |
| 728 | } |
| 729 | let wire = output; |
| 730 | let requests: Vec<_> = wire |
| 731 | .iter() |
| 732 | .filter(|frame| frame["method"] == "session/request_permission") |
| 733 | .collect(); |
| 734 | assert_eq!(requests.len(), usize::from(extension)); |
| 735 | assert_eq!(projection.permissions.len(), usize::from(extension)); |
| 736 | if extension { |
| 737 | let request = requests[0]; |
| 738 | assert_eq!( |
| 739 | request["params"]["toolCall"]["toolCallId"], |
| 740 | "acp-policy-call" |
| 741 | ); |
| 742 | let permission = projection |
| 743 | .permissions |
| 744 | .remove( |
| 745 | request["id"] |
| 746 | .as_str() |
| 747 | .ok_or_else(|| anyhow!("ACP permission ID missing"))?, |
| 748 | ) |
| 749 | .ok_or_else(|| anyhow!("ACP permission was not retained"))?; |
| 750 | rig.server |
| 751 | .prompt_run() |
| 752 | .answer_permission(&permission, true) |
| 753 | .await?; |
| 754 | assert_eq!( |
| 755 | tokio::time::timeout(Duration::from_secs(10), engine.recv_approval_event()) |
| 756 | .await?, |
| 757 | Some(MockApprovalEvent::Approved { |
| 758 | id: "acp-policy-call".into() |
| 759 | }) |
| 760 | ); |
| 761 | } |
| 762 | let events = rig.server.runtime.events_since(&thread, None)?; |
| 763 | let decided = events |
| 764 | .iter() |
| 765 | .find(|record| { |
| 766 | record.event == "approval.decided" |
| 767 | && record.payload["tool_call_id"] == "acp-policy-call" |
| 768 | }) |
| 769 | .ok_or_else(|| anyhow!("canonical approval receipt missing"))?; |
| 770 | assert_eq!( |
| 771 | decided.payload["decision"], |
| 772 | if forced && !extension { |
| 773 | "deny" |
| 774 | } else { |
| 775 | "allow" |
| 776 | } |
| 777 | ); |
| 778 | assert_eq!( |
| 779 | decided.payload["auto"].as_bool(), |
| 780 | if extension { None } else { Some(true) } |
| 781 | ); |
| 782 | if forced && !extension { |
| 783 | assert_eq!(decided.payload["posture"], "full_access_policy_hold"); |
| 784 | } |
| 785 | assert!( |
| 786 | rig.server |
| 787 | .runtime |
| 788 | .get_thread_detail(&thread) |
| 789 | .await? |
| 790 | .pending_approvals |
| 791 | .is_empty() |
| 792 | ); |
| 793 | let approval = decided.payload["approval_id"] |
| 794 | .as_str() |
| 795 | .ok_or_else(|| anyhow!("opaque approval ID missing"))?; |
| 796 | assert_ne!(approval, "acp-policy-call"); |
| 797 | for id in [approval, "acp-policy-call"] { |
| 798 | assert!( |
| 799 | !rig.server |
| 800 | .runtime |
| 801 | .deliver_external_approval( |
| 802 | id, |
| 803 | ExternalApprovalDecision::Allow { remember: false } |
| 804 | ) |
| 805 | .await |
| 806 | .expect("durable approval decision") |
| 807 | ); |
| 808 | } |
| 809 | if !forced || extension { |
| 810 | engine |
| 811 | .tx_event |
| 812 | .send(Event::ToolExecutionStarted { |
| 813 | id: "acp-policy-call".into(), |
| 814 | }) |
| 815 | .await?; |
| 816 | } |
| 817 | engine |
| 818 | .tx_event |
| 819 | .send(Event::ToolCallComplete { |
| 820 | id: "acp-policy-call".into(), |
| 821 | model_call: None, |
| 822 | name: "write".into(), |
| 823 | result: if forced && !extension { |
| 824 | Err(codewhale_engine::tools::spec::ToolError::permission_denied( |
| 825 | "fixture forced policy hold", |
| 826 | )) |
| 827 | } else { |
| 828 | Ok(codewhale_engine::tools::spec::ToolResult::success( |
| 829 | "fixture allowed", |
| 830 | )) |
| 831 | }, |
| 832 | }) |
| 833 | .await?; |
| 834 | engine |
| 835 | .tx_event |
| 836 | .send(Event::TurnComplete { |
| 837 | source_accounting: false, |
| 838 | |
| 839 | turn_id: None, |
| 840 | submission_id: None, |
| 841 | compaction_id: None, |
| 842 | usage: codewhale_models::Usage::default(), |
| 843 | parent_route_usage: codewhale_models::Usage::default(), |
| 844 | routed_usage_dropped_records: 0, |
| 845 | status: TurnOutcomeStatus::Completed, |
| 846 | error: None, |
| 847 | tool_catalog: None, |
| 848 | base_url: None, |
| 849 | }) |
| 850 | .await?; |
| 851 | tokio::time::timeout(Duration::from_secs(10), async { |
| 852 | loop { |
| 853 | if rig |
| 854 | .server |
| 855 | .runtime |
| 856 | .events_since(&thread, None)? |
| 857 | .iter() |
| 858 | .any(|record| { |
| 859 | record.turn_id.as_deref() == Some(turn.id.as_str()) |
| 860 | && record.event == "turn.completed" |
| 861 | }) |
| 862 | { |
| 863 | return Ok::<_, anyhow::Error>(()); |
| 864 | } |
| 865 | tokio::time::sleep(Duration::from_millis(10)).await; |
| 866 | } |
| 867 | }) |
| 868 | .await??; |
| 869 | let mut terminal = None; |
| 870 | let mut settled_output: Vec<Value> = Vec::new(); |
| 871 | for record in rig |
| 872 | .server |
| 873 | .runtime |
| 874 | .events_since(&thread, Some(projection.cursor))? |
| 875 | { |
| 876 | if let Some(completed) = rig |
| 877 | .server |
| 878 | .prompt_run() |
| 879 | .project_event( |
| 880 | &mut projection, |
| 881 | &record, |
| 882 | &mut recording(&mut settled_output), |
| 883 | ) |
| 884 | .await? |
| 885 | { |
| 886 | terminal = Some(completed); |
| 887 | } |
| 888 | } |
| 889 | assert_eq!( |
| 890 | terminal |
| 891 | .ok_or_else(|| anyhow!("ACP terminal projection missing"))? |
| 892 | .status, |
| 893 | RuntimeTurnStatus::Completed |
| 894 | ); |
| 895 | assert!(projection.permissions.is_empty()); |
| 896 | assert!(projection.calls.is_empty()); |
| 897 | assert!( |
| 898 | !settled_output |
| 899 | .iter() |
| 900 | .any(|frame| frame["method"] == "session/request_permission") |
| 901 | ); |
| 902 | rig.close().await; |
| 903 | } |
| 904 | Ok(()) |
| 905 | } |
| 906 | #[tokio::test(flavor = "current_thread")] |
| 907 | async fn projection_deduplicates_replay_and_refuses_dispatch_without_core_start() -> Result<()> |
| 908 | { |
| 909 | let mut rig = Rig::new(fixture_config(), vec![])?; |
| 910 | let id = rig.new_session().await; |
| 911 | let thread = rig.server.sessions[&id].thread_id.clone(); |
| 912 | let mut p = Projection { |
| 913 | session: &id, |
| 914 | thread: &thread, |
| 915 | turn: "turn-current", |
| 916 | workspace: Path::new("/"), |
| 917 | cursor: 0, |
| 918 | emit: true, |
| 919 | calls: HashMap::new(), |
| 920 | permissions: HashMap::new(), |
| 921 | }; |
| 922 | let mut output: Vec<Value> = Vec::new(); |
| 923 | let start = event( |
| 924 | 1, |
| 925 | &thread, |
| 926 | p.turn, |
| 927 | "item.started", |
| 928 | json!({"tool":{"id":"core-call","name":"read","input":{"path":"x"}}}), |
| 929 | ); |
| 930 | rig.server |
| 931 | .prompt_run() |
| 932 | .project_event(&mut p, &start, &mut recording(&mut output)) |
| 933 | .await?; |
| 934 | let before = output.len(); |
| 935 | rig.server |
| 936 | .prompt_run() |
| 937 | .project_event(&mut p, &start, &mut recording(&mut output)) |
| 938 | .await?; |
| 939 | assert_eq!(output.len(), before); |
| 940 | let dispatch = event( |
| 941 | 2, |
| 942 | &thread, |
| 943 | p.turn, |
| 944 | "tool.execution_started", |
| 945 | json!({"execution_id":"unknown"}), |
| 946 | ); |
| 947 | assert!( |
| 948 | rig.server |
| 949 | .prompt_run() |
| 950 | .project_event(&mut p, &dispatch, &mut recording(&mut output)) |
| 951 | .await |
| 952 | .is_err() |
| 953 | ); |
| 954 | rig.close().await; |
| 955 | Ok(()) |
| 956 | } |
| 957 | #[tokio::test(flavor = "current_thread")] |
| 958 | async fn external_agent_tool_completion_settles_from_the_external_call_id() -> Result<()> { |
| 959 | let mut rig = Rig::new(fixture_config(), vec![])?; |
| 960 | let id = rig.new_session().await; |
| 961 | let thread = rig.server.sessions[&id].thread_id.clone(); |
| 962 | let mut p = Projection { |
| 963 | session: &id, |
| 964 | thread: &thread, |
| 965 | turn: "turn-current", |
| 966 | workspace: Path::new("/"), |
| 967 | cursor: 0, |
| 968 | emit: true, |
| 969 | calls: HashMap::new(), |
| 970 | permissions: HashMap::new(), |
| 971 | }; |
| 972 | let mut output: Vec<Value> = Vec::new(); |
| 973 | let start = event( |
| 974 | 1, |
| 975 | &thread, |
| 976 | p.turn, |
| 977 | "item.started", |
| 978 | json!({"tool":{"id":"agent-call-1","name":"edit","input":{"path":"a.rs"}}}), |
| 979 | ); |
| 980 | rig.server |
| 981 | .prompt_run() |
| 982 | .project_event(&mut p, &start, &mut recording(&mut output)) |
| 983 | .await?; |
| 984 | assert_eq!(p.calls.len(), 1); |
| 985 | let done = event( |
| 986 | 2, |
| 987 | &thread, |
| 988 | p.turn, |
| 989 | "item.completed", |
| 990 | json!({"item":{"status":"completed","detail":"edited","metadata":{"external_agent":{"tool_call_id":"agent-call-1","kind":"edit"}}}}), |
| 991 | ); |
| 992 | rig.server |
| 993 | .prompt_run() |
| 994 | .project_event(&mut p, &done, &mut recording(&mut output)) |
| 995 | .await?; |
| 996 | assert!(p.calls.is_empty()); |
| 997 | let update = &output.last().expect("tool call update frame")["params"]["update"]; |
| 998 | assert_eq!(update["sessionUpdate"], "tool_call_update"); |
| 999 | assert_eq!(update["toolCallId"], "agent-call-1"); |
| 1000 | assert_eq!(update["status"], "completed"); |
| 1001 | rig.close().await; |
| 1002 | Ok(()) |
| 1003 | } |
| 1004 | #[tokio::test(flavor = "current_thread")] |
| 1005 | async fn projection_filters_foreign_turns_reasoning_and_unminted_approvals() -> Result<()> { |
| 1006 | let mut rig = Rig::new(fixture_config(), vec![])?; |
| 1007 | let id = rig.new_session().await; |
| 1008 | let thread = rig.server.sessions[&id].thread_id.clone(); |
| 1009 | let mut p = Projection { |
| 1010 | session: &id, |
| 1011 | thread: &thread, |
| 1012 | turn: "turn-current", |
| 1013 | workspace: Path::new("/"), |
| 1014 | cursor: 0, |
| 1015 | emit: true, |
| 1016 | calls: HashMap::new(), |
| 1017 | permissions: HashMap::new(), |
| 1018 | }; |
| 1019 | let mut output: Vec<Value> = Vec::new(); |
| 1020 | for record in [ |
| 1021 | event( |
| 1022 | 1, |
| 1023 | "foreign", |
| 1024 | p.turn, |
| 1025 | "item.delta", |
| 1026 | json!({"kind":"agent_message","delta":"foreign"}), |
| 1027 | ), |
| 1028 | event( |
| 1029 | 2, |
| 1030 | &thread, |
| 1031 | "foreign-turn", |
| 1032 | "item.delta", |
| 1033 | json!({"kind":"agent_message","delta":"other turn"}), |
| 1034 | ), |
| 1035 | event( |
| 1036 | 3, |
| 1037 | &thread, |
| 1038 | p.turn, |
| 1039 | "item.delta", |
| 1040 | json!({"kind":"reasoning","delta":"private reasoning"}), |
| 1041 | ), |
| 1042 | event( |
| 1043 | 4, |
| 1044 | &thread, |
| 1045 | p.turn, |
| 1046 | "approval.required", |
| 1047 | json!({"approval_id":"unminted","tool_call_id":"provider-id"}), |
| 1048 | ), |
| 1049 | ] { |
| 1050 | rig.server |
| 1051 | .prompt_run() |
| 1052 | .project_event(&mut p, &record, &mut recording(&mut output)) |
| 1053 | .await?; |
| 1054 | } |
| 1055 | assert!(output.is_empty()); |
| 1056 | assert!(p.permissions.is_empty()); |
| 1057 | rig.close().await; |
| 1058 | Ok(()) |
| 1059 | } |
| 1060 | #[tokio::test(flavor = "current_thread")] |
| 1061 | async fn terminal_store_fault_refuses_a_fabricated_completion() -> Result<()> { |
| 1062 | let mut rig = Rig::new(fixture_config(), vec![])?; |
| 1063 | let id = rig.new_session().await; |
| 1064 | let thread = rig.server.sessions[&id].thread_id.clone(); |
| 1065 | let mut p = Projection { |
| 1066 | session: &id, |
| 1067 | thread: &thread, |
| 1068 | turn: "turn-current", |
| 1069 | workspace: Path::new("/"), |
| 1070 | cursor: 0, |
| 1071 | emit: true, |
| 1072 | calls: HashMap::new(), |
| 1073 | permissions: HashMap::new(), |
| 1074 | }; |
| 1075 | let mut output: Vec<Value> = Vec::new(); |
| 1076 | let failure = event( |
| 1077 | 1, |
| 1078 | &thread, |
| 1079 | p.turn, |
| 1080 | codewhale_engine::runtime_threads::RUNTIME_STORE_FAILURE_EVENT, |
| 1081 | json!({"terminal":true,"message":"fixture store fault"}), |
| 1082 | ); |
| 1083 | let error = rig |
| 1084 | .server |
| 1085 | .prompt_run() |
| 1086 | .project_event(&mut p, &failure, &mut recording(&mut output)) |
| 1087 | .await |
| 1088 | .unwrap_err(); |
| 1089 | assert!(error.to_string().contains("no terminal receipt")); |
| 1090 | assert!(output.is_empty()); |
| 1091 | rig.close().await; |
| 1092 | Ok(()) |
| 1093 | } |
| 1094 | } |
| 1095 |