Skip to main content

agent_base/engine/
pipeline.rs

1use std::sync::Arc;
2use std::time::Duration;
3
4use async_trait::async_trait;
5use serde_json::Value;
6
7use crate::tool::{Content, Tool, ToolContext, ToolDecision, ToolPolicy, content_text};
8use crate::types::{AgentError, AgentResult, DEFAULT_TOOL_TIMEOUT_MS};
9
10/// Pure execution pipeline — cares about *how* to safely execute a tool.
11///
12/// Responsibilities: policy hooks, timeout, output size limit.
13/// Does NOT do: tool lookup, event emission, user-event forwarding.
14#[async_trait]
15pub trait ToolExecutionPipeline: Send + Sync {
16    async fn execute(
17        &self,
18        tool: &dyn Tool,
19        args: &Value,
20        ctx: &ToolContext,
21    ) -> AgentResult<Vec<Content>>;
22}
23
24/// Default pipeline: ToolPolicy hooks + timeout + output size limit.
25#[derive(Clone)]
26pub struct DefaultPipeline {
27    tool_policy: Option<Arc<dyn ToolPolicy>>,
28    default_tool_timeout_ms: u64,
29    tool_timeout_ms: Option<u64>,
30    max_output_chars: Option<usize>,
31}
32
33impl DefaultPipeline {
34    pub fn new(
35        tool_policy: Option<Arc<dyn ToolPolicy>>,
36        tool_timeout_ms: Option<u64>,
37        max_output_chars: Option<usize>,
38    ) -> Self {
39        Self {
40            tool_policy,
41            default_tool_timeout_ms: DEFAULT_TOOL_TIMEOUT_MS,
42            tool_timeout_ms,
43            max_output_chars,
44        }
45    }
46
47    pub fn with_default_timeout(mut self, timeout_ms: u64) -> Self {
48        self.default_tool_timeout_ms = timeout_ms;
49        self
50    }
51
52    pub fn policy(&self) -> Option<Arc<dyn ToolPolicy>> {
53        self.tool_policy.clone()
54    }
55}
56
57#[async_trait]
58impl ToolExecutionPipeline for DefaultPipeline {
59    async fn execute(
60        &self,
61        tool: &dyn Tool,
62        args: &Value,
63        ctx: &ToolContext,
64    ) -> AgentResult<Vec<Content>> {
65        // 1. before_call hook — may modify args or block the call entirely
66        let effective_args: std::borrow::Cow<'_, Value> = if let Some(policy) = &self.tool_policy {
67            match policy.before_call(tool.name(), args, ctx)? {
68                ToolDecision::Proceed => std::borrow::Cow::Borrowed(args),
69                ToolDecision::Block(msg) => {
70                    return Err(AgentError::ToolBlocked(msg));
71                }
72                ToolDecision::Modify(modified) => std::borrow::Cow::Owned(modified),
73            }
74        } else {
75            std::borrow::Cow::Borrowed(args)
76        };
77        let args = &*effective_args;
78
79        // 2. Execute with an **active-time** timeout: per-call → tool → global
80        // config → framework default. The budget measures active execution —
81        // stretches the tool paused while waiting on a human (see `ExecClock`,
82        // e.g. a confirmation popup) push the deadline out by exactly the
83        // paused time. Wall-clock timeouts here produce bogus `[Tool Timeout]`
84        // results while the user is still reading, with the side effects
85        // half-done. `0` is unbounded: the tool arms its own fuse (or the call
86        // is fire-and-forget), so no watchdog is needed.
87        let timeout_ms = tool
88            .call_timeout_ms(args)
89            .or(self.tool_timeout_ms)
90            .unwrap_or(self.default_tool_timeout_ms);
91        let budget = (timeout_ms > 0).then(|| Duration::from_millis(timeout_ms));
92        let started = std::time::Instant::now();
93        let call = tool.call(args, ctx);
94        tokio::pin!(call);
95        let output = loop {
96            let paused = ctx.exec_clock.paused_total();
97            let Some(deadline) = budget.and_then(|b| started.checked_add(b.saturating_add(paused)))
98            else {
99                // Unbounded budget, or an absurd one — run to completion
100                // (cancel still applies).
101                break call.as_mut().await;
102            };
103            tokio::select! {
104                result = &mut call => break result,
105                _ = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)) => {
106                    // The deadline moves while the clock is paused, and a pause
107                    // can start or end after this sleep was armed. Only a
108                    // deadline that still holds with fresh accounting is a real
109                    // overrun.
110                    let holds = budget
111                        .and_then(|b| {
112                            started.checked_add(b.saturating_add(ctx.exec_clock.paused_total()))
113                        })
114                        .is_some_and(|d| std::time::Instant::now() >= d);
115                    if !holds {
116                        continue;
117                    }
118                    tracing::warn!(
119                        tool = tool.name(),
120                        timeout_ms = timeout_ms,
121                        "tool execution timed out"
122                    );
123                    return Ok(vec![Content::text("[Tool Timeout]")]);
124                }
125            }
126        };
127        let output = output?;
128
129        // 3. Output size limit — reject by default rather than silently
130        // truncating (design §6.5). Tools that want to return a bounded
131        // subset should do their own explicit truncation before returning.
132        if let Some(max_chars) = self.max_output_chars {
133            let text_len = content_text(&output).chars().count();
134            if text_len > max_chars {
135                return Err(AgentError::ToolOutputTooLarge {
136                    name: tool.name().to_string(),
137                    max_chars,
138                });
139            }
140        }
141
142        // 4. after_call hook
143        if let Some(policy) = &self.tool_policy {
144            policy.after_call(tool.name(), args, &output, ctx)?;
145        }
146
147        Ok(output)
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154    use serde_json::json;
155
156    use crate::types::{ApprovalRequest, Language, SessionId};
157
158    // ── Test helpers ──
159
160    use tokio::sync::mpsc;
161
162    fn test_ctx() -> ToolContext {
163        let (tx, _rx) = mpsc::unbounded_channel();
164        ToolContext {
165            session_id: SessionId::new(1),
166            user_event_tx: tx,
167            llm_client: None,
168            session_store: None,
169            language: Language::En,
170            cancel_token: tokio_util::sync::CancellationToken::new(),
171            max_output_chars: None,
172            exec_clock: crate::tool::ExecClock::default(),
173            waiting_for_human: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
174            event_bus: crate::engine::EventBus::new(1),
175        }
176    }
177
178    struct EchoTool;
179    #[async_trait]
180    impl Tool for EchoTool {
181        fn name(&self) -> &'static str {
182            "echo"
183        }
184        fn description(&self) -> &'static str {
185            "echo"
186        }
187        fn schema(&self) -> Value {
188            json!({})
189        }
190        async fn call(&self, args: &Value, _ctx: &ToolContext) -> AgentResult<Vec<Content>> {
191            Ok(vec![Content::text(
192                args.get("msg").and_then(|v| v.as_str()).unwrap_or("ok"),
193            )])
194        }
195    }
196
197    struct SlowTool;
198    #[async_trait]
199    impl Tool for SlowTool {
200        fn name(&self) -> &'static str {
201            "slow"
202        }
203        fn description(&self) -> &'static str {
204            "slow"
205        }
206        fn schema(&self) -> Value {
207            json!({})
208        }
209        fn timeout_ms(&self) -> Option<u64> {
210            Some(50) // 50ms for testing
211        }
212        async fn call(&self, _args: &Value, _ctx: &ToolContext) -> AgentResult<Vec<Content>> {
213            tokio::time::sleep(Duration::from_secs(10)).await;
214            Ok(vec![Content::text("done")])
215        }
216    }
217
218    struct FailingTool;
219    #[async_trait]
220    impl Tool for FailingTool {
221        fn name(&self) -> &'static str {
222            "fail"
223        }
224        fn description(&self) -> &'static str {
225            "fail"
226        }
227        fn schema(&self) -> Value {
228            json!({})
229        }
230        async fn call(&self, _args: &Value, _ctx: &ToolContext) -> AgentResult<Vec<Content>> {
231            Err(AgentError::tool_not_found("intentional"))
232        }
233    }
234
235    struct TrackingPolicy {
236        before_count: std::sync::atomic::AtomicU32,
237        after_count: std::sync::atomic::AtomicU32,
238        fail_before: bool,
239    }
240    impl TrackingPolicy {
241        fn new() -> Self {
242            Self {
243                before_count: std::sync::atomic::AtomicU32::new(0),
244                after_count: std::sync::atomic::AtomicU32::new(0),
245                fail_before: false,
246            }
247        }
248        fn fail_before_call() -> Self {
249            Self {
250                before_count: std::sync::atomic::AtomicU32::new(0),
251                after_count: std::sync::atomic::AtomicU32::new(0),
252                fail_before: true,
253            }
254        }
255    }
256    #[async_trait]
257    impl ToolPolicy for TrackingPolicy {
258        async fn evaluate_approval(&self, _: &str, _: &Value) -> Option<ApprovalRequest> {
259            None
260        }
261        fn before_call(
262            &self,
263            _name: &str,
264            _args: &Value,
265            _ctx: &ToolContext,
266        ) -> AgentResult<ToolDecision> {
267            self.before_count
268                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
269            if self.fail_before {
270                return Err(AgentError::ToolBlocked("before_call denied".into()));
271            }
272            Ok(ToolDecision::Proceed)
273        }
274        fn after_call(
275            &self,
276            _name: &str,
277            _args: &Value,
278            _output: &[Content],
279            _ctx: &ToolContext,
280        ) -> AgentResult<()> {
281            self.after_count
282                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
283            Ok(())
284        }
285    }
286
287    // ── DefaultPipeline tests ──
288
289    #[tokio::test]
290    async fn basic_execution() {
291        let pipeline = DefaultPipeline::new(None, None, None);
292        let output = pipeline
293            .execute(&EchoTool, &json!({"msg": "hello"}), &test_ctx())
294            .await
295            .unwrap();
296        assert_eq!(content_text(&output), "hello");
297    }
298
299    #[tokio::test]
300    async fn policy_before_and_after_called() {
301        let policy = Arc::new(TrackingPolicy::new());
302        let pipeline = DefaultPipeline::new(Some(policy.clone()), None, None);
303
304        pipeline
305            .execute(&EchoTool, &json!({}), &test_ctx())
306            .await
307            .unwrap();
308
309        assert_eq!(
310            policy
311                .before_count
312                .load(std::sync::atomic::Ordering::SeqCst),
313            1
314        );
315        assert_eq!(
316            policy.after_count.load(std::sync::atomic::Ordering::SeqCst),
317            1
318        );
319    }
320
321    #[tokio::test]
322    async fn policy_before_call_aborts() {
323        let policy = Arc::new(TrackingPolicy::fail_before_call());
324        let pipeline = DefaultPipeline::new(Some(policy.clone()), None, None);
325
326        let result = pipeline.execute(&EchoTool, &json!({}), &test_ctx()).await;
327        assert!(result.is_err());
328        // after_call should NOT be called
329        assert_eq!(
330            policy.after_count.load(std::sync::atomic::Ordering::SeqCst),
331            0
332        );
333    }
334
335    #[tokio::test]
336    async fn timeout_fires() {
337        let pipeline = DefaultPipeline::new(None, Some(50), None); // 50ms timeout
338        let output = pipeline
339            .execute(&SlowTool, &json!({}), &test_ctx())
340            .await
341            .unwrap();
342        assert_eq!(content_text(&output), "[Tool Timeout]");
343    }
344
345    /// Sleeps `delay`; its budget comes from a per-call `timeout_ms` arg via
346    /// [`Tool::call_timeout_ms`], mirroring `execute_command`.
347    struct PerCallBudgetTool {
348        delay: Duration,
349    }
350    #[async_trait]
351    impl Tool for PerCallBudgetTool {
352        fn name(&self) -> &'static str {
353            "per_call_budget"
354        }
355        fn description(&self) -> &'static str {
356            "per_call_budget"
357        }
358        fn schema(&self) -> Value {
359            json!({})
360        }
361        async fn call(&self, _args: &Value, _ctx: &ToolContext) -> AgentResult<Vec<Content>> {
362            tokio::time::sleep(self.delay).await;
363            Ok(vec![Content::text("done")])
364        }
365        fn call_timeout_ms(&self, args: &Value) -> Option<u64> {
366            args.get("timeout_ms").and_then(Value::as_u64)
367        }
368    }
369
370    #[tokio::test]
371    async fn call_timeout_overrides_framework_default() {
372        // Framework default is 50ms; the per-call budget of 5s must win, or the
373        // 200ms sleep gets cut (session 20261018_7844215b: a 660s
374        // `execute_command` budget was killed at the 600s default).
375        let pipeline = DefaultPipeline::new(None, Some(50), None);
376        let output = pipeline
377            .execute(
378                &PerCallBudgetTool {
379                    delay: Duration::from_millis(200),
380                },
381                &json!({"timeout_ms": 5000}),
382                &test_ctx(),
383            )
384            .await
385            .unwrap();
386        assert_eq!(content_text(&output), "done");
387    }
388
389    #[tokio::test]
390    async fn call_timeout_zero_is_unbounded() {
391        // 0 = "never kill": no watchdog, even though the default is 50ms.
392        let pipeline = DefaultPipeline::new(None, Some(50), None);
393        let output = pipeline
394            .execute(
395                &PerCallBudgetTool {
396                    delay: Duration::from_millis(200),
397                },
398                &json!({"timeout_ms": 0}),
399                &test_ctx(),
400            )
401            .await
402            .unwrap();
403        assert_eq!(content_text(&output), "done");
404    }
405
406    #[tokio::test]
407    async fn call_timeout_absent_falls_back_to_default() {
408        // No per-call budget → the 50ms default cuts the 200ms sleep.
409        let pipeline = DefaultPipeline::new(None, Some(50), None);
410        let output = pipeline
411            .execute(
412                &PerCallBudgetTool {
413                    delay: Duration::from_millis(200),
414                },
415                &json!({}),
416                &test_ctx(),
417            )
418            .await
419            .unwrap();
420        assert_eq!(content_text(&output), "[Tool Timeout]");
421    }
422
423    /// Pauses the execution clock for a wall-clock stretch (a human wait),
424    /// then returns.
425    struct HumanWaitTool {
426        wait: Duration,
427    }
428    #[async_trait]
429    impl Tool for HumanWaitTool {
430        fn name(&self) -> &'static str {
431            "human_wait"
432        }
433        fn description(&self) -> &'static str {
434            "human_wait"
435        }
436        fn schema(&self) -> Value {
437            json!({})
438        }
439        fn timeout_ms(&self) -> Option<u64> {
440            Some(200) // 200ms of *active* time
441        }
442        async fn call(&self, _args: &Value, ctx: &ToolContext) -> AgentResult<Vec<Content>> {
443            let _paused = ctx.pause_execution_clock();
444            tokio::time::sleep(self.wait).await;
445            Ok(vec![Content::text("done")])
446        }
447    }
448
449    /// Burns `active` after an unpaused-start `lead`, with a `wait` pause in
450    /// between — models "tool works, pauses for the human, works again".
451    struct PauseThenRunTool {
452        lead: Duration,
453        wait: Duration,
454        active: Duration,
455    }
456    #[async_trait]
457    impl Tool for PauseThenRunTool {
458        fn name(&self) -> &'static str {
459            "pause_then_run"
460        }
461        fn description(&self) -> &'static str {
462            "pause_then_run"
463        }
464        fn schema(&self) -> Value {
465            json!({})
466        }
467        fn timeout_ms(&self) -> Option<u64> {
468            Some(200)
469        }
470        async fn call(&self, _args: &Value, ctx: &ToolContext) -> AgentResult<Vec<Content>> {
471            tokio::time::sleep(self.lead).await;
472            {
473                let _paused = ctx.pause_execution_clock();
474                tokio::time::sleep(self.wait).await;
475            }
476            tokio::time::sleep(self.active).await;
477            Ok(vec![Content::text("done")])
478        }
479    }
480
481    #[tokio::test]
482    async fn timeout_excludes_human_wait() {
483        // Wall clock: 600ms against a 200ms budget. Active time: ~0ms.
484        // The human wait must not count — no `[Tool Timeout]`.
485        let pipeline = DefaultPipeline::new(None, None, None);
486        let output = pipeline
487            .execute(
488                &HumanWaitTool {
489                    wait: Duration::from_millis(600),
490                },
491                &json!({}),
492                &test_ctx(),
493            )
494            .await
495            .unwrap();
496        assert_eq!(content_text(&output), "done");
497    }
498
499    #[tokio::test]
500    async fn timeout_still_counts_active_time_after_a_pause() {
501        // 30ms active + 400ms paused + 900ms active: the second active stretch
502        // blows the 200ms budget and must time out even though the pause was
503        // longer than everything else.
504        let pipeline = DefaultPipeline::new(None, None, None);
505        let output = pipeline
506            .execute(
507                &PauseThenRunTool {
508                    lead: Duration::from_millis(30),
509                    wait: Duration::from_millis(400),
510                    active: Duration::from_millis(900),
511                },
512                &json!({}),
513                &test_ctx(),
514            )
515            .await
516            .unwrap();
517        assert_eq!(content_text(&output), "[Tool Timeout]");
518    }
519
520    #[tokio::test]
521    async fn pause_mid_call_keeps_the_rest_of_the_budget() {
522        // 30ms active before the pause, 50ms after — both inside the 200ms
523        // budget once the 400ms human wait is excluded.
524        let pipeline = DefaultPipeline::new(None, None, None);
525        let output = pipeline
526            .execute(
527                &PauseThenRunTool {
528                    lead: Duration::from_millis(30),
529                    wait: Duration::from_millis(400),
530                    active: Duration::from_millis(50),
531                },
532                &json!({}),
533                &test_ctx(),
534            )
535            .await
536            .unwrap();
537        assert_eq!(content_text(&output), "done");
538    }
539
540    #[tokio::test]
541    async fn no_timeout_when_tool_fast() {
542        let pipeline = DefaultPipeline::new(None, Some(5000), None);
543        let output = pipeline
544            .execute(&EchoTool, &json!({"msg": "fast"}), &test_ctx())
545            .await
546            .unwrap();
547        assert_eq!(content_text(&output), "fast");
548    }
549
550    #[tokio::test]
551    async fn output_over_limit_is_rejected() {
552        let pipeline = DefaultPipeline::new(None, None, Some(10)); // max 10 chars
553        let result = pipeline
554            .execute(
555                &EchoTool,
556                &json!({"msg": "this is a very long message"}),
557                &test_ctx(),
558            )
559            .await;
560        assert!(matches!(
561            result,
562            Err(AgentError::ToolOutputTooLarge { max_chars: 10, .. })
563        ));
564    }
565
566    #[tokio::test]
567    async fn no_rejection_when_short() {
568        let pipeline = DefaultPipeline::new(None, None, Some(100));
569        let output = pipeline
570            .execute(&EchoTool, &json!({"msg": "short"}), &test_ctx())
571            .await
572            .unwrap();
573        assert_eq!(content_text(&output), "short");
574    }
575
576    #[tokio::test]
577    async fn output_over_limit_cjk_rejected() {
578        // CJK chars are 3 bytes each. The size check counts chars, not bytes,
579        // so a long Chinese string must still be rejected without panicking.
580        let pipeline = DefaultPipeline::new(None, None, Some(20));
581        let result = pipeline
582            .execute(
583                &EchoTool,
584                &json!({"msg": "这是一个很长的中文消息,用于测试多字节字符的超限处理"}),
585                &test_ctx(),
586            )
587            .await;
588        assert!(matches!(
589            result,
590            Err(AgentError::ToolOutputTooLarge { max_chars: 20, .. })
591        ));
592    }
593
594    #[tokio::test]
595    async fn cjk_within_char_limit_is_not_rejected() {
596        // 17 CJK chars = 51 bytes. With a 20-char limit, byte-counting would
597        // wrongly reject (51 > 20), but char-counting must accept (17 <= 20).
598        let pipeline = DefaultPipeline::new(None, None, Some(20));
599        let output = pipeline
600            .execute(
601                &EchoTool,
602                &json!({"msg": "这是一个用于验证字符计数的中文消息"}),
603                &test_ctx(),
604            )
605            .await
606            .unwrap();
607        assert_eq!(content_text(&output).chars().count(), 17);
608    }
609
610    #[tokio::test]
611    async fn timeout_plus_limit() {
612        let pipeline = DefaultPipeline::new(None, Some(50), Some(100));
613        let output = pipeline
614            .execute(&SlowTool, &json!({}), &test_ctx())
615            .await
616            .unwrap();
617        // timeout output is short, so it does not trip the size limit
618        assert_eq!(content_text(&output), "[Tool Timeout]");
619    }
620
621    #[tokio::test]
622    async fn tool_error_propagates() {
623        let pipeline = DefaultPipeline::new(None, None, None);
624        let result = pipeline
625            .execute(&FailingTool, &json!({}), &test_ctx())
626            .await;
627        assert!(result.is_err());
628    }
629
630    // ── ToolDecision tests ──
631
632    struct ModifyPolicy;
633    #[async_trait]
634    impl ToolPolicy for ModifyPolicy {
635        async fn evaluate_approval(&self, _: &str, _: &Value) -> Option<ApprovalRequest> {
636            None
637        }
638        fn before_call(
639            &self,
640            _name: &str,
641            _args: &Value,
642            _ctx: &ToolContext,
643        ) -> AgentResult<ToolDecision> {
644            // Replace the msg argument with "modified"
645            Ok(ToolDecision::Modify(json!({"msg": "modified"})))
646        }
647    }
648
649    struct BlockPolicy;
650    #[async_trait]
651    impl ToolPolicy for BlockPolicy {
652        async fn evaluate_approval(&self, _: &str, _: &Value) -> Option<ApprovalRequest> {
653            None
654        }
655        fn before_call(
656            &self,
657            name: &str,
658            _args: &Value,
659            _ctx: &ToolContext,
660        ) -> AgentResult<ToolDecision> {
661            Ok(ToolDecision::Block(format!("{name} is blocked")))
662        }
663    }
664
665    #[tokio::test]
666    async fn modify_decision_replaces_args() {
667        let pipeline = DefaultPipeline::new(Some(Arc::new(ModifyPolicy)), None, None);
668        let output = pipeline
669            .execute(&EchoTool, &json!({"msg": "original"}), &test_ctx())
670            .await
671            .unwrap();
672        // The policy replaced args with {"msg": "modified"}
673        assert_eq!(content_text(&output), "modified");
674    }
675
676    #[tokio::test]
677    async fn block_decision_returns_error() {
678        let pipeline = DefaultPipeline::new(Some(Arc::new(BlockPolicy)), None, None);
679        let result = pipeline
680            .execute(&EchoTool, &json!({"msg": "hello"}), &test_ctx())
681            .await;
682        assert!(result.is_err());
683        let err = result.unwrap_err();
684        assert!(
685            err.to_string().contains("is blocked"),
686            "expected block message, got: {err}"
687        );
688    }
689}