agentmux_srv_core/backend/providers.rs
1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Static provider registry — Rust equivalent of
5//! `frontend/app/view/agent/providers/index.ts`.
6//!
7//! All string data is `&'static str` / `&'static [&'static str]` so lookups
8//! are zero-allocation. The registry is initialised once via `LazyLock` and
9//! then read-only for the lifetime of the process.
10
11use std::collections::HashMap;
12use std::sync::LazyLock;
13
14// ─── Controller type ─────────────────────────────────────────────────────────
15
16/// How the provider process is managed.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum ControllerType {
19 /// A single long-running process; input is streamed to stdin.
20 Persistent,
21 /// A fresh subprocess is spawned for every turn; prior sessions are
22 /// resumed via `resume_flag`.
23 Subprocess,
24 /// Agent Client Protocol (ACP): JSON-RPC 2.0 over stdio.
25 /// Sessions are managed by the protocol — no resume flags needed.
26 Acp,
27 /// Muse Session Protocol (MSP, `muse serve`): Muse Code's own JSON-RPC
28 /// 2.0 over stdio, driven by the `msp` controller (blockcontroller/msp.rs).
29 Msp,
30 /// Provider-specific App Server protocol over a persistent JSONL stdio
31 /// transport. Protocol semantics are selected by [`AppServerKind`].
32 #[allow(dead_code)] // Off by default until SPEC_CODEX_APP_SERVER_FIRST_CLASS_PROVIDER_2026_09_12.md §15 Slice 6.
33 AppServer,
34 /// The CLI's own interactive UI in a terminal pane (view `term`, the
35 /// shell controller's `cmd` mode), for a CLI with no structured
36 /// interface: no transcript, tokens or resume of AgentMux's own.
37 /// SPEC_NINE_NEW_HARNESSES_2026_10_14.md §4.
38 Terminal,
39}
40
41/// Protocol spoken by a provider-neutral App Server controller.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum AppServerKind {
44 Codex,
45}
46
47/// Optional App Server capability advertised by a provider. Presence does not
48/// select the controller: `controller_type` remains the rollout switch.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub struct AppServerConfig {
51 pub kind: AppServerKind,
52 pub launch_args: &'static [&'static str],
53 pub fallback_controller: ControllerType,
54 pub fallback_output_format: &'static str,
55}
56
57/// How far AgentMux stands behind a harness: the lab's own door (`FirstClass`), or one that is installable and works
58/// but is not promised (`Preview`). It decides the picker, the defaults and the docs, and nothing about containers.
59/// An agent already running a preview harness is unaffected.
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub enum Tier {
62 FirstClass,
63 Preview,
64 /// A harness the person registered with a manifest (`providers_custom.rs`): AgentMux promises nothing about it.
65 Custom,
66}
67
68impl Tier {
69 /// The name the frontend catalog and block metadata use.
70 pub fn as_str(self) -> &'static str {
71 match self {
72 Tier::FirstClass => "first_class",
73 Tier::Preview => "preview",
74 Tier::Custom => "custom",
75 }
76 }
77}
78
79// ─── ProviderConfig ──────────────────────────────────────────────────────────
80
81/// All configuration needed to launch, authenticate, and stream output from
82/// a provider CLI.
83#[derive(Debug)]
84pub struct ProviderConfig {
85 /// Canonical provider identifier (e.g. `"claude"`).
86 pub id: &'static str,
87 /// First-class door or preview harness (`Tier`). Kept equal to the frontend catalog's `tier`.
88 pub tier: Tier,
89 /// Executable name on PATH (e.g. `"claude"`).
90 pub cli_command: &'static str,
91 /// Whether the provider keeps a persistent subprocess or spawns per turn.
92 pub controller_type: ControllerType,
93 /// Rich-client App Server capability, when the provider exposes one.
94 /// Kept separate from `controller_type` so the transport can land behind a
95 /// disabled-by-default rollout gate.
96 pub app_server: Option<AppServerConfig>,
97 /// Complete CLI args for a single-turn (subprocess) invocation.
98 /// The user prompt is written to the process's stdin.
99 pub launch_args: &'static [&'static str],
100 /// CLI args for persistent (long-running) mode.
101 /// `None` when `controller_type` is `Subprocess`.
102 pub persistent_launch_args: Option<&'static [&'static str]>,
103 /// Flag passed to resume a prior session, e.g. `"--resume"`.
104 /// `None` when the provider does not support simple-flag resume.
105 pub resume_flag: Option<&'static str>,
106 /// JSON field name in the CLI's init event that carries the session /
107 /// thread ID, e.g. `"session_id"` or `"thread_id"`.
108 pub session_id_field: &'static str,
109 /// Output format produced by the CLI in styled / streaming mode.
110 pub styled_output_format: &'static str,
111 // ── Auth isolation ───────────────────────────────────────────────────────
112 /// Environment variable that redirects the provider's config / auth
113 /// directory, e.g. `"CLAUDE_CONFIG_DIR"`.
114 pub auth_config_dir_env_var: &'static str,
115 /// Sub-directory name for this provider's auth/config dir, e.g. `"claude"`.
116 /// Resolved under `shared/providers/<name>/` (the default, account-wide and
117 /// instance-independent) and `shared/identities/<bundle>/<name>/` (per-identity)
118 /// — see `DataPaths::provider_auth_dir` and `identity_dir`.
119 pub auth_dir_name: &'static str,
120 /// Sub-directory (relative to this provider's config/auth dir) that
121 /// actually holds its native session/transcript history — e.g.
122 /// Claude's `"projects"`, Codex's `"sessions"`, Gemini's `"history"`.
123 /// `None` for providers with no simple directory-based history to
124 /// isolate/link (ACP providers — openclaw/pi/copilot — expose history
125 /// through the live protocol stream instead, not a fixed on-disk
126 /// path). Per-provider, filesystem-verified table:
127 /// `docs/specs/SPEC_UNIFIED_AGENT_HISTORY_STORE_2026-06-10.md` §2.1.
128 /// Used by `identity/auth_dirs.rs` to redirect an isolated identity's
129 /// history to the always-global
130 /// `DataPaths::identity_history_dir` — reagentx P1 on PR #2605 caught
131 /// that hardcoding `"projects"` there only worked for `claude`,
132 /// silently leaving every other OAuth-class provider's history
133 /// channel-local and unlinked.
134 pub history_native_subdir: Option<&'static str>,
135 /// Extra environment variables required for auth isolation.
136 /// Each entry is a `(key, value)` pair.
137 pub auth_extra_env: &'static [(&'static str, &'static str)],
138 /// Environment variables that must be *unset* before launching the CLI
139 /// (guards against nested-session issues, etc.).
140 pub unset_env: &'static [&'static str],
141 // ── npm install ──────────────────────────────────────────────────────────
142 /// npm package name used for local installation, e.g.
143 /// `"@anthropic-ai/claude-code"`.
144 pub npm_package: &'static str,
145 /// Version string passed to `npm install`, e.g. `"latest"` or `"0.116.0"`.
146 pub pinned_version: &'static str,
147 // ── Model vendor (harness vs. model vendor decoupling) ──────────────────
148 /// Environment variable this harness reads to redirect its model vendor
149 /// backend (e.g. Claude Code's `ANTHROPIC_BASE_URL`, pointing it at a
150 /// proxy/Bedrock/OpenRouter instead of Anthropic's default endpoint).
151 /// `None` when a harness isn't confirmed to support redirection — the
152 /// harness (CLI driving the session) and the model vendor (LLM backend
153 /// actually serving responses) are independent dimensions; this is the
154 /// declared capability side of that split. Set only where independently
155 /// verified, not guessed. See docs/specs for the harness/vendor concept.
156 pub base_url_env_var: Option<&'static str>,
157 /// Intelligence model vendors this harness talks to, most-default-first
158 /// (e.g. claude → `&["anthropic"]`, openclaw → `&["openai", "anthropic",
159 /// "google"]` since it's model-agnostic). Purely descriptive/display
160 /// data — drives the dual-icon vendor badge and the picker's default
161 /// vendor inference (`resolveEffectiveVendor` on the frontend); does not
162 /// gate anything at spawn time. The one thing that DOES gate spawn-time
163 /// behavior is `base_url_env_var` above — a provider can be redirected
164 /// to a custom endpoint independent of whether that endpoint's vendor
165 /// is even listed here.
166 pub supported_vendors: &'static [&'static str],
167 /// Path (relative to the agent's working directory) this provider
168 /// natively auto-discovers its startup instructions from — e.g.
169 /// `"CLAUDE.md"`, `"AGENTS.md"`, `".pi/APPEND_SYSTEM.md"`. `None` when
170 /// no native file-based convention is confirmed to exist (currently
171 /// only `kimi`) — `build_config_files` skips writing the instructions
172 /// file entirely in that case rather than writing inert content nobody
173 /// reads. Set only where independently verified against the provider's
174 /// own docs, not guessed — same discipline as `base_url_env_var` above.
175 /// See docs/specs/SPEC_PROVIDER_AWARE_STARTUP_INSTRUCTIONS_2026_08_24.md §2.
176 pub startup_instructions_filename: Option<&'static str>,
177 /// Every path (relative to the agent's working directory) this provider
178 /// **reads** as project instructions — which is not the same question as
179 /// `startup_instructions_filename` above, and is usually a superset of it.
180 ///
181 /// That field names the one file AgentMux *writes*: the canonical target
182 /// it picked per provider. This one names what the provider will pick up
183 /// on its own, whether AgentMux put it there or the repository did.
184 /// Copilot is the clearest case — it reads
185 /// `.github/copilot-instructions.md`, `CLAUDE.md` and `GEMINI.md` besides
186 /// the `AGENTS.md` chosen as the write target — and pi reads
187 /// `.pi/SYSTEM.md` as well as the `.pi/APPEND_SYSTEM.md` written to.
188 ///
189 /// Phase 3 of `SPEC_INSTRUCTION_AND_MEMORY_PORTABILITY_2026_09_09.md`
190 /// resolves this set to answer "what will this agent actually read", which
191 /// the write target alone cannot (Codex, PR #3144). Nothing writes these
192 /// paths — tracking is read-only by design, and the ownership protection
193 /// in `SPEC_CLAUDE_MD_OWNERSHIP_PROTECTION_2026_08_22.md` still governs
194 /// the one file AgentMux does write.
195 ///
196 /// **Same evidence rule as the field above: listed only where verified
197 /// against the provider's own docs, never guessed.** Where the only
198 /// confirmed source is the write target, that is the whole list — an
199 /// under-complete list means Phase 3 shows the operator less than the
200 /// truth, which is recoverable; a guessed one means it shows them
201 /// something false, which is not.
202 pub native_instruction_sources: &'static [&'static str],
203 /// Directories a provider scans for instruction files, for the providers
204 /// whose convention is a pattern rather than a fixed path.
205 ///
206 /// Copilot's `.github/instructions/**/*.instructions.md` is the reason
207 /// this exists: those are path-scoped instructions that genuinely reach
208 /// the agent, so a resolver reading only `native_instruction_sources`
209 /// above would produce an incomplete answer for any repository using them
210 /// (Codex, PR #3154), verified in
211 /// `docs/archive/research-cli-context-files-2026-04-23-copilot-verification.md`
212 /// claim 3.
213 ///
214 /// Structured rather than a glob string, because there is no glob engine
215 /// in the tree and one dependency for one pattern shape is a poor trade.
216 /// It also forces the two things a glob leaves implicit — whether to
217 /// descend, and what actually qualifies — to be stated.
218 ///
219 /// Same evidence rule as the two fields above.
220 pub native_instruction_dirs: &'static [InstructionDirScan],
221}
222
223/// A directory a provider reads instruction files out of.
224#[derive(Debug, Clone, Copy)]
225pub struct InstructionDirScan {
226 /// Working-directory-relative, e.g. `".github/instructions"`.
227 pub dir: &'static str,
228 /// Only files ending in this qualify, e.g. `".instructions.md"`.
229 pub suffix: &'static str,
230 /// Whether subdirectories are scanned too — Copilot's `**` says yes.
231 pub recursive: bool,
232}
233
234/// The model a freshly opened pane of this provider starts on, or `None` for a
235/// provider whose model the runtime menu does not wire (it passes no `--model`).
236///
237/// Mirrors the `default: true` row of the frontend catalog
238/// (`frontend/app/view/agent/providers/catalog.ts`), which is where the menu's
239/// default comes from; `providers/runtime-defaults-consistency.test.ts` fails when the two disagree.
240/// srv needs its own copy because `agent.open` builds a pane without going
241/// through the frontend, and a pane opened with no `--model` runs on the CLI's
242/// own default while its menu reads this one.
243pub fn default_model_for(provider_id: &str) -> Option<&'static str> {
244 match provider_id {
245 "claude" => Some("sonnet"),
246 "codex" => Some("gpt-6-astra"),
247 _ => None,
248 }
249}
250
251impl ProviderConfig {
252 /// Return the controller type as the string used in block metadata.
253 pub fn controller_type_str(&self) -> &'static str {
254 match self.controller_type {
255 ControllerType::Persistent => "persistent",
256 ControllerType::Subprocess => "subprocess",
257 ControllerType::Acp => "acp",
258 ControllerType::Msp => "msp",
259 ControllerType::AppServer => "app-server",
260 ControllerType::Terminal => "cmd",
261 }
262 }
263
264 /// Return the provider-specific continuation argv strategy stored in pane
265 /// metadata. Codex uses an `exec resume` subcommand; existing providers
266 /// append their configured flag.
267 pub fn resume_strategy_str(&self) -> &'static str {
268 if self.id == "codex" {
269 "codex-exec"
270 } else if self.resume_flag.is_some() {
271 "flag"
272 } else {
273 "none"
274 }
275 }
276
277 /// Packages installed next to `npm_package`, in the same `npm install` and
278 /// the same pinned dir: `(name, version)`. Pi's adapter (`pi-acp`) runs
279 /// the `pi` CLI, which is its own package (`@earendil-works/...`; the old
280 /// `@mariozechner/...` name stops at 0.73.1).
281 pub fn companion_npm_packages(&self) -> &'static [(&'static str, &'static str)] {
282 match self.id {
283 "pi" => &[("@earendil-works/pi-coding-agent", "1.0.4")],
284 _ => &[],
285 }
286 }
287
288 /// Every `name@version` an install of this provider passes to npm: the
289 /// pinned package (at `pin`, the effective pin) and its companions.
290 pub fn npm_install_specs(&self, pin: &str) -> Vec<String> {
291 let main = if pin.is_empty() {
292 self.npm_package.to_string()
293 } else {
294 format!("{}@{}", self.npm_package, pin)
295 };
296 std::iter::once(main)
297 .chain(self.companion_npm_packages().iter().map(|(n, v)| format!("{n}@{v}")))
298 .collect()
299 }
300
301 /// The flag that passes the prompt as an argument, for a CLI that doesn't
302 /// read it from stdin. No built-in provider needs one now, so the prompt
303 /// goes on stdin for all of them; the spawn path still honours the flag
304 /// stored in pane meta as `agent:prompt_arg_flag` (the frontend's
305 /// `promptArgFlag` mirrors it).
306 pub fn prompt_arg_flag(&self) -> Option<&'static str> {
307 None
308 }
309}
310
311// ─── Provider definitions ────────────────────────────────────────────────────
312//
313// One file per provider under providers/, so adding a provider adds a file.
314
315pub mod claude;
316pub mod codex;
317pub mod gemini;
318pub mod pi;
319pub mod copilot;
320pub mod dsh;
321pub mod grok;
322pub mod muse;
323pub mod opencode;
324
325use claude::CLAUDE;
326use codex::CODEX;
327use gemini::GEMINI;
328use pi::PI;
329use copilot::COPILOT;
330use dsh::DSH;
331use grok::GROK;
332use muse::MUSE;
333use opencode::OPENCODE;
334
335// ─── Static registry ─────────────────────────────────────────────────────────
336
337static REGISTRY: LazyLock<HashMap<&'static str, &'static ProviderConfig>> = LazyLock::new(|| {
338 let mut m = HashMap::new();
339 m.insert(CLAUDE.id, &CLAUDE);
340 m.insert(CODEX.id, &CODEX);
341 m.insert(GEMINI.id, &GEMINI);
342 m.insert(PI.id, &PI);
343 m.insert(COPILOT.id, &COPILOT);
344 m.insert(OPENCODE.id, &OPENCODE);
345 m.insert(GROK.id, &GROK);
346 m.insert(DSH.id, &DSH);
347 m.insert(MUSE.id, &MUSE);
348 m
349});
350
351// Aliases for provider IDs from older databases or alternate naming.
352static ALIASES: LazyLock<HashMap<&'static str, &'static str>> = LazyLock::new(|| {
353 let mut m = HashMap::new();
354 m.insert("claude-code", "claude");
355 m.insert("claude_code", "claude");
356 m.insert("codex-cli", "codex");
357 m.insert("gemini-cli", "gemini");
358 m.insert("copilot-cli", "copilot");
359 m.insert("github-copilot", "copilot");
360 m.insert("copilot_cli", "copilot");
361 m.insert("opencode-ai", "opencode");
362 m.insert("open-code", "opencode");
363 m.insert("grok-build", "grok");
364 m.insert("grok-cli", "grok");
365 m.insert("deepseek-harness", "dsh");
366 m.insert("muse-code", "muse");
367 m
368});
369
370// ─── Public API ──────────────────────────────────────────────────────────────
371
372/// Resolve a provider alias to its canonical ID.
373///
374/// Returns `id` unchanged if it is not a known alias.
375pub fn resolve_provider_alias(id: &str) -> &'static str {
376 ALIASES.get(id).copied().unwrap_or_else(|| {
377 // If the id itself is a canonical key return the interned key, otherwise
378 // return a best-effort static ref. The caller should treat the return
379 // value as a lookup key only.
380 REGISTRY
381 .get_key_value(id)
382 .map(|(k, _)| *k)
383 .unwrap_or("") // unknown — get_provider will return None
384 })
385}
386
387/// Where a PATH-only provider's own installer puts its CLI, for the case
388/// where that folder is not on this process's PATH yet. A provider's
389/// installer adds its folder to the user's PATH, but an AgentMux that is
390/// already running keeps the PATH it started with, so without this the CLI
391/// would read as missing until AgentMux restarts.
392pub fn known_install_paths(provider_id: &str) -> Vec<std::path::PathBuf> {
393 match resolve_provider_alias(provider_id) {
394 "grok" => grok_install_paths(dirs::home_dir()),
395 "muse" => muse_install_paths(
396 std::env::var_os("MUSE_INSTALL_DIR")
397 .or_else(|| std::env::var_os("LOCALAPPDATA").map(|d| std::path::PathBuf::from(d).join("Programs").join("muse").into()))
398 .map(std::path::PathBuf::from),
399 dirs::home_dir(),
400 ),
401 _ => Vec::new(),
402 }
403}
404
405/// A terminal-tier provider's pane (`agent.open`): a terminal running the
406/// CLI's own UI, started at once. The frontend's `TERMINAL_PANE_META` is the same.
407pub fn apply_terminal_pane_meta(provider: &ProviderConfig, meta: &mut crate::backend::obj::MetaMapType) {
408 if provider.controller_type == ControllerType::Terminal {
409 meta.insert("view".to_string(), serde_json::json!("term"));
410 meta.insert("cmd:interactive".to_string(), serde_json::json!(true));
411 meta.insert("cmd:runonstart".to_string(), serde_json::json!(true));
412 }
413}
414
415/// Where xAI's installers put Grok Build: `~/.grok/bin`.
416fn grok_install_paths(home: Option<std::path::PathBuf>) -> Vec<std::path::PathBuf> {
417 let exe = if cfg!(windows) { "grok.exe" } else { "grok" };
418 home.map(|h| h.join(".grok").join("bin").join(exe)).into_iter().collect()
419}
420
421/// Muse Code's native binary, not its launcher: on Windows the launcher is a
422/// `.cmd` a terminal pane can't run, and it would update itself hourly. The
423/// launcher records the version it installed in `.muse-version` beside
424/// `muse-bin-<version>.exe`. Elsewhere the launcher is a script that runs.
425fn muse_install_paths(install_dir: Option<std::path::PathBuf>, home: Option<std::path::PathBuf>) -> Vec<std::path::PathBuf> {
426 if cfg!(windows) {
427 let Some(dir) = install_dir else { return Vec::new() };
428 let Ok(version) = std::fs::read_to_string(dir.join(".muse-version")) else { return Vec::new() };
429 let version = version.trim();
430 if version.is_empty() || version.contains(['/', '\\']) {
431 return Vec::new();
432 }
433 vec![dir.join(format!("muse-bin-{version}.exe"))]
434 } else {
435 home.map(|h| h.join(".local").join("bin").join("muse")).into_iter().collect()
436 }
437}
438
439/// The `pi` installed next to `cmd` when `cmd` is pi-acp, for
440/// `PI_ACP_PI_COMMAND` (blockcontroller/acp.rs) and the auth check (`run_auth_check`). Without it pi-acp runs whatever `pi` is on PATH, often
441/// none (the managed install's `.bin` isn't on PATH) or an older one.
442/// SPEC_PI_HARNESS_VIA_PI_ACP_2026_10_06.md.
443pub fn pi_beside_pi_acp(cmd: &str) -> Option<String> {
444 if !is_pi_acp(cmd) {
445 return None;
446 }
447 let path = std::path::Path::new(cmd);
448 let dir = path.parent()?;
449 let names: &[&str] = if cfg!(windows) { &["pi.cmd", "pi.exe", "pi"] } else { &["pi"] };
450 names
451 .iter()
452 .map(|n| dir.join(n))
453 .find(|p| p.is_file())
454 .map(|p| p.to_string_lossy().into_owned())
455}
456
457/// Whether `cmd` (a path or bare name) is the pi-acp adapter.
458pub fn is_pi_acp(cmd: &str) -> bool {
459 std::path::Path::new(cmd)
460 .file_stem()
461 .is_some_and(|s| s.to_string_lossy().eq_ignore_ascii_case("pi-acp"))
462}
463
464/// A harness AgentMux no longer offers, with the one sentence an agent that used it is told. Such an agent is kept (its
465/// definition and history stay) and does not start; a pane that is still running it is refused at its next turn.
466/// `None` for every provider that is offered. Antigravity: Google's terms do not allow third-party tools on its login,
467/// and an account that does it can be suspended. The nine removed for the beta (Aider, Cline, Crush, Goose, Kilo, Kimi,
468/// MuxCode, OpenClaw, Qwen Code) are narrowed to the harnesses AgentMux keeps working.
469pub fn retired_reason(provider_id: &str) -> Option<&'static str> {
470 match provider_id.trim().to_ascii_lowercase().as_str() {
471 "antigravity" | "agy" | "antigravity-cli" | "antigravity_cli" => Some(RETIRED_ANTIGRAVITY),
472 "aider" | "aider-chat" => Some(RETIRED_AIDER),
473 "cline" | "cline-cli" => Some(RETIRED_CLINE),
474 "crush" | "crush-cli" => Some(RETIRED_CRUSH),
475 "goose" | "goose-cli" => Some(RETIRED_GOOSE),
476 "kilo" | "kilocode" | "kilo-code" => Some(RETIRED_KILO),
477 "kimi" | "kimi-cli" | "kimi_code" => Some(RETIRED_KIMI),
478 "muxcode" | "mux-code" | "mux_code" => Some(RETIRED_MUXCODE),
479 "openclaw" | "openclaw-cli" | "open-claw" => Some(RETIRED_OPENCLAW),
480 "qwen" | "qwen-code" | "qwen3-coder" => Some(RETIRED_QWEN),
481 _ => None,
482 }
483}
484
485/// Why an agent that names `provider_id` cannot start in this build, or `None` when the harness is here. A harness AgentMux
486/// retired gives its own sentence ([`retired_reason`]); any other that is not here (an agent written by a newer AgentMux, or a
487/// harness taken out) says so. Either way the agent is kept with its history, and can be changed to another harness or deleted.
488/// This is the one place a removed harness is said: a harness that is taken out is added to [`retired_reason`], not given a
489/// message of its own.
490pub fn harness_unusable_reason(provider_id: &str) -> Option<String> {
491 if get_provider(provider_id).is_some() {
492 return None;
493 }
494 Some(match retired_reason(provider_id) {
495 Some(why) => why.to_string(),
496 None => format!(
497 "This agent uses the harness '{}', which this version of AgentMux does not have. It is kept as it is, with its history: change it to another harness, or delete it.",
498 provider_id.trim()
499 ),
500 })
501}
502
503/// What a pane that used a retired harness is told, by the output format it was opened with. Panes record that format
504/// at launch (`agentOutputFormat`), so a pane restored from before the harness was removed is recognised without its
505/// definition. Only a format that one harness alone wrote can say so: the formats Aider, Cline, Crush, Goose, Kilo,
506/// MuxCode and OpenClaw wrote (`raw`, `acp`, `claude-stream-json`) are shared with harnesses that are offered.
507pub fn retired_reason_for_output_format(format: &str) -> Option<&'static str> {
508 match format {
509 "agy-stream-json" => Some(RETIRED_ANTIGRAVITY),
510 "kimi-stream-json" => Some(RETIRED_KIMI),
511 "qwen-stream-json" => Some(RETIRED_QWEN),
512 _ => None,
513 }
514}
515
516const RETIRED_ANTIGRAVITY: &str = "Antigravity is no longer available in AgentMux: Google's terms do not allow third-party tools to use its login, so use Gemini with a Google AI Studio or Gemini Enterprise API key, or another harness.";
517const RETIRED_AIDER: &str = "Aider is no longer available in AgentMux: it was removed in this version. Change this agent to another harness, or delete it.";
518const RETIRED_CLINE: &str = "Cline is no longer available in AgentMux: it was removed in this version. Change this agent to another harness, or delete it.";
519const RETIRED_CRUSH: &str = "Crush is no longer available in AgentMux: it was removed in this version. Change this agent to another harness, or delete it.";
520const RETIRED_GOOSE: &str = "Goose is no longer available in AgentMux: it was removed in this version. Change this agent to another harness, or delete it.";
521const RETIRED_KILO: &str = "Kilo is no longer available in AgentMux: it was removed in this version. Change this agent to another harness, or delete it.";
522const RETIRED_KIMI: &str = "Kimi is no longer available in AgentMux: it was removed in this version. Change this agent to another harness, or delete it.";
523const RETIRED_MUXCODE: &str = "MuxCode is no longer available in AgentMux: it was removed in this version. Change this agent to another harness, or delete it.";
524const RETIRED_OPENCLAW: &str = "OpenClaw is no longer available in AgentMux: it was removed in this version. Change this agent to another harness, or delete it.";
525const RETIRED_QWEN: &str = "Qwen Code is no longer available in AgentMux: it was removed in this version. Change this agent to another harness, or delete it.";
526
527/// Look up a provider by canonical ID or alias.
528///
529/// Returns `None` when the ID (and any resolved alias) does not match a known
530/// provider.
531pub fn get_provider(id: &str) -> Option<&'static ProviderConfig> {
532 // Direct lookup first.
533 if let Some(p) = REGISTRY.get(id) {
534 return Some(p);
535 }
536 // Fall back to alias resolution.
537 if let Some(canonical) = ALIASES.get(id).copied() {
538 return REGISTRY.get(canonical).copied();
539 }
540 // A registered custom harness: its id always starts `custom-`, so it never shadows a built-in or an alias.
541 super::providers_custom::get_custom_provider(id)
542}
543
544/// Every registered provider, for callers that must act on all of them
545/// rather than look one up by id — e.g. a migration backfilling
546/// conversation history for every provider that has a linkable native
547/// history directory ([`ProviderConfig::history_native_subdir`]), so a
548/// future provider gains that behavior automatically instead of needing
549/// a follow-up patch to an id list maintained elsewhere.
550pub fn all_providers() -> impl Iterator<Item = &'static ProviderConfig> {
551 REGISTRY.values().copied()
552}
553
554/// True when `dir` resolves to `provider`'s literal ambient home directory
555/// (e.g. `~/.claude` for Claude Code) rather than an AgentMux-isolated dir.
556/// Used to block identity bindings/spawns from ever pointing a spawned
557/// agent at the operator's own global CLI login — a real, currently-live
558/// instance of exactly this was found in this repo's own data (an account's
559/// `secret_ref.dir` set to the literal ambient path — see
560/// `docs/status/STATUS_IDENTITY_ISOLATION_GATE_NOT_ENFORCING_2026_08_20.md`
561/// §8), which nothing in the codebase previously validated against. See
562/// `docs/specs/SPEC_BLOCK_AMBIENT_HOME_DIR_IDENTITY_BINDING_2026_08_25.md`.
563///
564/// Canonicalizes both sides when possible (defeats `..`, symlink, and
565/// Windows `\\?\`-prefix tricks — same approach `identity::cleanup`'s
566/// containment check already uses); falls back to a normalized lexical
567/// comparison when either path doesn't exist yet on disk (e.g. validating a
568/// not-yet-materialized dir at account-creation time), so a not-yet-created
569/// ambient path can't slip past the guard just by not existing at check
570/// time.
571pub fn is_provider_ambient_home_dir(provider: &ProviderConfig, dir: &str) -> bool {
572 let ambient = crate::backend::base::get_home_dir().join(format!(".{}", provider.auth_dir_name));
573 paths_resolve_to_same_dir(&ambient, dir)
574}
575
576/// Placeholder written by `seed_claude_md_placeholder_if_missing` — explains
577/// itself so an operator who opens the file isn't confused by an unexplained
578/// empty one.
579const CLAUDE_MD_ISOLATION_PLACEHOLDER: &str = "<!--\n\
580AgentMux: intentionally empty.\n\
581\n\
582This is an isolated Claude Code config directory (CLAUDE_CONFIG_DIR),\n\
583separate from your personal ~/.claude/CLAUDE.md, so this agent never\n\
584silently inherits your personal global instructions. To give every\n\
585agent shared instructions, use Memory -> Global instead --\n\
586those compose into this agent's own project-level CLAUDE.md at launch,\n\
587not this file. See SPEC_ISOLATE_HOST_CLAUDE_MD_2026_08_31.md.\n\
588-->\n";
589
590/// Seeds an empty placeholder `CLAUDE.md` into an isolated Claude Code
591/// `CLAUDE_CONFIG_DIR` the first time it's used, so Claude Code CLI's own
592/// user-level `CLAUDE.md` discovery always finds *something* there instead
593/// of silently falling through to the operator's real
594/// `$HOME/.claude/CLAUDE.md`. `CLAUDE_CONFIG_DIR` relocates credential/
595/// session/project storage but AgentMux never wrote a `CLAUDE.md` into the
596/// relocated dir — verified live on a real machine: 18+ isolated `claude`
597/// config dirs, none with a `CLAUDE.md`, and a session whose
598/// `CLAUDE_CONFIG_DIR` was a genuinely separate (non-ambient) dir still
599/// received the real host file's contents. See
600/// `docs/specs/SPEC_ISOLATE_HOST_CLAUDE_MD_2026_08_31.md`.
601///
602/// Scoped to the `claude` provider only (`auth_dir_name == "claude"`) —
603/// this is a Claude Code CLI-specific fallback behavior; whether any other
604/// provider's CLI has an equivalent gap is unverified. Never overwrites an
605/// existing `CLAUDE.md` — Global Bundle (or anything else) may have
606/// legitimately placed real content at that path. Returns `Ok(true)` only
607/// when it actually wrote the placeholder.
608pub fn seed_claude_md_placeholder_if_missing(
609 provider: &ProviderConfig,
610 config_dir: &str,
611) -> std::io::Result<bool> {
612 if provider.auth_dir_name != "claude" {
613 return Ok(false);
614 }
615 // Codex P2 on PR #2854: a blank config_dir would resolve
616 // `Path::new("").join("CLAUDE.md")` relative to the server process's
617 // own CWD (`create_dir_all("")` succeeds, silently no-op) instead of
618 // erroring — writing an unrelated file while leaving the actual
619 // (empty-string) CLAUDE_CONFIG_DIR still exposed to ambient fallback.
620 // Reject before touching the filesystem so the caller's fail-closed
621 // handling (both call sites now block spawn on any Err here) covers
622 // this case too, rather than silently succeeding at nothing.
623 if config_dir.trim().is_empty() {
624 return Err(std::io::Error::new(
625 std::io::ErrorKind::InvalidInput,
626 "config_dir is empty",
627 ));
628 }
629 let path = std::path::Path::new(config_dir).join("CLAUDE.md");
630 if path.exists() {
631 return Ok(false);
632 }
633 std::fs::create_dir_all(config_dir)?;
634 std::fs::write(&path, CLAUDE_MD_ISOLATION_PLACEHOLDER)?;
635 Ok(true)
636}
637
638/// Days Claude Code keeps session transcripts in an AgentMux-owned config dir:
639/// forever. 36500 days (100 years) is the most Claude Code accepts, and larger
640/// values are rejected. Never 0, which deletes a transcript when its session ends.
641pub const CLAUDE_TRANSCRIPT_RETENTION_DAYS: u32 = 36_500;
642
643/// What AgentMux seeded before history was kept forever. Found in a config dir,
644/// it is AgentMux's own old value rather than a choice, so it is raised.
645const SUPERSEDED_TRANSCRIPT_RETENTION_DAYS: u64 = 180;
646
647/// Days added to the idle limit for Claude's own sweep, so it is only a backstop
648/// that fires after AgentMux's own proven removal would have run
649/// (`docs/specs/SPEC_HISTORY_COMPACT_FORM_ONLY_2026_11_23.md` section 5.5).
650const TRANSCRIPT_RETENTION_BACKSTOP_DAYS: u32 = 30;
651/// The sidecar key that records the retention AgentMux last wrote.
652const RETENTION_KEY: &str = "cleanupPeriodDays";
653
654/// The `cleanupPeriodDays` AgentMux seeds, from the live settings.
655///
656/// The flag is `history:sessionfilesweep`, which stays off until the history
657/// migration has proved every session and turns it on. Off: 36500, Claude's
658/// sweep never deletes. On: the idle limit + 30 days (31 to 60), so the sweep is a
659/// backstop behind AgentMux's own removal. Lowering it earlier would let the
660/// sweep delete files the store does not yet hold.
661pub fn transcript_retention_days(extra: &std::collections::HashMap<String, serde_json::Value>) -> u32 {
662 let policy = crate::backend::provider_sessions::Policy::from_extra(extra);
663 if policy.enabled {
664 policy.idle_days + TRANSCRIPT_RETENTION_BACKSTOP_DAYS
665 } else {
666 CLAUDE_TRANSCRIPT_RETENTION_DAYS
667 }
668}
669
670fn live_transcript_retention_days() -> u32 {
671 CONFIG.get().map_or(CLAUDE_TRANSCRIPT_RETENTION_DAYS, |c| transcript_retention_days(&c.get_settings().extra))
672}
673
674/// Seeds `cleanupPeriodDays` into an isolated Claude Code config dir's
675/// `settings.json` when it isn't set. Claude Code's default is 30 days, and
676/// its startup sweep deletes transcripts under `<config_dir>/projects`, which
677/// AgentMux junctions to the account's shared history — so any channel that
678/// launched an agent without this setting deleted every channel's month-old
679/// conversations, leaving `--resume` nothing to find.
680///
681/// The value is [`transcript_retention_days`] now. Claude only. Leaves an
682/// explicit `cleanupPeriodDays` alone, except values AgentMux itself wrote: the
683/// 180 and the 36500 it used to seed, and the last value it recorded in
684/// [`SEEDED_SIDECAR`], which follows the idle limit. Never rewrites a
685/// `settings.json` it can't parse as a JSON object. Callers must only pass a dir
686/// already confirmed not to be the operator's ambient home. Returns `Ok(true)`
687/// only when it wrote the setting.
688pub fn seed_transcript_retention_if_missing(
689 provider: &ProviderConfig,
690 config_dir: &str,
691) -> std::io::Result<bool> {
692 seed_transcript_retention(provider, config_dir, live_transcript_retention_days())
693}
694
695fn seed_transcript_retention(provider: &ProviderConfig, config_dir: &str, days: u32) -> std::io::Result<bool> {
696 if provider.auth_dir_name != "claude" {
697 return Ok(false);
698 }
699 if config_dir.trim().is_empty() {
700 return Err(std::io::Error::new(
701 std::io::ErrorKind::InvalidInput,
702 "config_dir is empty",
703 ));
704 }
705 let dir = std::path::Path::new(config_dir);
706 let path = dir.join("settings.json");
707 let mut settings = match std::fs::read_to_string(&path) {
708 Ok(text) => match serde_json::from_str::<serde_json::Value>(&text) {
709 Ok(serde_json::Value::Object(map)) => map,
710 _ => return Ok(false),
711 },
712 Err(e) if e.kind() == std::io::ErrorKind::NotFound => serde_json::Map::new(),
713 Err(e) => return Err(e),
714 };
715 let desired = u64::from(days);
716 let current = settings.get(RETENTION_KEY);
717 if let Some(v) = current {
718 let recorded = read_sidecar(dir).get(RETENTION_KEY).and_then(serde_json::Value::as_u64);
719 let ours = v.as_u64().is_some_and(|n| {
720 n == SUPERSEDED_TRANSCRIPT_RETENTION_DAYS || n == u64::from(CLAUDE_TRANSCRIPT_RETENTION_DAYS) || Some(n) == recorded
721 });
722 if !ours || v.as_u64() == Some(desired) {
723 return Ok(false);
724 }
725 }
726 settings.insert(RETENTION_KEY.to_string(), serde_json::json!(desired));
727 std::fs::create_dir_all(config_dir)?;
728 write_json_atomically(&path, &serde_json::Value::Object(settings))?;
729 // Only the new, shorter values are recorded: 36500 is told from a choice by its number.
730 set_sidecar_key(dir, RETENTION_KEY, (days != CLAUDE_TRANSCRIPT_RETENTION_DAYS).then_some(desired))?;
731 Ok(true)
732}
733
734/// `agent:compactat`: the context size, in tokens, at which Claude agents
735/// auto-compact. `0` leaves Claude Code's own point (the window minus 33K,
736/// about 967K on a 1M window). `docs/specs/SPEC_AGENT_SELF_COMPACTION_2026_10_23.md` §3.1.
737pub const SETTING_COMPACT_AT: &str = "agent:compactat";
738pub const DEFAULT_COMPACT_AT: u64 = 600_000;
739/// Claude Code compacts at its auto-compact window minus this much.
740const AUTO_COMPACT_MARGIN: u64 = 33_000;
741/// The range Claude Code accepts for `autoCompactWindow`.
742const AUTO_COMPACT_WINDOW_RANGE: (u64, u64) = (100_000, 1_000_000);
743/// The value applied by hand on every host on 2026-10-23, before this setting
744/// existed: AgentMux's own, so the setting may move it.
745const HAND_APPLIED_AUTO_COMPACT_WINDOW: u64 = 633_000;
746const AUTO_COMPACT_WINDOW_KEY: &str = "autoCompactWindow";
747/// What AgentMux last wrote into a config dir's `settings.json`, so a value it
748/// wrote can follow the setting while one a person chose is left alone.
749const SEEDED_SIDECAR: &str = ".agentmux-seeded.json";
750
751static CONFIG: std::sync::OnceLock<std::sync::Arc<crate::backend::wconfig::ConfigState>> = std::sync::OnceLock::new();
752
753/// Attach the live settings (bootstrap), so [`SETTING_COMPACT_AT`] can be read.
754pub fn install_config(config: std::sync::Arc<crate::backend::wconfig::ConfigState>) {
755 let _ = CONFIG.set(config);
756}
757
758/// A string setting now, when it is set and not empty.
759pub fn live_setting_str(key: &str) -> Option<String> {
760 let value = CONFIG.get()?.get_settings().extra.get(key)?.as_str()?.trim().to_string();
761 (!value.is_empty()).then_some(value)
762}
763
764/// `cli:usepath`: the ids of the providers whose CLI is the person's own copy on
765/// PATH, not AgentMux's (SPEC_ISOLATED_INSTALL_FOR_NON_NPM_CLIS_2026_11_05.md §3).
766pub const SETTING_USE_PATH: &str = "cli:usepath";
767
768/// `provider_id` is listed in [`SETTING_USE_PATH`] now. Absent: AgentMux's copy.
769pub fn uses_path_cli(provider_id: &str) -> bool {
770 CONFIG.get().is_some_and(|c| path_listed(&c.get_settings().extra, provider_id))
771}
772
773fn path_listed(extra: &std::collections::HashMap<String, serde_json::Value>, provider_id: &str) -> bool {
774 let ids = extra.get(SETTING_USE_PATH).and_then(serde_json::Value::as_array);
775 ids.is_some_and(|ids| ids.iter().any(|id| id.as_str() == Some(provider_id)))
776}
777
778/// [`SETTING_COMPACT_AT`] now, or its default.
779pub fn compact_at_setting() -> u64 {
780 CONFIG.get().and_then(|c| c.extra_u64(SETTING_COMPACT_AT)).unwrap_or(DEFAULT_COMPACT_AT)
781}
782
783/// The `autoCompactWindow` that makes Claude Code compact at `compact_at`
784/// tokens, clamped to the range it accepts; `None` for `0`, which leaves
785/// Claude Code's own.
786pub fn auto_compact_window(compact_at: u64) -> Option<u64> {
787 (compact_at > 0).then(|| (compact_at + AUTO_COMPACT_MARGIN).clamp(AUTO_COMPACT_WINDOW_RANGE.0, AUTO_COMPACT_WINDOW_RANGE.1))
788}
789
790/// Seeds Claude Code's `autoCompactWindow` into a config dir's
791/// `settings.json` from [`SETTING_COMPACT_AT`] (`compact_at`), so agents
792/// compact at that size instead of near a full 1M window.
793///
794/// Writes it when absent, or when the present value is AgentMux's own (the
795/// one recorded in [`SEEDED_SIDECAR`], or 633,000 with no sidecar); any other
796/// value is a person's choice and is left alone. `compact_at` 0 removes
797/// AgentMux's own value. Claude only; never rewrites a `settings.json` it
798/// can't parse as a JSON object. Returns `Ok(true)` only when it wrote.
799pub fn seed_auto_compact_window(provider: &ProviderConfig, config_dir: &str, compact_at: u64) -> std::io::Result<bool> {
800 if provider.auth_dir_name != "claude" {
801 return Ok(false);
802 }
803 if config_dir.trim().is_empty() {
804 return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "config_dir is empty"));
805 }
806 let dir = std::path::Path::new(config_dir);
807 let path = dir.join("settings.json");
808 let mut settings = match std::fs::read_to_string(&path) {
809 Ok(text) => match serde_json::from_str::<serde_json::Value>(&text) {
810 Ok(serde_json::Value::Object(map)) => map,
811 _ => return Ok(false),
812 },
813 Err(e) if e.kind() == std::io::ErrorKind::NotFound => serde_json::Map::new(),
814 Err(e) => return Err(e),
815 };
816 let seeded = read_sidecar(dir).get(AUTO_COMPACT_WINDOW_KEY).and_then(serde_json::Value::as_u64);
817 let current = settings.get(AUTO_COMPACT_WINDOW_KEY);
818 let ours = match current {
819 None => true,
820 Some(v) => v.as_u64().is_some_and(|n| Some(n) == seeded || (seeded.is_none() && n == HAND_APPLIED_AUTO_COMPACT_WINDOW)),
821 };
822 if !ours {
823 return Ok(false);
824 }
825 let current = current.and_then(serde_json::Value::as_u64);
826 let desired = auto_compact_window(compact_at);
827 if current == desired && seeded == desired {
828 return Ok(false);
829 }
830 match desired {
831 Some(window) => {
832 settings.insert(AUTO_COMPACT_WINDOW_KEY.to_string(), serde_json::json!(window));
833 write_json_atomically(&path, &serde_json::Value::Object(settings))?;
834 set_sidecar_key(dir, AUTO_COMPACT_WINDOW_KEY, Some(window))?;
835 Ok(true)
836 }
837 None => {
838 let _ = set_sidecar_key(dir, AUTO_COMPACT_WINDOW_KEY, None);
839 if current.is_none() {
840 return Ok(false);
841 }
842 settings.remove(AUTO_COMPACT_WINDOW_KEY);
843 write_json_atomically(&path, &serde_json::Value::Object(settings))?;
844 Ok(true)
845 }
846 }
847}
848
849/// What AgentMux last wrote into `dir`'s [`SEEDED_SIDECAR`]; empty when there is none.
850fn read_sidecar(dir: &std::path::Path) -> serde_json::Map<String, serde_json::Value> {
851 match std::fs::read_to_string(dir.join(SEEDED_SIDECAR)).ok().and_then(|t| serde_json::from_str(&t).ok()) {
852 Some(serde_json::Value::Object(map)) => map,
853 _ => serde_json::Map::new(),
854 }
855}
856
857/// Records (`Some`) or forgets (`None`) one key in the sidecar, keeping the others. The file goes when the last key does.
858fn set_sidecar_key(dir: &std::path::Path, key: &str, value: Option<u64>) -> std::io::Result<()> {
859 let mut record = read_sidecar(dir);
860 match value {
861 Some(v) => record.insert(key.to_string(), serde_json::json!(v)),
862 None => record.remove(key),
863 };
864 let path = dir.join(SEEDED_SIDECAR);
865 if record.is_empty() {
866 return match std::fs::remove_file(&path) {
867 Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
868 _ => Ok(()),
869 };
870 }
871 write_json_atomically(&path, &serde_json::Value::Object(record))
872}
873
874fn write_json_atomically(path: &std::path::Path, value: &serde_json::Value) -> std::io::Result<()> {
875 let body = serde_json::to_string_pretty(value).map_err(std::io::Error::other)?;
876 if let Some(parent) = path.parent() {
877 std::fs::create_dir_all(parent)?;
878 }
879 let tmp = path.with_extension("json.agentmux-tmp");
880 std::fs::write(&tmp, body)?;
881 std::fs::rename(&tmp, path)
882}
883
884/// Seeds every Claude setting AgentMux manages into `config_dir`'s
885/// `settings.json`: transcript retention and the auto-compact window, and
886/// the Explore sub-agent's model. Each
887/// soft-fails on its own; returns what couldn't be written, and why.
888pub fn seed_managed_claude_settings(provider: &ProviderConfig, config_dir: &str) -> Vec<(&'static str, std::io::Error)> {
889 let mut failed = Vec::new();
890 if let Err(e) = seed_transcript_retention_if_missing(provider, config_dir) {
891 // Claude Code's 30-day default would sweep the account's shared history.
892 failed.push(("transcript retention", e));
893 }
894 if let Err(e) = seed_auto_compact_window(provider, config_dir, compact_at_setting()) {
895 failed.push(("the auto-compact window", e));
896 }
897 if provider.auth_dir_name == "claude" {
898 if let Err(e) = crate::backend::subagent_model::seed_explore_agent(config_dir, crate::backend::subagent_model::explore_model().as_deref()) {
899 failed.push(("the Explore sub-agent's model", e));
900 }
901 }
902 failed
903}
904
905/// `provider`'s DEFAULT auth/config dir: `~/.agentmux/shared/providers/<auth_dir_name>/`
906/// — account-wide and version/channel-independent, so one login is shared by
907/// every instance (the structural fix for the per-channel validate-spin
908/// regression). A per-account auth dir (identity_handlers) still wins
909/// for explicit multi-account. Shared by agent open and `provider.ensureauthdir`.
910pub fn default_auth_dir(provider: &ProviderConfig) -> Result<String, String> {
911 if let Some(paths) = agentmux_common::DataPaths::from_env() {
912 return Ok(paths.provider_auth_dir(provider.auth_dir_name).to_string_lossy().into_owned());
913 }
914 let home = std::env::var("HOME")
915 .or_else(|_| std::env::var("USERPROFILE"))
916 .map_err(|_| "cannot determine home directory".to_string())?;
917 Ok(format!("{}/.agentmux/shared/providers/{}", home, provider.auth_dir_name))
918}
919
920/// Prepare an isolated provider auth/config directory for use as
921/// `CLAUDE_CONFIG_DIR` (or a provider's equivalent): create it, then apply
922/// every isolation guarantee that directory needs before a CLI is pointed
923/// at it.
924///
925/// Exists so callers cannot obtain a usable auth dir WITHOUT its isolation
926/// guarantees — the spawn paths call this instead of `create_dir_all` +
927/// a separately-skippable seed step. Deleting the isolation from a spawn
928/// path now means deleting the directory preparation too, which fails
929/// loudly instead of silently reopening the leak. See
930/// `docs/specs/SPEC_ISOLATE_HOST_CLAUDE_MD_2026_08_31.md` and
931/// `docs/reports/REPORT_CLAUDE_CONFIG_DIR_ISOLATION_EVIDENCE_2026_09_01.md`
932/// (the live three-arm experiment proving the leak is real and this closes
933/// it).
934pub fn prepare_provider_auth_dir(
935 provider: &ProviderConfig,
936 auth_dir: &str,
937) -> std::io::Result<()> {
938 if auth_dir.trim().is_empty() {
939 return Err(std::io::Error::new(
940 std::io::ErrorKind::InvalidInput,
941 "auth_dir is empty",
942 ));
943 }
944 std::fs::create_dir_all(auth_dir)?;
945 seed_claude_md_placeholder_if_missing(provider, auth_dir)?;
946 for (what, e) in seed_managed_claude_settings(provider, auth_dir) {
947 tracing::warn!(auth_dir, error = %e, "could not set Claude's {what}");
948 }
949 Ok(())
950}
951
952/// The actual comparison, split out with the reference side pre-resolved
953/// (not calling `get_home_dir()` internally) so it's directly testable
954/// against a tempdir instead of the real `$HOME`/`%USERPROFILE%` — same
955/// "inject the path, don't resolve it internally" pattern
956/// `read_claude_global_config` already uses (`agent_handlers/bundle.rs`).
957fn paths_resolve_to_same_dir(reference: &std::path::Path, candidate: &str) -> bool {
958 let candidate_path = std::path::Path::new(candidate);
959
960 if let (Ok(canon_reference), Ok(canon_candidate)) =
961 (std::fs::canonicalize(reference), std::fs::canonicalize(candidate_path))
962 {
963 return canon_reference == canon_candidate;
964 }
965
966 normalize_path_lexically(reference) == normalize_path_lexically(candidate_path)
967}
968
969/// Lexically normalizes a path with NO filesystem access (unlike
970/// `canonicalize`, safe to call on a path that doesn't exist). Collapses
971/// `.` and `..` components (codex P1, PR #2802: without this, a not-yet-
972/// created dir like `$HOME/.claude/.` compared unequal to `$HOME/.claude`
973/// under plain string comparison, bypassing the guard entirely on a fresh
974/// machine — a `..` segment is normalized the same way for the same
975/// reason). Never pops past a root/prefix/leading `..` — a leading `..`
976/// with nothing to cancel stays literal, standard lexical-normalization
977/// semantics.
978fn normalize_path_lexically(p: &std::path::Path) -> String {
979 use std::path::Component;
980
981 let mut normalized: Vec<Component> = Vec::new();
982 for component in p.components() {
983 match component {
984 Component::CurDir => {}
985 Component::ParentDir => {
986 if matches!(normalized.last(), Some(Component::Normal(_))) {
987 normalized.pop();
988 } else {
989 normalized.push(component);
990 }
991 }
992 other => normalized.push(other),
993 }
994 }
995 let joined: std::path::PathBuf = normalized.into_iter().collect();
996 let as_str = joined.to_string_lossy().replace('\\', "/");
997 let trimmed = as_str.trim_end_matches('/');
998
999 // codex P2, PR #2802: case-fold only on platforms whose default
1000 // filesystem is case-insensitive (Windows, macOS). Unconditionally
1001 // lowercasing made a not-yet-created `$HOME/.CLAUDE` compare equal to
1002 // `$HOME/.claude` on Linux (case-sensitive ext4) — once both existed,
1003 // canonicalize would correctly tell them apart, so the guard's
1004 // verdict depended on creation order instead of being deterministic.
1005 if cfg!(target_os = "windows") || cfg!(target_os = "macos") {
1006 trimmed.to_lowercase()
1007 } else {
1008 trimmed.to_string()
1009 }
1010}
1011
1012/// Whether `path` matches ANY registered provider's
1013/// `startup_instructions_filename` — used by the "click Launch" RPC write
1014/// path (`editor_handlers.rs`'s `WriteAgentConfig` handler), which receives
1015/// an already-built file list from the frontend with no accompanying
1016/// provider ID, so it can't otherwise tell "this is the startup
1017/// instructions file" from "this is some other config file" without either
1018/// re-deriving the mapping itself (drift risk) or checking membership here
1019/// (single source of truth). See
1020/// docs/specs/SPEC_PROVIDER_AWARE_STARTUP_INSTRUCTIONS_2026_08_24.md §3.
1021pub fn is_known_startup_instructions_filename(path: &str) -> bool {
1022 REGISTRY
1023 .values()
1024 .any(|p| p.startup_instructions_filename == Some(path))
1025}
1026
1027// ─── Tests ───────────────────────────────────────────────────────────────────
1028
1029#[cfg(test)]
1030mod tests;
1031
1032#[cfg(test)]
1033mod native_instruction_sources_tests;