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 => {
546                if line.as_bytes().get(i + 1) == Some(&b'/') {
547                    return Some(i);
548                }
549            }
550            _ => {}
551        }
552    }
553    None
554}
555
556// ---------------------------------------------------------------------------
557// Config-value expansion (mirrors pi `resolve-config-value.ts`)
558// ---------------------------------------------------------------------------
559
560/// A process-lifetime cache for `!command` resolutions, mirroring pi's
561/// `commandResultCache`. Keyed by the raw `!cmd` string (including the `!`).
562fn command_cache() -> &'static std::sync::Mutex<std::collections::HashMap<String, Option<String>>> {
563    static CACHE: std::sync::OnceLock<
564        std::sync::Mutex<std::collections::HashMap<String, Option<String>>>,
565    > = std::sync::OnceLock::new();
566    CACHE.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()))
567}
568
569/// Resolve a config value (API key, header value) that may be a shell command,
570/// an env-var template, or a literal — mirroring pi's `resolveConfigValue`.
571///
572/// - `!command` → run the rest as a shell command (`sh -c` on Unix, `cmd /C` on
573///   Windows), return trimmed stdout (cached per process). Missing shell or
574///   non-zero exit ⇒ `None`.
575/// - `$VAR` / `${VAR}` templates: interpolate from `env_overlay` (winning) then
576///   the process env. `$$`→`$`, `$!`→`!` escapes. Any referenced var that is
577///   unset ⇒ the **whole** value resolves to `None` (pi semantics).
578/// - Otherwise the literal string (returned as-is).
579///
580/// `env_overlay` is the `credential.env` map for auth.json keys (pi passes the
581/// same). `None` (or an empty overlay) means process-env only — used for
582/// models.json apiKey/headers, which have no env overlay.
583pub fn resolve_config_value(
584    config: &str,
585    env_overlay: Option<&BTreeMap<String, String>>,
586) -> Option<String> {
587    if let Some(cmd) = config.strip_prefix('!') {
588        return resolve_command(cmd);
589    }
590    resolve_template(config, env_overlay)
591}
592
593/// Like [`resolve_config_value`] but **uncached** — mirrors pi's
594/// `resolveConfigValueUncached`, used when a fresh resolution is required
595/// (e.g. headers, which pi resolves uncached so a rotating token is re-read).
596pub fn resolve_config_value_uncached(
597    config: &str,
598    env_overlay: Option<&BTreeMap<String, String>>,
599) -> Option<String> {
600    if let Some(cmd) = config.strip_prefix('!') {
601        return resolve_command_uncached(cmd);
602    }
603    resolve_template(config, env_overlay)
604}
605
606/// Resolve every header value via [`resolve_config_value_uncached`]; drop
607/// entries that resolve to `None` (mirrors pi `resolveHeaders`). Used on
608/// models.json `headers` maps before folding onto a model.
609pub fn resolve_headers(
610    headers: &BTreeMap<String, String>,
611    env_overlay: Option<&BTreeMap<String, String>>,
612) -> BTreeMap<String, String> {
613    let mut out = BTreeMap::new();
614    for (k, v) in headers {
615        if let Some(resolved) = resolve_config_value_uncached(v, env_overlay) {
616            out.insert(k.clone(), resolved);
617        }
618    }
619    out
620}
621
622/// Env lookup: `env_overlay` (if present) wins over the process env, matching
623/// pi's `resolveEnvConfigValue` (which checks `env?.[name]` before `process.env`).
624fn env_lookup(name: &str, env_overlay: Option<&BTreeMap<String, String>>) -> Option<String> {
625    if let Some(overlay) = env_overlay {
626        if let Some(v) = overlay.get(name) {
627            return Some(v.clone());
628        }
629    }
630    std::env::var(name).ok()
631}
632
633/// A parsed template part — literal text or an env-var reference.
634enum TemplatePart {
635    Literal(String),
636    Env(String),
637}
638
639/// Parse a `$VAR`/`${VAR}` template (mirrors pi `parseConfigValueTemplate`).
640/// `$$`→`$` and `$!`→`!` are escapes; `${NAME}` requires `NAME` to match
641/// `^[A-Za-z_][A-Za-z0-9_]*$` else the raw slice is kept literal; `$NAME` takes
642/// the longest `[A-Za-z_][A-Za-z0-9_]*` prefix as the name.
643fn parse_template(config: &str) -> Vec<TemplatePart> {
644    let mut parts: Vec<TemplatePart> = Vec::new();
645    let bytes = config.as_bytes();
646    let mut i = 0usize;
647    while i < bytes.len() {
648        // Find the next `$`.
649        match config[i..].find('$') {
650            None => {
651                push_literal(&mut parts, &config[i..]);
652                break;
653            }
654            Some(offset) => {
655                let dollar = i + offset;
656                push_literal(&mut parts, &config[i..dollar]);
657                let after = dollar + 1;
658                let next = bytes.get(after).copied();
659                if next == Some(b'$') || next == Some(b'!') {
660                    push_literal(&mut parts, &config[after..after + 1]);
661                    i = after + 1;
662                    continue;
663                }
664                if next == Some(b'{') {
665                    // ${NAME}
666                    if let Some(end_rel) = config[after + 1..].find('}') {
667                        let end = after + 1 + end_rel;
668                        let name = &config[after + 1..end];
669                        if is_env_name(name) {
670                            parts.push(TemplatePart::Env(name.to_string()));
671                        } else {
672                            // Not a valid name — keep the raw `${…}` literal.
673                            push_literal(&mut parts, &config[dollar..=end]);
674                        }
675                        i = end + 1;
676                        continue;
677                    }
678                    // No closing `}` — literal `$`.
679                    push_literal(&mut parts, "$");
680                    i = after;
681                    continue;
682                }
683                // $NAME (greedy prefix). Bare `$` with no name char follows.
684                if let Some(name) = env_name_prefix(&config[after..]) {
685                    parts.push(TemplatePart::Env(name.to_string()));
686                    i = after + name.len();
687                } else {
688                    push_literal(&mut parts, "$");
689                    i = after;
690                }
691            }
692        }
693    }
694    parts
695}
696
697fn push_literal(parts: &mut Vec<TemplatePart>, value: &str) {
698    if value.is_empty() {
699        return;
700    }
701    if let Some(TemplatePart::Literal(s)) = parts.last_mut() {
702        s.push_str(value);
703    } else {
704        parts.push(TemplatePart::Literal(value.to_string()));
705    }
706}
707
708fn is_env_name(s: &str) -> bool {
709    let mut chars = s.chars();
710    match chars.next() {
711        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
712        _ => return false,
713    }
714    chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
715}
716
717/// The longest `[A-Za-z_][A-Za-z0-9_]*` prefix of `s` (mirrors the TS
718/// `ENV_VAR_NAME_PREFIX_RE` match), or `None` when `s` doesn't start with one.
719fn env_name_prefix(s: &str) -> Option<&str> {
720    let mut chars = s.char_indices();
721    match chars.next() {
722        Some((_, c)) if c.is_ascii_alphabetic() || c == '_' => {}
723        _ => return None,
724    }
725    let end = chars
726        .find(|(_, c)| !(c.is_ascii_alphanumeric() || *c == '_'))
727        .map(|(idx, _)| idx)
728        .unwrap_or(s.len());
729    Some(&s[..end])
730}
731
732/// Resolve a parsed template: any referenced env var that is unset ⇒ the whole
733/// value is `None` (pi semantics). Literal-only templates pass through as-is.
734fn resolve_template(
735    config: &str,
736    env_overlay: Option<&BTreeMap<String, String>>,
737) -> Option<String> {
738    let parts = parse_template(config);
739    let mut out = String::with_capacity(config.len());
740    for part in parts {
741        match part {
742            TemplatePart::Literal(s) => out.push_str(&s),
743            TemplatePart::Env(name) => match env_lookup(&name, env_overlay) {
744                Some(v) => out.push_str(&v),
745                None => return None,
746            },
747        }
748    }
749    Some(out)
750}
751
752/// Run `cmd` (without the leading `!`), returning trimmed stdout. Cached per
753/// process (mirrors pi `executeCommand`). 10s timeout; non-zero exit / missing
754/// shell ⇒ `None`.
755fn resolve_command(cmd: &str) -> Option<String> {
756    let key = format!("!{cmd}");
757    if let Some(v) = command_cache().lock().ok()?.get(&key) {
758        return v.clone();
759    }
760    let result = resolve_command_uncached(cmd);
761    if let Ok(mut cache) = command_cache().lock() {
762        cache.insert(key, result.clone());
763    }
764    result
765}
766
767#[cfg(unix)]
768fn spawn_shell_command(cmd: &str) -> Option<std::process::Output> {
769    std::process::Command::new("sh")
770        .arg("-c")
771        .arg(cmd)
772        .stdin(std::process::Stdio::null())
773        .stdout(std::process::Stdio::piped())
774        .stderr(std::process::Stdio::null())
775        .output()
776        .ok()
777}
778
779#[cfg(windows)]
780fn spawn_shell_command(cmd: &str) -> Option<std::process::Output> {
781    use std::os::windows::process::CommandExt;
782    std::process::Command::new("cmd")
783        .arg("/C")
784        .arg(cmd)
785        .stdin(std::process::Stdio::null())
786        .stdout(std::process::Stdio::piped())
787        .stderr(std::process::Stdio::null())
788        .creation_flags(0x0800_0000) // CREATE_NO_WINDOW
789        .output()
790        .ok()
791}
792
793/// Uncached `!command` execution (mirrors pi `executeCommandUncached`).
794fn resolve_command_uncached(cmd: &str) -> Option<String> {
795    let output = spawn_shell_command(cmd)?;
796    if !output.status.success() {
797        return None;
798    }
799    let stdout = String::from_utf8_lossy(&output.stdout);
800    let trimmed = stdout.trim();
801    if trimmed.is_empty() {
802        None
803    } else {
804        Some(trimmed.to_string())
805    }
806}
807
808/// (`anthropic-messages`, or omitted/unknown). Unknown `api` is allowed through
809/// for forward-compat but flagged ignored-in-v1 in the docs. Public so
810/// [`crate::provider`] can scan models.json providers for an `authHeader:true`
811/// gateway bearer source.
812pub fn provider_is_anthropic_compatible(cfg: &ProviderConfig) -> bool {
813    match cfg.api.as_deref() {
814        None | Some("") | Some("anthropic-messages") => true,
815        _ => false,
816    }
817}
818
819/// Whether a configured provider uses the OpenAI Chat Completions protocol.
820pub fn provider_is_openai_completions(cfg: &ProviderConfig) -> bool {
821    matches!(cfg.api.as_deref(), Some("openai-completions"))
822}
823
824pub fn provider_is_openai_responses(cfg: &ProviderConfig) -> bool {
825    matches!(cfg.api.as_deref(), Some("openai-responses"))
826}
827
828/// Resolve an OpenAI-compatible provider key from its explicit config or a
829/// known provider's canonical environment variable. Arbitrary custom provider
830/// ids must declare `apiKey: "$ENV"`: deriving an env name by normalizing the
831/// id would collapse distinct native-Pi identities such as `a-b` and `a_b`.
832pub fn openai_provider_api_key(provider_id: &str, cfg: &ProviderConfig) -> Option<String> {
833    if let Some(raw) = cfg.api_key.as_deref().filter(|key| !key.is_empty()) {
834        if let Some(value) = resolve_config_value(raw, None).filter(|value| !value.is_empty()) {
835            return Some(value);
836        }
837    }
838
839    let name = native_provider_api_key_env_var(provider_id)?;
840    std::env::var(name).ok().filter(|value| !value.is_empty())
841}
842
843/// Provider-id-to-environment-variable mapping. Provider ids are
844/// identities, so aliases and case variants must not inherit another
845/// provider's credential.
846fn native_provider_api_key_env_var(provider_id: &str) -> Option<&'static str> {
847    match provider_id {
848        "openai" => crate::credentials::builtin_api_key_env(provider_id),
849        _ => None,
850    }
851}
852
853/// Convert a `(provider_id, ProviderConfig)` pair into a list of library
854/// [`Model`]s. Provider-level `base_url`/`headers`/`auth_header` fold into each
855/// model. Returns `None` for protocols that do not have a runtime provider.
856pub fn provider_to_models(provider_id: &str, cfg: &ProviderConfig) -> Option<Vec<Model>> {
857    let api = if provider_is_anthropic_compatible(cfg) {
858        Api::AnthropicMessages
859    } else if provider_is_openai_completions(cfg) {
860        Api::OpenaiCompletions
861    } else if provider_is_openai_responses(cfg) {
862        Api::OpenaiResponses
863    } else {
864        return None;
865    };
866    let provider_base = cfg.base_url.clone().unwrap_or_else(|| match api {
867        Api::OpenaiCompletions | Api::OpenaiResponses => "https://api.openai.com".to_string(),
868        _ => default_anthropic_base_url(),
869    });
870    let mut merged: Vec<Model> = Vec::with_capacity(cfg.models.len());
871    for def in &cfg.models {
872        let base_url = def
873            .base_url
874            .clone()
875            .unwrap_or_else(|| provider_base.clone());
876        let name = def.name.clone().unwrap_or_else(|| def.id.clone());
877        let mut m = Model::new(
878            def.id.clone(),
879            name,
880            api.clone(),
881            provider_id.to_string(),
882            base_url,
883        );
884        m.reasoning = def.reasoning.unwrap_or(false);
885        m.thinking_level_map = def.thinking_level_map.clone();
886        m.context_window = def.context_window.unwrap_or(0);
887        m.max_tokens = def.max_tokens.unwrap_or(0);
888        if let Some(cost) = &def.cost {
889            m.cost = cost.clone();
890            m.cost_configured = true;
891        }
892        m.input = parse_input_modalities(def.input.as_deref());
893        // Merge: model-level headers, then provider-level headers (provider wins
894        // on conflict — it's the more specific-to-this-endpoint declaration).
895        // Values are resolved via `resolve_headers` (`$ENV`/`!command` expansion,
896        // mirroring pi's `resolveHeadersOrThrow`) so a copied pi models.json
897        // referencing env vars / commands resolves the same way. Models.json
898        // providers have no credential env overlay (only auth.json keys do), so
899        // the expansion is env-only here.
900        // Credential-derived headers are NOT synthesized in the catalog —
901        // [`crate::provider::resolve`] applies it centrally so it can skip it
902        // when a higher-priority x-api-key source (`--api-key` / auth.json /
903        // `ANTHROPIC_API_KEY`) wins. Folding it here unconditionally would put a
904        // Bearer on the model even on the x-api-key path. See
905        // `models_json_bearer_token` + the fold loop in `resolve`.
906        let mut headers: BTreeMap<String, String> = BTreeMap::new();
907        if let Some(h) = def.headers.clone() {
908            for (k, v) in resolve_headers(&h, None) {
909                headers.insert(k, v);
910            }
911        }
912        if let Some(h) = cfg.headers.clone() {
913            for (k, v) in resolve_headers(&h, None) {
914                headers.insert(k, v);
915            }
916        }
917        if matches!(api, Api::OpenaiCompletions | Api::OpenaiResponses) {
918            if let Some(value) = def.compat.clone() {
919                if matches!(api, Api::OpenaiResponses) {
920                    if let Ok(compat) = serde_json::from_value(value) {
921                        m.compat = Some(StreamingProtocolCompat::OpenaiResponses(compat));
922                    }
923                } else if let Ok(compat) = serde_json::from_value(value) {
924                    m.compat = Some(StreamingProtocolCompat::OpenaiCompletions(compat));
925                }
926            }
927        }
928        if !headers.is_empty() {
929            m.headers = Some(headers);
930        }
931        merged.push(m);
932    }
933    Some(merged)
934}
935
936/// Parse `["text","image"]`-style modality strings into [`InputModality`]s;
937/// unknown values drop to text-only. `None` ⇒ text (the [`Model::new`] default).
938fn parse_input_modalities(input: Option<&[String]>) -> Vec<InputModality> {
939    match input {
940        None => vec![InputModality::Text],
941        Some(list) if list.is_empty() => vec![InputModality::Text],
942        Some(list) => list
943            .iter()
944            .filter_map(|s| match s.to_ascii_lowercase().as_str() {
945                "text" => Some(InputModality::Text),
946                "image" => Some(InputModality::Image),
947                _ => None,
948            })
949            .collect::<Vec<_>>()
950            .pipe(|v| {
951                if v.is_empty() {
952                    vec![InputModality::Text]
953                } else {
954                    v
955                }
956            }),
957    }
958}
959
960/// The first-party Anthropic endpoint — used as the fallback `base_url` when a
961/// models.json provider omits it. Kept here (not imported from `rpi_ai`) so the
962/// config layer never depends on the provider's private `models` module.
963/// Public so [`crate::provider::resolve`] can tell a gateway model (whose
964/// `base_url` differs from this) from a built-in Anthropic model.
965pub const ANTHROPIC_DEFAULT_BASE_URL: &str = "https://api.anthropic.com";
966
967/// Same value as [`ANTHROPIC_DEFAULT_BASE_URL`], as an owned `String` for the
968/// `unwrap_or_else` ergonomic used by [`provider_to_models`] and
969/// [`crate::provider::models_json_provider_auth`].
970pub fn default_anthropic_base_url() -> String {
971    ANTHROPIC_DEFAULT_BASE_URL.to_string()
972}
973
974// ---------------------------------------------------------------------------
975// Internals: dir ensure, atomic write, chmod
976// ---------------------------------------------------------------------------
977
978#[cfg(unix)]
979use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
980
981/// Create the config dir if missing. Mode 0o700 on Unix (mkdir default on
982/// Windows, where the sticky-permission concept doesn't apply).
983fn ensure_dir(dir: &Path) -> Result<(), ConfigError> {
984    if dir.exists() {
985        return Ok(());
986    }
987    std::fs::create_dir_all(dir).map_err(|e| ConfigError::Write {
988        path: dir.to_path_buf(),
989        source: e,
990    })?;
991    #[cfg(unix)]
992    {
993        let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700));
994    }
995    Ok(())
996}
997
998/// Write `bytes` to `path` atomically: a temp sibling → `rename`. The temp
999/// file lives next to the target so the rename stays on one filesystem.
1000pub(crate) fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), ConfigError> {
1001    let dir = path.parent().ok_or_else(|| ConfigError::Write {
1002        path: path.to_path_buf(),
1003        source: std::io::Error::new(std::io::ErrorKind::InvalidInput, "path has no parent"),
1004    })?;
1005    let tmp = dir.join(format!(
1006        ".{}.{}.tmp",
1007        path.file_name().and_then(|n| n.to_str()).unwrap_or("rpi"),
1008        uuid::Uuid::new_v4().simple()
1009    ));
1010    let mut options = std::fs::OpenOptions::new();
1011    options.write(true).create_new(true);
1012    #[cfg(unix)]
1013    options.mode(0o600);
1014    let mut file = options.open(&tmp).map_err(|source| ConfigError::Write {
1015        path: tmp.clone(),
1016        source,
1017    })?;
1018    if let Err(error) = file.write_all(bytes).and_then(|()| file.sync_all()) {
1019        // A partial staging file is never useful to a later caller. Best
1020        // effort cleanup also avoids leaving a misleading stale temp behind
1021        // when the target itself was left untouched.
1022        let _ = std::fs::remove_file(&tmp);
1023        return Err(ConfigError::Write {
1024            path: tmp,
1025            source: error,
1026        });
1027    }
1028    drop(file);
1029    if let Err(error) = std::fs::rename(&tmp, path) {
1030        // `rename` is the publish point; on failure the original target is
1031        // still intact. Remove the staging file before returning the error.
1032        let _ = std::fs::remove_file(&tmp);
1033        return Err(ConfigError::Write {
1034            path: path.to_path_buf(),
1035            source: error,
1036        });
1037    }
1038    Ok(())
1039}
1040
1041/// Best-effort tighten to owner-only (0o600). No-op on Windows (the Node
1042/// upstream applies no ACL either).
1043fn set_owner_only(_path: &Path) {
1044    #[cfg(unix)]
1045    {
1046        let _ = std::fs::set_permissions(_path, std::fs::Permissions::from_mode(0o600));
1047    }
1048}
1049
1050// A tiny `.pipe`-shim so the `parse_input_modalities` chain reads top-to-bottom
1051// without pulling itertools. Kept private to this module.
1052trait Pipe: Sized {
1053    fn pipe<R>(self, f: impl FnOnce(Self) -> R) -> R {
1054        f(self)
1055    }
1056}
1057impl<T> Pipe for T {}
1058
1059// ---------------------------------------------------------------------------
1060// Tests
1061// ---------------------------------------------------------------------------
1062
1063#[cfg(test)]
1064pub(crate) mod test_support {
1065    /// A shared workspace lock for tests that touch process-global env vars
1066    /// (`RPI_CODING_AGENT_DIR`, `ANTHROPIC_*`). All env-mutating tests across
1067    /// the crate (config / provider / auth) share this ONE mutex so they can't
1068    /// race on the shared environment. Hold the returned guard for the whole
1069    /// test (store it in a RAII struct).
1070    use std::sync::{Mutex, OnceLock};
1071    pub(crate) fn env_lock() -> &'static Mutex<()> {
1072        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
1073        LOCK.get_or_init(|| Mutex::new(()))
1074    }
1075}
1076
1077#[cfg(test)]
1078mod tests {
1079    use super::*;
1080    use crate::config::test_support::env_lock;
1081
1082    /// Point `RPI_CODING_AGENT_DIR` at a fresh temp dir for the duration of the
1083    /// test (cleaned up on drop). Holds the prior value of the env var to
1084    /// restore it. Hold the env lock for its whole lifetime.
1085    struct TempConfig {
1086        _guard: std::sync::MutexGuard<'static, ()>,
1087        _tmp: tempfile::TempDir,
1088        prev: Option<std::ffi::OsString>,
1089    }
1090    impl TempConfig {
1091        fn new() -> Self {
1092            let guard = env_lock().lock().unwrap();
1093            let prev = std::env::var_os(CONFIG_DIR_ENV);
1094            let tmp = tempfile::TempDir::new().unwrap();
1095            std::env::set_var(CONFIG_DIR_ENV, tmp.path());
1096            Self {
1097                _guard: guard,
1098                _tmp: tmp,
1099                prev,
1100            }
1101        }
1102    }
1103    impl Drop for TempConfig {
1104        fn drop(&mut self) {
1105            restore_env(CONFIG_DIR_ENV, self.prev.take());
1106        }
1107    }
1108
1109    #[test]
1110    fn read_auth_missing_file_is_empty() {
1111        let _cfg = TempConfig::new();
1112        let store = read_auth().unwrap();
1113        assert!(store.is_empty());
1114    }
1115
1116    #[test]
1117    fn upsert_then_read_roundtrip() {
1118        let _cfg = TempConfig::new();
1119        upsert_credential(
1120            "anthropic",
1121            Credential::ApiKey {
1122                key: Some("sk-test-123".into()),
1123                env: None,
1124            },
1125        )
1126        .unwrap();
1127        let store = read_auth().unwrap();
1128        match store.get("anthropic") {
1129            Some(Credential::ApiKey { key, .. }) => assert_eq!(key.as_deref(), Some("sk-test-123")),
1130            other => panic!("unexpected cred: {other:?}"),
1131        }
1132        // The file should exist and be JSON.
1133        let path = auth_path().unwrap();
1134        assert!(path.exists(), "auth.json should exist after upsert");
1135        let raw = std::fs::read_to_string(&path).unwrap();
1136        assert!(raw.contains("\"anthropic\""));
1137        assert!(raw.contains("api_key"));
1138    }
1139
1140    #[test]
1141    fn oauth_token_is_scoped_and_round_trips() {
1142        let _cfg = TempConfig::new();
1143        upsert_oauth_token("acme", "access".into(), "refresh".into(), 123).unwrap();
1144        assert!(matches!(
1145            read_oauth_token("acme").unwrap(),
1146            Some(Credential::Oauth { access, refresh, expires })
1147                if access == "access" && refresh == "refresh" && expires == 123
1148        ));
1149        assert!(read_oauth_token("other").unwrap().is_none());
1150    }
1151
1152    #[test]
1153    fn delete_credential_removes_entry() {
1154        let _cfg = TempConfig::new();
1155        upsert_credential(
1156            "anthropic",
1157            Credential::ApiKey {
1158                key: Some("k".into()),
1159                env: None,
1160            },
1161        )
1162        .unwrap();
1163        assert!(delete_credential("anthropic").unwrap());
1164        // Second delete is a no-op.
1165        assert!(!delete_credential("anthropic").unwrap());
1166        assert!(read_auth().unwrap().is_empty());
1167    }
1168
1169    #[test]
1170    fn load_models_config_missing_is_empty() {
1171        let _cfg = TempConfig::new();
1172        let c = load_models_config().unwrap();
1173        assert!(c.providers.is_empty());
1174    }
1175
1176    #[test]
1177    fn fallback_reader_prefers_primary_and_only_falls_back_when_missing() {
1178        let tmp = tempfile::tempdir().unwrap();
1179        let primary = tmp.path().join("primary.json");
1180        let fallback = tmp.path().join("fallback.json");
1181        std::fs::write(&fallback, "fallback").unwrap();
1182
1183        let (_, text) = read_text_with_fallback(primary.clone(), Some(fallback.clone()))
1184            .unwrap()
1185            .expect("fallback should be read");
1186        assert_eq!(text, "fallback");
1187
1188        std::fs::write(&primary, "primary").unwrap();
1189        let (path, text) = read_text_with_fallback(primary.clone(), Some(fallback))
1190            .unwrap()
1191            .expect("primary should be read");
1192        assert_eq!(path, primary);
1193        assert_eq!(text, "primary");
1194    }
1195
1196    #[test]
1197    fn fallback_reader_does_not_mask_primary_read_errors() {
1198        let tmp = tempfile::tempdir().unwrap();
1199        let primary = tmp.path().join("primary.json");
1200        let fallback = tmp.path().join("fallback.json");
1201        std::fs::create_dir(&primary).unwrap();
1202        std::fs::write(&fallback, "fallback").unwrap();
1203
1204        let error = read_text_with_fallback(primary.clone(), Some(fallback)).unwrap_err();
1205        assert!(matches!(error, ConfigError::Read { path, .. } if path == primary));
1206    }
1207
1208    #[test]
1209    fn load_models_config_parses_with_comments() {
1210        let _cfg = TempConfig::new();
1211        let json = r#"{
1212  // a one-api style gateway
1213  "providers": {
1214    "gateway": {
1215      "baseUrl": "https://gw.example.com",
1216      "authHeader": true,
1217      "apiKey": "gw-secret",
1218      "models": [
1219        { "id": "claude-sonnet-5", "name": "Sonnet via gateway" }
1220      ]
1221    }
1222  }
1223}"#;
1224        std::fs::write(models_path().unwrap(), json).unwrap();
1225        let c = load_models_config().unwrap();
1226        let gw = c
1227            .providers
1228            .get("gateway")
1229            .expect("gateway provider present");
1230        assert_eq!(gw.base_url.as_deref(), Some("https://gw.example.com"));
1231        assert!(gw.auth_header.unwrap_or(false));
1232        assert_eq!(gw.models.len(), 1);
1233        assert_eq!(gw.models[0].id, "claude-sonnet-5");
1234    }
1235
1236    #[test]
1237    fn provider_to_models_merges_headers_without_synth_bearer() {
1238        // `provider_to_models` merges model-level then provider-level headers,
1239        // but does NOT synthesize the `authHeader:true` Bearer itself — that
1240        // happens centrally in `crate::provider::resolve` (via
1241        // `models_json_bearer_token`) so it can be skipped on the x-api-key
1242        // path. Here the model carries only what the file declared.
1243        let cfg = ProviderConfig {
1244            name: None,
1245            base_url: Some("https://gw.example.com".into()),
1246            api_key: Some("gw-secret".into()),
1247            api: None,
1248            headers: Some({
1249                let mut h = BTreeMap::new();
1250                h.insert("x-portkey-key".into(), "portkey-secret".into());
1251                h
1252            }),
1253            auth_header: Some(true),
1254            models: vec![ModelDefinition {
1255                id: "claude-sonnet-5".into(),
1256                name: None,
1257                base_url: None,
1258                reasoning: None,
1259                thinking_level_map: None,
1260                context_window: None,
1261                max_tokens: None,
1262                cost: None,
1263                input: None,
1264                headers: None,
1265                compat: None,
1266            }],
1267        };
1268        let models = provider_to_models("gateway", &cfg).expect("anthropic-compatible");
1269        assert_eq!(models.len(), 1);
1270        let m = &models[0];
1271        assert_eq!(m.id, "claude-sonnet-5");
1272        assert_eq!(m.base_url, "https://gw.example.com");
1273        assert_eq!(m.provider, "gateway");
1274        let headers = m.headers.as_ref().expect("provider headers merged");
1275        // Declared provider header folds in…
1276        assert_eq!(
1277            headers.get("x-portkey-key").map(|s| s.as_str()),
1278            Some("portkey-secret")
1279        );
1280        // …but no Bearer is synthesized here. The bearer-from-authHeader path
1281        // is exercised end-to-end by the provider.rs `resolve` tests
1282        // (`models_json_auth_header_satisfies_auth_without_env`,
1283        // `api_key_flag_beats_models_json_bearer`).
1284        assert!(
1285            headers.get("authorization").is_none(),
1286            "provider_to_models must not synthesize the Bearer; resolve does"
1287        );
1288    }
1289
1290    #[test]
1291    fn provider_to_models_supports_openai_completions() {
1292        let config: ModelsConfig = serde_json::from_str(
1293            r#"{
1294                "providers": {
1295                    "oai": {
1296                        "api": "openai-completions",
1297                        "baseUrl": "https://gateway.example.com/v1",
1298                        "apiKey": "secret",
1299                        "models": [{"id":"gpt-test","maxTokens":4096}]
1300                    }
1301                }
1302            }"#,
1303        )
1304        .unwrap();
1305        let models = provider_to_models("oai", &config.providers["oai"]).unwrap();
1306        assert_eq!(models.len(), 1);
1307        assert_eq!(models[0].api, Api::OpenaiCompletions);
1308        assert_eq!(models[0].provider, "oai");
1309        assert_eq!(models[0].max_tokens, 4096);
1310        assert_eq!(models[0].cost, ModelCost::default());
1311        assert!(!models[0].has_pricing());
1312        assert!(
1313            models[0].headers.is_none(),
1314            "credentials are bound after provider resolution"
1315        );
1316    }
1317
1318    #[test]
1319    fn models_json_pricing_reaches_providers_and_survives_serialization() {
1320        let mut config = parse_models_json(
1321            r#"{
1322                "providers": {
1323                    "pricing-fixture": {
1324                        "api": "anthropic-messages",
1325                        "models": [{
1326                            "id": "priced-model",
1327                            "cost": {
1328                                "input": 2, "output": 8, "cacheRead": 0.2, "cacheWrite": 2.5,
1329                                "tiers": [{
1330                                    "inputTokensAbove": 1000000,
1331                                    "input": 4, "output": 16, "cacheRead": 0.4, "cacheWrite": 5
1332                                }]
1333                            }
1334                        }]
1335                    }
1336                }
1337            }"#,
1338        )
1339        .unwrap();
1340        let expected = config.providers["pricing-fixture"].models[0]
1341            .cost
1342            .clone()
1343            .unwrap();
1344        for api in [
1345            "anthropic-messages",
1346            "openai-completions",
1347            "openai-responses",
1348        ] {
1349            let cfg = config.providers.get_mut("pricing-fixture").unwrap();
1350            cfg.api = Some(api.into());
1351            let models = provider_to_models("pricing-fixture", cfg).unwrap();
1352            assert_eq!(models[0].cost, expected);
1353            assert!(models[0].has_pricing());
1354            let mut usage = rpi_ai::Usage::zero();
1355            usage.input = 100_000;
1356            usage.output = 250_000;
1357            usage.cache_read = 300_000;
1358            usage.cache_write = 400_000;
1359            let cost = rpi_ai::providers::anthropic::cost::calculate_cost(&models[0].cost, &usage);
1360            assert!((cost.total - 3.26).abs() < 1e-10, "base pricing for {api}");
1361            usage.input = 1_000_001;
1362            usage.output = 1_000_000;
1363            usage.cache_read = 0;
1364            usage.cache_write = 0;
1365            let cost = rpi_ai::providers::anthropic::cost::calculate_cost(&models[0].cost, &usage);
1366            assert!(
1367                (cost.total - 20.000004).abs() < 1e-10,
1368                "tiered pricing for {api}"
1369            );
1370        }
1371        let saved = serde_json::to_string(&config).unwrap();
1372        let reloaded = parse_models_json(&saved).unwrap();
1373        assert_eq!(
1374            reloaded.providers["pricing-fixture"].models[0].cost,
1375            Some(expected)
1376        );
1377        let cfg = config.providers.get_mut("pricing-fixture").unwrap();
1378        cfg.models[0].cost = Some(ModelCost::default());
1379        let free = provider_to_models("pricing-fixture", cfg).unwrap();
1380        assert_eq!(free[0].cost, ModelCost::default());
1381        assert!(
1382            free[0].has_pricing(),
1383            "explicit zero prices are still configured"
1384        );
1385    }
1386
1387    #[test]
1388    fn models_json_compat_reaches_the_model_for_openai_completions() {
1389        // The `compat` block is what lets a custom openai-completions provider
1390        // describe its quirks. `requiresThinkingAsText` is the one that decides
1391        // whether the model's own reasoning is sent back or dropped — see
1392        // `docs/debugging/llm-repetition-forensics.md` §八. If this hop ever breaks, the
1393        // setting silently does nothing (the provider falls back to
1394        // `Content::text_only`, which drops every thinking block).
1395        let config: ModelsConfig = serde_json::from_str(
1396            r#"{
1397                "providers": {
1398                    "qwen": {
1399                        "api": "openai-completions",
1400                        "baseUrl": "https://coding.example.com/v1",
1401                        "apiKey": "secret",
1402                        "models": [{
1403                            "id": "qwen3.7-plus",
1404                            "maxTokens": 131072,
1405                            "thinkingLevelMap": { "xhigh": "xhigh", "max": "max" },
1406                            "compat": { "requiresThinkingAsText": true }
1407                        }]
1408                    }
1409                }
1410            }"#,
1411        )
1412        .unwrap();
1413        let models = provider_to_models("qwen", &config.providers["qwen"]).unwrap();
1414        assert_eq!(
1415            models[0]
1416                .thinking_level_map
1417                .as_ref()
1418                .unwrap()
1419                .get(&rpi_ai::ThinkingLevel::Xhigh),
1420            Some(&Some("xhigh".into()))
1421        );
1422        match models[0].compat.as_ref().expect("compat must survive") {
1423            StreamingProtocolCompat::OpenaiCompletions(compat) => {
1424                assert_eq!(compat.requires_thinking_as_text, Some(true));
1425            }
1426            other => panic!("expected OpenaiCompletions compat, got {other:?}"),
1427        }
1428
1429        // An entry without `compat` stays on the default (thinking dropped).
1430        let plain: ModelsConfig = serde_json::from_str(
1431            r#"{
1432                "providers": {
1433                    "qwen": {
1434                        "api": "openai-completions",
1435                        "baseUrl": "https://coding.example.com/v1",
1436                        "apiKey": "secret",
1437                        "models": [{"id":"qwen3.7-plus"}]
1438                    }
1439                }
1440            }"#,
1441        )
1442        .unwrap();
1443        let plain_models = provider_to_models("qwen", &plain.providers["qwen"]).unwrap();
1444        assert!(plain_models[0].compat.is_none());
1445    }
1446
1447    #[test]
1448    fn custom_openai_provider_resolves_explicit_api_key_environment_reference() {
1449        let _guard = env_lock().lock().unwrap();
1450        let env_name = "RPI_FAKE_PROVIDER_API_KEY";
1451        std::env::set_var(env_name, "env-secret");
1452        let cfg = ProviderConfig {
1453            name: None,
1454            base_url: Some("https://gateway.example.com/v1".into()),
1455            api_key: Some("$RPI_FAKE_PROVIDER_API_KEY".into()),
1456            api: Some("openai-completions".into()),
1457            headers: None,
1458            auth_header: None,
1459            models: vec![ModelDefinition {
1460                id: "fake-model".into(),
1461                name: None,
1462                base_url: None,
1463                reasoning: None,
1464                thinking_level_map: None,
1465                context_window: None,
1466                max_tokens: None,
1467                cost: None,
1468                input: None,
1469                headers: None,
1470                compat: None,
1471            }],
1472        };
1473        let models = provider_to_models("rpi-fake-provider", &cfg).unwrap();
1474        assert_eq!(
1475            openai_provider_api_key("rpi-fake-provider", &cfg).as_deref(),
1476            Some("env-secret")
1477        );
1478        assert!(
1479            models[0].headers.is_none(),
1480            "discovery does not bind credentials"
1481        );
1482        std::env::remove_var(env_name);
1483    }
1484
1485    #[test]
1486    fn openai_protocol_ids_do_not_inherit_the_official_env_key() {
1487        let _guard = env_lock().lock().unwrap();
1488        let prev_openai = std::env::var_os("OPENAI_API_KEY");
1489        let prev_completions = std::env::var_os("OPENAI_COMPLETIONS_API_KEY");
1490        let prev_responses = std::env::var_os("OPENAI_RESPONSES_API_KEY");
1491        std::env::set_var("OPENAI_API_KEY", "official-key");
1492        std::env::remove_var("OPENAI_COMPLETIONS_API_KEY");
1493        std::env::remove_var("OPENAI_RESPONSES_API_KEY");
1494        let config = ProviderConfig {
1495            name: None,
1496            base_url: Some("https://gateway.example.com/v1".into()),
1497            api_key: None,
1498            api: Some("openai-responses".into()),
1499            headers: None,
1500            auth_header: None,
1501            models: Vec::new(),
1502        };
1503
1504        assert_eq!(
1505            openai_provider_api_key("openai", &config).as_deref(),
1506            Some("official-key")
1507        );
1508        assert!(openai_provider_api_key("openai-completions", &config).is_none());
1509        assert!(openai_provider_api_key("openai-responses", &config).is_none());
1510        assert!(openai_provider_api_key("OpenAI", &config).is_none());
1511
1512        restore_env("OPENAI_API_KEY", prev_openai);
1513        restore_env("OPENAI_COMPLETIONS_API_KEY", prev_completions);
1514        restore_env("OPENAI_RESPONSES_API_KEY", prev_responses);
1515    }
1516
1517    #[test]
1518    fn native_provider_api_key_env_mapping_uses_exact_provider_ids() {
1519        assert_eq!(
1520            native_provider_api_key_env_var("openai"),
1521            Some("OPENAI_API_KEY")
1522        );
1523        for provider in [
1524            "deepseek",
1525            "openrouter",
1526            "google",
1527            "groq",
1528            "qwen",
1529            "nvidia",
1530            "OpenAI",
1531            "openai-completions",
1532        ] {
1533            assert_eq!(
1534                native_provider_api_key_env_var(provider),
1535                None,
1536                "external providers must declare auth in their package or models.json"
1537            );
1538        }
1539    }
1540
1541    #[test]
1542    fn malformed_auth_json_is_an_error_not_silent_empty() {
1543        let _cfg = TempConfig::new();
1544        std::fs::write(auth_path().unwrap(), "{ not json").unwrap();
1545        assert!(matches!(read_auth(), Err(ConfigError::Json { .. })));
1546    }
1547
1548    #[test]
1549    fn agent_dir_nests_under_agent_by_default() {
1550        // With no env override, agent_dir() must end in `.../.rpi/agent`
1551        // (mirrors pi's `getAgentDir`). We can't assertion the home prefix
1552        // portably, but the leaf two segments are stable.
1553        let _guard = env_lock().lock().unwrap();
1554        let prev = std::env::var_os(CONFIG_DIR_ENV);
1555        std::env::remove_var(CONFIG_DIR_ENV);
1556        let dir = agent_dir().unwrap();
1557        restore_env(CONFIG_DIR_ENV, prev);
1558        assert!(dir.ends_with("agent"));
1559        assert!(dir
1560            .parent()
1561            .map(|p| p.ends_with(CONFIG_DIR_NAME))
1562            .unwrap_or(false));
1563    }
1564
1565    #[test]
1566    fn migrate_legacy_layout_moves_flat_files_into_agent() {
1567        // Drive the core migration directly against a temp root/agent so the
1568        // result is independent of whatever RPI_CODING_AGENT_DIR the parallel
1569        // TempConfig tests happen to set.
1570        let tmp = tempfile::TempDir::new().unwrap();
1571        let root = tmp.path().to_path_buf();
1572        let agent = root.join("agent");
1573        std::fs::write(root.join("auth.json"), "{}").unwrap();
1574        std::fs::write(root.join("models.json"), "{}").unwrap();
1575        std::fs::write(root.join(".setup_done"), "1").unwrap();
1576        let moved = migrate_legacy_layout_in(&root, &agent).unwrap();
1577        assert_eq!(moved, 3);
1578        assert!(agent.join("auth.json").exists());
1579        assert!(agent.join("models.json").exists());
1580        assert!(agent.join(".setup_done").exists());
1581        assert!(!root.join("auth.json").exists());
1582    }
1583
1584    #[test]
1585    fn migrate_legacy_layout_noop_when_agent_exists() {
1586        let tmp = tempfile::TempDir::new().unwrap();
1587        let root = tmp.path().to_path_buf();
1588        let agent = root.join("agent");
1589        std::fs::write(root.join("auth.json"), "{}").unwrap();
1590        std::fs::create_dir_all(&agent).unwrap();
1591        let moved = migrate_legacy_layout_in(&root, &agent).unwrap();
1592        assert_eq!(moved, 0); // agent/ already present — leave flat file alone
1593    }
1594
1595    #[test]
1596    fn migrate_legacy_layout_noop_when_no_flat_files() {
1597        let tmp = tempfile::TempDir::new().unwrap();
1598        let root = tmp.path().to_path_buf();
1599        let agent = root.join("agent");
1600        let moved = migrate_legacy_layout_in(&root, &agent).unwrap();
1601        assert_eq!(moved, 0);
1602    }
1603
1604    #[test]
1605    fn migrate_legacy_layout_public_skips_env_override() {
1606        // When RPI_CODING_AGENT_DIR is set, the public entry point is a no-op
1607        // (it must never touch an explicit override). TempConfig sets it.
1608        let _cfg = TempConfig::new();
1609        let moved = migrate_legacy_layout().unwrap();
1610        assert_eq!(moved, 0);
1611    }
1612
1613    #[test]
1614    fn read_trust_missing_file_is_empty() {
1615        let _cfg = TempConfig::new();
1616        assert!(read_trust().unwrap().is_empty());
1617    }
1618
1619    #[test]
1620    fn read_trust_parses_decisions() {
1621        let _cfg = TempConfig::new();
1622        let path = trust_path().unwrap();
1623        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1624        std::fs::write(
1625            &path,
1626            r#"{ "/home/me/proj": true, "/home/me/untrusted": false, "/home/me/null": null }"#,
1627        )
1628        .unwrap();
1629        let store = read_trust().unwrap();
1630        assert_eq!(store.len(), 3);
1631        assert_eq!(store.get("/home/me/proj").copied().flatten(), Some(true));
1632        assert_eq!(
1633            store.get("/home/me/untrusted").copied().flatten(),
1634            Some(false)
1635        );
1636        assert_eq!(store.get("/home/me/null").copied().flatten(), None);
1637    }
1638
1639    #[test]
1640    fn resolve_config_value_literal_passthrough() {
1641        assert_eq!(
1642            resolve_config_value("sk-literal-key", None),
1643            Some("sk-literal-key".into())
1644        );
1645    }
1646
1647    #[test]
1648    fn resolve_config_value_env_var() {
1649        let _guard = env_lock().lock().unwrap();
1650        let prev = std::env::var_os("RPI_TEST_CFG_KEY");
1651        let prev2 = std::env::var_os("RPI_TEST_CFG_KEY2");
1652        std::env::set_var("RPI_TEST_CFG_KEY", "secret-from-env");
1653        assert_eq!(
1654            resolve_config_value("$RPI_TEST_CFG_KEY", None),
1655            Some("secret-from-env".into())
1656        );
1657        assert_eq!(
1658            resolve_config_value("prefix-${RPI_TEST_CFG_KEY}-suffix", None),
1659            Some("prefix-secret-from-env-suffix".into())
1660        );
1661        // Two vars in one template.
1662        std::env::set_var("RPI_TEST_CFG_KEY2", "two");
1663        assert_eq!(
1664            resolve_config_value("a-$RPI_TEST_CFG_KEY-b-$RPI_TEST_CFG_KEY2-c", None),
1665            Some("a-secret-from-env-b-two-c".into())
1666        );
1667        // Env overlay wins over process env.
1668        let mut overlay = BTreeMap::new();
1669        overlay.insert("RPI_TEST_CFG_KEY".into(), "overlay-value".into());
1670        assert_eq!(
1671            resolve_config_value("$RPI_TEST_CFG_KEY", Some(&overlay)),
1672            Some("overlay-value".into())
1673        );
1674        restore_env("RPI_TEST_CFG_KEY", prev);
1675        restore_env("RPI_TEST_CFG_KEY2", prev2);
1676    }
1677
1678    #[test]
1679    fn resolve_config_value_unset_env_is_none() {
1680        let _guard = env_lock().lock().unwrap();
1681        let prev = std::env::var_os("RPI_TEST_CFG_ABSENT");
1682        std::env::remove_var("RPI_TEST_CFG_ABSENT");
1683        // Any referenced unset var ⇒ the whole value is None (pi semantics).
1684        assert_eq!(resolve_config_value("$RPI_TEST_CFG_ABSENT", None), None);
1685        assert_eq!(
1686            resolve_config_value("prefix-$RPI_TEST_CFG_ABSENT-suffix", None),
1687            None
1688        );
1689        restore_env("RPI_TEST_CFG_ABSENT", prev);
1690    }
1691
1692    #[test]
1693    fn resolve_config_value_dollar_dollar_escapes_literal() {
1694        assert_eq!(
1695            resolve_config_value("price-$$5", None),
1696            Some("price-$5".into())
1697        );
1698        assert_eq!(resolve_config_value("$!bang", None), Some("!bang".into()));
1699    }
1700
1701    #[test]
1702    fn resolve_config_value_command_runs_shell() {
1703        // `!echo resolved` → "resolved" (sh on Unix; `echo` works under cmd too).
1704        assert_eq!(
1705            resolve_config_value_uncached("!echo rpi-cfg-resolved", None),
1706            Some("rpi-cfg-resolved".into())
1707        );
1708        // Non-zero exit ⇒ None.
1709        assert_eq!(resolve_config_value_uncached("!false", None), None);
1710    }
1711
1712    #[test]
1713    fn resolve_headers_drops_unresolvable() {
1714        let _guard = env_lock().lock().unwrap();
1715        let prev = std::env::var_os("RPI_TEST_HDR_SET");
1716        std::env::set_var("RPI_TEST_HDR_SET", "set-value");
1717        let mut h = BTreeMap::new();
1718        h.insert("x-set".into(), "$RPI_TEST_HDR_SET".into());
1719        h.insert("x-unset".into(), "$RPI_TEST_HDR_UNSET".into());
1720        h.insert("x-literal".into(), "literal-value".into());
1721        let resolved = resolve_headers(&h, None);
1722        assert_eq!(resolved.len(), 2);
1723        assert_eq!(resolved.get("x-set").map(|s| s.as_str()), Some("set-value"));
1724        assert_eq!(
1725            resolved.get("x-literal").map(|s| s.as_str()),
1726            Some("literal-value")
1727        );
1728        assert!(!resolved.contains_key("x-unset"));
1729        restore_env("RPI_TEST_HDR_SET", prev);
1730    }
1731
1732    #[test]
1733    fn agent_dir_respects_env_override() {
1734        let _guard = env_lock().lock().unwrap();
1735        let prev = std::env::var_os(CONFIG_DIR_ENV);
1736        let tmp = tempfile::TempDir::new().unwrap();
1737        std::env::set_var(CONFIG_DIR_ENV, tmp.path());
1738        let dir = agent_dir().unwrap();
1739        restore_env(CONFIG_DIR_ENV, prev);
1740        assert_eq!(dir, tmp.path());
1741    }
1742
1743    #[test]
1744    fn relative_override_is_rejected() {
1745        let _guard = env_lock().lock().unwrap();
1746        let prev = std::env::var_os(CONFIG_DIR_ENV);
1747        std::env::set_var(CONFIG_DIR_ENV, "relative/path");
1748        let err = agent_dir().unwrap_err();
1749        restore_env(CONFIG_DIR_ENV, prev);
1750        assert!(matches!(err, ConfigError::RelativeOverride { .. }));
1751    }
1752
1753    /// Restore/remove an env var based on its prior `OsString` value.
1754    fn restore_env(name: &str, prev: Option<std::ffi::OsString>) {
1755        match prev {
1756            Some(v) => std::env::set_var(name, v),
1757            None => std::env::remove_var(name),
1758        }
1759    }
1760}