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