From 4c6cf2f163f692ab51d513c468e984b9fc31aded Mon Sep 17 00:00:00 2001 From: haojr Date: Tue, 1 Dec 2026 23:08:09 +0000 Subject: [PATCH] feat: runtime setup is a provider, key, model pick - provider table: OpenAI, Anthropic and Google Gemini rows beside DeepSeek and OpenRouter, and Other... (any OpenAI-compatible base URL + key; an Anthropic-compatible one for Claude Code); per-row key auth (bearer or a header), required headers, wrong-key statuses (Gemini: 400) and a model list call, each cited from the provider's API docs - after a key passes its check the node loads that provider's model list with the key; the ready card offers it (suggested model first, eight a page) and a pick becomes the runtime's default model on that provider (state.json models, POST /api/runtimes//model); a failed list keeps the row's default - OpenCode and Pi configs carry the picked model (declared under its provider for OpenCode) and Other as a custom provider; Claude Code takes a picked model on every tier - /runtimes lists every provider, none first, with Other... last - docs/user: providers, Other, the model pick Co-Authored-By: Claude Opus 5.5 --- crates/axe-core/src/core.rs | 6 + crates/axe-core/src/harness.rs | 211 +++++-- crates/axe-core/src/provider.rs | 688 +++++++++++++++++++-- crates/axe-core/src/runtime.rs | 312 ++++++++-- crates/axe-core/src/runtime_views.rs | 46 +- crates/axe-core/src/sealed.rs | 35 +- crates/axe-node/src/dispatch.rs | 21 +- crates/axe-node/src/node_link.rs | 1 + crates/axe-server/src/server.rs | 79 ++- crates/axe-telegram/src/telegram.rs | 332 +++++++++- crates/axe/tests/layering.rs | 4 + crates/axe/tests/telegram.rs | 191 +++++- docs/user/concepts/runtimes.md | 45 +- docs/user/guides/runtimes-from-telegram.md | 46 +- 14 files changed, 1768 insertions(+), 249 deletions(-) diff --git a/crates/axe-core/src/core.rs b/crates/axe-core/src/core.rs index 8e04492..3b213e1 100644 --- a/crates/axe-core/src/core.rs +++ b/crates/axe-core/src/core.rs @@ -86,6 +86,12 @@ pub trait Axe: Send + Sync + 'static { fn runtime_remove(&self, _runtime: &str) -> Result { anyhow::bail!("runtime changes need an axe server") } + /// Makes `model` node runtime `runtime`'s default model on provider + /// `provider` (`runtime::Registry::set_model`): the owner's pick after a + /// key login. + fn runtime_model(&self, _runtime: &str, _provider: &str, _model: &str) -> Result<()> { + anyhow::bail!("runtime changes need an axe server") + } /// Checks node runtime `runtime`'s login now /// (`runtime::Registry::check_now`); the outcome comes back as a card. fn runtime_check(&self, _runtime: &str) -> Result<()> { diff --git a/crates/axe-core/src/harness.rs b/crates/axe-core/src/harness.rs index ba07013..cc8f40c 100644 --- a/crates/axe-core/src/harness.rs +++ b/crates/axe-core/src/harness.rs @@ -176,38 +176,116 @@ pub enum ConfigFile { Pi, } +/// A provider login a runtime holds, for its config file +/// ([`ConfigFile::render`]): the provider, the runtime's model on it +/// ([`crate::runtime::Runtime::model_of`]) and, for `Other…`, its base URL. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Held { + pub id: &'static str, + pub model: String, + pub base_url: Option, +} + +impl Held { + /// A login of row `id` on its default model (tests, and a row the + /// owner picked no model for). + pub fn default_of(id: &'static str) -> Held { + Held { + id, + model: crate::provider::get(id) + .map_or("", |p| p.default_model) + .into(), + base_url: None, + } + } + + fn custom(&self) -> bool { + crate::provider::get(self.id).is_some_and(|p| p.custom) + } +} + impl ConfigFile { - /// The file's path under a runtime's login directory and its content - /// for a runtime holding the logins of `providers` (provider-table - /// order); `None` for [`ConfigFile::None`]. - pub fn render(&self, providers: &[&str]) -> Option<(&'static str, String)> { + /// The files (path under a runtime's login directory, content) for a + /// runtime holding the logins `held` (provider-table order); none for + /// [`ConfigFile::None`]. No secret goes in a file: keys stay in the + /// environment. + pub fn render(&self, held: &[Held]) -> Vec<(&'static str, String)> { + let first = held.iter().find(|h| !h.model.is_empty()); + let pretty = |v: &serde_json::Value| serde_json::to_string_pretty(v).expect("json") + "\n"; match self { - ConfigFile::None => None, + ConfigFile::None => vec![], ConfigFile::OpenCode => { // https://opencode.ai/config.json (v2 `config.mdx`: "Models", - // "Updates"); no secret goes in the file. + // "Updates", "Providers"). Each held model is declared under + // its provider, so a model the provider lists but OpenCode's + // catalog does not know yet still runs (2.4.3 refuses an + // undeclared one: "Model unavailable"); `Other…` is an + // `@ai-sdk/openai-compatible` provider reading its key from + // `env` (verified on 2.4.3 against a local mock). let mut v = serde_json::json!({ "$schema": "https://opencode.ai/config.json", "update": "disable", }); - if let Some(p) = providers.first().and_then(|id| crate::provider::get(id)) { - v["model"] = format!("{}/{}", p.id, p.default_model).into(); + if let Some(h) = first { + v["model"] = format!("{}/{}", h.id, h.model).into(); + } + let mut providers = serde_json::Map::new(); + for h in held.iter().filter(|h| !h.model.is_empty()) { + let mut models = serde_json::Map::new(); + models.insert(h.model.clone(), serde_json::json!({})); + let mut p = serde_json::json!({"models": models}); + if h.custom() { + let Some(url) = &h.base_url else { continue }; + let row = crate::provider::get(h.id).expect("row"); + p["npm"] = "@ai-sdk/openai-compatible".into(); + p["name"] = row.label.into(); + p["env"] = serde_json::json!([row.env]); + p["options"] = serde_json::json!({"baseURL": url}); + } + providers.insert(h.id.to_string(), p); } - let text = serde_json::to_string_pretty(&v).expect("json") + "\n"; - Some(("config/opencode/opencode.json", text)) + if !providers.is_empty() { + v["provider"] = providers.into(); + } + vec![("config/opencode/opencode.json", pretty(&v))] } ConfigFile::Pi => { - // Pi 1.7.0 `docs/settings.md` "Model and thinking"; no secret - // goes in the file. + // Pi 1.7.0 `docs/settings.md` "Model and thinking" and + // `docs/models.md` "Configure a compatible endpoint": Pi + // sends any model id to a built-in provider, and `Other…` is + // a `models.json` provider (`openai-completions`, `apiKey` + // from `$OTHER_API_KEY`; verified against a local mock). let mut v = serde_json::json!({ "$schema": "https://pi.dev/schemas/settings.schema.json", }); - if let Some(p) = providers.first().and_then(|id| crate::provider::get(id)) { - v["defaultProvider"] = p.id.into(); - v["defaultModel"] = p.default_model.into(); + if let Some(h) = first { + v["defaultProvider"] = h.id.into(); + v["defaultModel"] = h.model.clone().into(); + } + let mut providers = serde_json::Map::new(); + for h in held.iter().filter(|h| h.custom() && !h.model.is_empty()) { + let (Some(url), Some(row)) = (&h.base_url, crate::provider::get(h.id)) else { + continue; + }; + providers.insert( + h.id.to_string(), + serde_json::json!({ + "name": row.label, + "baseUrl": url, + "api": "openai-completions", + "apiKey": format!("${}", row.env), + "models": [{"id": h.model}], + }), + ); } - let text = serde_json::to_string_pretty(&v).expect("json") + "\n"; - Some(("agent/settings.json", text)) + let models = serde_json::json!({ + "$schema": "https://pi.dev/schemas/models.schema.json", + "providers": providers, + }); + vec![ + ("agent/settings.json", pretty(&v)), + ("agent/models.json", pretty(&models)), + ] } } } @@ -522,7 +600,11 @@ impl Harness { p.tools.contains(&self.name) && match self.providers { Providers::Table => true, - Providers::Fixed(_, Some(Endpoint::Anthropic)) => p.anthropic_url.is_some(), + // A row with an Anthropic-Messages endpoint, or `Other…` on + // an Anthropic-compatible URL the owner gives. + Providers::Fixed(_, Some(Endpoint::Anthropic)) => { + p.anthropic_url.is_some() || p.custom + } Providers::Fixed(_, None) => false, } } @@ -713,46 +795,99 @@ mod tests { ); } - /// OpenCode's config: the first provider's default model, no self - /// update (axe pins the version), never a key. + /// OpenCode's config: the first provider's model, each held model + /// declared under its provider, `Other…` as an OpenAI-compatible + /// provider, no self update (axe pins the version), never a key. #[test] - fn opencode_config_names_the_first_provider_default_model() { + fn opencode_config_names_the_first_provider_model() { let h = get("opencode").unwrap(); - let (path, text) = h.config.render(&["deepseek", "openrouter"]).unwrap(); - assert_eq!(path, "config/opencode/opencode.json"); - let v: serde_json::Value = serde_json::from_str(&text).unwrap(); + let d = Held::default_of; + let files = h.config.render(&[d("deepseek"), d("openrouter")]); + let [(path, text)] = &files[..] else { + panic!("{files:?}") + }; + assert_eq!(*path, "config/opencode/opencode.json"); + let v: serde_json::Value = serde_json::from_str(text).unwrap(); assert_eq!( v, serde_json::json!({"$schema": "https://opencode.ai/config.json", - "update": "disable", "model": "deepseek/deepseek-flash"}) + "update": "disable", "model": "deepseek/deepseek-flash", + "provider": { + "deepseek": {"models": {"deepseek-flash": {}}}, + "openrouter": {"models": {"~anthropic/claude-sonnet-latest": {}}}}}) ); - let (_, text) = h.config.render(&["openrouter"]).unwrap(); - assert!( - text.contains("\"openrouter/~anthropic/claude-sonnet-latest\""), - "{text}" + // The owner's pick, and `Other…` with its base URL. + let held = [ + Held { + id: "openai", + model: "gpt-6.2-astra".into(), + base_url: None, + }, + Held { + id: "other", + model: "qwen2.5-coder:7b".into(), + base_url: Some("http://localhost:11434/v1".into()), + }, + ]; + let v: serde_json::Value = serde_json::from_str(&h.config.render(&held)[0].1).unwrap(); + assert_eq!(v["model"], "openai/gpt-6.2-astra"); + assert_eq!( + v["provider"]["openai"], + serde_json::json!({"models": {"gpt-6.2-astra": {}}}) ); - let (_, text) = h.config.render(&[]).unwrap(); + assert_eq!( + v["provider"]["other"], + serde_json::json!({"npm": "@ai-sdk/openai-compatible", "name": "Other", + "env": ["OTHER_API_KEY"], "options": {"baseURL": "http://localhost:11434/v1"}, + "models": {"qwen2.5-coder:7b": {}}}) + ); + let text = &h.config.render(&[])[0].1; assert!(!text.contains("model"), "{text}"); - assert_eq!(get("codex").unwrap().config.render(&["deepseek"]), None); + assert!(get("codex") + .unwrap() + .config + .render(&[d("deepseek")]) + .is_empty()); assert_eq!(h.package, Some(("@opencode/cli", "2.4.3"))); } - /// Pi's settings: the first provider and its default model, never a - /// key, in its agent directory (`PI_CODING_AGENT_DIR`). + /// Pi's settings: the first provider and its model, never a key, in + /// its agent directory (`PI_CODING_AGENT_DIR`); `Other…` in its + /// `models.json`. #[test] - fn pi_settings_name_the_first_provider_and_its_default_model() { + fn pi_settings_name_the_first_provider_and_its_model() { let h = get("pi").unwrap(); assert_eq!(h.login_env, &[("PI_CODING_AGENT_DIR", "agent")]); - let (path, text) = h.config.render(&["openrouter", "deepseek"]).unwrap(); - assert_eq!(path, "agent/settings.json"); - let v: serde_json::Value = serde_json::from_str(&text).unwrap(); + let d = Held::default_of; + let files = h.config.render(&[d("openrouter"), d("deepseek")]); + assert_eq!(files[0].0, "agent/settings.json"); + let v: serde_json::Value = serde_json::from_str(&files[0].1).unwrap(); assert_eq!( v, serde_json::json!({"$schema": "https://pi.dev/schemas/settings.schema.json", "defaultProvider": "openrouter", "defaultModel": "~anthropic/claude-sonnet-latest"}) ); - let (_, text) = h.config.render(&[]).unwrap(); + assert_eq!(files[1].0, "agent/models.json"); + let m: serde_json::Value = serde_json::from_str(&files[1].1).unwrap(); + assert_eq!(m["providers"], serde_json::json!({})); + let other = Held { + id: "other", + model: "mock-b".into(), + base_url: Some("https://llm.example.com/v1".into()), + }; + let files = h.config.render(&[other]); + let v: serde_json::Value = serde_json::from_str(&files[0].1).unwrap(); + assert_eq!(v["defaultProvider"], "other"); + assert_eq!(v["defaultModel"], "mock-b"); + let m: serde_json::Value = serde_json::from_str(&files[1].1).unwrap(); + assert_eq!( + m["providers"]["other"], + serde_json::json!({"name": "Other", "baseUrl": "https://llm.example.com/v1", + "api": "openai-completions", "apiKey": "$OTHER_API_KEY", + "models": [{"id": "mock-b"}]}) + ); + let text = &h.config.render(&[])[0].1; assert!(!text.contains("default"), "{text}"); assert_eq!( h.package, diff --git a/crates/axe-core/src/provider.rs b/crates/axe-core/src/provider.rs index 47f78ca..19cb03e 100644 --- a/crates/axe-core/src/provider.rs +++ b/crates/axe-core/src/provider.rs @@ -17,6 +17,33 @@ pub struct ClaudeModels { pub subagent: &'static str, } +/// How a provider takes its key on the key check and the model list. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Auth { + /// `Authorization: Bearer `. + Bearer, + /// The key in this header (`x-goog-api-key`). + Header(&'static str), +} + +/// The shape of a provider's model list ([`parse_models`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ModelList { + /// OpenAI's: `{"data": [{"id", "created"?}]}` (OpenAI, DeepSeek, + /// OpenRouter, Anthropic, and OpenAI-compatible servers). + Data, + /// Gemini's: `{"models": [{"name": "models/", + /// "supportedGenerationMethods"}]}`. + Gemini, +} + +/// The id of the custom row (`Other…`). +pub const OTHER: &str = "other"; + +/// The most models a model pick offers: the suggested one, then the +/// provider's list (newest first where it dates them). +pub const MODELS_MAX: usize = 48; + #[derive(Debug)] pub struct Provider { /// The id rules, logins and forms use (`deepseek`). @@ -29,19 +56,38 @@ pub struct Provider { /// The key's format, for the sealed form and the login: prefix (may be /// empty when the provider documents none), min and max length. pub key: (&'static str, usize, usize), - /// A request that costs nothing and needs the key: `GET` with - /// `Authorization: Bearer `; 200 means a working key, 401 or 403 - /// a wrong one. The login check and the probe of a key login. + /// A request that costs nothing and needs the key: `GET` with the key + /// as [`Provider::auth`] says; 200 means a working key, a status in + /// [`Provider::bad_key`] a wrong one. The login check and the probe of + /// a key login. Empty on a [`Provider::custom`] row: from its base URL. pub key_check: &'static str, + /// How the key goes with the key check and the model list. + pub auth: Auth, + /// Other headers the provider's API requires on every call. + pub headers: &'static [(&'static str, &'static str)], + /// The statuses that mean a wrong key (401 and 403 for most; Gemini + /// answers a wrong key with 400). + pub bad_key: &'static [u16], + /// The provider's model list (`GET`, the key as for the key check), + /// for the model pick after a login; empty on a custom row. + pub models: &'static str, + /// The shape of that list. + pub list: ModelList, + /// Any OpenAI-compatible base URL the owner gives with the key + /// (`Other…`): its key check and model list are `/models`, or + /// `/v1/models` for Claude Code's Anthropic-compatible URL. + pub custom: bool, /// The account's balance, when the provider has an endpoint for it. pub balance: Option<&'static str>, - /// The model a runtime with this provider uses when a rule names none. + /// The model a runtime with this provider uses when a rule names none + /// and the owner picked none ([`crate::runtime::Health::models`]); the + /// suggested first pick. Empty on a custom row: its first listed model. pub default_model: &'static str, /// The harnesses ([`crate::harness::Harness::name`]) that can use it. pub tools: &'static [&'static str], /// The provider's Anthropic-Messages base URL, which Claude Code is /// pointed at (`ANTHROPIC_BASE_URL`); set when `tools` lists - /// `claude-code`. + /// `claude-code`, except on a custom row (the owner's URL). pub anthropic_url: Option<&'static str>, /// What Claude Code asks for per tier on that endpoint. pub claude_models: Option, @@ -61,6 +107,12 @@ pub const PROVIDERS: &[Provider] = &[ env: "DEEPSEEK_API_KEY", key: ("", 20, 256), key_check: "https://api.deepseek.com/models", + auth: Auth::Bearer, + headers: &[], + bad_key: &[401, 403], + models: "https://api.deepseek.com/models", + list: ModelList::Data, + custom: false, balance: Some("https://api.deepseek.com/user/balance"), default_model: "deepseek-flash", tools: &["claude-code", "opencode", "pi"], @@ -73,18 +125,28 @@ pub const PROVIDERS: &[Provider] = &[ }), console: "platform.deepseek.com", }, + // Model list: https://api-docs.deepseek.com/api/list-models. // https://openrouter.ai/docs/api-reference/api-keys/get-current-key // (GET /api/v1/key, bearer; 401 on a wrong key; `/api/v1/models` is a // public catalog, so no key check), key format `sk-or-v1-` and 64 hex // (https://openrouter.ai/docs/api_reference/authentication), credits // need a management key (no balance here). Claude Code: // https://openrouter.ai/docs/guides/guides/claude-code-integration + // Model list: https://openrouter.ai/docs/api-reference/models/get-models + // (`supported_parameters` filter, `data[].created`; newest first). Provider { id: "openrouter", label: "OpenRouter", env: "OPENROUTER_API_KEY", key: ("sk-or-v1-", 73, 128), key_check: "https://openrouter.ai/api/v1/key", + auth: Auth::Bearer, + headers: &[], + bad_key: &[401, 403], + // Only models that take tools: a coding agent calls tools. + models: "https://openrouter.ai/api/v1/models?supported_parameters=tools", + list: ModelList::Data, + custom: false, balance: None, default_model: "~anthropic/claude-sonnet-latest", tools: &["claude-code", "opencode", "pi"], @@ -97,6 +159,112 @@ pub const PROVIDERS: &[Provider] = &[ }), console: "openrouter.ai/keys", }, + // https://developers.openai.com/api/reference/resources/models/methods/list + // (GET /v1/models, bearer; `data[]` of `{id, object, created, + // owned_by}`, no pagination); a wrong key is 401 `invalid_api_key` + // (live, 20261201). OpenAI documents no key format: `sk-` as the Codex + // row's API key check. Models: + // https://developers.openai.com/api/docs/models. OpenCode (models.dev + // `openai.env`) and Pi (`providers.md`) read `OPENAI_API_KEY`. + Provider { + id: "openai", + label: "OpenAI", + env: "OPENAI_API_KEY", + key: ("sk-", 20, 512), + key_check: "https://api.openai.com/v1/models", + auth: Auth::Bearer, + headers: &[], + bad_key: &[401, 403], + models: "https://api.openai.com/v1/models", + list: ModelList::Data, + custom: false, + balance: None, + default_model: "gpt-6.2-sol", + tools: &["opencode", "pi"], + anthropic_url: None, + claude_models: None, + console: "platform.openai.com/api-keys", + }, + // https://platform.claude.com/docs/en/api/models-list (GET /v1/models, + // `limit` 1 to 1000, newest first; `data[]` of `{id, display_name, + // created_at, type}`) and https://platform.claude.com/docs/en/api/overview + // (`Authorization: Bearer` takes a Developer API key; `anthropic-version` + // required); a wrong key is 401 `authentication_error` (live, + // 20261201). Key prefix `sk-ant-` as the Claude Code row's API key + // check (Pi `providers.md`: `ANTHROPIC_API_KEY=sk-ant-...`). Models: + // https://platform.claude.com/docs/en/about-claude/models/overview. + // Claude Code takes an Anthropic key as its own API key login, so this + // row is for OpenCode and Pi, which read `ANTHROPIC_API_KEY`. + Provider { + id: "anthropic", + label: "Anthropic", + env: "ANTHROPIC_API_KEY", + key: ("sk-ant-", 40, 256), + key_check: "https://api.anthropic.com/v1/models", + auth: Auth::Bearer, + headers: &[("anthropic-version", "2026-10-21")], + bad_key: &[401, 403], + models: "https://api.anthropic.com/v1/models?limit=1000", + list: ModelList::Data, + custom: false, + balance: None, + default_model: "claude-sonnet-5-5", + tools: &["opencode", "pi"], + anthropic_url: None, + claude_models: None, + console: "platform.claude.com/settings/keys", + }, + // https://aistudio.google.com/api-reference/models/list-models (GET + // /v1beta/models, `pageSize` up to 1000; `models[]` of `{name: + // "models/", supportedGenerationMethods}`, `nextPageToken`) and + // https://aistudio.google.com/docs/api-key (`x-goog-api-key` header; + // `GEMINI_API_KEY`). A wrong key is 400 `API_KEY_INVALID` (live, + // 20261201), not 401. Google documents no key format. Models: + // https://aistudio.google.com/docs/models. Pi reads `GEMINI_API_KEY` + // (`providers.md`), and so does OpenCode (models.dev `google.env`). + Provider { + id: "google", + label: "Google Gemini", + env: "GEMINI_API_KEY", + key: ("", 20, 256), + key_check: "https://generativelanguage.googleapis.com/v1beta/models?pageSize=1000", + auth: Auth::Header("x-goog-api-key"), + headers: &[], + bad_key: &[400, 401, 403], + models: "https://generativelanguage.googleapis.com/v1beta/models?pageSize=1000", + list: ModelList::Gemini, + custom: false, + balance: None, + default_model: "gemini-3.8-flash", + tools: &["opencode", "pi"], + anthropic_url: None, + claude_models: None, + console: "aistudio.google.com/apikey", + }, + // Any OpenAI-compatible server (`Other…`): the owner gives its base URL + // with the key. Its key check and model list are OpenAI's list models + // call on that URL (`/models`, bearer, `data[].id`); for Claude + // Code an Anthropic-compatible base URL (`ANTHROPIC_BASE_URL`), checked + // with Anthropic's (`/v1/models`). Key format: any. + Provider { + id: OTHER, + label: "Other", + env: "OTHER_API_KEY", + key: ("", 1, 4096), + key_check: "", + auth: Auth::Bearer, + headers: &[], + bad_key: &[401, 403], + models: "", + list: ModelList::Data, + custom: true, + balance: None, + default_model: "", + tools: &["claude-code", "opencode", "pi"], + anthropic_url: None, + claude_models: None, + console: "", + }, ]; /// Every row: [`PROVIDERS`], plus test rows in this crate's tests. @@ -116,6 +284,12 @@ const TEST_PROVIDERS: &[Provider] = &[ env: "ACME_API_KEY", key: ("ak-", 10, 64), key_check: "https://api.acme.test/v1/models", + auth: Auth::Bearer, + headers: &[], + bad_key: &[401, 403], + models: "https://api.acme.test/v1/models", + list: ModelList::Data, + custom: false, balance: None, default_model: "acme-1", tools: &["keys-test"], @@ -129,6 +303,12 @@ const TEST_PROVIDERS: &[Provider] = &[ env: "ACME2_API_KEY", key: ("", 10, 64), key_check: "https://acme2.test/key", + auth: Auth::Bearer, + headers: &[], + bad_key: &[401, 403], + models: "https://acme2.test/models", + list: ModelList::Data, + custom: false, balance: None, default_model: "big", tools: &["keys-test"], @@ -178,6 +358,124 @@ impl Provider { chars: Some(crate::sealed::Chars::Nospace), } } + + /// The button and screen label: `Other…` for the custom row. + pub fn pick_label(&self) -> String { + match self.custom { + true => format!("{}…", self.label), + false => self.label.to_string(), + } + } + + /// The key check and the model list of this row for a runtime: a + /// custom row's from the owner's `base` URL (`anthropic`: Claude Code's + /// Anthropic-compatible one), else the row's own; `None` when a custom + /// row has no base URL. + pub fn calls(&self, base: Option<&str>, anthropic: bool) -> Option<(Call, Call)> { + let call = |url: String, headers: Vec<(&'static str, &'static str)>| Call { + url, + auth: self.auth, + headers, + bad_key: self.bad_key.to_vec(), + }; + if !self.custom { + let h = self.headers.to_vec(); + return Some(( + call(self.key_check.into(), h.clone()), + call(self.models.into(), h), + )); + } + let base = base?.trim_end_matches('/'); + // Anthropic's list models call and its version header (`claude` + // row of `PROVIDERS`, https://platform.claude.com/docs/en/api/models-list). + let (url, h) = match anthropic { + true => ( + format!("{base}/v1/models"), + vec![("anthropic-version", "2026-10-21")], + ), + false => (format!("{base}/models"), vec![]), + }; + Some((call(url.clone(), h.clone()), call(url, h))) + } +} + +/// The base URL `Other…` takes: `https://`, or `http://` to this host +/// (`localhost`, `127.0.0.1`, `[::1]`: a server on the node), with a host, +/// no credentials, query or fragment. +pub fn check_base_url(url: &str) -> anyhow::Result<()> { + let url = url.trim(); + let rest = match (url.strip_prefix("https://"), url.strip_prefix("http://")) { + (Some(r), _) => r, + (None, Some(r)) => { + let host = r.split(['/', ':']).next().unwrap_or(""); + let v6 = r.starts_with("[::1]"); + if !v6 && !matches!(host, "localhost" | "127.0.0.1") { + anyhow::bail!( + "an http:// base URL is only for this node (localhost); use https://" + ); + } + r + } + _ => anyhow::bail!("the base URL starts with https://"), + }; + let host = rest.split('/').next().unwrap_or(""); + if host.is_empty() || url.len() > 512 { + anyhow::bail!("the base URL has no host"); + } + if host.contains('@') + || url.contains(['?', '#']) + || url.chars().any(|c| c.is_whitespace() || c.is_control()) + { + anyhow::bail!("the base URL takes no credentials, query, fragment or spaces"); + } + Ok(()) +} + +/// One `GET` to a provider with a key: where, and how the key goes. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Call { + pub url: String, + pub auth: Auth, + pub headers: Vec<(&'static str, &'static str)>, + /// Statuses that mean a wrong key. + pub bad_key: Vec, +} + +impl Call { + /// A bearer call to `url` (401 and 403: a wrong key). + pub fn bearer(url: &str) -> Call { + Call { + url: url.into(), + auth: Auth::Bearer, + headers: vec![], + bad_key: vec![401, 403], + } + } + + /// This call with its scheme and host on `base` ([`on_base`]). + pub fn on(mut self, base: Option<&str>) -> Call { + if let Some(b) = base { + self.url = on_base(b, &self.url); + } + self + } + + #[allow(clippy::result_large_err)] + fn get(&self, key: &str, timeout: Duration) -> Result { + let agent = ureq::AgentBuilder::new() + .timeout(timeout) + .redirects(0) + .build(); + let mut r = agent.get(&self.url).set("Accept", "application/json"); + r = match self.auth { + Auth::Bearer => r.set("Authorization", &format!("Bearer {key}")), + Auth::Header(h) => r.set(h, key), + }; + for (k, v) in &self.headers { + r = r.set(k, v); + } + r.call() + } } /// How long a key check may take: a runtime checks its keys one after @@ -189,33 +487,31 @@ pub const KEY_CHECK_TIMEOUT: Duration = Duration::from_secs(10); pub enum KeyCheck { /// 200: the key works. Ok, - /// 401 or 403: the provider refused the key. + /// A wrong-key status ([`Provider::bad_key`]): the provider refused + /// the key. Bad(String), /// Anything else (429, 5xx, no answer): says nothing about the key. Unknown(String), } -/// Checks `key` with `GET url` and `Authorization: Bearer `. The key -/// is never in the outcome's text. -pub fn check_key(url: &str, key: &str, timeout: Duration) -> KeyCheck { - let agent = ureq::AgentBuilder::new() - .timeout(timeout) - .redirects(0) - .build(); - let r = agent - .get(url) - .set("Authorization", &format!("Bearer {key}")) - .set("Accept", "application/json") - .call(); - let short = |s: String| -> String { - let s = s.replace(key, ""); - let s = s.split_whitespace().collect::>().join(" "); - s.chars().take(200).collect() +/// `s` without `key`, on one line, at most 200 characters. +fn redact(s: String, key: &str) -> String { + let s = if key.is_empty() { + s + } else { + s.replace(key, "") }; - match r { + let s = s.split_whitespace().collect::>().join(" "); + s.chars().take(200).collect() +} + +/// Checks `key` with `call`. The key is never in the outcome's text. +pub fn check_key(call: &Call, key: &str, timeout: Duration) -> KeyCheck { + let short = |s: String| redact(s, key); + match call.get(key, timeout) { Ok(resp) if resp.status() == 200 => KeyCheck::Ok, Ok(resp) => KeyCheck::Unknown(format!("HTTP {}", resp.status())), - Err(ureq::Error::Status(code @ (401 | 403), resp)) => { + Err(ureq::Error::Status(code, resp)) if call.bad_key.contains(&code) => { let body = resp.into_string().unwrap_or_default(); KeyCheck::Bad(short(format!("wrong API key (HTTP {code}) {body}"))) } @@ -227,6 +523,78 @@ pub fn check_key(url: &str, key: &str, timeout: Duration) -> KeyCheck { } } +/// How long a model list may take (OpenRouter's is a few hundred models). +pub const MODEL_LIST_TIMEOUT: Duration = Duration::from_secs(15); + +/// The models `call` lists with `key`, in [`parse_models`] order; the +/// error (never with the key) when the call or its body failed. +pub fn list_models( + call: &Call, + list: ModelList, + key: &str, + timeout: Duration, +) -> std::result::Result, String> { + let body: serde_json::Value = match call.get(key, timeout) { + Ok(resp) => resp + .into_json() + .map_err(|e| redact(format!("unreadable model list: {e}"), key))?, + Err(ureq::Error::Status(code, _)) => return Err(format!("HTTP {code}")), + Err(e) => return Err(redact(format!("no answer: {e}"), key)), + }; + let models = parse_models(list, &body); + match models.is_empty() { + true => Err("the list has no models".into()), + false => Ok(models), + } +} + +/// The model ids of model list `body` of shape `list`: OpenAI's `data[].id` +/// (newest first when every entry has `created`, else as listed), Gemini's +/// `models[].name` without `models/` for models that generate content. +/// Duplicates dropped. +pub fn parse_models(list: ModelList, body: &serde_json::Value) -> Vec { + let mut out: Vec = match list { + ModelList::Data => { + let items = body["data"].as_array().cloned().unwrap_or_default(); + let mut items: Vec<(Option, String)> = items + .iter() + .filter_map(|m| Some((m["created"].as_i64(), m["id"].as_str()?.to_string()))) + .collect(); + if items.iter().all(|(c, _)| c.is_some()) { + items.sort_by_key(|i| std::cmp::Reverse(i.0)); + } + items.into_iter().map(|(_, id)| id).collect() + } + ModelList::Gemini => body["models"] + .as_array() + .into_iter() + .flatten() + .filter(|m| { + m["supportedGenerationMethods"] + .as_array() + .is_some_and(|g| g.iter().any(|x| x == "generateContent")) + }) + .filter_map(|m| m["name"].as_str()) + .map(|n| n.strip_prefix("models/").unwrap_or(n).to_string()) + .collect(), + }; + let mut seen = std::collections::BTreeSet::new(); + out.retain(|m| !m.is_empty() && m.len() <= 200 && seen.insert(m.clone())); + out +} + +/// The models a pick offers: `suggested` first (when set), then `listed` +/// without it, at most [`MODELS_MAX`]. +pub fn choices(suggested: &str, listed: &[String]) -> Vec { + let mut out: Vec = Vec::new(); + if !suggested.is_empty() { + out.push(suggested.to_string()); + } + out.extend(listed.iter().filter(|m| *m != suggested).cloned()); + out.truncate(MODELS_MAX); + out +} + #[cfg(test)] pub(crate) mod tests { use super::*; @@ -234,9 +602,20 @@ pub(crate) mod tests { use std::net::TcpListener; /// A local stand-in for a provider: answers every request 200 when it - /// carries `Authorization: Bearer `, else 401, and reports each - /// request line and its headers. + /// carries the key `good` (as a bearer or in any header), else 401, and + /// reports each request line and its headers. pub(crate) fn mock(good: &'static str) -> (String, std::sync::mpsc::Receiver) { + mock_with(good, |_| { + (200, r#"{"object":"list","data":[]}"#.to_string()) + }) + } + + /// [`mock`] answering a request with the key by `answer(request line)`: + /// a status and a JSON body. + pub(crate) fn mock_with( + good: &'static str, + answer: impl Fn(&str) -> (u16, String) + Send + 'static, + ) -> (String, std::sync::mpsc::Receiver) { let l = TcpListener::bind("127.0.0.1:0").unwrap(); let base = format!("http://{}", l.local_addr().unwrap()); let (tx, rx) = std::sync::mpsc::channel(); @@ -252,16 +631,18 @@ pub(crate) mod tests { } head.push_str(&line); } - let ok = head - .lines() - .any(|l| l.eq_ignore_ascii_case(&format!("authorization: Bearer {good}"))); + let ok = head.lines().skip(1).any(|l| { + let v = l.split_once(':').map_or("", |(_, v)| v.trim()); + v == good || v == format!("Bearer {good}") + }); let (status, body) = match ok { - true => ("200 OK", r#"{"object":"list","data":[]}"#), - false => ("401 Unauthorized", r#"{"error":"invalid key"}"#), + true => answer(head.lines().next().unwrap_or("")), + false => (401, r#"{"error":"invalid key"}"#.to_string()), }; + let reason = if status == 200 { "OK" } else { "Error" }; let _ = write!( s, - "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", + "HTTP/1.1 {status} {reason}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len() ); let _ = tx.send(head); @@ -277,41 +658,53 @@ pub(crate) mod tests { let n = p.id; assert!(ids.insert(n), "{n}: ids are unique"); crate::db::validate_name("provider", n).unwrap(); - assert!(!p.label.is_empty() && !p.default_model.is_empty(), "{n}"); - assert!(!p.console.is_empty(), "{n}: console"); + assert!(!p.label.is_empty(), "{n}"); + assert_eq!(p.custom, p.default_model.is_empty(), "{n}: default model"); + assert_eq!(p.custom, p.console.is_empty(), "{n}: console"); + assert_eq!(p.custom, p.key_check.is_empty(), "{n}: key check"); + assert_eq!(p.custom, p.models.is_empty(), "{n}: model list"); crate::sealed::check_env_name(p.env).unwrap(); assert!(p.env.ends_with("_API_KEY"), "{n}: env"); let (_, min, max) = p.key; assert!(0 < min && min < max, "{n}: key length"); - for u in [Some(p.key_check), p.balance, p.anthropic_url] - .into_iter() - .flatten() - { + for u in [p.balance, p.anthropic_url].into_iter().flatten().chain( + [p.key_check, p.models] + .into_iter() + .filter(|u| !u.is_empty()), + ) { assert!(u.starts_with("https://"), "{n}: {u}"); } + assert!(!p.bad_key.is_empty(), "{n}: bad key statuses"); assert!(!p.tools.is_empty(), "{n}: tools"); for t in p.tools { let h = crate::harness::get(t).unwrap_or_else(|| panic!("{n}: tool {t}")); assert!(h.takes_provider(p), "{n}: {t} takes it"); } - let claude = p.tools.contains(&"claude-code"); + let claude = p.tools.contains(&"claude-code") && !p.custom; assert_eq!(claude, p.anthropic_url.is_some(), "{n}: anthropic_url"); assert_eq!(claude, p.claude_models.is_some(), "{n}: claude_models"); // No two rows share a key file. assert_eq!(PROVIDERS.iter().filter(|q| q.env == p.env).count(), 1); } - assert!(PROVIDERS.len() >= 2, "v1 ships two rows"); + assert_eq!(PROVIDERS.iter().filter(|p| p.custom).count(), 1); + assert_eq!(get(OTHER).map(|p| p.custom), Some(true)); } - /// Each row's key check, against a local mock on the row's own path: - /// 200 is a working key, 401 a wrong one, and the key goes as a bearer. + /// Each row's key check and model list, against a local mock on the + /// row's own path: 200 is a working key, the row's wrong-key status a + /// wrong one, and the key goes as the row says, with its headers. #[test] fn each_provider_key_check_on_a_mock() { - for p in PROVIDERS { - let (base, seen) = mock("good-key-123"); - let url = on_base(&base, p.key_check); + for p in PROVIDERS.iter().filter(|p| !p.custom) { + let wrong = *p.bad_key.first().unwrap(); + let (base, seen) = mock_with("good-key-123", move |line| match line.contains("bad") { + true => (wrong, "{}".into()), + false => (200, r#"{"data":[],"models":[]}"#.into()), + }); + let (check, models) = p.calls(None, false).unwrap(); + let check = check.on(Some(&base)); assert_eq!( - check_key(&url, "good-key-123", KEY_CHECK_TIMEOUT), + check_key(&check, "good-key-123", KEY_CHECK_TIMEOUT), KeyCheck::Ok, "{}", p.id @@ -323,32 +716,223 @@ pub(crate) mod tests { "{}: {head}", p.id ); - match check_key(&url, "bad-key-456", KEY_CHECK_TIMEOUT) { + let auth = match p.auth { + Auth::Bearer => "authorization: Bearer good-key-123".to_string(), + Auth::Header(h) => format!("{h}: good-key-123"), + }; + let lower = head.to_lowercase(); + assert!(lower.contains(&auth.to_lowercase()), "{}: {head}", p.id); + for (k, v) in p.headers { + assert!( + lower.contains(&format!("{k}: {v}").to_lowercase()), + "{}: {k}", + p.id + ); + } + match check_key(&check, "bad-key-456", KEY_CHECK_TIMEOUT) { KeyCheck::Bad(m) => { assert!(m.contains("wrong API key (HTTP 401)"), "{m}"); assert!(!m.contains("bad-key-456"), "{m}"); } other => panic!("{}: {other:?}", p.id), } + let _ = seen.recv(); + // The model list goes to the row's own path, with the key. + let models = models.on(Some(&base)); + let _ = list_models(&models, p.list, "good-key-123", KEY_CHECK_TIMEOUT); + let head = seen.recv().unwrap(); + let path = p.models.splitn(4, '/').nth(3).unwrap(); + assert!( + head.starts_with(&format!("GET /{path} HTTP/1.1")), + "{}: {head}", + p.id + ); + assert!( + head.to_lowercase().contains(&auth.to_lowercase()), + "{}", + p.id + ); } // Nobody answering says nothing about the key. let l = TcpListener::bind("127.0.0.1:0").unwrap(); let url = format!("http://{}/models", l.local_addr().unwrap()); drop(l); assert!(matches!( - check_key(&url, "k", Duration::from_secs(2)), + check_key(&Call::bearer(&url), "k", Duration::from_secs(2)), KeyCheck::Unknown(_) )); } + /// Gemini answers a wrong key with 400 (`API_KEY_INVALID`, live + /// 20261201): a wrong key for that row, unknown for the others. + #[test] + fn a_400_is_a_wrong_key_only_where_the_row_says() { + // The body Gemini sent for a wrong key (live, 20261201). + let body = r#"{"error":{"code":400,"message":"API key not valid. Please pass a valid API key.","status":"INVALID_ARGUMENT","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"API_KEY_INVALID","domain":"googleapis.com"}]}}"#; + let (base, _seen) = mock_with("k-123", move |_| (400, body.into())); + let google = get("google").unwrap(); + let (check, _) = google.calls(None, false).unwrap(); + match check_key(&check.on(Some(&base)), "k-123", KEY_CHECK_TIMEOUT) { + KeyCheck::Bad(m) => assert!(m.contains("wrong API key (HTTP 400)"), "{m}"), + other => panic!("{other:?}"), + } + let (check, _) = get("openai").unwrap().calls(None, false).unwrap(); + assert!(matches!( + check_key(&check.on(Some(&base)), "k-123", KEY_CHECK_TIMEOUT), + KeyCheck::Unknown(_) + )); + } + + /// Each row's model list, parsed from its provider's documented + /// example response. + #[test] + fn model_lists_parse_each_providers_documented_shape() { + let parse = |id: &str, body: &str| { + let p = get(id).unwrap(); + parse_models(p.list, &serde_json::from_str(body).unwrap()) + }; + // https://api-docs.deepseek.com/api/list-models (example response, + // no `created`: kept as listed). + let deepseek = r#"{"object":"list","data":[ + {"id":"deepseek-flash","object":"model","owned_by":"deepseek","name":"DeepSeek-V4.1-Flash","context_window":1048576}, + {"id":"deepseek-v4-pro","object":"model","owned_by":"deepseek","name":"DeepSeek-V4-Pro"}]}"#; + assert_eq!( + parse("deepseek", deepseek), + ["deepseek-flash", "deepseek-v4-pro"] + ); + // https://developers.openai.com/api/reference/resources/models/methods/list + // (example response): newest `created` first. + let openai = r#"{"object":"list","data":[ + {"id":"model-id-0","object":"model","created":1686935002,"owned_by":"organization-owner","shutdown_date":null}, + {"id":"model-id-1","object":"model","created":1686935004,"owned_by":"organization-owner","shutdown_date":null}, + {"id":"model-id-2","object":"model","created":1686935003,"owned_by":"openai","shutdown_date":"2026-10-23"}]}"#; + assert_eq!( + parse("openai", openai), + ["model-id-1", "model-id-2", "model-id-0"] + ); + // https://platform.claude.com/docs/en/api/models-list (example + // response; `created_at` is a date, the list is newest first). + let anthropic = r#"{"data":[ + {"id":"claude-opus-5-5","created_at":"2026-09-21T00:00:00Z","display_name":"Claude Opus 5.5","lifecycle":"active","line":"opus","type":"model"}, + {"id":"claude-sonnet-5-5","created_at":"2026-09-01T00:00:00Z","display_name":"Claude Sonnet 5.5","type":"model"}], + "first_id":"claude-opus-5-5","has_more":false,"last_id":"claude-sonnet-5-5"}"#; + assert_eq!( + parse("anthropic", anthropic), + ["claude-opus-5-5", "claude-sonnet-5-5"] + ); + // https://aistudio.google.com/api-reference/models/list-models + // (Model: `name` "models/{model}", `supportedGenerationMethods`): + // only models that generate content, without `models/`. + let google = r#"{"models":[ + {"name":"models/gemini-1.5-flash-001","baseModelId":"gemini-1.5-flash","version":"001","displayName":"Gemini 1.5 Flash","supportedGenerationMethods":["generateContent","countTokens"]}, + {"name":"models/text-embedding-004","baseModelId":"text-embedding","version":"004","supportedGenerationMethods":["embedContent"]}], + "nextPageToken":"x"}"#; + assert_eq!(parse("google", google), ["gemini-1.5-flash-001"]); + // https://openrouter.ai/docs/api-reference/models/get-models + // (`data[]` with `id`, `created`, `supported_parameters`). + let openrouter = r#"{"data":[ + {"id":"openai/gpt-4","canonical_slug":"openai/gpt-4","name":"GPT-4","created":1692901234,"supported_parameters":["tools","temperature"]}, + {"id":"deepseek/deepseek-v4-flash","name":"DeepSeek V4 Flash","created":1792901234,"supported_parameters":["tools"]}]}"#; + assert_eq!( + parse("openrouter", openrouter), + ["deepseek/deepseek-v4-flash", "openai/gpt-4"] + ); + // An OpenAI-compatible server (`Other…`) lists the OpenAI way. + let other = r#"{"object":"list","data":[{"id":"qwen2.5-coder:7b","object":"model"}]}"#; + assert_eq!(parse(OTHER, other), ["qwen2.5-coder:7b"]); + // Nothing to list. + assert!(parse("openai", r#"{"error":{}}"#).is_empty()); + } + + #[test] + fn a_pick_offers_the_suggested_model_first() { + let listed: Vec = ["b", "a", "c"].iter().map(|s| s.to_string()).collect(); + assert_eq!(choices("a", &listed), ["a", "b", "c"]); + assert_eq!(choices("z", &listed), ["z", "b", "a", "c"]); + assert_eq!(choices("", &listed), ["b", "a", "c"]); + let many: Vec = (0..100).map(|i| format!("m{i}")).collect(); + assert_eq!(choices("", &many).len(), MODELS_MAX); + } + + /// A model list over the network: the listed models on 200, the + /// status when the provider refused, never the key. + #[test] + fn list_models_on_a_mock() { + let (base, _seen) = mock_with("good-key-123", |_| { + ( + 200, + r#"{"data":[{"id":"m1","created":1},{"id":"m2","created":2}]}"#.into(), + ) + }); + let call = Call::bearer(&format!("{base}/v1/models")); + assert_eq!( + list_models(&call, ModelList::Data, "good-key-123", KEY_CHECK_TIMEOUT).unwrap(), + ["m2", "m1"] + ); + let e = list_models(&call, ModelList::Data, "bad-key-456", KEY_CHECK_TIMEOUT).unwrap_err(); + assert_eq!(e, "HTTP 401"); + let (base, _seen) = mock_with("good-key-123", |_| (200, "{}".into())); + let call = Call::bearer(&format!("{base}/models")); + assert!(list_models(&call, ModelList::Data, "good-key-123", KEY_CHECK_TIMEOUT).is_err()); + } + + /// `Other…`: the key check and model list on the owner's base URL, + /// OpenAI's `/models` or, for Claude Code, Anthropic's + /// `/v1/models`; only https, or http to this node. + #[test] + fn other_takes_a_base_url() { + let p = get(OTHER).unwrap(); + assert!(p.calls(None, false).is_none()); + let (check, models) = p.calls(Some("https://llm.example.com/v1/"), false).unwrap(); + assert_eq!(check.url, "https://llm.example.com/v1/models"); + assert_eq!(models, check); + assert_eq!(check.auth, Auth::Bearer); + assert!(check.headers.is_empty()); + let (check, _) = p + .calls(Some("https://gw.example.com/anthropic"), true) + .unwrap(); + assert_eq!(check.url, "https://gw.example.com/anthropic/v1/models"); + assert_eq!(check.headers, [("anthropic-version", "2026-10-21")]); + for ok in [ + "https://llm.example.com/v1", + "http://localhost:11434/v1", + "http://127.0.0.1:8000", + "http://[::1]:8000/v1", + ] { + check_base_url(ok).unwrap_or_else(|e| panic!("{ok}: {e}")); + } + for bad in [ + "llm.example.com", + "http://llm.example.com/v1", + "https://", + "https://user:pw@llm.example.com", + "https://llm.example.com/v1?key=1", + "ftp://llm.example.com", + "https://llm.example.com/ v1", + ] { + assert!(check_base_url(bad).is_err(), "{bad}"); + } + assert_eq!(p.pick_label(), "Other…"); + assert_eq!(get("openai").unwrap().pick_label(), "OpenAI"); + } + #[test] fn harness_providers() { let ids = |h: &str| of_harness(h).map(|p| p.id).collect::>(); - assert_eq!(ids("claude-code"), ["deepseek", "openrouter"]); - assert_eq!(ids("opencode"), ["deepseek", "openrouter"]); - assert_eq!(ids("pi"), ["deepseek", "openrouter"]); + assert_eq!(ids("claude-code"), ["deepseek", "openrouter", OTHER]); + let table = [ + "deepseek", + "openrouter", + "openai", + "anthropic", + "google", + OTHER, + ]; + assert_eq!(ids("opencode"), table); + assert_eq!(ids("pi"), table); assert!(ids("codex").is_empty()); assert_eq!(get("deepseek").unwrap().env, "DEEPSEEK_API_KEY"); - assert!(get("anthropic").is_none()); + assert_eq!(get("google").unwrap().env, "GEMINI_API_KEY"); + assert!(get("anthropic").is_some_and(|p| !p.tools.contains(&"claude-code"))); } } diff --git a/crates/axe-core/src/runtime.rs b/crates/axe-core/src/runtime.rs index 2ee139c..1200bec 100644 --- a/crates/axe-core/src/runtime.rs +++ b/crates/axe-core/src/runtime.rs @@ -163,6 +163,11 @@ pub struct Health { /// `degraded`), as its last key check found it. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub providers: BTreeMap, + /// The model the owner picked per provider id, after its key login + /// (`/runtimes` model pick): the runtime's default model on that + /// provider; a provider with none runs its row's `default_model`. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub models: BTreeMap, } impl Runtime { @@ -192,6 +197,7 @@ impl Default for Health { login_at: None, added_at: None, providers: BTreeMap::new(), + models: BTreeMap::new(), } } } @@ -226,7 +232,7 @@ pub struct Runtime { } /// A card the owner should get: the runtime turned `state`. -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Default)] pub struct Alert { pub runtime: String, pub harness: String, @@ -239,6 +245,13 @@ pub struct Alert { /// The provider whose login it is about, on a runtime whose logins /// accumulate (one provider's key out of credit); `None`: the runtime. pub provider: Option, + /// A provider login that passed: the model the runtime runs on it. + pub model: Option, + /// ... and the models the owner may pick from, the current one first + /// (its model list; empty when it failed, see `models_error`). + pub models: Vec, + /// Why the provider's model list failed: the runtime keeps `model`. + pub models_error: Option, } impl Alert { @@ -251,6 +264,15 @@ impl Alert { if let Some(p) = &self.provider { v["provider"] = json!(p); } + if let Some(m) = &self.model { + v["model"] = json!(m); + } + if !self.models.is_empty() { + v["models"] = json!(self.models); + } + if let Some(e) = &self.models_error { + v["models_error"] = json!(e); + } v } @@ -335,15 +357,33 @@ pub fn login_provider(harness: &str, id: &str) -> Result<&'static crate::provide Ok(p) } +/// The file a custom provider's base URL is kept in, beside its key +/// (`/login/OTHER_BASE_URL`). +fn base_url_file(p: &crate::provider::Provider) -> &'static str { + match p.id { + crate::provider::OTHER => "OTHER_BASE_URL", + _ => "BASE_URL", + } +} + /// The variables Claude Code reads to reach provider `p`'s /// Anthropic-Messages endpoint with `key` as a bearer token, and those it /// must not see: an Anthropic key would be sent along to the provider /// (`x-api-key`), and a setup token would be read ahead of the login dir. -fn anthropic_env(p: &crate::provider::Provider, key: String) -> LoginEnv { +/// `url` is `Other…`'s base URL; `model` the runtime's model on `p`: one +/// that is not the row's default takes every tier, as a rule's model does +/// ([`tier_env`]). +fn anthropic_env( + p: &crate::provider::Provider, + key: String, + url: Option, + model: &str, +) -> LoginEnv { let mut set = vec![ ( "ANTHROPIC_BASE_URL", - p.anthropic_url.unwrap_or_default().to_string(), + url.or(p.anthropic_url.map(String::from)) + .unwrap_or_default(), ), ("ANTHROPIC_AUTH_TOKEN", key), // Empty, not only removed: Claude Code reads a key kept in its @@ -351,13 +391,15 @@ fn anthropic_env(p: &crate::provider::Provider, key: String) -> LoginEnv { ("ANTHROPIC_API_KEY", String::new()), ("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1".into()), ]; - if let Some(m) = &p.claude_models { - set.extend([ + match &p.claude_models { + Some(m) if model.is_empty() || model == p.default_model => set.extend([ ("ANTHROPIC_DEFAULT_OPUS_MODEL", m.opus.to_string()), ("ANTHROPIC_DEFAULT_SONNET_MODEL", m.sonnet.to_string()), ("ANTHROPIC_DEFAULT_HAIKU_MODEL", m.haiku.to_string()), ("CLAUDE_CODE_SUBAGENT_MODEL", m.subagent.to_string()), - ]); + ]), + _ if !model.is_empty() => set.extend(TIER_VARS.map(|v| (v, model.to_string()))), + _ => {} } (set, vec!["CLAUDE_CODE_OAUTH_TOKEN"]) } @@ -375,7 +417,7 @@ pub fn tier_env(with: Option<&crate::rule::Use>) -> Vec<(&'static str, String)> else { return vec![]; }; - if h.accumulates() || p.anthropic_url.is_none() { + if h.accumulates() || (p.anthropic_url.is_none() && !p.custom) { return vec![]; } let bare = |m: &str| m.trim_end_matches("[1m]").to_string(); @@ -387,17 +429,17 @@ pub fn tier_env(with: Option<&crate::rule::Use>) -> Vec<(&'static str, String)> return vec![]; } } - [ - "ANTHROPIC_DEFAULT_OPUS_MODEL", - "ANTHROPIC_DEFAULT_SONNET_MODEL", - "ANTHROPIC_DEFAULT_HAIKU_MODEL", - "CLAUDE_CODE_SUBAGENT_MODEL", - ] - .into_iter() - .map(|v| (v, model.clone())) - .collect() + TIER_VARS.into_iter().map(|v| (v, model.clone())).collect() } +/// Claude Code's model variables per tier. +const TIER_VARS: [&str; 4] = [ + "ANTHROPIC_DEFAULT_OPUS_MODEL", + "ANTHROPIC_DEFAULT_SONNET_MODEL", + "ANTHROPIC_DEFAULT_HAIKU_MODEL", + "CLAUDE_CODE_SUBAGENT_MODEL", +]; + /// How each harness can be logged in ([`crate::harness::Harness::logins`]). pub fn login_methods( harness: &str, @@ -515,7 +557,8 @@ impl Runtime { { // A provider login replaces the harness's own: its variables // only, never an Anthropic credential next to them. - let (s, r) = anthropic_env(p, key); + let model = self.model_of(p.id); + let (s, r) = anthropic_env(p, key, self.base_url(p.id), &model); set.extend(s); remove.extend(r); return (set, remove); @@ -534,6 +577,62 @@ impl Runtime { (set, remove) } + /// The runtime's model on provider `id`: the owner's pick + /// ([`Health::models`]), else the row's default (empty for `Other…` + /// before its first pick). + pub fn model_of(&self, id: &str) -> String { + self.health.models.get(id).cloned().unwrap_or_else(|| { + crate::provider::get(id) + .map_or("", |p| p.default_model) + .into() + }) + } + + /// The base URL stored with provider `id`'s key (`Other…`). + pub fn base_url(&self, id: &str) -> Option { + let p = crate::provider::get(id).filter(|p| p.custom)?; + let dir = self.login_secrets.as_ref()?; + let url = std::fs::read_to_string(dir.join(base_url_file(p))).ok()?; + Some(url.trim().to_string()).filter(|u| !u.is_empty()) + } + + /// Stores `url` as the base URL of custom provider `id`'s login, ahead + /// of its key ([`Runtime::login_key`]). + pub fn set_base_url(&self, id: &str, url: &str) -> Result<()> { + let Some(dir) = &self.login_secrets else { + bail!("runtime {} is not in the runtime registry", self.name); + }; + let p = login_provider(&self.harness, id)?; + if !p.custom { + bail!("{} takes no base URL", p.label); + } + let url = url.trim(); + crate::provider::check_base_url(url)?; + crate::sealed::write_private_file(&dir.join(base_url_file(p)), url.as_bytes()) + } + + /// The key check and model list calls of provider `p` for this + /// runtime ([`crate::provider::Provider::calls`]). + pub fn calls( + &self, + p: &crate::provider::Provider, + ) -> Option<(crate::provider::Call, crate::provider::Call)> { + let anthropic = crate::harness::get(&self.harness).is_some_and(|h| !h.accumulates()); + p.calls(self.base_url(p.id).as_deref(), anthropic) + } + + /// The provider logins it holds, for its config file. + pub fn held(&self) -> Vec { + self.providers() + .into_iter() + .map(|id| crate::harness::Held { + id, + model: self.model_of(id), + base_url: self.base_url(id), + }) + .collect() + } + /// The provider keys this runtime holds, in provider-table order. fn provider_keys(&self) -> Vec<(&'static crate::provider::Provider, String)> { let (Some(dir), Some(h)) = (&self.login_secrets, crate::harness::get(&self.harness)) else { @@ -557,6 +656,7 @@ impl Runtime { }; crate::provider::of_harness(&self.harness) .filter(|p| h.takes_provider(p) && dir.join(p.env).is_file()) + .filter(|p| !p.custom || dir.join(base_url_file(p)).is_file()) .map(|p| p.id) .collect() } @@ -593,11 +693,14 @@ impl Runtime { .iter() .filter_map(|(_, v, _)| *v) .collect(); - v.extend( - crate::provider::of_harness(&self.harness) - .filter(|p| h.is_some_and(|h| h.takes_provider(p))) - .map(|p| p.env), - ); + for p in crate::provider::of_harness(&self.harness) + .filter(|p| h.is_some_and(|h| h.takes_provider(p))) + { + v.push(p.env); + if p.custom { + v.push(base_url_file(p)); + } + } v } @@ -691,9 +794,13 @@ impl Runtime { if key.contains(['\n', '\r', '\0']) { bail!("the credential must be one line"); } + if p.custom && self.base_url(id).is_none() { + bail!("the {} login needs its base URL", p.label); + } crate::sealed::write_private_file(&dir.join(p.env), key.as_bytes())?; if !crate::harness::get(&self.harness).is_some_and(|h| h.accumulates()) { - self.remove_stored(&[p.env]); + let url = base_url_file(p); + self.remove_stored(&[p.env, url]); } self.write_config() } @@ -710,6 +817,9 @@ impl Runtime { } _ => {} } + if p.custom { + let _ = std::fs::remove_file(dir.join(base_url_file(p))); + } self.write_config() } @@ -721,20 +831,20 @@ impl Runtime { let (Some(h), Some(dir)) = (crate::harness::get(&self.harness), &self.login_dir) else { return Ok(()); }; - let Some((rel, text)) = h.config.render(&self.providers()) else { - return Ok(()); - }; - let path = dir.join(rel); - if let Some(parent) = path.parent() { - std::fs::create_dir_all(parent) - .with_context(|| format!("create {}", parent.display()))?; - } - if std::fs::read_to_string(&path).ok().as_deref() == Some(text.as_str()) { - return Ok(()); + for (rel, text) in h.config.render(&self.held()) { + let path = dir.join(rel); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent) + .with_context(|| format!("create {}", parent.display()))?; + } + if std::fs::read_to_string(&path).ok().as_deref() == Some(text.as_str()) { + continue; + } + let tmp = path.with_extension("json.tmp"); + std::fs::write(&tmp, &text).with_context(|| format!("write {}", tmp.display()))?; + std::fs::rename(&tmp, &path).with_context(|| format!("write {}", path.display()))?; } - let tmp = path.with_extension("json.tmp"); - std::fs::write(&tmp, &text).with_context(|| format!("write {}", tmp.display()))?; - std::fs::rename(&tmp, &path).with_context(|| format!("write {}", path.display())) + Ok(()) } /// Deletes the stored credentials other than `keep`: a login that @@ -1010,7 +1120,14 @@ pub struct Registry { /// key checks of a runtime with key logins (a thread). enum Probe { Cmd(Child), - Keys(std::sync::mpsc::Receiver>), + Keys(std::sync::mpsc::Receiver), +} + +/// What a key probe found: each key's check, and the model list of the +/// provider whose key was just added (when its check passed). +struct KeyProbe { + checks: Vec<(&'static str, crate::provider::KeyCheck)>, + models: Option, String>>, } impl Probe { @@ -1397,6 +1514,7 @@ impl Registry { until: None, quota: None, provider: Some(p), + ..Default::default() }); } let (state, until) = match f.class { @@ -1428,6 +1546,7 @@ impl Registry { until, quota: None, provider: None, + ..Default::default() }); if let Err(e) = rt.save() { eprintln!("axe node: runtime {name}: {e:#}"); @@ -1473,6 +1592,7 @@ impl Registry { until: Some(window), quota: Some(quota), provider: None, + ..Default::default() }; self.nearly_out.insert(name.to_string(), window); Some(alert) @@ -1529,6 +1649,7 @@ impl Registry { until: None, quota: None, provider: None, + ..Default::default() }), Err(e) => { eprintln!("axe node: runtime {name}: remove after a failed Add: {e:#}"); @@ -1588,25 +1709,40 @@ impl Registry { }; // A runtime on provider keys is checked by each provider's free key // check: a CLI's own status command only sees that a key is set. - let keys = rt.provider_keys(); + let keys: Vec<_> = rt + .provider_keys() + .into_iter() + .map(|(p, key)| (p, key, rt.calls(p))) + .collect(); if !keys.is_empty() { if let Some(log) = rt.probe_log() { let _ = std::fs::remove_file(log); } let base = self.key_check_base.clone(); + let new_key = self.new_keys.get(name).copied(); let (tx, rx) = std::sync::mpsc::channel(); std::thread::spawn(move || { - let out = keys - .into_iter() - .map(|(p, key)| { - let url = match &base { - Some(b) => crate::provider::on_base(b, p.key_check), - None => p.key_check.to_string(), - }; - let timeout = crate::provider::KEY_CHECK_TIMEOUT; - (p.id, crate::provider::check_key(&url, &key, timeout)) - }) - .collect(); + use crate::provider::{check_key, list_models, KeyCheck}; + let timeout = crate::provider::KEY_CHECK_TIMEOUT; + let mut out = KeyProbe { + checks: vec![], + models: None, + }; + for (p, key, calls) in keys { + let Some((check, list)) = calls else { + out.checks + .push((p.id, KeyCheck::Bad("no base URL is stored".into()))); + continue; + }; + let c = check_key(&check.on(base.as_deref()), &key, timeout); + // The new key's model list, for the owner's pick. + if new_key == Some(p.id) && c == KeyCheck::Ok { + let list = list.on(base.as_deref()); + let t = crate::provider::MODEL_LIST_TIMEOUT; + out.models = Some(list_models(&list, p.list, &key, t)); + } + out.checks.push((p.id, c)); + } let _ = tx.send(out); }); self.probed.insert(name.to_string(), Instant::now()); @@ -1682,9 +1818,9 @@ impl Registry { } }, Probe::Keys(rx) => match rx.try_recv() { - Ok(checks) => { - let (ok, status) = key_outcome(&checks); - done.push((name.clone(), ok, status, *at, Some(checks))); + Ok(k) => { + let (ok, status) = key_outcome(&k.checks); + done.push((name.clone(), ok, status, *at, Some(k))); } Err(std::sync::mpsc::TryRecvError::Empty) if !late => {} Err(_) => done.push((name.clone(), false, timed_out(), *at, None)), @@ -1692,10 +1828,12 @@ impl Registry { } } let mut alerts = std::mem::take(&mut self.ready); - for (name, mut ok, mut status, at, checks) in done { + for (name, mut ok, mut status, at, probe) in done { self.probes.remove(&name); let new_key = self.new_keys.remove(&name); - if let Some(checks) = checks { + let mut models = None; + if let Some(probe) = probe { + let checks = probe.checks; if let Some(id) = new_key { // The card is the new key's own outcome. let mine: Vec<_> = checks.iter().filter(|(p, _)| *p == id).cloned().collect(); @@ -1703,17 +1841,42 @@ impl Registry { true => (false, "the key is not stored".into()), false => key_outcome(&mine), }; + models = probe.models; + // `Other…` has no default model: a server that lists + // none adds nothing. + let custom = crate::provider::get(id).is_some_and(|p| p.custom); + if let (true, true, Some(Err(e))) = (ok, custom, &models) { + (ok, status) = (false, format!("its model list failed: {e}")); + } if !ok { self.drop_key(&name, id); } } self.provider_states(&name, &checks); } + // `Other…` runs its first listed model until the owner picks. + if let (true, Some(id), Some(Ok(list))) = (ok, new_key, &models) { + let none = self.get(&name).is_some_and(|r| r.model_of(id).is_empty()); + if let (true, Some(first)) = (none, list.first()) { + if let Err(e) = self.set_model(&name, id, first) { + eprintln!("axe node: runtime {name}: {e:#}"); + } + } + } let mut card = self.finished(&name, ok, &status, at); if let (Some(a), Some(id)) = (card.as_mut(), new_key) { if matches!(a.class.as_str(), LOGIN_OK | LOGIN_FAILED) { a.provider = Some(id.to_string()); } + if a.class == LOGIN_OK { + let model = self.get(&name).map(|r| r.model_of(id)).unwrap_or_default(); + match models { + Some(Ok(list)) => a.models = crate::provider::choices(&model, &list), + Some(Err(e)) => a.models_error = Some(e), + None => {} + } + a.model = Some(model).filter(|m| !m.is_empty()); + } } alerts.extend(card); } @@ -1738,6 +1901,30 @@ impl Registry { alerts } + /// Makes `model` runtime `name`'s default model on provider `id` (the + /// owner's pick from its model list), and rewrites its config. A rule + /// that names a model still runs that one. + pub fn set_model(&mut self, name: &str, id: &str, model: &str) -> Result<()> { + let model = model.trim(); + if model.is_empty() + || model.len() > 200 + || model.chars().any(|c| c.is_whitespace() || c.is_control()) + { + bail!("invalid model {model:?}"); + } + let Some(rt) = self.get_mut(name) else { + bail!("no runtime {name} on this node"); + }; + if !rt.providers().contains(&id) { + bail!("runtime {name} holds no {id} login"); + } + rt.health.models.insert(id.to_string(), model.to_string()); + rt.save()?; + rt.write_config()?; + eprintln!("axe node: runtime {name}: {id} runs {model} by default"); + Ok(()) + } + /// Drops runtime `name`'s key for provider `id`, whose first check /// failed: the login added nothing. fn drop_key(&mut self, name: &str, id: &str) { @@ -1747,6 +1934,11 @@ impl Registry { if let Err(e) = rt.remove_key(id) { eprintln!("axe node: runtime {name}: drop the {id} key: {e:#}"); } + if rt.health.models.remove(id).is_some() { + if let Err(e) = rt.save().and_then(|_| rt.write_config()) { + eprintln!("axe node: runtime {name}: {e:#}"); + } + } eprintln!("axe node: runtime {name}: the new {id} key failed its check; dropped"); } @@ -1840,6 +2032,7 @@ impl Registry { until: None, quota: None, provider: None, + ..Default::default() }) } @@ -1872,6 +2065,9 @@ impl Registry { "providers": r.providers().iter().map(|id| json!({ "id": id, "state": r.health.providers.get(*id).map_or("unchecked", |s| s.as_str()), + // Its default model there (the owner's pick or the + // row's default). + "model": r.model_of(id), })).collect::>(), "in_use": in_use(&r.name), }) @@ -2595,7 +2791,7 @@ exit 2 let hb = reg.heartbeat(|_| 0, 0); assert_eq!( hb["list"][0]["providers"], - json!([{"id": "deepseek", "state": "ok"}]) + json!([{"id": "deepseek", "state": "ok", "model": "deepseek-flash"}]) ); assert!(!hb.to_string().contains(DS)); @@ -2716,7 +2912,8 @@ exit 2 let hb = reg.heartbeat(|_| 0, 0); assert_eq!( hb["list"][0]["providers"], - json!([{"id": "acme", "state": "ok"}, {"id": "acme2", "state": "needs_login"}]) + json!([{"id": "acme", "state": "ok", "model": "acme-1"}, + {"id": "acme2", "state": "needs_login", "model": "big"}]) ); // Persisted with the runtime's health; an older file without it loads. let saved: Health = @@ -3536,7 +3733,8 @@ exit 2 let hb = reg.heartbeat(|_| 0, now); assert_eq!( hb["list"][0]["providers"], - json!([{"id": "acme", "state": "unchecked"}, {"id": "acme2", "state": "out_of_credit"}]) + json!([{"id": "acme", "state": "unchecked", "model": "acme-1"}, + {"id": "acme2", "state": "out_of_credit", "model": "big"}]) ); // Check: both keys pass, the provider works again. reg.check_now("keys-1"); diff --git a/crates/axe-core/src/runtime_views.rs b/crates/axe-core/src/runtime_views.rs index e3f754b..6af323c 100644 --- a/crates/axe-core/src/runtime_views.rs +++ b/crates/axe-core/src/runtime_views.rs @@ -377,8 +377,32 @@ pub fn provider_text(name: &str, harness: &str, first: bool) -> String { } } -/// Paste provider `id`'s API key for runtime `name` (O-b). -pub fn key_text(name: &str, id: &str) -> String { +/// The card after the owner picked `model` as runtime `name`'s default +/// model on provider `id`. +pub fn model_set_text(name: &str, id: &str, model: &str) -> String { + format!( + "{} runs {} on {model} by default. A routing rule can still name another model; pick \ + again below to change it.", + display(name), + provider_label(id) + ) +} + +/// Paste provider `id`'s API key for runtime `name` (O-b); `Other…` takes +/// a base URL with it (`anthropic`: Claude Code's Anthropic-compatible one). +pub fn key_text(name: &str, id: &str, anthropic: bool) -> String { + if crate::provider::get(id).is_some_and(|p| p.custom) { + let api = match anthropic { + true => "an Anthropic-compatible API (Messages)", + false => "an OpenAI-compatible API", + }; + return format!( + "{} · Other provider\nAny server with {api} that lists its models. Give its base \ + URL (https://…, or http://localhost for one on your node) and an API key in a sealed \ + form that only your node can read. Then pick a model from its list.", + display(name) + ); + } let (label, console) = crate::provider::get(id).map_or((id, ""), |p| (p.label, p.console)); let mut out = format!( "{} · {label}\nPaste a {label} API key. It goes through a sealed form that only your \ @@ -747,8 +771,22 @@ pub fn alert_text(a: &Value, r: &Routing, me: Option<&str>, c: &Clock) -> String } (Some(LOGIN_OK), _) if a["provider"].is_string() => { let id = a["provider"].as_str().unwrap_or_default(); - let model = crate::provider::get(id).map_or("", |p| p.default_model); - let head = format!("{n} is ready with {} ({model}).", provider_label(id)); + let model = a["model"] + .as_str() + .unwrap_or_else(|| crate::provider::get(id).map_or("", |p| p.default_model)); + let mut head = format!("{n} is ready with {} ({model}).", provider_label(id)); + // The model pick (`telegram::model_rows`), or why there is none. + if a["models"].as_array().is_some_and(|m| m.len() > 1) { + head.push_str(&format!( + "\nPick its default model below; {model} until you do. A routing rule can \ + still name another." + )); + } else if let Some(e) = a["models_error"].as_str() { + head.push_str(&format!( + "\nIts model list didn't load ({e}), so it runs {model}. A routing rule can \ + name another model." + )); + } match r.used(name, harness) { true => head, false => format!( diff --git a/crates/axe-core/src/sealed.rs b/crates/axe-core/src/sealed.rs index dbe67e5..68cb78b 100644 --- a/crates/axe-core/src/sealed.rs +++ b/crates/axe-core/src/sealed.rs @@ -507,14 +507,29 @@ impl Target { bail!("a {p} login is an API key (api_key), not {login}"); } } - match fields { - [f] if f.name == "secret" - && f.kind == Kind::Secret - && f.required - && f.env.is_none() => + let secret = |f: &Field| { + f.name == "secret" && f.kind == Kind::Secret && f.required && f.env.is_none() + }; + // `Other…`: its base URL, then the key. + let custom = provider + .as_deref() + .and_then(crate::provider::get) + .is_some_and(|p| p.custom); + match (custom, fields) { + (false, [f]) if secret(f) => Ok(()), + (true, [u, f]) + if secret(f) + && u.name == "base_url" + && u.kind == Kind::Text + && u.required + && u.env.is_none() => { Ok(()) } + (true, _) => bail!( + "an Other provider login form has the required fields base_url (text) \ + and secret" + ), _ => bail!("a runtime login form has one required secret field, secret"), } } @@ -1512,7 +1527,8 @@ impl Desk { self } - /// The desk handing registry changes (`runtime_add`, `runtime_remove`) + /// The desk handing registry changes (`runtime_add`, `runtime_remove`, + /// `runtime_model`) /// to the node, which applies them between picks and answers. pub fn with_runtime_jobs(mut self, jobs: RuntimeJobs) -> Desk { self.runtime_jobs = Some(jobs); @@ -1570,7 +1586,7 @@ impl Desk { Some("form_sign") => self.sign(q, now), Some("form_deliver") => self.deliver(q, now), Some("runtime_login") => self.device_login(q), - Some("runtime_add" | "runtime_remove") => self.runtime_job(q), + Some("runtime_add" | "runtime_remove" | "runtime_model") => self.runtime_job(q), Some("runtime_check") => self.check(q), _ => Err(anyhow::anyhow!("unknown form job")), }; @@ -1759,6 +1775,11 @@ impl Desk { return self.relay_code(runtime, value); } let (cfg, rt) = self.runtime(runtime)?; + if let (Some(id), Some(Val::Text(url))) = + (provider.as_deref(), vals.get("base_url")) + { + rt.set_base_url(id, url)?; + } rt.login(&cfg, login, provider.as_deref(), value)?; self.logged_in(runtime, provider.as_deref()); Ok(json!({"target": spec.target.describe(), "runtime": runtime, diff --git a/crates/axe-node/src/dispatch.rs b/crates/axe-node/src/dispatch.rs index 65d0ab8..f66abe2 100644 --- a/crates/axe-node/src/dispatch.rs +++ b/crates/axe-node/src/dispatch.rs @@ -112,8 +112,8 @@ pub(crate) fn run_provider(rt: &runtime::Runtime, with: Option<&Use>) -> Option< /// The `provider/model` a run of `with` on runtime `rt` runs, on a runtime /// whose logins accumulate (its CLI's log does not name it): the entry's -/// model, else the runtime's config default, its first provider's default -/// model (`harness::ConfigFile`). Recorded with the run's usage +/// model, else the runtime's config default, its model on its first +/// provider (`harness::ConfigFile`, `Runtime::model_of`). Recorded with the run's usage /// ([`crate::usage::Parsed::with_model`]). pub(crate) fn run_model(rt: &runtime::Runtime, with: Option<&Use>) -> Option { crate::harness::get(&rt.harness).filter(|h| h.accumulates())?; @@ -121,7 +121,7 @@ pub(crate) fn run_model(rt: &runtime::Runtime, with: Option<&Use>) -> Option = down.iter().map(|(r, _)| *r).collect(); let states = down_states(&rts, Some(down), now); - // A runtime holding several providers' keys runs that provider's - // default model; any other runs its own default. + // A runtime holding several providers' keys runs its model on that + // provider; any other runs its own default. let table = crate::harness::get(&rt.harness).is_some_and(|h| h.accumulates()); let with = provider.filter(|_| table).map(|p| Use { harness: rt.harness.clone(), - model: Some(format!("{}/{}", p.id, p.default_model)), + model: Some(format!("{}/{}", p.id, rt.model_of(p.id))), effort: None, }); Some(Pick { @@ -813,6 +813,15 @@ impl Dispatcher { .runtimes .create(&self.cfg, q["harness"].as_str().unwrap_or("")) .map(|name| json!({"runtime": name})), + // The owner's model pick after a provider login. + Some("runtime_model") => { + let name = q["runtime"].as_str().unwrap_or(""); + let id = q["provider"].as_str().unwrap_or(""); + let model = q["model"].as_str().unwrap_or(""); + self.runtimes + .set_model(name, id, model) + .map(|()| json!({"runtime": name, "provider": id, "model": model})) + } Some("runtime_remove") => { let name = q["runtime"].as_str().unwrap_or(""); let live = self.in_use(name); diff --git a/crates/axe-node/src/node_link.rs b/crates/axe-node/src/node_link.rs index 17ea0c2..ac92add 100644 --- a/crates/axe-node/src/node_link.rs +++ b/crates/axe-node/src/node_link.rs @@ -430,6 +430,7 @@ impl Store { | "runtime_login" | "runtime_add" | "runtime_remove" + | "runtime_model" | "runtime_check" ) ) { diff --git a/crates/axe-server/src/server.rs b/crates/axe-server/src/server.rs index bd9736c..74d98cd 100644 --- a/crates/axe-server/src/server.rs +++ b/crates/axe-server/src/server.rs @@ -192,6 +192,15 @@ impl crate::core::Axe for State { fn runtime_remove(&self, runtime: &str) -> Result { runtime_remove(self, runtime) } + fn runtime_model(&self, runtime: &str, provider: &str, model: &str) -> Result<()> { + runtime_job( + self, + json!({"kind": "runtime_model", "runtime": runtime, "provider": provider, + "model": model}), + )?; + eprintln!("axe server: runtime {runtime}: {provider} model set to {model}"); + Ok(()) + } fn runtime_check(&self, runtime: &str) -> Result<()> { runtime_job(self, json!({"kind": "runtime_check", "runtime": runtime}))?; eprintln!("axe server: runtime {runtime}: check requested"); @@ -304,8 +313,8 @@ fn node_admission_job(st: &State, job: serde_json::Value) -> Result Result { let v = relay_job(st, job, None, FORM_RELAY_TIMEOUT).map_err(anyhow::Error::msg)?; if let Some(e) = v["error"].as_str() { @@ -1998,6 +2007,13 @@ struct RuntimeAddBody { who: Who, } +/// A runtime's default model on one provider (`/runtimes` model pick). +#[derive(Deserialize)] +struct RuntimeModelBody { + provider: String, + model: String, +} + #[derive(Deserialize)] struct RuntimeLoginBody { method: String, @@ -2904,6 +2920,15 @@ fn route(st: &State, req: &Request) -> Result { runtime_job(st, json!({"kind": "runtime_check", "runtime": name}))?; ok(200, &json!({"runtime": name, "checking": true})) } + // Sets a runtime's default model on one provider (the model pick). + ("POST", ["api", "runtimes", name, "model"]) => { + let b: RuntimeModelBody = req.json()?; + crate::core::Axe::runtime_model(st, name, &b.provider, &b.model)?; + ok( + 200, + &json!({"runtime": name, "provider": b.provider, "model": b.model}), + ) + } ("DELETE", ["api", "runtimes", name]) => { let note = runtime_remove(st, name)?; ok(200, &json!({"runtime": name, "note": note})) @@ -4489,6 +4514,16 @@ fn runtime_login( } let label = format!("{} API key", p.label); login_form(st, bot, runtime, &harness, method, Some(p), &label)?; + if p.custom { + let api = match crate::harness::get(&harness).is_some_and(|h| h.accumulates()) { + true => "OpenAI-compatible", + false => "Anthropic-compatible", + }; + return Ok(format!( + "Sealed form sent for runtime {runtime}: tap \"Open sealed form\", then give the \ + server's {api} base URL and its API key." + )); + } return Ok(format!( "Sealed form sent for runtime {runtime}: tap \"Open sealed form\" and paste your {} \ API key (get one at {}).", @@ -4568,16 +4603,36 @@ fn login_form( login: login.into(), provider: provider.map(|p| p.id.to_string()), }, - fields: vec![crate::sealed::Field { - name: "secret".into(), - label: label.to_string(), - kind: crate::sealed::Kind::Secret, - required: true, - max: None, - choices: vec![], - env: None, - check, - }], + fields: { + let mut f = vec![crate::sealed::Field { + name: "secret".into(), + label: label.to_string(), + kind: crate::sealed::Kind::Secret, + required: true, + max: None, + choices: vec![], + env: None, + check, + }]; + // `Other…`: the server's base URL first (checked again by the + // node, `provider::check_base_url`). + if provider.is_some_and(|p| p.custom) { + f.insert( + 0, + crate::sealed::Field { + name: "base_url".into(), + label: "Base URL (https://…)".into(), + kind: crate::sealed::Kind::Text, + required: true, + max: Some(512), + choices: vec![], + env: None, + check: None, + }, + ); + } + f + }, ttl: None, from: "/runtimes".into(), }; diff --git a/crates/axe-telegram/src/telegram.rs b/crates/axe-telegram/src/telegram.rs index 2a24299..1864591 100644 --- a/crates/axe-telegram/src/telegram.rs +++ b/crates/axe-telegram/src/telegram.rs @@ -122,8 +122,10 @@ const WEB_GROUP: &str = "A sign-in link goes only to my private chat: send /web /// provider's key screen, `rtx:` cancel a login (a new runtime that never /// logged in is dropped), `rtrm:` confirm a removal (A6), /// `rtrm!:` remove, `rtroute` the routing view (R1, read only), -/// `rtcheck:` check a login now (out of credit: after a top-up) and -/// `rtdone` close a card. On a screen a press edits it in place; on a card it +/// `rtcheck:` check a login now (out of credit: after a top-up), +/// `rtmodel::` pick the `i`th model of a ready card's list (its +/// `flags.models`, for its `flags.provider`), `rtmpage::` +/// turn that list's page, and `rtdone` close a card. On a screen a press edits it in place; on a card it /// replies with the screen. Routing has no buttons of its own: the owner /// asks the bot in free text. const RUNTIMES_BUTTON: &str = "runtimes"; @@ -139,6 +141,10 @@ const DONE_BUTTON: &str = "rtdone"; const CHECK_BUTTON: &str = "rtcheck:"; const PROVIDER_BUTTON: &str = "rtprov:"; const KEY_BUTTON: &str = "rtkey:"; +const MODEL_BUTTON: &str = "rtmodel:"; +const MODEL_PAGE: &str = "rtmpage:"; +/// Models per page of a model pick: one a row, within Telegram's keyboard. +const MODEL_PAGE_SIZE: usize = 8; /// Buttons of the retired mixed `/runtimes` row (primary, backup, no /// backup, cancel a removal): a press on an old message only gets a toast. const RETIRED_BUTTONS: &[&str] = &["rtpri:", "rtbak:", "rtbak-", "rtrm-"]; @@ -170,6 +176,10 @@ enum RuntimePress<'a> { Confirm(&'a str), /// Check a login now: a passing check ends out of credit. Check(&'a str), + /// Pick a ready card's model: runtime, index in its list. + Model(&'a str, usize), + /// Turn a ready card's model list: runtime, page. + ModelPage(&'a str, usize), Routing, Done, Retired, @@ -193,6 +203,14 @@ impl<'a> RuntimePress<'a> { if let Some(n) = data.strip_prefix(CHECK_BUTTON) { return Some(RuntimePress::Check(n)); } + if let Some(m) = data.strip_prefix(MODEL_BUTTON) { + let (name, i) = m.rsplit_once(':')?; + return Some(RuntimePress::Model(name, i.parse().ok()?)); + } + if let Some(m) = data.strip_prefix(MODEL_PAGE) { + let (name, page) = m.rsplit_once(':')?; + return Some(RuntimePress::ModelPage(name, page.parse().ok()?)); + } if let Some(n) = data.strip_prefix(LOGIN_CANCEL) { return Some(RuntimePress::CancelLogin(n)); } @@ -337,19 +355,24 @@ fn add_screen() -> Screen { } /// Pick a provider for runtime `name` of `harness` (O-a): one button per -/// provider it does not hold yet (`held`), then Cancel (a runtime that +/// provider it does not hold yet (`held`), `Other…` last, then Cancel (a runtime that /// never logged in is dropped) or Back. A harness with one login (Claude's /// `Other provider…`) lists every row it takes and goes Back to its login /// methods: a provider key replaces its login. fn provider_screen(name: &str, harness: &str, held: &[String], first: bool) -> Screen { let h = crate::harness::get(harness); let single = h.is_some_and(|h| !h.accumulates()); - let buttons: Vec<(String, String)> = crate::provider::of_harness(harness) + let offered: Vec<&crate::provider::Provider> = crate::provider::of_harness(harness) .filter(|p| h.is_some_and(|h| h.takes_provider(p))) .filter(|p| single || !held.iter().any(|x| x == p.id)) - .map(|p| button(p.label, format!("{KEY_BUTTON}{name}:{}", p.id))) .collect(); - let mut rows: Vec> = buttons.chunks(3).map(<[_]>::to_vec).collect(); + let pick = |p: &&crate::provider::Provider| { + button(p.pick_label(), format!("{KEY_BUTTON}{name}:{}", p.id)) + }; + // The named providers three a row, then `Other…` on its own. + let named: Vec<_> = offered.iter().filter(|p| !p.custom).map(pick).collect(); + let mut rows: Vec> = named.chunks(3).map(<[_]>::to_vec).collect(); + rows.extend(offered.iter().filter(|p| p.custom).map(|p| vec![pick(p)])); rows.push(vec![match (single, first) { (true, _) => button("Back", format!("{LOGIN_BUTTON}{name}")), (false, true) => button("Cancel", format!("{LOGIN_CANCEL}{name}")), @@ -361,16 +384,20 @@ fn provider_screen(name: &str, harness: &str, held: &[String], first: bool) -> S ) } -/// Paste provider `id`'s key for runtime `name` (O-b): the sealed form, or -/// Cancel. -fn key_screen(name: &str, id: &str) -> Screen { +/// Paste provider `id`'s key for runtime `name` of `harness` (O-b): the +/// sealed form (`Other…`: its base URL and key), or Cancel. +fn key_screen(name: &str, harness: &str, id: &str) -> Screen { + let anthropic = crate::harness::get(harness).is_some_and(|h| !h.accumulates()); + let custom = crate::provider::get(id).is_some_and(|p| p.custom); + let label = if custom { + "Paste URL + key" + } else { + "Paste API key" + }; ( - crate::runtime_views::key_text(name, id), + crate::runtime_views::key_text(name, id, anthropic), fit(vec![vec![ - button( - "Paste API key", - format!("{LOGIN_BUTTON}{name}:api_key:{id}"), - ), + button(label, format!("{LOGIN_BUTTON}{name}:api_key:{id}")), button("Cancel", format!("{LOGIN_CANCEL}{name}")), ]]), ) @@ -436,6 +463,60 @@ fn routing_screen(r: &Routing, me: &str, c: &Clock) -> Screen { ) } +/// The model pick of runtime `name`'s ready card: page `page` of `models` +/// (one a row, `current` marked), ‹ Back and More › between pages, then +/// Routing and Done. +fn model_rows( + name: &str, + models: &[String], + current: &str, + page: usize, +) -> Vec> { + let pages = models.len().div_ceil(MODEL_PAGE_SIZE).max(1); + let page = page.min(pages - 1); + let mut rows: Vec> = models + .iter() + .enumerate() + .skip(page * MODEL_PAGE_SIZE) + .take(MODEL_PAGE_SIZE) + .map(|(i, m)| { + let label = match m == current { + true => format!("• {m}"), + false => m.clone(), + }; + vec![button(label, format!("{MODEL_BUTTON}{name}:{i}"))] + }) + .collect(); + let mut nav = vec![]; + if page > 0 { + nav.push(button("‹ Back", format!("{MODEL_PAGE}{name}:{}", page - 1))); + } + if page + 1 < pages { + nav.push(button( + format!("More › ({}/{pages})", page + 1), + format!("{MODEL_PAGE}{name}:{}", page + 1), + )); + } + if !nav.is_empty() { + rows.push(nav); + } + rows.push(vec![ + button("Routing →", ROUTING_BUTTON), + button("Done", DONE_BUTTON), + ]); + fit(rows) +} + +/// The models of ready card flags `f` (`flags.models`). +fn card_models(f: &Value) -> Vec { + f["models"] + .as_array() + .into_iter() + .flatten() + .filter_map(|m| m.as_str().map(String::from)) + .collect() +} + /// A runtime card's buttons (A5, A7), and whether it is a state card that /// closes when the runtime works again (`flags.runtime_alert`) rather than /// a one-off outcome (`flags.runtime_ready`). @@ -1691,6 +1772,9 @@ impl Gateway { let card = f["runtime_alert"] == true || f["runtime_ready"] == true; let ours = match &press { RuntimePress::Done => card, + RuntimePress::Model(..) | RuntimePress::ModelPage(..) => { + f["runtime_ready"] == true && f["models"].is_array() + } RuntimePress::List | RuntimePress::Routing | RuntimePress::Menu(_) @@ -1707,6 +1791,22 @@ impl Gateway { // (a passing one closes the out-of-credit card in place). let toast = match press { RuntimePress::Retired => Some(RETIRED_TOAST.to_string()), + RuntimePress::Model(name, i) => Some(match card_models(f).get(i) { + None => "That model is no longer on this card.".to_string(), + Some(model) => { + let provider = f["provider"].as_str().unwrap_or_default(); + match store.runtime_model(name, provider, model) { + Ok(()) => { + store.set_flag(stored.id, "$.model", json!(model))?; + format!("{} runs {model} by default", routing::display(name)) + } + Err(e) => format!("The model was not set: {e:#}") + .chars() + .take(190) + .collect(), + } + } + }), RuntimePress::Check(name) => Some(match store.runtime_check(name) { Ok(()) => { self.login_started(name, &b.name(), chat); @@ -1744,6 +1844,31 @@ impl Gateway { }; let next: Screen = match press { RuntimePress::Retired | RuntimePress::Check(_) => return Ok(true), + // A ready card's model pick edits the card in place. + RuntimePress::Model(name, _) | RuntimePress::ModelPage(name, _) => { + let fresh = store.message_at(&b.name(), chat, tg_msg)?.unwrap_or(stored); + let models = card_models(&fresh.flags); + let current = fresh.flags["model"] + .as_str() + .unwrap_or_default() + .to_string(); + let (text, page) = match press { + RuntimePress::Model(_, i) if models.get(i) == Some(¤t) => ( + crate::runtime_views::model_set_text( + name, + fresh.flags["provider"].as_str().unwrap_or_default(), + ¤t, + ), + i / MODEL_PAGE_SIZE, + ), + RuntimePress::Model(_, i) => (fresh.text.clone(), i / MODEL_PAGE_SIZE), + RuntimePress::ModelPage(_, p) => (fresh.text.clone(), p), + _ => unreachable!(), + }; + let rows = model_rows(name, &models, ¤t, page); + self.edit_screen(b, store, &fresh, &(text, rows)); + return Ok(true); + } RuntimePress::Done => { store.claim_close(stored.id, &stored.text, "done")?; self.clear_buttons(b, chat, tg_msg); @@ -1784,7 +1909,12 @@ impl Gateway { } None => runtimes_screen(&r, &clock), }, - RuntimePress::Key(name, provider) => key_screen(name, provider), + RuntimePress::Key(name, provider) => { + let harness = raw(name) + .and_then(|r| r["harness"].as_str().map(String::from)) + .unwrap_or_default(); + key_screen(name, &harness, provider) + } RuntimePress::Login(name, method, provider) => { let text = match store.runtime_login(&me, name, method, provider) { Ok(text) => { @@ -2187,11 +2317,19 @@ impl Gateway { let clock = Clock::new(&store.bot_timezone(&name).unwrap_or_default(), now()); let text = crate::runtime_views::alert_text(a, &r, Some(&name), &clock); let (buttons, state_card) = card_buttons(a, &r); - let opts = SendOpts { + let mut opts = SendOpts { chat, buttons, ..SendOpts::default() }; + // A provider login that passed with its model list: the pick. + let models: Vec = card_models(a); + let model = a["model"].as_str().unwrap_or_default(); + let pick = + a["class"] == crate::runtime::LOGIN_OK && a["provider"].is_string() && models.len() > 1; + if pick { + (opts.buttons, opts.rows) = flat(&model_rows(runtime, &models, model, 0)); + } let out = self.send(store, &name, &text, &opts)?; let id = out .last() @@ -2204,6 +2342,11 @@ impl Gateway { store.set_flag(id, "$.runtime", json!(runtime))?; } } + if pick { + store.set_flag(id, "$.provider", a["provider"].clone())?; + store.set_flag(id, "$.models", json!(models))?; + store.set_flag(id, "$.model", json!(model))?; + } if let (true, Some(w)) = (nearly, window) { store.set_flag(id, "$.nearly_out", json!(w))?; } @@ -4506,11 +4649,28 @@ mod tests { "Set up Pi 1\nPi runs models from many providers. Pick the first; \ you can add more later. You pay the provider per use." ); + assert_eq!( + labels(&s.1), + [ + vec!["DeepSeek", "OpenRouter", "OpenAI"], + vec!["Anthropic", "Google Gemini"], + vec!["Other…"], + vec!["Cancel"] + ] + ); assert_eq!( data(&s.1), - ["rtkey:pi-1:deepseek", "rtkey:pi-1:openrouter", "rtx:pi-1"] + [ + "rtkey:pi-1:deepseek", + "rtkey:pi-1:openrouter", + "rtkey:pi-1:openai", + "rtkey:pi-1:anthropic", + "rtkey:pi-1:google", + "rtkey:pi-1:other", + "rtx:pi-1" + ] ); - let s = key_screen("pi-1", "openrouter"); + let s = key_screen("pi-1", "pi", "openrouter"); assert!(check(&s).starts_with("Pi 1 · OpenRouter\n"), "{}", s.0); assert_eq!(data(&s.1), ["rtlogin:pi-1:api_key:openrouter", "rtx:pi-1"]); } @@ -4531,12 +4691,18 @@ mod tests { models instead of its own. Pick one; its key replaces this runtime's login. \ You pay the provider per use." ); - assert_eq!(labels(&s.1), [vec!["DeepSeek", "OpenRouter"], vec!["Back"]]); + // Only rows with an Anthropic-Messages endpoint, and + // `Other…` on an Anthropic-compatible URL. + assert_eq!( + labels(&s.1), + [vec!["DeepSeek", "OpenRouter"], vec!["Other…"], vec!["Back"]] + ); assert_eq!( data(&s.1), [ "rtkey:claude-2:deepseek", "rtkey:claude-2:openrouter", + "rtkey:claude-2:other", "rtlogin:claude-2" ] ); @@ -4549,7 +4715,7 @@ mod tests { RuntimePress::parse("rtprov:claude-2"), Some(RuntimePress::Providers("claude-2")) ); - let s = key_screen("claude-2", "openrouter"); + let s = key_screen("claude-2", "claude-code", "openrouter"); assert_eq!( check(&s), "Claude 2 · OpenRouter\nPaste a OpenRouter API key. It goes through a sealed \ @@ -4567,6 +4733,20 @@ mod tests { Some("openrouter") )) ); + // Other…: a base URL and a key in one sealed form. + let s = key_screen("claude-2", "claude-code", "other"); + assert_eq!( + check(&s), + "Claude 2 · Other provider\nAny server with an Anthropic-compatible API \ + (Messages) that lists its models. Give its base URL (https://…, or \ + http://localhost for one on your node) and an API key in a sealed form that \ + only your node can read. Then pick a model from its list." + ); + assert_eq!(labels(&s.1), [vec!["Paste URL + key", "Cancel"]]); + assert_eq!( + data(&s.1), + ["rtlogin:claude-2:api_key:other", "rtx:claude-2"] + ); // Codex takes no provider row: no Other provider…. assert!(!labels(&login_screen("codex-2", "codex").1) .concat() @@ -4588,17 +4768,22 @@ mod tests { ); assert_eq!( labels(&s.1), - [vec!["DeepSeek", "OpenRouter"], vec!["Cancel"]] - ); - assert_eq!( - data(&s.1), [ - "rtkey:opencode-1:deepseek", - "rtkey:opencode-1:openrouter", - "rtx:opencode-1" + vec!["DeepSeek", "OpenRouter", "OpenAI"], + vec!["Anthropic", "Google Gemini"], + vec!["Other…"], + vec!["Cancel"] ] ); - let s = key_screen("opencode-1", "deepseek"); + assert_eq!(data(&s.1)[0], "rtkey:opencode-1:deepseek"); + assert_eq!(data(&s.1)[5], "rtkey:opencode-1:other"); + let s = key_screen("opencode-1", "opencode", "other"); + assert!( + check(&s).contains("Any server with an OpenAI-compatible API that lists"), + "{}", + s.0 + ); + let s = key_screen("opencode-1", "opencode", "deepseek"); assert_eq!( check(&s), "OpenCode 1 · DeepSeek\nPaste a DeepSeek API key. It goes through a sealed form \ @@ -4658,15 +4843,23 @@ mod tests { check(&s), "Add a provider to OpenCode 1\nPick one. You pay the provider per use." ); - assert_eq!(labels(&s.1), [vec!["OpenRouter"], vec!["Back"]]); assert_eq!( - data(&s.1), - ["rtkey:opencode-1:openrouter", "rtacct:opencode-1"] + labels(&s.1), + [ + vec!["OpenRouter", "OpenAI", "Anthropic"], + vec!["Google Gemini"], + vec!["Other…"], + vec!["Back"] + ] ); + assert_eq!(data(&s.1)[0], "rtkey:opencode-1:openrouter"); + assert_eq!(data(&s.1).last(), Some(&"rtacct:opencode-1")); // Holding every provider: no Add provider. let mut all = oc.clone(); - all["providers"] = json!([{"id": "deepseek", "state": "ok"}, - {"id": "openrouter", "state": "ok"}]); + all["providers"] = json!(crate::provider::PROVIDERS + .iter() + .map(|p| json!({"id": p.id, "state": "ok"})) + .collect::>()); let r2 = routing(vec![all], &[], &[]); let s = runtime_screen(&r2, r2.account("opencode-1").unwrap(), &c); assert_eq!(labels(&s.1), [vec!["Remove…"], vec!["Back"]]); @@ -4714,6 +4907,79 @@ mod tests { button("Done", "rtdone") ] ); + + // Ready with its model list: the pick, the current model first. + let mut listed = a("login_ok", "ok", ""); + listed["model"] = json!("deepseek-flash"); + listed["models"] = json!(["deepseek-flash", "deepseek-v4-pro"]); + assert_eq!( + crate::runtime_views::alert_text(&listed, &r, Some("tn-cos"), &c), + "OpenCode 1 is ready with DeepSeek (deepseek-flash).\nPick its default model \ + below; deepseek-flash until you do. A routing rule can still name another.\nNot \ + used yet. To use it, tell me (e.g. \"run research tasks on OpenCode 1\"); \ + Routing shows the result." + ); + // The list failed: it runs the row's default. + let mut failed = a("login_ok", "ok", ""); + failed["model"] = json!("deepseek-flash"); + failed["models_error"] = json!("HTTP 503"); + assert!(crate::runtime_views::alert_text(&failed, &r, None, &c).starts_with( + "OpenCode 1 is ready with DeepSeek (deepseek-flash).\nIts model list didn't load \ + (HTTP 503), so it runs deepseek-flash. A routing rule can name another model." + )); + } + + /// The model pick on a ready card (spec: "pick a model from that + /// provider's live model list ... paged"): eight a page, one a row, + /// the current one marked, Back and More between pages, then Routing + /// and Done; every callback within Telegram's 64 bytes. + #[test] + fn model_pick_pages() { + let models: Vec = (0..20).map(|i| format!("vendor/model-{i}")).collect(); + let rows = model_rows("opencode-1", &models, "vendor/model-0", 0); + let l = labels(&rows); + assert_eq!(l[0], ["• vendor/model-0"]); + assert_eq!(l[1], ["vendor/model-1"]); + assert_eq!(l[8], ["More › (1/3)"]); + assert_eq!(l[9], ["Routing →", "Done"]); + assert_eq!(rows.len(), 10); + assert_eq!(data(&rows)[1], "rtmodel:opencode-1:1"); + assert_eq!(data(&rows)[8], "rtmpage:opencode-1:1"); + let rows = model_rows("opencode-1", &models, "vendor/model-17", 2); + let l = labels(&rows); + assert_eq!(l[0], ["vendor/model-16"]); + assert_eq!(l[1], ["• vendor/model-17"]); + assert_eq!(l[4], ["‹ Back"]); + assert_eq!(data(&rows)[0], "rtmodel:opencode-1:16"); + assert_eq!(data(&rows)[4], "rtmpage:opencode-1:1"); + // A page past the end shows the last one. + assert_eq!( + model_rows("opencode-1", &models, "", 9), + rows_of(&models, 2) + ); + let rows = model_rows("opencode-1", &models, "", 1); + assert_eq!(labels(&rows)[8], ["‹ Back", "More › (2/3)"]); + for (d, want) in [ + ( + "rtmodel:opencode-1:12", + RuntimePress::Model("opencode-1", 12), + ), + ( + "rtmpage:opencode-1:2", + RuntimePress::ModelPage("opencode-1", 2), + ), + ] { + assert_eq!(RuntimePress::parse(d), Some(want), "{d}"); + } + assert_eq!(RuntimePress::parse("rtmodel:opencode-1:x"), None); + assert_eq!( + crate::runtime_views::model_set_text("opencode-1", "openrouter", "z-ai/glm-5"), + "OpenCode 1 runs OpenRouter on z-ai/glm-5 by default. A routing rule can still \ + name another model; pick again below to change it." + ); + fn rows_of(models: &[String], page: usize) -> Vec> { + model_rows("opencode-1", models, "", page) + } } /// One meter slot per line (store doc diff --git a/crates/axe/tests/layering.rs b/crates/axe/tests/layering.rs index 148b6d6..d354fb8 100644 --- a/crates/axe/tests/layering.rs +++ b/crates/axe/tests/layering.rs @@ -346,6 +346,10 @@ const TWINS: &[(&str, &str)] = &[ "runtime_check", r#"("POST", ["api", "runtimes", name, "check"])"#, ), + ( + "runtime_model", + r#"("POST", ["api", "runtimes", name, "model"])"#, + ), ("view", r#"("GET", ["api", "views", view])"#), ("form_submit", r#"("POST", ["api", "forms", id, "submit"])"#), ("task_exists", r#"("GET", ["api", "tasks", id])"#), diff --git a/crates/axe/tests/telegram.rs b/crates/axe/tests/telegram.rs index 451087d..c49e502 100644 --- a/crates/axe/tests/telegram.rs +++ b/crates/axe/tests/telegram.rs @@ -4773,7 +4773,16 @@ fn every_open_form_in_a_chat_keeps_its_button() { /// A local provider stand-in for key checks: 200 for `good`, else 401. fn key_mock(good: &'static str) -> String { + key_mock_of(&[good]) +} + +/// [`key_mock`] taking any of the keys `good`. A request with one gets a +/// model list (DeepSeek's documented shape, +/// https://api-docs.deepseek.com/api/list-models), except OpenRouter's +/// model list, which answers 503 (a list that failed). +fn key_mock_of(good: &[&'static str]) -> String { use std::io::{BufRead, BufReader, Write}; + let good = good.to_vec(); let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let base = format!("http://{}", l.local_addr().unwrap()); std::thread::spawn(move || { @@ -4781,17 +4790,28 @@ fn key_mock(good: &'static str) -> String { let Ok(mut s) = s else { break }; let mut r = BufReader::new(s.try_clone().unwrap()); let mut ok = false; + let mut first = String::new(); loop { let mut line = String::new(); if r.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" { break; } - ok |= line - .trim() - .eq_ignore_ascii_case(&format!("authorization: Bearer {good}")); + if first.is_empty() { + first = line.clone(); + } + ok |= good.iter().any(|g| { + line.trim() + .eq_ignore_ascii_case(&format!("authorization: Bearer {g}")) + }); } + const MODELS: &str = r#"{"object":"list","data":[ + {"id":"deepseek-flash","object":"model","owned_by":"deepseek"}, + {"id":"deepseek-v4-pro","object":"model","owned_by":"deepseek"}]}"#; let (status, body) = match ok { - true => ("200 OK", r#"{"object":"list","data":[]}"#), + true if first.contains("supported_parameters") => { + ("503 Service Unavailable", r#"{"error":"down"}"#) + } + true => ("200 OK", MODELS), false => ("401 Unauthorized", r#"{"error":"invalid key"}"#), }; let _ = write!( @@ -4813,6 +4833,8 @@ fn key_mock(good: &'static str) -> String { #[test] fn opencode_sets_up_from_telegram_with_a_provider_key() { const GOOD: &str = "good-deepseek-key-0123456789"; + // Built here, not spelled out: a literal looks like a real key. + let or_good: &'static str = Box::leak(format!("sk-or-v1-{}", "1".repeat(64)).into_boxed_str()); let dir = tempfile::tempdir().unwrap(); let reg = dir.path().join("runtimes"); std::fs::create_dir_all(®).unwrap(); @@ -4823,7 +4845,7 @@ fn opencode_sets_up_from_telegram_with_a_provider_key() { )); rig.srv().ok(&["bot", "pause", "cos"]); rig.add_bot("aux"); - let base = key_mock(GOOD); + let base = key_mock_of(&[GOOD, or_good]); let _disp = rig .srv() .dispatcher(&[], &[(axe::runtime::KEY_CHECK_BASE_ENV, base.as_str())]); @@ -4901,13 +4923,20 @@ fn opencode_sets_up_from_telegram_with_a_provider_key() { .starts_with("Set up OpenCode 1\n"), "{pick}" ); + // Every provider of the table, none first-class, and Other…. assert_eq!( keyboard_of(&pick), kb(&[ &[ ("DeepSeek", "rtkey:opencode-1:deepseek"), - ("OpenRouter", "rtkey:opencode-1:openrouter") + ("OpenRouter", "rtkey:opencode-1:openrouter"), + ("OpenAI", "rtkey:opencode-1:openai") + ], + &[ + ("Anthropic", "rtkey:opencode-1:anthropic"), + ("Google Gemini", "rtkey:opencode-1:google") ], + &[("Other…", "rtkey:opencode-1:other")], &[("Cancel", "rtx:opencode-1")] ]) ); @@ -4970,16 +4999,70 @@ fn opencode_sets_up_from_telegram_with_a_provider_key() { let spec = form_of(1); submit(107, &spec, GOOD); let ready = card("OpenCode 1 is ready with DeepSeek (deepseek-flash)."); + assert!( + ready["text"] + .as_str() + .unwrap() + .contains("Pick its default model below; deepseek-flash until you do."), + "{ready}" + ); + // The model pick: DeepSeek's live list, the suggested model first. assert_eq!( keyboard_of(&ready), - kb(&[&[("Routing →", "rtroute"), ("Done", "rtdone")]]) + kb(&[ + &[("• deepseek-flash", "rtmodel:opencode-1:0")], + &[("deepseek-v4-pro", "rtmodel:opencode-1:1")], + &[("Routing →", "rtroute"), ("Done", "rtdone")] + ]) ); let home = reg.join("opencode-1/home"); - let config: Value = + let config_of = || -> Value { serde_json::from_slice(&std::fs::read(home.join("config/opencode/opencode.json")).unwrap()) - .unwrap(); + .unwrap() + }; + let config = config_of(); assert_eq!(config["model"], "deepseek/deepseek-flash"); assert_eq!(config["update"], "disable"); + // Pick deepseek-v4-pro: the runtime's default model, the card edited. + wait_for("the ready card recorded", 20, || { + rig.messages() + .last() + .is_some_and(|m| m.2.starts_with("OpenCode 1 is ready")) + }); + let ready_tg = rig.messages().last().unwrap().3; + let toasts = rig.stub.calls("answerCallbackQuery").len(); + press_on(150, ready_tg, "rtmodel:opencode-1:1"); + let picked = edit_of(&rig, ready_tg, 1); + assert_eq!( + picked["text"], + "OpenCode 1 runs DeepSeek on deepseek-v4-pro by default. A routing rule can still name \ + another model; pick again below to change it." + ); + assert_eq!( + keyboard_of(&picked), + kb(&[ + &[("deepseek-flash", "rtmodel:opencode-1:0")], + &[("• deepseek-v4-pro", "rtmodel:opencode-1:1")], + &[("Routing →", "rtroute"), ("Done", "rtdone")] + ]) + ); + let toast = rig.stub.calls("answerCallbackQuery")[toasts].params.clone(); + assert_eq!( + toast["text"], "OpenCode 1 runs deepseek-v4-pro by default", + "{toast}" + ); + let config = config_of(); + assert_eq!(config["model"], "deepseek/deepseek-v4-pro"); + assert_eq!( + config["provider"]["deepseek"], + json!({"models": {"deepseek-v4-pro": {}}}) + ); + let state: Value = + serde_json::from_slice(&std::fs::read(reg.join("opencode-1/state.json")).unwrap()).unwrap(); + assert_eq!(state["models"], json!({"deepseek": "deepseek-v4-pro"})); + wait_for("the model reported", 20, || { + rig.srv().get("/api/runtimes")["runtimes"][0]["providers"][0]["model"] == "deepseek-v4-pro" + }); assert_eq!( std::fs::read_to_string(reg.join("opencode-1/login/DEEPSEEK_API_KEY")).unwrap(), GOOD @@ -4991,7 +5074,7 @@ fn opencode_sets_up_from_telegram_with_a_provider_key() { }); // Add provider: OpenRouter with a wrong key; it keeps DeepSeek. - press_on(108, list_tg, "rtacct:opencode-1"); + press_on(151, list_tg, "rtacct:opencode-1"); let detail = edit_of(&rig, list_tg, 6); assert!( detail["text"] @@ -5004,18 +5087,24 @@ fn opencode_sets_up_from_telegram_with_a_provider_key() { keyboard_of(&detail)[0], [("Add provider".to_string(), "rtprov:opencode-1".to_string())] ); - press_on(109, list_tg, "rtprov:opencode-1"); + press_on(152, list_tg, "rtprov:opencode-1"); let more = edit_of(&rig, list_tg, 7); assert_eq!( keyboard_of(&more), kb(&[ - &[("OpenRouter", "rtkey:opencode-1:openrouter")], + &[ + ("OpenRouter", "rtkey:opencode-1:openrouter"), + ("OpenAI", "rtkey:opencode-1:openai"), + ("Anthropic", "rtkey:opencode-1:anthropic") + ], + &[("Google Gemini", "rtkey:opencode-1:google")], + &[("Other…", "rtkey:opencode-1:other")], &[("Back", "rtacct:opencode-1")] ]) ); - press_on(110, list_tg, "rtlogin:opencode-1:api_key:openrouter"); + press_on(153, list_tg, "rtlogin:opencode-1:api_key:openrouter"); let spec = form_of(2); - submit(111, &spec, &format!("sk-or-v1-{}", "0".repeat(64))); + submit(154, &spec, &format!("sk-or-v1-{}", "0".repeat(64))); let failed = card("OpenCode 1: the OpenRouter key didn't work."); assert_eq!( keyboard_of(&failed), @@ -5030,6 +5119,79 @@ fn opencode_sets_up_from_telegram_with_a_provider_key() { .srv() .ok(&["runtimes", "list"]) .contains("opencode-1 (opencode): ok")); + + // A working OpenRouter key whose model list fails (503): ready on the + // row's default model, no pick. + press_on(155, list_tg, "rtlogin:opencode-1:api_key:openrouter"); + let spec = form_of(3); + submit(156, &spec, or_good); + let ready = card("OpenCode 1 is ready with OpenRouter (~anthropic/claude-sonnet-latest)."); + assert!( + ready["text"].as_str().unwrap().contains( + "\nIts model list didn't load (HTTP 503), so it runs \ + ~anthropic/claude-sonnet-latest. A routing rule can name another model." + ), + "{ready}" + ); + assert_eq!( + keyboard_of(&ready), + kb(&[&[("Routing →", "rtroute"), ("Done", "rtdone")]]) + ); + + // Other…: any OpenAI-compatible server by its base URL and key, in one + // sealed form; its first listed model until the owner picks. + press_on(157, list_tg, "rtkey:opencode-1:other"); + let other = edit_of(&rig, list_tg, 10); + assert!( + other["text"] + .as_str() + .unwrap() + .starts_with("OpenCode 1 · Other provider\nAny server with an OpenAI-compatible API"), + "{other}" + ); + assert_eq!( + keyboard_of(&other), + kb(&[&[ + ("Paste URL + key", "rtlogin:opencode-1:api_key:other"), + ("Cancel", "rtx:opencode-1") + ]]) + ); + press_on(158, list_tg, "rtlogin:opencode-1:api_key:other"); + let spec = form_of(4); + let names: Vec<&str> = spec.fields.iter().map(|f| f.name.as_str()).collect(); + assert_eq!(names, ["base_url", "secret"]); + let sealed = axe::sealed::seal( + &spec, + &json!({"base_url": "https://llm.example.test/v1", "secret": GOOD}), + ) + .unwrap(); + rig.stub.push_to( + AUX_TOKEN, + json!({"update_id": 159, "message": { + "message_id": 859, "date": 0, "from": user(OWNER), + "chat": {"id": OWNER, "type": "private"}, + "web_app_data": {"data": sealed.text(), "button_text": "Open sealed form"}}}), + ); + rig.stub.wait_confirmed(159); + let ready = card("OpenCode 1 is ready with Other (deepseek-flash)."); + assert_eq!( + keyboard_of(&ready)[0], + [( + "• deepseek-flash".to_string(), + "rtmodel:opencode-1:0".to_string() + )] + ); + assert_eq!( + std::fs::read_to_string(reg.join("opencode-1/login/OTHER_BASE_URL")).unwrap(), + "https://llm.example.test/v1" + ); + let config = config_of(); + assert_eq!( + config["provider"]["other"], + json!({"npm": "@ai-sdk/openai-compatible", "name": "Other", "env": ["OTHER_API_KEY"], + "options": {"baseURL": "https://llm.example.test/v1"}, + "models": {"deepseek-flash": {}}}) + ); } /// Claude on another provider from Telegram (store doc @@ -5098,6 +5260,7 @@ fn claude_logs_in_to_another_provider_from_telegram() { ("DeepSeek", "rtkey:claude-1:deepseek"), ("OpenRouter", "rtkey:claude-1:openrouter") ], + &[("Other…", "rtkey:claude-1:other")], &[("Back", "rtlogin:claude-1")] ]) ); diff --git a/docs/user/concepts/runtimes.md b/docs/user/concepts/runtimes.md index cd5281f..2555ae9 100644 --- a/docs/user/concepts/runtimes.md +++ b/docs/user/concepts/runtimes.md @@ -47,15 +47,24 @@ or needs_login, or its weekly quota reaching 80%, sends the owner one card login and always healthy. **Providers.** A provider is who serves and bills the model; the provider -table holds one row each (`provider.rs`: `deepseek`, `openrouter`), with the -variable the key is read from, the key's format, a free key check (`GET` -with the key as a bearer: 200 is a working key, 401 a wrong one), and the -harnesses that can use it; `axe runtimes add --help`, `axe runtimes login +table holds one row each (`provider.rs`: `deepseek`, `openrouter`, `openai`, +`anthropic`, `google`, and `other`), with the variable the key is read +from, the key's format, a free key check (`GET` with the key as a bearer, +or in a header such as Gemini's `x-goog-api-key`: 200 is a working key, 401 +or 403 a wrong one, and 400 for Gemini), its model list (the model pick +after a login, see +[runtimes from Telegram](../guides/runtimes-from-telegram.md)), and the +harnesses that can use it. `other` (*Other…*) is any OpenAI-compatible +server the owner names by its base URL, kept beside the key +(`/login/OTHER_BASE_URL`); its key check and model list are +`/models` (`/v1/models` on Claude Code's Anthropic-compatible +URL). `openai`, `anthropic` and `google` are for OpenCode and Pi; Claude +takes an Anthropic key as its own API key login; `axe runtimes add --help`, `axe runtimes login --help` and `axe rule add --help` list the harnesses and providers from these rows. A harness row says which providers it takes (`Harness::providers`): Claude takes Anthropic by its own logins, or the key -of one row with an Anthropic-Messages endpoint (`anthropic_url`); Codex takes -OpenAI only. `axe runtimes login --method api_key --provider +of one row with an Anthropic-Messages endpoint (`anthropic_url`) or of +`other`; Codex takes OpenAI only. `axe runtimes login --method api_key --provider --bot ` sends the owner a sealed form for that provider's key (`sealed::Target::Runtime` carries the `provider`; a harness that does not take it is refused before the form is sent, and again by the node). The key is @@ -65,7 +74,8 @@ replaces the last login like any other, and the run gets `ANTHROPIC_BASE_URL`, the key as `ANTHROPIC_AUTH_TOKEN` (a bearer), the row's model per tier (`ANTHROPIC_DEFAULT_*_MODEL`, `CLAUDE_CODE_SUBAGENT_MODEL`) and an empty `ANTHROPIC_API_KEY`, never an Anthropic credential -(`Runtime::env`). A rule's model that is none of the row's tier models +(`Runtime::env`); a model the owner picked that is not the row's default +(or any `other` model) takes every tier. A rule's model that is none of the row's tier models (`claude-code:openrouter/deepseek/deepseek-v4-flash`) takes every tier, so Claude Code's background and subagent calls stay on it (`runtime::tier_env`). From Telegram this login is *Other provider…* @@ -79,13 +89,16 @@ runtime (ids and states only). verified on 2.4.3: `Harness::package`) as `opencode run --standalone --format json --auto --title axe -s ses_ `: a private server per run, and `-s` creates the session on the first run and resumes it -after. It takes the provider table (`deepseek`, `openrouter`): one key per -provider, each checked by its key check, which is also the probe. A runtime +after. It takes the provider table (`deepseek`, `openrouter`, `openai`, +`anthropic`, `google`, `other`): one key per provider, each checked by its key check, which is also the probe. A runtime keeps everything OpenCode writes under its own login directory through the four XDG variables (`config`, `data`, `state`, `cache` under `//home`), shares nothing with `~/.config/opencode`, and axe writes its `config/opencode/opencode.json` (`harness::ConfigFile`): the -first held provider's default model (`deepseek/deepseek-flash`) and +first held provider's model (the owner's pick, else the row's default: +`deepseek/deepseek-flash`), each held model declared under its provider +(OpenCode refuses a model its catalog does not list yet), `other` as an +`@ai-sdk/openai-compatible` provider on its base URL, and `"update": "disable"`, never a key; it is rewritten when a key is added or dropped and when the node loads the registry. Keys reach OpenCode as environment variables (`DEEPSEEK_API_KEY`), where its built-in providers read @@ -102,12 +115,14 @@ verified on 1.7.0: `Harness::package`) as `pi --mode json -p --no-approve session on the first run and resumes it after, `--no-approve` ignores Pi files in the run folder, and `--offline` skips Pi's startup update check and catalog refresh. It takes the same provider table as OpenCode -(`deepseek`, `openrouter`), one key per provider, with the same setup. A +(every row), one key per provider, with the same setup. A runtime points `PI_CODING_AGENT_DIR` at `//home/agent`, shares nothing with `~/.pi`, and axe writes its `agent/settings.json` (`harness::ConfigFile`): the first held provider as `defaultProvider` and -its default model as `defaultModel`, never a key. Keys reach Pi as -environment variables (`DEEPSEEK_API_KEY`, `OPENROUTER_API_KEY`). A bot's +its model as `defaultModel`, and `agent/models.json` with `other` as an +`openai-completions` provider on its base URL, never a key. Keys reach Pi as +environment variables (`DEEPSEEK_API_KEY`, `OPENROUTER_API_KEY`, +`GEMINI_API_KEY`, ...). A bot's system prompt goes in as `--append-system-prompt ` on every run (`Harness::bot_args`), a rule's model as `--model provider/model` and its effort as `--thinking `. Pi exits 0 even when the provider fails, so @@ -134,4 +149,6 @@ both (`harness.rs`). An entry naming no provider (`claude-code`, Claude and Codex picks are as before. A runtime picked by a pin, a bot's primary or backup, a resumed session or failover gets the rule's first entry for its harness that it serves, else its own default model, never a model -it has no login for (`RuntimeConfig::with`). +it has no login for (`RuntimeConfig::with`). A runtime's own default on a +provider is the model the owner picked after its key login, else the +row's default (`Runtime::model_of`). diff --git a/docs/user/guides/runtimes-from-telegram.md b/docs/user/guides/runtimes-from-telegram.md index 96553b8..42b8407 100644 --- a/docs/user/guides/runtimes-from-telegram.md +++ b/docs/user/guides/runtimes-from-telegram.md @@ -112,24 +112,28 @@ on the others. takes precedence over the login directory. Or *Other provider…* (shown while a provider-table row has an Anthropic-Messages endpoint, `runtime_views::other_provider`): one button - per such row (DeepSeek, OpenRouter), then OpenCode's key screen and sealed - form for that provider's key (`telegram::provider_screen`, - `telegram::key_screen`); *Back* returns to the login methods. The key - replaces the runtime's login like any other, Claude Code reaches the - provider with it as a bearer token (see + per such row (DeepSeek, OpenRouter) and *Other…* (any Anthropic-compatible + base URL), then OpenCode's key screen and sealed form for that provider's + key (`telegram::provider_screen`, `telegram::key_screen`); *Back* returns + to the login methods. The key replaces the runtime's login like any + other, Claude Code reaches the provider with it as a bearer token (see [Runtimes](../concepts/runtimes.md), Providers), and the card says "Claude 2 - is ready with DeepSeek (deepseek-flash)." A rule names the provider to use - it (`claude-code:deepseek/deepseek-flash`); bare Claude rules keep to - Anthropic logins. + is ready with DeepSeek (deepseek-flash)." with the model pick (below). A + rule names the provider to use it (`claude-code:deepseek/deepseek-flash`); + bare Claude rules keep to Anthropic logins. - **Codex.** *Paste API key*: the key arrives in a sealed form and goes to `codex login --with-api-key` on stdin. Or *Device code*: `codex login --device-auth` runs on the node, and its link and code are relayed to the owner. - **OpenCode** (a runtime that holds one key per provider). *Set up OpenCode* (or *OpenCode* under *Add runtime*) adds `OpenCode 1` and asks - which provider first, one button per provider-table row it takes - (`telegram::provider_screen`); the provider's screen says where to get a - key, and *Paste API key* sends a sealed form with one field, that - provider's key (`runtime_login` with `--provider`). The node stores it, + which provider first, one button per provider-table row it takes, three a + row (DeepSeek, OpenRouter, OpenAI, Anthropic, Google Gemini), then + *Other…* on its own row (`telegram::provider_screen`); no provider comes + first. The provider's screen says where to get a key, and *Paste API key* + sends a sealed form with one field, that provider's key (`runtime_login` + with `--provider`). *Other…* takes any OpenAI-compatible server: + *Paste URL + key* sends one sealed form with its base URL (`https://`, or `http://` + to `localhost` on the node; `provider::check_base_url`) and its key. The node stores it, rewrites the runtime's `opencode.json` and checks the key at once with the provider's free key check. The card says "OpenCode 1 is ready with DeepSeek (deepseek-flash)." or "OpenCode 1: the DeepSeek key didn't work. @@ -143,6 +147,24 @@ on the others. provider and key screens); the node rewrites the runtime's Pi `settings.json` instead. +**Model pick.** A provider key that passes its check also loads that +provider's model list with the key (`provider::list_models`, the row's +`models` call: OpenRouter's lists only models that take tools, Gemini's only +models that generate content), and the ready card offers it: the runtime's +current model first (the row's `default_model`, marked `•`), then the list, +newest first where the provider dates its models, at most 48, eight a page +with *‹ Back* and *More ›* (`telegram::model_rows`). A press makes that model +the runtime's default on that provider (`Axe::runtime_model`, +`POST /api/runtimes//model`, the node's `Registry::set_model`, kept +in `state.json` `models`): the node rewrites the runtime's config and the +card says "OpenCode 1 runs DeepSeek on deepseek-v4-pro by default."; pick +again on the same card to change it. A routing rule that names a model +still runs that model. If the list call fails, the card says so and the +runtime keeps the row's default model; *Other…* has no default, so it runs +its first listed model, and a server that lists none adds nothing. +The runtime report (`GET /api/runtimes`) has each provider's model +(`providers[].model`). + A login made this way is checked at once (`runtime::Registry::check_now`) and the outcome comes as a card: ready for all bots and tasks (and whether anything uses the runtime yet), or what the check said