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 [`AgentHome`] 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::InvalidAgentHome {
82                val: dir.to_string_lossy().into_owned(),
83            });
84        }
85        return Ok(dir.to_path_buf());
86    }
87    if let Some(val) = std::env::var_os(CONFIG_DIR_ENV) {
88        let p = PathBuf::from(&val);
89        if !p.is_absolute() {
90            return Err(ConfigError::RelativeOverride {
91                env: CONFIG_DIR_ENV,
92                val: val.to_string_lossy().into_owned(),
93            });
94        }
95        return Ok(p);
96    }
97    let home = dirs::home_dir().ok_or(ConfigError::NoHomeDir {
98        env: CONFIG_DIR_ENV,
99    })?;
100    Ok(home.join(CONFIG_DIR_NAME).join("agent"))
101}
102
103/// One session's agent home.
104///
105/// `explicit = Some(path)` is the library-embedding mode: every reader and
106/// writer is addressed through this value, so several harnesses can live in one
107/// process with different homes. CLI sessions use [`AgentHome::process`], which
108/// preserves the historical `RPI_CODING_AGENT_DIR` / `~/.rpi/agent` behavior.
109#[derive(Clone, Debug, Default, PartialEq, Eq)]
110pub struct AgentHome {
111    explicit: Option<PathBuf>,
112}
113
114impl AgentHome {
115    /// The historical process home (`RPI_CODING_AGENT_DIR` / `~/.rpi/agent`).
116    pub fn process() -> Self {
117        Self::default()
118    }
119
120    /// Build an agent home from an optional explicit path.
121    ///
122    /// `Some(path)` is validated eagerly: the path must be absolute. Returning
123    /// an error here (instead of lazily on first use) keeps every later reader
124    /// infallible with respect to home shape and prevents a partially applied
125    /// home in embedders that tolerate per-call errors.
126    pub fn from_option(explicit: Option<PathBuf>) -> Result<Self, ConfigError> {
127        if let Some(path) = explicit.as_deref() {
128            if !path.is_absolute() {
129                return Err(ConfigError::InvalidAgentHome {
130                    val: path.to_string_lossy().into_owned(),
131                });
132            }
133        }
134        Ok(Self { explicit })
135    }
136
137    pub fn explicit_path(&self) -> Option<&Path> {
138        self.explicit.as_deref()
139    }
140
141    pub fn is_explicit(&self) -> bool {
142        self.explicit.is_some()
143    }
144
145    pub fn root(&self) -> Result<PathBuf, ConfigError> {
146        agent_dir_at(self.explicit_path())
147    }
148
149    pub fn auth_path(&self) -> Result<PathBuf, ConfigError> {
150        Ok(self.root()?.join("auth.json"))
151    }
152
153    pub fn models_path(&self) -> Result<PathBuf, ConfigError> {
154        Ok(self.root()?.join("models.json"))
155    }
156
157    pub fn settings_path(&self) -> Result<PathBuf, ConfigError> {
158        Ok(self.root()?.join("settings.json"))
159    }
160
161    pub fn trust_path(&self) -> Result<PathBuf, ConfigError> {
162        Ok(self.root()?.join("trust.json"))
163    }
164
165    pub fn read_auth(&self) -> Result<AuthStore, ConfigError> {
166        read_auth_at(self.explicit_path())
167    }
168
169    pub fn write_auth(&self, store: &AuthStore) -> Result<(), ConfigError> {
170        write_auth_at(self.explicit_path(), store)
171    }
172
173    pub fn upsert_credential(
174        &self,
175        provider_id: &str,
176        cred: Credential,
177    ) -> Result<(), ConfigError> {
178        upsert_credential_at(self.explicit_path(), provider_id, cred)
179    }
180
181    pub fn upsert_oauth_token(
182        &self,
183        provider_id: &str,
184        access: String,
185        refresh: String,
186        expires: i64,
187    ) -> Result<(), ConfigError> {
188        upsert_oauth_token_at(self.explicit_path(), provider_id, access, refresh, expires)
189    }
190
191    pub fn replace_oauth_token_if_unchanged(
192        &self,
193        provider_id: &str,
194        expected: (&str, &str, i64),
195        access: String,
196        refresh: String,
197        expires: i64,
198    ) -> Result<bool, ConfigError> {
199        replace_oauth_token_if_unchanged_at(
200            self.explicit_path(),
201            provider_id,
202            expected,
203            access,
204            refresh,
205            expires,
206        )
207    }
208
209    pub fn read_oauth_token(&self, provider_id: &str) -> Result<Option<Credential>, ConfigError> {
210        read_oauth_token_at(self.explicit_path(), provider_id)
211    }
212
213    pub fn delete_credential(&self, provider_id: &str) -> Result<bool, ConfigError> {
214        delete_credential_at(self.explicit_path(), provider_id)
215    }
216
217    pub fn models_config(&self) -> Result<ModelsConfig, ConfigError> {
218        load_models_config_at(self.explicit_path())
219    }
220
221    pub fn save_models_config(&self, cfg: &ModelsConfig) -> Result<(), ConfigError> {
222        save_models_config_at(self.explicit_path(), cfg)
223    }
224
225    pub fn add_provider(
226        &self,
227        provider_id: &str,
228        api: &str,
229        base_url: &str,
230        api_key: &str,
231        model: ProviderModelConfig<'_>,
232        supports_images: Option<bool>,
233    ) -> Result<(), String> {
234        add_provider_at(
235            self.explicit_path(),
236            provider_id,
237            api,
238            base_url,
239            api_key,
240            model,
241            supports_images,
242        )
243    }
244
245    pub fn update_provider(
246        &self,
247        provider_id: &str,
248        api: &str,
249        base_url: &str,
250        api_key: Option<&str>,
251        model: ProviderModelConfig<'_>,
252        supports_images: bool,
253    ) -> Result<(), String> {
254        update_provider_at(
255            self.explicit_path(),
256            provider_id,
257            api,
258            base_url,
259            api_key,
260            model,
261            supports_images,
262        )
263    }
264
265    pub fn delete_provider(&self, provider_id: &str) -> Result<(), String> {
266        delete_provider_at(self.explicit_path(), provider_id)
267    }
268
269    pub fn read_trust(&self) -> Result<TrustStore, ConfigError> {
270        read_trust_at(self.explicit_path())
271    }
272
273    pub fn project_trust_decision(&self, cwd: &Path) -> Result<Option<bool>, ConfigError> {
274        project_trust_decision_at(self.explicit_path(), cwd)
275    }
276
277    pub fn set_project_trust(&self, cwd: &Path, trusted: Option<bool>) -> Result<(), ConfigError> {
278        set_project_trust_at(self.explicit_path(), cwd, trusted)
279    }
280}
281
282/// The config dir one level above the agent dir (`~/.rpi`, or the parent of an
283/// env override). Used by [`migrate_legacy_layout`] to locate the old flat
284/// layout. Returns `None` when the env override has no parent (a root path).
285fn config_root_dir() -> Result<PathBuf, ConfigError> {
286    let agent = agent_dir()?;
287    agent
288        .parent()
289        .map(Path::to_path_buf)
290        .ok_or(ConfigError::NoHomeDir {
291            env: CONFIG_DIR_ENV,
292        })
293}
294
295/// `~/.rpi/agent/auth.json`.
296pub fn auth_path() -> Result<PathBuf, ConfigError> {
297    auth_path_at(None)
298}
299
300pub(crate) fn auth_path_at(agent_dir: Option<&Path>) -> Result<PathBuf, ConfigError> {
301    Ok(agent_dir_at(agent_dir)?.join("auth.json"))
302}
303
304/// `~/.rpi/agent/models.json`.
305pub fn models_path() -> Result<PathBuf, ConfigError> {
306    models_path_at(None)
307}
308
309pub(crate) fn models_path_at(agent_dir: Option<&Path>) -> Result<PathBuf, ConfigError> {
310    Ok(agent_dir_at(agent_dir)?.join("models.json"))
311}
312
313/// `~/.rpi/agent/settings.json` (saved default provider/model/thinking + theme).
314pub fn settings_path() -> Result<PathBuf, ConfigError> {
315    settings_path_at(None)
316}
317
318pub(crate) fn settings_path_at(agent_dir: Option<&Path>) -> Result<PathBuf, ConfigError> {
319    Ok(agent_dir_at(agent_dir)?.join("settings.json"))
320}
321
322/// `~/.rpi/agent/trust.json` (per-cwd project trust decisions).
323pub fn trust_path() -> Result<PathBuf, ConfigError> {
324    trust_path_at(None)
325}
326
327pub(crate) fn trust_path_at(agent_dir: Option<&Path>) -> Result<PathBuf, ConfigError> {
328    Ok(agent_dir_at(agent_dir)?.join("trust.json"))
329}
330
331fn read_text_with_fallback(
332    primary: PathBuf,
333    fallback: Option<PathBuf>,
334) -> Result<Option<(PathBuf, String)>, ConfigError> {
335    match std::fs::read_to_string(&primary) {
336        Ok(text) => Ok(Some((primary, text))),
337        Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
338            let Some(fallback) = fallback.filter(|path| path != &primary) else {
339                return Ok(None);
340            };
341            match std::fs::read_to_string(&fallback) {
342                Ok(text) => Ok(Some((fallback, text))),
343                Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(None),
344                Err(source) => Err(ConfigError::Read {
345                    path: fallback,
346                    source,
347                }),
348            }
349        }
350        Err(source) => Err(ConfigError::Read {
351            path: primary,
352            source,
353        }),
354    }
355}
356
357/// One-time best-effort migration of a pre-nesting flat layout
358/// (`~/.rpi/{auth.json,models.json,.setup_done}`) into the
359/// nested `~/.rpi/agent/` layout. **No-op when `RPI_CODING_AGENT_DIR` is set**
360/// (never touch an explicit override), when the agent dir already exists, or
361/// when no flat files are present. Idempotent: a partial move resumes. Errors
362/// are swallowed (logged via the returned `Result` only so tests can observe);
363/// `app::run` ignores them so a migration hiccup never blocks startup.
364pub fn migrate_legacy_layout() -> Result<usize, ConfigError> {
365    // Only migrate the default home-backed layout — never an env override.
366    if std::env::var_os(CONFIG_DIR_ENV).is_some() {
367        return Ok(0);
368    }
369    let root = match config_root_dir() {
370        Ok(p) => p,
371        Err(_) => return Ok(0),
372    };
373    let agent = agent_dir()?;
374    migrate_legacy_layout_in(&root, &agent)
375}
376
377/// The core migration (no env gate): if `agent/` is absent but flat files exist
378/// under `root`, move `{auth.json,models.json,.setup_done}` into
379/// `agent/`. Idempotent. Factored out so tests can drive it against a temp
380/// root/agent pair without touching the env (the public
381/// [`migrate_legacy_layout`] short-circuits on an env override, which tests
382/// can't unset portably while other tests run).
383fn migrate_legacy_layout_in(root: &Path, agent: &Path) -> Result<usize, ConfigError> {
384    // If the agent dir already exists with any content, assume already migrated.
385    if agent.exists() {
386        return Ok(0);
387    }
388    // Probe for a flat file. If none, nothing to migrate.
389    let flat_auth = root.join("auth.json");
390    let flat_models = root.join("models.json");
391    if !flat_auth.exists() && !flat_models.exists() {
392        return Ok(0);
393    }
394    std::fs::create_dir_all(agent).map_err(|e| ConfigError::Write {
395        path: agent.to_path_buf(),
396        source: e,
397    })?;
398    let mut moved = 0usize;
399    for leaf in ["auth.json", "models.json", ".setup_done"] {
400        let from = root.join(leaf);
401        let to = agent.join(leaf);
402        if from.exists() && !to.exists() {
403            // `rename` across the same filesystem is atomic; fall back to copy
404            // + remove on cross-device (rare for a home dir).
405            if let Err(_e) = std::fs::rename(&from, &to) {
406                if std::fs::copy(&from, &to).is_ok() {
407                    let _ = std::fs::remove_file(&from);
408                }
409            }
410            moved += 1;
411        }
412    }
413    Ok(moved)
414}
415
416// ---------------------------------------------------------------------------
417// auth.json — Credential store
418// ---------------------------------------------------------------------------
419
420/// Read the auth store. Missing file ⇒ empty store (not an error). Malformed
421/// JSON ⇒ `ConfigError::Json` (we do not silently swallow a corrupt auth file).
422pub fn read_auth() -> Result<AuthStore, ConfigError> {
423    read_auth_at(None)
424}
425
426/// [`read_auth`] against an explicit agent home.
427pub(crate) fn read_auth_at(agent_dir: Option<&Path>) -> Result<AuthStore, ConfigError> {
428    let path = auth_path_at(agent_dir)?;
429    match read_text_with_fallback(path, None)? {
430        Some((path, text)) => {
431            serde_json::from_str(&text).map_err(|source| ConfigError::Json { path, source })
432        }
433        None => Ok(AuthStore::new()),
434    }
435}
436
437/// Serializes this process's read-modify-write updates of the auth store. It is
438/// held only for the read and the write, never while calling a provider
439/// package, so two providers committing at once cannot drop each other's entry.
440fn auth_store_lock() -> &'static std::sync::Mutex<()> {
441    static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
442    &LOCK
443}
444
445/// Atomically write the whole auth store (ensures the dir exists, writes a
446/// temp sibling, `rename`s over the target, then `chmod 0o600` on Unix).
447/// Callers that read-modify-write must hold the internal store lock.
448pub fn write_auth(store: &AuthStore) -> Result<(), ConfigError> {
449    write_auth_at(None, store)
450}
451
452/// [`write_auth`] against an explicit agent home.
453pub(crate) fn write_auth_at(
454    agent_dir: Option<&Path>,
455    store: &AuthStore,
456) -> Result<(), ConfigError> {
457    let path = auth_path_at(agent_dir)?;
458    let dir = agent_dir_at(agent_dir)?;
459    ensure_dir(&dir)?;
460    let json = serde_json::to_string_pretty(store).unwrap();
461    atomic_write(&path, json.as_bytes())?;
462    set_owner_only(&path);
463    Ok(())
464}
465
466/// Read-modify-write: upsert a credential for `provider_id`. Re-reads the
467/// latest store under the lock, so other providers' entries are preserved.
468pub fn upsert_credential(provider_id: &str, cred: Credential) -> Result<(), ConfigError> {
469    upsert_credential_at(None, provider_id, cred)
470}
471
472/// [`upsert_credential`] against an explicit agent home.
473pub(crate) fn upsert_credential_at(
474    agent_dir: Option<&Path>,
475    provider_id: &str,
476    cred: Credential,
477) -> Result<(), ConfigError> {
478    let _store_guard = auth_store_lock()
479        .lock()
480        .unwrap_or_else(std::sync::PoisonError::into_inner);
481    let mut store = read_auth_at(agent_dir)?;
482    store.insert(provider_id.to_string(), cred);
483    write_auth_at(agent_dir, &store)
484}
485
486/// Store an OAuth token under exactly one provider id using the atomic auth
487/// store writer. Token values never enter the event or session layer.
488pub fn upsert_oauth_token(
489    provider_id: &str,
490    access: String,
491    refresh: String,
492    expires: i64,
493) -> Result<(), ConfigError> {
494    upsert_credential(
495        provider_id,
496        Credential::Oauth {
497            access,
498            refresh,
499            expires,
500        },
501    )
502}
503
504/// [`upsert_oauth_token`] against an explicit agent home.
505pub(crate) fn upsert_oauth_token_at(
506    agent_dir: Option<&Path>,
507    provider_id: &str,
508    access: String,
509    refresh: String,
510    expires: i64,
511) -> Result<(), ConfigError> {
512    upsert_credential_at(
513        agent_dir,
514        provider_id,
515        Credential::Oauth {
516            access,
517            refresh,
518            expires,
519        },
520    )
521}
522
523/// Replace `provider_id`'s OAuth token only if the stored one still has the
524/// `expected` access, refresh and expiry. Returns `false`, writing nothing, when
525/// a login or logout replaced or removed it meanwhile, so a late refresh result
526/// never undoes that user action.
527pub fn replace_oauth_token_if_unchanged(
528    provider_id: &str,
529    expected: (&str, &str, i64),
530    access: String,
531    refresh: String,
532    expires: i64,
533) -> Result<bool, ConfigError> {
534    replace_oauth_token_if_unchanged_at(None, provider_id, expected, access, refresh, expires)
535}
536
537/// [`replace_oauth_token_if_unchanged`] against an explicit agent home.
538pub(crate) fn replace_oauth_token_if_unchanged_at(
539    agent_dir: Option<&Path>,
540    provider_id: &str,
541    expected: (&str, &str, i64),
542    access: String,
543    refresh: String,
544    expires: i64,
545) -> Result<bool, ConfigError> {
546    let _store_guard = auth_store_lock()
547        .lock()
548        .unwrap_or_else(std::sync::PoisonError::into_inner);
549    let mut store = read_auth_at(agent_dir)?;
550    let unchanged = matches!(
551        store.get(provider_id),
552        Some(Credential::Oauth { access, refresh, expires })
553            if (access.as_str(), refresh.as_str(), *expires) == expected
554    );
555    if unchanged {
556        store.insert(
557            provider_id.to_string(),
558            Credential::Oauth {
559                access,
560                refresh,
561                expires,
562            },
563        );
564        write_auth_at(agent_dir, &store)?;
565    }
566    Ok(unchanged)
567}
568
569/// Read only the OAuth credential for one provider.
570pub fn read_oauth_token(provider_id: &str) -> Result<Option<Credential>, ConfigError> {
571    read_oauth_token_at(None, provider_id)
572}
573
574/// [`read_oauth_token`] against an explicit agent home.
575pub(crate) fn read_oauth_token_at(
576    agent_dir: Option<&Path>,
577    provider_id: &str,
578) -> Result<Option<Credential>, ConfigError> {
579    Ok(match read_auth_at(agent_dir)?.get(provider_id) {
580        Some(Credential::Oauth {
581            access,
582            refresh,
583            expires,
584        }) => Some(Credential::Oauth {
585            access: access.clone(),
586            refresh: refresh.clone(),
587            expires: *expires,
588        }),
589        _ => None,
590    })
591}
592
593/// Remove `provider_id` from the store. Returns `true` if a credential was
594/// present (and is now gone), `false` if it was already absent. Always rewrites
595/// the file when the provider existed (so `auth logout` reflects the new state
596/// on disk even if the map isn't empty).
597pub fn delete_credential(provider_id: &str) -> Result<bool, ConfigError> {
598    delete_credential_at(None, provider_id)
599}
600
601/// [`delete_credential`] against an explicit agent home.
602pub(crate) fn delete_credential_at(
603    agent_dir: Option<&Path>,
604    provider_id: &str,
605) -> Result<bool, ConfigError> {
606    let _store_guard = auth_store_lock()
607        .lock()
608        .unwrap_or_else(std::sync::PoisonError::into_inner);
609    let mut store = read_auth_at(agent_dir)?;
610    if store.remove(provider_id).is_some() {
611        write_auth_at(agent_dir, &store)?;
612        Ok(true)
613    } else {
614        Ok(false)
615    }
616}
617
618// ---------------------------------------------------------------------------
619// models.json — provider/model catalog
620// ---------------------------------------------------------------------------
621
622/// Load `~/.rpi/models.json`. Missing file ⇒ empty config (no error).
623pub fn load_models_config() -> Result<ModelsConfig, ConfigError> {
624    load_models_config_at(None)
625}
626
627/// [`load_models_config`] against an explicit agent home.
628pub(crate) fn load_models_config_at(agent_dir: Option<&Path>) -> Result<ModelsConfig, ConfigError> {
629    let path = models_path_at(agent_dir)?;
630    match read_text_with_fallback(path, None)? {
631        Some((path, text)) => {
632            parse_models_json(&text).map_err(|source| ConfigError::Json { path, source })
633        }
634        None => Ok(ModelsConfig::default()),
635    }
636}
637
638/// Diagnose unsupported compat keys and malformed values without rejecting
639/// unrelated providers.
640/// Atomically write the whole `~/.rpi/models.json` (used by the interactive
641/// provider form). Note: unlike [`crate::settings::save_settings`], this
642/// serializes the modeled config directly, so hand-written comments and unknown
643/// fields in `models.json` are not preserved on rewrite. A timestamped
644/// `models.json.bak-*` snapshot is written first so a mistake can be reverted.
645pub fn save_models_config(cfg: &ModelsConfig) -> Result<(), ConfigError> {
646    save_models_config_at(None, cfg)
647}
648
649/// [`save_models_config`] against an explicit agent home.
650pub(crate) fn save_models_config_at(
651    agent_dir: Option<&Path>,
652    cfg: &ModelsConfig,
653) -> Result<(), ConfigError> {
654    let path = models_path_at(agent_dir)?;
655    let dir = agent_dir_at(agent_dir)?;
656    ensure_dir(&dir)?;
657    // Back up the existing file before rewriting it (best-effort; a missing
658    // file is normal on first save).
659    if let Ok(existing) = std::fs::read(&path) {
660        let stamp = std::time::SystemTime::now()
661            .duration_since(std::time::UNIX_EPOCH)
662            .map(|d| d.as_secs())
663            .unwrap_or(0);
664        let backup = dir.join(format!("models.json.bak-{stamp}"));
665        let _ = std::fs::write(&backup, existing);
666    }
667    let text = serde_json::to_string_pretty(cfg).map_err(|source| ConfigError::Json {
668        path: path.clone(),
669        source,
670    })?;
671    atomic_write(&path, text.as_bytes())
672}
673
674/// Metadata for the first model in a user-configured provider.
675pub struct ProviderModelConfig<'a> {
676    pub id: &'a str,
677    pub name: Option<&'a str>,
678    pub context_window: Option<u64>,
679    pub max_tokens: Option<u64>,
680}
681
682/// Add one user-configured provider and its first model to `models.json`.
683///
684/// This is shared by the interactive provider form and RPC clients so both
685/// surfaces enforce the same protocol, URL, duplicate, and size checks.
686pub fn add_provider(
687    provider_id: &str,
688    api: &str,
689    base_url: &str,
690    api_key: &str,
691    model: ProviderModelConfig<'_>,
692    supports_images: Option<bool>,
693) -> Result<(), String> {
694    add_provider_at(
695        None,
696        provider_id,
697        api,
698        base_url,
699        api_key,
700        model,
701        supports_images,
702    )
703}
704
705/// [`add_provider`] against an explicit agent home.
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: ProviderModelConfig<'_>,
714    supports_images: Option<bool>,
715) -> Result<(), String> {
716    let ProviderModelConfig {
717        id: model_id,
718        name: model_name,
719        context_window,
720        max_tokens,
721    } = model;
722    const MAX_FIELD: usize = 4096;
723    let provider_id = provider_id.trim();
724    let api = api.trim();
725    let base_url = base_url.trim();
726    let api_key = api_key.trim();
727    let model_id = model_id.trim();
728    let model_name = model_name.map(str::trim).filter(|value| !value.is_empty());
729    if provider_id.is_empty()
730        || api.is_empty()
731        || base_url.is_empty()
732        || api_key.is_empty()
733        || model_id.is_empty()
734    {
735        return Err("provider, protocol, base URL, API key, and model ID are required".into());
736    }
737    for (label, value) in [
738        ("provider", provider_id),
739        ("protocol", api),
740        ("base URL", base_url),
741        ("API key", api_key),
742        ("model ID", model_id),
743    ] {
744        if value.len() > MAX_FIELD {
745            return Err(format!("{label} is too long"));
746        }
747    }
748    if model_name.is_some_and(|value| value.len() > MAX_FIELD) {
749        return Err("model name is too long".into());
750    }
751    if context_window == Some(0) {
752        return Err("context window must be greater than zero".into());
753    }
754    if max_tokens == Some(0) {
755        return Err("max output tokens must be greater than zero".into());
756    }
757    if !matches!(
758        api,
759        "anthropic-messages" | "openai-completions" | "openai-responses"
760    ) {
761        return Err("unsupported provider protocol".into());
762    }
763    if !(base_url.starts_with("http://") || base_url.starts_with("https://")) {
764        return Err("base URL must start with http:// or https://".into());
765    }
766    let mut config = load_models_config_at(agent_dir).map_err(|error| error.to_string())?;
767    if config.providers.contains_key(provider_id) {
768        return Err(format!(
769            "provider {provider_id:?} already has a models.json configuration"
770        ));
771    }
772    config.providers.insert(
773        provider_id.to_owned(),
774        ProviderConfig {
775            name: None,
776            base_url: Some(base_url.to_owned()),
777            api_key: Some(api_key.to_owned()),
778            api: Some(api.to_owned()),
779            headers: None,
780            auth_header: None,
781            models: vec![ModelDefinition {
782                id: model_id.to_owned(),
783                name: model_name.map(str::to_owned),
784                base_url: None,
785                reasoning: None,
786                thinking_level_map: None,
787                context_window,
788                max_tokens,
789                cost: None,
790                input: supports_images.map(|supports| {
791                    if supports {
792                        vec!["text".to_string(), "image".to_string()]
793                    } else {
794                        vec!["text".to_string()]
795                    }
796                }),
797                headers: None,
798                compat: None,
799            }],
800        },
801    );
802    save_models_config_at(agent_dir, &config).map_err(|error| error.to_string())
803}
804
805/// Update an existing models.json provider and its first model. An omitted API
806/// key preserves the existing key, so editing metadata does not require
807/// exposing or re-entering a secret.
808pub fn update_provider(
809    provider_id: &str,
810    api: &str,
811    base_url: &str,
812    api_key: Option<&str>,
813    model: ProviderModelConfig<'_>,
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,
823        supports_images,
824    )
825}
826
827/// [`update_provider`] against an explicit agent home.
828#[allow(clippy::too_many_arguments)]
829pub(crate) fn update_provider_at(
830    agent_dir: Option<&Path>,
831    provider_id: &str,
832    api: &str,
833    base_url: &str,
834    api_key: Option<&str>,
835    model: ProviderModelConfig<'_>,
836    supports_images: bool,
837) -> Result<(), String> {
838    let ProviderModelConfig {
839        id: model_id,
840        name: model_name,
841        context_window,
842        max_tokens,
843    } = model;
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.
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.
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.
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// ---------------------------------------------------------------------------
1196// Internals: dir ensure, atomic write, chmod
1197// ---------------------------------------------------------------------------
1198
1199#[cfg(unix)]
1200use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
1201
1202/// Create the config dir if missing. Mode 0o700 on Unix (mkdir default on
1203/// Windows, where the sticky-permission concept doesn't apply).
1204fn ensure_dir(dir: &Path) -> Result<(), ConfigError> {
1205    if dir.exists() {
1206        return Ok(());
1207    }
1208    std::fs::create_dir_all(dir).map_err(|e| ConfigError::Write {
1209        path: dir.to_path_buf(),
1210        source: e,
1211    })?;
1212    #[cfg(unix)]
1213    {
1214        let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
1215    }
1216    Ok(())
1217}
1218
1219/// Write `bytes` to `path` atomically: a temp sibling → `rename`. The temp
1220/// file lives next to the target so the rename stays on one filesystem.
1221pub(crate) fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), ConfigError> {
1222    let dir = path.parent().ok_or_else(|| ConfigError::Write {
1223        path: path.to_path_buf(),
1224        source: std::io::Error::new(std::io::ErrorKind::InvalidInput, "path has no parent"),
1225    })?;
1226    let tmp = dir.join(format!(
1227        ".{}.{}.tmp",
1228        path.file_name().and_then(|n| n.to_str()).unwrap_or("rpi"),
1229        uuid::Uuid::new_v4().simple()
1230    ));
1231    let mut options = std::fs::OpenOptions::new();
1232    options.write(true).create_new(true);
1233    #[cfg(unix)]
1234    options.mode(0o600);
1235    let mut file = options.open(&tmp).map_err(|source| ConfigError::Write {
1236        path: tmp.clone(),
1237        source,
1238    })?;
1239    if let Err(error) = file.write_all(bytes).and_then(|()| file.sync_all()) {
1240        // A partial staging file is never useful to a later caller. Best
1241        // effort cleanup also avoids leaving a misleading stale temp behind
1242        // when the target itself was left untouched.
1243        let _ = std::fs::remove_file(&tmp);
1244        return Err(ConfigError::Write {
1245            path: tmp,
1246            source: error,
1247        });
1248    }
1249    drop(file);
1250    if let Err(error) = std::fs::rename(&tmp, path) {
1251        // `rename` is the publish point; on failure the original target is
1252        // still intact. Remove the staging file before returning the error.
1253        let _ = std::fs::remove_file(&tmp);
1254        return Err(ConfigError::Write {
1255            path: path.to_path_buf(),
1256            source: error,
1257        });
1258    }
1259    Ok(())
1260}
1261
1262/// Best-effort tighten to owner-only (0o600). No-op on Windows (the Node
1263/// upstream applies no ACL either).
1264fn set_owner_only(_path: &Path) {
1265    #[cfg(unix)]
1266    {
1267        let _ = std::fs::set_permissions(_path, std::fs::Permissions::from_mode(0o600));
1268    }
1269}
1270
1271// ---------------------------------------------------------------------------
1272// Tests
1273// ---------------------------------------------------------------------------
1274
1275#[cfg(test)]
1276pub(crate) mod test_support {
1277    /// A shared workspace lock for tests that touch process-global env vars
1278    /// (`RPI_CODING_AGENT_DIR`, `ANTHROPIC_*`). All env-mutating tests across
1279    /// the crate (config / provider / auth) share this ONE mutex so they can't
1280    /// race on the shared environment. Hold the returned guard for the whole
1281    /// test (store it in a RAII struct).
1282    use std::sync::{Mutex, OnceLock};
1283    pub(crate) fn env_lock() -> &'static Mutex<()> {
1284        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
1285        LOCK.get_or_init(|| Mutex::new(()))
1286    }
1287
1288    /// Isolate session-directory overrides while holding the shared env lock.
1289    /// Restore the inherited value before releasing the lock, even on unwind.
1290    pub(crate) struct SessionDirEnv {
1291        _guard: std::sync::MutexGuard<'static, ()>,
1292        previous: Option<std::ffi::OsString>,
1293    }
1294
1295    impl SessionDirEnv {
1296        pub(crate) fn new(directory: Option<&std::path::Path>) -> Self {
1297            let guard = env_lock().lock().unwrap();
1298            let previous = std::env::var_os("RPI_CODING_AGENT_SESSION_DIR");
1299            match directory {
1300                Some(directory) => std::env::set_var("RPI_CODING_AGENT_SESSION_DIR", directory),
1301                None => std::env::remove_var("RPI_CODING_AGENT_SESSION_DIR"),
1302            }
1303            Self {
1304                _guard: guard,
1305                previous,
1306            }
1307        }
1308    }
1309
1310    impl Drop for SessionDirEnv {
1311        fn drop(&mut self) {
1312            match self.previous.take() {
1313                Some(value) => std::env::set_var("RPI_CODING_AGENT_SESSION_DIR", value),
1314                None => std::env::remove_var("RPI_CODING_AGENT_SESSION_DIR"),
1315            }
1316        }
1317    }
1318}
1319
1320#[cfg(test)]
1321mod tests {
1322    use super::*;
1323    use crate::config::test_support::env_lock;
1324
1325    /// Point `RPI_CODING_AGENT_DIR` at a fresh temp dir for the duration of the
1326    /// test (cleaned up on drop). Holds the prior value of the env var to
1327    /// restore it. Hold the env lock for its whole lifetime.
1328    struct TempConfig {
1329        _guard: std::sync::MutexGuard<'static, ()>,
1330        _tmp: tempfile::TempDir,
1331        prev: Option<std::ffi::OsString>,
1332    }
1333    impl TempConfig {
1334        fn new() -> Self {
1335            let guard = env_lock().lock().unwrap();
1336            let prev = std::env::var_os(CONFIG_DIR_ENV);
1337            let tmp = tempfile::TempDir::new().unwrap();
1338            std::env::set_var(CONFIG_DIR_ENV, tmp.path());
1339            Self {
1340                _guard: guard,
1341                _tmp: tmp,
1342                prev,
1343            }
1344        }
1345    }
1346    impl Drop for TempConfig {
1347        fn drop(&mut self) {
1348            restore_env(CONFIG_DIR_ENV, self.prev.take());
1349        }
1350    }
1351
1352    #[test]
1353    fn read_auth_missing_file_is_empty() {
1354        let _cfg = TempConfig::new();
1355        let store = read_auth().unwrap();
1356        assert!(store.is_empty());
1357    }
1358
1359    #[test]
1360    fn upsert_then_read_roundtrip() {
1361        let _cfg = TempConfig::new();
1362        upsert_credential(
1363            "anthropic",
1364            Credential::ApiKey {
1365                key: Some("sk-test-123".into()),
1366                env: None,
1367            },
1368        )
1369        .unwrap();
1370        let store = read_auth().unwrap();
1371        match store.get("anthropic") {
1372            Some(Credential::ApiKey { key, .. }) => assert_eq!(key.as_deref(), Some("sk-test-123")),
1373            other => panic!("unexpected cred: {other:?}"),
1374        }
1375        // The file should exist and be JSON.
1376        let path = auth_path().unwrap();
1377        assert!(path.exists(), "auth.json should exist after upsert");
1378        let raw = std::fs::read_to_string(&path).unwrap();
1379        assert!(raw.contains("\"anthropic\""));
1380        assert!(raw.contains("api_key"));
1381    }
1382
1383    #[test]
1384    fn add_provider_writes_protocol_endpoint_key_and_model() {
1385        let _cfg = TempConfig::new();
1386        add_provider(
1387            "gateway",
1388            "openai-completions",
1389            "https://api.example.test/v1",
1390            "fixture-key",
1391            ProviderModelConfig {
1392                id: "model-a",
1393                name: Some("Model A"),
1394                context_window: Some(128_000),
1395                max_tokens: Some(4096),
1396            },
1397            Some(true),
1398        )
1399        .unwrap();
1400        let config = load_models_config().unwrap();
1401        let provider = config.providers.get("gateway").unwrap();
1402        assert_eq!(provider.api.as_deref(), Some("openai-completions"));
1403        assert_eq!(
1404            provider.base_url.as_deref(),
1405            Some("https://api.example.test/v1")
1406        );
1407        assert_eq!(provider.api_key.as_deref(), Some("fixture-key"));
1408        assert_eq!(provider.models[0].id, "model-a");
1409        assert_eq!(provider.models[0].name.as_deref(), Some("Model A"));
1410        assert_eq!(provider.models[0].context_window, Some(128_000));
1411        assert_eq!(provider.models[0].max_tokens, Some(4096));
1412        assert_eq!(
1413            provider.models[0].input.as_deref(),
1414            Some(["text".to_string(), "image".to_string()].as_slice())
1415        );
1416    }
1417
1418    #[test]
1419    fn add_provider_rejects_duplicate_and_unsupported_protocol() {
1420        let _cfg = TempConfig::new();
1421        add_provider(
1422            "gateway",
1423            "openai-responses",
1424            "https://api.example.test/v1",
1425            "fixture-key",
1426            ProviderModelConfig {
1427                id: "model-a",
1428                name: None,
1429                context_window: None,
1430                max_tokens: None,
1431            },
1432            None,
1433        )
1434        .unwrap();
1435        let duplicate = add_provider(
1436            "gateway",
1437            "openai-completions",
1438            "https://api.example.test/v1",
1439            "fixture-key-2",
1440            ProviderModelConfig {
1441                id: "model-b",
1442                name: None,
1443                context_window: None,
1444                max_tokens: None,
1445            },
1446            None,
1447        )
1448        .unwrap_err();
1449        assert!(duplicate.contains("already"));
1450        let unsupported = add_provider(
1451            "other",
1452            "unsupported",
1453            "https://api.example.test/v1",
1454            "fixture-key",
1455            ProviderModelConfig {
1456                id: "model-a",
1457                name: None,
1458                context_window: None,
1459                max_tokens: None,
1460            },
1461            None,
1462        )
1463        .unwrap_err();
1464        assert!(unsupported.contains("unsupported"));
1465        let invalid_context = add_provider(
1466            "context-zero",
1467            "openai-completions",
1468            "https://api.example.test/v1",
1469            "fixture-key",
1470            ProviderModelConfig {
1471                id: "model-a",
1472                name: None,
1473                context_window: Some(0),
1474                max_tokens: None,
1475            },
1476            None,
1477        )
1478        .unwrap_err();
1479        assert!(invalid_context.contains("context window"));
1480    }
1481
1482    #[test]
1483    fn update_and_delete_provider_change_models_json() {
1484        let _cfg = TempConfig::new();
1485        add_provider(
1486            "gateway",
1487            "openai-completions",
1488            "https://api.example.test/v1",
1489            "fixture-key",
1490            ProviderModelConfig {
1491                id: "model-a",
1492                name: Some("Model A"),
1493                context_window: Some(128_000),
1494                max_tokens: Some(4096),
1495            },
1496            Some(false),
1497        )
1498        .unwrap();
1499        update_provider(
1500            "gateway",
1501            "openai-responses",
1502            "https://new.example.test/v1",
1503            None,
1504            ProviderModelConfig {
1505                id: "model-b",
1506                name: Some("Model B"),
1507                context_window: Some(256_000),
1508                max_tokens: Some(8192),
1509            },
1510            true,
1511        )
1512        .unwrap();
1513        let provider = load_models_config()
1514            .unwrap()
1515            .providers
1516            .get("gateway")
1517            .unwrap()
1518            .clone();
1519        assert_eq!(provider.api.as_deref(), Some("openai-responses"));
1520        assert_eq!(
1521            provider.base_url.as_deref(),
1522            Some("https://new.example.test/v1")
1523        );
1524        assert_eq!(provider.api_key.as_deref(), Some("fixture-key"));
1525        assert_eq!(provider.models[0].id, "model-b");
1526        assert_eq!(provider.models[0].max_tokens, Some(8192));
1527        assert_eq!(
1528            provider.models[0].input.as_deref(),
1529            Some(["text".to_string(), "image".to_string()].as_slice())
1530        );
1531        delete_provider("gateway").unwrap();
1532        assert!(!load_models_config()
1533            .unwrap()
1534            .providers
1535            .contains_key("gateway"));
1536    }
1537
1538    #[test]
1539    fn oauth_token_is_scoped_and_round_trips() {
1540        let _cfg = TempConfig::new();
1541        upsert_oauth_token("acme", "access".into(), "refresh".into(), 123).unwrap();
1542        assert!(matches!(
1543            read_oauth_token("acme").unwrap(),
1544            Some(Credential::Oauth { access, refresh, expires })
1545                if access == "access" && refresh == "refresh" && expires == 123
1546        ));
1547        assert!(read_oauth_token("other").unwrap().is_none());
1548    }
1549
1550    #[test]
1551    fn delete_credential_removes_entry() {
1552        let _cfg = TempConfig::new();
1553        upsert_credential(
1554            "anthropic",
1555            Credential::ApiKey {
1556                key: Some("k".into()),
1557                env: None,
1558            },
1559        )
1560        .unwrap();
1561        assert!(delete_credential("anthropic").unwrap());
1562        // Second delete is a no-op.
1563        assert!(!delete_credential("anthropic").unwrap());
1564        assert!(read_auth().unwrap().is_empty());
1565    }
1566
1567    #[test]
1568    fn load_models_config_missing_is_empty() {
1569        let _cfg = TempConfig::new();
1570        let c = load_models_config().unwrap();
1571        assert!(c.providers.is_empty());
1572    }
1573
1574    #[test]
1575    fn fallback_reader_prefers_primary_and_only_falls_back_when_missing() {
1576        let tmp = tempfile::tempdir().unwrap();
1577        let primary = tmp.path().join("primary.json");
1578        let fallback = tmp.path().join("fallback.json");
1579        std::fs::write(&fallback, "fallback").unwrap();
1580
1581        let (_, text) = read_text_with_fallback(primary.clone(), Some(fallback.clone()))
1582            .unwrap()
1583            .expect("fallback should be read");
1584        assert_eq!(text, "fallback");
1585
1586        std::fs::write(&primary, "primary").unwrap();
1587        let (path, text) = read_text_with_fallback(primary.clone(), Some(fallback))
1588            .unwrap()
1589            .expect("primary should be read");
1590        assert_eq!(path, primary);
1591        assert_eq!(text, "primary");
1592    }
1593
1594    #[test]
1595    fn fallback_reader_does_not_mask_primary_read_errors() {
1596        let tmp = tempfile::tempdir().unwrap();
1597        let primary = tmp.path().join("primary.json");
1598        let fallback = tmp.path().join("fallback.json");
1599        std::fs::create_dir(&primary).unwrap();
1600        std::fs::write(&fallback, "fallback").unwrap();
1601
1602        let error = read_text_with_fallback(primary.clone(), Some(fallback)).unwrap_err();
1603        assert!(matches!(error, ConfigError::Read { path, .. } if path == primary));
1604    }
1605
1606    #[test]
1607    fn load_models_config_parses_with_comments() {
1608        let _cfg = TempConfig::new();
1609        let json = r#"{
1610  // a one-api style gateway
1611  "providers": {
1612    "gateway": {
1613      "baseUrl": "https://gw.example.com",
1614      "authHeader": true,
1615      "apiKey": "gw-secret",
1616      "models": [
1617        { "id": "claude-sonnet-5", "name": "Sonnet via gateway" }
1618      ]
1619    }
1620  }
1621}"#;
1622        std::fs::write(models_path().unwrap(), json).unwrap();
1623        let c = load_models_config().unwrap();
1624        let gw = c
1625            .providers
1626            .get("gateway")
1627            .expect("gateway provider present");
1628        assert_eq!(gw.base_url.as_deref(), Some("https://gw.example.com"));
1629        assert!(gw.auth_header.unwrap_or(false));
1630        assert_eq!(gw.models.len(), 1);
1631        assert_eq!(gw.models[0].id, "claude-sonnet-5");
1632    }
1633
1634    #[test]
1635    fn provider_to_models_merges_headers_without_synth_bearer() {
1636        // `provider_to_models` merges model-level then provider-level headers,
1637        // but does NOT synthesize the `authHeader:true` Bearer itself — that
1638        // happens centrally in `crate::provider::resolve` (via
1639        // `models_json_bearer_token`) so it can be skipped on the x-api-key
1640        // path. Here the model carries only what the file declared.
1641        let cfg = ProviderConfig {
1642            name: None,
1643            base_url: Some("https://gw.example.com".into()),
1644            api_key: Some("gw-secret".into()),
1645            api: None,
1646            headers: Some({
1647                let mut h = BTreeMap::new();
1648                h.insert("x-portkey-key".into(), "portkey-secret".into());
1649                h
1650            }),
1651            auth_header: Some(true),
1652            models: vec![ModelDefinition {
1653                id: "claude-sonnet-5".into(),
1654                name: None,
1655                base_url: None,
1656                reasoning: None,
1657                thinking_level_map: None,
1658                context_window: None,
1659                max_tokens: None,
1660                cost: None,
1661                input: None,
1662                headers: None,
1663                compat: None,
1664            }],
1665        };
1666        let models = provider_to_models("gateway", &cfg).expect("anthropic-compatible");
1667        assert_eq!(models.len(), 1);
1668        let m = &models[0];
1669        assert_eq!(m.id, "claude-sonnet-5");
1670        assert_eq!(m.base_url, "https://gw.example.com");
1671        assert_eq!(m.provider, "gateway");
1672        let headers = m.headers.as_ref().expect("provider headers merged");
1673        // Declared provider header folds in…
1674        assert_eq!(
1675            headers.get("x-portkey-key").map(|s| s.as_str()),
1676            Some("portkey-secret")
1677        );
1678        // …but no Bearer is synthesized here. The bearer-from-authHeader path
1679        // is exercised end-to-end by the provider.rs `resolve` tests
1680        // (`models_json_auth_header_satisfies_auth_without_env`,
1681        // `api_key_flag_beats_models_json_bearer`).
1682        assert!(
1683            headers.get("authorization").is_none(),
1684            "provider_to_models must not synthesize the Bearer; resolve does"
1685        );
1686    }
1687
1688    #[test]
1689    fn provider_to_models_supports_openai_completions() {
1690        let config: ModelsConfig = serde_json::from_str(
1691            r#"{
1692                "providers": {
1693                    "oai": {
1694                        "api": "openai-completions",
1695                        "baseUrl": "https://gateway.example.com/v1",
1696                        "apiKey": "secret",
1697                        "models": [{"id":"gpt-test","maxTokens":4096}]
1698                    }
1699                }
1700            }"#,
1701        )
1702        .unwrap();
1703        let models = provider_to_models("oai", &config.providers["oai"]).unwrap();
1704        assert_eq!(models.len(), 1);
1705        assert_eq!(models[0].api, Api::OpenaiCompletions);
1706        assert_eq!(models[0].provider, "oai");
1707        assert_eq!(models[0].max_tokens, 4096);
1708        assert_eq!(models[0].cost, ModelCost::default());
1709        assert!(!models[0].has_pricing());
1710        assert!(
1711            models[0].headers.is_none(),
1712            "credentials are bound after provider resolution"
1713        );
1714    }
1715
1716    #[test]
1717    fn models_json_pricing_reaches_providers_and_survives_serialization() {
1718        let mut config = parse_models_json(
1719            r#"{
1720                "providers": {
1721                    "pricing-fixture": {
1722                        "api": "anthropic-messages",
1723                        "models": [{
1724                            "id": "priced-model",
1725                            "cost": {
1726                                "input": 2, "output": 8, "cacheRead": 0.2, "cacheWrite": 2.5,
1727                                "tiers": [{
1728                                    "inputTokensAbove": 1000000,
1729                                    "input": 4, "output": 16, "cacheRead": 0.4, "cacheWrite": 5
1730                                }]
1731                            }
1732                        }]
1733                    }
1734                }
1735            }"#,
1736        )
1737        .unwrap();
1738        let expected = config.providers["pricing-fixture"].models[0]
1739            .cost
1740            .clone()
1741            .unwrap();
1742        for api in [
1743            "anthropic-messages",
1744            "openai-completions",
1745            "openai-responses",
1746        ] {
1747            let cfg = config.providers.get_mut("pricing-fixture").unwrap();
1748            cfg.api = Some(api.into());
1749            let models = provider_to_models("pricing-fixture", cfg).unwrap();
1750            assert_eq!(models[0].cost, expected);
1751            assert!(models[0].has_pricing());
1752            let mut usage = rpi_ai::Usage::zero();
1753            usage.input = 100_000;
1754            usage.output = 250_000;
1755            usage.cache_read = 300_000;
1756            usage.cache_write = 400_000;
1757            let cost = rpi_ai::providers::anthropic::cost::calculate_cost(&models[0].cost, &usage);
1758            assert!((cost.total - 3.26).abs() < 1e-10, "base pricing for {api}");
1759            usage.input = 1_000_001;
1760            usage.output = 1_000_000;
1761            usage.cache_read = 0;
1762            usage.cache_write = 0;
1763            let cost = rpi_ai::providers::anthropic::cost::calculate_cost(&models[0].cost, &usage);
1764            assert!(
1765                (cost.total - 20.000004).abs() < 1e-10,
1766                "tiered pricing for {api}"
1767            );
1768        }
1769        let saved = serde_json::to_string(&config).unwrap();
1770        let reloaded = parse_models_json(&saved).unwrap();
1771        assert_eq!(
1772            reloaded.providers["pricing-fixture"].models[0].cost,
1773            Some(expected)
1774        );
1775        let cfg = config.providers.get_mut("pricing-fixture").unwrap();
1776        cfg.models[0].cost = Some(ModelCost::default());
1777        let free = provider_to_models("pricing-fixture", cfg).unwrap();
1778        assert_eq!(free[0].cost, ModelCost::default());
1779        assert!(
1780            free[0].has_pricing(),
1781            "explicit zero prices are still configured"
1782        );
1783    }
1784
1785    #[test]
1786    fn models_json_compat_reaches_the_model_for_openai_completions() {
1787        // The `compat` block is what lets a custom openai-completions provider
1788        // describe its quirks. `requiresThinkingAsText` is the one that decides
1789        // whether the model's own reasoning is sent back or dropped — see
1790        // `docs/debugging/llm-repetition-forensics.md` §八. If this hop ever breaks, the
1791        // setting silently does nothing (the provider falls back to
1792        // `Content::text_only`, which drops every thinking block).
1793        let config: ModelsConfig = serde_json::from_str(
1794            r#"{
1795                "providers": {
1796                    "qwen": {
1797                        "api": "openai-completions",
1798                        "baseUrl": "https://coding.example.com/v1",
1799                        "apiKey": "secret",
1800                        "models": [{
1801                            "id": "qwen3.7-plus",
1802                            "maxTokens": 131072,
1803                            "thinkingLevelMap": { "xhigh": "xhigh", "max": "max" },
1804                            "compat": { "requiresThinkingAsText": true }
1805                        }]
1806                    }
1807                }
1808            }"#,
1809        )
1810        .unwrap();
1811        let models = provider_to_models("qwen", &config.providers["qwen"]).unwrap();
1812        assert_eq!(
1813            models[0]
1814                .thinking_level_map
1815                .as_ref()
1816                .unwrap()
1817                .get(&rpi_ai::ThinkingLevel::Xhigh),
1818            Some(&Some("xhigh".into()))
1819        );
1820        match models[0].compat.as_ref().expect("compat must survive") {
1821            StreamingProtocolCompat::OpenaiCompletions(compat) => {
1822                assert_eq!(compat.requires_thinking_as_text, Some(true));
1823            }
1824            other => panic!("expected OpenaiCompletions compat, got {other:?}"),
1825        }
1826
1827        // An entry without `compat` stays on the default (thinking dropped).
1828        let plain: ModelsConfig = serde_json::from_str(
1829            r#"{
1830                "providers": {
1831                    "qwen": {
1832                        "api": "openai-completions",
1833                        "baseUrl": "https://coding.example.com/v1",
1834                        "apiKey": "secret",
1835                        "models": [{"id":"qwen3.7-plus"}]
1836                    }
1837                }
1838            }"#,
1839        )
1840        .unwrap();
1841        let plain_models = provider_to_models("qwen", &plain.providers["qwen"]).unwrap();
1842        assert!(plain_models[0].compat.is_none());
1843    }
1844
1845    #[test]
1846    fn models_json_accepts_pi_deepseek_compat_and_warns_on_unknown_or_invalid_fields() {
1847        let mut config: ModelsConfig = serde_json::from_value(serde_json::json!({
1848            "providers": { "deepseek": {
1849                "api": "openai-completions",
1850                "models": [{ "id": "reasoner", "reasoning": true, "compat": {
1851                    "thinkingFormat": "deepseek",
1852                    "requiresReasoningContentOnAssistantMessages": true
1853                }}]
1854            }}
1855        }))
1856        .unwrap();
1857        assert!(model_compat_warnings(&config).is_empty());
1858        let models = provider_to_models("deepseek", &config.providers["deepseek"]).unwrap();
1859        assert!(rpi_ai::model::prior_reasoning_is_replayed(&models[0]));
1860        let Some(StreamingProtocolCompat::OpenaiCompletions(compat)) = &models[0].compat else {
1861            panic!("missing model compatibility flags");
1862        };
1863        assert_eq!(compat.requires_reasoning_content, Some(true));
1864        assert_eq!(
1865            compat.thinking_format,
1866            Some(rpi_ai::model::OpenaiThinkingFormat::Deepseek)
1867        );
1868
1869        config.providers["deepseek"].models[0]
1870            .compat
1871            .as_mut()
1872            .unwrap()["misspelledField"] = serde_json::json!("secret-fixture-value");
1873        let warnings = model_compat_warnings(&config);
1874        assert_eq!(warnings.len(), 1);
1875        assert!(warnings[0].contains("deepseek") && warnings[0].contains("reasoner"));
1876        assert!(warnings[0].contains("unknown field \"misspelledField\""));
1877        assert!(!warnings[0].contains("secret-fixture-value"));
1878
1879        config.providers["deepseek"].models[0].compat =
1880            Some(serde_json::json!({"requiresReasoningContent": "secret-fixture-token"}));
1881        let warning = &model_compat_warnings(&config)[0];
1882        assert!(warning.contains("invalid configuration"));
1883        assert!(!warning.contains("secret-fixture-token"));
1884        config.providers["deepseek"].models[0].compat =
1885            Some(serde_json::json!({"thinkingFormat": "unsupported"}));
1886        assert!(model_compat_warnings(&config)[0].contains("invalid configuration"));
1887    }
1888
1889    #[test]
1890    fn responses_compat_diagnostics_use_the_responses_schema() {
1891        let config: ModelsConfig = serde_json::from_value(serde_json::json!({
1892            "providers": { "relay": {
1893                "api": "openai-responses", "models": [{ "id": "test", "compat": {
1894                    "supportsOpenAIGrammarTools": true, "supportsStore": false
1895                }}]
1896            }}
1897        }))
1898        .unwrap();
1899        let warnings = model_compat_warnings(&config);
1900        assert_eq!(warnings.len(), 1);
1901        assert!(warnings[0].contains("supportsStore"));
1902    }
1903
1904    #[test]
1905    fn native_reasoning_content_key_wins_over_a_conflicting_pi_alias() {
1906        let config: ModelsConfig = serde_json::from_value(serde_json::json!({
1907            "providers": { "relay": {
1908                "api": "openai-completions", "models": [{ "id": "test", "compat": {
1909                    "requiresReasoningContent": false,
1910                    "requiresReasoningContentOnAssistantMessages": true
1911                }}]
1912            }}
1913        }))
1914        .unwrap();
1915        let warnings = model_compat_warnings(&config);
1916        assert_eq!(warnings.len(), 1);
1917        assert!(warnings[0].contains("takes precedence"));
1918        let models = provider_to_models("relay", &config.providers["relay"]).unwrap();
1919        let Some(StreamingProtocolCompat::OpenaiCompletions(compat)) = &models[0].compat else {
1920            panic!("valid native flag must survive an alias conflict");
1921        };
1922        assert_eq!(compat.requires_reasoning_content, Some(false));
1923    }
1924
1925    #[test]
1926    fn custom_openai_provider_resolves_explicit_api_key_environment_reference() {
1927        let _guard = env_lock().lock().unwrap();
1928        let env_name = "RPI_FAKE_PROVIDER_API_KEY";
1929        std::env::set_var(env_name, "env-secret");
1930        let cfg = ProviderConfig {
1931            name: None,
1932            base_url: Some("https://gateway.example.com/v1".into()),
1933            api_key: Some("$RPI_FAKE_PROVIDER_API_KEY".into()),
1934            api: Some("openai-completions".into()),
1935            headers: None,
1936            auth_header: None,
1937            models: vec![ModelDefinition {
1938                id: "fake-model".into(),
1939                name: None,
1940                base_url: None,
1941                reasoning: None,
1942                thinking_level_map: None,
1943                context_window: None,
1944                max_tokens: None,
1945                cost: None,
1946                input: None,
1947                headers: None,
1948                compat: None,
1949            }],
1950        };
1951        let models = provider_to_models("rpi-fake-provider", &cfg).unwrap();
1952        assert_eq!(
1953            openai_provider_api_key("rpi-fake-provider", &cfg).as_deref(),
1954            Some("env-secret")
1955        );
1956        assert!(
1957            models[0].headers.is_none(),
1958            "discovery does not bind credentials"
1959        );
1960        std::env::remove_var(env_name);
1961    }
1962
1963    #[test]
1964    fn openai_protocol_ids_do_not_inherit_the_official_env_key() {
1965        let _guard = env_lock().lock().unwrap();
1966        let prev_openai = std::env::var_os("OPENAI_API_KEY");
1967        let prev_completions = std::env::var_os("OPENAI_COMPLETIONS_API_KEY");
1968        let prev_responses = std::env::var_os("OPENAI_RESPONSES_API_KEY");
1969        std::env::set_var("OPENAI_API_KEY", "official-key");
1970        std::env::remove_var("OPENAI_COMPLETIONS_API_KEY");
1971        std::env::remove_var("OPENAI_RESPONSES_API_KEY");
1972        let config = ProviderConfig {
1973            name: None,
1974            base_url: Some("https://gateway.example.com/v1".into()),
1975            api_key: None,
1976            api: Some("openai-responses".into()),
1977            headers: None,
1978            auth_header: None,
1979            models: Vec::new(),
1980        };
1981
1982        assert_eq!(
1983            openai_provider_api_key("openai", &config).as_deref(),
1984            Some("official-key")
1985        );
1986        assert!(openai_provider_api_key("openai-completions", &config).is_none());
1987        assert!(openai_provider_api_key("openai-responses", &config).is_none());
1988        assert!(openai_provider_api_key("OpenAI", &config).is_none());
1989
1990        restore_env("OPENAI_API_KEY", prev_openai);
1991        restore_env("OPENAI_COMPLETIONS_API_KEY", prev_completions);
1992        restore_env("OPENAI_RESPONSES_API_KEY", prev_responses);
1993    }
1994
1995    #[test]
1996    fn native_provider_api_key_env_mapping_uses_exact_provider_ids() {
1997        assert_eq!(
1998            native_provider_api_key_env_var("openai"),
1999            Some("OPENAI_API_KEY")
2000        );
2001        for provider in [
2002            "deepseek",
2003            "openrouter",
2004            "google",
2005            "groq",
2006            "qwen",
2007            "nvidia",
2008            "OpenAI",
2009            "openai-completions",
2010        ] {
2011            assert_eq!(
2012                native_provider_api_key_env_var(provider),
2013                None,
2014                "external providers must declare auth in their package or models.json"
2015            );
2016        }
2017    }
2018
2019    #[test]
2020    fn malformed_auth_json_is_an_error_not_silent_empty() {
2021        let _cfg = TempConfig::new();
2022        std::fs::write(auth_path().unwrap(), "{ not json").unwrap();
2023        assert!(matches!(read_auth(), Err(ConfigError::Json { .. })));
2024    }
2025
2026    #[test]
2027    fn agent_dir_nests_under_agent_by_default() {
2028        // With no env override, agent_dir() must end in `.../.rpi/agent`
2029        // (mirrors pi's `getAgentDir`). We can't assertion the home prefix
2030        // portably, but the leaf two segments are stable.
2031        let _guard = env_lock().lock().unwrap();
2032        let prev = std::env::var_os(CONFIG_DIR_ENV);
2033        std::env::remove_var(CONFIG_DIR_ENV);
2034        let dir = agent_dir().unwrap();
2035        restore_env(CONFIG_DIR_ENV, prev);
2036        assert!(dir.ends_with("agent"));
2037        assert!(dir
2038            .parent()
2039            .map(|p| p.ends_with(CONFIG_DIR_NAME))
2040            .unwrap_or(false));
2041    }
2042
2043    #[test]
2044    fn migrate_legacy_layout_moves_flat_files_into_agent() {
2045        // Drive the core migration directly against a temp root/agent so the
2046        // result is independent of whatever RPI_CODING_AGENT_DIR the parallel
2047        // TempConfig tests happen to set.
2048        let tmp = tempfile::TempDir::new().unwrap();
2049        let root = tmp.path().to_path_buf();
2050        let agent = root.join("agent");
2051        std::fs::write(root.join("auth.json"), "{}").unwrap();
2052        std::fs::write(root.join("models.json"), "{}").unwrap();
2053        std::fs::write(root.join(".setup_done"), "1").unwrap();
2054        let moved = migrate_legacy_layout_in(&root, &agent).unwrap();
2055        assert_eq!(moved, 3);
2056        assert!(agent.join("auth.json").exists());
2057        assert!(agent.join("models.json").exists());
2058        assert!(agent.join(".setup_done").exists());
2059        assert!(!root.join("auth.json").exists());
2060    }
2061
2062    #[test]
2063    fn migrate_legacy_layout_noop_when_agent_exists() {
2064        let tmp = tempfile::TempDir::new().unwrap();
2065        let root = tmp.path().to_path_buf();
2066        let agent = root.join("agent");
2067        std::fs::write(root.join("auth.json"), "{}").unwrap();
2068        std::fs::create_dir_all(&agent).unwrap();
2069        let moved = migrate_legacy_layout_in(&root, &agent).unwrap();
2070        assert_eq!(moved, 0); // agent/ already present — leave flat file alone
2071    }
2072
2073    #[test]
2074    fn migrate_legacy_layout_noop_when_no_flat_files() {
2075        let tmp = tempfile::TempDir::new().unwrap();
2076        let root = tmp.path().to_path_buf();
2077        let agent = root.join("agent");
2078        let moved = migrate_legacy_layout_in(&root, &agent).unwrap();
2079        assert_eq!(moved, 0);
2080    }
2081
2082    #[test]
2083    fn migrate_legacy_layout_public_skips_env_override() {
2084        // When RPI_CODING_AGENT_DIR is set, the public entry point is a no-op
2085        // (it must never touch an explicit override). TempConfig sets it.
2086        let _cfg = TempConfig::new();
2087        let moved = migrate_legacy_layout().unwrap();
2088        assert_eq!(moved, 0);
2089    }
2090
2091    #[test]
2092    fn read_trust_missing_file_is_empty() {
2093        let _cfg = TempConfig::new();
2094        assert!(read_trust().unwrap().is_empty());
2095    }
2096
2097    #[test]
2098    fn read_trust_parses_decisions() {
2099        let _cfg = TempConfig::new();
2100        let path = trust_path().unwrap();
2101        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
2102        std::fs::write(
2103            &path,
2104            r#"{ "/home/me/proj": true, "/home/me/untrusted": false, "/home/me/null": null }"#,
2105        )
2106        .unwrap();
2107        let store = read_trust().unwrap();
2108        assert_eq!(store.len(), 3);
2109        assert_eq!(store.get("/home/me/proj").copied().flatten(), Some(true));
2110        assert_eq!(
2111            store.get("/home/me/untrusted").copied().flatten(),
2112            Some(false)
2113        );
2114        assert_eq!(store.get("/home/me/null").copied().flatten(), None);
2115    }
2116
2117    #[test]
2118    fn resolve_config_value_literal_passthrough() {
2119        assert_eq!(
2120            resolve_config_value("sk-literal-key", None),
2121            Some("sk-literal-key".into())
2122        );
2123    }
2124
2125    #[test]
2126    fn resolve_config_value_env_var() {
2127        let _guard = env_lock().lock().unwrap();
2128        let prev = std::env::var_os("RPI_TEST_CFG_KEY");
2129        let prev2 = std::env::var_os("RPI_TEST_CFG_KEY2");
2130        std::env::set_var("RPI_TEST_CFG_KEY", "secret-from-env");
2131        assert_eq!(
2132            resolve_config_value("$RPI_TEST_CFG_KEY", None),
2133            Some("secret-from-env".into())
2134        );
2135        assert_eq!(
2136            resolve_config_value("prefix-${RPI_TEST_CFG_KEY}-suffix", None),
2137            Some("prefix-secret-from-env-suffix".into())
2138        );
2139        // Two vars in one template.
2140        std::env::set_var("RPI_TEST_CFG_KEY2", "two");
2141        assert_eq!(
2142            resolve_config_value("a-$RPI_TEST_CFG_KEY-b-$RPI_TEST_CFG_KEY2-c", None),
2143            Some("a-secret-from-env-b-two-c".into())
2144        );
2145        // Env overlay wins over process env.
2146        let mut overlay = BTreeMap::new();
2147        overlay.insert("RPI_TEST_CFG_KEY".into(), "overlay-value".into());
2148        assert_eq!(
2149            resolve_config_value("$RPI_TEST_CFG_KEY", Some(&overlay)),
2150            Some("overlay-value".into())
2151        );
2152        restore_env("RPI_TEST_CFG_KEY", prev);
2153        restore_env("RPI_TEST_CFG_KEY2", prev2);
2154    }
2155
2156    #[test]
2157    fn resolve_config_value_unset_env_is_none() {
2158        let _guard = env_lock().lock().unwrap();
2159        let prev = std::env::var_os("RPI_TEST_CFG_ABSENT");
2160        std::env::remove_var("RPI_TEST_CFG_ABSENT");
2161        // Any referenced unset var ⇒ the whole value is None (pi semantics).
2162        assert_eq!(resolve_config_value("$RPI_TEST_CFG_ABSENT", None), None);
2163        assert_eq!(
2164            resolve_config_value("prefix-$RPI_TEST_CFG_ABSENT-suffix", None),
2165            None
2166        );
2167        restore_env("RPI_TEST_CFG_ABSENT", prev);
2168    }
2169
2170    #[test]
2171    fn resolve_config_value_dollar_dollar_escapes_literal() {
2172        assert_eq!(
2173            resolve_config_value("price-$$5", None),
2174            Some("price-$5".into())
2175        );
2176        assert_eq!(resolve_config_value("$!bang", None), Some("!bang".into()));
2177    }
2178
2179    #[test]
2180    fn resolve_config_value_command_runs_shell() {
2181        // `!echo resolved` → "resolved" (sh on Unix; `echo` works under cmd too).
2182        assert_eq!(
2183            resolve_config_value_uncached("!echo rpi-cfg-resolved", None),
2184            Some("rpi-cfg-resolved".into())
2185        );
2186        // Non-zero exit ⇒ None.
2187        assert_eq!(resolve_config_value_uncached("!false", None), None);
2188    }
2189
2190    #[test]
2191    fn resolve_headers_drops_unresolvable() {
2192        let _guard = env_lock().lock().unwrap();
2193        let prev = std::env::var_os("RPI_TEST_HDR_SET");
2194        std::env::set_var("RPI_TEST_HDR_SET", "set-value");
2195        let mut h = BTreeMap::new();
2196        h.insert("x-set".into(), "$RPI_TEST_HDR_SET".into());
2197        h.insert("x-unset".into(), "$RPI_TEST_HDR_UNSET".into());
2198        h.insert("x-literal".into(), "literal-value".into());
2199        let resolved = resolve_headers(&h, None);
2200        assert_eq!(resolved.len(), 2);
2201        assert_eq!(resolved.get("x-set").map(|s| s.as_str()), Some("set-value"));
2202        assert_eq!(
2203            resolved.get("x-literal").map(|s| s.as_str()),
2204            Some("literal-value")
2205        );
2206        assert!(!resolved.contains_key("x-unset"));
2207        restore_env("RPI_TEST_HDR_SET", prev);
2208    }
2209
2210    #[test]
2211    fn agent_dir_respects_env_override() {
2212        let _guard = env_lock().lock().unwrap();
2213        let prev = std::env::var_os(CONFIG_DIR_ENV);
2214        let tmp = tempfile::TempDir::new().unwrap();
2215        std::env::set_var(CONFIG_DIR_ENV, tmp.path());
2216        let dir = agent_dir().unwrap();
2217        restore_env(CONFIG_DIR_ENV, prev);
2218        assert_eq!(dir, tmp.path());
2219    }
2220
2221    #[test]
2222    fn relative_override_is_rejected() {
2223        let _guard = env_lock().lock().unwrap();
2224        let prev = std::env::var_os(CONFIG_DIR_ENV);
2225        std::env::set_var(CONFIG_DIR_ENV, "relative/path");
2226        let err = agent_dir().unwrap_err();
2227        restore_env(CONFIG_DIR_ENV, prev);
2228        assert!(matches!(err, ConfigError::RelativeOverride { .. }));
2229    }
2230
2231    /// Restore/remove an env var based on its prior `OsString` value.
2232    fn restore_env(name: &str, prev: Option<std::ffi::OsString>) {
2233        match prev {
2234            Some(v) => std::env::set_var(name, v),
2235            None => std::env::remove_var(name),
2236        }
2237    }
2238}
2239
2240/// Convert host configuration with the same rules as the embeddable runtime.
2241pub fn provider_to_models(provider_id: &str, cfg: &ProviderConfig) -> Option<Vec<Model>> {
2242    rpi_runtime::config::provider_to_models(provider_id, cfg, &crate::provider::CliValues)
2243}