Skip to content

The agent that grows with you

refactor(agent/creds): unify auth-store OAuth removal and suppress-only steps; compact credential_sources/persistence (-35% LOC)

Tekniumb5aa16f7856a
diff --git a/agent/credential_persistence.py b/agent/credential_persistence.py
index 287fff3ccce..29d93d6e216 100644
--- a/agent/credential_persistence.py
+++ b/agent/credential_persistence.py
@@ -1,10 +1,9 @@
"""Credential-pool disk-boundary sanitization helpers.
-These helpers define which credential-pool entries are references to borrowed
-runtime secrets and strip raw values before those entries are written to
-``auth.json``. They intentionally have no dependency on ``hermes_cli.auth`` so
-both the pool model and the final auth-store write boundary can share the same
-policy without import cycles.
+Decide which pool entries are references to *borrowed* runtime secrets and
+strip raw values before those entries reach ``auth.json``. Deliberately free
+of ``hermes_cli.auth`` imports so the pool model and the auth-store write
+boundary share one policy without import cycles.
"""
from __future__ import annotations
@@ -14,9 +13,9 @@ import re
from typing import Any, Dict, Mapping
-# Sources Hermes owns and can intentionally persist in auth.json. Everything
-# else with a non-empty source is treated as borrowed/reference-only by default
-# so future external secret providers fail closed at the disk boundary.
+# Sources Hermes owns and may persist with secrets. Any other non-empty,
+# non-manual source is borrowed/reference-only so new external providers fail
+# closed at the disk boundary.
_PERSISTABLE_PROVIDER_SOURCES = frozenset({
("anthropic", "hermes_pkce"),
("minimax-oauth", "oauth"),
@@ -25,87 +24,42 @@ _PERSISTABLE_PROVIDER_SOURCES = frozenset({
("xai-oauth", "device_code"),
})
+# Metadata keys that look secret-ish by suffix but are safe to persist.
_SAFE_SECRETISH_METADATA_KEYS = frozenset({
- "secret_fingerprint",
- "secret_source",
- "token_type",
- "scope",
- "client_id",
- "agent_key_id",
- "agent_key_expires_at",
- "agent_key_expires_in",
- "agent_key_reused",
- "agent_key_obtained_at",
- "expires_at",
- "expires_at_ms",
- "expires_in",
- "last_refresh",
- "last_status",
- "last_status_at",
- "last_error_code",
- "last_error_reason",
- "last_error_message",
+ "secret_fingerprint", "secret_source", "token_type", "scope", "client_id",
+ "agent_key_id", "agent_key_expires_at", "agent_key_expires_in",
+ "agent_key_reused", "agent_key_obtained_at", "expires_at", "expires_at_ms",
+ "expires_in", "last_refresh", "last_status", "last_status_at",
+ "last_error_code", "last_error_reason", "last_error_message",
"last_error_reset_at",
})
_SECRET_VALUE_KEYS = frozenset({
- "access_token",
- "refresh_token",
- "agent_key",
- "api_key",
- "apikey",
- "api_token",
- "auth_token",
- "authorization",
- "bearer_token",
- "client_secret",
- "credential",
- "credentials",
- "id_token",
- "oauth_token",
- "private_key",
- "secret_key",
- "session_token",
- "password",
- "secret",
- "token",
- "tokens",
+ "access_token", "refresh_token", "agent_key", "api_key", "apikey",
+ "api_token", "auth_token", "authorization", "bearer_token", "client_secret",
+ "credential", "credentials", "id_token", "oauth_token", "private_key",
+ "secret_key", "session_token", "password", "secret", "token", "tokens",
})
_SECRET_VALUE_SUFFIXES = (
- "_api_key",
- "_api_token",
- "_access_token",
- "_auth_token",
- "_refresh_token",
- "_bearer_token",
- "_client_secret",
- "_id_token",
- "_oauth_token",
- "_private_key",
- "_session_token",
- "_secret_key",
- "_password",
- "_secret",
- "_token",
- "_key",
+ "_api_key", "_api_token", "_access_token", "_auth_token", "_refresh_token",
+ "_bearer_token", "_client_secret", "_id_token", "_oauth_token",
+ "_private_key", "_session_token", "_secret_key", "_password", "_secret",
+ "_token", "_key",
)
_CAMEL_CASE_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")
def _normalize_key(key: Any) -> str:
- raw = str(key or "").strip()
- raw = _CAMEL_CASE_BOUNDARY.sub("_", raw)
+ raw = _CAMEL_CASE_BOUNDARY.sub("_", str(key or "").strip())
return raw.lower().replace("-", "_").replace(".", "_")
def is_borrowed_credential_source(source: Any, provider_id: Any = None) -> bool:
"""Return True when ``source`` points at a borrowed/reference-only secret."""
normalized_source = str(source or "").strip().lower()
- if not normalized_source:
- return False
- if normalized_source == "manual" or normalized_source.startswith("manual:"):
+ if not normalized_source or normalized_source == "manual" or normalized_source.startswith("manual:"):
return False
normalized_provider = str(provider_id or "").strip().lower()
return (normalized_provider, normalized_source) not in _PERSISTABLE_PROVIDER_SOURCES
@@ -115,12 +69,15 @@ def _is_secret_payload_key(key: Any) -> bool:
normalized = _normalize_key(key)
if not normalized or normalized in _SAFE_SECRETISH_METADATA_KEYS:
return False
- if normalized in _SECRET_VALUE_KEYS:
- return True
- return normalized.endswith(_SECRET_VALUE_SUFFIXES)
+ return normalized in _SECRET_VALUE_KEYS or normalized.endswith(_SECRET_VALUE_SUFFIXES)
+
+def fingerprint_secret_value(value: Any) -> str | None:
+ """Non-reversible ``sha256:<16 hex>`` fingerprint of one secret value.
-def _fingerprint_value(value: Any) -> str | None:
+ Callers comparing a live secret against the ``secret_fingerprint`` left on
+ a sanitized (borrowed) pool row need exactly the digest this module writes.
+ """
if value is None:
return None
text = str(value)
@@ -130,27 +87,16 @@ def _fingerprint_value(value: Any) -> str | None:
return f"sha256:{digest[:16]}"
-def fingerprint_secret_value(value: Any) -> str | None:
- """Public, non-reversible fingerprint for a single secret value.
-
- Callers that compare a live secret against the ``secret_fingerprint`` left
- on a sanitized (borrowed) pool row need the same digest this module writes.
- """
- return _fingerprint_value(value)
-
-
def _credential_secret_fingerprint(payload: Mapping[str, Any]) -> str | None:
for key in ("agent_key", "access_token", "refresh_token", "api_key", "token", "secret"):
- fingerprint = _fingerprint_value(payload.get(key))
+ fingerprint = fingerprint_secret_value(payload.get(key))
if fingerprint:
return fingerprint
-
for key, value in payload.items():
if _is_secret_payload_key(key):
- fingerprint = _fingerprint_value(value)
+ fingerprint = fingerprint_secret_value(value)
if fingerprint:
return fingerprint
-
existing = payload.get("secret_fingerprint")
if isinstance(existing, str) and existing.startswith("sha256:"):
return existing
@@ -163,21 +109,15 @@ def sanitize_borrowed_credential_payload(
) -> Dict[str, Any]:
"""Return a disk-safe credential-pool payload.
- Owned sources (manual entries and Hermes-owned OAuth/device-code state)
- pass through unchanged. Borrowed/reference-only sources keep labels,
- source refs, status/cooldown metadata, counters, and a non-reversible
- fingerprint, but raw secret value fields are removed.
+ Owned sources pass through unchanged. Borrowed sources keep labels,
+ source refs, status/cooldown metadata, counters and a fingerprint, but
+ every raw secret value field is removed.
"""
result = dict(payload)
if not is_borrowed_credential_source(result.get("source"), provider_id):
return result
-
fingerprint = _credential_secret_fingerprint(result)
- sanitized = {
- key: value
- for key, value in result.items()
- if not _is_secret_payload_key(key)
- }
+ sanitized = {k: v for k, v in result.items() if not _is_secret_payload_key(k)}
if fingerprint:
sanitized["secret_fingerprint"] = fingerprint
return sanitized
diff --git a/agent/credential_sources.py b/agent/credential_sources.py
index 4c0e35d588e..67c06eaf316 100644
--- a/agent/credential_sources.py
+++ b/agent/credential_sources.py
@@ -1,46 +1,18 @@
"""Unified removal contract for every credential source Hermes reads from.
-Hermes seeds its credential pool from many places:
-
- env:<VAR> — os.environ / ~/.hermes/.env
- claude_code — ~/.claude/.credentials.json
- hermes_pkce — ~/.hermes/.anthropic_oauth.json
- device_code — auth.json providers.<provider> (nous, openai-codex, ...)
- qwen-cli — ~/.qwen/oauth_creds.json
- gh_cli — gh auth token
- config:<name> — custom_providers config entry
- model_config — model.api_key when model.provider == "custom"
- manual — user ran `hermes auth add`
-
-Each source has its own reader inside ``agent.credential_pool._seed_from_*``
-(which keep their existing shape — we haven't restructured them). What we
-unify here is **removal**:
-
- ``hermes auth remove <provider> <N>`` must make the pool entry stay gone.
-
-Before this module, every source had an ad-hoc removal branch in
-``auth_remove_command``, and several sources had no branch at all — so
-``auth remove`` silently reverted on the next ``load_pool()`` call for
-qwen-cli, nous device_code (partial), hermes_pkce, copilot gh_cli, and
-custom-config sources.
-
-Now every source registers a ``RemovalStep`` that does exactly three things
-in the same shape:
-
- 1. Clean up whatever externally-readable state the source reads from
- (.env line, auth.json block, OAuth file, etc.)
- 2. Suppress the ``(provider, source_id)`` in auth.json so the
- corresponding ``_seed_from_*`` branch skips the upsert on re-load
- 3. Return ``RemovalResult`` describing what was cleaned and any
- diagnostic hints the user should see (shell-exported env vars,
- external credential files we deliberately don't delete, etc.)
-
-Adding a new credential source is:
- - wire up a reader branch in ``_seed_from_*`` (existing pattern)
- - gate that reader behind ``is_source_suppressed(provider, source_id)``
- - register a ``RemovalStep`` here
-
-No more per-source if/elif chain in ``auth_remove_command``.
+The pool is seeded from many sources (``env:<VAR>``, ``claude_code``,
+``hermes_pkce``, ``device_code``, ``qwen-cli``, ``gh_cli``, ``config:<name>``,
+``model_config``, ``manual``). Readers live in ``agent.credential_pool``; what
+is unified here is **removal**: ``hermes auth remove <provider> <N>`` must make
+the entry stay gone across ``load_pool()`` calls.
+
+Every source registers a ``RemovalStep`` whose ``remove_fn`` does three things:
+clean the external state the source reads from, suppress ``(provider,
+source_id)`` in auth.json so the seeding branch skips the upsert, and return a
+``RemovalResult`` with user-facing ``cleaned``/``hints`` lines.
+
+Adding a source: wire a reader branch in ``_seed_from_*``, gate it behind
+``is_source_suppressed(provider, source_id)``, register a ``RemovalStep`` here.
"""
from __future__ import annotations
@@ -54,20 +26,11 @@ from typing import Callable, List, Optional
class RemovalResult:
"""Outcome of removing a credential source.
- Attributes:
- cleaned: Short strings describing external state that was actually
- mutated (``"Cleared XAI_API_KEY from .env"``,
- ``"Cleared openai-codex OAuth tokens from auth store"``).
- Printed as plain lines to the user.
- hints: Diagnostic lines ABOUT state the user may need to clean up
- themselves or is deliberately left intact (shell-exported env
- var, Claude Code credential file we don't delete, etc.).
- Printed as plain lines to the user. Always non-destructive.
- suppress: Whether to call ``suppress_credential_source`` after
- cleanup so future ``load_pool`` calls skip this source.
- Default True — almost every source needs this to stay sticky.
- The only legitimate False is ``manual`` entries, which aren't
- seeded from anywhere external.
+ ``cleaned``: external state actually mutated (printed to the user).
+ ``hints``: non-destructive diagnostics about state left intact or that the
+ user must clean up themselves. ``suppress``: call
+ ``suppress_credential_source`` afterwards so ``load_pool`` skips the source;
+ only ``manual`` entries (never seeded externally) legitimately use False.
"""
cleaned: List[str] = field(default_factory=list)
@@ -77,22 +40,11 @@ class RemovalResult:
@dataclass
class RemovalStep:
- """How to remove one specific credential source cleanly.
-
- Attributes:
- provider: Provider pool key (``"xai"``, ``"anthropic"``, ``"nous"``, ...).
- Special value ``"*"`` means "matches any provider" — used for
- sources like ``manual`` that aren't provider-specific.
- source_id: Source identifier as it appears in
- ``PooledCredential.source``. May be a literal (``"claude_code"``)
- or a prefix pattern matched via ``match_fn``.
- match_fn: Optional predicate overriding literal ``source_id``
- matching. Gets the removed entry's source string. Used for
- ``env:*`` (any env-seeded key), ``config:*`` (any custom
- pool), and ``manual:*`` (any manual-source variant).
- remove_fn: ``(provider, removed_entry) -> RemovalResult``. Does the
- actual cleanup and returns what happened for the user.
- description: One-line human-readable description for docs / tests.
+ """How to remove one credential source.
+
+ ``provider`` ``"*"`` matches any provider. ``match_fn`` overrides literal
+ ``source_id`` matching (prefix patterns like ``env:*`` / ``config:*``).
+ ``remove_fn(provider, removed_entry) -> RemovalResult``.
"""
provider: str
@@ -109,22 +61,11 @@ class RemovalStep:
return source == self.source_id
-_REGISTRY: List[RemovalStep] = []
-
-
-def register(step: RemovalStep) -> RemovalStep:
- _REGISTRY.append(step)
- return step
-
-
def find_removal_step(provider: str, source: str) -> Optional[RemovalStep]:
- """Return the first matching RemovalStep, or None if unregistered.
+ """First matching RemovalStep, or None.
- Unregistered sources fall through to the default remove path in
- ``auth_remove_command``: the pool entry is already gone (that happens
- before dispatch), no external cleanup, no suppression. This is the
- correct behaviour for ``manual`` entries — they were only ever stored
- in the pool, nothing external to clean up.
+ Unregistered sources (``manual``) fall through to the caller's default:
+ the pool entry is already gone, nothing external to clean, no suppression.
"""
for step in _REGISTRY:
if step.matches(provider, source):
@@ -132,23 +73,8 @@ def find_removal_step(provider: str, source: str) -> Optional[RemovalStep]:
return None
-# ---------------------------------------------------------------------------
-# Individual RemovalStep implementations — one per source.
-# ---------------------------------------------------------------------------
-# Each remove_fn is intentionally small and single-purpose. Adding a new
-# credential source means adding ONE entry here — no other changes to
-# auth_remove_command.
-
-
def _remove_env_source(provider: str, removed) -> RemovalResult:
- """env:<VAR> — the most common case.
-
- Handles three user situations:
- 1. Var lives only in ~/.hermes/.env → clear it
- 2. Var lives only in the user's shell (shell profile, systemd
- EnvironmentFile, launchd plist) → hint them where to unset it
- 3. Var lives in both → clear from .env, hint about shell
- """
+ """env:<VAR> — clear from ~/.hermes/.env; hint when the shell exports it."""
from hermes_cli.config import get_env_path, remove_env_value
result = RemovalResult()
@@ -156,18 +82,14 @@ def _remove_env_source(provider: str, removed) -> RemovalResult:
if not env_var:
return result
- # Detect shell vs .env BEFORE remove_env_value pops os.environ.
+ # Detect shell vs .env BEFORE remove_env_value pops os.environ. Read the
+ # .env as utf-8-sig like hermes_cli/config.py: a locale/BOM-sensitive read
+ # would misreport a Notepad-edited .env var as a shell export.
env_in_process = bool(os.getenv(env_var))
env_in_dotenv = False
try:
env_path = get_env_path()
if env_path.exists():
- # Read the .env as UTF-8 with BOM tolerance, matching the
- # canonical reader in hermes_cli/config.py. read_text() with no
- # encoding falls back to the system locale (cp1252/GBK on Windows)
- # and never strips a BOM, so a Notepad-edited .env (BOM + non-ASCII
- # values) would make the first line fail the startswith() check —
- # misreporting a .env-backed var as a shell export.
env_in_dotenv = any(
line.strip().startswith(f"{env_var}=")
for line in env_path.read_text(
@@ -178,8 +100,7 @@ def _remove_env_source(provider: str, removed) -> RemovalResult:
pass
shell_exported = env_in_process and not env_in_dotenv
- cleared = remove_env_value(env_var)
- if cleared:
+ if remove_env_value(env_var):
result.cleaned.append(f"Cleared {env_var} from .env")
if shell_exported:
@@ -199,19 +120,6 @@ def _remove_env_source(provider: str, removed) -> RemovalResult:
return result
-def _remove_claude_code(provider: str, removed) -> RemovalResult:
- """~/.claude/.credentials.json is owned by Claude Code itself.
-
- We don't delete it — the user's Claude Code install still needs to
- work. We just suppress it so Hermes stops reading it.
- """
- return RemovalResult(hints=[
- "Suppressed claude_code credential — it will not be re-seeded.",
- "Note: Claude Code credentials still live in ~/.claude/.credentials.json",
- "Run `hermes auth add anthropic` to re-enable if needed.",
- ])
-
-
def _remove_hermes_pkce(provider: str, removed) -> RemovalResult:
"""~/.hermes/.anthropic_oauth.json is ours — delete it outright."""
from hermes_constants import get_hermes_home
@@ -229,11 +137,7 @@ def _remove_hermes_pkce(provider: str, removed) -> RemovalResult:
def _clear_auth_store_provider(provider: str) -> bool:
"""Delete auth_store.providers[provider]. Returns True if deleted."""
- from hermes_cli.auth import (
- _auth_store_lock,
- _load_auth_store,
- _save_auth_store,
- )
+ from hermes_cli.auth import _auth_store_lock, _load_auth_store, _save_auth_store
with _auth_store_lock():
auth_store = _load_auth_store()
@@ -245,28 +149,11 @@ def _clear_auth_store_provider(provider: str) -> bool:
return False
-def _remove_nous_device_code(provider: str, removed) -> RemovalResult:
- """Nous OAuth lives in auth.json providers.nous — clear it and suppress.
-
- We suppress in addition to clearing because nothing else stops a future
- `hermes auth add nous` (or any other path that writes providers.nous)
- from re-seeding before the user has decided to. Suppression forces
- them to go through `hermes auth add nous` to re-engage, which is the
- documented re-add path and clears the suppression atomically.
- """
- result = RemovalResult()
- if _clear_auth_store_provider(provider):
- result.cleaned.append(f"Cleared {provider} OAuth tokens from auth store")
- return result
-
-
-def _remove_minimax_oauth(provider: str, removed) -> RemovalResult:
- """MiniMax OAuth lives in auth.json providers.minimax-oauth — clear it.
-
- Same pattern as Nous: single-source OAuth state with refresh tokens.
- Suppression of the `oauth` source ensures the pool reseed path
- (_seed_from_singletons) doesn't instantly undo the removal.
- """
+def _remove_auth_store_oauth(provider: str, removed) -> RemovalResult:
+ """OAuth state in auth.json ``providers.<provider>`` (nous, minimax-oauth,
+ xai-oauth, openai-codex): clear it. Suppression (by the dispatcher) is
+ still required — otherwise ``_seed_from_singletons`` re-seeds from any
+ path that rewrites the block before the user re-adds it deliberately."""
result = RemovalResult()
if _clear_auth_store_provider(provider):
result.cleaned.append(f"Cleared {provider} OAuth tokens from auth store")
@@ -274,19 +161,7 @@ def _remove_minimax_oauth(provider: str, removed) -> RemovalResult:
def _remove_xai_oauth_device_code(provider: str, removed) -> RemovalResult:
- """xAI OAuth tokens live in auth.json providers.xai-oauth — clear them.
-
- Without this step, ``hermes auth remove xai-oauth <N>`` silently undoes
- itself: the central dispatcher only removes the in-memory pool entry,
- leaves ``providers.xai-oauth`` in auth.json intact, and on the next
- ``load_pool("xai-oauth")`` call ``_seed_from_singletons`` re-seeds the
- entry from the still-present singleton — credentials reappear with no
- user feedback. Clearing the singleton in step with the suppression set
- by the central dispatcher makes the removal stick.
- """
- result = RemovalResult()
- if _clear_auth_store_provider(provider):
- result.cleaned.append(f"Cleared {provider} OAuth tokens from auth store")
+ result = _remove_auth_store_oauth(provider, removed)
result.hints.append(
"Run `hermes model` → xAI Grok OAuth (SuperGrok / Premium+) to re-authenticate if needed."
)
@@ -294,30 +169,15 @@ def _remove_xai_oauth_device_code(provider: str, removed) -> RemovalResult:
def _remove_codex_device_code(provider: str, removed) -> RemovalResult:
- """Codex tokens live in TWO places: our auth store AND ~/.codex/auth.json.
-
- refresh_codex_oauth_pure() writes both every time, so clearing only
- the Hermes auth store is not enough — _seed_from_singletons() would
- re-import from ~/.codex/auth.json on the next load_pool() call and
- the removal would be instantly undone. We suppress instead of
- deleting Codex CLI's file, so the Codex CLI itself keeps working.
-
- The canonical source name in ``_seed_from_singletons`` is
- ``"device_code"`` (no prefix). Entries may show up in the pool as
- either ``"device_code"`` (seeded) or ``"manual:device_code"`` (added
- via ``hermes auth add openai-codex``), but in both cases the re-seed
- gate lives at the ``"device_code"`` suppression key. We suppress
- that canonical key here; the central dispatcher also suppresses
- ``removed.source`` which is fine — belt-and-suspenders, idempotent.
+ """Codex tokens also live in ~/.codex/auth.json (Codex CLI's file, kept).
+
+ Suppress the canonical ``device_code`` key — not just ``removed.source`` —
+ so a ``manual:device_code`` removal still blocks the ``device_code``
+ re-seed path. Idempotent with the dispatcher's own suppression.
"""
from hermes_cli.auth import suppress_credential_source
- result = RemovalResult()
- if _clear_auth_store_provider(provider):
- result.cleaned.append(f"Cleared {provider} OAuth tokens from auth store")
- # Suppress the canonical re-seed source, not just whatever source the
- # removed entry had. Otherwise `manual:device_code` removals wouldn't
- # block the `device_code` re-seed path.
+ result = _remove_auth_store_oauth(provider, removed)
suppress_credential_source(provider, "device_code")
result.hints.extend([
"Suppressed openai-codex device_code source — it will not be re-seeded.",
@@ -327,41 +187,15 @@ def _remove_codex_device_code(provider: str, removed) -> RemovalResult:
return result
-def _remove_qwen_cli(provider: str, removed) -> RemovalResult:
- """~/.qwen/oauth_creds.json is owned by the Qwen CLI.
-
- Same pattern as claude_code — suppress, don't delete. The user's
- Qwen CLI install still reads from that file.
- """
- return RemovalResult(hints=[
- "Suppressed qwen-cli credential — it will not be re-seeded.",
- "Note: Qwen CLI credentials still live in ~/.qwen/oauth_creds.json",
- "Run `hermes auth add qwen-oauth` to re-enable if needed.",
- ])
-
-
def _remove_copilot_gh(provider: str, removed) -> RemovalResult:
- """Copilot token comes from `gh auth token` or COPILOT_GITHUB_TOKEN / GH_TOKEN / GITHUB_TOKEN.
-
- Copilot is special: the same token can be seeded as multiple source
- entries (gh_cli from ``_seed_from_singletons`` plus env:<VAR> from
- ``_seed_from_env``), so removing one entry without suppressing the
- others lets the duplicates resurrect. We suppress ALL known copilot
- sources here so removal is stable regardless of which entry the
- user clicked.
-
- We don't touch the user's gh CLI or shell state — just suppress so
- Hermes stops picking the token up.
- """
- # Suppress ALL copilot source variants up-front so no path resurrects
- # the pool entry. The central dispatcher in auth_remove_command will
- # ALSO suppress removed.source, but it's idempotent so double-calling
- # is harmless.
+ """The same Copilot token is seeded as gh_cli AND env:<VAR> rows, so
+ suppress every variant or the duplicates resurrect the entry. gh CLI and
+ shell state are left untouched."""
from hermes_cli.auth import suppress_credential_source
+
suppress_credential_source(provider, "gh_cli")
for env_var in ("COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"):
suppress_credential_source(provider, f"env:{env_var}")
-
return RemovalResult(hints=[
"Suppressed all copilot token sources (gh_cli + env vars) — they will not be re-seeded.",
"Note: Your gh CLI / shell environment is unchanged.",
@@ -369,83 +203,83 @@ def _remove_copilot_gh(provider: str, removed) -> RemovalResult:
])
-def _remove_custom_config(provider: str, removed) -> RemovalResult:
- """Custom provider pools are seeded from custom_providers config or
- model.api_key. Both are in config.yaml — modifying that from here
- is more invasive than suppression. We suppress; the user can edit
- config.yaml if they want to remove the key from disk entirely.
- """
- source_label = removed.source
- return RemovalResult(hints=[
- f"Suppressed {source_label} — it will not be re-seeded.",
- "Note: The underlying value in config.yaml is unchanged. Edit it "
- "directly if you want to remove the credential from disk.",
- ])
-
+def _suppress_only(*hints: str) -> Callable[..., RemovalResult]:
+ """remove_fn for sources whose backing file/config belongs to another tool
+ (Claude Code, Qwen CLI, config.yaml): never delete it, just suppress and
+ explain. ``{source}`` in a hint is the removed entry's source string."""
+ def remove_fn(provider: str, removed) -> RemovalResult:
+ return RemovalResult(hints=[h.format(source=removed.source) for h in hints])
+ return remove_fn
-def _register_all_sources() -> None:
- """Called once on module import.
- ORDER MATTERS — ``find_removal_step`` returns the first match. Put
- provider-specific steps before the generic ``env:*`` step so that e.g.
- copilot's ``env:GH_TOKEN`` goes through the copilot removal (which
- doesn't touch the user's shell), not the generic env-var removal
- (which would try to clear .env).
- """
- register(RemovalStep(
+# ORDER MATTERS — ``find_removal_step`` returns the first match. Provider-
+# specific steps precede the generic ``env:*`` step so copilot's ``env:GH_TOKEN``
+# takes the copilot path (no .env edits) rather than the generic env-var removal.
+_REGISTRY: List[RemovalStep] = [
+ RemovalStep(
provider="copilot", source_id="gh_cli",
match_fn=lambda src: src == "gh_cli" or src.startswith("env:"),
remove_fn=_remove_copilot_gh,
description="gh auth token / COPILOT_GITHUB_TOKEN / GH_TOKEN",
- ))
- register(RemovalStep(
+ ),
+ RemovalStep(
provider="*", source_id="env:",
match_fn=lambda src: src.startswith("env:"),
remove_fn=_remove_env_source,
description="Any env-seeded credential (XAI_API_KEY, DEEPSEEK_API_KEY, etc.)",
- ))
- register(RemovalStep(
+ ),
+ RemovalStep(
provider="anthropic", source_id="claude_code",
- remove_fn=_remove_claude_code,
+ remove_fn=_suppress_only(
+ "Suppressed claude_code credential — it will not be re-seeded.",
+ "Note: Claude Code credentials still live in ~/.claude/.credentials.json",
+ "Run `hermes auth add anthropic` to re-enable if needed.",
+ ),
description="~/.claude/.credentials.json",
- ))
- register(RemovalStep(
+ ),
+ RemovalStep(
provider="anthropic", source_id="hermes_pkce",
remove_fn=_remove_hermes_pkce,
description="~/.hermes/.anthropic_oauth.json",
- ))
- register(RemovalStep(
+ ),
+ RemovalStep(
provider="nous", source_id="device_code",
- remove_fn=_remove_nous_device_code,
+ remove_fn=_remove_auth_store_oauth,
description="auth.json providers.nous",
- ))
- register(RemovalStep(
+ ),
+ RemovalStep(
provider="openai-codex", source_id="device_code",
match_fn=lambda src: src == "device_code" or src.endswith(":device_code"),
remove_fn=_remove_codex_device_code,
description="auth.json providers.openai-codex + ~/.codex/auth.json",
- ))
- register(RemovalStep(
+ ),
+ RemovalStep(
provider="xai-oauth", source_id="device_code",
remove_fn=_remove_xai_oauth_device_code,
description="auth.json providers.xai-oauth",
- ))
- register(RemovalStep(
+ ),
+ RemovalStep(
provider="qwen-oauth", source_id="qwen-cli",
- remove_fn=_remove_qwen_cli,
+ remove_fn=_suppress_only(
+ "Suppressed qwen-cli credential — it will not be re-seeded.",
+ "Note: Qwen CLI credentials still live in ~/.qwen/oauth_creds.json",
+ "Run `hermes auth add qwen-oauth` to re-enable if needed.",
+ ),
description="~/.qwen/oauth_creds.json",
- ))
- register(RemovalStep(
+ ),
+ RemovalStep(
provider="minimax-oauth", source_id="oauth",
- remove_fn=_remove_minimax_oauth,
+ remove_fn=_remove_auth_store_oauth,
description="auth.json providers.minimax-oauth",
- ))
- register(RemovalStep(
+ ),
+ RemovalStep(
provider="*", source_id="config:",
match_fn=lambda src: src.startswith("config:") or src == "model_config",
- remove_fn=_remove_custom_config,
+ remove_fn=_suppress_only(
+ "Suppressed {source} — it will not be re-seeded.",
+ "Note: The underlying value in config.yaml is unchanged. Edit it "
+ "directly if you want to remove the credential from disk.",
+ ),
description="Custom provider config.yaml api_key field",
- ))
-
-
-_register_all_sources()
+ ),
+]