Skip to main content

agent_base/engine/
executor.rs

1//! ActionExecutor seam (M3 design §3) — the kernel's one hole for "how a turn's
2//! output becomes actions, and how actions become observations".
3//!
4//! Domain-neutral by construction: the kernel knows nothing about tool calls or
5//! CodeAct. Backends implement [`ActionExecutor`] (and own their history
6//! protocol — the kernel pushes [`Observation::history_messages`] verbatim).
7//! Session life-and-death is a separate axis ([`SessionHandle`]) so neither
8//! trait becomes a god-face (OV-12).
9//!
10//! Contracts encoded here:
11//! - **Four-state parse** (D4+OV-7): [`ParseOutcome::Actions`] /
12//!   [`ParseOutcome::Empty`] / [`ParseOutcome::Incomplete`] /
13//!   [`ParseOutcome::Malformed`] map onto the loop's existing branches
14//!   (execute / nudge / nudge-retry / salvage-breaker).
15//! - **Observation always returns** (D15): once anything ran, `execute`
16//!   returns `Ok(Observation)` carrying `batch_status` (even `EnvDied`);
17//!   [`ExecError`] means not a single action got off the ground.
18//! - **Two-layer error face** (D9): per-action refusals and failures are
19//!   [`ActionOutcome`]s (model-visible), never error variants.
20
21use std::future::Future;
22use std::sync::Arc;
23use std::time::Duration;
24
25use async_trait::async_trait;
26use tokio_util::sync::CancellationToken;
27
28use crate::engine::runtime::LlmTurnResult;
29use crate::types::{
30    Action, ActionFormat, ActionOutcome, ApprovalDecision, ApprovalRequest, AskAnswer, AskOption,
31    ChatMessage, Observation,
32};
33
34/// The four-state verdict of `parse` (D4+OV-7).
35#[derive(Clone, Debug, PartialEq)]
36pub enum ParseOutcome {
37    /// This turn's output is one or more backend-format actions.
38    Actions(Vec<Action>),
39    /// Nothing actionable — the loop's old empty branch (nudge).
40    Empty,
41    /// Truncation salvage ran and the turn is still incomplete —
42    /// the loop's nudge-retry branch.
43    Incomplete,
44    /// Structural anomaly after salvage — the loop's old anomaly branch
45    /// (existing breaker / salvage semantics).
46    Malformed,
47}
48
49impl ParseOutcome {
50    /// True when this turn's output is action work (materialized or not):
51    /// such turns are never text-nudged or text-pushed.
52    pub fn has_action_intent(&self) -> bool {
53        matches!(self, ParseOutcome::Actions(_) | ParseOutcome::Incomplete)
54    }
55}
56
57/// `parse` failed to classify at all (internal invariant broken).
58#[derive(thiserror::Error, Debug)]
59pub enum ParseError {
60    #[error("turn output could not be classified: {0}")]
61    Unparseable(String),
62}
63
64/// Batch-level execution failure — reserved for "not one action ran" (D15).
65#[derive(thiserror::Error, Debug)]
66pub enum ExecError {
67    #[error("batch did not run: {reason}")]
68    NothingRan { reason: String },
69}
70
71/// Session lifecycle failure ([`SessionHandle::rebuild`]).
72#[derive(thiserror::Error, Debug)]
73pub enum SessionError {
74    #[error("session rebuild failed: {0}")]
75    RebuildFailed(String),
76}
77
78/// The product layer failed to carry an interaction to completion.
79#[derive(thiserror::Error, Debug)]
80pub enum InteractionError {
81    #[error("interaction timed out: {0}")]
82    Timeout(String),
83    #[error("interaction cancelled")]
84    Cancelled,
85    #[error("interaction channel failed: {0}")]
86    Channel(String),
87}
88
89/// Default per-interaction watchdog ([`ExecCtx::interact_timeout`]) — an
90/// unanswered suspension must not deadlock the run (M3 failure table: an
91/// unanswered consent hangs forever). Generous, because this is human reading
92/// time; a product that owns the human relationship (phimint's TUI) clears it
93/// to `None` and leans on the run's cancel token alone.
94pub const DEFAULT_INTERACT_TIMEOUT: Duration = Duration::from_secs(600);
95
96/// Product-layer interaction surface hung off [`ExecCtx`] (OV-6): consent and
97/// ask_user suspend the executing action and wait for the product to answer.
98/// Routed through the host's single throat — the same seam policy and journal
99/// already use. `cancel` is the run's one token (interrupt / timeout /
100/// watchdog); implementations must release promptly on it.
101#[async_trait]
102pub trait InteractionChannel: Send + Sync {
103    /// Consent / approval request; suspends until the product layer answers.
104    async fn request_consent(
105        &self,
106        request: ApprovalRequest,
107        cancel: &CancellationToken,
108    ) -> Result<ApprovalDecision, InteractionError>;
109
110    /// Ask the user to pick between candidates; suspends until answered.
111    /// A skip is an answer too ([`AskAnswer::Skipped`]) — never re-ask.
112    async fn ask_user(
113        &self,
114        question: &str,
115        options: &[AskOption],
116        cancel: &CancellationToken,
117    ) -> Result<AskAnswer, InteractionError>;
118}
119
120/// Execution context threaded through `execute` (OV-6): one cancel token for
121/// user interrupt / timeout / watchdog, one interaction channel for consent
122/// and ask_user. Reach the channel only through [`ExecCtx::request_consent`] /
123/// [`ExecCtx::ask_user`] — those carry the suspension discipline (answer /
124/// cancel / watchdog deadline); calling the trait directly drops it.
125pub struct ExecCtx {
126    /// User interrupt / timeout / watchdog share this token.
127    pub cancel: CancellationToken,
128    /// Consent / ask_user suspension points.
129    pub interact: Arc<dyn InteractionChannel>,
130    /// Per-interaction deadline: an unanswered suspension cancels the run's
131    /// token and fails with [`InteractionError::Timeout`] instead of hanging
132    /// forever. `None` = the run's cancel token is the only guard (human time
133    /// is unbounded — phimint's TUI sets this).
134    pub interact_timeout: Option<Duration>,
135}
136
137impl ExecCtx {
138    /// One run's execution context. Interactions carry the
139    /// [`DEFAULT_INTERACT_TIMEOUT`] watchdog; the construction site overrides
140    /// (or clears) `interact_timeout` when it knows better.
141    pub fn new(cancel: CancellationToken, interact: Arc<dyn InteractionChannel>) -> Self {
142        Self {
143            cancel,
144            interact,
145            interact_timeout: Some(DEFAULT_INTERACT_TIMEOUT),
146        }
147    }
148
149    /// Set the per-interaction deadline (`None` = wait as long as the run lives).
150    pub fn with_interact_timeout(mut self, interact_timeout: Option<Duration>) -> Self {
151        self.interact_timeout = interact_timeout;
152        self
153    }
154
155    /// Consent request: suspends on the product layer, released by the answer,
156    /// the cancel token, or the interaction watchdog.
157    pub async fn request_consent(
158        &self,
159        request: ApprovalRequest,
160    ) -> Result<ApprovalDecision, InteractionError> {
161        let call = self.interact.request_consent(request, &self.cancel);
162        self.guard(call).await
163    }
164
165    /// Ask the user to pick between candidates: suspends like
166    /// [`ExecCtx::request_consent`] and shares its guards.
167    pub async fn ask_user(
168        &self,
169        question: &str,
170        options: &[AskOption],
171    ) -> Result<AskAnswer, InteractionError> {
172        let call = self.interact.ask_user(question, options, &self.cancel);
173        self.guard(call).await
174    }
175
176    /// The suspension discipline (failure table: an unanswered interaction
177    /// must not deadlock the run): answer first, then cancel, then the
178    /// watchdog — which fires through cancel too, so every other suspension
179    /// point and the batch unwind on the same token.
180    async fn guard<T>(
181        &self,
182        call: impl Future<Output = Result<T, InteractionError>>,
183    ) -> Result<T, InteractionError> {
184        tokio::select! {
185            biased;
186            answer = call => answer,
187            _ = self.cancel.cancelled() => Err(InteractionError::Cancelled),
188            waited = async {
189                match self.interact_timeout {
190                    Some(d) => {
191                        tokio::time::sleep(d).await;
192                        d
193                    }
194                    None => std::future::pending().await,
195                }
196            } => {
197                self.cancel.cancel();
198                Err(InteractionError::Timeout(format!(
199                    "no answer within {waited:?}; the run was cancelled"
200                )))
201            }
202        }
203    }
204}
205
206/// The seam: one turn's output in, one observation out.
207#[async_trait]
208pub trait ActionExecutor: Send + Sync {
209    /// Turn output → this backend's action format. Truncation salvage (structural
210    /// verdict + text-channel harvest) is a parse-end move; stream aggregation
211    /// stays in the provider layer. CodeAct implementations must validate the
212    /// full batch before executing anything (D2).
213    fn parse(&self, turn: &LlmTurnResult) -> Result<ParseOutcome, ParseError>;
214
215    /// Execute a batch and return the observation. Never dropped because the
216    /// environment died (D15): if anything ran, it's `Ok(Observation)` with
217    /// `batch_status` set; `Err(ExecError)` only when nothing ran.
218    async fn execute(
219        &mut self,
220        actions: Vec<Action>,
221        ctx: &ExecCtx,
222    ) -> Result<Observation, ExecError>;
223}
224
225/// Session life-and-death (OV-12): a different axis from the action face.
226#[async_trait]
227pub trait SessionHandle: Send + Sync {
228    /// Whether the execution environment is still usable.
229    fn is_alive(&self) -> bool;
230
231    /// Rebuild after `is_alive()` goes false. Failure fails the whole turn —
232    /// no retry loop on a dead environment (D10).
233    async fn rebuild(&mut self) -> Result<(), SessionError>;
234}
235
236/// Model-visible fate for an action the crash window cut off (OV-4). The
237/// kernel owns this vocabulary and hands it to the backend inside
238/// [`ActionOutcome::summary`]; a backend only renders the fate in its own
239/// history shape ([`ActionBackend::render_fates`]).
240pub const INTERRUPTED_SUMMARY: &str = "已中断/未执行";
241
242/// The kernel's mount face for one runtime's injected action backend (T10c).
243/// The built-in tool-call backend keeps its own flow; this face serves any
244/// other action format one session can interleave with it (envelope turns go
245/// to tools, text turns go here).
246///
247/// Supertraits are the M3a seam contracts. The extra methods are the two
248/// things the kernel needs to route a session around a backend — its format
249/// (checkpoint pin / resume affinity, T5) and its history shape for a batch
250/// that produced no observation (dangling-batch synthesis at resume, OV-4;
251/// `Err(ExecError)` fates, D15). The kernel pushes the rendered messages
252/// verbatim, same as [`Observation::history_messages`].
253#[async_trait]
254pub trait ActionBackend: ActionExecutor + SessionHandle {
255    /// This backend's action format. Must not be [`ActionFormat::ToolCall`] —
256    /// the built-in tool-call backend owns that format and its flow.
257    fn format(&self) -> ActionFormat;
258
259    /// Render one batch's history from per-action fates in this backend's own
260    /// protocol shape — the messages ride [`ActionOutcome`]s' summaries
261    /// (including [`INTERRUPTED_SUMMARY`]) and are pushed as-is.
262    fn render_fates(&self, actions: &[Action], fates: &[ActionOutcome]) -> Vec<ChatMessage>;
263}
264
265/// The fail-closed interaction surface for a runtime that mounted an action
266/// backend but no product channel: every human request refuses with the gap
267/// named. An unanswered interaction must fail closed — never hang, never
268/// silently allow.
269pub(crate) struct FailClosedInteract;
270
271#[async_trait]
272impl InteractionChannel for FailClosedInteract {
273    async fn request_consent(
274        &self,
275        _request: ApprovalRequest,
276        _cancel: &CancellationToken,
277    ) -> Result<ApprovalDecision, InteractionError> {
278        Err(InteractionError::Channel(
279            "no interaction channel mounted on this runtime".into(),
280        ))
281    }
282
283    async fn ask_user(
284        &self,
285        _question: &str,
286        _options: &[AskOption],
287        _cancel: &CancellationToken,
288    ) -> Result<AskAnswer, InteractionError> {
289        Err(InteractionError::Channel(
290            "no interaction channel mounted on this runtime".into(),
291        ))
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298    use crate::types::{ActionFormat, ActionOutcome, BatchStatus};
299    use std::sync::Mutex;
300    use tokio::sync::{mpsc, oneshot};
301
302    fn turn() -> LlmTurnResult {
303        LlmTurnResult {
304            full_text: String::new(),
305            reasoning_text: String::new(),
306            is_tool_call: true,
307            tool_calls: vec![serde_json::json!({
308                "id": "call_1", "name": "echo", "arguments": "{\"x\":1}"
309            })],
310            integrity: Default::default(),
311            usage: None,
312            finish_reason: Some("tool_calls".into()),
313            ttft_ms: 1,
314            llm_duration_ms: 2,
315            reasoning_only: false,
316            thinking_signature: None,
317        }
318    }
319
320    fn action(id: &str) -> Action {
321        Action {
322            id: id.into(),
323            name: "echo".into(),
324            args: serde_json::Value::String(r#"{"x":1}"#.into()),
325            identity: r#"echo::{"x":1}"#.into(),
326            format: ActionFormat::ToolCall,
327        }
328    }
329
330    /// Test double standing in for a backend (the tool-call executor lands in
331    /// T4; this pins the contract shape in the meantime).
332    struct DummyExecutor;
333
334    #[async_trait]
335    impl ActionExecutor for DummyExecutor {
336        fn parse(&self, turn: &LlmTurnResult) -> Result<ParseOutcome, ParseError> {
337            if turn.is_tool_call && !turn.tool_calls.is_empty() {
338                Ok(ParseOutcome::Actions(vec![action("call_1")]))
339            } else {
340                Ok(ParseOutcome::Empty)
341            }
342        }
343
344        async fn execute(
345            &mut self,
346            actions: Vec<Action>,
347            _ctx: &ExecCtx,
348        ) -> Result<Observation, ExecError> {
349            if actions.is_empty() {
350                return Err(ExecError::NothingRan {
351                    reason: "empty batch".into(),
352                });
353            }
354            Ok(Observation {
355                outcomes: actions
356                    .iter()
357                    .map(|a| ActionOutcome {
358                        action_id: a.id.clone(),
359                        name: a.name.clone(),
360                        ok: true,
361                        denied: false,
362                        summary: "1".into(),
363                        details: None,
364                    })
365                    .collect(),
366                events: vec![],
367                history_messages: vec![],
368                batch_status: BatchStatus::Completed,
369            })
370        }
371    }
372
373    struct NoopInteract;
374
375    #[async_trait]
376    impl InteractionChannel for NoopInteract {
377        async fn request_consent(
378            &self,
379            _request: ApprovalRequest,
380            _cancel: &CancellationToken,
381        ) -> Result<ApprovalDecision, InteractionError> {
382            Ok(ApprovalDecision::AllowOnce)
383        }
384
385        async fn ask_user(
386            &self,
387            _question: &str,
388            _options: &[AskOption],
389            _cancel: &CancellationToken,
390        ) -> Result<AskAnswer, InteractionError> {
391            Ok(AskAnswer::Picked {
392                id: "a".into(),
393                label: "ok".into(),
394            })
395        }
396    }
397
398    fn ctx() -> ExecCtx {
399        ExecCtx::new(CancellationToken::new(), Arc::new(NoopInteract))
400    }
401
402    fn approval_request() -> ApprovalRequest {
403        ApprovalRequest {
404            title: "t".into(),
405            message: "m".into(),
406            action_key: None,
407            risk_level: crate::types::RiskLevel::Safe,
408            raw: None,
409            source: None,
410        }
411    }
412
413    #[tokio::test]
414    async fn parse_four_states_are_distinct() {
415        let exec = DummyExecutor;
416        assert!(matches!(
417            exec.parse(&turn()).unwrap(),
418            ParseOutcome::Actions(_)
419        ));
420        let mut empty_turn = turn();
421        empty_turn.is_tool_call = false;
422        empty_turn.tool_calls = vec![];
423        assert_eq!(exec.parse(&empty_turn).unwrap(), ParseOutcome::Empty);
424        // Incomplete / Malformed are backend verdicts; the contract is that all
425        // four states are expressible and distinct.
426        assert_ne!(
427            std::mem::discriminant(&ParseOutcome::Incomplete),
428            std::mem::discriminant(&ParseOutcome::Malformed)
429        );
430    }
431
432    #[tokio::test]
433    async fn execute_returns_observation_when_anything_ran() {
434        let mut exec = DummyExecutor;
435        let obs = exec.execute(vec![action("call_1")], &ctx()).await.unwrap();
436        assert_eq!(obs.batch_status, BatchStatus::Completed);
437        assert_eq!(obs.outcomes.len(), 1);
438        assert!(obs.outcomes[0].ok);
439    }
440
441    #[tokio::test]
442    async fn execute_errors_only_when_nothing_ran() {
443        let mut exec = DummyExecutor;
444        let err = exec.execute(vec![], &ctx()).await.unwrap_err();
445        assert!(matches!(err, ExecError::NothingRan { .. }));
446    }
447
448    #[tokio::test]
449    async fn interaction_channel_round_trips() {
450        let ctx = ctx();
451        let decision = ctx.request_consent(approval_request()).await.unwrap();
452        assert_eq!(decision, ApprovalDecision::AllowOnce);
453        assert_eq!(
454            ctx.ask_user("?", &[]).await.unwrap(),
455            AskAnswer::Picked {
456                id: "a".into(),
457                label: "ok".into(),
458            }
459        );
460    }
461
462    /// A channel whose answers arrive on a oneshot the test holds — the
463    /// product side of a suspension (in a cell, the host-call round trip).
464    /// An uncompleted oneshot is "nobody answered".
465    struct ScriptedInteract {
466        arrived: mpsc::UnboundedSender<&'static str>,
467        consent: Mutex<Option<oneshot::Receiver<ApprovalDecision>>>,
468        ask: Mutex<Option<oneshot::Receiver<AskAnswer>>>,
469    }
470
471    #[async_trait]
472    impl InteractionChannel for ScriptedInteract {
473        async fn request_consent(
474            &self,
475            _request: ApprovalRequest,
476            _cancel: &CancellationToken,
477        ) -> Result<ApprovalDecision, InteractionError> {
478            let _ = self.arrived.send("consent");
479            let rx = self
480                .consent
481                .lock()
482                .unwrap()
483                .take()
484                .expect("one consent answer per test");
485            rx.await
486                .map_err(|_| InteractionError::Channel("answer dropped".into()))
487        }
488
489        async fn ask_user(
490            &self,
491            _question: &str,
492            _options: &[AskOption],
493            _cancel: &CancellationToken,
494        ) -> Result<AskAnswer, InteractionError> {
495            let _ = self.arrived.send("ask");
496            let rx = self
497                .ask
498                .lock()
499                .unwrap()
500                .take()
501                .expect("one ask answer per test");
502            rx.await
503                .map_err(|_| InteractionError::Channel("answer dropped".into()))
504        }
505    }
506
507    fn scripted(
508        consent: Option<oneshot::Receiver<ApprovalDecision>>,
509        ask: Option<oneshot::Receiver<AskAnswer>>,
510    ) -> (Arc<ScriptedInteract>, mpsc::UnboundedReceiver<&'static str>) {
511        let (arrived_tx, arrived_rx) = mpsc::unbounded_channel();
512        (
513            Arc::new(ScriptedInteract {
514                arrived: arrived_tx,
515                consent: Mutex::new(consent),
516                ask: Mutex::new(ask),
517            }),
518            arrived_rx,
519        )
520    }
521
522    /// Scenario 1 (T8): a consent from inside the batch suspends on the
523    /// product layer and resumes with the answer.
524    #[tokio::test]
525    async fn consent_suspends_until_the_product_answers() {
526        let (answer_tx, answer_rx) = oneshot::channel();
527        let (interact, mut arrived) = scripted(Some(answer_rx), None);
528        let ctx = ExecCtx::new(CancellationToken::new(), interact);
529        let call = tokio::spawn(async move { ctx.request_consent(approval_request()).await });
530        assert_eq!(
531            arrived.recv().await,
532            Some("consent"),
533            "the suspension is parked"
534        );
535        answer_tx.send(ApprovalDecision::AllowAlways).unwrap();
536        assert_eq!(call.await.unwrap().unwrap(), ApprovalDecision::AllowAlways);
537    }
538
539    /// Scenario 2 (T8): an ask suspends and resumes with the user's pick.
540    #[tokio::test]
541    async fn ask_user_suspends_until_the_user_picks() {
542        let (answer_tx, answer_rx) = oneshot::channel();
543        let (interact, mut arrived) = scripted(None, Some(answer_rx));
544        let ctx = ExecCtx::new(CancellationToken::new(), interact);
545        let call = tokio::spawn(async move {
546            ctx.ask_user(
547                "which first?",
548                &[AskOption {
549                    id: "a".into(),
550                    label: "search".into(),
551                    note: None,
552                }],
553            )
554            .await
555        });
556        assert_eq!(arrived.recv().await, Some("ask"));
557        answer_tx
558            .send(AskAnswer::Picked {
559                id: "a".into(),
560                label: "search".into(),
561            })
562            .unwrap();
563        assert_eq!(
564            call.await.unwrap().unwrap(),
565            AskAnswer::Picked {
566                id: "a".into(),
567                label: "search".into(),
568            }
569        );
570    }
571
572    /// Scenario 3 (T8): interrupt — the run's cancel token releases a
573    /// suspended interaction instead of leaving it hanging.
574    #[tokio::test]
575    async fn interrupt_cancels_a_suspended_interaction() {
576        let (answer_tx, answer_rx) = oneshot::channel();
577        let (interact, mut arrived) = scripted(Some(answer_rx), None);
578        let token = CancellationToken::new();
579        let ctx = ExecCtx::new(token.clone(), interact);
580        let call = tokio::spawn(async move { ctx.request_consent(approval_request()).await });
581        assert_eq!(arrived.recv().await, Some("consent"));
582        token.cancel();
583        assert!(matches!(
584            call.await.unwrap(),
585            Err(InteractionError::Cancelled)
586        ));
587        drop(answer_tx);
588    }
589
590    /// Failure-table guard: an unanswered interaction must not deadlock —
591    /// the watchdog fires, the run is cancelled through the same token
592    /// (timeout goes through cancel), and the error says so in words.
593    #[tokio::test]
594    async fn an_unanswered_interaction_fails_the_run_through_cancel() {
595        let (answer_tx, answer_rx) = oneshot::channel();
596        let (interact, mut arrived) = scripted(Some(answer_rx), None);
597        let token = CancellationToken::new();
598        let ctx = ExecCtx::new(token.clone(), interact)
599            .with_interact_timeout(Some(Duration::from_millis(50)));
600        let call = tokio::spawn(async move { ctx.request_consent(approval_request()).await });
601        assert_eq!(arrived.recv().await, Some("consent"));
602        let err = call.await.unwrap().unwrap_err();
603        let msg = err.to_string();
604        assert!(matches!(&err, InteractionError::Timeout(_)), "{msg}");
605        assert!(
606            msg.contains("no answer within 50ms"),
607            "timeout wording: {msg}"
608        );
609        assert!(
610            msg.contains("the run was cancelled"),
611            "timeout wording: {msg}"
612        );
613        assert!(
614            token.is_cancelled(),
615            "timeout must fire through the run's cancel token"
616        );
617        drop(answer_tx);
618    }
619
620    struct DeadSession;
621
622    #[async_trait]
623    impl SessionHandle for DeadSession {
624        fn is_alive(&self) -> bool {
625            false
626        }
627
628        async fn rebuild(&mut self) -> Result<(), SessionError> {
629            Err(SessionError::RebuildFailed("worker gone".into()))
630        }
631    }
632
633    #[tokio::test]
634    async fn session_handle_rebuild_failure_is_explicit() {
635        let mut handle = DeadSession;
636        assert!(!handle.is_alive());
637        assert!(matches!(
638            handle.rebuild().await,
639            Err(SessionError::RebuildFailed(_))
640        ));
641    }
642}