llm-host/llmhost/opencode.py
Neil Bantoc 13a7def080 opencode: label models with the catalog title, not the slug
/models showed "qwen3.8-27b (Local)" where the catalog already has a name
meant for reading: "Qwen3.8 27B". The dict key stays the slug -- that is the
model id the API answers to -- so only the display name changes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-11-02 23:52:31 -08:00

291 lines
10 KiB
Python

"""opencode integration: install it if missing, and register llm-host as a provider.
Two shapes of provider, both created from here:
local this machine's server, reached over localhost, reading llm-host's key file
directly. Provider id `llmhost`, display name "LLMHost (Local)".
remote another machine's server, reached by hostname with the key copied into
~/.config/opencode/<provider>.key. Provider id `llmhost-<shorthost>`,
display name "LLMHost (<host>)". Printed by `llmhost opencode-config`
for pasting on the client; this module never writes it here.
The two never collide, so one opencode config can point at a local server and any
number of remote ones at once. Which block is *this machine's* is decided by the
key-file reference, not by the provider's name, so a renamed provider is still
recognised and a remote provider that happens to sit under the `llmhost` id is
never overwritten. Other providers and settings are left untouched.
"""
import json
import os
import shutil
import subprocess
from pathlib import Path
from urllib.parse import urlsplit
from . import paths
PROVIDER = "llmhost"
DISPLAY = "LLMHost"
LOCAL_LABEL = "Local"
LOCALHOSTS = ("localhost", "127.0.0.1", "::1", "[::1]")
INSTALL_URL = "https://opencode.ai/install"
def find():
exe = shutil.which("opencode")
if exe:
return exe
p = paths.HOME / ".opencode/bin/opencode"
return str(p) if p.exists() else None
def install(log=print):
"""Run opencode's official installer (installs to ~/.opencode/bin, adds it to PATH)."""
log(f"$ curl -fsSL {INSTALL_URL} | bash")
r = subprocess.run(["bash", "-c", f"set -o pipefail; curl -fsSL {INSTALL_URL} | bash"])
return find() if r.returncode == 0 else None
def config_dir():
return Path(os.environ.get("XDG_CONFIG_HOME") or paths.HOME / ".config") / "opencode"
def config_file():
d = config_dir()
for name in ("opencode.json", "opencode.jsonc"):
if (d / name).exists():
return d / name
return d / "opencode.json"
def remote_provider(host):
"""Provider id for a server reached at `host`."""
return f"{PROVIDER}-{host.split('.')[0]}"
def remote_key_file(prov):
return f"~/.config/opencode/{prov}.key"
def key_ref(key_path):
return "{file:" + str(key_path) + "}"
def provider_block(cfg, host, key_path, label):
models = {}
for m in cfg["models"]:
# Key by the slug -- that's the model id the API answers to -- but show the
# catalog's title, which is what reads well in opencode's /models list.
entry = {"name": f"{m.get('title') or m['name']} ({label})", "tool_call": True,
"limit": {"context": m["est_context"], "output": min(65536, m["est_context"] // 2)}}
if m.get("reasoning"):
entry["reasoning"] = True
models[m["name"]] = entry
return {
"npm": "@ai-sdk/openai-compatible",
"name": f"{DISPLAY} ({label})",
"options": {"baseURL": f"http://{host}:{cfg['api_port']}/v1", "apiKey": key_ref(key_path)},
"models": models,
}
def local_block(cfg):
return provider_block(cfg, "localhost", str(paths.KEY_FILE), LOCAL_LABEL)
def base_host(block):
"""Hostname from a provider's baseURL, or "" if it hasn't got one."""
try:
url = block["options"]["baseURL"]
except (KeyError, TypeError):
return ""
return (urlsplit(url).hostname or "").lower()
def is_local_block(prov_id, block):
"""True when this provider block is *this machine's* llm-host server.
Identified by its key-file reference, which only `configure` ever writes, so the
block is still ours after a rename. The id fallback catches blocks written before
the key moved (LLMHOST_CONFIG), but only alongside a localhost baseURL -- a remote
provider sitting under the `llmhost` id must not match.
"""
if not isinstance(block, dict):
return False
api_key = (block.get("options") or {}).get("apiKey") or ""
if str(paths.KEY_FILE) in api_key:
return True
return prov_id == PROVIDER and base_host(block) in LOCALHOSTS
def local_ids(providers):
return [p for p, block in providers.items() if is_local_block(p, block)]
def ours_ids(providers):
"""Every provider this module created: the local one plus any pasted `llmhost-*`."""
return [p for p, block in providers.items()
if is_local_block(p, block) or p.startswith(PROVIDER + "-")
or (isinstance(block, dict) and str(block.get("name", "")).startswith(DISPLAY + " ("))]
def _strip_jsonc(text):
"""Remove comments and trailing commas outside strings. Returns (clean_text, had_comments)."""
out, i, n, had_comments = [], 0, len(text), False
while i < n:
c = text[i]
if c == '"':
j = i + 1
while j < n and text[j] != '"':
j += 2 if text[j] == "\\" else 1
out.append(text[i:j + 1])
i = j + 1
elif text.startswith("//", i):
had_comments = True
while i < n and text[i] != "\n":
i += 1
elif text.startswith("/*", i):
had_comments = True
end = text.find("*/", i + 2)
i = n if end < 0 else end + 2
elif c == ",":
j = i + 1
while j < n and text[j] in " \t\r\n":
j += 1
if j < n and text[j] in "}]":
i += 1 # trailing comma: drop it
else:
out.append(c)
i += 1
else:
out.append(c)
i += 1
return "".join(out), had_comments
def _read(path):
"""Returns (data, "") or (None, reason) when the file can't be rewritten safely."""
if not path.exists():
return {"$schema": "https://opencode.ai/config.json"}, ""
text = path.read_text()
try:
return json.loads(text), ""
except ValueError:
clean, had_comments = _strip_jsonc(text)
if had_comments:
return None, "has-comments"
try:
return json.loads(clean), "" # only trailing commas; safe to normalize
except ValueError:
return None, "unparsable"
def _write(path, data, backup=True):
path.parent.mkdir(parents=True, exist_ok=True)
if backup and path.exists():
before = path.with_name(path.name + ".before-llmhost")
if not before.exists():
shutil.copy2(path, before)
tmp = path.with_name(path.name + ".tmp")
tmp.write_text(json.dumps(data, indent=2) + "\n")
os.replace(tmp, path)
def configure(cfg):
"""Add or refresh this machine's provider. Returns (status, path, prov_id); status is
added, updated, unchanged, has-comments or unparsable (the last two leave the file alone)."""
path = config_file()
data, problem = _read(path)
if problem:
return problem, path, PROVIDER
providers = data.setdefault("provider", {})
mine = local_ids(providers)
if mine:
prov = mine[0] # ours already, whatever it has been renamed to
elif PROVIDER not in providers:
prov = PROVIDER
else:
# Something else is sitting under `llmhost` (most likely a remote server pasted
# from `opencode-config --provider llmhost`). Don't touch it; take a free id.
prov = f"{PROVIDER}-local"
n = 2
while prov in providers:
prov, n = f"{PROVIDER}-local{n}", n + 1
before = json.dumps(data, sort_keys=True)
existed = prov in providers
providers[prov] = local_block(cfg)
if "model" not in data:
data["model"] = f"{prov}/{cfg['active']}"
if json.dumps(data, sort_keys=True) == before:
return "unchanged", path, prov
_write(path, data)
return ("updated" if existed else "added"), path, prov
def _pick_fallback_model(providers, removed):
"""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.
Providers are taken in id order so the choice is stable."""
for prov in sorted(set(ours_ids(providers)) - set(removed)):
models = (providers.get(prov) or {}).get("models") or {}
if models:
return f"{prov}/{next(iter(models))}"
return None
def remove(prov_ids=None, local=True, host=None, every=False):
"""Remove llm-host providers from this machine's opencode config.
local this machine's provider, found by key-file reference
host the provider pointing at `host` (a remote server being retired)
every every provider this module created, local and remote
Returns (status, path, removed_ids, new_model); status is removed, none or a
problem code. `model` is repointed at a surviving llm-host provider if it named
one that went away, and dropped only when none is left. Providers llm-host didn't
create are never removed and never become the fallback -- including ones pointing
at the same `host`, since retiring our provider is no reason to delete theirs.
"""
path = config_file()
if not path.exists():
return "none", path, [], None
data, problem = _read(path)
if problem:
return problem, path, [], None
providers = data.get("provider") or {}
targets = set(prov_ids or [])
if every:
targets |= set(ours_ids(providers))
if local:
targets |= set(local_ids(providers))
if host:
# Scoped to providers we created: another tool's provider may well point at the
# same server, and retiring ours is no reason to delete theirs.
h = host.lower().split(".")[0]
targets |= {p for p in ours_ids(providers)
if base_host(providers[p]).split(".")[0] == h}
targets &= set(providers)
if not targets:
return "none", path, [], None
for prov in targets:
del providers[prov]
new_model = None
model = data.get("model") or ""
if model.split("/", 1)[0] in targets:
new_model = _pick_fallback_model(providers, targets)
if new_model:
data["model"] = new_model
else:
del data["model"]
if not providers:
data.pop("provider", None)
_write(path, data, backup=False)
return "removed", path, sorted(targets), new_model
def snippet(cfg, prov=PROVIDER):
return json.dumps({"provider": {prov: local_block(cfg)}}, indent=2)