Skip to main content

agentmux_srv/server/
providers_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! RPC: `providers.models` — authoritative model catalog for a provider,
5//! fetched from the Anthropic Models API with the account-global OAuth token.
6//!
7//! Best-effort by design: any missing token (e.g. macOS Keychain), expiry, or
8//! network failure returns an empty `models` list, and the frontend keeps its
9//! bundled static catalog. Claude's comes from the Anthropic Models API;
10//! Codex's from the list its CLI caches per account (`backend/codex_models.rs`);
11//! other providers return empty. See `backend/model_catalog.rs` and
12//! `docs/specs/SPEC_MODEL_CATALOG_REFRESH_2026_07_02.md`.
13
14use std::sync::Arc;
15
16use crate::backend::model_catalog::{fetch_model_catalog, resolve_access_token, CatalogModel};
17use crate::backend::providers::get_provider;
18use crate::backend::rpc::engine::WshRpcEngine;
19
20use super::AppState;
21
22#[derive(serde::Deserialize, ts_rs::TS)]
23#[ts(export, export_to = "../../../frontend/types/rpc/")]
24pub struct ProvidersModelsParams {
25    pub provider_id: String,
26}
27
28#[derive(serde::Serialize, serde::Deserialize, ts_rs::TS)]
29#[ts(export, export_to = "../../../frontend/types/rpc/")]
30pub struct ProvidersModelsResult {
31    /// `CatalogModel` serializes to `{ id, display_name }`, plus Codex's
32    /// `efforts` and `default_effort` for each model.
33    pub models: Vec<CatalogModel>,
34}
35
36fn empty_result() -> Result<ProvidersModelsResult, String> {
37    Ok(ProvidersModelsResult { models: vec![] })
38}
39
40pub fn register_providers_handlers(engine: &Arc<WshRpcEngine>, _state: &AppState) {
41    // providers.models → authoritative model list for a provider: Claude's
42    // from GET /v1/models with the account-global OAuth token, Codex's from
43    // its CLI's per-account cache.
44    engine.register_typed(
45        "providers.models",
46        move |params: ProvidersModelsParams, _ctx| async move {
47
48                // Providers other than Claude and Codex fall back to the
49                // frontend's static catalog.
50                let provider = match get_provider(&params.provider_id) {
51                    Some(p) => p,
52                    None => return Err(format!("unknown provider: {}", params.provider_id)),
53                };
54                // Codex: the models every Codex account here lists, as their
55                // CLI last fetched them (one list serves every Codex pane).
56                if provider.id == "codex" {
57                    let paths = match agentmux_common::DataPaths::from_env() {
58                        Some(p) => p,
59                        None => return empty_result(),
60                    };
61                    let auth_dir_name = provider.auth_dir_name;
62                    let models = tokio::task::spawn_blocking(move || {
63                        crate::backend::codex_models::models_every_account_lists(crate::backend::codex_models::codex_dirs(
64                            &paths.identities_dir(),
65                            auth_dir_name,
66                        ))
67                    })
68                    .await
69                    .unwrap_or_default();
70                    return Ok(ProvidersModelsResult { models });
71                }
72                if provider.id != "claude" {
73                    return empty_result();
74                }
75
76                // Account-GLOBAL shared creds dir (version/channel-independent).
77                // If data paths can't be resolved (CI / unusual env), stay
78                // best-effort per the module contract: empty list → FE keeps its
79                // static catalog, rather than erroring the RPC.
80                let paths = match agentmux_common::DataPaths::from_env() {
81                    Some(p) => p,
82                    None => return empty_result(),
83                };
84                let dir = paths.provider_auth_dir(provider.auth_dir_name);
85                // `allow_keychain_fallback: false` — this RPC is fired
86                // automatically, unprompted, on every app launch
87                // (`frontend/app-init.ts`'s init wave). Persisting or reading
88                // back a stored fallback token (model_catalog.rs's steps 2/3)
89                // can trigger an interactive macOS Keychain password prompt;
90                // a background model-label refresh must never surface one.
91                // The `CLAUDE_CODE_OAUTH_TOKEN` env var itself is still
92                // honored either way (a plain process-env read, no keychain
93                // involved) — only the keychain-touching persist/read-back
94                // is skipped, so macOS falls back to its static bundled
95                // catalog only when that env var isn't set for this process.
96                let token = match resolve_access_token(&dir, false).await {
97                    Some(t) => t,
98                    // No token from the `.credentials.json` file or the
99                    // CLAUDE_CODE_OAUTH_TOKEN env var — the two sources this
100                    // background call is allowed to use (see the comment
101                    // above; the keychain-backed fallback is deliberately
102                    // excluded) → empty → frontend keeps its static
103                    // fallback.
104                    None => return empty_result(),
105                };
106
107                let models = fetch_model_catalog(&token).await.unwrap_or_default();
108                Ok(ProvidersModelsResult { models })
109        },
110    );
111}