Skip to main content

trusty_code/tools/
traits.rs

1//! Core trait abstractions for tool execution, agent running, search, and skills.
2//!
3//! Why: DI through traits lets tcode swap concrete implementations (subprocess
4//! runner vs. in-process mock; Brave vs. Tavily search; fs skill store vs.
5//! embedded) without changing call sites. This is the SOA seam that keeps
6//! the workflow engine and PM loop testable.
7//! What: Defines `ToolExecutor`, `AgentRunner`, `SearchProvider`, and
8//! `SkillResolver`. All are object-safe (`dyn`-able) and `Send + Sync`.
9//! Test: Mock impls of each trait are constructed in unit tests for
10//! `ToolRegistry`, delegating commands, and related code.
11
12use std::path::PathBuf;
13
14use anyhow::Result;
15use async_trait::async_trait;
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18
19// ── ToolResult ──────────────────────────────────────────────────────────────
20
21/// Structured result of a tool execution.
22///
23/// Why: Hard-failing the LLM loop on every tool error is brittle — the model
24/// often can recover (retry with different args, fall back to another tool, or
25/// explain the failure in its final answer). A structured error lets the caller
26/// surface failure back to the LLM as a `tool_result` with `is_error: true`
27/// while keeping the loop running.
28/// What: `Success(String)` carries a successful textual result; `Error` carries
29/// a message plus a `recoverable` flag.
30/// Test: `ToolResult::err(...).is_error()` is true; `ok(...).content()` returns
31/// the success string. Exercised in `tools::registry` and delegate tests.
32#[derive(Debug)]
33pub enum ToolResult {
34    /// Tool executed successfully; inner string is the textual result.
35    Success(String),
36    /// Tool failed; `message` describes why; `recoverable` advises the LLM loop.
37    Error { message: String, recoverable: bool },
38}
39
40impl ToolResult {
41    /// Construct a successful result.
42    ///
43    /// Why: Single canonical happy-path constructor used by every tool.
44    /// What: Wraps `s` in `Success`.
45    /// Test: Trivially exercised by every successful tool execute().
46    pub fn ok(s: impl Into<String>) -> Self {
47        ToolResult::Success(s.into())
48    }
49
50    /// Construct a recoverable error.
51    ///
52    /// Why: Most tool failures are non-fatal — wrong arg, transient network,
53    /// empty result. The LLM should see the error and decide.
54    /// What: Wraps `msg` with `recoverable = true`.
55    /// Test: Exercised by delegate and registry tests.
56    pub fn err(msg: impl Into<String>) -> Self {
57        ToolResult::Error {
58            message: msg.into(),
59            recoverable: true,
60        }
61    }
62
63    /// Construct a fatal (non-recoverable) error.
64    ///
65    /// Why: Some failures (invariant violations, credential rejection) should
66    /// not be retried; callers should bail.
67    /// What: Wraps `msg` with `recoverable = false`.
68    /// Test: Checked by `is_fatal` predicates in tests.
69    pub fn fatal(msg: impl Into<String>) -> Self {
70        ToolResult::Error {
71            message: msg.into(),
72            recoverable: false,
73        }
74    }
75
76    /// Whether this result is an error variant.
77    ///
78    /// Why: Dispatch paths need a cheap predicate to log/branch on failure.
79    /// What: Returns `true` for any `Error`, `false` for `Success`.
80    /// Test: `ToolResult::err("x").is_error()` is true.
81    pub fn is_error(&self) -> bool {
82        matches!(self, ToolResult::Error { .. })
83    }
84
85    /// Whether this error is fatal (not recoverable). `false` for Success.
86    ///
87    /// Why: Callers that distinguish fatal-vs-recoverable need this to decide
88    /// whether to retry or bail.
89    /// What: True only for `Error { recoverable: false, .. }`.
90    /// Test: `ToolResult::fatal("x").is_fatal()` is true.
91    pub fn is_fatal(&self) -> bool {
92        matches!(
93            self,
94            ToolResult::Error {
95                recoverable: false,
96                ..
97            }
98        )
99    }
100
101    /// Extract the message string for both variants.
102    ///
103    /// Why: Callers like the LLM loop need the raw string regardless of
104    /// success/failure to pass back as `tool_result` content.
105    /// What: Returns the payload string for both `Success` and `Error`.
106    /// Test: `ToolResult::ok("hi").content()` == "hi";
107    ///       `ToolResult::err("oops").content()` == "oops".
108    pub fn content(&self) -> &str {
109        match self {
110            ToolResult::Success(s) => s.as_str(),
111            ToolResult::Error { message, .. } => message.as_str(),
112        }
113    }
114}
115
116// ── ToolExecutor ─────────────────────────────────────────────────────────────
117
118/// Access tiers controlling which users/transports may invoke a tool.
119///
120/// Why: tcode exposes tools over multiple surfaces (CLI, API, TUI). Some tools
121/// (memory writes, shell exec) are unsafe for untrusted callers. `ServiceTier`
122/// provides a stable ladder that tools can declare their restrictions against.
123/// What: Ordered by trust level — `All` is the highest-privilege tier.
124/// Test: `rbac::tests::*` cover tier matching logic.
125#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
126#[serde(rename_all = "snake_case")]
127pub enum ServiceTier {
128    /// Trusted operator — full tool access.
129    #[default]
130    All,
131    /// Analytics/reporting callers — read-heavy, no mutations.
132    Analytics,
133    /// Read-only callers — can only observe state.
134    ReadOnly,
135}
136
137/// Object-safe executor interface for a single named tool.
138///
139/// Why: Abstracts over all tool kinds (fs, shell, web search, delegate, MCP
140/// bridge) so the registry and dispatch loop are tool-agnostic. New tools drop
141/// in by implementing this trait without touching the PM loop.
142/// What: `name()` is the string key used in LLM function calls; `schema()`
143/// emits the JSON function descriptor; `execute(args)` performs the action.
144/// Test: `ToolRegistry` tests register a `MockTool` implementing this trait.
145#[async_trait]
146pub trait ToolExecutor: Send + Sync {
147    /// The tool's function name as exposed to the LLM.
148    fn name(&self) -> &str;
149
150    /// JSON schema describing the tool's parameters (OpenAI function format).
151    fn schema(&self) -> Value;
152
153    /// Execute the tool with the given JSON argument object.
154    async fn execute(&self, args: Value) -> ToolResult;
155
156    /// Access tiers that are **blocked** from calling this tool.
157    ///
158    /// Why: Tools declare which tiers they restrict; an empty list means
159    /// universally accessible. This inverted model means adding RBAC to
160    /// existing tools is a no-op by default.
161    /// What: Returns a slice of `ServiceTier` values that are NOT allowed.
162    /// Test: `rbac::tests::can_access_tier_*`.
163    fn restricted_tiers(&self) -> &[ServiceTier] {
164        &[]
165    }
166}
167
168// ── RunContext ───────────────────────────────────────────────────────────────
169
170/// Per-invocation context threaded from orchestrator to agent runner.
171///
172/// Why: Passing per-call directives (assigned file, turn budget, working dir)
173/// as a `RunContext` instead of via `std::env::set_var` is sound under
174/// multi-threaded tokio — env mutation is not thread-safe in Rust 2024.
175/// What: Carries optional overrides; runners apply them to child processes via
176/// `Command::env` / `Command::current_dir`.
177/// Test: Exercised in `AgentRunner` trait tests (`test_run_with_history_forwards_ctx`).
178#[derive(Debug, Default, Clone)]
179pub struct RunContext {
180    /// Path to scope any file-writing tool to for this call.
181    pub assigned_file: Option<PathBuf>,
182    /// Max-turns cap override for this invocation.
183    pub max_turns_override: Option<u32>,
184    /// Working directory for the subprocess.
185    pub working_dir: Option<PathBuf>,
186    /// LLM model override for this invocation.
187    pub model: Option<String>,
188}
189
190// ── AgentOutput ──────────────────────────────────────────────────────────────
191
192/// Structured output returned by an `AgentRunner`.
193///
194/// Why: Downstream phases need a concise `summary` for template substitution
195/// while also needing the full `content` for file extraction. Bundling them
196/// avoids separate trait methods. (#2683) A delegated engineer's caller (the
197/// PM's `delegate_to_agent` tool) also needs to know whether the agent
198/// terminated by an EXPLICIT, successful `finish_task` completion — that is the
199/// authoritative "the task is genuinely done" signal used to prevent a
200/// gratuitous post-finish re-delegation from mislabeling a complete run.
201/// What: `content` is raw agent output; `summary` is the extracted `## Summary`
202/// section (or a prefix fallback); `finish_status` (#2683) is `Some` only when
203/// the loop ended via an accepted `finish_task` call, carrying that call's
204/// reported status.
205/// Test: Constructed from IPC result messages in integration paths;
206/// `finish_status` propagation is covered by
207/// `agent_loop::tests::explicit_finish_task_terminates_loop_with_structured_summary`
208/// and `tools::delegate::tests::completion_signal_latches_on_completed_finish`.
209#[derive(Debug, Clone)]
210pub struct AgentOutput {
211    /// Raw output from the agent.
212    pub content: String,
213    /// Extracted summary (e.g. `## Summary` section), if present.
214    pub summary: Option<String>,
215    /// Aggregated LLM token usage for this invocation.
216    pub usage: crate::perf::TokenUsage,
217    /// The status of an explicit `finish_task` completion, if the loop ended
218    /// via one (#2683). `None` when the run ended any other way (turn cap,
219    /// timeout, a plain no-tool-call stop, or an error).
220    pub finish_status: Option<crate::tools::finish_task::FinishStatus>,
221}
222
223impl AgentOutput {
224    /// Build from content alone; summary/usage will be defaults.
225    ///
226    /// Why: Convenience constructor for simple agent results.
227    /// What: Sets `content`, leaves `summary` None, `usage` zeroed, and
228    /// `finish_status` None (no explicit finish observed).
229    /// Test: Used in mock runners throughout this crate's tests.
230    pub fn from_content(content: impl Into<String>) -> Self {
231        Self {
232            content: content.into(),
233            summary: None,
234            usage: crate::perf::TokenUsage::default(),
235            finish_status: None,
236        }
237    }
238
239    /// Return summary if present, else fall back to content.
240    ///
241    /// Why: Callers that want a short form for template injection should not
242    /// have to branch on `Option`.
243    /// What: Returns `&summary` if `Some`, otherwise `&content`.
244    /// Test: `agent_output_summary_or_content_fallback`.
245    pub fn summary_or_content(&self) -> &str {
246        self.summary.as_deref().unwrap_or(&self.content)
247    }
248}
249
250// ── AgentRunner ──────────────────────────────────────────────────────────────
251
252/// Runs a task against a named agent.
253///
254/// Why: Abstracts over how an agent is executed — subprocess, in-process, or
255/// mock. Lets tests avoid spawning real processes.
256/// What: `run(agent_name, task)` returns the agent's `AgentOutput`.
257/// `run_with_context` extends this to pass per-invocation overrides; the
258/// default forwards to `run()` so existing mock runners keep working.
259/// Test: `MockAgentRunner` in tests implements this; `test_run_with_history_forwards_ctx`
260/// verifies the default delegation chain.
261#[async_trait]
262pub trait AgentRunner: Send + Sync {
263    /// Run a task against the named agent.
264    async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput>;
265
266    /// Run with per-invocation overrides in `ctx`.
267    ///
268    /// Why: Replaces `std::env::set_var` threading of per-call state. Default
269    /// impl ignores `ctx` and falls back to `run()` so legacy mock runners
270    /// keep working unchanged.
271    /// What: Concrete runners override this to scope env vars to the child.
272    /// Test: Wave-loop and runner tests prove context fields reach the child.
273    async fn run_with_context(
274        &self,
275        agent_name: &str,
276        task: &str,
277        _ctx: &RunContext,
278    ) -> Result<AgentOutput> {
279        self.run(agent_name, task).await
280    }
281
282    /// Run a task while forwarding prior session history.
283    ///
284    /// Why: Persistent-session agents need prior turns so the sub-agent can
285    /// rebuild context in a fresh subprocess.
286    /// What: Default delegates to `run_with_context(ctx)` so `working_dir`
287    /// and `model` are honoured even when the runner does not override this.
288    /// Test: `test_run_with_history_forwards_ctx`.
289    async fn run_with_history(
290        &self,
291        agent_name: &str,
292        task: &str,
293        _history: &[HistoryMessage],
294        ctx: &RunContext,
295    ) -> Result<AgentOutput> {
296        self.run_with_context(agent_name, task, ctx).await
297    }
298}
299
300// ── HistoryMessage ───────────────────────────────────────────────────────────
301
302/// A prior conversation turn forwarded to persistent-session agents.
303///
304/// Why: Persistent-session runners replay history on each subprocess restart
305/// so the sub-agent preserves conversational context.
306/// What: `role` is `"user"` or `"assistant"`; `content` is the turn text.
307/// Test: Used in `AgentRunner::run_with_history` signature.
308#[derive(Debug, Clone, Serialize, Deserialize)]
309pub struct HistoryMessage {
310    pub role: String,
311    pub content: String,
312}
313
314// ── SearchProvider ───────────────────────────────────────────────────────────
315
316/// A search hit returned by a `SearchProvider`.
317///
318/// Why: Uniform result type for web/code search so callers are provider-agnostic.
319/// What: `title`, `url`, `snippet` — the minimal useful set.
320/// Test: Used in `SearchProvider` mock tests.
321#[derive(Debug, Clone, Serialize, Deserialize)]
322pub struct SearchResult {
323    pub title: String,
324    pub url: String,
325    pub snippet: String,
326}
327
328/// Web/code search backend abstraction.
329///
330/// Why: Swap Brave for Tavily / DuckDuckGo / a test stub by changing the
331/// registered impl — no callers change.
332/// What: `search(query, n)` returns up to `n` results.
333/// Test: A stub `SearchProvider` returns a fixed vector in mock tests.
334#[async_trait]
335pub trait SearchProvider: Send + Sync {
336    /// Run a search for `query` and return up to `n` results.
337    async fn search(&self, query: &str, n: usize) -> Result<Vec<SearchResult>>;
338}
339
340// ── SkillResolver ────────────────────────────────────────────────────────────
341
342/// Resolves named skills to their Markdown content.
343///
344/// Why: Skill sources vary (project `.claude/`, user `~/.claude/`, bundled
345/// config); callers should not care which. #2069 splits skills into cheap,
346/// always-cached metadata (name + description) and an on-demand-loaded body
347/// so the PM/agents can see the full catalog without paying every skill's
348/// token cost up front — `metadata()` is the cached catalog, `resolve()` is
349/// the lazy, per-invocation body load.
350/// What: `resolve(name)` returns `Some(content)` if found. `list()` returns
351/// all discoverable names. `metadata()` returns the full cached
352/// `SkillMetadata` catalog (name + description), the progressive-disclosure
353/// prompt injection uses.
354/// Test: `crate::skills::tests::fs_skill_resolver_*` construct an
355/// `FsSkillResolver` (this trait's concrete filesystem impl) over a tempdir
356/// and assert `resolve()`/`list()`/`metadata()` all agree.
357pub trait SkillResolver: Send + Sync {
358    /// Look up a skill by name and return its Markdown content, if found.
359    fn resolve(&self, name: &str) -> Option<String>;
360    /// List all discoverable skill names.
361    fn list(&self) -> Vec<String>;
362    /// Cached metadata (name + description) for every discoverable skill.
363    fn metadata(&self) -> Vec<crate::skills::SkillMetadata>;
364}
365
366// ── Tests ─────────────────────────────────────────────────────────────────────
367
368#[cfg(test)]
369mod tests {
370    use std::path::PathBuf;
371    use std::sync::{Arc, Mutex};
372
373    use anyhow::Result;
374    use async_trait::async_trait;
375
376    use super::*;
377    use crate::perf::TokenUsage;
378
379    /// Mock runner that records the `RunContext` received in `run_with_context`.
380    ///
381    /// Why: We need to assert that the default `run_with_history` impl actually
382    /// forwards `ctx` to `run_with_context` (regression guard).
383    /// What: Records each ctx snapshot; `run` is unused in this test.
384    /// Test: `test_run_with_history_forwards_ctx`.
385    struct CtxCapture {
386        captured: Arc<Mutex<Vec<RunContext>>>,
387    }
388
389    #[async_trait]
390    impl AgentRunner for CtxCapture {
391        async fn run(&self, _agent_name: &str, _task: &str) -> Result<AgentOutput> {
392            Ok(AgentOutput::from_content("run"))
393        }
394
395        async fn run_with_context(
396            &self,
397            _agent_name: &str,
398            _task: &str,
399            ctx: &RunContext,
400        ) -> Result<AgentOutput> {
401            self.captured
402                .lock()
403                .expect("lock poisoned")
404                .push(ctx.clone());
405            Ok(AgentOutput::from_content("run_with_context"))
406        }
407        // NOTE: run_with_history is intentionally NOT overridden — we test the
408        // default impl defined in the trait.
409    }
410
411    /// Verifies that the default `run_with_history` forwards `ctx` to
412    /// `run_with_context` rather than dropping it.
413    ///
414    /// Why: Without this, persistent-session agents lose `working_dir` and
415    /// `model` when the default implementation falls through.
416    /// What: Calls `run_with_history` with specific `working_dir` and `model`,
417    /// then asserts `run_with_context` received those values.
418    /// Test: This test itself.
419    #[tokio::test]
420    async fn test_run_with_history_forwards_ctx() {
421        let captured = Arc::new(Mutex::new(Vec::new()));
422        let runner = CtxCapture {
423            captured: captured.clone(),
424        };
425
426        let ctx = RunContext {
427            working_dir: Some(PathBuf::from("/tmp/test-wd")),
428            model: Some("anthropic/claude-opus-4-5".to_string()),
429            max_turns_override: Some(5),
430            assigned_file: None,
431        };
432
433        let out = runner
434            .run_with_history("test-agent", "do something", &[], &ctx)
435            .await
436            .expect("run_with_history should succeed");
437
438        assert_eq!(
439            out.content, "run_with_context",
440            "default run_with_history must call run_with_context, not run()"
441        );
442
443        let snaps = captured.lock().expect("lock poisoned");
444        assert_eq!(
445            snaps.len(),
446            1,
447            "run_with_context must be called exactly once"
448        );
449
450        let recorded = &snaps[0];
451        assert_eq!(
452            recorded.working_dir,
453            Some(PathBuf::from("/tmp/test-wd")),
454            "working_dir must be forwarded"
455        );
456        assert_eq!(
457            recorded.model,
458            Some("anthropic/claude-opus-4-5".to_string()),
459            "model must be forwarded"
460        );
461        assert_eq!(
462            recorded.max_turns_override,
463            Some(5),
464            "max_turns_override must be forwarded"
465        );
466    }
467
468    /// Verify `ToolResult` predicates and content accessor.
469    ///
470    /// Why: Guard the semantics of `is_error`, `is_fatal`, and `content`.
471    /// What: Constructs each variant and checks all three predicates.
472    /// Test: This test itself.
473    #[test]
474    fn tool_result_predicates() {
475        let ok = ToolResult::ok("hello");
476        assert!(!ok.is_error());
477        assert!(!ok.is_fatal());
478        assert_eq!(ok.content(), "hello");
479
480        let err = ToolResult::err("oops");
481        assert!(err.is_error());
482        assert!(!err.is_fatal());
483        assert_eq!(err.content(), "oops");
484
485        let fatal = ToolResult::fatal("crash");
486        assert!(fatal.is_error());
487        assert!(fatal.is_fatal());
488        assert_eq!(fatal.content(), "crash");
489    }
490
491    /// Verify `AgentOutput::summary_or_content` fallback.
492    ///
493    /// Why: Callers rely on this to get a short form without branching.
494    /// What: `summary=Some` returns summary; `summary=None` returns content.
495    /// Test: This test itself.
496    #[test]
497    fn agent_output_summary_or_content_fallback() {
498        let with_summary = AgentOutput {
499            content: "full content".into(),
500            summary: Some("short summary".into()),
501            usage: TokenUsage::default(),
502            finish_status: None,
503        };
504        assert_eq!(with_summary.summary_or_content(), "short summary");
505
506        let no_summary = AgentOutput::from_content("just content");
507        assert_eq!(no_summary.summary_or_content(), "just content");
508    }
509}