From 633bbf35a08d84614328a5f136e98e308e43ffce Mon Sep 17 00:00:00 2001 From: Lap Tran Date: Fri, 6 Nov 2026 21:10:54 -0500 Subject: [PATCH] feat(home): sync the OpenCode Go key after account switches --- home.nix | 11 +++ home/bin/opencode-go-key-sync | 178 ++++++++++++++++++++++++++++++++++ rebuild.sh | 1 + 3 files changed, 190 insertions(+) create mode 100755 home/bin/opencode-go-key-sync diff --git a/home.nix b/home.nix index 70fd781..67caa36 100644 --- a/home.nix +++ b/home.nix @@ -41,6 +41,11 @@ in syntaxHighlighting.enable = true; # commands turn green when valid initContent = '' bindkey '^f' autosuggest-accept + # Keep the OpenCode Go CLI, Pi, no-mistakes, and Hermes key aligned with + # the desktop app login after an account switch. + if [ -x "$HOME/.local/bin/opencode-go-key-sync" ]; then + "$HOME/.local/bin/opencode-go-key-sync" >/dev/null 2>&1 || true + fi ''; shellAliases = { ".." = "cd .."; @@ -168,6 +173,12 @@ in source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/bin/opencode-go-token"; force = true; }; + # Copy the desktop app's OpenCode Go login into the CLI, Pi, and Hermes stores. + # The app writes opencode.db only; those tools read auth.json and .env. + home.file.".local/bin/opencode-go-key-sync" = { + source = config.lib.file.mkOutOfStoreSymlink "${dotfiles}/home/bin/opencode-go-key-sync"; + force = true; + }; # Codex 0.160+ profiles live in $CODEX_HOME/.config.toml. The app does not # touch these, so they can be symlinked normally. home.file.".codex/luna.config.toml" = { diff --git a/home/bin/opencode-go-key-sync b/home/bin/opencode-go-key-sync new file mode 100755 index 0000000..b89abc3 --- /dev/null +++ b/home/bin/opencode-go-key-sync @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +"""Copy the OpenCode Go key from the desktop app store into the CLI auth files. + +The OpenCode desktop app writes its login to + /opencode/opencode.db (table credential, integration opencode-go) +but the opencode CLI, firstmate workers, pi, and no-mistakes read + /opencode/auth.json (opencode-go.key) + ~/.pi/agent/auth.json (opencode-go.key) + +After an account switch the app store is current and those JSON files still hold +the old key, so workers and the validation pipeline fail with a usage or auth +error. Run this after switching accounts. + +Safety: + * The app credential is the source only when it is newer than the target file. + * If a target file is newer than the app credential, it is left alone and the + command reports a conflict instead of overwriting a manual login. + * The key is never printed. + +Exit status: 0 in sync or updated, 2 conflict, 1 no source credential. +""" + +import argparse +import json +import os +import sqlite3 +import sys +import tempfile +import time + + +def data_home(): + return os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share") + + +def app_credential(): + db = os.path.join(data_home(), "opencode", "opencode.db") + if not os.path.exists(db): + return None + con = sqlite3.connect(f"file:{db}?mode=ro", uri=True) + try: + row = con.execute( + "select value, time_updated from credential" + " where integration_id='opencode-go' order by time_updated desc limit 1" + ).fetchone() + finally: + con.close() + if not row: + return None + try: + payload = json.loads(row[0]) + except Exception: + return None + key = payload.get("key") if isinstance(payload, dict) else None + if not key: + return None + return key, int(row[1]) / 1000.0 + + +def read_target(path): + with open(path) as fh: + data = json.load(fh) + entry = data.get("opencode-go") + key = entry.get("key") if isinstance(entry, dict) else None + return data, key + + +def write_target(path, data): + directory = os.path.dirname(path) + fd, tmp = tempfile.mkstemp(dir=directory, prefix=".auth.", suffix=".json") + try: + with os.fdopen(fd, "w") as fh: + json.dump(data, fh) + os.chmod(tmp, 0o600) + os.replace(tmp, path) + finally: + if os.path.exists(tmp): + os.unlink(tmp) + + +def target_paths(): + return [ + os.path.join(data_home(), "opencode", "auth.json"), + os.path.expanduser("~/.pi/agent/auth.json"), + ] + + +def sync_hermes(source_key, check): + """Update OPENCODE_GO_API_KEY in the Hermes env file when it differs.""" + path = os.path.expanduser("~/.hermes/.env") + if not os.path.exists(path): + return 0 + with open(path) as fh: + lines = fh.readlines() + current = None + for line in lines: + stripped = line.rstrip("\n") + if stripped.startswith("OPENCODE_GO_API_KEY="): + current = stripped.split("=", 1)[1] + break + if current is None: + return 0 + label = "hermes/.env" + if current == source_key: + print(f"{label}: in sync") + return 0 + if check: + print(f"{label}: stale, would update", file=sys.stderr) + return 2 + rewritten = [] + for line in lines: + if line.startswith("OPENCODE_GO_API_KEY="): + rewritten.append(f"OPENCODE_GO_API_KEY={source_key}\n") + else: + rewritten.append(line) + with open(path, "w") as fh: + fh.writelines(rewritten) + os.chmod(path, 0o600) + print(f"{label}: updated") + return 0 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--check", + action="store_true", + help="report drift and exit 2 instead of updating", + ) + args = parser.parse_args() + + source = app_credential() + if not source: + print( + "opencode-go-key-sync: no opencode-go credential in the app store", + file=sys.stderr, + ) + return 1 + source_key, source_time = source + + status = 0 + for path in target_paths(): + label = os.path.basename(os.path.dirname(path)) + "/" + os.path.basename(path) + if not os.path.exists(path): + print(f"{label}: missing, skipped", file=sys.stderr) + status = max(status, 2) + continue + data, current_key = read_target(path) + if current_key == source_key: + print(f"{label}: in sync") + continue + target_time = os.path.getmtime(path) + if target_time > source_time: + print( + f"{label}: has a newer key than the app store, left unchanged" + " (log in again in the app, or update this file by hand)", + file=sys.stderr, + ) + status = max(status, 2) + continue + if args.check: + print(f"{label}: stale, would update", file=sys.stderr) + status = max(status, 2) + continue + entry = data.get("opencode-go") + if not isinstance(entry, dict): + entry = {"type": "api"} + entry["key"] = source_key + data["opencode-go"] = entry + write_target(path, data) + print(f"{label}: updated") + + status = max(status, sync_hermes(source_key, args.check)) + return status + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/rebuild.sh b/rebuild.sh index bc4f63d..f2b9ab7 100755 --- a/rebuild.sh +++ b/rebuild.sh @@ -47,6 +47,7 @@ managed=( "$HOME/.config/opencode2/AGENTS.md" "$HOME/.local/bin/oc2" "$HOME/.local/bin/opencode-go-token" + "$HOME/.local/bin/opencode-go-key-sync" "$HOME/.pi/agent/settings.json" "$HOME/.pi/agent/models.json" "$HOME/.pi/agent/AGENTS.md"