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