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:
parent
3da3d8ed45
commit
7ad0642d2e
3 changed files with 189 additions and 20 deletions
133
llmhost/opencode.py
Normal file
133
llmhost/opencode.py
Normal file
|
|
@ -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)
|
||||
Loading…
Add table
Add a link
Reference in a new issue