Skip to main content

agentmux_srv_core/backend/model_gateway/
launch.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent's route and model, and the environment that points its harness at the gateway.
5//!
6//! The choice is kept on the agent's definition as a content blob, so it follows the agent's id and
7//! needs no column. The environment is built at every spawn and never persisted: the token in it lives
8//! for this srv launch.
9
10use super::catalog::{self, Model, Route};
11use super::{token, PATH_PREFIX};
12use crate::backend::storage::content::AgentContent;
13use crate::backend::storage::store::Store;
14use serde::{Deserialize, Serialize};
15use std::collections::HashMap;
16
17/// The definition content type that holds the [`Choice`].
18pub const CONTENT_TYPE: &str = "agent:model_route";
19/// The definition content type that marks a route the agent has left but whose harness may still be running a turn on it:
20/// the gateway keeps answering that route's token until the harness is relaunched ([`super::switch::finish_leaving`]).
21pub const LEAVING_TYPE: &str = "agent:model_route_leaving";
22/// A model with a context of this many tokens or more gets Claude Code's `[1m]` mark, so it does not compact early.
23const LONG_CONTEXT: u32 = 1_000_000;
24/// The variable Claude Code reads for the window it auto-compacts in.
25const COMPACT_WINDOW_VAR: &str = "CLAUDE_CODE_AUTO_COMPACT_WINDOW";
26
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28pub struct Choice {
29    pub route: String,
30    pub model: String,
31}
32
33/// The route and model of the agent definition `def_id`, if it has chosen one.
34pub fn choice_of(mstore: &Store, def_id: &str) -> Option<Choice> {
35    let content = mstore.agent_content_get(def_id, CONTENT_TYPE).ok()??;
36    serde_json::from_str(&content.content).ok()
37}
38
39/// The route and model the agent has left but may still be running a turn on, if any.
40pub fn leaving(mstore: &Store, def_id: &str) -> Option<Choice> {
41    serde_json::from_str(&mstore.agent_content_get(def_id, LEAVING_TYPE).ok()??.content).ok()
42}
43
44/// The model the gateway sends the agent's requests for `route` to: its chosen one, or, on a route it has just left, the
45/// one it was on, so a turn in flight finishes (see [`super::switch::finish_leaving`]). None: the agent is not set to it.
46pub fn model_on_route(mstore: &Store, def_id: &str, route: &'static Route) -> Option<&'static Model> {
47    let chosen = choice_of(mstore, def_id).filter(|c| c.route == route.id).and_then(|c| route.model(&c.model));
48    // The model it was running, so what the rest of the turn costs is counted at that model's prices.
49    chosen.or_else(|| leaving(mstore, def_id).filter(|c| c.route == route.id).and_then(|c| route.model(&c.model)))
50}
51
52/// Saves the agent's route and model after the shared validation, with the model made explicit.
53pub fn set_choice(mstore: &Store, def_id: &str, harness: &str, route: &str, model: &str) -> Result<Choice, String> {
54    let (route, model) = catalog::validate(harness, route, model)?;
55    let choice = Choice { route: route.id.to_string(), model: model.id.to_string() };
56    let content = serde_json::to_string(&choice).map_err(|e| e.to_string())?;
57    mstore
58        .agent_content_set(&AgentContent { agent_id: def_id.to_string(), content_type: CONTENT_TYPE.to_string(), content, updated_at: agentmux_common::time::now_ms() })
59        .map_err(|e| e.to_string())?;
60    Ok(choice)
61}
62
63/// The variables that point Claude Code at the gateway on `route`. The key is not among them: the
64/// token is the harness's whole credential, and `ANTHROPIC_API_KEY` is emptied so no other key is used.
65pub fn env_for(route: &Route, model: &Model, token: &str, local_url: &str) -> Vec<(String, String)> {
66    let marked = if model.context >= LONG_CONTEXT { format!("{}[1m]", model.id) } else { model.id.to_string() };
67    let var = |k: &str, v: String| (k.to_string(), v);
68    let mut env = vec![
69        var("ANTHROPIC_BASE_URL", format!("{}{PATH_PREFIX}{}", local_url.trim_end_matches('/'), route.id)),
70        var("ANTHROPIC_AUTH_TOKEN", token.to_string()),
71        var("ANTHROPIC_API_KEY", String::new()),
72        var("ANTHROPIC_DEFAULT_OPUS_MODEL", marked.clone()),
73        var("ANTHROPIC_DEFAULT_SONNET_MODEL", marked.clone()),
74        var("ANTHROPIC_DEFAULT_HAIKU_MODEL", marked),
75        var("CLAUDE_CODE_SUBAGENT_MODEL", model.id.to_string()),
76    ];
77    // The `[1m]` mark above makes the CLI take a 1M window and compact near its end; on a route that is a
78    // million tokens re-read every turn. The CLI compacts at this budget instead (`autoCompactThreshold`).
79    if let Some(budget) = model.compact_budget() {
80        env.push(var(COMPACT_WINDOW_VAR, budget.to_string()));
81    }
82    // Bedrock may refuse the beta flags Claude Code adds for features it does not know; this turns them off on the client, so
83    // the gateway forwards no flag Bedrock has not heard of.
84    if route.id == super::bedrock::ROUTE_ID {
85        env.push(var(super::bedrock::BETAS_OFF_VAR, "1".to_string()));
86    }
87    env
88}
89
90/// The variables that point Claude Code at the gateway's key route: its address and the agent's token. No model is
91/// named (the harness asks for the models it always does and the key's account answers), and `ANTHROPIC_API_KEY` is
92/// emptied so no other key is used. The key is not among them: it stays in the keychain.
93pub fn env_for_key_route(token: &str, local_url: &str) -> Vec<(String, String)> {
94    vec![
95        ("ANTHROPIC_BASE_URL".to_string(), format!("{}{PATH_PREFIX}{}", local_url.trim_end_matches('/'), catalog::KEY_ROUTE_ID)),
96        ("ANTHROPIC_AUTH_TOKEN".to_string(), token.to_string()),
97        ("ANTHROPIC_API_KEY".to_string(), String::new()),
98    ]
99}
100
101/// The block meta key the pane, its footer and its header read for the model the agent really runs: the route's
102/// and the model's names, or absent on the harness's own sign-in. Without it they show the harness's nominal model
103/// (the alias the pane was configured with), which on a route is not what answers.
104pub const BLOCK_META_KEY: &str = "agent:route_model";
105
106/// What the pane shows for a route and model.
107pub fn pane_meta(route: &Route, model: &Model) -> serde_json::Value {
108    serde_json::json!({ "route": route.id, "route_label": route.label, "model": model.id, "label": model.label })
109}
110
111/// Keeps the pane's `agent:route_model` as the launch has it. The next block update the start sends carries it.
112fn publish_to_block(mstore: &Store, block_id: &str, shown: Option<(&Route, &Model)>) {
113    let mut update = crate::backend::obj::MetaMapType::new();
114    update.insert(BLOCK_META_KEY.to_string(), shown.map_or(serde_json::Value::Null, |(r, m)| pane_meta(r, m)));
115    if let Err(e) = crate::backend::wcore::object_meta::update_object_meta(mstore, &format!("block:{block_id}"), &update) {
116        tracing::warn!(block_id, error = %e, "model route: the pane's model name was not stored");
117    }
118}
119
120/// Adds the gateway environment to the spawn of the agent on `block_id` when its definition has a route, and
121/// records the real model on the pane. Over whatever a persisted `cmd:env` carried: these are reserved names, set by
122/// srv at every spawn.
123pub fn carry_for_block(mstore: &Store, block_id: &str, env_vars: &mut HashMap<String, String>) {
124    let Ok(Some(instance)) = mstore.instance_get_active_for_block(block_id) else { return };
125    let Ok(Some(def)) = mstore.agent_def_get(&instance.definition_id) else { return };
126    // A relaunch is the end of a turn on a route the agent has left: its token stops working now.
127    super::switch::finish_leaving_after_relaunch(mstore, &def.id, block_id, |b| super::switch::pane_in_a_turn(mstore, b));
128    let choice = choice_of(mstore, &def.id);
129    let validated = choice.as_ref().and_then(|c| catalog::validate(&def.provider, &c.route, &c.model).ok());
130    publish_to_block(mstore, block_id, validated);
131    let Some((route, model)) = validated else {
132        if let Some(c) = choice {
133            tracing::warn!(agent = %def.slug, route = %c.route, "model route: the agent's saved route no longer validates; launching without it");
134        }
135        return;
136    };
137    let Ok(local_url) = std::env::var("AGENTMUX_LOCAL_URL") else {
138        tracing::warn!(agent = %def.slug, "model route: srv's own address is not known; launching without the route");
139        return;
140    };
141    let token = token::token_for(&def.slug, &def.id, route.id);
142    merge_route_env(env_vars, route, model, &token, &local_url);
143}
144
145/// srv's route environment over the agent's own, except a compaction window the agent's own environment set below the
146/// budget (`Agents env_set`, My Agents): that one is the person's choice, not srv's.
147fn merge_route_env(env_vars: &mut HashMap<String, String>, route: &Route, model: &Model, token: &str, local_url: &str) {
148    let own_window = env_vars.get(COMPACT_WINDOW_VAR).and_then(|v| v.trim().parse::<u32>().ok());
149    env_vars.extend(env_for(route, model, token, local_url));
150    if let (Some(own), Some(budget)) = (own_window, model.compact_budget()) {
151        if own < budget {
152            env_vars.insert(COMPACT_WINDOW_VAR.to_string(), own.to_string());
153        }
154    }
155}
156#[cfg(test)]
157mod tests {
158    use super::*;
159
160    #[test]
161    fn the_harness_is_given_the_gateway_and_never_a_key() {
162        let route = catalog::route("openrouter").unwrap();
163        let model = route.model("deepseek/deepseek-v4.1-flash-1017").unwrap();
164        let env: HashMap<_, _> = env_for(route, model, "amxg_tok", "http://127.0.0.1:4000/").into_iter().collect();
165        assert_eq!(env["ANTHROPIC_BASE_URL"], "http://127.0.0.1:4000/api/v1/model/openrouter");
166        assert_eq!(env["ANTHROPIC_AUTH_TOKEN"], "amxg_tok");
167        assert_eq!(env["ANTHROPIC_API_KEY"], "");
168        assert_eq!(env["ANTHROPIC_DEFAULT_SONNET_MODEL"], "deepseek/deepseek-v4.1-flash-1017[1m]");
169        assert_eq!(env["CLAUDE_CODE_SUBAGENT_MODEL"], "deepseek/deepseek-v4.1-flash-1017");
170        assert!(!env.values().any(|v| v.contains("openrouter.ai")), "the upstream address stays in srv");
171    }
172
173    #[test]
174    fn a_model_with_a_long_window_compacts_at_the_budget_not_at_the_end_of_its_window() {
175        let route = catalog::route("openrouter").unwrap();
176        let long = route.model("deepseek/deepseek-v4.1-flash-1017").unwrap();
177        assert!(long.context >= LONG_CONTEXT, "the window the CLI is told is 1M");
178        let env: HashMap<_, _> = env_for(route, long, "t", "http://127.0.0.1:4000").into_iter().collect();
179        assert_eq!(env["CLAUDE_CODE_AUTO_COMPACT_WINDOW"], "300000");
180        assert!(env["ANTHROPIC_DEFAULT_SONNET_MODEL"].ends_with("[1m]"), "the mark stays: the model does read 1M");
181        let short = Model { context: 128_000, ..*long };
182        assert_eq!(short.compact_budget(), None);
183        let env: HashMap<_, _> = env_for(route, &short, "t", "http://127.0.0.1:4000").into_iter().collect();
184        assert!(!env.contains_key("CLAUDE_CODE_AUTO_COMPACT_WINDOW"), "a window within the budget needs no override");
185    }
186
187    #[test]
188    fn a_window_the_agent_set_lower_than_the_budget_is_kept_and_a_higher_one_is_not() {
189        let route = catalog::route("openrouter").unwrap();
190        let model = route.model("deepseek/deepseek-v4.1-flash-1017").unwrap();
191        let merged = |own: Option<&str>| {
192            let mut env: HashMap<String, String> = own.map(|v| (COMPACT_WINDOW_VAR.to_string(), v.to_string())).into_iter().collect();
193            merge_route_env(&mut env, route, model, "t", "http://127.0.0.1:4000");
194            env[COMPACT_WINDOW_VAR].clone()
195        };
196        assert_eq!(merged(None), "300000");
197        assert_eq!(merged(Some("150000")), "150000", "the person asked for earlier");
198        assert_eq!(merged(Some("900000")), "300000", "a window above the budget is what the budget is for");
199        assert_eq!(merged(Some("auto")), "300000", "not a number");
200    }
201
202    #[test]
203    fn a_route_just_left_keeps_answering_until_the_harness_is_relaunched() {
204        let store = Store::open_in_memory().unwrap();
205        let mut def = crate::backend::storage::agents::test_agent_def("def-leave", "Leaver", "claude", "host", 1, "");
206        store.agent_def_insert(&mut def).unwrap();
207        let route = catalog::route("openrouter").unwrap();
208        assert!(model_on_route(&store, "def-leave", route).is_none(), "never on the route");
209        set_choice(&store, "def-leave", "claude", "openrouter", "deepseek/deepseek-v4-pro-0813").unwrap();
210        assert_eq!(model_on_route(&store, "def-leave", route).unwrap().id, "deepseek/deepseek-v4-pro-0813");
211        super::super::switch::move_to(&store, "def-leave", "claude", super::super::switch::Target::OwnLogin, |_| true).unwrap();
212        assert_eq!(model_on_route(&store, "def-leave", route).unwrap().id, "deepseek/deepseek-v4-pro-0813", "a turn in flight finishes, and is counted at the model it runs");
213        super::super::switch::finish_leaving(&store, "def-leave");
214        assert!(model_on_route(&store, "def-leave", route).is_none(), "after the relaunch it is refused");
215    }
216
217    #[test]
218    fn the_pane_is_told_the_model_that_really_answers_and_forgets_it_off_the_route() {
219        use crate::backend::obj::{Block, MetaMapType};
220        const BLOCK: &str = "5b1a3c52-7d0e-4d43-9a43-2f6a0f4f3c11";
221        let store = Store::open_in_memory().unwrap();
222        let mut def = crate::backend::storage::agents::test_agent_def("def-pane", "Paned", "claude", "host", 1, "");
223        store.agent_def_insert(&mut def).unwrap();
224        let mut meta = MetaMapType::new();
225        meta.insert("view".to_string(), serde_json::json!("agent"));
226        let mut block = Block { oid: BLOCK.to_string(), parentoref: String::new(), version: 0, runtimeopts: None, stickers: None, meta, subblockids: None };
227        store.insert(&mut block).unwrap();
228        let instance = crate::backend::storage::agents::test_agent_instance("inst-pane", "def-pane", BLOCK, 0);
229        store.instance_create(&instance).unwrap();
230        let shown = |store: &Store| store.get::<Block>(BLOCK).unwrap().unwrap().meta.get(BLOCK_META_KEY).cloned().unwrap_or(serde_json::Value::Null);
231
232        set_choice(&store, "def-pane", "claude", "openrouter", "deepseek/deepseek-v4-pro-0813").unwrap();
233        carry_for_block(&store, BLOCK, &mut HashMap::new());
234        assert_eq!(shown(&store), serde_json::json!({ "route": "openrouter", "route_label": "OpenRouter", "model": "deepseek/deepseek-v4-pro-0813", "label": "DeepSeek V4 Pro" }));
235
236        store.agent_content_delete("def-pane", CONTENT_TYPE).unwrap();
237        carry_for_block(&store, BLOCK, &mut HashMap::new());
238        assert_eq!(shown(&store), serde_json::Value::Null, "back on the harness's own sign-in the pane shows its own model again");
239    }
240}