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