opencode: offer one model, not a menu where four of five fail

Only one model is loaded at a time, so listing every model that fits gave a
picker with one working entry and four that now answer 404 -- and the entry that
worked changed id on every `llmhost switch`, invalidating any client's saved
default.

Replace the list with a single entry, `default`, which is a name the API itself
answers to: vLLM takes it as a second --served-model-name and still reports the
real slug, being first in the list; the MLX proxy accepts it as an alias. So
`llmhost/default` survives a switch. The local entry is labelled with whatever is
loaded, refreshed by both switch paths; a remote block is pasted once and never
refreshed, so it names no model rather than make a claim that goes stale.

Existing configs point at a specific model, which this provider no longer has and
opencode would reject, so configure() and sync() migrate `<prov>/<model>` to
`<prov>/default`. Other providers' defaults are untouched, and an older remote
block that still lists many models keeps working, including as the fallback when
the local provider is removed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Neil Bantoc 2026-11-03 02:26:34 -08:00
parent 51c2880a2e
commit 9af7f1e545
6 changed files with 124 additions and 50 deletions

View file

@ -72,8 +72,7 @@ A config with comments (`.jsonc`) is never rewritten, since that would drop them
**On another machine**, run `llmhost opencode-config` on the server. It prints a provider block and a one-liner **On another machine**, run `llmhost opencode-config` on the server. It prints a provider block and a one-liner
that copies the API key over. That block is named **LLMHost (<the server's hostname>)** — e.g. `LLMHost (popos.local)` that copies the API key over. That block is named **LLMHost (<the server's hostname>)** — e.g. `LLMHost (popos.local)`
— under the provider id `llmhost-<shorthost>`. Only one model is loaded at a time; pick the one the server is — under the provider id `llmhost-<shorthost>`.
currently running.
### One opencode, several servers ### One opencode, several servers
@ -85,11 +84,16 @@ of remote ones at once, each named after the machine it reaches:
| local | `llmhost` | `LLMHost (Local)` | read straight from `~/.config/llm-host/api_key` | | local | `llmhost` | `LLMHost (Local)` | read straight from `~/.config/llm-host/api_key` |
| remote | `llmhost-<shorthost>` | `LLMHost (<host>)` | copied to `~/.config/opencode/llmhost-<shorthost>.key` | | remote | `llmhost-<shorthost>` | `LLMHost (<host>)` | copied to `~/.config/opencode/llmhost-<shorthost>.key` |
Models are listed as `<title> · <slug> (<where>)` — `Qwen3.8 27B · qwen3.8-27b (Local)` — so the picker is Each provider offers a **single model**, `default`, rather than every model that fits. One model is loaded at a
searchable by the slug, which is the id used everywhere else (`--model llmhost/<slug>`, `llmhost switch <slug>`). time, so a list of them would be a menu of one entry that works and the rest answering `404 model_not_found` —
Since only one model is loaded at a time, the local provider marks the loaded one `(Local, loaded)` and and naming the loaded model would break the client's saved default on the next `llmhost switch`. `default` is a
`llmhost switch` (and the dashboard) refresh that marker. Picking one of the others is not a silent mistake: name the API also answers to, so `llmhost/default` keeps working across switches: vLLM takes it as a second
the API answers `404 model_not_found` naming what is actually loaded. `--served-model-name` (and still reports the real slug, being the first), and on a Mac the proxy accepts it as an
alias. The local entry is labelled with whatever is loaded — `Default model · Qwen3.8 27B (Local)` — and
`llmhost switch`, the dashboard and `llmhost update` keep that label current. A config that still points at a
specific model (`llmhost/qwen3.8-27b`) is migrated to `llmhost/default` the next time llm-host writes the block.
To serve a different model, switch the server: `llmhost switch <name>` or the dashboard. Clients don't choose.
Which block belongs to *this* machine is decided by the key-file reference it carries, not by its name. So the Which block belongs to *this* machine is decided by the key-file reference it carries, not by its name. So the
provider is still recognised after you rename it, a remote provider that happens to sit under the `llmhost` id is provider is still recognised after you rename it, a remote provider that happens to sit under the `llmhost` id is

View file

@ -164,8 +164,9 @@ def _uncached(usage):
def make_handler(inner_port, served_name, context, key, stats, aliases=(), reasoning=None): def make_handler(inner_port, served_name, context, key, stats, aliases=(), reasoning=None):
# Names a client may call the loaded model: its llm-host name and its repo id. # Names a client may call the loaded model: its llm-host name, its repo id, and the
accepted = {served_name.lower(), *(a.lower() for a in aliases if a)} # stable alias that means "whatever is loaded" (plan.SERVED_ALIAS).
accepted = {served_name.lower(), plan.SERVED_ALIAS, *(a.lower() for a in aliases if a)}
class Proxy(BaseHTTPRequestHandler): class Proxy(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1" protocol_version = "HTTP/1.1"
@ -222,7 +223,9 @@ def make_handler(inner_port, served_name, context, key, stats, aliases=(), reaso
self._json(404, {"error": { self._json(404, {"error": {
"message": f"model '{want}' is not loaded; this server is serving " "message": f"model '{want}' is not loaded; this server is serving "
f"'{served_name}'. Load it with `llmhost switch {want}` " f"'{served_name}'. Load it with `llmhost switch {want}` "
f"(one model is loaded at a time), or ask for '{served_name}'.", f"(one model is loaded at a time), or ask for '{served_name}' "
f"-- or for '{plan.SERVED_ALIAS}', which always means whatever "
f"is loaded.",
"type": "invalid_request_error", "code": "model_not_found", "param": "model"}}) "type": "invalid_request_error", "code": "model_not_found", "param": "model"}})
return False return False

View file

@ -22,7 +22,7 @@ import subprocess
from pathlib import Path from pathlib import Path
from urllib.parse import urlsplit from urllib.parse import urlsplit
from . import paths from . import paths, plan
PROVIDER = "llmhost" PROVIDER = "llmhost"
DISPLAY = "LLMHost" DISPLAY = "LLMHost"
@ -113,24 +113,28 @@ def key_ref(key_path):
return "{file:" + str(key_path) + "}" return "{file:" + str(key_path) + "}"
def model_label(m, label, loaded=False): def model_label(active, label, name_it):
"""What opencode shows in /models: the catalog title to read, then the slug, which is """What opencode shows for the single entry. One model is loaded at a time, so there is
the id used everywhere else (`--model llmhost/<slug>`, `llmhost switch <slug>`) and so nothing to choose here -- the label's job is to say which one answers right now. Only
the thing worth being able to search for.""" where llm-host keeps the block in sync, though: a remote block is pasted once and never
where = f"{label}, loaded" if loaded else label refreshed, so naming a model there would be a claim that goes stale on the next switch."""
return f"{m.get('title') or m['name']} \u00b7 {m['name']} ({where})" if name_it and active:
return f"Default model \u00b7 {active.get('title') or active['name']} ({label})"
return f"Default model ({label})"
def provider_block(cfg, host, key_path, label, mark_loaded=False): def provider_block(cfg, host, key_path, label, mark_loaded=False):
models = {} # A single entry, keyed by the alias the API also answers to. Listing every model that
for m in cfg["models"]: # fits would be a menu of four things that 404 and one that works, and naming the loaded
# Key by the slug -- that's the model id the API answers to. # one would break every client's saved default on each `llmhost switch`.
entry = {"name": model_label(m, label, mark_loaded and m["name"] == cfg.get("active")), active = next((m for m in cfg["models"] if m["name"] == cfg.get("active")), None)
"tool_call": True, ctx = (active or {}).get("est_context") or min(
"limit": {"context": m["est_context"], "output": min(65536, m["est_context"] // 2)}} (m["est_context"] for m in cfg["models"]), default=32768)
if m.get("reasoning"): entry = {"name": model_label(active, label, mark_loaded), "tool_call": True,
entry["reasoning"] = True "limit": {"context": ctx, "output": min(65536, ctx // 2)}}
models[m["name"]] = entry if (active or {}).get("reasoning"):
entry["reasoning"] = True
models = {plan.SERVED_ALIAS: entry}
return { return {
"npm": "@ai-sdk/openai-compatible", "npm": "@ai-sdk/openai-compatible",
"name": f"{DISPLAY} ({label})", "name": f"{DISPLAY} ({label})",
@ -270,7 +274,9 @@ def configure(cfg):
existed = prov in providers existed = prov in providers
providers[prov] = local_block(cfg) providers[prov] = local_block(cfg)
if "model" not in data: if "model" not in data:
data["model"] = f"{prov}/{cfg['active']}" data["model"] = f"{prov}/{plan.SERVED_ALIAS}"
else:
_retarget_model(data, prov)
# Unconditional: a cached key for our provider is stale or redundant either way. # Unconditional: a cached key for our provider is stale or redundant either way.
cleared = bool(clear_auth(prov)) cleared = bool(clear_auth(prov))
if json.dumps(data, sort_keys=True) == before: if json.dumps(data, sort_keys=True) == before:
@ -280,6 +286,18 @@ def configure(cfg):
return ("updated" if existed else "added"), path, prov, cleared return ("updated" if existed else "added"), path, prov, cleared
def _retarget_model(data, prov):
"""Move a default that named one of our models onto the alias. Our provider used to
list every model that fits, so an existing config can point at `llmhost/qwen3.8-27b`
-- an id this provider no longer has, which opencode would reject outright."""
model = data.get("model") or ""
their_prov, _, their_model = model.partition("/")
if their_prov == prov and their_model != plan.SERVED_ALIAS:
data["model"] = f"{prov}/{plan.SERVED_ALIAS}"
return True
return False
def _pick_fallback_model(providers, removed): def _pick_fallback_model(providers, removed):
"""A `model` value from a surviving llm-host provider: its first model, which is the """A `model` value from a surviving llm-host provider: its first model, which is the
one its own plan preferred, rather than whichever name happens to sort first. one its own plan preferred, rather than whichever name happens to sort first.
@ -360,6 +378,7 @@ def sync(cfg):
prov = mine[0] prov = mine[0]
before = json.dumps(data, sort_keys=True) before = json.dumps(data, sort_keys=True)
providers[prov] = local_block(cfg) providers[prov] = local_block(cfg)
_retarget_model(data, prov)
if json.dumps(data, sort_keys=True) == before: if json.dumps(data, sort_keys=True) == before:
return None return None
_write(path, data, backup=False) _write(path, data, backup=False)

View file

@ -120,7 +120,7 @@ def catalog_entry(catalog, name):
def vllm_args(entry, choice, port, tp): def vllm_args(entry, choice, port, tp):
"""Arguments after `vllm serve`.""" """Arguments after `vllm serve`."""
v = entry.get("vllm", {}) v = entry.get("vllm", {})
args = [choice["repo"], "--served-model-name", entry["name"], args = [choice["repo"], "--served-model-name", entry["name"], SERVED_ALIAS,
"--host", "0.0.0.0", "--port", str(port), "--host", "0.0.0.0", "--port", str(port),
"--max-model-len", "-1", # let vLLM fit the context to free memory (capped at native) "--max-model-len", "-1", # let vLLM fit the context to free memory (capped at native)
"--gpu-memory-utilization", f"{choice['util']:.2f}", "--gpu-memory-utilization", f"{choice['util']:.2f}",
@ -162,6 +162,14 @@ def mlx_args(entry, choice, port):
return args return args
# A second name the API answers to, besides the model's own. opencode (and any client
# with a saved default) points at this instead of a specific model, so the choice keeps
# working after `llmhost switch` -- only one model is loaded at a time, so naming one in
# a client config only ever goes stale. vLLM takes it as a second --served-model-name and
# still reports the real slug, being the first; the MLX proxy accepts it as an alias.
SERVED_ALIAS = "default"
# ---- reasoning effort ------------------------------------------------------------- # ---- reasoning effort -------------------------------------------------------------
# Not a backend flag: it's a chat-template kwarg, read per request. "default" means send # Not a backend flag: it's a chat-template kwarg, read per request. "default" means send
# nothing and let the template decide; "off" suppresses thinking; anything else is an # nothing and let the template decide; "off" suppresses thinking; anything else is an

View file

@ -7,7 +7,7 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
import harness import harness
ROOT = harness.setup() ROOT = harness.setup()
from llmhost import opencode, paths from llmhost import opencode, paths, plan
harness.guard(paths, ROOT) harness.guard(paths, ROOT)
CFG = harness.config() CFG = harness.config()
@ -36,15 +36,15 @@ check("id is llmhost", prov == "llmhost", prov)
check('name is "LLMHost (Local)"', d["provider"]["llmhost"]["name"] == "LLMHost (Local)", d["provider"]["llmhost"]["name"]) check('name is "LLMHost (Local)"', d["provider"]["llmhost"]["name"] == "LLMHost (Local)", d["provider"]["llmhost"]["name"])
check("baseURL localhost", d["provider"]["llmhost"]["options"]["baseURL"] == "http://localhost:1134/v1") check("baseURL localhost", d["provider"]["llmhost"]["options"]["baseURL"] == "http://localhost:1134/v1")
check("apiKey -> llm-host key file", str(paths.KEY_FILE) in d["provider"]["llmhost"]["options"]["apiKey"]) check("apiKey -> llm-host key file", str(paths.KEY_FILE) in d["provider"]["llmhost"]["options"]["apiKey"])
check("model set", d["model"] == "llmhost/ornith-1.5-9b", d.get("model")) check("model set to the alias", d["model"] == "llmhost/default", d.get("model"))
mods = d["provider"]["llmhost"]["models"] mods = d["provider"]["llmhost"]["models"]
check("model keyed by slug", "qwen3.8-27b" in mods, list(mods)) check("exactly one entry", list(mods) == ["default"], list(mods))
check("label = title + slug", mods["qwen3.8-27b"]["name"] == "Qwen3.8 27B \u00b7 qwen3.8-27b (Local)", mods["qwen3.8-27b"]["name"]) check("keyed by the API alias", list(mods) == [plan.SERVED_ALIAS])
check("active model marked loaded", mods[CFG["active"]]["name"].endswith("(Local, loaded)"), mods[CFG["active"]]["name"]) check("label names the loaded model", mods["default"]["name"] == "Default model \u00b7 Ornith 1.5 9B (Local)", mods["default"]["name"])
check("only the active one is marked", check("limits come from the loaded model",
sum(v["name"].endswith(", loaded)") for v in mods.values()) == 1, mods["default"]["limit"]["context"] == next(m["est_context"] for m in CFG["models"] if m["name"] == CFG["active"]),
[v["name"] for v in mods.values()]) mods["default"]["limit"])
check("slug searchable for every model", all(k in v["name"] for k, v in mods.items())) check("reasoning flag from the loaded model", mods["default"].get("reasoning") is True, mods["default"])
print("\n2. local + remote side by side") print("\n2. local + remote side by side")
rp, rb = remote("popos.local") rp, rb = remote("popos.local")
@ -53,9 +53,9 @@ st, path, prov, authcl = opencode.configure(CFG)
d = load() d = load()
check("remote id is llmhost-popos", rp == "llmhost-popos", rp) check("remote id is llmhost-popos", rp == "llmhost-popos", rp)
check('remote name is "LLMHost (popos.local)"', rb["name"] == "LLMHost (popos.local)", rb["name"]) check('remote name is "LLMHost (popos.local)"', rb["name"] == "LLMHost (popos.local)", rb["name"])
check("remote model label", rb["models"]["qwen3.8-27b"]["name"] == "Qwen3.8 27B \u00b7 qwen3.8-27b (popos.local)", rb["models"]["qwen3.8-27b"]["name"]) check("remote has one entry too", list(rb["models"]) == ["default"], list(rb["models"]))
check("remote block is NOT marked loaded", not any(", loaded)" in v["name"] for v in rb["models"].values()), check("remote label names no model (it would go stale)",
[v["name"] for v in rb["models"].values()]) rb["models"]["default"]["name"] == "Default model (popos.local)", rb["models"]["default"]["name"])
check("local added alongside", sorted(d["provider"]) == ["llmhost", "llmhost-popos"], sorted(d["provider"])) check("local added alongside", sorted(d["provider"]) == ["llmhost", "llmhost-popos"], sorted(d["provider"]))
check("remote untouched", d["provider"][rp] == rb) check("remote untouched", d["provider"][rp] == rb)
check("existing model kept", d["model"] == f"{rp}/qwen3.8-27b", d["model"]) check("existing model kept", d["model"] == f"{rp}/qwen3.8-27b", d["model"])
@ -70,24 +70,35 @@ check("remote block intact", d["provider"]["llmhost"] == rb2)
check("local under llmhost-local", d["provider"]["llmhost-local"]["options"]["baseURL"] == "http://localhost:1134/v1") check("local under llmhost-local", d["provider"]["llmhost-local"]["options"]["baseURL"] == "http://localhost:1134/v1")
print("\n4. user renamed the local provider (gap 2)") print("\n4. user renamed the local provider (gap 2)")
reset({"provider": {"mymac": opencode.local_block(CFG)}, "model": "mymac/ornith-1.5-9b"}) reset({"provider": {"mymac": opencode.local_block(CFG)}, "model": "mymac/default"})
st, path, prov, authcl = opencode.configure(CFG) st, path, prov, authcl = opencode.configure(CFG)
d = load() d = load()
check("recognised under new name", prov == "mymac", prov) check("recognised under new name", prov == "mymac", prov)
check("no duplicate added", list(d["provider"]) == ["mymac"], list(d["provider"])) check("no duplicate added", list(d["provider"]) == ["mymac"], list(d["provider"]))
check("status unchanged", st == "unchanged", st) check("nothing to change -> unchanged", st == "unchanged", st)
# But a stale per-model default IS a change worth making.
reset({"provider": {"mymac": opencode.local_block(CFG)}, "model": "mymac/ornith-1.5-9b"})
st, path, prov, authcl = opencode.configure(CFG)
check("a stale default makes it an update", st == "updated", st)
check("and it is migrated", load()["model"] == "mymac/default", load().get("model"))
print("\n5. uninstall: remove local, keep remote, repoint model") print("\n5. uninstall: remove local, keep remote, repoint model")
rp, rb = remote("popos.local") rp, rb = remote("popos.local")
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": "llmhost/ornith-1.5-9b"}) reset({"provider": {"llmhost": opencode.local_block(CFG), rp: rb}, "model": "llmhost/default"})
st, path, removed, new_model = opencode.remove(local=True) st, path, removed, new_model = opencode.remove(local=True)
d = load() d = load()
check("status removed", st == "removed", st) check("status removed", st == "removed", st)
check("removed only local", removed == ["llmhost"], removed) check("removed only local", removed == ["llmhost"], removed)
check("remote survives", list(d["provider"]) == [rp], list(d["provider"])) check("remote survives", list(d["provider"]) == [rp], list(d["provider"]))
first = CFG["models"][0]["name"] check("model repointed to the surviving provider's entry",
check("model repointed to remote's first (plan-order) model", new_model == f"{rp}/{plan.SERVED_ALIAS}" and d["model"] == new_model, (new_model, d.get("model")))
new_model == f"{rp}/{first}" and d["model"] == new_model, (new_model, d.get("model"))) # An older remote block, pasted before the single-entry change, still lists every model;
# the fallback takes its first in plan order rather than whichever name sorts first.
legacy = {**rb, "models": {m["name"]: {"name": m["name"]} for m in CFG["models"]}}
reset({"provider": {"llmhost": opencode.local_block(CFG), rp: legacy}, "model": "llmhost/default"})
st, path, removed, new_model = opencode.remove(local=True)
check("legacy multi-model block falls back to its first",
new_model == f"{rp}/{CFG['models'][0]['name']}", new_model)
print("\n6. uninstall must NOT glob llmhost*") print("\n6. uninstall must NOT glob llmhost*")
reset({"provider": {rp: rb}, "model": f"{rp}/qwen3.8-27b"}) reset({"provider": {rp: rb}, "model": f"{rp}/qwen3.8-27b"})
@ -249,13 +260,16 @@ check("config dir gone", not paths.CONFIG_DIR.exists())
check("a reinstall mints a different key", paths.api_key(create=True).strip() != key2.strip()) check("a reinstall mints a different key", paths.api_key(create=True).strip() != key2.strip())
print("\n20. sync() refreshes an existing block after a switch") print("\n20. sync() refreshes an existing block after a switch")
reset({"provider": {"llmhost": opencode.local_block(CFG)}, "model": "llmhost/" + CFG["active"]}) reset({"provider": {"llmhost": opencode.local_block(CFG)}, "model": "llmhost/default"})
switched = dict(CFG, active="qwen3-coder") switched = dict(CFG, active="qwen3-coder")
prov = opencode.sync(switched) prov = opencode.sync(switched)
mods = load()["provider"]["llmhost"]["models"] d = load()
mods = d["provider"]["llmhost"]["models"]
check("reported the provider", prov == "llmhost", prov) check("reported the provider", prov == "llmhost", prov)
check("new model marked loaded", mods["qwen3-coder"]["name"].endswith("(Local, loaded)"), mods["qwen3-coder"]["name"]) check("still one entry, same id", list(mods) == ["default"], list(mods))
check("old one unmarked", not mods[CFG["active"]]["name"].endswith(", loaded)"), mods[CFG["active"]]["name"]) check("label follows the switch", "Qwen3 Coder 30B A3B" in mods["default"]["name"], mods["default"]["name"])
check("the client's saved default still resolves", d["model"] == "llmhost/default", d.get("model"))
check("reasoning dropped for a non-reasoning model", "reasoning" not in mods["default"], mods["default"])
check("idempotent", opencode.sync(switched) is None) check("idempotent", opencode.sync(switched) is None)
print("\n21. sync() never wires opencode up on its own") print("\n21. sync() never wires opencode up on its own")
@ -268,4 +282,18 @@ check("foreign provider untouched", load()["provider"] == {"popos-vllm": foreign
reset({"provider": {"mymac": opencode.local_block(CFG)}}) reset({"provider": {"mymac": opencode.local_block(CFG)}})
check("finds a renamed local block", opencode.sync(dict(CFG, active="qwen3-coder")) == "mymac") check("finds a renamed local block", opencode.sync(dict(CFG, active="qwen3-coder")) == "mymac")
check.section("22. a default naming a specific model is migrated to the alias")
for old_model, expect in (("llmhost/qwen3.8-27b", "llmhost/default"),
("llmhost/ornith-1.5-9b", "llmhost/default"),
("llmhost/default", "llmhost/default"),
("popos-vllm/qwen3.8-27b", "popos-vllm/qwen3.8-27b"),
("llmhost-popos/qwen3.8-27b", "llmhost-popos/qwen3.8-27b")):
reset({"provider": {"llmhost": opencode.local_block(CFG)}, "model": old_model})
opencode.configure(CFG)
got = load().get("model")
check(f"{old_model} -> {expect}", got == expect, got)
reset({"provider": {"mymac": opencode.local_block(CFG)}, "model": "mymac/qwen3-coder"})
opencode.sync(dict(CFG, active="qwen3-coder"))
check("migrated under a renamed provider too", load()["model"] == "mymac/default", load().get("model"))
check.done(ROOT) check.done(ROOT)

View file

@ -82,6 +82,18 @@ check("200 when absent", post(None)[0] == 200)
check("200 when empty", post("")[0] == 200) check("200 when empty", post("")[0] == 200)
check("200 when blank", post(" ")[0] == 200) check("200 when blank", post(" ")[0] == 200)
check.section("4b. the stable alias always means whatever is loaded")
from llmhost import plan
check("alias accepted", post(plan.SERVED_ALIAS)[0] == 200, post(plan.SERVED_ALIAS)[0])
check("alias is 'default'", plan.SERVED_ALIAS == "default")
seen.clear()
post(plan.SERVED_ALIAS)
check("still forwarded as default_model", seen and seen[-1].get("model") == "default_model", seen[-1] if seen else None)
check("vLLM is told to serve it as a second name",
plan.vllm_args({"name": "m", "context": 1024}, {"repo": "r", "util": 0.9}, 8000, 1)[1:4]
== ["--served-model-name", "m", plan.SERVED_ALIAS],
plan.vllm_args({"name": "m", "context": 1024}, {"repo": "r", "util": 0.9}, 8000, 1)[:5])
print("\n5. a model that ISN'T loaded is refused, not silently answered") print("\n5. a model that ISN'T loaded is refused, not silently answered")
code, body = post("qwen3.8-27b") code, body = post("qwen3.8-27b")
check("404", code == 404, code) check("404", code == 404, code)