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 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 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 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 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 #[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 #[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 #[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 #[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}