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