use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use tokio_util::sync::CancellationToken;
use crate::engine::runtime::LlmTurnResult;
use crate::types::{
Action, ActionFormat, ActionOutcome, ApprovalDecision, ApprovalRequest, AskAnswer, AskOption,
ChatMessage, Observation,
};
#[derive(Clone, Debug, PartialEq)]
pub enum ParseOutcome {
Actions(Vec<Action>),
Empty,
Incomplete,
Malformed,
}
impl ParseOutcome {
pub fn has_action_intent(&self) -> bool {
matches!(self, ParseOutcome::Actions(_) | ParseOutcome::Incomplete)
}
}
#[derive(thiserror::Error, Debug)]
pub enum ParseError {
#[error("turn output could not be classified: {0}")]
Unparseable(String),
}
#[derive(thiserror::Error, Debug)]
pub enum ExecError {
#[error("batch did not run: {reason}")]
NothingRan { reason: String },
}
#[derive(thiserror::Error, Debug)]
pub enum SessionError {
#[error("session rebuild failed: {0}")]
RebuildFailed(String),
}
#[derive(thiserror::Error, Debug)]
pub enum InteractionError {
#[error("interaction timed out: {0}")]
Timeout(String),
#[error("interaction cancelled")]
Cancelled,
#[error("interaction channel failed: {0}")]
Channel(String),
}
pub const DEFAULT_INTERACT_TIMEOUT: Duration = Duration::from_secs(600);
#[async_trait]
pub trait InteractionChannel: Send + Sync {
async fn request_consent(
&self,
request: ApprovalRequest,
cancel: &CancellationToken,
) -> Result<ApprovalDecision, InteractionError>;
async fn ask_user(
&self,
question: &str,
options: &[AskOption],
cancel: &CancellationToken,
) -> Result<AskAnswer, InteractionError>;
}
pub struct ExecCtx {
pub cancel: CancellationToken,
pub interact: Arc<dyn InteractionChannel>,
pub interact_timeout: Option<Duration>,
}
impl ExecCtx {
pub fn new(cancel: CancellationToken, interact: Arc<dyn InteractionChannel>) -> Self {
Self {
cancel,
interact,
interact_timeout: Some(DEFAULT_INTERACT_TIMEOUT),
}
}
pub fn with_interact_timeout(mut self, interact_timeout: Option<Duration>) -> Self {
self.interact_timeout = interact_timeout;
self
}
pub async fn request_consent(
&self,
request: ApprovalRequest,
) -> Result<ApprovalDecision, InteractionError> {
let call = self.interact.request_consent(request, &self.cancel);
self.guard(call).await
}
pub async fn ask_user(
&self,
question: &str,
options: &[AskOption],
) -> Result<AskAnswer, InteractionError> {
let call = self.interact.ask_user(question, options, &self.cancel);
self.guard(call).await
}
async fn guard<T>(
&self,
call: impl Future<Output = Result<T, InteractionError>>,
) -> Result<T, InteractionError> {
tokio::select! {
biased;
answer = call => answer,
_ = self.cancel.cancelled() => Err(InteractionError::Cancelled),
waited = async {
match self.interact_timeout {
Some(d) => {
tokio::time::sleep(d).await;
d
}
None => std::future::pending().await,
}
} => {
self.cancel.cancel();
Err(InteractionError::Timeout(format!(
"no answer within {waited:?}; the run was cancelled"
)))
}
}
}
}
#[async_trait]
pub trait ActionExecutor: Send + Sync {
fn parse(&self, turn: &LlmTurnResult) -> Result<ParseOutcome, ParseError>;
async fn execute(
&mut self,
actions: Vec<Action>,
ctx: &ExecCtx,
) -> Result<Observation, ExecError>;
}
#[async_trait]
pub trait SessionHandle: Send + Sync {
fn is_alive(&self) -> bool;
async fn rebuild(&mut self) -> Result<(), SessionError>;
}
pub const INTERRUPTED_SUMMARY: &str = "已中断/未执行";
#[async_trait]
pub trait ActionBackend: ActionExecutor + SessionHandle {
fn format(&self) -> ActionFormat;
fn render_fates(&self, actions: &[Action], fates: &[ActionOutcome]) -> Vec<ChatMessage>;
}
pub(crate) struct FailClosedInteract;
#[async_trait]
impl InteractionChannel for FailClosedInteract {
async fn request_consent(
&self,
_request: ApprovalRequest,
_cancel: &CancellationToken,
) -> Result<ApprovalDecision, InteractionError> {
Err(InteractionError::Channel(
"no interaction channel mounted on this runtime".into(),
))
}
async fn ask_user(
&self,
_question: &str,
_options: &[AskOption],
_cancel: &CancellationToken,
) -> Result<AskAnswer, InteractionError> {
Err(InteractionError::Channel(
"no interaction channel mounted on this runtime".into(),
))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::{ActionFormat, ActionOutcome, BatchStatus};
use std::sync::Mutex;
use tokio::sync::{mpsc, oneshot};
fn turn() -> LlmTurnResult {
LlmTurnResult {
full_text: String::new(),
reasoning_text: String::new(),
is_tool_call: true,
tool_calls: vec![serde_json::json!({
"id": "call_1", "name": "echo", "arguments": "{\"x\":1}"
})],
integrity: Default::default(),
usage: None,
finish_reason: Some("tool_calls".into()),
ttft_ms: 1,
llm_duration_ms: 2,
reasoning_only: false,
thinking_signature: None,
}
}
fn action(id: &str) -> Action {
Action {
id: id.into(),
name: "echo".into(),
args: serde_json::Value::String(r#"{"x":1}"#.into()),
identity: r#"echo::{"x":1}"#.into(),
format: ActionFormat::ToolCall,
}
}
struct DummyExecutor;
#[async_trait]
impl ActionExecutor for DummyExecutor {
fn parse(&self, turn: &LlmTurnResult) -> Result<ParseOutcome, ParseError> {
if turn.is_tool_call && !turn.tool_calls.is_empty() {
Ok(ParseOutcome::Actions(vec![action("call_1")]))
} else {
Ok(ParseOutcome::Empty)
}
}
async fn execute(
&mut self,
actions: Vec<Action>,
_ctx: &ExecCtx,
) -> Result<Observation, ExecError> {
if actions.is_empty() {
return Err(ExecError::NothingRan {
reason: "empty batch".into(),
});
}
Ok(Observation {
outcomes: actions
.iter()
.map(|a| ActionOutcome {
action_id: a.id.clone(),
name: a.name.clone(),
ok: true,
denied: false,
summary: "1".into(),
details: None,
})
.collect(),
events: vec![],
history_messages: vec![],
batch_status: BatchStatus::Completed,
})
}
}
struct NoopInteract;
#[async_trait]
impl InteractionChannel for NoopInteract {
async fn request_consent(
&self,
_request: ApprovalRequest,
_cancel: &CancellationToken,
) -> Result<ApprovalDecision, InteractionError> {
Ok(ApprovalDecision::AllowOnce)
}
async fn ask_user(
&self,
_question: &str,
_options: &[AskOption],
_cancel: &CancellationToken,
) -> Result<AskAnswer, InteractionError> {
Ok(AskAnswer::Picked {
id: "a".into(),
label: "ok".into(),
})
}
}
fn ctx() -> ExecCtx {
ExecCtx::new(CancellationToken::new(), Arc::new(NoopInteract))
}
fn approval_request() -> ApprovalRequest {
ApprovalRequest {
title: "t".into(),
message: "m".into(),
action_key: None,
risk_level: crate::types::RiskLevel::Safe,
raw: None,
source: None,
}
}
#[tokio::test]
async fn parse_four_states_are_distinct() {
let exec = DummyExecutor;
assert!(matches!(
exec.parse(&turn()).unwrap(),
ParseOutcome::Actions(_)
));
let mut empty_turn = turn();
empty_turn.is_tool_call = false;
empty_turn.tool_calls = vec![];
assert_eq!(exec.parse(&empty_turn).unwrap(), ParseOutcome::Empty);
assert_ne!(
std::mem::discriminant(&ParseOutcome::Incomplete),
std::mem::discriminant(&ParseOutcome::Malformed)
);
}
#[tokio::test]
async fn execute_returns_observation_when_anything_ran() {
let mut exec = DummyExecutor;
let obs = exec.execute(vec![action("call_1")], &ctx()).await.unwrap();
assert_eq!(obs.batch_status, BatchStatus::Completed);
assert_eq!(obs.outcomes.len(), 1);
assert!(obs.outcomes[0].ok);
}
#[tokio::test]
async fn execute_errors_only_when_nothing_ran() {
let mut exec = DummyExecutor;
let err = exec.execute(vec![], &ctx()).await.unwrap_err();
assert!(matches!(err, ExecError::NothingRan { .. }));
}
#[tokio::test]
async fn interaction_channel_round_trips() {
let ctx = ctx();
let decision = ctx.request_consent(approval_request()).await.unwrap();
assert_eq!(decision, ApprovalDecision::AllowOnce);
assert_eq!(
ctx.ask_user("?", &[]).await.unwrap(),
AskAnswer::Picked {
id: "a".into(),
label: "ok".into(),
}
);
}
struct ScriptedInteract {
arrived: mpsc::UnboundedSender<&'static str>,
consent: Mutex<Option<oneshot::Receiver<ApprovalDecision>>>,
ask: Mutex<Option<oneshot::Receiver<AskAnswer>>>,
}
#[async_trait]
impl InteractionChannel for ScriptedInteract {
async fn request_consent(
&self,
_request: ApprovalRequest,
_cancel: &CancellationToken,
) -> Result<ApprovalDecision, InteractionError> {
let _ = self.arrived.send("consent");
let rx = self
.consent
.lock()
.unwrap()
.take()
.expect("one consent answer per test");
rx.await
.map_err(|_| InteractionError::Channel("answer dropped".into()))
}
async fn ask_user(
&self,
_question: &str,
_options: &[AskOption],
_cancel: &CancellationToken,
) -> Result<AskAnswer, InteractionError> {
let _ = self.arrived.send("ask");
let rx = self
.ask
.lock()
.unwrap()
.take()
.expect("one ask answer per test");
rx.await
.map_err(|_| InteractionError::Channel("answer dropped".into()))
}
}
fn scripted(
consent: Option<oneshot::Receiver<ApprovalDecision>>,
ask: Option<oneshot::Receiver<AskAnswer>>,
) -> (Arc<ScriptedInteract>, mpsc::UnboundedReceiver<&'static str>) {
let (arrived_tx, arrived_rx) = mpsc::unbounded_channel();
(
Arc::new(ScriptedInteract {
arrived: arrived_tx,
consent: Mutex::new(consent),
ask: Mutex::new(ask),
}),
arrived_rx,
)
}
#[tokio::test]
async fn consent_suspends_until_the_product_answers() {
let (answer_tx, answer_rx) = oneshot::channel();
let (interact, mut arrived) = scripted(Some(answer_rx), None);
let ctx = ExecCtx::new(CancellationToken::new(), interact);
let call = tokio::spawn(async move { ctx.request_consent(approval_request()).await });
assert_eq!(
arrived.recv().await,
Some("consent"),
"the suspension is parked"
);
answer_tx.send(ApprovalDecision::AllowAlways).unwrap();
assert_eq!(call.await.unwrap().unwrap(), ApprovalDecision::AllowAlways);
}
#[tokio::test]
async fn ask_user_suspends_until_the_user_picks() {
let (answer_tx, answer_rx) = oneshot::channel();
let (interact, mut arrived) = scripted(None, Some(answer_rx));
let ctx = ExecCtx::new(CancellationToken::new(), interact);
let call = tokio::spawn(async move {
ctx.ask_user(
"which first?",
&[AskOption {
id: "a".into(),
label: "search".into(),
note: None,
}],
)
.await
});
assert_eq!(arrived.recv().await, Some("ask"));
answer_tx
.send(AskAnswer::Picked {
id: "a".into(),
label: "search".into(),
})
.unwrap();
assert_eq!(
call.await.unwrap().unwrap(),
AskAnswer::Picked {
id: "a".into(),
label: "search".into(),
}
);
}
#[tokio::test]
async fn interrupt_cancels_a_suspended_interaction() {
let (answer_tx, answer_rx) = oneshot::channel();
let (interact, mut arrived) = scripted(Some(answer_rx), None);
let token = CancellationToken::new();
let ctx = ExecCtx::new(token.clone(), interact);
let call = tokio::spawn(async move { ctx.request_consent(approval_request()).await });
assert_eq!(arrived.recv().await, Some("consent"));
token.cancel();
assert!(matches!(
call.await.unwrap(),
Err(InteractionError::Cancelled)
));
drop(answer_tx);
}
#[tokio::test]
async fn an_unanswered_interaction_fails_the_run_through_cancel() {
let (answer_tx, answer_rx) = oneshot::channel();
let (interact, mut arrived) = scripted(Some(answer_rx), None);
let token = CancellationToken::new();
let ctx = ExecCtx::new(token.clone(), interact)
.with_interact_timeout(Some(Duration::from_millis(50)));
let call = tokio::spawn(async move { ctx.request_consent(approval_request()).await });
assert_eq!(arrived.recv().await, Some("consent"));
let err = call.await.unwrap().unwrap_err();
let msg = err.to_string();
assert!(matches!(&err, InteractionError::Timeout(_)), "{msg}");
assert!(
msg.contains("no answer within 50ms"),
"timeout wording: {msg}"
);
assert!(
msg.contains("the run was cancelled"),
"timeout wording: {msg}"
);
assert!(
token.is_cancelled(),
"timeout must fire through the run's cancel token"
);
drop(answer_tx);
}
struct DeadSession;
#[async_trait]
impl SessionHandle for DeadSession {
fn is_alive(&self) -> bool {
false
}
async fn rebuild(&mut self) -> Result<(), SessionError> {
Err(SessionError::RebuildFailed("worker gone".into()))
}
}
#[tokio::test]
async fn session_handle_rebuild_failure_is_explicit() {
let mut handle = DeadSession;
assert!(!handle.is_alive());
assert!(matches!(
handle.rebuild().await,
Err(SessionError::RebuildFailed(_))
));
}
}