trusty_code/plugins/agents.rs
1//! Phase-1 plugin AGENT ingestion: discovery, namespacing, and resolution
2//! (issue #3539).
3//!
4//! Why: a plugin's `agents/*.md` files are the exact same
5//! Markdown+frontmatter format `agents::md_loader` already parses for
6//! project/embedded agents — the only new work is namespacing
7//! (`<plugin>:<name>`) and two Phase-1 leaf-only guarantees #3539 locks in:
8//! unsupported frontmatter fields (`effort`/`maxTurns`/`memory`/`isolation`/
9//! `disallowedTools` — trusty-mpm's own agent schema, which a plugin may
10//! carry over) are dropped with a warning rather than failing the load, and
11//! an `extends:` chain is never composed (a plugin agent is always a leaf —
12//! cross-catalog compose is a later-phase item).
13//! What: [`discover_plugin_agents`] lists every plugin agent as a fully
14//! projected [`AgentConfig`] (used by `agents::protocol::agents_list`'s
15//! `plugin` tier); [`find_plugin_agent_config`] resolves one namespaced
16//! `<plugin>:<name>` on demand (used by `agents::resolve_agent`, the
17//! dispatch path). Both route through [`load_plugin_agent`], which reuses
18//! `agents::md_loader`'s frontmatter/body parsing
19//! ([`crate::agents::md_loader::extract_body`],
20//! [`crate::agents::md_loader::project_to_agent_config`]) rather than
21//! duplicating the projection — the only difference from a disk agent load
22//! is the namespaced name and the two Phase-1 guards above.
23//! Test: `tests::*` — discovery finds and namespaces agents, unsupported
24//! fields are dropped with a warning, `extends:` is warned-and-ignored,
25//! resolution finds/misses a namespaced name, a base-agent-named plugin
26//! agent is excluded from listing.
27
28use std::path::Path;
29
30use anyhow::Context;
31use trusty_agents_common::agents::metadata::agent_metadata_from_str;
32
33use crate::agents::AgentConfig;
34use crate::agents::md_loader::{extract_body, project_to_agent_config};
35
36use super::discover_plugin_roots;
37
38/// trusty-mpm agent-frontmatter fields tcode's `AgentConfig` has no slot
39/// for. Present on a plugin agent, they are dropped with one aggregated
40/// warning rather than failing the load (#3539's locked Phase-1 contract).
41const UNSUPPORTED_AGENT_FIELDS: &[&str] = &[
42 "effort",
43 "maxTurns",
44 "memory",
45 "isolation",
46 "disallowedTools",
47];
48
49/// List every plugin agent across every discovered plugin, fully projected
50/// and namespaced.
51///
52/// Why: `agents::protocol::agents_list`'s `plugin` tier needs the same
53/// `AgentConfig` shape (for `description`/`model` in its wire entry) the
54/// embedded and disk tiers already produce.
55/// What: for each [`PluginRoot`](crate::plugins::PluginRoot), scans `agents_dir` via
56/// `agents::discover_agents` (the same `.md`-only, `.toml`-warns scan disk
57/// agents use), skips any local name `agents::protocol::is_base_agent`
58/// recognizes (a plugin literally shipping `base-engineer.md` etc. is
59/// excluded exactly like the embedded/disk tiers — #3539's base-filter
60/// interaction clause), and loads the rest via
61/// [`load_plugin_agent`]. A load failure is logged at WARN and skipped
62/// (never aborts the whole scan), mirroring `agents::load_all_agents`'s
63/// per-file resilience. Sorted by the final namespaced name.
64/// Test: `tests::discover_plugin_agents_namespaces_entries`,
65/// `tests::discover_plugin_agents_excludes_base_named_agent`,
66/// `tests::discover_plugin_agents_skips_unparseable_agent`.
67pub fn discover_plugin_agents(project_root: &Path) -> Vec<AgentConfig> {
68 let mut out: Vec<AgentConfig> = Vec::new();
69 for root in discover_plugin_roots(project_root) {
70 for (agent_name, path) in crate::agents::discover_agents(&root.agents_dir) {
71 if crate::agents::protocol::is_base_agent(&agent_name) {
72 continue;
73 }
74 match load_plugin_agent(&root.name, &agent_name, &path, &root.agents_dir) {
75 Ok(cfg) => out.push(cfg),
76 Err(e) => tracing::warn!("skipping plugin agent '{}:{agent_name}': {e}", root.name),
77 }
78 }
79 }
80 out.sort_by(|a, b| a.agent.name.cmp(&b.agent.name));
81 out
82}
83
84/// Load one plugin agent file, namespaced `<plugin>:<agent_name>`.
85///
86/// Why: the single load path both [`discover_plugin_agents`] (listing) and
87/// [`find_plugin_agent_config`] (dispatch resolution) share, so the
88/// namespacing + unsupported-field-drop + extends-warn contract is written
89/// exactly once.
90/// What: FIRST requires `path`'s canonicalized identity to stay contained
91/// within `agents_dir`'s own canonicalization
92/// (`plugins::path_is_contained` — code-critic PR #3547 re-review,
93/// CRITICAL 5, CWE-59) — rejects a `path` that is (or resolves through) a
94/// symlink escaping `agents_dir`, e.g. `agents/leak.md -> ~/.ssh/id_rsa`,
95/// BEFORE any content is read. Only then reads `path`, parses frontmatter
96/// via `trusty_agents_common::agents::metadata::agent_metadata_from_str`
97/// (no `compose_agent` call — a plugin agent is a leaf, #3539), warns and
98/// drops any [`UNSUPPORTED_AGENT_FIELDS`] present (see
99/// [`warn_unsupported_fields`]), warns (never errors) on a present
100/// `extends:` — the agent is still loaded as a direct/leaf document with no
101/// inheritance resolved — then projects via
102/// `agents::md_loader::project_to_agent_config` exactly as a disk agent
103/// would, overriding only `agent.name` with the namespaced form. An
104/// unreadable file or a rejected symlink are the only error paths.
105/// Test: `tests::load_plugin_agent_projects_fields`,
106/// `tests::load_plugin_agent_warns_and_drops_unsupported_fields`,
107/// `tests::load_plugin_agent_warns_on_extends_and_treats_as_leaf`,
108/// `tests::load_plugin_agent_missing_file_errors`,
109/// `tests::load_plugin_agent_rejects_symlinked_file`.
110pub(crate) fn load_plugin_agent(
111 plugin: &str,
112 agent_name: &str,
113 path: &Path,
114 agents_dir: &Path,
115) -> anyhow::Result<AgentConfig> {
116 let namespaced = format!("{plugin}:{agent_name}");
117
118 if !super::path_is_contained(path, agents_dir) {
119 anyhow::bail!(
120 "plugin agent '{namespaced}' at {} is a symlink (or resolves through one) outside \
121 the plugin's agents directory — rejected as a potential host-file disclosure \
122 (#3547)",
123 path.display()
124 );
125 }
126
127 let raw = std::fs::read_to_string(path)
128 .with_context(|| format!("reading plugin agent {}", path.display()))?;
129
130 warn_unsupported_fields(&namespaced, &raw);
131
132 let meta = agent_metadata_from_str(&raw);
133 if let Some(parent) = &meta.extends {
134 tracing::warn!(
135 "plugin agent '{namespaced}' declares extends: '{parent}' — tcode Phase 1 plugin \
136 agents are leaf-only (no cross-catalog compose, #3539); loading its own \
137 frontmatter/body only, the parent is not resolved"
138 );
139 }
140
141 let body = extract_body(&raw);
142 let mut cfg = project_to_agent_config(agent_name, meta, body);
143 // #7948: a plugin agent gets the same grammar and fail-closed rejection
144 // a disk agent does; the error names the file an operator must fix.
145 cfg.permissions = crate::permissions::parse_permissions(&path.display().to_string(), &raw)?;
146 cfg.agent.name = namespaced;
147 Ok(cfg)
148}
149
150/// Warn once (one aggregated line) when `raw`'s frontmatter declares any
151/// [`UNSUPPORTED_AGENT_FIELDS`].
152///
153/// Why: `#3539` requires "DROP unsupported plugin fields ... with a
154/// one-line warn per agent" — one line naming every dropped field, not one
155/// line per field (mirrors `agents::warn_on_orphaned_toml`'s aggregation
156/// convention). Uses `skills::frontmatter::parse_frontmatter`'s generic
157/// flat key/value scan (reused across the agents/skills domain split
158/// rather than re-implemented) purely to detect KEY PRESENCE — the
159/// supported-field values themselves are parsed separately via
160/// `agent_metadata_from_str`.
161/// What: no-op when none of the fields are present.
162/// Test: `tests::load_plugin_agent_warns_and_drops_unsupported_fields`.
163fn warn_unsupported_fields(namespaced: &str, raw: &str) {
164 let map = crate::skills::frontmatter::parse_frontmatter(raw);
165 let dropped: Vec<&str> = UNSUPPORTED_AGENT_FIELDS
166 .iter()
167 .copied()
168 .filter(|k| map.contains_key(*k))
169 .collect();
170 if !dropped.is_empty() {
171 tracing::warn!(
172 "plugin agent '{namespaced}' declares unsupported field(s) {} — dropped (tcode \
173 Phase 1 plugin support maps role/description/model/max_tokens/tools only, #3539)",
174 dropped.join(", ")
175 );
176 }
177}
178
179/// Resolve one namespaced `<plugin>:<agent_name>` to its [`AgentConfig`], or
180/// `None` when no such plugin/agent exists.
181///
182/// Why: `agents::resolve_agent`'s dispatch-time entry point for a
183/// namespaced name — mirrors that function's own `NotFound`
184/// (nothing found, `None`) vs `Load` (found but failed to parse, `Some(Err)`)
185/// distinction so its caller can build the identical error shape.
186/// What: validates `plugin:agent_name` via
187/// `plugins::is_valid_namespaced_name` FIRST, before any path is built
188/// (code-critic PR #3547 review, HIGH 3 — the guard belongs to this
189/// function, not merely to an upstream caller that happens to reject `:`
190/// today) — `None` on a traversal/unsafe-charset payload like
191/// `plugin:../../etc`. Then finds the [`PluginRoot`](crate::plugins::PluginRoot) whose resolved `name`
192/// equals `plugin` (not the directory name, which may differ — see
193/// [`PluginRoot`](crate::plugins::PluginRoot)'s doc); `None` if no such plugin. Within it, `None` if
194/// `<agent_name>.md` does not exist; otherwise `Some` wrapping
195/// [`load_plugin_agent`]'s result.
196/// Test: `tests::find_plugin_agent_config_resolves_known_agent`,
197/// `tests::find_plugin_agent_config_unknown_plugin_is_none`,
198/// `tests::find_plugin_agent_config_unknown_agent_is_none`,
199/// `tests::find_plugin_agent_config_rejects_traversal_name`.
200pub fn find_plugin_agent_config(
201 project_root: &Path,
202 plugin: &str,
203 agent_name: &str,
204) -> Option<anyhow::Result<AgentConfig>> {
205 if !super::is_valid_namespaced_name(&format!("{plugin}:{agent_name}")) {
206 return None;
207 }
208 let root = discover_plugin_roots(project_root)
209 .into_iter()
210 .find(|p| p.name == plugin)?;
211 let path = root.agents_dir.join(format!("{agent_name}.md"));
212 if !path.exists() {
213 return None;
214 }
215 Some(load_plugin_agent(
216 &root.name,
217 agent_name,
218 &path,
219 &root.agents_dir,
220 ))
221}
222
223#[cfg(test)]
224#[path = "agents_tests.rs"]
225mod tests;