opencode: clear the cached key, and let --purge keep the API key

opencode caches a provider's key in ~/.local/share/opencode/auth.json and that
copy wins over opencode.json: with a stale entry it fails auth without sending
a request at all and asks for the key interactively. Verified by A/B on a live
install -- correct entry works, wrong entry never reaches the server, absent
entry works and reads the key file.

llm-host mints a fresh key whenever the config dir is purged, so the cached
copy went stale on every reinstall. configure() now drops the entry for its own
provider, leaving the {file:...} reference authoritative; it tracks the key file
and cannot go stale. remove() takes the cached key with the provider. Other
providers' credentials are never touched, and an unreadable store is left alone
rather than repaired.

Add `uninstall --purge --keep-key` so the key survives a purge and a reinstall
reuses it -- clients elsewhere then keep working. Warn about the new key when
it doesn't. Factor the purge into purge() so it can be tested without touching
a real install.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Neil Bantoc 2026-11-03 00:19:54 -08:00
parent 13a7def080
commit 8c6615dbb4
3 changed files with 101 additions and 11 deletions

View file

@ -54,7 +54,7 @@ PYTHONPATH=. python3 -P -m llmhost plan --simulate apple:64 # a 64 GB Mac
| `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 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, backends and this machine's opencode provider; asks before deleting downloaded models (`--models` deletes without asking) | | `llmhost uninstall [--purge] [--models] [--keep-key]` | remove services, backends and this machine's opencode provider; asks before deleting downloaded models (`--models` deletes without asking). `--purge --keep-key` keeps the API key so a reinstall reuses it |
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.
@ -95,6 +95,24 @@ Retiring a server is the one thing the servers can't do for each other: uninstal
clients pointing at it. On each client, run `llmhost opencode-remove --host popos.local` (or delete the block by 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). hand if llm-host isn't installed there).
### If opencode keeps asking for the API key
opencode caches a provider's key in its own credential store, `~/.local/share/opencode/auth.json`, and **that copy
wins over `opencode.json`**: 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 `uninstall --purge` + reinstall.
Setup therefore deletes the cached entry for its own provider each time it runs, leaving the `{file:...}` reference
in `opencode.json` authoritative — that tracks the key file, so it can't go stale. Other providers' credentials in
that file are never touched. If you hit this on a client machine, delete the provider's entry from `auth.json` and
let it read the key file again.
To avoid invalidating remote clients in the first place, purge with `--keep-key`:
```bash
llmhost uninstall --purge --keep-key # keeps ~/.config/llm-host/api_key; a reinstall reuses it
```
## How models are chosen ## How models are chosen
`llmhost/catalog.json` lists each model with every build of it (FP8, BF16, NVFP4, AWQ, MLX 8/6/4-bit), `llmhost/catalog.json` lists each model with every build of it (FP8, BF16, NVFP4, AWQ, MLX 8/6/4-bit),

View file

@ -209,7 +209,7 @@ 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, prov = opencode.configure(cfg) status, path, prov, auth_cleared = opencode.configure(cfg)
if status in ("has-comments", "unparsable"): if status in ("has-comments", "unparsable"):
why = "has comments, which an automatic edit would delete" if status == "has-comments" else "isn't valid JSON" why = "has comments, which an automatic edit would delete" if status == "has-comments" else "isn't valid JSON"
say(f"\n{path} {why}, so it was left as is.\n" say(f"\n{path} {why}, so it was left as is.\n"
@ -220,6 +220,10 @@ def setup_opencode(cfg, ask, install_ok=False, later="llmhost opencode-setup"):
say(f"\nopencode: {msg} the `{prov}` provider \u2014 {label} \u2014 in {path} (http://localhost:{cfg['api_port']}/v1).") say(f"\nopencode: {msg} the `{prov}` provider \u2014 {label} \u2014 in {path} (http://localhost:{cfg['api_port']}/v1).")
if prov != opencode.PROVIDER: if prov != opencode.PROVIDER:
say(f"(`{opencode.PROVIDER}` is taken by another provider, which was left alone.)") say(f"(`{opencode.PROVIDER}` is taken by another provider, which was left alone.)")
if auth_cleared:
say(f"Cleared opencode's cached key for `{prov}` in {opencode.auth_file()}, so it reads\n"
f"{paths.KEY_FILE} instead. A cached copy goes stale whenever the key is\n"
f"regenerated, and opencode then asks for it interactively.")
if status == "added": if status == "added":
say(f"Start it with: opencode (pick a model with /models; this server answers as {prov}/{cfg['active']})") say(f"Start it with: opencode (pick a model with /models; this server answers as {prov}/{cfg['active']})")
@ -517,6 +521,23 @@ def hf_cache_rm_cmd(repos):
"--cache-dir", str(paths.hf_hub_dir()), *[f"model/{r}" for r in repos]] "--cache-dir", str(paths.hf_hub_dir()), *[f"model/{r}" for r in repos]]
def purge(keep_key=False):
"""Remove the config dir, the data dir and the launcher. With keep_key, the API key
survives, so a reinstall reuses it and clients configured with it keep working
(setup only mints a key when the file is absent). Returns the kept path, or None."""
keep = paths.KEY_FILE.read_text() if keep_key and paths.KEY_FILE.exists() else None
shutil.rmtree(paths.CONFIG_DIR, ignore_errors=True)
shutil.rmtree(paths.DATA, ignore_errors=True)
paths.SHIM.unlink(missing_ok=True)
if keep is None:
return None
paths.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
fd = os.open(paths.KEY_FILE, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
f.write(keep)
return paths.KEY_FILE
def cmd_uninstall(a): def cmd_uninstall(a):
# Read the catalog now: --purge deletes it along with the rest of llm-host. # Read the catalog now: --purge deletes it along with the rest of llm-host.
cached = cached_catalog_models() cached = cached_catalog_models()
@ -542,10 +563,14 @@ def cmd_uninstall(a):
why = "has comments" if oc_status == "has-comments" else "isn't valid JSON" 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.") 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) kept = purge(a.keep_key)
shutil.rmtree(paths.DATA, ignore_errors=True) if kept is None:
paths.SHIM.unlink(missing_ok=True) say("Removed config, API key and llm-host itself.")
say("Removed config, API key and llm-host itself.") say("A reinstall mints a new API key, so clients elsewhere will need the new one\n"
"(`llmhost opencode-config`). Keep the current key instead with: --purge --keep-key")
else:
say(f"Removed config and llm-host itself; kept the API key at {kept},\n"
"so a reinstall reuses it and clients elsewhere keep working.")
if not cached: if not cached:
return return
total = sum(g for _, g in cached) total = sum(g for _, g in cached)
@ -669,6 +694,7 @@ def main(argv=None):
s = sub.add_parser("uninstall", help="remove services and backends (asks before deleting models)") s = sub.add_parser("uninstall", help="remove services and backends (asks before deleting models)")
s.add_argument("--purge", action="store_true", help="also remove config, API key and llm-host itself") s.add_argument("--purge", action="store_true", help="also remove config, API key and llm-host itself")
s.add_argument("--models", action="store_true", help="also delete downloaded models without asking") s.add_argument("--models", action="store_true", help="also delete downloaded models without asking")
s.add_argument("--keep-key", action="store_true", help="with --purge, keep the API key so a reinstall reuses it")
s.set_defaults(fn=cmd_uninstall) s.set_defaults(fn=cmd_uninstall)
sub.add_parser("run-model").set_defaults(fn=cmd_run_model) sub.add_parser("run-model").set_defaults(fn=cmd_run_model)
sub.add_parser("run-web").set_defaults(fn=cmd_run_web) sub.add_parser("run-web").set_defaults(fn=cmd_run_web)

View file

@ -58,6 +58,48 @@ def config_file():
return d / "opencode.json" 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): def remote_provider(host):
"""Provider id for a server reached at `host`.""" """Provider id for a server reached at `host`."""
return f"{PROVIDER}-{host.split('.')[0]}" return f"{PROVIDER}-{host.split('.')[0]}"
@ -192,12 +234,13 @@ def _write(path, data, backup=True):
def configure(cfg): def configure(cfg):
"""Add or refresh this machine's provider. Returns (status, path, prov_id); status is """Add or refresh this machine's provider. Returns (status, path, prov_id, auth_cleared);
added, updated, unchanged, has-comments or unparsable (the last two leave the file alone).""" status is added, updated, unchanged, has-comments or unparsable (the last two leave the
file alone)."""
path = config_file() path = config_file()
data, problem = _read(path) data, problem = _read(path)
if problem: if problem:
return problem, path, PROVIDER return problem, path, PROVIDER, False
providers = data.setdefault("provider", {}) providers = data.setdefault("provider", {})
mine = local_ids(providers) mine = local_ids(providers)
@ -218,11 +261,13 @@ def configure(cfg):
providers[prov] = local_block(cfg) providers[prov] = local_block(cfg)
if "model" not in data: if "model" not in data:
data["model"] = f"{prov}/{cfg['active']}" data["model"] = f"{prov}/{cfg['active']}"
# 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: if json.dumps(data, sort_keys=True) == before:
return "unchanged", path, prov return "unchanged", path, prov, cleared
_write(path, data) _write(path, data)
return ("updated" if existed else "added"), path, prov return ("updated" if existed else "added"), path, prov, cleared
def _pick_fallback_model(providers, removed): def _pick_fallback_model(providers, removed):
@ -273,6 +318,7 @@ def remove(prov_ids=None, local=True, host=None, every=False):
for prov in targets: for prov in targets:
del providers[prov] del providers[prov]
clear_auth(*targets)
new_model = None new_model = None
model = data.get("model") or "" model = data.get("model") or ""
if model.split("/", 1)[0] in targets: if model.split("/", 1)[0] in targets: