Commit Graph

208 Commits

Author SHA1 Message Date
Teknium
99cf3a6358 fix(providers): seed_pool_credentials takes plain values; hosted ambient tokens reach the host
Under plugins.isolation: host, profile_call encodes kwargs without callable refs, so the
is_suppressed / explicitly_configured lambdas arrived in the host as non-callable Opaque values
and a hosted provider seeded nothing (while _profile_seeds_pool still disabled generic env
seeding). The seam now passes data: suppressed_sources (frozenset) and explicitly_configured
(bool), computed only for profiles that override the seam.

Shell-exported GH_TOKEN-style names are always stripped from child envs, so a hosted provider
that declares them (env_vars + ambient_credentials) never saw a shell-only token. The plugin host
env now re-adds exactly those names through get_secret under the host home's scope: the launch
home keeps its shell value, a routed home gets only its own .env value, never the launch one.
2026-10-26 00:32:10 -07:00
Teknium
2e30ce41c9 refactor(copilot): move credential logic behind generic ProviderProfile seams
GitHub->Copilot token exchange (hermes_cli/copilot_auth.py) moves into the
in-tree copilot plugin (plugins/model-providers/copilot/credentials.py), and
core's Copilot credential branches become generic profile hooks the plugin
fills: resolve_api_key_secret, runtime_base_url, prepare_pool_entry,
seed_pool_credentials, remove_credential_source, refresh_runtime_credentials,
is_stale_credential_error, request_rejection_hint, external_auth_evidence and
the ambient_credentials field. Behaviour-preserving (gh auth token fallback kept).
2026-10-25 18:04:13 -07:00
unsupportedpastels
ed6414fd6d fix(providers): keep a built-in's key off a custom entry that shares its name
A `providers:` entry keyed like a built-in (`providers.deepseek` with
`key_env: DEEPSEEK_ENTRY_KEY`) has the durable pool slug `deepseek`, which
is also the built-in's pool id. `load_pool("deepseek")` seeds that pool
from the built-in's own env vars (`env:DEEPSEEK_API_KEY`), and the
named-custom rung reads the pool before the entry's key_env. Every turn
to the entry's endpoint therefore carried the built-in provider's key,
sending a credential to a host it was never configured for. Seen live on
v0.22.1 and main. The same slug pool was also loaded unfiltered by a
bare `provider: custom` route whose URL matches the entry, by restoring
the primary after a cross-provider fallback (which then swapped in the
built-in row's key and base_url), and by a delegated child's pool. With
the declared variable unset, the host-derived `DEEPSEEK_API_KEY` stood in
for it on DeepSeek's own host.

Credential ownership now holds on every pool acquisition for the entry's
runtime. agent/custom_entry_pool.py defines it by provenance: for an
entry that declares a credential (api_key, key_env/api_key_env or
key_cmd), a slug pool contributes only its manual (`hermes auth add`)
rows and rows seeded from the entry's own key_env; `custom:<name>` pools
stay whole. The entry-scoped view is applied on:
- main, frozen and auxiliary resolution, and URL-matched bare custom
  routes (the owning entry comes from the frozen config when present);
- primary restore, keyed on the snapshot's runtime identity (`custom` /
  `custom:<name>`), never on the shared slug: no owned rows keeps the
  entry's fixed credential;
- a delegated child's pool.
A bare custom route to an entry with a declared credential now gets that
credential, and a declared credential that resolves to nothing gets no
implicit host-gated env key (the key_env warning says so truthfully).

Unchanged: explicit built-in picks still use their env keys; the
built-in loads and persists its whole pool (persisting a view leaves the
omitted rows on disk); entries that declare no credential resolve as
before; manual rows keep their precedence on the main path, and aux
resolution stays configured-key-first.

