1use 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#[derive(Clone, Debug, PartialEq)]
36pub enum ParseOutcome {
37 Actions(Vec<Action>),
39 Empty,
41 Incomplete,
44 Malformed,
47}
48
49impl ParseOutcome {
50 pub fn has_action_intent(&self) -> bool {
53 matches!(self, ParseOutcome::Actions(_) | ParseOutcome::Incomplete)
54 }
55}
56
57#[derive(thiserror::Error, Debug)]
59pub enum ParseError {
60 #[error("turn output could not be classified: {0}")]
61 Unparseable(String),
62}
63
64#[derive(thiserror::Error, Debug)]
66pub enum ExecError {
67 #[error("batch did not run: {reason}")]
68 NothingRan { reason: String },
69}
70
71#[derive(thiserror::Error, Debug)]
73pub enum SessionError {
74 #[error("session rebuild failed: {0}")]
75 RebuildFailed(String),
76}
77
78#[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
89pub const DEFAULT_INTERACT_TIMEOUT: Duration = Duration::from_secs(600);
95
96#[async_trait]
102pub trait InteractionChannel: Send + Sync {
103 async fn request_consent(
105 &self,
106 request: ApprovalRequest,
107 cancel: &CancellationToken,
108 ) -> Result<ApprovalDecision, InteractionError>;
109
110 async fn ask_user(
113 &self,
114 question: &str,
115 options: &[AskOption],
116 cancel: &CancellationToken,
117 ) -> Result<AskAnswer, InteractionError>;
118}
119
120pub struct ExecCtx {
126 pub cancel: CancellationToken,
128 pub interact: Arc<dyn InteractionChannel>,
130 pub interact_timeout: Option<Duration>,
135}
136
137impl ExecCtx {
138 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 pub fn with_interact_timeout(mut self, interact_timeout: Option<Duration>) -> Self {
151 self.interact_timeout = interact_timeout;
152 self
153 }
154
155 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 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 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#[async_trait]
208pub trait ActionExecutor: Send + Sync {
209 fn parse(&self, turn: &LlmTurnResult) -> Result<ParseOutcome, ParseError>;
214
215 async fn execute(
219 &mut self,
220 actions: Vec<Action>,
221 ctx: &ExecCtx,
222 ) -> Result<Observation, ExecError>;
223}
224
225#[async_trait]
227pub trait SessionHandle: Send + Sync {
228 fn is_alive(&self) -> bool;
230
231 async fn rebuild(&mut self) -> Result<(), SessionError>;
234}
235
236pub const INTERRUPTED_SUMMARY: &str = "已中断/未执行";
241
242#[async_trait]
254pub trait ActionBackend: ActionExecutor + SessionHandle {
255 fn format(&self) -> ActionFormat;
258
259 fn render_fates(&self, actions: &[Action], fates: &[ActionOutcome]) -> Vec<ChatMessage>;
263}
264
265pub(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 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 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 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 #[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 #[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 #[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 #[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}