defect_agent/tool.rs
1//! Tool abstraction.
2//!
3//! Both builtin tools (`defect-tools`) and MCP adapters (`defect-mcp`) integrate
4//! into the agent main loop by implementing the [`Tool`] trait.
5//!
6//! ## ACP alignment
7//!
8//! [`Tool::describe`] and [`ToolEvent::Progress`] / [`ToolEvent::Completed`]
9//! directly reuse ACP's [`ToolCallUpdateFields`] to avoid duplicating fields.
10//! The main loop enriches the fields produced by the tool with metadata such as
11//! [`ToolCallId`] and [`raw_input`], then forwards them as `session/update` and
12//! `session/request_permission`.
13//!
14//! [`ToolCallId`]: agent_client_protocol_schema::ToolCallId
15//! [`ToolCallUpdateFields`]: agent_client_protocol_schema::ToolCallUpdateFields
16//! [`raw_input`]: agent_client_protocol_schema::ToolCallUpdateFields::raw_input
17
18use std::path::Path;
19use std::pin::Pin;
20use std::sync::Arc;
21
22use agent_client_protocol_schema::{ToolCallId, ToolCallUpdateFields};
23use futures::Stream;
24use futures::future::BoxFuture;
25use serde::{Deserialize, Serialize};
26use thiserror::Error;
27use tokio_util::sync::CancellationToken;
28
29use crate::error::BoxError;
30use crate::fs::FsBackend;
31use crate::http::HttpClient;
32use crate::session::EventEmitter;
33use crate::shell::ShellBackend;
34
35mod background_tasks;
36mod goal_done;
37mod skill;
38mod spawn_agent;
39pub use background_tasks::{CancelBackgroundTaskTool, InspectBackgroundTaskTool};
40pub use goal_done::{GOAL_DONE_TOOL_NAME, GoalDoneTool};
41pub use skill::{SkillEntry, SkillTool, SkillTriggers};
42pub use spawn_agent::{SpawnAgentTool, SubagentProfile};
43
44/// Tool's "public face": describes the parameter shape without any execution capability.
45///
46/// [`crate::llm::CompletionRequest::tools`] accepts `Vec<ToolSchema>`.
47/// Providers don't hold `dyn Tool`; they serialize schemas into wire JSON.
48#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
49pub struct ToolSchema {
50 pub name: String,
51 pub description: String,
52 /// JSON Schema for the parameters. Uses a subset of Draft 2020-12 (the exact subset
53 /// and escaping rules are documented in `tool-trait.md`).
54 pub input_schema: serde_json::Value,
55}
56
57/// Self-description of a tool call, directly mapping to ACP's [`ToolCallUpdateFields`].
58///
59/// Purpose (the same data drives three ACP messages):
60/// - First push of a `ToolCall` (`status = Pending`)
61/// - The `tool_call` field in a `RequestPermission` request
62/// - Baseline for incremental updates via [`ToolEvent::Progress`]
63///
64/// Field conventions:
65/// - `tool_call_id` is not in this struct; it is assigned uniformly by the main loop
66/// (using the LLM's `tool_use_id` or a self-generated UUID). The tool does not care
67/// about it.
68/// - `raw_input` is filled by the main loop with the original args. Tool implementations
69/// must not set it themselves, to avoid divergence from the real parameters on the
70/// wire.
71/// - `status` is inferred from the [`ToolEvent`] variant: `Progress` → `InProgress`,
72/// `Completed` → `Completed`, `Failed` → `Failed`. Tools must not set it themselves.
73///
74/// [`ToolCallUpdateFields`]: agent_client_protocol_schema::ToolCallUpdateFields
75#[derive(Debug, Clone)]
76pub struct ToolCallDescription {
77 pub fields: ToolCallUpdateFields,
78}
79
80/// Safety level for a tool.
81///
82/// This is only a **hint** fed to the external sandbox policy; the final Allow / Deny /
83/// Ask decision is made by the policy (in combination with user configuration, prior
84/// authorization, etc.). The trait itself does not enforce any policy.
85///
86/// The `serde` representation uses `snake_case` (`read_only` / `mutating` / `destructive`
87/// / `network`), so that `defect-config` can deserialize it directly from TOML in hook
88/// matchers and similar contexts.
89#[non_exhaustive]
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
91#[serde(rename_all = "snake_case")]
92pub enum SafetyClass {
93 /// Read-only: list directories, read files, query metadata.
94 ReadOnly,
95 /// Mutating: writes files or modifies state; side effects may or may not be
96 /// reversible.
97 Mutating,
98 /// Destructive: deleting files, moving, executing commands.
99 Destructive,
100 /// Outbound network: HTTP / DNS / any remote I/O.
101 Network,
102}
103
104/// Elements of the event stream produced by [`Tool::execute`].
105///
106/// Terminal semantics: the stream contains **at most one** [`ToolEvent::Completed`] or
107/// [`ToolEvent::Failed`], and it must be the last event in the stream. When the main
108/// loop encounters a terminal event, it considers the tool call finished and does not
109/// consume any further elements.
110#[non_exhaustive]
111#[derive(Debug)]
112pub enum ToolEvent {
113 /// Progress delta: the main loop forwards this as a `tool_call_update` in an ACP
114 /// `session/update`.
115 /// Contains only the fields that changed, matching the "patch" semantics of
116 /// [`ToolCallUpdateFields`].
117 ///
118 /// [`ToolCallUpdateFields`]: agent_client_protocol_schema::ToolCallUpdateFields
119 Progress(ToolCallUpdateFields),
120
121 /// Successful completion. `fields` contains the remaining final-state fields (e.g.,
122 /// final content, locations, raw_output); the main loop is responsible for setting
123 /// `status` to `Completed`.
124 Completed(ToolCallUpdateFields),
125
126 /// Terminal failure. Carries the Rust-side error so the caller can retry or log it;
127 /// when mapping to ACP, the main loop sets `status` to `Failed` and places the
128 /// [`ToolError`] text into `content`.
129 Failed(ToolError),
130}
131
132/// Event stream for [`Tool::execute`]. Type-erased so that `dyn Tool` can be used
133/// directly.
134pub type ToolStream = Pin<Box<dyn Stream<Item = ToolEvent> + Send>>;
135
136/// The execution environment injected into [`Tool::execute`].
137///
138/// An explicit struct rather than environment variables or thread-locals, making it easy
139/// to construct in tests and avoiding implicit global state. Fields are marked
140/// `non_exhaustive` to allow future additions (sandbox handles, ACP backchannels, etc.)
141/// without breaking existing implementations.
142#[non_exhaustive]
143pub struct ToolContext<'a> {
144 /// The default working directory for the tool (typically the ACP session's `cwd`).
145 pub cwd: &'a Path,
146 /// Cancellation token: triggered by upstream `session/cancel`, user Ctrl+C, timeout,
147 /// etc.
148 /// Tool implementations should check `cancel.is_cancelled()` at long loops or await
149 /// points and exit as soon as possible.
150 pub cancel: CancellationToken,
151 /// Filesystem backend. The `fs` tool family (`read_file` / `write_file` /
152 /// `edit_file`) reads and writes files through it. During assembly, `defect-acp`
153 /// selects either `LocalFsBackend` or `AcpFsBackend` based on the client-negotiated
154 /// [`FileSystemCapabilities`]; tool implementations are completely unaware of this.
155 ///
156 /// Uses [`Arc`] instead of a borrow: `Tool::execute` returns a `'static` future /
157 /// stream, and tools typically `clone` the fs into async tasks. A borrow cannot
158 /// survive across `.await`.
159 ///
160 /// [`FileSystemCapabilities`]: agent_client_protocol_schema::FileSystemCapabilities
161 pub fs: Arc<dyn FsBackend>,
162 /// Shell execution backend. The `bash` tool uses it to create a terminal and run
163 /// commands; during assembly, `defect-acp` selects either `LocalShellBackend` or
164 /// `AcpShellBackend` based on the client-negotiated [`ClientCapabilities::terminal`],
165 /// and tool implementations are unaware of the choice.
166 ///
167 /// Same `Arc` trade-off as `fs` — `Tool::execute` returns a `'static` future.
168 ///
169 /// [`ClientCapabilities::terminal`]: agent_client_protocol_schema::ClientCapabilities
170 pub shell: Arc<dyn ShellBackend>,
171 /// HTTP fetch backend. The `fetch` tool uses it to perform network reads; it is set
172 /// up at the CLI entry point (constructed from `HttpClientConfig` as a process-level
173 /// [`HttpClient`] instance and reused). Tool implementations receive an [`Arc`]
174 /// clone; `Tool::execute` is a `'static` future, so borrowing cannot survive across
175 /// await points.
176 pub http: Arc<dyn HttpClient>,
177 /// The model id selected for the current turn. Most tools do not need this; the
178 /// `spawn_agent` sub-agent tool uses it to "fall back the model to the parent
179 /// session's current selection" — `ToolContext` does not carry a provider registry,
180 /// but carrying this string is enough for `spawn_agent` to call `entry_for_model` on
181 /// its own captured registry to resolve the provider the parent is currently using.
182 /// Populated from `config.model` by [`TurnRunner`](crate::session::TurnRunner) when
183 /// constructing the context.
184 pub current_model: &'a str,
185 /// The provider vendor selected for the current turn. Together with
186 /// [`Self::current_model`] this forms a `(vendor, model)` selection pair — when a
187 /// `spawn_agent` sub-agent falls back to the parent's choice, it uses this pair to
188 /// call `entry_for` on the registry for exact resolution (avoiding provider
189 /// mis-selection when multiple gateways serve the same model name). An empty string
190 /// means the value was not injected (legacy/test paths); in that case `spawn_agent`
191 /// falls back to looking up the first entry by bare model id. Populated by the turn
192 /// runner from `config.provider` when constructing the context.
193 pub current_provider: &'a str,
194 /// Session-level background task handle. When `Some`, tools can fire-and-forget a
195 /// task that outlives the current turn (primarily for `spawn_agent {
196 /// run_in_background: true }`); `None` means the context does not support background
197 /// execution (e.g., nested sub-agent turns or tests), and tools should fall back to
198 /// synchronous execution.
199 ///
200 /// Uses an owned [`Arc`]-backed handle instead of a borrow: `Tool::execute` returns a
201 /// `'static` future, and a borrow cannot survive across await. Injected by the
202 /// top-level [`TurnRunner`](crate::session::TurnRunner) when constructing the
203 /// context; not injected for nested sub-agent turns (structurally prevents background
204 /// tasks from spawning themselves).
205 pub background: Option<crate::session::BackgroundTasks>,
206 /// Subagent event bridge: when `Some`, a tool can wrap internally spawned sub-turn
207 /// events as [`crate::event::AgentEvent::Subagent`] and forward them back to the
208 /// parent session's event stream for nested observability display. Currently only
209 /// used by `spawn_agent`. Injected by the turn runner in `session::turn` for each
210 /// tool according to its [`ToolCallId`] — **injected for both top-level and nested
211 /// sub-agent turns** (recursive bridging), with the mount point expressed by
212 /// [`SubagentBridge::parent_tool_call_id`].
213 pub subagent_bridge: Option<SubagentBridge>,
214 /// The active sandbox policy for this turn snapshot. `spawn_agent` uses it to pass
215 /// the parent's current real policy to child agents — after a `session/set_mode`
216 /// switch, newly created turns propagate the new policy through this field, so child
217 /// agents never see a stale process-level default. When `None`, `spawn_agent` falls
218 /// back to the policy captured at construction time (testing / uninjected scenarios).
219 /// Most tools ignore this field.
220 pub policy: Option<Arc<dyn crate::policy::SandboxPolicy>>,
221 /// Shared state for the `--goal` goal-driven loop. When `Some`, this session runs in
222 /// goal mode; the `goal_done` tool calls [`crate::session::GoalState::mark_reached`]
223 /// to set the flag, and the `goal-gate` hook uses it to decide whether to release or
224 /// extend a turn when it voluntarily stops. `None` means non-goal mode (the default);
225 /// the `goal_done` tool is not registered and this field is never read.
226 pub goal: Option<Arc<crate::session::GoalState>>,
227 /// How many more layers of subagent can be dispatched from the current layer. The
228 /// top-level turn starts at the configured initial limit; `spawn_agent` decrements it
229 /// by one when injecting a nested turn for a child agent. `0` means the child agent
230 /// cannot obtain the `spawn_agent` tool (depth exhausted, structurally preventing
231 /// further recursion) — replacing the old hard-coded "whitelist never contains
232 /// `spawn_agent`". This is a functional gate, unrelated to observability, so it is
233 /// independent of the optional [`Self::subagent_bridge`] and also takes effect in
234 /// test / no-bridge scenarios. Defaults to `0` (most conservative: no explicit
235 /// injection means no dispatch; the top-level turn must explicitly use
236 /// [`Self::with_subagent_depth`]).
237 pub subagent_depth: u32,
238}
239
240/// A handle for bridging sub-turn events (spawned internally by a tool) back into the
241/// parent session's event stream.
242///
243/// Holds the parent session's [`EventEmitter`] and the [`ToolCallId`] that initiated this
244/// tool invocation. `Clone` is cheap (internally `Arc` + small string).
245///
246/// ## Recursive bridging: each layer only prepends its own id
247///
248/// The full ancestor chain is not stored here — it is accumulated incrementally as events
249/// **bubble upward** through each layer's bridge. The bridge subscriber (e.g.,
250/// `spawn_agent`'s `bridge_task`) at each layer:
251/// - Receives a **leaf** event from the sub-turn → wraps it as
252/// `Subagent{ ancestor_path: [parent_tool_call_id], agent_type: <this layer's profile>,
253/// inner: leaf }`;
254/// - Receives an **already** `Subagent` (from a deeper layer, already carrying a partial
255/// chain) → **prepends** `parent_tool_call_id` to the head of its `ancestor_path`,
256/// leaving `inner` leaf and deeper `agent_type` unchanged.
257///
258/// Thus after passing through N layers of bridging, `ancestor_path` is exactly the
259/// complete id chain from the top layer down to the leaf. Each layer only needs to know
260/// its own hop — this lets frontend, backend, and arbitrary depths share the same logic.
261///
262/// The recursive **depth gate** is not here — it is functional and must always apply
263/// (including in non-observability / test scenarios), so it lives in the separate
264/// [`ToolContext::subagent_depth`] field rather than in this optional bridge.
265#[derive(Clone)]
266pub struct SubagentBridge {
267 /// Event bus of the parent session. Wrapped [`crate::event::AgentEvent::Subagent`]
268 /// events are emitted here.
269 pub parent_events: Arc<EventEmitter>,
270 /// The tool call ID that spawned this subagent (the corresponding tool span in the
271 /// parent trace). The bridge prepends this ID, serving as the mount point of this
272 /// subagent within the parent trace.
273 pub parent_tool_call_id: ToolCallId,
274}
275
276impl<'a> ToolContext<'a> {
277 /// Constructs a minimal `ToolContext`. The `#[non_exhaustive]` attribute prevents
278 /// external crates from constructing the struct directly with a literal — this
279 /// constructor is the only cross-crate entry point. When adding new fields, add
280 /// default values to the signature or provide a new constructor to avoid breaking
281 /// existing call sites.
282 pub fn new(
283 cwd: &'a Path,
284 cancel: CancellationToken,
285 fs: Arc<dyn FsBackend>,
286 shell: Arc<dyn ShellBackend>,
287 http: Arc<dyn HttpClient>,
288 current_model: &'a str,
289 ) -> Self {
290 Self {
291 cwd,
292 cancel,
293 fs,
294 shell,
295 http,
296 current_model,
297 current_provider: "",
298 background: None,
299 subagent_bridge: None,
300 policy: None,
301 goal: None,
302 subagent_depth: 0,
303 }
304 }
305
306 /// Inject the provider vendor selected for the current turn, forming a selection pair
307 /// with `current_model`.
308 /// If not called, defaults to an empty string (`spawn_agent` falls back to picking
309 /// the first entry by bare model id).
310 #[must_use]
311 pub fn with_current_provider(mut self, vendor: &'a str) -> Self {
312 self.current_provider = vendor;
313 self
314 }
315
316 /// Inject the remaining subagent dispatch depth from this layer onward. The tool
317 /// driver for the top-level turn calls with the configured initial cap; `spawn_agent`
318 /// injects the decremented value for nested child-agent turns. If not called,
319 /// defaults to `0` (most conservative: no subagent dispatch allowed).
320 #[must_use]
321 pub fn with_subagent_depth(mut self, depth: u32) -> Self {
322 self.subagent_depth = depth;
323 self
324 }
325
326 /// Inject the active sandbox policy for this turn snapshot. The top-level turn's tool
327 /// driver uses this to pass the parent turn's policy to `spawn_agent`; if not called,
328 /// `policy` is `None` (child agent nesting / testing), and `spawn_agent` falls back
329 /// to the policy captured at construction time.
330 #[must_use]
331 pub fn with_policy(mut self, policy: Arc<dyn crate::policy::SandboxPolicy>) -> Self {
332 self.policy = Some(policy);
333 self
334 }
335
336 /// Inject a session-level background task handle. The top-level turn's tool driver
337 /// uses this to enable `run_in_background`; if not called, `background` is `None`
338 /// (the default for sub-agents / tests), and tools fall back to synchronous
339 /// execution.
340 #[must_use]
341 pub fn with_background(mut self, background: crate::session::BackgroundTasks) -> Self {
342 self.background = Some(background);
343 self
344 }
345
346 /// Inject shared state for the `--goal` goal-driven loop. The `goal_done` tool sets
347 /// `reached` based on this state; if not called, `goal` is `None` (non-goal mode, the
348 /// default).
349 #[must_use]
350 pub fn with_goal(mut self, goal: Arc<crate::session::GoalState>) -> Self {
351 self.goal = Some(goal);
352 self
353 }
354
355 /// Inject a subagent event bridge. The tool driver injects one per tool call in
356 /// `session::turn`, keyed by [`ToolCallId`], so that `spawn_agent` can nest child
357 /// turn events back into the parent trace.
358 #[must_use]
359 pub fn with_subagent_bridge(mut self, bridge: SubagentBridge) -> Self {
360 self.subagent_bridge = Some(bridge);
361 self
362 }
363}
364
365/// Tools callable by the agent.
366///
367/// Implementors are typically stateless (each invocation receives all dependencies via
368/// `args` + [`ToolContext`]); if you need to hold state such as connections or caches,
369/// place the state on `Self` and register an `Arc<Self>` with the main loop.
370pub trait Tool: Send + Sync {
371 /// Tool metadata. Returns a reference to avoid allocating on every call.
372 fn schema(&self) -> &ToolSchema;
373
374 /// Provides a safety-level hint to the sandbox policy without actually executing the
375 /// tool.
376 ///
377 /// `args` is the already-deserialized JSON value — the same tool's safety level may
378 /// vary by arguments (e.g., the `bash` tool escalates to [`SafetyClass::Destructive`]
379 /// when `command` contains `rm`). The implementation should be a **pure function**
380 /// and perform no IO.
381 fn safety_hint(&self, args: &serde_json::Value) -> SafetyClass;
382
383 /// Generates a "self-description" before execution, for display to the ACP client.
384 ///
385 /// The async signature and [`ToolContext`] injection allow implementations to perform
386 /// lightweight IO during the describe phase (typical example: `write_file` reads the
387 /// old content before requesting authorization, producing a precise old↔new diff for
388 /// the client—more reviewable than "entirely new content").
389 ///
390 /// Performance constraint: `describe` runs before every ACP `ToolCall` push.
391 /// Implementations should remain fast and graceful on failure (on IO failure, degrade
392 /// to returning basic fields; do not let `describe` itself throw—the signature
393 /// provides no error channel).
394 ///
395 /// See the field conventions on [`ToolCallDescription`] for which fields are filled
396 /// by whom.
397 fn describe<'a>(
398 &'a self,
399 args: &'a serde_json::Value,
400 ctx: ToolContext<'a>,
401 ) -> BoxFuture<'a, ToolCallDescription>;
402
403 /// Initiates a tool call and returns an event stream.
404 ///
405 /// See [`ToolEvent`] for the stream elements. The stream must end immediately after
406 /// the terminal event. Dropping the stream is treated as cancellation (equivalent to
407 /// `ctx.cancel.cancel()`).
408 fn execute(&self, args: serde_json::Value, ctx: ToolContext<'_>) -> ToolStream;
409}
410
411/// Tool execution error.
412///
413/// The granularity is intentionally coarse — finer-grained error types are carried by
414/// built-in tools themselves in the `Execution` source. Here we only distinguish the
415/// broad categories that the main loop needs to handle differently.
416#[non_exhaustive]
417#[derive(Debug, Error)]
418pub enum ToolError {
419 /// Canceled by the caller (triggered via [`ToolContext::cancel`]).
420 #[error("tool canceled")]
421 Canceled,
422
423 /// The tool arguments failed JSON parsing or schema validation. The main loop can
424 /// send this back to the LLM so the model can fix the parameters and retry.
425 #[error("invalid tool arguments: {0}")]
426 InvalidArgs(#[source] BoxError),
427
428 /// Runtime error (I/O failure, non-zero subprocess exit, network error, etc.).
429 #[error("tool execution failed: {0}")]
430 Execution(#[source] BoxError),
431}