From f84f7934bbc701d9a32791c898a81370786e0840 Mon Sep 17 00:00:00 2001 From: haojr Date: Wed, 2 Dec 2026 00:48:54 +0000 Subject: [PATCH] feat: drop the runtime default model; rules choose models Owner pick A (tn-cos #6541/#6548): a runtime stores no model of its own. Reverts the model pick of #281, keeping the provider -> key flow and rows. - remove the ready-card model pick (rtmodel/rtmpage buttons; old ones now answer with the retired toast), POST /api/runtimes//model, Axe::runtime_model, the node's runtime_model job, Registry::set_model, state.json `models` (an old file still loads; the field is dropped) and the provider model-list call (list_models, parse_models, choices) - a rule naming no model runs the provider row's default_model; the ready card says the runtime is ready with its provider and to ask the bot for another model; Other... has no default, so its card asks for one - before a run whose rule names a model, the runtime's OpenCode/Pi config declares it under its provider (Runtime::write_config_for): OpenCode refuses an undeclared model its catalog lacks, and Other's models are known only from the rule - runtime report: providers[] back to id and state - docs/user: runtimes concept and Telegram guide Co-Authored-By: Claude Opus 5.5 --- crates/axe-core/src/core.rs | 6 - crates/axe-core/src/harness.rs | 48 ++-- crates/axe-core/src/provider.rs | 287 ++----------------- crates/axe-core/src/runtime.rs | 307 ++++++++++----------- crates/axe-core/src/runtime_views.rs | 44 ++- crates/axe-core/src/sealed.rs | 5 +- crates/axe-node/src/dispatch.rs | 36 ++- crates/axe-node/src/dispatch/bots.rs | 6 + crates/axe-node/src/node_link.rs | 1 - crates/axe-server/src/server.rs | 29 +- crates/axe-telegram/src/telegram.rs | 241 +++------------- crates/axe/tests/layering.rs | 4 - crates/axe/tests/runtime_pick.rs | 123 +++++++++ crates/axe/tests/telegram.rs | 101 ++----- docs/user/concepts/runtimes.md | 39 +-- docs/user/guides/runtimes-from-telegram.md | 28 +- 16 files changed, 453 insertions(+), 852 deletions(-) diff --git a/crates/axe-core/src/core.rs b/crates/axe-core/src/core.rs index 3b213e1..8e04492 100644 --- a/crates/axe-core/src/core.rs +++ b/crates/axe-core/src/core.rs @@ -86,12 +86,6 @@ 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 cc8f40c..bfbcbbb 100644 --- a/crates/axe-core/src/harness.rs +++ b/crates/axe-core/src/harness.rs @@ -177,24 +177,27 @@ pub enum ConfigFile { } /// 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. +/// ([`ConfigFile::render`]): the provider, the models to declare on it +/// (its row's default first, then a run's rule model; +/// [`crate::runtime::Runtime::held`]) and, for `Other…`, its base URL. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Held { pub id: &'static str, - pub model: String, + pub models: Vec, 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). + /// A login of row `id` on its default model (tests). pub fn default_of(id: &'static str) -> Held { Held { id, - model: crate::provider::get(id) - .map_or("", |p| p.default_model) - .into(), + models: crate::provider::get(id) + .map(|p| p.default_model) + .filter(|m| !m.is_empty()) + .map(String::from) + .into_iter() + .collect(), base_url: None, } } @@ -210,7 +213,7 @@ impl ConfigFile { /// [`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 first = held.iter().find(|h| !h.models.is_empty()); let pretty = |v: &serde_json::Value| serde_json::to_string_pretty(v).expect("json") + "\n"; match self { ConfigFile::None => vec![], @@ -227,12 +230,14 @@ impl ConfigFile { "update": "disable", }); if let Some(h) = first { - v["model"] = format!("{}/{}", h.id, h.model).into(); + v["model"] = format!("{}/{}", h.id, h.models[0]).into(); } let mut providers = serde_json::Map::new(); - for h in held.iter().filter(|h| !h.model.is_empty()) { + for h in held.iter().filter(|h| !h.models.is_empty()) { let mut models = serde_json::Map::new(); - models.insert(h.model.clone(), serde_json::json!({})); + for m in &h.models { + models.insert(m.clone(), serde_json::json!({})); + } let mut p = serde_json::json!({"models": models}); if h.custom() { let Some(url) = &h.base_url else { continue }; @@ -260,10 +265,10 @@ impl ConfigFile { }); if let Some(h) = first { v["defaultProvider"] = h.id.into(); - v["defaultModel"] = h.model.clone().into(); + v["defaultModel"] = h.models[0].clone().into(); } let mut providers = serde_json::Map::new(); - for h in held.iter().filter(|h| h.custom() && !h.model.is_empty()) { + for h in held.iter().filter(|h| h.custom() && !h.models.is_empty()) { let (Some(url), Some(row)) = (&h.base_url, crate::provider::get(h.id)) else { continue; }; @@ -274,7 +279,7 @@ impl ConfigFile { "baseUrl": url, "api": "openai-completions", "apiKey": format!("${}", row.env), - "models": [{"id": h.model}], + "models": h.models.iter().map(|m| serde_json::json!({"id": m})).collect::>(), }), ); } @@ -816,24 +821,25 @@ mod tests { "deepseek": {"models": {"deepseek-flash": {}}}, "openrouter": {"models": {"~anthropic/claude-sonnet-latest": {}}}}}) ); - // The owner's pick, and `Other…` with its base URL. + // A rule's model declared beside the row's default, and `Other…` + // with its base URL and the model a rule names. let held = [ Held { id: "openai", - model: "gpt-6.2-astra".into(), + models: vec!["gpt-6.2-sol".into(), "gpt-6.2-astra".into()], base_url: None, }, Held { id: "other", - model: "qwen2.5-coder:7b".into(), + models: vec!["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["model"], "openai/gpt-6.2-sol"); assert_eq!( v["provider"]["openai"], - serde_json::json!({"models": {"gpt-6.2-astra": {}}}) + serde_json::json!({"models": {"gpt-6.2-sol": {}, "gpt-6.2-astra": {}}}) ); assert_eq!( v["provider"]["other"], @@ -873,7 +879,7 @@ mod tests { assert_eq!(m["providers"], serde_json::json!({})); let other = Held { id: "other", - model: "mock-b".into(), + models: vec!["mock-b".into()], base_url: Some("https://llm.example.com/v1".into()), }; let files = h.config.render(&[other]); diff --git a/crates/axe-core/src/provider.rs b/crates/axe-core/src/provider.rs index 19cb03e..5c17de7 100644 --- a/crates/axe-core/src/provider.rs +++ b/crates/axe-core/src/provider.rs @@ -17,7 +17,7 @@ pub struct ClaudeModels { pub subagent: &'static str, } -/// How a provider takes its key on the key check and the model list. +/// How a provider takes its key on the key check. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Auth { /// `Authorization: Bearer `. @@ -26,24 +26,9 @@ pub enum Auth { 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`). @@ -61,27 +46,21 @@ pub struct Provider { /// [`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. + /// How the key goes with the key check. 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. + /// (`Other…`): its key check is `/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 - /// and the owner picked none ([`crate::runtime::Health::models`]); the - /// suggested first pick. Empty on a custom row: its first listed model. + /// The model a runtime with this provider uses when a rule names none. + /// Empty on a custom row: a rule names its model. pub default_model: &'static str, /// The harnesses ([`crate::harness::Harness::name`]) that can use it. pub tools: &'static [&'static str], @@ -110,8 +89,6 @@ pub const PROVIDERS: &[Provider] = &[ 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", @@ -125,15 +102,12 @@ 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", @@ -143,9 +117,6 @@ pub const PROVIDERS: &[Provider] = &[ 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", @@ -175,8 +146,6 @@ pub const PROVIDERS: &[Provider] = &[ 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", @@ -204,8 +173,6 @@ pub const PROVIDERS: &[Provider] = &[ 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", @@ -231,8 +198,6 @@ pub const PROVIDERS: &[Provider] = &[ 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", @@ -242,8 +207,8 @@ pub const PROVIDERS: &[Provider] = &[ 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 + // with the key. Its key check is OpenAI's list models call on that URL + // (`/models`, bearer); for Claude // Code an Anthropic-compatible base URL (`ANTHROPIC_BASE_URL`), checked // with Anthropic's (`/v1/models`). Key format: any. Provider { @@ -255,8 +220,6 @@ pub const PROVIDERS: &[Provider] = &[ auth: Auth::Bearer, headers: &[], bad_key: &[401, 403], - models: "", - list: ModelList::Data, custom: true, balance: None, default_model: "", @@ -287,8 +250,6 @@ const TEST_PROVIDERS: &[Provider] = &[ 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", @@ -306,8 +267,6 @@ const TEST_PROVIDERS: &[Provider] = &[ auth: Auth::Bearer, headers: &[], bad_key: &[401, 403], - models: "https://acme2.test/models", - list: ModelList::Data, custom: false, balance: None, default_model: "big", @@ -367,11 +326,10 @@ impl Provider { } } - /// 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)> { + /// The key check of this row for a runtime: a custom row's on 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 check_call(&self, base: Option<&str>, anthropic: bool) -> Option { let call = |url: String, headers: Vec<(&'static str, &'static str)>| Call { url, auth: self.auth, @@ -379,11 +337,7 @@ impl Provider { 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), - )); + return Some(call(self.key_check.into(), self.headers.to_vec())); } let base = base?.trim_end_matches('/'); // Anthropic's list models call and its version header (`claude` @@ -395,7 +349,7 @@ impl Provider { ), false => (format!("{base}/models"), vec![]), }; - Some((call(url.clone(), h.clone()), call(url, h))) + Some(call(url, h)) } } @@ -523,78 +477,6 @@ pub fn check_key(call: &Call, 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::*; @@ -662,16 +544,15 @@ pub(crate) mod tests { 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 [p.balance, p.anthropic_url].into_iter().flatten().chain( - [p.key_check, p.models] - .into_iter() - .filter(|u| !u.is_empty()), - ) { + for u in [p.balance, p.anthropic_url] + .into_iter() + .flatten() + .chain([p.key_check].into_iter().filter(|u| !u.is_empty())) + { assert!(u.starts_with("https://"), "{n}: {u}"); } assert!(!p.bad_key.is_empty(), "{n}: bad key statuses"); @@ -690,7 +571,7 @@ pub(crate) mod tests { assert_eq!(get(OTHER).map(|p| p.custom), Some(true)); } - /// Each row's key check and model list, against a local mock on the + /// Each row's key check, 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] @@ -701,8 +582,7 @@ pub(crate) mod tests { true => (wrong, "{}".into()), false => (200, r#"{"data":[],"models":[]}"#.into()), }); - let (check, models) = p.calls(None, false).unwrap(); - let check = check.on(Some(&base)); + let check = p.check_call(None, false).unwrap().on(Some(&base)); assert_eq!( check_key(&check, "good-key-123", KEY_CHECK_TIMEOUT), KeyCheck::Ok, @@ -737,21 +617,6 @@ pub(crate) mod tests { 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(); @@ -771,125 +636,33 @@ pub(crate) mod tests { 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(); + let check = google.check_call(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(); + let check = get("openai").unwrap().check_call(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, + /// `Other…`: the key check 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!(p.check_call(None, false).is_none()); + let check = p + .check_call(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) + let check = p + .check_call(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")]); diff --git a/crates/axe-core/src/runtime.rs b/crates/axe-core/src/runtime.rs index 1200bec..dbfde71 100644 --- a/crates/axe-core/src/runtime.rs +++ b/crates/axe-core/src/runtime.rs @@ -163,11 +163,6 @@ 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 { @@ -197,7 +192,6 @@ impl Default for Health { login_at: None, added_at: None, providers: BTreeMap::new(), - models: BTreeMap::new(), } } } @@ -232,7 +226,7 @@ pub struct Runtime { } /// A card the owner should get: the runtime turned `state`. -#[derive(Debug, Clone, PartialEq, Default)] +#[derive(Debug, Clone, PartialEq)] pub struct Alert { pub runtime: String, pub harness: String, @@ -245,13 +239,6 @@ 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 { @@ -264,15 +251,6 @@ 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 } @@ -370,15 +348,9 @@ fn base_url_file(p: &crate::provider::Provider) -> &'static str { /// 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. -/// `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 { +/// `url` is `Other…`'s base URL; it has no tier models, so a rule names +/// its model ([`tier_env`]). +fn anthropic_env(p: &crate::provider::Provider, key: String, url: Option) -> LoginEnv { let mut set = vec![ ( "ANTHROPIC_BASE_URL", @@ -391,15 +363,13 @@ fn anthropic_env( ("ANTHROPIC_API_KEY", String::new()), ("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1".into()), ]; - match &p.claude_models { - Some(m) if model.is_empty() || model == p.default_model => set.extend([ + if let Some(m) = &p.claude_models { + 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"]) } @@ -557,8 +527,7 @@ impl Runtime { { // A provider login replaces the harness's own: its variables // only, never an Anthropic credential next to them. - let model = self.model_of(p.id); - let (s, r) = anthropic_env(p, key, self.base_url(p.id), &model); + let (s, r) = anthropic_env(p, key, self.base_url(p.id)); set.extend(s); remove.extend(r); return (set, remove); @@ -577,17 +546,6 @@ 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)?; @@ -611,24 +569,38 @@ impl Runtime { 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)> { + /// The key check of provider `p` for this runtime + /// ([`crate::provider::Provider::check_call`]). + pub fn check_call(&self, p: &crate::provider::Provider) -> Option { let anthropic = crate::harness::get(&self.harness).is_some_and(|h| !h.accumulates()); - p.calls(self.base_url(p.id).as_deref(), anthropic) + p.check_call(self.base_url(p.id).as_deref(), anthropic) } - /// The provider logins it holds, for its config file. - pub fn held(&self) -> Vec { + /// The provider logins it holds, for its config file: each on its + /// row's default model, and the model `with` names declared under its + /// provider (a run's rule; `Other…` has no default, so only a rule's). + pub fn held(&self, with: Option<&crate::rule::Use>) -> Vec { + let named = with.and_then(|u| Some((u.provider()?.id, u.model.as_deref()?))); self.providers() .into_iter() - .map(|id| crate::harness::Held { - id, - model: self.model_of(id), - base_url: self.base_url(id), + .map(|id| { + let row = crate::provider::get(id).map_or("", |p| p.default_model); + let mut models: Vec = Some(row.to_string()) + .filter(|m| !m.is_empty()) + .into_iter() + .collect(); + if let Some((_, m)) = named.filter(|(p, _)| *p == id) { + // `provider/model`: the model after the provider. + let bare = m.split_once('/').map_or(m, |(_, rest)| rest); + if !models.iter().any(|x| x == bare) { + models.push(bare.to_string()); + } + } + crate::harness::Held { + id, + models, + base_url: self.base_url(id), + } }) .collect() } @@ -828,10 +800,18 @@ impl Runtime { /// logins it holds. Nothing for a harness with no such file, or a /// runtime on the CLI's default directory (the owner's own config). pub fn write_config(&self) -> Result<()> { + self.write_config_for(None) + } + + /// [`Runtime::write_config`] before a run of `with`: a model its rule + /// names is declared under its provider too ([`Runtime::held`]), since + /// OpenCode refuses a model its catalog lacks unless declared, and + /// `Other…`'s models are known only from the rule. + pub fn write_config_for(&self, with: Option<&crate::rule::Use>) -> Result<()> { let (Some(h), Some(dir)) = (crate::harness::get(&self.harness), &self.login_dir) else { return Ok(()); }; - for (rel, text) in h.config.render(&self.held()) { + for (rel, text) in h.config.render(&self.held(with)) { let path = dir.join(rel); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent) @@ -1120,14 +1100,7 @@ pub struct Registry { /// key checks of a runtime with key logins (a thread). enum Probe { Cmd(Child), - 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>>, + Keys(std::sync::mpsc::Receiver>), } impl Probe { @@ -1514,7 +1487,6 @@ impl Registry { until: None, quota: None, provider: Some(p), - ..Default::default() }); } let (state, until) = match f.class { @@ -1546,7 +1518,6 @@ impl Registry { until, quota: None, provider: None, - ..Default::default() }); if let Err(e) = rt.save() { eprintln!("axe node: runtime {name}: {e:#}"); @@ -1592,7 +1563,6 @@ impl Registry { until: Some(window), quota: Some(quota), provider: None, - ..Default::default() }; self.nearly_out.insert(name.to_string(), window); Some(alert) @@ -1649,7 +1619,6 @@ impl Registry { until: None, quota: None, provider: None, - ..Default::default() }), Err(e) => { eprintln!("axe node: runtime {name}: remove after a failed Add: {e:#}"); @@ -1712,37 +1681,24 @@ impl Registry { let keys: Vec<_> = rt .provider_keys() .into_iter() - .map(|(p, key)| (p, key, rt.calls(p))) + .map(|(p, key)| (p, key, rt.check_call(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 || { - use crate::provider::{check_key, list_models, KeyCheck}; + use crate::provider::{check_key, 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 out: Vec<_> = keys + .into_iter() + .map(|(p, key, check)| match check { + None => (p.id, KeyCheck::Bad("no base URL is stored".into())), + Some(c) => (p.id, check_key(&c.on(base.as_deref()), &key, timeout)), + }) + .collect(); let _ = tx.send(out); }); self.probed.insert(name.to_string(), Instant::now()); @@ -1818,9 +1774,9 @@ impl Registry { } }, Probe::Keys(rx) => match rx.try_recv() { - Ok(k) => { - let (ok, status) = key_outcome(&k.checks); - done.push((name.clone(), ok, status, *at, Some(k))); + Ok(checks) => { + let (ok, status) = key_outcome(&checks); + done.push((name.clone(), ok, status, *at, Some(checks))); } Err(std::sync::mpsc::TryRecvError::Empty) if !late => {} Err(_) => done.push((name.clone(), false, timed_out(), *at, None)), @@ -1828,12 +1784,10 @@ impl Registry { } } let mut alerts = std::mem::take(&mut self.ready); - for (name, mut ok, mut status, at, probe) in done { + for (name, mut ok, mut status, at, checks) in done { self.probes.remove(&name); let new_key = self.new_keys.remove(&name); - let mut models = None; - if let Some(probe) = probe { - let checks = probe.checks; + if let Some(checks) = 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(); @@ -1841,42 +1795,17 @@ 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); } @@ -1901,30 +1830,6 @@ 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) { @@ -1934,11 +1839,6 @@ 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"); } @@ -2032,7 +1932,6 @@ impl Registry { until: None, quota: None, provider: None, - ..Default::default() }) } @@ -2065,9 +1964,6 @@ 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), }) @@ -2791,7 +2687,7 @@ exit 2 let hb = reg.heartbeat(|_| 0, 0); assert_eq!( hb["list"][0]["providers"], - json!([{"id": "deepseek", "state": "ok", "model": "deepseek-flash"}]) + json!([{"id": "deepseek", "state": "ok"}]) ); assert!(!hb.to_string().contains(DS)); @@ -2912,8 +2808,8 @@ exit 2 let hb = reg.heartbeat(|_| 0, 0); assert_eq!( hb["list"][0]["providers"], - json!([{"id": "acme", "state": "ok", "model": "acme-1"}, - {"id": "acme2", "state": "needs_login", "model": "big"}]) + json!([{"id": "acme", "state": "ok"}, + {"id": "acme2", "state": "needs_login"}]) ); // Persisted with the runtime's health; an older file without it loads. let saved: Health = @@ -3032,6 +2928,81 @@ exit 2 let reg = Registry::load(&cfg).unwrap(); assert!(reg.get("opencode-1").is_some()); assert_eq!(read()["model"], "deepseek/deepseek-flash"); + + // A run whose rule names a model declares it beside the row's + // default; the config's default stays the row's, nothing stored. + let rt = reg.get("opencode-1").unwrap(); + let rule = |m: &str| crate::rule::Use { + harness: "opencode".into(), + model: Some(m.into()), + effort: None, + }; + rt.write_config_for(Some(&rule("deepseek/deepseek-v4-pro"))) + .unwrap(); + assert_eq!(read()["model"], "deepseek/deepseek-flash"); + assert_eq!( + read()["provider"]["deepseek"], + serde_json::json!({"models": {"deepseek-flash": {}, "deepseek-v4-pro": {}}}) + ); + // A model on a provider it holds no key for declares nothing. + rt.write_config_for(Some(&rule("openrouter/openai/gpt-6.2-sol"))) + .unwrap(); + assert!(read()["provider"].get("openrouter").is_none()); + let state = + std::fs::read_to_string(tmp.path().join("runtimes/opencode-1/state.json")).unwrap(); + assert!(!state.contains("models"), "{state}"); + } + + /// A `state.json` from a version that stored a picked model per + /// provider (`models`, axe#281) still loads; the field is dropped. + #[test] + fn a_stored_model_pick_is_ignored() { + let h: Health = serde_json::from_str( + r#"{"state":"ok","providers":{"openrouter":"ok"},"models":{"openrouter":"openai/gpt-6.2-sol"}}"#, + ) + .unwrap(); + assert_eq!(h.state, OK); + assert!(!serde_json::to_string(&h).unwrap().contains("models")); + } + + /// `Other…` has no default model: its config declares the provider + /// only before a run whose rule names its model. + #[test] + fn other_is_declared_with_the_model_a_rule_names() { + let tmp = tempfile::tempdir().unwrap(); + let (cfg, reg) = registry(tmp.path()); + let mut reg = reg; + assert_eq!(reg.create(&cfg, "opencode").unwrap(), "opencode-1"); + let rt = reg.get("opencode-1").unwrap().clone(); + rt.set_base_url(crate::provider::OTHER, "https://llm.example.test/v1") + .unwrap(); + rt.login(&cfg, "api_key", Some(crate::provider::OTHER), "k-123") + .unwrap(); + assert_eq!(rt.providers(), [crate::provider::OTHER]); + let config = tmp + .path() + .join("runtimes/opencode-1/home/config/opencode/opencode.json"); + let read = + || -> Value { serde_json::from_slice(&std::fs::read(&config).unwrap()).unwrap() }; + assert!(read().get("model").is_none(), "{}", read()); + assert!(read().get("provider").is_none(), "{}", read()); + let with = crate::rule::Use { + harness: "opencode".into(), + model: Some("other/qwen2.5-coder".into()), + effort: None, + }; + let held = rt.held(Some(&with)); + assert_eq!(held[0].models, ["qwen2.5-coder"]); + rt.write_config_for(Some(&with)).unwrap(); + assert_eq!(read()["model"], "other/qwen2.5-coder"); + assert_eq!( + read()["provider"]["other"]["models"], + serde_json::json!({"qwen2.5-coder": {}}) + ); + assert_eq!( + read()["provider"]["other"]["options"]["baseURL"], + "https://llm.example.test/v1" + ); } /// A Pi runtime from Add: its own agent directory with the settings axe @@ -3733,8 +3704,8 @@ exit 2 let hb = reg.heartbeat(|_| 0, now); assert_eq!( hb["list"][0]["providers"], - json!([{"id": "acme", "state": "unchecked", "model": "acme-1"}, - {"id": "acme2", "state": "out_of_credit", "model": "big"}]) + json!([{"id": "acme", "state": "unchecked"}, + {"id": "acme2", "state": "out_of_credit"}]) ); // 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 6af323c..fc04cd1 100644 --- a/crates/axe-core/src/runtime_views.rs +++ b/crates/axe-core/src/runtime_views.rs @@ -377,17 +377,6 @@ pub fn provider_text(name: &str, harness: &str, first: bool) -> 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 { @@ -399,7 +388,7 @@ pub fn key_text(name: &str, id: &str, anthropic: bool) -> String { 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.", + form that only your node can read.", display(name) ); } @@ -771,22 +760,21 @@ 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 = 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." - )); - } + let model = crate::provider::get(id).map_or("", |p| p.default_model); + // Models come from routing rules, which the owner sets by + // asking the bot; a row's default runs when a rule names none. + let head = match model { + "" => format!( + "{n} is ready with {}. It has no default model: tell me which model to \ + run on it (e.g. \"run research tasks on {n} with model X\").", + provider_label(id) + ), + m => format!( + "{n} is ready with {} ({m}). For another model, tell me which (e.g. \"run \ + research tasks on {n} with model X\").", + provider_label(id) + ), + }; 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 68cb78b..69c75ac 100644 --- a/crates/axe-core/src/sealed.rs +++ b/crates/axe-core/src/sealed.rs @@ -1527,8 +1527,7 @@ impl Desk { self } - /// The desk handing registry changes (`runtime_add`, `runtime_remove`, - /// `runtime_model`) + /// The desk handing registry changes (`runtime_add`, `runtime_remove`) /// 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); @@ -1586,7 +1585,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" | "runtime_model") => self.runtime_job(q), + Some("runtime_add" | "runtime_remove") => self.runtime_job(q), Some("runtime_check") => self.check(q), _ => Err(anyhow::anyhow!("unknown form job")), }; diff --git a/crates/axe-node/src/dispatch.rs b/crates/axe-node/src/dispatch.rs index f66abe2..f09dc41 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 model on its first -/// provider (`harness::ConfigFile`, `Runtime::model_of`). Recorded with the run's usage +/// model, else the runtime's config default, its first provider's row +/// default (`harness::ConfigFile`). 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,9 @@ 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 its model on that - // provider; any other runs its own default. + // A runtime holding several providers' keys runs that provider's + // default model; any other runs its own default. let table = crate::harness::get(&rt.harness).is_some_and(|h| h.accumulates()); + // `Other…` has no default: the model the failed rule named on it. let with = provider.filter(|_| table).map(|p| Use { harness: rt.harness.clone(), - model: Some(format!("{}/{}", p.id, rt.model_of(p.id))), + model: match p.default_model { + "" => down + .iter() + .find(|(_, u)| u.provider().is_some_and(|q| q.id == p.id)) + .and_then(|(_, u)| u.model.clone()), + m => Some(format!("{}/{m}", p.id)), + }, effort: None, }); Some(Pick { @@ -813,15 +822,6 @@ 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); @@ -1703,6 +1703,12 @@ impl Dispatcher { env.push(("AXE_WORKTREE", cwd.display().to_string())); // The runtime's login: its directory variable, or none for the default. let started_at = now_unix(); + // A model the rule names is declared in the runtime's config first. + if with.is_some_and(|u| u.model.is_some()) { + if let Err(e) = rt.write_config_for(with) { + eprintln!("axe node: runtime {}: config: {e:#}", rt.name); + } + } let (login, unset) = rt.env(); env.extend(login); env.extend(crate::runtime::tier_env(with)); diff --git a/crates/axe-node/src/dispatch/bots.rs b/crates/axe-node/src/dispatch/bots.rs index a854b3b..72cf383 100644 --- a/crates/axe-node/src/dispatch/bots.rs +++ b/crates/axe-node/src/dispatch/bots.rs @@ -457,6 +457,12 @@ impl Dispatcher { } env.push(("AXE_WORKTREE", cwd.display().to_string())); let started_at = super::now_unix(); + // A model the rule names is declared in the runtime's config first. + if with.as_ref().is_some_and(|u| u.model.is_some()) { + if let Err(e) = rt.write_config_for(with.as_ref()) { + eprintln!("axe node: runtime {}: config: {e:#}", rt.name); + } + } let (login, unset) = rt.env(); env.extend(login); env.extend(crate::runtime::tier_env(with.as_ref())); diff --git a/crates/axe-node/src/node_link.rs b/crates/axe-node/src/node_link.rs index ac92add..17ea0c2 100644 --- a/crates/axe-node/src/node_link.rs +++ b/crates/axe-node/src/node_link.rs @@ -430,7 +430,6 @@ 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 74d98cd..43b2f98 100644 --- a/crates/axe-server/src/server.rs +++ b/crates/axe-server/src/server.rs @@ -192,15 +192,6 @@ 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"); @@ -313,8 +304,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() { @@ -2007,13 +1998,6 @@ 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, @@ -2920,15 +2904,6 @@ 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})) diff --git a/crates/axe-telegram/src/telegram.rs b/crates/axe-telegram/src/telegram.rs index 1864591..38aa2e9 100644 --- a/crates/axe-telegram/src/telegram.rs +++ b/crates/axe-telegram/src/telegram.rs @@ -122,10 +122,8 @@ 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), -/// `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 +/// `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 /// replies with the screen. Routing has no buttons of its own: the owner /// asks the bot in free text. const RUNTIMES_BUTTON: &str = "runtimes"; @@ -141,13 +139,13 @@ 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-"]; +/// backup, cancel a removal) and of the retired ready-card model pick +/// (models come from routing rules): a press on an old message only gets +/// a toast. +const RETIRED_BUTTONS: &[&str] = &[ + "rtpri:", "rtbak:", "rtbak-", "rtrm-", "rtmodel:", "rtmpage:", +]; const RETIRED_TOAST: &str = "This button is retired: /runtimes lists your runtimes; tell me to change routing."; /// Callback data prefix of the `/cost` reply's buttons: `cost:` @@ -176,10 +174,6 @@ 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, @@ -203,14 +197,6 @@ 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)); } @@ -463,60 +449,6 @@ 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`). @@ -1772,9 +1704,6 @@ 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(_) @@ -1791,22 +1720,6 @@ 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); @@ -1844,31 +1757,6 @@ 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); @@ -2317,19 +2205,11 @@ 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 mut opts = SendOpts { + let 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() @@ -2342,11 +2222,6 @@ 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))?; } @@ -4740,7 +4615,7 @@ mod tests { "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." + only your node can read." ); assert_eq!(labels(&s.1), [vec!["Paste URL + key", "Cancel"]]); assert_eq!( @@ -4873,13 +4748,32 @@ mod tests { let ok = a("login_ok", "ok", ""); assert_eq!( crate::runtime_views::alert_text(&ok, &r, Some("tn-cos"), &c), - "OpenCode 1 is ready with DeepSeek (deepseek-flash).\nNot used yet. To use it, \ - tell me (e.g. \"run research tasks on OpenCode 1\"); Routing shows the result." + "OpenCode 1 is ready with DeepSeek (deepseek-flash). For another model, tell me \ + which (e.g. \"run research tasks on OpenCode 1 with model X\").\nNot used yet. \ + To use it, tell me (e.g. \"run research tasks on OpenCode 1\"); Routing shows \ + the result." ); + // A ready card has no model buttons: rules choose models. assert_eq!( card_buttons(&ok, &r).0, [button("Routing →", "rtroute"), button("Done", "rtdone")] ); + // `Other…` has no default model: a rule names it. + let mut other = ok.clone(); + other["provider"] = json!("other"); + assert_eq!( + crate::runtime_views::alert_text(&other, &r, Some("tn-cos"), &c) + .lines() + .next(), + Some( + "OpenCode 1 is ready with Other. It has no default model: tell me which \ + model to run on it (e.g. \"run research tasks on OpenCode 1 with model X\")." + ) + ); + // An old card's model pick only gets a toast. + for d in ["rtmodel:opencode-1:3", "rtmpage:opencode-1:1"] { + assert_eq!(RuntimePress::parse(d), Some(RuntimePress::Retired), "{d}"); + } let msg = "DeepSeek: wrong API key (HTTP 401) {\"error\":\"invalid key\"}"; let failed = a("login_failed", "removed", msg); assert_eq!( @@ -4907,79 +4801,6 @@ 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 d354fb8..148b6d6 100644 --- a/crates/axe/tests/layering.rs +++ b/crates/axe/tests/layering.rs @@ -346,10 +346,6 @@ 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/runtime_pick.rs b/crates/axe/tests/runtime_pick.rs index 2304d9f..837219d 100644 --- a/crates/axe/tests/runtime_pick.rs +++ b/crates/axe/tests/runtime_pick.rs @@ -937,3 +937,126 @@ agents = ["claude"] } } } + +/// Models come from rules only (task 2447): an OpenCode runtime on an +/// OpenRouter key runs the model a rule names (`-m provider/model`, +/// declared in its `opencode.json` first), and with a rule naming no model +/// runs the provider row's default from its config; nothing about a model +/// is stored with the runtime. +#[test] +fn opencode_runs_the_rules_model_else_the_providers_default() { + use std::os::unix::fs::PermissionsExt as _; + let tmp = tempfile::tempdir().unwrap(); + let dir = tmp.path(); + let bin = dir.join("bin"); + std::fs::create_dir_all(&bin).unwrap(); + let fake = bin.join("opencode"); + std::fs::write(&fake, FAKE).unwrap(); + std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap(); + let rt = dir.join("runtimes/opencode-1"); + std::fs::create_dir_all(rt.join("home")).unwrap(); + std::fs::create_dir_all(rt.join("login")).unwrap(); + std::fs::write( + rt.join("runtime.toml"), + format!( + "harness = \"opencode\"\nagent = \"opencode\"\nlogin_dir = \"{}\"\nprobe = []\n", + rt.join("home").display() + ), + ) + .unwrap(); + std::fs::write( + rt.join("login/OPENROUTER_API_KEY"), + format!("sk-or-v1-{}", "2".repeat(64)), + ) + .unwrap(); + std::fs::write( + rt.join("state.json"), + json!({"state": "ok", "providers": {"openrouter": "ok"}}).to_string(), + ) + .unwrap(); + for p in ["a", "b"] { + std::fs::create_dir_all(dir.join("ws").join(p)).unwrap(); + } + std::fs::create_dir_all(dir.join("out")).unwrap(); + let cfg = format!( + r#" +workspace_root = "{ws}" +log_dir = "{logs}" +poll_seconds = 1 + +[pool] +total = 4 + +[worktrees] + +[runtimes] +dir = "{runtimes}" + +[agents.opencode] +cmd = ["{bin}/opencode", "run", "{{prompt}}"] +session = "none" +harness = "opencode" +"#, + ws = dir.join("ws").display(), + logs = dir.join("logs").display(), + runtimes = dir.join("runtimes").display(), + bin = bin.display(), + ); + let path = dir.join("config.toml"); + std::fs::write(&path, cfg).unwrap(); + let srv = Server::start_with(dir, &path, Some(TOKEN), &[], &[]); + let rig = Rig { _tmp: tmp, srv }; + rig.ok(&["rule", "add", "--default", "--use", "opencode"]); + rig.ok(&[ + "rule", + "add", + "--match", + "label=a", + "--use", + "opencode:openrouter/openai/gpt-6.2-sol", + ]); + let config = rig + .dir() + .join("runtimes/opencode-1/home/config/opencode/opencode.json"); + let read = || -> Value { serde_json::from_slice(&std::fs::read(&config).unwrap()).unwrap() }; + + // No model in the rule: no -m, the config's default (the row's). + let id: i64 = rig + .ok(&["task", "add", "--title", "t", "--project", "b"]) + .trim() + .parse() + .unwrap(); + rig.dispatch_once(); + let (runtime, rule, args) = rig.task_pick(id).expect("a run"); + assert_eq!( + (runtime.as_str(), rule.as_str()), + ("opencode-1", "rule:1 (default)") + ); + assert!(args.is_empty(), "{args:?}"); + assert_eq!( + read()["model"], + "openrouter/~anthropic/claude-sonnet-latest" + ); + + // The rule's model: passed with -m and declared under its provider. + let id: i64 = rig + .ok(&["task", "add", "--title", "t", "--project", "a"]) + .trim() + .parse() + .unwrap(); + rig.dispatch_once(); + let (runtime, rule, args) = rig.task_pick(id).expect("a run"); + assert_eq!( + (runtime.as_str(), rule.as_str()), + ("opencode-1", "rule:2 (label=a)") + ); + assert_eq!(args, ["-m", "openrouter/openai/gpt-6.2-sol"]); + let v = read(); + assert_eq!(v["model"], "openrouter/~anthropic/claude-sonnet-latest"); + assert_eq!( + v["provider"]["openrouter"]["models"], + json!({"~anthropic/claude-sonnet-latest": {}, "openai/gpt-6.2-sol": {}}) + ); + let state = std::fs::read_to_string(rig.dir().join("runtimes/opencode-1/state.json")).unwrap(); + assert!(!state.contains("model"), "{state}"); +} diff --git a/crates/axe/tests/telegram.rs b/crates/axe/tests/telegram.rs index c49e502..b2f8878 100644 --- a/crates/axe/tests/telegram.rs +++ b/crates/axe/tests/telegram.rs @@ -4778,8 +4778,7 @@ fn key_mock(good: &'static str) -> String { /// [`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). +/// https://api-docs.deepseek.com/api/list-models). fn key_mock_of(good: &[&'static str]) -> String { use std::io::{BufRead, BufReader, Write}; let good = good.to_vec(); @@ -4790,15 +4789,11 @@ fn key_mock_of(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; } - if first.is_empty() { - first = line.clone(); - } ok |= good.iter().any(|g| { line.trim() .eq_ignore_ascii_case(&format!("authorization: Bearer {g}")) @@ -4808,9 +4803,6 @@ fn key_mock_of(good: &[&'static str]) -> String { {"id":"deepseek-flash","object":"model","owned_by":"deepseek"}, {"id":"deepseek-v4-pro","object":"model","owned_by":"deepseek"}]}"#; let (status, body) = match ok { - true if first.contains("supported_parameters") => { - ("503 Service Unavailable", r#"{"error":"down"}"#) - } true => ("200 OK", MODELS), false => ("401 Unauthorized", r#"{"error":"invalid key"}"#), }; @@ -5000,20 +4992,16 @@ fn opencode_sets_up_from_telegram_with_a_provider_key() { 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["text"].as_str().unwrap().contains( + "For another model, tell me which (e.g. \"run research tasks on OpenCode 1 with \ + model X\")." + ), "{ready}" ); - // The model pick: DeepSeek's live list, the suggested model first. + // No model pick: rules choose models. assert_eq!( keyboard_of(&ready), - kb(&[ - &[("• deepseek-flash", "rtmodel:opencode-1:0")], - &[("deepseek-v4-pro", "rtmodel:opencode-1:1")], - &[("Routing →", "rtroute"), ("Done", "rtdone")] - ]) + kb(&[&[("Routing →", "rtroute"), ("Done", "rtdone")]]) ); let home = reg.join("opencode-1/home"); let config_of = || -> Value { @@ -5023,46 +5011,22 @@ fn opencode_sets_up_from_telegram_with_a_provider_key() { 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": {}}}) + json!({"models": {"deepseek-flash": {}}}) ); + // Nothing about a model is stored or reported for the runtime. 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!(state.get("models").is_none(), "{state}"); + wait_for("the provider reported", 20, || { + rig.srv().get("/api/runtimes")["runtimes"][0]["providers"][0]["state"].is_string() }); + assert!( + rig.srv().get("/api/runtimes")["runtimes"][0]["providers"][0] + .get("model") + .is_none() + ); assert_eq!( std::fs::read_to_string(reg.join("opencode-1/login/DEEPSEEK_API_KEY")).unwrap(), GOOD @@ -5120,26 +5084,18 @@ fn opencode_sets_up_from_telegram_with_a_provider_key() { .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. + // A working OpenRouter key: ready on the row's default model. 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. + // sealed form; no default model, so a rule names one. press_on(157, list_tg, "rtkey:opencode-1:other"); let other = edit_of(&rig, list_tg, 10); assert!( @@ -5173,25 +5129,20 @@ fn opencode_sets_up_from_telegram_with_a_provider_key() { "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)."); + let ready = card("OpenCode 1 is ready with Other. It has no default model"); assert_eq!( - keyboard_of(&ready)[0], - [( - "• deepseek-flash".to_string(), - "rtmodel:opencode-1:0".to_string() - )] + keyboard_of(&ready), + kb(&[&[("Routing →", "rtroute"), ("Done", "rtdone")]]) ); assert_eq!( std::fs::read_to_string(reg.join("opencode-1/login/OTHER_BASE_URL")).unwrap(), "https://llm.example.test/v1" ); + // Declared in the config only before a run whose rule names its model + // (`Runtime::write_config_for`). 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": {}}}) - ); + assert!(config["provider"]["other"].is_null(), "{config}"); + assert_eq!(config["model"], "deepseek/deepseek-flash"); } /// Claude on another provider from Telegram (store doc diff --git a/docs/user/concepts/runtimes.md b/docs/user/concepts/runtimes.md index 2555ae9..1b403fb 100644 --- a/docs/user/concepts/runtimes.md +++ b/docs/user/concepts/runtimes.md @@ -51,14 +51,12 @@ 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 +or 403 a wrong one, and 400 for Gemini), its default model (run when a +rule names none), 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 is `/models` +(`/v1/models` on Claude Code's Anthropic-compatible URL), and it has +no default model, so a rule names its model. `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 @@ -74,8 +72,7 @@ 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 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 +(`Runtime::env`). 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…* @@ -95,12 +92,14 @@ 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 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 +first held provider's row default (`deepseek/deepseek-flash`), each held +row's default declared under its provider, `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 +dropped and when the node loads the registry. Before a run whose rule names +a model, that model is declared under its provider too +(`Runtime::write_config_for`): OpenCode refuses a model its catalog does not +list yet, and an `other` model is known only from the rule. Keys reach OpenCode as environment variables (`DEEPSEEK_API_KEY`), where its built-in providers read them. A bot's system prompt goes in `OPENCODE_CONFIG_CONTENT` as an `instructions` file (`Harness::bot_env`), and a rule's effort as a model @@ -119,8 +118,9 @@ and catalog refresh. It takes the same provider table as OpenCode 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 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 +its row default as `defaultModel`, and `agent/models.json` with `other` as +an `openai-completions` provider on its base URL and the rule's model, +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 @@ -149,6 +149,7 @@ 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`). 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`). +it has no login for (`RuntimeConfig::with`). A runtime stores no model of +its own: models come only from rules, and a provider login runs its row's +`default_model` when a rule names none. The owner sets a model by asking a +bot for a rule (`axe rule add --use opencode:openrouter/openai/gpt-6.2-sol`). diff --git a/docs/user/guides/runtimes-from-telegram.md b/docs/user/guides/runtimes-from-telegram.md index 42b8407..517ec42 100644 --- a/docs/user/guides/runtimes-from-telegram.md +++ b/docs/user/guides/runtimes-from-telegram.md @@ -118,7 +118,7 @@ on the others. 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)." with the model pick (below). A + is ready with DeepSeek (deepseek-flash)." (see Models, 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 @@ -147,23 +147,15 @@ 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`). +**Models.** A runtime stores no model of its own: routing rules choose +models. A provider login runs its row's default model (`provider.rs` +`default_model`) when a rule names none, and the ready card says which, +then "For another model, tell me which (e.g. "run research tasks on +OpenCode 1 with model X")." The owner asks the bot, which adds a rule +(`axe rule add --use opencode:openrouter/openai/gpt-6.2-sol`). *Other…* has +no default model, so its card says "It has no default model: tell me which +model to run on it". Ready cards have no model buttons; a model button on +a card from an older version only answers that it is retired. 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