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
32
README.md
32
README.md
|
|
@ -52,8 +52,9 @@ PYTHONPATH=. python3 -P -m llmhost plan --simulate apple:64 # a 64 GB Mac
|
||||||
| `llmhost key` | print the API key |
|
| `llmhost key` | print the API key |
|
||||||
| `llmhost opencode-setup` | install opencode here if needed and connect it to this server |
|
| `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 opencode-config` | print what to add to opencode on another machine |
|
||||||
|
| `llmhost opencode-remove` | take llm-host back out of this machine's opencode config (`--host` for a retired remote server, `--all` for every one) |
|
||||||
| `llmhost update` | pull the latest llm-host and re-plan (`--backend` also upgrades vLLM/MLX) |
|
| `llmhost update` | pull the latest llm-host and re-plan (`--backend` also upgrades vLLM/MLX) |
|
||||||
| `llmhost uninstall [--purge] [--models]` | remove services and backends; asks before deleting downloaded models (`--models` deletes without asking) |
|
| `llmhost uninstall [--purge] [--models]` | remove services, backends and this machine's opencode provider; asks before deleting downloaded models (`--models` deletes without asking) |
|
||||||
|
|
||||||
The dashboard (`http://<host>.local:11340`) shows the active model, throughput, KV cache, GPU utilization,
|
The dashboard (`http://<host>.local:11340`) shows the active model, throughput, KV cache, GPU utilization,
|
||||||
temperature and power with 10-minute charts, the server log, and buttons to switch models or stop the server.
|
temperature and power with 10-minute charts, the server log, and buttons to switch models or stop the server.
|
||||||
|
|
@ -62,14 +63,37 @@ temperature and power with 10-minute charts, the server log, and buttons to swit
|
||||||
|
|
||||||
**On the server itself**, setup handles it: if opencode isn't installed it offers to install it (official
|
**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`
|
installer, into `~/.opencode/bin`), then adds an `llmhost` provider to `~/.config/opencode/opencode.json`
|
||||||
pointing at `http://localhost:<api port>/v1` and reading the key straight from llm-host's key file. Other
|
pointing at `http://localhost:<api port>/v1` and reading the key straight from llm-host's key file. It shows up
|
||||||
providers and your default model are left alone; the first change backs the file up as `opencode.json.before-llmhost`.
|
in opencode as **LLMHost (Local)**. 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`
|
`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`.
|
(`--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.
|
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
|
**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.
|
that copies the API key over. That block is named **LLMHost (<the server's hostname>)** — e.g. `LLMHost (popos.local)`
|
||||||
|
— under the provider id `llmhost-<shorthost>`. Only one model is loaded at a time; pick the one the server is
|
||||||
|
currently running.
|
||||||
|
|
||||||
|
### One opencode, several servers
|
||||||
|
|
||||||
|
The two paths use different provider ids, so a single opencode config can point at a local server and any number
|
||||||
|
of remote ones at once, each named after the machine it reaches:
|
||||||
|
|
||||||
|
| | provider id | shows up as | API key |
|
||||||
|
|---|---|---|---|
|
||||||
|
| local | `llmhost` | `LLMHost (Local)` | read straight from `~/.config/llm-host/api_key` |
|
||||||
|
| remote | `llmhost-<shorthost>` | `LLMHost (<host>)` | copied to `~/.config/opencode/llmhost-<shorthost>.key` |
|
||||||
|
|
||||||
|
Which block belongs to *this* machine is decided by the key-file reference it carries, not by its name. So the
|
||||||
|
provider is still recognised after you rename it, a remote provider that happens to sit under the `llmhost` id is
|
||||||
|
never overwritten (setup takes `llmhost-local` instead and says so), and `uninstall` removes only the local
|
||||||
|
provider — remote ones, and providers llm-host didn't create, are left in place. If a provider's default model
|
||||||
|
goes away with it, `model` is repointed at a surviving llm-host provider, and dropped only if there is none.
|
||||||
|
|
||||||
|
Retiring a server is the one thing the servers can't do for each other: uninstalling on `popos` can't reach the
|
||||||
|
clients pointing at it. On each client, run `llmhost opencode-remove --host popos.local` (or delete the block by
|
||||||
|
hand if llm-host isn't installed there).
|
||||||
|
|
||||||
## How models are chosen
|
## How models are chosen
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -209,15 +209,19 @@ def setup_opencode(cfg, ask, install_ok=False, later="llmhost opencode-setup"):
|
||||||
say("opencode's installer failed; see the output above. Retry later with: llmhost opencode-setup")
|
say("opencode's installer failed; see the output above. Retry later with: llmhost opencode-setup")
|
||||||
return
|
return
|
||||||
say("opencode installed to ~/.opencode/bin (open a new terminal, or run: export PATH=\"$HOME/.opencode/bin:$PATH\")")
|
say("opencode installed to ~/.opencode/bin (open a new terminal, or run: export PATH=\"$HOME/.opencode/bin:$PATH\")")
|
||||||
status, path = opencode.configure(cfg)
|
status, path, prov = opencode.configure(cfg)
|
||||||
if status == "has-comments":
|
if status in ("has-comments", "unparsable"):
|
||||||
say(f"\n{path} has comments, which an automatic edit would delete, so it was left as is.\n"
|
why = "has comments, which an automatic edit would delete" if status == "has-comments" else "isn't valid JSON"
|
||||||
f"Add this to its \"provider\" section yourself:\n{opencode.snippet(cfg)}")
|
say(f"\n{path} {why}, so it was left as is.\n"
|
||||||
|
f"Add this to its \"provider\" section yourself:\n{opencode.snippet(cfg, prov)}")
|
||||||
return
|
return
|
||||||
msg = {"added": "Added", "updated": "Updated", "unchanged": "Already up to date:"}[status]
|
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).")
|
label = f"{opencode.DISPLAY} ({opencode.LOCAL_LABEL})"
|
||||||
|
say(f"\nopencode: {msg} the `{prov}` provider \u2014 {label} \u2014 in {path} (http://localhost:{cfg['api_port']}/v1).")
|
||||||
|
if prov != opencode.PROVIDER:
|
||||||
|
say(f"(`{opencode.PROVIDER}` is taken by another provider, which was left alone.)")
|
||||||
if status == "added":
|
if status == "added":
|
||||||
say(f"Start it with: opencode (pick a model with /models; this server answers as {opencode.PROVIDER}/{cfg['active']})")
|
say(f"Start it with: opencode (pick a model with /models; this server answers as {prov}/{cfg['active']})")
|
||||||
|
|
||||||
|
|
||||||
def cmd_opencode_setup(a):
|
def cmd_opencode_setup(a):
|
||||||
|
|
@ -459,11 +463,11 @@ def cmd_download(a):
|
||||||
def cmd_opencode(a):
|
def cmd_opencode(a):
|
||||||
cfg = _service_check()
|
cfg = _service_check()
|
||||||
host = a.host or default_host()
|
host = a.host or default_host()
|
||||||
prov = a.provider or f"llmhost-{host.split('.')[0]}"
|
prov = a.provider or opencode.remote_provider(host)
|
||||||
keyfile = f"~/.config/opencode/{prov}.key"
|
keyfile = opencode.remote_key_file(prov)
|
||||||
snippet = {
|
snippet = {
|
||||||
"$schema": "https://opencode.ai/config.json",
|
"$schema": "https://opencode.ai/config.json",
|
||||||
"provider": {prov: opencode.provider_block(cfg, host, keyfile, host.split(".")[0])},
|
"provider": {prov: opencode.provider_block(cfg, host, keyfile, host)},
|
||||||
"model": f"{prov}/{cfg['active']}",
|
"model": f"{prov}/{cfg['active']}",
|
||||||
}
|
}
|
||||||
if a.json:
|
if a.json:
|
||||||
|
|
@ -480,7 +484,10 @@ On another machine running opencode:
|
||||||
2. Merge this into ~/.config/opencode/opencode.json:
|
2. Merge this into ~/.config/opencode/opencode.json:
|
||||||
""")
|
""")
|
||||||
say(json.dumps(snippet, indent=2))
|
say(json.dumps(snippet, indent=2))
|
||||||
say(f"\nOnly the active model answers at a time; switch with `llmhost switch <name>` or the dashboard.")
|
say(f"""
|
||||||
|
It shows up in opencode as "{opencode.DISPLAY} ({host})". Only the active model answers at a
|
||||||
|
time; switch with `llmhost switch <name>` or the dashboard. If this server goes away, remove
|
||||||
|
the block there with: llmhost opencode-remove --host {host}""")
|
||||||
|
|
||||||
|
|
||||||
def cmd_update(a):
|
def cmd_update(a):
|
||||||
|
|
@ -526,6 +533,14 @@ def cmd_uninstall(a):
|
||||||
for d in ("venv-vllm", "venv-mlx", "cuda", "nvcc-test"):
|
for d in ("venv-vllm", "venv-mlx", "cuda", "nvcc-test"):
|
||||||
shutil.rmtree(paths.DATA / d, ignore_errors=True)
|
shutil.rmtree(paths.DATA / d, ignore_errors=True)
|
||||||
say("Removed services and backend environments.")
|
say("Removed services and backend environments.")
|
||||||
|
# Before the --purge below: the provider is identified by its reference to KEY_FILE.
|
||||||
|
oc_status, oc_path, oc_removed, oc_model = opencode.remove(local=True)
|
||||||
|
if oc_status == "removed":
|
||||||
|
say(f"opencode: removed {', '.join('`' + r + '`' for r in oc_removed)} from {oc_path}."
|
||||||
|
+ (f" Its default model is now {oc_model}." if oc_model else ""))
|
||||||
|
elif oc_status in ("has-comments", "unparsable"):
|
||||||
|
why = "has comments" if oc_status == "has-comments" else "isn't valid JSON"
|
||||||
|
say(f"opencode: {oc_path} {why}, so it was left alone; remove the llm-host provider by hand.")
|
||||||
if a.purge:
|
if a.purge:
|
||||||
shutil.rmtree(paths.CONFIG_DIR, ignore_errors=True)
|
shutil.rmtree(paths.CONFIG_DIR, ignore_errors=True)
|
||||||
shutil.rmtree(paths.DATA, ignore_errors=True)
|
shutil.rmtree(paths.DATA, ignore_errors=True)
|
||||||
|
|
@ -554,6 +569,22 @@ def cmd_uninstall(a):
|
||||||
+ " ".join(cmd).replace(str(paths.HOME), "~"))
|
+ " ".join(cmd).replace(str(paths.HOME), "~"))
|
||||||
|
|
||||||
|
|
||||||
|
def cmd_opencode_remove(a):
|
||||||
|
explicit = bool(a.provider or a.host or a.all)
|
||||||
|
status, path, removed, new_model = opencode.remove(
|
||||||
|
prov_ids=[a.provider] if a.provider else None,
|
||||||
|
local=not explicit, host=a.host, every=a.all)
|
||||||
|
if status in ("has-comments", "unparsable"):
|
||||||
|
why = "has comments" if status == "has-comments" else "isn't valid JSON"
|
||||||
|
raise SystemExit(f"{path} {why}; edit it by hand.")
|
||||||
|
if status == "none":
|
||||||
|
say(f"No matching llm-host provider in {path}.")
|
||||||
|
return
|
||||||
|
say(f"Removed {', '.join('`' + r + '`' for r in removed)} from {path}.")
|
||||||
|
if new_model:
|
||||||
|
say(f"opencode's default model is now {new_model}.")
|
||||||
|
|
||||||
|
|
||||||
def cmd_run_model(a):
|
def cmd_run_model(a):
|
||||||
cfg = _service_check()
|
cfg = _service_check()
|
||||||
cat = paths.load_catalog()
|
cat = paths.load_catalog()
|
||||||
|
|
@ -626,6 +657,12 @@ def main(argv=None):
|
||||||
s.add_argument("--provider", help="opencode provider id")
|
s.add_argument("--provider", help="opencode provider id")
|
||||||
s.add_argument("--json", action="store_true", help="print only the JSON")
|
s.add_argument("--json", action="store_true", help="print only the JSON")
|
||||||
s.set_defaults(fn=cmd_opencode)
|
s.set_defaults(fn=cmd_opencode)
|
||||||
|
s = sub.add_parser("opencode-remove", help="remove llm-host providers from this machine's opencode config")
|
||||||
|
s.add_argument("--host", help="remove the provider pointing at this host (a retired remote server)")
|
||||||
|
s.add_argument("--provider", help="remove this provider id")
|
||||||
|
s.add_argument("--all", action="store_true", help="remove every llm-host provider, local and remote")
|
||||||
|
s.set_defaults(fn=cmd_opencode_remove)
|
||||||
|
|
||||||
s = sub.add_parser("update", help="pull the latest llm-host and re-plan")
|
s = sub.add_parser("update", help="pull the latest llm-host and re-plan")
|
||||||
s.add_argument("--backend", action="store_true", help="also reinstall/upgrade the backend")
|
s.add_argument("--backend", action="store_true", help="also reinstall/upgrade the backend")
|
||||||
s.set_defaults(fn=cmd_update)
|
s.set_defaults(fn=cmd_update)
|
||||||
|
|
|
||||||
|
|
@ -1,18 +1,33 @@
|
||||||
"""opencode integration: install it if missing, and register llm-host as a provider.
|
"""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
|
Two shapes of provider, both created from here:
|
||||||
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.
|
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 json
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
from . import paths
|
from . import paths
|
||||||
|
|
||||||
PROVIDER = "llmhost"
|
PROVIDER = "llmhost"
|
||||||
|
DISPLAY = "LLMHost"
|
||||||
|
LOCAL_LABEL = "Local"
|
||||||
|
LOCALHOSTS = ("localhost", "127.0.0.1", "::1", "[::1]")
|
||||||
INSTALL_URL = "https://opencode.ai/install"
|
INSTALL_URL = "https://opencode.ai/install"
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -43,6 +58,19 @@ def config_file():
|
||||||
return d / "opencode.json"
|
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):
|
def provider_block(cfg, host, key_path, label):
|
||||||
models = {}
|
models = {}
|
||||||
for m in cfg["models"]:
|
for m in cfg["models"]:
|
||||||
|
|
@ -53,12 +81,52 @@ def provider_block(cfg, host, key_path, label):
|
||||||
models[m["name"]] = entry
|
models[m["name"]] = entry
|
||||||
return {
|
return {
|
||||||
"npm": "@ai-sdk/openai-compatible",
|
"npm": "@ai-sdk/openai-compatible",
|
||||||
"name": f"llm-host ({label})",
|
"name": f"{DISPLAY} ({label})",
|
||||||
"options": {"baseURL": f"http://{host}:{cfg['api_port']}/v1", "apiKey": "{file:" + key_path + "}"},
|
"options": {"baseURL": f"http://{host}:{cfg['api_port']}/v1", "apiKey": key_ref(key_path)},
|
||||||
"models": models,
|
"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):
|
def _strip_jsonc(text):
|
||||||
"""Remove comments and trailing commas outside strings. Returns (clean_text, had_comments)."""
|
"""Remove comments and trailing commas outside strings. Returns (clean_text, had_comments)."""
|
||||||
out, i, n, had_comments = [], 0, len(text), False
|
out, i, n, had_comments = [], 0, len(text), False
|
||||||
|
|
@ -93,41 +161,129 @@ def _strip_jsonc(text):
|
||||||
return "".join(out), had_comments
|
return "".join(out), had_comments
|
||||||
|
|
||||||
|
|
||||||
def configure(cfg):
|
def _read(path):
|
||||||
"""Add or refresh the llmhost provider. Returns (status, path); status is one of
|
"""Returns (data, "") or (None, reason) when the file can't be rewritten safely."""
|
||||||
added, updated, unchanged, or has-comments (file left alone because rewriting would drop them)."""
|
if not path.exists():
|
||||||
path = config_file()
|
return {"$schema": "https://opencode.ai/config.json"}, ""
|
||||||
if path.exists():
|
text = path.read_text()
|
||||||
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:
|
try:
|
||||||
data = json.loads(text)
|
return json.loads(clean), "" # only trailing commas; safe to normalize
|
||||||
except ValueError:
|
except ValueError:
|
||||||
clean, had_comments = _strip_jsonc(text)
|
return None, "unparsable"
|
||||||
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
|
|
||||||
|
|
||||||
|
def _write(path, data, backup=True):
|
||||||
path.parent.mkdir(parents=True, exist_ok=True)
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
if path.exists():
|
if backup and path.exists():
|
||||||
backup = path.with_name(path.name + ".before-llmhost")
|
before = path.with_name(path.name + ".before-llmhost")
|
||||||
if not backup.exists():
|
if not before.exists():
|
||||||
shutil.copy2(path, backup)
|
shutil.copy2(path, before)
|
||||||
tmp = path.with_name(path.name + ".tmp")
|
tmp = path.with_name(path.name + ".tmp")
|
||||||
tmp.write_text(json.dumps(data, indent=2) + "\n")
|
tmp.write_text(json.dumps(data, indent=2) + "\n")
|
||||||
os.replace(tmp, path)
|
os.replace(tmp, path)
|
||||||
return ("updated" if existed else "added"), path
|
|
||||||
|
|
||||||
|
|
||||||
def snippet(cfg):
|
def configure(cfg):
|
||||||
return json.dumps({"provider": {PROVIDER: provider_block(cfg, "localhost", str(paths.KEY_FILE), "local")}}, indent=2)
|
"""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