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