agentmux_srv_core/backend/model_catalog.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Model catalog — authoritative Claude model list from the Anthropic Models
5//! API (`GET /v1/models`), fetched with the agent's OAuth Bearer token.
6//!
7//! Why this exists: the agent-pane model dropdown was a hand-curated list whose
8//! version labels ("Sonnet 4.6", …) drift every time Anthropic ships a model.
9//! The CLI has no list-models surface, and prompting a model for the list is
10//! hallucination-prone — so we read the authoritative catalog from
11//! `GET /v1/models`. Verified 2026-07-02: a Claude **Max subscription** OAuth
12//! token returns HTTP 200 (no API key, no `oauth-2025-04-20` beta header) with
13//! the current models incl. `claude-sonnet-5` | "Claude Sonnet 5".
14//!
15//! This is a **metadata read only** — never call `/v1/messages` with this token
16//! (that would cross the subscription-vs-API billing line). Access is treated as
17//! best-effort: any failure (missing token on macOS Keychain, 401/expiry,
18//! network) returns `None`, and the caller falls back to the bundled curated
19//! catalog. See `docs/specs/SPEC_MODEL_CATALOG_REFRESH_2026_07_02.md`.
20//!
21//! STATUS: fetch + parse layer (this file). Remaining wiring per the spec —
22//! not yet implemented here:
23//! - cache the result per `(provider, cli_version)` under the data dir;
24//! - expose via a `providers.models` RPC (+ add `models` to Rust
25//! `ProviderConfig`, `backend/providers.rs`);
26//! - trigger a refresh on CLI install/upgrade (`install_handlers.rs` /
27//! `cli_handlers.rs`), plus an optional lazy ">30d & token valid" refetch
28//! modeled on `backend/cron/mod.rs` / `memory_heartbeat.rs`;
29//! - frontend: overlay `providers/index.ts` `models` with the cached catalog
30//! and converge the strip / `/model` dropdowns to read it.
31
32use std::path::Path;
33
34use crate::identity::key_validator::client;
35use crate::identity::secret_store;
36
37/// Fixed, sentinel account id for the user-supplied long-lived
38/// `CLAUDE_CODE_OAUTH_TOKEN` (from `claude setup-token`), persisted via
39/// `identity::secret_store::put`/`get`. Those wrap it in `account_key()`
40/// (`"acct:{account_id}"`), so the actual keychain entry is
41/// `"acct:system:claude-code-oauth-token"` — this constant only needs to be
42/// distinct as an *account id* from the per-identity account ids used
43/// elsewhere (see `identity::resolver`, `identity::oauth_client`), which are
44/// account UUIDs and would never collide with this sentinel string. This is a
45/// single, system-wide fallback token, not tied to any AgentMux identity.
46const CLAUDE_OAUTH_TOKEN_ACCOUNT: &str = "system:claude-code-oauth-token";
47
48/// One entry in the model dropdown. `id` is the concrete `--model` value the
49/// CLI accepts (e.g. `claude-sonnet-5`); `display_name` is the label to show
50/// (e.g. "Claude Sonnet 5"), taken verbatim from the API.
51#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
52#[ts(export, export_to = "../../../frontend/types/rpc/")]
53pub struct CatalogModel {
54 pub id: String,
55 pub display_name: String,
56 /// The reasoning efforts this model takes, in the CLI's order (Codex:
57 /// `low` … `ultra`, different per model). Empty when the source doesn't
58 /// say (Claude's catalog), and the frontend keeps its own levels.
59 #[serde(default, skip_serializing_if = "Vec::is_empty")]
60 #[ts(optional, as = "Option<Vec<String>>")]
61 pub efforts: Vec<String>,
62 /// The effort the CLI uses when none is passed.
63 #[serde(default, skip_serializing_if = "Option::is_none")]
64 #[ts(optional)]
65 pub default_effort: Option<String>,
66}
67
68/// Read the Claude OAuth access token from an isolated auth dir's
69/// `.credentials.json` (`claudeAiOauth.accessToken`). Returns `None` when the
70/// file/token is absent — notably on **macOS**, where the CLI stores creds in
71/// the Keychain rather than this file (see the `COMMAND_CHECK_CLI_AUTH`
72/// handler in `cli_handlers.rs`); [`resolve_access_token`] then tries its
73/// other sources before falling back to the bundled catalog. Windows/Linux
74/// keep the token here.
75pub fn read_oauth_access_token(config_dir: &Path) -> Option<String> {
76 let creds_path = config_dir.join(".credentials.json");
77 let content = std::fs::read_to_string(&creds_path).ok()?;
78 let json: serde_json::Value = serde_json::from_str(&content).ok()?;
79 let token = json
80 .get("claudeAiOauth")
81 .and_then(|o| o.get("accessToken"))
82 .and_then(|v| v.as_str())?;
83 if token.is_empty() {
84 None
85 } else {
86 Some(token.to_string())
87 }
88}
89
90/// Resolve the Claude OAuth access token to use for the model-catalog fetch,
91/// trying multiple sources in order before giving up (→ caller falls back to
92/// the bundled curated catalog, unchanged from before this existed). Order:
93///
94/// 1. [`read_oauth_access_token`] — the `.credentials.json` file written by
95/// the Claude Code CLI. Covers Linux/Windows with zero behavior change.
96/// 2. The `CLAUDE_CODE_OAUTH_TOKEN` env var — the long-lived token a user
97/// gets by running `claude setup-token` themselves in a real terminal
98/// (Anthropic's documented recipe for headless/CI use of Claude Code)
99/// and exporting before launching AgentMux. This is how macOS — where
100/// Claude Code keeps its token in the Keychain, not a plain file — gets
101/// a token at all. When found, it is persisted into AgentMux's own
102/// OS-keychain-backed secret store (`identity::secret_store`) under
103/// [`CLAUDE_OAUTH_TOKEN_ACCOUNT`] so a later run still has it even
104/// without the env var set (e.g. the app relaunched from the Dock
105/// rather than from the terminal that had it exported).
106/// 3. AgentMux's own secret store — a token persisted by a previous run of
107/// step 2.
108///
109/// Callers should use this instead of calling [`read_oauth_access_token`]
110/// directly. Never logs the token.
111///
112/// `allow_keychain_fallback` gates the two operations in steps 2/3 that
113/// actually touch the OS keychain (via `identity::secret_store`, which
114/// wraps blocking `keyring` syscalls): *persisting* a freshly-read env-var
115/// token, and reading back a *previously-persisted* one. Either can trigger
116/// an interactive macOS "App wants to use your confidential information"
117/// password prompt whenever a stored entry exists under a code signature
118/// the OS doesn't already trust (e.g. a rebuilt local dev binary). That's
119/// fine for a flow the user explicitly triggered, but this function's only
120/// caller today (`providers.models`) is a silent, fire-and-forget background
121/// refresh fired on every app launch (`frontend/app-init.ts`) — a keychain
122/// prompt appearing unprompted at startup, for a purely cosmetic
123/// model-label refresh, is not acceptable.
124///
125/// Reading the `CLAUDE_CODE_OAUTH_TOKEN` env var itself is a plain
126/// process-env read with no keychain interaction, so it's always
127/// attempted regardless of this flag (Codex P2, PR #2654) — only the
128/// persist-on-find and read-the-stored-copy operations are skipped when
129/// `false`. Pass `false` from any automatic/background caller; pass `true`
130/// only from a path the user explicitly initiated.
131pub async fn resolve_access_token(config_dir: &Path, allow_keychain_fallback: bool) -> Option<String> {
132 if let Some(token) = read_oauth_access_token(config_dir) {
133 return Some(token);
134 }
135 tokio::task::spawn_blocking(move || {
136 resolve_fallback_access_token(
137 || std::env::var("CLAUDE_CODE_OAUTH_TOKEN").ok(),
138 |token| {
139 if !allow_keychain_fallback {
140 return;
141 }
142 if let Err(e) = secret_store::put(CLAUDE_OAUTH_TOKEN_ACCOUNT, token) {
143 tracing::warn!("model catalog: failed to persist CLAUDE_CODE_OAUTH_TOKEN: {e}");
144 }
145 },
146 || {
147 if !allow_keychain_fallback {
148 return None;
149 }
150 secret_store::get(CLAUDE_OAUTH_TOKEN_ACCOUNT)
151 .ok()
152 .map(|z| z.to_string())
153 },
154 )
155 })
156 .await
157 .unwrap_or(None)
158}
159
160/// Pure resolution-order logic backing steps 2/3 of [`resolve_access_token`],
161/// factored out so it is unit-testable without touching a real OS keychain
162/// (`identity::secret_store` wraps the `keyring` crate directly with no
163/// mockable seam, so tests inject plain closures here instead).
164fn resolve_fallback_access_token(
165 env_var: impl FnOnce() -> Option<String>,
166 persist: impl FnOnce(&str),
167 stored: impl FnOnce() -> Option<String>,
168) -> Option<String> {
169 if let Some(token) = env_var().filter(|t| !t.is_empty()) {
170 persist(&token);
171 return Some(token);
172 }
173 stored().filter(|t| !t.is_empty())
174}
175
176/// Map a `GET /v1/models` response body (`{ "data": [ { id, display_name }, … ] }`)
177/// to our catalog. `display_name` falls back to `id` when absent. Extracted from
178/// the network call so it is unit-testable without an outbound request.
179fn parse_models(body: &serde_json::Value) -> Vec<CatalogModel> {
180 body.get("data")
181 .and_then(|v| v.as_array())
182 .map(|arr| {
183 arr.iter()
184 .filter_map(|m| {
185 let id = m.get("id")?.as_str()?.to_string();
186 let display_name = m
187 .get("display_name")
188 .and_then(|v| v.as_str())
189 .unwrap_or(id.as_str())
190 .to_string();
191 Some(CatalogModel { id, display_name, ..Default::default() })
192 })
193 .collect()
194 })
195 .unwrap_or_default()
196}
197
198/// Fetch the authoritative model catalog. Returns `None` (→ caller uses the
199/// bundled fallback) on network error, non-2xx (incl. 401 token expiry), or an
200/// empty/garbled body. Never logs the token.
201pub async fn fetch_model_catalog(access_token: &str) -> Option<Vec<CatalogModel>> {
202 let resp = match client()
203 .get("https://api.anthropic.com/v1/models")
204 .header("Authorization", format!("Bearer {access_token}"))
205 .header("anthropic-version", "2023-06-01")
206 .send()
207 .await
208 {
209 Ok(r) => r,
210 Err(e) => {
211 tracing::warn!("model catalog: network error: {e}");
212 return None;
213 }
214 };
215 if !resp.status().is_success() {
216 // 401 here means the OAuth token expired — keep last-good cache and
217 // refetch on the next auth/install event (spec §3 caveats).
218 tracing::warn!("model catalog: HTTP {} from /v1/models", resp.status());
219 return None;
220 }
221 let body: serde_json::Value = match resp.json().await {
222 Ok(b) => b,
223 Err(e) => {
224 tracing::warn!("model catalog: bad JSON: {e}");
225 return None;
226 }
227 };
228 let models = parse_models(&body);
229 if models.is_empty() {
230 None
231 } else {
232 Some(models)
233 }
234}
235
236#[cfg(test)]
237mod tests {
238 use super::*;
239
240 #[tokio::test]
241 async fn resolve_access_token_never_touches_keychain_when_fallback_disallowed() {
242 // The fix for the app-launch keychain-prompt regression: when
243 // `allow_keychain_fallback` is false, no `.credentials.json` exists
244 // (the macOS case), and the env var isn't set either, this must
245 // return None without ever entering the keychain-touching persist/
246 // read-back branch — not just "return the same result," but
247 // structurally skip it, since even a *read* of a stale keychain
248 // entry can trigger an OS prompt. This test can't observe "no
249 // syscall happened" directly, but a real keychain entry under
250 // CLAUDE_OAUTH_TOKEN_ACCOUNT existing on the machine this test runs
251 // on would make the old (pre-fix) code path return Some(..) — so
252 // None here is a meaningful assertion, not a vacuous one, whenever
253 // such an entry happens to be present.
254 let _lock = crate::test_support::ISOLATED_AUTH_ENV_LOCK
255 .lock()
256 .unwrap_or_else(|e| e.into_inner());
257 let had_env = std::env::var("CLAUDE_CODE_OAUTH_TOKEN").ok();
258 std::env::remove_var("CLAUDE_CODE_OAUTH_TOKEN");
259
260 let tmp = tempfile::tempdir().unwrap();
261 let got = resolve_access_token(tmp.path(), false).await;
262
263 if let Some(v) = had_env {
264 std::env::set_var("CLAUDE_CODE_OAUTH_TOKEN", v);
265 }
266 assert_eq!(got, None);
267 }
268
269 #[tokio::test]
270 async fn resolve_access_token_still_honors_env_var_when_fallback_disallowed() {
271 // Codex P2, PR #2654: reading CLAUDE_CODE_OAUTH_TOKEN is a plain
272 // process-env read with no keychain interaction, so it must still
273 // resolve even with `allow_keychain_fallback: false` — only
274 // persisting it (or reading a previously-persisted copy) is
275 // keychain-touching and gated. Before this fix, disallowing
276 // keychain fallback also silently dropped this env var, making the
277 // only real caller (providers.models) always return an empty
278 // catalog for exactly the users this env var exists for.
279 let _lock = crate::test_support::ISOLATED_AUTH_ENV_LOCK
280 .lock()
281 .unwrap_or_else(|e| e.into_inner());
282 let had_env = std::env::var("CLAUDE_CODE_OAUTH_TOKEN").ok();
283 std::env::set_var("CLAUDE_CODE_OAUTH_TOKEN", "sk-ant-oat-test-token");
284
285 let tmp = tempfile::tempdir().unwrap();
286 let got = resolve_access_token(tmp.path(), false).await;
287
288 match had_env {
289 Some(v) => std::env::set_var("CLAUDE_CODE_OAUTH_TOKEN", v),
290 None => std::env::remove_var("CLAUDE_CODE_OAUTH_TOKEN"),
291 }
292 assert_eq!(got.as_deref(), Some("sk-ant-oat-test-token"));
293 }
294
295 #[test]
296 fn parses_models_and_falls_back_display_name_to_id() {
297 let body = serde_json::json!({
298 "data": [
299 { "id": "claude-sonnet-5", "display_name": "Claude Sonnet 5" },
300 { "id": "claude-opus-4-8" } // no display_name → falls back to id
301 ]
302 });
303 let got = parse_models(&body);
304 assert_eq!(got.len(), 2);
305 assert_eq!(got[0], CatalogModel { id: "claude-sonnet-5".into(), display_name: "Claude Sonnet 5".into(), ..Default::default() });
306 assert_eq!(got[1].display_name, "claude-opus-4-8");
307 }
308
309 #[test]
310 fn empty_when_data_missing_or_wrong_shape() {
311 assert!(parse_models(&serde_json::json!({})).is_empty());
312 assert!(parse_models(&serde_json::json!({ "data": "nope" })).is_empty());
313 }
314
315 #[test]
316 fn skips_entries_without_id() {
317 let body = serde_json::json!({ "data": [ { "display_name": "no id here" }, { "id": "claude-haiku-4-5" } ] });
318 let got = parse_models(&body);
319 assert_eq!(got.len(), 1);
320 assert_eq!(got[0].id, "claude-haiku-4-5");
321 }
322
323 #[test]
324 fn fallback_prefers_env_var_and_persists_it() {
325 let mut persisted = None;
326 let got = resolve_fallback_access_token(
327 || Some("sk-ant-oat-from-env".to_string()),
328 |token| persisted = Some(token.to_string()),
329 || Some("sk-ant-oat-from-store".to_string()),
330 );
331 assert_eq!(got.as_deref(), Some("sk-ant-oat-from-env"));
332 assert_eq!(persisted.as_deref(), Some("sk-ant-oat-from-env"));
333 }
334
335 #[test]
336 fn fallback_uses_secret_store_when_env_var_absent() {
337 let mut persist_calls = 0;
338 let got = resolve_fallback_access_token(
339 || None,
340 |_| persist_calls += 1,
341 || Some("sk-ant-oat-from-store".to_string()),
342 );
343 assert_eq!(got.as_deref(), Some("sk-ant-oat-from-store"));
344 assert_eq!(persist_calls, 0);
345 }
346
347 #[test]
348 fn fallback_treats_empty_env_var_as_absent() {
349 let got = resolve_fallback_access_token(
350 || Some(String::new()),
351 |_| panic!("must not persist an empty token"),
352 || Some("sk-ant-oat-from-store".to_string()),
353 );
354 assert_eq!(got.as_deref(), Some("sk-ant-oat-from-store"));
355 }
356
357 #[test]
358 fn fallback_none_when_no_source_has_a_token() {
359 let got = resolve_fallback_access_token(|| None, |_| panic!("must not persist"), || None);
360 assert!(got.is_none());
361 }
362}