"""Credential bootstrap so the same code runs on Windows (local) and Linux (HF). - Windows / local: do nothing — the agy login already lives in the OS keyring. - HF / Linux / headless: paste the whole credential JSON into ONE secret env var `AGY_CREDS_JSON`, and set `AGY_CREDS_PATH` to the file path agy reads creds from on that box. On startup we write the JSON to that path so agy picks it up. Everything is env-driven; nothing is hardcoded to one machine. """ from __future__ import annotations import json import os from pathlib import Path def ensure_credentials() -> str | None: """Materialize creds from env, if provided. Returns the written path or None.""" blob = os.environ.get("AGY_CREDS_JSON", "").strip() if not blob: # Local Windows path: keyring already holds the login. No-op. return None try: json.loads(blob) # validate so a bad paste fails loudly, not silently except json.JSONDecodeError as e: raise RuntimeError(f"AGY_CREDS_JSON is not valid JSON: {e}") from e path = os.environ.get("AGY_CREDS_PATH", "").strip() if not path: # Optional: per-key homes get the credential via agy_bridge.ensure_home(). return None # HF secrets are literal strings, so expand $HOME / ~ ourselves. path = os.path.expandvars(os.path.expanduser(path)) p = Path(path) p.parent.mkdir(parents=True, exist_ok=True) p.write_text(blob, encoding="utf-8") try: os.chmod(p, 0o600) # tighten perms on POSIX; harmless on Windows except OSError: pass return str(p)