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 in TOML so
4//! model, prompt, and LLM parameters can evolve without code changes.
5//! What: `AgentConfig` and all nested config types, deserializable from the
6//! `.claude/agents/<name>.toml` format compatible with Claude Code sub-agents.
7//! Test: `AgentConfig::from_toml_str` on inline TOML succeeds and round-trips.
8
9use serde::{Deserialize, Serialize};
10
11/// Top-level agent configuration loaded from `<name>.toml`.
12///
13/// Why: Declarative agent configs let operators define or override agents
14/// without touching Rust code.
15/// What: `agent` carries identity/role; `llm` carries model/token params;
16/// `system_prompt` carries the prompt text; optional sections add capabilities.
17/// Test: `agent_config_roundtrip`, `agent_config_minimal`.
18#[derive(Debug, Clone, Serialize, Deserialize, Default)]
19pub struct AgentConfig {
20    /// Core identity fields.
21    pub agent: AgentInfo,
22    /// LLM parameters for this agent.
23    #[serde(default)]
24    pub llm: LlmParams,
25    /// System prompt content.
26    #[serde(default)]
27    pub system_prompt: SystemPrompt,
28    /// Optional tool permissions.
29    #[serde(default)]
30    pub tools: Option<ToolsConfig>,
31    /// Optional runner override.
32    #[serde(default)]
33    pub runner: Option<RunnerConfig>,
34}
35
36impl AgentConfig {
37    /// Parse an `AgentConfig` from a TOML string.
38    ///
39    /// Why: Useful in tests and for in-process loading of bundled config.
40    /// What: Delegates to `toml::from_str`.
41    /// Test: `agent_config_roundtrip`.
42    pub fn from_toml_str(s: &str) -> Result<Self, toml::de::Error> {
43        toml::from_str(s)
44    }
45
46    /// Load an `AgentConfig` from a TOML file on disk.
47    ///
48    /// Why: Primary entry point for the agent loader during harness startup.
49    /// What: Reads the file, then calls `from_toml_str`.
50    /// Test: Integration tests place a TOML file in a tempdir and call this.
51    pub fn load(path: &std::path::Path) -> anyhow::Result<Self> {
52        let src = std::fs::read_to_string(path)
53            .map_err(|e| anyhow::anyhow!("failed to read agent config {}: {e}", path.display()))?;
54        toml::from_str(&src)
55            .map_err(|e| anyhow::anyhow!("invalid agent config {}: {e}", path.display()))
56    }
57}
58
59/// Core identity fields for an agent.
60///
61/// Why: Every agent needs a stable `name` (the dispatch key) and `model`.
62/// What: `name`, optional `role`, optional `model`.
63/// Test: `agent_config_minimal` asserts that `name` is loaded.
64#[derive(Debug, Clone, Serialize, Deserialize, Default)]
65pub struct AgentInfo {
66    /// The agent's dispatch key (e.g. `"engineer"`, `"python-engineer"`).
67    pub name: String,
68    /// Optional free-form role description.
69    #[serde(default)]
70    pub role: Option<String>,
71    /// LLM model override (e.g. `"anthropic/claude-sonnet-4-6"`,
72    /// `"bedrock/us.anthropic.claude-sonnet-4-6"`).
73    #[serde(default)]
74    pub model: Option<String>,
75    /// Human-readable description of what this agent does.
76    #[serde(default)]
77    pub description: Option<String>,
78}
79
80/// LLM parameters for a single agent.
81///
82/// Why: Each agent may need different temperature, token budget, or model. The
83/// backend (OpenRouter vs. Bedrock) is no longer a boolean here — it is derived
84/// from the resolved model slug by `provider::provider_for` (#1021), so a single
85/// slug like `bedrock/...` selects the backend without a separate flag.
86/// What: Standard LLM knobs, all optional with sensible defaults.
87/// Test: `agent_config_llm_params`.
88#[derive(Debug, Clone, Serialize, Deserialize, Default)]
89pub struct LlmParams {
90    /// Sampling temperature (0.0–1.0).
91    #[serde(default)]
92    pub temperature: Option<f32>,
93    /// Maximum tokens in the LLM response.
94    #[serde(default)]
95    pub max_tokens: Option<u32>,
96    /// Model override at the `[llm]` level (lower precedence than `[agent].model`).
97    #[serde(default)]
98    pub model_override: Option<String>,
99}
100
101/// System prompt for an agent.
102///
103/// Why: Keeping the prompt in config (not source code) lets operators tune
104/// agent behavior without a Rust recompile.
105/// What: `content` is the raw prompt text; `append_skills` is a list of skill
106/// names to inject at startup.
107/// Test: `agent_config_system_prompt`.
108#[derive(Debug, Clone, Serialize, Deserialize, Default)]
109pub struct SystemPrompt {
110    /// Raw prompt text.
111    #[serde(default)]
112    pub content: String,
113    /// Skill names to inject into the prompt.
114    #[serde(default)]
115    pub append_skills: Vec<String>,
116}
117
118/// Per-agent tool permissions.
119///
120/// Why: Restricts which tools an agent may call, preventing e.g. the
121/// plan-agent from shelling out.
122/// What: `allowed` is an explicit allowlist; `None` means "all registered tools".
123/// Test: `ToolRegistry::dispatch_gated` tests exercise the allowlist.
124#[derive(Debug, Clone, Serialize, Deserialize, Default)]
125pub struct ToolsConfig {
126    /// Explicit allowlist of tool names. `None` = all tools permitted.
127    #[serde(default)]
128    pub allowed: Option<Vec<String>>,
129}
130
131/// Runner backend selection for an agent.
132///
133/// Why: Different agents may use different execution backends (subprocess,
134/// in-process, Claude Code CLI).
135/// What: `kind` selects the backend; defaults to `SubProcess`.
136/// Test: `agent_config_runner_kind`.
137#[derive(Debug, Clone, Serialize, Deserialize, Default)]
138pub struct RunnerConfig {
139    /// Which backend to use for this agent.
140    #[serde(default)]
141    pub kind: RunnerKind,
142}
143
144/// Execution backend for agent invocations.
145///
146/// Why: Abstracts over the concrete runner selected at startup so config can
147/// swap backends without code changes. As of #1029 the in-process runner is the
148/// real, production default — the M1 model-comparison harness drives a delegated
149/// sub-agent inside the PM's own process (cheap, observable, usage rolls up onto
150/// one transcript). The subprocess and Claude-Code CLI backends are retained as
151/// future variants for deployments that need process isolation.
152/// What: `InProcess` is the default (drives the sub-agent's `AgentLoop` in the
153/// same process — see `crate::runner::InProcessAgentRunner`); `SubProcess` spawns
154/// a new process via NDJSON IPC; `ClaudeCode` wraps the `claude` CLI binary.
155/// Test: `runner_kind_deserializes`, `runner_kind_defaults_to_in_process`.
156#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
157#[serde(rename_all = "snake_case")]
158pub enum RunnerKind {
159    /// Drive the sub-agent's `AgentLoop` in the PM's own process (the default).
160    #[default]
161    InProcess,
162    /// Spawn a subprocess; communicate via NDJSON over stdin/stdout.
163    SubProcess,
164    /// Use the `claude` CLI binary as the runner.
165    ClaudeCode,
166}
167
168// ── Tests ─────────────────────────────────────────────────────────────────────
169
170#[cfg(test)]
171mod tests {
172    use super::*;
173
174    const MINIMAL_TOML: &str = r#"
175[agent]
176name = "engineer"
177"#;
178
179    const FULL_TOML: &str = r#"
180[agent]
181name = "python-engineer"
182role = "engineer"
183model = "anthropic/claude-sonnet-4-6"
184description = "Python software engineer"
185
186[llm]
187temperature = 0.2
188max_tokens = 8192
189
190[system_prompt]
191content = "You are a Python expert."
192
193[tools]
194allowed = ["delegate_to_agent", "search_code"]
195
196[runner]
197kind = "claude_code"
198"#;
199
200    /// Minimal config with only `[agent].name` parses successfully.
201    ///
202    /// Why: Operators should be able to define a minimal agent without
203    /// specifying every optional field.
204    /// What: `from_toml_str(MINIMAL_TOML)` returns `Ok` with `name == "engineer"`.
205    /// Test: This test.
206    #[test]
207    fn agent_config_minimal() {
208        let cfg = AgentConfig::from_toml_str(MINIMAL_TOML).expect("parse minimal");
209        assert_eq!(cfg.agent.name, "engineer");
210        assert!(cfg.agent.model.is_none());
211        assert!(cfg.tools.is_none());
212    }
213
214    /// Full config round-trips through TOML parsing.
215    ///
216    /// Why: Verify all fields are decoded correctly.
217    /// What: `from_toml_str(FULL_TOML)` round-trips all fields.
218    /// Test: This test.
219    #[test]
220    fn agent_config_roundtrip() {
221        let cfg = AgentConfig::from_toml_str(FULL_TOML).expect("parse full");
222        assert_eq!(cfg.agent.name, "python-engineer");
223        assert_eq!(
224            cfg.agent.model.as_deref(),
225            Some("anthropic/claude-sonnet-4-6")
226        );
227        assert_eq!(cfg.llm.temperature, Some(0.2));
228        assert_eq!(cfg.llm.max_tokens, Some(8192));
229        assert_eq!(cfg.system_prompt.content, "You are a Python expert.");
230        let allowed = cfg.tools.as_ref().and_then(|t| t.allowed.as_ref());
231        let expected: Vec<String> =
232            vec!["delegate_to_agent".to_string(), "search_code".to_string()];
233        assert_eq!(allowed.map(|v| v.as_slice()), Some(expected.as_slice()));
234        assert_eq!(
235            cfg.runner.as_ref().map(|r| &r.kind),
236            Some(&RunnerKind::ClaudeCode)
237        );
238    }
239
240    /// `RunnerKind` deserializes from `snake_case` strings via a TOML wrapper table.
241    ///
242    /// Why: Verify the serde rename_all contract.
243    /// What: Parse a `[runner]` table with `kind = "claude_code"` → `RunnerKind::ClaudeCode`.
244    /// Test: This test.
245    #[test]
246    fn runner_kind_deserializes() {
247        #[derive(serde::Deserialize)]
248        struct Wrapper {
249            kind: RunnerKind,
250        }
251        let w: Wrapper = toml::from_str("kind = \"claude_code\"").expect("parse runner kind");
252        assert_eq!(w.kind, RunnerKind::ClaudeCode);
253    }
254
255    /// `RunnerKind` defaults to `InProcess` (the real default since #1029).
256    ///
257    /// Why: The acceptance criterion for #1029 makes the in-process runner the
258    /// production default; a regression that flipped it back to `SubProcess`
259    /// would silently route every undeclared agent through the wrong backend.
260    /// What: `RunnerKind::default()` equals `InProcess`; an agent config with no
261    /// `[runner]` table leaves `runner` `None` (callers treat absence as default).
262    /// Test: this test.
263    #[test]
264    fn runner_kind_defaults_to_in_process() {
265        assert_eq!(RunnerKind::default(), RunnerKind::InProcess);
266        let cfg = AgentConfig::from_toml_str(MINIMAL_TOML).expect("parse minimal");
267        assert!(
268            cfg.runner.is_none(),
269            "absent [runner] leaves runner None; callers apply the InProcess default"
270        );
271    }
272}