Skip to main content

agent_base/tool/
mod.rs

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