Skip to main content

rpi_runtime/
config.rs

1//! Host-supplied configuration and provider-scoped credentials. No file access.
2use rpi_ai::{Api, InputModality, Model, ModelCost, StreamingProtocolCompat, ThinkingLevelMap};
3use std::collections::BTreeMap;
4use std::path::PathBuf;
5pub const DEFAULT_PROVIDER_ID: &str = "anthropic";
6#[derive(Debug, thiserror::Error)]
7pub enum ConfigError {
8    #[error("could not resolve home directory (set {env} to override)")]
9    NoHomeDir { env: &'static str },
10    #[error("config dir override {env}={val:?} is not an absolute path")]
11    RelativeOverride { env: &'static str, val: String },
12    /// Explicit agent homes are absolute by contract; a relative value cannot
13    /// be resolved against the process working directory safely.
14    #[error("agent home {val:?} is not an absolute path")]
15    InvalidAgentHome { val: String },
16    #[error("could not read {path}: {source}")]
17    Read {
18        path: PathBuf,
19        #[source]
20        source: std::io::Error,
21    },
22    #[error("could not write {path}: {source}")]
23    Write {
24        path: PathBuf,
25        #[source]
26        source: std::io::Error,
27    },
28    #[error("invalid JSON in {path}: {source}")]
29    Json {
30        path: PathBuf,
31        #[source]
32        source: serde_json::Error,
33    },
34}
35
36/// A stored credential. Mirrors the TS `Credential` union
37/// (`packages/ai/src/auth/types.ts`). OAuth credentials are provider-scoped
38/// and must never be logged or exposed to the agent transcript.
39#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
40#[serde(rename_all = "snake_case", tag = "type")]
41pub enum Credential {
42    /// An API key, optionally sourced from an env var map. v1 stores only the
43    /// literal `key` (the `env` field is kept for upstream-shape compatibility).
44    ApiKey {
45        key: Option<String>,
46        #[serde(default, skip_serializing_if = "Option::is_none")]
47        env: Option<BTreeMap<String, String>>,
48    },
49    /// OAuth tokens (access + refresh + expiry).
50    Oauth {
51        access: String,
52        #[serde(default)]
53        refresh: String,
54        /// Unix epoch seconds. `0` means no known expiry.
55        #[serde(default)]
56        expires: i64,
57    },
58}
59
60/// The auth store: `providerId -> Credential`. Mirrors upstream
61/// `Record<providerId, Credential>`.
62pub type AuthStore = BTreeMap<String, Credential>;
63
64/// The `models.json` document. Mirrors TS `{ providers: Record<id, ProviderConfig> }`
65/// (`core/model-config.ts` `ModelsConfigSchema`).
66#[derive(serde::Serialize, serde::Deserialize, Default, Debug, Clone)]
67#[serde(rename_all = "camelCase")]
68pub struct ModelsConfig {
69    #[serde(default, skip_serializing_if = "indexmap::IndexMap::is_empty")]
70    // Provider entries are walked in declaration order, so declaration order
71    // participates in the final available-model fallback.
72    pub providers: indexmap::IndexMap<String, ProviderConfig>,
73}
74
75/// A provider entry in `models.json`. The fields mirror the TS `ProviderConfig`
76/// for protocol, endpoint, headers, credentials and model metadata.
77#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
78#[serde(rename_all = "camelCase")]
79pub struct ProviderConfig {
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub name: Option<String>,
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub base_url: Option<String>,
84    #[serde(default, skip_serializing_if = "Option::is_none")]
85    pub api_key: Option<String>,
86    #[serde(default, skip_serializing_if = "Option::is_none")]
87    pub api: Option<String>,
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub headers: Option<BTreeMap<String, String>>,
90    /// `true` ⇒ wrap `api_key` as `Authorization: Bearer <key>` (mirrors
91    /// upstream `provider-composer.ts` `authHeader`).
92    #[serde(default, skip_serializing_if = "Option::is_none")]
93    pub auth_header: Option<bool>,
94    #[serde(default, skip_serializing_if = "Vec::is_empty")]
95    pub models: Vec<ModelDefinition>,
96}
97
98/// One model under a provider. `id` is required (mirrors TS `ModelDefinition`).
99#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
100#[serde(rename_all = "camelCase")]
101pub struct ModelDefinition {
102    pub id: String,
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    pub name: Option<String>,
105    #[serde(default, skip_serializing_if = "Option::is_none")]
106    pub base_url: Option<String>,
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub reasoning: Option<bool>,
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub thinking_level_map: Option<ThinkingLevelMap>,
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub context_window: Option<u64>,
113    #[serde(default, skip_serializing_if = "Option::is_none")]
114    pub max_tokens: Option<u64>,
115    /// USD per million tokens, including optional long-context pricing tiers.
116    #[serde(default, skip_serializing_if = "Option::is_none")]
117    pub cost: Option<ModelCost>,
118    /// Free-form modality strings ("text"/"image"); unknown values fall back
119    /// to text-only.
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub input: Option<Vec<String>>,
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub headers: Option<BTreeMap<String, String>>,
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub compat: Option<serde_json::Value>,
126}
127
128pub fn model_compat_warnings(config: &ModelsConfig) -> Vec<String> {
129    let mut warnings = Vec::new();
130    for (provider, cfg) in &config.providers {
131        let defaults = match cfg.api.as_deref() {
132            Some("openai-completions") => {
133                serde_json::to_value(rpi_ai::model::OpenaiCompletionsCompat::default())
134                    .expect("compat defaults serialize")
135            }
136            Some("openai-responses") => {
137                serde_json::to_value(rpi_ai::model::OpenaiResponsesCompat::default())
138                    .expect("compat defaults serialize")
139            }
140            _ if provider_is_anthropic_compatible(cfg) => {
141                serde_json::to_value(rpi_ai::model::AnthropicMessagesCompat::default())
142                    .expect("compat defaults serialize")
143            }
144            _ => continue,
145        };
146        for model in &cfg.models {
147            let Some(value) = &model.compat else { continue };
148            let context = format!("provider {provider:?}, model {:?}, compat", model.id);
149            if let Some(fields) = value.as_object() {
150                if provider_is_openai_completions(cfg) {
151                    if let (Some(native), Some(alias)) = (
152                        fields.get("requiresReasoningContent"),
153                        fields.get("requiresReasoningContentOnAssistantMessages"),
154                    ) {
155                        if native != alias {
156                            warnings.push(format!("{context}: conflicting reasoning-content flags; requiresReasoningContent takes precedence"));
157                        }
158                    }
159                }
160                for key in fields.keys() {
161                    let alias = provider_is_openai_completions(cfg)
162                        && key == "requiresReasoningContentOnAssistantMessages";
163                    if defaults.get(key).is_none() && !alias {
164                        warnings.push(format!("{context}: unknown field {key:?}; ignored"));
165                    }
166                }
167            }
168            let parsed = if provider_is_openai_completions(cfg) {
169                serde_json::from_value::<rpi_ai::model::OpenaiCompletionsCompat>(
170                    normalize_completions_compat(value.clone()),
171                )
172                .map(|_| ())
173            } else if provider_is_anthropic_compatible(cfg) {
174                serde_json::from_value::<rpi_ai::model::AnthropicMessagesCompat>(value.clone())
175                    .map(|_| ())
176            } else {
177                serde_json::from_value::<rpi_ai::model::OpenaiResponsesCompat>(value.clone())
178                    .map(|_| ())
179            };
180            if let Err(error) = parsed {
181                // Serde's full error may echo a malformed value, including a
182                // credential accidentally pasted into a boolean field.
183                let error = error.to_string();
184                let expected = error
185                    .rsplit_once(", expected ")
186                    .map_or("a valid compat object", |(_, expected)| expected);
187                warnings.push(format!(
188                    "{context}: invalid configuration; expected {expected}; compat ignored"
189                ));
190            }
191        }
192    }
193    warnings
194}
195
196fn normalize_completions_compat(mut value: serde_json::Value) -> serde_json::Value {
197    if let Some(fields) = value.as_object_mut() {
198        if let Some(alias) = fields.remove("requiresReasoningContentOnAssistantMessages") {
199            fields.entry("requiresReasoningContent").or_insert(alias);
200        }
201    }
202    value
203}
204
205pub fn provider_is_anthropic_compatible(cfg: &ProviderConfig) -> bool {
206    matches!(
207        cfg.api.as_deref(),
208        None | Some("") | Some("anthropic-messages")
209    )
210}
211
212/// Whether a configured provider uses the OpenAI Chat Completions protocol.
213pub fn provider_is_openai_completions(cfg: &ProviderConfig) -> bool {
214    matches!(cfg.api.as_deref(), Some("openai-completions"))
215}
216
217pub fn provider_is_openai_responses(cfg: &ProviderConfig) -> bool {
218    matches!(cfg.api.as_deref(), Some("openai-responses"))
219}
220
221pub fn provider_to_models(
222    provider_id: &str,
223    cfg: &ProviderConfig,
224    values: &dyn crate::ValueSource,
225) -> Option<Vec<Model>> {
226    let api = if provider_is_anthropic_compatible(cfg) {
227        Api::AnthropicMessages
228    } else if provider_is_openai_completions(cfg) {
229        Api::OpenaiCompletions
230    } else if provider_is_openai_responses(cfg) {
231        Api::OpenaiResponses
232    } else {
233        return None;
234    };
235    let provider_base = cfg.base_url.clone().unwrap_or_else(|| match api {
236        Api::OpenaiCompletions | Api::OpenaiResponses => "https://api.openai.com".to_string(),
237        _ => default_anthropic_base_url(),
238    });
239    let mut merged: Vec<Model> = Vec::with_capacity(cfg.models.len());
240    for def in &cfg.models {
241        let base_url = def
242            .base_url
243            .clone()
244            .unwrap_or_else(|| provider_base.clone());
245        let name = def.name.clone().unwrap_or_else(|| def.id.clone());
246        let mut m = Model::new(
247            def.id.clone(),
248            name,
249            api.clone(),
250            provider_id.to_string(),
251            base_url,
252        );
253        m.reasoning = def.reasoning.unwrap_or(false);
254        m.thinking_level_map = def.thinking_level_map.clone();
255        m.context_window = def.context_window.unwrap_or(0);
256        m.max_tokens = def.max_tokens.unwrap_or(0);
257        if let Some(cost) = &def.cost {
258            m.cost = cost.clone();
259            m.cost_configured = true;
260        }
261        m.input = parse_input_modalities(def.input.as_deref());
262        // Merge: model-level headers, then provider-level headers (provider wins
263        // on conflict — it's the more specific-to-this-endpoint declaration).
264        // Values are resolved via `resolve_headers` (`$ENV`/`!command` expansion,
265        // mirroring pi's `resolveHeadersOrThrow`) so a copied pi models.json
266        // referencing env vars / commands resolves the same way. Models.json
267        // providers have no credential env overlay (only auth.json keys do), so
268        // the expansion is env-only here.
269        // Credential-derived headers are NOT synthesized in the catalog —
270        // [`crate::RuntimeConfig::resolve`] applies it centrally so it can skip it
271        // when a higher-priority x-api-key source (`--api-key` / auth.json /
272        // `ANTHROPIC_API_KEY`) wins. Folding it here unconditionally would put a
273        // Bearer on the model even on the x-api-key path. See
274        // `models_json_bearer_token` + the fold loop in `resolve`.
275        let mut headers: BTreeMap<String, String> = BTreeMap::new();
276        if let Some(h) = def.headers.clone() {
277            for (k, v) in crate::values::resolve_headers(&h, None, values) {
278                headers.insert(k, v);
279            }
280        }
281        if let Some(h) = cfg.headers.clone() {
282            for (k, v) in crate::values::resolve_headers(&h, None, values) {
283                headers.insert(k, v);
284            }
285        }
286        if let Some(value) = def.compat.clone() {
287            match api {
288                Api::OpenaiResponses => {
289                    if let Ok(compat) = serde_json::from_value(value) {
290                        m.compat = Some(StreamingProtocolCompat::OpenaiResponses(compat));
291                    }
292                }
293                Api::OpenaiCompletions => {
294                    if let Ok(compat) = serde_json::from_value(normalize_completions_compat(value))
295                    {
296                        m.compat = Some(StreamingProtocolCompat::OpenaiCompletions(compat));
297                    }
298                }
299                Api::AnthropicMessages => {
300                    if let Ok(compat) = serde_json::from_value(value) {
301                        m.compat = Some(StreamingProtocolCompat::AnthropicMessages(compat));
302                    }
303                }
304                _ => {}
305            }
306        }
307        if !headers.is_empty() {
308            m.headers = Some(headers);
309        }
310        merged.push(m);
311    }
312    Some(merged)
313}
314
315/// Parse `["text","image"]`-style modality strings into [`InputModality`]s;
316/// unknown values drop to text-only. `None` ⇒ text (the [`Model::new`] default).
317fn parse_input_modalities(input: Option<&[String]>) -> Vec<InputModality> {
318    match input {
319        None => vec![InputModality::Text],
320        Some([]) => vec![InputModality::Text],
321        Some(list) => list
322            .iter()
323            .filter_map(|s| match s.to_ascii_lowercase().as_str() {
324                "text" => Some(InputModality::Text),
325                "image" => Some(InputModality::Image),
326                _ => None,
327            })
328            .collect::<Vec<_>>()
329            .pipe(|v| {
330                if v.is_empty() {
331                    vec![InputModality::Text]
332                } else {
333                    v
334                }
335            }),
336    }
337}
338
339/// The first-party Anthropic endpoint — used as the fallback `base_url` when a
340/// models.json provider omits it. Kept here (not imported from `rpi_ai`) so the
341/// config layer never depends on the provider's private `models` module.
342/// Public so [`crate::RuntimeConfig::resolve`] can tell a gateway model (whose
343/// `base_url` differs from this) from a built-in Anthropic model.
344pub const ANTHROPIC_DEFAULT_BASE_URL: &str = "https://api.anthropic.com";
345
346/// Same value as [`ANTHROPIC_DEFAULT_BASE_URL`], as an owned `String` for the
347/// `unwrap_or_else` ergonomic used by [`provider_to_models`].
348pub fn default_anthropic_base_url() -> String {
349    ANTHROPIC_DEFAULT_BASE_URL.to_string()
350}
351
352trait Pipe: Sized {
353    fn pipe<R>(self, f: impl FnOnce(Self) -> R) -> R {
354        f(self)
355    }
356}
357impl<T> Pipe for T {}