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:
parent
13a7def080
commit
8c6615dbb4
3 changed files with 101 additions and 11 deletions
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue