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

@ -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: