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(crate) mod schema_budget;
17
18mod activate_tool;
19mod activation;
20mod deferred;
21
22pub use activate_tool::ActivateTool;
23pub use activation::ToolActivation;
24pub use deferred::DeferredTool;
25
26pub use auto_continue::AutoContinueTool;
27pub use update_plan::UpdatePlanTool;
28
29pub use policy::{DenyAllToolPolicy, ToolDecision, ToolPolicy};
30
31// Re-export pure types from agent-types
32pub use agent_types::{
33 ActivationContext, Content, ToolExposure, ToolMetadata, content_details, content_images,
34 content_text,
35};
36
37/// Per-call execution-clock control, shared between the tool and the
38/// pipeline's timeout ([`crate::engine::DefaultPipeline`]).
39///
40/// The timeout measures **active** execution time: stretches spent waiting on
41/// a human are excluded ([`ExecClock::pause`]), so a tool that asks the user a
42/// question is never killed by its own execution budget while the user is
43/// still reading. Every [`ToolContext`] built per call gets a fresh clock —
44/// pauses never leak into a later call.
45#[derive(Clone, Default)]
46pub struct ExecClock {
47 inner: Arc<ExecClockInner>,
48}
49
50#[derive(Default)]
51struct ExecClockInner {
52 state: std::sync::Mutex<ExecClockState>,
53}
54
55#[derive(Default)]
56struct ExecClockState {
57 /// Live pause guards. Non-zero ⇒ the clock is paused (nesting supported).
58 live: usize,
59 /// When the current pause began (`Some` while paused).
60 started: Option<std::time::Instant>,
61 /// Paused time already banked from closed pauses.
62 total: std::time::Duration,
63}
64
65impl ExecClock {
66 /// Hold the clock paused for as long as the returned guard lives.
67 /// Nesting is fine: the clock resumes when the outermost guard drops.
68 pub fn pause(&self) -> ExecPauseGuard {
69 let mut state = self.lock();
70 state.live += 1;
71 if state.live == 1 {
72 state.started = Some(std::time::Instant::now());
73 }
74 ExecPauseGuard {
75 clock: self.clone(),
76 }
77 }
78
79 /// Paused time so far, including the open pause if any. The pipeline's
80 /// deadline is `start + budget + paused_total()`, so a pause pushes the
81 /// timeout out by exactly the time the human spent.
82 pub fn paused_total(&self) -> std::time::Duration {
83 let state = self.lock();
84 state.total
85 + state
86 .started
87 .map_or(std::time::Duration::ZERO, |s| s.elapsed())
88 }
89
90 fn resume(&self) {
91 let mut state = self.lock();
92 state.live = state.live.saturating_sub(1);
93 if state.live == 0
94 && let Some(started) = state.started.take()
95 {
96 state.total += started.elapsed();
97 }
98 }
99
100 fn lock(&self) -> std::sync::MutexGuard<'_, ExecClockState> {
101 // A panic while holding the clock must not poison it — worst case the
102 // accounting is slightly off, never "the tool can never time out".
103 self.inner
104 .state
105 .lock()
106 .unwrap_or_else(std::sync::PoisonError::into_inner)
107 }
108}
109
110/// RAII pause handle — see [`ExecClock::pause`].
111pub struct ExecPauseGuard {
112 clock: ExecClock,
113}
114
115impl Drop for ExecPauseGuard {
116 fn drop(&mut self) {
117 self.clock.resume();
118 }
119}
120
121#[derive(Clone)]
122pub struct ToolContext {
123 pub session_id: SessionId,
124 /// Channel for sending user-space events (progress, sub-agent, structured).
125 /// Tools should use `emit_user_event()` or `emit_progress()`.
126 pub user_event_tx: mpsc::UnboundedSender<UserEvent>,
127 pub llm_client: Option<Arc<dyn llm_trait::LlmProvider>>,
128 pub session_store: Option<Arc<dyn SessionStore>>,
129 /// Language preference for tool output.
130 /// Defaults to `Language::En` if not set.
131 pub language: crate::types::Language,
132 /// Cancellation token for checking if the operation should be cancelled.
133 pub cancel_token: tokio_util::sync::CancellationToken,
134 /// Output budget for this call, in characters (set from the engine's
135 /// `max_tool_output_chars`). Tools that can return large results (e.g.
136 /// `read_file`) should self-truncate to this bound and mark the cut, so
137 /// the engine's hard reject (§6.5) never fires for a paginated read.
138 pub max_output_chars: Option<usize>,
139 /// Execution clock for this call — see [`ExecClock`]. Pause it while the
140 /// tool waits on a human ([`ToolContext::pause_execution_clock`]).
141 pub exec_clock: ExecClock,
142 /// Set by [`ToolContext::mark_waiting_for_human`] when the call left a
143 /// human step pending (a pick, a confirmation) instead of finishing the
144 /// work. The engine folds it into the run state after the call.
145 pub waiting_for_human: Arc<AtomicBool>,
146 /// Internal runtime event bus (framework tools emit `RuntimeEvent`s here).
147 /// `pub(crate)` — engine-internal; user tools should use `emit_user_event()`.
148 pub(crate) event_bus: crate::engine::EventBus,
149}
150
151impl ToolContext {
152 /// Pause this call's execution clock for as long as the guard lives.
153 ///
154 /// Call this while waiting on a human (a confirmation popup, a login):
155 /// the pipeline's tool timeout does not count the paused stretch.
156 pub fn pause_execution_clock(&self) -> ExecPauseGuard {
157 self.exec_clock.pause()
158 }
159
160 /// Mark that this call left a human step pending (a design-canvas screen
161 /// awaiting a pick, a confirmation). The engine records it on the run: a
162 /// run that ends here is *waiting for the user*, not an incomplete task,
163 /// so the guard must not nudge "continue working" over the human's turn.
164 pub fn mark_waiting_for_human(&self) {
165 self.waiting_for_human.store(true, Ordering::Relaxed);
166 }
167
168 /// Send a user-space event (progress, sub-agent forwarding, structured data).
169 ///
170 /// Dual-write: the event goes to `user_event_tx` (the tool select arm
171 /// renders it in real time) and to the event bus for external subscribers
172 /// (bridge remote clients, persistence). The bus copy carries `agent_id:
173 /// None` — the self-echo marker — so bus loopback drops it instead of
174 /// re-rendering (see `crate::engine::runtime::is_self_echo_user_event`).
175 pub fn emit_user_event(&self, event: UserEvent) {
176 let _ = self.user_event_tx.send(event.clone());
177 self.event_bus.emit(RuntimeEvent::UserEvent {
178 session_id: self.session_id.clone(),
179 event,
180 agent_id: None,
181 trace_id: None,
182 });
183 }
184
185 /// Convenience: send a progress event with text.
186 pub fn emit_progress(&self, text: impl Into<String>) {
187 self.emit_user_event(UserEvent::Progress { text: text.into() });
188 }
189
190 /// Convenience: emit a partial result during long-running tool execution.
191 /// `is_partial: true` means more output is coming; `false` means final.
192 pub fn emit_partial_result(
193 &self,
194 tool_call_id: &str,
195 content: impl Into<String>,
196 is_partial: bool,
197 ) {
198 self.emit_user_event(UserEvent::ToolPartialResult {
199 tool_call_id: tool_call_id.to_string(),
200 content: content.into(),
201 is_partial,
202 });
203 }
204
205 /// Test-only constructor: a `ToolContext` with a disconnected event
206 /// channel and no LLM/session backends. Lets downstream tests drop their
207 /// bespoke `dummy_ctx()` helpers.
208 pub fn for_test() -> Self {
209 let (tx, _rx) = mpsc::unbounded_channel();
210 ToolContext {
211 session_id: SessionId::new(0),
212 user_event_tx: tx,
213 llm_client: None,
214 session_store: None,
215 language: crate::types::Language::En,
216 cancel_token: tokio_util::sync::CancellationToken::new(),
217 max_output_chars: None,
218 exec_clock: ExecClock::default(),
219 waiting_for_human: Arc::new(AtomicBool::new(false)),
220 event_bus: crate::engine::EventBus::new(1),
221 }
222 }
223
224 /// Host-side constructor for host-initiated tool execution outside the
225 /// engine loop (e.g. a REPL driving a tool through the same approval path
226 /// as the engine). User events are accepted but dropped — there is no
227 /// engine event loop to render them.
228 pub fn new(
229 session_id: SessionId,
230 llm_client: Option<Arc<dyn crate::llm_trait::LlmProvider>>,
231 session_store: Option<Arc<dyn SessionStore>>,
232 cancel_token: tokio_util::sync::CancellationToken,
233 ) -> Self {
234 let (tx, _rx) = mpsc::unbounded_channel();
235 ToolContext {
236 session_id,
237 user_event_tx: tx,
238 llm_client,
239 session_store,
240 language: crate::types::Language::En,
241 cancel_token,
242 max_output_chars: None,
243 exec_clock: ExecClock::default(),
244 waiting_for_human: Arc::new(AtomicBool::new(false)),
245 event_bus: crate::engine::EventBus::new(1),
246 }
247 }
248}
249
250#[async_trait]
251pub trait Tool: Send + Sync {
252 fn name(&self) -> &'static str;
253 /// Human-readable description of what this tool does and when to use it.
254 fn description(&self) -> &'static str;
255 /// JSON Schema for the tool's input arguments (MCP `inputSchema` shape,
256 /// without the provider envelope).
257 fn schema(&self) -> Value;
258 async fn call(&self, args: &Value, ctx: &ToolContext) -> AgentResult<Vec<Content>>;
259
260 /// Timeout for this tool in milliseconds.
261 ///
262 /// Returns `Some(ms)` to enforce a timeout, or `None` to use the
263 /// framework's default timeout from `ToolConfig.default_tool_timeout_ms`.
264 /// Tools that need more or less time should override this method.
265 fn timeout_ms(&self) -> Option<u64> {
266 None // Use framework default
267 }
268
269 /// Execution budget for a specific call, derived from its `args`.
270 ///
271 /// The pipeline watchdog consults this before arming: `Some(ms)` overrides
272 /// [`Tool::timeout_ms`] for this invocation, and `Some(0)` means unbounded
273 /// (no watchdog — the tool enforces its own limits, or the call is
274 /// fire-and-forget). `None` falls back to [`Tool::timeout_ms`] / config.
275 ///
276 /// Tools whose arguments carry a per-call timeout (e.g. `timeout_ms`)
277 /// MUST surface it here. Otherwise the pipeline arms its own watchdog
278 /// from the tool-level default and can kill a call that the tool was
279 /// explicitly promised more time for (session 20261018_7844215b: a
280 /// 660s `execute_command` budget was cut at the 600s framework default).
281 fn call_timeout_ms(&self, _args: &Value) -> Option<u64> {
282 self.timeout_ms()
283 }
284
285 /// Machine-readable metadata for tool introspection.
286 ///
287 /// The default implementation derives `name` and `description` from
288 /// [`Tool::name`] and [`Tool::description`], sets `origin` to `"custom"`,
289 /// and leaves `requirements` empty. Tool authors are encouraged to
290 /// override this to provide an accurate `origin` and `version`.
291 fn metadata(&self) -> ToolMetadata {
292 ToolMetadata {
293 name: self.name().to_string(),
294 description: self.description().to_string(),
295 origin: "custom".to_string(),
296 version: "unknown".to_string(),
297 requirements: vec![],
298 }
299 }
300
301 /// Visibility level for this tool. Default: `Direct` (always visible).
302 ///
303 /// Override to return `Deferred` (conditionally visible) or `Hidden`
304 /// (never visible to the model). `Deferred` tools are only included
305 /// when [`Tool::should_activate`] returns `true`.
306 fn exposure(&self) -> ToolExposure {
307 ToolExposure::Direct
308 }
309
310 /// Activation condition for `Deferred` tools.
311 ///
312 /// Called once per turn for each `Deferred` tool. Return `true` to
313 /// include this tool in the model's tool list this turn. Ignored for
314 /// `Direct` and `Hidden` tools.
315 ///
316 /// The default makes `Deferred` mean what it says: open only once the model
317 /// has asked for this tool by name, via
318 /// [`crate::tool::ActivateTool`]. `ctx.current_tools` carries the names the
319 /// session has opened so far. Override only to auto-open on something else
320 /// — a workspace shape, a config flag — and say so in the override.
321 fn should_activate(&self, ctx: &ActivationContext) -> bool {
322 ctx.current_tools.iter().any(|n| n == self.name())
323 }
324}
325
326#[async_trait]
327pub trait TypedTool: Send + Sync {
328 type Args: serde::de::DeserializeOwned + schemars::JsonSchema;
329 type Output: serde::Serialize;
330
331 fn name(&self) -> &'static str;
332 fn description(&self) -> &'static str;
333 async fn call_typed(&self, args: Self::Args, ctx: &ToolContext) -> AgentResult<Self::Output>;
334
335 fn format_output(&self, output: Self::Output) -> Content {
336 // A `String` output is emitted verbatim; any other serializable type is
337 // rendered as JSON. This avoids `serde_json::to_string` wrapping a plain
338 // string in literal double quotes (`hello` → `"hello"`), which would leak
339 // quotes into the LLM-visible tool result.
340 match serde_json::to_value(&output) {
341 Ok(serde_json::Value::String(s)) => Content::text(s),
342 Ok(other) => Content::text(other.to_string()),
343 Err(_) => Content::text(String::new()),
344 }
345 }
346
347 /// Machine-readable origin of this tool (crate name, `"agent-base"`, or `"custom"`).
348 fn origin(&self) -> &'static str {
349 "custom"
350 }
351
352 /// Crate/package version, or `"unknown"` when built outside a crate.
353 fn version(&self) -> &'static str {
354 "unknown"
355 }
356
357 /// Visibility level for this tool. Default: `Direct` (always visible).
358 fn exposure(&self) -> ToolExposure {
359 ToolExposure::Direct
360 }
361
362 /// Activation condition for `Deferred` tools. Ignored for `Direct`/`Hidden`.
363 /// Defaults to the same opt-in rule as [`Tool::should_activate`].
364 fn should_activate(&self, ctx: &ActivationContext) -> bool {
365 ctx.current_tools.iter().any(|n| n == self.name())
366 }
367}
368
369#[async_trait]
370impl<T: TypedTool + Send + Sync + 'static> Tool for T {
371 fn name(&self) -> &'static str {
372 TypedTool::name(self)
373 }
374
375 fn description(&self) -> &'static str {
376 TypedTool::description(self)
377 }
378
379 fn schema(&self) -> Value {
380 // Generate a provider-safe JSON Schema: Draft 7 (not 2020-12), with
381 // nested subschemas inlined (no `$ref`/`$defs`/`/definitions`) and no
382 // root `$schema`/meta-schema key. OpenAI-compatible function-calling
383 // rejects `$ref` and 2020-12's `$defs`, so the default 2020-12 output
384 // would break any `Args` containing a nested enum or struct.
385 let settings = schemars::generate::SchemaSettings::draft07().with(|s| {
386 s.inline_subschemas = true;
387 s.meta_schema = None;
388 });
389 let generator = schemars::SchemaGenerator::new(settings);
390 let schema = generator.into_root_schema_for::<T::Args>();
391 serde_json::to_value(schema).unwrap_or(Value::Null)
392 }
393
394 fn metadata(&self) -> ToolMetadata {
395 ToolMetadata {
396 name: self.name().to_string(),
397 description: self.description().to_string(),
398 origin: self.origin().to_string(),
399 version: self.version().to_string(),
400 requirements: vec![],
401 }
402 }
403
404 fn exposure(&self) -> ToolExposure {
405 TypedTool::exposure(self)
406 }
407
408 fn should_activate(&self, ctx: &ActivationContext) -> bool {
409 TypedTool::should_activate(self, ctx)
410 }
411
412 async fn call(&self, args: &Value, ctx: &ToolContext) -> AgentResult<Vec<Content>> {
413 let typed_args: T::Args =
414 serde_json::from_value(args.clone()).map_err(|e| AgentError::ToolArgsInvalid {
415 name: self.name().to_string(),
416 // Carry the serde detail ("missing field `task` …") — the model
417 // can only fix what the message names. Same "{e} (args: …)"
418 // shape as the phase1 JSON-parse failure site (tool_engine.rs)
419 // and the contract asserted in recovery.rs.
420 raw: format!("{e} (args: {args})"),
421 })?;
422 let output = self.call_typed(typed_args, ctx).await?;
423 Ok(vec![self.format_output(output)])
424 }
425}
426
427/// Render a single tool's definition into the OpenAI function-calling
428/// envelope. Tools only provide `name`/`description`/`schema`; the envelope is
429/// assembled here at the LLM boundary (Anthropic gets its own renderer, and
430/// tool authors stay protocol-agnostic).
431///
432/// The schema passes through [`schema_budget`] on the way out. That is the
433/// only place every definition is guaranteed to cross, so it is where a
434/// per-tool ceiling belongs — see the module docs for why it is best-effort.
435pub fn render_tool_definition(tool: &dyn Tool) -> Value {
436 let mut parameters = tool.schema();
437 match schema_budget::fit_schema_to_budget(&mut parameters) {
438 schema_budget::FitOutcome::Untouched => {}
439 schema_budget::FitOutcome::Compressed(pass) => {
440 tracing::info!(
441 tool = tool.name(),
442 pass,
443 "tool schema compressed to fit the request budget"
444 );
445 }
446 schema_budget::FitOutcome::OverBudget => {
447 // Kept on purpose: a tool the model cannot see, it routes around.
448 tracing::warn!(
449 tool = tool.name(),
450 budget = schema_budget::MAX_TOOL_SCHEMA_BYTES,
451 "tool schema exceeds the request budget after every pass; sent as-is"
452 );
453 }
454 }
455 json!({
456 "type": "function",
457 "function": {
458 "name": tool.name(),
459 "description": tool.description(),
460 "parameters": parameters,
461 }
462 })
463}
464
465pub(crate) type ToolRef = Arc<dyn Tool>;
466
467#[derive(Clone, Default)]
468pub struct ToolRegistry {
469 tools: HashMap<String, ToolRef>,
470}
471
472impl ToolRegistry {
473 pub fn register(&mut self, tool: impl Tool + 'static) {
474 self.tools.insert(tool.name().to_string(), Arc::new(tool));
475 }
476
477 pub fn register_arc(&mut self, tool: Arc<dyn Tool>) {
478 self.tools.insert(tool.name().to_string(), tool);
479 }
480
481 /// Remove a tool from the registry by name.
482 pub fn remove(&mut self, name: &str) {
483 self.tools.remove(name);
484 }
485
486 pub fn get(&self, name: &str) -> Option<ToolRef> {
487 self.tools.get(name).cloned()
488 }
489
490 pub fn definitions(&self) -> Vec<Value> {
491 let mut tools: Vec<_> = self.tools.values().collect();
492 tools.sort_by_key(|t| t.name());
493 tools
494 .into_iter()
495 .map(|t| render_tool_definition(t.as_ref()))
496 .collect()
497 }
498
499 /// Return tool definitions filtered by [`ToolExposure`].
500 ///
501 /// - `Direct` tools are always included.
502 /// - `Deferred` tools are included only when `should_activate(ctx)` returns `true`.
503 /// - `Hidden` tools are never included.
504 pub fn definitions_filtered(&self, ctx: &ActivationContext) -> Vec<Value> {
505 let mut tools: Vec<_> = self.tools.values().collect();
506 tools.sort_by_key(|t| t.name());
507
508 // Single sequential pass: collect Direct names first, then evaluate
509 // Deferred tools in sorted order. Each Deferred tool sees the names of
510 // all Direct + previously-activated Deferred tools in ctx.current_tools.
511 // Evaluation order matters: a later Deferred tool can see an earlier one,
512 // but not vice versa.
513 //
514 // `ctx.current_tools` arrives seeded with the session's openings (see
515 // [`ToolActivation`]); the default `should_activate` reads them from
516 // here, so they must be in the pool before the first Deferred tool is
517 // asked.
518 let direct_names: Vec<String> = tools
519 .iter()
520 .filter(|t| t.exposure() == ToolExposure::Direct)
521 .map(|t| t.name().to_string())
522 .collect();
523
524 let mut activated_names = direct_names.clone();
525 for name in &ctx.current_tools {
526 if !activated_names.contains(name) {
527 activated_names.push(name.clone());
528 }
529 }
530 for t in &tools {
531 if t.exposure() == ToolExposure::Deferred {
532 let mut ctx_with_tools = ctx.clone();
533 ctx_with_tools.current_tools = activated_names.clone();
534 if t.should_activate(&ctx_with_tools) {
535 activated_names.push(t.name().to_string());
536 }
537 }
538 }
539
540 tools
541 .into_iter()
542 .filter(|t| match t.exposure() {
543 ToolExposure::Direct => true,
544 ToolExposure::Deferred => activated_names.contains(&t.name().to_string()),
545 ToolExposure::Hidden => false,
546 })
547 .map(|t| render_tool_definition(t.as_ref()))
548 .collect()
549 }
550
551 pub fn len(&self) -> usize {
552 self.tools.len()
553 }
554
555 pub fn is_empty(&self) -> bool {
556 self.tools.is_empty()
557 }
558
559 /// Collect metadata for every registered tool, sorted by name.
560 ///
561 /// This is the preferred introspection API for consumers — it returns a
562 /// stable `ToolMetadata` struct per tool instead of having callers parse
563 /// the LLM-facing JSON definitions.
564 pub fn metadatas(&self) -> Vec<ToolMetadata> {
565 let mut list: Vec<_> = self.tools.values().map(|tool| tool.metadata()).collect();
566 list.sort_by(|a, b| a.name.cmp(&b.name));
567 list
568 }
569}
570
571#[cfg(test)]
572mod tests;