Skip to main content

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