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//! Concurrent `rpi auth login` from two shells could lose one update — that's
26//! accepted and documented; adding a file lock is deferred.
27//!
28//! # Config-value expansion
29//!
30//! [`resolve_config_value`] expands `$ENV`/`${ENV}`/`!command` inside
31//! `apiKey`/`headers` exactly like upstream's `resolve-config-value.ts` — so a
32//! copied pi `models.json`/`auth.json` that references env vars or shell
33//! commands resolves the same way. Applied where rpi consumes those values
34//! (auth.json key, models.json bearer apiKey, provider/model `headers`).
35
36use std::collections::BTreeMap;
37use std::io::Write;
38use std::path::{Path, PathBuf};
39
40use rpi_ai::{Api, InputModality, Model, ModelCost, StreamingProtocolCompat, ThinkingLevelMap};
41
42/// The config directory name under the home dir.
43pub const CONFIG_DIR_NAME: &str = ".rpi";
44
45/// Env var that overrides the whole config dir. Absolute path; relative
46/// values are rejected.
47pub const CONFIG_DIR_ENV: &str = "RPI_CODING_AGENT_DIR";
48
49/// The provider id under which `rpi auth login` stores the Anthropic key.
50/// Mirrors upstream's fixed `anthropic` provider id.
51pub const DEFAULT_PROVIDER_ID: &str = "anthropic";
52
53// ---------------------------------------------------------------------------
54// Errors
55// ---------------------------------------------------------------------------
56
57/// A config-layer error (path resolution, IO, JSON). Surfaced to the user by
58/// the `auth` subcommand / `provider::resolve`.
59#[derive(Debug, thiserror::Error)]
60pub enum ConfigError {
61    #[error("could not resolve home directory (set {env} to override)")]
62    NoHomeDir { env: &'static str },
63    #[error("config dir override {env}={val:?} is not an absolute path")]
64    RelativeOverride { env: &'static str, val: String },
65    #[error("could not read {path}: {source}")]
66    Read {
67        path: PathBuf,
68        #[source]
69        source: std::io::Error,
70    },
71    #[error("could not write {path}: {source}")]
72    Write {
73        path: PathBuf,
74        #[source]
75        source: std::io::Error,
76    },
77    #[error("invalid JSON in {path}: {source}")]
78    Json {
79        path: PathBuf,
80        #[source]
81        source: serde_json::Error,
82    },
83}
84
85// ---------------------------------------------------------------------------
86// Path resolution
87// ---------------------------------------------------------------------------
88
89/// The rpi config directory (`~/.rpi/agent` by default, `RPI_CODING_AGENT_DIR`
90/// override). Creates nothing — purely a path computation. The `agent/` layer
91/// is `join(homedir(), CONFIG_DIR_NAME, "agent")`. The env override points at
92/// the agent dir itself.
93pub fn agent_dir() -> Result<PathBuf, ConfigError> {
94    if let Some(val) = std::env::var_os(CONFIG_DIR_ENV) {
95        let p = PathBuf::from(&val);
96        if !p.is_absolute() {
97            return Err(ConfigError::RelativeOverride {
98                env: CONFIG_DIR_ENV,
99                val: val.to_string_lossy().into_owned(),
100            });
101        }
102        return Ok(p);
103    }
104    let home = dirs::home_dir().ok_or(ConfigError::NoHomeDir {
105        env: CONFIG_DIR_ENV,
106    })?;
107    Ok(home.join(CONFIG_DIR_NAME).join("agent"))
108}
109
110/// The config dir one level above the agent dir (`~/.rpi`, or the parent of an
111/// env override). Used by [`migrate_legacy_layout`] to locate the old flat
112/// layout. Returns `None` when the env override has no parent (a root path).
113fn config_root_dir() -> Result<PathBuf, ConfigError> {
114    let agent = agent_dir()?;
115    agent
116        .parent()
117        .map(Path::to_path_buf)
118        .ok_or(ConfigError::NoHomeDir {
119            env: CONFIG_DIR_ENV,
120        })
121}
122
123/// `~/.rpi/agent/auth.json`.
124pub fn auth_path() -> Result<PathBuf, ConfigError> {
125    Ok(agent_dir()?.join("auth.json"))
126}
127
128/// `~/.rpi/agent/models.json`.
129pub fn models_path() -> Result<PathBuf, ConfigError> {
130    Ok(agent_dir()?.join("models.json"))
131}
132
133/// `~/.rpi/agent/settings.json` (saved default provider/model/thinking + theme).
134pub fn settings_path() -> Result<PathBuf, ConfigError> {
135    Ok(agent_dir()?.join("settings.json"))
136}
137
138/// `~/.rpi/agent/trust.json` (per-cwd project trust decisions).
139pub fn trust_path() -> Result<PathBuf, ConfigError> {
140    Ok(agent_dir()?.join("trust.json"))
141}
142
143fn read_text_with_fallback(
144    primary: PathBuf,
145    fallback: Option<PathBuf>,
146) -> Result<Option<(PathBuf, String)>, ConfigError> {
147    match std::fs::read_to_string(&primary) {
148        Ok(text) => Ok(Some((primary, text))),
149        Err(source) if source.kind() == std::io::ErrorKind::NotFound => {
150            let Some(fallback) = fallback.filter(|path| path != &primary) else {
151                return Ok(None);
152            };
153            match std::fs::read_to_string(&fallback) {
154                Ok(text) => Ok(Some((fallback, text))),
155                Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(None),
156                Err(source) => Err(ConfigError::Read {
157                    path: fallback,
158                    source,
159                }),
160            }
161        }
162        Err(source) => Err(ConfigError::Read {
163            path: primary,
164            source,
165        }),
166    }
167}
168
169/// One-time best-effort migration of a pre-nesting flat layout
170/// (`~/.rpi/{auth.json,models.json,.setup_done}`) into the
171/// nested `~/.rpi/agent/` layout. **No-op when `RPI_CODING_AGENT_DIR` is set**
172/// (never touch an explicit override), when the agent dir already exists, or
173/// when no flat files are present. Idempotent: a partial move resumes. Errors
174/// are swallowed (logged via the returned `Result` only so tests can observe);
175/// `app::run` ignores them so a migration hiccup never blocks startup.
176pub fn migrate_legacy_layout() -> Result<usize, ConfigError> {
177    // Only migrate the default home-backed layout — never an env override.
178    if std::env::var_os(CONFIG_DIR_ENV).is_some() {
179        return Ok(0);
180    }
181    let root = match config_root_dir() {
182        Ok(p) => p,
183        Err(_) => return Ok(0),
184    };
185    let agent = agent_dir()?;
186    migrate_legacy_layout_in(&root, &agent)
187}
188
189/// The core migration (no env gate): if `agent/` is absent but flat files exist
190/// under `root`, move `{auth.json,models.json,.setup_done}` into
191/// `agent/`. Idempotent. Factored out so tests can drive it against a temp
192/// root/agent pair without touching the env (the public
193/// [`migrate_legacy_layout`] short-circuits on an env override, which tests
194/// can't unset portably while other tests run).
195fn migrate_legacy_layout_in(root: &Path, agent: &Path) -> Result<usize, ConfigError> {
196    // If the agent dir already exists with any content, assume already migrated.
197    if agent.exists() {
198        return Ok(0);
199    }
200    // Probe for a flat file. If none, nothing to migrate.
201    let flat_auth = root.join("auth.json");
202    let flat_models = root.join("models.json");
203    if !flat_auth.exists() && !flat_models.exists() {
204        return Ok(0);
205    }
206    std::fs::create_dir_all(agent).map_err(|e| ConfigError::Write {
207        path: agent.to_path_buf(),
208        source: e,
209    })?;
210    let mut moved = 0usize;
211    for leaf in ["auth.json", "models.json", ".setup_done"] {
212        let from = root.join(leaf);
213        let to = agent.join(leaf);
214        if from.exists() && !to.exists() {
215            // `rename` across the same filesystem is atomic; fall back to copy
216            // + remove on cross-device (rare for a home dir).
217            if let Err(_e) = std::fs::rename(&from, &to) {
218                if std::fs::copy(&from, &to).is_ok() {
219                    let _ = std::fs::remove_file(&from);
220                }
221            }
222            moved += 1;
223        }
224    }
225    Ok(moved)
226}
227
228// ---------------------------------------------------------------------------
229// auth.json — Credential store
230// ---------------------------------------------------------------------------
231
232/// A stored credential. Mirrors the TS `Credential` union
233/// (`packages/ai/src/auth/types.ts`). OAuth credentials are provider-scoped
234/// and must never be logged or exposed to the agent transcript.
235#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
236#[serde(rename_all = "snake_case", tag = "type")]
237pub enum Credential {
238    /// An API key, optionally sourced from an env var map. v1 stores only the
239    /// literal `key` (the `env` field is kept for upstream-shape compatibility).
240    ApiKey {
241        key: Option<String>,
242        #[serde(default, skip_serializing_if = "Option::is_none")]
243        env: Option<BTreeMap<String, String>>,
244    },
245    /// OAuth tokens (access + refresh + expiry).
246    Oauth {
247        access: String,
248        #[serde(default)]
249        refresh: String,
250        /// Unix epoch seconds. `0` means no known expiry.
251        #[serde(default)]
252        expires: i64,
253    },
254}
255
256/// The auth store: `providerId -> Credential`. Mirrors upstream
257/// `Record<providerId, Credential>`.
258pub type AuthStore = BTreeMap<String, Credential>;
259
260/// Read the auth store. Missing file ⇒ empty store (not an error). Malformed
261/// JSON ⇒ `ConfigError::Json` (we do not silently swallow a corrupt auth file).
262pub fn read_auth() -> Result<AuthStore, ConfigError> {
263    let path = auth_path()?;
264    match read_text_with_fallback(path, None)? {
265        Some((path, text)) => {
266            serde_json::from_str(&text).map_err(|source| ConfigError::Json { path, source })
267        }
268        None => Ok(AuthStore::new()),
269    }
270}
271
272/// Atomically write the whole auth store (ensures the dir exists, writes a
273/// temp sibling, `rename`s over the target, then `chmod 0o600` on Unix).
274pub fn write_auth(store: &AuthStore) -> Result<(), ConfigError> {
275    let path = auth_path()?;
276    let dir = agent_dir()?;
277    ensure_dir(&dir)?;
278    let json = serde_json::to_string_pretty(store).unwrap();
279    atomic_write(&path, json.as_bytes())?;
280    set_owner_only(&path);
281    Ok(())
282}
283
284/// Read-modify-write: upsert a credential for `provider_id`.
285pub fn upsert_credential(provider_id: &str, cred: Credential) -> Result<(), ConfigError> {
286    let mut store = read_auth()?;
287    store.insert(provider_id.to_string(), cred);
288    write_auth(&store)
289}
290
291/// Store an OAuth token under exactly one provider id using the atomic auth
292/// store writer. Token values never enter the event or session layer.
293pub fn upsert_oauth_token(
294    provider_id: &str,
295    access: String,
296    refresh: String,
297    expires: i64,
298) -> Result<(), ConfigError> {
299    upsert_credential(
300        provider_id,
301        Credential::Oauth {
302            access,
303            refresh,
304            expires,
305        },
306    )
307}
308
309/// Read only the OAuth credential for one provider.
310pub fn read_oauth_token(provider_id: &str) -> Result<Option<Credential>, ConfigError> {
311    Ok(match read_auth()?.get(provider_id) {
312        Some(Credential::Oauth {
313            access,
314            refresh,
315            expires,
316        }) => Some(Credential::Oauth {
317            access: access.clone(),
318            refresh: refresh.clone(),
319            expires: *expires,
320        }),
321        _ => None,
322    })
323}
324
325/// Remove `provider_id` from the store. Returns `true` if a credential was
326/// present (and is now gone), `false` if it was already absent. Always rewrites
327/// the file when the provider existed (so `auth logout` reflects the new state
328/// on disk even if the map isn't empty).
329pub fn delete_credential(provider_id: &str) -> Result<bool, ConfigError> {
330    let mut store = read_auth()?;
331    if store.remove(provider_id).is_some() {
332        write_auth(&store)?;
333        Ok(true)
334    } else {
335        Ok(false)
336    }
337}
338
339// ---------------------------------------------------------------------------
340// models.json — provider/model catalog
341// ---------------------------------------------------------------------------
342
343/// The `models.json` document. Mirrors TS `{ providers: Record<id, ProviderConfig> }`
344/// (`core/model-config.ts` `ModelsConfigSchema`).
345#[derive(serde::Serialize, serde::Deserialize, Default, Debug, Clone)]
346#[serde(rename_all = "camelCase")]
347pub struct ModelsConfig {
348    #[serde(default, skip_serializing_if = "indexmap::IndexMap::is_empty")]
349    // Provider entries are walked in declaration order, so declaration order
350    // participates in the final available-model fallback.
351    pub providers: indexmap::IndexMap<String, ProviderConfig>,
352}
353
354/// A provider entry in `models.json`. The fields mirror the TS `ProviderConfig`
355/// one-for-one; v1 honors `base_url`/`api_key`/`headers`/`auth_header`/`models`,
356/// and **ignores** `api` values other than `anthropic-messages` (documented).
357#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
358#[serde(rename_all = "camelCase")]
359pub struct ProviderConfig {
360    #[serde(default, skip_serializing_if = "Option::is_none")]
361    pub name: Option<String>,
362    #[serde(default, skip_serializing_if = "Option::is_none")]
363    pub base_url: Option<String>,
364    #[serde(default, skip_serializing_if = "Option::is_none")]
365    pub api_key: Option<String>,
366    #[serde(default, skip_serializing_if = "Option::is_none")]
367    pub api: Option<String>,
368    #[serde(default, skip_serializing_if = "Option::is_none")]
369    pub headers: Option<BTreeMap<String, String>>,
370    /// `true` ⇒ wrap `api_key` as `Authorization: Bearer <key>` (mirrors
371    /// upstream `provider-composer.ts` `authHeader`).
372    #[serde(default, skip_serializing_if = "Option::is_none")]
373    pub auth_header: Option<bool>,
374    #[serde(default, skip_serializing_if = "Vec::is_empty")]
375    pub models: Vec<ModelDefinition>,
376}
377
378/// One model under a provider. `id` is required (mirrors TS `ModelDefinition`).
379#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
380#[serde(rename_all = "camelCase")]
381pub struct ModelDefinition {
382    pub id: String,
383    #[serde(default, skip_serializing_if = "Option::is_none")]
384    pub name: Option<String>,
385    #[serde(default, skip_serializing_if = "Option::is_none")]
386    pub base_url: Option<String>,
387    #[serde(default, skip_serializing_if = "Option::is_none")]
388    pub reasoning: Option<bool>,
389    #[serde(default, skip_serializing_if = "Option::is_none")]
390    pub thinking_level_map: Option<ThinkingLevelMap>,
391    #[serde(default, skip_serializing_if = "Option::is_none")]
392    pub context_window: Option<u64>,
393    #[serde(default, skip_serializing_if = "Option::is_none")]
394    pub max_tokens: Option<u64>,
395    /// USD per million tokens, including optional long-context pricing tiers.
396    #[serde(default, skip_serializing_if = "Option::is_none")]
397    pub cost: Option<ModelCost>,
398    /// Free-form modality strings ("text"/"image"); unknown values fall back
399    /// to text-only.
400    #[serde(default, skip_serializing_if = "Option::is_none")]
401    pub input: Option<Vec<String>>,
402    #[serde(default, skip_serializing_if = "Option::is_none")]
403    pub headers: Option<BTreeMap<String, String>>,
404    #[serde(default, skip_serializing_if = "Option::is_none")]
405    pub compat: Option<serde_json::Value>,
406}
407
408/// Load `~/.rpi/models.json`. Missing file ⇒ empty config (no error).
409pub fn load_models_config() -> Result<ModelsConfig, ConfigError> {
410    let path = models_path()?;
411    match read_text_with_fallback(path, None)? {
412        Some((path, text)) => {
413            parse_models_json(&text).map_err(|source| ConfigError::Json { path, source })
414        }
415        None => Ok(ModelsConfig::default()),
416    }
417}
418
419/// Atomically write the whole `~/.rpi/models.json` (used by the interactive
420/// provider form). Note: unlike [`crate::settings::save_settings`], this
421/// serializes the modeled config directly, so hand-written comments and unknown
422/// fields in `models.json` are not preserved on rewrite. A timestamped
423/// `models.json.bak-*` snapshot is written first so a mistake can be reverted.
424pub fn save_models_config(cfg: &ModelsConfig) -> Result<(), ConfigError> {
425    let path = models_path()?;
426    let dir = agent_dir()?;
427    ensure_dir(&dir)?;
428    // Back up the existing file before rewriting it (best-effort; a missing
429    // file is normal on first save).
430    if let Ok(existing) = std::fs::read(&path) {
431        let stamp = std::time::SystemTime::now()
432            .duration_since(std::time::UNIX_EPOCH)
433            .map(|d| d.as_secs())
434            .unwrap_or(0);
435        let backup = dir.join(format!("models.json.bak-{stamp}"));
436        let _ = std::fs::write(&backup, existing);
437    }
438    let text = serde_json::to_string_pretty(cfg).map_err(|source| ConfigError::Json {
439        path: path.clone(),
440        source,
441    })?;
442    atomic_write(&path, text.as_bytes())
443}
444
445// ---------------------------------------------------------------------------
446// trust.json — project-trust store (read-only layout parity with pi)
447// ---------------------------------------------------------------------------
448
449/// The trust store: `canonicalCwd -> decision` (`true`/`false`/`null`). Mirrors
450/// pi's `TrustFile = Record<string, boolean | null | undefined>`
451/// (`trust-manager.ts`). rpi reads this for layout parity (a copied pi
452/// `trust.json` parses + is located correctly) but does **not** gate any
453/// project resources behind trust in v1 — there is no trust prompt. Deferred.
454pub type TrustStore = BTreeMap<String, Option<bool>>;
455
456/// Read `~/.rpi/agent/trust.json`. Missing file ⇒ empty store (not an error).
457/// Malformed JSON ⇒ `ConfigError::Json`. `null` decisions deserialize as
458/// `None`; absent entries are simply not present.
459pub fn read_trust() -> Result<TrustStore, ConfigError> {
460    let path = trust_path()?;
461    match std::fs::read_to_string(&path) {
462        Ok(text) => serde_json::from_str(&text).map_err(|e| ConfigError::Json {
463            path: path.clone(),
464            source: e,
465        }),
466        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(TrustStore::new()),
467        Err(e) => Err(ConfigError::Read { path, source: e }),
468    }
469}
470
471/// Persist the trust decision for a project directory. The path is canonical
472/// when it exists, with an absolute fallback for a project being created.
473pub fn set_project_trust(cwd: &Path, trusted: Option<bool>) -> Result<(), ConfigError> {
474    let key = std::fs::canonicalize(cwd)
475        .unwrap_or_else(|_| cwd.to_path_buf())
476        .to_string_lossy()
477        .into_owned();
478    let mut store = read_trust()?;
479    if let Some(decision) = trusted {
480        store.insert(key, Some(decision));
481    } else {
482        store.remove(&key);
483    }
484    let path = trust_path()?;
485    ensure_dir(&agent_dir()?)?;
486    let json = serde_json::to_string_pretty(&store).unwrap();
487    atomic_write(&path, json.as_bytes())?;
488    set_owner_only(&path);
489    Ok(())
490}
491
492/// Return the stored trust decision for `cwd`. A missing entry (or an entry
493/// explicitly set to `null`) returns `None`; callers choose their safe default.
494pub fn project_trust_decision(cwd: &Path) -> Result<Option<bool>, ConfigError> {
495    let key = std::fs::canonicalize(cwd)
496        .unwrap_or_else(|_| cwd.to_path_buf())
497        .to_string_lossy()
498        .into_owned();
499    Ok(read_trust()?.get(&key).copied().flatten())
500}
501
502/// Parse the models JSON, tolerating `//` line comments (a minimal subset of
503/// upstream's `stripJsonComments`). Tries strict JSON first; on failure, strips
504/// `//…` to end-of-line and retries.
505fn parse_models_json(text: &str) -> Result<ModelsConfig, serde_json::Error> {
506    match serde_json::from_str(text) {
507        Ok(c) => Ok(c),
508        Err(first) => {
509            // Best-effort comment strip — only `//` to EOL, never inside strings
510            // (a `//` inside a JSON string would already have made the strict
511            // parse fail for a *different* reason; stripping naively is an
512            // acceptable v1 trade-off, documented as a limitation).
513            let stripped = strip_line_comments(text);
514            serde_json::from_str(&stripped).map_err(|_| first)
515        }
516    }
517}
518
519/// Strip `//` line comments (to end-of-line), skipping `//` that appears inside
520/// a double-quoted string. A minimal subset of upstream's `stripJsonComments`,
521/// shared by [`parse_models_json`] and [`crate::settings::load_settings`] so a
522/// copied pi `models.json`/`settings.json` (which pi allows comments in) parses.
523pub(crate) fn strip_line_comments(text: &str) -> String {
524    text.lines()
525        .map(|line| match find_line_comment(line) {
526            Some(idx) => line[..idx].to_string(),
527            None => line.to_string(),
528        })
529        .collect::<Vec<_>>()
530        .join("\n")
531}
532
533/// Index of a `//` line comment that is *not* inside a double-quoted string.
534fn find_line_comment(line: &str) -> Option<usize> {
535    let mut in_str = false;
536    let mut esc = false;
537    for (i, ch) in line.char_indices() {
538        if esc {
539            esc = false;
540            continue;
541        }
542        match ch {
543            '\\' if in_str => esc = true,
544            '"' => in_str = !in_str,
545            '/' if !in_str && line.as_bytes().get(i + 1) == Some(&b'/') => {
546                return Some(i);
547            }
548            _ => {}
549        }
550    }
551    None
552}
553
554// ---------------------------------------------------------------------------
555// Config-value expansion (mirrors pi `resolve-config-value.ts`)
556// ---------------------------------------------------------------------------
557
558/// A process-lifetime cache for `!command` resolutions, mirroring pi's
559/// `commandResultCache`. Keyed by the raw `!cmd` string (including the `!`).
560fn command_cache() -> &'static std::sync::Mutex<std::collections::HashMap<String, Option<String>>> {
561    static CACHE: std::sync::OnceLock<
562        std::sync::Mutex<std::collections::HashMap<String, Option<String>>>,
563    > = std::sync::OnceLock::new();
564    CACHE.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()))
565}
566
567/// Resolve a config value (API key, header value) that may be a shell command,
568/// an env-var template, or a literal — mirroring pi's `resolveConfigValue`.
569///
570/// - `!command` → run the rest as a shell command (`sh -c` on Unix, `cmd /C` on
571///   Windows), return trimmed stdout (cached per process). Missing shell or
572///   non-zero exit ⇒ `None`.
573/// - `$VAR` / `${VAR}` templates: interpolate from `env_overlay` (winning) then
574///   the process env. `$$`→`$`, `$!`→`!` escapes. Any referenced var that is
575///   unset ⇒ the **whole** value resolves to `None` (pi semantics).
576/// - Otherwise the literal string (returned as-is).
577///
578/// `env_overlay` is the `credential.env` map for auth.json keys (pi passes the
579/// same). `None` (or an empty overlay) means process-env only — used for
580/// models.json apiKey/headers, which have no env overlay.
581pub fn resolve_config_value(
582    config: &str,
583    env_overlay: Option<&BTreeMap<String, String>>,
584) -> Option<String> {
585    if let Some(cmd) = config.strip_prefix('!') {
586        return resolve_command(cmd);
587    }
588    resolve_template(config, env_overlay)
589}
590
591/// Like [`resolve_config_value`] but **uncached** — mirrors pi's
592/// `resolveConfigValueUncached`, used when a fresh resolution is required
593/// (e.g. headers, which pi resolves uncached so a rotating token is re-read).
594pub fn resolve_config_value_uncached(
595    config: &str,
596    env_overlay: Option<&BTreeMap<String, String>>,
597) -> Option<String> {
598    if let Some(cmd) = config.strip_prefix('!') {
599        return resolve_command_uncached(cmd);
600    }
601    resolve_template(config, env_overlay)
602}
603
604/// Resolve every header value via [`resolve_config_value_uncached`]; drop
605/// entries that resolve to `None` (mirrors pi `resolveHeaders`). Used on
606/// models.json `headers` maps before folding onto a model.
607pub fn resolve_headers(
608    headers: &BTreeMap<String, String>,
609    env_overlay: Option<&BTreeMap<String, String>>,
610) -> BTreeMap<String, String> {
611    let mut out = BTreeMap::new();
612    for (k, v) in headers {
613        if let Some(resolved) = resolve_config_value_uncached(v, env_overlay) {
614            out.insert(k.clone(), resolved);
615        }
616    }
617    out
618}
619
620/// Env lookup: `env_overlay` (if present) wins over the process env, matching
621/// pi's `resolveEnvConfigValue` (which checks `env?.[name]` before `process.env`).
622fn env_lookup(name: &str, env_overlay: Option<&BTreeMap<String, String>>) -> Option<String> {
623    if let Some(overlay) = env_overlay {
624        if let Some(v) = overlay.get(name) {
625            return Some(v.clone());
626        }
627    }
628    std::env::var(name).ok()
629}
630
631/// A parsed template part — literal text or an env-var reference.
632enum TemplatePart {
633    Literal(String),
634    Env(String),
635}
636
637/// Parse a `$VAR`/`${VAR}` template (mirrors pi `parseConfigValueTemplate`).
638/// `$$`→`$` and `$!`→`!` are escapes; `${NAME}` requires `NAME` to match
639/// `^[A-Za-z_][A-Za-z0-9_]*$` else the raw slice is kept literal; `$NAME` takes
640/// the longest `[A-Za-z_][A-Za-z0-9_]*` prefix as the name.
641fn parse_template(config: &str) -> Vec<TemplatePart> {
642    let mut parts: Vec<TemplatePart> = Vec::new();
643    let bytes = config.as_bytes();
644    let mut i = 0usize;
645    while i < bytes.len() {
646        // Find the next `$`.
647        match config[i..].find('$') {
648            None => {
649                push_literal(&mut parts, &config[i..]);
650                break;
651            }
652            Some(offset) => {
653                let dollar = i + offset;
654                push_literal(&mut parts, &config[i..dollar]);
655                let after = dollar + 1;
656                let next = bytes.get(after).copied();
657                if next == Some(b'$') || next == Some(b'!') {
658                    push_literal(&mut parts, &config[after..after + 1]);
659                    i = after + 1;
660                    continue;
661                }
662                if next == Some(b'{') {
663                    // ${NAME}
664                    if let Some(end_rel) = config[after + 1..].find('}') {
665                        let end = after + 1 + end_rel;
666                        let name = &config[after + 1..end];
667                        if is_env_name(name) {
668                            parts.push(TemplatePart::Env(name.to_string()));
669                        } else {
670                            // Not a valid name — keep the raw `${…}` literal.
671                            push_literal(&mut parts, &config[dollar..=end]);
672                        }
673                        i = end + 1;
674                        continue;
675                    }
676                    // No closing `}` — literal `$`.
677                    push_literal(&mut parts, "$");
678                    i = after;
679                    continue;
680                }
681                // $NAME (greedy prefix). Bare `$` with no name char follows.
682                if let Some(name) = env_name_prefix(&config[after..]) {
683                    parts.push(TemplatePart::Env(name.to_string()));
684                    i = after + name.len();
685                } else {
686                    push_literal(&mut parts, "$");
687                    i = after;
688                }
689            }
690        }
691    }
692    parts
693}
694
695fn push_literal(parts: &mut Vec<TemplatePart>, value: &str) {
696    if value.is_empty() {
697        return;
698    }
699    if let Some(TemplatePart::Literal(s)) = parts.last_mut() {
700        s.push_str(value);
701    } else {
702        parts.push(TemplatePart::Literal(value.to_string()));
703    }
704}
705
706fn is_env_name(s: &str) -> bool {
707    let mut chars = s.chars();
708    match chars.next() {
709        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
710        _ => return false,
711    }
712    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
713}
714
715/// The longest `[A-Za-z_][A-Za-z0-9_]*` prefix of `s` (mirrors the TS
716/// `ENV_VAR_NAME_PREFIX_RE` match), or `None` when `s` doesn't start with one.
717fn env_name_prefix(s: &str) -> Option<&str> {
718    let mut chars = s.char_indices();
719    match chars.next() {
720        Some((_, c)) if c.is_ascii_alphabetic() || c == '_' => {}
721        _ => return None,
722    }
723    let end = chars
724        .find(|(_, c)| !(c.is_ascii_alphanumeric() || *c == '_'))
725        .map(|(idx, _)| idx)
726        .unwrap_or(s.len());
727    Some(&s[..end])
728}
729
730/// Resolve a parsed template: any referenced env var that is unset ⇒ the whole
731/// value is `None` (pi semantics). Literal-only templates pass through as-is.
732fn resolve_template(
733    config: &str,
734    env_overlay: Option<&BTreeMap<String, String>>,
735) -> Option<String> {
736    let parts = parse_template(config);
737    let mut out = String::with_capacity(config.len());
738    for part in parts {
739        match part {
740            TemplatePart::Literal(s) => out.push_str(&s),
741            TemplatePart::Env(name) => {
742                let v = env_lookup(&name, env_overlay)?;
743                out.push_str(&v)
744            }
745        }
746    }
747    Some(out)
748}
749
750/// Run `cmd` (without the leading `!`), returning trimmed stdout. Cached per
751/// process (mirrors pi `executeCommand`). 10s timeout; non-zero exit / missing
752/// shell ⇒ `None`.
753fn resolve_command(cmd: &str) -> Option<String> {
754    let key = format!("!{cmd}");
755    if let Some(v) = command_cache().lock().ok()?.get(&key) {
756        return v.clone();
757    }
758    let result = resolve_command_uncached(cmd);
759    if let Ok(mut cache) = command_cache().lock() {
760        cache.insert(key, result.clone());
761    }
762    result
763}
764
765#[cfg(unix)]
766fn spawn_shell_command(cmd: &str) -> Option<std::process::Output> {
767    std::process::Command::new("sh")
768        .arg("-c")
769        .arg(cmd)
770        .stdin(std::process::Stdio::null())
771        .stdout(std::process::Stdio::piped())
772        .stderr(std::process::Stdio::null())
773        .output()
774        .ok()
775}
776
777#[cfg(windows)]
778fn spawn_shell_command(cmd: &str) -> Option<std::process::Output> {
779    use std::os::windows::process::CommandExt;
780    std::process::Command::new("cmd")
781        .arg("/C")
782        .arg(cmd)
783        .stdin(std::process::Stdio::null())
784        .stdout(std::process::Stdio::piped())
785        .stderr(std::process::Stdio::null())
786        .creation_flags(0x0800_0000) // CREATE_NO_WINDOW
787        .output()
788        .ok()
789}
790
791/// Uncached `!command` execution (mirrors pi `executeCommandUncached`).
792fn resolve_command_uncached(cmd: &str) -> Option<String> {
793    let output = spawn_shell_command(cmd)?;
794    if !output.status.success() {
795        return None;
796    }
797    let stdout = String::from_utf8_lossy(&output.stdout);
798    let trimmed = stdout.trim();
799    if trimmed.is_empty() {
800        None
801    } else {
802        Some(trimmed.to_string())
803    }
804}
805
806/// (`anthropic-messages`, or omitted/unknown). Unknown `api` is allowed through
807/// for forward-compat but flagged ignored-in-v1 in the docs. Public so
808/// [`crate::provider`] can scan models.json providers for an `authHeader:true`
809/// gateway bearer source.
810pub fn provider_is_anthropic_compatible(cfg: &ProviderConfig) -> bool {
811    match cfg.api.as_deref() {
812        None | Some("") | Some("anthropic-messages") => true,
813        _ => false,
814    }
815}
816
817/// Whether a configured provider uses the OpenAI Chat Completions protocol.
818pub fn provider_is_openai_completions(cfg: &ProviderConfig) -> bool {
819    matches!(cfg.api.as_deref(), Some("openai-completions"))
820}
821
822pub fn provider_is_openai_responses(cfg: &ProviderConfig) -> bool {
823    matches!(cfg.api.as_deref(), Some("openai-responses"))
824}
825
826/// Resolve an OpenAI-compatible provider key from its explicit config or a
827/// known provider's canonical environment variable. Arbitrary custom provider
828/// ids must declare `apiKey: "$ENV"`: deriving an env name by normalizing the
829/// id would collapse distinct native-Pi identities such as `a-b` and `a_b`.
830pub fn openai_provider_api_key(provider_id: &str, cfg: &ProviderConfig) -> Option<String> {
831    if let Some(raw) = cfg.api_key.as_deref().filter(|key| !key.is_empty()) {
832        if let Some(value) = resolve_config_value(raw, None).filter(|value| !value.is_empty()) {
833            return Some(value);
834        }
835    }
836
837    let name = native_provider_api_key_env_var(provider_id)?;
838    std::env::var(name).ok().filter(|value| !value.is_empty())
839}
840
841/// Provider-id-to-environment-variable mapping. Provider ids are
842/// identities, so aliases and case variants must not inherit another
843/// provider's credential.
844fn native_provider_api_key_env_var(provider_id: &str) -> Option<&'static str> {
845    match provider_id {
846        "openai" => crate::credentials::builtin_api_key_env(provider_id),
847        _ => None,
848    }
849}
850
851/// Convert a `(provider_id, ProviderConfig)` pair into a list of library
852/// [`Model`]s. Provider-level `base_url`/`headers`/`auth_header` fold into each
853/// model. Returns `None` for protocols that do not have a runtime provider.
854pub fn provider_to_models(provider_id: &str, cfg: &ProviderConfig) -> Option<Vec<Model>> {
855    let api = if provider_is_anthropic_compatible(cfg) {
856        Api::AnthropicMessages
857    } else if provider_is_openai_completions(cfg) {
858        Api::OpenaiCompletions
859    } else if provider_is_openai_responses(cfg) {
860        Api::OpenaiResponses
861    } else {
862        return None;
863    };
864    let provider_base = cfg.base_url.clone().unwrap_or_else(|| match api {
865        Api::OpenaiCompletions | Api::OpenaiResponses => "https://api.openai.com".to_string(),
866        _ => default_anthropic_base_url(),
867    });
868    let mut merged: Vec<Model> = Vec::with_capacity(cfg.models.len());
869    for def in &cfg.models {
870        let base_url = def
871            .base_url
872            .clone()
873            .unwrap_or_else(|| provider_base.clone());
874        let name = def.name.clone().unwrap_or_else(|| def.id.clone());
875        let mut m = Model::new(
876            def.id.clone(),
877            name,
878            api.clone(),
879            provider_id.to_string(),
880            base_url,
881        );
882        m.reasoning = def.reasoning.unwrap_or(false);
883        m.thinking_level_map = def.thinking_level_map.clone();
884        m.context_window = def.context_window.unwrap_or(0);
885        m.max_tokens = def.max_tokens.unwrap_or(0);
886        if let Some(cost) = &def.cost {
887            m.cost = cost.clone();
888            m.cost_configured = true;
889        }
890        m.input = parse_input_modalities(def.input.as_deref());
891        // Merge: model-level headers, then provider-level headers (provider wins
892        // on conflict — it's the more specific-to-this-endpoint declaration).
893        // Values are resolved via `resolve_headers` (`$ENV`/`!command` expansion,
894        // mirroring pi's `resolveHeadersOrThrow`) so a copied pi models.json
895        // referencing env vars / commands resolves the same way. Models.json
896        // providers have no credential env overlay (only auth.json keys do), so
897        // the expansion is env-only here.
898        // Credential-derived headers are NOT synthesized in the catalog —
899        // [`crate::provider::resolve`] applies it centrally so it can skip it
900        // when a higher-priority x-api-key source (`--api-key` / auth.json /
901        // `ANTHROPIC_API_KEY`) wins. Folding it here unconditionally would put a
902        // Bearer on the model even on the x-api-key path. See
903        // `models_json_bearer_token` + the fold loop in `resolve`.
904        let mut headers: BTreeMap<String, String> = BTreeMap::new();
905        if let Some(h) = def.headers.clone() {
906            for (k, v) in resolve_headers(&h, None) {
907                headers.insert(k, v);
908            }
909        }
910        if let Some(h) = cfg.headers.clone() {
911            for (k, v) in resolve_headers(&h, None) {
912                headers.insert(k, v);
913            }
914        }
915        if matches!(api, Api::OpenaiCompletions | Api::OpenaiResponses) {
916            if let Some(value) = def.compat.clone() {
917                if matches!(api, Api::OpenaiResponses) {
918                    if let Ok(compat) = serde_json::from_value(value) {
919                        m.compat = Some(StreamingProtocolCompat::OpenaiResponses(compat));
920                    }
921                } else if let Ok(compat) = serde_json::from_value(value) {
922                    m.compat = Some(StreamingProtocolCompat::OpenaiCompletions(compat));
923                }
924            }
925        }
926        if !headers.is_empty() {
927            m.headers = Some(headers);
928        }
929        merged.push(m);
930    }
931    Some(merged)
932}
933
934/// Parse `["text","image"]`-style modality strings into [`InputModality`]s;
935/// unknown values drop to text-only. `None` ⇒ text (the [`Model::new`] default).
936fn parse_input_modalities(input: Option<&[String]>) -> Vec<InputModality> {
937    match input {
938        None => vec![InputModality::Text],
939        Some(list) if list.is_empty() => vec![InputModality::Text],
940        Some(list) => list
941            .iter()
942            .filter_map(|s| match s.to_ascii_lowercase().as_str() {
943                "text" => Some(InputModality::Text),
944                "image" => Some(InputModality::Image),
945                _ => None,
946            })
947            .collect::<Vec<_>>()
948            .pipe(|v| {
949                if v.is_empty() {
950                    vec![InputModality::Text]
951                } else {
952                    v
953                }
954            }),
955    }
956}
957
958/// The first-party Anthropic endpoint — used as the fallback `base_url` when a
959/// models.json provider omits it. Kept here (not imported from `rpi_ai`) so the
960/// config layer never depends on the provider's private `models` module.
961/// Public so [`crate::provider::resolve`] can tell a gateway model (whose
962/// `base_url` differs from this) from a built-in Anthropic model.
963pub const ANTHROPIC_DEFAULT_BASE_URL: &str = "https://api.anthropic.com";
964
965/// Same value as [`ANTHROPIC_DEFAULT_BASE_URL`], as an owned `String` for the
966/// `unwrap_or_else` ergonomic used by [`provider_to_models`] and
967/// [`crate::provider::models_json_provider_auth`].
968pub fn default_anthropic_base_url() -> String {
969    ANTHROPIC_DEFAULT_BASE_URL.to_string()
970}
971
972// ---------------------------------------------------------------------------
973// Internals: dir ensure, atomic write, chmod
974// ---------------------------------------------------------------------------
975
976#[cfg(unix)]
977use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
978
979/// Create the config dir if missing. Mode 0o700 on Unix (mkdir default on
980/// Windows, where the sticky-permission concept doesn't apply).
981fn ensure_dir(dir: &Path) -> Result<(), ConfigError> {
982    if dir.exists() {
983        return Ok(());
984    }
985    std::fs::create_dir_all(dir).map_err(|e| ConfigError::Write {
986        path: dir.to_path_buf(),
987        source: e,
988    })?;
989    #[cfg(unix)]
990    {
991        let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
992    }
993    Ok(())
994}
995
996/// Write `bytes` to `path` atomically: a temp sibling → `rename`. The temp
997/// file lives next to the target so the rename stays on one filesystem.
998pub(crate) fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), ConfigError> {
999    let dir = path.parent().ok_or_else(|| ConfigError::Write {
1000        path: path.to_path_buf(),
1001        source: std::io::Error::new(std::io::ErrorKind::InvalidInput, "path has no parent"),
1002    })?;
1003    let tmp = dir.join(format!(
1004        ".{}.{}.tmp",
1005        path.file_name().and_then(|n| n.to_str()).unwrap_or("rpi"),
1006        uuid::Uuid::new_v4().simple()
1007    ));
1008    let mut options = std::fs::OpenOptions::new();
1009    options.write(true).create_new(true);
1010    #[cfg(unix)]
1011    options.mode(0o600);
1012    let mut file = options.open(&tmp).map_err(|source| ConfigError::Write {
1013        path: tmp.clone(),
1014        source,
1015    })?;
1016    if let Err(error) = file.write_all(bytes).and_then(|()| file.sync_all()) {
1017        // A partial staging file is never useful to a later caller. Best
1018        // effort cleanup also avoids leaving a misleading stale temp behind
1019        // when the target itself was left untouched.
1020        let _ = std::fs::remove_file(&tmp);
1021        return Err(ConfigError::Write {
1022            path: tmp,
1023            source: error,
1024        });
1025    }
1026    drop(file);
1027    if let Err(error) = std::fs::rename(&tmp, path) {
1028        // `rename` is the publish point; on failure the original target is
1029        // still intact. Remove the staging file before returning the error.
1030        let _ = std::fs::remove_file(&tmp);
1031        return Err(ConfigError::Write {
1032            path: path.to_path_buf(),
1033            source: error,
1034        });
1035    }
1036    Ok(())
1037}
1038
1039/// Best-effort tighten to owner-only (0o600). No-op on Windows (the Node
1040/// upstream applies no ACL either).
1041fn set_owner_only(_path: &Path) {
1042    #[cfg(unix)]
1043    {
1044        let _ = std::fs::set_permissions(_path, std::fs::Permissions::from_mode(0o600));
1045    }
1046}
1047
1048// A tiny `.pipe`-shim so the `parse_input_modalities` chain reads top-to-bottom
1049// without pulling itertools. Kept private to this module.
1050trait Pipe: Sized {
1051    fn pipe<R>(self, f: impl FnOnce(Self) -> R) -> R {
1052        f(self)
1053    }
1054}
1055impl<T> Pipe for T {}
1056
1057// ---------------------------------------------------------------------------
1058// Tests
1059// ---------------------------------------------------------------------------
1060
1061#[cfg(test)]
1062pub(crate) mod test_support {
1063    /// A shared workspace lock for tests that touch process-global env vars
1064    /// (`RPI_CODING_AGENT_DIR`, `ANTHROPIC_*`). All env-mutating tests across
1065    /// the crate (config / provider / auth) share this ONE mutex so they can't
1066    /// race on the shared environment. Hold the returned guard for the whole
1067    /// test (store it in a RAII struct).
1068    use std::sync::{Mutex, OnceLock};
1069    pub(crate) fn env_lock() -> &'static Mutex<()> {
1070        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
1071        LOCK.get_or_init(|| Mutex::new(()))
1072    }
1073}
1074
1075#[cfg(test)]
1076mod tests {
1077    use super::*;
1078    use crate::config::test_support::env_lock;
1079
1080    /// Point `RPI_CODING_AGENT_DIR` at a fresh temp dir for the duration of the
1081    /// test (cleaned up on drop). Holds the prior value of the env var to
1082    /// restore it. Hold the env lock for its whole lifetime.
1083    struct TempConfig {
1084        _guard: std::sync::MutexGuard<'static, ()>,
1085        _tmp: tempfile::TempDir,
1086        prev: Option<std::ffi::OsString>,
1087    }
1088    impl TempConfig {
1089        fn new() -> Self {
1090            let guard = env_lock().lock().unwrap();
1091            let prev = std::env::var_os(CONFIG_DIR_ENV);
1092            let tmp = tempfile::TempDir::new().unwrap();
1093            std::env::set_var(CONFIG_DIR_ENV, tmp.path());
1094            Self {
1095                _guard: guard,
1096                _tmp: tmp,
1097                prev,
1098            }
1099        }
1100    }
1101    impl Drop for TempConfig {
1102        fn drop(&mut self) {
1103            restore_env(CONFIG_DIR_ENV, self.prev.take());
1104        }
1105    }
1106
1107    #[test]
1108    fn read_auth_missing_file_is_empty() {
1109        let _cfg = TempConfig::new();
1110        let store = read_auth().unwrap();
1111        assert!(store.is_empty());
1112    }
1113
1114    #[test]
1115    fn upsert_then_read_roundtrip() {
1116        let _cfg = TempConfig::new();
1117        upsert_credential(
1118            "anthropic",
1119            Credential::ApiKey {
1120                key: Some("sk-test-123".into()),
1121                env: None,
1122            },
1123        )
1124        .unwrap();
1125        let store = read_auth().unwrap();
1126        match store.get("anthropic") {
1127            Some(Credential::ApiKey { key, .. }) => assert_eq!(key.as_deref(), Some("sk-test-123")),
1128            other => panic!("unexpected cred: {other:?}"),
1129        }
1130        // The file should exist and be JSON.
1131        let path = auth_path().unwrap();
1132        assert!(path.exists(), "auth.json should exist after upsert");
1133        let raw = std::fs::read_to_string(&path).unwrap();
1134        assert!(raw.contains("\"anthropic\""));
1135        assert!(raw.contains("api_key"));
1136    }
1137
1138    #[test]
1139    fn oauth_token_is_scoped_and_round_trips() {
1140        let _cfg = TempConfig::new();
1141        upsert_oauth_token("acme", "access".into(), "refresh".into(), 123).unwrap();
1142        assert!(matches!(
1143            read_oauth_token("acme").unwrap(),
1144            Some(Credential::Oauth { access, refresh, expires })
1145                if access == "access" && refresh == "refresh" && expires == 123
1146        ));
1147        assert!(read_oauth_token("other").unwrap().is_none());
1148    }
1149
1150    #[test]
1151    fn delete_credential_removes_entry() {
1152        let _cfg = TempConfig::new();
1153        upsert_credential(
1154            "anthropic",
1155            Credential::ApiKey {
1156                key: Some("k".into()),
1157                env: None,
1158            },
1159        )
1160        .unwrap();
1161        assert!(delete_credential("anthropic").unwrap());
1162        // Second delete is a no-op.
1163        assert!(!delete_credential("anthropic").unwrap());
1164        assert!(read_auth().unwrap().is_empty());
1165    }
1166
1167    #[test]
1168    fn load_models_config_missing_is_empty() {
1169        let _cfg = TempConfig::new();
1170        let c = load_models_config().unwrap();
1171        assert!(c.providers.is_empty());
1172    }
1173
1174    #[test]
1175    fn fallback_reader_prefers_primary_and_only_falls_back_when_missing() {
1176        let tmp = tempfile::tempdir().unwrap();
1177        let primary = tmp.path().join("primary.json");
1178        let fallback = tmp.path().join("fallback.json");
1179        std::fs::write(&fallback, "fallback").unwrap();
1180
1181        let (_, text) = read_text_with_fallback(primary.clone(), Some(fallback.clone()))
1182            .unwrap()
1183            .expect("fallback should be read");
1184        assert_eq!(text, "fallback");
1185
1186        std::fs::write(&primary, "primary").unwrap();
1187        let (path, text) = read_text_with_fallback(primary.clone(), Some(fallback))
1188            .unwrap()
1189            .expect("primary should be read");
1190        assert_eq!(path, primary);
1191        assert_eq!(text, "primary");
1192    }
1193
1194    #[test]
1195    fn fallback_reader_does_not_mask_primary_read_errors() {
1196        let tmp = tempfile::tempdir().unwrap();
1197        let primary = tmp.path().join("primary.json");
1198        let fallback = tmp.path().join("fallback.json");
1199        std::fs::create_dir(&primary).unwrap();
1200        std::fs::write(&fallback, "fallback").unwrap();
1201
1202        let error = read_text_with_fallback(primary.clone(), Some(fallback)).unwrap_err();
1203        assert!(matches!(error, ConfigError::Read { path, .. } if path == primary));
1204    }
1205
1206    #[test]
1207    fn load_models_config_parses_with_comments() {
1208        let _cfg = TempConfig::new();
1209        let json = r#"{
1210  // a one-api style gateway
1211  "providers": {
1212    "gateway": {
1213      "baseUrl": "https://gw.example.com",
1214      "authHeader": true,
1215      "apiKey": "gw-secret",
1216      "models": [
1217        { "id": "claude-sonnet-5", "name": "Sonnet via gateway" }
1218      ]
1219    }
1220  }
1221}"#;
1222        std::fs::write(models_path().unwrap(), json).unwrap();
1223        let c = load_models_config().unwrap();
1224        let gw = c
1225            .providers
1226            .get("gateway")
1227            .expect("gateway provider present");
1228        assert_eq!(gw.base_url.as_deref(), Some("https://gw.example.com"));
1229        assert!(gw.auth_header.unwrap_or(false));
1230        assert_eq!(gw.models.len(), 1);
1231        assert_eq!(gw.models[0].id, "claude-sonnet-5");
1232    }
1233
1234    #[test]
1235    fn provider_to_models_merges_headers_without_synth_bearer() {
1236        // `provider_to_models` merges model-level then provider-level headers,
1237        // but does NOT synthesize the `authHeader:true` Bearer itself — that
1238        // happens centrally in `crate::provider::resolve` (via
1239        // `models_json_bearer_token`) so it can be skipped on the x-api-key
1240        // path. Here the model carries only what the file declared.
1241        let cfg = ProviderConfig {
1242            name: None,
1243            base_url: Some("https://gw.example.com".into()),
1244            api_key: Some("gw-secret".into()),
1245            api: None,
1246            headers: Some({
1247                let mut h = BTreeMap::new();
1248                h.insert("x-portkey-key".into(), "portkey-secret".into());
1249                h
1250            }),
1251            auth_header: Some(true),
1252            models: vec![ModelDefinition {
1253                id: "claude-sonnet-5".into(),
1254                name: None,
1255                base_url: None,
1256                reasoning: None,
1257                thinking_level_map: None,
1258                context_window: None,
1259                max_tokens: None,
1260                cost: None,
1261                input: None,
1262                headers: None,
1263                compat: None,
1264            }],
1265        };
1266        let models = provider_to_models("gateway", &cfg).expect("anthropic-compatible");
1267        assert_eq!(models.len(), 1);
1268        let m = &models[0];
1269        assert_eq!(m.id, "claude-sonnet-5");
1270        assert_eq!(m.base_url, "https://gw.example.com");
1271        assert_eq!(m.provider, "gateway");
1272        let headers = m.headers.as_ref().expect("provider headers merged");
1273        // Declared provider header folds in…
1274        assert_eq!(
1275            headers.get("x-portkey-key").map(|s| s.as_str()),
1276            Some("portkey-secret")
1277        );
1278        // …but no Bearer is synthesized here. The bearer-from-authHeader path
1279        // is exercised end-to-end by the provider.rs `resolve` tests
1280        // (`models_json_auth_header_satisfies_auth_without_env`,
1281        // `api_key_flag_beats_models_json_bearer`).
1282        assert!(
1283            headers.get("authorization").is_none(),
1284            "provider_to_models must not synthesize the Bearer; resolve does"
1285        );
1286    }
1287
1288    #[test]
1289    fn provider_to_models_supports_openai_completions() {
1290        let config: ModelsConfig = serde_json::from_str(
1291            r#"{
1292                "providers": {
1293                    "oai": {
1294                        "api": "openai-completions",
1295                        "baseUrl": "https://gateway.example.com/v1",
1296                        "apiKey": "secret",
1297                        "models": [{"id":"gpt-test","maxTokens":4096}]
1298                    }
1299                }
1300            }"#,
1301        )
1302        .unwrap();
1303        let models = provider_to_models("oai", &config.providers["oai"]).unwrap();
1304        assert_eq!(models.len(), 1);
1305        assert_eq!(models[0].api, Api::OpenaiCompletions);
1306        assert_eq!(models[0].provider, "oai");
1307        assert_eq!(models[0].max_tokens, 4096);
1308        assert_eq!(models[0].cost, ModelCost::default());
1309        assert!(!models[0].has_pricing());
1310        assert!(
1311            models[0].headers.is_none(),
1312            "credentials are bound after provider resolution"
1313        );
1314    }
1315
1316    #[test]
1317    fn models_json_pricing_reaches_providers_and_survives_serialization() {
1318        let mut config = parse_models_json(
1319            r#"{
1320                "providers": {
1321                    "pricing-fixture": {
1322                        "api": "anthropic-messages",
1323                        "models": [{
1324                            "id": "priced-model",
1325                            "cost": {
1326                                "input": 2, "output": 8, "cacheRead": 0.2, "cacheWrite": 2.5,
1327                                "tiers": [{
1328                                    "inputTokensAbove": 1000000,
1329                                    "input": 4, "output": 16, "cacheRead": 0.4, "cacheWrite": 5
1330                                }]
1331                            }
1332                        }]
1333                    }
1334                }
1335            }"#,
1336        )
1337        .unwrap();
1338        let expected = config.providers["pricing-fixture"].models[0]
1339            .cost
1340            .clone()
1341            .unwrap();
1342        for api in [
1343            "anthropic-messages",
1344            "openai-completions",
1345            "openai-responses",
1346        ] {
1347            let cfg = config.providers.get_mut("pricing-fixture").unwrap();
1348            cfg.api = Some(api.into());
1349            let models = provider_to_models("pricing-fixture", cfg).unwrap();
1350            assert_eq!(models[0].cost, expected);
1351            assert!(models[0].has_pricing());
1352            let mut usage = rpi_ai::Usage::zero();
1353            usage.input = 100_000;
1354            usage.output = 250_000;
1355            usage.cache_read = 300_000;
1356            usage.cache_write = 400_000;
1357            let cost = rpi_ai::providers::anthropic::cost::calculate_cost(&models[0].cost, &usage);
1358            assert!((cost.total - 3.26).abs() < 1e-10, "base pricing for {api}");
1359            usage.input = 1_000_001;
1360            usage.output = 1_000_000;
1361            usage.cache_read = 0;
1362            usage.cache_write = 0;
1363            let cost = rpi_ai::providers::anthropic::cost::calculate_cost(&models[0].cost, &usage);
1364            assert!(
1365                (cost.total - 20.000004).abs() < 1e-10,
1366                "tiered pricing for {api}"
1367            );
1368        }
1369        let saved = serde_json::to_string(&config).unwrap();
1370        let reloaded = parse_models_json(&saved).unwrap();
1371        assert_eq!(
1372            reloaded.providers["pricing-fixture"].models[0].cost,
1373            Some(expected)
1374        );
1375        let cfg = config.providers.get_mut("pricing-fixture").unwrap();
1376        cfg.models[0].cost = Some(ModelCost::default());
1377        let free = provider_to_models("pricing-fixture", cfg).unwrap();
1378        assert_eq!(free[0].cost, ModelCost::default());
1379        assert!(
1380            free[0].has_pricing(),
1381            "explicit zero prices are still configured"
1382        );
1383    }
1384
1385    #[test]
1386    fn models_json_compat_reaches_the_model_for_openai_completions() {
1387        // The `compat` block is what lets a custom openai-completions provider
1388        // describe its quirks. `requiresThinkingAsText` is the one that decides
1389        // whether the model's own reasoning is sent back or dropped — see
1390        // `docs/debugging/llm-repetition-forensics.md` §八. If this hop ever breaks, the
1391        // setting silently does nothing (the provider falls back to
1392        // `Content::text_only`, which drops every thinking block).
1393        let config: ModelsConfig = serde_json::from_str(
1394            r#"{
1395                "providers": {
1396                    "qwen": {
1397                        "api": "openai-completions",
1398                        "baseUrl": "https://coding.example.com/v1",
1399                        "apiKey": "secret",
1400                        "models": [{
1401                            "id": "qwen3.7-plus",
1402                            "maxTokens": 131072,
1403                            "thinkingLevelMap": { "xhigh": "xhigh", "max": "max" },
1404                            "compat": { "requiresThinkingAsText": true }
1405                        }]
1406                    }
1407                }
1408            }"#,
1409        )
1410        .unwrap();
1411        let models = provider_to_models("qwen", &config.providers["qwen"]).unwrap();
1412        assert_eq!(
1413            models[0]
1414                .thinking_level_map
1415                .as_ref()
1416                .unwrap()
1417                .get(&rpi_ai::ThinkingLevel::Xhigh),
1418            Some(&Some("xhigh".into()))
1419        );
1420        match models[0].compat.as_ref().expect("compat must survive") {
1421            StreamingProtocolCompat::OpenaiCompletions(compat) => {
1422                assert_eq!(compat.requires_thinking_as_text, Some(true));
1423            }
1424            other => panic!("expected OpenaiCompletions compat, got {other:?}"),
1425        }
1426
1427        // An entry without `compat` stays on the default (thinking dropped).
1428        let plain: ModelsConfig = serde_json::from_str(
1429            r#"{
1430                "providers": {
1431                    "qwen": {
1432                        "api": "openai-completions",
1433                        "baseUrl": "https://coding.example.com/v1",
1434                        "apiKey": "secret",
1435                        "models": [{"id":"qwen3.7-plus"}]
1436                    }
1437                }
1438            }"#,
1439        )
1440        .unwrap();
1441        let plain_models = provider_to_models("qwen", &plain.providers["qwen"]).unwrap();
1442        assert!(plain_models[0].compat.is_none());
1443    }
1444
1445    #[test]
1446    fn custom_openai_provider_resolves_explicit_api_key_environment_reference() {
1447        let _guard = env_lock().lock().unwrap();
1448        let env_name = "RPI_FAKE_PROVIDER_API_KEY";
1449        std::env::set_var(env_name, "env-secret");
1450        let cfg = ProviderConfig {
1451            name: None,
1452            base_url: Some("https://gateway.example.com/v1".into()),
1453            api_key: Some("$RPI_FAKE_PROVIDER_API_KEY".into()),
1454            api: Some("openai-completions".into()),
1455            headers: None,
1456            auth_header: None,
1457            models: vec![ModelDefinition {
1458                id: "fake-model".into(),
1459                name: None,
1460                base_url: None,
1461                reasoning: None,
1462                thinking_level_map: None,
1463                context_window: None,
1464                max_tokens: None,
1465                cost: None,
1466                input: None,
1467                headers: None,
1468                compat: None,
1469            }],
1470        };
1471        let models = provider_to_models("rpi-fake-provider", &cfg).unwrap();
1472        assert_eq!(
1473            openai_provider_api_key("rpi-fake-provider", &cfg).as_deref(),
1474            Some("env-secret")
1475        );
1476        assert!(
1477            models[0].headers.is_none(),
1478            "discovery does not bind credentials"
1479        );
1480        std::env::remove_var(env_name);
1481    }
1482
1483    #[test]
1484    fn openai_protocol_ids_do_not_inherit_the_official_env_key() {
1485        let _guard = env_lock().lock().unwrap();
1486        let prev_openai = std::env::var_os("OPENAI_API_KEY");
1487        let prev_completions = std::env::var_os("OPENAI_COMPLETIONS_API_KEY");
1488        let prev_responses = std::env::var_os("OPENAI_RESPONSES_API_KEY");
1489        std::env::set_var("OPENAI_API_KEY", "official-key");
1490        std::env::remove_var("OPENAI_COMPLETIONS_API_KEY");
1491        std::env::remove_var("OPENAI_RESPONSES_API_KEY");
1492        let config = ProviderConfig {
1493            name: None,
1494            base_url: Some("https://gateway.example.com/v1".into()),
1495            api_key: None,
1496            api: Some("openai-responses".into()),
1497            headers: None,
1498            auth_header: None,
1499            models: Vec::new(),
1500        };
1501
1502        assert_eq!(
1503            openai_provider_api_key("openai", &config).as_deref(),
1504            Some("official-key")
1505        );
1506        assert!(openai_provider_api_key("openai-completions", &config).is_none());
1507        assert!(openai_provider_api_key("openai-responses", &config).is_none());
1508        assert!(openai_provider_api_key("OpenAI", &config).is_none());
1509
1510        restore_env("OPENAI_API_KEY", prev_openai);
1511        restore_env("OPENAI_COMPLETIONS_API_KEY", prev_completions);
1512        restore_env("OPENAI_RESPONSES_API_KEY", prev_responses);
1513    }
1514
1515    #[test]
1516    fn native_provider_api_key_env_mapping_uses_exact_provider_ids() {
1517        assert_eq!(
1518            native_provider_api_key_env_var("openai"),
1519            Some("OPENAI_API_KEY")
1520        );
1521        for provider in [
1522            "deepseek",
1523            "openrouter",
1524            "google",
1525            "groq",
1526            "qwen",
1527            "nvidia",
1528            "OpenAI",
1529            "openai-completions",
1530        ] {
1531            assert_eq!(
1532                native_provider_api_key_env_var(provider),
1533                None,
1534                "external providers must declare auth in their package or models.json"
1535            );
1536        }
1537    }
1538
1539    #[test]
1540    fn malformed_auth_json_is_an_error_not_silent_empty() {
1541        let _cfg = TempConfig::new();
1542        std::fs::write(auth_path().unwrap(), "{ not json").unwrap();
1543        assert!(matches!(read_auth(), Err(ConfigError::Json { .. })));
1544    }
1545
1546    #[test]
1547    fn agent_dir_nests_under_agent_by_default() {
1548        // With no env override, agent_dir() must end in `.../.rpi/agent`
1549        // (mirrors pi's `getAgentDir`). We can't assertion the home prefix
1550        // portably, but the leaf two segments are stable.
1551        let _guard = env_lock().lock().unwrap();
1552        let prev = std::env::var_os(CONFIG_DIR_ENV);
1553        std::env::remove_var(CONFIG_DIR_ENV);
1554        let dir = agent_dir().unwrap();
1555        restore_env(CONFIG_DIR_ENV, prev);
1556        assert!(dir.ends_with("agent"));
1557        assert!(dir
1558            .parent()
1559            .map(|p| p.ends_with(CONFIG_DIR_NAME))
1560            .unwrap_or(false));
1561    }
1562
1563    #[test]
1564    fn migrate_legacy_layout_moves_flat_files_into_agent() {
1565        // Drive the core migration directly against a temp root/agent so the
1566        // result is independent of whatever RPI_CODING_AGENT_DIR the parallel
1567        // TempConfig tests happen to set.
1568        let tmp = tempfile::TempDir::new().unwrap();
1569        let root = tmp.path().to_path_buf();
1570        let agent = root.join("agent");
1571        std::fs::write(root.join("auth.json"), "{}").unwrap();
1572        std::fs::write(root.join("models.json"), "{}").unwrap();
1573        std::fs::write(root.join(".setup_done"), "1").unwrap();
1574        let moved = migrate_legacy_layout_in(&root, &agent).unwrap();
1575        assert_eq!(moved, 3);
1576        assert!(agent.join("auth.json").exists());
1577        assert!(agent.join("models.json").exists());
1578        assert!(agent.join(".setup_done").exists());
1579        assert!(!root.join("auth.json").exists());
1580    }
1581
1582    #[test]
1583    fn migrate_legacy_layout_noop_when_agent_exists() {
1584        let tmp = tempfile::TempDir::new().unwrap();
1585        let root = tmp.path().to_path_buf();
1586        let agent = root.join("agent");
1587        std::fs::write(root.join("auth.json"), "{}").unwrap();
1588        std::fs::create_dir_all(&agent).unwrap();
1589        let moved = migrate_legacy_layout_in(&root, &agent).unwrap();
1590        assert_eq!(moved, 0); // agent/ already present — leave flat file alone
1591    }
1592
1593    #[test]
1594    fn migrate_legacy_layout_noop_when_no_flat_files() {
1595        let tmp = tempfile::TempDir::new().unwrap();
1596        let root = tmp.path().to_path_buf();
1597        let agent = root.join("agent");
1598        let moved = migrate_legacy_layout_in(&root, &agent).unwrap();
1599        assert_eq!(moved, 0);
1600    }
1601
1602    #[test]
1603    fn migrate_legacy_layout_public_skips_env_override() {
1604        // When RPI_CODING_AGENT_DIR is set, the public entry point is a no-op
1605        // (it must never touch an explicit override). TempConfig sets it.
1606        let _cfg = TempConfig::new();
1607        let moved = migrate_legacy_layout().unwrap();
1608        assert_eq!(moved, 0);
1609    }
1610
1611    #[test]
1612    fn read_trust_missing_file_is_empty() {
1613        let _cfg = TempConfig::new();
1614        assert!(read_trust().unwrap().is_empty());
1615    }
1616
1617    #[test]
1618    fn read_trust_parses_decisions() {
1619        let _cfg = TempConfig::new();
1620        let path = trust_path().unwrap();
1621        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1622        std::fs::write(
1623            &path,
1624            r#"{ "/home/me/proj": true, "/home/me/untrusted": false, "/home/me/null": null }"#,
1625        )
1626        .unwrap();
1627        let store = read_trust().unwrap();
1628        assert_eq!(store.len(), 3);
1629        assert_eq!(store.get("/home/me/proj").copied().flatten(), Some(true));
1630        assert_eq!(
1631            store.get("/home/me/untrusted").copied().flatten(),
1632            Some(false)
1633        );
1634        assert_eq!(store.get("/home/me/null").copied().flatten(), None);
1635    }
1636
1637    #[test]
1638    fn resolve_config_value_literal_passthrough() {
1639        assert_eq!(
1640            resolve_config_value("sk-literal-key", None),
1641            Some("sk-literal-key".into())
1642        );
1643    }
1644
1645    #[test]
1646    fn resolve_config_value_env_var() {
1647        let _guard = env_lock().lock().unwrap();
1648        let prev = std::env::var_os("RPI_TEST_CFG_KEY");
1649        let prev2 = std::env::var_os("RPI_TEST_CFG_KEY2");
1650        std::env::set_var("RPI_TEST_CFG_KEY", "secret-from-env");
1651        assert_eq!(
1652            resolve_config_value("$RPI_TEST_CFG_KEY", None),
1653            Some("secret-from-env".into())
1654        );
1655        assert_eq!(
1656            resolve_config_value("prefix-${RPI_TEST_CFG_KEY}-suffix", None),
1657            Some("prefix-secret-from-env-suffix".into())
1658        );
1659        // Two vars in one template.
1660        std::env::set_var("RPI_TEST_CFG_KEY2", "two");
1661        assert_eq!(
1662            resolve_config_value("a-$RPI_TEST_CFG_KEY-b-$RPI_TEST_CFG_KEY2-c", None),
1663            Some("a-secret-from-env-b-two-c".into())
1664        );
1665        // Env overlay wins over process env.
1666        let mut overlay = BTreeMap::new();
1667        overlay.insert("RPI_TEST_CFG_KEY".into(), "overlay-value".into());
1668        assert_eq!(
1669            resolve_config_value("$RPI_TEST_CFG_KEY", Some(&overlay)),
1670            Some("overlay-value".into())
1671        );
1672        restore_env("RPI_TEST_CFG_KEY", prev);
1673        restore_env("RPI_TEST_CFG_KEY2", prev2);
1674    }
1675
1676    #[test]
1677    fn resolve_config_value_unset_env_is_none() {
1678        let _guard = env_lock().lock().unwrap();
1679        let prev = std::env::var_os("RPI_TEST_CFG_ABSENT");
1680        std::env::remove_var("RPI_TEST_CFG_ABSENT");
1681        // Any referenced unset var ⇒ the whole value is None (pi semantics).
1682        assert_eq!(resolve_config_value("$RPI_TEST_CFG_ABSENT", None), None);
1683        assert_eq!(
1684            resolve_config_value("prefix-$RPI_TEST_CFG_ABSENT-suffix", None),
1685            None
1686        );
1687        restore_env("RPI_TEST_CFG_ABSENT", prev);
1688    }
1689
1690    #[test]
1691    fn resolve_config_value_dollar_dollar_escapes_literal() {
1692        assert_eq!(
1693            resolve_config_value("price-$$5", None),
1694            Some("price-$5".into())
1695        );
1696        assert_eq!(resolve_config_value("$!bang", None), Some("!bang".into()));
1697    }
1698
1699    #[test]
1700    fn resolve_config_value_command_runs_shell() {
1701        // `!echo resolved` → "resolved" (sh on Unix; `echo` works under cmd too).
1702        assert_eq!(
1703            resolve_config_value_uncached("!echo rpi-cfg-resolved", None),
1704            Some("rpi-cfg-resolved".into())
1705        );
1706        // Non-zero exit ⇒ None.
1707        assert_eq!(resolve_config_value_uncached("!false", None), None);
1708    }
1709
1710    #[test]
1711    fn resolve_headers_drops_unresolvable() {
1712        let _guard = env_lock().lock().unwrap();
1713        let prev = std::env::var_os("RPI_TEST_HDR_SET");
1714        std::env::set_var("RPI_TEST_HDR_SET", "set-value");
1715        let mut h = BTreeMap::new();
1716        h.insert("x-set".into(), "$RPI_TEST_HDR_SET".into());
1717        h.insert("x-unset".into(), "$RPI_TEST_HDR_UNSET".into());
1718        h.insert("x-literal".into(), "literal-value".into());
1719        let resolved = resolve_headers(&h, None);
1720        assert_eq!(resolved.len(), 2);
1721        assert_eq!(resolved.get("x-set").map(|s| s.as_str()), Some("set-value"));
1722        assert_eq!(
1723            resolved.get("x-literal").map(|s| s.as_str()),
1724            Some("literal-value")
1725        );
1726        assert!(!resolved.contains_key("x-unset"));
1727        restore_env("RPI_TEST_HDR_SET", prev);
1728    }
1729
1730    #[test]
1731    fn agent_dir_respects_env_override() {
1732        let _guard = env_lock().lock().unwrap();
1733        let prev = std::env::var_os(CONFIG_DIR_ENV);
1734        let tmp = tempfile::TempDir::new().unwrap();
1735        std::env::set_var(CONFIG_DIR_ENV, tmp.path());
1736        let dir = agent_dir().unwrap();
1737        restore_env(CONFIG_DIR_ENV, prev);
1738        assert_eq!(dir, tmp.path());
1739    }
1740
1741    #[test]
1742    fn relative_override_is_rejected() {
1743        let _guard = env_lock().lock().unwrap();
1744        let prev = std::env::var_os(CONFIG_DIR_ENV);
1745        std::env::set_var(CONFIG_DIR_ENV, "relative/path");
1746        let err = agent_dir().unwrap_err();
1747        restore_env(CONFIG_DIR_ENV, prev);
1748        assert!(matches!(err, ConfigError::RelativeOverride { .. }));
1749    }
1750
1751    /// Restore/remove an env var based on its prior `OsString` value.
1752    fn restore_env(name: &str, prev: Option<std::ffi::OsString>) {
1753        match prev {
1754            Some(v) => std::env::set_var(name, v),
1755            None => std::env::remove_var(name),
1756        }
1757    }
1758}