diff --git a/README.md b/README.md index e270f17..d355ef8 100644 --- a/README.md +++ b/README.md @@ -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-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 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://.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. @@ -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 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 `llmhost/catalog.json` lists each model with every build of it (FP8, BF16, NVFP4, AWQ, MLX 8/6/4-bit), diff --git a/llmhost/cli.py b/llmhost/cli.py index 7a23d3e..a903f7d 100644 --- a/llmhost/cli.py +++ b/llmhost/cli.py @@ -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") return 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"): 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" @@ -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).") if prov != opencode.PROVIDER: 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": 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]] +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): # Read the catalog now: --purge deletes it along with the rest of llm-host. 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" say(f"opencode: {oc_path} {why}, so it was left alone; remove the llm-host provider by hand.") if a.purge: - shutil.rmtree(paths.CONFIG_DIR, ignore_errors=True) - shutil.rmtree(paths.DATA, ignore_errors=True) - paths.SHIM.unlink(missing_ok=True) - say("Removed config, API key and llm-host itself.") + kept = purge(a.keep_key) + if kept is None: + 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: return 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.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("--keep-key", action="store_true", help="with --purge, keep the API key so a reinstall reuses it") s.set_defaults(fn=cmd_uninstall) sub.add_parser("run-model").set_defaults(fn=cmd_run_model) sub.add_parser("run-web").set_defaults(fn=cmd_run_web) diff --git a/llmhost/opencode.py b/llmhost/opencode.py index 6f396bd..1390ce9 100644 --- a/llmhost/opencode.py +++ b/llmhost/opencode.py @@ -58,6 +58,48 @@ def config_file(): 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): """Provider id for a server reached at `host`.""" return f"{PROVIDER}-{host.split('.')[0]}" @@ -192,12 +234,13 @@ def _write(path, data, backup=True): def configure(cfg): - """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).""" + """Add or refresh this machine's provider. Returns (status, path, prov_id, auth_cleared); + 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 + return problem, path, PROVIDER, False providers = data.setdefault("provider", {}) mine = local_ids(providers) @@ -218,11 +261,13 @@ def configure(cfg): providers[prov] = local_block(cfg) if "model" not in data: 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: - return "unchanged", path, prov + return "unchanged", path, prov, cleared _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): @@ -273,6 +318,7 @@ def remove(prov_ids=None, local=True, host=None, every=False): for prov in targets: del providers[prov] + clear_auth(*targets) new_model = None model = data.get("model") or "" if model.split("/", 1)[0] in targets: