From 7ad0642d2e9afa8745d541812b80277710e2888e Mon Sep 17 00:00:00 2001 From: neil Date: Mon, 2 Nov 2026 05:37:35 -0800 Subject: [PATCH] Offer to install opencode and connect it to the local server After setup, if opencode is missing, offer to install it with its official installer; then add an `llmhost` provider pointing at http://localhost:/v1 that reads llm-host's key file directly. Other providers and the default model are kept, the original config is backed up once, trailing commas are tolerated, and a config with comments is left untouched (the block is printed instead). Re-runs and `llmhost update` keep the provider's port and models in sync. New: `llmhost opencode-setup`, and setup flags --opencode / --no-opencode. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01QaE1hpvyZTJixEbUUMj9Ca --- README.md | 16 ++++-- llmhost/cli.py | 60 ++++++++++++++------ llmhost/opencode.py | 133 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 189 insertions(+), 20 deletions(-) create mode 100644 llmhost/opencode.py diff --git a/README.md b/README.md index 1816b36..46ad722 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,8 @@ PYTHONPATH=. python3 -P -m llmhost plan --simulate apple:64 # a 64 GB Mac | `llmhost logs -f` | follow the model server log | | `llmhost start` / `stop` / `restart` | control the model server (stop frees the GPU) | | `llmhost key` | print the API key | -| `llmhost opencode-config` | print what to add to opencode on your client machine | +| `llmhost opencode-setup` | install opencode here if needed and connect it to this server | +| `llmhost opencode-config` | print what to add to opencode on another machine | | `llmhost update` | pull the latest llm-host and re-plan (`--backend` also upgrades vLLM/MLX) | | `llmhost uninstall [--purge]` | remove services and backends (downloaded models are kept) | @@ -58,9 +59,16 @@ temperature and power with 10-minute charts, the server log, and buttons to swit ## Connecting opencode -Run `llmhost opencode-config` on the server. It prints a provider block for `~/.config/opencode/opencode.json` -and a one-liner that copies the API key to the client. Only one model is loaded at a time; pick the one -the server is currently running. +**On the server itself**, setup handles it: if opencode isn't installed it offers to install it (official +installer, into `~/.opencode/bin`), then adds an `llmhost` provider to `~/.config/opencode/opencode.json` +pointing at `http://localhost:/v1` and reading the key straight from llm-host's key file. Other +providers and your default model are left alone; the first change backs the file up as `opencode.json.before-llmhost`. +`llmhost update` keeps the provider's port and model list in sync. Run it on demand with `llmhost opencode-setup` +(`--yes` to install without asking); skip it during setup with `--no-opencode`, or install without asking with `--opencode`. +A config with comments (`.jsonc`) is never rewritten, since that would drop them; setup prints the block to paste instead. + +**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. Only one model is loaded at a time; pick the one the server is currently running. ## How models are chosen diff --git a/llmhost/cli.py b/llmhost/cli.py index 4eaba89..0fa3a30 100644 --- a/llmhost/cli.py +++ b/llmhost/cli.py @@ -9,7 +9,7 @@ import sys import time import urllib.request -from . import hfcache, hw, paths, plan, service +from . import hfcache, hw, opencode, paths, plan, service from .backends import vllm as vllm_backend # stdlib-only module; safe to import anywhere VERSION = "0.1.0" @@ -144,9 +144,40 @@ Done. API: http://{host}:{cfg['api_port']}/v1 (OpenAI-compatible) Dashboard: http://{host}:{cfg['web_port']} API key: {paths.KEY_FILE} (show it with: llmhost key) - Model: {active} — {"not started yet; run: llmhost start" if a.no_start else ("loading" if hfcache.is_downloaded(first["repo"]) else "downloading, then loading") + "; watch with: llmhost logs -f"} + Model: {active} — {"not started yet; run: llmhost start" if a.no_start else ("loading" if hfcache.is_downloaded(first["repo"]) else "downloading, then loading") + "; watch with: llmhost logs -f"}""") + if not a.no_opencode: + setup_opencode(cfg, ask=sys.stdin.isatty() and not a.yes, install_ok=a.opencode) + say(f"\nOther machines: run `llmhost opencode-config` here for their opencode setup.") -Connect opencode: run `llmhost opencode-config` and follow what it prints.""") + +def setup_opencode(cfg, ask, install_ok=False, later="llmhost opencode-setup"): + """Offer to install opencode, then point it at this server via localhost.""" + if not opencode.find(): + if not install_ok: + if not ask: + say(f"\nopencode isn't installed. To install it and connect it to llm-host: {later}") + return + if input("\nopencode isn't installed. Install it and connect it to llm-host? [Y/n] ").strip().lower() not in ("", "y", "yes"): + say("Skipped. Later: llmhost opencode-setup") + return + say("\n== Installing opencode ==") + if not opencode.install(say): + say("opencode's installer failed; see the output above. Retry later with: llmhost opencode-setup") + return + say("opencode installed to ~/.opencode/bin (open a new terminal, or run: export PATH=\"$HOME/.opencode/bin:$PATH\")") + status, path = opencode.configure(cfg) + if status == "has-comments": + say(f"\n{path} has comments, which an automatic edit would delete, so it was left as is.\n" + f"Add this to its \"provider\" section yourself:\n{opencode.snippet(cfg)}") + return + msg = {"added": "Added", "updated": "Updated", "unchanged": "Already up to date:"}[status] + say(f"\nopencode: {msg} the `{opencode.PROVIDER}` provider in {path} (http://localhost:{cfg['api_port']}/v1).") + if status == "added": + say(f"Start it with: opencode (pick a model with /models; this server answers as {opencode.PROVIDER}/{cfg['active']})") + + +def cmd_opencode_setup(a): + setup_opencode(_service_check(), ask=sys.stdin.isatty(), install_ok=a.yes, later="llmhost opencode-setup --yes") def port_free(port): @@ -292,25 +323,17 @@ def cmd_opencode(a): host = a.host or default_host() prov = a.provider or f"llmhost-{host.split('.')[0]}" keyfile = f"~/.config/opencode/{prov}.key" - models = {} - for m in cfg["models"]: - entry = {"name": f"{m['name']} ({host.split('.')[0]})", "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 snippet = { "$schema": "https://opencode.ai/config.json", - "provider": {prov: { - "npm": "@ai-sdk/openai-compatible", "name": f"llm-host ({host})", - "options": {"baseURL": f"http://{host}:{cfg['api_port']}/v1", "apiKey": "{file:" + keyfile + "}"}, - "models": models}}, + "provider": {prov: opencode.provider_block(cfg, host, keyfile, host.split(".")[0])}, "model": f"{prov}/{cfg['active']}", } if a.json: say(json.dumps(snippet, indent=2)) return - say(f"""On the machine running opencode: + say(f"""(On this machine itself, `llmhost opencode-setup` does all of this automatically.) + +On another machine running opencode: 1. Save the API key: mkdir -p ~/.config/opencode && ssh {os.environ.get('USER', 'you')}@{host} 'cat {paths.KEY_FILE}' > {keyfile} && chmod 600 {keyfile} @@ -382,6 +405,8 @@ def main(argv=None): s.add_argument("--api-port", type=int) s.add_argument("--web-port", type=int) s.add_argument("--no-start", action="store_true", help="install everything but don't start the services") + s.add_argument("--opencode", action="store_true", help="install opencode without asking if it's missing") + s.add_argument("--no-opencode", action="store_true", help="don't install or configure opencode") s.add_argument("--skip-backend", action="store_true", help=argparse.SUPPRESS) s.set_defaults(fn=cmd_setup) @@ -408,7 +433,10 @@ def main(argv=None): s = sub.add_parser("download", help="download a model ahead of time") s.add_argument("model") s.set_defaults(fn=cmd_download) - s = sub.add_parser("opencode-config", help="print opencode setup for connecting to this server") + s = sub.add_parser("opencode-setup", help="install opencode here if needed and add llm-host as a provider") + s.add_argument("--yes", "-y", action="store_true", help="install opencode without asking") + s.set_defaults(fn=cmd_opencode_setup) + s = sub.add_parser("opencode-config", help="print opencode setup for another machine") s.add_argument("--host", help="hostname clients use (default: .local)") s.add_argument("--provider", help="opencode provider id") s.add_argument("--json", action="store_true", help="print only the JSON") diff --git a/llmhost/opencode.py b/llmhost/opencode.py new file mode 100644 index 0000000..365f58d --- /dev/null +++ b/llmhost/opencode.py @@ -0,0 +1,133 @@ +"""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. +""" +import json +import os +import shutil +import subprocess +from pathlib import Path + +from . import paths + +PROVIDER = "llmhost" +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 provider_block(cfg, host, key_path, label): + models = {} + for m in cfg["models"]: + entry = {"name": f"{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"llm-host ({label})", + "options": {"baseURL": f"http://{host}:{cfg['api_port']}/v1", "apiKey": "{file:" + key_path + "}"}, + "models": models, + } + + +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 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() + try: + data = json.loads(text) + 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"} + + 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 + + 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) + 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)