Skip to content

The agent that grows with you

refactor(honcho): trim the oauth persistence docstrings and helpers

Erosika498545bd23dc
diff --git a/plugins/memory/honcho/__init__.py b/plugins/memory/honcho/__init__.py
index af33ab835c0..f30b2c3a0d7 100644
--- a/plugins/memory/honcho/__init__.py
+++ b/plugins/memory/honcho/__init__.py
@@ -166,8 +166,7 @@ class HonchoMemoryProvider(DialecticMixin, MemoryProvider):
return False
def save_config(self, values, hermes_home):
- """Merge ``values`` into $HERMES_HOME/honcho.json (Honcho SDK native format).
- A file that exists but does not parse raises instead of being replaced by ``values`` alone."""
+ """Merge ``values`` into $HERMES_HOME/honcho.json (Honcho SDK native format); a file that does not parse raises."""
from pathlib import Path
from utils import atomic_json_write
from plugins.memory.honcho.oauth import _read_config_strict
diff --git a/plugins/memory/honcho/cli.py b/plugins/memory/honcho/cli.py
index 4fbe5a6a0bf..d1442b569bc 100644
--- a/plugins/memory/honcho/cli.py
+++ b/plugins/memory/honcho/cli.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import copy
import json
import os
import sys
@@ -67,20 +68,16 @@ def _local_config_path() -> Path:
class _ReadConfig(dict):
- """The config a command works on, carrying what disk held when it was read (``snapshot``) and where
- (``path``), so _write_config() can apply only the command's edits onto a fresh read."""
+ """A command's config, with the ``snapshot`` and ``path`` _write_config() needs to apply only its edits."""
- snapshot: dict
- path: Path
+ def __init__(self, raw: dict, path: Path):
+ super().__init__(raw)
+ self.snapshot, self.path = copy.deepcopy(raw), path
def _read_config() -> dict:
- import copy
path = _config_path()
- raw = read_json_or_empty(path)
- cfg = _ReadConfig(raw)
- cfg.snapshot, cfg.path = copy.deepcopy(raw), path
- return cfg
+ return _ReadConfig(read_json_or_empty(path), path)
class ConfigWriteRefused(Exception):
@@ -88,8 +85,7 @@ class ConfigWriteRefused(Exception):
def _refuse_unparseable(path: Path) -> None:
- """Raise ConfigWriteRefused when ``path`` exists but cannot be parsed: writing back the ``{}`` a
- tolerant read returns would drop every other host."""
+ """Raise ConfigWriteRefused when ``path`` exists but cannot be parsed; writing back ``{}`` would drop every host."""
from plugins.memory.honcho.oauth import _read_config_strict
try:
_read_config_strict(path)
@@ -99,10 +95,8 @@ def _refuse_unparseable(path: Path) -> None:
def _apply_edits(base: dict, edited: dict, current: dict) -> dict:
- """Return ``current`` with every root key and ``hosts.<h>.<k>`` the command changed between ``base``
- and ``edited`` applied. Keys the command left alone keep their on-disk value, so a token rotation
- that landed while the command ran survives; a key the command set deliberately wins."""
- import copy
+ """Return ``current`` with the root keys and ``hosts.<h>.<k>`` the command changed (``base`` to ``edited``)
+ applied. An untouched key keeps its on-disk value, so a rotation that landed while the command ran survives."""
out = copy.deepcopy(current)
for key in (set(base) | set(edited)) - {"hosts"}:
if key in edited and edited[key] != base.get(key):
@@ -126,9 +120,8 @@ def _apply_edits(base: dict, edited: dict, current: dict) -> dict:
def _write_config(cfg: dict, path: Path | None = None) -> None:
- """Persist ``cfg`` under the same cross-process lock the token refresh holds. When ``cfg`` is the
- object _read_config() returned for this path, only the command's edits are applied onto a fresh read
- of disk; a plain dict is written whole."""
+ """Persist ``cfg`` under the token refresh's cross-process lock. The object _read_config() returned
+ for this path has only its edits applied onto a fresh read of disk; a plain dict is written whole."""
from plugins.memory.honcho.oauth import _config_refresh_lock, _read_config_strict
from utils import atomic_json_write
path = path or _local_config_path()
@@ -177,8 +170,7 @@ def _default_block_and_key(cfg: dict) -> tuple[dict, bool]:
def _resolve_api_key(cfg: dict, block: dict | None = None, *, env: bool = True) -> str:
"""API key for ``block`` (default: the active host's block), host -> root -> env. A self-hosted
http(s) or host:port ``baseUrl`` without a key yields "local" so credential guards accept it.
- ``env=False`` counts only what is on disk: a write that enables a block must not rely on a variable
- that can vanish from the next process."""
+ ``env=False`` counts only what is on disk: a variable can vanish from the next process."""
block = _host_block(cfg, _host_key()) if block is None else block
key = (block.get("apiKey") or cfg.get("apiKey", "") or (os.environ.get("HONCHO_API_KEY", "") if env else ""))
if key:
@@ -333,13 +325,6 @@ def sync_honcho_profiles_quiet() -> int:
return _sync_profiles(verbose=False)
-def _no_credential_hint(host: str) -> str:
- profile = _active_profile_name()
- setup = "hermes honcho setup" + (f" --target-profile {profile}" if profile != "default" else "")
- return (f"Honcho stays disabled: no API key or base URL is configured for this profile, and the default "
- f"profile's key is not shared.\n Run '{setup}' to sign in, or set apiKey on hosts.{host} in {_config_path()}.")
-
-
def cmd_enable(args) -> None:
"""Enable Honcho for the active profile; refuses a block that cannot authenticate."""
cfg = _read_config()
@@ -347,7 +332,10 @@ def cmd_enable(args) -> None:
label = _label(host)
block = cfg.setdefault("hosts", {}).setdefault(host, {})
if not _resolve_api_key(cfg, block, env=False):
- return print(f" {label}{_no_credential_hint(host)}\n")
+ profile = _active_profile_name()
+ setup = "hermes honcho setup" + (f" --target-profile {profile}" if profile != "default" else "")
+ return print(f" {label}Honcho stays disabled: no API key or base URL is configured for this profile, and the default "
+ f"profile's key is not shared.\n Run '{setup}' to sign in, or set apiKey on hosts.{host} in {_config_path()}.\n")
if block.get("enabled") is True:
return print(f" {label}Honcho is already enabled.\n")
block["enabled"] = True
diff --git a/plugins/memory/honcho/oauth.py b/plugins/memory/honcho/oauth.py
index e3e45d0b88b..6c9b9808dba 100644
--- a/plugins/memory/honcho/oauth.py
+++ b/plugins/memory/honcho/oauth.py
@@ -273,8 +273,7 @@ def _rotate_and_persist(
rotated = _exchange_with_retry(cred, now=now)
except Exception as exc:
if isinstance(exc, OAuthRefreshError) and exc.permanent:
- # The file lock is best-effort: a sibling may have rotated first, making our
- # refresh token a replay. If disk moved on, adopt that grant instead of killing it.
+ # The file lock is best-effort: a sibling may have rotated first, so adopt what it wrote instead.
disk = _load_cred(path, host)
if disk is not None and disk.refresh_token != cred.refresh_token:
_dead_grants.pop(key, None)
@@ -349,14 +348,10 @@ def ensure_fresh_token(
logger.info("Honcho OAuth token refreshed for host %s", host)
return (rotated.access_token, True) if rotated is not None else (current.access_token, False)
-def force_refresh_token(
- path: Path, host: str, *, failed_access_token: str | None = None
-) -> str | None:
- """Rotate ``host``'s token now, ignoring local expiry (recovers a 401 on a
- token the local clock still thinks is valid). ``failed_access_token`` is the
- bearer the server rejected: when disk already holds a different one, a sibling
- rotated the single-use refresh token first, so adopt its grant instead of
- re-exchanging (a replay can revoke the whole grant)."""
+def force_refresh_token(path: Path, host: str, *, failed_access_token: str | None = None) -> str | None:
+ """Rotate ``host``'s token now, ignoring local expiry (recovers a 401 on a token the local clock
+ still thinks is valid). When disk no longer holds ``failed_access_token`` a sibling rotated first:
+ adopt its grant, since replaying the single-use refresh token can revoke the whole grant."""
now = time.time()
key = (str(path), host)
with _refresh_lock, _config_refresh_lock(path):
@@ -367,8 +362,7 @@ def force_refresh_token(
# Dead grant, or an exchange just failed transiently: callers fail open.
if _grant_is_dead(key, cred) or _in_failure_cooldown(key):
return None
- # Disk moving off the rejected bearer is the authoritative signal: the expiry cache is
- # empty in sibling processes and already equals disk after this process's first waiter.
+ # Disk, not the expiry cache, is the signal: the cache is empty in sibling processes.
if failed_access_token and cred.access_token != failed_access_token and not cred.is_expired(now=now):
_expiry_cache[key] = (cred.expires_at, cred.access_token)
return cred.access_token
@@ -388,12 +382,11 @@ def install_grant(
) -> OAuthCredential:
"""Apply a fresh OAuth grant (an OAuthTokenResponse dict) to ``path`` for ``host``: deep-merge the
grant's ``config`` into the file root (preserving other hosts and root keys), then write the host's
- ``apiKey`` and ``oauth`` block. ``apply_config=False`` stores tokens only. Runs under the same locks
- as a refresh so a login cannot interleave with a sibling's read-modify-write of the file."""
+ ``apiKey`` and ``oauth`` block. ``apply_config=False`` stores tokens only. Holds the refresh locks so a
+ login cannot interleave with a sibling's read-modify-write."""
now = time.time() if now is None else now
cred = OAuthCredential.from_token_response(grant, now=now, client_id=client_id, token_endpoint=token_endpoint)
with _refresh_lock, _config_refresh_lock(path):
- # Strict read: a login must not seed its root merge from a store it could not read.
raw = _read_config_strict(path)
granted_config = grant.get("config")
if isinstance(granted_config, dict):
diff --git a/plugins/memory/honcho/session_auth.py b/plugins/memory/honcho/session_auth.py
index 19faa365b70..d9a86ca58e5 100644
--- a/plugins/memory/honcho/session_auth.py
+++ b/plugins/memory/honcho/session_auth.py
@@ -96,9 +96,8 @@ class SessionAuthMixin:
def _force_reauth(self, failed_access_token: str | None = None) -> bool:
"""Rotate the token after a 401 and rebind the client. False for a static API key, a dead
- grant, or a failed exchange. ``failed_access_token`` is the bearer the failing operation
- sent, snapshotted by ``_authed_call`` before it ran: the live client's ``api_key`` is
- rotated in place by sibling waiters, so reading it here would defeat the adopt check."""
+ grant, or a failed exchange. ``failed_access_token`` is the bearer the operation sent; sibling
+ waiters rotate the live client's ``api_key`` in place, so it cannot be read back here."""
try:
from plugins.memory.honcho import oauth
from plugins.memory.honcho.client import reset_honcho_client
@@ -106,9 +105,7 @@ class SessionAuthMixin:
host = getattr(self._config, "host", "") or ""
if not host:
return False
- token = oauth.force_refresh_token(
- self._bound_config_path(), host, failed_access_token=failed_access_token
- )
+ token = oauth.force_refresh_token(self._bound_config_path(), host, failed_access_token=failed_access_token)
if not token:
return False
if not oauth.apply_token_to_client(self.honcho, token):