model switch also switches provider (gpt models were sent to the Claude API)
ci / check (pull_request) Canceled after 0s
ci / check (push) Canceled after 0s

This commit is contained in:
hermes committed 2026-10-01 12:15:39 +00:00
1 parent 658ada46f7
commit ad73e8f1c2
7 files changed
+171 -21

No files matched your search

+22
View File
@@ -78,6 +78,23 @@ pub fn window(models: &[ModelInfo], id: &str) -> u64 {
})
}
/// Provider serving `id`: catalog entry, else by name (`claude-*` vs OpenAI families).
pub fn kind_of(models: &[ModelInfo], id: &str) -> Option<Kind> {
if let Some(m) = models.iter().find(|m| m.id == id) {
return Some(m.kind);
}
let openai = id.starts_with("gpt-")
|| id.starts_with("codex")
|| (id.starts_with('o') && id[1..].starts_with(|c: char| c.is_ascii_digit()));
if id.starts_with("claude") {
Some(Kind::Claude)
} else if openai {
Some(Kind::Codex)
} else {
None
}
}
/// Auto-compaction threshold: 90% of the window, leaving room for the reply.
pub fn compact_threshold(window: u64, max_output: u32) -> usize {
(window * 9 / 10).min(window.saturating_sub(max_output as u64)) as usize
@@ -156,6 +173,11 @@ mod tests {
ms.extend(fallback(Kind::Codex));
assert_eq!(default_for(Kind::Codex, &ms), "gpt-5.6-sol");
assert_eq!(compact_threshold(1_000_000, 16_384), 900_000);
assert_eq!(kind_of(&ms, "gpt-5.6-terra"), Some(Kind::Codex), "catalog");
assert_eq!(kind_of(&[], "gpt-7"), Some(Kind::Codex), "by name");
assert_eq!(kind_of(&[], "o4-mini"), Some(Kind::Codex));
assert_eq!(kind_of(&[], "claude-x"), Some(Kind::Claude));
assert_eq!(kind_of(&[], "opus"), None);
assert_eq!(compact_threshold(20_000, 16_384), 3_616);
}
}
+17 -1
View File
@@ -324,6 +324,11 @@ async fn main() -> Result<()> {
.or(kinds.first().copied())
.unwrap_or(Kind::Claude);
let models = catalog(&kinds).await;
// an explicit model picks its provider unless --provider says otherwise
let kind = match (&cli.provider, cli.model.as_deref().or(cfg.model.as_deref())) {
(None, Some(m)) => hx_ai::models::kind_of(&models, m).unwrap_or(kind),
_ => kind,
};
let model = cli.model.or(cfg.model).unwrap_or_else(|| {
match kind {
Kind::Claude => cfg.claude_model.clone(),
@@ -455,7 +460,18 @@ async fn main() -> Result<()> {
}
let specs = command_specs(&mcp, &cwd, &models, &kinds);
if cli.mode == Mode::Rpc {
let r = rpc::serve(agent, abort, specs, hx_tui::project_files(&cwd), dir).await;
let r = rpc::serve(
agent,
abort,
rpc::Ctx {
specs,
files: hx_tui::project_files(&cwd),
session_dir: dir,
models: models.clone(),
make_provider: provider,
},
)
.await;
mgr.shutdown().await;
return r;
}
+28 -10
View File
@@ -47,13 +47,22 @@ fn reply(id: &Value, r: Result<Value, String>) {
/// `state`, `messages`, `fork {id}`, `clear`, `set_model {model}`, `compact`,
/// `complete {line, cursor?}` (cursor = byte offset, default end), `sessions {scope?: project|all}`,
/// `new`, `resume {path}`. One prompt at a time.
pub async fn serve(
mut agent: Agent,
abort: AbortHandle,
specs: Vec<hx_core::command::CmdSpec>,
files: Vec<String>,
session_dir: std::path::PathBuf,
) -> Result<()> {
pub struct Ctx {
pub specs: Vec<hx_core::command::CmdSpec>,
pub files: Vec<String>,
pub session_dir: std::path::PathBuf,
pub models: Vec<hx_ai::models::ModelInfo>,
pub make_provider: fn(hx_ai::auth::Kind) -> hx_ai::Result<Arc<dyn hx_ai::Provider>>,
}
pub async fn serve(mut agent: Agent, abort: AbortHandle, cx: Ctx) -> Result<()> {
let Ctx {
specs,
files,
session_dir,
models,
make_provider,
} = cx;
agent.bus.add(Notify);
let agent = Arc::new(Mutex::new(agent));
let busy = Arc::new(std::sync::atomic::AtomicBool::new(false));
@@ -136,10 +145,19 @@ pub async fn serve(
.map(|_| json!({}))
.map_err(|e| e.to_string()),
"set_model" => match p["model"].as_str() {
Some(m) => {
a.model = m.into();
Ok(json!({"model": m}))
// switch provider too when the model belongs to another one
Some(m) => match hx_ai::models::kind_of(&models, m) {
Some(k) => make_provider(k).map(|prov| {
a.provider = prov;
a.model = m.into();
json!({"model": m, "provider": format!("{k:?}").to_lowercase()})
}),
None => {
a.model = m.into();
Ok(json!({"model": m}))
}
}
.map_err(|e| e.to_string()),
None => Err("params.model required".into()),
},
"compact" => a
+86 -8
View File
@@ -650,14 +650,31 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
}
"model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.model))),
"model" => {
let mut a = agent.lock().await;
a.model = arg.into();
set_window(app, &mut a, models, auto_compact);
app.model = arg.into();
app.t.push(Item::Info(format!(
"model → {arg} · context {}k",
hx_ai::models::window(models, arg) / 1000
)));
// a model belongs to one provider: switch provider with it
let k = hx_ai::models::kind_of(models, arg).unwrap_or(app.kind);
let p = if k == app.kind {
Ok(None)
} else {
make_provider(k).map(Some).map_err(|e| e.to_string())
};
match p {
Ok(p) => {
let mut a = agent.lock().await;
if let Some(p) = p {
a.provider = p;
app.kind = k;
app.quota = None;
}
a.model = arg.into();
set_window(app, &mut a, models, auto_compact);
app.model = arg.into();
app.t.push(Item::Info(format!(
"model → {arg} ({k:?}) · context {}k",
hx_ai::models::window(models, arg) / 1000
)));
}
Err(e) => app.t.push(Item::Error(format!("/model {arg}: {e}"))),
}
}
"provider" => match arg
.parse::<Kind>()
@@ -1456,6 +1473,67 @@ mod tests {
assert_eq!(until(10_030, 10_000), "1m");
}
#[tokio::test]
async fn model_switch_follows_provider() {
use std::sync::atomic::{AtomicUsize, Ordering};
static CODEX_CALLS: AtomicUsize = AtomicUsize::new(0);
let t = tempfile::tempdir().unwrap();
let (agent, _) = Agent::new(
Arc::new(NoProvider),
Default::default(),
hx_core::session::Session::open(t.path().join("s.jsonl")).unwrap(),
hx_core::tool::ToolCtx {
cwd: t.path().into(),
state: Default::default(),
},
);
let agent = Arc::new(Mutex::new(agent));
let (tx, _rx) = mpsc::unbounded_channel();
let mut models = hx_ai::models::fallback(Kind::Claude);
models.extend(hx_ai::models::fallback(Kind::Codex));
let ls: LspStatus = Box::new(|| Box::pin(async { vec![] }));
let cmds: Commands = Box::new(|_, _| None);
let mut app = test_app();
app.kind = Kind::Claude;
// codex not logged in: error, nothing changes
let fail: MakeProvider =
Box::new(|_| Err(hx_ai::Error::Http("not logged in to Codex".into())));
let ctx = Ctx {
agent: &agent,
tx: &tx,
make_provider: &fail,
models: &models,
auto_compact: true,
cwd: t.path(),
lsp_status: &ls,
commands: &cmds,
};
submit(&mut app, "/model gpt-5.6-terra".into(), &ctx).await;
assert_eq!((app.kind, app.model.as_str()), (Kind::Claude, "m1"));
assert!(matches!(app.t.items.last(), Some(Item::Error(e)) if e.contains("not logged in")));
let ok: MakeProvider = Box::new(|k| {
assert_eq!(k, Kind::Codex);
CODEX_CALLS.fetch_add(1, Ordering::SeqCst);
Ok(Arc::new(NoProvider))
});
let ctx = Ctx {
make_provider: &ok,
..ctx
};
submit(&mut app, "/model gpt-5.6-terra".into(), &ctx).await;
assert_eq!(
(app.kind, app.model.as_str()),
(Kind::Codex, "gpt-5.6-terra")
);
assert_eq!(agent.lock().await.model, "gpt-5.6-terra");
assert_eq!(CODEX_CALLS.load(Ordering::SeqCst), 1);
// same provider: no new client
submit(&mut app, "/model gpt-5.6-luna".into(), &ctx).await;
assert_eq!(CODEX_CALLS.load(Ordering::SeqCst), 1);
}
struct NoProvider;
#[async_trait::async_trait]
impl Provider for NoProvider {
+8
View File
@@ -18,4 +18,12 @@ echo "$log" | grep -q '"auth": "Bearer fake-token"'
echo "$log" | grep -q 'oauth-2025-04-20'
echo "$log" | grep -q 'hi from hx' # bash tool result sent back to the model
ls "$tmp/home/.hx/sessions/"*/*.jsonl > /dev/null
# a GPT model goes to the Codex endpoint, not to the Claude API (both logged in)
echo '{"claude":{"access":"fake-token","refresh":"r","expires":99999999999999},"codex":{"access":"cx-token","refresh":"r","expires":99999999999999,"account_id":"acc"}}' > "$tmp/home/.hx/auth.json"
HOME="$tmp/home" HX_BASE_URL="http://127.0.0.1:$port" "$root/target/debug/hx" -m gpt-5.6-terra -p "hi" > /dev/null 2> "$tmp/err" || true
curl -s "http://127.0.0.1:$port/" | python3 -c '
import json, sys
last = json.load(sys.stdin)[-1]
assert last["path"].endswith("/responses") and last["body"]["model"] == "gpt-5.6-terra" and last["auth"] == "Bearer cx-token", last
' || { echo "FAIL: gpt model not routed to codex"; cat "$tmp/err"; exit 1; }
echo "e2e ok"
+7 -1
View File
@@ -23,7 +23,13 @@ class H(http.server.BaseHTTPRequestHandler):
def do_POST(self):
body = json.loads(self.rfile.read(int(self.headers["content-length"])))
LOG.append({"auth": self.headers.get("authorization"), "beta": self.headers.get("anthropic-beta"), "body": body})
LOG.append({"path": self.path, "auth": self.headers.get("authorization"), "beta": self.headers.get("anthropic-beta"), "body": body})
if self.path.endswith("/responses"):
# Codex route: only the request matters to the tests
self.send_response(400)
self.end_headers()
self.wfile.write(b'{"detail": "fake codex"}')
return
turn = TURNS[min(len(LOG) - 1, len(TURNS) - 1)]
self.send_response(200)
self.send_header("anthropic-ratelimit-unified-5h-utilization", "0.42")
+3 -1
View File
@@ -69,7 +69,9 @@ check("quota in footer", "5h 42%")
send(b"/usage\r")
check("usage report", "58% left, resets in 2h1")
send(b"/model claude-opus-5-5\r")
check("model switch", "model → claude-opus-5-5 · context 1000k")
check("model switch", "model → claude-opus-5-5 (Claude) · context 1000k")
send(b"/model gpt-5.6-sol\r")
check("gpt model needs codex login", "not logged in to Codex")
send(b"/model claude-sonnet-5-6-preview\r")
check("live catalog window", "context 2000k")
check("live catalog cached", "") if os.path.exists(f"{tmp}/home/.hx/models-claude.json") else (print("FAIL no model cache"), globals().update(ok=False))