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:<api port>/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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01QaE1hpvyZTJixEbUUMj9Ca
This commit is contained in:
neil 2026-11-02 05:37:35 -08:00
parent 3da3d8ed45
commit 7ad0642d2e
3 changed files with 189 additions and 20 deletions

View file

@ -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: <hostname>.local)")
s.add_argument("--provider", help="opencode provider id")
s.add_argument("--json", action="store_true", help="print only the JSON")