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            usage: None,
311            finish_reason: Some("tool_calls".into()),
312            ttft_ms: 1,
313            llm_duration_ms: 2,
314            reasoning_only: false,
315            thinking_signature: None,
316        }
317    }
318
319    fn action(id: &str) -> Action {
320        Action {
321            id: id.into(),
322            name: "echo".into(),
323            args: serde_json::Value::String(r#"{"x":1}"#.into()),
324            identity: r#"echo::{"x":1}"#.into(),
325            format: ActionFormat::ToolCall,
326        }
327    }
328
329    /// Test double standing in for a backend (the tool-call executor lands in
330    /// T4; this pins the contract shape in the meantime).
331    struct DummyExecutor;
332
333    #[async_trait]
334    impl ActionExecutor for DummyExecutor {
335        fn parse(&self, turn: &LlmTurnResult) -> Result<ParseOutcome, ParseError> {
336            if turn.is_tool_call && !turn.tool_calls.is_empty() {
337                Ok(ParseOutcome::Actions(vec![action("call_1")]))
338            } else {
339                Ok(ParseOutcome::Empty)
340            }
341        }
342
343        async fn execute(
344            &mut self,
345            actions: Vec<Action>,
346            _ctx: &ExecCtx,
347        ) -> Result<Observation, ExecError> {
348            if actions.is_empty() {
349                return Err(ExecError::NothingRan {
350                    reason: "empty batch".into(),
351                });
352            }
353            Ok(Observation {
354                outcomes: actions
355                    .iter()
356                    .map(|a| ActionOutcome {
357                        action_id: a.id.clone(),
358                        name: a.name.clone(),
359                        ok: true,
360                        denied: false,
361                        summary: "1".into(),
362                        details: None,
363                    })
364                    .collect(),
365                events: vec![],
366                history_messages: vec![],
367                batch_status: BatchStatus::Completed,
368            })
369        }
370    }
371
372    struct NoopInteract;
373
374    #[async_trait]
375    impl InteractionChannel for NoopInteract {
376        async fn request_consent(
377            &self,
378            _request: ApprovalRequest,
379            _cancel: &CancellationToken,
380        ) -> Result<ApprovalDecision, InteractionError> {
381            Ok(ApprovalDecision::AllowOnce)
382        }
383
384        async fn ask_user(
385            &self,
386            _question: &str,
387            _options: &[AskOption],
388            _cancel: &CancellationToken,
389        ) -> Result<AskAnswer, InteractionError> {
390            Ok(AskAnswer::Picked {
391                id: "a".into(),
392                label: "ok".into(),
393            })
394        }
395    }
396
397    fn ctx() -> ExecCtx {
398        ExecCtx::new(CancellationToken::new(), Arc::new(NoopInteract))
399    }
400
401    fn approval_request() -> ApprovalRequest {
402        ApprovalRequest {
403            title: "t".into(),
404            message: "m".into(),
405            action_key: None,
406            risk_level: crate::types::RiskLevel::Safe,
407            raw: None,
408            source: None,
409        }
410    }
411
412    #[tokio::test]
413    async fn parse_four_states_are_distinct() {
414        let exec = DummyExecutor;
415        assert!(matches!(
416            exec.parse(&turn()).unwrap(),
417            ParseOutcome::Actions(_)
418        ));
419        let mut empty_turn = turn();
420        empty_turn.is_tool_call = false;
421        empty_turn.tool_calls = vec![];
422        assert_eq!(exec.parse(&empty_turn).unwrap(), ParseOutcome::Empty);
423        // Incomplete / Malformed are backend verdicts; the contract is that all
424        // four states are expressible and distinct.
425        assert_ne!(
426            std::mem::discriminant(&ParseOutcome::Incomplete),
427            std::mem::discriminant(&ParseOutcome::Malformed)
428        );
429    }
430
431    #[tokio::test]
432    async fn execute_returns_observation_when_anything_ran() {
433        let mut exec = DummyExecutor;
434        let obs = exec.execute(vec![action("call_1")], &ctx()).await.unwrap();
435        assert_eq!(obs.batch_status, BatchStatus::Completed);
436        assert_eq!(obs.outcomes.len(), 1);
437        assert!(obs.outcomes[0].ok);
438    }
439
440    #[tokio::test]
441    async fn execute_errors_only_when_nothing_ran() {
442        let mut exec = DummyExecutor;
443        let err = exec.execute(vec![], &ctx()).await.unwrap_err();
444        assert!(matches!(err, ExecError::NothingRan { .. }));
445    }
446
447    #[tokio::test]
448    async fn interaction_channel_round_trips() {
449        let ctx = ctx();
450        let decision = ctx.request_consent(approval_request()).await.unwrap();
451        assert_eq!(decision, ApprovalDecision::AllowOnce);
452        assert_eq!(
453            ctx.ask_user("?", &[]).await.unwrap(),
454            AskAnswer::Picked {
455                id: "a".into(),
456                label: "ok".into(),
457            }
458        );
459    }
460
461    /// A channel whose answers arrive on a oneshot the test holds — the
462    /// product side of a suspension (in a cell, the host-call round trip).
463    /// An uncompleted oneshot is "nobody answered".
464    struct ScriptedInteract {
465        arrived: mpsc::UnboundedSender<&'static str>,
466        consent: Mutex<Option<oneshot::Receiver<ApprovalDecision>>>,
467        ask: Mutex<Option<oneshot::Receiver<AskAnswer>>>,
468    }
469
470    #[async_trait]
471    impl InteractionChannel for ScriptedInteract {
472        async fn request_consent(
473            &self,
474            _request: ApprovalRequest,
475            _cancel: &CancellationToken,
476        ) -> Result<ApprovalDecision, InteractionError> {
477            let _ = self.arrived.send("consent");
478            let rx = self
479                .consent
480                .lock()
481                .unwrap()
482                .take()
483                .expect("one consent answer per test");
484            rx.await
485                .map_err(|_| InteractionError::Channel("answer dropped".into()))
486        }
487
488        async fn ask_user(
489            &self,
490            _question: &str,
491            _options: &[AskOption],
492            _cancel: &CancellationToken,
493        ) -> Result<AskAnswer, InteractionError> {
494            let _ = self.arrived.send("ask");
495            let rx = self
496                .ask
497                .lock()
498                .unwrap()
499                .take()
500                .expect("one ask answer per test");
501            rx.await
502                .map_err(|_| InteractionError::Channel("answer dropped".into()))
503        }
504    }
505
506    fn scripted(
507        consent: Option<oneshot::Receiver<ApprovalDecision>>,
508        ask: Option<oneshot::Receiver<AskAnswer>>,
509    ) -> (Arc<ScriptedInteract>, mpsc::UnboundedReceiver<&'static str>) {
510        let (arrived_tx, arrived_rx) = mpsc::unbounded_channel();
511        (
512            Arc::new(ScriptedInteract {
513                arrived: arrived_tx,
514                consent: Mutex::new(consent),
515                ask: Mutex::new(ask),
516            }),
517            arrived_rx,
518        )
519    }
520
521    /// Scenario 1 (T8): a consent from inside the batch suspends on the
522    /// product layer and resumes with the answer.
523    #[tokio::test]
524    async fn consent_suspends_until_the_product_answers() {
525        let (answer_tx, answer_rx) = oneshot::channel();
526        let (interact, mut arrived) = scripted(Some(answer_rx), None);
527        let ctx = ExecCtx::new(CancellationToken::new(), interact);
528        let call = tokio::spawn(async move { ctx.request_consent(approval_request()).await });
529        assert_eq!(
530            arrived.recv().await,
531            Some("consent"),
532            "the suspension is parked"
533        );
534        answer_tx.send(ApprovalDecision::AllowAlways).unwrap();
535        assert_eq!(call.await.unwrap().unwrap(), ApprovalDecision::AllowAlways);
536    }
537
538    /// Scenario 2 (T8): an ask suspends and resumes with the user's pick.
539    #[tokio::test]
540    async fn ask_user_suspends_until_the_user_picks() {
541        let (answer_tx, answer_rx) = oneshot::channel();
542        let (interact, mut arrived) = scripted(None, Some(answer_rx));
543        let ctx = ExecCtx::new(CancellationToken::new(), interact);
544        let call = tokio::spawn(async move {
545            ctx.ask_user(
546                "which first?",
547                &[AskOption {
548                    id: "a".into(),
549                    label: "search".into(),
550                    note: None,
551                }],
552            )
553            .await
554        });
555        assert_eq!(arrived.recv().await, Some("ask"));
556        answer_tx
557            .send(AskAnswer::Picked {
558                id: "a".into(),
559                label: "search".into(),
560            })
561            .unwrap();
562        assert_eq!(
563            call.await.unwrap().unwrap(),
564            AskAnswer::Picked {
565                id: "a".into(),
566                label: "search".into(),
567            }
568        );
569    }
570
571    /// Scenario 3 (T8): interrupt — the run's cancel token releases a
572    /// suspended interaction instead of leaving it hanging.
573    #[tokio::test]
574    async fn interrupt_cancels_a_suspended_interaction() {
575        let (answer_tx, answer_rx) = oneshot::channel();
576        let (interact, mut arrived) = scripted(Some(answer_rx), None);
577        let token = CancellationToken::new();
578        let ctx = ExecCtx::new(token.clone(), interact);
579        let call = tokio::spawn(async move { ctx.request_consent(approval_request()).await });
580        assert_eq!(arrived.recv().await, Some("consent"));
581        token.cancel();
582        assert!(matches!(
583            call.await.unwrap(),
584            Err(InteractionError::Cancelled)
585        ));
586        drop(answer_tx);
587    }
588
589    /// Failure-table guard: an unanswered interaction must not deadlock —
590    /// the watchdog fires, the run is cancelled through the same token
591    /// (timeout goes through cancel), and the error says so in words.
592    #[tokio::test]
593    async fn an_unanswered_interaction_fails_the_run_through_cancel() {
594        let (answer_tx, answer_rx) = oneshot::channel();
595        let (interact, mut arrived) = scripted(Some(answer_rx), None);
596        let token = CancellationToken::new();
597        let ctx = ExecCtx::new(token.clone(), interact)
598            .with_interact_timeout(Some(Duration::from_millis(50)));
599        let call = tokio::spawn(async move { ctx.request_consent(approval_request()).await });
600        assert_eq!(arrived.recv().await, Some("consent"));
601        let err = call.await.unwrap().unwrap_err();
602        let msg = err.to_string();
603        assert!(matches!(&err, InteractionError::Timeout(_)), "{msg}");
604        assert!(
605            msg.contains("no answer within 50ms"),
606            "timeout wording: {msg}"
607        );
608        assert!(
609            msg.contains("the run was cancelled"),
610            "timeout wording: {msg}"
611        );
612        assert!(
613            token.is_cancelled(),
614            "timeout must fire through the run's cancel token"
615        );
616        drop(answer_tx);
617    }
618
619    struct DeadSession;
620
621    #[async_trait]
622    impl SessionHandle for DeadSession {
623        fn is_alive(&self) -> bool {
624            false
625        }
626
627        async fn rebuild(&mut self) -> Result<(), SessionError> {
628            Err(SessionError::RebuildFailed("worker gone".into()))
629        }
630    }
631
632    #[tokio::test]
633    async fn session_handle_rebuild_failure_is_explicit() {
634        let mut handle = DeadSession;
635        assert!(!handle.is_alive());
636        assert!(matches!(
637            handle.rebuild().await,
638            Err(SessionError::RebuildFailed(_))
639        ));
640    }
641}