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.
197/// What: `content` is raw agent output; `summary` is the extracted `## Summary`
198/// section (or a prefix fallback).
199/// Test: Constructed from IPC result messages in integration paths.
200#[derive(Debug, Clone)]
201pub struct AgentOutput {
202 /// Raw output from the agent.
203 pub content: String,
204 /// Extracted summary (e.g. `## Summary` section), if present.
205 pub summary: Option<String>,
206 /// Aggregated LLM token usage for this invocation.
207 pub usage: crate::perf::TokenUsage,
208}
209
210impl AgentOutput {
211 /// Build from content alone; summary/usage will be defaults.
212 ///
213 /// Why: Convenience constructor for simple agent results.
214 /// What: Sets `content`, leaves `summary` None, `usage` zeroed.
215 /// Test: Used in mock runners throughout this crate's tests.
216 pub fn from_content(content: impl Into<String>) -> Self {
217 Self {
218 content: content.into(),
219 summary: None,
220 usage: crate::perf::TokenUsage::default(),
221 }
222 }
223
224 /// Return summary if present, else fall back to content.
225 ///
226 /// Why: Callers that want a short form for template injection should not
227 /// have to branch on `Option`.
228 /// What: Returns `&summary` if `Some`, otherwise `&content`.
229 /// Test: `agent_output_summary_or_content_fallback`.
230 pub fn summary_or_content(&self) -> &str {
231 self.summary.as_deref().unwrap_or(&self.content)
232 }
233}
234
235// ── AgentRunner ──────────────────────────────────────────────────────────────
236
237/// Runs a task against a named agent.
238///
239/// Why: Abstracts over how an agent is executed — subprocess, in-process, or
240/// mock. Lets tests avoid spawning real processes.
241/// What: `run(agent_name, task)` returns the agent's `AgentOutput`.
242/// `run_with_context` extends this to pass per-invocation overrides; the
243/// default forwards to `run()` so existing mock runners keep working.
244/// Test: `MockAgentRunner` in tests implements this; `test_run_with_history_forwards_ctx`
245/// verifies the default delegation chain.
246#[async_trait]
247pub trait AgentRunner: Send + Sync {
248 /// Run a task against the named agent.
249 async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput>;
250
251 /// Run with per-invocation overrides in `ctx`.
252 ///
253 /// Why: Replaces `std::env::set_var` threading of per-call state. Default
254 /// impl ignores `ctx` and falls back to `run()` so legacy mock runners
255 /// keep working unchanged.
256 /// What: Concrete runners override this to scope env vars to the child.
257 /// Test: Wave-loop and runner tests prove context fields reach the child.
258 async fn run_with_context(
259 &self,
260 agent_name: &str,
261 task: &str,
262 _ctx: &RunContext,
263 ) -> Result<AgentOutput> {
264 self.run(agent_name, task).await
265 }
266
267 /// Run a task while forwarding prior session history.
268 ///
269 /// Why: Persistent-session agents need prior turns so the sub-agent can
270 /// rebuild context in a fresh subprocess.
271 /// What: Default delegates to `run_with_context(ctx)` so `working_dir`
272 /// and `model` are honoured even when the runner does not override this.
273 /// Test: `test_run_with_history_forwards_ctx`.
274 async fn run_with_history(
275 &self,
276 agent_name: &str,
277 task: &str,
278 _history: &[HistoryMessage],
279 ctx: &RunContext,
280 ) -> Result<AgentOutput> {
281 self.run_with_context(agent_name, task, ctx).await
282 }
283}
284
285// ── HistoryMessage ───────────────────────────────────────────────────────────
286
287/// A prior conversation turn forwarded to persistent-session agents.
288///
289/// Why: Persistent-session runners replay history on each subprocess restart
290/// so the sub-agent preserves conversational context.
291/// What: `role` is `"user"` or `"assistant"`; `content` is the turn text.
292/// Test: Used in `AgentRunner::run_with_history` signature.
293#[derive(Debug, Clone, Serialize, Deserialize)]
294pub struct HistoryMessage {
295 pub role: String,
296 pub content: String,
297}
298
299// ── SearchProvider ───────────────────────────────────────────────────────────
300
301/// A search hit returned by a `SearchProvider`.
302///
303/// Why: Uniform result type for web/code search so callers are provider-agnostic.
304/// What: `title`, `url`, `snippet` — the minimal useful set.
305/// Test: Used in `SearchProvider` mock tests.
306#[derive(Debug, Clone, Serialize, Deserialize)]
307pub struct SearchResult {
308 pub title: String,
309 pub url: String,
310 pub snippet: String,
311}
312
313/// Web/code search backend abstraction.
314///
315/// Why: Swap Brave for Tavily / DuckDuckGo / a test stub by changing the
316/// registered impl — no callers change.
317/// What: `search(query, n)` returns up to `n` results.
318/// Test: A stub `SearchProvider` returns a fixed vector in mock tests.
319#[async_trait]
320pub trait SearchProvider: Send + Sync {
321 /// Run a search for `query` and return up to `n` results.
322 async fn search(&self, query: &str, n: usize) -> Result<Vec<SearchResult>>;
323}
324
325// ── SkillResolver ────────────────────────────────────────────────────────────
326
327/// Resolves named skills to their Markdown content.
328///
329/// Why: Skill sources vary (project `.claude/`, user `~/.claude/`, bundled
330/// config); callers should not care which. #2069 splits skills into cheap,
331/// always-cached metadata (name + description) and an on-demand-loaded body
332/// so the PM/agents can see the full catalog without paying every skill's
333/// token cost up front — `metadata()` is the cached catalog, `resolve()` is
334/// the lazy, per-invocation body load.
335/// What: `resolve(name)` returns `Some(content)` if found. `list()` returns
336/// all discoverable names. `metadata()` returns the full cached
337/// `SkillMetadata` catalog (name + description), the progressive-disclosure
338/// prompt injection uses.
339/// Test: `crate::skills::tests::fs_skill_resolver_*` construct an
340/// `FsSkillResolver` (this trait's concrete filesystem impl) over a tempdir
341/// and assert `resolve()`/`list()`/`metadata()` all agree.
342pub trait SkillResolver: Send + Sync {
343 /// Look up a skill by name and return its Markdown content, if found.
344 fn resolve(&self, name: &str) -> Option<String>;
345 /// List all discoverable skill names.
346 fn list(&self) -> Vec<String>;
347 /// Cached metadata (name + description) for every discoverable skill.
348 fn metadata(&self) -> Vec<crate::skills::SkillMetadata>;
349}
350
351// ── Tests ─────────────────────────────────────────────────────────────────────
352
353#[cfg(test)]
354mod tests {
355 use std::path::PathBuf;
356 use std::sync::{Arc, Mutex};
357
358 use anyhow::Result;
359 use async_trait::async_trait;
360
361 use super::*;
362 use crate::perf::TokenUsage;
363
364 /// Mock runner that records the `RunContext` received in `run_with_context`.
365 ///
366 /// Why: We need to assert that the default `run_with_history` impl actually
367 /// forwards `ctx` to `run_with_context` (regression guard).
368 /// What: Records each ctx snapshot; `run` is unused in this test.
369 /// Test: `test_run_with_history_forwards_ctx`.
370 struct CtxCapture {
371 captured: Arc<Mutex<Vec<RunContext>>>,
372 }
373
374 #[async_trait]
375 impl AgentRunner for CtxCapture {
376 async fn run(&self, _agent_name: &str, _task: &str) -> Result<AgentOutput> {
377 Ok(AgentOutput::from_content("run"))
378 }
379
380 async fn run_with_context(
381 &self,
382 _agent_name: &str,
383 _task: &str,
384 ctx: &RunContext,
385 ) -> Result<AgentOutput> {
386 self.captured
387 .lock()
388 .expect("lock poisoned")
389 .push(ctx.clone());
390 Ok(AgentOutput::from_content("run_with_context"))
391 }
392 // NOTE: run_with_history is intentionally NOT overridden — we test the
393 // default impl defined in the trait.
394 }
395
396 /// Verifies that the default `run_with_history` forwards `ctx` to
397 /// `run_with_context` rather than dropping it.
398 ///
399 /// Why: Without this, persistent-session agents lose `working_dir` and
400 /// `model` when the default implementation falls through.
401 /// What: Calls `run_with_history` with specific `working_dir` and `model`,
402 /// then asserts `run_with_context` received those values.
403 /// Test: This test itself.
404 #[tokio::test]
405 async fn test_run_with_history_forwards_ctx() {
406 let captured = Arc::new(Mutex::new(Vec::new()));
407 let runner = CtxCapture {
408 captured: captured.clone(),
409 };
410
411 let ctx = RunContext {
412 working_dir: Some(PathBuf::from("/tmp/test-wd")),
413 model: Some("anthropic/claude-opus-4-5".to_string()),
414 max_turns_override: Some(5),
415 assigned_file: None,
416 };
417
418 let out = runner
419 .run_with_history("test-agent", "do something", &[], &ctx)
420 .await
421 .expect("run_with_history should succeed");
422
423 assert_eq!(
424 out.content, "run_with_context",
425 "default run_with_history must call run_with_context, not run()"
426 );
427
428 let snaps = captured.lock().expect("lock poisoned");
429 assert_eq!(
430 snaps.len(),
431 1,
432 "run_with_context must be called exactly once"
433 );
434
435 let recorded = &snaps[0];
436 assert_eq!(
437 recorded.working_dir,
438 Some(PathBuf::from("/tmp/test-wd")),
439 "working_dir must be forwarded"
440 );
441 assert_eq!(
442 recorded.model,
443 Some("anthropic/claude-opus-4-5".to_string()),
444 "model must be forwarded"
445 );
446 assert_eq!(
447 recorded.max_turns_override,
448 Some(5),
449 "max_turns_override must be forwarded"
450 );
451 }
452
453 /// Verify `ToolResult` predicates and content accessor.
454 ///
455 /// Why: Guard the semantics of `is_error`, `is_fatal`, and `content`.
456 /// What: Constructs each variant and checks all three predicates.
457 /// Test: This test itself.
458 #[test]
459 fn tool_result_predicates() {
460 let ok = ToolResult::ok("hello");
461 assert!(!ok.is_error());
462 assert!(!ok.is_fatal());
463 assert_eq!(ok.content(), "hello");
464
465 let err = ToolResult::err("oops");
466 assert!(err.is_error());
467 assert!(!err.is_fatal());
468 assert_eq!(err.content(), "oops");
469
470 let fatal = ToolResult::fatal("crash");
471 assert!(fatal.is_error());
472 assert!(fatal.is_fatal());
473 assert_eq!(fatal.content(), "crash");
474 }
475
476 /// Verify `AgentOutput::summary_or_content` fallback.
477 ///
478 /// Why: Callers rely on this to get a short form without branching.
479 /// What: `summary=Some` returns summary; `summary=None` returns content.
480 /// Test: This test itself.
481 #[test]
482 fn agent_output_summary_or_content_fallback() {
483 let with_summary = AgentOutput {
484 content: "full content".into(),
485 summary: Some("short summary".into()),
486 usage: TokenUsage::default(),
487 };
488 assert_eq!(with_summary.summary_or_content(), "short summary");
489
490 let no_summary = AgentOutput::from_content("just content");
491 assert_eq!(no_summary.summary_or_content(), "just content");
492 }
493}