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