The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(honcho): compact client/session modules (no behavior change)
Teknium33f883219aea
diff --git a/plugins/memory/honcho/client.py b/plugins/memory/honcho/client.pyindex 4c717b4535b..4760ba0d9f2 100644--- a/plugins/memory/honcho/client.py+++ b/plugins/memory/honcho/client.py@@ -1,8 +1,8 @@-"""Honcho client initialization and configuration.+"""Honcho client construction and ``HonchoClientConfig`` resolution.-Config file resolution: $HERMES_HOME/honcho.json -> ~/.honcho/config.json -> env-vars (HONCHO_API_KEY, HONCHO_ENVIRONMENT). Within a file, explicit host-block-fields win over flat/global fields, which win over defaults.+Config file resolution: $HERMES_HOME/honcho.json -> ~/.honcho/config.json -> env vars+(HONCHO_API_KEY, HONCHO_ENVIRONMENT). Within a file, host-block fields win over+flat/global fields, which win over defaults."""from __future__ import annotations@@ -22,18 +22,11 @@ from agent.secret_scope import get_secretfrom hermes_cli.profiles import _get_default_hermes_homefrom hermes_constants import get_hermes_home-# Cache/slot cluster lives in client_cache.py; the names are re-exported here-# because tests and reset bookkeeping reach them through this module.+# Cache/slot cluster lives in client_cache.py; re-exported because tests and reset+# bookkeeping reach these names through this module.from plugins.memory.honcho.client_cache import ( # noqa: F401- _DEFAULT_HTTP_TIMEOUT,- _apply_fresh_oauth_token,- _client_cache_key,- _client_slots,- _client_slots_lock,- _credential_fingerprint,- _honcho_json_timeout_memo,- _refresh_cached_oauth,- _slot_for,+ _DEFAULT_HTTP_TIMEOUT, _apply_fresh_oauth_token, _client_cache_key, _client_slots, _client_slots_lock,+ _credential_fingerprint, _honcho_json_timeout_memo, _refresh_cached_oauth, _slot_for,)if TYPE_CHECKING:@@ -45,11 +38,8 @@ HOST = "hermes"def _sanitize_url(url: str | None) -> str | None:- """Return url, or None (with a warning) if it carries non-printable ASCII.-- A stray terminal escape in a pasted URL otherwise makes the SDK raise at- client construction and poisons startup.- """+ """``url``, or None (with a warning) if it carries non-printable ASCII: a stray terminal+ escape in a pasted URL otherwise makes the SDK raise at client construction."""if url is None or all(0x20 <= ord(c) < 0x7F for c in url):return urllogger.warning("Honcho base_url contains non-printable characters and will be ignored: %r", url)@@ -74,17 +64,13 @@ def _host_block(raw: dict, host: str) -> dict:def resolve_active_host() -> str:- """Derive the Honcho host key: HERMES_HONCHO_HOST env, else the active profile.-- The config's ``defaultHost`` is honored only for the default profile, so- named profiles stay isolated instead of all sharing one host.- """+ """Honcho host key: HERMES_HONCHO_HOST env, else the active profile. The config's+ ``defaultHost`` is honored only for the default profile so named profiles stay isolated."""explicit = os.environ.get("HERMES_HONCHO_HOST", "").strip()if explicit:return explicittry:from hermes_cli.profiles import get_active_profile_name-profile_host = profile_host_key(get_active_profile_name())except Exception:profile_host = HOST@@ -109,12 +95,9 @@ def resolve_global_config_path() -> Path:def resolve_config_path() -> Path:- """Return the active Honcho config path.-- $HERMES_HOME/honcho.json -> default profile's honcho.json (host blocks- accumulate there via setup/clone) -> ~/.honcho/config.json (also the- first-time-setup write target when nothing exists).- """+ """Active Honcho config path: $HERMES_HOME/honcho.json -> default profile's honcho.json+ (host blocks accumulate there via setup/clone) -> ~/.honcho/config.json (also the+ first-time-setup write target when nothing exists)."""local_path = get_hermes_home() / "honcho.json"if local_path.exists():return local_path@@ -156,12 +139,11 @@ def _first_set(*vals, default):def _first_parsed(vals, caster: Callable[[Any], Any], default):"""First non-None value that ``caster`` accepts, else default."""- for val in vals:- if val is not None:- try:- return caster(val)- except (ValueError, TypeError):- pass+ for val in (v for v in vals if v is not None):+ try:+ return caster(val)+ except (ValueError, TypeError):+ passreturn default@@ -242,11 +224,9 @@ class _HostLookup:def _is_local_base_url(base_url: str | None) -> bool:- """True for loopback/RFC1918/link-local/ULA/CGNAT self-hosted Honcho URLs.-- Local deployments can run without auth but the SDK needs a non-empty- api_key, so LAN/VPN URLs get the same placeholder-key treatment as localhost.- """+ """True for loopback/RFC1918/link-local/ULA/CGNAT self-hosted Honcho URLs. Local+ deployments can run without auth but the SDK needs a non-empty api_key, so LAN/VPN+ URLs get the same placeholder-key treatment as localhost."""if not base_url:return Falsetry:@@ -277,20 +257,15 @@ def _connection_fields(look: _HostLookup, host: str, path: Path) -> dict[str, An# Named-profile host blocks do NOT inherit the default host's apiKey (profiles# are credential-isolated); the failure is silent 401s, so warn loudly.if not api_key and host_block and host != HOST and _host_block(raw, HOST).get("apiKey"):- logger.warning(- "Honcho host block '%s' has no apiKey; the default '%s' host's key "- "is NOT inherited (profiles are credential-isolated). Set apiKey on "- "hosts.%s in %s or this profile runs unauthenticated.",- host, HOST, host, path,- )+ logger.warning("Honcho host block '%s' has no apiKey; the default '%s' host's key "+ "is NOT inherited (profiles are credential-isolated). Set apiKey on "+ "hosts.%s in %s or this profile runs unauthenticated.", host, HOST, host, path)# The SDK's native format (and Claude Desktop) nests the URL at endpoint.baseUrl;# read it before the flat Hermes spellings.endpoint_block = raw.get("endpoint")native_base_url = endpoint_block.get("baseUrl") if isinstance(endpoint_block, dict) else None- base_url = _sanitize_url(- host_block.get("baseUrl") or host_block.get("base_url") or native_base_url- or raw.get("baseUrl") or raw.get("base_url") or _env_base_url()- )+ base_url = _sanitize_url(host_block.get("baseUrl") or host_block.get("base_url") or native_base_url+ or raw.get("baseUrl") or raw.get("base_url") or _env_base_url())return {"workspace_id": look.pick("workspace") or host,"ai_peer": look.pick("aiPeer") or host,@@ -314,9 +289,7 @@ def _behavior_fields(look: _HostLookup, explicitly_configured: bool) -> dict[str# Migration guard: configs that predate observationMode keep the old# "unified" default; fresh installs get "directional" (all observations on).observation_mode = _normalize_choice(- look.pick("observationMode") or ("unified" if explicitly_configured else "directional"),- _OBSERVATION_MODES,- )+ look.pick("observationMode") or ("unified" if explicitly_configured else "directional"), _OBSERVATION_MODES)return {"peer_name": look.pick("peerName"),# pinUserPeer is the clearer name; the original pinPeerName stays accepted.@@ -409,9 +382,8 @@ class HonchoClientConfig:raw: dict[str, Any] = field(default_factory=dict)# A hosts.<host> block or explicit enabled flag, vs auto-enabled from a stray env key.explicitly_configured: bool = False- # Provenance captured at resolution time. Bound consumers use these instead of- # re-resolving: the resolvers read a ContextVar that background threads can't- # see, so re-resolution there lands on the DEFAULT profile.+ # Provenance captured at resolution time; bound consumers use these instead of+ # re-resolving (the resolvers read a ContextVar background threads can't see).config_path: Path | None = Nonehermes_home: Path | None = None@@ -426,24 +398,17 @@ class HonchoClientConfig:api_key = get_secret("HONCHO_API_KEY")base_url = _sanitize_url(_env_base_url())return cls(- host=resolved_host,- workspace_id=workspace_id,- api_key=api_key,+ host=resolved_host, workspace_id=workspace_id, api_key=api_key, base_url=base_url,environment=os.environ.get("HONCHO_ENVIRONMENT", "production"),- base_url=base_url,timeout=_resolve_optional_float(os.environ.get("HONCHO_TIMEOUT")),- ai_peer=resolved_host,- enabled=bool(api_key or base_url),- config_path=resolve_config_path(),- hermes_home=get_hermes_home(),+ ai_peer=resolved_host, enabled=bool(api_key or base_url),+ config_path=resolve_config_path(), hermes_home=get_hermes_home(),)@classmethoddef from_global_config(cls, host: str | None = None, config_path: Path | None = None) -> HonchoClientConfig:- """Create config from the resolved Honcho config path, falling back to env.-- When host is None, derives it from the active Hermes profile.- """+ """Config from the resolved Honcho config path, falling back to env. ``host=None``+ derives it from the active Hermes profile."""resolved_host = host or resolve_active_host()path = config_path or resolve_config_path()if not path.exists():@@ -459,14 +424,9 @@ class HonchoClientConfig:explicitly_configured = bool(host_block) or raw.get("enabled") is Truelook = _HostLookup(host_block, raw)return cls(- host=resolved_host,- **_connection_fields(look, resolved_host, path),- **_behavior_fields(look, explicitly_configured),- sessions=raw.get("sessions", {}),- raw=raw,- explicitly_configured=explicitly_configured,- config_path=path,- hermes_home=get_hermes_home(),+ host=resolved_host, **_connection_fields(look, resolved_host, path), **_behavior_fields(look, explicitly_configured),+ sessions=raw.get("sessions", {}), raw=raw, explicitly_configured=explicitly_configured,+ config_path=path, hermes_home=get_hermes_home(),)@staticmethod@@ -475,11 +435,8 @@ class HonchoClientConfig:import subprocesstry:- root = subprocess.run(- ["git", "rev-parse", "--show-toplevel"],- capture_output=True, text=True, encoding='utf-8', errors='replace', cwd=cwd, timeout=5,- stdin=subprocess.DEVNULL,- )+ root = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True,+ encoding='utf-8', errors='replace', cwd=cwd, timeout=5, stdin=subprocess.DEVNULL)except (OSError, subprocess.TimeoutExpired):return Nonereturn Path(root.stdout.strip()).name if root.returncode == 0 else None@@ -490,11 +447,9 @@ class HonchoClientConfig:@classmethoddef _enforce_session_id_limit(cls, sanitized: str, original: str) -> str:- """Truncate to the limit with a ``-<sha256 prefix>`` suffix hashed over the ORIGINAL key.-- Two long keys sharing a prefix stay distinct; two keys that sanitize- identically still collide intentionally (same logical session).- """+ """Truncate to the limit with a ``-<sha256 prefix>`` suffix hashed over the ORIGINAL key:+ two long keys sharing a prefix stay distinct; keys that sanitize identically still+ collide intentionally (same logical session)."""max_len, hash_len = cls._HONCHO_SESSION_ID_MAX_LEN, cls._HONCHO_SESSION_ID_HASH_LENif len(sanitized) <= max_len:return sanitized@@ -506,19 +461,13 @@ class HonchoClientConfig:return f"{self.peer_name}-{name}" if self.session_peer_prefix and self.peer_name else namedef resolve_session_name(- self,- cwd: str | None = None,- session_title: str | None = None,- session_id: str | None = None,- gateway_session_key: str | None = None,+ self, cwd: str | None = None, session_title: str | None = None,+ session_id: str | None = None, gateway_session_key: str | None = None,) -> str | None:- """Resolve the Honcho session name.-- Order: gateway session key (per-chat isolation no cwd/strategy gives) ->- per-session strategy's session_id (authoritative, so a generated title- never remaps a live conversation) -> sessions map override -> /title ->- per-repo (git root name) -> per-directory (basename) -> global (workspace).- """+ """Resolve the Honcho session name. Order: gateway session key (per-chat isolation no+ cwd/strategy gives) -> per-session strategy's session_id (authoritative, so a generated+ title never remaps a live conversation) -> sessions map override -> /title ->+ per-repo (git root name) -> per-directory (basename) -> global (workspace)."""import redef _slug(text: str) -> str:@@ -542,12 +491,9 @@ class HonchoClientConfig:def spawn_context_thread(target, *, name: str, daemon: bool = True, args: tuple = ()) -> "_threading.Thread":- """Spawn a thread that inherits the caller's contextvars.-- Profile isolation is a ContextVar (set_hermes_home_override); a plain- Thread starts with an EMPTY context, so ambient resolution on it would- silently land on the default profile.- """+ """Thread that inherits the caller's contextvars: profile isolation is a ContextVar+ (set_hermes_home_override) and a plain Thread starts EMPTY, so ambient resolution on it+ would silently land on the default profile."""import contextvarsctx = contextvars.copy_context()@@ -555,14 +501,11 @@ def spawn_context_thread(target, *, name: str, daemon: bool = True, args: tupledef get_honcho_client(config: HonchoClientConfig | None = None) -> Honcho:- """Get or create the Honcho client for this config's identity.-- Clients are cached PER IDENTITY (host, workspace, provenance paths, credential- fingerprint, timeout) so multi-profile processes don't share a first-config-wins- client. With no config, the active honcho.json is resolved — correct only on threads- that see the profile ContextVar; pass a bound config elsewhere. Thread-safe: each- identity's client is built exactly once under concurrent first calls (SingletonSlot).- """+ """Get or create the Honcho client for this config's identity. Clients are cached PER+ IDENTITY (host, workspace, provenance paths, credential fingerprint, timeout) so+ multi-profile processes don't share a first-config-wins client. With no config the active+ honcho.json is resolved — correct only on threads that see the profile ContextVar; pass a+ bound config elsewhere. Each identity's client is built once under concurrent first calls."""key = _client_cache_key(config)slot = _slot_for(key)cached = slot.peek()@@ -580,12 +523,9 @@ def get_honcho_client(config: HonchoClientConfig | None = None) -> Honcho:_apply_fresh_oauth_token(config)if not config.api_key and not config.base_url:- raise ValueError(- "Honcho API key not found. "- "Get your API key at https://app.honcho.dev, "- "then run 'hermes honcho setup' or set HONCHO_API_KEY. "- "For local instances, set HONCHO_BASE_URL instead."- )+ raise ValueError("Honcho API key not found. Get your API key at https://app.honcho.dev, "+ "then run 'hermes honcho setup' or set HONCHO_API_KEY. "+ "For local instances, set HONCHO_BASE_URL instead.")return slot.get(lambda: _build_client(config))@@ -601,11 +541,8 @@ def _build_client(config: HonchoClientConfig) -> "Honcho":try:from honcho import Honchoexcept ImportError:- raise ImportError(- "honcho-ai is required for Honcho integration. "- "Install it with: pip install honcho-ai "- "(or run `hermes honcho setup` to configure)."- )+ raise ImportError("honcho-ai is required for Honcho integration. Install it with: pip install honcho-ai "+ "(or run `hermes honcho setup` to configure).")# config.yaml honcho.base_url / timeout fill whatever honcho.json left unset.base_url, timeout = config.base_url, config.timeout@@ -628,11 +565,8 @@ def _build_client(config: HonchoClientConfig) -> "Honcho":else:# Name the SDK's environment fallback at INFO so a self-hosted user whose# config wasn't picked up notices they're talking to the public cloud.- logger.info(- "Initializing Honcho client (host: %s, workspace: %s, "- "base_url unset — SDK will resolve from environment=%s)",- config.host, config.workspace_id, config.environment,- )+ logger.info("Initializing Honcho client (host: %s, workspace: %s, base_url unset — SDK will resolve from environment=%s)",+ config.host, config.workspace_id, config.environment)# Local instances need no key but the SDK wants a non-empty string: honor a# key set EXPLICITLY in honcho.json (host block or root) and treat an@@ -642,10 +576,7 @@ def _build_client(config: HonchoClientConfig) -> "Honcho":if _is_local_base_url(base_url) and not (_host_block(raw, config.host).get("apiKey") or raw.get("apiKey")):api_key = "local"- kwargs: dict = {- "workspace_id": config.workspace_id, "api_key": api_key,- "environment": config.environment, "timeout": timeout,- }+ kwargs: dict = {"workspace_id": config.workspace_id, "api_key": api_key, "environment": config.environment, "timeout": timeout}if base_url:# The SDK's route builders already carry the version prefix ("/v3/..."), so# strip a trailing version segment from any base_url to avoid "/v3/v3/...".diff --git a/plugins/memory/honcho/client_cache.py b/plugins/memory/honcho/client_cache.pyindex c5a3d44bd91..c8c9169a7de 100644--- a/plugins/memory/honcho/client_cache.py+++ b/plugins/memory/honcho/client_cache.py@@ -1,10 +1,9 @@"""Per-identity Honcho client cache: cache keys, slots, and OAuth refresh hooks.-One SingletonSlot per client identity, replacing the single process-wide slot-that pinned the first profile's workspace and bearer for every later profile-in multi-profile processes (#69123, #74065). Origin-module symbols are-imported lazily so tests that monkeypatch ``client.resolve_config_path`` etc.-keep intercepting.+One SingletonSlot per client identity, so multi-profile processes don't pin the first+profile's workspace and bearer for every later profile. Origin-module symbols are+imported lazily so tests that monkeypatch ``client.resolve_config_path`` etc. keep+intercepting."""from __future__ import annotations@@ -49,32 +48,24 @@ def _fingerprint_basis(block: dict, key_fn) -> str:def _credential_fingerprint(config: HonchoClientConfig | None) -> str:- """Stable identity for the credential a client will be built with, or ''.-- Must NOT change on in-place access-token rotation, but must change on- account switch so 'hermes honcho setup' yields a NEW cache identity.- """+ """Stable identity for the credential a client will be built with, or ''. Must NOT change+ on in-place access-token rotation, but must change on account switch so+ 'hermes honcho setup' yields a NEW cache identity."""from plugins.memory.honcho.client import _host_blocktry:if config is not None:basis = _fingerprint_basis(_host_block(config.raw or {}, config.host), lambda: config.api_key)else:- # Ambient: correct on main threads; bound configs are the supported- # path for background threads.+ # Ambient: correct on main threads; bound configs are the supported path for background threads.raw, block = _ambient_host_block()if raw is None:return ""from agent.secret_scope import get_secret-- basis = _fingerprint_basis(- block, lambda: block.get("apiKey") or raw.get("apiKey") or get_secret("HONCHO_API_KEY") or ""- )- if basis:- return hashlib.sha256(basis.encode("utf-8")).hexdigest()[:16]+ basis = _fingerprint_basis(block, lambda: block.get("apiKey") or raw.get("apiKey") or get_secret("HONCHO_API_KEY") or "")+ return hashlib.sha256(basis.encode("utf-8")).hexdigest()[:16] if basis else ""except Exception:- pass- return ""+ return ""def _ambient_host_block() -> tuple[dict | None, dict]:@@ -89,26 +80,19 @@ def _ambient_host_block() -> tuple[dict | None, dict]:def _client_cache_key(config: HonchoClientConfig | None) -> tuple:- """Cache identity for a Honcho client build.-- Explicit configs key on connection identity, provenance paths, effective- timeout, and the credential fingerprint (the access token itself is NOT in- the key — in-place rotation must stay within one slot). Ambient callers- (config=None) key on what from_global_config() would resolve.- """+ """Cache identity for a Honcho client build. Explicit configs key on connection identity,+ provenance paths, effective timeout, and the credential fingerprint (the access token itself+ is NOT in the key — in-place rotation must stay within one slot). Ambient callers+ (config=None) key on what from_global_config() would resolve."""from plugins.memory.honcho.client import resolve_active_host, resolve_config_pathif config is not None:- return (- "explicit", config.host, config.workspace_id, config.base_url or "", config.environment,- str(config.config_path) if config.config_path is not None else "",- str(config.hermes_home) if config.hermes_home is not None else "",- _resolve_timeout_from_sources(config), _credential_fingerprint(config),- )- return (- "ambient", str(resolve_config_path()), resolve_active_host(),- _resolve_timeout_from_sources(None), _credential_fingerprint(None),- )+ return ("explicit", config.host, config.workspace_id, config.base_url or "", config.environment,+ str(config.config_path) if config.config_path is not None else "",+ str(config.hermes_home) if config.hermes_home is not None else "",+ _resolve_timeout_from_sources(config), _credential_fingerprint(config))+ return ("ambient", str(resolve_config_path()), resolve_active_host(),+ _resolve_timeout_from_sources(None), _credential_fingerprint(None))def _slot_identity(key: tuple) -> tuple:@@ -117,12 +101,9 @@ def _slot_identity(key: tuple) -> tuple:def _slot_for(key: tuple) -> SingletonSlot:- """Return the slot for ``key``, evicting stale same-identity slots.-- A same (kind, host, paths) identity with a different credential/timeout- drops the old slot so the replaced client stops being served; otherwise- credential churn leaks one pinned client per change.- """+ """Slot for ``key``, evicting stale same-identity slots: a same (kind, host, paths) identity+ with a different credential/timeout drops the old slot so the replaced client stops being+ served; otherwise credential churn leaks one pinned client per change."""identity = _slot_identity(key)with _client_slots_lock:slot = _client_slots.get(key)@@ -140,7 +121,6 @@ def _config_yaml_timeout() -> float | None:try:from hermes_cli.config import load_config_readonly-honcho_cfg = load_config_readonly().get("honcho", {})if isinstance(honcho_cfg, dict):return _resolve_optional_float(honcho_cfg.get("timeout"), honcho_cfg.get("request_timeout"))@@ -174,11 +154,8 @@ def _honcho_json_timeout() -> float | None:def _resolve_timeout_from_sources(config: HonchoClientConfig | None) -> float:- """Mirror the build path's timeout resolution exactly.-- Any skew between this and ``_build`` makes the staleness check disagree- with the built client forever and rebuild it on every call.- """+ """Mirror the build path's timeout resolution exactly: any skew makes the staleness check+ disagree with the built client forever and rebuild it on every call."""from plugins.memory.honcho.client import _resolve_optional_floatif config is not None:@@ -193,15 +170,11 @@ def _resolve_timeout_from_sources(config: HonchoClientConfig | None) -> float:def _apply_fresh_oauth_token(config: HonchoClientConfig) -> None:- """Refresh a near-expiry OAuth grant and point ``config.api_key`` at it.-- No-op for static keys or on failure (the first 401 triggers session.py's- forced rotation). Refreshes against the config's BOUND path: the ambient- resolver on daemon threads lands on the default profile's file.- """+ """Refresh a near-expiry OAuth grant and point ``config.api_key`` at it. No-op for static+ keys or on failure (the first 401 triggers session.py's forced rotation). Refreshes against+ the config's BOUND path: the ambient resolver on daemon threads lands on the default profile."""try:from plugins.memory.honcho import oauth-token, _ = oauth.ensure_fresh_token(config.bound_config_path(), config.host)if token:config.api_key = token@@ -210,16 +183,12 @@ def _apply_fresh_oauth_token(config: HonchoClientConfig) -> None:def _refresh_cached_oauth(client: Honcho, config: HonchoClientConfig | None, slot: SingletonSlot | None = None) -> None:- """Rotate the cached client's Bearer in place when its OAuth token is stale.-- If the in-place rotation can't apply (SDK shape change), the slot is reset- so the next acquisition rebuilds with the fresh token.- """+ """Rotate the cached client's Bearer in place when its OAuth token is stale. If the in-place+ rotation can't apply (SDK shape change), the slot is reset so the next acquisition rebuilds."""from plugins.memory.honcho.client import resolve_active_host, resolve_config_pathtry:from plugins.memory.honcho import oauth-if config is not None:host, path = config.host, config.bound_config_path()else:diff --git a/plugins/memory/honcho/session.py b/plugins/memory/honcho/session.pyindex 97f3a7e4ad2..514068936f3 100644--- a/plugins/memory/honcho/session.py+++ b/plugins/memory/honcho/session.py@@ -11,11 +11,7 @@ from datetime import datetimefrom typing import Any, TYPE_CHECKINGfrom plugins.memory.honcho.client import get_honcho_client, spawn_context_thread-from plugins.memory.honcho.session_auth import ( # noqa: F401 — re-exported public API- HonchoAuthError,- SessionAuthMixin,- _is_auth_error,-)+from plugins.memory.honcho.session_auth import HonchoAuthError, SessionAuthMixin, _is_auth_error # noqa: F401 — re-exportedfrom plugins.memory.honcho.session_context import SessionContextMixinfrom plugins.memory.honcho.session_migration import SessionMigrationMixinfrom plugins.memory.honcho.session_peers import SessionPeersMixin@@ -44,32 +40,17 @@ class HonchoSession:def add_message(self, role: str, content: str, **kwargs: Any) -> None:"""Add a message to the local cache."""- self.messages.append({- "role": role,- "content": content,- "timestamp": datetime.now().isoformat(),- **kwargs,- })+ self.messages.append({"role": role, "content": content, "timestamp": datetime.now().isoformat(), **kwargs})self.updated_at = datetime.now()-class HonchoSessionManager(- SessionAuthMixin, SessionPeersMixin, SessionContextMixin, SessionMigrationMixin,-):- """Manages conversation sessions using Honcho.-- Runs alongside hermes' SQLite state and file-based memory, adding persistent- cross-session user modeling. Auth retry, peer-ID resolution, recall (context/- search/conclusions/dialectic) and memory-file migration live in the mixins.- """+class HonchoSessionManager(SessionAuthMixin, SessionPeersMixin, SessionContextMixin, SessionMigrationMixin):+ """Conversation sessions backed by Honcho, alongside hermes' SQLite state and file memory.+ Auth retry, peer-ID resolution, recall and memory-file migration live in the mixins."""def __init__(- self,- honcho: Honcho | None = None,- context_tokens: int | None = None,- config: Any | None = None,- runtime_user_peer_name: str | None = None,- runtime_user_peer_name_alt: str | None = None,+ self, honcho: Honcho | None = None, context_tokens: int | None = None, config: Any | None = None,+ runtime_user_peer_name: str | None = None, runtime_user_peer_name_alt: str | None = None,):"""``honcho`` defaults to the per-identity cached client; ``context_tokens`` capscontext() calls (None = Honcho default); the runtime peer names are the gateway@@ -117,13 +98,10 @@ class HonchoSessionManager(@propertydef honcho(self) -> Honcho:- """Get the Honcho client, refreshing a near-expiry OAuth token in place.-- Always goes through ``get_honcho_client`` WITH this manager's bound config: a- long session can't outlive its 1h access token, and daemon threads (async- writer, prefetch, sync) can't see the ambient ContextVar profile, so a bare- ``get_honcho_client()`` would migrate them onto the first-built profile.- """+ """The Honcho client, refreshing a near-expiry OAuth token in place. Always goes through+ ``get_honcho_client`` WITH this manager's bound config: a long session can't outlive its+ 1h access token, and daemon threads can't see the ambient ContextVar profile, so a bare+ ``get_honcho_client()`` would migrate them onto the first-built profile."""self._honcho = get_honcho_client(self._config)return self._honcho@@ -144,40 +122,29 @@ class HonchoSessionManager(def _sdk_session(self, session_id: str) -> Any:"""Get or create the SDK session (cached until a client rebuild clears the cache)."""- return self._cached_sdk_object(- self._sessions_cache, session_id, lambda: self.honcho.session(session_id),- )+ return self._cached_sdk_object(self._sessions_cache, session_id, lambda: self.honcho.session(session_id))def _get_or_create_peer(self, peer_id: str) -> Any:"""Get or create a Honcho peer (one get-or-create API call, then cached)."""return self._cached_sdk_object(- self._peers_cache, peer_id,- lambda: self._authed_call("peer setup", lambda: self.honcho.peer(peer_id)),- )+ self._peers_cache, peer_id, lambda: self._authed_call("peer setup", lambda: self.honcho.peer(peer_id)))# ----- Session creation -----def _configure_session_peers(self, session_id: str, user_peer: Any, assistant_peer: Any) -> bool:"""add_peers with the local observation config, then adopt the server's effective- config (set via the Honcho UI, it wins over local defaults).-- Observation booleans are manager-scoped, so the last session init wins.- Returns False when auth died mid-way (already recorded by _authed_call).- """+ config (set via the Honcho UI, it wins over local defaults). Observation booleans are+ manager-scoped, so the last session init wins. Returns False when auth died mid-way+ (already recorded by _authed_call)."""peers = (("user", user_peer), ("ai", assistant_peer))try:from honcho.session import SessionPeerConfigpeer_entries = [- (peer, SessionPeerConfig(- observe_me=getattr(self, f"_{kind}_observe_me"),- observe_others=getattr(self, f"_{kind}_observe_others"),- ))+ (peer, SessionPeerConfig(observe_me=getattr(self, f"_{kind}_observe_me"),+ observe_others=getattr(self, f"_{kind}_observe_others")))for kind, peer in peers]- self._authed_call(- "session peer setup",- lambda: self._sdk_session(session_id).add_peers(peer_entries),- )+ self._authed_call("session peer setup", lambda: self._sdk_session(session_id).add_peers(peer_entries))try:server_cfgs = self._authed_call("peer configuration read",@@ -188,11 +155,8 @@ class HonchoSessionManager(value = getattr(server_cfg, field_name)if value is not None:setattr(self, f"_{kind}_{field_name}", value)- logger.debug(- "Honcho observation synced from server: user(me=%s,others=%s) ai(me=%s,others=%s)",- self._user_observe_me, self._user_observe_others,- self._ai_observe_me, self._ai_observe_others,- )+ logger.debug("Honcho observation synced from server: user(me=%s,others=%s) ai(me=%s,others=%s)",+ self._user_observe_me, self._user_observe_others, self._ai_observe_me, self._ai_observe_others)except HonchoAuthError:raiseexcept Exception as e:@@ -208,20 +172,15 @@ class HonchoSessionManager(try:ctx = self._authed_call("session context load",- lambda: self._sdk_session(session_id).context(summary=True, tokens=self._context_tokens),- )+ lambda: self._sdk_session(session_id).context(summary=True, tokens=self._context_tokens))existing_messages = ctx.messages or []if len(existing_messages) > 1:timestamps = [m.created_at for m in existing_messages if m.created_at]if timestamps and timestamps != sorted(timestamps):- logger.warning(- "Honcho messages not chronologically ordered for session '%s', sorting", session_id,- )+ logger.warning("Honcho messages not chronologically ordered for session '%s', sorting", session_id)existing_messages = sorted(existing_messages, key=lambda m: m.created_at or datetime.min)if existing_messages:- logger.info(- "Honcho session '%s' retrieved (%d existing messages)", session_id, len(existing_messages),- )+ logger.info("Honcho session '%s' retrieved (%d existing messages)", session_id, len(existing_messages))else:logger.info("Honcho session '%s' created (new)", session_id)return existing_messages@@ -231,23 +190,16 @@ class HonchoSessionManager(logger.warning("Honcho session '%s' loaded (failed to fetch context: %s)", session_id, e)return []- def _get_or_create_honcho_session(- self, session_id: str, user_peer: Any, assistant_peer: Any- ) -> tuple[Any, list]:- """Get or create a Honcho session with peers configured.-- Returns (honcho_session, existing_messages); a cached session yields no messages.- """+ def _get_or_create_honcho_session(self, session_id: str, user_peer: Any, assistant_peer: Any) -> tuple[Any, list]:+ """(honcho_session, existing_messages) with peers configured; a cached session yields no messages."""with self._cache_lock:if session_id in self._sessions_cache:logger.debug("Honcho session '%s' retrieved from cache", session_id)return self._sessions_cache[session_id], []self._authed_call("session setup", lambda: self._sdk_session(session_id))- existing_messages: list = (- self._load_existing_messages(session_id)- if self._configure_session_peers(session_id, user_peer, assistant_peer) else []- )+ existing_messages: list = (self._load_existing_messages(session_id)+ if self._configure_session_peers(session_id, user_peer, assistant_peer) else [])with self._cache_lock:honcho_session = self._sessions_cache.get(session_id)@@ -273,20 +225,13 @@ class HonchoSessionManager(honcho_session_id = self._sanitize_id(key)user_peer = self._get_or_create_peer(user_peer_id)assistant_peer = self._get_or_create_peer(assistant_peer_id)- _, existing_messages = self._get_or_create_honcho_session(- honcho_session_id, user_peer, assistant_peer- )+ _, existing_messages = self._get_or_create_honcho_session(honcho_session_id, user_peer, assistant_peer)session = HonchoSession(- key=key, user_peer_id=user_peer_id, assistant_peer_id=assistant_peer_id,- honcho_session_id=honcho_session_id,+ key=key, user_peer_id=user_peer_id, assistant_peer_id=assistant_peer_id, honcho_session_id=honcho_session_id,messages=[- {- "role": "assistant" if msg.peer_id == assistant_peer_id else "user",- "content": msg.content,- "timestamp": msg.created_at.isoformat() if msg.created_at else "",- "_synced": True,- }+ {"role": "assistant" if msg.peer_id == assistant_peer_id else "user", "content": msg.content,+ "timestamp": msg.created_at.isoformat() if msg.created_at else "", "_synced": True}for msg in existing_messages],)@@ -308,13 +253,8 @@ class HonchoSessionManager(assistant_peer = self._get_or_create_peer(session.assistant_peer_id)honcho_session = self._sessions_cache.get(session.honcho_session_id)if honcho_session is None:- honcho_session, _ = self._get_or_create_honcho_session(- session.honcho_session_id, user_peer, assistant_peer- )- honcho_messages = [- (user_peer if m["role"] == "user" else assistant_peer).message(m["content"])- for m in new_messages- ]+ honcho_session, _ = self._get_or_create_honcho_session(session.honcho_session_id, user_peer, assistant_peer)+ honcho_messages = [(user_peer if m["role"] == "user" else assistant_peer).message(m["content"]) for m in new_messages]honcho_session.add_messages(honcho_messages)return len(honcho_messages)@@ -356,11 +296,8 @@ class HonchoSessionManager(logger.error("Honcho async writer error: %s", e)def save(self, session: HonchoSession) -> None:- """Save messages to Honcho, respecting write_frequency.-- "async" enqueues for the background thread; "turn" flushes now; "session"- defers until flush_all(); int N flushes every N turns.- """+ """Save messages per write_frequency: "async" enqueues for the background thread; "turn"+ flushes now; "session" defers until flush_all(); int N flushes every N turns."""self._turn_counter += 1wf = self._write_frequencyif wf == "async":@@ -395,10 +332,7 @@ class HonchoSessionManager(returnwith self._async_thread_lock:if self._async_thread is None or not self._async_thread.is_alive():- self._async_thread = spawn_context_thread(- self._async_writer_loop,- name="honcho-async-writer",- )+ self._async_thread = spawn_context_thread(self._async_writer_loop, name="honcho-async-writer")self._async_thread.start()def stop_async_writer(self) -> None:diff --git a/plugins/memory/honcho/session_auth.py b/plugins/memory/honcho/session_auth.pyindex 19ce2935b43..25dc5852b54 100644--- a/plugins/memory/honcho/session_auth.py+++ b/plugins/memory/honcho/session_auth.py@@ -13,10 +13,8 @@ logger = logging.getLogger("plugins.memory.honcho.session")class HonchoAuthError(RuntimeError):- """Auth failure that survived a forced refresh and one retry.-- Raised, not swallowed, so callers can tell a rejected credential from an empty result.- """+ """Auth failure that survived a forced refresh and one retry. Raised, not swallowed, so+ callers can tell a rejected credential from an empty result."""# Matched narrowly: a false positive spends a token rotation, and a lost rotation revokes the grant.@@ -50,11 +48,8 @@ _REAUTH_REQUIRED_MESSAGE = (def _auth_error_message(exc: BaseException) -> str:- return (- "Honcho rejected our credentials and a forced token refresh did not "- f"recover: {_redact_tokens(str(exc))}. "- "Re-authenticate with 'hermes honcho setup'."- )+ return (f"Honcho rejected our credentials and a forced token refresh did not recover: {_redact_tokens(str(exc))}. "+ "Re-authenticate with 'hermes honcho setup'.")class SessionAuthMixin:@@ -63,11 +58,8 @@ class SessionAuthMixin:def _record_auth_failure(self, exc: BaseException) -> None:detail = _redact_tokens(str(exc))if self._auth_failure is None:- logger.error(- "Honcho authentication failed and token refresh did not recover; "- "memory sync and recall are paused until the user re-authenticates: %s",- detail,- )+ logger.error("Honcho authentication failed and token refresh did not recover; "+ "memory sync and recall are paused until the user re-authenticates: %s", detail)self._auth_failure = detaildef _clear_auth_failure(self) -> None:@@ -84,17 +76,12 @@ class SessionAuthMixin:return self._auth_failuredef _bound_config_path(self) -> Path:- """Config path for OAuth checks, bound to this manager's profile.-- Background threads can't see the ContextVar-backed ambient profile, so the- bound path keeps them on THIS profile's honcho.json; ambient resolution is- only the fallback for managers built without a config (tests).- """+ """Config path for OAuth checks, bound to this manager's profile: background threads can't+ see the ContextVar-backed ambient profile, so the bound path keeps them on THIS profile's+ honcho.json; ambient resolution is only the fallback for configless managers (tests)."""from plugins.memory.honcho.client import HonchoClientConfig, resolve_config_path- if isinstance(self._config, HonchoClientConfig):- return self._config.bound_config_path()- return resolve_config_path()+ return self._config.bound_config_path() if isinstance(self._config, HonchoClientConfig) else resolve_config_path()def _reauth_required(self) -> bool:"""True when the grant is dead and only a new login can fix it (no network call)."""@@ -108,10 +95,8 @@ class SessionAuthMixin:return Falsedef _force_reauth(self) -> bool:- """Rotate the token after a 401 and rebind the client.-- False for a static API key, a dead grant, or a failed exchange.- """+ """Rotate the token after a 401 and rebind the client. False for a static API key, a dead+ grant, or a failed exchange."""try:from plugins.memory.honcho import oauthfrom plugins.memory.honcho.client import reset_honcho_client@@ -135,11 +120,9 @@ class SessionAuthMixin:return Falsedef _authed_call(self, op_name: str, operation: Callable[[], Any]) -> Any:- """Run an authenticated SDK operation, forcing one token refresh on a 401.-- ``operation`` must re-resolve peer/session objects itself: a failed- in-place refresh rebuilds the client, orphaning objects captured earlier.- """+ """Run an authenticated SDK operation, forcing one token refresh on a 401. ``operation``+ must re-resolve peer/session objects itself: a failed in-place refresh rebuilds the+ client, orphaning objects captured earlier."""if self._reauth_required():exc = HonchoAuthError(_REAUTH_REQUIRED_MESSAGE)self._record_auth_failure(exc)@@ -151,10 +134,8 @@ class SessionAuthMixin:except Exception as e:if not _is_auth_error(e):raise- logger.warning(- "Honcho %s hit an auth error; forcing token refresh and "- "retrying once: %s", op_name, _redact_tokens(str(e)),- )+ logger.warning("Honcho %s hit an auth error; forcing token refresh and retrying once: %s",+ op_name, _redact_tokens(str(e)))if not self._force_reauth():self._record_auth_failure(e)raise HonchoAuthError(_auth_error_message(e)) from ediff --git a/plugins/memory/honcho/session_migration.py b/plugins/memory/honcho/session_migration.pyindex 1cad107af38..575dfb86392 100644--- a/plugins/memory/honcho/session_migration.py+++ b/plugins/memory/honcho/session_migration.py@@ -19,11 +19,8 @@ _MEMORY_FILES = (class SessionMigrationMixin:def migrate_memory_files(self, session_key: str, memory_dir: str) -> bool:- """Upload MEMORY.md / USER.md / SOUL.md to Honcho when it activates on an- instance with locally consolidated memory. Skips missing/empty files.-- Returns True if at least one file was uploaded.- """+ """Upload MEMORY.md / USER.md / SOUL.md to Honcho when it activates on an instance with+ locally consolidated memory; skips missing/empty files. True if at least one uploaded."""memory_path = Path(memory_dir)if not memory_path.exists():return False@@ -36,23 +33,17 @@ class SessionMigrationMixin:logger.warning("No Honcho session cached for '%s', skipping memory migration", session_key)return False- # Owner-scoped: these files describe the install owner. Uploading them under a- # non-owner's peer (any other human in a shared channel) would make Honcho's- # deriver attribute the owner's facts to that person. The owner is the CONFIG- # fact peerName — never a re-resolution of the session's own peer, which would- # compare the triggering user to themselves and pass for everyone.- # No declared owner: without a runtime identity this is the single-operator- # path; with one, nobody can be proven to be the owner.+ # Owner-scoped: these files describe the install owner; uploading them under another+ # human's peer would make Honcho attribute the owner's facts to that person. The owner is+ # the CONFIG peerName — never a re-resolution of the session's own peer (that would compare+ # the triggering user to themselves). No declared owner: single-operator only when there is+ # no runtime identity; with one, nobody can be proven to be the owner.owner_peer_id = self._declared_owner_peer_id()- session_is_owner = (- session.user_peer_id == owner_peer_id if owner_peer_id is not None else not self._runtime_user_ids()- )+ session_is_owner = (session.user_peer_id == owner_peer_id if owner_peer_id is not None+ else not self._runtime_user_ids())if not session_is_owner:- logger.info(- "Skipping memory-file migration: session user peer '%s' is not the "- "declared owner (peerName=%s)",- session.user_peer_id, owner_peer_id or "unset",- )+ logger.info("Skipping memory-file migration: session user peer '%s' is not the declared owner (peerName=%s)",+ session.user_peer_id, owner_peer_id or "unset")return Falseuploaded = False@@ -62,12 +53,10 @@ class SessionMigrationMixin:if not content:continuetarget_peer_id = session.user_peer_id if target_kind == "user" else session.assistant_peer_id- wrapped = (- "<prior_memory_file>\n<context>\n"- "This file was consolidated from local conversations BEFORE Honcho was activated.\n"- f"{description}. Treat as foundational context for this user.\n"- f"</context>\n\n{content}\n</prior_memory_file>\n"- )+ wrapped = ("<prior_memory_file>\n<context>\n"+ "This file was consolidated from local conversations BEFORE Honcho was activated.\n"+ f"{description}. Treat as foundational context for this user.\n"+ f"</context>\n\n{content}\n</prior_memory_file>\n")def _upload() -> None:self._sdk_session(session.honcho_session_id).upload_file(diff --git a/plugins/memory/honcho/session_peers.py b/plugins/memory/honcho/session_peers.pyindex d8cfee9233c..cf28865c7d4 100644--- a/plugins/memory/honcho/session_peers.py+++ b/plugins/memory/honcho/session_peers.py@@ -26,13 +26,9 @@ class SessionPeersMixin:return getattr(self._config, name, default) if self._config is not None else defaultdef _runtime_user_ids(self) -> list[str]:- """Return runtime identity candidates in lookup order (deduped, blanks dropped)."""- candidates: list[str] = []- for value in (self._runtime_user_peer_name, self._runtime_user_peer_name_alt):- candidate = str(value).strip() if value is not None else ""- if candidate and candidate not in candidates:- candidates.append(candidate)- return candidates+ """Runtime identity candidates in lookup order (deduped, blanks dropped)."""+ candidates = [str(v).strip() for v in (self._runtime_user_peer_name, self._runtime_user_peer_name_alt) if v is not None]+ return list(dict.fromkeys(c for c in candidates if c))def _peer_aliases(self) -> dict:aliases = self._cfg("user_peer_aliases", {})@@ -40,11 +36,8 @@ class SessionPeersMixin:def _explicit_user_peer_ids(self) -> set[str]:"""Return sanitized user peer IDs that came from explicit config."""- explicit_ids = {- self._sanitize_id(alias.strip())- for alias in self._peer_aliases().values()- if isinstance(alias, str) and alias.strip()- }+ explicit_ids = {self._sanitize_id(alias.strip()) for alias in self._peer_aliases().values()+ if isinstance(alias, str) and alias.strip()}owner = self._declared_owner_peer_id()if owner:explicit_ids.add(owner)@@ -66,17 +59,12 @@ class SessionPeersMixin:def _declared_owner_peer_id(self) -> str | None:"""Sanitized ``peerName`` (the install owner), or None when none is declared."""- peer_name = self._cfg("peer_name")- if peer_name and str(peer_name).strip():- return self._sanitize_id(str(peer_name).strip())- return None+ peer_name = str(self._cfg("peer_name") or "").strip()+ return self._sanitize_id(peer_name) if peer_name else Nonedef _resolve_user_peer_id(self, key: str) -> str:- """Resolve the Honcho user peer ID for this manager/session.-- Order: pinned peerName -> alias of a runtime identity -> (prefixed) runtime- identity -> configured peerName -> session-key fallback.- """+ """Honcho user peer ID for this manager/session. Order: pinned peerName -> alias of a+ runtime identity -> (prefixed) runtime identity -> configured peerName -> session-key fallback."""peer_name = self._cfg("peer_name")if peer_name and self._cfg("pin_peer_name", False) is True:return self._sanitize_id(peer_name)@@ -104,9 +92,7 @@ class SessionPeersMixin:normalized = self._sanitize_id((peer or "user").strip() or "user")return {"user": session.user_peer_id, "ai": session.assistant_peer_id}.get(normalized, normalized)- def _resolve_observer_target(- self, session: HonchoSession, peer: str | None,- ) -> tuple[str, str | None]:+ def _resolve_observer_target(self, session: HonchoSession, peer: str | None) -> tuple[str, str | None]:"""Resolve (observer, target) peer IDs for context/search/profile queries."""target_peer_id = self._resolve_peer_id(session, peer)if target_peer_id == session.assistant_peer_id: