Skip to main content

trusty_code/agents/
config.rs

1//! Agent configuration schema for tcode.
2//!
3//! Why: Sub-agents (and the PM itself) are defined declaratively so model,
4//! prompt, and LLM parameters can evolve without code changes. As of #2897
5//! Slice D, the on-disk source format is Markdown+frontmatter
6//! (`.claude/agents/<name>.md`) ONLY — the original TOML loader
7//! (`AgentConfig::from_toml_str`/`AgentConfig::load`) has been retired; see
8//! `agents::md_loader` for the current loader and
9//! `scripts/migrate-tcode-agents-toml-to-md.py` for the one-time converter a
10//! project with pre-#2897 `.toml` agent files should run.
11//! What: `AgentConfig` and all nested config types. These are pure data
12//! structs — format-agnostic — that `agents::md_loader::project_to_agent_config`
13//! populates from a composed `.md` document's frontmatter + body.
14//! Test: `agent_config_default_is_empty`, `runner_kind_defaults_to_in_process`;
15//! the loading path itself is covered by `agents::md_loader::tests::*`.
16
17use serde::{Deserialize, Serialize};
18
19/// Top-level agent configuration.
20///
21/// Why: Declarative agent configs let operators define or override agents
22/// without touching Rust code.
23/// What: `agent` carries identity/role; `llm` carries model/token params;
24/// `system_prompt` carries the prompt text; optional sections add capabilities.
25/// Populated by `agents::md_loader::project_to_agent_config` from a composed
26/// `.md` agent document.
27/// Test: `agent_config_default_is_empty`; `agents::md_loader::tests::*` cover
28/// the actual field-projection contract end-to-end.
29#[derive(Debug, Clone, Serialize, Deserialize, Default)]
30pub struct AgentConfig {
31    /// Core identity fields.
32    pub agent: AgentInfo,
33    /// LLM parameters for this agent.
34    #[serde(default)]
35    pub llm: LlmParams,
36    /// System prompt content.
37    #[serde(default)]
38    pub system_prompt: SystemPrompt,
39    /// Optional tool permissions.
40    #[serde(default)]
41    pub tools: Option<ToolsConfig>,
42    /// Optional runner override.
43    #[serde(default)]
44    pub runner: Option<RunnerConfig>,
45    /// (#7948) Optional per-verb permission map from the agent's own
46    /// `permissions:` frontmatter block.
47    ///
48    /// Why: `tools.allowed` cannot say "run `git status` freely, never run
49    /// `rm`". The allowlist still runs first, so this can only narrow.
50    /// What: `None` for every agent without a `permissions:` block (every stock
51    /// bundled agent). Populated by `crate::agents::md_loader` and
52    /// `crate::plugins::agents` via `crate::permissions::parse_permissions`.
53    /// `#[serde(skip)]`: the `.md` frontmatter is the source of truth, and
54    /// compiled glob matchers have no serde form.
55    /// Test: `agents::md_loader::tests::permissions_block_projects_onto_agent_config`,
56    /// `agents::md_loader::tests::embedded_permissions_block_projects_onto_agent_config`,
57    /// `agents::md_loader::tests::embedded_extends_permissions_block_projects_onto_agent_config`.
58    #[serde(skip)]
59    pub permissions: Option<crate::permissions::PermissionMap>,
60}
61
62/// Core identity fields for an agent.
63///
64/// Why: Every agent needs a stable `name` (the dispatch key) and `model`.
65/// What: `name`, optional `role`, optional `model`.
66/// Test: `agent_config_default_is_empty` asserts the zero-value default;
67/// `agents::md_loader::tests::load_md_agent_base_case` covers real loading.
68#[derive(Debug, Clone, Serialize, Deserialize, Default)]
69pub struct AgentInfo {
70    /// The agent's dispatch key (e.g. `"engineer"`, `"python-engineer"`).
71    pub name: String,
72    /// Optional free-form role description.
73    #[serde(default)]
74    pub role: Option<String>,
75    /// LLM model override (e.g. `"anthropic/claude-sonnet-4-6"`,
76    /// `"bedrock/us.anthropic.claude-sonnet-4-6"`).
77    #[serde(default)]
78    pub model: Option<String>,
79    /// Human-readable description of what this agent does.
80    #[serde(default)]
81    pub description: Option<String>,
82}
83
84/// LLM parameters for a single agent.
85///
86/// Why: Each agent may need different temperature, token budget, or model. The
87/// backend (OpenRouter vs. Bedrock) is no longer a boolean here — it is derived
88/// from the resolved model slug by `provider::provider_for` (#1021), so a single
89/// slug like `bedrock/...` selects the backend without a separate flag.
90/// What: Standard LLM knobs, all optional with sensible defaults.
91/// Test: `agent_config_llm_params`.
92#[derive(Debug, Clone, Serialize, Deserialize, Default)]
93pub struct LlmParams {
94    /// Sampling temperature (0.0–1.0).
95    #[serde(default)]
96    pub temperature: Option<f32>,
97    /// Maximum tokens in the LLM response.
98    #[serde(default)]
99    pub max_tokens: Option<u32>,
100    /// Model override at the `[llm]` level (lower precedence than `[agent].model`).
101    #[serde(default)]
102    pub model_override: Option<String>,
103}
104
105/// System prompt for an agent.
106///
107/// Why: Keeping the prompt in config (not source code) lets operators tune
108/// agent behavior without a Rust recompile.
109/// What: `content` is the raw prompt text; `append_skills` is a list of skill
110/// names to inject at startup.
111/// Test: `agent_config_system_prompt`.
112#[derive(Debug, Clone, Serialize, Deserialize, Default)]
113pub struct SystemPrompt {
114    /// Raw prompt text.
115    #[serde(default)]
116    pub content: String,
117    /// Skill names to inject into the prompt.
118    #[serde(default)]
119    pub append_skills: Vec<String>,
120}
121
122/// Per-agent tool permissions.
123///
124/// Why: Restricts which tools an agent may call, preventing e.g. the
125/// plan-agent from shelling out.
126/// What: `allowed` is an explicit allowlist; `None` means "all registered tools".
127/// Test: `ToolRegistry::dispatch_gated` tests exercise the allowlist.
128#[derive(Debug, Clone, Serialize, Deserialize, Default)]
129pub struct ToolsConfig {
130    /// Explicit allowlist of tool names. `None` = all tools permitted.
131    #[serde(default)]
132    pub allowed: Option<Vec<String>>,
133}
134
135/// Runner backend selection for an agent.
136///
137/// Why: Different agents may use different execution backends (subprocess,
138/// in-process, Claude Code CLI).
139/// What: `kind` selects the backend; defaults to `SubProcess`.
140/// Test: `agent_config_runner_kind`.
141#[derive(Debug, Clone, Serialize, Deserialize, Default)]
142pub struct RunnerConfig {
143    /// Which backend to use for this agent.
144    #[serde(default)]
145    pub kind: RunnerKind,
146}
147
148/// Execution backend for agent invocations.
149///
150/// Why: Abstracts over the concrete runner selected at startup so config can
151/// swap backends without code changes. As of #1029 the in-process runner is the
152/// real, production default — the M1 model-comparison harness drives a delegated
153/// sub-agent inside the PM's own process (cheap, observable, usage rolls up onto
154/// one transcript). The subprocess and Claude-Code CLI backends are retained as
155/// future variants for deployments that need process isolation.
156/// What: `InProcess` is the default (drives the sub-agent's `AgentLoop` in the
157/// same process — see `crate::runner::InProcessAgentRunner`); `SubProcess` spawns
158/// a new process via NDJSON IPC; `ClaudeCode` wraps the `claude` CLI binary.
159/// Test: `runner_kind_defaults_to_in_process`.
160#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
161#[serde(rename_all = "snake_case")]
162pub enum RunnerKind {
163    /// Drive the sub-agent's `AgentLoop` in the PM's own process (the default).
164    #[default]
165    InProcess,
166    /// Spawn a subprocess; communicate via NDJSON over stdin/stdout.
167    SubProcess,
168    /// Use the `claude` CLI binary as the runner.
169    ClaudeCode,
170}
171
172// ── Tests ─────────────────────────────────────────────────────────────────────
173
174#[cfg(test)]
175mod tests {
176    use super::*;
177
178    /// `AgentConfig::default()` yields the expected all-empty baseline.
179    ///
180    /// Why: #2897 Slice D retired the TOML parsing tests (`from_toml_str`
181    /// itself is gone); the actual frontmatter -> `AgentConfig` field mapping
182    /// is now covered end-to-end by `agents::md_loader::tests::*`
183    /// (`load_md_agent_base_case`, `parallel fixture` field assertions,
184    /// etc.). What remains testable in THIS module is the plain-data
185    /// `Default` contract every construction path relies on.
186    /// What: every field is the type's zero value; `tools`/`runner` are
187    /// `None`.
188    /// Test: this test.
189    #[test]
190    fn agent_config_default_is_empty() {
191        let cfg = AgentConfig::default();
192        assert_eq!(cfg.agent.name, "");
193        assert!(cfg.agent.model.is_none());
194        assert!(cfg.tools.is_none());
195        assert!(cfg.runner.is_none());
196        assert_eq!(cfg.system_prompt.content, "");
197    }
198
199    /// `RunnerKind` defaults to `InProcess` (the real default since #1029).
200    ///
201    /// Why: The acceptance criterion for #1029 makes the in-process runner the
202    /// production default; a regression that flipped it back to `SubProcess`
203    /// would silently route every undeclared agent through the wrong backend.
204    /// What: `RunnerKind::default()` equals `InProcess`; a default-constructed
205    /// `AgentConfig` (mirroring an agent with no `[runner]`/no runner
206    /// frontmatter) leaves `runner` `None` (callers treat absence as default).
207    /// Test: this test.
208    #[test]
209    fn runner_kind_defaults_to_in_process() {
210        assert_eq!(RunnerKind::default(), RunnerKind::InProcess);
211        let cfg = AgentConfig::default();
212        assert!(
213            cfg.runner.is_none(),
214            "absent runner config leaves runner None; callers apply the InProcess default"
215        );
216    }
217}