1use super::{is_secret_key, Config};
39use std::fmt;
40
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum Applies {
44 NextRun,
47 RestartProcess,
51}
52
53fn applies_to(section: &str) -> Applies {
58 match section {
59 "web" | "gateway" => Applies::RestartProcess,
60 _ => Applies::NextRun,
61 }
62}
63
64impl Applies {
65 pub fn as_str(&self) -> &'static str {
66 match self {
67 Applies::NextRun => "next run",
68 Applies::RestartProcess => "restart the background process",
69 }
70 }
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum Kind {
76 Str,
77 Integer,
78 Float,
79 Bool,
80 List,
81 Datetime,
82}
83
84impl Kind {
85 fn of(value: &toml::Value) -> Kind {
86 match value {
87 toml::Value::String(_) => Kind::Str,
88 toml::Value::Integer(_) => Kind::Integer,
89 toml::Value::Float(_) => Kind::Float,
90 toml::Value::Boolean(_) => Kind::Bool,
91 toml::Value::Array(_) => Kind::List,
92 toml::Value::Datetime(_) => Kind::Datetime,
93 toml::Value::Table(_) => Kind::List,
96 }
97 }
98}
99
100impl Kind {
101 pub fn as_str(self) -> &'static str {
105 match self {
106 Kind::Str => "str",
107 Kind::Integer => "integer",
108 Kind::Float => "float",
109 Kind::Bool => "bool",
110 Kind::List => "list",
111 Kind::Datetime => "datetime",
112 }
113 }
114}
115
116impl fmt::Display for Kind {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 f.write_str(match self {
119 Kind::Str => "a string",
120 Kind::Integer => "an integer",
121 Kind::Float => "a number",
122 Kind::Bool => "true or false",
123 Kind::List => "a list",
124 Kind::Datetime => "a date",
125 })
126 }
127}
128
129fn is_empty_string(value: &toml::Value) -> bool {
131 matches!(value, toml::Value::String(s) if s.is_empty())
132}
133
134#[derive(Debug, Clone, PartialEq)]
136pub struct Setting {
137 pub section: String,
138 pub key: String,
139 pub default: Option<toml::Value>,
142 pub value: Option<toml::Value>,
144 pub kind: Kind,
145 pub secret: bool,
147 pub applies: Applies,
148 pub about: &'static str,
150 pub choices: &'static [&'static str],
152}
153
154impl Setting {
155 pub fn path(&self) -> String {
157 format!("{}.{}", self.section, self.key)
158 }
159
160 pub fn is_default(&self) -> bool {
162 self.value == self.default
163 }
164
165 pub fn rendered(&self) -> String {
168 if self.secret {
169 return "«redacted»".to_string();
170 }
171 match &self.value {
172 Some(value) => render(value),
173 None => "(not set)".to_string(),
174 }
175 }
176
177 pub fn rendered_default(&self) -> Option<String> {
182 if self.secret {
183 return None;
184 }
185 self.default.as_ref().map(render)
186 }
187}
188
189impl fmt::Display for Setting {
190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191 write!(f, "{} = {}", self.path(), self.rendered())?;
192 if self.is_default() {
193 write!(f, " (default)")?;
194 }
195 if self.applies == Applies::RestartProcess {
196 write!(f, " [{}]", self.applies.as_str())?;
197 }
198 Ok(())
199 }
200}
201
202pub(crate) const ABSENT_BY_DEFAULT: &[(&str, &str, Kind)] = &[
208 ("flares", "total_tokens", Kind::Integer),
210 ("provider", "api_key", Kind::Str),
211 ("provider", "api_key_env", Kind::Str),
212 ("provider", "aux", Kind::Str),
213 ("provider", "delegate", Kind::Str),
214 ("provider", "fallback", Kind::List),
215 ("provider", "temperature", Kind::Float),
216 ("provider", "max_tokens", Kind::Integer),
217 ("provider", "profile", Kind::Str),
218 ("provider", "top_p", Kind::Float),
219 ("provider", "seed", Kind::Integer),
220 ("provider", "stop", Kind::List),
221 ("provider", "reasoning_effort", Kind::Str),
222 ("provider", "parallel_tool_calls", Kind::Bool),
223 ("provider", "tool_choice", Kind::Str),
224 ("provider", "vision", Kind::Bool),
225 ("agent", "output_schema", Kind::Str),
226 ("tools", "workspace_root", Kind::Str),
227 ("sessions", "dir", Kind::Str),
228 ("attachments", "dir", Kind::Str),
229 ("plugins", "dir", Kind::Str),
230 ("plugins", "mcp_timeout_secs", Kind::Integer),
231 ("web", "auth_token", Kind::Str),
232 ("web", "default_profile", Kind::Str),
233 ("cli", "color", Kind::Bool),
234 ("cli", "markdown", Kind::Bool),
235 ("update", "remote", Kind::Str),
236 ("update", "releases", Kind::Str),
237];
238
239#[cfg(test)]
246const NOT_SETTINGS: &[&str] = &[
247 "provider.route",
248 "provider.extra_body",
249 "hooks.settings",
250 "dotenv",
251 "profile",
252 "route_pin",
253 "no_mcp",
254];
255
256fn absent_default(section: &str, key: &str) -> Option<toml::Value> {
264 match (section, key) {
265 ("provider", "reasoning_effort") => Some(toml::Value::String(
266 crate::reasoning::SHIPPED_DEFAULT.into(),
267 )),
268 _ => None,
269 }
270}
271
272fn render(value: &toml::Value) -> String {
274 match value {
275 toml::Value::String(s) => toml::Value::String(s.clone()).to_string(),
276 other => other.to_string(),
277 }
278}
279
280impl Config {
281 pub fn settings(&self) -> Vec<Setting> {
286 let Ok(defaults) = toml::Value::try_from(Config::default()) else {
287 return Vec::new();
288 };
289 let Ok(current) = toml::Value::try_from(self) else {
290 return Vec::new();
291 };
292 let mut out = Vec::new();
293 for (section, table) in defaults.as_table().into_iter().flatten() {
294 let loaded = current.get(section).and_then(toml::Value::as_table);
295 for (key, default) in table.as_table().into_iter().flatten() {
296 if matches!(default, toml::Value::Table(_)) {
297 continue;
298 }
299 if default
300 .as_array()
301 .is_some_and(|items| items.iter().any(toml::Value::is_table))
302 {
303 continue;
304 }
305 let value = loaded.and_then(|t| t.get(key)).cloned();
306 out.push(Setting {
307 section: section.clone(),
308 key: key.clone(),
309 kind: Kind::of(default),
310 default: Some(default.clone()),
311 value,
312 secret: is_secret_key(key),
313 applies: applies_to(section),
314 about: "",
315 choices: &[],
316 });
317 }
318 }
319 for (section, key, kind) in ABSENT_BY_DEFAULT {
320 let value = current
321 .get(section)
322 .and_then(toml::Value::as_table)
323 .and_then(|t| t.get(*key))
324 .cloned();
325 out.push(Setting {
326 section: (*section).to_string(),
327 key: (*key).to_string(),
328 kind: *kind,
329 default: absent_default(section, key),
330 value,
331 secret: is_secret_key(key),
332 applies: applies_to(section),
333 about: "",
334 choices: &[],
335 });
336 }
337 out.sort_by_key(Setting::path);
338 out.dedup_by(|a, b| a.path() == b.path());
339 for setting in &mut out {
342 let path = setting.path();
343 setting.about = about(&path);
344 setting.choices = choices(&path);
345 if let Some(kind) = word_default(&path) {
346 setting.kind = kind;
347 }
348 }
349 out
350 }
351
352 pub fn setting(&self, path: &str) -> Option<Setting> {
354 self.settings()
355 .into_iter()
356 .find(|s| s.path() == path.trim())
357 }
358}
359
360pub fn parse_value(raw: &str) -> toml::Value {
367 let raw = raw.trim();
368 if let Ok(value) = format!("v = {raw}").parse::<toml::Value>() {
369 if let Some(inner) = value.get("v") {
370 return inner.clone();
371 }
372 }
373 toml::Value::String(raw.to_string())
374}
375
376pub fn set_in_text(
383 text: &str,
384 path: &str,
385 value: &toml::Value,
386) -> std::result::Result<String, String> {
387 let schema = Config::default();
388 let Some(setting) = schema.setting(path) else {
389 return Err(unknown_setting(&schema, path));
390 };
391 let typed = Kind::of(value);
392 if typed != setting.kind && !(setting.kind == Kind::Integer && is_unlimited(value)) {
395 return Err(format!(
396 "`{}` holds {} — {} is {}",
397 setting.path(),
398 setting.kind,
399 render(value),
400 typed
401 ));
402 }
403 let edited = super::toml_set_value(text, &setting.section, &setting.key, &render(value));
404 let checked = super::parse_text(&edited).map_err(|e| {
405 format!(
406 "that would not load, so nothing was saved: {}",
407 one_line(&e.to_string())
408 )
409 })?;
410 if names_a_route(&setting) {
415 checked.validate_routes().map_err(|e| {
416 format!(
417 "that would not load, so nothing was saved: {}",
418 one_line(&e.to_string())
419 )
420 })?;
421 }
422 if setting.section == "context" {
426 checked.context.validate().map_err(|e| {
427 format!(
428 "that would not load, so nothing was saved: {}",
429 one_line(&e.to_string())
430 )
431 })?;
432 }
433 match checked.setting(&setting.path()) {
434 Some(after) if after.value.as_ref() == Some(value) => Ok(edited),
435 Some(after) if is_empty_string(value) && after.value.is_none() => Ok(edited),
440 Some(after) => Err(format!(
441 "the file would read `{}` back as {}, not {}; nothing was saved",
442 setting.path(),
443 after.rendered(),
444 render(value)
445 )),
446 None => Err(format!(
447 "`{}` disappeared from the file when it was edited; nothing was saved",
448 setting.path()
449 )),
450 }
451}
452
453pub fn set_list_in_text(
459 text: &str,
460 path: &str,
461 items: &[String],
462) -> std::result::Result<String, String> {
463 let value = toml::Value::Array(items.iter().cloned().map(toml::Value::String).collect());
464 set_in_text(text, path, &value)
465}
466
467pub fn about(path: &str) -> &'static str {
474 const ABOUT: &[(&str, &str)] = &[
475 ("agent.context_file_max_chars", "Truncate one context file past this many characters, keeping its head and tail; 0 = no per-file cap"),
477 ("agent.context_files_budget_chars", "Ceiling across every context file; whole files are dropped past it, broadest first"),
478 ("agent.max_consecutive_malformed_tool_calls", "Stop the run after this many consecutive tool calls that could not be used"),
479 ("agent.max_iterations", "How many model-and-tool round trips one turn may take"),
480 ("agent.output_schema", "A JSON Schema every reply must satisfy, as a path or inline JSON"),
481 ("agent.system_prompt", "The standing instructions every run starts with, added to the built-in prompt rather than replacing it"),
482 ("agent.trace_content", "Include prompts, arguments and results in trace spans"),
483 (
484 "agent.prompt_blocks",
485 "Standing prompt blocks after system_prompt: `auto` (per model family), a list of names, or `off`",
486 ),
487 (
489 "cli.approval",
490 "What an `ask` policy does: `ask` prompts, `auto` never does, `smart` asks a cheap model first and escalates when it is unsure",
491 ),
492 ("cli.clear_on_exit", "What an interactive exit does to the screen: `screen`, `all` or `off`"),
493 ("cli.color", "Colour on a terminal; unset means decide from the stream, and from `NO_COLOR`"),
494 ("cli.history_size", "How many commands the REPL remembers for arrow-up"),
495 ("cli.markdown", "Markdown in replies; unset means on when colour is on"),
496 ("context.compact_at", "Share of the model's window at which a request is compacted, e.g. 0.85; 0 turns the threshold off"),
498 ("context.handoff_chars", "Hard cap, in characters, on the compiled handoff that stands in for the dropped middle"),
499 ("context.judge", "Ask one model one bounded question about why the dropped turns went the way they did"),
500 ("context.judge_timeout_secs", "How long that one call may take before the deterministic handoff ships without it"),
501 ("context.protect_last_n", "Turns kept verbatim at the tail; 0 is read as 1"),
502 ("context.window_tokens", "The window to assume when the endpoint advertises none; 0 assumes nothing"),
503 ("gateway.api_session_ttl_hours", "How long a session made by `POST /v1/chat/completions` is kept"),
505 ("gateway.check_interval_hours", "How often the gateway runs the update check and logs what it found"),
506 ("hooks.order", "The hooks that run, and in what order, by name; one that is not listed does not run, and `[]` runs none"),
511 ("plugins.dir", "Root of the shared plugin directory (default `<config_dir>/plugins`)"),
513 ("plugins.enabled", "The plugins to load, by directory name; one that is not listed loads only as a wire profile"),
514 ("plugins.mcp_timeout_secs", "Ceiling on one MCP call, for `[[mcp]]` entries that state none of their own"),
515 ("provider.api_key", "A key written into the file; prefer `api_key_env` or `ECLIPSE_API_KEY`, which keep it out of it"),
517 ("provider.api_key_env", "Name of an environment variable holding the key"),
518 ("provider.aux", "The route that does the agent's own housekeeping — the summary of trimmed turns — and never the user's work"),
519 ("provider.base_url", "Base URL of an OpenAI-compatible API, up to the `/v1`"),
520 ("provider.context_budget_tokens", "Soft cap on the conversation sent to the model, in estimated tokens (characters / 4, a rough heuristic)"),
521 ("provider.delegate", "The route a `delegate` call's child agent runs on unless the call names one"),
522 ("provider.fallback", "The routes tried in order when a request fails for a transient reason"),
523 ("provider.max_retries", "Extra attempts after a request fails with 408, 429 or 5xx, or could not be sent (0 = never)"),
524 ("provider.max_tokens", "Cap on the reply, in tokens"),
525 ("provider.model", "The model every request asks for"),
526 ("provider.parallel_tool_calls", "Ask for several tool calls in one reply"),
527 ("provider.profile", "Wire profile: `openai` (default), `llamacpp`, or one a plugin declares"),
528 ("provider.reasoning_effort", "How much the model thinks, on backends that have the knob (`low`, `medium`, `high` …), or `omit` to put no reasoning field on the wire at all"),
529 ("provider.retry_after_send", "Also retry a request that failed after it went out — a dropped connection, or nothing for `timeout_secs`"),
530 ("provider.retry_base_delay_ms", "How long the first retry waits; each further attempt doubles it"),
531 ("provider.seed", "Ask for a reproducible sample, where the backend supports it"),
532 ("provider.stop", "Up to four sequences the reply stops at"),
533 ("provider.stream", "Ask for a token-by-token (SSE) reply"),
534 ("provider.temperature", "Sampling temperature, unset leaves whatever the server defaults to"),
535 ("provider.timeout_secs", "Ceiling on one request, from connect to last byte"),
536 ("provider.tool_choice", "`auto`, `none`, `required`, or one tool's name"),
537 ("provider.top_p", "Nucleus sampling: draw from the smallest set of tokens holding this much probability"),
538 ("provider.vision", "Declare whether this route's model can see images (overrides the wire profile)"),
539 (
541 "attachments.dir",
542 "Where attached pictures are stored; defaults to `<state_dir>/attachments`"
543 ),
544 (
545 "attachments.max_total_bytes",
546 "Ceiling for every picture kept on disk, in bytes; the oldest are pruned when an attach would exceed it, and only then is an attach refused (0 = no ceiling)"
547 ),
548 ("sessions.auto_prune", "Apply the retention limits when the CLI starts, before the first prompt"),
550 ("sessions.autotitle", "Name sessions: a name derived from the opening message, plus at most one small-model call"),
551 ("sessions.dir", "Where sessions are stored; defaults to `<state_dir>/sessions`"),
552 ("sessions.lock_wait_secs", "How long a run waits for another process to release the same session; 0 fails on the first refusal"),
553 ("sessions.retention_keep_count", "Default for `sessions prune --keep-count`: keep only the newest N; 0 = disabled"),
554 ("sessions.retention_keep_days", "Default for `sessions prune --keep-days`: delete sessions idle longer than this; 0 = disabled"),
555 ("skills.index_budget_chars", "Ceiling for the skill index in the system prompt, in characters"),
557 ("vision.mode", "A picture goes to the turn's model (`native`), to a route that describes it (`text`), or wherever the model's declared vision allows (`auto`)"),
559 ("vision.route", "The route that describes a picture, for `text` and for `auto`'s fallback; empty means there is none"),
560 ("vision.allow_cloud", "Let a picture be described by a route that is not on this machine"),
561 ("flares.count", "Default number of jobs for `flares run -n`; a local run starts from it (default 3)"),
563 ("flares.max_concurrent", "The most flares one run may have in flight, whatever the routes allow"),
564 ("flares.max_iterations", "Per flare, when the job does not say: what `delegate` gives a child"),
565 ("flares.total_iterations", "The run's own budget: what stops one wandering flare eating the others' turns"),
566 ("flares.total_tokens", "Optional spend cap for the whole run, in tokens; unset = the budgets are the ceiling"),
567 ("tools.concurrency", "How many of one turn's tool calls run at the same time; 1 runs them in order"),
569 ("tools.deferred", "Tools that stay callable but are not described in the request, so they cost no tokens until needed"),
570 ("tools.delegate", "The `delegate` tool's policy: hand a job to a child agent"),
571 ("tools.disabled", "Tools removed entirely, whatever their policy says"),
572 ("tools.execute_code", "The `execute_code` tool: a short program run from a temporary file, with a bridge to the tools"),
573 ("tools.fetch", "The `fetch` tool: one URL in, its text out"),
574 ("tools.fetch_html", "`text` renders HTML responses as plain text; `raw` returns the source"),
575 ("tools.fetch_timeout_secs", "Ceiling on one `fetch`"),
576 ("tools.max_output_bytes", "Tool output is cut to this many bytes before the model sees it"),
577 ("tools.memory", "The `memory` tool's policy: write a durable fact to MEMORY.md"),
578 ("tools.patch", "The `patch` tool's policy: a targeted edit of a file that already exists"),
579 ("tools.read_file", "The `read_file` tool"),
580 ("tools.rewrite_guard_bytes", "Above this size, `write_file` needs `force` to clobber an existing file"),
581 ("tools.script", "The `script` tool's policy: run a file from the scripts directory"),
582 ("tools.search_files", "The `search_files` tool's policy: a read-only walk of the workspace"),
583 ("tools.shell", "The `shell` tool: run a command on this machine"),
584 ("tools.shell_allowlist", "If set, `shell` may only run these program names, without a shell"),
585 ("tools.shell_ask", "Which `shell` commands ask first: `dangerous` asks only for the un-undoable ones"),
586 ("tools.shell_isolate", "What a `shell` command can reach: `off`, `process` (private PID namespace) or `fs` (bubblewrap)"),
587 ("tools.shell_isolate_hide", "Paths replaced by an empty directory in `fs` mode, so nothing in them can be read"),
588 ("tools.shell_isolate_network", "Whether `fs` isolation keeps the network"),
589 ("tools.shell_isolate_writable", "Extra paths bound read-write in `fs` mode, beyond the workspace and the scripts directory"),
590 ("tools.shell_timeout_secs", "Ceiling on one `shell` command"),
591 ("tools.tool_call", "Call a tool a search found, without it being described up front"),
592 ("tools.tool_describe", "Ask for a deferred tool's full schema"),
593 ("tools.tool_search", "The `tool_search` tool's policy: look for a deferred tool"),
594 ("tools.workspace_root", "The file tools are confined to this directory"),
595 ("tools.write_file", "The `write_file` tool"),
596 ("update.check", "How often the update check asks: `daily`, `weekly` or `off`"),
598 ("update.releases", "Where the newest release is asked for, instead of the public GitHub repository"),
599 ("update.remote", "Where the latest commit is asked for, instead of the public GitHub repository"),
600 ("update.track", "Which branch a source install follows: `release` is main, `develop` is the branch work lands on"),
601 ("user.file", "The user model file, relative to the config directory unless absolute"),
603 ("user.memory_budget_chars", "Ceiling for `MEMORY.md` in characters"),
604 ("user.memory_file", "The agent's memory file, resolved the same way"),
605 ("web.auth_token", "The dashboard's login secret, generated by `config init`"),
607 ("web.default_profile", "The profile the dashboard serves when neither `--profile` nor `ECLIPSE_PROFILE` names one"),
608 ("web.host", "The address the dashboard binds; loopback only"),
609 ("web.port", "The port the dashboard listens on"),
610 ("web.session_ttl_hours", "How long a browser stays signed in"),
611 ];
612 ABOUT
613 .iter()
614 .find(|(key, _)| *key == path)
615 .map(|(_, about)| *about)
616 .unwrap_or("")
617}
618
619fn word_default(path: &str) -> Option<Kind> {
630 match path {
631 "agent.max_iterations" => Some(Kind::Integer),
632 _ => None,
633 }
634}
635
636const UNLIMITED: &[&str] = &[
638 "unlimited",
639 "none",
640 "null",
641 "inf",
642 "infinite",
643 "infinity",
644 "∞",
645];
646
647fn is_unlimited(value: &toml::Value) -> bool {
648 value
649 .as_str()
650 .is_some_and(|w| UNLIMITED.contains(&w.trim().to_ascii_lowercase().as_str()))
651}
652
653pub fn choices(path: &str) -> &'static [&'static str] {
654 const ANY: &[&str] = &["deny", "ask", "allow"];
655 match path {
656 p if p.starts_with("tools.")
658 && matches!(
659 p.split_once('.').map(|(_, k)| k),
660 Some(
661 "delegate"
662 | "execute_code"
663 | "fetch"
664 | "memory"
665 | "patch"
666 | "read_file"
667 | "script"
668 | "search_files"
669 | "shell"
670 | "tool_call"
671 | "tool_describe"
672 | "tool_search"
673 | "write_file"
674 )
675 ) =>
676 {
677 ANY
678 }
679 "vision.mode" => &["native", "text", "auto"],
683 "cli.approval" => &["ask", "auto", "smart"],
686 "cli.clear_on_exit" => &["screen", "all", "off"],
687 "tools.fetch_html" => &["text", "raw"],
688 "tools.shell_ask" => &["dangerous", "always"],
689 "tools.shell_isolate" => &["off", "process", "fs"],
690 "update.check" => &["daily", "weekly", "off"],
691 "update.track" => &["release", "develop"],
692 _ => &[],
693 }
694}
695
696fn names_a_route(setting: &Setting) -> bool {
698 names_a_route_path(&setting.path())
699}
700
701fn names_a_route_path(path: &str) -> bool {
702 path.starts_with("provider.route")
705 || matches!(
706 path,
707 "provider.aux" | "provider.delegate" | "provider.fallback" | "vision.route"
708 )
709}
710
711pub fn unset_in_text(text: &str, path: &str) -> std::result::Result<String, String> {
716 let schema = Config::default();
717 let Some(setting) = schema.setting(path) else {
718 return Err(unknown_setting(&schema, path));
719 };
720 let edited = super::toml_comment_out(text, &setting.section, &setting.key);
721 let checked = super::parse_text(&edited).map_err(|e| {
722 format!(
723 "that would not load, so nothing was saved: {}",
724 one_line(&e.to_string())
725 )
726 })?;
727 match checked.setting(&setting.path()) {
728 Some(after) if after.value == setting.value => Ok(edited),
734 Some(after) => Err(format!(
735 "the file would still read `{}` as {}; nothing was saved",
736 setting.path(),
737 after.rendered()
738 )),
739 None => Err(format!(
740 "`{}` disappeared from the file when it was edited; nothing was saved",
741 setting.path()
742 )),
743 }
744}
745
746fn unknown_setting(schema: &Config, path: &str) -> String {
749 let path = path.trim();
750 let (section, key) = path.split_once('.').unwrap_or(("", path));
751 let settings = schema.settings();
752 if let Some(elsewhere) = settings.iter().find(|s| s.key == key) {
753 return format!(
754 "`{path}` is not a setting: `{key}` is read under [{}]. Write `{}`.",
755 elsewhere.section,
756 elsewhere.path()
757 );
758 }
759 let mut near: Vec<String> = settings
760 .iter()
761 .filter(|s| s.key.contains(key) || key.contains(&s.key) || s.section == section)
762 .map(Setting::path)
763 .take(8)
764 .collect();
765 if near.is_empty() {
766 near = settings.iter().take(8).map(Setting::path).collect();
767 }
768 format!(
769 "`{path}` is not a setting in this build. `eclipse config keys` lists all of them; \
770 close to what you wrote: {}",
771 near.join(", ")
772 )
773}
774
775pub(super) fn one_line(text: &str) -> String {
776 text.split_whitespace().collect::<Vec<_>>().join(" ")
777}
778
779#[cfg(test)]
780mod tests {
781 use super::*;
782
783 fn paths() -> Vec<String> {
784 Config::default()
785 .settings()
786 .into_iter()
787 .map(|s| s.path())
788 .collect()
789 }
790
791 #[test]
792 fn the_catalogue_is_derived_from_the_config_itself() {
793 let paths = paths();
794 assert!(paths.contains(&"provider.model".to_string()), "{paths:?}");
795 assert!(paths.contains(&"tools.shell".to_string()), "{paths:?}");
796 assert!(paths.contains(&"web.port".to_string()), "{paths:?}");
797 assert!(
799 !paths.iter().any(|k| k.starts_with("provider.route")),
800 "a route is a table to edit, not a value: {paths:?}"
801 );
802 assert!(
803 paths.iter().all(|k| k.matches('.').count() == 1),
804 "{paths:?}"
805 );
806 let mut sorted = paths.clone();
808 sorted.sort();
809 assert_eq!(paths, sorted);
810 }
811
812 #[test]
821 fn every_field_a_default_config_omits_is_still_settable() {
822 let mut c = Config::default();
823 c.provider.api_key = Some("probe".into());
824 c.provider.api_key_env = Some("PROBE_KEY".into());
825 c.provider.aux = Some("mmnuc/small".into());
826 c.provider.delegate = Some("mmnuc/small".into());
827 c.provider.fallback = Some(vec!["local".into()]);
828 c.provider.temperature = Some(0.5);
829 c.provider.max_tokens = Some(1024);
830 c.provider.profile = Some("openai".into());
831 c.provider.top_p = Some(0.9);
832 c.provider.seed = Some(7);
833 c.provider.stop = Some(vec!["</s>".into()]);
834 c.provider.reasoning_effort = Some("low".into());
835 c.provider.parallel_tool_calls = Some(true);
836 c.provider.vision = Some(true);
837 c.provider.tool_choice = Some(crate::hooks::ToolChoice::Auto);
838 c.provider.extra_body = Some(serde_json::json!({"chat_template_kwargs": {"x": 1}}));
839 c.agent.output_schema = Some("{}".into());
840 c.tools.workspace_root = Some(std::path::PathBuf::from("/w"));
841 c.sessions.dir = Some(std::path::PathBuf::from("/s"));
842 c.plugins.dir = Some(std::path::PathBuf::from("/p"));
843 c.plugins.mcp_timeout_secs = Some(30);
844 c.web.auth_token = Some("probe-token".into());
845 c.web.default_profile = Some("work".into());
846 c.cli.color = Some(false);
847 c.cli.markdown = Some(true);
848 c.update.remote = Some("https://mirror.internal/latest".into());
849 c.update.releases = Some("https://mirror.internal/releases".into());
850
851 let filled = toml::Value::try_from(&c).expect("a filled config serialises");
852 let schema = Config::default();
853 let mut checked = 0;
854 for (section, table) in filled.as_table().expect("a table").iter() {
855 let Some(table) = table.as_table() else {
856 continue;
857 };
858 for key in table.keys() {
859 let path = format!("{section}.{key}");
860 if NOT_SETTINGS.contains(&path.as_str()) {
861 continue;
862 }
863 assert!(
864 schema.setting(&path).is_some(),
865 "`{path}` is a real field but not a setting: `config set {path} …` would refuse it"
866 );
867 checked += 1;
868 }
869 }
870 assert!(
871 checked > 60,
872 "the walk has to see the whole catalogue, not a corner: {checked}"
873 );
874 }
875
876 #[test]
880 fn a_turn_budget_takes_a_number_and_the_word_for_no_cap() {
881 let schema = Config::default();
882 let setting = schema.setting("agent.max_iterations").expect("a setting");
883 assert_eq!(setting.kind, Kind::Integer, "a number, not a word");
884
885 let edited = set_in_text("", "agent.max_iterations", &toml::Value::Integer(40)).unwrap();
886 let cfg = super::super::parse_text(&edited).unwrap();
887 assert_eq!(cfg.agent.max_iterations, 40);
888
889 let edited = set_in_text(
890 "",
891 "agent.max_iterations",
892 &toml::Value::String("unlimited".into()),
893 )
894 .unwrap();
895 let cfg = super::super::parse_text(&edited).unwrap();
896 assert_eq!(cfg.agent.max_iterations, usize::MAX);
897
898 let refused = set_in_text(
900 "",
901 "agent.max_iterations",
902 &toml::Value::String("lots".into()),
903 )
904 .unwrap_err();
905 assert!(refused.contains("max_iterations"), "{refused}");
906 }
907
908 #[test]
911 fn every_key_is_explained_and_the_closed_sets_name_their_values() {
912 let settings = Config::default().settings();
913 assert!(
914 settings.len() > 80,
915 "the whole catalogue: {}",
916 settings.len()
917 );
918 for s in &settings {
919 assert!(
920 !s.about.trim().is_empty(),
921 "{} has no description — add it to `about`",
922 s.path()
923 );
924 assert!(s.about.len() < 160, "{}: too long for a row", s.path());
925 assert!(
926 !s.about.ends_with('.'),
927 "{}: no trailing full stop",
928 s.path()
929 );
930 }
931 assert!(
935 about("hooks.order").contains("does not run"),
936 "{}",
937 about("hooks.order")
938 );
939 assert_eq!(choices("cli.approval"), &["ask", "auto", "smart"]);
940 assert_eq!(choices("tools.read_file"), &["deny", "ask", "allow"]);
941 assert!(choices("provider.model").is_empty());
942 }
943
944 #[test]
948 fn every_key_that_is_absent_by_default_is_real_and_settable() {
949 for (section, key, kind) in ABSENT_BY_DEFAULT {
950 let path = format!("{section}.{key}");
951 let sample = match kind {
952 Kind::Str if names_a_route_path(&path) => toml::Value::String("default".into()),
956 Kind::Str => toml::Value::String("probe".into()),
957 Kind::Integer => toml::Value::Integer(7),
958 Kind::Float => toml::Value::Float(0.5),
959 Kind::Bool => toml::Value::Boolean(true),
960 Kind::List if names_a_route_path(&path) => {
964 toml::Value::Array(vec![toml::Value::String("default".into())])
965 }
966 Kind::List => toml::Value::Array(vec![toml::Value::String("probe".into())]),
967 Kind::Datetime => continue,
968 };
969 let edited = set_in_text("", &path, &sample).unwrap_or_else(|e| panic!("{path}: {e}"));
970 let cfg = super::super::parse_text(&edited).unwrap_or_else(|e| panic!("{path}: {e}"));
971 assert_eq!(
972 cfg.setting(&path).and_then(|s| s.value),
973 Some(sample),
974 "{path} did not read back — is it a real field?"
975 );
976 }
977 }
978
979 #[test]
980 fn an_absent_key_reports_itself_as_unset_and_is_not_the_default() {
981 let schema = Config::default();
982 let key = schema
983 .setting("provider.api_key")
984 .expect("api_key is a setting");
985 assert!(key.secret, "a key by that name is a secret");
986 assert_eq!(
987 key.rendered(),
988 "«redacted»",
989 "never printed, even when unset"
990 );
991 assert_eq!(key.value, None, "absent is not the empty string");
992 let plain = schema
993 .setting("provider.model")
994 .expect("model is a setting");
995 assert!(!plain.secret);
996 }
997
998 #[test]
1001 fn a_count_is_not_a_credential() {
1002 let schema = Config::default();
1003 let window = schema
1004 .setting("context.window_tokens")
1005 .expect("window_tokens is a setting");
1006 assert!(!window.secret, "a token count is not a token");
1007 assert_eq!(window.rendered(), "0", "and its value is readable");
1008 assert!(schema.setting("provider.api_key").unwrap().secret);
1009 assert!(
1010 !schema.setting("provider.api_key_env").unwrap().secret,
1011 "the name of a variable is not the variable"
1012 );
1013 }
1014
1015 #[test]
1016 fn setting_a_key_edits_one_line_and_everything_else_survives() {
1017 let text = "# my provider\n[provider]\n# the name the endpoint serves\nmodel = \"old\"\n\n[web]\nport = 8787\n";
1018 let edited =
1019 set_in_text(text, "provider.model", &toml::Value::String("new".into())).unwrap();
1020 assert!(edited.contains("model = \"new\""), "{edited}");
1021 assert!(
1022 edited.contains("# my provider") && edited.contains("# the name"),
1023 "{edited}"
1024 );
1025 assert!(edited.contains("port = 8787"), "{edited}");
1026 assert!(!edited.contains("\"old\""), "{edited}");
1027 }
1028
1029 #[test]
1030 fn a_typed_value_is_written_as_toml_and_read_back() {
1031 let text = "[web]\nport = 8787\n";
1032 let edited = set_in_text(text, "web.port", &toml::Value::Integer(9000)).unwrap();
1033 assert!(edited.contains("port = 9000"), "{edited}");
1034 let cfg = super::super::parse_text(&edited).unwrap();
1035 assert_eq!(cfg.web.port, 9000);
1036 }
1037
1038 #[test]
1039 fn a_value_of_the_wrong_shape_is_refused_with_the_shape_it_wants() {
1040 let text = "[web]\nport = 8787\n";
1041 let err = set_in_text(text, "web.port", &toml::Value::String("nine".into())).unwrap_err();
1042 assert!(err.contains("`web.port` holds an integer"), "{err}");
1043 assert!(err.contains("\"nine\" is a string"), "{err}");
1044
1045 let err =
1046 set_in_text(text, "web.session_ttl_hours", &toml::Value::Boolean(true)).unwrap_err();
1047 assert!(err.contains("an integer"), "{err}");
1048 }
1049
1050 #[test]
1051 fn a_key_this_build_does_not_read_is_refused_and_the_right_table_is_named() {
1052 let text = "[web]\n";
1053 let err = set_in_text(text, "web.model", &toml::Value::String("m".into())).unwrap_err();
1054 assert!(err.contains("`model` is read under [provider]"), "{err}");
1055 assert!(err.contains("provider.model"), "{err}");
1056
1057 let err = set_in_text(text, "provider.modl", &toml::Value::String("m".into())).unwrap_err();
1058 assert!(err.contains("is not a setting"), "{err}");
1059 assert!(err.contains("config keys"), "where to look: {err}");
1060 }
1061
1062 #[test]
1065 fn a_fallback_naming_a_route_that_does_not_exist_is_refused() {
1066 let text = "[provider]\nbase_url = \"http://127.0.0.1:8080/v1\"\nmodel = \"m\"\n";
1067 let err = set_in_text(
1068 text,
1069 "provider.fallback",
1070 &toml::Value::Array(vec![toml::Value::String("ghost".into())]),
1071 )
1072 .unwrap_err();
1073 assert!(err.contains("ghost"), "{err}");
1074 assert!(err.contains("nothing was saved"), "{err}");
1075 }
1076
1077 #[test]
1078 fn a_context_share_outside_the_window_is_refused() {
1079 let err = set_in_text("", "context.compact_at", &toml::Value::Float(1.5)).unwrap_err();
1080 assert!(err.contains("context.compact_at"), "{err}");
1081 assert!(err.contains("nothing was saved"), "{err}");
1082 let err = set_in_text("", "context.handoff_chars", &toml::Value::Integer(50)).unwrap_err();
1083 assert!(err.contains("context.handoff_chars"), "{err}");
1084 }
1085
1086 #[test]
1087 fn a_key_the_config_does_not_have_yet_is_inserted_under_its_section() {
1088 let text = "[provider]\nbase_url = \"http://x/v1\"\n";
1089 let edited = set_in_text(
1090 text,
1091 "provider.api_key_env",
1092 &toml::Value::String("MY_KEY".into()),
1093 )
1094 .unwrap();
1095 assert!(edited.contains("api_key_env = \"MY_KEY\""), "{edited}");
1096 let cfg = super::super::parse_text(&edited).unwrap();
1097 assert_eq!(cfg.provider.api_key_env.as_deref(), Some("MY_KEY"));
1098 }
1099
1100 #[test]
1101 fn unsetting_a_key_comments_it_out_and_the_default_comes_back() {
1102 let text = "[web]\nport = 9000\n";
1103 let edited = unset_in_text(text, "web.port").unwrap();
1104 assert!(
1105 edited.contains("# port = 9000"),
1106 "the line is kept as documentation: {edited}"
1107 );
1108 let cfg = super::super::parse_text(&edited).unwrap();
1109 assert_eq!(cfg.web.port, Config::default().web.port);
1110 }
1111
1112 #[test]
1117 fn the_reasoning_key_reports_the_shipped_default_as_value_and_default() {
1118 let fresh = super::super::parse_text(&super::super::starter_config().unwrap())
1119 .expect("the starter");
1120 let row = fresh
1121 .setting("provider.reasoning_effort")
1122 .expect("the key is in the catalogue");
1123 assert_eq!(
1124 row.rendered(),
1125 format!("\"{}\"", crate::reasoning::SHIPPED_DEFAULT),
1126 "a fresh install has the level written down"
1127 );
1128 assert!(
1129 row.is_default(),
1130 "and the value is the default, so `config keys` marks it (default)"
1131 );
1132
1133 let older = Config::default();
1135 let row = older
1136 .setting("provider.reasoning_effort")
1137 .expect("the key is in the catalogue");
1138 assert_eq!(
1139 row.default,
1140 Some(toml::Value::String(
1141 crate::reasoning::SHIPPED_DEFAULT.into()
1142 )),
1143 "the resolver's answer is reportable even with no line in the file"
1144 );
1145 assert_eq!(row.value, None, "and the file genuinely sets nothing");
1146 assert_eq!(
1147 older.provider.reasoning_effort, None,
1148 "the config struct still sends nothing to a backend that declares no default"
1149 );
1150 }
1151
1152 #[test]
1156 fn the_reasoning_key_takes_the_omit_sentinel_as_a_value() {
1157 let cfg = super::super::parse_text(
1158 "[provider]\nbase_url = \"http://h/v1\"\nmodel = \"m\"\nreasoning_effort = \"omit\"\n",
1159 )
1160 .expect("the sentinel loads");
1161 assert_eq!(cfg.provider.reasoning_effort.as_deref(), Some("omit"));
1162 let row = cfg
1163 .setting("provider.reasoning_effort")
1164 .expect("the key is in the catalogue");
1165 assert_eq!(row.rendered(), "\"omit\"");
1166 assert!(
1167 !row.is_default(),
1168 "an operator's choice, not the shipped default"
1169 );
1170 }
1171
1172 #[test]
1173 fn a_bare_word_is_a_string_and_toml_literals_keep_their_type() {
1174 assert_eq!(
1175 parse_value("gemma-4-12b"),
1176 toml::Value::String("gemma-4-12b".into())
1177 );
1178 assert_eq!(parse_value("3"), toml::Value::Integer(3));
1179 assert_eq!(parse_value("true"), toml::Value::Boolean(true));
1180 assert_eq!(parse_value("0.5"), toml::Value::Float(0.5));
1181 assert_eq!(
1182 parse_value(r#"["a", "b"]"#),
1183 toml::Value::Array(vec![
1184 toml::Value::String("a".into()),
1185 toml::Value::String("b".into())
1186 ])
1187 );
1188 assert_eq!(parse_value(""), toml::Value::String(String::new()));
1189 }
1190
1191 #[test]
1193 fn vision_mode_offers_its_three_words() {
1194 assert_eq!(choices("vision.mode"), &["native", "text", "auto"]);
1195 for word in choices("vision.mode") {
1198 assert!(
1199 Config::default().setting("vision.mode").is_some(),
1200 "the key exists"
1201 );
1202 assert!(
1203 crate::config::Config::from_toml_str(&format!("[vision]\nmode = \"{word}\"\n"))
1204 .is_ok(),
1205 "{word} is a value the config accepts"
1206 );
1207 }
1208 }
1209
1210 #[test]
1214 fn a_route_typo_is_refused_by_the_command_that_writes_it() {
1215 let err =
1216 set_in_text("", "vision.route", &toml::Value::String("sigth".into())).unwrap_err();
1217 assert!(
1218 err.contains("names `sigth`") && err.contains("Routes that exist"),
1219 "{err}"
1220 );
1221 assert!(set_in_text("", "vision.route", &toml::Value::String("default".into())).is_ok());
1223 let edited = set_in_text("", "agent.max_iterations", &toml::Value::Integer(40)).unwrap();
1225 assert!(edited.contains("max_iterations = 40"));
1226 }
1227
1228 #[test]
1231 fn a_gateway_key_says_restart_instead_of_next_run() {
1232 let schema = Config::default();
1233 for path in [
1234 "gateway.check_interval_hours",
1235 "gateway.api_session_ttl_hours",
1236 "web.port",
1237 ] {
1238 let s = schema
1239 .setting(path)
1240 .unwrap_or_else(|| panic!("{path} exists"));
1241 assert_eq!(
1242 s.applies,
1243 Applies::RestartProcess,
1244 "{path} is read once by a process"
1245 );
1246 }
1247 let s = schema.setting("agent.max_iterations").expect("a setting");
1248 assert_eq!(s.applies, Applies::NextRun, "the agent is rebuilt per run");
1249 assert_eq!(
1250 Applies::RestartProcess.as_str(),
1251 "restart the background process"
1252 );
1253 }
1254}