trusty_code/agents/protocol.rs
1//! `agents.*` JSON-RPC methods — the daemon's full-tier AGENT CATALOG
2//! surface (issue #3449), backing the Foundry GUI's Agents management tab.
3//!
4//! Why: distinct from `session.get_agents` (`crate::serve::rest::agents` /
5//! `crate::session::protocol_agents`), which answers "who is running (or
6//! ran) inside one existing session" — this module answers "what agents
7//! could I dispatch?", independent of any session. The GUI's Agents tab
8//! needs to list every agent across BOTH tiers `resolve_agent` already
9//! recognises (embedded ∪ disk — see [`super::resolve_agent`]'s docs) and
10//! let an operator add/remove disk-tier ones; the embedded roster (32
11//! agents incl. `pm`, #2958/#3437) is compiled in and therefore read-only.
12//! There is exactly ONE disk tier active at a time — `<binding
13//! root>/.claude/agents` when a project is bound, `~/.claude/agents`
14//! (Claude-Code's user-level convention) when projectless (see
15//! `crate::binding::ProjectBinding::agents_dir`) — so every disk entry this
16//! module reports carries the SAME tier label for one daemon instance,
17//! computed once at [`register`] time from how the daemon itself was
18//! started, never re-derived per request.
19//! What: [`register`] wires three methods onto a shared, immutable
20//! [`AgentsCatalogState`] (`dir` + `tier`, both fixed for the daemon's
21//! lifetime — no `Mutex` needed, every operation here is a stateless
22//! filesystem call):
23//! - `agents.list` -> `{"agents": [{name, tier, description?, model?}]}`,
24//! the union of the embedded roster (`tier: "embedded"`) and the
25//! resolved disk tier (`tier: "project"` or `"user"`) — a disk agent
26//! overriding an embedded name WINS and suppresses the embedded copy of
27//! that name, mirroring [`super::resolve_agent`]'s disk-wins precedence
28//! exactly (so the catalog never shows the same name twice with two
29//! different tiers). An unparseable disk file surfaces as `tier:
30//! "broken"` (see [`agents_list`]'s docs) — again mirroring
31//! `resolve_agent`, whose disk-wins rule applies even to a malformed
32//! file, so dispatch of that name fails rather than falling back.
33//! - `agents.create{name, content}` -> writes
34//! `<dir>/<name>.md` from the caller-supplied Markdown+frontmatter body.
35//! Rejects (see [`validate_agent_name`]) a `name` that is empty, exceeds
36//! [`MAX_AGENT_NAME_LEN`], contains anything outside `[a-z0-9-]`, or
37//! collides with an EMBEDDED name (embedded is read-only — this endpoint
38//! never lets a disk file silently shadow it) with `-32001
39//! permission_denied` (403); an already-existing disk file of the same
40//! name with a `-32009 already_exists` conflict (409, use
41//! delete-then-create to replace).
42//! - `agents.delete{name}` -> removes `<dir>/<name>.md`. `-32002 not_found`
43//! (404) if no disk file exists under that name; `-32001
44//! permission_denied` (403) if `name` names an EMBEDDED agent (nothing
45//! to delete on disk — the embedded roster cannot be removed).
46//!
47//! Test: `tests::*`.
48
49use std::path::{Path, PathBuf};
50
51use serde::Deserialize;
52use serde_json::{Value, json};
53
54use crate::jsonrpc::{ConnectionContext, Router, RpcError};
55
56use super::{AgentConfig, discover_agents, load_embedded_default_agents, md_loader};
57
58/// Maximum length for a caller-supplied agent `name` in [`agents_create`].
59///
60/// Why: a generous but finite bound — long enough for any real agent slug,
61/// short enough to reject a pathological payload before it ever reaches the
62/// filesystem.
63const MAX_AGENT_NAME_LEN: usize = 64;
64
65/// Shared, immutable state every `agents.*` handler in this module closes
66/// over: the resolved disk agents directory and its tier label for this
67/// daemon instance.
68///
69/// Why: `dir`/`tier` are fixed for the daemon's entire lifetime (derived
70/// once from `ProjectBinding` at startup, see `crate::serve::build_router_at`)
71/// — no shared mutable state, no `Mutex`, unlike `WorkstreamStore`.
72/// What: `dir` is `ProjectBinding::agents_dir()`'s result; `tier` is
73/// `"project"` when a project is bound, `"user"` when projectless.
74#[derive(Clone)]
75pub struct AgentsCatalogState {
76 /// The resolved disk agents directory (project- or user-scoped).
77 pub dir: PathBuf,
78 /// `"project"` or `"user"` — which tier `dir` represents.
79 pub tier: &'static str,
80}
81
82impl AgentsCatalogState {
83 /// Build state from a resolved agents directory and whether a project
84 /// is bound.
85 ///
86 /// Why: keeps the "project bound -> tier project, else user" rule in one
87 /// place rather than re-deriving it at every call site that constructs
88 /// this state (today: `crate::serve::build_router_at`).
89 /// What: `tier = "project"` when `project_bound`, else `"user"`.
90 pub fn new(dir: PathBuf, project_bound: bool) -> Self {
91 Self {
92 dir,
93 tier: if project_bound { "project" } else { "user" },
94 }
95 }
96}
97
98/// Register `agents.list`, `agents.create`, `agents.delete` onto `router`.
99///
100/// Why: the one place listing this namespace's full surface, mirroring
101/// every other `*::protocol::register` in this crate.
102/// What: clones `state` once per method (cheap — `PathBuf` + `&'static
103/// str`) into a small adapter closure that forwards to the corresponding
104/// free function below.
105/// Test: `tests::register_wires_all_three_methods`.
106pub fn register(router: &mut Router, state: AgentsCatalogState) {
107 let s = state.clone();
108 router.register(
109 "agents.list",
110 move |params: Value, ctx: ConnectionContext| {
111 let s = s.clone();
112 async move { agents_list(&s, params, ctx).await }
113 },
114 );
115
116 let s = state.clone();
117 router.register(
118 "agents.create",
119 move |params: Value, ctx: ConnectionContext| {
120 let s = s.clone();
121 async move { agents_create(&s, params, ctx).await }
122 },
123 );
124
125 let s = state;
126 router.register(
127 "agents.delete",
128 move |params: Value, ctx: ConnectionContext| {
129 let s = s.clone();
130 async move { agents_delete(&s, params, ctx).await }
131 },
132 );
133}
134
135/// Whether `name` names one of the 5 `BASE-*` composition-template agents
136/// (`base-agent`, `base-engineer`, `base-ops`, `base-qa`, `base-research` —
137/// see [`crate::assets::BASE_AGENT_NAMES`]) rather than a real, dispatchable
138/// agent.
139///
140/// Why: these 5 templates exist ONLY to be `extends:`-ed by concrete agents
141/// (`agents::resolve_agent`/`agents::md_loader::load_md_agent` must keep
142/// resolving them by name — that is how composition works) and are NEVER
143/// meant to be dispatched directly. [`crate::assets::DEFAULT_AGENTS`]
144/// already never includes them (Slice E3, #2958's roster decision — see
145/// `assets::tests::base_templates_are_never_dispatchable`), but a real
146/// project's disk `.claude/agents/` dir can legitimately contain
147/// `BASE-*.md` files (trusty-mpm's own bundle installs them verbatim —
148/// `crates/trusty-mpm/src/core/bundle_all.rs`), so [`agents_list`]'s disk
149/// half must filter them out itself — this is that single filter, not a
150/// scattered `starts_with` check per call site.
151/// What: case-insensitive membership in [`crate::assets::BASE_AGENT_NAMES`]
152/// — the disk filename convention is `BASE-QA.md` (uppercase stem) while
153/// the frontmatter `name:`/`extends:` convention is lowercase `base-qa`, so
154/// this must tolerate either.
155/// Test: `tests::list_excludes_base_agents_but_resolve_agent_still_finds_them`.
156///
157/// `pub(crate)`: also reused by `plugins::agents::discover_plugin_agents`
158/// (#3539) so a plugin literally shipping `base-engineer.md` etc. is
159/// excluded from the catalog exactly like the embedded/disk tiers, via the
160/// same single filter.
161pub(crate) fn is_base_agent(name: &str) -> bool {
162 crate::assets::BASE_AGENT_NAMES.contains(&name.to_ascii_lowercase().as_str())
163}
164
165/// Wire shape for one catalog entry — shared by `agents.list`'s embedded and
166/// disk halves so the two are indistinguishable to a client beyond `tier`.
167fn entry_json(cfg: &AgentConfig, tier: &str) -> Value {
168 json!({
169 "name": cfg.agent.name,
170 "tier": tier,
171 "description": cfg.agent.description,
172 "model": cfg.agent.model,
173 })
174}
175
176/// `agents.list` -> the full embedded ∪ disk catalog.
177///
178/// Why: the GUI's Agents tab roster fetch — see module docs for the
179/// disk-wins-over-embedded union rule.
180/// What: ignores `params` (no filters yet). Builds the embedded set keyed by
181/// name, then overlays disk entries, removing the embedded entry of the same
182/// name whenever a disk override exists. A disk `.md` that FAILS to parse is
183/// surfaced as `tier: "broken"` (description = the parse error, still
184/// overriding any embedded entry of the same name) rather than skipped —
185/// because [`super::resolve_agent`]'s disk-wins rule applies even to a
186/// malformed file ("a disk parse error is surfaced, never silently
187/// substituted", #3441), dispatch of that name WILL fail, and a catalog
188/// that skipped the broken file would show the shadowed embedded entry as
189/// healthy/dispatchable — lying about what `task.run` will actually do
190/// (code-critic PR #3465 review, MEDIUM). A broken entry keeps the delete
191/// affordance: removing the bad file is exactly the repair path. Sorted by
192/// name.
193///
194/// The 5 `BASE-*` composition-template agents ([`is_base_agent`]) are
195/// excluded from this list entirely — on either tier — because they are
196/// extends-sources only and never meant to be dispatched (issue #3465
197/// follow-up). This is a LISTING-only filter: [`super::resolve_agent`] and
198/// `md_loader::load_md_agent` are untouched, so composition (a leaf agent's
199/// `extends: base-engineer`) keeps working exactly as before — only the
200/// user-facing catalog an operator browses/picks from hides them.
201///
202/// A FOURTH tier, `"plugin"`, is layered on top when `state.tier ==
203/// "project"` (issue #3539 — Phase 1 Claude Code plugin support): every
204/// agent discovered under `<project_root>/.claude/plugins/*/agents/` is
205/// added, namespaced `<plugin>:<name>` by
206/// `plugins::agents::discover_plugin_agents`. This is ADDITIVE ONLY — the
207/// namespaced key can never collide with an embedded or disk agent's
208/// unnamespaced name, so a plugin agent never overrides (or is suppressed
209/// by) a project/embedded entry of the "same" local name; see that
210/// function's docs for the base-agent-name exclusion it applies too.
211/// Projectless daemons (`state.tier == "user"`) see no plugin tier — #3539
212/// scopes plugin discovery to a bound project's `.claude/plugins/`.
213/// Test: `tests::list_returns_embedded_when_disk_empty`,
214/// `tests::list_disk_override_wins_and_suppresses_embedded`,
215/// `tests::list_disk_only_entries_are_additive`,
216/// `tests::list_marks_unparseable_disk_override_as_broken`,
217/// `tests::list_excludes_base_agents_but_resolve_agent_still_finds_them`,
218/// `tests::list_includes_namespaced_plugin_agents`,
219/// `tests::list_plugin_agent_does_not_override_project_agent_of_same_local_name`.
220async fn agents_list(
221 state: &AgentsCatalogState,
222 _params: Value,
223 _ctx: ConnectionContext,
224) -> Result<Value, RpcError> {
225 let mut by_name: Vec<(String, Value)> = load_embedded_default_agents()
226 .iter()
227 .filter(|cfg| !is_base_agent(&cfg.agent.name))
228 .map(|cfg| (cfg.agent.name.clone(), entry_json(cfg, "embedded")))
229 .collect();
230
231 for (name, path) in discover_agents(&state.dir) {
232 if is_base_agent(&name) {
233 continue;
234 }
235 let entry = match md_loader::load_md_agent(&path) {
236 Ok(cfg) => entry_json(&cfg, state.tier),
237 Err(e) => {
238 tracing::warn!("agents.list: disk agent '{name}' is unparseable: {e}");
239 json!({
240 "name": name,
241 "tier": "broken",
242 "description": format!("unparseable agent file — dispatch of this name will fail until it is fixed or deleted: {e}"),
243 "model": Value::Null,
244 })
245 }
246 };
247 match by_name.iter_mut().find(|(n, _)| *n == name) {
248 Some(slot) => slot.1 = entry,
249 None => by_name.push((name, entry)),
250 }
251 }
252
253 if state.tier == "project"
254 && let Some(project_root) = crate::plugins::project_root_two_levels_up(&state.dir)
255 {
256 for cfg in crate::plugins::agents::discover_plugin_agents(&project_root) {
257 let name = cfg.agent.name.clone();
258 // Namespacing already guarantees no collision with an
259 // unnamespaced project/embedded name; the containment check is
260 // defense-in-depth so "additive only" holds even if two plugins
261 // resolved to the same namespaced name (first one found wins).
262 if !by_name.iter().any(|(n, _)| *n == name) {
263 by_name.push((name, entry_json(&cfg, "plugin")));
264 }
265 }
266 }
267
268 by_name.sort_by(|a, b| a.0.cmp(&b.0));
269 let agents: Vec<Value> = by_name.into_iter().map(|(_, v)| v).collect();
270 Ok(json!({ "agents": agents }))
271}
272
273/// `params` shape for `agents.create`.
274#[derive(Deserialize)]
275struct CreateParams {
276 name: String,
277 content: String,
278}
279
280/// Validate a caller-supplied agent/skill name against the shared naming
281/// contract (issue #3449): non-empty, `[a-z0-9-]` only, bounded length.
282///
283/// Why: this is ALSO the path-traversal guard — a name matching this
284/// pattern can never contain `/`, `..`, or any other path-breaking
285/// character, so `dir.join(format!("{name}.md"))` is always confined to
286/// `dir` by construction. Shared verbatim by `agents::protocol` and
287/// `skills::protocol` (issue #3449's paired endpoints) so the two surfaces
288/// can never drift into two different naming rules.
289/// What: `Err(RpcError::invalid_argument(..))` on any violation.
290/// Test: `tests::validate_name_rejects_empty`,
291/// `tests::validate_name_rejects_uppercase`,
292/// `tests::validate_name_rejects_path_traversal`,
293/// `tests::validate_name_rejects_too_long`,
294/// `tests::validate_name_accepts_lowercase_alnum_hyphen`.
295pub(crate) fn validate_agent_name(name: &str) -> Result<(), RpcError> {
296 if name.is_empty() {
297 return Err(RpcError::invalid_argument("name must not be empty"));
298 }
299 if name.len() > MAX_AGENT_NAME_LEN {
300 return Err(RpcError::invalid_argument(format!(
301 "name must be at most {MAX_AGENT_NAME_LEN} characters"
302 )));
303 }
304 if !name
305 .bytes()
306 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
307 {
308 return Err(RpcError::invalid_argument(
309 "name must match [a-z0-9-]+ (lowercase letters, digits, hyphens only)",
310 ));
311 }
312 Ok(())
313}
314
315/// `agents.create` -> write `<dir>/<name>.md` from `content`.
316///
317/// Why: the GUI's Agents tab add-flow — creates a new disk-tier agent.
318/// What: `201`-shaped success `{"name", "tier"}` (REST layer maps this to
319/// `201 Created`, see `serve::rest::agent_catalog::create`). Errors: invalid
320/// `name` (`-32602`/`-32003`), `name` collides with an embedded agent
321/// (`-32001 permission_denied`, 403 — embedded is read-only), an existing
322/// disk file of the same name (`-32009 already_exists`, 409, use
323/// delete-then-create to replace), or a write-side I/O failure (`-32603
324/// internal`). The existence check is NOT a separate `path.exists()`
325/// pre-check — that was a TOCTOU hole (code-critic PR #3465 review, HIGH 1:
326/// two concurrent creates with the same name could both pass the check and
327/// the second would silently clobber the first, violating the documented
328/// 409 invariant). [`write_new_file`] makes the check-and-create a single
329/// atomic `O_CREAT|O_EXCL` filesystem operation instead.
330/// Test: `tests::create_writes_file_and_returns_tier`,
331/// `tests::create_rejects_invalid_name`,
332/// `tests::create_rejects_embedded_name_collision`,
333/// `tests::create_rejects_existing_disk_file`,
334/// `tests::create_conflict_does_not_clobber_existing_content`.
335async fn agents_create(
336 state: &AgentsCatalogState,
337 params: Value,
338 _ctx: ConnectionContext,
339) -> Result<Value, RpcError> {
340 let p: CreateParams = serde_json::from_value(params)
341 .map_err(|e| RpcError::invalid_params(format!("agents.create: {e}")))?;
342
343 validate_agent_name(&p.name)?;
344
345 if crate::assets::DEFAULT_AGENTS
346 .iter()
347 .any(|a| a.name() == p.name)
348 {
349 return Err(RpcError::permission_denied(format!(
350 "'{}' is an embedded agent and cannot be overridden by name via this endpoint",
351 p.name
352 )));
353 }
354
355 let path = agent_path(&state.dir, &p.name)?;
356 if let Some(parent) = path.parent() {
357 std::fs::create_dir_all(parent)
358 .map_err(|e| RpcError::internal(format!("creating agents dir: {e}")))?;
359 }
360 write_new_file(&path, &p.content, || {
361 format!("agent '{}' already exists on disk", p.name)
362 })?;
363
364 Ok(json!({ "name": p.name, "tier": state.tier }))
365}
366
367/// Atomically create `path` with `content`, failing with `-32009
368/// already_exists` if the file already exists — the ONE way both
369/// `agents.create` and `skills.create` materialise a new catalog file.
370///
371/// Why: a `path.exists()` pre-check followed by `std::fs::write` is a
372/// TOCTOU race — two concurrent creates can both pass the check, and the
373/// loser's `write` silently clobbers the winner (code-critic PR #3465
374/// review, HIGH 1/HIGH 2). `OpenOptions::create_new(true)` maps to
375/// `O_CREAT|O_EXCL`: the kernel makes existence-check-plus-create one
376/// atomic operation, so exactly one of N racing creates succeeds and every
377/// other receives `ErrorKind::AlreadyExists`, which this maps onto the same
378/// `409`-shaped conflict the pre-check used to (approximately) provide.
379/// What: `conflict_msg` is lazily built only on the conflict path. Any
380/// other I/O failure maps to `-32603 internal`.
381/// Test: `tests::create_rejects_existing_disk_file`,
382/// `tests::create_conflict_does_not_clobber_existing_content`,
383/// `crate::skills::protocol::tests::create_rejects_existing_disk_skill`.
384pub(crate) fn write_new_file(
385 path: &Path,
386 content: &str,
387 conflict_msg: impl FnOnce() -> String,
388) -> Result<(), RpcError> {
389 use std::io::Write;
390
391 let mut file = match std::fs::OpenOptions::new()
392 .write(true)
393 .create_new(true)
394 .open(path)
395 {
396 Ok(f) => f,
397 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
398 return Err(RpcError::already_exists(conflict_msg()));
399 }
400 Err(e) => return Err(RpcError::internal(format!("creating file: {e}"))),
401 };
402 file.write_all(content.as_bytes())
403 .map_err(|e| RpcError::internal(format!("writing file: {e}")))?;
404 Ok(())
405}
406
407/// `params` shape for `agents.delete`.
408#[derive(Deserialize)]
409struct DeleteParams {
410 name: String,
411}
412
413/// `agents.delete` -> remove `<dir>/<name>.md`.
414///
415/// Why: the GUI's Agents tab remove-flow (two-step inline confirm on the
416/// client side — this endpoint itself is a single, non-idempotent DELETE).
417/// What: `{}` on success. `-32002 not_found` (404) when no disk file exists
418/// under `name` AND it is not embedded; `-32001 permission_denied` (403)
419/// when `name` names an embedded agent (nothing to delete — the embedded
420/// roster is compiled in, never on disk).
421/// Test: `tests::delete_removes_disk_file`,
422/// `tests::delete_missing_name_returns_not_found`,
423/// `tests::delete_embedded_name_returns_permission_denied`.
424async fn agents_delete(
425 state: &AgentsCatalogState,
426 params: Value,
427 _ctx: ConnectionContext,
428) -> Result<Value, RpcError> {
429 let p: DeleteParams = serde_json::from_value(params)
430 .map_err(|e| RpcError::invalid_params(format!("agents.delete: {e}")))?;
431 validate_agent_name(&p.name)?;
432
433 let path = agent_path(&state.dir, &p.name)?;
434 if !path.exists() {
435 if crate::assets::DEFAULT_AGENTS
436 .iter()
437 .any(|a| a.name() == p.name)
438 {
439 return Err(RpcError::permission_denied(format!(
440 "'{}' is an embedded agent and cannot be deleted",
441 p.name
442 )));
443 }
444 return Err(RpcError::not_found(format!(
445 "no disk agent named '{}'",
446 p.name
447 )));
448 }
449
450 std::fs::remove_file(&path).map_err(|e| RpcError::internal(format!("deleting agent: {e}")))?;
451 Ok(json!({}))
452}
453
454/// Join a validated `name` onto `dir` as `<dir>/<name>.md`.
455///
456/// Why: one seam for the join so both write paths (`create`, `delete`)
457/// build the path identically; `name` must already have passed
458/// [`validate_agent_name`] before this is called (it re-validates as a
459/// defense-in-depth belt-and-suspenders, never trust-by-construction alone).
460/// What: `Err` if `name` fails validation; otherwise `dir.join("<name>.md")`.
461fn agent_path(dir: &Path, name: &str) -> Result<PathBuf, RpcError> {
462 validate_agent_name(name)?;
463 Ok(dir.join(format!("{name}.md")))
464}
465
466#[cfg(test)]
467#[path = "protocol_tests.rs"]
468mod tests;