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