"""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/.key. Provider id `llmhost-`, display name "LLMHost ()". 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 re import shutil import subprocess from pathlib import Path from urllib.parse import urlsplit from . import paths, plan PROVIDER = "llmhost" DISPLAY = "LLMHost" LOCAL_LABEL = "Local" LOCALHOSTS = ("localhost", "127.0.0.1", "::1", "[::1]") INSTALL_SCRIPT = paths.SRC / "opencode-install.sh" DEFAULT_REPO = "https://git.neilbantoc.dev/pub/llm-host.git" # install.sh's default too 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): """Install opencode the way every machine does: through llm-host's opencode-install.sh, which runs opencode's official installer (into ~/.opencode/bin, added to PATH). Only the install step: this machine's provider is configure()'s, since it reads the key file in place and is kept in sync on every switch.""" log(f"$ {INSTALL_SCRIPT.name} --install-only") r = subprocess.run(["bash", str(INSTALL_SCRIPT), "--install-only"]) return find() if r.returncode == 0 else None def raw_file_url(repo, ref, name): """Where a file in `repo` at `ref` is fetched raw: GitHub's raw host, or the /raw/branch/ path Gitea and Forgejo use. None for a remote that isn't https.""" m = re.match(r"^https://([^/]+)/(.+?)(\.git)?/?$", repo or "") if not m: return None host, path = m.group(1), m.group(2) if host.lower() == "github.com": return f"https://raw.githubusercontent.com/{path}/{ref}/{name}" return f"https://{host}/{path}/raw/branch/{ref}/{name}" _installer = None def installer_url(): """opencode-install.sh's URL in the repo this server was installed from, so the command handed to other machines follows a fork and needs nothing but the API to work. Falls back to the main repo.""" global _installer if _installer is None: def git(*args): try: r = subprocess.run(["git", "-C", str(paths.SRC), *args], capture_output=True, text=True, timeout=5) return r.stdout.strip() if r.returncode == 0 else "" except (OSError, subprocess.TimeoutExpired): return "" ref = git("rev-parse", "--abbrev-ref", "HEAD") _installer = (raw_file_url(git("config", "--get", "remote.origin.url"), ref if ref and ref != "HEAD" else "main", INSTALL_SCRIPT.name) or raw_file_url(DEFAULT_REPO, "main", INSTALL_SCRIPT.name)) return _installer def remote_command(base_url): """The one line another machine runs to connect its opencode to this server.""" return f'/bin/bash -c "$(curl -fsSL {installer_url()})" -- --url {base_url}' def client_targets(cfg, lan_host): """Where other machines reach the API, as [(where, base URL)], most useful first. The API's public address (recorded by `llmhost install-newt`) when there is one, and the local-network address too unless the dashboard is public -- a public dashboard is seen from outside, where a LAN address is only noise.""" lan = ("on your local network", f"http://{lan_host}:{cfg['api_port']}") public = (cfg.get("newt") or {}).get("api_url") if not public: return [lan] out = [("from the internet", public)] if not cfg.get("dashboard_public"): out.append(lan) return out 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 auth_file(): """opencode's credential store (XDG_DATA_HOME, not the config dir).""" return Path(os.environ.get("XDG_DATA_HOME") or paths.HOME / ".local/share") / "opencode" / "auth.json" def clear_auth(*provs): """Drop opencode's cached API key for these providers. Returns the ids cleared. opencode caches a provider's key in its own auth store, and that copy wins over the config: when it is stale, opencode fails auth without even sending a request and asks for the key interactively. llm-host mints a fresh key whenever the config dir is purged, so a cached copy goes stale on every reinstall. Our provider block points at the key file, which never goes stale -- so the cache is only ever a liability for it, and removing the entry makes the file reference authoritative. """ path = auth_file() if not path.exists(): return [] try: data = json.loads(path.read_text()) except (OSError, ValueError): return [] # not ours to repair if not isinstance(data, dict): return [] gone = [p for p in provs if p in data] if not gone: return [] for p in gone: del data[p] try: mode = path.stat().st_mode & 0o777 except OSError: mode = 0o600 tmp = path.with_name(path.name + ".llmhost-tmp") fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode) with os.fdopen(fd, "w") as f: json.dump(data, f, indent=2) f.write("\n") os.replace(tmp, path) return gone 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 model_label(active, label, name_it): """What opencode shows for the single entry. One model is loaded at a time, so there is nothing to choose here -- the label's job is to say which one answers right now. Only where llm-host keeps the block in sync, though: a remote block is pasted once and never refreshed, so naming a model there would be a claim that goes stale on the next switch.""" if name_it and active: return f"Default model \u00b7 {active.get('title') or active['name']} ({label})" return f"Default model ({label})" # The effort levels opencode offers on its own for an OpenAI-compatible reasoning model. # A model's template defines its own set, and one it lacks makes the template raise, so # the block hides those and adds the model's own. (The proxy also maps a stray level to # the nearest real one, so a pasted block that predates a switch still works.) # The reasoning levels opencode offers of its own accord for a model marked `reasoning`. OPENCODE_EFFORTS = ("low", "medium", "high") def effort_variants(): """opencode `variants` that switch its reasoning menu off. The effort level is set on llm-host's dashboard and the proxy drops whatever a client asks for, so a chooser here would be a menu that silently does nothing -- and whose levels this model's template may not even define. One model, one setting, one place to change it.""" return {level: {"disabled": True} for level in OPENCODE_EFFORTS} def provider_block(cfg, host, key_path, label, mark_loaded=False, base_url=None): # A single entry, keyed by the alias the API also answers to. Listing every model that # fits would be a menu of four things that 404 and one that works, and naming the loaded # one would break every client's saved default on each `llmhost switch`. active = next((m for m in cfg["models"] if m["name"] == cfg.get("active")), None) ctx = (active or {}).get("est_context") or min( (m["est_context"] for m in cfg["models"]), default=32768) entry = {"name": model_label(active, label, mark_loaded), "tool_call": True, "limit": {"context": ctx, "output": min(65536, ctx // 2)}} if (active or {}).get("reasoning"): # `reasoning` so opencode renders the thinking blocks; `variants` so it doesn't # offer to set the effort itself. entry["reasoning"] = True entry["variants"] = effort_variants() models = {plan.SERVED_ALIAS: entry} return { "npm": "@ai-sdk/openai-compatible", "name": f"{DISPLAY} ({label})", "options": {"baseURL": base_url or f"http://{host}:{cfg['api_port']}/v1", "apiKey": key_ref(key_path)}, "models": models, } def local_block(cfg): # Only the local block is marked: llm-host keeps it in sync on every switch, whereas a # remote block is a snapshot pasted elsewhere and would go stale the moment it changed. return provider_block(cfg, "localhost", str(paths.KEY_FILE), LOCAL_LABEL, mark_loaded=True) 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, auth_cleared); 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, False 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}/{plan.SERVED_ALIAS}" else: _retarget_model(data, prov) # Unconditional: a cached key for our provider is stale or redundant either way. cleared = bool(clear_auth(prov)) if json.dumps(data, sort_keys=True) == before: return "unchanged", path, prov, cleared _write(path, data) 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): """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] clear_auth(*targets) 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 sync(cfg): """Refresh an existing local provider block -- after a model switch, so the entry's name and limits keep up with what's loaded. Never adds one: if opencode isn't wired up here, switching a model is no reason to wire it. Returns the provider id, or None.""" path = config_file() if not path.exists(): return None data, problem = _read(path) if problem: return None providers = data.get("provider") or {} mine = local_ids(providers) if not mine: return None prov = mine[0] before = json.dumps(data, sort_keys=True) providers[prov] = local_block(cfg) _retarget_model(data, prov) if json.dumps(data, sort_keys=True) == before: return None _write(path, data, backup=False) return prov def snippet(cfg, prov=PROVIDER): return json.dumps({"provider": {prov: local_block(cfg)}}, indent=2)