Skip to main content

agentmux_srv_core/backend/model_gateway/
ask.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What an agent asks for when it names a route, resolved once for `Agents spawn`, `create` and `update`,
5//! so the three cannot disagree (spec section 5.1). Pure: the key check is a closure the caller supplies.
6
7use super::catalog::{self, Model, Route};
8use super::launch::Choice;
9use serde_json::{json, Value};
10
11/// The words that mean the harness's own sign-in rather than a route.
12const OWN_LOGIN: &[&str] = &["anthropic", "login", "default"];
13
14#[derive(Debug)]
15pub struct Picked {
16    pub route: &'static Route,
17    pub model: &'static Model,
18}
19
20/// The route and model a new agent runs on.
21///
22/// - `route` names one: it must serve the harness, and `model` (or the route's default) must be one it serves.
23/// - `route` is the harness's own sign-in: no route, whatever the leader had.
24/// - `route` is absent: the leader's route is inherited, and `model` picks a model on it.
25/// - Neither: no route; `model` is the harness's own model choice, which the caller handles.
26///
27/// A picked route needs its key in the Vault; when it is not there the answer says what to ask for.
28pub fn resolve(harness: &str, route: Option<&str>, model: Option<&str>, inherited: Option<&Choice>, key_present: impl Fn(&Route) -> bool) -> Result<Option<Picked>, String> {
29    let route = route.map(str::trim).filter(|r| !r.is_empty());
30    let model = model.map(str::trim).filter(|m| !m.is_empty());
31    let (route_id, model_id) = match (route, inherited) {
32        (Some(r), _) if OWN_LOGIN.contains(&r.to_lowercase().as_str()) => return Ok(None),
33        (Some(r), _) => (r.to_string(), model.unwrap_or("").to_string()),
34        (None, Some(c)) => (c.route.clone(), model.unwrap_or(&c.model).to_string()),
35        (None, None) => return Ok(None),
36    };
37    let (route, model) = catalog::validate(harness, &route_id, &model_id)?;
38    if !key_present(route) {
39        return Err(format!(
40            "KEY_MISSING: route {} needs a Vault api-key entry labelled \"{}\", and the Vault has none. \
41             Ask the person to add it (Vault request, kind api-key, that label), then try again",
42            route.id, route.key_label
43        ));
44    }
45    Ok(Some(Picked { route, model }))
46}
47
48/// The line the person's approval names: where the agent's model traffic goes and who pays.
49pub fn consent_line(picked: &Picked) -> String {
50    format!(
51        " It runs {} on {} through the \"{}\" route, billed to the \"{}\" key in the Vault, not to a plan; \
52         that costs money for every turn until it is stopped.",
53        picked.route.harness, picked.model.label, picked.route.label, picked.route.key_label
54    )
55}
56
57/// `Agents routes`: the catalog as a caller may use it. `key_present` says whether a route's key is in the Vault.
58pub fn listing(harness: Option<&str>, key_present: impl Fn(&Route) -> bool) -> Value {
59    let routes: Vec<Value> = catalog::ROUTES
60        .iter()
61        .filter(|r| harness.is_none_or(|h| r.harness == h))
62        .map(|r| {
63            let models: Vec<Value> = r
64                .models
65                .iter()
66                .map(|m| {
67                    json!({
68                        "id": m.id, "label": m.label, "context": m.context, "tools": m.tools, "thinking": m.thinking, "images": m.images,
69                        "price_in_per_million": m.price_in, "price_out_per_million": m.price_out, "default": m.id == r.default_model,
70                    })
71                })
72                .collect();
73            json!({ "route": r.id, "label": r.label, "harness": r.harness, "paid": true, "key_label": r.key_label, "key_present": key_present(r), "models": models })
74        })
75        .collect();
76    json!({
77        "routes": routes,
78        "note": "pass route (and optionally model) to Agents spawn or create; route \"anthropic\" is the harness's own sign-in. A route is billed to its key, not to a plan",
79    })
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85
86    fn has_key(_: &Route) -> bool {
87        true
88    }
89
90    #[test]
91    fn a_named_route_gets_its_default_model_or_the_one_asked_for() {
92        let p = resolve("claude", Some("openrouter"), None, None, has_key).unwrap().unwrap();
93        assert_eq!((p.route.id, p.model.id), ("openrouter", "deepseek/deepseek-v4.1-flash-1017"));
94        let p = resolve("claude", Some("openrouter"), Some("deepseek/deepseek-v4-pro-0813"), None, has_key).unwrap().unwrap();
95        assert_eq!(p.model.id, "deepseek/deepseek-v4-pro-0813");
96    }
97
98    #[test]
99    fn the_harness_own_login_means_no_route_even_when_the_leader_has_one() {
100        let leader = Choice { route: "openrouter".into(), model: "deepseek/deepseek-v4.1-flash-1017".into() };
101        for word in ["anthropic", "Login", "default"] {
102            assert!(resolve("claude", Some(word), Some("sonnet"), Some(&leader), has_key).unwrap().is_none(), "{word}");
103        }
104    }
105
106    #[test]
107    fn a_worker_inherits_its_leaders_route_and_a_model_changes_only_the_model() {
108        let leader = Choice { route: "openrouter".into(), model: "deepseek/deepseek-v4.1-flash-1017".into() };
109        let same = resolve("claude", None, None, Some(&leader), has_key).unwrap().unwrap();
110        assert_eq!(same.model.id, "deepseek/deepseek-v4.1-flash-1017");
111        let other = resolve("claude", None, Some("deepseek/deepseek-v4-pro-0813"), Some(&leader), has_key).unwrap().unwrap();
112        assert_eq!((other.route.id, other.model.id), ("openrouter", "deepseek/deepseek-v4-pro-0813"));
113        assert!(resolve("claude", None, Some("sonnet"), None, has_key).unwrap().is_none(), "no route: the model is the harness's own");
114    }
115
116    #[test]
117    fn a_route_that_cannot_be_used_says_why() {
118        assert!(resolve("claude", Some("nowhere"), None, None, has_key).unwrap_err().contains("openrouter"));
119        assert!(resolve("codex", Some("openrouter"), None, None, has_key).unwrap_err().contains("serves claude"));
120        let missing = resolve("claude", Some("openrouter"), None, None, |_| false).unwrap_err();
121        assert!(missing.starts_with("KEY_MISSING") && missing.contains("OpenRouter API key"), "{missing}");
122    }
123
124    #[test]
125    fn the_approval_names_the_route_the_model_and_who_pays() {
126        let p = resolve("claude", Some("openrouter"), None, None, has_key).unwrap().unwrap();
127        let line = consent_line(&p);
128        assert!(line.contains("DeepSeek V4.1 Flash") && line.contains("OpenRouter") && line.contains("not to a plan"), "{line}");
129    }
130
131    #[test]
132    fn the_listing_says_which_routes_have_a_key_and_what_they_cost() {
133        let all = listing(None, |_| false);
134        assert_eq!(all["routes"][0]["route"], "openrouter");
135        assert_eq!(all["routes"][0]["key_present"], false);
136        assert_eq!(all["routes"][0]["models"][0]["default"], true);
137        assert!(all["routes"][0]["models"][0]["price_in_per_million"].as_f64().unwrap() > 0.0);
138        assert!(listing(Some("codex"), has_key)["routes"].as_array().unwrap().is_empty());
139    }
140}