| 1 | use std::time::{Duration, Instant}; |
| 2 | |
| 3 | use anyhow::Result; |
| 4 | |
| 5 | type ExecSettlementProbe = std::pin::Pin< |
| 6 | Box<dyn std::future::Future<Output = Result<crate::core::ops::SubAgentSettlement>> + Send>, |
| 7 | >; |
| 8 | |
| 9 | /// Read the existing Engine stream through the one-shot host's final boundary. |
| 10 | /// Successful parent receipts remain pending while admitted children or their |
| 11 | /// completion inbox can still produce another normal Engine turn. This owns |
| 12 | /// only the deferred output receipt, never child execution or a turn loop. |
| 13 | pub struct ExecAgentEvents { |
| 14 | handle: crate::core::engine::EngineHandle, |
| 15 | deadline: tokio::time::Instant, |
| 16 | terminal: Option<crate::core::events::Event>, |
| 17 | probe: Option<ExecSettlementProbe>, |
| 18 | next_probe_at: tokio::time::Instant, |
| 19 | in_flight_usage: codewhale_models::Usage, |
| 20 | } |
| 21 | |
| 22 | impl ExecAgentEvents { |
| 23 | pub fn new(handle: crate::core::engine::EngineHandle, deadline: Instant) -> Self { |
| 24 | Self { |
| 25 | handle, |
| 26 | deadline: deadline.into(), |
| 27 | terminal: None, |
| 28 | probe: None, |
| 29 | next_probe_at: tokio::time::Instant::now(), |
| 30 | in_flight_usage: codewhale_models::Usage::default(), |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | fn stop_settlement( |
| 35 | &mut self, |
| 36 | status: crate::core::events::TurnOutcomeStatus, |
| 37 | error: String, |
| 38 | ) -> crate::core::events::Event { |
| 39 | use crate::core::events::Event; |
| 40 | self.handle |
| 41 | .cancel_with_reason(crate::core::engine::CancelReason::External); |
| 42 | // Cancellation is out of band; shutdown remains in the existing |
| 43 | // Engine mailbox so it also cancels detached session children. |
| 44 | let _ = self.handle.try_send(crate::core::ops::Op::Shutdown); |
| 45 | self.probe = None; |
| 46 | let mut terminal = self.terminal.take().expect("pending parent receipt"); |
| 47 | if let Event::TurnComplete { |
| 48 | status: terminal_status, |
| 49 | error: terminal_error, |
| 50 | usage, |
| 51 | parent_route_usage, |
| 52 | routed_usage_dropped_records, |
| 53 | .. |
| 54 | } = &mut terminal |
| 55 | { |
| 56 | *terminal_status = status; |
| 57 | *terminal_error = Some(error); |
| 58 | crate::core::turn::add_usage_to(usage, &self.in_flight_usage); |
| 59 | crate::core::turn::add_usage_to(parent_route_usage, &self.in_flight_usage); |
| 60 | // The host cannot prove usage settlement after abandoning the |
| 61 | // inbox. Keep reported usage and explicitly mark coverage partial. |
| 62 | *routed_usage_dropped_records = routed_usage_dropped_records.saturating_add(1); |
| 63 | } |
| 64 | self.in_flight_usage = codewhale_models::Usage::default(); |
| 65 | terminal |
| 66 | } |
| 67 | |
| 68 | pub async fn next(&mut self) -> Option<crate::core::events::Event> { |
| 69 | use crate::core::events::{Event, TurnOutcomeStatus}; |
| 70 | // Keep the streamed event on the stack instead of allocating another |
| 71 | // box for every token merely to equalize the two small control arms. |
| 72 | #[allow(clippy::large_enum_variant)] |
| 73 | enum Input { |
| 74 | Event(Option<Event>), |
| 75 | Probe(Result<crate::core::ops::SubAgentSettlement>), |
| 76 | Poll, |
| 77 | } |
| 78 | loop { |
| 79 | if matches!( |
| 80 | self.terminal, |
| 81 | Some(Event::TurnComplete { status, .. }) if status != TurnOutcomeStatus::Completed |
| 82 | ) { |
| 83 | return self.terminal.take(); |
| 84 | } |
| 85 | let settling = self.terminal.is_some(); |
| 86 | if settling && self.handle.is_cancelled() { |
| 87 | return Some(self.stop_settlement( |
| 88 | TurnOutcomeStatus::Interrupted, |
| 89 | "Headless exec cancelled while settling children; recorded usage is partial." |
| 90 | .to_string(), |
| 91 | )); |
| 92 | } |
| 93 | if settling && tokio::time::Instant::now() >= self.deadline { |
| 94 | return Some(self.stop_settlement( |
| 95 | TurnOutcomeStatus::Failed, |
| 96 | "Headless exec wall-clock budget exhausted while settling children; recorded usage is partial." |
| 97 | .to_string(), |
| 98 | )); |
| 99 | } |
| 100 | if settling && self.probe.is_none() && tokio::time::Instant::now() >= self.next_probe_at |
| 101 | { |
| 102 | let handle = self.handle.clone(); |
| 103 | self.probe = Some(Box::pin( |
| 104 | async move { handle.get_subagent_settlement().await }, |
| 105 | )); |
| 106 | } |
| 107 | let probing = self.probe.is_some(); |
| 108 | let wake_at = self.deadline.min(if probing { |
| 109 | tokio::time::Instant::now() + Duration::from_millis(250) |
| 110 | } else { |
| 111 | self.next_probe_at |
| 112 | }); |
| 113 | let input = { |
| 114 | let mut events = self.handle.rx_event.write().await; |
| 115 | tokio::select! { |
| 116 | biased; |
| 117 | // Drain queued SessionUpdated/TurnComplete events before |
| 118 | // accepting the later actor-owned idle receipt. |
| 119 | event = events.recv() => Input::Event(event), |
| 120 | result = async { self.probe.as_mut().expect("active probe").await }, if probing => Input::Probe(result), |
| 121 | () = tokio::time::sleep_until(wake_at), if settling => Input::Poll, |
| 122 | } |
| 123 | }; |
| 124 | match input { |
| 125 | Input::Poll => {} |
| 126 | Input::Probe(Ok(snapshot)) if snapshot.is_settled() => { |
| 127 | self.probe = None; |
| 128 | return self.terminal.take(); |
| 129 | } |
| 130 | Input::Probe(Ok(_)) => { |
| 131 | self.probe = None; |
| 132 | self.next_probe_at = tokio::time::Instant::now() + Duration::from_millis(250); |
| 133 | } |
| 134 | Input::Probe(Err(error)) => { |
| 135 | return Some(self.stop_settlement( |
| 136 | TurnOutcomeStatus::Failed, |
| 137 | format!( |
| 138 | "Cannot verify child settlement: {error}; recorded usage is partial." |
| 139 | ), |
| 140 | )); |
| 141 | } |
| 142 | Input::Event(None) if settling => { |
| 143 | return Some(self.stop_settlement( |
| 144 | TurnOutcomeStatus::Failed, |
| 145 | "Engine event channel closed before child settlement; recorded usage is partial." |
| 146 | .to_string(), |
| 147 | )); |
| 148 | } |
| 149 | Input::Event(None) => return None, |
| 150 | Input::Event(Some(mut event)) => { |
| 151 | match &mut event { |
| 152 | Event::TurnComplete { |
| 153 | usage, |
| 154 | parent_route_usage, |
| 155 | routed_usage_dropped_records, |
| 156 | status, |
| 157 | error, |
| 158 | .. |
| 159 | } => { |
| 160 | if let Some(Event::TurnComplete { |
| 161 | usage: prior_usage, |
| 162 | parent_route_usage: prior_parent_usage, |
| 163 | routed_usage_dropped_records: prior_dropped, |
| 164 | .. |
| 165 | }) = self.terminal.take() |
| 166 | { |
| 167 | crate::core::turn::add_usage_to(usage, &prior_usage); |
| 168 | crate::core::turn::add_usage_to( |
| 169 | parent_route_usage, |
| 170 | &prior_parent_usage, |
| 171 | ); |
| 172 | *routed_usage_dropped_records = |
| 173 | routed_usage_dropped_records.saturating_add(prior_dropped); |
| 174 | } |
| 175 | self.in_flight_usage = codewhale_models::Usage::default(); |
| 176 | if *status == TurnOutcomeStatus::Completed && error.is_none() { |
| 177 | self.terminal = Some(event); |
| 178 | self.next_probe_at = tokio::time::Instant::now(); |
| 179 | continue; |
| 180 | } |
| 181 | } |
| 182 | Event::TurnUsage { usage, .. } => { |
| 183 | crate::core::turn::add_usage_to(&mut self.in_flight_usage, usage); |
| 184 | } |
| 185 | Event::Error { envelope, .. } |
| 186 | if settling && exec_error_event_is_fatal(envelope) => |
| 187 | { |
| 188 | let terminal = self.stop_settlement( |
| 189 | TurnOutcomeStatus::Failed, |
| 190 | format!( |
| 191 | "{}; child settlement stopped and recorded usage is partial.", |
| 192 | envelope.message |
| 193 | ), |
| 194 | ); |
| 195 | self.terminal = Some(terminal); |
| 196 | } |
| 197 | _ => {} |
| 198 | } |
| 199 | return Some(event); |
| 200 | } |
| 201 | } |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | /// Should a mid-turn engine error event force the final exec summary into |
| 207 | /// failure? Only non-recoverable envelopes do. Recoverable warnings (stream |
| 208 | /// stall notices, transient retry noise) are emitted on the stream for |
| 209 | /// visibility, but the terminal `TurnComplete` event carries the |
| 210 | /// authoritative turn outcome — a warning must never fail a run whose turn |
| 211 | /// later completes. |
| 212 | pub fn exec_error_event_is_fatal(envelope: &codewhale_error_taxonomy::ErrorEnvelope) -> bool { |
| 213 | !envelope.recoverable |
| 214 | } |
| 215 |