Skip to main content

agent_base/tool/
mod.rs

1use std::collections::HashMap;
2use std::sync::Arc;
3
4use async_trait::async_trait;
5use serde_json::{Value, json};
6use tokio::sync::mpsc;
7
8use crate::engine::SessionStore;
9use crate::types::{AgentError, AgentResult, RuntimeEvent, SessionId, UserEvent};
10
11pub mod auto_continue;
12pub mod policy;
13pub mod update_plan;
14
15pub use auto_continue::AutoContinueTool;
16pub use update_plan::UpdatePlanTool;
17
18pub use policy::{DenyAllToolPolicy, ToolDecision, ToolPolicy};
19
20// Re-export pure types from agent-types
21pub use agent_types::{
22    ActivationContext, Content, ToolExposure, ToolMetadata, content_details, content_text,
23};
24
25/// Per-call execution-clock control, shared between the tool and the
26/// pipeline's timeout ([`crate::engine::DefaultPipeline`]).
27///
28/// The timeout measures **active** execution time: stretches spent waiting on
29/// a human are excluded ([`ExecClock::pause`]), so a tool that asks the user a
30/// question is never killed by its own execution budget while the user is
31/// still reading. Every [`ToolContext`] built per call gets a fresh clock —
32/// pauses never leak into a later call.
33#[derive(Clone, Default)]
34pub struct ExecClock {
35    inner: Arc<ExecClockInner>,
36}
37
38#[derive(Default)]
39struct ExecClockInner {
40    state: std::sync::Mutex<ExecClockState>,
41}
42
43#[derive(Default)]
44struct ExecClockState {
45    /// Live pause guards. Non-zero ⇒ the clock is paused (nesting supported).
46    live: usize,
47    /// When the current pause began (`Some` while paused).
48    started: Option<std::time::Instant>,
49    /// Paused time already banked from closed pauses.
50    total: std::time::Duration,
51}
52
53impl ExecClock {
54    /// Hold the clock paused for as long as the returned guard lives.
55    /// Nesting is fine: the clock resumes when the outermost guard drops.
56    pub fn pause(&self) -> ExecPauseGuard {
57        let mut state = self.lock();
58        state.live += 1;
59        if state.live == 1 {
60            state.started = Some(std::time::Instant::now());
61        }
62        ExecPauseGuard {
63            clock: self.clone(),
64        }
65    }
66
67    /// Paused time so far, including the open pause if any. The pipeline's
68    /// deadline is `start + budget + paused_total()`, so a pause pushes the
69    /// timeout out by exactly the time the human spent.
70    pub fn paused_total(&self) -> std::time::Duration {
71        let state = self.lock();
72        state.total
73            + state
74                .started
75                .map_or(std::time::Duration::ZERO, |s| s.elapsed())
76    }
77
78    fn resume(&self) {
79        let mut state = self.lock();
80        state.live = state.live.saturating_sub(1);
81        if state.live == 0
82            && let Some(started) = state.started.take()
83        {
84            state.total += started.elapsed();
85        }
86    }
87
88    fn lock(&self) -> std::sync::MutexGuard<'_, ExecClockState> {
89        // A panic while holding the clock must not poison it — worst case the
90        // accounting is slightly off, never "the tool can never time out".
91        self.inner
92            .state
93            .lock()
94            .unwrap_or_else(std::sync::PoisonError::into_inner)
95    }
96}
97
98/// RAII pause handle — see [`ExecClock::pause`].
99pub struct ExecPauseGuard {
100    clock: ExecClock,
101}
102
103impl Drop for ExecPauseGuard {
104    fn drop(&mut self) {
105        self.clock.resume();
106    }
107}
108
109#[derive(Clone)]
110pub struct ToolContext {
111    pub session_id: SessionId,
112    /// Channel for sending user-space events (progress, sub-agent, structured).
113    /// Tools should use `emit_user_event()` or `emit_progress()`.
114    pub user_event_tx: mpsc::UnboundedSender<UserEvent>,
115    pub llm_client: Option<Arc<dyn llm_trait::LlmProvider>>,
116    pub session_store: Option<Arc<dyn SessionStore>>,
117    /// Language preference for tool output.
118    /// Defaults to `Language::En` if not set.
119    pub language: crate::types::Language,
120    /// Cancellation token for checking if the operation should be cancelled.
121    pub cancel_token: tokio_util::sync::CancellationToken,
122    /// Output budget for this call, in characters (set from the engine's
123    /// `max_tool_output_chars`). Tools that can return large results (e.g.
124    /// `read_file`) should self-truncate to this bound and mark the cut, so
125    /// the engine's hard reject (§6.5) never fires for a paginated read.
126    pub max_output_chars: Option<usize>,
127    /// Execution clock for this call — see [`ExecClock`]. Pause it while the
128    /// tool waits on a human ([`ToolContext::pause_execution_clock`]).
129    pub exec_clock: ExecClock,
130    /// Internal runtime event bus (framework tools emit `RuntimeEvent`s here).
131    /// `pub(crate)` — engine-internal; user tools should use `emit_user_event()`.
132    pub(crate) event_bus: crate::engine::EventBus,
133}
134
135impl ToolContext {
136    /// Pause this call's execution clock for as long as the guard lives.
137    ///
138    /// Call this while waiting on a human (a confirmation popup, a login):
139    /// the pipeline's tool timeout does not count the paused stretch.
140    pub fn pause_execution_clock(&self) -> ExecPauseGuard {
141        self.exec_clock.pause()
142    }
143
144    /// Send a user-space event (progress, sub-agent forwarding, structured data).
145    ///
146    /// Dual-write: the event goes to `user_event_tx` (the tool select arm
147    /// renders it in real time) and to the event bus for external subscribers
148    /// (bridge remote clients, persistence). The bus copy carries `agent_id:
149    /// None` — the self-echo marker — so bus loopback drops it instead of
150    /// re-rendering (see `crate::engine::runtime::is_self_echo_user_event`).
151    pub fn emit_user_event(&self, event: UserEvent) {
152        let _ = self.user_event_tx.send(event.clone());
153        self.event_bus.emit(RuntimeEvent::UserEvent {
154            session_id: self.session_id.clone(),
155            event,
156            agent_id: None,
157            trace_id: None,
158        });
159    }
160
161    /// Convenience: send a progress event with text.
162    pub fn emit_progress(&self, text: impl Into<String>) {
163        self.emit_user_event(UserEvent::Progress { text: text.into() });
164    }
165
166    /// Convenience: emit a partial result during long-running tool execution.
167    /// `is_partial: true` means more output is coming; `false` means final.
168    pub fn emit_partial_result(
169        &self,
170        tool_call_id: &str,
171        content: impl Into<String>,
172        is_partial: bool,
173    ) {
174        self.emit_user_event(UserEvent::ToolPartialResult {
175            tool_call_id: tool_call_id.to_string(),
176            content: content.into(),
177            is_partial,
178        });
179    }
180
181    /// Test-only constructor: a `ToolContext` with a disconnected event
182    /// channel and no LLM/session backends. Lets downstream tests drop their
183    /// bespoke `dummy_ctx()` helpers.
184    pub fn for_test() -> Self {
185        let (tx, _rx) = mpsc::unbounded_channel();
186        ToolContext {
187            session_id: SessionId::new(0),
188            user_event_tx: tx,
189            llm_client: None,
190            session_store: None,
191            language: crate::types::Language::En,
192            cancel_token: tokio_util::sync::CancellationToken::new(),
193            max_output_chars: None,
194            exec_clock: ExecClock::default(),
195            event_bus: crate::engine::EventBus::new(1),
196        }
197    }
198
199    /// Host-side constructor for host-initiated tool execution outside the
200    /// engine loop (e.g. a REPL driving a tool through the same approval path
201    /// as the engine). User events are accepted but dropped — there is no
202    /// engine event loop to render them.
203    pub fn new(
204        session_id: SessionId,
205        llm_client: Option<Arc<dyn crate::llm_trait::LlmProvider>>,
206        session_store: Option<Arc<dyn SessionStore>>,
207        cancel_token: tokio_util::sync::CancellationToken,
208    ) -> Self {
209        let (tx, _rx) = mpsc::unbounded_channel();
210        ToolContext {
211            session_id,
212            user_event_tx: tx,
213            llm_client,
214            session_store,
215            language: crate::types::Language::En,
216            cancel_token,
217            max_output_chars: None,
218            exec_clock: ExecClock::default(),
219            event_bus: crate::engine::EventBus::new(1),
220        }
221    }
222}
223
224#[async_trait]
225pub trait Tool: Send + Sync {
226    fn name(&self) -> &'static str;
227    /// Human-readable description of what this tool does and when to use it.
228    fn description(&self) -> &'static str;
229    /// JSON Schema for the tool's input arguments (MCP `inputSchema` shape,
230    /// without the provider envelope).
231    fn schema(&self) -> Value;
232    async fn call(&self, args: &Value, ctx: &ToolContext) -> AgentResult<Vec<Content>>;
233
234    /// Timeout for this tool in milliseconds.
235    ///
236    /// Returns `Some(ms)` to enforce a timeout, or `None` to use the
237    /// framework's default timeout from `ToolConfig.default_tool_timeout_ms`.
238    /// Tools that need more or less time should override this method.
239    fn timeout_ms(&self) -> Option<u64> {
240        None // Use framework default
241    }
242
243    /// Machine-readable metadata for tool introspection.
244    ///
245    /// The default implementation derives `name` and `description` from
246    /// [`Tool::name`] and [`Tool::description`], sets `origin` to `"custom"`,
247    /// and leaves `requirements` empty. Tool authors are encouraged to
248    /// override this to provide an accurate `origin` and `version`.
249    fn metadata(&self) -> ToolMetadata {
250        ToolMetadata {
251            name: self.name().to_string(),
252            description: self.description().to_string(),
253            origin: "custom".to_string(),
254            version: "unknown".to_string(),
255            requirements: vec![],
256        }
257    }
258
259    /// Visibility level for this tool. Default: `Direct` (always visible).
260    ///
261    /// Override to return `Deferred` (conditionally visible) or `Hidden`
262    /// (never visible to the model). `Deferred` tools are only included
263    /// when [`Tool::should_activate`] returns `true`.
264    fn exposure(&self) -> ToolExposure {
265        ToolExposure::Direct
266    }
267
268    /// Activation condition for `Deferred` tools.
269    ///
270    /// Called once per turn for each `Deferred` tool. Return `true` to
271    /// include this tool in the model's tool list this turn. Ignored for
272    /// `Direct` and `Hidden` tools.
273    fn should_activate(&self, _ctx: &ActivationContext) -> bool {
274        true
275    }
276}
277
278#[async_trait]
279pub trait TypedTool: Send + Sync {
280    type Args: serde::de::DeserializeOwned + schemars::JsonSchema;
281    type Output: serde::Serialize;
282
283    fn name(&self) -> &'static str;
284    fn description(&self) -> &'static str;
285    async fn call_typed(&self, args: Self::Args, ctx: &ToolContext) -> AgentResult<Self::Output>;
286
287    fn format_output(&self, output: Self::Output) -> Content {
288        // A `String` output is emitted verbatim; any other serializable type is
289        // rendered as JSON. This avoids `serde_json::to_string` wrapping a plain
290        // string in literal double quotes (`hello` → `"hello"`), which would leak
291        // quotes into the LLM-visible tool result.
292        match serde_json::to_value(&output) {
293            Ok(serde_json::Value::String(s)) => Content::text(s),
294            Ok(other) => Content::text(other.to_string()),
295            Err(_) => Content::text(String::new()),
296        }
297    }
298
299    /// Machine-readable origin of this tool (crate name, `"agent-base"`, or `"custom"`).
300    fn origin(&self) -> &'static str {
301        "custom"
302    }
303
304    /// Crate/package version, or `"unknown"` when built outside a crate.
305    fn version(&self) -> &'static str {
306        "unknown"
307    }
308
309    /// Visibility level for this tool. Default: `Direct` (always visible).
310    fn exposure(&self) -> ToolExposure {
311        ToolExposure::Direct
312    }
313
314    /// Activation condition for `Deferred` tools. Ignored for `Direct`/`Hidden`.
315    fn should_activate(&self, _ctx: &ActivationContext) -> bool {
316        true
317    }
318}
319
320#[async_trait]
321impl<T: TypedTool + Send + Sync + 'static> Tool for T {
322    fn name(&self) -> &'static str {
323        TypedTool::name(self)
324    }
325
326    fn description(&self) -> &'static str {
327        TypedTool::description(self)
328    }
329
330    fn schema(&self) -> Value {
331        // Generate a provider-safe JSON Schema: Draft 7 (not 2020-12), with
332        // nested subschemas inlined (no `$ref`/`$defs`/`/definitions`) and no
333        // root `$schema`/meta-schema key. OpenAI-compatible function-calling
334        // rejects `$ref` and 2020-12's `$defs`, so the default 2020-12 output
335        // would break any `Args` containing a nested enum or struct.
336        let settings = schemars::generate::SchemaSettings::draft07().with(|s| {
337            s.inline_subschemas = true;
338            s.meta_schema = None;
339        });
340        let generator = schemars::SchemaGenerator::new(settings);
341        let schema = generator.into_root_schema_for::<T::Args>();
342        serde_json::to_value(schema).unwrap_or(Value::Null)
343    }
344
345    fn metadata(&self) -> ToolMetadata {
346        ToolMetadata {
347            name: self.name().to_string(),
348            description: self.description().to_string(),
349            origin: self.origin().to_string(),
350            version: self.version().to_string(),
351            requirements: vec![],
352        }
353    }
354
355    fn exposure(&self) -> ToolExposure {
356        TypedTool::exposure(self)
357    }
358
359    fn should_activate(&self, ctx: &ActivationContext) -> bool {
360        TypedTool::should_activate(self, ctx)
361    }
362
363    async fn call(&self, args: &Value, ctx: &ToolContext) -> AgentResult<Vec<Content>> {
364        let typed_args: T::Args =
365            serde_json::from_value(args.clone()).map_err(|_| AgentError::ToolArgsInvalid {
366                name: self.name().to_string(),
367                raw: args.to_string(),
368            })?;
369        let output = self.call_typed(typed_args, ctx).await?;
370        Ok(vec![self.format_output(output)])
371    }
372}
373
374/// Render a single tool's definition into the OpenAI function-calling
375/// envelope. Tools only provide `name`/`description`/`schema`; the envelope is
376/// assembled here at the LLM boundary (Anthropic gets its own renderer, and
377/// tool authors stay protocol-agnostic).
378pub fn render_tool_definition(tool: &dyn Tool) -> Value {
379    json!({
380        "type": "function",
381        "function": {
382            "name": tool.name(),
383            "description": tool.description(),
384            "parameters": tool.schema(),
385        }
386    })
387}
388
389pub(crate) type ToolRef = Arc<dyn Tool>;
390
391#[derive(Clone, Default)]
392pub struct ToolRegistry {
393    tools: HashMap<String, ToolRef>,
394}
395
396impl ToolRegistry {
397    pub fn register(&mut self, tool: impl Tool + 'static) {
398        self.tools.insert(tool.name().to_string(), Arc::new(tool));
399    }
400
401    pub fn register_arc(&mut self, tool: Arc<dyn Tool>) {
402        self.tools.insert(tool.name().to_string(), tool);
403    }
404
405    /// Remove a tool from the registry by name.
406    pub fn remove(&mut self, name: &str) {
407        self.tools.remove(name);
408    }
409
410    pub fn get(&self, name: &str) -> Option<ToolRef> {
411        self.tools.get(name).cloned()
412    }
413
414    pub fn definitions(&self) -> Vec<Value> {
415        let mut tools: Vec<_> = self.tools.values().collect();
416        tools.sort_by_key(|t| t.name());
417        tools
418            .into_iter()
419            .map(|t| render_tool_definition(t.as_ref()))
420            .collect()
421    }
422
423    /// Return tool definitions filtered by [`ToolExposure`].
424    ///
425    /// - `Direct` tools are always included.
426    /// - `Deferred` tools are included only when `should_activate(ctx)` returns `true`.
427    /// - `Hidden` tools are never included.
428    pub fn definitions_filtered(&self, ctx: &ActivationContext) -> Vec<Value> {
429        let mut tools: Vec<_> = self.tools.values().collect();
430        tools.sort_by_key(|t| t.name());
431
432        // Single sequential pass: collect Direct names first, then evaluate
433        // Deferred tools in sorted order. Each Deferred tool sees the names of
434        // all Direct + previously-activated Deferred tools in ctx.current_tools.
435        // Evaluation order matters: a later Deferred tool can see an earlier one,
436        // but not vice versa.
437        let direct_names: Vec<String> = tools
438            .iter()
439            .filter(|t| t.exposure() == ToolExposure::Direct)
440            .map(|t| t.name().to_string())
441            .collect();
442
443        let mut activated_names = direct_names.clone();
444        for t in &tools {
445            if t.exposure() == ToolExposure::Deferred {
446                let mut ctx_with_tools = ctx.clone();
447                ctx_with_tools.current_tools = activated_names.clone();
448                if t.should_activate(&ctx_with_tools) {
449                    activated_names.push(t.name().to_string());
450                }
451            }
452        }
453
454        tools
455            .into_iter()
456            .filter(|t| match t.exposure() {
457                ToolExposure::Direct => true,
458                ToolExposure::Deferred => activated_names.contains(&t.name().to_string()),
459                ToolExposure::Hidden => false,
460            })
461            .map(|t| render_tool_definition(t.as_ref()))
462            .collect()
463    }
464
465    pub fn len(&self) -> usize {
466        self.tools.len()
467    }
468
469    pub fn is_empty(&self) -> bool {
470        self.tools.is_empty()
471    }
472
473    /// Collect metadata for every registered tool, sorted by name.
474    ///
475    /// This is the preferred introspection API for consumers — it returns a
476    /// stable `ToolMetadata` struct per tool instead of having callers parse
477    /// the LLM-facing JSON definitions.
478    pub fn metadatas(&self) -> Vec<ToolMetadata> {
479        let mut list: Vec<_> = self.tools.values().map(|tool| tool.metadata()).collect();
480        list.sort_by(|a, b| a.name.cmp(&b.name));
481        list
482    }
483}
484
485#[cfg(test)]
486mod tests {
487    use super::*;
488
489    #[test]
490    fn exec_clock_pause_accounting() {
491        let clock = ExecClock::default();
492        assert_eq!(clock.paused_total(), std::time::Duration::ZERO);
493
494        let guard = clock.pause();
495        std::thread::sleep(std::time::Duration::from_millis(30));
496        // An open pause counts in-flight — the pipeline's deadline moves live.
497        assert!(clock.paused_total() >= std::time::Duration::from_millis(30));
498        drop(guard);
499        let banked = clock.paused_total();
500        assert!(banked >= std::time::Duration::from_millis(30));
501
502        // Closed pauses stay banked; a later pause adds to them.
503        std::thread::sleep(std::time::Duration::from_millis(10));
504        assert_eq!(clock.paused_total(), banked);
505        let g2 = clock.pause();
506        std::thread::sleep(std::time::Duration::from_millis(20));
507        assert!(clock.paused_total() >= banked + std::time::Duration::from_millis(20));
508        drop(g2);
509    }
510
511    #[test]
512    fn exec_clock_nested_guards_resume_once() {
513        let clock = ExecClock::default();
514        let outer = clock.pause();
515        let inner = clock.pause();
516        std::thread::sleep(std::time::Duration::from_millis(15));
517        drop(inner);
518        std::thread::sleep(std::time::Duration::from_millis(15));
519        // Still paused via `outer` — the in-flight pause keeps growing.
520        let during = clock.paused_total();
521        assert!(during >= std::time::Duration::from_millis(30));
522        drop(outer);
523        let after = clock.paused_total();
524        assert!(after >= during);
525        std::thread::sleep(std::time::Duration::from_millis(10));
526        assert_eq!(clock.paused_total(), after);
527    }
528
529    #[test]
530    fn exec_clock_guard_drop_unwinds_from_panic() {
531        // A panic while holding the guard must not poison the clock.
532        let clock = ExecClock::default();
533        let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
534            let _guard = clock.pause();
535            panic!("boom");
536        }));
537        assert!(caught.is_err());
538        std::thread::sleep(std::time::Duration::from_millis(5));
539        let banked = clock.paused_total();
540        std::thread::sleep(std::time::Duration::from_millis(10));
541        assert_eq!(clock.paused_total(), banked, "clock must be resumed");
542    }
543
544    #[test]
545    fn content_text_ctor_and_into_vec() {
546        let c = Content::text("hello");
547        let v: Vec<Content> = c.clone().into();
548        assert_eq!(v.len(), 1);
549        assert!(matches!(v[0], Content::Text { .. }));
550        assert!(matches!(&c, Content::Text { text } if text == "hello"));
551    }
552
553    #[test]
554    fn content_serializes_with_type_tag() {
555        let c = Content::text("hi");
556        let j = serde_json::to_value(&c).unwrap();
557        assert_eq!(j["type"], "text");
558        assert_eq!(j["text"], "hi");
559    }
560
561    #[test]
562    fn tool_context_for_test_constructs() {
563        let ctx = ToolContext::for_test();
564        assert!(ctx.llm_client.is_none());
565        assert!(ctx.session_store.is_none());
566        assert!(!ctx.cancel_token.is_cancelled());
567        ctx.emit_progress("hello");
568    }
569
570    #[test]
571    fn typed_tool_schema_is_derived_from_args() {
572        #[derive(schemars::JsonSchema, serde::Deserialize, serde::Serialize)]
573        struct GreetArgs {
574            name: String,
575            #[serde(default)]
576            times: u32,
577        }
578
579        let schema = schemars::schema_for!(GreetArgs);
580        let j = serde_json::to_value(&schema).unwrap();
581        // The derived schema exposes the struct's fields as object properties.
582        assert!(j["properties"]["name"].is_object());
583        assert!(j["properties"]["times"].is_object());
584    }
585
586    #[test]
587    fn typed_tool_schema_is_provider_safe_for_nested_enum() {
588        #[derive(schemars::JsonSchema, serde::Deserialize, serde::Serialize)]
589        enum Status {
590            Active,
591            Paused,
592        }
593
594        #[derive(schemars::JsonSchema, serde::Deserialize, serde::Serialize)]
595        struct Args {
596            name: String,
597            status: Status,
598        }
599
600        #[derive(Default)]
601        struct NestedTool;
602        #[async_trait]
603        impl TypedTool for NestedTool {
604            type Args = Args;
605            type Output = String;
606            fn name(&self) -> &'static str {
607                "nested"
608            }
609            fn description(&self) -> &'static str {
610                ""
611            }
612            async fn call_typed(
613                &self,
614                _args: Args,
615                _ctx: &ToolContext,
616            ) -> crate::types::AgentResult<String> {
617                Ok(String::new())
618            }
619        }
620
621        let schema = Tool::schema(&NestedTool);
622        let raw = schema.to_string();
623        // OpenAI-compatible function-calling rejects $ref / $defs; the nested
624        // enum must be inlined rather than referenced.
625        assert!(!raw.contains("$ref"), "schema contains $ref: {raw}");
626        assert!(!raw.contains("$defs"), "schema contains $defs: {raw}");
627        assert!(
628            !raw.contains("definitions"),
629            "schema has definitions: {raw}"
630        );
631        assert!(schema.get("$schema").is_none(), "schema has $schema key");
632
633        // The enum variants are inlined directly under properties.status.
634        let variants: Vec<&str> = schema["properties"]["status"]["enum"]
635            .as_array()
636            .unwrap()
637            .iter()
638            .map(|v| v.as_str().unwrap())
639            .collect();
640        assert!(variants.contains(&"Active"), "missing Active: {variants:?}");
641        assert!(variants.contains(&"Paused"), "missing Paused: {variants:?}");
642    }
643
644    #[test]
645    fn definitions_are_sorted_by_name() {
646        struct NamedTool(&'static str);
647        #[async_trait::async_trait]
648        impl Tool for NamedTool {
649            fn name(&self) -> &'static str {
650                self.0
651            }
652            fn description(&self) -> &'static str {
653                ""
654            }
655            fn schema(&self) -> serde_json::Value {
656                serde_json::Value::Null
657            }
658            async fn call(
659                &self,
660                _args: &serde_json::Value,
661                _ctx: &ToolContext,
662            ) -> crate::types::AgentResult<Vec<Content>> {
663                Ok(vec![])
664            }
665        }
666
667        let mut registry = ToolRegistry::default();
668        registry.register(NamedTool("zeta"));
669        registry.register(NamedTool("alpha"));
670        registry.register(NamedTool("mike"));
671
672        let defs = registry.definitions();
673        let names: Vec<&str> = defs
674            .iter()
675            .map(|d| d["function"]["name"].as_str().unwrap())
676            .collect();
677        assert_eq!(names, vec!["alpha", "mike", "zeta"]);
678    }
679
680    // ── B4: content image / partial result / typed-tool blanket / registry ──
681
682    #[test]
683    fn content_image_and_content_text_skips_images() {
684        let img = Content::image("base64data", "image/png");
685        assert!(
686            matches!(&img, Content::Image { data, mime_type } if data == "base64data" && mime_type == "image/png")
687        );
688
689        let text = content_text(&[
690            Content::text("a"),
691            Content::image("b", "image/png"),
692            Content::text("c"),
693        ]);
694        assert_eq!(text, "a\nc");
695    }
696
697    #[test]
698    fn emit_partial_result_sends_event() {
699        let (tx, mut rx) = mpsc::unbounded_channel();
700        let ctx = ToolContext {
701            session_id: SessionId::new(0),
702            user_event_tx: tx,
703            llm_client: None,
704            session_store: None,
705            language: crate::types::Language::En,
706            cancel_token: tokio_util::sync::CancellationToken::new(),
707            max_output_chars: None,
708            exec_clock: ExecClock::default(),
709            event_bus: crate::engine::EventBus::new(1),
710        };
711        ctx.emit_partial_result("tc1", "partial", true);
712        match rx.try_recv().unwrap() {
713            UserEvent::ToolPartialResult {
714                tool_call_id,
715                content,
716                is_partial,
717            } => {
718                assert_eq!(tool_call_id, "tc1");
719                assert_eq!(content, "partial");
720                assert!(is_partial);
721            }
722            other => panic!("unexpected event: {other:?}"),
723        }
724    }
725
726    // Dual-write contract (Batch E follow-up): a tool UserEvent must reach
727    // event_bus subscribers (bridge remote clients, persistence) as well as the
728    // per-call user_event channel — and the bus copy must carry `agent_id: None`,
729    // the self-echo marker that tells bus loopback not to re-render it (see
730    // `engine::event_bus::is_self_echo_user_event`).
731    #[test]
732    fn emit_user_event_dual_writes_to_event_bus() {
733        let (tx, mut rx) = mpsc::unbounded_channel();
734        let ctx = ToolContext {
735            session_id: SessionId::new(7),
736            user_event_tx: tx,
737            llm_client: None,
738            session_store: None,
739            language: crate::types::Language::En,
740            cancel_token: tokio_util::sync::CancellationToken::new(),
741            max_output_chars: None,
742            exec_clock: ExecClock::default(),
743            event_bus: crate::engine::EventBus::new(4),
744        };
745        let mut bus_rx = ctx.event_bus.subscribe();
746        ctx.emit_progress("working");
747
748        // Direct channel still gets the event (real-time tool select arm).
749        assert!(
750            matches!(rx.try_recv().unwrap(), UserEvent::Progress { text } if text == "working")
751        );
752
753        // Bus copy for external subscribers, stamped and marked self-echo.
754        match bus_rx.try_recv().unwrap() {
755            crate::types::RuntimeEvent::UserEvent {
756                session_id,
757                event,
758                agent_id,
759                ..
760            } => {
761                assert_eq!(session_id, SessionId::new(7));
762                assert!(matches!(event, UserEvent::Progress { text } if text == "working"));
763                assert!(agent_id.is_none());
764            }
765            other => panic!("unexpected bus event: {other:?}"),
766        }
767    }
768
769    // A concrete TypedTool exercising the blanket `impl Tool for T`.
770    #[derive(schemars::JsonSchema, serde::Deserialize, serde::Serialize)]
771    struct GreetArgs {
772        name: String,
773    }
774
775    struct GreetTool;
776    #[async_trait]
777    impl TypedTool for GreetTool {
778        type Args = GreetArgs;
779        type Output = String;
780        fn name(&self) -> &'static str {
781            "greet"
782        }
783        fn description(&self) -> &'static str {
784            "greets a name"
785        }
786        fn origin(&self) -> &'static str {
787            "test-crate"
788        }
789        fn version(&self) -> &'static str {
790            "1.0.0"
791        }
792        async fn call_typed(&self, args: GreetArgs, _ctx: &ToolContext) -> AgentResult<String> {
793            Ok(format!("Hello, {}!", args.name))
794        }
795    }
796
797    #[test]
798    fn typed_tool_blanket_delegates_name_description() {
799        let t = GreetTool;
800        assert_eq!(Tool::name(&t), "greet");
801        assert_eq!(Tool::description(&t), "greets a name");
802    }
803
804    #[test]
805    fn typed_tool_metadata_uses_origin_and_version() {
806        let m = Tool::metadata(&GreetTool);
807        assert_eq!(m.name, "greet");
808        assert_eq!(m.description, "greets a name");
809        assert_eq!(m.origin, "test-crate");
810        assert_eq!(m.version, "1.0.0");
811        assert!(m.requirements.is_empty());
812    }
813
814    #[tokio::test]
815    async fn typed_tool_call_deserializes_and_formats() {
816        let ctx = ToolContext::for_test();
817        let out = Tool::call(&GreetTool, &json!({"name": "world"}), &ctx)
818            .await
819            .unwrap();
820        // format_output emits a String verbatim (not JSON-quoted).
821        assert_eq!(content_text(&out), "Hello, world!");
822    }
823
824    // A struct-typed output confirms non-String outputs still serialize as JSON.
825    #[derive(serde::Serialize)]
826    struct GreetResult {
827        message: String,
828    }
829
830    struct GreetStructTool;
831    #[async_trait]
832    impl TypedTool for GreetStructTool {
833        type Args = GreetArgs;
834        type Output = GreetResult;
835        fn name(&self) -> &'static str {
836            "greet_struct"
837        }
838        fn description(&self) -> &'static str {
839            "greets as json"
840        }
841        async fn call_typed(
842            &self,
843            args: GreetArgs,
844            _ctx: &ToolContext,
845        ) -> AgentResult<GreetResult> {
846            Ok(GreetResult {
847                message: format!("Hello, {}!", args.name),
848            })
849        }
850    }
851
852    #[test]
853    fn format_output_json_serializes_struct() {
854        let out = GreetStructTool.format_output(GreetResult {
855            message: "hi".into(),
856        });
857        assert_eq!(content_text(&[out]), r#"{"message":"hi"}"#);
858    }
859
860    #[tokio::test]
861    async fn typed_tool_call_invalid_args_is_tool_args_invalid() {
862        let ctx = ToolContext::for_test();
863        let err = Tool::call(&GreetTool, &json!({"nope": 1}), &ctx)
864            .await
865            .unwrap_err();
866        assert!(matches!(err, AgentError::ToolArgsInvalid { .. }));
867    }
868
869    struct NamedTool(&'static str);
870    #[async_trait]
871    impl Tool for NamedTool {
872        fn name(&self) -> &'static str {
873            self.0
874        }
875        fn description(&self) -> &'static str {
876            ""
877        }
878        fn schema(&self) -> serde_json::Value {
879            serde_json::Value::Null
880        }
881        async fn call(
882            &self,
883            _args: &serde_json::Value,
884            _ctx: &ToolContext,
885        ) -> AgentResult<Vec<Content>> {
886            Ok(vec![])
887        }
888    }
889
890    #[test]
891    fn registry_register_arc_get_remove_len_is_empty() {
892        let mut r = ToolRegistry::default();
893        assert!(r.is_empty());
894        assert_eq!(r.len(), 0);
895
896        let t: Arc<dyn Tool> = Arc::new(NamedTool("x"));
897        r.register_arc(t);
898        assert!(!r.is_empty());
899        assert_eq!(r.len(), 1);
900        assert!(r.get("x").is_some());
901        assert!(r.get("missing").is_none());
902
903        r.remove("x");
904        assert!(r.is_empty());
905    }
906
907    #[test]
908    fn metadatas_are_sorted_by_name() {
909        let mut r = ToolRegistry::default();
910        r.register(NamedTool("zeta"));
911        r.register(NamedTool("alpha"));
912
913        let metas = r.metadatas();
914        let names: Vec<&str> = metas.iter().map(|m| m.name.as_str()).collect();
915        assert_eq!(names, vec!["alpha", "zeta"]);
916        assert_eq!(metas[0].origin, "custom");
917        assert_eq!(metas[0].version, "unknown");
918    }
919
920    // ── Phase 2: ToolExposure + definitions_filtered ────────────────────
921
922    struct ExposureTool(&'static str, ToolExposure);
923    #[async_trait]
924    impl Tool for ExposureTool {
925        fn name(&self) -> &'static str {
926            self.0
927        }
928        fn description(&self) -> &'static str {
929            ""
930        }
931        fn schema(&self) -> serde_json::Value {
932            serde_json::Value::Null
933        }
934        async fn call(
935            &self,
936            _args: &serde_json::Value,
937            _ctx: &ToolContext,
938        ) -> AgentResult<Vec<Content>> {
939            Ok(vec![])
940        }
941        fn exposure(&self) -> ToolExposure {
942            self.1.clone()
943        }
944    }
945
946    struct ConditionalTool(&'static str, bool);
947    #[async_trait]
948    impl Tool for ConditionalTool {
949        fn name(&self) -> &'static str {
950            self.0
951        }
952        fn description(&self) -> &'static str {
953            ""
954        }
955        fn schema(&self) -> serde_json::Value {
956            serde_json::Value::Null
957        }
958        async fn call(
959            &self,
960            _args: &serde_json::Value,
961            _ctx: &ToolContext,
962        ) -> AgentResult<Vec<Content>> {
963            Ok(vec![])
964        }
965        fn exposure(&self) -> ToolExposure {
966            ToolExposure::Deferred
967        }
968        fn should_activate(&self, _ctx: &ActivationContext) -> bool {
969            self.1
970        }
971    }
972
973    fn default_ctx() -> ActivationContext {
974        ActivationContext {
975            session_id: crate::types::SessionId::new(0),
976            current_tools: vec![],
977            workspace: std::path::PathBuf::from("/tmp"),
978        }
979    }
980
981    #[test]
982    fn tool_exposure_default_is_direct() {
983        // NamedTool doesn't override exposure() → default Direct
984        let t = NamedTool("x");
985        assert_eq!(t.exposure(), ToolExposure::Direct);
986    }
987
988    #[test]
989    fn tool_should_activate_default_is_true() {
990        let t = NamedTool("x");
991        assert!(t.should_activate(&default_ctx()));
992    }
993
994    #[test]
995    fn definitions_filtered_includes_direct_excludes_hidden() {
996        let mut r = ToolRegistry::default();
997        r.register(ExposureTool("direct_a", ToolExposure::Direct));
998        r.register(ExposureTool("hidden_a", ToolExposure::Hidden));
999        r.register(ExposureTool("direct_b", ToolExposure::Direct));
1000
1001        let defs = r.definitions_filtered(&default_ctx());
1002        let names: Vec<&str> = defs
1003            .iter()
1004            .map(|d| d["function"]["name"].as_str().unwrap())
1005            .collect();
1006        assert_eq!(names, vec!["direct_a", "direct_b"]);
1007    }
1008
1009    #[test]
1010    fn definitions_filtered_includes_deferred_when_activated() {
1011        let mut r = ToolRegistry::default();
1012        r.register(ExposureTool("always", ToolExposure::Direct));
1013        r.register(ConditionalTool("maybe", true)); // should_activate = true
1014        r.register(ConditionalTool("never", false)); // should_activate = false
1015
1016        let defs = r.definitions_filtered(&default_ctx());
1017        let names: Vec<&str> = defs
1018            .iter()
1019            .map(|d| d["function"]["name"].as_str().unwrap())
1020            .collect();
1021        assert_eq!(names, vec!["always", "maybe"]);
1022    }
1023
1024    #[test]
1025    fn definitions_filtered_all_hidden_returns_empty() {
1026        let mut r = ToolRegistry::default();
1027        r.register(ExposureTool("h1", ToolExposure::Hidden));
1028        r.register(ExposureTool("h2", ToolExposure::Hidden));
1029
1030        let defs = r.definitions_filtered(&default_ctx());
1031        assert!(defs.is_empty());
1032    }
1033
1034    #[test]
1035    fn definitions_filtered_empty_registry() {
1036        let r = ToolRegistry::default();
1037        let defs = r.definitions_filtered(&default_ctx());
1038        assert!(defs.is_empty());
1039    }
1040
1041    #[test]
1042    fn definitions_unfiltered_includes_hidden() {
1043        // The original definitions() method does NOT filter — all tools appear.
1044        let mut r = ToolRegistry::default();
1045        r.register(ExposureTool("visible", ToolExposure::Direct));
1046        r.register(ExposureTool("secret", ToolExposure::Hidden));
1047
1048        let defs = r.definitions();
1049        assert_eq!(defs.len(), 2);
1050    }
1051}