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