Skip to main content

capo_agent/settings/
mod.rs

1#![cfg_attr(test, allow(clippy::expect_used, clippy::unwrap_used))]
2
3//! Structured user settings (`~/.capo/agent/settings.toml`).
4//!
5//! TOML is the current on-disk format for capo's editable settings. The
6//! loader still accepts legacy `settings.json` when no TOML file exists.
7//! Sections beyond the Phase 0 baseline (e.g. `ui.theme` variants,
8//! `logging` rotation) are reserved for M4+ and intentionally minimal here.
9
10mod cli;
11mod load;
12
13pub use cli::CliOverrides;
14pub use load::{load, load_with};
15
16use serde::{Deserialize, Serialize};
17
18#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
19pub struct Settings {
20    #[serde(default)]
21    pub model: ModelSettings,
22    #[serde(default)]
23    pub anthropic: AnthropicSettings,
24    #[serde(default)]
25    pub ui: UiSettings,
26    #[serde(default)]
27    pub session: SessionSettings,
28    #[serde(default)]
29    pub logging: LoggingSettings,
30    /// v0.10 Phase A: permission mode picker default. Top-level
31    /// `[permissions]` section in settings.toml. See spec §3.
32    #[serde(default)]
33    pub permissions: PermissionsSettings,
34}
35
36impl Settings {
37    pub fn load(cli: &CliOverrides) -> crate::Result<Self> {
38        load::load(cli)
39    }
40
41    pub fn load_with<F>(
42        agent_dir: &std::path::Path,
43        cli: &CliOverrides,
44        env_lookup: F,
45    ) -> crate::Result<Self>
46    where
47        F: Fn(&str) -> Option<String>,
48    {
49        load::load_with(agent_dir, cli, env_lookup)
50    }
51}
52
53/// Supported LLM providers. `Settings::model.provider` is a string for
54/// JSON-friendliness; this enum is the parsed form.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum LlmProviderKind {
57    /// Direct HTTPS call to `api.anthropic.com`. Requires an API key
58    /// (env `ANTHROPIC_API_KEY` or `auth.json::anthropic.key`).
59    Anthropic,
60    /// Shells out to the locally-installed `claude` binary
61    /// (Claude Code CLI). The CLI handles its own authentication;
62    /// capo's `Auth` is not consulted. Requires `claude` on `$PATH`.
63    ClaudeCode,
64    /// Shells out to the locally-installed `codex` binary
65    /// (OpenAI Codex CLI). The CLI handles its own authentication;
66    /// capo's `Auth` is not consulted. Requires `codex` on `$PATH`.
67    CodexCli,
68    /// Direct HTTPS call to OpenAI's API. Requires an API key
69    /// (env `OPENAI_API_KEY` or `auth.json::openai.key`).
70    Openai,
71    /// Direct HTTPS call to Google's Gemini REST API. Requires an API key
72    /// (env `GEMINI_API_KEY` or `auth.json::gemini.key`).
73    Gemini,
74    /// Shells out to the locally-installed `gemini` binary (Google's
75    /// Gemini CLI). The CLI handles its own authentication; capo's `Auth`
76    /// is not consulted. Requires `gemini` on `$PATH`.
77    GeminiCli,
78}
79
80impl LlmProviderKind {
81    /// Parse a `Settings::model.provider` string. Case-insensitive.
82    pub fn parse(s: &str) -> Result<Self, String> {
83        match s.trim().to_ascii_lowercase().as_str() {
84            "anthropic" => Ok(Self::Anthropic),
85            "claude-code" | "claude_code" => Ok(Self::ClaudeCode),
86            "codex-cli" | "codex_cli" => Ok(Self::CodexCli),
87            "openai" => Ok(Self::Openai),
88            "gemini" => Ok(Self::Gemini),
89            "gemini-cli" | "gemini_cli" => Ok(Self::GeminiCli),
90            other => Err(format!(
91                "unknown LLM provider {other:?}; expected one of: anthropic, claude-code, codex-cli, openai, gemini, gemini-cli"
92            )),
93        }
94    }
95}
96
97#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
98pub struct ModelSettings {
99    /// Provider tag. One of: `"anthropic"`, `"claude-code"`, `"codex-cli"`,
100    /// `"openai"`, `"gemini"`, `"gemini-cli"`.
101    /// See [`LlmProviderKind`] for semantics. Validated at LLM construction
102    /// time (not at settings deserialize) so a forgotten provider only
103    /// blocks the user when they actually launch capo.
104    pub provider: String,
105    pub name: String,
106    pub max_tokens: u32,
107}
108
109impl Default for ModelSettings {
110    fn default() -> Self {
111        Self {
112            provider: "anthropic".to_string(),
113            name: "claude-sonnet-4-6".to_string(),
114            max_tokens: 8192,
115        }
116    }
117}
118
119#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
120pub struct AnthropicSettings {
121    /// Base URL for the Anthropic HTTP API. Defaults to the public endpoint;
122    /// override via `CAPO_ANTHROPIC_BASE_URL` env or `anthropic.base_url` in
123    /// `settings.json` to route through a corporate proxy or test server.
124    /// Only consulted when `model.provider == "anthropic"` (CLI providers
125    /// shell out to their own binaries and ignore this).
126    pub base_url: String,
127}
128
129impl Default for AnthropicSettings {
130    fn default() -> Self {
131        Self {
132            base_url: "https://api.anthropic.com".to_string(),
133        }
134    }
135}
136
137#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
138pub struct UiSettings {
139    pub theme: String,
140    pub streaming_throttle_ms: u32,
141    pub footer_show_cost: bool,
142    /// v0.9 Phase A: hide MessageBlock::Thinking entirely from rendering.
143    /// Default true — most users don't want to read the model's reasoning.
144    #[serde(default = "default_hide_thinking_blocks")]
145    pub hide_thinking_blocks: bool,
146    /// v0.9 Phase A: collapse ToolResult output to "tool ✓ (N lines)" 1-liner.
147    /// Default true — keeps transcript scannable.
148    #[serde(default = "default_collapse_tool_output_by_default")]
149    pub collapse_tool_output_by_default: bool,
150    /// v0.9 Phase A: collapse tool-call args when pretty-printed > N lines.
151    /// 0 disables. Default 2.
152    #[serde(default = "default_collapse_tool_args_max_lines")]
153    pub collapse_tool_args_max_lines: u32,
154    /// v0.9 Phase A: collapse assistant messages older than N from the end.
155    /// 0 disables (opt-in). Default 0.
156    #[serde(default = "default_collapse_history_after")]
157    pub collapse_history_after: u32,
158}
159
160fn default_hide_thinking_blocks() -> bool {
161    true
162}
163
164fn default_collapse_tool_output_by_default() -> bool {
165    true
166}
167
168fn default_collapse_tool_args_max_lines() -> u32 {
169    2
170}
171
172fn default_collapse_history_after() -> u32 {
173    0
174}
175
176impl Default for UiSettings {
177    fn default() -> Self {
178        Self {
179            theme: "dark".to_string(),
180            streaming_throttle_ms: 50,
181            footer_show_cost: true,
182            hide_thinking_blocks: default_hide_thinking_blocks(),
183            collapse_tool_output_by_default: default_collapse_tool_output_by_default(),
184            collapse_tool_args_max_lines: default_collapse_tool_args_max_lines(),
185            collapse_history_after: default_collapse_history_after(),
186        }
187    }
188}
189
190#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
191pub struct SessionSettings {
192    pub autosave: bool,
193    /// Fraction of context window (0.0..=1.0) at which autocompact triggers.
194    /// Name keeps `_pct` for spec/JSON-config compatibility, but the value is
195    /// always interpreted as a 0.0–1.0 fraction. `0.0` disables autocompact.
196    pub compact_at_context_pct: f32,
197    /// Total LLM context window in tokens. Used by `AutocompactExtension`
198    /// to compute the absolute compaction threshold. Default 200_000
199    /// matches motosan-agent-loop's `AutocompactConfig::default`. **Override
200    /// for newer models** (Sonnet 4.5+ supports 1_000_000).
201    pub max_context_tokens: usize,
202    /// Number of recent user-turn boundaries kept verbatim during compaction.
203    pub keep_turns: usize,
204}
205
206impl Default for SessionSettings {
207    fn default() -> Self {
208        Self {
209            autosave: true,
210            compact_at_context_pct: 0.85,
211            max_context_tokens: 1_000_000,
212            keep_turns: 3,
213        }
214    }
215}
216
217#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
218pub struct PermissionsSettings {
219    /// Permission mode for new sessions. One of `"bypass"`, `"accept-edits"`,
220    /// `"prompt"`. Mismatched values fall through to `Settings::default()`
221    /// handling (the binary surfaces a parse error at load time, then
222    /// falls back to the type-level default — `"prompt"`).
223    ///
224    /// Edit via `/settings` or directly via `~/.capo/agent/settings.toml`.
225    ///
226    /// **NOT to be confused with** `~/.capo/agent/permissions.toml` (a
227    /// separate file holding the `[bash]`/`[write]`/`[edit]` allowlist —
228    /// covered by the existing `Policy` loader). The `[permissions]`
229    /// section here ONLY carries `default_mode`.
230    #[serde(default = "default_permission_mode_str")]
231    pub default_mode: String,
232}
233
234impl Default for PermissionsSettings {
235    fn default() -> Self {
236        Self {
237            default_mode: default_permission_mode_str(),
238        }
239    }
240}
241
242fn default_permission_mode_str() -> String {
243    "prompt".to_string()
244}
245
246#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
247pub struct LoggingSettings {
248    pub level: String,
249    pub file: String,
250}
251
252impl Default for LoggingSettings {
253    fn default() -> Self {
254        Self {
255            level: "info".to_string(),
256            file: "~/.capo/agent/capo.log".to_string(),
257        }
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264
265    #[test]
266    fn settings_default_matches_documented_baseline() {
267        let s = Settings::default();
268        assert_eq!(s.model.provider, "anthropic");
269        assert_eq!(s.model.name, "claude-sonnet-4-6");
270        assert_eq!(s.model.max_tokens, 8192);
271        assert_eq!(s.anthropic.base_url, "https://api.anthropic.com");
272        assert_eq!(s.ui.theme, "dark");
273        assert_eq!(s.ui.streaming_throttle_ms, 50);
274        assert!(s.ui.footer_show_cost);
275        assert!(s.session.autosave);
276        assert!((s.session.compact_at_context_pct - 0.85).abs() < f32::EPSILON);
277        assert_eq!(s.session.max_context_tokens, 1_000_000);
278        assert_eq!(s.session.keep_turns, 3);
279        assert_eq!(s.logging.level, "info");
280        assert_eq!(s.logging.file, "~/.capo/agent/capo.log");
281    }
282
283    #[test]
284    fn settings_serde_round_trips() {
285        let original = Settings::default();
286        let json = match serde_json::to_string_pretty(&original) {
287            Ok(json) => json,
288            Err(err) => panic!("serialize failed: {err}"),
289        };
290        let back: Settings = match serde_json::from_str(&json) {
291            Ok(settings) => settings,
292            Err(err) => panic!("deserialize failed: {err}"),
293        };
294        assert_eq!(original, back);
295    }
296
297    #[test]
298    fn settings_loads_partial_json_with_defaults_for_missing_sections() {
299        let json = r#"{ "model": { "provider": "anthropic", "name": "x", "max_tokens": 4096 } }"#;
300        let s: Settings = match serde_json::from_str(json) {
301            Ok(settings) => settings,
302            Err(err) => panic!("deserialize failed: {err}"),
303        };
304        assert_eq!(s.model.name, "x");
305        // Missing sections fall back to defaults.
306        assert_eq!(s.ui.theme, "dark");
307        assert!((s.session.compact_at_context_pct - 0.85).abs() < f32::EPSILON);
308    }
309
310    #[test]
311    fn settings_v0_10_permissions_default_mode_defaults_to_prompt() {
312        let s = Settings::default();
313        assert_eq!(s.permissions.default_mode, "prompt");
314    }
315
316    #[test]
317    fn settings_v0_10_permissions_section_round_trips() {
318        let mut s = Settings::default();
319        s.permissions.default_mode = "bypass".into();
320        let toml_str = toml::to_string(&s).expect("serialize");
321        assert!(toml_str.contains("default_mode = \"bypass\""));
322        let back: Settings = toml::from_str(&toml_str).expect("deserialize");
323        assert_eq!(back.permissions.default_mode, "bypass");
324    }
325
326    #[test]
327    fn settings_v0_10_missing_permissions_section_uses_default() {
328        // Existing v0.9 settings.toml has no [permissions] — must still load.
329        let toml_str = r#"
330[model]
331provider = "anthropic"
332name = "claude-opus-4-7"
333max_tokens = 8192
334"#;
335        let s: Settings = toml::from_str(toml_str).expect("load partial");
336        assert_eq!(s.permissions.default_mode, "prompt");
337    }
338
339    #[test]
340    fn ui_settings_v0_9_defaults() {
341        let s = UiSettings::default();
342        assert!(
343            s.hide_thinking_blocks,
344            "hide_thinking_blocks should default to true"
345        );
346        assert!(
347            s.collapse_tool_output_by_default,
348            "collapse_tool_output_by_default should default to true"
349        );
350        assert_eq!(s.collapse_tool_args_max_lines, 2);
351        assert_eq!(s.collapse_history_after, 0);
352    }
353
354    #[test]
355    fn ui_settings_v0_9_round_trips_through_toml() {
356        let mut s = Settings::default();
357        s.ui.hide_thinking_blocks = false;
358        s.ui.collapse_tool_output_by_default = false;
359        s.ui.collapse_tool_args_max_lines = 5;
360        s.ui.collapse_history_after = 10;
361        let toml_str = toml::to_string(&s).expect("serialize");
362        // Smoke: payload contains the new fields.
363        assert!(toml_str.contains("hide_thinking_blocks = false"));
364        assert!(toml_str.contains("collapse_tool_output_by_default = false"));
365        assert!(toml_str.contains("collapse_tool_args_max_lines = 5"));
366        assert!(toml_str.contains("collapse_history_after = 10"));
367        let back: Settings = toml::from_str(&toml_str).expect("deserialize");
368        assert!(!back.ui.hide_thinking_blocks);
369        assert!(!back.ui.collapse_tool_output_by_default);
370        assert_eq!(back.ui.collapse_tool_args_max_lines, 5);
371        assert_eq!(back.ui.collapse_history_after, 10);
372    }
373
374    fn parse_ok(input: &str) -> LlmProviderKind {
375        match LlmProviderKind::parse(input) {
376            Ok(kind) => kind,
377            Err(err) => panic!("parse failed for {input}: {err}"),
378        }
379    }
380
381    fn parse_err(input: &str) -> String {
382        match LlmProviderKind::parse(input) {
383            Ok(kind) => panic!("parse should have failed for {input}: {kind:?}"),
384            Err(err) => err,
385        }
386    }
387
388    #[test]
389    fn llm_provider_kind_parses_all_three() {
390        assert_eq!(parse_ok("anthropic"), LlmProviderKind::Anthropic);
391        assert_eq!(parse_ok("claude-code"), LlmProviderKind::ClaudeCode);
392        assert_eq!(parse_ok("claude_code"), LlmProviderKind::ClaudeCode);
393        assert_eq!(parse_ok("codex-cli"), LlmProviderKind::CodexCli);
394        assert_eq!(parse_ok("CODEX-CLI"), LlmProviderKind::CodexCli);
395    }
396
397    #[test]
398    fn llm_provider_kind_rejects_unknown() {
399        let err = parse_err("gpt-4");
400        assert!(err.contains("unknown LLM provider"));
401        assert!(err.contains("gpt-4"));
402        assert!(err.contains("anthropic"));
403    }
404
405    #[test]
406    fn parse_recognizes_v0_5_providers() {
407        assert!(matches!(parse_ok("openai"), LlmProviderKind::Openai));
408        assert!(matches!(parse_ok("gemini"), LlmProviderKind::Gemini));
409        assert!(matches!(parse_ok("gemini-cli"), LlmProviderKind::GeminiCli));
410        assert!(matches!(parse_ok("gemini_cli"), LlmProviderKind::GeminiCli));
411    }
412
413    #[test]
414    fn parse_unknown_provider_lists_all_six_supported_names() {
415        let err = parse_err("nope");
416        for name in [
417            "anthropic",
418            "claude-code",
419            "codex-cli",
420            "openai",
421            "gemini",
422            "gemini-cli",
423        ] {
424            assert!(err.contains(name), "{name} missing from: {err}");
425        }
426    }
427}