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#[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#[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 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 let timeout_ms = tool
86 .timeout_ms()
87 .or(self.tool_timeout_ms)
88 .unwrap_or(self.default_tool_timeout_ms);
89 let budget = Duration::from_millis(timeout_ms);
90 let started = std::time::Instant::now();
91 let call = tool.call(args, ctx);
92 tokio::pin!(call);
93 let output = loop {
94 let paused = ctx.exec_clock.paused_total();
95 let Some(deadline) = started.checked_add(budget.saturating_add(paused)) else {
96 break call.as_mut().await;
98 };
99 tokio::select! {
100 result = &mut call => break result,
101 _ = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)) => {
102 let holds = started
107 .checked_add(budget.saturating_add(ctx.exec_clock.paused_total()))
108 .is_some_and(|d| std::time::Instant::now() >= d);
109 if !holds {
110 continue;
111 }
112 tracing::warn!(
113 tool = tool.name(),
114 timeout_ms = timeout_ms,
115 "tool execution timed out"
116 );
117 return Ok(vec![Content::text("[Tool Timeout]")]);
118 }
119 }
120 };
121 let output = output?;
122
123 if let Some(max_chars) = self.max_output_chars {
127 let text_len = content_text(&output).chars().count();
128 if text_len > max_chars {
129 return Err(AgentError::ToolOutputTooLarge {
130 name: tool.name().to_string(),
131 max_chars,
132 });
133 }
134 }
135
136 if let Some(policy) = &self.tool_policy {
138 policy.after_call(tool.name(), args, &output, ctx)?;
139 }
140
141 Ok(output)
142 }
143}
144
145#[cfg(test)]
146mod tests {
147 use super::*;
148 use serde_json::json;
149
150 use crate::types::{ApprovalRequest, Language, SessionId};
151
152 use tokio::sync::mpsc;
155
156 fn test_ctx() -> ToolContext {
157 let (tx, _rx) = mpsc::unbounded_channel();
158 ToolContext {
159 session_id: SessionId::new(1),
160 user_event_tx: tx,
161 llm_client: None,
162 session_store: None,
163 language: Language::En,
164 cancel_token: tokio_util::sync::CancellationToken::new(),
165 max_output_chars: None,
166 exec_clock: crate::tool::ExecClock::default(),
167 event_bus: crate::engine::EventBus::new(1),
168 }
169 }
170
171 struct EchoTool;
172 #[async_trait]
173 impl Tool for EchoTool {
174 fn name(&self) -> &'static str {
175 "echo"
176 }
177 fn description(&self) -> &'static str {
178 "echo"
179 }
180 fn schema(&self) -> Value {
181 json!({})
182 }
183 async fn call(&self, args: &Value, _ctx: &ToolContext) -> AgentResult<Vec<Content>> {
184 Ok(vec![Content::text(
185 args.get("msg").and_then(|v| v.as_str()).unwrap_or("ok"),
186 )])
187 }
188 }
189
190 struct SlowTool;
191 #[async_trait]
192 impl Tool for SlowTool {
193 fn name(&self) -> &'static str {
194 "slow"
195 }
196 fn description(&self) -> &'static str {
197 "slow"
198 }
199 fn schema(&self) -> Value {
200 json!({})
201 }
202 fn timeout_ms(&self) -> Option<u64> {
203 Some(50) }
205 async fn call(&self, _args: &Value, _ctx: &ToolContext) -> AgentResult<Vec<Content>> {
206 tokio::time::sleep(Duration::from_secs(10)).await;
207 Ok(vec![Content::text("done")])
208 }
209 }
210
211 struct FailingTool;
212 #[async_trait]
213 impl Tool for FailingTool {
214 fn name(&self) -> &'static str {
215 "fail"
216 }
217 fn description(&self) -> &'static str {
218 "fail"
219 }
220 fn schema(&self) -> Value {
221 json!({})
222 }
223 async fn call(&self, _args: &Value, _ctx: &ToolContext) -> AgentResult<Vec<Content>> {
224 Err(AgentError::tool_not_found("intentional"))
225 }
226 }
227
228 struct TrackingPolicy {
229 before_count: std::sync::atomic::AtomicU32,
230 after_count: std::sync::atomic::AtomicU32,
231 fail_before: bool,
232 }
233 impl TrackingPolicy {
234 fn new() -> Self {
235 Self {
236 before_count: std::sync::atomic::AtomicU32::new(0),
237 after_count: std::sync::atomic::AtomicU32::new(0),
238 fail_before: false,
239 }
240 }
241 fn fail_before_call() -> Self {
242 Self {
243 before_count: std::sync::atomic::AtomicU32::new(0),
244 after_count: std::sync::atomic::AtomicU32::new(0),
245 fail_before: true,
246 }
247 }
248 }
249 #[async_trait]
250 impl ToolPolicy for TrackingPolicy {
251 async fn evaluate_approval(&self, _: &str, _: &Value) -> Option<ApprovalRequest> {
252 None
253 }
254 fn before_call(
255 &self,
256 _name: &str,
257 _args: &Value,
258 _ctx: &ToolContext,
259 ) -> AgentResult<ToolDecision> {
260 self.before_count
261 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
262 if self.fail_before {
263 return Err(AgentError::ToolBlocked("before_call denied".into()));
264 }
265 Ok(ToolDecision::Proceed)
266 }
267 fn after_call(
268 &self,
269 _name: &str,
270 _args: &Value,
271 _output: &[Content],
272 _ctx: &ToolContext,
273 ) -> AgentResult<()> {
274 self.after_count
275 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
276 Ok(())
277 }
278 }
279
280 #[tokio::test]
283 async fn basic_execution() {
284 let pipeline = DefaultPipeline::new(None, None, None);
285 let output = pipeline
286 .execute(&EchoTool, &json!({"msg": "hello"}), &test_ctx())
287 .await
288 .unwrap();
289 assert_eq!(content_text(&output), "hello");
290 }
291
292 #[tokio::test]
293 async fn policy_before_and_after_called() {
294 let policy = Arc::new(TrackingPolicy::new());
295 let pipeline = DefaultPipeline::new(Some(policy.clone()), None, None);
296
297 pipeline
298 .execute(&EchoTool, &json!({}), &test_ctx())
299 .await
300 .unwrap();
301
302 assert_eq!(
303 policy
304 .before_count
305 .load(std::sync::atomic::Ordering::SeqCst),
306 1
307 );
308 assert_eq!(
309 policy.after_count.load(std::sync::atomic::Ordering::SeqCst),
310 1
311 );
312 }
313
314 #[tokio::test]
315 async fn policy_before_call_aborts() {
316 let policy = Arc::new(TrackingPolicy::fail_before_call());
317 let pipeline = DefaultPipeline::new(Some(policy.clone()), None, None);
318
319 let result = pipeline.execute(&EchoTool, &json!({}), &test_ctx()).await;
320 assert!(result.is_err());
321 assert_eq!(
323 policy.after_count.load(std::sync::atomic::Ordering::SeqCst),
324 0
325 );
326 }
327
328 #[tokio::test]
329 async fn timeout_fires() {
330 let pipeline = DefaultPipeline::new(None, Some(50), None); let output = pipeline
332 .execute(&SlowTool, &json!({}), &test_ctx())
333 .await
334 .unwrap();
335 assert_eq!(content_text(&output), "[Tool Timeout]");
336 }
337
338 struct HumanWaitTool {
341 wait: Duration,
342 }
343 #[async_trait]
344 impl Tool for HumanWaitTool {
345 fn name(&self) -> &'static str {
346 "human_wait"
347 }
348 fn description(&self) -> &'static str {
349 "human_wait"
350 }
351 fn schema(&self) -> Value {
352 json!({})
353 }
354 fn timeout_ms(&self) -> Option<u64> {
355 Some(200) }
357 async fn call(&self, _args: &Value, ctx: &ToolContext) -> AgentResult<Vec<Content>> {
358 let _paused = ctx.pause_execution_clock();
359 tokio::time::sleep(self.wait).await;
360 Ok(vec![Content::text("done")])
361 }
362 }
363
364 struct PauseThenRunTool {
367 lead: Duration,
368 wait: Duration,
369 active: Duration,
370 }
371 #[async_trait]
372 impl Tool for PauseThenRunTool {
373 fn name(&self) -> &'static str {
374 "pause_then_run"
375 }
376 fn description(&self) -> &'static str {
377 "pause_then_run"
378 }
379 fn schema(&self) -> Value {
380 json!({})
381 }
382 fn timeout_ms(&self) -> Option<u64> {
383 Some(200)
384 }
385 async fn call(&self, _args: &Value, ctx: &ToolContext) -> AgentResult<Vec<Content>> {
386 tokio::time::sleep(self.lead).await;
387 {
388 let _paused = ctx.pause_execution_clock();
389 tokio::time::sleep(self.wait).await;
390 }
391 tokio::time::sleep(self.active).await;
392 Ok(vec![Content::text("done")])
393 }
394 }
395
396 #[tokio::test]
397 async fn timeout_excludes_human_wait() {
398 let pipeline = DefaultPipeline::new(None, None, None);
401 let output = pipeline
402 .execute(
403 &HumanWaitTool {
404 wait: Duration::from_millis(600),
405 },
406 &json!({}),
407 &test_ctx(),
408 )
409 .await
410 .unwrap();
411 assert_eq!(content_text(&output), "done");
412 }
413
414 #[tokio::test]
415 async fn timeout_still_counts_active_time_after_a_pause() {
416 let pipeline = DefaultPipeline::new(None, None, None);
420 let output = pipeline
421 .execute(
422 &PauseThenRunTool {
423 lead: Duration::from_millis(30),
424 wait: Duration::from_millis(400),
425 active: Duration::from_millis(900),
426 },
427 &json!({}),
428 &test_ctx(),
429 )
430 .await
431 .unwrap();
432 assert_eq!(content_text(&output), "[Tool Timeout]");
433 }
434
435 #[tokio::test]
436 async fn pause_mid_call_keeps_the_rest_of_the_budget() {
437 let pipeline = DefaultPipeline::new(None, None, None);
440 let output = pipeline
441 .execute(
442 &PauseThenRunTool {
443 lead: Duration::from_millis(30),
444 wait: Duration::from_millis(400),
445 active: Duration::from_millis(50),
446 },
447 &json!({}),
448 &test_ctx(),
449 )
450 .await
451 .unwrap();
452 assert_eq!(content_text(&output), "done");
453 }
454
455 #[tokio::test]
456 async fn no_timeout_when_tool_fast() {
457 let pipeline = DefaultPipeline::new(None, Some(5000), None);
458 let output = pipeline
459 .execute(&EchoTool, &json!({"msg": "fast"}), &test_ctx())
460 .await
461 .unwrap();
462 assert_eq!(content_text(&output), "fast");
463 }
464
465 #[tokio::test]
466 async fn output_over_limit_is_rejected() {
467 let pipeline = DefaultPipeline::new(None, None, Some(10)); let result = pipeline
469 .execute(
470 &EchoTool,
471 &json!({"msg": "this is a very long message"}),
472 &test_ctx(),
473 )
474 .await;
475 assert!(matches!(
476 result,
477 Err(AgentError::ToolOutputTooLarge { max_chars: 10, .. })
478 ));
479 }
480
481 #[tokio::test]
482 async fn no_rejection_when_short() {
483 let pipeline = DefaultPipeline::new(None, None, Some(100));
484 let output = pipeline
485 .execute(&EchoTool, &json!({"msg": "short"}), &test_ctx())
486 .await
487 .unwrap();
488 assert_eq!(content_text(&output), "short");
489 }
490
491 #[tokio::test]
492 async fn output_over_limit_cjk_rejected() {
493 let pipeline = DefaultPipeline::new(None, None, Some(20));
496 let result = pipeline
497 .execute(
498 &EchoTool,
499 &json!({"msg": "这是一个很长的中文消息,用于测试多字节字符的超限处理"}),
500 &test_ctx(),
501 )
502 .await;
503 assert!(matches!(
504 result,
505 Err(AgentError::ToolOutputTooLarge { max_chars: 20, .. })
506 ));
507 }
508
509 #[tokio::test]
510 async fn cjk_within_char_limit_is_not_rejected() {
511 let pipeline = DefaultPipeline::new(None, None, Some(20));
514 let output = pipeline
515 .execute(
516 &EchoTool,
517 &json!({"msg": "这是一个用于验证字符计数的中文消息"}),
518 &test_ctx(),
519 )
520 .await
521 .unwrap();
522 assert_eq!(content_text(&output).chars().count(), 17);
523 }
524
525 #[tokio::test]
526 async fn timeout_plus_limit() {
527 let pipeline = DefaultPipeline::new(None, Some(50), Some(100));
528 let output = pipeline
529 .execute(&SlowTool, &json!({}), &test_ctx())
530 .await
531 .unwrap();
532 assert_eq!(content_text(&output), "[Tool Timeout]");
534 }
535
536 #[tokio::test]
537 async fn tool_error_propagates() {
538 let pipeline = DefaultPipeline::new(None, None, None);
539 let result = pipeline
540 .execute(&FailingTool, &json!({}), &test_ctx())
541 .await;
542 assert!(result.is_err());
543 }
544
545 struct ModifyPolicy;
548 #[async_trait]
549 impl ToolPolicy for ModifyPolicy {
550 async fn evaluate_approval(&self, _: &str, _: &Value) -> Option<ApprovalRequest> {
551 None
552 }
553 fn before_call(
554 &self,
555 _name: &str,
556 _args: &Value,
557 _ctx: &ToolContext,
558 ) -> AgentResult<ToolDecision> {
559 Ok(ToolDecision::Modify(json!({"msg": "modified"})))
561 }
562 }
563
564 struct BlockPolicy;
565 #[async_trait]
566 impl ToolPolicy for BlockPolicy {
567 async fn evaluate_approval(&self, _: &str, _: &Value) -> Option<ApprovalRequest> {
568 None
569 }
570 fn before_call(
571 &self,
572 name: &str,
573 _args: &Value,
574 _ctx: &ToolContext,
575 ) -> AgentResult<ToolDecision> {
576 Ok(ToolDecision::Block(format!("{name} is blocked")))
577 }
578 }
579
580 #[tokio::test]
581 async fn modify_decision_replaces_args() {
582 let pipeline = DefaultPipeline::new(Some(Arc::new(ModifyPolicy)), None, None);
583 let output = pipeline
584 .execute(&EchoTool, &json!({"msg": "original"}), &test_ctx())
585 .await
586 .unwrap();
587 assert_eq!(content_text(&output), "modified");
589 }
590
591 #[tokio::test]
592 async fn block_decision_returns_error() {
593 let pipeline = DefaultPipeline::new(Some(Arc::new(BlockPolicy)), None, None);
594 let result = pipeline
595 .execute(&EchoTool, &json!({"msg": "hello"}), &test_ctx())
596 .await;
597 assert!(result.is_err());
598 let err = result.unwrap_err();
599 assert!(
600 err.to_string().contains("is blocked"),
601 "expected block message, got: {err}"
602 );
603 }
604}