Skip to main content

microclaw_engine/config/
core.rs

1use super::*;
2
3pub fn normalize_model_name(value: &str) -> Option<String> {
4    let trimmed = value.trim();
5    if trimmed.is_empty() || trimmed == "*" {
6        None
7    } else {
8        Some(trimmed.to_string())
9    }
10}
11
12pub(crate) fn normalize_string_list(values: &mut Vec<String>, lowercase: bool) {
13    *values = values
14        .drain(..)
15        .map(|value| {
16            let value = value.trim();
17            if lowercase {
18                value.to_ascii_lowercase()
19            } else {
20                value.to_string()
21            }
22        })
23        .filter(|value| !value.is_empty())
24        .collect();
25    values.sort();
26    values.dedup();
27}
28
29pub fn resolve_model_name_with_fallback(
30    provider: &str,
31    candidate: Option<&str>,
32    fallback: Option<&str>,
33) -> String {
34    candidate
35        .and_then(normalize_model_name)
36        .or_else(|| fallback.and_then(normalize_model_name))
37        .unwrap_or_else(|| default_model_for_provider_name(provider).to_string())
38}
39
40/// Expands a path string, replacing `~` with the user's home directory.
41pub(crate) fn expand_path(path: &str) -> PathBuf {
42    match shellexpand::tilde(path) {
43        std::borrow::Cow::Borrowed(p) => PathBuf::from(p),
44        std::borrow::Cow::Owned(p) => PathBuf::from(p),
45    }
46}
47
48pub(crate) fn detect_system_timezone() -> String {
49    match iana_time_zone::get_timezone() {
50        Ok(tz_name) => tz_name,
51        Err(e) => {
52            warn!("Failed to detect system timezone automatically: {e}. Falling back to UTC.");
53            "UTC".into()
54        }
55    }
56}
57
58/// Language for user-facing runtime messages (refusals, approval prompts,
59/// recovery notices). `en` preserves historical output; approval reply
60/// keywords are recognized in both languages regardless.
61#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
62#[serde(rename_all = "lowercase")]
63pub enum UserMessageLanguage {
64    #[default]
65    En,
66    Zh,
67    Bilingual,
68}
69
70/// How much time detail the runtime injects into the prompt for the current
71/// turn. Lower values keep the cached prompt prefix stable across turns, which
72/// is what prompt caching requires: anything that changes every turn must live
73/// in the transient turn-context block instead of the system prompt.
74#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
75#[serde(rename_all = "lowercase")]
76pub enum SystemPromptTimeDetail {
77    /// No clock in the system prompt. The live time is only available through
78    /// the `get_current_time` tool and the transient turn-context block.
79    None,
80    /// Date only (`YYYY-MM-DD`) in the configured timezone. Stable for a whole
81    /// local day, so the prefix still survives within a day.
82    #[default]
83    Date,
84    /// Full local and UTC timestamps. Changes on every turn, so the system
85    /// prompt prefix is invalidated continuously.
86    Full,
87}
88
89#[derive(Clone, Debug, Serialize, Deserialize)]
90pub struct Config {
91    // --- LLM / API ---
92    #[serde(default = "default_llm_provider")]
93    pub llm_provider: String,
94    #[serde(default = "default_api_key")]
95    pub api_key: String,
96    /// Additional API keys forming a rotation pool with `api_key`: on
97    /// auth (401/403) or rate-limit (429) errors the provider advances to
98    /// the next key before retrying.
99    #[serde(default)]
100    pub api_keys: Vec<String>,
101    #[serde(default = "default_model")]
102    pub model: String,
103    #[serde(default)]
104    pub provider_presets: HashMap<String, LlmProviderProfile>,
105    #[serde(default)]
106    pub llm_providers: HashMap<String, LlmProviderProfile>,
107    #[serde(default)]
108    pub llm_base_url: Option<String>,
109    #[serde(default = "default_llm_user_agent")]
110    pub llm_user_agent: String,
111    #[serde(default = "default_max_tokens")]
112    pub max_tokens: u32,
113    #[serde(default = "default_max_tool_iterations")]
114    pub max_tool_iterations: usize,
115    #[serde(default = "default_compaction_timeout_secs")]
116    pub compaction_timeout_secs: u64,
117    /// Optional per-task auxiliary model overrides (e.g. a cheaper model for
118    /// compaction). Empty by default, in which case the main model is used.
119    #[serde(default)]
120    pub aux_models: AuxModels,
121    /// Optional fallback model used when the primary model's provider keeps
122    /// failing (after retries) or its circuit breaker is open. None disables
123    /// fallback (and the breaker wrapper) entirely — behaviour is then
124    /// identical to the primary provider alone.
125    #[serde(default)]
126    pub fallback_model: Option<String>,
127    #[serde(default = "default_max_history_messages")]
128    pub max_history_messages: usize,
129    #[serde(default = "default_max_document_size_mb")]
130    pub max_document_size_mb: u64,
131    #[serde(default = "default_memory_token_budget")]
132    pub memory_token_budget: usize,
133    /// Percentage of memory_token_budget reserved for L0 Identity (PROFILE) memories. Default: 20.
134    #[serde(default = "default_memory_l0_identity_pct")]
135    pub memory_l0_identity_pct: usize,
136    /// Percentage of memory_token_budget reserved for L1 Essential (high-confidence) memories. Default: 30.
137    #[serde(default = "default_memory_l1_essential_pct")]
138    pub memory_l1_essential_pct: usize,
139    #[serde(default = "default_memory_max_entries_per_chat")]
140    pub memory_max_entries_per_chat: usize,
141    #[serde(default = "default_memory_max_global_entries")]
142    pub memory_max_global_entries: usize,
143    /// Maximum active triples per chat in the knowledge graph. 0 = unlimited. Default: 1000.
144    #[serde(default = "default_kg_max_triples_per_chat")]
145    pub kg_max_triples_per_chat: usize,
146    /// Tool-result content over this many Unicode characters is truncated in
147    /// the message history and the full body is stored as an artifact the
148    /// agent can read via `fetch_artifact`. Set to 0 to disable. Default: 4000.
149    #[serde(default = "default_tool_result_truncation_threshold_chars")]
150    pub tool_result_truncation_threshold_chars: usize,
151    /// When truncating, keep this many leading characters of the original
152    /// content in the message history. Default: 1500.
153    #[serde(default = "default_tool_result_truncation_head_chars")]
154    pub tool_result_truncation_head_chars: usize,
155    /// When truncating, keep this many trailing characters (so the agent
156    /// still sees errors/summaries that often live at the end). Default: 500.
157    #[serde(default = "default_tool_result_truncation_tail_chars")]
158    pub tool_result_truncation_tail_chars: usize,
159    /// Lifetime for stashed tool-result artifacts before they're pruned.
160    /// Long enough to span a typical multi-turn task. Default: 24 hours.
161    #[serde(default = "default_tool_result_artifact_ttl_hours")]
162    pub tool_result_artifact_ttl_hours: u64,
163    /// Half-life (in days) of the recency-decay multiplier applied to
164    /// non-PROFILE memories during L1/L2 ranking. After `half_life_days`,
165    /// a memory's effective score is half of its raw confidence; PROFILE
166    /// memories never decay. Set to 0 to disable decay. Default: 30.
167    #[serde(default = "default_memory_recency_half_life_days")]
168    pub memory_recency_half_life_days: f64,
169    /// Graph-augmented memory recall: after the flat L0-L2 layers are built,
170    /// seed the temporal knowledge graph from entities the query mentions and
171    /// pull in connected facts a few hops out (a "# Connected" block). Surfaces
172    /// multi-hop context the flat layers miss, using the graph the reflector
173    /// already builds — local-only, no embeddings or extra LLM calls. Default: true.
174    #[serde(default = "default_memory_graph_recall_enabled")]
175    pub memory_graph_recall_enabled: bool,
176    /// Maximum hops to expand outward from query-seeded entities during
177    /// graph-augmented recall. Clamped to 1-3. Default: 2.
178    #[serde(default = "default_memory_graph_max_hops")]
179    pub memory_graph_max_hops: usize,
180    /// Maximum number of connected triples injected by graph-augmented recall
181    /// (also bounded by the overall memory token budget). Set to 0 to disable.
182    /// Default: 10.
183    #[serde(default = "default_memory_graph_max_triples")]
184    pub memory_graph_max_triples: usize,
185    /// Sliding-window size (in past tool calls) used by the duplicate-call
186    /// circuit breaker. When the same `(tool_name, args)` shows up
187    /// `tool_repeat_limit` times within this many recent calls, the next
188    /// invocation is short-circuited with an error so the agent picks a
189    /// different approach. Set to 0 to disable. Default: 10.
190    #[serde(default = "default_tool_repeat_window")]
191    pub tool_repeat_window: usize,
192    /// Repeat threshold for the duplicate-call circuit breaker. Default: 3.
193    #[serde(default = "default_tool_repeat_limit")]
194    pub tool_repeat_limit: usize,
195    /// Enable Anthropic prompt-cache breakpoints (system + last 3 messages).
196    /// Cuts repeat-turn input cost ~75% for multi-turn chats. Anthropic-only;
197    /// no effect on OpenAI-compatible providers. Default: true.
198    #[serde(default = "default_anthropic_prompt_cache_enabled")]
199    pub anthropic_prompt_cache_enabled: bool,
200    /// Let Anthropic clear old tool results on the server (context editing,
201    /// beta) in addition to MicroClaw's own compaction. Default: false.
202    #[serde(default)]
203    pub anthropic_context_editing: bool,
204    /// Cache TTL for Anthropic prompt cache. "5m" (default) or "1h".
205    /// "1h" requires extended-cache opt-in on the API key.
206    #[serde(default = "default_anthropic_prompt_cache_ttl")]
207    pub anthropic_prompt_cache_ttl: String,
208    /// Enable transparent filesystem checkpoints via a shadow git repo.
209    /// When on, microclaw snapshots each chat's working directory at the
210    /// start of every agent turn so users can `/rewind` to a prior state.
211    /// Off by default — opt in per chat or via global config. Requires `git`
212    /// on PATH.
213    #[serde(default = "default_checkpoints_enabled")]
214    pub checkpoints_enabled: bool,
215    /// Auto-archive `agent-created` skills that haven't been activated in
216    /// this many days and are themselves at least this old. The skill dir
217    /// is moved under `<skills_dir>/.archived/` (recoverable). Set to 0
218    /// to disable. Default: 30 days.
219    #[serde(default = "default_skill_archive_after_days")]
220    pub skill_archive_after_days: u64,
221    /// When building the skills section of the system prompt, inline the
222    /// full body of the top-K skills whose descriptions match the user
223    /// query and list the rest as `name: description` only. Cuts prompt
224    /// cost as the skill library grows. Set to 0 to fall back to the
225    /// flat catalog. Default: 3.
226    #[serde(default = "default_skills_catalog_top_k")]
227    pub skills_catalog_top_k: usize,
228    /// How much live time detail the system prompt carries. The default `date`
229    /// keeps the cached prefix stable within a local day; the live clock and
230    /// query-scoped context are injected per turn instead. Set to `full` to
231    /// restore the previous always-current timestamps in the system prompt.
232    #[serde(default)]
233    pub system_prompt_time_detail: SystemPromptTimeDetail,
234    #[serde(default = "default_max_session_messages")]
235    pub max_session_messages: usize,
236    /// Cap on rendered unified-diff lines attached by file-modifying tools
237    /// (edit_file / write_file). Default: 120.
238    #[serde(default = "default_diff_max_lines")]
239    pub diff_max_lines: usize,
240    /// Deliver file-edit diffs as chat messages on channels that opted into
241    /// progress updates. The web UI always receives diff events. Default: true.
242    #[serde(default = "default_file_diffs_in_chat")]
243    pub file_diffs_in_chat: bool,
244    /// Let write_file / edit_file modify MicroClaw's own governance files
245    /// (the config file, AGENTS.md / SOUL.md / USER.md under data_dir, soul
246    /// and context directories, the path allowlist). Off by default: those
247    /// files are injected into every chat's prompt or define access policy,
248    /// so only scoped tools such as write_memory may change them.
249    #[serde(default)]
250    pub allow_governance_file_writes: bool,
251    /// Approximate context window (tokens) of the configured model, used by
252    /// the mid-turn context-pressure check. Default: 200000.
253    #[serde(default = "default_model_context_window")]
254    pub model_context_window: usize,
255    /// Compact the session mid-turn once a request consumes this percentage
256    /// of `model_context_window`. 0 disables the pressure check (the
257    /// overflow-error retry still applies). Default: 85.
258    #[serde(default = "default_context_pressure_compact_pct")]
259    pub context_pressure_compact_pct: usize,
260    /// Per-model context windows (tokens), overriding `model_context_window`
261    /// and the built-in model table, e.g. `{"my-local-model": 32768}`.
262    #[serde(default)]
263    pub model_context_windows: HashMap<String, usize>,
264    /// Compact automatically when the conversation approaches the model's
265    /// context window (`context_pressure_compact_pct`, at most 90%). Manual
266    /// compaction keeps working when this is off. Default: true.
267    #[serde(default = "default_true")]
268    pub auto_compact: bool,
269    /// Before summarizing, older tool outputs are cleared; the most recent
270    /// this many tokens of tool output are always kept. Default: 40000.
271    #[serde(default = "default_prune_protect_tokens")]
272    pub prune_protect_tokens: usize,
273    /// Clear older tool outputs only when that frees at least this many
274    /// tokens (smaller savings are not worth invalidating the prompt cache).
275    /// Default: 20000.
276    #[serde(default = "default_prune_minimum_tokens")]
277    pub prune_minimum_tokens: usize,
278    /// Keep roughly the last this many tokens of conversation verbatim when
279    /// summarizing. 0 keeps the last `compact_keep_recent` messages instead.
280    /// Default: 0.
281    #[serde(default)]
282    pub compact_keep_recent_tokens: usize,
283    /// Extra instructions for compaction summaries (what to preserve).
284    #[serde(default)]
285    pub compact_instructions: Option<String>,
286    /// Directory of project agent definitions (`<name>.md`) offered to the
287    /// `explore` tool. Set by embedders for trusted workspaces.
288    #[serde(default)]
289    pub project_agents_dir: Option<String>,
290    /// More agent directories (embedder plugins), searched after
291    /// `project_agents_dir`; the first definition of a name wins.
292    #[serde(default, skip_serializing_if = "Vec::is_empty")]
293    pub extra_agents_dirs: Vec<String>,
294    /// Read-only skill directories (embedder plugins) offered after the
295    /// skills directory; a skill there with an existing name is ignored.
296    #[serde(default, skip_serializing_if = "Vec::is_empty")]
297    pub extra_skills_dirs: Vec<String>,
298    /// More MCP configuration files (embedder plugins), loaded after
299    /// `mcp.json` and `mcp.d/*.json`.
300    #[serde(default, skip_serializing_if = "Vec::is_empty")]
301    pub extra_mcp_configs: Vec<String>,
302    /// Embedder-supplied gate consulted before every tool call (permission
303    /// rules, user hooks). Never read from or written to the file.
304    #[serde(skip)]
305    pub tool_gate: crate::tool_gate::ToolGateHandle,
306    /// Offer the model the context tools `context_note` and
307    /// `rewind_context`. Default: false.
308    #[serde(default)]
309    pub context_tools: bool,
310    /// Run foreground shell commands so the user can move a running one to
311    /// the background (MicroClaw Code's Ctrl+B). Set by embedders for coding
312    /// workspaces; never read from or written to the file.
313    #[serde(skip)]
314    pub detachable_foreground_commands: bool,
315    /// Tell the model how full its context is on every request. Default:
316    /// false (on in coding workspaces).
317    #[serde(default)]
318    pub context_budget_hint: bool,
319    /// Offer the read-only `explore` helper. Default: false (on in coding
320    /// workspaces).
321    #[serde(default)]
322    pub explore_tool: bool,
323    /// Opt-in post-edit quality pass: after a turn that ran edit_file /
324    /// write_file, one extra review iteration runs before the reply is
325    /// finalized.
326    #[serde(default)]
327    pub self_recheck: SelfRecheckConfig,
328    #[serde(default = "default_compact_keep_recent")]
329    pub compact_keep_recent: usize,
330    #[serde(default = "default_tool_timeout_secs")]
331    pub default_tool_timeout_secs: u64,
332    #[serde(default)]
333    pub tool_timeout_overrides: HashMap<String, u64>,
334    #[serde(default = "default_mcp_request_timeout_secs")]
335    pub default_mcp_request_timeout_secs: u64,
336    #[serde(default)]
337    pub show_thinking: bool,
338    #[serde(default)]
339    pub subagents: SubagentConfig,
340    #[serde(default)]
341    pub idle_checkin: IdleCheckinConfig,
342    #[serde(default)]
343    pub heartbeat: HeartbeatConfig,
344    #[serde(default)]
345    pub token_budget: TokenBudgetConfig,
346    #[serde(default)]
347    pub alerts: AlertsConfig,
348    #[serde(default)]
349    pub trust_report: TrustReportConfig,
350    /// Language for user-facing refusals/approval prompts/notices.
351    #[serde(default)]
352    pub user_message_language: UserMessageLanguage,
353    #[serde(default)]
354    pub sleep_time: SleepTimeConfig,
355    #[serde(default)]
356    pub interjection: InterjectionConfig,
357    #[serde(default)]
358    pub a2a: A2AConfig,
359
360    // --- Concurrency ---
361    /// Maximum number of pending messages per chat before oldest are dropped.
362    #[serde(default = "default_chat_turn_queue_max_pending")]
363    pub chat_turn_queue_max_pending: usize,
364    /// Inject pending messages into the active agent loop between iterations,
365    /// rather than queuing them for a separate re-run. Default: true.
366    #[serde(default = "default_true")]
367    pub enable_mid_turn_injection: bool,
368    /// On non-web channels (Telegram/Discord/Slack), send a small ack message
369    /// when a follow-up arrives mid-turn and is folded into the active loop.
370    /// Default: true. Has no effect when `enable_mid_turn_injection` is false.
371    #[serde(default = "default_true")]
372    pub mid_turn_injection_echo: bool,
373    /// Maximum number of tools to execute concurrently in a single wave.
374    #[serde(default = "default_parallel_tool_max_concurrency")]
375    pub parallel_tool_max_concurrency: usize,
376    /// Override concurrency class for specific tools (e.g., promote safe MCP tools).
377    /// Keys are tool names, values are "read_only", "side_effect", or "exclusive".
378    #[serde(default)]
379    pub tool_concurrency_overrides: HashMap<String, String>,
380    /// OpenAI-compatible request-body overrides applied for all models/providers.
381    /// Set a key to `null` to remove that field from the outgoing JSON body.
382    #[serde(default)]
383    pub openai_compat_body_overrides: HashMap<String, serde_json::Value>,
384    /// OpenAI-compatible request-body overrides keyed by provider name.
385    /// Provider keys are normalized to lowercase.
386    #[serde(default)]
387    pub openai_compat_body_overrides_by_provider:
388        HashMap<String, HashMap<String, serde_json::Value>>,
389    /// OpenAI-compatible request-body overrides keyed by model name.
390    #[serde(default)]
391    pub openai_compat_body_overrides_by_model: HashMap<String, HashMap<String, serde_json::Value>>,
392
393    // --- Paths & environment ---
394    #[serde(default = "default_data_dir")]
395    pub data_dir: String,
396    #[serde(default)]
397    pub skills_dir: Option<String>,
398    #[serde(default = "default_working_dir")]
399    pub working_dir: String,
400    #[serde(default = "default_working_dir_isolation")]
401    pub working_dir_isolation: WorkingDirIsolation,
402    #[serde(default = "default_high_risk_tool_user_confirmation_required")]
403    pub high_risk_tool_user_confirmation_required: bool,
404    /// Caller channels whose high-risk tool calls (shell commands) need an
405    /// explicit human approval. Control chats always do. Default:
406    /// `["web", "code"]` — the interactive operator surfaces.
407    #[serde(default = "default_approval_channels")]
408    pub approval_channels: Vec<String>,
409    /// Caller channels whose sub-agents may only use read-only tools, so
410    /// workspace writes stay with the main agent. Default: `["code"]`.
411    #[serde(default = "default_read_only_subagent_channels")]
412    pub read_only_subagent_channels: Vec<String>,
413    /// Regex patterns that always require operator approval before bash will
414    /// run, even in non-control chats. Extends the per-chat risk policy with
415    /// command-content inspection so destructive shell snippets cannot slip
416    /// through just because the caller happens to be in a permissive chat.
417    /// Patterns are matched case-insensitively against the full command
418    /// string. Set to an empty list to disable command-content gating.
419    #[serde(default = "default_bash_dangerous_patterns")]
420    pub bash_dangerous_patterns: Vec<String>,
421    /// RTK (Rust Token Killer) bash-output compression. Off by default.
422    #[serde(default)]
423    pub rtk: RtkConfig,
424    #[serde(default)]
425    pub sandbox: SandboxConfig,
426    #[serde(default, skip_serializing_if = "Option::is_none")]
427    pub override_timezone: Option<String>,
428    #[serde(default = "default_timezone", skip_serializing)]
429    pub timezone: String,
430    #[serde(default = "default_control_chat_ids")]
431    pub control_chat_ids: Vec<i64>,
432    #[serde(default)]
433    pub discord_bot_token: Option<String>,
434    #[serde(default)]
435    pub discord_allowed_channels: Vec<u64>,
436    #[serde(default)]
437    pub discord_no_mention: bool,
438    #[serde(default = "default_allow_group_slash_without_mention")]
439    pub allow_group_slash_without_mention: bool,
440
441    // --- Web UI ---
442    #[serde(default = "default_web_enabled")]
443    pub web_enabled: bool,
444    #[serde(default = "default_web_host")]
445    pub web_host: String,
446    #[serde(default = "default_web_port")]
447    pub web_port: u16,
448    #[serde(default = "default_web_max_inflight_per_session")]
449    pub web_max_inflight_per_session: usize,
450    #[serde(default = "default_web_max_requests_per_window")]
451    pub web_max_requests_per_window: usize,
452    #[serde(default = "default_web_rate_window_seconds")]
453    pub web_rate_window_seconds: u64,
454    #[serde(default = "default_web_run_history_limit")]
455    pub web_run_history_limit: usize,
456    #[serde(default = "default_web_session_idle_ttl_seconds")]
457    pub web_session_idle_ttl_seconds: u64,
458    #[serde(default)]
459    pub web_fetch_validation: WebContentValidationConfig,
460    #[serde(default)]
461    pub web_fetch_url_validation: WebFetchUrlValidationConfig,
462    /// Pluggable web-search backend (duckduckgo | searxng | brave | tavily | keenable).
463    /// Defaults to DuckDuckGo, preserving historical behavior.
464    #[serde(default)]
465    pub web_search: SearchProviderConfig,
466    /// Outbound message guardrail (off | redact | block). Off by default;
467    /// scans delivered bot messages for credential-like strings.
468    #[serde(default)]
469    pub output_guardrail: OutputGuardrailConfig,
470    /// Pre-tool-call policy (mode off | warn | block, deny_tools, max_risk,
471    /// allow_tools). Off by default; violations are sealed into the audit log.
472    #[serde(default)]
473    pub tool_policy: crate::tool_guardrails::ToolPolicyConfig,
474    /// Process policy for configured HTTP(S) endpoints and every URL exposed
475    /// through the shared tool registry. Off by default for compatibility.
476    #[serde(default)]
477    pub egress_policy: EgressPolicyConfig,
478
479    // --- Embedding ---
480    #[serde(default)]
481    pub embedding_provider: Option<String>,
482    #[serde(default)]
483    pub embedding_api_key: Option<String>,
484    #[serde(default)]
485    pub embedding_base_url: Option<String>,
486    #[serde(default)]
487    pub embedding_model: Option<String>,
488    #[serde(default)]
489    pub embedding_dim: Option<usize>,
490    #[serde(default)]
491    pub openai_api_key: Option<String>,
492
493    // --- Pricing ---
494    #[serde(default = "default_model_prices")]
495    pub model_prices: Vec<ModelPrice>,
496
497    // --- Reflector ---
498    #[serde(default = "default_reflector_enabled")]
499    pub reflector_enabled: bool,
500    #[serde(default = "default_reflector_interval_mins")]
501    pub reflector_interval_mins: u64,
502    // --- Scheduled-task DLQ auto-replay ---
503    /// Automatically retry scheduled tasks that landed in the dead-letter
504    /// queue (e.g. a one-shot task that hit a transient failure), up to
505    /// `dlq_max_replay_attempts` times. Default: true.
506    #[serde(default = "default_dlq_replay_enabled")]
507    pub dlq_replay_enabled: bool,
508    /// How often the DLQ auto-replay sweep runs, in seconds. Default: 300.
509    #[serde(default = "default_dlq_replay_interval_secs")]
510    pub dlq_replay_interval_secs: u64,
511    /// Maximum automatic replay attempts per task before it is left in the
512    /// DLQ for manual inspection. Default: 3.
513    #[serde(default = "default_dlq_max_replay_attempts")]
514    pub dlq_max_replay_attempts: u32,
515    /// Minimum tool_use blocks in a turn before the end-of-turn skill
516    /// review fires. Autonomous skill creation is on by default; set to
517    /// 0 to disable entirely. Default: 5.
518    #[serde(default = "default_skill_review_min_tool_calls")]
519    pub skill_review_min_tool_calls: usize,
520
521    // --- Soul ---
522    /// Path to a SOUL.md file that defines the bot's personality, voice, and values.
523    /// If not set, looks for SOUL.md in data_dir root, then current directory.
524    #[serde(default = "default_soul_path")]
525    pub soul_path: Option<String>,
526    /// Directory for per-bot SOUL files. Defaults to <data_dir>/souls when unset.
527    #[serde(default = "default_souls_dir")]
528    pub souls_dir: Option<String>,
529
530    // --- Project context files ---
531    /// Directory of project-level context Markdown files injected into the
532    /// system prompt for every chat. Use this for workspace-wide facts that
533    /// belong above per-chat memory but are not personality (which lives in
534    /// SOUL.md). Defaults to `<data_dir>/context/` when unset; missing
535    /// directories are silently skipped.
536    #[serde(default)]
537    pub context_dir: Option<String>,
538    /// Hard cap (in characters) on the combined size of all loaded context
539    /// files, to keep prefix-cache friendly system prompts from blowing up.
540    /// Set to 0 to disable the project-context layer entirely.
541    #[serde(default = "default_context_max_chars")]
542    pub context_max_chars: usize,
543
544    // --- Per-chat user model (USER.md) ---
545    /// When a turn was triggered by an inbound voice message and this is
546    /// true, the bot's text reply is also rendered to audio via the TTS
547    /// layer and sent back through the same channel. Off by default — opt
548    /// in explicitly because each round trip burns one extra TTS call.
549    /// Has no effect unless `media.tts.enabled` is also true.
550    #[serde(default)]
551    pub voice_round_trip: bool,
552
553    /// Hard cap on USER.md size. Hermes ships a 1375-char limit on its
554    /// equivalent file to force the curator to summarize rather than append.
555    /// Set to 0 to disable the user-model layer entirely; the chat falls
556    /// back to PROFILE memories alone. Curation is folded into the
557    /// reflector LLM call (see scheduler.rs), so there is no per-tick
558    /// amortization knob: the LLM itself returns null when no rewrite is
559    /// warranted.
560    #[serde(default = "default_user_model_max_chars")]
561    pub user_model_max_chars: usize,
562
563    // --- ClawHub ---
564    #[serde(flatten)]
565    pub clawhub: ClawHubConfig,
566
567    // --- Plugins ---
568    #[serde(default)]
569    pub plugins: PluginsConfig,
570
571    // --- Media tools (OpenAI-compatible) ---
572    /// Multimedia tool configuration (image generation / vision / TTS / STT).
573    /// When unset, each tool defaults to `enabled: false`. API key and base URL
574    /// fall back to `openai_api_key` / `openai_base_url`, so users who already
575    /// have their OpenAI credential wired up get zero-config.
576    #[serde(default)]
577    pub media: MediaConfig,
578
579    /// Override for the OpenAI-compatible base URL used by media tools. When
580    /// unset, media tools use `https://api.openai.com/v1`.
581    #[serde(default)]
582    pub openai_base_url: Option<String>,
583
584    // --- Voice / Speech-to-text ---
585    /// Voice transcription provider: "openai" uses OpenAI Whisper API, "local" uses voice_transcription_command
586    #[serde(default = "default_voice_provider", rename = "voice_provider")]
587    pub voice_provider: String,
588    /// Command template for local voice transcription. Use {file} as placeholder for audio file path.
589    /// Example: "whisper-mlx --file {file}" or "/usr/local/bin/whisper {file}"
590    #[serde(default, rename = "voice_transcription_command")]
591    pub voice_transcription_command: Option<String>,
592
593    // --- Observability ---
594    #[serde(default)]
595    pub observability: Option<serde_yaml::Value>,
596
597    // --- Channel registry (new dynamic config) ---
598    /// Per-channel configuration. Keys are channel names (e.g. "telegram", "discord", "slack", "irc", "web").
599    /// Each value is channel-specific config deserialized by the adapter.
600    /// If empty, synthesized from legacy flat fields below in post_deserialize().
601    #[serde(default)]
602    pub channels: HashMap<String, serde_yaml::Value>,
603
604    // --- Legacy channel fields (deprecated, use `channels:` instead) ---
605    #[serde(default = "default_telegram_bot_token")]
606    pub telegram_bot_token: String,
607    #[serde(default = "default_bot_username")]
608    pub bot_username: String,
609    #[serde(default)]
610    pub allowed_groups: Vec<i64>,
611}
612
613pub(crate) fn collect_enabled_channel_endpoints(value: &serde_yaml::Value, out: &mut Vec<String>) {
614    let Some(mapping) = value.as_mapping() else {
615        return;
616    };
617    if mapping
618        .get(serde_yaml::Value::String("enabled".into()))
619        .and_then(serde_yaml::Value::as_bool)
620        == Some(false)
621    {
622        return;
623    }
624
625    for (key, value) in mapping {
626        let Some(key) = key.as_str() else {
627            continue;
628        };
629        let key = key.to_ascii_lowercase();
630        let is_endpoint_key = key.contains("url") || key.contains("endpoint");
631        if is_endpoint_key {
632            if let Some(endpoint) = value
633                .as_str()
634                .map(str::trim)
635                .filter(|endpoint| !endpoint.is_empty())
636            {
637                out.push(endpoint.to_string());
638            }
639        }
640        match value {
641            serde_yaml::Value::Mapping(_) => collect_enabled_channel_endpoints(value, out),
642            serde_yaml::Value::Sequence(values) => {
643                for value in values {
644                    collect_enabled_channel_endpoints(value, out);
645                }
646            }
647            _ => {}
648        }
649    }
650}
651
652impl Config {
653    /// Whether `chat_id` is a control chat. An empty `control_chat_ids` list
654    /// means NO chat has control privileges (default deny) — every privileged
655    /// surface (skill management, /learn, /log, ...) must route through this
656    /// so that rule stays in one place.
657    pub fn is_control_chat(&self, chat_id: i64) -> bool {
658        self.control_chat_ids.contains(&chat_id)
659    }
660
661    fn ensure_mapping_mut(value: &mut serde_yaml::Value) -> &mut serde_yaml::Mapping {
662        if !matches!(value, serde_yaml::Value::Mapping(_)) {
663            *value = serde_yaml::Value::Mapping(serde_yaml::Mapping::new());
664        }
665        value
666            .as_mapping_mut()
667            .expect("value should be a mapping after initialization")
668    }
669
670    fn channel_default_account_id(&self, channel: &str) -> Option<String> {
671        let channel_cfg = self.channels.get(channel)?;
672        let mut account_ids: Vec<String> = channel_cfg
673            .get("accounts")
674            .and_then(|v| v.as_mapping())
675            .map(|m| {
676                m.keys()
677                    .filter_map(|k| k.as_str().map(ToOwned::to_owned))
678                    .collect()
679            })
680            .unwrap_or_default();
681        account_ids.sort();
682        channel_cfg
683            .get("default_account")
684            .and_then(|v| v.as_str())
685            .map(str::trim)
686            .filter(|v| !v.is_empty())
687            .map(ToOwned::to_owned)
688            .or_else(|| {
689                if channel_cfg
690                    .get("accounts")
691                    .and_then(|v| v.get("default"))
692                    .is_some()
693                {
694                    Some("default".to_string())
695                } else {
696                    account_ids.first().cloned()
697                }
698            })
699    }
700
701    fn llm_override_target(&self, channel: &str) -> Option<(String, Option<String>)> {
702        let channel = channel.trim();
703        if channel.is_empty() {
704            return None;
705        }
706        if let Some((base_channel, account_id)) = channel.split_once('.') {
707            let base_channel = base_channel.trim();
708            let account_id = account_id.trim();
709            if base_channel.is_empty() || account_id.is_empty() {
710                return None;
711            }
712            return Some((base_channel.to_string(), Some(account_id.to_string())));
713        }
714
715        Some((
716            channel.to_string(),
717            self.channel_default_account_id(channel),
718        ))
719    }
720
721    fn llm_override_mapping_mut(&mut self, channel: &str) -> Option<&mut serde_yaml::Mapping> {
722        let (base_channel, account_id) = self.llm_override_target(channel)?;
723        let channel_value = self
724            .channels
725            .entry(base_channel)
726            .or_insert_with(|| serde_yaml::Value::Mapping(serde_yaml::Mapping::new()));
727        let channel_map = Self::ensure_mapping_mut(channel_value);
728        if let Some(account_id) = account_id {
729            let accounts_key = serde_yaml::Value::String("accounts".to_string());
730            let accounts_value = channel_map
731                .entry(accounts_key)
732                .or_insert_with(|| serde_yaml::Value::Mapping(serde_yaml::Mapping::new()));
733            let accounts_map = Self::ensure_mapping_mut(accounts_value);
734            let account_value = accounts_map
735                .entry(serde_yaml::Value::String(account_id))
736                .or_insert_with(|| serde_yaml::Value::Mapping(serde_yaml::Mapping::new()));
737            return Some(Self::ensure_mapping_mut(account_value));
738        }
739        Some(channel_map)
740    }
741
742    pub fn set_provider_override_for_channel(&mut self, channel: &str, provider: Option<&str>) {
743        let Some(target) = self.llm_override_mapping_mut(channel) else {
744            return;
745        };
746        let provider_preset_key = serde_yaml::Value::String("provider_preset".to_string());
747        let llm_provider_key = serde_yaml::Value::String("llm_provider".to_string());
748        target.remove(&provider_preset_key);
749        target.remove(&llm_provider_key);
750        if let Some(provider) = provider
751            .map(str::trim)
752            .filter(|provider| !provider.is_empty())
753            .map(|provider| provider.to_ascii_lowercase())
754        {
755            target.insert(
756                provider_preset_key,
757                serde_yaml::Value::String(provider.to_string()),
758            );
759        }
760    }
761
762    pub fn set_model_override_for_channel(&mut self, channel: &str, model: Option<&str>) {
763        let Some(target) = self.llm_override_mapping_mut(channel) else {
764            return;
765        };
766        let model_key = serde_yaml::Value::String("model".to_string());
767        target.remove(&model_key);
768        if let Some(model) = model.and_then(normalize_model_name) {
769            target.insert(model_key, serde_yaml::Value::String(model.to_string()));
770        }
771    }
772
773    fn channel_account_bot_username(&self, channel: &str, account_id: &str) -> Option<String> {
774        self.channels
775            .get(channel)
776            .and_then(|v| v.get("accounts"))
777            .and_then(|v| v.get(account_id))
778            .and_then(|v| v.get("bot_username"))
779            .and_then(|v| v.as_str())
780            .map(str::trim)
781            .filter(|v| !v.is_empty())
782            .map(ToOwned::to_owned)
783    }
784
785    fn channel_account_soul_path(&self, channel: &str, account_id: &str) -> Option<String> {
786        self.channels
787            .get(channel)
788            .and_then(|v| v.get("accounts"))
789            .and_then(|v| v.get(account_id))
790            .and_then(|v| v.get("soul_path"))
791            .and_then(|v| v.as_str())
792            .map(str::trim)
793            .filter(|v| !v.is_empty())
794            .map(ToOwned::to_owned)
795    }
796
797    fn provider_override_from_value(value: &serde_yaml::Value) -> Option<String> {
798        value
799            .get("provider_preset")
800            .and_then(|v| v.as_str())
801            .or_else(|| value.get("llm_provider").and_then(|v| v.as_str()))
802            .map(str::trim)
803            .filter(|v| !v.is_empty())
804            .map(|v| v.to_ascii_lowercase())
805    }
806
807    fn channel_account_provider_override(&self, channel: &str, account_id: &str) -> Option<String> {
808        self.channels
809            .get(channel)
810            .and_then(|v| v.get("accounts"))
811            .and_then(|v| v.get(account_id))
812            .and_then(Self::provider_override_from_value)
813    }
814
815    fn model_override_from_value(value: &serde_yaml::Value) -> Option<String> {
816        value
817            .get("model")
818            .and_then(|v| v.as_str())
819            .and_then(normalize_model_name)
820    }
821
822    fn channel_account_model_override(&self, channel: &str, account_id: &str) -> Option<String> {
823        self.channels
824            .get(channel)
825            .and_then(|v| v.get("accounts"))
826            .and_then(|v| v.get(account_id))
827            .and_then(Self::model_override_from_value)
828    }
829
830    pub fn provider_override_for_channel(&self, channel: &str) -> Option<String> {
831        if let Some((base_channel, account_id)) = channel.split_once('.') {
832            if let Some(v) = self.channel_account_provider_override(base_channel, account_id) {
833                return Some(v);
834            }
835            return self
836                .channels
837                .get(base_channel)
838                .and_then(Self::provider_override_from_value);
839        }
840
841        if let Some(default_account) = self.channel_default_account_id(channel) {
842            if let Some(v) = self.channel_account_provider_override(channel, &default_account) {
843                return Some(v);
844            }
845        }
846
847        self.channels
848            .get(channel)
849            .and_then(Self::provider_override_from_value)
850    }
851
852    pub fn model_override_for_channel(&self, channel: &str) -> Option<String> {
853        if let Some((base_channel, account_id)) = channel.split_once('.') {
854            if let Some(v) = self.channel_account_model_override(base_channel, account_id) {
855                return Some(v);
856            }
857            return self
858                .channels
859                .get(base_channel)
860                .and_then(Self::model_override_from_value);
861        }
862
863        if let Some(default_account) = self.channel_default_account_id(channel) {
864            if let Some(v) = self.channel_account_model_override(channel, &default_account) {
865                return Some(v);
866            }
867        }
868
869        self.channels
870            .get(channel)
871            .and_then(Self::model_override_from_value)
872    }
873
874    pub fn soul_path_for_channel(&self, channel: &str) -> Option<String> {
875        let channel_override = self
876            .channels
877            .get(channel)
878            .and_then(|v| v.get("soul_path"))
879            .and_then(|v| v.as_str())
880            .map(str::trim)
881            .filter(|v| !v.is_empty())
882            .map(ToOwned::to_owned);
883        if channel_override.is_some() {
884            return channel_override;
885        }
886
887        if let Some((base_channel, account_id)) = channel.split_once('.') {
888            if let Some(v) = self.channel_account_soul_path(base_channel, account_id) {
889                return Some(v);
890            }
891            return self
892                .channels
893                .get(base_channel)
894                .and_then(|v| v.get("soul_path"))
895                .and_then(|v| v.as_str())
896                .map(str::trim)
897                .filter(|v| !v.is_empty())
898                .map(ToOwned::to_owned);
899        }
900
901        if let Some(default_account) = self.channel_default_account_id(channel) {
902            if let Some(v) = self.channel_account_soul_path(channel, &default_account) {
903                return Some(v);
904            }
905        }
906
907        self.channels
908            .get(channel)
909            .and_then(|v| v.get("soul_path"))
910            .and_then(|v| v.as_str())
911            .map(str::trim)
912            .filter(|v| !v.is_empty())
913            .map(ToOwned::to_owned)
914    }
915
916    pub fn bot_username_for_channel(&self, channel: &str) -> String {
917        let channel_override = self
918            .channels
919            .get(channel)
920            .and_then(|v| v.get("bot_username"))
921            .and_then(|v| v.as_str())
922            .map(str::trim)
923            .filter(|v| !v.is_empty());
924        if let Some(v) = channel_override {
925            return v.to_string();
926        }
927
928        if let Some((base_channel, account_id)) = channel.split_once('.') {
929            if let Some(v) = self.channel_account_bot_username(base_channel, account_id) {
930                return v;
931            }
932        } else if let Some(default_account) = self.channel_default_account_id(channel) {
933            if let Some(v) = self.channel_account_bot_username(channel, &default_account) {
934                return v;
935            }
936        }
937
938        let global = self.bot_username.trim();
939        if !global.is_empty() {
940            global.to_string()
941        } else {
942            default_bot_username()
943        }
944    }
945
946    pub fn bot_username_overrides(&self) -> HashMap<String, String> {
947        let mut overrides: HashMap<String, String> = self
948            .channels
949            .iter()
950            .filter_map(|(channel, cfg)| {
951                cfg.get("bot_username")
952                    .and_then(|v| v.as_str())
953                    .map(str::trim)
954                    .filter(|v| !v.is_empty())
955                    .map(|v| (channel.clone(), v.to_string()))
956            })
957            .collect();
958
959        for (channel, channel_cfg) in &self.channels {
960            let accounts = channel_cfg.get("accounts").and_then(|v| v.as_mapping());
961            let Some(accounts) = accounts else {
962                continue;
963            };
964            let default_account = self.channel_default_account_id(channel);
965            for (key, value) in accounts {
966                let Some(account_id) = key.as_str() else {
967                    continue;
968                };
969                let username = value
970                    .get("bot_username")
971                    .and_then(|v| v.as_str())
972                    .map(str::trim)
973                    .filter(|v| !v.is_empty());
974                let Some(username) = username else {
975                    continue;
976                };
977                if default_account
978                    .as_deref()
979                    .map(|v| v == account_id)
980                    .unwrap_or(false)
981                {
982                    overrides.insert(channel.clone(), username.to_string());
983                } else {
984                    overrides.insert(format!("{channel}.{account_id}"), username.to_string());
985                }
986            }
987        }
988
989        overrides
990    }
991
992    pub fn llm_provider_overrides(&self) -> HashMap<String, String> {
993        let mut overrides: HashMap<String, String> = self
994            .channels
995            .iter()
996            .filter_map(|(channel, cfg)| {
997                Self::provider_override_from_value(cfg).map(|provider| (channel.clone(), provider))
998            })
999            .collect();
1000
1001        for (channel, channel_cfg) in &self.channels {
1002            let accounts = channel_cfg.get("accounts").and_then(|v| v.as_mapping());
1003            let Some(accounts) = accounts else {
1004                continue;
1005            };
1006            let default_account = self.channel_default_account_id(channel);
1007            for (key, value) in accounts {
1008                let Some(account_id) = key.as_str() else {
1009                    continue;
1010                };
1011                let Some(provider) = Self::provider_override_from_value(value) else {
1012                    continue;
1013                };
1014                if default_account
1015                    .as_deref()
1016                    .map(|v| v == account_id)
1017                    .unwrap_or(false)
1018                {
1019                    overrides.insert(channel.clone(), provider);
1020                } else {
1021                    overrides.insert(format!("{channel}.{account_id}"), provider);
1022                }
1023            }
1024        }
1025
1026        overrides
1027    }
1028
1029    #[cfg(any(test, feature = "test-support"))]
1030    pub fn test_defaults() -> Self {
1031        Self {
1032            telegram_bot_token: "tok".into(),
1033            bot_username: "bot".into(),
1034            llm_provider: "anthropic".into(),
1035            api_key: "key".into(),
1036            api_keys: Vec::new(),
1037            model: "claude-sonnet-4-5-20250929".into(),
1038            provider_presets: HashMap::new(),
1039            llm_providers: HashMap::new(),
1040            llm_base_url: None,
1041            llm_user_agent: default_llm_user_agent(),
1042            max_tokens: 8192,
1043            max_tool_iterations: 100,
1044            compaction_timeout_secs: 180,
1045            aux_models: AuxModels::default(),
1046            fallback_model: None,
1047            max_history_messages: 50,
1048            max_document_size_mb: 100,
1049            memory_token_budget: 1500,
1050            memory_l0_identity_pct: 20,
1051            memory_l1_essential_pct: 30,
1052            memory_max_entries_per_chat: 200,
1053            memory_max_global_entries: 500,
1054            kg_max_triples_per_chat: 1000,
1055            tool_result_truncation_threshold_chars: 4000,
1056            tool_result_truncation_head_chars: 1500,
1057            tool_result_truncation_tail_chars: 500,
1058            tool_result_artifact_ttl_hours: 24,
1059            memory_recency_half_life_days: 30.0,
1060            memory_graph_recall_enabled: true,
1061            memory_graph_max_hops: 2,
1062            memory_graph_max_triples: 10,
1063            tool_repeat_window: 10,
1064            tool_repeat_limit: 3,
1065            anthropic_prompt_cache_enabled: true,
1066            anthropic_context_editing: false,
1067            anthropic_prompt_cache_ttl: "5m".into(),
1068            checkpoints_enabled: false,
1069            skill_archive_after_days: 30,
1070            skills_catalog_top_k: 3,
1071            system_prompt_time_detail: SystemPromptTimeDetail::default(),
1072            data_dir: default_data_dir(),
1073            skills_dir: None,
1074            working_dir: default_working_dir(),
1075            working_dir_isolation: WorkingDirIsolation::Chat,
1076            high_risk_tool_user_confirmation_required: true,
1077            approval_channels: default_approval_channels(),
1078            read_only_subagent_channels: default_read_only_subagent_channels(),
1079            bash_dangerous_patterns: default_bash_dangerous_patterns(),
1080            rtk: RtkConfig::default(),
1081            sandbox: SandboxConfig::default(),
1082            openai_api_key: None,
1083            override_timezone: None,
1084            timezone: "UTC".into(),
1085            allowed_groups: vec![],
1086            control_chat_ids: vec![],
1087            max_session_messages: 40,
1088            diff_max_lines: default_diff_max_lines(),
1089            file_diffs_in_chat: default_file_diffs_in_chat(),
1090            allow_governance_file_writes: false,
1091            model_context_window: default_model_context_window(),
1092            context_pressure_compact_pct: default_context_pressure_compact_pct(),
1093            model_context_windows: HashMap::new(),
1094            auto_compact: true,
1095            prune_protect_tokens: default_prune_protect_tokens(),
1096            prune_minimum_tokens: default_prune_minimum_tokens(),
1097            compact_keep_recent_tokens: 0,
1098            compact_instructions: None,
1099            project_agents_dir: None,
1100            extra_agents_dirs: Vec::new(),
1101            extra_skills_dirs: Vec::new(),
1102            extra_mcp_configs: Vec::new(),
1103            tool_gate: Default::default(),
1104            context_tools: false,
1105            detachable_foreground_commands: false,
1106            context_budget_hint: false,
1107            explore_tool: false,
1108            self_recheck: SelfRecheckConfig::default(),
1109            compact_keep_recent: 20,
1110            default_tool_timeout_secs: default_tool_timeout_secs(),
1111            tool_timeout_overrides: HashMap::new(),
1112            default_mcp_request_timeout_secs: default_mcp_request_timeout_secs(),
1113            discord_bot_token: None,
1114            discord_allowed_channels: vec![],
1115            discord_no_mention: false,
1116            allow_group_slash_without_mention: false,
1117            show_thinking: false,
1118            subagents: SubagentConfig::default(),
1119            idle_checkin: IdleCheckinConfig::default(),
1120            heartbeat: HeartbeatConfig::default(),
1121            token_budget: TokenBudgetConfig::default(),
1122            alerts: AlertsConfig::default(),
1123            trust_report: TrustReportConfig::default(),
1124            user_message_language: UserMessageLanguage::default(),
1125            sleep_time: SleepTimeConfig::default(),
1126            interjection: InterjectionConfig::default(),
1127            a2a: A2AConfig::default(),
1128            openai_compat_body_overrides: HashMap::new(),
1129            openai_compat_body_overrides_by_provider: HashMap::new(),
1130            openai_compat_body_overrides_by_model: HashMap::new(),
1131            web_enabled: true,
1132            web_host: "127.0.0.1".into(),
1133            web_port: 10961,
1134            web_max_inflight_per_session: 10,
1135            web_max_requests_per_window: 8,
1136            web_rate_window_seconds: 10,
1137            web_run_history_limit: 512,
1138            web_session_idle_ttl_seconds: 300,
1139            web_fetch_validation: WebContentValidationConfig::default(),
1140            web_fetch_url_validation: WebFetchUrlValidationConfig::default(),
1141            web_search: SearchProviderConfig::default(),
1142            output_guardrail: OutputGuardrailConfig::default(),
1143            tool_policy: crate::tool_guardrails::ToolPolicyConfig::default(),
1144            egress_policy: EgressPolicyConfig::default(),
1145            model_prices: vec![],
1146            embedding_provider: None,
1147            embedding_api_key: None,
1148            embedding_base_url: None,
1149            embedding_model: None,
1150            embedding_dim: None,
1151            reflector_enabled: true,
1152            reflector_interval_mins: 15,
1153            dlq_replay_enabled: true,
1154            dlq_replay_interval_secs: 300,
1155            dlq_max_replay_attempts: 3,
1156            skill_review_min_tool_calls: 5,
1157            soul_path: None,
1158            souls_dir: None,
1159            context_dir: None,
1160            context_max_chars: 8000,
1161            user_model_max_chars: 1500,
1162            voice_round_trip: false,
1163            clawhub: ClawHubConfig::default(),
1164            plugins: PluginsConfig::default(),
1165            media: MediaConfig::default(),
1166            openai_base_url: None,
1167            voice_provider: "openai".into(),
1168            voice_transcription_command: None,
1169            observability: None,
1170            channels: HashMap::new(),
1171            chat_turn_queue_max_pending: 20,
1172            enable_mid_turn_injection: true,
1173            mid_turn_injection_echo: true,
1174            parallel_tool_max_concurrency: 8,
1175            tool_concurrency_overrides: HashMap::new(),
1176        }
1177    }
1178
1179    /// Data root directory from config.
1180    pub fn data_root_dir(&self) -> PathBuf {
1181        expand_path(&self.data_dir)
1182    }
1183
1184    /// Runtime data directory (db, memory, exports, etc.).
1185    pub fn runtime_data_dir(&self) -> String {
1186        let root = self.data_root_dir();
1187        // Avoid nested runtime/runtime if data_dir is already runtime
1188        if root.file_name().and_then(|n| n.to_str()) == Some("runtime") {
1189            return root.to_string_lossy().to_string();
1190        }
1191        root.join("runtime").to_string_lossy().to_string()
1192    }
1193
1194    /// Skills directory. Priority: MICROCLAW_SKILLS_DIR env var > skills_dir config > <data_dir>/skills
1195    pub fn skills_data_dir(&self) -> String {
1196        // 1. Check env var first
1197        if let Ok(explicit_dir) = std::env::var("MICROCLAW_SKILLS_DIR") {
1198            let trimmed = explicit_dir.trim();
1199            if !trimmed.is_empty() {
1200                return expand_path(trimmed).to_string_lossy().to_string();
1201            }
1202        }
1203        // 2. Check config file
1204        if let Some(configured) = &self.skills_dir {
1205            let trimmed = configured.trim();
1206            if !trimmed.is_empty() {
1207                return expand_path(trimmed).to_string_lossy().to_string();
1208            }
1209        }
1210        // 3. Default to <data_dir>/skills
1211        self.data_root_dir()
1212            .join("skills")
1213            .to_string_lossy()
1214            .to_string()
1215    }
1216
1217    /// Souls directory. Priority: souls_dir config > <data_dir>/souls
1218    pub fn souls_data_dir(&self) -> String {
1219        if let Some(configured) = &self.souls_dir {
1220            let trimmed = configured.trim();
1221            if !trimmed.is_empty() {
1222                return expand_path(trimmed).to_string_lossy().to_string();
1223            }
1224        }
1225        self.data_root_dir()
1226            .join("souls")
1227            .to_string_lossy()
1228            .to_string()
1229    }
1230
1231    pub fn clawhub_lockfile_path(&self) -> PathBuf {
1232        self.data_root_dir().join("clawhub.lock.json")
1233    }
1234
1235    /// Lockfile path plus block flag for load-time skill verification,
1236    /// or `None` when `clawhub_verify_on_load: off`.
1237    pub fn clawhub_load_verification(&self) -> Option<(PathBuf, bool)> {
1238        match self.clawhub.verify_on_load {
1239            ClawHubVerifyMode::Off => None,
1240            ClawHubVerifyMode::Warn => Some((self.clawhub_lockfile_path(), false)),
1241            ClawHubVerifyMode::Block => Some((self.clawhub_lockfile_path(), true)),
1242        }
1243    }
1244
1245    pub fn config_path_for_setup() -> PathBuf {
1246        if let Ok(custom) = std::env::var("MICROCLAW_CONFIG") {
1247            return expand_path(&custom);
1248        }
1249        if std::path::Path::new("./microclaw.config.yaml").exists() {
1250            return PathBuf::from("./microclaw.config.yaml");
1251        }
1252        if std::path::Path::new("./microclaw.config.yml").exists() {
1253            return PathBuf::from("./microclaw.config.yml");
1254        }
1255        if std::env::var("SNAP").is_ok() {
1256            if let Ok(snap_user_common) = std::env::var("SNAP_USER_COMMON") {
1257                return PathBuf::from(snap_user_common).join("config.yaml");
1258            }
1259        }
1260        PathBuf::from("microclaw.config.yaml")
1261    }
1262
1263    pub fn resolve_config_path() -> Result<Option<PathBuf>, MicroClawError> {
1264        // 1. Check MICROCLAW_CONFIG env var for custom path
1265        if let Ok(custom) = std::env::var("MICROCLAW_CONFIG") {
1266            let expanded = expand_path(&custom);
1267            if expanded.exists() {
1268                return Ok(Some(expanded));
1269            }
1270            return Err(MicroClawError::Config(format!(
1271                "MICROCLAW_CONFIG points to non-existent file: {custom}"
1272            )));
1273        }
1274
1275        if std::path::Path::new("./microclaw.config.yaml").exists() {
1276            return Ok(Some(PathBuf::from("./microclaw.config.yaml")));
1277        }
1278        if std::path::Path::new("./microclaw.config.yml").exists() {
1279            return Ok(Some(PathBuf::from("./microclaw.config.yml")));
1280        }
1281        Ok(None)
1282    }
1283
1284    fn inferred_channel_enabled(&self, channel: &str) -> bool {
1285        match channel {
1286            "telegram" => {
1287                !self.telegram_bot_token.trim().is_empty() || self.channels.contains_key("telegram")
1288            }
1289            "discord" => {
1290                self.discord_bot_token
1291                    .as_deref()
1292                    .map(|v| !v.trim().is_empty())
1293                    .unwrap_or(false)
1294                    || self.channels.contains_key("discord")
1295            }
1296            "web" => self.web_enabled || self.channels.contains_key("web"),
1297            _ => self.channels.contains_key(channel),
1298        }
1299    }
1300
1301    fn explicit_channel_enabled(&self, channel: &str) -> Option<bool> {
1302        self.channels
1303            .get(channel)
1304            .and_then(|v| v.get("enabled"))
1305            .and_then(|v| v.as_bool())
1306    }
1307
1308    pub fn channel_enabled(&self, channel: &str) -> bool {
1309        let needle = channel.trim().to_lowercase();
1310        if let Some(explicit) = self.explicit_channel_enabled(&needle) {
1311            return explicit;
1312        }
1313        self.inferred_channel_enabled(&needle)
1314    }
1315
1316    /// Classify every known channel into `(enabled, configured_but_disabled)`.
1317    /// A channel is "configured" when it has credentials/config present (a
1318    /// `channels.<name>` block or a legacy top-level token); it is "enabled"
1319    /// per [`channel_enabled`]. Used both for the no-channel config error and
1320    /// for `microclaw doctor`, so the two stay consistent.
1321    pub fn channel_status(&self) -> (Vec<&'static str>, Vec<&'static str>) {
1322        let configured = [
1323            (
1324                "telegram",
1325                !self.telegram_bot_token.trim().is_empty()
1326                    || self.channels.contains_key("telegram"),
1327            ),
1328            (
1329                "discord",
1330                self.discord_bot_token
1331                    .as_deref()
1332                    .map(|v| !v.trim().is_empty())
1333                    .unwrap_or(false)
1334                    || self.channels.contains_key("discord"),
1335            ),
1336            ("slack", self.channels.contains_key("slack")),
1337            ("feishu", self.channels.contains_key("feishu")),
1338            ("irc", self.channels.contains_key("irc")),
1339            ("web", self.web_enabled || self.channels.contains_key("web")),
1340        ];
1341        let mut enabled = Vec::new();
1342        let mut configured_but_disabled = Vec::new();
1343        for (name, is_configured) in configured {
1344            if !is_configured {
1345                continue;
1346            }
1347            if self.channel_enabled(name) {
1348                enabled.push(name);
1349            } else {
1350                configured_but_disabled.push(name);
1351            }
1352        }
1353        (enabled, configured_but_disabled)
1354    }
1355
1356    /// Load config from YAML file.
1357    pub fn load() -> Result<Self, MicroClawError> {
1358        let yaml_path = Self::resolve_config_path()?;
1359
1360        if let Some(path) = yaml_path {
1361            return Self::load_from_path(&path);
1362        }
1363
1364        // No config file found at all
1365        Err(MicroClawError::Config(
1366            "No microclaw.config.yaml found. Run `microclaw setup` to create one.".into(),
1367        ))
1368    }
1369
1370    /// Load and validate a specific YAML configuration file.
1371    pub fn load_from_path(path: &Path) -> Result<Self, MicroClawError> {
1372        Self::load_from_path_inner(path, false)
1373    }
1374
1375    /// Load a specific configuration for a channel-free foreground runtime.
1376    ///
1377    /// All provider, tool, path, and security validation is retained. Only the
1378    /// Server requirement that at least one delivery channel be enabled is
1379    /// waived, because MicroClaw Code and other headless callers deliver results through
1380    /// their own application boundary.
1381    pub fn load_from_path_for_headless(path: &Path) -> Result<Self, MicroClawError> {
1382        Self::load_from_path_inner(path, true)
1383    }
1384
1385    /// Build and validate a channel-free configuration for an embedded caller.
1386    pub fn for_embedded(
1387        provider: impl Into<String>,
1388        model: impl Into<String>,
1389        api_key: impl Into<String>,
1390        base_url: Option<String>,
1391    ) -> Result<Self, MicroClawError> {
1392        let mut config: Config = serde_yaml::from_str("{}")
1393            .map_err(|error| MicroClawError::Config(error.to_string()))?;
1394        config.llm_provider = provider.into();
1395        config.model = model.into();
1396        config.api_key = api_key.into();
1397        config.llm_base_url = base_url;
1398        config.web_enabled = true;
1399        config.post_deserialize()?;
1400        config.web_enabled = false;
1401        config.channels.remove("web");
1402        Ok(config)
1403    }
1404
1405    fn load_from_path_inner(path: &Path, allow_no_channels: bool) -> Result<Self, MicroClawError> {
1406        let path_str = path.to_string_lossy().to_string();
1407        let content = std::fs::read_to_string(path)
1408            .map_err(|e| MicroClawError::Config(format!("Failed to read {path_str}: {e}")))?;
1409        if let Ok(raw) = serde_yaml::from_str::<serde_yaml::Value>(&content) {
1410            if let Some(map) = raw.as_mapping() {
1411                let old_top_level = map
1412                    .get(serde_yaml::Value::String("web_auth_token".to_string()))
1413                    .is_some();
1414                let old_channel_level = map
1415                    .get(serde_yaml::Value::String("channels".to_string()))
1416                    .and_then(|v| v.as_mapping())
1417                    .and_then(|channels| channels.get(serde_yaml::Value::String("web".to_string())))
1418                    .and_then(|v| v.as_mapping())
1419                    .map(|web| {
1420                        web.contains_key(serde_yaml::Value::String("auth_token".to_string()))
1421                    })
1422                    .unwrap_or(false);
1423                if old_top_level || old_channel_level {
1424                    warn!(
1425                        "Deprecated web auth token config detected in {}. \
1426`web_auth_token` / `channels.web.auth_token` are ignored; migrate to operator password + API keys.",
1427                        path_str
1428                    );
1429                }
1430                for warning in unknown_top_level_key_warnings(map) {
1431                    warn!("{warning} (in {path_str})");
1432                }
1433            }
1434        }
1435        let mut config: Config = serde_yaml::from_str(&content)
1436            .map_err(|error| MicroClawError::Config(friendly_yaml_error(&path_str, &error)))?;
1437        let synthesized_channel = allow_no_channels && config.channel_status().0.is_empty();
1438        if synthesized_channel {
1439            config.web_enabled = true;
1440        }
1441        config.post_deserialize()?;
1442        if crate::tool_guardrails::global_policy_has_no_rules(&config.tool_policy) {
1443            tracing::warn!(
1444                "tool_policy.mode is on but allow_tools, deny_tools and max_risk are all empty: \
1445                 every tool is still permitted. Add an allowlist, a deny list or a max_risk ceiling."
1446            );
1447        }
1448        if synthesized_channel {
1449            config.web_enabled = false;
1450            config.channels.remove("web");
1451        }
1452        Ok(config)
1453    }
1454
1455    /// Apply post-deserialization normalization and validation.
1456    pub fn post_deserialize(&mut self) -> Result<(), MicroClawError> {
1457        self.llm_provider = self.llm_provider.trim().to_lowercase();
1458
1459        self.model = resolve_model_name_with_fallback(&self.llm_provider, Some(&self.model), None);
1460        self.provider_presets =
1461            normalize_provider_profiles(std::mem::take(&mut self.provider_presets));
1462        self.llm_providers = normalize_provider_profiles(std::mem::take(&mut self.llm_providers));
1463        for (alias, preset) in self.provider_presets.clone() {
1464            self.llm_providers
1465                .entry(alias)
1466                .and_modify(|existing| {
1467                    *existing = merge_provider_profile(preset.clone(), existing.clone());
1468                })
1469                .or_insert(preset);
1470        }
1471        for channel_cfg in self.channels.values_mut() {
1472            migrate_model_override_alias_to_provider_preset(channel_cfg, &self.provider_presets);
1473        }
1474
1475        self.override_timezone = self
1476            .override_timezone
1477            .as_ref()
1478            .map(|v| v.trim().to_string())
1479            .filter(|v| !v.is_empty());
1480        if self
1481            .override_timezone
1482            .as_deref()
1483            .is_some_and(|v| v.eq_ignore_ascii_case("auto"))
1484        {
1485            self.override_timezone = None;
1486        }
1487
1488        // Normalize and validate timezone.
1489        // Priority: override_timezone > system auto-detect.
1490        let tz_raw = self
1491            .override_timezone
1492            .clone()
1493            .unwrap_or_else(|| "auto".to_string());
1494
1495        if tz_raw.eq_ignore_ascii_case("auto") {
1496            let detected = detect_system_timezone();
1497            if detected.parse::<chrono_tz::Tz>().is_ok() {
1498                self.timezone = detected;
1499            } else {
1500                warn!(
1501                    "Detected system timezone '{}' is not recognized by chrono-tz. Falling back to UTC.",
1502                    detected
1503                );
1504                self.timezone = "UTC".into();
1505            }
1506        } else {
1507            tz_raw
1508                .parse::<chrono_tz::Tz>()
1509                .map_err(|_| MicroClawError::Config(format!("Invalid timezone: {tz_raw}")))?;
1510            self.timezone = tz_raw;
1511        }
1512
1513        // Filter empty llm_base_url
1514        if let Some(ref url) = self.llm_base_url {
1515            if url.trim().is_empty() {
1516                self.llm_base_url = None;
1517            }
1518        }
1519        self.llm_user_agent = self.llm_user_agent.trim().to_string();
1520        if self.llm_user_agent.is_empty() {
1521            self.llm_user_agent = default_llm_user_agent();
1522        }
1523        if let Some(dir) = &self.skills_dir {
1524            let trimmed = dir.trim().to_string();
1525            self.skills_dir = if trimmed.is_empty() {
1526                None
1527            } else {
1528                Some(expand_path(&trimmed).to_string_lossy().to_string())
1529            };
1530        }
1531        if let Some(dir) = &self.souls_dir {
1532            let trimmed = dir.trim().to_string();
1533            self.souls_dir = if trimmed.is_empty() {
1534                None
1535            } else {
1536                Some(expand_path(&trimmed).to_string_lossy().to_string())
1537            };
1538        }
1539        if let Some(dir) = &self.plugins.dir {
1540            let trimmed = dir.trim().to_string();
1541            self.plugins.dir = if trimmed.is_empty() {
1542                None
1543            } else {
1544                Some(expand_path(&trimmed).to_string_lossy().to_string())
1545            };
1546        }
1547        if self.working_dir.trim().is_empty() {
1548            self.working_dir = default_working_dir();
1549        } else {
1550            self.working_dir = expand_path(&self.working_dir).to_string_lossy().to_string();
1551        }
1552        self.data_dir = expand_path(&self.data_dir).to_string_lossy().to_string();
1553        self.sandbox.image = self.sandbox.image.trim().to_string();
1554        if self.sandbox.image.is_empty() {
1555            self.sandbox.image = default_sandbox_image();
1556        }
1557        self.sandbox.container_prefix = self.sandbox.container_prefix.trim().to_string();
1558        if self.sandbox.container_prefix.is_empty() {
1559            self.sandbox.container_prefix = default_sandbox_container_prefix();
1560        }
1561        normalize_string_list(&mut self.sandbox.credential_env_allowlist, false);
1562        normalize_string_list(&mut self.egress_policy.allow_hosts, true);
1563        normalize_string_list(&mut self.egress_policy.deny_hosts, true);
1564        normalize_string_list(&mut self.tool_policy.allow_tools, false);
1565        normalize_string_list(&mut self.tool_policy.deny_tools, false);
1566        for grant in &mut self.tool_policy.grants {
1567            grant.channel = grant
1568                .channel
1569                .take()
1570                .map(|value| value.trim().to_ascii_lowercase())
1571                .filter(|value| !value.is_empty());
1572            grant.principal = grant
1573                .principal
1574                .take()
1575                .map(|value| value.trim().to_ascii_lowercase())
1576                .filter(|value| !value.is_empty());
1577            normalize_string_list(&mut grant.allow_tools, false);
1578            normalize_string_list(&mut grant.deny_tools, false);
1579        }
1580        if self.web_host.trim().is_empty() {
1581            self.web_host = default_web_host();
1582        }
1583        self.a2a.public_base_url = self
1584            .a2a
1585            .public_base_url
1586            .as_ref()
1587            .map(|v| v.trim().trim_end_matches('/').to_string())
1588            .filter(|v| !v.is_empty());
1589        self.a2a.agent_name = self
1590            .a2a
1591            .agent_name
1592            .as_ref()
1593            .map(|v| v.trim().to_string())
1594            .filter(|v| !v.is_empty());
1595        self.a2a.agent_description = self
1596            .a2a
1597            .agent_description
1598            .as_ref()
1599            .map(|v| v.trim().to_string())
1600            .filter(|v| !v.is_empty());
1601        self.a2a.shared_tokens = self
1602            .a2a
1603            .shared_tokens
1604            .drain(..)
1605            .map(|v| v.trim().to_string())
1606            .filter(|v| !v.is_empty())
1607            .collect();
1608        self.a2a.peers = self
1609            .a2a
1610            .peers
1611            .drain()
1612            .filter_map(|(name, mut peer)| {
1613                let normalized = name.trim().to_ascii_lowercase();
1614                if normalized.is_empty() {
1615                    return None;
1616                }
1617                peer.base_url = peer.base_url.trim().trim_end_matches('/').to_string();
1618                if peer.base_url.is_empty() {
1619                    return None;
1620                }
1621                peer.bearer_token = peer
1622                    .bearer_token
1623                    .as_ref()
1624                    .map(|v| v.trim().to_string())
1625                    .filter(|v| !v.is_empty());
1626                peer.description = peer
1627                    .description
1628                    .as_ref()
1629                    .map(|v| v.trim().to_string())
1630                    .filter(|v| !v.is_empty());
1631                peer.default_session_key = peer
1632                    .default_session_key
1633                    .as_ref()
1634                    .map(|v| v.trim().to_string())
1635                    .filter(|v| !v.is_empty());
1636                Some((normalized, peer))
1637            })
1638            .collect();
1639        if let Some(provider) = &self.embedding_provider {
1640            let p = provider.trim().to_lowercase();
1641            self.embedding_provider = if p.is_empty() { None } else { Some(p) };
1642        }
1643        if let Some(v) = &self.embedding_api_key {
1644            if v.trim().is_empty() {
1645                self.embedding_api_key = None;
1646            }
1647        }
1648        if let Some(v) = &self.embedding_base_url {
1649            if v.trim().is_empty() {
1650                self.embedding_base_url = None;
1651            }
1652        }
1653        if let Some(v) = &self.embedding_model {
1654            let m = v.trim().to_string();
1655            self.embedding_model = if m.is_empty() { None } else { Some(m) };
1656        }
1657        if let Some(v) = self.embedding_dim {
1658            if v == 0 {
1659                self.embedding_dim = None;
1660            }
1661        }
1662        if let Some(web_cfg) = self
1663            .channels
1664            .get_mut("web")
1665            .and_then(|v| v.as_mapping_mut())
1666        {
1667            if web_cfg
1668                .remove(serde_yaml::Value::String("auth_token".to_string()))
1669                .is_some()
1670            {
1671                warn!(
1672                    "Deprecated `channels.web.auth_token` detected and ignored. \
1673Use operator password + API keys for Web auth."
1674                );
1675            }
1676        }
1677        if self.web_max_inflight_per_session == 0 {
1678            self.web_max_inflight_per_session = default_web_max_inflight_per_session();
1679        }
1680        if self.web_max_requests_per_window == 0 {
1681            self.web_max_requests_per_window = default_web_max_requests_per_window();
1682        }
1683        if self.web_rate_window_seconds == 0 {
1684            self.web_rate_window_seconds = default_web_rate_window_seconds();
1685        }
1686        if self.web_run_history_limit == 0 {
1687            self.web_run_history_limit = default_web_run_history_limit();
1688        }
1689        if self.web_session_idle_ttl_seconds == 0 {
1690            self.web_session_idle_ttl_seconds = default_web_session_idle_ttl_seconds();
1691        }
1692        self.web_fetch_validation.normalize();
1693        self.web_fetch_url_validation.normalize();
1694        self.web_search.normalize();
1695        if self.max_document_size_mb == 0 {
1696            self.max_document_size_mb = default_max_document_size_mb();
1697        }
1698        if self.default_tool_timeout_secs == 0 {
1699            self.default_tool_timeout_secs = default_tool_timeout_secs();
1700        }
1701        if self.default_mcp_request_timeout_secs == 0 {
1702            self.default_mcp_request_timeout_secs = default_mcp_request_timeout_secs();
1703        }
1704        if self.subagents.max_concurrent == 0 {
1705            self.subagents.max_concurrent = default_subagent_max_concurrent();
1706        }
1707        if self.subagents.max_active_per_chat == 0 {
1708            self.subagents.max_active_per_chat = default_subagent_max_active_per_chat();
1709        }
1710        if self.subagents.run_timeout_secs == 0 {
1711            self.subagents.run_timeout_secs = default_subagent_run_timeout_secs();
1712        }
1713        if self.subagents.max_spawn_depth == 0 {
1714            self.subagents.max_spawn_depth = default_subagent_max_spawn_depth();
1715        }
1716        self.subagents.max_spawn_depth = self.subagents.max_spawn_depth.min(5);
1717        if self.subagents.max_children_per_run == 0 {
1718            self.subagents.max_children_per_run = default_subagent_max_children_per_run();
1719        }
1720        if self.subagents.announce_relay_interval_secs == 0 {
1721            self.subagents.announce_relay_interval_secs =
1722                default_subagent_announce_relay_interval_secs();
1723        }
1724        self.subagents.announce_relay_interval_secs =
1725            self.subagents.announce_relay_interval_secs.clamp(1, 300);
1726        if self.subagents.max_tokens_per_run <= 0 {
1727            self.subagents.max_tokens_per_run = default_subagent_max_tokens_per_run();
1728        }
1729        self.subagents.max_tokens_per_run =
1730            self.subagents.max_tokens_per_run.clamp(2_000, 2_000_000);
1731        if self.subagents.orchestrate_max_workers == 0 {
1732            self.subagents.orchestrate_max_workers = default_subagent_orchestrate_max_workers();
1733        }
1734        self.subagents.orchestrate_max_workers =
1735            self.subagents.orchestrate_max_workers.clamp(1, 12);
1736        self.subagents.acp.normalize();
1737        self.tool_timeout_overrides = self
1738            .tool_timeout_overrides
1739            .drain()
1740            .filter_map(|(name, timeout_secs)| {
1741                let normalized = name.trim().to_ascii_lowercase();
1742                if normalized.is_empty() || timeout_secs == 0 {
1743                    None
1744                } else {
1745                    Some((normalized, timeout_secs))
1746                }
1747            })
1748            .collect();
1749        self.openai_compat_body_overrides =
1750            normalize_body_override_params(std::mem::take(&mut self.openai_compat_body_overrides));
1751        self.openai_compat_body_overrides_by_provider = self
1752            .openai_compat_body_overrides_by_provider
1753            .drain()
1754            .filter_map(|(provider, params)| {
1755                let provider = provider.trim().to_ascii_lowercase();
1756                if provider.is_empty() {
1757                    return None;
1758                }
1759                let params = normalize_body_override_params(params);
1760                if params.is_empty() {
1761                    None
1762                } else {
1763                    Some((provider, params))
1764                }
1765            })
1766            .collect();
1767        self.openai_compat_body_overrides_by_model = self
1768            .openai_compat_body_overrides_by_model
1769            .drain()
1770            .filter_map(|(model, params)| {
1771                let model = model.trim().to_string();
1772                if model.is_empty() {
1773                    return None;
1774                }
1775                let params = normalize_body_override_params(params);
1776                if params.is_empty() {
1777                    None
1778                } else {
1779                    Some((model, params))
1780                }
1781            })
1782            .collect();
1783        if self.memory_token_budget == 0 {
1784            self.memory_token_budget = default_memory_token_budget();
1785        }
1786        for price in &mut self.model_prices {
1787            price.model = price.model.trim().to_string();
1788            if price.model.is_empty() {
1789                return Err(MicroClawError::Config(
1790                    "model_prices entries must include non-empty model".into(),
1791                ));
1792            }
1793            if !(price.input_per_million_usd.is_finite() && price.input_per_million_usd >= 0.0) {
1794                return Err(MicroClawError::Config(format!(
1795                    "model_prices[{}].input_per_million_usd must be >= 0",
1796                    price.model
1797                )));
1798            }
1799            if !(price.output_per_million_usd.is_finite() && price.output_per_million_usd >= 0.0) {
1800                return Err(MicroClawError::Config(format!(
1801                    "model_prices[{}].output_per_million_usd must be >= 0",
1802                    price.model
1803                )));
1804            }
1805        }
1806
1807        // Synthesize `channels` map from legacy flat fields if empty
1808        if self.channels.is_empty() {
1809            if !self.telegram_bot_token.trim().is_empty() {
1810                self.channels.insert(
1811                    "telegram".into(),
1812                    serde_yaml::to_value(serde_json::json!({
1813                        "enabled": true,
1814                        "bot_token": self.telegram_bot_token,
1815                        "bot_username": self.bot_username,
1816                        "allowed_groups": self.allowed_groups,
1817                    }))
1818                    .unwrap(),
1819                );
1820            }
1821            if let Some(ref token) = self.discord_bot_token {
1822                if !token.trim().is_empty() {
1823                    self.channels.insert(
1824                        "discord".into(),
1825                        serde_yaml::to_value(serde_json::json!({
1826                            "enabled": true,
1827                            "bot_token": token,
1828                            "allowed_channels": self.discord_allowed_channels,
1829                            "no_mention": self.discord_no_mention,
1830                        }))
1831                        .unwrap(),
1832                    );
1833                }
1834            }
1835            if self.web_enabled {
1836                self.channels.insert(
1837                    "web".into(),
1838                    serde_yaml::to_value(serde_json::json!({
1839                        "enabled": true,
1840                        "host": self.web_host,
1841                        "port": self.web_port,
1842                    }))
1843                    .unwrap(),
1844                );
1845            }
1846        }
1847
1848        // Validate required fields
1849        let (enabled_channels, configured_but_disabled) = self.channel_status();
1850        if enabled_channels.is_empty() {
1851            let hint = if configured_but_disabled.is_empty() {
1852                String::new()
1853            } else {
1854                format!(
1855                    " These channels are configured but not enabled: {}. \
1856                     Set `channels.<name>.enabled: true` (or run `microclaw setup`).",
1857                    configured_but_disabled.join(", ")
1858                )
1859            };
1860            return Err(MicroClawError::Config(format!(
1861                "At least one channel must be enabled and configured (via channels.<name>.enabled or legacy channel settings).{hint}"
1862            )));
1863        }
1864        if self.api_key.is_empty() && !provider_allows_empty_api_key(&self.llm_provider) {
1865            return Err(MicroClawError::Config("api_key is required".into()));
1866        }
1867        if is_openai_codex_provider(&self.llm_provider) {
1868            if !self.api_key.trim().is_empty() {
1869                return Err(MicroClawError::Config(
1870                    "openai-codex ignores microclaw.config.yaml api_key. Configure ~/.codex/auth.json or run `codex login` instead.".into(),
1871                ));
1872            }
1873            if self
1874                .llm_base_url
1875                .as_ref()
1876                .map(|v| !v.trim().is_empty())
1877                .unwrap_or(false)
1878            {
1879                return Err(MicroClawError::Config(
1880                    "openai-codex ignores microclaw.config.yaml llm_base_url. Configure ~/.codex/config.toml instead.".into(),
1881                ));
1882            }
1883            let has_codex_auth = codex_auth_file_has_access_token()?;
1884            if !has_codex_auth {
1885                return Err(MicroClawError::Config(
1886                    "openai-codex requires ~/.codex/auth.json (access token or OPENAI_API_KEY), or OPENAI_CODEX_ACCESS_TOKEN. Run `codex login` or update Codex config files.".into(),
1887                ));
1888            }
1889        }
1890        if is_qwen_portal_provider(&self.llm_provider) && self.api_key.trim().is_empty() {
1891            let has_qwen_auth = qwen_oauth_file_has_access_token()?;
1892            if !has_qwen_auth {
1893                return Err(MicroClawError::Config(
1894                    "qwen-portal requires api_key, or ~/.qwen/oauth_creds.json (access_token), or QWEN_PORTAL_ACCESS_TOKEN.".into(),
1895                ));
1896            }
1897        }
1898
1899        self.validate_configured_egress()?;
1900
1901        Ok(())
1902    }
1903
1904    fn validate_configured_egress(&self) -> Result<(), MicroClawError> {
1905        if self.egress_policy.mode == EgressPolicyMode::Off {
1906            return Ok(());
1907        }
1908        for url in self.configured_egress_endpoints() {
1909            let decision =
1910                crate::internal::tool_runtime::egress::evaluate_url(&self.egress_policy, &url);
1911            match decision {
1912                crate::internal::tool_runtime::egress::EgressDecision::Warn(reason) => {
1913                    warn!(url = %url, reason = %reason, "configured endpoint violates egress policy");
1914                }
1915                crate::internal::tool_runtime::egress::EgressDecision::Block(reason) => {
1916                    return Err(MicroClawError::Config(format!(
1917                        "configured endpoint `{url}` blocked by egress policy: {reason}"
1918                    )));
1919                }
1920                crate::internal::tool_runtime::egress::EgressDecision::Allow => {}
1921            }
1922        }
1923        Ok(())
1924    }
1925
1926    fn configured_egress_endpoints(&self) -> Vec<String> {
1927        let mut urls = Vec::new();
1928        {
1929            let mut add = |value: Option<&str>| {
1930                if let Some(value) = value.map(str::trim).filter(|value| !value.is_empty()) {
1931                    urls.push(value.to_string());
1932                }
1933            };
1934
1935            add(self.llm_base_url.as_deref());
1936            for profile in self
1937                .provider_presets
1938                .values()
1939                .chain(self.llm_providers.values())
1940            {
1941                add(profile.llm_base_url.as_deref());
1942            }
1943            add(self.embedding_base_url.as_deref());
1944            add(self.openai_base_url.as_deref());
1945
1946            let media_enabled = self.media.image_gen.enabled
1947                || self.media.vision.enabled
1948                || self.media.tts.enabled
1949                || self.media.stt.enabled
1950                || self.media.podcast.enabled;
1951            if media_enabled {
1952                add(self.media.base_url.as_deref());
1953            }
1954            if self.media.tts.enabled || self.media.podcast.enabled {
1955                add(self.media.tts.base_url.as_deref());
1956            }
1957            if self.media.podcast.enabled {
1958                add(self.media.podcast.base_url.as_deref());
1959            }
1960
1961            if self.web_search.effective_backend()
1962                == crate::internal::tool_runtime::web_search::SearchBackend::Searxng
1963            {
1964                add(Some(&self.web_search.searxng_base_url));
1965            }
1966            for peer in self.a2a.peers.values().filter(|peer| peer.enabled) {
1967                add(Some(&peer.base_url));
1968            }
1969            if self.clawhub.agent_tools_enabled {
1970                add(Some(&self.clawhub.registry));
1971            }
1972            if self.alerts.enabled {
1973                add(Some(&self.alerts.webhook_url));
1974            }
1975        }
1976
1977        for channel in self.channels.values() {
1978            collect_enabled_channel_endpoints(channel, &mut urls);
1979        }
1980
1981        urls.sort();
1982        urls.dedup();
1983        urls
1984    }
1985
1986    fn merged_profile_from_alias(&self, alias: &str) -> Option<ResolvedLlmProviderProfile> {
1987        let alias = alias.trim().to_ascii_lowercase();
1988        if alias.is_empty() {
1989            return None;
1990        }
1991        if alias == self.llm_provider {
1992            let mut provider = self.llm_provider.clone();
1993            let mut api_key = self.api_key.clone();
1994            let mut api_keys = self.api_keys.clone();
1995            let mut llm_base_url = self.llm_base_url.clone();
1996            let mut llm_user_agent = self.llm_user_agent.clone();
1997            let mut default_model = self.model.clone();
1998            let mut models = vec![default_model.clone()];
1999            let mut show_thinking = self.show_thinking;
2000            if let Some(profile) = self.llm_providers.get(&alias) {
2001                if let Some(v) = &profile.provider {
2002                    provider = v.clone();
2003                }
2004                if let Some(v) = &profile.api_key {
2005                    api_key = v.clone();
2006                }
2007                if !profile.api_keys.is_empty() {
2008                    api_keys = profile.api_keys.clone();
2009                }
2010                if let Some(v) = &profile.llm_base_url {
2011                    llm_base_url = Some(v.clone());
2012                }
2013                if let Some(v) = &profile.llm_user_agent {
2014                    llm_user_agent = v.clone();
2015                }
2016                if let Some(v) = &profile.default_model {
2017                    default_model = v.clone();
2018                }
2019                if !profile.models.is_empty() {
2020                    models = profile.models.clone();
2021                }
2022                if let Some(v) = profile.show_thinking {
2023                    show_thinking = v;
2024                }
2025            }
2026            default_model = resolve_model_name_with_fallback(
2027                &provider,
2028                Some(&default_model),
2029                Some(&self.model),
2030            );
2031            models = models
2032                .into_iter()
2033                .filter_map(|model| normalize_model_name(&model))
2034                .collect();
2035            if !models.iter().any(|m| m == &default_model) {
2036                models.push(default_model.clone());
2037            }
2038            models.sort();
2039            models.dedup();
2040            return Some(ResolvedLlmProviderProfile {
2041                alias,
2042                provider,
2043                api_key,
2044                api_keys,
2045                llm_base_url,
2046                llm_user_agent,
2047                default_model,
2048                models,
2049                show_thinking,
2050            });
2051        }
2052
2053        let profile = self.llm_providers.get(&alias)?;
2054        let provider = profile.provider.clone().unwrap_or_else(|| alias.clone());
2055        let api_key = profile
2056            .api_key
2057            .clone()
2058            .unwrap_or_else(|| self.api_key.clone());
2059        // A profile with its own key(s) never inherits the top-level pool.
2060        let api_keys = if !profile.api_keys.is_empty() {
2061            profile.api_keys.clone()
2062        } else if profile.api_key.is_none() {
2063            self.api_keys.clone()
2064        } else {
2065            Vec::new()
2066        };
2067        let llm_base_url = profile
2068            .llm_base_url
2069            .clone()
2070            .or_else(|| self.llm_base_url.clone());
2071        let llm_user_agent = profile
2072            .llm_user_agent
2073            .clone()
2074            .unwrap_or_else(|| self.llm_user_agent.clone());
2075        let default_model = resolve_model_name_with_fallback(
2076            &provider,
2077            profile.default_model.as_deref(),
2078            Some(&self.model),
2079        );
2080        let mut models = if profile.models.is_empty() {
2081            vec![default_model.clone()]
2082        } else {
2083            profile
2084                .models
2085                .clone()
2086                .into_iter()
2087                .filter_map(|model| normalize_model_name(&model))
2088                .collect()
2089        };
2090        let show_thinking = profile.show_thinking.unwrap_or(self.show_thinking);
2091        if !models.iter().any(|m| m == &default_model) {
2092            models.push(default_model.clone());
2093        }
2094        models.sort();
2095        models.dedup();
2096        Some(ResolvedLlmProviderProfile {
2097            alias,
2098            provider,
2099            api_key,
2100            api_keys,
2101            llm_base_url,
2102            llm_user_agent,
2103            default_model,
2104            models,
2105            show_thinking,
2106        })
2107    }
2108
2109    pub fn resolve_llm_provider_profile(&self, alias: &str) -> Option<ResolvedLlmProviderProfile> {
2110        self.merged_profile_from_alias(alias)
2111    }
2112
2113    pub fn list_llm_provider_profiles(&self) -> Vec<ResolvedLlmProviderProfile> {
2114        let mut out = Vec::new();
2115        if let Some(default_profile) = self.resolve_llm_provider_profile(&self.llm_provider) {
2116            out.push(default_profile);
2117        }
2118        let mut aliases: Vec<String> = self.llm_providers.keys().cloned().collect();
2119        aliases.sort();
2120        aliases.dedup();
2121        for alias in aliases {
2122            if alias == self.llm_provider {
2123                continue;
2124            }
2125            if let Some(profile) = self.resolve_llm_provider_profile(&alias) {
2126                out.push(profile);
2127            }
2128        }
2129        out
2130    }
2131
2132    /// Deserialize a typed channel config from the `channels` map.
2133    pub fn channel_config<T: DeserializeOwned>(&self, name: &str) -> Option<T> {
2134        self.channels
2135            .get(name)
2136            .and_then(|v| serde_yaml::from_value(v.clone()).ok())
2137    }
2138
2139    pub fn model_price(&self, model: &str) -> Option<&ModelPrice> {
2140        let needle = model.trim();
2141        self.model_prices
2142            .iter()
2143            .find(|p| p.model.eq_ignore_ascii_case(needle))
2144            .or_else(|| self.model_prices.iter().find(|p| p.model == "*"))
2145    }
2146
2147    pub fn estimate_cost_usd(
2148        &self,
2149        model: &str,
2150        input_tokens: i64,
2151        output_tokens: i64,
2152    ) -> Option<f64> {
2153        let price = self.model_price(model)?;
2154        let in_tok = input_tokens.max(0) as f64;
2155        let out_tok = output_tokens.max(0) as f64;
2156        Some(
2157            (in_tok / 1_000_000.0) * price.input_per_million_usd
2158                + (out_tok / 1_000_000.0) * price.output_per_million_usd,
2159        )
2160    }
2161
2162    pub fn tool_timeout_secs(&self, tool_name: &str, fallback: u64) -> u64 {
2163        let normalized = tool_name.trim().to_ascii_lowercase();
2164        if let Some(timeout_secs) = self.tool_timeout_overrides.get(&normalized) {
2165            return *timeout_secs;
2166        }
2167        if self.default_tool_timeout_secs == 0 {
2168            fallback
2169        } else {
2170            self.default_tool_timeout_secs
2171        }
2172    }
2173
2174    pub fn mcp_request_timeout_secs(&self) -> u64 {
2175        if self.default_mcp_request_timeout_secs == 0 {
2176            default_mcp_request_timeout_secs()
2177        } else {
2178            self.default_mcp_request_timeout_secs
2179        }
2180    }
2181
2182    /// Save config as YAML to the given path.
2183    #[allow(dead_code)]
2184    pub fn save_yaml(&self, path: &str) -> Result<(), MicroClawError> {
2185        let content = serde_yaml::to_string(self)
2186            .map_err(|e| MicroClawError::Config(format!("Failed to serialize config: {e}")))?;
2187        std::fs::write(path, content)?;
2188        Ok(())
2189    }
2190}
2191
2192pub(crate) fn normalize_body_override_params(
2193    params: HashMap<String, serde_json::Value>,
2194) -> HashMap<String, serde_json::Value> {
2195    params
2196        .into_iter()
2197        .filter_map(|(key, value)| {
2198            let key = key.trim().to_string();
2199            if key.is_empty() {
2200                None
2201            } else {
2202                Some((key, value))
2203            }
2204        })
2205        .collect()
2206}
2207
2208pub(crate) fn normalize_provider_profiles(
2209    profiles: HashMap<String, LlmProviderProfile>,
2210) -> HashMap<String, LlmProviderProfile> {
2211    profiles
2212        .into_iter()
2213        .filter_map(|(alias, mut profile)| {
2214            let alias = alias.trim().to_ascii_lowercase();
2215            if alias.is_empty() {
2216                return None;
2217            }
2218            profile.provider = profile
2219                .provider
2220                .as_ref()
2221                .map(|v| v.trim().to_ascii_lowercase())
2222                .filter(|v| !v.is_empty());
2223            profile.api_key = profile
2224                .api_key
2225                .as_ref()
2226                .map(|v| v.trim().to_string())
2227                .filter(|v| !v.is_empty());
2228            profile.llm_base_url = profile
2229                .llm_base_url
2230                .as_ref()
2231                .map(|v| v.trim().to_string())
2232                .filter(|v| !v.is_empty());
2233            profile.llm_user_agent = profile
2234                .llm_user_agent
2235                .as_ref()
2236                .map(|v| v.trim().to_string())
2237                .filter(|v| !v.is_empty());
2238            profile.default_model = profile
2239                .default_model
2240                .as_ref()
2241                .and_then(|v| normalize_model_name(v));
2242            profile.models = profile
2243                .models
2244                .into_iter()
2245                .filter_map(|m| normalize_model_name(&m))
2246                .collect::<Vec<_>>();
2247            profile.models.sort();
2248            profile.models.dedup();
2249            Some((alias, profile))
2250        })
2251        .collect()
2252}
2253
2254pub(crate) fn migrate_model_override_alias_to_provider_preset(
2255    value: &mut serde_yaml::Value,
2256    known_profiles: &HashMap<String, LlmProviderProfile>,
2257) {
2258    let Some(map) = value.as_mapping_mut() else {
2259        return;
2260    };
2261
2262    let provider_preset_key = serde_yaml::Value::String("provider_preset".to_string());
2263    let llm_provider_key = serde_yaml::Value::String("llm_provider".to_string());
2264    let model_key = serde_yaml::Value::String("model".to_string());
2265
2266    let has_provider_override =
2267        map.contains_key(&provider_preset_key) || map.contains_key(&llm_provider_key);
2268    if !has_provider_override {
2269        let maybe_profile_alias = map
2270            .get(&model_key)
2271            .and_then(|v| v.as_str())
2272            .map(str::trim)
2273            .filter(|v| !v.is_empty())
2274            .map(|v| v.to_ascii_lowercase());
2275        if let Some(alias) = maybe_profile_alias {
2276            if known_profiles.contains_key(&alias) {
2277                map.insert(
2278                    provider_preset_key.clone(),
2279                    serde_yaml::Value::String(alias),
2280                );
2281                map.remove(&model_key);
2282            }
2283        }
2284    }
2285
2286    let accounts_key = serde_yaml::Value::String("accounts".to_string());
2287    if let Some(accounts) = map.get_mut(&accounts_key).and_then(|v| v.as_mapping_mut()) {
2288        for (_, account) in accounts.iter_mut() {
2289            migrate_model_override_alias_to_provider_preset(account, known_profiles);
2290        }
2291    }
2292}
2293
2294pub(crate) fn merge_provider_profile(
2295    base: LlmProviderProfile,
2296    override_profile: LlmProviderProfile,
2297) -> LlmProviderProfile {
2298    let mut models = if override_profile.models.is_empty() {
2299        base.models
2300    } else {
2301        override_profile.models
2302    };
2303    models.sort();
2304    models.dedup();
2305
2306    LlmProviderProfile {
2307        provider: override_profile.provider.or(base.provider),
2308        api_key: override_profile.api_key.or(base.api_key),
2309        api_keys: if override_profile.api_keys.is_empty() {
2310            base.api_keys
2311        } else {
2312            override_profile.api_keys
2313        },
2314        llm_base_url: override_profile.llm_base_url.or(base.llm_base_url),
2315        llm_user_agent: override_profile.llm_user_agent.or(base.llm_user_agent),
2316        default_model: override_profile.default_model.or(base.default_model),
2317        models,
2318        show_thinking: override_profile.show_thinking.or(base.show_thinking),
2319    }
2320}
2321
2322/// Result of `microclaw config check` on one file. Errors mean the config
2323/// won't load; warnings mean it loads but something is probably a typo.
2324#[derive(Debug, Default)]
2325pub struct ConfigCheckReport {
2326    pub errors: Vec<String>,
2327    pub warnings: Vec<String>,
2328    /// Present when the config parsed: (enabled channels, configured-but-
2329    /// disabled channels, provider, model).
2330    pub summary: Option<(Vec<&'static str>, Vec<&'static str>, String, String)>,
2331}
2332
2333impl ConfigCheckReport {
2334    pub fn ok(&self) -> bool {
2335        self.errors.is_empty()
2336    }
2337}
2338
2339/// Validate config file content without starting anything: YAML syntax with
2340/// line/column, unknown-key warnings with did-you-mean, full schema
2341/// deserialization (typed enums reject typos), and post-deserialize
2342/// normalization/validation. Pure function over the text for testability.
2343pub fn check_config_content(path_str: &str, content: &str) -> ConfigCheckReport {
2344    let mut report = ConfigCheckReport::default();
2345
2346    // 1) YAML syntax. serde_yaml errors carry line/column.
2347    let raw: serde_yaml::Value = match serde_yaml::from_str(content) {
2348        Ok(v) => v,
2349        Err(e) => {
2350            report.errors.push(format!("YAML syntax error: {e}"));
2351            return report;
2352        }
2353    };
2354
2355    // 2) Unknown top-level keys (serde ignores them silently on load).
2356    if let Some(map) = raw.as_mapping() {
2357        report.warnings.extend(unknown_top_level_key_warnings(map));
2358    } else {
2359        report
2360            .errors
2361            .push("Config root must be a YAML mapping (key: value pairs).".to_string());
2362        return report;
2363    }
2364
2365    // 3) Full schema deserialization (typed enums catch value typos with a
2366    //    did-you-mean suggestion) + post-deserialize validation.
2367    match serde_yaml::from_str::<Config>(content) {
2368        Err(e) => {
2369            report.errors.push(friendly_yaml_error(path_str, &e));
2370        }
2371        Ok(mut config) => match config.post_deserialize() {
2372            // Covers value validation including the "no channel enabled" case.
2373            Err(e) => report.errors.push(e.to_string()),
2374            Ok(()) => {
2375                if crate::tool_guardrails::global_policy_has_no_rules(&config.tool_policy) {
2376                    report.warnings.push(format!(
2377                        "tool_policy.mode is `{}` but allow_tools, deny_tools and max_risk are all \
2378                         empty, so every tool is still permitted. Add an allowlist, a deny list \
2379                         or a max_risk ceiling.",
2380                        serde_yaml::to_string(&config.tool_policy.mode)
2381                            .unwrap_or_default()
2382                            .trim()
2383                    ));
2384                }
2385                let (enabled, disabled) = config.channel_status();
2386                report.summary = Some((
2387                    enabled,
2388                    disabled,
2389                    config.llm_provider.clone(),
2390                    config.model.clone(),
2391                ));
2392            }
2393        },
2394    }
2395    report
2396}
2397
2398/// CLI entry point for `microclaw config check`. Prints a human-readable
2399/// report and returns the process exit code (0 = loadable, 1 = errors,
2400/// 2 = file missing/unreadable).
2401pub fn run_config_check() -> i32 {
2402    let path = match Config::resolve_config_path() {
2403        Ok(Some(p)) => p,
2404        Ok(None) => {
2405            eprintln!("✗ No microclaw.config.yaml found. Run `microclaw setup` to create one.");
2406            return 2;
2407        }
2408        Err(e) => {
2409            eprintln!("✗ {e}");
2410            return 2;
2411        }
2412    };
2413    let path_str = path.to_string_lossy().to_string();
2414    let content = match std::fs::read_to_string(&path) {
2415        Ok(c) => c,
2416        Err(e) => {
2417            eprintln!("✗ Failed to read {path_str}: {e}");
2418            return 2;
2419        }
2420    };
2421
2422    println!("Checking {path_str}");
2423    let report = check_config_content(&path_str, &content);
2424    for w in &report.warnings {
2425        println!("  ⚠ {w}");
2426    }
2427    for e in &report.errors {
2428        println!("  ✗ {e}");
2429    }
2430    if let Some((enabled, disabled, provider, model)) = &report.summary {
2431        let enabled_str = if enabled.is_empty() {
2432            "none".to_string()
2433        } else {
2434            enabled.join(", ")
2435        };
2436        println!("  provider: {provider} · model: {model}");
2437        println!("  channels enabled: {enabled_str}");
2438        if !disabled.is_empty() {
2439            println!("  configured but disabled: {}", disabled.join(", "));
2440        }
2441    }
2442    if report.ok() {
2443        println!(
2444            "✓ Config OK{}",
2445            if report.warnings.is_empty() {
2446                ""
2447            } else {
2448                " (with warnings)"
2449            }
2450        );
2451        0
2452    } else {
2453        println!("✗ Config has errors — fix them and re-run, or run `microclaw setup`.");
2454        1
2455    }
2456}
2457
2458/// Turn a raw `serde_yaml` parse error into an actionable message. When the
2459/// error is an unknown field or variant (the common YAML typo), suggest the
2460/// closest valid name, and always point the user at `setup` / the example
2461/// config. The original error (with its line/column) is preserved.
2462pub(crate) fn friendly_yaml_error(path_str: &str, err: &serde_yaml::Error) -> String {
2463    let raw = err.to_string();
2464    let mut hint = String::new();
2465    if let Some((kind, token)) = extract_unknown_token(&raw) {
2466        match suggest_closest(token, &extract_backtick_options(&raw)) {
2467            Some(best) => {
2468                hint = format!("\n\n  Unknown {kind} `{token}` — did you mean `{best}`?");
2469            }
2470            None => hint = format!("\n\n  Unknown {kind} `{token}`."),
2471        }
2472    }
2473    format!(
2474        "Failed to parse {path_str}: {raw}{hint}\n\n  \
2475         Edit the config and re-run, or run `microclaw setup`.\n  \
2476         Reference: https://github.com/microclaw/microclaw/blob/main/microclaw.config.example.yaml"
2477    )
2478}
2479
2480/// Build the set of accepted top-level config keys by serializing a baseline
2481/// `Config` (so it stays in sync with the struct, including the flattened
2482/// `clawhub_*` keys), plus the few fields excluded from serialization and the
2483/// deprecated aliases handled elsewhere. Returns `None` if the baseline can't
2484/// be derived, so callers skip the check rather than emit spurious warnings.
2485pub(crate) fn known_top_level_config_keys() -> Option<std::collections::BTreeSet<String>> {
2486    let base: Config = serde_yaml::from_str("{}").ok()?;
2487    let serde_yaml::Value::Mapping(serialized) = serde_yaml::to_value(&base).ok()? else {
2488        return None;
2489    };
2490    let mut known: std::collections::BTreeSet<String> = serialized
2491        .keys()
2492        .filter_map(|k| k.as_str().map(str::to_string))
2493        .collect();
2494    // Accepted on input but excluded from serialization (skip_serializing[_if])
2495    // or kept only for backward-compatible deprecation warnings.
2496    for k in ["timezone", "override_timezone", "web_auth_token"] {
2497        known.insert(k.to_string());
2498    }
2499    // Sanity guard: a healthy Config has many keys; if we somehow derived only
2500    // a handful, treat the set as unreliable and skip the check.
2501    if known.len() < 5 {
2502        return None;
2503    }
2504    Some(known)
2505}
2506
2507/// Soft-validate top-level config keys: serde silently ignores unknown fields,
2508/// so a typo like `discrod:` is otherwise invisible. Returns one human-readable
2509/// warning per unrecognized key (with a did-you-mean suggestion when close).
2510/// Does not fail the load.
2511pub(crate) fn unknown_top_level_key_warnings(map: &serde_yaml::Mapping) -> Vec<String> {
2512    let Some(known) = known_top_level_config_keys() else {
2513        return Vec::new();
2514    };
2515    let candidates: Vec<String> = known.iter().cloned().collect();
2516    let mut warnings = Vec::new();
2517    for key in map.keys() {
2518        let Some(name) = key.as_str() else { continue };
2519        if known.contains(name) {
2520            continue;
2521        }
2522        match suggest_closest(name, &candidates) {
2523            Some(best) => warnings.push(format!(
2524                "Unknown config key `{name}` (ignored) — did you mean `{best}`?"
2525            )),
2526            None => warnings.push(format!("Unknown config key `{name}` (ignored).")),
2527        }
2528    }
2529    warnings
2530}
2531
2532/// Extract `(kind, token)` from a serde "unknown variant/field `X`" message.
2533pub(crate) fn extract_unknown_token(raw: &str) -> Option<(&'static str, &str)> {
2534    for (needle, kind) in [
2535        ("unknown variant `", "variant"),
2536        ("unknown field `", "field"),
2537    ] {
2538        if let Some(start) = raw.find(needle) {
2539            let rest = &raw[start + needle.len()..];
2540            if let Some(end) = rest.find('`') {
2541                return Some((kind, &rest[..end]));
2542            }
2543        }
2544    }
2545    None
2546}
2547
2548/// Collect the backtick-quoted options listed after "expected" in a serde error.
2549pub(crate) fn extract_backtick_options(raw: &str) -> Vec<String> {
2550    let Some(exp) = raw.find("expected") else {
2551        return Vec::new();
2552    };
2553    let mut out = Vec::new();
2554    let mut rest = &raw[exp..];
2555    while let Some(open) = rest.find('`') {
2556        rest = &rest[open + 1..];
2557        if let Some(close) = rest.find('`') {
2558            out.push(rest[..close].to_string());
2559            rest = &rest[close + 1..];
2560        } else {
2561            break;
2562        }
2563    }
2564    out
2565}
2566
2567/// Pick the closest option to `token` by edit distance, if one is "close
2568/// enough" (distance at most a third of the token length, min 2).
2569pub(crate) fn suggest_closest(token: &str, options: &[String]) -> Option<String> {
2570    let threshold = (token.chars().count() / 3).max(2);
2571    options
2572        .iter()
2573        .map(|o| (levenshtein(token, o), o))
2574        .filter(|(d, _)| *d <= threshold)
2575        .min_by_key(|(d, _)| *d)
2576        .map(|(_, o)| o.clone())
2577}
2578
2579/// Standard Levenshtein edit distance.
2580pub(crate) fn levenshtein(a: &str, b: &str) -> usize {
2581    let a: Vec<char> = a.chars().collect();
2582    let b: Vec<char> = b.chars().collect();
2583    let mut prev: Vec<usize> = (0..=b.len()).collect();
2584    let mut cur = vec![0usize; b.len() + 1];
2585    for (i, ca) in a.iter().enumerate() {
2586        cur[0] = i + 1;
2587        for (j, cb) in b.iter().enumerate() {
2588            let cost = if ca == cb { 0 } else { 1 };
2589            cur[j + 1] = (prev[j + 1] + 1).min(cur[j] + 1).min(prev[j] + cost);
2590        }
2591        std::mem::swap(&mut prev, &mut cur);
2592    }
2593    prev[b.len()]
2594}
2595
2596#[cfg(test)]
2597mod tests {
2598    use super::*;
2599    #[allow(unused_imports)]
2600    use crate::config::test_prelude::*;
2601
2602    #[test]
2603    fn config_check_reports_syntax_errors_with_location() {
2604        let report = check_config_content("t.yaml", "telegram_bot_token: [unclosed");
2605        assert!(!report.ok());
2606        assert!(report.errors[0].contains("YAML syntax error"));
2607        assert!(report.summary.is_none());
2608    }
2609
2610    #[test]
2611    fn config_check_warns_on_unknown_key_with_suggestion() {
2612        let report = check_config_content(
2613            "t.yaml",
2614            "telegram_bot_token: tok\nbot_username: bot\napi_key: key\nmax_tool_iterationz: 5\n",
2615        );
2616        assert!(report.ok(), "unknown keys warn but do not fail the check");
2617        assert!(
2618            report
2619                .warnings
2620                .iter()
2621                .any(|w| w.contains("max_tool_iterationz") && w.contains("max_tool_iterations")),
2622            "expected did-you-mean warning, got: {:?}",
2623            report.warnings
2624        );
2625        let (enabled, _, provider, _) = report.summary.as_ref().unwrap();
2626        assert!(enabled.contains(&"telegram"));
2627        assert_eq!(provider, "anthropic");
2628    }
2629
2630    #[test]
2631    fn config_check_rejects_bad_enum_value_with_suggestion() {
2632        let report = check_config_content("t.yaml", "api_key: key\ntool_policy:\n  mode: blok\n");
2633        assert!(!report.ok());
2634        assert!(
2635            report.errors[0].contains("blok") && report.errors[0].contains("block"),
2636            "expected did-you-mean on enum typo, got: {:?}",
2637            report.errors
2638        );
2639    }
2640
2641    #[test]
2642    fn config_check_warns_when_tool_policy_has_no_rules() {
2643        let report = check_config_content("t.yaml", "api_key: key\ntool_policy:\n  mode: block\n");
2644        assert!(report.ok(), "errors: {:?}", report.errors);
2645        assert!(
2646            report
2647                .warnings
2648                .iter()
2649                .any(|w| w.contains("tool_policy.mode is `block`")
2650                    && w.contains("every tool is still permitted")),
2651            "expected empty-policy warning, got: {:?}",
2652            report.warnings
2653        );
2654
2655        // Any rule silences it.
2656        let report = check_config_content(
2657            "t.yaml",
2658            "api_key: key\ntool_policy:\n  mode: block\n  allow_tools: [read_file]\n",
2659        );
2660        assert!(report.ok(), "errors: {:?}", report.errors);
2661        assert!(
2662            !report.warnings.iter().any(|w| w.contains("tool_policy")),
2663            "unexpected warning: {:?}",
2664            report.warnings
2665        );
2666        let report = check_config_content("t.yaml", "api_key: key\n");
2667        assert!(!report.warnings.iter().any(|w| w.contains("tool_policy")));
2668    }
2669
2670    #[test]
2671    fn config_check_flags_no_enabled_channel() {
2672        // The web channel is on by default, so a bare config is loadable.
2673        let report = check_config_content("t.yaml", "api_key: key\n");
2674        assert!(report.ok(), "errors: {:?}", report.errors);
2675        let (enabled, ..) = report.summary.as_ref().unwrap();
2676        assert!(enabled.contains(&"web"));
2677
2678        // Explicitly disabling every channel fails post-deserialize
2679        // validation — the check surfaces that as an error.
2680        let report = check_config_content(
2681            "t.yaml",
2682            "api_key: key\nchannels:\n  web:\n    enabled: false\n",
2683        );
2684        assert!(
2685            !report.ok(),
2686            "disabling all channels should be an error, got warnings: {:?}",
2687            report.warnings
2688        );
2689    }
2690
2691    #[test]
2692    fn config_check_rejects_non_mapping_root() {
2693        let report = check_config_content("t.yaml", "- just\n- a\n- list\n");
2694        assert!(!report.ok());
2695        assert!(report.errors[0].contains("mapping"));
2696    }
2697
2698    #[test]
2699    fn friendly_error_suggests_closest_field() {
2700        // A real serde_yaml unknown-field error for a mistyped key.
2701        #[derive(Debug, serde::Deserialize)]
2702        #[serde(deny_unknown_fields)]
2703        struct Mini {
2704            #[allow(dead_code)]
2705            discord: bool,
2706        }
2707        let err = serde_yaml::from_str::<Mini>("discrod: true\n").unwrap_err();
2708        let msg = friendly_yaml_error("cfg.yaml", &err);
2709        assert!(msg.contains("did you mean `discord`?"), "got: {msg}");
2710        assert!(msg.contains("microclaw setup"));
2711    }
2712
2713    #[test]
2714    fn extract_and_suggest_helpers() {
2715        let raw = "unknown variant `discrod`, expected one of `telegram`, `discord`, `slack`";
2716        assert_eq!(extract_unknown_token(raw), Some(("variant", "discrod")));
2717        let opts = extract_backtick_options(raw);
2718        assert_eq!(opts, vec!["telegram", "discord", "slack"]);
2719        assert_eq!(
2720            suggest_closest("discrod", &opts).as_deref(),
2721            Some("discord")
2722        );
2723        // Nothing close → no suggestion.
2724        assert_eq!(suggest_closest("zzzzzz", &opts), None);
2725    }
2726
2727    #[test]
2728    fn levenshtein_basics() {
2729        assert_eq!(levenshtein("kitten", "sitting"), 3);
2730        assert_eq!(levenshtein("discord", "discord"), 0);
2731        assert_eq!(levenshtein("", "abc"), 3);
2732    }
2733
2734    #[test]
2735    fn channel_status_splits_enabled_and_disabled() {
2736        let cfg: Config = serde_yaml::from_str(
2737            "api_key: k\nweb_enabled: false\nchannels:\n  telegram:\n    enabled: true\n  discord:\n    enabled: false\n",
2738        )
2739        .unwrap();
2740        let (enabled, disabled) = cfg.channel_status();
2741        assert_eq!(enabled, vec!["telegram"]);
2742        assert_eq!(disabled, vec!["discord"]);
2743    }
2744
2745    #[test]
2746    fn no_enabled_channel_error_names_disabled_channel() {
2747        let mut cfg: Config = serde_yaml::from_str(
2748            "api_key: k\nweb_enabled: false\nchannels:\n  telegram:\n    enabled: false\n",
2749        )
2750        .unwrap();
2751        let err = cfg.post_deserialize().unwrap_err().to_string();
2752        assert!(err.contains("configured but not enabled"), "got: {err}");
2753        assert!(err.contains("telegram"), "got: {err}");
2754    }
2755
2756    #[test]
2757    fn aux_models_parse_from_yaml() {
2758        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\naux_models:\n  compaction: claude-haiku-4-5\n  reflector: claude-haiku-4-5\n";
2759        let config: Config = serde_yaml::from_str(yaml).unwrap();
2760        assert_eq!(
2761            config.aux_models.compaction.as_deref(),
2762            Some("claude-haiku-4-5")
2763        );
2764        assert_eq!(
2765            config.aux_models.reflector_model(),
2766            Some("claude-haiku-4-5")
2767        );
2768    }
2769
2770    #[test]
2771    fn aux_models_absent_yaml_defaults_to_none() {
2772        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\n";
2773        let config: Config = serde_yaml::from_str(yaml).unwrap();
2774        assert!(config.aux_models.compaction.is_none());
2775    }
2776
2777    #[test]
2778    fn aux_models_title_vision_parse_from_yaml() {
2779        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\naux_models:\n  title: claude-haiku-4-5\n  vision: claude-haiku-4-5\n";
2780        let config: Config = serde_yaml::from_str(yaml).unwrap();
2781        assert_eq!(config.aux_models.title_model(), Some("claude-haiku-4-5"));
2782        assert_eq!(config.aux_models.vision_model(), Some("claude-haiku-4-5"));
2783    }
2784
2785    #[test]
2786    fn test_clawhub_config_defaults() {
2787        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\n";
2788        let config: Config = serde_yaml::from_str(yaml).unwrap();
2789        assert_eq!(config.clawhub.registry, "https://clawhub.ai");
2790        assert!(config.clawhub.agent_tools_enabled);
2791    }
2792
2793    #[test]
2794    fn test_voice_config_defaults() {
2795        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\n";
2796        let config: Config = serde_yaml::from_str(yaml).unwrap();
2797        assert_eq!(config.voice_provider, "openai");
2798        assert!(config.voice_transcription_command.is_none());
2799    }
2800
2801    #[test]
2802    fn test_voice_config_local_provider() {
2803        let yaml = r#"
2804telegram_bot_token: tok
2805bot_username: bot
2806api_key: key
2807voice_provider: "local"
2808voice_transcription_command: "whisper-mlx --file {file}"
2809"#;
2810        let config: Config = serde_yaml::from_str(yaml).unwrap();
2811        assert_eq!(config.voice_provider, "local");
2812        assert_eq!(
2813            config.voice_transcription_command,
2814            Some("whisper-mlx --file {file}".into())
2815        );
2816    }
2817
2818    #[test]
2819    fn test_config_yaml_roundtrip() {
2820        let config = test_config();
2821        let yaml = serde_yaml::to_string(&config).unwrap();
2822        let parsed: Config = serde_yaml::from_str(&yaml).unwrap();
2823        assert_eq!(parsed.telegram_bot_token, "tok");
2824        assert_eq!(parsed.max_tokens, 8192);
2825        assert_eq!(parsed.llm_provider, "anthropic");
2826    }
2827
2828    #[test]
2829    fn test_default_data_dir_uses_microclaw_home() {
2830        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\n";
2831        let config: Config = serde_yaml::from_str(yaml).unwrap();
2832        assert!(config.data_dir.ends_with(".microclaw"));
2833    }
2834
2835    #[test]
2836    fn test_config_sandbox_defaults_to_off() {
2837        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\n";
2838        let config: Config = serde_yaml::from_str(yaml).unwrap();
2839        assert!(matches!(config.sandbox.mode, SandboxMode::Off));
2840        assert!(matches!(config.sandbox.backend, SandboxBackend::Auto));
2841        assert!(config.sandbox.require_runtime);
2842        assert_eq!(config.sandbox.image, "ubuntu:25.10");
2843    }
2844
2845    #[test]
2846    fn test_post_deserialize_empty_working_dir_uses_default() {
2847        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\nworking_dir: '  '\n";
2848        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
2849        config.post_deserialize().unwrap();
2850        assert!(std::path::PathBuf::from(&config.working_dir)
2851            .ends_with(std::path::Path::new(".microclaw").join("working_dir")));
2852    }
2853
2854    #[test]
2855    fn test_post_deserialize_zero_memory_budget_uses_default() {
2856        let yaml =
2857            "telegram_bot_token: tok\nbot_username: bot\napi_key: key\nmemory_token_budget: 0\n";
2858        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
2859        config.post_deserialize().unwrap();
2860        assert_eq!(config.memory_token_budget, 1500);
2861    }
2862
2863    #[test]
2864    fn test_config_working_dir_isolation_defaults_to_chat() {
2865        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\n";
2866        let config: Config = serde_yaml::from_str(yaml).unwrap();
2867        assert!(matches!(
2868            config.working_dir_isolation,
2869            WorkingDirIsolation::Chat
2870        ));
2871    }
2872
2873    #[test]
2874    fn test_config_working_dir_isolation_accepts_chat() {
2875        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\nworking_dir_isolation: chat\n";
2876        let config: Config = serde_yaml::from_str(yaml).unwrap();
2877        assert!(matches!(
2878            config.working_dir_isolation,
2879            WorkingDirIsolation::Chat
2880        ));
2881    }
2882
2883    #[test]
2884    fn test_config_working_dir_isolation_accepts_true() {
2885        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\nworking_dir_isolation: true\n";
2886        let config: Config = serde_yaml::from_str(yaml).unwrap();
2887        assert!(matches!(
2888            config.working_dir_isolation,
2889            WorkingDirIsolation::Chat
2890        ));
2891    }
2892
2893    #[test]
2894    fn test_config_working_dir_isolation_accepts_false() {
2895        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\nworking_dir_isolation: false\n";
2896        let config: Config = serde_yaml::from_str(yaml).unwrap();
2897        assert!(matches!(
2898            config.working_dir_isolation,
2899            WorkingDirIsolation::Shared
2900        ));
2901    }
2902
2903    #[test]
2904    fn test_high_risk_tool_user_confirmation_required_defaults_true() {
2905        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\n";
2906        let config: Config = serde_yaml::from_str(yaml).unwrap();
2907        assert!(config.high_risk_tool_user_confirmation_required);
2908    }
2909
2910    #[test]
2911    fn test_high_risk_tool_user_confirmation_required_accepts_false() {
2912        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\nhigh_risk_tool_user_confirmation_required: false\n";
2913        let config: Config = serde_yaml::from_str(yaml).unwrap();
2914        assert!(!config.high_risk_tool_user_confirmation_required);
2915    }
2916
2917    #[test]
2918    fn test_config_post_deserialize() {
2919        let yaml =
2920            "telegram_bot_token: tok\nbot_username: bot\napi_key: key\nllm_provider: ANTHROPIC\n";
2921        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
2922        config.post_deserialize().unwrap();
2923        assert_eq!(config.llm_provider, "anthropic");
2924        assert_eq!(config.model, "claude-sonnet-4-5-20250929");
2925    }
2926
2927    #[test]
2928    fn test_post_deserialize_invalid_timezone() {
2929        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\noverride_timezone: Mars/Olympus\n";
2930        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
2931        let err = config.post_deserialize().unwrap_err();
2932        let msg = err.to_string();
2933        assert!(msg.contains("Invalid timezone"));
2934    }
2935
2936    #[test]
2937    fn test_post_deserialize_auto_timezone_resolves_to_valid_tz() {
2938        let yaml =
2939            "telegram_bot_token: tok\nbot_username: bot\napi_key: key\noverride_timezone: auto\n";
2940        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
2941        config.post_deserialize().unwrap();
2942        assert!(config.timezone.parse::<chrono_tz::Tz>().is_ok());
2943    }
2944
2945    #[test]
2946    fn test_post_deserialize_missing_api_key() {
2947        let yaml = "telegram_bot_token: tok\nbot_username: bot\n";
2948        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
2949        let err = config.post_deserialize().unwrap_err();
2950        let msg = err.to_string();
2951        assert!(msg.contains("api_key is required"));
2952    }
2953
2954    #[test]
2955    fn test_post_deserialize_openai_codex_allows_empty_api_key() {
2956        let _guard = env_lock();
2957        let prev_codex_home = std::env::var("CODEX_HOME").ok();
2958        let prev_access = std::env::var("OPENAI_CODEX_ACCESS_TOKEN").ok();
2959        std::env::remove_var("OPENAI_CODEX_ACCESS_TOKEN");
2960
2961        let auth_dir = std::env::temp_dir().join(format!(
2962            "microclaw-codex-auth-{}",
2963            std::time::SystemTime::now()
2964                .duration_since(std::time::UNIX_EPOCH)
2965                .unwrap_or_default()
2966                .as_nanos()
2967        ));
2968        std::fs::create_dir_all(&auth_dir).unwrap();
2969        std::fs::write(
2970            auth_dir.join("auth.json"),
2971            r#"{"tokens":{"access_token":"tok"}}"#,
2972        )
2973        .unwrap();
2974        std::env::set_var("CODEX_HOME", &auth_dir);
2975
2976        let yaml =
2977            "telegram_bot_token: tok\nbot_username: bot\nllm_provider: openai-codex\nmodel: gpt-5.3-codex\n";
2978        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
2979        config.post_deserialize().unwrap();
2980
2981        if let Some(prev) = prev_codex_home {
2982            std::env::set_var("CODEX_HOME", prev);
2983        } else {
2984            std::env::remove_var("CODEX_HOME");
2985        }
2986        if let Some(prev) = prev_access {
2987            std::env::set_var("OPENAI_CODEX_ACCESS_TOKEN", prev);
2988        } else {
2989            std::env::remove_var("OPENAI_CODEX_ACCESS_TOKEN");
2990        }
2991        let _ = std::fs::remove_file(auth_dir.join("auth.json"));
2992        let _ = std::fs::remove_dir(auth_dir);
2993        assert_eq!(config.llm_provider, "openai-codex");
2994    }
2995
2996    #[test]
2997    fn test_post_deserialize_missing_bot_tokens() {
2998        let yaml = "bot_username: bot\napi_key: key\nweb_enabled: false\n";
2999        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3000        let err = config.post_deserialize().unwrap_err();
3001        let msg = err.to_string();
3002        assert!(msg.contains("channel must be enabled"));
3003    }
3004
3005    #[test]
3006    fn test_post_deserialize_discord_only() {
3007        let yaml = "bot_username: bot\napi_key: key\ndiscord_bot_token: discord_tok\n";
3008        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3009        // Should succeed: discord_bot_token is set even though telegram_bot_token is empty
3010        config.post_deserialize().unwrap();
3011    }
3012
3013    #[test]
3014    fn test_post_deserialize_irc_only() {
3015        let yaml = r##"
3016api_key: key
3017channels:
3018  irc:
3019    enabled: true
3020    server: "irc.example.com"
3021    nick: "microclaw"
3022    channels: "#microclaw"
3023"##;
3024        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3025        config.post_deserialize().unwrap();
3026        assert!(config.channel_enabled("irc"));
3027    }
3028
3029    #[test]
3030    fn test_post_deserialize_channel_enabled_flag_overrides_legacy_inference() {
3031        let yaml = "telegram_bot_token: tok\nbot_username: bot\ndiscord_bot_token: discord_tok\napi_key: key\nchannels:\n  telegram:\n    enabled: false\n  discord:\n    enabled: true\n  web:\n    enabled: false\n";
3032        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3033        config.post_deserialize().unwrap();
3034
3035        assert!(!config.channel_enabled("telegram"));
3036        assert!(config.channel_enabled("discord"));
3037        assert!(!config.channel_enabled("web"));
3038    }
3039
3040    #[test]
3041    fn test_post_deserialize_channel_enabled_flag_controls_web() {
3042        let yaml =
3043            "api_key: key\ndiscord_bot_token: discord_tok\nchannels:\n  web:\n    enabled: false\n";
3044        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3045        config.post_deserialize().unwrap();
3046
3047        assert!(!config.channel_enabled("web"));
3048    }
3049
3050    #[test]
3051    fn test_post_deserialize_openai_default_model() {
3052        let yaml =
3053            "telegram_bot_token: tok\nbot_username: bot\napi_key: key\nllm_provider: openai\n";
3054        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3055        config.post_deserialize().unwrap();
3056        assert_eq!(config.model, "gpt-5.2");
3057    }
3058
3059    #[test]
3060    fn test_post_deserialize_wildcard_model_falls_back_to_provider_default() {
3061        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\nllm_provider: openai\nmodel: '*'\n";
3062        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3063        config.post_deserialize().unwrap();
3064        assert_eq!(config.model, "gpt-5.2");
3065    }
3066
3067    #[test]
3068    fn test_post_deserialize_openai_codex_default_model() {
3069        let _guard = env_lock();
3070        let prev_codex_home = std::env::var("CODEX_HOME").ok();
3071        let prev_access = std::env::var("OPENAI_CODEX_ACCESS_TOKEN").ok();
3072        std::env::remove_var("OPENAI_CODEX_ACCESS_TOKEN");
3073
3074        let auth_dir = std::env::temp_dir().join(format!(
3075            "microclaw-codex-auth-{}",
3076            std::time::SystemTime::now()
3077                .duration_since(std::time::UNIX_EPOCH)
3078                .unwrap_or_default()
3079                .as_nanos()
3080        ));
3081        std::fs::create_dir_all(&auth_dir).unwrap();
3082        std::fs::write(
3083            auth_dir.join("auth.json"),
3084            r#"{"tokens":{"access_token":"tok"}}"#,
3085        )
3086        .unwrap();
3087        std::env::set_var("CODEX_HOME", &auth_dir);
3088
3089        let yaml = "telegram_bot_token: tok\nbot_username: bot\nllm_provider: openai-codex\n";
3090        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3091        config.post_deserialize().unwrap();
3092
3093        if let Some(prev) = prev_codex_home {
3094            std::env::set_var("CODEX_HOME", prev);
3095        } else {
3096            std::env::remove_var("CODEX_HOME");
3097        }
3098        if let Some(prev) = prev_access {
3099            std::env::set_var("OPENAI_CODEX_ACCESS_TOKEN", prev);
3100        } else {
3101            std::env::remove_var("OPENAI_CODEX_ACCESS_TOKEN");
3102        }
3103        let _ = std::fs::remove_file(auth_dir.join("auth.json"));
3104        let _ = std::fs::remove_dir(auth_dir);
3105        assert_eq!(config.model, "gpt-5.3-codex");
3106    }
3107
3108    #[test]
3109    fn test_post_deserialize_openai_codex_missing_oauth_token() {
3110        let _guard = env_lock();
3111        let prev_codex_home = std::env::var("CODEX_HOME").ok();
3112        let prev_access = std::env::var("OPENAI_CODEX_ACCESS_TOKEN").ok();
3113        std::env::remove_var("OPENAI_CODEX_ACCESS_TOKEN");
3114
3115        let auth_dir = std::env::temp_dir().join(format!(
3116            "microclaw-codex-auth-missing-{}",
3117            std::time::SystemTime::now()
3118                .duration_since(std::time::UNIX_EPOCH)
3119                .unwrap_or_default()
3120                .as_nanos()
3121        ));
3122        std::fs::create_dir_all(&auth_dir).unwrap();
3123        std::env::set_var("CODEX_HOME", &auth_dir);
3124
3125        let yaml = "telegram_bot_token: tok\nbot_username: bot\nllm_provider: openai-codex\n";
3126        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3127        let err = config.post_deserialize().unwrap_err();
3128        let msg = err.to_string();
3129
3130        if let Some(prev) = prev_codex_home {
3131            std::env::set_var("CODEX_HOME", prev);
3132        } else {
3133            std::env::remove_var("CODEX_HOME");
3134        }
3135        if let Some(prev) = prev_access {
3136            std::env::set_var("OPENAI_CODEX_ACCESS_TOKEN", prev);
3137        } else {
3138            std::env::remove_var("OPENAI_CODEX_ACCESS_TOKEN");
3139        }
3140        let _ = std::fs::remove_dir(auth_dir);
3141
3142        assert!(msg.contains("openai-codex requires ~/.codex/auth.json"));
3143    }
3144
3145    #[test]
3146    fn test_post_deserialize_openai_codex_rejects_plain_api_key_without_oauth() {
3147        let _guard = env_lock();
3148        let prev_codex_home = std::env::var("CODEX_HOME").ok();
3149        let prev_access = std::env::var("OPENAI_CODEX_ACCESS_TOKEN").ok();
3150        std::env::remove_var("OPENAI_CODEX_ACCESS_TOKEN");
3151
3152        let auth_dir = std::env::temp_dir().join(format!(
3153            "microclaw-codex-auth-plain-key-{}",
3154            std::time::SystemTime::now()
3155                .duration_since(std::time::UNIX_EPOCH)
3156                .unwrap_or_default()
3157                .as_nanos()
3158        ));
3159        std::fs::create_dir_all(&auth_dir).unwrap();
3160        std::env::set_var("CODEX_HOME", &auth_dir);
3161
3162        let yaml = "telegram_bot_token: tok\nbot_username: bot\nllm_provider: openai-codex\napi_key: sk-user-stale\n";
3163        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3164        let err = config.post_deserialize().unwrap_err();
3165        let msg = err.to_string();
3166
3167        if let Some(prev) = prev_codex_home {
3168            std::env::set_var("CODEX_HOME", prev);
3169        } else {
3170            std::env::remove_var("CODEX_HOME");
3171        }
3172        if let Some(prev) = prev_access {
3173            std::env::set_var("OPENAI_CODEX_ACCESS_TOKEN", prev);
3174        } else {
3175            std::env::remove_var("OPENAI_CODEX_ACCESS_TOKEN");
3176        }
3177        let _ = std::fs::remove_dir(auth_dir);
3178
3179        assert!(msg.contains("ignores microclaw.config.yaml api_key"));
3180    }
3181
3182    #[test]
3183    fn test_post_deserialize_openai_codex_allows_env_access_token() {
3184        let _guard = env_lock();
3185        let prev_codex_home = std::env::var("CODEX_HOME").ok();
3186        let prev_access = std::env::var("OPENAI_CODEX_ACCESS_TOKEN").ok();
3187        std::env::remove_var("CODEX_HOME");
3188        std::env::set_var("OPENAI_CODEX_ACCESS_TOKEN", "env-token");
3189
3190        let yaml = "telegram_bot_token: tok\nbot_username: bot\nllm_provider: openai-codex\n";
3191        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3192        config.post_deserialize().unwrap();
3193
3194        if let Some(prev) = prev_codex_home {
3195            std::env::set_var("CODEX_HOME", prev);
3196        } else {
3197            std::env::remove_var("CODEX_HOME");
3198        }
3199        if let Some(prev) = prev_access {
3200            std::env::set_var("OPENAI_CODEX_ACCESS_TOKEN", prev);
3201        } else {
3202            std::env::remove_var("OPENAI_CODEX_ACCESS_TOKEN");
3203        }
3204
3205        assert_eq!(config.llm_provider, "openai-codex");
3206    }
3207
3208    #[test]
3209    fn test_post_deserialize_qwen_code_allows_oauth_without_api_key() {
3210        let _guard = env_lock();
3211        let prev_qwen_home = std::env::var("QWEN_HOME").ok();
3212        let prev_qwen_access = std::env::var("QWEN_PORTAL_ACCESS_TOKEN").ok();
3213        std::env::remove_var("QWEN_PORTAL_ACCESS_TOKEN");
3214
3215        let qwen_dir = std::env::temp_dir().join(format!(
3216            "microclaw-qwen-auth-{}",
3217            std::time::SystemTime::now()
3218                .duration_since(std::time::UNIX_EPOCH)
3219                .unwrap_or_default()
3220                .as_nanos()
3221        ));
3222        std::fs::create_dir_all(&qwen_dir).unwrap();
3223        std::fs::write(
3224            qwen_dir.join("oauth_creds.json"),
3225            r#"{"access_token":"qwen-oauth-token"}"#,
3226        )
3227        .unwrap();
3228        std::env::set_var("QWEN_HOME", &qwen_dir);
3229
3230        let yaml = "telegram_bot_token: tok\nbot_username: bot\nllm_provider: qwen-portal\n";
3231        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3232        config.post_deserialize().unwrap();
3233
3234        if let Some(prev) = prev_qwen_home {
3235            std::env::set_var("QWEN_HOME", prev);
3236        } else {
3237            std::env::remove_var("QWEN_HOME");
3238        }
3239        if let Some(prev) = prev_qwen_access {
3240            std::env::set_var("QWEN_PORTAL_ACCESS_TOKEN", prev);
3241        } else {
3242            std::env::remove_var("QWEN_PORTAL_ACCESS_TOKEN");
3243        }
3244        let _ = std::fs::remove_file(qwen_dir.join("oauth_creds.json"));
3245        let _ = std::fs::remove_dir(qwen_dir);
3246
3247        assert_eq!(config.llm_provider, "qwen-portal");
3248    }
3249
3250    #[test]
3251    fn test_post_deserialize_qwen_code_missing_oauth_and_api_key() {
3252        let _guard = env_lock();
3253        let prev_qwen_home = std::env::var("QWEN_HOME").ok();
3254        let prev_qwen_access = std::env::var("QWEN_PORTAL_ACCESS_TOKEN").ok();
3255        std::env::remove_var("QWEN_PORTAL_ACCESS_TOKEN");
3256
3257        let qwen_dir = std::env::temp_dir().join(format!(
3258            "microclaw-qwen-auth-missing-{}",
3259            std::time::SystemTime::now()
3260                .duration_since(std::time::UNIX_EPOCH)
3261                .unwrap_or_default()
3262                .as_nanos()
3263        ));
3264        std::fs::create_dir_all(&qwen_dir).unwrap();
3265        std::env::set_var("QWEN_HOME", &qwen_dir);
3266
3267        let yaml = "telegram_bot_token: tok\nbot_username: bot\nllm_provider: qwen-portal\n";
3268        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3269        let err = config.post_deserialize().unwrap_err();
3270
3271        if let Some(prev) = prev_qwen_home {
3272            std::env::set_var("QWEN_HOME", prev);
3273        } else {
3274            std::env::remove_var("QWEN_HOME");
3275        }
3276        if let Some(prev) = prev_qwen_access {
3277            std::env::set_var("QWEN_PORTAL_ACCESS_TOKEN", prev);
3278        } else {
3279            std::env::remove_var("QWEN_PORTAL_ACCESS_TOKEN");
3280        }
3281        let _ = std::fs::remove_dir(qwen_dir);
3282
3283        assert!(err
3284            .to_string()
3285            .contains("qwen-portal requires api_key, or ~/.qwen/oauth_creds.json"));
3286    }
3287
3288    #[test]
3289    fn test_post_deserialize_ollama_default_model_and_empty_key() {
3290        let yaml = "telegram_bot_token: tok\nbot_username: bot\nllm_provider: ollama\n";
3291        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3292        config.post_deserialize().unwrap();
3293        assert_eq!(config.model, "llama3.2");
3294    }
3295
3296    #[test]
3297    fn test_post_deserialize_empty_base_url_becomes_none() {
3298        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\nllm_base_url: '  '\n";
3299        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3300        config.post_deserialize().unwrap();
3301        assert!(config.llm_base_url.is_none());
3302    }
3303
3304    #[test]
3305    fn test_post_deserialize_empty_llm_user_agent_uses_default() {
3306        let yaml =
3307            "telegram_bot_token: tok\nbot_username: bot\napi_key: key\nllm_user_agent: '  '\n";
3308        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3309        config.post_deserialize().unwrap();
3310        assert_eq!(
3311            config.llm_user_agent,
3312            crate::http_client::default_llm_user_agent()
3313        );
3314    }
3315
3316    #[test]
3317    fn test_post_deserialize_provider_case_insensitive() {
3318        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\nllm_provider: '  ANTHROPIC  '\n";
3319        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3320        config.post_deserialize().unwrap();
3321        assert_eq!(config.llm_provider, "anthropic");
3322        assert_eq!(config.model, "claude-sonnet-4-5-20250929");
3323    }
3324
3325    #[test]
3326    fn test_post_deserialize_normalizes_openai_compat_body_overrides() {
3327        let yaml = r#"
3328telegram_bot_token: tok
3329bot_username: bot
3330api_key: key
3331openai_compat_body_overrides:
3332  " temperature ": 0.2
3333  "  ": 1
3334openai_compat_body_overrides_by_provider:
3335  " OPENAI ":
3336    " top_p ": 0.95
3337    "": 1
3338  "  ":
3339    seed: 7
3340openai_compat_body_overrides_by_model:
3341  " gpt-5.2 ":
3342    " frequency_penalty ": 0.1
3343    "": 1
3344  " ":
3345    seed: 7
3346"#;
3347        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3348        config.post_deserialize().unwrap();
3349
3350        assert_eq!(
3351            config.openai_compat_body_overrides.get("temperature"),
3352            Some(&serde_json::json!(0.2))
3353        );
3354        assert!(!config.openai_compat_body_overrides.contains_key("  "));
3355
3356        let provider_params = config
3357            .openai_compat_body_overrides_by_provider
3358            .get("openai")
3359            .unwrap();
3360        assert_eq!(provider_params.get("top_p"), Some(&serde_json::json!(0.95)));
3361        assert!(!provider_params.contains_key(""));
3362        assert!(!config
3363            .openai_compat_body_overrides_by_provider
3364            .contains_key(" OPENAI "));
3365
3366        let model_params = config
3367            .openai_compat_body_overrides_by_model
3368            .get("gpt-5.2")
3369            .unwrap();
3370        assert_eq!(
3371            model_params.get("frequency_penalty"),
3372            Some(&serde_json::json!(0.1))
3373        );
3374        assert!(!model_params.contains_key(""));
3375    }
3376
3377    #[test]
3378    fn test_post_deserialize_normalizes_subagent_acp_config() {
3379        let yaml = r#"
3380telegram_bot_token: tok
3381bot_username: bot
3382api_key: key
3383subagents:
3384  acp:
3385    enabled: true
3386    command: "  codex  "
3387    args: ["  --model  ", " ", "gpt-5.4"]
3388    env:
3389      " OPENAI_API_KEY ": abc
3390      "   ": ignored
3391    default_target: "  worker  "
3392    targets:
3393      " worker ":
3394        enabled: true
3395        command: "  codex-worker  "
3396        args: [" --fast "]
3397        env:
3398          " TOKEN ": xyz
3399"#;
3400        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3401        config.post_deserialize().unwrap();
3402
3403        assert!(config.subagents.acp.default_target.enabled);
3404        assert_eq!(config.subagents.acp.default_target.command, "codex");
3405        assert_eq!(
3406            config.subagents.acp.default_target.args,
3407            vec!["--model".to_string(), "gpt-5.4".to_string()]
3408        );
3409        assert_eq!(
3410            config
3411                .subagents
3412                .acp
3413                .default_target
3414                .env
3415                .get("OPENAI_API_KEY"),
3416            Some(&"abc".to_string())
3417        );
3418        assert_eq!(
3419            config.subagents.acp.default_target_name.as_deref(),
3420            Some("worker")
3421        );
3422        assert!(!config.subagents.acp.default_target.env.contains_key("   "));
3423        let target = config.subagents.acp.targets.get("worker").unwrap();
3424        assert!(target.enabled);
3425        assert_eq!(target.command, "codex-worker");
3426        assert_eq!(target.args, vec!["--fast".to_string()]);
3427        assert_eq!(target.env.get("TOKEN"), Some(&"xyz".to_string()));
3428    }
3429
3430    #[test]
3431    fn test_post_deserialize_web_non_local_no_token_required() {
3432        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\nweb_enabled: true\nweb_host: 0.0.0.0\n";
3433        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3434        config.post_deserialize().unwrap();
3435    }
3436
3437    #[test]
3438    fn test_post_deserialize_web_channel_auth_token_is_removed() {
3439        let yaml = "telegram_bot_token: tok\nbot_username: bot\napi_key: key\nweb_enabled: true\nweb_host: 0.0.0.0\nchannels:\n  web:\n    enabled: true\n    auth_token: token123\n";
3440        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3441        config.post_deserialize().unwrap();
3442        let has_auth_token = config
3443            .channels
3444            .get("web")
3445            .and_then(|v| v.as_mapping())
3446            .map(|map| map.contains_key(serde_yaml::Value::String("auth_token".to_string())))
3447            .unwrap_or(false);
3448        assert!(!has_auth_token);
3449    }
3450
3451    #[test]
3452    fn test_model_prices_parse_and_estimate() {
3453        let yaml = r#"
3454telegram_bot_token: tok
3455bot_username: bot
3456api_key: key
3457model_prices:
3458  - model: claude-sonnet-4-5-20250929
3459    input_per_million_usd: 3.0
3460    output_per_million_usd: 15.0
3461"#;
3462        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3463        config.post_deserialize().unwrap();
3464        let est = config
3465            .estimate_cost_usd("claude-sonnet-4-5-20250929", 1000, 2000)
3466            .unwrap();
3467        assert!((est - 0.033).abs() < 1e-9);
3468    }
3469
3470    #[test]
3471    fn test_model_prices_invalid_rejected() {
3472        let yaml = r#"
3473telegram_bot_token: tok
3474bot_username: bot
3475api_key: key
3476model_prices:
3477  - model: ""
3478    input_per_million_usd: 1.0
3479    output_per_million_usd: 1.0
3480"#;
3481        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3482        let err = config.post_deserialize().unwrap_err();
3483        assert!(err
3484            .to_string()
3485            .contains("model_prices entries must include non-empty model"));
3486    }
3487
3488    #[test]
3489    fn test_config_yaml_with_all_optional_fields() {
3490        let yaml = r#"
3491telegram_bot_token: tok
3492bot_username: bot
3493api_key: key
3494openai_api_key: sk-test
3495override_timezone: US/Eastern
3496allowed_groups: [123, 456]
3497control_chat_ids: [999]
3498max_session_messages: 60
3499compact_keep_recent: 30
3500discord_bot_token: discord_tok
3501discord_allowed_channels: [111, 222]
3502"#;
3503        let mut config: Config = serde_yaml::from_str(yaml).unwrap();
3504        config.post_deserialize().unwrap();
3505        assert_eq!(config.openai_api_key.as_deref(), Some("sk-test"));
3506        assert_eq!(config.timezone, "US/Eastern");
3507        assert_eq!(config.allowed_groups, vec![123, 456]);
3508        assert_eq!(config.control_chat_ids, vec![999]);
3509        assert_eq!(config.max_session_messages, 60);
3510        assert_eq!(config.compact_keep_recent, 30);
3511        assert_eq!(config.discord_allowed_channels, vec![111, 222]);
3512    }
3513
3514    #[test]
3515    fn test_expand_path_with_tilde() {
3516        let home = PathBuf::from(shellexpand::tilde("~").as_ref());
3517        let path = "~/foo/bar";
3518        let expanded = expand_path(path);
3519        assert_eq!(expanded, home.join("foo/bar"));
3520
3521        let path = "~";
3522        let expanded = expand_path(path);
3523        assert_eq!(expanded, home);
3524
3525        let path = "/absolute/path";
3526        let expanded = expand_path(path);
3527        assert_eq!(expanded, std::path::PathBuf::from("/absolute/path"));
3528    }
3529
3530    #[test]
3531    fn unknown_top_level_key_is_flagged() {
3532        let map = mapping_of("definitely_not_a_key: true\napi_key: k\n");
3533        let warnings = unknown_top_level_key_warnings(&map);
3534        assert!(
3535            warnings.iter().any(|w| w.contains("definitely_not_a_key")),
3536            "expected an unknown-key warning, got: {warnings:?}"
3537        );
3538        // A real key in the same document must not be flagged.
3539        assert!(
3540            !warnings.iter().any(|w| w.contains("`api_key`")),
3541            "api_key should be recognized, got: {warnings:?}"
3542        );
3543    }
3544
3545    #[test]
3546    fn unknown_key_gets_did_you_mean() {
3547        // `api_ky` is one edit away from the real `api_key`.
3548        let map = mapping_of("api_ky: k\n");
3549        let warnings = unknown_top_level_key_warnings(&map);
3550        assert!(
3551            warnings
3552                .iter()
3553                .any(|w| w.contains("api_ky") && w.contains("did you mean `api_key`")),
3554            "expected a did-you-mean suggestion, got: {warnings:?}"
3555        );
3556    }
3557
3558    #[test]
3559    fn known_top_level_keys_produce_no_warnings() {
3560        // A spread of real keys: plain fields, a nested struct, the flattened
3561        // clawhub_* keys, and the skip-serialized timezone fields.
3562        let yaml = "api_key: k\ntelegram_bot_token: t\nclawhub_registry: https://x\n\
3563timezone: UTC\noverride_timezone: UTC\nsandbox:\n  enabled: false\n";
3564        let warnings = unknown_top_level_key_warnings(&mapping_of(yaml));
3565        assert!(warnings.is_empty(), "unexpected warnings: {warnings:?}");
3566    }
3567}