opencode: name providers LLMHost (Local) / LLMHost (<host>), identify by key file
The local and remote setup paths already used distinct provider ids, so one
opencode config can point at a local server and any number of remote ones.
Name them after the machine they reach so they're tellable apart in /models.
Decide which block is *this* machine's by the key-file reference it carries
rather than by its name, so:
- a provider renamed by hand is still recognised and updated in place
instead of a second one being added next to it;
- a remote provider sitting under the `llmhost` id is no longer silently
overwritten with a localhost baseURL (setup takes `llmhost-local` and
says so) -- the one-shot .before-llmhost backup could not recover it;
- uninstall removes only the local provider, never `llmhost-*` blocks for
servers that are still running, and never providers it didn't create.
Add `llmhost opencode-remove` for the case the servers can't handle for each
other: uninstalling on a server can't reach the clients pointing at it. Wire
uninstall to it, repointing opencode's default model at a surviving llm-host
provider and dropping `model` only when none is left.
Also split config read/write out of configure() and report `unparsable`: a
syntactically broken opencode.json used to raise ValueError mid-setup.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
a250812d42
commit
504ea3018a
3 changed files with 264 additions and 47 deletions
|
|
@ -1,18 +1,33 @@
|
|||
"""opencode integration: install it if missing, and register llm-host as a provider.
|
||||
|
||||
On the server itself the provider points at localhost and reads the key straight from
|
||||
llm-host's key file, so nothing has to be copied. Re-running keeps the provider's port and
|
||||
model list in sync with the current plan. Other providers and settings are left untouched.
|
||||
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"
|
||||
|
||||
|
||||
|
|
@ -43,6 +58,19 @@ def config_file():
|
|||
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"]:
|
||||
|
|
@ -53,12 +81,52 @@ def provider_block(cfg, host, key_path, label):
|
|||
models[m["name"]] = entry
|
||||
return {
|
||||
"npm": "@ai-sdk/openai-compatible",
|
||||
"name": f"llm-host ({label})",
|
||||
"options": {"baseURL": f"http://{host}:{cfg['api_port']}/v1", "apiKey": "{file:" + key_path + "}"},
|
||||
"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
|
||||
|
|
@ -93,41 +161,129 @@ def _strip_jsonc(text):
|
|||
return "".join(out), had_comments
|
||||
|
||||
|
||||
def configure(cfg):
|
||||
"""Add or refresh the llmhost provider. Returns (status, path); status is one of
|
||||
added, updated, unchanged, or has-comments (file left alone because rewriting would drop them)."""
|
||||
path = config_file()
|
||||
if path.exists():
|
||||
text = path.read_text()
|
||||
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:
|
||||
data = json.loads(text)
|
||||
return json.loads(clean), "" # only trailing commas; safe to normalize
|
||||
except ValueError:
|
||||
clean, had_comments = _strip_jsonc(text)
|
||||
if had_comments:
|
||||
return "has-comments", path
|
||||
data = json.loads(clean) # only trailing commas; safe to normalize
|
||||
else:
|
||||
data = {"$schema": "https://opencode.ai/config.json"}
|
||||
return None, "unparsable"
|
||||
|
||||
before = json.dumps(data, sort_keys=True)
|
||||
providers = data.setdefault("provider", {})
|
||||
existed = PROVIDER in providers
|
||||
providers[PROVIDER] = provider_block(cfg, "localhost", str(paths.KEY_FILE), "local")
|
||||
if "model" not in data:
|
||||
data["model"] = f"{PROVIDER}/{cfg['active']}"
|
||||
if json.dumps(data, sort_keys=True) == before:
|
||||
return "unchanged", path
|
||||
|
||||
def _write(path, data, backup=True):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if path.exists():
|
||||
backup = path.with_name(path.name + ".before-llmhost")
|
||||
if not backup.exists():
|
||||
shutil.copy2(path, backup)
|
||||
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)
|
||||
return ("updated" if existed else "added"), path
|
||||
|
||||
|
||||
def snippet(cfg):
|
||||
return json.dumps({"provider": {PROVIDER: provider_block(cfg, "localhost", str(paths.KEY_FILE), "local")}}, indent=2)
|
||||
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)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue