Skip to main content

agent_base/tool/
deferred.rs

1//! [`DeferredTool`]: wrap a tool so it is named in the roster but costs the
2//! request nothing until the model opens it.
3//!
4//! The wrapper is the whole point. The alternative — overriding `exposure()` on
5//! each tool — means touching every crate a tool lives in, and the ones worth
6//! deferring (browser, canvas, image) are exactly the ones phimint does not
7//! own. One adapter at the registration site keeps the decision where it
8//! belongs: with the product, which knows what its current shape of work needs.
9
10use std::sync::Arc;
11
12use async_trait::async_trait;
13use serde_json::Value;
14
15use super::{Content, Tool, ToolContext, ToolExposure};
16
17/// A tool that is on the roster but not on the wire until it is opened.
18///
19/// Everything except [`Tool::exposure`] is delegated — same name, same
20/// description, same schema, same behaviour. The only thing that changes is
21/// when the model is told it exists.
22pub struct DeferredTool {
23    inner: Arc<dyn Tool>,
24}
25
26impl DeferredTool {
27    pub fn new(inner: Arc<dyn Tool>) -> Self {
28        Self { inner }
29    }
30
31    /// The wrapped tool, for a caller that needs the real one (the roster and
32    /// `activate_tool`'s candidates are both rendered from it).
33    pub fn inner(&self) -> Arc<dyn Tool> {
34        Arc::clone(&self.inner)
35    }
36}
37
38#[async_trait]
39impl Tool for DeferredTool {
40    fn name(&self) -> &'static str {
41        self.inner.name()
42    }
43
44    fn description(&self) -> &'static str {
45        self.inner.description()
46    }
47
48    fn schema(&self) -> Value {
49        self.inner.schema()
50    }
51
52    fn exposure(&self) -> ToolExposure {
53        ToolExposure::Deferred
54    }
55
56    async fn call(
57        &self,
58        args: &Value,
59        ctx: &ToolContext,
60    ) -> crate::types::AgentResult<Vec<Content>> {
61        self.inner.call(args, ctx).await
62    }
63
64    fn timeout_ms(&self) -> Option<u64> {
65        self.inner.timeout_ms()
66    }
67
68    fn call_timeout_ms(&self, args: &Value) -> Option<u64> {
69        self.inner.call_timeout_ms(args)
70    }
71
72    fn metadata(&self) -> super::ToolMetadata {
73        self.inner.metadata()
74    }
75}
76
77#[cfg(test)]
78mod tests {
79    use std::sync::atomic::AtomicBool;
80
81    use super::*;
82    use crate::engine::EventBus;
83    use crate::tool::{ActivationContext, ExecClock, ToolActivation, render_tool_definition};
84    use crate::types::{AgentResult, SessionId};
85    use serde_json::json;
86
87    struct Named(&'static str, ToolExposure);
88
89    #[async_trait]
90    impl Tool for Named {
91        fn name(&self) -> &'static str {
92            self.0
93        }
94        fn description(&self) -> &'static str {
95            "inner description"
96        }
97        fn schema(&self) -> Value {
98            json!({"type": "object", "properties": {"a": {"type": "string"}}})
99        }
100        fn exposure(&self) -> ToolExposure {
101            self.1.clone()
102        }
103        async fn call(&self, _args: &Value, _ctx: &ToolContext) -> AgentResult<Vec<Content>> {
104            Ok(vec![Content::text("inner ran")])
105        }
106    }
107
108    fn ctx() -> ToolContext {
109        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
110        ToolContext {
111            session_id: SessionId::new(0),
112            user_event_tx: tx,
113            llm_client: None,
114            session_store: None,
115            language: crate::types::Language::En,
116            cancel_token: tokio_util::sync::CancellationToken::new(),
117            max_output_chars: None,
118            exec_clock: ExecClock::default(),
119            waiting_for_human: Arc::new(AtomicBool::new(false)),
120            event_bus: EventBus::new(1),
121        }
122    }
123
124    /// Value: protects=the decision the wrapper exists for — deferring is a
125    /// packaging call, so it must not change what the tool is or does; the
126    /// model gets the same name, description, schema and behaviour either way.
127    /// fails_when=the wrapper alters any of them. why_new=the wrapper is new.
128    /// seam=registration -> request; no_claim=that the inner tool is unchanged
129    /// in ways not covered here (its own config).
130    #[tokio::test]
131    async fn wrapping_changes_when_a_tool_is_announced_and_nothing_else() {
132        let inner = Arc::new(Named("browser_navigate", ToolExposure::Direct));
133        let deferred = DeferredTool::new(Arc::clone(&inner) as Arc<dyn Tool>);
134
135        assert_eq!(deferred.name(), "browser_navigate");
136        assert_eq!(deferred.description(), "inner description");
137        assert_eq!(deferred.schema(), inner.schema());
138        assert_eq!(deferred.timeout_ms(), inner.timeout_ms());
139
140        assert_eq!(deferred.exposure(), ToolExposure::Deferred);
141        assert_eq!(
142            inner.exposure(),
143            ToolExposure::Direct,
144            "the inner is untouched"
145        );
146
147        let out = deferred.call(&json!({}), &ctx()).await.expect("delegates");
148        assert!(
149            matches!(&out[0], Content::Text { text } if text == "inner ran"),
150            "and it still does the work"
151        );
152    }
153
154    /// Value: protects=the roster's promise — a wrapped tool must cost the
155    /// request nothing until it is opened, which is the entire reason to wrap
156    /// it; fails_when=a wrapped tool shows up unopened. why_new=the wrapper is
157    /// new. seam=ToolExposure -> definitions_filtered; no_claim=that the
158    /// product wraps the right tools.
159    #[test]
160    fn a_wrapped_tool_costs_nothing_until_it_is_opened() {
161        use crate::tool::ToolRegistry;
162
163        let mut r = ToolRegistry::default();
164        r.register(Named("plain", ToolExposure::Direct));
165        r.register(DeferredTool::new(Arc::new(Named(
166            "late",
167            ToolExposure::Direct,
168        ))));
169
170        let closed = ActivationContext {
171            session_id: SessionId::new(0),
172            current_tools: vec![],
173            workspace: std::path::PathBuf::from("/tmp"),
174        };
175        let names = |ctx: &ActivationContext| -> Vec<String> {
176            r.definitions_filtered(ctx)
177                .iter()
178                .map(|d| d["function"]["name"].as_str().unwrap().to_string())
179                .collect()
180        };
181        assert_eq!(names(&closed), vec!["plain".to_string()], "not yet");
182
183        let _ = ToolActivation::new();
184        let mut open = closed.clone();
185        open.current_tools = vec!["late".to_string()];
186        assert_eq!(
187            names(&open),
188            vec!["late".to_string(), "plain".to_string()],
189            "and once opened it is on the request like any other"
190        );
191    }
192
193    /// Value: protects=what `activate_tool` hands back — it renders from the
194    /// wrapper, so the wrapper must reach the inner tool's real definition or
195    /// the model gets a blank schema and calls blind; fails_when=the rendered
196    /// definition loses the inner's arguments. why_new=the wrapper is new.
197    /// seam=wrapper -> wire definition.
198    #[test]
199    fn the_rendered_definition_is_the_inner_tools() {
200        let deferred = DeferredTool::new(Arc::new(Named("late", ToolExposure::Direct)));
201        let def = render_tool_definition(&deferred);
202        assert_eq!(def["function"]["name"], "late");
203        assert_eq!(def["function"]["description"], "inner description");
204        assert_eq!(
205            def["function"]["parameters"]["properties"]["a"]["type"],
206            "string"
207        );
208    }
209}