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(|e| AgentError::ToolArgsInvalid {
398 name: self.name().to_string(),
399 // Carry the serde detail ("missing field `task` …") — the model
400 // can only fix what the message names. Same "{e} (args: …)"
401 // shape as the phase1 JSON-parse failure site (tool_engine.rs)
402 // and the contract asserted in recovery.rs.
403 raw: format!("{e} (args: {args})"),
404 })?;
405 let output = self.call_typed(typed_args, ctx).await?;
406 Ok(vec![self.format_output(output)])
407 }
408}
409
410/// Render a single tool's definition into the OpenAI function-calling
411/// envelope. Tools only provide `name`/`description`/`schema`; the envelope is
412/// assembled here at the LLM boundary (Anthropic gets its own renderer, and
413/// tool authors stay protocol-agnostic).
414pub fn render_tool_definition(tool: &dyn Tool) -> Value {
415 json!({
416 "type": "function",
417 "function": {
418 "name": tool.name(),
419 "description": tool.description(),
420 "parameters": tool.schema(),
421 }
422 })
423}
424
425pub(crate) type ToolRef = Arc<dyn Tool>;
426
427#[derive(Clone, Default)]
428pub struct ToolRegistry {
429 tools: HashMap<String, ToolRef>,
430}
431
432impl ToolRegistry {
433 pub fn register(&mut self, tool: impl Tool + 'static) {
434 self.tools.insert(tool.name().to_string(), Arc::new(tool));
435 }
436
437 pub fn register_arc(&mut self, tool: Arc<dyn Tool>) {
438 self.tools.insert(tool.name().to_string(), tool);
439 }
440
441 /// Remove a tool from the registry by name.
442 pub fn remove(&mut self, name: &str) {
443 self.tools.remove(name);
444 }
445
446 pub fn get(&self, name: &str) -> Option<ToolRef> {
447 self.tools.get(name).cloned()
448 }
449
450 pub fn definitions(&self) -> Vec<Value> {
451 let mut tools: Vec<_> = self.tools.values().collect();
452 tools.sort_by_key(|t| t.name());
453 tools
454 .into_iter()
455 .map(|t| render_tool_definition(t.as_ref()))
456 .collect()
457 }
458
459 /// Return tool definitions filtered by [`ToolExposure`].
460 ///
461 /// - `Direct` tools are always included.
462 /// - `Deferred` tools are included only when `should_activate(ctx)` returns `true`.
463 /// - `Hidden` tools are never included.
464 pub fn definitions_filtered(&self, ctx: &ActivationContext) -> Vec<Value> {
465 let mut tools: Vec<_> = self.tools.values().collect();
466 tools.sort_by_key(|t| t.name());
467
468 // Single sequential pass: collect Direct names first, then evaluate
469 // Deferred tools in sorted order. Each Deferred tool sees the names of
470 // all Direct + previously-activated Deferred tools in ctx.current_tools.
471 // Evaluation order matters: a later Deferred tool can see an earlier one,
472 // but not vice versa.
473 let direct_names: Vec<String> = tools
474 .iter()
475 .filter(|t| t.exposure() == ToolExposure::Direct)
476 .map(|t| t.name().to_string())
477 .collect();
478
479 let mut activated_names = direct_names.clone();
480 for t in &tools {
481 if t.exposure() == ToolExposure::Deferred {
482 let mut ctx_with_tools = ctx.clone();
483 ctx_with_tools.current_tools = activated_names.clone();
484 if t.should_activate(&ctx_with_tools) {
485 activated_names.push(t.name().to_string());
486 }
487 }
488 }
489
490 tools
491 .into_iter()
492 .filter(|t| match t.exposure() {
493 ToolExposure::Direct => true,
494 ToolExposure::Deferred => activated_names.contains(&t.name().to_string()),
495 ToolExposure::Hidden => false,
496 })
497 .map(|t| render_tool_definition(t.as_ref()))
498 .collect()
499 }
500
501 pub fn len(&self) -> usize {
502 self.tools.len()
503 }
504
505 pub fn is_empty(&self) -> bool {
506 self.tools.is_empty()
507 }
508
509 /// Collect metadata for every registered tool, sorted by name.
510 ///
511 /// This is the preferred introspection API for consumers — it returns a
512 /// stable `ToolMetadata` struct per tool instead of having callers parse
513 /// the LLM-facing JSON definitions.
514 pub fn metadatas(&self) -> Vec<ToolMetadata> {
515 let mut list: Vec<_> = self.tools.values().map(|tool| tool.metadata()).collect();
516 list.sort_by(|a, b| a.name.cmp(&b.name));
517 list
518 }
519}
520
521#[cfg(test)]
522mod tests;