Skip to main content

rpi_cli/
config.rs

1//! # Layout
2//!
3//! Uses a nested layout: a `~/.rpi/agent/` directory (or one pointed at via
4//! `RPI_CODING_AGENT_DIR`) "just works":
5//!
6//! ```text
7//! ~/.rpi/                 (RPI_CODING_AGENT_DIR env overrides the agent/ dir)
8//! └── agent/
9//!     ├── auth.json       # persisted credentials (mode 0o600 on Unix)
10//!     ├── models.json     # user-defined provider/model catalog (hand-edited)
11//!     ├── settings.json   # saved default provider/model/thinking + theme
12//!     ├── trust.json      # per-cwd project trust decisions (read-only parity)
13//!     ├── .setup_done     # first-time-setup sentinel (extras.rs)
14//! ```
15//!
16//! Flat-installed `~/.rpi/{auth.json,models.json}` from older rpi releases are
17//! migrated under `agent/` on the next launch by [`migrate_legacy_layout`]
18//! (best-effort, idempotent; only when the env override is unset).
19//!
20//! # Concurrency
21//!
22//! v1 is a single-process CLI, so we use **atomic rename** instead of upstream's
23//! `proper-lockfile`: write a sibling temp file, `fs::rename` over the target,
24//! then `chmod 0o600` on Unix (Windows chmod is a no-op, matching Node).
25//! Within one process, auth.json read-modify-write updates (upsert and delete)
26//! run under a short in-memory lock, so concurrent provider renewals cannot
27//! drop each other's entries. Across processes, two `rpi auth login` runs from
28//! two shells could still lose one update — that's accepted and documented;
29//! adding a file lock is deferred.
30//!
31//! # Config-value expansion
32//!
33//! [`resolve_config_value`] expands `$ENV`/`${ENV}`/`!command` inside
34//! `apiKey`/`headers` exactly like upstream's `resolve-config-value.ts` — so a
35//! copied pi `models.json`/`auth.json` that references env vars or shell
36//! commands resolves the same way. Applied where rpi consumes those values
37//! (auth.json key, models.json bearer apiKey, provider/model `headers`).
38
39use std::collections::BTreeMap;
40use std::io::Write;
41use std::path::{Path, PathBuf};
42
43use rpi_ai::Model;
44#[cfg(test)]
45use rpi_ai::{Api, ModelCost, StreamingProtocolCompat};
46pub use rpi_runtime::config::{
47    default_anthropic_base_url, model_compat_warnings, provider_is_anthropic_compatible,
48    provider_is_openai_completions, provider_is_openai_responses, AuthStore, ConfigError,
49    Credential, ModelDefinition, ModelsConfig, ProviderConfig, ANTHROPIC_DEFAULT_BASE_URL,
50};
51
52/// The config directory name under the home dir.
53pub const CONFIG_DIR_NAME: &str = ".rpi";
54
55/// Env var that overrides the whole config dir. Absolute path; relative
56/// values are rejected.
57pub const CONFIG_DIR_ENV: &str = "RPI_CODING_AGENT_DIR";
58
59/// The provider id under which `rpi auth login` stores the Anthropic key.
60/// Mirrors upstream's fixed `anthropic` provider id.
61pub use rpi_runtime::config::DEFAULT_PROVIDER_ID;
62
63// ---------------------------------------------------------------------------
64// Path resolution
65// ---------------------------------------------------------------------------
66
67/// The rpi config directory (`~/.rpi/agent` by default, `RPI_CODING_AGENT_DIR`
68/// override). Creates nothing — purely a path computation. The `agent/` layer
69/// is `join(homedir(), CONFIG_DIR_NAME, "agent")`. The env override points at
70/// the agent dir itself.
71pub fn agent_dir() -> Result<PathBuf, ConfigError> {
72    agent_dir_at(None)
73}
74
75/// Resolve the agent home for one harness: an explicit `--agent-dir` wins,
76/// otherwise the historical `RPI_CODING_AGENT_DIR` / `~/.rpi/agent` path.
77/// Relative overrides are rejected (same rule as the env var).
78pub(crate) fn agent_dir_at(override_dir: Option<&Path>) -> Result<PathBuf, ConfigError> {
79    if let Some(dir) = override_dir {
80        if !dir.is_absolute() {
81            return Err(ConfigError::RelativeOverride {
82                env: "--agent-dir",
83                val: dir.to_string_lossy().into_owned(),
84            });
85        }
86        return Ok(dir.to_path_buf());
87    }
88    if let Some(val) = std::env::var_os(CONFIG_DIR_ENV) {
89        let p = PathBuf::from(&val);
90        if !p.is_absolute() {
91            return Err(ConfigError::RelativeOverride {
92                env: CONFIG_DIR_ENV,
93                val: val.to_string_lossy().into_owned(),
94            });
95        }
96        return Ok(p);
97    }
98    let home = dirs::home_dir().ok_or(ConfigError::NoHomeDir {
99        env: CONFIG_DIR_ENV,
100    })?;
101    Ok(home.join(CONFIG_DIR_NAME).join("agent"))
102}
103
104/// One session's agent home.
105///
106/// `explicit = Some(path)` is the library-embedding mode: every reader and
107/// writer is addressed through this value, so several harnesses can live in one
108/// process with different homes. CLI sessions use [`AgentHome::process`], which
109/// preserves the historical `RPI_CODING_AGENT_DIR` / `~/.rpi/agent` behavior.
110#[derive(Clone, Debug, Default, PartialEq, Eq)]
111pub struct AgentHome {
112    explicit: Option<PathBuf>,
113}
114
115impl AgentHome {
116    /// The historical process home (`RPI_CODING_AGENT_DIR` / `~/.rpi/agent`).
117    pub fn process() -> Self {
118        Self::default()
119    }
120
121    pub fn from_option(explicit: Option<PathBuf>) -> Self {
122        Self { explicit }
123    }
124
125    pub fn explicit_path(&self) -> Option<&Path> {
126        self.explicit.as_deref()
127    }
128
129    pub fn is_explicit(&self) -> bool {
130        self.explicit.is_some()
131    }
132
133    pub fn root(&self) -> Result<PathBuf, ConfigError> {
134        agent_dir_at(self.explicit_path())
135    }
136
137    pub fn auth_path(&self) -> Result<PathBuf, ConfigError> {
138        Ok(self.root()?.join("auth.json"))
139    }
140
141    pub fn models_path(&self) -> Result<PathBuf, ConfigError> {
142        Ok(self.root()?.join("models.json"))
143    }
144
145    pub fn settings_path(&self) -> Result<PathBuf, ConfigError> {
146        Ok(self.root()?.join("settings.json"))
147    }
148
149    pub fn trust_path(&self) -> Result<PathBuf, ConfigError> {
150        Ok(self.root()?.join("trust.json"))
151    }
152
153    pub fn read_auth(&self) -> Result<AuthStore, ConfigError> {
154        read_auth_at(self.explicit_path())
155    }
156
157    pub fn write_auth(&self, store: &AuthStore) -> Result<(), ConfigError> {
158        write_auth_at(self.explicit_path(), store)
159    }
160
161    pub fn upsert_credential(
162        &self,
163        provider_id: &str,
164        cred: Credential,
165    ) -> Result<(), ConfigError> {
166        upsert_credential_at(self.explicit_path(), provider_id, cred)
167    }
168
169    pub fn upsert_oauth_token(
170        &self,
171        provider_id: &str,
172        access: String,
173        refresh: String,
174        expires: i64,
175    ) -> Result<(), ConfigError> {
176        upsert_oauth_token_at(self.explicit_path(), provider_id, access, refresh, expires)
177    }
178
179    pub fn replace_oauth_token_if_unchanged(
180        &self,
181        provider_id: &str,
182        expected: (&str, &str, i64),
183        access: String,
184        refresh: String,
185        expires: i64,
186    ) -> Result<bool, ConfigError> {
187        replace_oauth_token_if_unchanged_at(
188            self.explicit_path(),
189            provider_id,
190            expected,
191            access,
192            refresh,
193            expires,
194        )
195    }
196
197    pub fn read_oauth_token(&self, provider_id: &str) -> Result<Option<Credential>, ConfigError> {
198        read_oauth_token_at(self.explicit_path(), provider_id)
199    }
200
201    pub fn delete_credential(&self, provider_id: &str) -> Result<bool, ConfigError> {
202        delete_credential_at(self.explicit_path(), provider_id)
203    }
204
205    pub fn models_config(&self) -> Result<ModelsConfig, ConfigError> {
206        load_models_config_at(self.explicit_path())
207    }
208
209    pub fn save_models_config(&self, cfg: &ModelsConfig) -> Result<(), ConfigError> {
210        save_models_config_at(self.explicit_path(), cfg)
211    }
212
213    #[allow(clippy::too_many_arguments)]
214    pub fn add_provider(
215        &self,
216        provider_id: &str,
217        api: &str,
218        base_url: &str,
219        api_key: &str,
220        model_id: &str,
221        model_name: Option<&str>,
222        context_window: Option<u64>,
223        max_tokens: Option<u64>,
224        supports_images: Option<bool>,
225    ) -> Result<(), String> {
226        add_provider_at(
227            self.explicit_path(),
228            provider_id,
229            api,
230            base_url,
231            api_key,
232            model_id,
233            model_name,
234            context_window,
235            max_tokens,
236            supports_images,
237        )
238    }
239
240    #[allow(clippy::too_many_arguments)]
241    pub fn update_provider(
242        &self,
243        provider_id: &str,
244        api: &str,
245        base_url: &str,
246        api_key: Option<&str>,
247        model_id: &str,
248        model_name: Option<&str>,
249        context_window: Option<u64>,
250        max_tokens: Option<u64>,
251        supports_images: bool,
252    ) -> Result<(), String> {
253        update_provider_at(
254            self.explicit_path(),
255            provider_id,
256            api,
257            base_url,
258            api_key,
259            model_id,
260            model_name,
261            context_window,
262            max_tokens,
263            supports_images,
264        )
265    }
266
267    pub fn delete_provider(&self, provider_id: &str) -> Result<(), String> {
268        delete_provider_at(self.explicit_path(), provider_id)
269    }
270
271    pub fn read_trust(&self) -> Result<TrustStore, ConfigError> {
272        read_trust_at(self.explicit_path())
273    }
274
275    pub fn project_trust_decision(&self, cwd: &Path) -> Result<Option<bool>, ConfigError> {
276        project_trust_decision_at(self.explicit_path(), cwd)
277    }
278
279    pub fn set_project_trust(&self, cwd: &Path, trusted: Option<bool>) -> Result<(), ConfigError> {
280        set_project_trust_at(self.explicit_path(), cwd, trusted)
281    }
282}
283
284/// The config dir one level above the agent dir (`~/.rpi`, or the parent of an
285/// env override). Used by [`migrate_legacy_layout`] to locate the old flat
286/// layout. Returns `None` when the env override has no parent (a root path).
287fn config_root_dir() -> Result<PathBuf, ConfigError> {
288    let agent = agent_dir()?;
289    agent
290        .parent()
291        .map(Path::to_path_buf)
292        .ok_or(ConfigError::NoHomeDir {
293            env: CONFIG_DIR_ENV,
294        })
295}
296
297/// `~/.rpi/agent/auth.json`.
298pub fn auth_path() -> Result<PathBuf, ConfigError> {
299    auth_path_at(None)
300}
301
302pub(crate) fn auth_path_at(agent_dir: Option<&Path>) -> Result<PathBuf, ConfigError> {
303    Ok(agent_dir_at(agent_dir)?.join("auth.json"))
304}
305
306/// `~/.rpi/agent/models.json`.
307pub fn models_path() -> Result<PathBuf, ConfigError> {
308    models_path_at(None)
309}
310
311pub(crate) fn models_path_at(agent_dir: Option<&Path>) -> Result<PathBuf, ConfigError> {
312    Ok(agent_dir_at(agent_dir)?.join("models.json"))
313}
314
315/// `~/.rpi/agent/settings.json` (saved default provider/model/thinking + theme).
316pub fn settings_path() -> Result<PathBuf, ConfigError> {
317    settings_path_at(None)
318}
319
320pub(crate) fn settings_path_at(agent_dir: Option<&Path>) -> Result<PathBuf, ConfigError> {
321    Ok(agent_dir_at(agent_dir)?.join("settings.json"))
322}
323
324/// `~/.rpi/agent/trust.json` (per-cwd project trust decisions).
325pub fn trust_path() -> Result<PathBuf, ConfigError> {
326    trust_path_at(None)
327}
328
329pub(crate) fn trust_path_at(agent_dir: Option<&Path>) -> Result<PathBuf, ConfigError> {
330    Ok(agent_dir_at(agent_dir)?.join("trust.json"))
331}
332
333fn read_text_with_fallback(
334    primary: PathBuf,
335    fallback: Option<PathBuf>,
336) -> Result<Option<(PathBuf, String)>, ConfigError> {
337    match std::fs::read_to_string(&primary) {
338        Ok(text) => Ok(Some((primary, text))),
339        Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
340            let Some(fallback) = fallback.filter(|path| path != &primary) else {
341                return Ok(None);
342            };
343            match std::fs::read_to_string(&fallback) {
344                Ok(text) => Ok(Some((fallback, text))),
345                Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(None),
346                Err(source) => Err(ConfigError::Read {
347                    path: fallback,
348                    source,
349                }),
350            }
351        }
352        Err(source) => Err(ConfigError::Read {
353            path: primary,
354            source,
355        }),
356    }
357}
358
359/// One-time best-effort migration of a pre-nesting flat layout
360/// (`~/.rpi/{auth.json,models.json,.setup_done}`) into the
361/// nested `~/.rpi/agent/` layout. **No-op when `RPI_CODING_AGENT_DIR` is set**
362/// (never touch an explicit override), when the agent dir already exists, or
363/// when no flat files are present. Idempotent: a partial move resumes. Errors
364/// are swallowed (logged via the returned `Result` only so tests can observe);
365/// `app::run` ignores them so a migration hiccup never blocks startup.
366pub fn migrate_legacy_layout() -> Result<usize, ConfigError> {
367    // Only migrate the default home-backed layout — never an env override.
368    if std::env::var_os(CONFIG_DIR_ENV).is_some() {
369        return Ok(0);
370    }
371    let root = match config_root_dir() {
372        Ok(p) => p,
373        Err(_) => return Ok(0),
374    };
375    let agent = agent_dir()?;
376    migrate_legacy_layout_in(&root, &agent)
377}
378
379/// The core migration (no env gate): if `agent/` is absent but flat files exist
380/// under `root`, move `{auth.json,models.json,.setup_done}` into
381/// `agent/`. Idempotent. Factored out so tests can drive it against a temp
382/// root/agent pair without touching the env (the public
383/// [`migrate_legacy_layout`] short-circuits on an env override, which tests
384/// can't unset portably while other tests run).
385fn migrate_legacy_layout_in(root: &Path, agent: &Path) -> Result<usize, ConfigError> {
386    // If the agent dir already exists with any content, assume already migrated.
387    if agent.exists() {
388        return Ok(0);
389    }
390    // Probe for a flat file. If none, nothing to migrate.
391    let flat_auth = root.join("auth.json");
392    let flat_models = root.join("models.json");
393    if !flat_auth.exists() && !flat_models.exists() {
394        return Ok(0);
395    }
396    std::fs::create_dir_all(agent).map_err(|e| ConfigError::Write {
397        path: agent.to_path_buf(),
398        source: e,
399    })?;
400    let mut moved = 0usize;
401    for leaf in ["auth.json", "models.json", ".setup_done"] {
402        let from = root.join(leaf);
403        let to = agent.join(leaf);
404        if from.exists() && !to.exists() {
405            // `rename` across the same filesystem is atomic; fall back to copy
406            // + remove on cross-device (rare for a home dir).
407            if let Err(_e) = std::fs::rename(&from, &to) {
408                if std::fs::copy(&from, &to).is_ok() {
409                    let _ = std::fs::remove_file(&from);
410                }
411            }
412            moved += 1;
413        }
414    }
415    Ok(moved)
416}
417
418// ---------------------------------------------------------------------------
419// auth.json — Credential store
420// ---------------------------------------------------------------------------
421
422/// Read the auth store. Missing file ⇒ empty store (not an error). Malformed
423/// JSON ⇒ `ConfigError::Json` (we do not silently swallow a corrupt auth file).
424pub fn read_auth() -> Result<AuthStore, ConfigError> {
425    read_auth_at(None)
426}
427
428/// [`read_auth`] against an explicit agent home (`--agent-dir`).
429pub(crate) fn read_auth_at(agent_dir: Option<&Path>) -> Result<AuthStore, ConfigError> {
430    let path = auth_path_at(agent_dir)?;
431    match read_text_with_fallback(path, None)? {
432        Some((path, text)) => {
433            serde_json::from_str(&text).map_err(|source| ConfigError::Json { path, source })
434        }
435        None => Ok(AuthStore::new()),
436    }
437}
438
439/// Serializes this process's read-modify-write updates of the auth store. It is
440/// held only for the read and the write, never while calling a provider
441/// package, so two providers committing at once cannot drop each other's entry.
442fn auth_store_lock() -> &'static std::sync::Mutex<()> {
443    static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
444    &LOCK
445}
446
447/// Atomically write the whole auth store (ensures the dir exists, writes a
448/// temp sibling, `rename`s over the target, then `chmod 0o600` on Unix).
449/// Callers that read-modify-write must hold the internal store lock.
450pub fn write_auth(store: &AuthStore) -> Result<(), ConfigError> {
451    write_auth_at(None, store)
452}
453
454/// [`write_auth`] against an explicit agent home (`--agent-dir`).
455pub(crate) fn write_auth_at(
456    agent_dir: Option<&Path>,
457    store: &AuthStore,
458) -> Result<(), ConfigError> {
459    let path = auth_path_at(agent_dir)?;
460    let dir = agent_dir_at(agent_dir)?;
461    ensure_dir(&dir)?;
462    let json = serde_json::to_string_pretty(store).unwrap();
463    atomic_write(&path, json.as_bytes())?;
464    set_owner_only(&path);
465    Ok(())
466}
467
468/// Read-modify-write: upsert a credential for `provider_id`. Re-reads the
469/// latest store under the lock, so other providers' entries are preserved.
470pub fn upsert_credential(provider_id: &str, cred: Credential) -> Result<(), ConfigError> {
471    upsert_credential_at(None, provider_id, cred)
472}
473
474/// [`upsert_credential`] against an explicit agent home (`--agent-dir`).
475pub(crate) fn upsert_credential_at(
476    agent_dir: Option<&Path>,
477    provider_id: &str,
478    cred: Credential,
479) -> Result<(), ConfigError> {
480    let _store_guard = auth_store_lock()
481        .lock()
482        .unwrap_or_else(std::sync::PoisonError::into_inner);
483    let mut store = read_auth_at(agent_dir)?;
484    store.insert(provider_id.to_string(), cred);
485    write_auth_at(agent_dir, &store)
486}
487
488/// Store an OAuth token under exactly one provider id using the atomic auth
489/// store writer. Token values never enter the event or session layer.
490pub fn upsert_oauth_token(
491    provider_id: &str,
492    access: String,
493    refresh: String,
494    expires: i64,
495) -> Result<(), ConfigError> {
496    upsert_credential(
497        provider_id,
498        Credential::Oauth {
499            access,
500            refresh,
501            expires,
502        },
503    )
504}
505
506/// [`upsert_oauth_token`] against an explicit agent home.
507pub(crate) fn upsert_oauth_token_at(
508    agent_dir: Option<&Path>,
509    provider_id: &str,
510    access: String,
511    refresh: String,
512    expires: i64,
513) -> Result<(), ConfigError> {
514    upsert_credential_at(
515        agent_dir,
516        provider_id,
517        Credential::Oauth {
518            access,
519            refresh,
520            expires,
521        },
522    )
523}
524
525/// Replace `provider_id`'s OAuth token only if the stored one still has the
526/// `expected` access, refresh and expiry. Returns `false`, writing nothing, when
527/// a login or logout replaced or removed it meanwhile, so a late refresh result
528/// never undoes that user action.
529pub fn replace_oauth_token_if_unchanged(
530    provider_id: &str,
531    expected: (&str, &str, i64),
532    access: String,
533    refresh: String,
534    expires: i64,
535) -> Result<bool, ConfigError> {
536    replace_oauth_token_if_unchanged_at(None, provider_id, expected, access, refresh, expires)
537}
538
539/// [`replace_oauth_token_if_unchanged`] against an explicit agent home.
540pub(crate) fn replace_oauth_token_if_unchanged_at(
541    agent_dir: Option<&Path>,
542    provider_id: &str,
543    expected: (&str, &str, i64),
544    access: String,
545    refresh: String,
546    expires: i64,
547) -> Result<bool, ConfigError> {
548    let _store_guard = auth_store_lock()
549        .lock()
550        .unwrap_or_else(std::sync::PoisonError::into_inner);
551    let mut store = read_auth_at(agent_dir)?;
552    let unchanged = matches!(
553        store.get(provider_id),
554        Some(Credential::Oauth { access, refresh, expires })
555            if (access.as_str(), refresh.as_str(), *expires) == expected
556    );
557    if unchanged {
558        store.insert(
559            provider_id.to_string(),
560            Credential::Oauth {
561                access,
562                refresh,
563                expires,
564            },
565        );
566        write_auth_at(agent_dir, &store)?;
567    }
568    Ok(unchanged)
569}
570
571/// Read only the OAuth credential for one provider.
572pub fn read_oauth_token(provider_id: &str) -> Result<Option<Credential>, ConfigError> {
573    read_oauth_token_at(None, provider_id)
574}
575
576/// [`read_oauth_token`] against an explicit agent home.
577pub(crate) fn read_oauth_token_at(
578    agent_dir: Option<&Path>,
579    provider_id: &str,
580) -> Result<Option<Credential>, ConfigError> {
581    Ok(match read_auth_at(agent_dir)?.get(provider_id) {
582        Some(Credential::Oauth {
583            access,
584            refresh,
585            expires,
586        }) => Some(Credential::Oauth {
587            access: access.clone(),
588            refresh: refresh.clone(),
589            expires: *expires,
590        }),
591        _ => None,
592    })
593}
594
595/// Remove `provider_id` from the store. Returns `true` if a credential was
596/// present (and is now gone), `false` if it was already absent. Always rewrites
597/// the file when the provider existed (so `auth logout` reflects the new state
598/// on disk even if the map isn't empty).
599pub fn delete_credential(provider_id: &str) -> Result<bool, ConfigError> {
600    delete_credential_at(None, provider_id)
601}
602
603/// [`delete_credential`] against an explicit agent home.
604pub(crate) fn delete_credential_at(
605    agent_dir: Option<&Path>,
606    provider_id: &str,
607) -> Result<bool, ConfigError> {
608    let _store_guard = auth_store_lock()
609        .lock()
610        .unwrap_or_else(std::sync::PoisonError::into_inner);
611    let mut store = read_auth_at(agent_dir)?;
612    if store.remove(provider_id).is_some() {
613        write_auth_at(agent_dir, &store)?;
614        Ok(true)
615    } else {
616        Ok(false)
617    }
618}
619
620// ---------------------------------------------------------------------------
621// models.json — provider/model catalog
622// ---------------------------------------------------------------------------
623
624/// Load `~/.rpi/models.json`. Missing file ⇒ empty config (no error).
625pub fn load_models_config() -> Result<ModelsConfig, ConfigError> {
626    load_models_config_at(None)
627}
628
629/// [`load_models_config`] against an explicit agent home (`--agent-dir`).
630pub(crate) fn load_models_config_at(agent_dir: Option<&Path>) -> Result<ModelsConfig, ConfigError> {
631    let path = models_path_at(agent_dir)?;
632    match read_text_with_fallback(path, None)? {
633        Some((path, text)) => {
634            parse_models_json(&text).map_err(|source| ConfigError::Json { path, source })
635        }
636        None => Ok(ModelsConfig::default()),
637    }
638}
639
640/// Diagnose unsupported compat keys and malformed values without rejecting
641/// unrelated providers.
642/// Atomically write the whole `~/.rpi/models.json` (used by the interactive
643/// provider form). Note: unlike [`crate::settings::save_settings`], this
644/// serializes the modeled config directly, so hand-written comments and unknown
645/// fields in `models.json` are not preserved on rewrite. A timestamped
646/// `models.json.bak-*` snapshot is written first so a mistake can be reverted.
647pub fn save_models_config(cfg: &ModelsConfig) -> Result<(), ConfigError> {
648    save_models_config_at(None, cfg)
649}
650
651/// [`save_models_config`] against an explicit agent home (`--agent-dir`).
652pub(crate) fn save_models_config_at(
653    agent_dir: Option<&Path>,
654    cfg: &ModelsConfig,
655) -> Result<(), ConfigError> {
656    let path = models_path_at(agent_dir)?;
657    let dir = agent_dir_at(agent_dir)?;
658    ensure_dir(&dir)?;
659    // Back up the existing file before rewriting it (best-effort; a missing
660    // file is normal on first save).
661    if let Ok(existing) = std::fs::read(&path) {
662        let stamp = std::time::SystemTime::now()
663            .duration_since(std::time::UNIX_EPOCH)
664            .map(|d| d.as_secs())
665            .unwrap_or(0);
666        let backup = dir.join(format!("models.json.bak-{stamp}"));
667        let _ = std::fs::write(&backup, existing);
668    }
669    let text = serde_json::to_string_pretty(cfg).map_err(|source| ConfigError::Json {
670        path: path.clone(),
671        source,
672    })?;
673    atomic_write(&path, text.as_bytes())
674}
675
676/// Add one user-configured provider and its first model to `models.json`.
677///
678/// This is shared by the interactive provider form and RPC clients so both
679/// surfaces enforce the same protocol, URL, duplicate, and size checks.
680pub fn add_provider(
681    provider_id: &str,
682    api: &str,
683    base_url: &str,
684    api_key: &str,
685    model_id: &str,
686    model_name: Option<&str>,
687    context_window: Option<u64>,
688    max_tokens: Option<u64>,
689    supports_images: Option<bool>,
690) -> Result<(), String> {
691    add_provider_at(
692        None,
693        provider_id,
694        api,
695        base_url,
696        api_key,
697        model_id,
698        model_name,
699        context_window,
700        max_tokens,
701        supports_images,
702    )
703}
704
705/// [`add_provider`] against an explicit agent home (`--agent-dir`).
706#[allow(clippy::too_many_arguments)]
707pub(crate) fn add_provider_at(
708    agent_dir: Option<&Path>,
709    provider_id: &str,
710    api: &str,
711    base_url: &str,
712    api_key: &str,
713    model_id: &str,
714    model_name: Option<&str>,
715    context_window: Option<u64>,
716    max_tokens: Option<u64>,
717    supports_images: Option<bool>,
718) -> Result<(), String> {
719    const MAX_FIELD: usize = 4096;
720    let provider_id = provider_id.trim();
721    let api = api.trim();
722    let base_url = base_url.trim();
723    let api_key = api_key.trim();
724    let model_id = model_id.trim();
725    let model_name = model_name.map(str::trim).filter(|value| !value.is_empty());
726    if provider_id.is_empty()
727        || api.is_empty()
728        || base_url.is_empty()
729        || api_key.is_empty()
730        || model_id.is_empty()
731    {
732        return Err("provider, protocol, base URL, API key, and model ID are required".into());
733    }
734    for (label, value) in [
735        ("provider", provider_id),
736        ("protocol", api),
737        ("base URL", base_url),
738        ("API key", api_key),
739        ("model ID", model_id),
740    ] {
741        if value.len() > MAX_FIELD {
742            return Err(format!("{label} is too long"));
743        }
744    }
745    if model_name.is_some_and(|value| value.len() > MAX_FIELD) {
746        return Err("model name is too long".into());
747    }
748    if context_window == Some(0) {
749        return Err("context window must be greater than zero".into());
750    }
751    if max_tokens == Some(0) {
752        return Err("max output tokens must be greater than zero".into());
753    }
754    if !matches!(
755        api,
756        "anthropic-messages" | "openai-completions" | "openai-responses"
757    ) {
758        return Err("unsupported provider protocol".into());
759    }
760    if !(base_url.starts_with("http://") || base_url.starts_with("https://")) {
761        return Err("base URL must start with http:// or https://".into());
762    }
763    let mut config = load_models_config_at(agent_dir).map_err(|error| error.to_string())?;
764    if config.providers.contains_key(provider_id) {
765        return Err(format!(
766            "provider {provider_id:?} already has a models.json configuration"
767        ));
768    }
769    config.providers.insert(
770        provider_id.to_owned(),
771        ProviderConfig {
772            name: None,
773            base_url: Some(base_url.to_owned()),
774            api_key: Some(api_key.to_owned()),
775            api: Some(api.to_owned()),
776            headers: None,
777            auth_header: None,
778            models: vec![ModelDefinition {
779                id: model_id.to_owned(),
780                name: model_name.map(str::to_owned),
781                base_url: None,
782                reasoning: None,
783                thinking_level_map: None,
784                context_window,
785                max_tokens,
786                cost: None,
787                input: supports_images.map(|supports| {
788                    if supports {
789                        vec!["text".to_string(), "image".to_string()]
790                    } else {
791                        vec!["text".to_string()]
792                    }
793                }),
794                headers: None,
795                compat: None,
796            }],
797        },
798    );
799    save_models_config_at(agent_dir, &config).map_err(|error| error.to_string())
800}
801
802/// Update an existing models.json provider and its first model. An omitted API
803/// key preserves the existing key, so editing metadata does not require
804/// exposing or re-entering a secret.
805pub fn update_provider(
806    provider_id: &str,
807    api: &str,
808    base_url: &str,
809    api_key: Option<&str>,
810    model_id: &str,
811    model_name: Option<&str>,
812    context_window: Option<u64>,
813    max_tokens: Option<u64>,
814    supports_images: bool,
815) -> Result<(), String> {
816    update_provider_at(
817        None,
818        provider_id,
819        api,
820        base_url,
821        api_key,
822        model_id,
823        model_name,
824        context_window,
825        max_tokens,
826        supports_images,
827    )
828}
829
830/// [`update_provider`] against an explicit agent home (`--agent-dir`).
831#[allow(clippy::too_many_arguments)]
832pub(crate) fn update_provider_at(
833    agent_dir: Option<&Path>,
834    provider_id: &str,
835    api: &str,
836    base_url: &str,
837    api_key: Option<&str>,
838    model_id: &str,
839    model_name: Option<&str>,
840    context_window: Option<u64>,
841    max_tokens: Option<u64>,
842    supports_images: bool,
843) -> Result<(), String> {
844    let provider_id = provider_id.trim();
845    let api = api.trim();
846    let base_url = base_url.trim();
847    let model_id = model_id.trim();
848    let model_name = model_name.map(str::trim).filter(|value| !value.is_empty());
849    if provider_id.is_empty() || api.is_empty() || base_url.is_empty() || model_id.is_empty() {
850        return Err("provider, protocol, base URL, and model ID are required".into());
851    }
852    if !matches!(
853        api,
854        "anthropic-messages" | "openai-completions" | "openai-responses"
855    ) {
856        return Err("unsupported provider protocol".into());
857    }
858    if !(base_url.starts_with("http://") || base_url.starts_with("https://")) {
859        return Err("base URL must start with http:// or https://".into());
860    }
861    if context_window == Some(0) {
862        return Err("context window must be greater than zero".into());
863    }
864    if max_tokens == Some(0) {
865        return Err("max output tokens must be greater than zero".into());
866    }
867    let mut config = load_models_config_at(agent_dir).map_err(|error| error.to_string())?;
868    let provider = config
869        .providers
870        .get_mut(provider_id)
871        .ok_or_else(|| format!("provider {provider_id:?} has no models.json configuration"))?;
872    provider.api = Some(api.to_owned());
873    provider.base_url = Some(base_url.to_owned());
874    if let Some(api_key) = api_key.map(str::trim).filter(|value| !value.is_empty()) {
875        provider.api_key = Some(api_key.to_owned());
876    }
877    let model = provider
878        .models
879        .first_mut()
880        .ok_or_else(|| format!("provider {provider_id:?} has no model to update"))?;
881    model.id = model_id.to_owned();
882    model.name = model_name.map(str::to_owned);
883    model.context_window = context_window;
884    model.max_tokens = max_tokens;
885    model.input = Some(if supports_images {
886        vec!["text".to_string(), "image".to_string()]
887    } else {
888        vec!["text".to_string()]
889    });
890    save_models_config_at(agent_dir, &config).map_err(|error| error.to_string())
891}
892
893/// Delete a user-configured provider from models.json.
894pub fn delete_provider(provider_id: &str) -> Result<(), String> {
895    delete_provider_at(None, provider_id)
896}
897
898/// [`delete_provider`] against an explicit agent home (`--agent-dir`).
899pub(crate) fn delete_provider_at(
900    agent_dir: Option<&Path>,
901    provider_id: &str,
902) -> Result<(), String> {
903    let provider_id = provider_id.trim();
904    if provider_id.is_empty() {
905        return Err("provider is required".into());
906    }
907    let mut config = load_models_config_at(agent_dir).map_err(|error| error.to_string())?;
908    if config.providers.shift_remove(provider_id).is_none() {
909        return Err(format!(
910            "provider {provider_id:?} has no models.json configuration"
911        ));
912    }
913    save_models_config_at(agent_dir, &config).map_err(|error| error.to_string())
914}
915
916// ---------------------------------------------------------------------------
917// trust.json — project-trust store (read-only layout parity with pi)
918// ---------------------------------------------------------------------------
919
920/// The trust store: `canonicalCwd -> decision` (`true`/`false`/`null`). Mirrors
921/// pi's `TrustFile = Record<string, boolean | null | undefined>`
922/// (`trust-manager.ts`). rpi reads this for layout parity (a copied pi
923/// `trust.json` parses + is located correctly) but does **not** gate any
924/// project resources behind trust in v1 — there is no trust prompt. Deferred.
925pub type TrustStore = BTreeMap<String, Option<bool>>;
926
927/// Read `~/.rpi/agent/trust.json`. Missing file ⇒ empty store (not an error).
928/// Malformed JSON ⇒ `ConfigError::Json`. `null` decisions deserialize as
929/// `None`; absent entries are simply not present.
930pub fn read_trust() -> Result<TrustStore, ConfigError> {
931    read_trust_at(None)
932}
933
934pub(crate) fn read_trust_at(agent_dir: Option<&Path>) -> Result<TrustStore, ConfigError> {
935    let path = trust_path_at(agent_dir)?;
936    match std::fs::read_to_string(&path) {
937        Ok(text) => serde_json::from_str(&text).map_err(|e| ConfigError::Json {
938            path: path.clone(),
939            source: e,
940        }),
941        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(TrustStore::new()),
942        Err(e) => Err(ConfigError::Read { path, source: e }),
943    }
944}
945
946/// Persist the trust decision for a project directory. The path is canonical
947/// when it exists, with an absolute fallback for a project being created.
948pub fn set_project_trust(cwd: &Path, trusted: Option<bool>) -> Result<(), ConfigError> {
949    set_project_trust_at(None, cwd, trusted)
950}
951
952/// [`set_project_trust`] against an explicit agent home (`--agent-dir`).
953pub(crate) fn set_project_trust_at(
954    agent_dir: Option<&Path>,
955    cwd: &Path,
956    trusted: Option<bool>,
957) -> Result<(), ConfigError> {
958    let key = std::fs::canonicalize(cwd)
959        .unwrap_or_else(|_| cwd.to_path_buf())
960        .to_string_lossy()
961        .into_owned();
962    let mut store = read_trust_at(agent_dir)?;
963    if let Some(decision) = trusted {
964        store.insert(key, Some(decision));
965    } else {
966        store.remove(&key);
967    }
968    let path = trust_path_at(agent_dir)?;
969    ensure_dir(&agent_dir_at(agent_dir)?)?;
970    let json = serde_json::to_string_pretty(&store).unwrap();
971    atomic_write(&path, json.as_bytes())?;
972    set_owner_only(&path);
973    Ok(())
974}
975
976/// Return the stored trust decision for `cwd`. A missing entry (or an entry
977/// explicitly set to `null`) returns `None`; callers choose their safe default.
978pub fn project_trust_decision(cwd: &Path) -> Result<Option<bool>, ConfigError> {
979    project_trust_decision_at(None, cwd)
980}
981
982/// [`project_trust_decision`] under an explicit agent home (`--agent-dir`).
983pub(crate) fn project_trust_decision_at(
984    agent_dir: Option<&Path>,
985    cwd: &Path,
986) -> Result<Option<bool>, ConfigError> {
987    let key = std::fs::canonicalize(cwd)
988        .unwrap_or_else(|_| cwd.to_path_buf())
989        .to_string_lossy()
990        .into_owned();
991    Ok(read_trust_at(agent_dir)?.get(&key).copied().flatten())
992}
993
994/// Parse the models JSON, tolerating `//` line comments (a minimal subset of
995/// upstream's `stripJsonComments`). Tries strict JSON first; on failure, strips
996/// `//…` to end-of-line and retries.
997fn parse_models_json(text: &str) -> Result<ModelsConfig, serde_json::Error> {
998    match serde_json::from_str(text) {
999        Ok(c) => Ok(c),
1000        Err(first) => {
1001            // Best-effort comment strip — only `//` to EOL, never inside strings
1002            // (a `//` inside a JSON string would already have made the strict
1003            // parse fail for a *different* reason; stripping naively is an
1004            // acceptable v1 trade-off, documented as a limitation).
1005            let stripped = strip_line_comments(text);
1006            serde_json::from_str(&stripped).map_err(|_| first)
1007        }
1008    }
1009}
1010
1011/// Strip `//` line comments (to end-of-line), skipping `//` that appears inside
1012/// a double-quoted string. A minimal subset of upstream's `stripJsonComments`,
1013/// shared by [`parse_models_json`] and [`crate::settings::load_settings`] so a
1014/// copied pi `models.json`/`settings.json` (which pi allows comments in) parses.
1015pub(crate) fn strip_line_comments(text: &str) -> String {
1016    text.lines()
1017        .map(|line| match find_line_comment(line) {
1018            Some(idx) => line[..idx].to_string(),
1019            None => line.to_string(),
1020        })
1021        .collect::<Vec<_>>()
1022        .join("\n")
1023}
1024
1025/// Index of a `//` line comment that is *not* inside a double-quoted string.
1026fn find_line_comment(line: &str) -> Option<usize> {
1027    let mut in_str = false;
1028    let mut esc = false;
1029    for (i, ch) in line.char_indices() {
1030        if esc {
1031            esc = false;
1032            continue;
1033        }
1034        match ch {
1035            '\\' if in_str => esc = true,
1036            '"' => in_str = !in_str,
1037            '/' if !in_str && line.as_bytes().get(i + 1) == Some(&b'/') => {
1038                return Some(i);
1039            }
1040            _ => {}
1041        }
1042    }
1043    None
1044}
1045
1046// ---------------------------------------------------------------------------
1047// Config-value expansion (mirrors pi `resolve-config-value.ts`)
1048// ---------------------------------------------------------------------------
1049
1050/// A process-lifetime cache for `!command` resolutions, mirroring pi's
1051/// `commandResultCache`. Keyed by the raw `!cmd` string (including the `!`).
1052fn command_cache() -> &'static std::sync::Mutex<std::collections::HashMap<String, Option<String>>> {
1053    static CACHE: std::sync::OnceLock<
1054        std::sync::Mutex<std::collections::HashMap<String, Option<String>>>,
1055    > = std::sync::OnceLock::new();
1056    CACHE.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()))
1057}
1058
1059/// Resolve a config value (API key, header value) that may be a shell command,
1060/// an env-var template, or a literal — mirroring pi's `resolveConfigValue`.
1061///
1062/// - `!command` → run the rest as a shell command (`sh -c` on Unix, `cmd /C` on
1063///   Windows), return trimmed stdout (cached per process). Missing shell or
1064///   non-zero exit ⇒ `None`.
1065/// - `$VAR` / `${VAR}` templates: interpolate from `env_overlay` (winning) then
1066///   the process env. `$$`→`$`, `$!`→`!` escapes. Any referenced var that is
1067///   unset ⇒ the **whole** value resolves to `None` (pi semantics).
1068/// - Otherwise the literal string (returned as-is).
1069///
1070/// `env_overlay` is the `credential.env` map for auth.json keys (pi passes the
1071/// same). `None` (or an empty overlay) means process-env only — used for
1072/// models.json apiKey/headers, which have no env overlay.
1073pub fn resolve_config_value(
1074    config: &str,
1075    env_overlay: Option<&BTreeMap<String, String>>,
1076) -> Option<String> {
1077    rpi_runtime::values::resolve_config_value(
1078        config,
1079        env_overlay,
1080        &crate::provider::CliValues,
1081        true,
1082    )
1083}
1084
1085/// Like [`resolve_config_value`] but **uncached** — mirrors pi's
1086/// `resolveConfigValueUncached`, used when a fresh resolution is required
1087/// (e.g. headers, which pi resolves uncached so a rotating token is re-read).
1088pub fn resolve_config_value_uncached(
1089    config: &str,
1090    env_overlay: Option<&BTreeMap<String, String>>,
1091) -> Option<String> {
1092    rpi_runtime::values::resolve_config_value(
1093        config,
1094        env_overlay,
1095        &crate::provider::CliValues,
1096        false,
1097    )
1098}
1099
1100/// Resolve every header value via [`resolve_config_value_uncached`]; drop
1101/// entries that resolve to `None` (mirrors pi `resolveHeaders`). Used on
1102/// models.json `headers` maps before folding onto a model.
1103pub fn resolve_headers(
1104    headers: &BTreeMap<String, String>,
1105    env_overlay: Option<&BTreeMap<String, String>>,
1106) -> BTreeMap<String, String> {
1107    rpi_runtime::values::resolve_headers(headers, env_overlay, &crate::provider::CliValues)
1108}
1109
1110/// Run `cmd` (without the leading `!`), returning trimmed stdout. Cached per
1111/// process (mirrors pi `executeCommand`). 10s timeout; non-zero exit / missing
1112/// shell ⇒ `None`.
1113pub(crate) fn resolve_command(cmd: &str) -> Option<String> {
1114    let key = format!("!{cmd}");
1115    if let Some(v) = command_cache().lock().ok()?.get(&key) {
1116        return v.clone();
1117    }
1118    let result = resolve_command_uncached(cmd);
1119    if let Ok(mut cache) = command_cache().lock() {
1120        cache.insert(key, result.clone());
1121    }
1122    result
1123}
1124
1125#[cfg(unix)]
1126fn spawn_shell_command(cmd: &str) -> Option<std::process::Output> {
1127    std::process::Command::new("sh")
1128        .arg("-c")
1129        .arg(cmd)
1130        .stdin(std::process::Stdio::null())
1131        .stdout(std::process::Stdio::piped())
1132        .stderr(std::process::Stdio::null())
1133        .output()
1134        .ok()
1135}
1136
1137#[cfg(windows)]
1138fn spawn_shell_command(cmd: &str) -> Option<std::process::Output> {
1139    use std::os::windows::process::CommandExt;
1140    std::process::Command::new("cmd")
1141        .arg("/C")
1142        .arg(cmd)
1143        .stdin(std::process::Stdio::null())
1144        .stdout(std::process::Stdio::piped())
1145        .stderr(std::process::Stdio::null())
1146        .creation_flags(0x0800_0000) // CREATE_NO_WINDOW
1147        .output()
1148        .ok()
1149}
1150
1151/// Uncached `!command` execution (mirrors pi `executeCommandUncached`).
1152pub(crate) fn resolve_command_uncached(cmd: &str) -> Option<String> {
1153    let output = spawn_shell_command(cmd)?;
1154    if !output.status.success() {
1155        return None;
1156    }
1157    let stdout = String::from_utf8_lossy(&output.stdout);
1158    let trimmed = stdout.trim();
1159    if trimmed.is_empty() {
1160        None
1161    } else {
1162        Some(trimmed.to_string())
1163    }
1164}
1165
1166/// (`anthropic-messages`, or omitted/unknown). Unknown `api` is allowed through
1167/// for forward-compat but flagged ignored-in-v1 in the docs. Public so
1168/// [`crate::provider`] can scan models.json providers for an `authHeader:true`
1169/// gateway bearer source.
1170/// Resolve an OpenAI-compatible provider key from its explicit config or a
1171/// known provider's canonical environment variable. Arbitrary custom provider
1172/// ids must declare `apiKey: "$ENV"`: deriving an env name by normalizing the
1173/// id would collapse distinct native-Pi identities such as `a-b` and `a_b`.
1174pub fn openai_provider_api_key(provider_id: &str, cfg: &ProviderConfig) -> Option<String> {
1175    if let Some(raw) = cfg.api_key.as_deref().filter(|key| !key.is_empty()) {
1176        if let Some(value) = resolve_config_value(raw, None).filter(|value| !value.is_empty()) {
1177            return Some(value);
1178        }
1179    }
1180
1181    let name = native_provider_api_key_env_var(provider_id)?;
1182    std::env::var(name).ok().filter(|value| !value.is_empty())
1183}
1184
1185/// Provider-id-to-environment-variable mapping. Provider ids are
1186/// identities, so aliases and case variants must not inherit another
1187/// provider's credential.
1188fn native_provider_api_key_env_var(provider_id: &str) -> Option<&'static str> {
1189    match provider_id {
1190        "openai" => crate::credentials::builtin_api_key_env(provider_id),
1191        _ => None,
1192    }
1193}
1194
1195/// Convert a `(provider_id, ProviderConfig)` pair into a list of library
1196/// [`Model`]s. Provider-level `base_url`/`headers`/`auth_header` fold into each
1197/// model. Returns `None` for protocols that do not have a runtime provider.
1198// ---------------------------------------------------------------------------
1199// Internals: dir ensure, atomic write, chmod
1200// ---------------------------------------------------------------------------
1201
1202#[cfg(unix)]
1203use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
1204
1205/// Create the config dir if missing. Mode 0o700 on Unix (mkdir default on
1206/// Windows, where the sticky-permission concept doesn't apply).
1207fn ensure_dir(dir: &Path) -> Result<(), ConfigError> {
1208    if dir.exists() {
1209        return Ok(());
1210    }
1211    std::fs::create_dir_all(dir).map_err(|e| ConfigError::Write {
1212        path: dir.to_path_buf(),
1213        source: e,
1214    })?;
1215    #[cfg(unix)]
1216    {
1217        let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
1218    }
1219    Ok(())
1220}
1221
1222/// Write `bytes` to `path` atomically: a temp sibling → `rename`. The temp
1223/// file lives next to the target so the rename stays on one filesystem.
1224pub(crate) fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), ConfigError> {
1225    let dir = path.parent().ok_or_else(|| ConfigError::Write {
1226        path: path.to_path_buf(),
1227        source: std::io::Error::new(std::io::ErrorKind::InvalidInput, "path has no parent"),
1228    })?;
1229    let tmp = dir.join(format!(
1230        ".{}.{}.tmp",
1231        path.file_name().and_then(|n| n.to_str()).unwrap_or("rpi"),
1232        uuid::Uuid::new_v4().simple()
1233    ));
1234    let mut options = std::fs::OpenOptions::new();
1235    options.write(true).create_new(true);
1236    #[cfg(unix)]
1237    options.mode(0o600);
1238    let mut file = options.open(&tmp).map_err(|source| ConfigError::Write {
1239        path: tmp.clone(),
1240        source,
1241    })?;
1242    if let Err(error) = file.write_all(bytes).and_then(|()| file.sync_all()) {
1243        // A partial staging file is never useful to a later caller. Best
1244        // effort cleanup also avoids leaving a misleading stale temp behind
1245        // when the target itself was left untouched.
1246        let _ = std::fs::remove_file(&tmp);
1247        return Err(ConfigError::Write {
1248            path: tmp,
1249            source: error,
1250        });
1251    }
1252    drop(file);
1253    if let Err(error) = std::fs::rename(&tmp, path) {
1254        // `rename` is the publish point; on failure the original target is
1255        // still intact. Remove the staging file before returning the error.
1256        let _ = std::fs::remove_file(&tmp);
1257        return Err(ConfigError::Write {
1258            path: path.to_path_buf(),
1259            source: error,
1260        });
1261    }
1262    Ok(())
1263}
1264
1265/// Best-effort tighten to owner-only (0o600). No-op on Windows (the Node
1266/// upstream applies no ACL either).
1267fn set_owner_only(_path: &Path) {
1268    #[cfg(unix)]
1269    {
1270        let _ = std::fs::set_permissions(_path, std::fs::Permissions::from_mode(0o600));
1271    }
1272}
1273
1274// ---------------------------------------------------------------------------
1275// Tests
1276// ---------------------------------------------------------------------------
1277
1278#[cfg(test)]
1279pub(crate) mod test_support {
1280    /// A shared workspace lock for tests that touch process-global env vars
1281    /// (`RPI_CODING_AGENT_DIR`, `ANTHROPIC_*`). All env-mutating tests across
1282    /// the crate (config / provider / auth) share this ONE mutex so they can't
1283    /// race on the shared environment. Hold the returned guard for the whole
1284    /// test (store it in a RAII struct).
1285    use std::sync::{Mutex, OnceLock};
1286    pub(crate) fn env_lock() -> &'static Mutex<()> {
1287        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
1288        LOCK.get_or_init(|| Mutex::new(()))
1289    }
1290
1291    /// Isolate session-directory overrides while holding the shared env lock.
1292    /// Restore the inherited value before releasing the lock, even on unwind.
1293    pub(crate) struct SessionDirEnv {
1294        _guard: std::sync::MutexGuard<'static, ()>,
1295        previous: Option<std::ffi::OsString>,
1296    }
1297
1298    impl SessionDirEnv {
1299        pub(crate) fn new(directory: Option<&std::path::Path>) -> Self {
1300            let guard = env_lock().lock().unwrap();
1301            let previous = std::env::var_os("RPI_CODING_AGENT_SESSION_DIR");
1302            match directory {
1303                Some(directory) => std::env::set_var("RPI_CODING_AGENT_SESSION_DIR", directory),
1304                None => std::env::remove_var("RPI_CODING_AGENT_SESSION_DIR"),
1305            }
1306            Self {
1307                _guard: guard,
1308                previous,
1309            }
1310        }
1311    }
1312
1313    impl Drop for SessionDirEnv {
1314        fn drop(&mut self) {
1315            match self.previous.take() {
1316                Some(value) => std::env::set_var("RPI_CODING_AGENT_SESSION_DIR", value),
1317                None => std::env::remove_var("RPI_CODING_AGENT_SESSION_DIR"),
1318            }
1319        }
1320    }
1321}
1322
1323#[cfg(test)]
1324mod tests {
1325    use super::*;
1326    use crate::config::test_support::env_lock;
1327
1328    /// Point `RPI_CODING_AGENT_DIR` at a fresh temp dir for the duration of the
1329    /// test (cleaned up on drop). Holds the prior value of the env var to
1330    /// restore it. Hold the env lock for its whole lifetime.
1331    struct TempConfig {
1332        _guard: std::sync::MutexGuard<'static, ()>,
1333        _tmp: tempfile::TempDir,
1334        prev: Option<std::ffi::OsString>,
1335    }
1336    impl TempConfig {
1337        fn new() -> Self {
1338            let guard = env_lock().lock().unwrap();
1339            let prev = std::env::var_os(CONFIG_DIR_ENV);
1340            let tmp = tempfile::TempDir::new().unwrap();
1341            std::env::set_var(CONFIG_DIR_ENV, tmp.path());
1342            Self {
1343                _guard: guard,
1344                _tmp: tmp,
1345                prev,
1346            }
1347        }
1348    }
1349    impl Drop for TempConfig {
1350        fn drop(&mut self) {
1351            restore_env(CONFIG_DIR_ENV, self.prev.take());
1352        }
1353    }
1354
1355    #[test]
1356    fn read_auth_missing_file_is_empty() {
1357        let _cfg = TempConfig::new();
1358        let store = read_auth().unwrap();
1359        assert!(store.is_empty());
1360    }
1361
1362    #[test]
1363    fn upsert_then_read_roundtrip() {
1364        let _cfg = TempConfig::new();
1365        upsert_credential(
1366            "anthropic",
1367            Credential::ApiKey {
1368                key: Some("sk-test-123".into()),
1369                env: None,
1370            },
1371        )
1372        .unwrap();
1373        let store = read_auth().unwrap();
1374        match store.get("anthropic") {
1375            Some(Credential::ApiKey { key, .. }) => assert_eq!(key.as_deref(), Some("sk-test-123")),
1376            other => panic!("unexpected cred: {other:?}"),
1377        }
1378        // The file should exist and be JSON.
1379        let path = auth_path().unwrap();
1380        assert!(path.exists(), "auth.json should exist after upsert");
1381        let raw = std::fs::read_to_string(&path).unwrap();
1382        assert!(raw.contains("\"anthropic\""));
1383        assert!(raw.contains("api_key"));
1384    }
1385
1386    #[test]
1387    fn add_provider_writes_protocol_endpoint_key_and_model() {
1388        let _cfg = TempConfig::new();
1389        add_provider(
1390            "gateway",
1391            "openai-completions",
1392            "https://api.example.test/v1",
1393            "fixture-key",
1394            "model-a",
1395            Some("Model A"),
1396            Some(128_000),
1397            Some(4096),
1398            Some(true),
1399        )
1400        .unwrap();
1401        let config = load_models_config().unwrap();
1402        let provider = config.providers.get("gateway").unwrap();
1403        assert_eq!(provider.api.as_deref(), Some("openai-completions"));
1404        assert_eq!(
1405            provider.base_url.as_deref(),
1406            Some("https://api.example.test/v1")
1407        );
1408        assert_eq!(provider.api_key.as_deref(), Some("fixture-key"));
1409        assert_eq!(provider.models[0].id, "model-a");
1410        assert_eq!(provider.models[0].name.as_deref(), Some("Model A"));
1411        assert_eq!(provider.models[0].context_window, Some(128_000));
1412        assert_eq!(provider.models[0].max_tokens, Some(4096));
1413        assert_eq!(
1414            provider.models[0].input.as_deref(),
1415            Some(["text".to_string(), "image".to_string()].as_slice())
1416        );
1417    }
1418
1419    #[test]
1420    fn add_provider_rejects_duplicate_and_unsupported_protocol() {
1421        let _cfg = TempConfig::new();
1422        add_provider(
1423            "gateway",
1424            "openai-responses",
1425            "https://api.example.test/v1",
1426            "fixture-key",
1427            "model-a",
1428            None,
1429            None,
1430            None,
1431            None,
1432        )
1433        .unwrap();
1434        let duplicate = add_provider(
1435            "gateway",
1436            "openai-completions",
1437            "https://api.example.test/v1",
1438            "fixture-key-2",
1439            "model-b",
1440            None,
1441            None,
1442            None,
1443            None,
1444        )
1445        .unwrap_err();
1446        assert!(duplicate.contains("already"));
1447        let unsupported = add_provider(
1448            "other",
1449            "unsupported",
1450            "https://api.example.test/v1",
1451            "fixture-key",
1452            "model-a",
1453            None,
1454            None,
1455            None,
1456            None,
1457        )
1458        .unwrap_err();
1459        assert!(unsupported.contains("unsupported"));
1460        let invalid_context = add_provider(
1461            "context-zero",
1462            "openai-completions",
1463            "https://api.example.test/v1",
1464            "fixture-key",
1465            "model-a",
1466            None,
1467            Some(0),
1468            None,
1469            None,
1470        )
1471        .unwrap_err();
1472        assert!(invalid_context.contains("context window"));
1473    }
1474
1475    #[test]
1476    fn update_and_delete_provider_change_models_json() {
1477        let _cfg = TempConfig::new();
1478        add_provider(
1479            "gateway",
1480            "openai-completions",
1481            "https://api.example.test/v1",
1482            "fixture-key",
1483            "model-a",
1484            Some("Model A"),
1485            Some(128_000),
1486            Some(4096),
1487            Some(false),
1488        )
1489        .unwrap();
1490        update_provider(
1491            "gateway",
1492            "openai-responses",
1493            "https://new.example.test/v1",
1494            None,
1495            "model-b",
1496            Some("Model B"),
1497            Some(256_000),
1498            Some(8192),
1499            true,
1500        )
1501        .unwrap();
1502        let provider = load_models_config()
1503            .unwrap()
1504            .providers
1505            .get("gateway")
1506            .unwrap()
1507            .clone();
1508        assert_eq!(provider.api.as_deref(), Some("openai-responses"));
1509        assert_eq!(
1510            provider.base_url.as_deref(),
1511            Some("https://new.example.test/v1")
1512        );
1513        assert_eq!(provider.api_key.as_deref(), Some("fixture-key"));
1514        assert_eq!(provider.models[0].id, "model-b");
1515        assert_eq!(provider.models[0].max_tokens, Some(8192));
1516        assert_eq!(
1517            provider.models[0].input.as_deref(),
1518            Some(["text".to_string(), "image".to_string()].as_slice())
1519        );
1520        delete_provider("gateway").unwrap();
1521        assert!(!load_models_config()
1522            .unwrap()
1523            .providers
1524            .contains_key("gateway"));
1525    }
1526
1527    #[test]
1528    fn oauth_token_is_scoped_and_round_trips() {
1529        let _cfg = TempConfig::new();
1530        upsert_oauth_token("acme", "access".into(), "refresh".into(), 123).unwrap();
1531        assert!(matches!(
1532            read_oauth_token("acme").unwrap(),
1533            Some(Credential::Oauth { access, refresh, expires })
1534                if access == "access" && refresh == "refresh" && expires == 123
1535        ));
1536        assert!(read_oauth_token("other").unwrap().is_none());
1537    }
1538
1539    #[test]
1540    fn delete_credential_removes_entry() {
1541        let _cfg = TempConfig::new();
1542        upsert_credential(
1543            "anthropic",
1544            Credential::ApiKey {
1545                key: Some("k".into()),
1546                env: None,
1547            },
1548        )
1549        .unwrap();
1550        assert!(delete_credential("anthropic").unwrap());
1551        // Second delete is a no-op.
1552        assert!(!delete_credential("anthropic").unwrap());
1553        assert!(read_auth().unwrap().is_empty());
1554    }
1555
1556    #[test]
1557    fn load_models_config_missing_is_empty() {
1558        let _cfg = TempConfig::new();
1559        let c = load_models_config().unwrap();
1560        assert!(c.providers.is_empty());
1561    }
1562
1563    #[test]
1564    fn fallback_reader_prefers_primary_and_only_falls_back_when_missing() {
1565        let tmp = tempfile::tempdir().unwrap();
1566        let primary = tmp.path().join("primary.json");
1567        let fallback = tmp.path().join("fallback.json");
1568        std::fs::write(&fallback, "fallback").unwrap();
1569
1570        let (_, text) = read_text_with_fallback(primary.clone(), Some(fallback.clone()))
1571            .unwrap()
1572            .expect("fallback should be read");
1573        assert_eq!(text, "fallback");
1574
1575        std::fs::write(&primary, "primary").unwrap();
1576        let (path, text) = read_text_with_fallback(primary.clone(), Some(fallback))
1577            .unwrap()
1578            .expect("primary should be read");
1579        assert_eq!(path, primary);
1580        assert_eq!(text, "primary");
1581    }
1582
1583    #[test]
1584    fn fallback_reader_does_not_mask_primary_read_errors() {
1585        let tmp = tempfile::tempdir().unwrap();
1586        let primary = tmp.path().join("primary.json");
1587        let fallback = tmp.path().join("fallback.json");
1588        std::fs::create_dir(&primary).unwrap();
1589        std::fs::write(&fallback, "fallback").unwrap();
1590
1591        let error = read_text_with_fallback(primary.clone(), Some(fallback)).unwrap_err();
1592        assert!(matches!(error, ConfigError::Read { path, .. } if path == primary));
1593    }
1594
1595    #[test]
1596    fn load_models_config_parses_with_comments() {
1597        let _cfg = TempConfig::new();
1598        let json = r#"{
1599  // a one-api style gateway
1600  "providers": {
1601    "gateway": {
1602      "baseUrl": "https://gw.example.com",
1603      "authHeader": true,
1604      "apiKey": "gw-secret",
1605      "models": [
1606        { "id": "claude-sonnet-5", "name": "Sonnet via gateway" }
1607      ]
1608    }
1609  }
1610}"#;
1611        std::fs::write(models_path().unwrap(), json).unwrap();
1612        let c = load_models_config().unwrap();
1613        let gw = c
1614            .providers
1615            .get("gateway")
1616            .expect("gateway provider present");
1617        assert_eq!(gw.base_url.as_deref(), Some("https://gw.example.com"));
1618        assert!(gw.auth_header.unwrap_or(false));
1619        assert_eq!(gw.models.len(), 1);
1620        assert_eq!(gw.models[0].id, "claude-sonnet-5");
1621    }
1622
1623    #[test]
1624    fn provider_to_models_merges_headers_without_synth_bearer() {
1625        // `provider_to_models` merges model-level then provider-level headers,
1626        // but does NOT synthesize the `authHeader:true` Bearer itself — that
1627        // happens centrally in `crate::provider::resolve` (via
1628        // `models_json_bearer_token`) so it can be skipped on the x-api-key
1629        // path. Here the model carries only what the file declared.
1630        let cfg = ProviderConfig {
1631            name: None,
1632            base_url: Some("https://gw.example.com".into()),
1633            api_key: Some("gw-secret".into()),
1634            api: None,
1635            headers: Some({
1636                let mut h = BTreeMap::new();
1637                h.insert("x-portkey-key".into(), "portkey-secret".into());
1638                h
1639            }),
1640            auth_header: Some(true),
1641            models: vec![ModelDefinition {
1642                id: "claude-sonnet-5".into(),
1643                name: None,
1644                base_url: None,
1645                reasoning: None,
1646                thinking_level_map: None,
1647                context_window: None,
1648                max_tokens: None,
1649                cost: None,
1650                input: None,
1651                headers: None,
1652                compat: None,
1653            }],
1654        };
1655        let models = provider_to_models("gateway", &cfg).expect("anthropic-compatible");
1656        assert_eq!(models.len(), 1);
1657        let m = &models[0];
1658        assert_eq!(m.id, "claude-sonnet-5");
1659        assert_eq!(m.base_url, "https://gw.example.com");
1660        assert_eq!(m.provider, "gateway");
1661        let headers = m.headers.as_ref().expect("provider headers merged");
1662        // Declared provider header folds in…
1663        assert_eq!(
1664            headers.get("x-portkey-key").map(|s| s.as_str()),
1665            Some("portkey-secret")
1666        );
1667        // …but no Bearer is synthesized here. The bearer-from-authHeader path
1668        // is exercised end-to-end by the provider.rs `resolve` tests
1669        // (`models_json_auth_header_satisfies_auth_without_env`,
1670        // `api_key_flag_beats_models_json_bearer`).
1671        assert!(
1672            headers.get("authorization").is_none(),
1673            "provider_to_models must not synthesize the Bearer; resolve does"
1674        );
1675    }
1676
1677    #[test]
1678    fn provider_to_models_supports_openai_completions() {
1679        let config: ModelsConfig = serde_json::from_str(
1680            r#"{
1681                "providers": {
1682                    "oai": {
1683                        "api": "openai-completions",
1684                        "baseUrl": "https://gateway.example.com/v1",
1685                        "apiKey": "secret",
1686                        "models": [{"id":"gpt-test","maxTokens":4096}]
1687                    }
1688                }
1689            }"#,
1690        )
1691        .unwrap();
1692        let models = provider_to_models("oai", &config.providers["oai"]).unwrap();
1693        assert_eq!(models.len(), 1);
1694        assert_eq!(models[0].api, Api::OpenaiCompletions);
1695        assert_eq!(models[0].provider, "oai");
1696        assert_eq!(models[0].max_tokens, 4096);
1697        assert_eq!(models[0].cost, ModelCost::default());
1698        assert!(!models[0].has_pricing());
1699        assert!(
1700            models[0].headers.is_none(),
1701            "credentials are bound after provider resolution"
1702        );
1703    }
1704
1705    #[test]
1706    fn models_json_pricing_reaches_providers_and_survives_serialization() {
1707        let mut config = parse_models_json(
1708            r#"{
1709                "providers": {
1710                    "pricing-fixture": {
1711                        "api": "anthropic-messages",
1712                        "models": [{
1713                            "id": "priced-model",
1714                            "cost": {
1715                                "input": 2, "output": 8, "cacheRead": 0.2, "cacheWrite": 2.5,
1716                                "tiers": [{
1717                                    "inputTokensAbove": 1000000,
1718                                    "input": 4, "output": 16, "cacheRead": 0.4, "cacheWrite": 5
1719                                }]
1720                            }
1721                        }]
1722                    }
1723                }
1724            }"#,
1725        )
1726        .unwrap();
1727        let expected = config.providers["pricing-fixture"].models[0]
1728            .cost
1729            .clone()
1730            .unwrap();
1731        for api in [
1732            "anthropic-messages",
1733            "openai-completions",
1734            "openai-responses",
1735        ] {
1736            let cfg = config.providers.get_mut("pricing-fixture").unwrap();
1737            cfg.api = Some(api.into());
1738            let models = provider_to_models("pricing-fixture", cfg).unwrap();
1739            assert_eq!(models[0].cost, expected);
1740            assert!(models[0].has_pricing());
1741            let mut usage = rpi_ai::Usage::zero();
1742            usage.input = 100_000;
1743            usage.output = 250_000;
1744            usage.cache_read = 300_000;
1745            usage.cache_write = 400_000;
1746            let cost = rpi_ai::providers::anthropic::cost::calculate_cost(&models[0].cost, &usage);
1747            assert!((cost.total - 3.26).abs() < 1e-10, "base pricing for {api}");
1748            usage.input = 1_000_001;
1749            usage.output = 1_000_000;
1750            usage.cache_read = 0;
1751            usage.cache_write = 0;
1752            let cost = rpi_ai::providers::anthropic::cost::calculate_cost(&models[0].cost, &usage);
1753            assert!(
1754                (cost.total - 20.000004).abs() < 1e-10,
1755                "tiered pricing for {api}"
1756            );
1757        }
1758        let saved = serde_json::to_string(&config).unwrap();
1759        let reloaded = parse_models_json(&saved).unwrap();
1760        assert_eq!(
1761            reloaded.providers["pricing-fixture"].models[0].cost,
1762            Some(expected)
1763        );
1764        let cfg = config.providers.get_mut("pricing-fixture").unwrap();
1765        cfg.models[0].cost = Some(ModelCost::default());
1766        let free = provider_to_models("pricing-fixture", cfg).unwrap();
1767        assert_eq!(free[0].cost, ModelCost::default());
1768        assert!(
1769            free[0].has_pricing(),
1770            "explicit zero prices are still configured"
1771        );
1772    }
1773
1774    #[test]
1775    fn models_json_compat_reaches_the_model_for_openai_completions() {
1776        // The `compat` block is what lets a custom openai-completions provider
1777        // describe its quirks. `requiresThinkingAsText` is the one that decides
1778        // whether the model's own reasoning is sent back or dropped — see
1779        // `docs/debugging/llm-repetition-forensics.md` §八. If this hop ever breaks, the
1780        // setting silently does nothing (the provider falls back to
1781        // `Content::text_only`, which drops every thinking block).
1782        let config: ModelsConfig = serde_json::from_str(
1783            r#"{
1784                "providers": {
1785                    "qwen": {
1786                        "api": "openai-completions",
1787                        "baseUrl": "https://coding.example.com/v1",
1788                        "apiKey": "secret",
1789                        "models": [{
1790                            "id": "qwen3.7-plus",
1791                            "maxTokens": 131072,
1792                            "thinkingLevelMap": { "xhigh": "xhigh", "max": "max" },
1793                            "compat": { "requiresThinkingAsText": true }
1794                        }]
1795                    }
1796                }
1797            }"#,
1798        )
1799        .unwrap();
1800        let models = provider_to_models("qwen", &config.providers["qwen"]).unwrap();
1801        assert_eq!(
1802            models[0]
1803                .thinking_level_map
1804                .as_ref()
1805                .unwrap()
1806                .get(&rpi_ai::ThinkingLevel::Xhigh),
1807            Some(&Some("xhigh".into()))
1808        );
1809        match models[0].compat.as_ref().expect("compat must survive") {
1810            StreamingProtocolCompat::OpenaiCompletions(compat) => {
1811                assert_eq!(compat.requires_thinking_as_text, Some(true));
1812            }
1813            other => panic!("expected OpenaiCompletions compat, got {other:?}"),
1814        }
1815
1816        // An entry without `compat` stays on the default (thinking dropped).
1817        let plain: ModelsConfig = serde_json::from_str(
1818            r#"{
1819                "providers": {
1820                    "qwen": {
1821                        "api": "openai-completions",
1822                        "baseUrl": "https://coding.example.com/v1",
1823                        "apiKey": "secret",
1824                        "models": [{"id":"qwen3.7-plus"}]
1825                    }
1826                }
1827            }"#,
1828        )
1829        .unwrap();
1830        let plain_models = provider_to_models("qwen", &plain.providers["qwen"]).unwrap();
1831        assert!(plain_models[0].compat.is_none());
1832    }
1833
1834    #[test]
1835    fn models_json_accepts_pi_deepseek_compat_and_warns_on_unknown_or_invalid_fields() {
1836        let mut config: ModelsConfig = serde_json::from_value(serde_json::json!({
1837            "providers": { "deepseek": {
1838                "api": "openai-completions",
1839                "models": [{ "id": "reasoner", "reasoning": true, "compat": {
1840                    "thinkingFormat": "deepseek",
1841                    "requiresReasoningContentOnAssistantMessages": true
1842                }}]
1843            }}
1844        }))
1845        .unwrap();
1846        assert!(model_compat_warnings(&config).is_empty());
1847        let models = provider_to_models("deepseek", &config.providers["deepseek"]).unwrap();
1848        assert!(rpi_ai::model::prior_reasoning_is_replayed(&models[0]));
1849        let Some(StreamingProtocolCompat::OpenaiCompletions(compat)) = &models[0].compat else {
1850            panic!("missing model compatibility flags");
1851        };
1852        assert_eq!(compat.requires_reasoning_content, Some(true));
1853        assert_eq!(
1854            compat.thinking_format,
1855            Some(rpi_ai::model::OpenaiThinkingFormat::Deepseek)
1856        );
1857
1858        config.providers["deepseek"].models[0]
1859            .compat
1860            .as_mut()
1861            .unwrap()["misspelledField"] = serde_json::json!("secret-fixture-value");
1862        let warnings = model_compat_warnings(&config);
1863        assert_eq!(warnings.len(), 1);
1864        assert!(warnings[0].contains("deepseek") && warnings[0].contains("reasoner"));
1865        assert!(warnings[0].contains("unknown field \"misspelledField\""));
1866        assert!(!warnings[0].contains("secret-fixture-value"));
1867
1868        config.providers["deepseek"].models[0].compat =
1869            Some(serde_json::json!({"requiresReasoningContent": "secret-fixture-token"}));
1870        let warning = &model_compat_warnings(&config)[0];
1871        assert!(warning.contains("invalid configuration"));
1872        assert!(!warning.contains("secret-fixture-token"));
1873        config.providers["deepseek"].models[0].compat =
1874            Some(serde_json::json!({"thinkingFormat": "unsupported"}));
1875        assert!(model_compat_warnings(&config)[0].contains("invalid configuration"));
1876    }
1877
1878    #[test]
1879    fn responses_compat_diagnostics_use_the_responses_schema() {
1880        let config: ModelsConfig = serde_json::from_value(serde_json::json!({
1881            "providers": { "relay": {
1882                "api": "openai-responses", "models": [{ "id": "test", "compat": {
1883                    "supportsOpenAIGrammarTools": true, "supportsStore": false
1884                }}]
1885            }}
1886        }))
1887        .unwrap();
1888        let warnings = model_compat_warnings(&config);
1889        assert_eq!(warnings.len(), 1);
1890        assert!(warnings[0].contains("supportsStore"));
1891    }
1892
1893    #[test]
1894    fn native_reasoning_content_key_wins_over_a_conflicting_pi_alias() {
1895        let config: ModelsConfig = serde_json::from_value(serde_json::json!({
1896            "providers": { "relay": {
1897                "api": "openai-completions", "models": [{ "id": "test", "compat": {
1898                    "requiresReasoningContent": false,
1899                    "requiresReasoningContentOnAssistantMessages": true
1900                }}]
1901            }}
1902        }))
1903        .unwrap();
1904        let warnings = model_compat_warnings(&config);
1905        assert_eq!(warnings.len(), 1);
1906        assert!(warnings[0].contains("takes precedence"));
1907        let models = provider_to_models("relay", &config.providers["relay"]).unwrap();
1908        let Some(StreamingProtocolCompat::OpenaiCompletions(compat)) = &models[0].compat else {
1909            panic!("valid native flag must survive an alias conflict");
1910        };
1911        assert_eq!(compat.requires_reasoning_content, Some(false));
1912    }
1913
1914    #[test]
1915    fn custom_openai_provider_resolves_explicit_api_key_environment_reference() {
1916        let _guard = env_lock().lock().unwrap();
1917        let env_name = "RPI_FAKE_PROVIDER_API_KEY";
1918        std::env::set_var(env_name, "env-secret");
1919        let cfg = ProviderConfig {
1920            name: None,
1921            base_url: Some("https://gateway.example.com/v1".into()),
1922            api_key: Some("$RPI_FAKE_PROVIDER_API_KEY".into()),
1923            api: Some("openai-completions".into()),
1924            headers: None,
1925            auth_header: None,
1926            models: vec![ModelDefinition {
1927                id: "fake-model".into(),
1928                name: None,
1929                base_url: None,
1930                reasoning: None,
1931                thinking_level_map: None,
1932                context_window: None,
1933                max_tokens: None,
1934                cost: None,
1935                input: None,
1936                headers: None,
1937                compat: None,
1938            }],
1939        };
1940        let models = provider_to_models("rpi-fake-provider", &cfg).unwrap();
1941        assert_eq!(
1942            openai_provider_api_key("rpi-fake-provider", &cfg).as_deref(),
1943            Some("env-secret")
1944        );
1945        assert!(
1946            models[0].headers.is_none(),
1947            "discovery does not bind credentials"
1948        );
1949        std::env::remove_var(env_name);
1950    }
1951
1952    #[test]
1953    fn openai_protocol_ids_do_not_inherit_the_official_env_key() {
1954        let _guard = env_lock().lock().unwrap();
1955        let prev_openai = std::env::var_os("OPENAI_API_KEY");
1956        let prev_completions = std::env::var_os("OPENAI_COMPLETIONS_API_KEY");
1957        let prev_responses = std::env::var_os("OPENAI_RESPONSES_API_KEY");
1958        std::env::set_var("OPENAI_API_KEY", "official-key");
1959        std::env::remove_var("OPENAI_COMPLETIONS_API_KEY");
1960        std::env::remove_var("OPENAI_RESPONSES_API_KEY");
1961        let config = ProviderConfig {
1962            name: None,
1963            base_url: Some("https://gateway.example.com/v1".into()),
1964            api_key: None,
1965            api: Some("openai-responses".into()),
1966            headers: None,
1967            auth_header: None,
1968            models: Vec::new(),
1969        };
1970
1971        assert_eq!(
1972            openai_provider_api_key("openai", &config).as_deref(),
1973            Some("official-key")
1974        );
1975        assert!(openai_provider_api_key("openai-completions", &config).is_none());
1976        assert!(openai_provider_api_key("openai-responses", &config).is_none());
1977        assert!(openai_provider_api_key("OpenAI", &config).is_none());
1978
1979        restore_env("OPENAI_API_KEY", prev_openai);
1980        restore_env("OPENAI_COMPLETIONS_API_KEY", prev_completions);
1981        restore_env("OPENAI_RESPONSES_API_KEY", prev_responses);
1982    }
1983
1984    #[test]
1985    fn native_provider_api_key_env_mapping_uses_exact_provider_ids() {
1986        assert_eq!(
1987            native_provider_api_key_env_var("openai"),
1988            Some("OPENAI_API_KEY")
1989        );
1990        for provider in [
1991            "deepseek",
1992            "openrouter",
1993            "google",
1994            "groq",
1995            "qwen",
1996            "nvidia",
1997            "OpenAI",
1998            "openai-completions",
1999        ] {
2000            assert_eq!(
2001                native_provider_api_key_env_var(provider),
2002                None,
2003                "external providers must declare auth in their package or models.json"
2004            );
2005        }
2006    }
2007
2008    #[test]
2009    fn malformed_auth_json_is_an_error_not_silent_empty() {
2010        let _cfg = TempConfig::new();
2011        std::fs::write(auth_path().unwrap(), "{ not json").unwrap();
2012        assert!(matches!(read_auth(), Err(ConfigError::Json { .. })));
2013    }
2014
2015    #[test]
2016    fn agent_dir_nests_under_agent_by_default() {
2017        // With no env override, agent_dir() must end in `.../.rpi/agent`
2018        // (mirrors pi's `getAgentDir`). We can't assertion the home prefix
2019        // portably, but the leaf two segments are stable.
2020        let _guard = env_lock().lock().unwrap();
2021        let prev = std::env::var_os(CONFIG_DIR_ENV);
2022        std::env::remove_var(CONFIG_DIR_ENV);
2023        let dir = agent_dir().unwrap();
2024        restore_env(CONFIG_DIR_ENV, prev);
2025        assert!(dir.ends_with("agent"));
2026        assert!(dir
2027            .parent()
2028            .map(|p| p.ends_with(CONFIG_DIR_NAME))
2029            .unwrap_or(false));
2030    }
2031
2032    #[test]
2033    fn migrate_legacy_layout_moves_flat_files_into_agent() {
2034        // Drive the core migration directly against a temp root/agent so the
2035        // result is independent of whatever RPI_CODING_AGENT_DIR the parallel
2036        // TempConfig tests happen to set.
2037        let tmp = tempfile::TempDir::new().unwrap();
2038        let root = tmp.path().to_path_buf();
2039        let agent = root.join("agent");
2040        std::fs::write(root.join("auth.json"), "{}").unwrap();
2041        std::fs::write(root.join("models.json"), "{}").unwrap();
2042        std::fs::write(root.join(".setup_done"), "1").unwrap();
2043        let moved = migrate_legacy_layout_in(&root, &agent).unwrap();
2044        assert_eq!(moved, 3);
2045        assert!(agent.join("auth.json").exists());
2046        assert!(agent.join("models.json").exists());
2047        assert!(agent.join(".setup_done").exists());
2048        assert!(!root.join("auth.json").exists());
2049    }
2050
2051    #[test]
2052    fn migrate_legacy_layout_noop_when_agent_exists() {
2053        let tmp = tempfile::TempDir::new().unwrap();
2054        let root = tmp.path().to_path_buf();
2055        let agent = root.join("agent");
2056        std::fs::write(root.join("auth.json"), "{}").unwrap();
2057        std::fs::create_dir_all(&agent).unwrap();
2058        let moved = migrate_legacy_layout_in(&root, &agent).unwrap();
2059        assert_eq!(moved, 0); // agent/ already present — leave flat file alone
2060    }
2061
2062    #[test]
2063    fn migrate_legacy_layout_noop_when_no_flat_files() {
2064        let tmp = tempfile::TempDir::new().unwrap();
2065        let root = tmp.path().to_path_buf();
2066        let agent = root.join("agent");
2067        let moved = migrate_legacy_layout_in(&root, &agent).unwrap();
2068        assert_eq!(moved, 0);
2069    }
2070
2071    #[test]
2072    fn migrate_legacy_layout_public_skips_env_override() {
2073        // When RPI_CODING_AGENT_DIR is set, the public entry point is a no-op
2074        // (it must never touch an explicit override). TempConfig sets it.
2075        let _cfg = TempConfig::new();
2076        let moved = migrate_legacy_layout().unwrap();
2077        assert_eq!(moved, 0);
2078    }
2079
2080    #[test]
2081    fn read_trust_missing_file_is_empty() {
2082        let _cfg = TempConfig::new();
2083        assert!(read_trust().unwrap().is_empty());
2084    }
2085
2086    #[test]
2087    fn read_trust_parses_decisions() {
2088        let _cfg = TempConfig::new();
2089        let path = trust_path().unwrap();
2090        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
2091        std::fs::write(
2092            &path,
2093            r#"{ "/home/me/proj": true, "/home/me/untrusted": false, "/home/me/null": null }"#,
2094        )
2095        .unwrap();
2096        let store = read_trust().unwrap();
2097        assert_eq!(store.len(), 3);
2098        assert_eq!(store.get("/home/me/proj").copied().flatten(), Some(true));
2099        assert_eq!(
2100            store.get("/home/me/untrusted").copied().flatten(),
2101            Some(false)
2102        );
2103        assert_eq!(store.get("/home/me/null").copied().flatten(), None);
2104    }
2105
2106    #[test]
2107    fn resolve_config_value_literal_passthrough() {
2108        assert_eq!(
2109            resolve_config_value("sk-literal-key", None),
2110            Some("sk-literal-key".into())
2111        );
2112    }
2113
2114    #[test]
2115    fn resolve_config_value_env_var() {
2116        let _guard = env_lock().lock().unwrap();
2117        let prev = std::env::var_os("RPI_TEST_CFG_KEY");
2118        let prev2 = std::env::var_os("RPI_TEST_CFG_KEY2");
2119        std::env::set_var("RPI_TEST_CFG_KEY", "secret-from-env");
2120        assert_eq!(
2121            resolve_config_value("$RPI_TEST_CFG_KEY", None),
2122            Some("secret-from-env".into())
2123        );
2124        assert_eq!(
2125            resolve_config_value("prefix-${RPI_TEST_CFG_KEY}-suffix", None),
2126            Some("prefix-secret-from-env-suffix".into())
2127        );
2128        // Two vars in one template.
2129        std::env::set_var("RPI_TEST_CFG_KEY2", "two");
2130        assert_eq!(
2131            resolve_config_value("a-$RPI_TEST_CFG_KEY-b-$RPI_TEST_CFG_KEY2-c", None),
2132            Some("a-secret-from-env-b-two-c".into())
2133        );
2134        // Env overlay wins over process env.
2135        let mut overlay = BTreeMap::new();
2136        overlay.insert("RPI_TEST_CFG_KEY".into(), "overlay-value".into());
2137        assert_eq!(
2138            resolve_config_value("$RPI_TEST_CFG_KEY", Some(&overlay)),
2139            Some("overlay-value".into())
2140        );
2141        restore_env("RPI_TEST_CFG_KEY", prev);
2142        restore_env("RPI_TEST_CFG_KEY2", prev2);
2143    }
2144
2145    #[test]
2146    fn resolve_config_value_unset_env_is_none() {
2147        let _guard = env_lock().lock().unwrap();
2148        let prev = std::env::var_os("RPI_TEST_CFG_ABSENT");
2149        std::env::remove_var("RPI_TEST_CFG_ABSENT");
2150        // Any referenced unset var ⇒ the whole value is None (pi semantics).
2151        assert_eq!(resolve_config_value("$RPI_TEST_CFG_ABSENT", None), None);
2152        assert_eq!(
2153            resolve_config_value("prefix-$RPI_TEST_CFG_ABSENT-suffix", None),
2154            None
2155        );
2156        restore_env("RPI_TEST_CFG_ABSENT", prev);
2157    }
2158
2159    #[test]
2160    fn resolve_config_value_dollar_dollar_escapes_literal() {
2161        assert_eq!(
2162            resolve_config_value("price-$$5", None),
2163            Some("price-$5".into())
2164        );
2165        assert_eq!(resolve_config_value("$!bang", None), Some("!bang".into()));
2166    }
2167
2168    #[test]
2169    fn resolve_config_value_command_runs_shell() {
2170        // `!echo resolved` → "resolved" (sh on Unix; `echo` works under cmd too).
2171        assert_eq!(
2172            resolve_config_value_uncached("!echo rpi-cfg-resolved", None),
2173            Some("rpi-cfg-resolved".into())
2174        );
2175        // Non-zero exit ⇒ None.
2176        assert_eq!(resolve_config_value_uncached("!false", None), None);
2177    }
2178
2179    #[test]
2180    fn resolve_headers_drops_unresolvable() {
2181        let _guard = env_lock().lock().unwrap();
2182        let prev = std::env::var_os("RPI_TEST_HDR_SET");
2183        std::env::set_var("RPI_TEST_HDR_SET", "set-value");
2184        let mut h = BTreeMap::new();
2185        h.insert("x-set".into(), "$RPI_TEST_HDR_SET".into());
2186        h.insert("x-unset".into(), "$RPI_TEST_HDR_UNSET".into());
2187        h.insert("x-literal".into(), "literal-value".into());
2188        let resolved = resolve_headers(&h, None);
2189        assert_eq!(resolved.len(), 2);
2190        assert_eq!(resolved.get("x-set").map(|s| s.as_str()), Some("set-value"));
2191        assert_eq!(
2192            resolved.get("x-literal").map(|s| s.as_str()),
2193            Some("literal-value")
2194        );
2195        assert!(!resolved.contains_key("x-unset"));
2196        restore_env("RPI_TEST_HDR_SET", prev);
2197    }
2198
2199    #[test]
2200    fn agent_dir_respects_env_override() {
2201        let _guard = env_lock().lock().unwrap();
2202        let prev = std::env::var_os(CONFIG_DIR_ENV);
2203        let tmp = tempfile::TempDir::new().unwrap();
2204        std::env::set_var(CONFIG_DIR_ENV, tmp.path());
2205        let dir = agent_dir().unwrap();
2206        restore_env(CONFIG_DIR_ENV, prev);
2207        assert_eq!(dir, tmp.path());
2208    }
2209
2210    #[test]
2211    fn relative_override_is_rejected() {
2212        let _guard = env_lock().lock().unwrap();
2213        let prev = std::env::var_os(CONFIG_DIR_ENV);
2214        std::env::set_var(CONFIG_DIR_ENV, "relative/path");
2215        let err = agent_dir().unwrap_err();
2216        restore_env(CONFIG_DIR_ENV, prev);
2217        assert!(matches!(err, ConfigError::RelativeOverride { .. }));
2218    }
2219
2220    /// Restore/remove an env var based on its prior `OsString` value.
2221    fn restore_env(name: &str, prev: Option<std::ffi::OsString>) {
2222        match prev {
2223            Some(v) => std::env::set_var(name, v),
2224            None => std::env::remove_var(name),
2225        }
2226    }
2227}
2228
2229/// Convert host configuration with the same rules as the embeddable runtime.
2230pub fn provider_to_models(provider_id: &str, cfg: &ProviderConfig) -> Option<Vec<Model>> {
2231    rpi_runtime::config::provider_to_models(provider_id, cfg, &crate::provider::CliValues)
2232}