Skip to content

The agent that grows with you

fix(auth): save a profile's first single-use login, and never print Added for an unsaved row

John Paul Solivadc824c5f65bd
diff --git a/agent/credential_pool.py b/agent/credential_pool.py
index c19a60632e4..d6df1850b9f 100644
--- a/agent/credential_pool.py
+++ b/agent/credential_pool.py
@@ -820,8 +820,7 @@ def _write_through_provider_state_to_global_root(
def _singleton_target_for_entry(pool: "CredentialPool", entry: "PooledCredential") -> Optional[Path]:
"""Root ``.anthropic_oauth.json`` when *entry* is a borrowed hermes_pkce row, else None."""
- borrowed_ids = getattr(pool, "_borrowed_root_ids", None) or ()
- if entry.source != "hermes_pkce" or entry.id not in borrowed_ids:
+ if entry.source != "hermes_pkce" or entry.id not in getattr(pool, "_borrowed_root_ids", ()):
return None
try:
from agent.anthropic_credentials import _root_hermes_oauth_file
@@ -1011,7 +1010,7 @@ class CredentialPool(CredentialPoolAdminMixin, CredentialPoolModelCooldownMixin)
self._current_id: Optional[str] = None
# Ids of rows read via the global-root fallback (single-use OAuth
# providers only); set by load_pool(), consumed by add_entry().
- self._borrowed_root_ids: Optional[Set[str]] = None
+ self._borrowed_root_ids: Set[str] = set()
self._persisted_token_pairs: Dict[str, Tuple[Any, Any]] = {}
self._strategy = get_pool_strategy(provider)
# RLock: _replace_entry/_persist self-acquire it so the DEFERRED
diff --git a/agent/credential_pool_admin.py b/agent/credential_pool_admin.py
index ccf7476326f..1d94ae9d0a2 100644
--- a/agent/credential_pool_admin.py
+++ b/agent/credential_pool_admin.py
@@ -18,6 +18,10 @@ def _cleared_status_copy(entry: PooledCredential) -> PooledCredential:
extra={k: v for k, v in entry.extra.items() if k != "failure_reason"})
+class CredentialNotSavedError(RuntimeError):
+ """``add_entry`` wrote the pool but the store does not hold the new row."""
+
+
class CredentialPoolAdminMixin:
def reset_status(self, credential_id: str) -> Optional[PooledCredential]:
"""Clear only the target's local error state, preserving sibling cooldowns."""
@@ -109,43 +113,49 @@ class CredentialPoolAdminMixin:
def add_entry(self, entry: PooledCredential) -> PooledCredential:
from agent.credential_pool import (
- SINGLE_USE_REFRESH_POOL_PROVIDERS, _borrowed_single_use_pool_root, _next_priority,
- _profile_owns_pool_provider, write_credential_pool,
+ _borrowed_single_use_pool_root, _next_priority, _profile_owns_pool_provider,
+ write_credential_pool,
)
from hermes_cli import auth as auth_mod
+ from hermes_cli.auth_oauth_grants import SINGLE_USE_REFRESH_POOL_PROVIDERS
with self._lock:
entry = replace(entry, priority=_next_priority(self._entries))
self._entries.append(entry)
- borrowed_ids = set(getattr(self, "_borrowed_root_ids", ()) or ())
- # A named profile adding its FIRST single-use OAuth credential
- # must claim the row in its own store even when root has no row to
- # borrow. In that empty-root case ``_borrowed_root_ids`` is empty,
- # but the generic ``_persist`` path still classifies the profile as
- # a borrower and sends the payload through persist_pool_entries'
- # update-only root merge. With no matching root id the new row is
- # dropped while ``hermes auth add`` reports success.
- profile_claims_first_single_use_row = (
+ borrowed_ids = self._borrowed_root_ids
+ # Decided now, not from load_pool()'s snapshot: a profile with no
+ # rows of its own borrows from root even when root has none, and
+ # ``_persist`` would send the new row to the update-only root merge,
+ # which drops it (#103694).
+ profile_borrows = (
self.provider in SINGLE_USE_REFRESH_POOL_PROVIDERS
and not _profile_owns_pool_provider(self.provider)
and _borrowed_single_use_pool_root() is not None
)
- if borrowed_ids or profile_claims_first_single_use_row:
- # ``hermes -p <profile> auth add <single-use provider>``: the
- # profile is claiming its OWN credential. Persist only the
- # profile-owned rows locally — copying the borrowed root
- # grant alongside them would fork its single-use refresh
- # token (#100339). The same local-claim path is required when
- # root and profile are both empty. Once the profile
- # owns rows, the root fallback for this provider is shadowed
- # (existing contract).
+ if borrowed_ids or profile_borrows:
+ # ``hermes -p <profile> auth add <single-use provider>``: a fresh
+ # login inside the profile is the profile's OWN credential, so
+ # it goes to the profile store, never to root. Borrowed root
+ # rows stay out of it — a copy would fork their single-use
+ # refresh token (#100339). Once the profile owns rows, the root
+ # fallback for this provider is shadowed.
self._entries = [e for e in self._entries if e.id not in borrowed_ids]
written = write_credential_pool(
self.provider, [e.to_dict() for e in self._entries],
token_bases=self._persisted_token_pairs,
)
self._persisted_token_pairs = auth_mod._token_pairs_by_id(written)
- self._borrowed_root_ids = None
+ self._borrowed_root_ids = set()
else:
self._persist()
+ # Callers print "Added" on return; a row the store did not keep
+ # must fail loudly instead.
+ if not any(isinstance(row, dict) and row.get("id") == entry.id
+ for row in auth_mod.read_credential_pool(self.provider)):
+ self._entries = [e for e in self._entries if e.id != entry.id]
+ raise CredentialNotSavedError(
+ f"The {self.provider} credential was not saved: {auth_mod._auth_file_path()} "
+ f"does not contain it after the write, so nothing was added. Check that the file "
+ f"is writable, then run the command again."
+ )
return entry
diff --git a/hermes_cli/auth_commands.py b/hermes_cli/auth_commands.py
index 69ba2535be7..71c61ccb855 100644
--- a/hermes_cli/auth_commands.py
+++ b/hermes_cli/auth_commands.py
@@ -18,6 +18,7 @@ from agent.credential_pool import (
STRATEGY_RANDOM, STRATEGY_LEAST_USED, PooledCredential, _codex_principal_identity,
_exhausted_until, _normalize_custom_pool_name, get_pool_strategy, label_from_token, list_custom_pool_providers,
load_pool)
+from agent.credential_pool_admin import CredentialNotSavedError
import hermes_cli.auth as auth_mod
from hermes_cli.auth import PROVIDER_REGISTRY
from hermes_cli.auth_plugin_providers import (
@@ -405,6 +406,8 @@ def auth_add_command(args) -> None:
except auth_mod.AuthError as exc:
# A denied / mismatched / timed-out OAuth login is a user-facing outcome, not a crash.
raise SystemExit(f"Login failed: {auth_mod.format_auth_error(exc)}") from exc
+ except CredentialNotSavedError as exc:
+ raise SystemExit(str(exc)) from exc
if wanted_priority is not None:
placed_pool = load_pool(provider)
moved = placed_pool.move_entry(entry.id, int(wanted_priority))
diff --git a/tests/agent/test_credential_pool_profile_oauth_fork.py b/tests/agent/test_credential_pool_profile_oauth_fork.py
index 1ced29e942c..12271a01be9 100644
--- a/tests/agent/test_credential_pool_profile_oauth_fork.py
+++ b/tests/agent/test_credential_pool_profile_oauth_fork.py
@@ -17,6 +17,8 @@ import urllib.request
import pytest
+from hermes_cli.auth_oauth_grants import SINGLE_USE_REFRESH_POOL_PROVIDERS
+
@pytest.fixture
def fleet(tmp_path, monkeypatch):
@@ -367,61 +369,44 @@ def test_profile_auth_add_owns_only_its_own_rows(fleet):
assert [e["id"] for e in fleet["rows"](fleet["root"])] == ["abc123"]
-def test_profile_auth_add_on_empty_root_persists_to_profile(fleet):
- """Named profile adding a single-use credential when root store has no rows (#103694).
-
- When root has no rows for the single-use provider (e.g. fresh root or unconfigured
- provider), load_pool() records an empty borrowed_ids set. The profile's add_entry()
- must persist the newly added credential to the profile store instead of silently
- routing to update-only root merge.
- """
[email protected]("provider", sorted(SINGLE_USE_REFRESH_POOL_PROVIDERS))
+def test_profile_fresh_add_with_no_login_anywhere_lands_in_the_profile(fleet, provider):
+ """#103694: with no rows in root or the profile, a login made inside the
+ profile is the profile's own credential. It must be readable afterwards,
+ and root must be left exactly as it was."""
from agent.credential_pool import AUTH_TYPE_OAUTH, PooledCredential, load_pool
- root = fleet["root"]
- (root / "auth.json").write_text(json.dumps({"version": 1, "providers": {}, "credential_pool": {}}))
+ root_file = fleet["root"] / "auth.json"
+ store = json.loads(root_file.read_text())
+ store["credential_pool"].pop(provider, None)
+ root_file.write_text(json.dumps(store))
+ kid = _profile(fleet, "kid")
+ root_before = root_file.read_bytes()
- fresh_profile = _profile(fleet, "fresh_profile")
- fleet["use"](fresh_profile)
- pool = load_pool("anthropic")
- pool.add_entry(PooledCredential(
- provider="anthropic", id="fresh001", label="fresh_auth", auth_type=AUTH_TYPE_OAUTH,
- priority=0, source="manual:hermes_pkce", access_token="sk-ant-oat01-FRESH",
- refresh_token="rt-fresh",
+ fleet["use"](kid)
+ load_pool(provider).add_entry(PooledCredential(
+ provider=provider, id="fresh1", label="mine", auth_type=AUTH_TYPE_OAUTH, priority=0,
+ source="manual:device_code", access_token="at-fresh", refresh_token="rt-fresh",
))
- assert fleet["rows"](fresh_profile) is not None, "credential was dropped without persisting (#103694)"
- assert [e["id"] for e in fleet["rows"](fresh_profile)] == ["fresh001"]
- assert fleet["rows"](root) is None
-
-
-def test_profile_auth_add_persists_when_root_and_profile_are_empty(fleet):
- """A named-profile OAuth login must not report success then
- discard the new row when neither the root nor profile has that provider.
- With no borrowed root ids, add_entry previously used _persist(); the
- borrowed-root safety path is update-only and therefore ignored the brand-
- new id. This is the exact empty-store state after a lost shared auth.json.
- """
- from agent.credential_pool import AUTH_TYPE_OAUTH, PooledCredential, load_pool
+ assert "fresh1" in [e.id for e in load_pool(provider).entries()]
+ assert "fresh1" in [r["id"] for r in json.loads((kid / "auth.json").read_text())["credential_pool"][provider]]
+ assert root_file.read_bytes() == root_before
- root = fleet["root"]
- store = json.loads((root / "auth.json").read_text())
- del store["credential_pool"]["anthropic"]
- (root / "auth.json").write_text(json.dumps(store))
- kid = _profile(fleet, "empty-kid")
- fleet["use"](kid)
- pool = load_pool("anthropic")
- assert pool.entries() == []
- assert pool._borrowed_root_ids == set()
+def test_auth_add_never_reports_added_for_a_row_the_store_did_not_keep(fleet, monkeypatch, capsys):
+ """"Added" is printed only for a credential the store holds afterwards."""
+ from argparse import Namespace
- pool.add_entry(PooledCredential(
- provider="anthropic", id="own-empty", label="mine", auth_type=AUTH_TYPE_OAUTH,
- priority=0, source="manual:hermes_pkce", access_token="at-mine-empty",
- refresh_token="rt-mine-empty",
- ))
+ import agent.credential_pool as credential_pool
+ from hermes_cli.auth_commands import auth_add_command
- assert [e["id"] for e in fleet["rows"](kid)] == ["own-empty"]
- assert fleet["rows"](root) is None
+ monkeypatch.setattr(credential_pool, "write_credential_pool", lambda *a, **kw: [])
+ with pytest.raises(SystemExit, match="not saved"):
+ auth_add_command(Namespace(
+ provider="openrouter", auth_type="api-key", api_key="sk-or-v1-new", label="new", priority=None,
+ ))
+ assert "Added" not in capsys.readouterr().out
def test_classic_mode_persist_is_unchanged(fleet):
diff --git a/website/docs/user-guide/profiles.md b/website/docs/user-guide/profiles.md
index 50f8e260ee6..c816f6da495 100644
--- a/website/docs/user-guide/profiles.md
+++ b/website/docs/user-guide/profiles.md
@@ -102,7 +102,7 @@ hermes profile create backup --clone-all
Copies **everything** — config, API keys, personality, all memories, skills, plugins. A complete working snapshot. Per-profile history is excluded (session history, `state.db`, `backups/`, `state-snapshots/`, `checkpoints/`) — these belong to the source profile and can reach tens of GB. When cloning from the default profile, the local-model runtime trees (`models/`, `runtimes/`, `node/` — downloaded weights and managed binaries, re-fetched on demand) are skipped too, as `hermes backup` already does. **Cron jobs are not cloned** either: they are scheduled work bound to the source profile and its delivery channel, and a clone that inherited them would run every job twice (two gateways, same job ids). The new profile starts with an empty `cron/`. For a full backup including history and cron jobs, use `hermes profile export` or `hermes backup` instead.
:::note OAuth logins are shared, not copied
-Anthropic (Claude Pro/Max), OpenAI Codex, and xAI OAuth logins use **single-use refresh tokens** — a copy of one is not a second credential, it is the same credential with two owners, and the first profile to refresh it revokes it for every other copy. `--clone-all` (and the dashboard's credential mirroring) therefore drops those OAuth rows from the clone. The new profile keeps reading the login from the root `~/.hermes/auth.json`, and a token refresh performed inside any profile is written back to root, so all profiles stay signed in. Static API keys are copied as usual. To give a profile its own separate OAuth login, run `hermes -p <name> auth add <provider>` inside it.
+Anthropic (Claude Pro/Max), OpenAI Codex, and xAI OAuth logins use **single-use refresh tokens** — a copy of one is not a second credential, it is the same credential with two owners, and the first profile to refresh it revokes it for every other copy. `--clone-all` (and the dashboard's credential mirroring) therefore drops those OAuth rows from the clone. The new profile keeps reading the login from the root `~/.hermes/auth.json`, and a token refresh performed inside any profile is written back to root, so all profiles stay signed in. Static API keys are copied as usual. To give a profile its own separate OAuth login, run `hermes -p <name> auth add <provider>` inside it. That login is saved in the profile's own `auth.json`, also when root has no login for the provider yet, and from then on the profile uses it instead of the root login; root's `auth.json` is not changed. If the login cannot be saved, the command fails with an error instead of printing `Added`.
:::
### Clone from a specific profile
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/profiles.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/profiles.md
index 105b70aa66c..2c5c515989b 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/profiles.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/profiles.md
@@ -70,6 +70,10 @@ hermes profile create backup --clone-all
复制**所有内容**——配置、API 密钥、人格、记忆、技能、cron 任务、插件。会排除每个 profile 自己的历史数据(会话历史、`state.db`、`backups/`、`state-snapshots/`、`checkpoints/`),这些数据属于源 profile 且可能达到数十 GB。若要包含历史的完整备份,请使用 `hermes profile export` 或 `hermes backup`。
+:::note OAuth 登录是共享的,而不是复制的
+Anthropic(Claude Pro/Max)、OpenAI Codex 和 xAI 的 OAuth 登录使用**一次性刷新令牌**——复制一份并不会得到第二个凭证,而是同一个凭证有了两个持有者,第一个刷新它的 profile 会让其他所有副本失效。因此 `--clone-all`(以及仪表盘的凭证镜像)不会把这些 OAuth 条目复制到克隆中。新 profile 继续从根目录的 `~/.hermes/auth.json` 读取登录,任何 profile 中执行的令牌刷新都会写回根目录,所有 profile 都保持登录状态。静态 API 密钥照常复制。若要让某个 profile 拥有自己独立的 OAuth 登录,请在其中运行 `hermes -p <name> auth add <provider>`。该登录保存在这个 profile 自己的 `auth.json` 中(即使根目录还没有该提供商的登录也是如此),此后该 profile 使用它而不是根目录的登录;根目录的 `auth.json` 不会被修改。如果登录无法保存,命令会报错,而不会打印 `Added`。
+:::
+
### 从指定 profile 克隆
```bash