1use std::fmt;
4use std::sync::atomic::{AtomicUsize, Ordering};
5use std::sync::{Arc, Mutex, PoisonError};
6
7use futures::future::BoxFuture;
8
9use super::invocation_context::InvocationContext;
10use super::invocation_state::InvocationState;
11use crate::cancel::{CancelHandle, CancelOptions, CancelSignal};
12use crate::context_manager::ContextManager;
13use crate::interrupt::{Interrupt, InterruptError, InterruptSource, InterruptState};
14use crate::interventions::InterventionHandler;
15use crate::models::Model;
16use crate::sandbox::{Sandbox, default_sandbox};
17use crate::state_store::StateStore;
18use crate::telemetry::Tracer;
19use crate::tools::{Tool, ToolContext, ToolOutcome, ToolRegistry};
20use crate::types::{InterruptParams, JsonValue, Message, ToolResultBlock, ToolResultContent, ToolUse};
21
22pub(crate) trait ToolPipeline: Send + Sync {
25 fn call_tool(
28 &self,
29 agent: ToolAgent,
30 tool_use: ToolUse,
31 ) -> BoxFuture<'static, Result<ToolResultBlock, InterruptError>>;
32
33 fn call_tool_refusing(
36 &self,
37 agent: ToolAgent,
38 tool_use: ToolUse,
39 refusal: Refusal,
40 ) -> BoxFuture<'static, Result<ToolResultBlock, RefusedCall>>;
41}
42
43pub(crate) type Refusal = Box<dyn FnOnce(&InterruptError) -> String + Send>;
45
46#[derive(Debug, Clone, PartialEq, thiserror::Error)]
49#[error("{interrupts}")]
50#[non_exhaustive]
51pub struct RefusedCall {
52 pub interrupts: InterruptError,
54 pub result: Option<ToolResultBlock>,
58}
59
60impl RefusedCall {
61 pub(crate) fn new(interrupts: InterruptError, result: Option<ToolResultBlock>) -> Self {
62 Self { interrupts, result }
63 }
64}
65
66#[derive(Default)]
69struct CallScope {
70 tool_use_id: String,
71 next_call: AtomicUsize,
72 interrupts: Mutex<Vec<Interrupt>>,
73}
74
75#[derive(Clone, Default)]
78pub(crate) struct ChildInheritance {
79 pub(crate) context_manager: Option<ContextManager>,
81 pub(crate) interventions: Arc<[Arc<dyn InterventionHandler>]>,
83 pub(crate) tracer: Option<Arc<Tracer>>,
85}
86
87#[derive(Clone)]
93#[non_exhaustive]
94pub struct ToolAgent {
95 id: String,
96 name: Option<String>,
97 session_id: String,
98 app_state: StateStore,
99 model_state: StateStore,
100 model: Arc<dyn Model>,
101 aux_model: Option<Arc<dyn Model>>,
102 cancel_handle: CancelHandle,
103 cancel_signal: CancelSignal,
104 messages: Arc<[Message]>,
105 tool_registry: Arc<ToolRegistry>,
106 invocation_context: Option<InvocationContext>,
107 interrupt_state: InterruptState,
108 pipeline: Option<Arc<dyn ToolPipeline>>,
109 call_scope: Option<Arc<CallScope>>,
110 sandbox: Arc<dyn Sandbox>,
111 printer: bool,
112 inheritance: ChildInheritance,
113}
114
115impl ToolAgent {
116 pub(crate) fn new(id: impl Into<String>, session_id: impl Into<String>, model: Arc<dyn Model>) -> Self {
118 let cancel_handle = CancelHandle::new();
119 Self {
120 id: id.into(),
121 name: None,
122 session_id: session_id.into(),
123 app_state: StateStore::new(),
124 model_state: StateStore::new(),
125 model,
126 aux_model: None,
127 cancel_signal: cancel_handle.signal(),
128 cancel_handle,
129 messages: Arc::from(Vec::new()),
130 tool_registry: Arc::new(ToolRegistry::new()),
131 invocation_context: None,
132 interrupt_state: InterruptState::new(),
133 pipeline: None,
134 call_scope: None,
135 sandbox: default_sandbox().clone(),
136 printer: false,
137 inheritance: ChildInheritance::default(),
138 }
139 }
140
141 pub(crate) fn with_name(mut self, name: Option<String>) -> Self {
142 self.name = name;
143 self
144 }
145
146 pub(crate) fn with_state(mut self, app_state: StateStore, model_state: StateStore) -> Self {
147 self.app_state = app_state;
148 self.model_state = model_state;
149 self
150 }
151
152 pub(crate) fn with_aux_model(mut self, aux_model: Option<Arc<dyn Model>>) -> Self {
153 self.aux_model = aux_model;
154 self
155 }
156
157 pub(crate) fn with_cancel_handle(mut self, cancel_handle: CancelHandle) -> Self {
158 self.cancel_signal = cancel_handle.signal();
159 self.cancel_handle = cancel_handle;
160 self
161 }
162
163 pub(crate) fn with_cancel_signal(mut self, cancel_signal: CancelSignal) -> Self {
164 self.cancel_signal = cancel_signal;
165 self
166 }
167
168 pub(crate) fn with_messages(mut self, messages: Arc<[Message]>) -> Self {
169 self.messages = messages;
170 self
171 }
172
173 pub(crate) fn with_tool_registry(mut self, tool_registry: Arc<ToolRegistry>) -> Self {
174 self.tool_registry = tool_registry;
175 self
176 }
177
178 pub(crate) fn with_invocation_context(mut self, invocation_context: Option<InvocationContext>) -> Self {
179 self.invocation_context = invocation_context;
180 self
181 }
182
183 pub(crate) fn with_interrupt_state(mut self, interrupt_state: InterruptState) -> Self {
184 self.interrupt_state = interrupt_state;
185 self
186 }
187
188 pub(crate) fn with_pipeline(mut self, pipeline: Arc<dyn ToolPipeline>) -> Self {
189 self.pipeline = Some(pipeline);
190 self
191 }
192
193 pub(crate) fn for_tool_call(&self, tool_use_id: &str) -> Self {
196 let mut view = self.clone();
197 view.call_scope = Some(Arc::new(CallScope {
198 tool_use_id: tool_use_id.to_owned(),
199 ..CallScope::default()
200 }));
201 view
202 }
203
204 pub(crate) fn take_inner_interrupts(&self) -> Vec<Interrupt> {
206 let Some(scope) = &self.call_scope else {
207 return Vec::new();
208 };
209 std::mem::take(&mut *scope.interrupts.lock().unwrap_or_else(PoisonError::into_inner))
210 }
211
212 fn record_inner_interrupts(&self, error: &InterruptError) {
213 let Some(scope) = &self.call_scope else {
214 return;
215 };
216 let mut recorded = scope.interrupts.lock().unwrap_or_else(PoisonError::into_inner);
217 for interrupt in &error.interrupts {
218 if !recorded.iter().any(|known| known.id == interrupt.id) {
219 recorded.push(interrupt.clone());
220 }
221 }
222 }
223
224 fn next_call_id(&self) -> String {
228 match &self.call_scope {
229 Some(scope) => {
230 let n = scope.next_call.fetch_add(1, Ordering::SeqCst);
231 format!("{}:call:{n}", scope.tool_use_id)
232 }
233 None => format!("tooluse_{}", uuid::Uuid::new_v4()),
234 }
235 }
236
237 pub(crate) fn with_sandbox(mut self, sandbox: Arc<dyn Sandbox>) -> Self {
238 self.sandbox = sandbox;
239 self
240 }
241
242 pub(crate) fn with_printer(mut self, printer: bool) -> Self {
243 self.printer = printer;
244 self
245 }
246
247 pub(crate) fn with_inheritance(mut self, inheritance: ChildInheritance) -> Self {
248 self.inheritance = inheritance;
249 self
250 }
251
252 pub(crate) fn inheritance(&self) -> &ChildInheritance {
254 &self.inheritance
255 }
256
257 pub(crate) fn printer(&self) -> bool {
259 self.printer
260 }
261
262 pub(crate) fn interrupt_state(&self) -> &InterruptState {
263 &self.interrupt_state
264 }
265
266 #[must_use]
268 pub fn id(&self) -> &str {
269 &self.id
270 }
271
272 #[must_use]
274 pub fn name(&self) -> &str {
275 self.name.as_deref().unwrap_or(super::agent::DEFAULT_AGENT_NAME)
276 }
277
278 #[must_use]
280 pub fn session_id(&self) -> &str {
281 &self.session_id
282 }
283
284 #[must_use]
286 pub fn app_state(&self) -> &StateStore {
287 &self.app_state
288 }
289
290 #[must_use]
292 pub fn model_state(&self) -> &StateStore {
293 &self.model_state
294 }
295
296 #[must_use]
298 pub fn model(&self) -> &Arc<dyn Model> {
299 &self.model
300 }
301
302 #[must_use]
304 pub fn sandbox(&self) -> &Arc<dyn Sandbox> {
305 &self.sandbox
306 }
307
308 #[must_use]
310 pub fn aux_model(&self) -> &Arc<dyn Model> {
311 self.aux_model.as_ref().unwrap_or(&self.model)
312 }
313
314 #[must_use]
316 pub fn cancel_signal(&self) -> CancelSignal {
317 self.cancel_signal.clone()
318 }
319
320 pub fn cancel(&self, options: CancelOptions) {
323 self.cancel_handle.cancel(options);
324 }
325
326 #[must_use]
328 pub fn messages(&self) -> &[Message] {
329 &self.messages
330 }
331
332 #[must_use]
334 pub fn tool_registry(&self) -> &ToolRegistry {
335 &self.tool_registry
336 }
337
338 #[must_use]
340 pub fn invocation_context(&self) -> Option<&InvocationContext> {
341 self.invocation_context.as_ref()
342 }
343
344 pub async fn call_tool(&self, name: &str, input: JsonValue) -> Result<ToolResultBlock, InterruptError> {
359 let tool_use = ToolUse::new(name, self.next_call_id(), input);
360 let outcome = match &self.pipeline {
361 Some(pipeline) => pipeline.call_tool(self.clone(), tool_use).await,
362 None => self.run_directly(tool_use).await,
363 };
364 outcome.inspect_err(|error| self.record_inner_interrupts(error))
365 }
366
367 pub async fn call_tool_without_interrupts(
414 &self,
415 name: &str,
416 input: JsonValue,
417 refusal: impl FnOnce(&InterruptError) -> String + Send + 'static,
418 ) -> Result<ToolResultBlock, RefusedCall> {
419 let tool_use = ToolUse::new(name, self.next_call_id(), input);
420 let mut detached = self.clone();
421 detached.interrupt_state = InterruptState::new();
422 match &self.pipeline {
423 Some(pipeline) => pipeline.call_tool_refusing(detached, tool_use, Box::new(refusal)).await,
424 None => detached
425 .run_directly(tool_use)
426 .await
427 .map_err(|interrupts| RefusedCall::new(interrupts, None)),
428 }
429 }
430
431 async fn run_directly(&self, tool_use: ToolUse) -> Result<ToolResultBlock, InterruptError> {
432 let Some(tool) = self.tool_registry.get(&tool_use.name).cloned() else {
433 return Ok(not_found_result(&tool_use));
434 };
435 let agent = self.for_tool_call(&tool_use.tool_use_id);
436 let context = ToolContext::new(tool_use.clone(), agent.clone(), InvocationState::new());
437 let outcome = run_tool(tool.as_ref(), context).await;
438 let inner = agent.take_inner_interrupts();
439 match outcome {
440 Some(ToolOutcome::Interrupt(interrupts)) => Err(interrupts),
441 _ if !inner.is_empty() => Err(InterruptError::new(inner)),
442 Some(ToolOutcome::Result(result)) => Ok(result),
443 None => Ok(no_result(&tool_use)),
444 }
445 }
446
447 pub(crate) fn raise_interrupt(&self, id: &str, params: &InterruptParams) -> Result<JsonValue, InterruptError> {
449 self.interrupt_state.raise(id, params, InterruptSource::Hook)
450 }
451}
452
453pub(crate) async fn run_tool(tool: &dyn Tool, context: ToolContext) -> Option<ToolOutcome> {
455 tool.stream(context).run(|_| {}).await
456}
457
458pub(crate) fn not_found_result(tool_use: &ToolUse) -> ToolResultBlock {
460 ToolResultBlock::error(
461 tool_use.tool_use_id.clone(),
462 vec![ToolResultContent::text(format!(
463 "Tool '{}' not found in registry",
464 tool_use.name
465 ))],
466 )
467}
468
469pub(crate) fn no_result(tool_use: &ToolUse) -> ToolResultBlock {
471 ToolResultBlock::error(
472 tool_use.tool_use_id.clone(),
473 vec![ToolResultContent::text(format!(
474 "Tool '{}' did not return a result",
475 tool_use.name
476 ))],
477 )
478}
479
480impl fmt::Debug for ToolAgent {
481 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
482 f.debug_struct("ToolAgent")
483 .field("id", &self.id)
484 .field("name", &self.name)
485 .field("messages", &self.messages.len())
486 .field("tool_registry", &self.tool_registry)
487 .finish_non_exhaustive()
488 }
489}
490
491#[cfg(test)]
492mod tests {
493 use serde_json::json;
494
495 use super::*;
496 use crate::test_support::MockTool;
497 use crate::testing::MockModel;
498 use crate::types::ToolResultStatus;
499
500 struct StubPipeline;
501
502 impl ToolPipeline for StubPipeline {
503 fn call_tool(
504 &self,
505 agent: ToolAgent,
506 tool_use: ToolUse,
507 ) -> BoxFuture<'static, Result<ToolResultBlock, InterruptError>> {
508 Box::pin(async move {
509 Ok(ToolResultBlock::success(
510 tool_use.tool_use_id,
511 vec![ToolResultContent::text(format!("{}:{}", agent.id(), tool_use.name))],
512 ))
513 })
514 }
515
516 fn call_tool_refusing(
517 &self,
518 agent: ToolAgent,
519 tool_use: ToolUse,
520 _refusal: Refusal,
521 ) -> BoxFuture<'static, Result<ToolResultBlock, RefusedCall>> {
522 let call = self.call_tool(agent, tool_use);
523 Box::pin(async move { call.await.map_err(|interrupts| RefusedCall::new(interrupts, None)) })
524 }
525 }
526
527 fn agent() -> ToolAgent {
528 let registry = ToolRegistry::with_tools(MockTool::new("echo").with_result(|context| {
529 ToolResultBlock::success(
530 context.tool_use().tool_use_id.clone(),
531 vec![ToolResultContent::json(context.tool_use().input.clone())],
532 )
533 .into()
534 }))
535 .unwrap();
536 ToolAgent::new("agent-1", "s-1", Arc::new(MockModel::new())).with_tool_registry(Arc::new(registry))
537 }
538
539 #[tokio::test]
540 async fn call_tool_runs_through_the_pipeline() {
541 let result = agent()
542 .with_pipeline(Arc::new(StubPipeline))
543 .call_tool("echo", json!({}))
544 .await
545 .unwrap();
546 assert!(result.tool_use_id.starts_with("tooluse_"));
547 assert_eq!(result.content, vec![ToolResultContent::text("agent-1:echo")]);
548 }
549
550 #[tokio::test]
551 async fn call_tool_without_a_pipeline_runs_the_registry_tool() {
552 let result = agent().call_tool("echo", json!({"a": 1})).await.unwrap();
553 assert_eq!(result.content, vec![ToolResultContent::json(json!({"a": 1}))]);
554 let missing = agent().call_tool("missing", json!({})).await.unwrap();
555 assert_eq!(missing.status, ToolResultStatus::Error);
556 assert_eq!(
557 missing.content,
558 vec![ToolResultContent::text("Tool 'missing' not found in registry")]
559 );
560 }
561
562 #[tokio::test]
563 async fn call_tool_inside_a_tool_call_numbers_its_calls_by_the_outer_id() {
564 let view = agent().with_pipeline(Arc::new(StubPipeline)).for_tool_call("outer");
565 let first = view.call_tool("echo", json!({})).await.unwrap();
566 let second = view.call_tool("echo", json!({})).await.unwrap();
567 assert_eq!(
568 (first.tool_use_id.as_str(), second.tool_use_id.as_str()),
569 ("outer:call:0", "outer:call:1")
570 );
571 let rerun = agent().with_pipeline(Arc::new(StubPipeline)).for_tool_call("outer");
572 assert_eq!(
573 rerun.call_tool("echo", json!({})).await.unwrap().tool_use_id,
574 "outer:call:0"
575 );
576 }
577
578 #[tokio::test]
579 async fn call_tool_returns_and_records_an_inner_interrupt() {
580 let registry = ToolRegistry::with_tools(MockTool::new("ask").with_result(|context| {
581 match context.interrupt(InterruptParams::new("approve")) {
582 Ok(_) => ToolOutcome::Result(ToolResultBlock::success(context.tool_use().tool_use_id.clone(), vec![])),
583 Err(interrupt) => ToolOutcome::Interrupt(interrupt),
584 }
585 }))
586 .unwrap();
587 let view = ToolAgent::new("agent-1", "s-1", Arc::new(MockModel::new()))
588 .with_tool_registry(Arc::new(registry))
589 .for_tool_call("outer");
590 let error = view.call_tool("ask", json!({})).await.unwrap_err();
591 assert_eq!(error.interrupts[0].id, "tool:outer:call:0:approve");
592 assert_eq!(view.take_inner_interrupts(), error.interrupts);
593 assert!(view.take_inner_interrupts().is_empty());
594 }
595
596 fn asking_registry() -> ToolRegistry {
597 ToolRegistry::with_tools(MockTool::new("ask").with_result(|context| {
598 match context.interrupt(InterruptParams::new("approve")) {
599 Ok(response) => ToolOutcome::Result(ToolResultBlock::success(
600 context.tool_use().tool_use_id.clone(),
601 vec![ToolResultContent::json(response)],
602 )),
603 Err(interrupt) => ToolOutcome::Interrupt(interrupt),
604 }
605 }))
606 .unwrap()
607 }
608
609 #[tokio::test]
610 async fn call_tool_without_interrupts_returns_the_interrupt_without_recording_it() {
611 let view = ToolAgent::new("agent-1", "s-1", Arc::new(MockModel::new()))
612 .with_tool_registry(Arc::new(asking_registry()))
613 .for_tool_call("outer");
614 let error = view
615 .call_tool_without_interrupts("ask", json!({}), |_| "refused".to_owned())
616 .await
617 .unwrap_err();
618 assert_eq!(error.interrupts.interrupts[0].id, "tool:outer:call:0:approve");
619 assert_eq!(error.result, None);
620 assert!(view.take_inner_interrupts().is_empty());
621 assert!(view.interrupt_state().interrupt_list().is_empty());
622 }
623
624 #[tokio::test]
625 async fn call_tool_without_interrupts_ignores_saved_responses() {
626 let agent = ToolAgent::new("agent-1", "s-1", Arc::new(MockModel::new()))
627 .with_tool_registry(Arc::new(asking_registry()));
628 assert!(agent.for_tool_call("outer").call_tool("ask", json!({})).await.is_err());
629 agent
630 .interrupt_state()
631 .respond("tool:outer:call:0:approve", json!("yes"));
632 let refused = agent
633 .for_tool_call("outer")
634 .call_tool_without_interrupts("ask", json!({}), |_| "refused".to_owned())
635 .await;
636 assert!(refused.is_err());
637 let answered = agent.for_tool_call("outer").call_tool("ask", json!({})).await.unwrap();
638 assert_eq!(answered.content, vec![ToolResultContent::json(json!("yes"))]);
639 }
640
641 #[test]
642 fn aux_model_defaults_to_the_model() {
643 let agent = agent();
644 assert!(Arc::ptr_eq(agent.aux_model(), agent.model()));
645 let aux: Arc<dyn Model> = Arc::new(MockModel::new());
646 let agent = agent.with_aux_model(Some(aux.clone()));
647 assert!(Arc::ptr_eq(agent.aux_model(), &aux));
648 }
649
650 #[test]
651 fn cancel_fires_the_agent_signal() {
652 let agent = agent();
653 let signal = agent.cancel_signal();
654 agent.cancel(CancelOptions::default());
655 assert!(signal.is_cancelled());
656 }
657}