Skip to main content

trusty_agents_common/
lib.rs

1//! Stable plugin API surface shared between `trusty-agents` and external agent crates.
2//!
3//! Why: The original design placed `ToolExecutor` / `AgentPlugin` / `ToolResult`
4//!      inside the host crate's `lib.rs`. That created a hard cargo dependency
5//!      cycle (trusty-agents → agent crate → trusty-agents), because external agent
6//!      crates need the trait to implement it AND `trusty-agents` needs the agent
7//!      crate to inject the plugin at startup. Cargo cannot resolve circular
8//!      path dependencies even when they are logically one-directional at the
9//!      binary level. Extracting the minimal trait surface into this tiny
10//!      crate breaks the cycle: both `trusty-agents` and every agent crate depend
11//!      on `trusty-agents-common`, but never on each other through the lib.
12//! What: Re-defines the previously trusty-agents-internal types — `ToolExecutor`
13//!       trait, `ToolResult` enum, `ToolExecutionTier` enum, `ServiceTier`
14//!       enum (RBAC tiers), and `AgentPlugin` struct — as the public surface.
15//!       Also hosts the harness-adapter framework (`adapters`) and the
16//!       JSON-backed session ledger (`session_registry`), both moved here in
17//!       Wave 1 of the trusty-agents-common build-out (issue #862, refs #830/#832).
18//!       `trusty-agents` re-exports them via `trusty_agents::agent_api`,
19//!       `trusty_agents::adapters`, and `trusty_agents::session_registry` for
20//!       source-level compatibility with the existing call sites in
21//!       `crates/trusty-agents/src/**`.
22//! Test: Compile-tested transitively via `crates/trusty-agents` (host);
23//!       `ToolResult`'s predicates are covered by
24//!       `tool_result_is_error_distinguishes_variants`.
25
26// docs.rs builds a release's documentation once, from the uploaded tarball,
27// so a broken intra-doc link is baked into that version forever and only a new
28// release can correct it. Deny keeps this crate at zero rather than letting the
29// ratchet in `scripts/check_rustdoc_links.sh` absorb a new one.
30#![deny(rustdoc::broken_intra_doc_links)]
31
32pub mod perf;
33
34pub mod runner;
35
36pub mod adapters;
37
38pub mod session_registry;
39
40pub mod events;
41
42pub mod harness_doc;
43
44pub mod agent_content;
45
46pub mod compress;
47
48pub mod agents;
49
50pub mod skills;
51
52pub mod connectors;
53
54pub mod workstreams;
55
56pub mod transport;
57
58// #11550: the agents.health socket path, shared by tagent and `tm tui`.
59pub mod health;
60
61// #7735: shared closing-block extraction (Improvement recommendations /
62// Prompt feedback), slice 1 of docs/specs/self-improvement-loop.md.
63pub mod self_improvement;
64
65use std::sync::Arc;
66
67use async_trait::async_trait;
68use serde::{Deserialize, Serialize};
69use serde_json::Value;
70
71/// Structured result of a tool execution.
72///
73/// Why: Hard-failing the LLM loop on every tool error is brittle — the model
74///      often can recover (retry with different args, fall back to another
75///      tool, or explain the failure in its final answer). Returning a
76///      structured `Error { recoverable }` lets us surface the failure back
77///      to the LLM as a `tool_result` with `is_error: true` while keeping the
78///      loop running, unless `recoverable = false` in which case callers may
79///      choose to stop.
80/// What: `Success(String)` carries a successful textual result; `Error`
81///       carries a message plus a `recoverable` flag.
82/// Test: `ToolResult::err(...).is_error()` is true; `ok(...).content()`
83///       returns the success string. Exercised across `trusty-agents/tools/**`.
84#[derive(Debug)]
85pub enum ToolResult {
86    Success(String),
87    Error { message: String, recoverable: bool },
88}
89
90impl ToolResult {
91    /// Success with a textual payload.
92    ///
93    /// Why: Single canonical happy-path constructor used by every tool.
94    /// What: Wraps `s` in `Success`.
95    /// Test: Trivially exercised by every successful tool execute().
96    pub fn ok(s: impl Into<String>) -> Self {
97        ToolResult::Success(s.into())
98    }
99
100    /// Recoverable error: loop continues, LLM sees `is_error: true`.
101    ///
102    /// Why: Most tool failures are non-fatal — wrong arg, transient network,
103    ///      empty result. We want the model to see the error and decide.
104    /// What: Wraps `msg` with `recoverable = true`.
105    /// Test: Exercised by tool error tests across the workspace.
106    pub fn err(msg: impl Into<String>) -> Self {
107        ToolResult::Error {
108            message: msg.into(),
109            recoverable: true,
110        }
111    }
112
113    /// Fatal (non-recoverable) error: callers may choose to stop the loop.
114    ///
115    /// Why: Some failures (invariant violations, credential rejection) shouldn't
116    ///      be retried by the LLM; callers should surface them and bail.
117    /// What: Wraps `msg` with `recoverable = false`.
118    /// Test: Used by `is_fatal` tests in trusty-agents.
119    pub fn fatal(msg: impl Into<String>) -> Self {
120        ToolResult::Error {
121            message: msg.into(),
122            recoverable: false,
123        }
124    }
125
126    /// Whether this result is an error variant.
127    ///
128    /// Why: Dispatch paths need a cheap predicate to log/branch on failure.
129    /// What: Returns `true` for any `Error`, `false` for `Success`.
130    /// Test: `tool_result_is_error_distinguishes_variants`.
131    pub fn is_error(&self) -> bool {
132        matches!(self, ToolResult::Error { .. })
133    }
134
135    /// Whether this error is fatal (not recoverable). `false` for Success.
136    ///
137    /// Why: Callers that distinguish fatal-vs-recoverable need this to decide
138    ///      whether to retry or bail.
139    /// What: True only for `Error { recoverable: false, .. }`.
140    /// Test: `tool_result_is_fatal_only_for_non_recoverable`.
141    pub fn is_fatal(&self) -> bool {
142        matches!(
143            self,
144            ToolResult::Error {
145                recoverable: false,
146                ..
147            }
148        )
149    }
150
151    /// Access the inner textual content (success body or error message).
152    ///
153    /// Why: The LLM tool-result payload is always a string; this lets callers
154    ///      treat success/error uniformly when serialising.
155    /// What: Returns the success body or the error message.
156    /// Test: Implicit in every test that asserts on `result.content()`.
157    pub fn content(&self) -> &str {
158        match self {
159            Self::Success(s) => s,
160            Self::Error { message, .. } => message,
161        }
162    }
163}
164
165/// Two-tier tool execution model (trusty-agents #447).
166///
167/// Why: The dispatch path treats always-on tools fundamentally differently
168///      from on-demand tools — they run automatically, their output becomes
169///      context rather than a `tool_result`, and they must not appear in the
170///      LLM's tool list. Encoding the distinction as an enum on the trait
171///      makes it impossible to accidentally schedule an `AlwaysOn` tool as
172///      `OnDemand` or vice-versa.
173/// What: `OnDemand` is the default (current behavior); `AlwaysOn` opts the
174///       tool into the pre-LLM context-building pipeline.
175/// Test: Default exercised by every existing tool; `AlwaysOn` exercised by
176///       `trusty-agents`'s `tools/always_on::build_live_context_*`.
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
178pub enum ToolExecutionTier {
179    #[default]
180    OnDemand,
181    AlwaysOn,
182}
183
184/// RBAC service tier (trusty-agents #445).
185///
186/// Why: Different transports (CLI, Slack, Telegram, HTTP) expose the same
187///      tool registry to users with different trust levels. Tools opt into
188///      RBAC by listing the tiers that must be denied access. Defined here
189///      (not in `trusty-agents/rbac`) because the `ToolExecutor::restricted_tiers`
190///      signature returns `&[ServiceTier]` — external agent crates would not
191///      be able to implement the trait without seeing the enum.
192/// What: `All` (full access — controller / authenticated operator),
193///       `Analytics` (read + analytical queries, no mutations), `ReadOnly`
194///       (passive observation only, the strictest tier).
195///       Serializes as `snake_case` so TOML/JSON authors can write
196///       `tier = "read_only"` rather than the variant name. `Default` is
197///       `All` so callsites that forget to set a tier degrade open at the
198///       controller (unauthenticated transports MUST set a stricter default).
199/// Test: `trusty-agents/rbac` covers serde + ordering; `trusty-agents/tools/mod::dispatch_for_user_*`
200///       covers integration with dispatch.
201#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize, Serialize, Default)]
202#[serde(rename_all = "snake_case")]
203pub enum ServiceTier {
204    /// Full access — the controller / authenticated operator.
205    #[default]
206    All,
207    /// Analytics-only tier — read + analytical queries, no mutations.
208    Analytics,
209    /// Read-only tier — passive observation only. The strictest tier.
210    ReadOnly,
211}
212
213/// A tool invocable by an LLM through function calling.
214///
215/// Why: Replaces hardcoded string-match dispatch with polymorphic execution.
216///      Living in `trusty-agents-common` (not in `trusty-agents`) so external agent
217///      crates can implement it without depending on the full host crate,
218///      breaking the cargo dependency cycle.
219/// What: Supplies OpenAI-compatible JSON schema via `schema()` and executes
220///       parsed arguments in `execute()`. Returns a structured `ToolResult`
221///       so failures can be surfaced back to the LLM without tearing down
222///       the loop.
223/// Test: See unit tests in `trusty-agents/tools/mod.rs` for `ToolRegistry`.
224#[async_trait]
225pub trait ToolExecutor: Send + Sync {
226    /// Tool name — must match `function.name` in the schema and the LLM's
227    /// `tool_call.name`.
228    fn name(&self) -> &str;
229
230    /// Full OpenAI-compatible tool schema object (`{"type":"function", ...}`).
231    fn schema(&self) -> Value;
232
233    /// Execute the tool with already-parsed JSON arguments.
234    ///
235    /// Why: Returning `ToolResult` rather than `Result<String>` means
236    ///      transient / user-visible failures (missing arg, HTTP 500, refused
237    ///      command) flow back to the LLM as structured errors instead of
238    ///      aborting the whole turn.
239    /// What: Returns `ToolResult::Success` on success or `ToolResult::Error`
240    ///       on failure.
241    /// Test: Each concrete impl has tests; registry dispatches through this.
242    async fn execute(&self, args: Value) -> ToolResult;
243
244    /// Tiers that are NOT permitted to invoke this tool.
245    ///
246    /// Why: RBAC at the dispatch boundary; see `ServiceTier`.
247    /// What: Default returns empty (no restriction). Concrete tools override.
248    /// Test: exercised by `trusty-agents`'s `tools/mod::filter_tools_for_user_*`.
249    fn restricted_tiers(&self) -> &[ServiceTier] {
250        &[]
251    }
252
253    /// Whether this tool is `AlwaysOn` or `OnDemand`.
254    ///
255    /// Why: Always-on tools run automatically before each LLM call; on-demand
256    ///      tools appear in the LLM's tool list. See `ToolExecutionTier`.
257    /// What: Default returns `OnDemand`.
258    /// Test: exercised by `trusty-agents`'s `tools/always_on::build_live_context_*`.
259    fn execution_tier(&self) -> ToolExecutionTier {
260        ToolExecutionTier::OnDemand
261    }
262
263    /// The OpenRPC scope this tool was discovered under (trusty-agents #453,
264    /// #3208), e.g. `"google.gmail.read"`.
265    ///
266    /// Why: Only tools sourced from the OpenRPC tool registry (endpoints like
267    ///      `gworkspace`, `trusty-memory`) carry a meaningful scope —
268    ///      in-process tools (git, delegate_to_agent, shell, ...) are gated
269    ///      entirely by the existing name/glob allowlist + RBAC-tier checks
270    ///      and have no scope concept. Defaulting to `None` means "not part
271    ///      of the scoped surface, not subject to scope-pattern gating"
272    ///      rather than "unscoped == open" — callers that DO consult scopes
273    ///      only apply the check when this returns `Some`.
274    /// What: Default returns `None`. `RegistryToolExecutor` overrides this
275    ///       with its `DiscoveredTool`'s `scope` field.
276    /// Test: `trusty-agents/tools/registry/adapter` round-trips the override;
277    ///       `trusty-agents/ctrl/pm_task/dispatch/persona::filter_persona_tool_names_*`
278    ///       covers the enforcement consumer.
279    fn scope(&self) -> Option<&str> {
280        None
281    }
282}
283
284/// Named bundle of `ToolExecutor`s for a specific persona.
285///
286/// Why: Replaces hard-coded persona-to-tool branches in `trusty-agents`'s
287///      `ctrl/mod.rs` with a data-driven injection point. New agent crates
288///      register by adding themselves to the plugin list constructed in
289///      `trusty-agents`'s `main.rs`; ctrl never needs to learn their names.
290///      Lives here (not in `trusty-agents`) so agent crates can construct one
291///      without depending on the host.
292/// What: Holds the persona name the plugin's tools apply to plus an
293///       `Arc<dyn ToolExecutor>` per tool. Cloning is cheap (Arc reference
294///       counts) so the plugin can be reused across sessions.
295/// Test: indirectly, by the trusty-agents python_skill tests that build plugins.
296#[derive(Clone)]
297pub struct AgentPlugin {
298    /// Persona name (e.g. `"example-assistant"`) this plugin's tools belong to.
299    pub persona_name: String,
300    /// Tool executors to register when the named persona becomes active.
301    pub tools: Vec<Arc<dyn ToolExecutor>>,
302}
303
304impl AgentPlugin {
305    /// Construct a plugin for the named persona.
306    ///
307    /// Why: Single canonical constructor keeps callers from accidentally
308    ///      leaving fields uninitialised when the struct grows.
309    /// What: Stores the persona name (converting `impl Into<String>` so
310    ///       call sites can pass `&str` literals) and the tool vector.
311    /// Test: Indirectly via `agent_plugin_lookup_returns_matching_plugin`
312    ///       (`trusty-agents`), which constructs plugins through this ctor.
313    pub fn new(persona_name: impl Into<String>, tools: Vec<Arc<dyn ToolExecutor>>) -> Self {
314        Self {
315            persona_name: persona_name.into(),
316            tools,
317        }
318    }
319}
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324
325    /// Verifies `is_error` splits `Success` from both `Error` flavours.
326    ///
327    /// Why: Dispatch paths branch on this predicate to decide whether to feed
328    ///      the LLM an `is_error: true` tool result. This assertion used to
329    ///      live in a downstream agent crate, deleted in #3732 — it belongs
330    ///      beside the type it covers, not in a downstream agent crate.
331    /// What: Asserts `ok` is not an error while `err`/`fatal` both are.
332    /// Test: self.
333    #[test]
334    fn tool_result_is_error_distinguishes_variants() {
335        assert!(!ToolResult::ok("done").is_error());
336        assert!(ToolResult::err("retry me").is_error());
337        assert!(ToolResult::fatal("bad creds").is_error());
338    }
339
340    /// Verifies `is_fatal` is true only for the non-recoverable error.
341    ///
342    /// Why: Callers stop the loop on fatal and keep going on recoverable;
343    ///      conflating the two either hangs on unrecoverable failures or
344    ///      aborts on transient ones.
345    /// What: Asserts `fatal` is fatal while `err` and `ok` are not.
346    /// Test: self.
347    #[test]
348    fn tool_result_is_fatal_only_for_non_recoverable() {
349        assert!(ToolResult::fatal("bad creds").is_fatal());
350        assert!(!ToolResult::err("retry me").is_fatal());
351        assert!(!ToolResult::ok("done").is_fatal());
352    }
353}