Refs #140297
2026-10-17 13:29:00 -04:00
Teknium
cb54b6bcd6 fix(credentials): a frozen session's pool seeds from its frozen config
A bare custom route takes its key from the custom_providers entry that
owns its base_url, through the credential pool. The pool seeded that
entry from live config.yaml even inside frozen_runtime_config, so a warm
owner (secrets cached in memory, so cold recovery's refusal never ran)
sent the key rotated in config.yaml to the session's endpoint.

The pool's config read now returns the session's frozen config while a
frozen resolution is active. A loopback test covers warm (the running
owner) and cold (a restarted owner refuses by name): no request carries
the rotated key.

Review finding on #139615 (independent review)
2026-10-16 02:21:08 -07:00
Teknium
a89f374d7c Merge origin/main (#45: 255 commits to 3b63f7b0a4) into feat/unified-gateway-runtime
Conflicts (2 files, 1 hunk each); every main-side change is kept, ported to
where the branch moved the code:

hermes_cli/kanban_db.py (build_worker_context helpers _ctx_cap .. _ctx_comments)
  main:   f5a6651231c/d56e357556f coerce foreign/text timestamps on read; in
          _ctx_role_history the "Recent work" stamp became
          _ctx_stamp(_to_epoch(row['ended_at']) or 0, now) instead of int().
  branch: moved the whole _ctx_* helper block into hermes_cli/kanban_db_context.py
          (kanban_db.py imports it back), deleting it from kanban_db.py.
  merged: kept the branch's deletion in kanban_db.py and applied main's change in
          kanban_db_context.py::_ctx_role_history as
          _ctx_stamp(_kb._to_epoch(row['ended_at']) or 0, now). Main's other
          timestamp coercions in kanban_db.py (Task/Run/Comment/Attachment/Event
          from_row, _TASK_EPOCH_COLUMNS, release_stale_claims,
          _extend_live_stale_claim, task_age) auto-merged unchanged.

hermes_cli/web_server.py (_lifespan)
  main:   d7830c6f42 reworded one comment in the free-tier bootstrap block
          ("the ONE place its identity is created" -> "the one boot-time creator
          of its identity"; guests are now also created on first connector use).
  branch: moved _lifespan's body into hermes_cli/web_server_app.py::app_lifespan.
  merged: kept the branch's relocation and applied main's comment rewording in
          web_server_app.py.

Merge-induced health fix (no conflict marker; the combination tripped the ratchet):
apps/desktop/src/app/session/hooks/use-cwd-actions.ts::changeSessionCwd
  main:   63ed3caa4ba/dbc538547fc grew the function (statusbar cwd change for the
          focused chat / tile runtime ids) to CC 20.
  branch: added the session_busy refusal mapping (sidebar.projects.moveBusy) in
          its catch, +1 branch -> CC 21 > target 20 (scripts/check health blocking).
  merged: both behaviours kept; the busy-error mapping moved verbatim into a
          module-level cwdChangeError(err) helper. Health back to 0 blocking.

Check: every line main added between 1fd1827726 and 3b63f7b0a4 (317 files) is
present in the merged tree.
2026-10-12 16:55:20 -07:00
alt-glitch
da8b412460 fix(free-tier): drop guest pool rows, note failed mints under the lock, share connectors_token
Fixes from the automated review on #135143:

- A guest that carried inference in a gated build left a device_code row in
  credential_pool.nous. Reopened without the launch gate, the pool still
  handed that welcome-host token to the runtime. _seed_nous_singleton now
  treats a guest without the free tier as having no runtime material, which
  runs the existing prune of singleton-seeded rows.
- The failure memo was written after _reconcile_and_provision released its
  locks, so a caller queued on them could slip in before the cooldown existed
  and mint again. The mint failure is now noted inside the locked block;
  ensure_portal_identity reuses that record instead of counting it twice.
- _nous_shared_shape dropped connectors_token, so a profile adopting the shared
  guest had to exchange for a new connector token. It is now kept.

New test: tests/agent/test_credential_pool_connectors_guest.py, red on both
#135072's head and this PR's previous head.
2026-10-13 01:35:42 +05:30
alt-glitch
5ebef93797 fix(free-tier): a guest kept for connectors never acts as a free-tier login
With the previous commit a guest identity can exist in a process where the
free tier is off (no HERMES_GUEST_ONBOARDING). Several readers assumed that
any guest on disk is a free-tier login. A read-only audit found these:

- resolve_nous_runtime_credentials exchanged an inference token for it, which
  routed runtime, credential pool, auxiliary models, pricing and the catalog
  to the welcome host. It now raises a non-terminal nous_auth_missing, so the
  identity is never quarantined and stays for connectors.
- get_nous_auth_status / get_nous_auth_status_local reported logged_in and
  free_tier. They now answer as with no Nous login (pool snapshot).
- get_nous_portal_account_info treated the guest as an account login. It now
  falls through to the pool and logged-out answers.
- guest_notice_pending showed "free Nous inference and connectors are now
  available" in the CLI. It now requires guest_enabled().
- The credential pool no longer seeds the guest.
- The shared-store import prompts (auth add nous, nous_subscription) no longer
  offer to import a guest as OAuth credentials.
- The model picker keeps the normal Nous row for a guest kept for connectors;
  only nous.guest: false still drops it.

One predicate decides all of these: anon_auth.guest_without_free_tier().
2026-10-13 01:35:42 +05:30
Teknium
408cc0d12e Merge origin/main (#32: 36 commits to cf23a1a5cc) into feat/unified-gateway-runtime
17 conflicts, all from main's lint sweep (ruff UP007/UP017/UP022/UP028/UP031/UP037/UP041,
FURB188/FURB192); no other main commit touches a conflicted file. Resolution: the branch side
of each file plus main's exact autofix (ruff 0.15.10, main's ruff.strict.toml, --fix
--unsafe-fixes). ruff.strict.toml takes main's copy. The pool-retirement live fixture stays
deleted with the pooled backend this branch retires.
2026-10-09 10:24:04 -07:00
Maciej Lisiewski
2ff58849f4 ci: ruff UP037 fixes 2026-10-09 17:34:38 +02:00
Maciej Lisiewski
9eab688b42 ci: ruff UP017 fixes 2026-10-09 17:34:36 +02:00
Maciej Lisiewski
32b70e9733 ci: FURB188, FURB192 linter fixes 2026-10-09 17:31:52 +02:00
Teknium
aa71cf9e1f fix(credential-pool): frozen routes pick pool keys from their frozen provider entry
A session frozen on a named custom provider at endpoint A resolves its route
under frozen_runtime_config, but custom_provider_pool_key_candidates() read the
provider entry from LIVE config.yaml. After the user edited the live entry's
base_url to B, the R2-M1 endpoint guard compared the frozen URL A against live
B and returned no pool keys, so the next owner turn shipped no-key-required
to A (auth-required A rejects it). It also failed the other way: a session
launched with an explicit base_url B for that provider passed the guard once
live config said B, and borrowed A's pool key.

custom_provider_pool_key_candidates() now takes the config to scan (default
still live config), and _try_resolve_from_custom_pool passes the active
frozen_runtime_config snapshot. The frozen entry owns the endpoint, so the
R2-M1 guard is unchanged: a launch URL override never inherits the named pool,
and the frozen endpoint keeps its pool after live edits. The auth store itself
is still read live, so refresh and rotation keep working. Line count for
agent/credential_pool.py goes 3,120 -> 3,116.

Red on r6-base (sources swapped from `git show r6-base:`):
  test_frozen_named_route_keeps_its_pool_after_live_endpoint_edit
    At index 1 diff: 'no-key-required' != 'sk-pool-key-for-endpoint-a'
  test_frozen_launch_url_override_never_borrows_the_named_pool
    At index 0 diff: 'sk-pool-key-for-endpoint-a' != 'no-key-required'
Green after: tests/gateway/test_session_policy.py 13 passed; adjacent
pool/runtime-provider files 237 passed.

Also switches one pre-existing `import hermes_cli.anon_auth as anon_auth` in the touched test
file to `from hermes_cli import anon_auth` (PLR0402 under ruff.strict.toml blocked the hook).

Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5458083694
2026-10-08 19:08:58 -07:00
Teknium
65bec86e37 Merge origin/main (#27: 19 commits to 517b5e10fe) into feat/unified-gateway-runtime
45 conflicts, all from #135177 (lefthook + `ruff check --fix` over 2,366 files). No other main commit
touches a conflicted file. Resolution: the branch side of each file, then main's exact autofix
(ruff 0.15.10, `--config ./ruff.strict.toml --fix`) on it — rewrites only (typing generics, noqa
drops, import forms), no import removed. tests/cron/test_bot_chat_cli_home.py stays deleted
(1cc9cb9199 retired its lane).
2026-10-08 12:09:24 -07:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
Teknium
0d90fac99d refactor(agent): move _parse_absolute_timestamp to credential_pool_timestamps
Moved unchanged; credential_pool imports it back (hermes_cli.auth,
auth_oauth_grants import it from there). Code-health FILE_LINES ratchet on
PR #106742 (credential_pool.py 3145 > 3140).

(cherry picked from commit bcf8920a139dd7aa7bbf56fbdd599aa3755cfcd9)
2026-10-07 10:57:33 -07:00
Teknium
b178d9098c Merge origin/main (#18: 76 commits to 3569fba6a6) into feat/unified-gateway-runtime
No conflicts. Overlapping auto-merges: agent/conversation_loop.py, agent/credential_pool.py,
cron/{executions,jobs,scheduler}.py, hermes_cli/{main,update_cmd}.py, Desktop i18n en/types,
locales/_keys.desktop.json, tests/fixtures/resolution_allowlist.json, cron docs.
2026-10-07 07:33:34 -07:00
unsupportedpastels
bf23bccef3 fix(auth): a profile's auth add never copies root's login into the profile
Root's login for nous, openai-codex and xai-oauth can live only in its
auth.json `providers.<id>` block, with no pool rows yet. In a profile
that borrows from root, load_pool() seeds it as a `device_code` entry
through the root fallback. The write-time claim in add_entry() kept
every entry except root's pool rows, so the profile's first `auth add`
wrote root's single-use refresh token into the profile's auth.json: a
forked grant (#100339) that the heal cannot match, because root has no
pool row for it.

- add_entry() writes only the added row when a profile claims a
  single-use provider. Rows the profile seeds from its own sources are
  seeded again on the next load.
- _seed_tokens_singleton() (openai-codex, xai-oauth) no longer seeds
  root's providers block into a profile that owns its own rows, the
  rule _seed_nous_singleton already applies. On current main such a
  profile copied root's refresh token into its own pool on every load.
2026-10-07 09:59:11 -04:00
John Paul Soliva
dc824c5f65 fix(auth): save a profile's first single-use login, and never print Added for an unsaved row
- Decide the profile claim when the row is written (the check from #101827)
  and drop the None sentinel from #103712. On current main load_pool() leaves
  a profile that borrows from an empty root at the default, so the sentinel
  alone never reached the claim path (its test stays red).
- add_entry() re-reads the store after writing. A missing row raises
  CredentialNotSavedError; `hermes auth add` exits with that message instead
  of printing "Added", and the dashboard pool endpoint returns it as a 400.
- Tests: the two contributor tests become one invariant over every
  SINGLE_USE_REFRESH_POOL_PROVIDERS provider (the row is readable, root
  auth.json is byte-identical), plus the CLI success-line contract.
- Docs: profiles page, EN and zh-Hans.

Fixes #103694

(cherry picked from commit 0e250a005a3353564642ce70f100d89174a583f2)
2026-10-07 09:59:11 -04:00
0xAlyDev
f383e66b3e fix(auth): persist profile single-use OAuth credentials when root store is empty
Fixes #103694: When a named profile runs auth add for a single-use
refresh provider (e.g. Anthropic, Codex, xAI) and the root store has
no existing rows for that provider, load_pool() sets _borrowed_root_ids = set().

Previously, add_entry() checked if borrowed_ids:, which evaluated to
False on an empty set. It fell back to _persist() -> persist_pool_entries(),
which routed to the update-only _update_root_pool_rows() on root. Because
root had no rows to update, the credential was dropped with no error and
never written to the profile's auth.json.

Checking if borrowed_ids is not None: ensures that profile-scoped pools
persist their new credential directly to the profile store via write_credential_pool(),
transitioning the profile to owning rows for that provider.

(cherry picked from commit b7467a2999832749f540d86530cf463ca0945b04)
(cherry picked from commit 9c604999e233cf6d74a83e4d7c141785b341b0d6)
2026-10-07 09:59:11 -04:00
Teknium
26c5401ad2 fix: explicit launch key wins over a named provider's pool; pools stay on their endpoint
R2-M1. `_resolve_named_custom_runtime` consulted the credential pool before the
explicit launch key, so `--api-key` (or an alias launch key) was silently replaced by
a saved `providers.<key>` pool credential; 5fd3fcf1db extended that ordering to the
frozen session path. `custom_provider_pool_key_candidates` also matched the provider
name before endpoint equality, so a launch-overridden base_url received the named
provider's pooled credential for its configured host.

- Named-custom and direct-alias resolution skip the pool when a usable explicit key
  is supplied (same precedence as the candidates list below it).
- A name-matched custom entry yields its pool keys only when its configured base_url
  equals the effective base_url (trailing slash normalized); otherwise no pool.

(cherry picked from commit 83482eff366bfb984ac69d2bf3a0c44c6c09d753)
2026-10-06 14:25:21 -07:00
Teknium
f12e6b66d9 feat(auth): brokered PKCE, expiry-driven rotation and aux on plugin OAuth rows
Generic plugin-OAuth support that the Solstice provider needs. None of it
names a provider:

- OAuthPKCEConfig.token_request: a confidential client whose secret lives
  behind a broker hands the grant to the plugin in place of a token_url
  POST. The old refresh_token is kept when the response omits one, which
  Google does on refresh.
- Plugin OAuth rows rotate 2 minutes ahead of their stored expires_at_ms
  (shared with the anthropic rule). Opaque bearers such as Google's ya29.*
  carry no JWT exp, so this stored expiry is the only clock they have.
- A row whose refresh grant just went DEAD stays DEAD on the inference 401
  that follows; before this it was re-benched EXHAUSTED and the dead token
  was replayed every cooldown.
- The auxiliary client serves an OAuth plugin that ships create_client from
  its pooled row on the main runtime's endpoint (compression, titles). It
  used to return "not directly supported".
- A 401 on a plugin OAuth row prints a re-sign-in hint, not the API-key
  advice.
- The Gemini native adapter exposes its method names, auth headers and
  error builder so a Bearer-auth subclass can reuse it without the API-key
  remedies.
2026-10-05 23:33:41 -07:00
kshitijk4poor
74449250c7 docs(fallback): fold the stranded #20465 comment into its branch; keep the pool docstring caller-free
The comment explains the index reset in the not-activated branch, which already carries a two-line version of it; the rate-limit check that used to sit under the long copy moved. The new pool method's docstring named its one caller.
2026-10-02 00:03:01 +05:30
xxxigm
c5a68f0777 fix(fallback): lift a reopened Codex quota window before gating the primary restore
A Codex 429 benches the pool entry and arms the session cooldown until a resets_at that can be days out. The pool's throttled usage probe notices an early reopen (redeemed reset, top-up), but only on select(); a session pinned to its fallback gates on the cooldown and next_available_at, which never probe, so it stayed on the fallback for the whole declared window.
2026-10-02 00:03:01 +05:30
Eva
8ec0f627ec fix(credential-pool): keep the quota probe's rotated Codex tokens when clearing the cooldown 2026-10-01 06:49:33 -04:00
Brooklyn Nicholson
e89164233f fix(auth): leave a lock-free window between deferred refresh holds
A deferred single-use refresh sweep (_refresh_pending_entries) chained N
cross-process auth-store holds back-to-back. Each hold legitimately spans its
refresh POST (single-use-token safety is test-pinned), but a waiter on the same
profile's auth.json with the shorter AUTH_LOCK_TIMEOUT_SECONDS = 15s timeout (a
Desktop assistant start) starved for the whole chain, not one refresh (#124533).

Space consecutive holds by 0.5s so a waiter's 50ms poll cadence can interleave;
the sweep still finishes promptly. The lock-across-POST contract itself is
deliberately unchanged.
2026-09-29 18:47:44 -05:00
kshitijk4poor
96cce6843d refactor(auth): drop impossible auth_store dict guard 2026-09-27 18:37:01 +05:30
kshitijk4poor
c8043a3630 fix(auth): drop redundant ownership auth.json reads in nous seeding and load_pool
_seed_nous_singleton re-read auth.json via _profile_owns_pool_provider even
though its only caller (_seed_from_singletons) just loaded the active store
and passed it in; check the passed auth_store through a shared
_store_owns_pool_provider predicate instead (same non-empty-list semantics,
also used by _profile_owns_pool_provider).

In load_pool, borrowing_root_grant repeated the guard that sets
owns_provider (non-None exactly when that guard holds), so test
`owns_provider is False` directly. The tail ownership re-read ran even
with no disk rows, where it could only assign set() -- the constructor
default -- so gate it on disk_ids and re-read only when _persist() ran.
Fix the stale "Computed once" comment.
2026-09-27 18:37:01 +05:30
kshitijk4poor
3dac1b3ae1 fix(auth): read flat refresh_token for forkable pool rows; reuse pool ownership in load_pool
_is_forkable_pool_row only ever receives flat credential_pool rows (the
strip loop over pool entries and heal_pool_rows over _pool_rows), so the
tokens-nesting fallback of _block_tokens was dead weight; read
refresh_token the same way _is_oauth_pool_payload does.

load_pool asked _profile_owns_pool_provider (an uncached auth.json read)
twice. Compute it once after the fork heal and reuse it for the
_borrowed_root_ids check unless _persist() rewrote the store in between
(that write can give the profile its own rows). _seed_nous_singleton keeps
its own call: threading the value through _seed_from_singletons would
change a signature that tests monkeypatch with fixed-arity fakes.
2026-09-27 18:37:01 +05:30
kshitijk4poor
e7bab8eb18 fix(auth): don't reseed root's nous grant into a profile that owns nous rows
A profile left with only an agent_key nous row after the fork strip/heal still
"owns" nous but has no local providers.nous block. The next load_pool('nous')
fell back to the global root block in _seed_nous_singleton and upserted root's
single-use refresh token into the profile pool, recreating the fork one load
later (both device_code and manual:* ak-row shapes). Skip seeding from the
global-root fallback when the profile owns local nous rows; borrowing profiles
(no local rows) are unaffected.

Also drop the redundant try/except around _global_auth_file_path() in
_profile_owns_pool_provider; that function already handles its own failures.
The existing nous strip test now reloads the pool after strip and asserts no
profile row carries root's refresh token.
2026-09-27 18:37:01 +05:30
kshitijk4poor
ddcd845993 fix(auth): skip auth.json re-read for pool ownership in classic mode
nous now takes the single-use path, so every load_pool('nous') (once per
message plus aux calls) re-parsed auth.json in _profile_owns_pool_provider.
In classic mode (_global_auth_file_path() is None) read_credential_pool has
no root fallback and persist_pool_entries cannot route to root, so the
answer is effectively always "owns": return early.

Also point the persist_pool_entries docstring at
SINGLE_USE_REFRESH_POOL_PROVIDERS and document why nous is deliberately
absent from _SINGLE_USE_REFRESH_PROVIDERS (own auth-store locking).
2026-09-27 18:37:01 +05:30
kshitijk4poor
5e2d55ca9c fix(codex): quota probe and /usage pool paths use the pool route base
Pool rows keep the canonical chatgpt.com URL, so the quota-restored probe
(auth_codex + CredentialPool) and the /usage tier-3 and forced-refresh
paths paired a gateway key with chatgpt.com/backend-api/wham/usage. Route
them through _codex_pool_route_base_url, the chat route's rule
(HERMES_CODEX_BASE_URL > model.base_url > row URL).

Refs #121486
2026-09-25 21:27:06 +05:30
ethernet
41934d5015 Merge remote-tracking branch 'origin/main' into ethie/pm-clean 2026-09-24 06:21:50 -04:00
kshitijk4poor
f24a1d7f92 refactor(credential_pool): drop the loop index _persist no longer reads
The previous commit replaced the positional write with _replace_entry, leaving
the enumerate index unused (ruff B007; flagged by the pre-arm simplify gate).
2026-09-24 15:44:48 +05:30
kshitijk4poor
754ea72538 refactor(credential_pool): collapse the stale-writer early returns
`_credential_token_pair` already maps a non-dict row to (None, None), so the
separate isinstance guard and second early return in
`_merge_pool_row_generation` were the same branch. Adopting a peer generation
now goes through the existing `_replace_entry` swap primitive.
2026-09-24 15:44:48 +05:30
kshitijk4poor
9e66e405cf fix(auth): return the post-persist entry from _adopt; give the adoption guard test teeth
_persist() may swap a peer's newer token generation into self._entries,
but _adopt() returned the pre-persist object. Callers that rebind the live
client from that return value (try_refresh_matching -> _swap_credential,
auxiliary_client, account_usage) would keep using the stale pair for one
guaranteed 401 while the pool already held the rotated one. Re-look the
entry up by id after persisting so the return value matches the pool.

The "adopt only if the written pair differs from the live pair" guard is
kept: without it every ordinary flush would replace the live object and
pull peer cooldown state merged into the written row into memory. The
kept generation test now asserts an unchanged-pair flush preserves object
identity and that a stale writer's _adopt returns the adopted entry;
reverting either the guard or the re-lookup fails both parametrizations.

Also move the reference-only-rows comment onto the blank-pair guard it
describes instead of the rehydration statement.
2026-09-24 15:44:48 +05:30
kshitijk4poor
d525b443f5 refactor(auth): one token-base helper with one blank-row policy; dedupe generation copy loop
The id->token-pair base map was built three ways: _persist dropped
(None, None) pairs, load_pool and _sync_entry_from_pool_store kept them.
_merge_pool_row_generation treats a missing base as "unknown" (plain
recency merge) but a (None, None) base as a known generation, so a
token-less row got the generation override on the first flush after
load_pool and the plain merge on every later one.

Policy chosen: KEEP blank bases everywhere (new auth_mod._token_pairs_by_id,
built on the existing _entry_ids). A blank base means "no pair when we last
looked", which is exactly the CAS witness the boundary needs: when a peer
lands a pair on that row, every flush of ours keeps the peer's generation
instead of writing our blank tokens back. Dropping blank bases would make
the first flush keep the peer's pair and later flushes overwrite it.
_sync_entry_from_pool_store now records the base before its no-token-
material bail-out so all three sites agree. _update_root_pool_rows reuses
_entry_ids for its incoming map as well.

Also collapse the three copy-from-disk-else-pop loops in
_merge_pool_row_generation into a local _take_from_disk helper.
failure_reason is passed alongside _POOL_STATUS_FIELDS rather than added
to the shared constant, which auth_codex/auth_oauth_grants and
_merge_disk_cooldown_state also consume.
2026-09-24 15:44:48 +05:30
kshitijk4poor
badd8f56e4 fix(auth): scope only terminal DEAD verdicts to the stale token generation
When a stale pool's persist finds the disk pair moved, #120943 copied every
status field from disk, so the stale writer's NEWER account-wide verdict
(402 billing / 429 throttle -> EXHAUSTED) was erased and the rotated pair
re-entered selection immediately. Only a terminal auth death is tied to the
pair it was observed on: discard the stale writer's DEAD onto the peer's
pair, but leave any other status for _merge_disk_cooldown_state's ordinary
recency merge.

Also travel `scope` and `inference_base_url` with the pair (a Nous refresh
rewrites them together with the tokens, so a stale writer must not stamp an
old scope/route onto the newer pair); use the always-initialised
_persisted_token_pairs directly; and re-hydrate an in-memory entry from the
written row only when the store overrode its pair, so unchanged rows keep
runtime-only fields to_dict() omits.

Tests: fold the stale-later-402 witness (rt-1 kept AND last_status ==
exhausted) into the stale-terminal-verdict test and drop the separate 429
rollback test it subsumes.

Fixes #120815

Co-authored-by: John Paul Soliva <soliva.johnpaul@icloud.com>
2026-09-24 15:44:48 +05:30
JoaoMarcos44
d2f54de2cc fix(auth): bind stale pool writes to token generation
(cherry picked from commit 1f5c7bcd076cd6184fb048ea1a57c4549f5f4991)
2026-09-24 15:44:48 +05:30
ethernet
c399093de9 merge: reconcile profile-scoped routes and shared desktop backend with PM 2026-09-21 13:18:11 -04:00
teknium1
2632229bcf fix(auth): named profiles read the root auth.json again (revert #111724)
Reverts 93889b770d ("named profiles no longer inherit the root
profile's auth.json"). After the Desktop update every bot profile that had
relied on the root OpenAI Codex login failed with "No Codex credentials
stored. Run `hermes -p <bot> auth add openai-codex --type oauth`", and users
had to re-run the device-code flow once per bot (5-6 times in the field
report). Sharing one grant across profiles is the intended design: OAuth
refresh tokens are single-use, so ONE grant lives at the root, profiles
resolve it read-only, and a refresh under a profile writes the rotated chain
back to root (Codex / xAI write-through, borrowed-row pool bookkeeping,
forked-grant heal) — never a per-profile copy.

Restored: `_global_auth_file_path` / `_load_global_auth_store` fallback in
`_load_provider_state*` / `read_credential_pool` / `_provider_state_transaction`,
Codex + xAI root write-through, `credential_pool` borrowed-root persistence,
`heal_forked_single_use_oauth_grants`, `share_auth` on profile creation
(Desktop create dialog checkbox), and the docs. `profile_credential_audit.py`
(the `hermes update` "profiles without a provider" notice) is removed with it.

Kept from after #111724: `_save_codex_tokens(set_active=...)` for image gen,
the plugin-auth `status` dispatch and the external-login notice in
`hermes auth list`, and the registry-derived env-var hint in agent_init.
2026-09-21 09:55:40 -07:00
teknium1
d03b5f3770 fix(auth): skip the Copilot token exchange while copilot is only an ambient gh-CLI credential
load_pool("copilot") exchanged the gh CLI token on every load — on installs where copilot is
never selected (main provider deepseek, aux slots auto) that is a network round-trip plus the
"degraded to RAW token" warning on every pool load, ~2 per turn, 1000+ times in five days for
the reporter (#114740). The exchange result only matters once a model is routed to copilot, so
the seeder now keeps the raw token and skips the exchange (and the warning) until
is_provider_explicitly_configured("copilot") is true; the load that follows the user selecting
copilot re-seeds and exchanges as before. auxiliary.<task>.provider now counts as selecting a
provider in _config_selects_provider, like a MoA slot, so an aux slot pinned to copilot still
gets the exchanged token. Contributor tests trimmed to two invariants.
2026-09-20 13:22:30 -07:00
Mohamad Kanso
bd2b8124f4 fix(auth): prevent repeated copilot raw token exchange warnings (#114740) 2026-09-20 13:22:30 -07:00
teknium1
bce20d0b1f feat: model-provider plugins classify their own API errors via ProviderProfile.classify_api_error
A kind: model-provider plugin is loaded by providers/ discovery and never enters the
PluginManager hook lifecycle, so transform_api_error_classification was unreachable for it
without shipping a second plugin component. The profile now carries an optional
classify_api_error(error, *, status_code, error_code, message, body, model) callable,
consulted as a classifier stage right after the generic plugin hooks and only for the
provider that produced the error. None or an unknown reason leaves the built-in verdict;
built-in providers are untouched (no name table, no lifecycle change).

Also: a plugin refresh_credential returning None/empty was treated as a successful refresh
(row marked ok, stale bearer replayed up to the refresh cap). It now benches the row like a
failed refresh POST, so the loop rotates or falls to the generic sign-in copy.

Part of #116408

(cherry picked from commit b8129fd6fd6a0cf4eeee6d95a5d5d823668a306d)
2026-09-19 21:24:05 -07:00
teknium1
ec1238fa65 fix(credential-pool): plugin refresh keeps rotated tokens, runs locked, and quarantines dead grants
Independent review of the plugin refresh branch (#116553) found four gaps
between what model-provider-plugin.md promises for `refresh_credential`
and what `_refresh_entry_impl` did:

1. `replace(entry, **hook_result)` raised TypeError on any non-field key
   (`expires_in`, `token_type`, `scope` — the natural token-endpoint shape),
   the except benched the row EXHAUSTED and the pair the server had already
   rotated was dropped: for single-use refresh tokens that is a lost login.
   Field keys now go through `replace()`, everything else merges into
   `entry.extra` (mirrors `from_dict`); `None` = no rotation, mark ok.
2. Plugin providers skipped the locked single-use path, so a gateway and a
   CLI could both POST the same refresh token (`refresh_token_reused`).
   Providers with a hook now take the `_auth_store_lock` path: re-read the
   pool store, adopt a peer's usable rotation and skip the hook, else call
   it and write through. Eligibility derives from `plugin_refresh_hook()`,
   not from extending the built-in name tuple.
3. A raising hook re-benched EXHAUSTED every cooldown forever at DEBUG.
   `AuthError(relogin_required=True)` (or a grant-dead OAuth code) is now
   terminal: the row goes DEAD with a WARNING naming `hermes auth add`.
   Any other exception stays a transient bench (negative test kept).
4. `from_dict`'s extra sweep round-tripped a stray row-level `provider` key
   back onto the row on `to_dict()`; it is bookkeeping, not metadata.

New logic lives in `agent/credential_pool_plugin.py` — credential_pool.py
is at the size cap; the facade only dispatches.

Part of #116408
2026-09-19 20:45:06 -07:00
teknium1
dce233e809 feat(auth): OAuth-shaped provider plugins register, log in and refresh through their profile
An out-of-tree ProviderProfile with auth_type oauth_device_code/oauth_external loaded and inferred
but was invisible to hermes auth: _register_plugin_provider skipped every auth_type except
external_process and api_key, so resolve_provider() said "Unknown provider", `hermes auth add`
had nothing to dispatch to, the pool could not refresh its rows (REFRESHABLE_OAUTH_PROVIDERS is a
name set) and PooledCredential.from_dict dropped every extra key outside _EXTRA_KEYS on reload.

- hermes_cli/auth_plugin_providers.py (new sibling; auth.py is at the size cap): the registry
  mirror now registers every profile under the auth_type it declares, re-syncs after discovery /
  on a miss (salvaged from #101768), and owns the seam lookups: auth_handler dispatch, the
  fail-loud error for a non-api-key profile that ships no handler, and refresh eligibility
  derived from the profile's refresh_credential hook (never a name set).
- providers/base.py: ProviderProfile.auth_handler(action, args) (salvaged from #111610, sync only)
  and refresh_credential(entry) -> rotated fields. A separate hook rather than
  auth_handler("refresh", ...) because the pool holds a credential row, not an argparse namespace,
  and needs tokens back rather than a bool.
- hermes_cli/auth_commands.py: add/status/logout/refresh (incl. interactive add) consult the
  plugin handler before the built-in path; `auth refresh` admits plugin rows via the predicate.
- agent/credential_pool.py: _refresh_entry_impl calls the profile hook; from_dict keeps every
  non-field key in extra so plugin metadata survives load -> save -> load (to_dict already wrote
  it all; sanitize_borrowed_credential_payload semantics unchanged).
- hermes_cli/auth.py: config import moved below PROVIDER_REGISTRY (salvaged from #94231) so a
  plugin imported during discovery never sees a partial auth module.

Built-in providers are untouched: only custom/openrouter were unregistered profiles before and
both stay in the skip list; anthropic/nous/openai-codex auth add/status/refresh output is
byte-identical in the before/after probe.

Part of #116408. Salvages #111610 (@Finn763), #101768 (@zihaofeng2001, absorbing #106361 by
@Finn763) and #94231 (@Kyzcreig).

Co-authored-by: finn763 <165816600+finn763@users.noreply.github.com>
Co-authored-by: zihaofeng2001 <zihaofeng2001@gmail.com>
Co-authored-by: Kyzcreig <9063726+Kyzcreig@users.noreply.github.com>
2026-09-19 20:45:06 -07:00
rjshrjndrn
7034628c92 fix(codex): proxy override survives credential rotation and model.base_url is honoured
HERMES_CODEX_BASE_URL was applied at pool resolution and on the auxiliary
clients, but two paths still sent the openai-codex provider back to the
default ChatGPT backend:

- credential rotation: client_lifecycle._swap_credential adopts
  PooledCredential.runtime_base_url, which for openai-codex was the pool
  row's stored canonical URL, so the first 401/429 rotation silently left
  the proxy. The override now lives in runtime_base_url, the one place every
  reader of a Codex pool row (resolution and rotation) goes through.
- model.base_url: the openai-codex branch of _pool_entry_mode_and_url
  returned before the generic model.base_url block. It now honours
  model.base_url under model.provider: openai-codex when the pool row still
  carries the canonical URL (env override keeps precedence).

Slim port of #40924 onto the current layout (the original patched
run_agent._swap_credential, the pool seeder and a new auth.py helper; the
seeder half landed in b62bb2a3d5, the helper is replaced by the
profile-scoped get_secret_str read the landed fixes already use).

Fixes #40913
2026-09-19 10:33:08 -07:00
teknium1
a70053d9d7 fix(auth): throttle the pre-probe Codex refresh and pin the pool-side wiring
Review follow-up on the #89415 pre-probe refresh:

- `_refresh_expired_codex_probe_token` ran ahead of `_probe_codex_quota_restored`'s
  5-minute per-token cache with no throttle of its own, so a frozen entry whose
  refresh keeps failing (revoked grant, network down) POSTed to the token endpoint
  under the pool lock on every credential selection. It now consults the same
  per-token probe cache before refreshing and reserves the stale token's slot on
  failure, restoring the pre-PR budget of at most one network call per interval.
- The pool-side refresh adopted the rotated pair into the pool row only; the next
  selection's `_sync_entry_from_auth_store` saw a differing singleton and re-adopted
  the consumed pair (clearing the cooldown with it). Stamp `last_refresh` and write
  the pair back to `providers.openai-codex` exactly as `_refresh_entry` does.
- Tests: one resolver-side refresh test is replaced by one that drives
  `CredentialPool.select()` (probe receives the refreshed bearer, both disk sides
  hold the rotated pair across a second selection) and a control that repeated
  selections with a failing refresh make a single refresh attempt.
2026-09-19 09:40:56 -07:00
teknium1
a564f77746 fix(auth): hermes auth reset survives a live session's next pool flush
A running gateway/chat holds the credential pool in memory. When the CLI
resets a still-binding cooldown from another process, the reset row on
disk has no status at all, so the recency merge in write_credential_pool
(which ranks by last_status_at) could not tell "reset after my cooldown"
from "never had a status" and let the live pool's stale EXHAUSTED entry
win on its next ordinary flush - a rotation, a token refresh, a sibling
429. `hermes auth reset` printed success and the cooldown came back
(#89415, step B in the thread). status_cleared_ids only protects the
resetting write itself.

reset_status/reset_statuses now stamp status_cleared_at on the cleared
row. The disk-cooldown merge adopts the disk row whenever the in-memory
entry is DEAD/EXHAUSTED and that marker postdates its last_status_at, and
_resync_stale_entry lifts the in-memory cooldown from the same marker, so
the live session serves the credential again without a restart. The
marker is sticky but only outranks OLDER statuses: a fresh exhaustion
after the reset stamps a newer last_status_at and still binds.

Live probe (temp HERMES_HOME, fake Codex entry, process A = live pool,
process B = real auth_reset_command): before, disk read `exhausted`
again after A's flush and A re-selected None; after, disk stays clear and
A re-selects the entry (mem ok). Control: reset then a new 402 stays
exhausted through flush and re-select.
2026-09-19 09:40:56 -07:00
Teknium
63bcdcaa43 fix(auth): refresh an expired Codex token before the quota-restored probe
_probe_codex_quota_restored was called with the exhausted pool entry's
stored access token. Exhausted entries are skipped by the proactive refresh
chain, so for any cooldown longer than the access-token lifetime (the
weekly-cap case the probe exists for) that token has expired: the usage
endpoint answers 401 token_expired, the probe maps it to None, and the
cooldown is kept. A mid-cooldown credit top-up or plan upgrade was
therefore never discovered until last_error_reset_at elapsed, even though
the refresh token was still valid (#89415).

Add _refresh_expired_codex_probe_token: when the stored token is expired
and a refresh token exists, rotate the pair via refresh_codex_oauth_pure
(cooldown untouched), persist it (refresh tokens are single-use), and probe
with the live token. Both probe callers use it: the pool-only resolve path
(_probe_codex_pool_entry_quota_restored) and
CredentialPool._codex_quota_restored_upstream. A probe that still reports
100% keeps the bench; the rotated tokens are persisted either way.

Fixes #89415
2026-09-19 09:40:56 -07:00
liuhao1024
8530d81b55 fix(credential-pool): treat rotate-to-self after mark as no-recovery
mark_exhausted_and_rotate benched the failed entry, then _select_unlocked
could hand the very same entry straight back (the auth-store sync adopted
fresher tokens and cleared the bench mid-selection, or a false-positive
quota probe lifted it). The caller took the non-None result as a successful
rotation and retried the same 429 with no attempt cap: a sole-credential
openai-codex pool on a weekly usage_limit_reached spun at ~2 req/s for
hours, ~11k requests, turn never failed (#97315).

If the post-mark selection returns the just-marked entry, return None so
the failure surfaces and provider fallback / error propagation proceed —
mirroring the single-entry guard on the unmatched-identity branch.
Multi-entry pools still rotate to a healthy sibling. Ported from PR #97328.

Fixes #97315
2026-09-19 09:40:56 -07:00