Skip to main content

strands/agent/
tool_agent.rs

1//! The agent view that per-tool hook events and tools see.
2
3use 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
22/// Runs a tool call through the agent's full per-tool pipeline (hooks, interventions,
23/// middleware). The agent loop supplies it; a [`ToolAgent`] without one runs the tool directly.
24pub(crate) trait ToolPipeline: Send + Sync {
25    /// Runs `tool_use` for `agent` and returns the final result, or the interrupts that stopped
26    /// it.
27    fn call_tool(
28        &self,
29        agent: ToolAgent,
30        tool_use: ToolUse,
31    ) -> BoxFuture<'static, Result<ToolResultBlock, InterruptError>>;
32
33    /// Runs `tool_use` like [`call_tool`](Self::call_tool), refusing an interrupt its
34    /// before-call hooks raise with `refusal`'s text, which `AfterToolCallEvent` sees.
35    fn call_tool_refusing(
36        &self,
37        agent: ToolAgent,
38        tool_use: ToolUse,
39        refusal: Refusal,
40    ) -> BoxFuture<'static, Result<ToolResultBlock, RefusedCall>>;
41}
42
43/// The text of a refused inner call's error result, from the interrupts it raised.
44pub(crate) type Refusal = Box<dyn FnOnce(&InterruptError) -> String + Send>;
45
46/// An inner call that stopped for human input, from
47/// [`ToolAgent::call_tool_without_interrupts`]. Nothing records or registers its interrupts.
48#[derive(Debug, Clone, PartialEq, thiserror::Error)]
49#[error("{interrupts}")]
50#[non_exhaustive]
51pub struct RefusedCall {
52    /// The unanswered interrupts.
53    pub interrupts: InterruptError,
54    /// When a before-call hook or intervention raised them (an approval, say): the refusal's
55    /// error result as `AfterToolCallEvent` left it, which a hook may have changed. `None` when
56    /// middleware or the tool itself raised them; `AfterToolCallEvent` does not fire then.
57    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/// The tool call a view runs for: [`ToolAgent::call_tool`] numbers its inner calls from it and
67/// records their interrupts on it, so the outer call stops with them.
68#[derive(Default)]
69struct CallScope {
70    tool_use_id: String,
71    next_call: AtomicUsize,
72    interrupts: Mutex<Vec<Interrupt>>,
73}
74
75/// What the default subagent builder passes from the parent to a child besides its tools,
76/// model, sandbox and printer setting.
77#[derive(Clone, Default)]
78pub(crate) struct ChildInheritance {
79    /// The parent's context manager, whose tools the child does not inherit.
80    pub(crate) context_manager: Option<ContextManager>,
81    /// The parent's intervention handlers, shared with the child.
82    pub(crate) interventions: Arc<[Arc<dyn InterventionHandler>]>,
83    /// The parent's tracer, whose trace attributes the child copies.
84    pub(crate) tracer: Option<Arc<Tracer>>,
85}
86
87/// The view of the agent that tools and per-tool hook events get.
88///
89/// Tools run on their own tasks, so this view is `'static` and cheap to clone. It shares the
90/// agent's app state, model state, models and cancel handle, and holds a snapshot of the messages
91/// and tool registry taken when the tool batch started. History cannot be rewritten mid-batch.
92#[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    /// Creates a view with the given identity and model, and empty state otherwise.
117    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    /// The view a tool with the id `tool_use_id` runs with: its inner calls get ids derived from
194    /// that id.
195    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    /// The interrupts inner calls raised during this view's tool call, removed from it.
205    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    /// `<toolUseId>:call:<n>` inside a tool call, numbered in call order, so a resumed tool's
225    /// calls get the ids (and the interrupt responses) of the first run; `tooluse_<uuid>`
226    /// elsewhere.
227    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    /// What children of the default subagent builder inherit.
253    pub(crate) fn inheritance(&self) -> &ChildInheritance {
254        &self.inheritance
255    }
256
257    /// Whether the agent prints to stdout; children of the default subagent builder inherit it.
258    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    /// The agent's unique id.
267    #[must_use]
268    pub fn id(&self) -> &str {
269        &self.id
270    }
271
272    /// The agent's name.
273    #[must_use]
274    pub fn name(&self) -> &str {
275        self.name.as_deref().unwrap_or(super::agent::DEFAULT_AGENT_NAME)
276    }
277
278    /// The id of the current conversation session.
279    #[must_use]
280    pub fn session_id(&self) -> &str {
281        &self.session_id
282    }
283
284    /// The agent's app state, shared with the agent.
285    #[must_use]
286    pub fn app_state(&self) -> &StateStore {
287        &self.app_state
288    }
289
290    /// The model provider's runtime state, shared with the agent.
291    #[must_use]
292    pub fn model_state(&self) -> &StateStore {
293        &self.model_state
294    }
295
296    /// The agent's model.
297    #[must_use]
298    pub fn model(&self) -> &Arc<dyn Model> {
299        &self.model
300    }
301
302    /// Where the agent's tools run commands and touch files (`sandbox`), shared with the agent.
303    #[must_use]
304    pub fn sandbox(&self) -> &Arc<dyn Sandbox> {
305        &self.sandbox
306    }
307
308    /// The model for auxiliary side calls; the agent's model unless one was configured.
309    #[must_use]
310    pub fn aux_model(&self) -> &Arc<dyn Model> {
311        self.aux_model.as_ref().unwrap_or(&self.model)
312    }
313
314    /// The agent's cancellation signal for the current invocation.
315    #[must_use]
316    pub fn cancel_signal(&self) -> CancelSignal {
317        self.cancel_signal.clone()
318    }
319
320    /// Cancels the agent's current invocation (`cancel`). With
321    /// [`CancelOptions::after_current_tools`] the agent stops once the running tool batch ends.
322    pub fn cancel(&self, options: CancelOptions) {
323        self.cancel_handle.cancel(options);
324    }
325
326    /// The conversation history when the tool batch started.
327    #[must_use]
328    pub fn messages(&self) -> &[Message] {
329        &self.messages
330    }
331
332    /// The agent's tools when the tool batch started.
333    #[must_use]
334    pub fn tool_registry(&self) -> &ToolRegistry {
335        &self.tool_registry
336    }
337
338    /// The request the tool batch belongs to.
339    #[must_use]
340    pub fn invocation_context(&self) -> Option<&InvocationContext> {
341        self.invocation_context.as_ref()
342    }
343
344    /// Calls a registered tool through the agent's full per-tool pipeline (hooks, interventions,
345    /// middleware) and returns its result.
346    ///
347    /// Inside a tool, the call's id is `<toolUseId>:call:<n>`, numbered in call order from 0;
348    /// elsewhere it is a fresh `tooluse_<uuid>`. Failures, an unknown tool name included, are
349    /// error results.
350    ///
351    /// # Errors
352    ///
353    /// The [`InterruptError`] when a hook or intervention on the inner call (an approval, say)
354    /// or the inner tool itself raised an interrupt. Return it with `?`: the calling tool then
355    /// stops with the interrupt, and it stops with it even if it carries on. On resume the
356    /// calling tool runs again from the start, its inner calls get the same ids, and the
357    /// answered call proceeds.
358    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    /// Calls a registered tool like [`call_tool`](Self::call_tool), for a caller that cannot stop
368    /// for human input, such as code orchestrating tools.
369    ///
370    /// An interrupt the inner call raises (from a hook, an intervention, middleware or the tool
371    /// itself) is returned in the error, but it is neither recorded on the calling tool nor
372    /// registered with the agent: the calling tool completes, and a resume never runs it again.
373    /// When a before-call hook or intervention raised it, the call is refused with an error
374    /// result whose text `refusal` gives, and `AfterToolCallEvent` fires with that result, as
375    /// for a call a hook cancels. Responses saved on the agent do not answer such an interrupt;
376    /// a preemptive response ([`InterruptParams::with_response`]) still does. Call ids are
377    /// numbered as for [`call_tool`](Self::call_tool).
378    ///
379    /// ```
380    /// use serde_json::json;
381    /// use strands::Agent;
382    /// use strands::agent::DirectToolCallOptions;
383    /// use strands::tools::FunctionTool;
384    /// use strands::types::{InterruptParams, ToolResultContent};
385    ///
386    /// # tokio::runtime::Runtime::new()?.block_on(async {
387    /// let ask = FunctionTool::builder("ask", "needs a human").callback(|_, context| async move {
388    ///     context.interrupt(InterruptParams::new("approve"))?;
389    ///     Ok(json!("approved"))
390    /// });
391    /// let outer = FunctionTool::builder("outer", "calls ask").callback(|_, context| async move {
392    ///     let refused = context
393    ///         .agent()
394    ///         .call_tool_without_interrupts("ask", json!({}), |_| "needs a human".to_owned())
395    ///         .await
396    ///         .is_err();
397    ///     Ok(json!(format!("refused: {refused}")))
398    /// });
399    /// let mut agent = Agent::builder().tools([ask, outer]).printer(false).build()?;
400    /// let result = agent
401    ///     .tool("outer")
402    ///     .invoke_with(json!({}), DirectToolCallOptions { record_direct_tool_call: Some(false) })
403    ///     .await?;
404    /// assert!(matches!(&result.content[..], [ToolResultContent::Text(text)] if text.text == "refused: true"));
405    /// # Ok::<(), Box<dyn std::error::Error>>(())
406    /// # })?;
407    /// # Ok::<(), Box<dyn std::error::Error>>(())
408    /// ```
409    ///
410    /// # Errors
411    ///
412    /// A [`RefusedCall`] when the inner call raised an unanswered interrupt.
413    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    /// Raises a hook interrupt with the given id.
448    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
453/// Runs a tool to its outcome, dropping progress events.
454pub(crate) async fn run_tool(tool: &dyn Tool, context: ToolContext) -> Option<ToolOutcome> {
455    tool.stream(context).run(|_| {}).await
456}
457
458/// The result for a tool use that names no registered tool.
459pub(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
469/// The result for a tool whose stream ended without an outcome.
470pub(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}