The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(plugins/memory): honcho — extract session context/auth/peers/migration, dialectic, client cache, tool schemas; unify _parse_* config helpers; table-driven CLI
Teknium64f430a0516f
diff --git a/plugins/memory/honcho/__init__.py b/plugins/memory/honcho/__init__.pyindex 1347014cea7..10166bc5d99 100644--- a/plugins/memory/honcho/__init__.py+++ b/plugins/memory/honcho/__init__.py@@ -1,16 +1,11 @@"""Honcho memory plugin — MemoryProvider for Honcho AI-native memory.-Provides cross-session user modeling with dialectic Q&A, semantic search,-peer cards, and persistent conclusions via the Honcho SDK. Honcho provides AI-native cross-session user-modeling with dialectic Q&A, semantic search, peer cards, and conclusions.+Cross-session user modeling with dialectic Q&A, semantic search, peer cards and+persistent conclusions via the Honcho SDK. Five tools (profile, search, reasoning,+context, conclude) are exposed through the MemoryProvider interface.-Five tools (profile, search, reasoning, context, conclude) are exposed-through the MemoryProvider interface.--Config: Uses the existing Honcho config chain:- 1. $HERMES_HOME/honcho.json (profile-scoped)- 2. ~/.honcho/config.json (legacy global)- 3. Environment variables+Config chain: $HERMES_HOME/honcho.json (profile-scoped) -> ~/.honcho/config.json+(legacy global) -> environment variables."""from __future__ import annotations@@ -23,17 +18,25 @@ import timefrom typing import Any, Callable, Dict, List, Optionalfrom agent.memory_manager import sanitize_context-from agent.memory_provider import TRIVIAL_PROMPT_RE, MemoryProvider, is_trivial_prompt+from agent.memory_provider import MemoryProvider, is_trivial_promptfrom plugins.memory.honcho.client import spawn_context_thread+from plugins.memory.honcho.dialectic import DialecticMixin+from plugins.memory.honcho.tool_schemas import ( # noqa: F401 — re-exported+ ALL_TOOL_SCHEMAS,+ CONCLUDE_SCHEMA,+ CONTEXT_SCHEMA,+ PROFILE_SCHEMA,+ REASONING_SCHEMA,+ SEARCH_SCHEMA,+)from tools.registry import tool_errorlogger = logging.getLogger(__name__)-# Gateway-internal notifications can arrive through the same user-role channel-# as genuine user messages. They are execution metadata, not conversation, and-# must never become durable personal memory. Keep this deliberately anchored:-# a human discussing one of these strings mid-message is still valid input.+# Gateway-internal notifications arrive through the same user-role channel as genuine+# user messages; they are execution metadata and must never become durable memory.+# Deliberately anchored: a human discussing one of these strings mid-message is valid input._INTERNAL_GATEWAY_TURN_RE = re.compile(r"^\s*(?:"r"\[ASYNC (?:DELEGATION )?(?:BATCH )?COMPLETE[^\]]*\]|"@@ -54,226 +57,56 @@ def _is_internal_gateway_turn(text: str) -> bool:return bool(_INTERNAL_GATEWAY_TURN_RE.match(text or ""))-# ----------------------------------------------------------------------------# Tool schemas (moved from tools/honcho_tools.py)-# -----------------------------------------------------------------------------PROFILE_SCHEMA = {- "name": "honcho_profile",- "description": (- "Read or write a peer's CARD — a short, curated list of standing facts "- "about that peer (name, role, preferences, communication style, recurring "- "patterns). This is the cheapest, fastest Honcho call: no query, no LLM, "- "just the current card. Pass `card` to overwrite it; omit `card` to read. "- "An empty read returns a `hint` explaining why (observation disabled, fresh "- "peer, representation still warming up) — that is NOT an error; the card "- "accumulates over time from observed conversation. "- "Related tools: honcho_context for the fuller standing snapshot (card + "- "representation + summary + recent messages); honcho_search to find "- "specific things that were actually said; honcho_reasoning for a "- "synthesized answer to a question."- ),- "parameters": {- "type": "object",- "properties": {- "peer": {- "type": "string",- "description": "Peer to query. Built-in aliases: 'user' (default), 'ai'. Or pass any peer ID from this workspace.",- },- "card": {- "type": "array",- "items": {"type": "string"},- "description": "New peer card as a list of fact strings. Omit to read the current card.",- },- },- "required": [],- },-}+def _cfg_usable(cfg) -> bool:+ """Enabled with a credential or a self-hosted URL to talk to."""+ return bool(cfg.enabled and (cfg.api_key or cfg.base_url))-SEARCH_SCHEMA = {- "name": "honcho_search",- "description": (- "Hybrid (semantic + keyword) search over a peer's actual message "- "history across ALL past sessions they took part in — not just the "- "current one. Returns RRF-ranked raw message excerpts (what was "- "literally said, including the assistant's own messages about the "- "peer), no LLM synthesis. Cheaper and faster than honcho_reasoning. "- "Use this to recall specific past facts — 'what did I say about X', "- "'what was the regimen/decision/config we settled on' — and reason "- "over the excerpts yourself. For nuanced questions needing synthesis, "- "use honcho_reasoning instead."- ),- "parameters": {- "type": "object",- "properties": {- "query": {- "type": "string",- "description": "What to look for — a topic, keyword, name, or natural-language description of the fact you're trying to recall.",- },- "max_tokens": {- "type": "integer",- "description": "Approximate budget for returned excerpts (default 800, max 2000). Larger budgets return more/longer ranked snippets.",- },- "peer": {- "type": "string",- "description": "Whose history to search. Built-in aliases: 'user' (default), 'ai'. Or pass any peer ID from this workspace. Spans every session that peer took part in.",- },- },- "required": ["query"],- },-}-REASONING_SCHEMA = {- "name": "honcho_reasoning",- "description": (- "Ask Honcho's dialectic agent a natural-language question about a peer and "- "get back a SYNTHESIZED answer. This is the only Honcho tool that runs an "- "LLM: it agentically searches both raw messages and derived conclusions, "- "reasons over them, and writes a prose answer — so it is the slowest and "- "most expensive call (seconds + tokens). Reach for it for nuanced or "- "open-ended questions ('how does this person prefer to receive feedback?', "- "'what's their relationship to project X?') where you want Honcho to do the "- "synthesis. For a specific fact that was stated, prefer honcho_search "- "(cheap, raw excerpts, you synthesize). For standing profile facts, prefer "- "honcho_profile / honcho_context (no LLM). "- "Pass reasoning_level to control depth: minimal (fast/cheap), low (default), "- "medium, high, max (deep/expensive). Omit for the configured default."+# Static per-mode system prompt text (prompt-cache friendly: never changes between turns).+_TOOL_GUIDE = (+ "Use honcho_profile for a quick factual snapshot, "+ "honcho_search for raw excerpts, honcho_context for raw peer context, "+ "honcho_reasoning for synthesized answers (pass reasoning_level "+ "minimal/low/medium/high/max — you pick the depth per call), "+ "honcho_conclude to save facts about the user."+)+_PROMPT_HEADERS = {+ "context": (+ "# Honcho Memory\nActive (context-injection mode). Relevant user context is automatically "+ "injected before each turn. No memory tools are available — context is managed automatically."),- "parameters": {- "type": "object",- "properties": {- "query": {- "type": "string",- "description": "A natural language question.",- },- "reasoning_level": {- "type": "string",- "description": (- "Override the default reasoning depth. "- "Omit to use the configured default (typically low).\n"- "reasoning_level parameter guide:\n"- "- minimal: use ONLY for a single quick factual lookup (e.g. "- "'what is the user's name'). Honcho hard-caps this tier's output "- "at 250 tokens combined with the model's own hidden reasoning "- "tokens — a multi-part answer can get cut off mid-thought before "- "it even reaches the final-answer phase, especially on models "- "with reasoning/thinking enabled.\n"- "- low/medium/high/max: use for anything requiring a synthesized, "- "multi-fact, or summary-style answer (e.g. 'summarize known facts "- "about this peer', 'what are their communication preferences'). "- "These tiers have no output-token cap of their own (fall back to "- "Honcho's 8192-token global default), so they don't have "- "minimal's cutoff failure mode.\n"- " - low: straightforward questions with clear answers\n"- " - medium: multi-aspect questions requiring synthesis across observations\n"- " - high: complex behavioral patterns, contradictions, deep analysis\n"- " - max: thorough audit-level analysis, leave no stone unturned\n"- "Default to at least 'low' unless the query is genuinely a single "- "fact lookup."- ),- "enum": ["minimal", "low", "medium", "high", "max"],- },- "peer": {- "type": "string",- "description": "Peer to query. Built-in aliases: 'user' (default), 'ai'. Or pass any peer ID from this workspace.",- },- },- "required": ["query"],- },-}--CONTEXT_SCHEMA = {- "name": "honcho_context",- "description": (- "Retrieve the standing SNAPSHOT Honcho holds for the current session — "- "session summary, the peer's representation, the peer card, and the most "- "recent messages — in one call. No query, no LLM synthesis (cheaper than "- "honcho_reasoning). Use it to orient yourself on what Honcho currently "- "knows about this conversation and peer. This is a fixed snapshot, not a "- "search: to look up a specific past fact use honcho_search; to ask a "- "question and get a synthesized answer use honcho_reasoning; for just the "- "compact card use honcho_profile."+ "tools": (+ f"# Honcho Memory\nActive (tools-only mode). {_TOOL_GUIDE} "+ "No automatic context injection — you must use tools to access memory."),- "parameters": {- "type": "object",- "properties": {- "peer": {- "type": "string",- "description": "Peer to query. Built-in aliases: 'user' (default), 'ai'. Or pass any peer ID from this workspace.",- },- },- "required": [],- },-}--CONCLUDE_SCHEMA = {- "name": "honcho_conclude",- "description": (- "Write, delete, or list CONCLUSIONS — persistent, derived facts about a peer that "- "feeds their long-term profile (card + representation). Use this to record "- "something durable you've learned about the peer (a stable preference, a "- "correction, a standing constraint) so future sessions carry it forward. "- "You MUST pass exactly one of `conclusion` (to create), `delete_id` (to "- "delete), or `list` (to list/search); any other combination is an error. "- "A deletion ID is an opaque server-generated string: first call with `list=true` "- "and optionally `query`, then pass the returned ID as `delete_id`. "- "Deletion exists only for "- "PII removal — for merely wrong facts, write a corrected conclusion instead; "- "Honcho self-heals contradictions over time. This is a WRITE tool: to read "- "the profile use honcho_profile / honcho_context, and to search what was "- "said use honcho_search."+ "hybrid": (+ "# Honcho Memory\nActive (hybrid mode). Relevant context is auto-injected AND memory tools "+ f"are available. {_TOOL_GUIDE}"),- "parameters": {- "type": "object",- "properties": {- "conclusion": {- "type": "string",- "description": "A factual statement to persist. Provide this when creating a conclusion. Do not send it together with delete_id or list.",- },- "delete_id": {- "type": "string",- "description": "Conclusion ID to delete for PII removal. Provide this when deleting a conclusion. Do not send it together with conclusion or list. Get this id from a prior `list` call — never guess it.",- },- "list": {- "type": "boolean",- "description": "Set to true to list or search stored conclusions (with their ids) instead of creating or deleting one. Do not send together with conclusion or delete_id.",- },- "query": {- "type": "string",- "description": "Optional semantic search query, used only when `list` is true. Omit to list the most recent conclusions instead of searching.",- },- "peer": {- "type": "string",- "description": "The peer the conclusion is ABOUT. Built-in aliases: 'user' (default), 'ai'. Or pass any peer ID from this workspace.",- },- },- "required": [],- },}+# (context key, section header) for the injected base-context block, in display order.+_CONTEXT_SECTIONS = (+ ("summary", "Session Summary"),+ ("representation", "User Representation"),+ ("card", "User Peer Card"),+ ("ai_representation", "AI Self-Representation"),+ ("ai_card", "AI Identity Card"),+)-ALL_TOOL_SCHEMAS = [PROFILE_SCHEMA, SEARCH_SCHEMA, REASONING_SCHEMA, CONTEXT_SCHEMA, CONCLUDE_SCHEMA]-+_PREWARM_QUERY = "Summarize what you know about this user. Focus on preferences, current projects, and working style."-# ----------------------------------------------------------------------------# MemoryProvider implementation-# ----------------------------------------------------------------------------class HonchoMemoryProvider(MemoryProvider):+class HonchoMemoryProvider(DialecticMixin, MemoryProvider):"""Honcho AI-native memory with dialectic Q&A and persistent user modeling."""def backup_paths(self) -> List[str]:- """Honcho keeps its peer/session config under ~/.honcho when no- profile-local honcho.json exists (see client.resolve_config_path)."""- paths: List[str] = []+ """Whole ~/.honcho dir (peer/session config when no profile-local honcho.json exists)."""try:from .client import resolve_global_config_path- global_cfg = resolve_global_config_path()- # Capture the whole ~/.honcho dir so sibling state travels with it.- paths.append(str(global_cfg.parent))+ return [str(resolve_global_config_path().parent)]except Exception:- pass- return paths+ return []def __init__(self, query_rewriter: Optional[Callable[[str], str]] = None):self._manager = None # HonchoSessionManager@@ -284,27 +117,26 @@ class HonchoMemoryProvider(MemoryProvider):self._prefetch_lock = threading.Lock()self._prefetch_thread: Optional[threading.Thread] = Noneself._sync_thread: Optional[threading.Thread] = None-+ self._memwrite_thread: Optional[threading.Thread] = Noneself._recall_mode = "hybrid" # "context", "tools", or "hybrid"# Base context cache — refreshed on context_cadence, not frozenself._base_context_cache: Optional[str] = Noneself._base_context_lock = threading.Lock()- # Recall cadence and liveness state.+ # Recall cadence state (overwritten from config in initialize()).self._turn_count = 0self._query_rewrite_enabled = Falseself._injection_frequency = "every-turn" # or "first-turn"self._context_cadence = 1 # minimum turns between context API callsself._dialectic_cadence = 1 # backwards-compat fallback; wizard writes 2 on new configs- self._dialectic_depth = 1 # how many .chat() calls per dialectic cycle (1-3)+ self._dialectic_depth = 1 # .chat() calls per dialectic cycle (1-3)self._dialectic_depth_levels: list[str] | None = None # per-pass reasoning levelsself._reasoning_heuristic: bool = True # scale base level by query lengthself._reasoning_level_cap: str = "high" # ceiling for auto-selected level- self._last_context_turn = -999- self._last_dialectic_turn = -999+ self._last_context_turn = self._last_dialectic_turn = -999- # Liveness + observability state+ # Liveness stateself._prefetch_thread_started_at: float = 0.0 # monotonic ts of current threadself._prefetch_result_fired_at: int = -999 # turn the pending result was fired atself._dialectic_empty_streak: int = 0 # consecutive empty returns@@ -315,12 +147,9 @@ class HonchoMemoryProvider(MemoryProvider):self._lazy_init_session_id: Optional[str] = Noneself._init_thread: Optional[threading.Thread] = Noneself._init_lock = threading.Lock()- self._init_error = ""-# Init auth failures live here because the failed manager is discarded.self._init_auth_failure: Optional[str] = Noneself._init_auth_notice_emitted = False-# Cron and flush contexts disable the plugin entirely.self._cron_skipped = False@@ -332,26 +161,21 @@ class HonchoMemoryProvider(MemoryProvider):"""Check if Honcho is configured. No network calls."""try:from plugins.memory.honcho.client import HonchoClientConfig- cfg = HonchoClientConfig.from_global_config()- return cfg.enabled and bool(cfg.api_key or cfg.base_url)+ return _cfg_usable(HonchoClientConfig.from_global_config())except Exception:return Falsedef save_config(self, values, hermes_home):"""Write config to $HERMES_HOME/honcho.json (Honcho SDK native format)."""- import json- import osfrom pathlib import Path- config_path = Path(hermes_home) / "honcho.json"- existing = {}- if config_path.exists():- try:- existing = json.loads(config_path.read_text(encoding="utf-8"))- except Exception:- pass- existing.update(values)from utils import atomic_json_write- atomic_json_write(config_path, existing, mode=0o600)+ from plugins.memory.honcho.client import _read_config+ config_path = Path(hermes_home) / "honcho.json"+ try:+ existing = _read_config(config_path)+ except Exception:+ existing = {}+ atomic_json_write(config_path, {**existing, **values}, mode=0o600)def get_config_schema(self):return [@@ -365,64 +189,52 @@ class HonchoMemoryProvider(MemoryProvider):from plugins.memory.honcho.cli import cmd_setupcmd_setup(types.SimpleNamespace())- def initialize(self, session_id: str, **kwargs) -> None:- """Initialize Honcho session manager.+ # ----- Session lifecycle ------ Handles cron guards, recall configuration, session resolution,- memory migration, and optional dialectic prewarming.- """+ def initialize(self, session_id: str, **kwargs) -> None:+ """Configure recall settings and start (or defer) Honcho session creation."""try:- agent_context = kwargs.get("agent_context", "")- platform = kwargs.get("platform", "cli")+ agent_context, platform = kwargs.get("agent_context", ""), kwargs.get("platform", "cli")if agent_context in {"cron", "flush"} or platform == "cron":logger.debug("Honcho skipped: cron/flush context (agent_context=%s, platform=%s)",agent_context, platform)self._cron_skipped = Truereturn- from plugins.memory.honcho.client import HonchoClientConfig, get_honcho_client- from plugins.memory.honcho.session import HonchoSessionManager+ from plugins.memory.honcho.client import HonchoClientConfig, get_honcho_client # noqa: F401 — ImportError probe+ from plugins.memory.honcho.session import HonchoSessionManager # noqa: F401cfg = HonchoClientConfig.from_global_config()- if not cfg.enabled or not (cfg.api_key or cfg.base_url):+ if not _cfg_usable(cfg):logger.debug("Honcho not configured — plugin inactive")returnself._config = cfg-- self._recall_mode = cfg.recall_mode # "context", "tools", or "hybrid"+ self._recall_mode = cfg.recall_modelogger.debug("Honcho recall_mode: %s", self._recall_mode)-- self._injection_frequency = cfg.injection_frequency- self._context_cadence = cfg.context_cadence- self._dialectic_cadence = cfg.dialectic_cadence+ for name in ("injection_frequency", "context_cadence", "dialectic_cadence",+ "dialectic_depth_levels", "reasoning_heuristic"):+ setattr(self, f"_{name}", getattr(cfg, name))self._query_rewrite_enabled = cfg.query_rewriteself._FIRST_TURN_BASE_TIMEOUT = cfg.first_turn_base_waitself._FIRST_TURN_DIALECTIC_CAP = cfg.first_turn_dialectic_waitself._dialectic_depth = max(1, min(cfg.dialectic_depth, 3))- self._dialectic_depth_levels = cfg.dialectic_depth_levels- self._reasoning_heuristic = cfg.reasoning_heuristicif cfg.reasoning_level_cap in self._LEVEL_ORDER:self._reasoning_level_cap = cfg.reasoning_level_cap- # aiPeer comes from honcho.json (host block or root) only.- # SOUL.md is persona content, not identity config.-+ # aiPeer comes from honcho.json only; SOUL.md is persona content, not identity config.self._lazy_init_kwargs = dict(kwargs)self._lazy_init_session_id = session_idself._session_key = self._resolve_session_key(cfg, session_id, **kwargs)- # Network-backed session creation can block on Honcho service or DB- # outages. Startup must fail open for context/hybrid modes, where- # Honcho is initialized only to enrich prompts. Tools-only mode has- # an explicit contract: init_on_session_start=False stays lazy until- # the first tool call, while init_on_session_start=True remains an- # eager, ready-on-return initialization path.+ # Session creation can block on Honcho/DB outages, so context/hybrid startup+ # fails open in a background thread. Tools-only mode has an explicit contract:+ # init_on_session_start=False stays lazy until the first tool call, True is eager.if self._recall_mode == "tools":if cfg.init_on_session_start:self._ensure_session()- return- logger.debug("Honcho tools-only mode — deferring session init until first tool call")+ else:+ logger.debug("Honcho tools-only mode — deferring session init until first tool call")returnself._start_session_init_background(wait_timeout=0.1)@@ -435,211 +247,125 @@ class HonchoMemoryProvider(MemoryProvider):def _resolve_session_key(self, cfg, session_id: str, **kwargs) -> str:"""Resolve the Honcho session key without touching the network."""- session_title = kwargs.get("session_title")- gateway_session_key = kwargs.get("gateway_session_key")return (cfg.resolve_session_name(- session_title=session_title,+ session_title=kwargs.get("session_title"),session_id=session_id,- gateway_session_key=gateway_session_key,+ gateway_session_key=kwargs.get("gateway_session_key"),)or session_idor "hermes-default")- def _start_session_init_background(self, *, wait_timeout: float = 0.0) -> None:- """Start Honcho session initialization in a daemon thread.+ def _can_start_init(self) -> bool:+ return not (self._cron_skipped or self._session_initialized) and bool(self._config) and self._lazy_init_kwargs is not None- This keeps Hermes CLI/gateway startup responsive when Honcho is down,- slow, or its database is unhealthy. The thread may still take the SDK- timeout path, but it cannot block agent construction or first prompt- assembly. ``wait_timeout`` lets fast/mock initializations finish before- returning while still failing open for slow backends.- """- if self._cron_skipped or self._session_initialized:- return- if not self._config or self._lazy_init_kwargs is None:- return+ def _run_session_init(self, label: str) -> bool:+ """Run _do_session_init with the deferred kwargs; on failure discard the manager+ and (for auth failures) keep the detail for the one-time notice."""+ from plugins.memory.honcho.session import HonchoAuthError+ init_kwargs = self._lazy_init_kwargs+ if init_kwargs is None: # another init path already consumed the deferred kwargs+ return self._manager is not None+ try:+ self._do_session_init(self._config, self._lazy_init_session_id or "hermes-default", **dict(init_kwargs))+ self._lazy_init_kwargs = None+ self._lazy_init_session_id = None+ if self._init_auth_failure is not None:+ self._init_auth_failure = None+ self._init_auth_notice_emitted = False+ return True+ except Exception as e:+ self._manager = None+ self._session_initialized = False+ detail: object = e+ if isinstance(e, HonchoAuthError):+ # Keep the auth detail so the one-time notice survives the manager discard.+ self._init_auth_failure = str(e)+ detail = "authentication rejected"+ logger.warning("Honcho %s session init failed: %s", label, detail)+ return False++ def _start_session_init_background(self, *, wait_timeout: float = 0.0) -> None:+ """Start session initialization in a daemon thread so a slow/down Honcho can't+ block agent construction or first prompt assembly. ``wait_timeout`` lets fast+ (mock) initializations finish before returning."""+ if not self._can_start_init():+ returnwith self._init_lock:- if self._cron_skipped or self._session_initialized:+ if not self._can_start_init() or (self._init_thread and self._init_thread.is_alive()):return- if self._init_thread and self._init_thread.is_alive():- return- if not self._config or self._lazy_init_kwargs is None:- return-- cfg = self._config- init_kwargs = dict(self._lazy_init_kwargs)- init_session_id = self._lazy_init_session_id or "hermes-default"-- def _run() -> None:- from plugins.memory.honcho.session import HonchoAuthError-- try:- self._do_session_init(cfg, init_session_id, **init_kwargs)- self._lazy_init_kwargs = None- self._lazy_init_session_id = None- self._init_error = ""- self._clear_init_auth_failure()- except HonchoAuthError as e:- self._init_error = str(e)- self._record_init_auth_failure(e)- self._manager = None- logger.warning("Honcho background session init failed: authentication rejected")- except Exception as e:- self._init_error = str(e)- self._manager = None- logger.warning("Honcho background session init failed: %s", e)-self._init_thread = spawn_context_thread(- _run,- name="honcho-session-init",+ lambda: self._run_session_init("background"), name="honcho-session-init",)self._init_thread.start()if wait_timeout > 0:self._init_thread.join(timeout=wait_timeout)+ def _ensure_session(self) -> bool:+ """Lazily initialize the Honcho session (tools-only mode). True when the manager is ready."""+ if self._manager and self._session_initialized:+ return True+ if not self._can_start_init() or (self._init_thread and self._init_thread.is_alive()):+ return False+ return self._run_session_init("lazy") and self._manager is not None+def _do_session_init(self, cfg, session_id: str, **kwargs) -> None:- """Shared session initialization logic for both eager and lazy paths."""+ """Shared session initialization for both eager and lazy paths."""from plugins.memory.honcho.client import get_honcho_clientfrom plugins.memory.honcho.session import HonchoSessionManager- client = get_honcho_client(cfg)self._manager = HonchoSessionManager(- honcho=client,+ honcho=get_honcho_client(cfg),config=cfg,context_tokens=cfg.context_tokens,runtime_user_peer_name=kwargs.get("user_id") or None,runtime_user_peer_name_alt=kwargs.get("user_id_alt") or None,)-self._session_key = self._resolve_session_key(cfg, session_id, **kwargs)logger.debug("Honcho session key resolved: %s", self._session_key)- # Create the remote session before running startup-only migration and- # prewarm work. Do not mark the provider ready until this method's- # synchronous setup has finished; background startup sets _manager before- # get_or_create()/migration/prewarm are complete, and lifecycle hooks must+ # The provider is not "ready" until this method returns: background startup sets+ # _manager before get_or_create/migration/prewarm finish, and lifecycle hooks must# not treat that partially initialized state as usable.session = self._manager.get_or_create(self._session_key)- # Skip under per-session strategy: every Hermes run creates a fresh- # Honcho session by design, so uploading MEMORY.md/USER.md/SOUL.md to- # each one would flood the backend with short-lived duplicates instead- # of performing a one-time migration.- try:- if not session.messages and cfg.session_strategy != "per-session":+ # Per-session strategy creates a fresh Honcho session every run, so a per-run+ # MEMORY.md/USER.md/SOUL.md upload would flood the backend with duplicates.+ if cfg.session_strategy == "per-session":+ logger.debug(+ "Honcho memory file migration skipped: per-session strategy creates a fresh session per run (%s)",+ self._session_key,+ )+ elif not session.messages:+ try:from hermes_constants import get_hermes_home- mem_dir = str(get_hermes_home() / "memories")- self._manager.migrate_memory_files(self._session_key, mem_dir)+ self._manager.migrate_memory_files(self._session_key, str(get_hermes_home() / "memories"))logger.debug("Honcho memory file migration attempted for new session: %s", self._session_key)- elif cfg.session_strategy == "per-session":- logger.debug(- "Honcho memory file migration skipped: per-session strategy creates a fresh session per run (%s)",- self._session_key,- )- except Exception as e:- logger.debug("Honcho memory file migration skipped: %s", e)+ except Exception as e:+ logger.debug("Honcho memory file migration skipped: %s", e)- # Query-aware base retrieval starts with the first substantive message.- # Generic dialectic prewarm is incompatible with latest-message rewriting.+ # Generic dialectic prewarm is incompatible with latest-message query rewriting,+ # which needs the first substantive user message.if self._recall_mode in {"context", "hybrid"}:if self._query_rewriter is None or not self._query_rewrite_enabled:- _prewarm_query = (- "Summarize what you know about this user. "- "Focus on preferences, current projects, and working style."+ self._spawn_dialectic(+ _PREWARM_QUERY, thread_name="honcho-prewarm-dialectic", fired_at=0,+ log_label="dialectic prewarm", use_query_rewrite=False,)-- def _prewarm_dialectic() -> None:- try:- r = self._run_dialectic_depth(- _prewarm_query, use_query_rewrite=False- )- except Exception as exc:- logger.debug("Honcho dialectic prewarm failed: %s", exc)- self._note_dialectic_failure(exc)- return- if r and r.strip():- with self._prefetch_lock:- self._prefetch_result = r- self._prefetch_result_fired_at = 0- self._last_dialectic_turn = 0- self._dialectic_empty_streak = 0- else:- self._dialectic_empty_streak += 1-- self._prefetch_thread_started_at = time.monotonic()- prewarm_thread = spawn_context_thread(- _prewarm_dialectic,- name="honcho-prewarm-dialectic",- )- prewarm_thread.start()- self._prefetch_thread = prewarm_threadlogger.debug("Honcho dialectic prewarm started for session: %s", self._session_key)else:- logger.debug(- "Honcho generic dialectic prewarm skipped: awaiting first user message"- )+ logger.debug("Honcho generic dialectic prewarm skipped: awaiting first user message")self._session_initialized = True- def _ensure_session(self) -> bool:- """Lazily initialize the Honcho session (for tools-only mode).-- Returns True if the manager is ready, False otherwise.- """- if self._manager and self._session_initialized:- return True- if self._cron_skipped:- return False- if self._init_thread and self._init_thread.is_alive():- return False- if not self._config or self._lazy_init_kwargs is None:- return False-- from plugins.memory.honcho.session import HonchoAuthError-- try:- self._do_session_init(- self._config,- self._lazy_init_session_id or "hermes-default",- **self._lazy_init_kwargs,- )- # Clear lazy refs- self._lazy_init_kwargs = None- self._lazy_init_session_id = None- self._clear_init_auth_failure()- return self._manager is not None- except HonchoAuthError as e:- self._record_init_auth_failure(e)- self._manager = None- self._session_initialized = False- logger.warning("Honcho lazy session init failed: authentication rejected")- return False- except Exception as e:- self._manager = None- self._session_initialized = False- logger.warning("Honcho lazy session init failed: %s", e)- return False-- def _record_init_auth_failure(self, exc: BaseException) -> None:- """Keep the auth detail so the one-time notice survives the manager discard."""- self._init_auth_failure = str(exc)-- def _clear_init_auth_failure(self) -> None:- if self._init_auth_failure is not None:- self._init_auth_failure = None- self._init_auth_notice_emitted = False-def _session_ready(self) -> bool:- """Return whether a manager/session key can be used safely.+ """Whether the manager/session key can be used safely.- Background initialization sets ``_manager`` before the blocking- get-or-create call completes, so ``_session_initialized`` guards real- async startup. Tests and legacy direct construction may inject a ready- manager/session key without setting that flag; allow that only when no- init thread is currently in flight.+ Background init sets ``_manager`` before get-or-create completes, so+ ``_session_initialized`` is the real guard; tests/legacy construction may inject+ a ready manager without the flag — allow that only with no init thread in flight."""if not self._manager or not self._session_key:return False@@ -647,265 +373,144 @@ class HonchoMemoryProvider(MemoryProvider):return Truereturn not (self._init_thread and self._init_thread.is_alive())- def _format_first_turn_context(self, ctx: dict) -> str:- """Format the prefetch context dict into a readable system prompt block."""- parts = []-- # Session summary — session-scoped context, placed first for relevance- summary = ctx.get("summary", "")- if summary:- parts.append(f"## Session Summary\n{summary}")+ def _writes_enabled(self) -> bool:+ """``saveMessages`` is the operator's hard write gate for every Honcho mutation path."""+ return not self._cron_skipped and getattr(self._config, "save_messages", True)- rep = ctx.get("representation", "")- if rep:- parts.append(f"## User Representation\n{rep}")-- card = ctx.get("card", "")- if card:- parts.append(f"## User Peer Card\n{card}")-- ai_rep = ctx.get("ai_representation", "")- if ai_rep:- parts.append(f"## AI Self-Representation\n{ai_rep}")+ def _ready_or_kick_init(self) -> bool:+ """True when writes may proceed; otherwise (outside tools mode) start background init."""+ if self._session_ready():+ return True+ if self._recall_mode != "tools":+ self._start_session_init_background()+ return False- ai_card = ctx.get("ai_card", "")- if ai_card:- parts.append(f"## AI Identity Card\n{ai_card}")+ # ----- Prompt / prefetch ------ if not parts:- return ""+ def _format_first_turn_context(self, ctx: dict) -> str:+ """Format the prefetch context dict into a readable system prompt block."""+ parts = [f"## {header}\n{ctx.get(key, '')}" for key, header in _CONTEXT_SECTIONS if ctx.get(key, "")]return "\n\n".join(parts)def system_prompt_block(self) -> str:- """Return system prompt text, adapted by recall_mode.-- Returns only the mode header and tool instructions — static text- that doesn't change between turns (prompt-cache friendly).- Live context (representation, card) is injected via prefetch().- """- if self._cron_skipped:+ """Static mode header + tool instructions (prompt-cache friendly).+ Live context (representation, card) is injected via prefetch()."""+ if self._cron_skipped or not (self._config or (self._manager and self._session_key)):return ""- if not self._manager or not self._session_key:- if not self._config:- return ""+ return _PROMPT_HEADERS.get(self._recall_mode, _PROMPT_HEADERS["hybrid"])++ def _first_turn_wait(self, base: float) -> float:+ """Turn-1 wait budget: a short request timeout may tighten, but never expand, it."""+ request_timeout = getattr(self._config, "timeout", None)+ if request_timeout is not None:+ base = min(base, max(0.0, request_timeout))+ return max(0.0, base)++ def _fetch_base_context_layer(self, query: str, first_turn_base_deadline: float | None) -> str:+ """Layer 1: representation + card. The first fetch gets the remaining turn-1 budget;+ later turns consume the refresh queued by the previous turn."""+ with self._base_context_lock:+ first_base_fetch = self._base_context_cache is None+ if first_base_fetch:+ self._base_context_cache = ""+ self._last_context_turn = self._turn_count+ base_context = self._base_context_cache- if self._recall_mode == "context":- header = (- "# Honcho Memory\n"- "Active (context-injection mode). Relevant user context is automatically "- "injected before each turn. No memory tools are available — context is "- "managed automatically."- )- elif self._recall_mode == "tools":- header = (- "# Honcho Memory\n"- "Active (tools-only mode). Use honcho_profile for a quick factual snapshot, "- "honcho_search for raw excerpts, honcho_context for raw peer context, "- "honcho_reasoning for synthesized answers (pass reasoning_level "- "minimal/low/medium/high/max — you pick the depth per call), "- "honcho_conclude to save facts about the user. "- "No automatic context injection — you must use tools to access memory."- )- else: # hybrid- header = (- "# Honcho Memory\n"- "Active (hybrid mode). Relevant context is auto-injected AND memory tools are available. "- "Use honcho_profile for a quick factual snapshot, "- "honcho_search for raw excerpts, honcho_context for raw peer context, "- "honcho_reasoning for synthesized answers (pass reasoning_level "- "minimal/low/medium/high/max — you pick the depth per call), "- "honcho_conclude to save facts about the user."- )+ if not self._manager:+ return base_context++ def _adopt(ctx: dict) -> str:+ """Cache a fresh context dict's formatted block; keep the old text if it formats empty."""+ formatted = self._format_first_turn_context(ctx)+ if formatted:+ with self._base_context_lock:+ self._base_context_cache = formatted+ return formatted or base_context++ if not first_base_fetch:+ fresh_ctx = self._manager.pop_context_result(self._session_key)+ return _adopt(fresh_ctx) if fresh_ctx else base_context++ ctx_holder: dict[str, dict] = {}++ def _fetch_base() -> None:+ ctx = self._manager.get_prefetch_context(self._session_key, query or None) or {}+ ctx_holder["ctx"] = ctx+ if ctx:+ self._manager.set_context_result(self._session_key, ctx)++ bt = self._spawn_write(_fetch_base, "honcho-base-first", "Honcho first-turn base context failed: %s")+ base_wait = max(0.0, first_turn_base_deadline - time.monotonic()) if first_turn_base_deadline is not None else 0.0+ bt.join(timeout=base_wait)+ ctx = ctx_holder.get("ctx")+ if ctx:+ self._manager.pop_context_result(self._session_key)+ return _adopt(ctx)+ if bt.is_alive():+ logger.debug("Honcho first-turn base context still running after %.1fs — will surface on next turn", base_wait)+ return base_context++ def _first_turn_dialectic_wait(self, query: str) -> None:+ """Turn 1 only: reuse an in-flight prewarm or start one dialectic, then wait briefly.+ Unfinished work stays async and surfaces on a later turn."""+ with self._prefetch_lock:+ prewarm_landed = bool(self._prefetch_result)+ if prewarm_landed and self._last_dialectic_turn == -999:+ self._last_dialectic_turn = self._turn_count+ if self._last_dialectic_turn != -999 or not query:+ return- return header+ dia_wait = self._first_turn_wait(self._FIRST_TURN_DIALECTIC_CAP)+ if not self._thread_is_live():+ self._spawn_dialectic(+ query, thread_name="honcho-prefetch-first", fired_at=self._turn_count,+ log_label="first-turn dialectic",+ )+ live = self._prefetch_thread+ if live is not None:+ live.join(timeout=dia_wait)+ if self._prefetch_thread and self._prefetch_thread.is_alive():+ logger.debug("Honcho first-turn dialectic still running after %.1fs — will surface on next turn", dia_wait)def prefetch(self, query: str, *, session_id: str = "") -> str:- """Return base context (representation + card) plus dialectic supplement.-- Assembles two layers:- 1. Base context from peer.context() — cached, refreshed on context_cadence- 2. Dialectic supplement — cached, refreshed on dialectic_cadence-- Returns empty in tools-only mode and respects the configured injection- frequency and context budget.- """- if self._cron_skipped:+ """Base context (representation + card, refreshed on context_cadence) plus the+ dialectic supplement (refreshed on dialectic_cadence), within the context budget.+ Empty in tools-only mode."""+ if self._cron_skipped or self._recall_mode == "tools":return ""- # Tools-only mode has no automatic injection.- if self._recall_mode == "tools":- return ""-- first_turn_base_deadline = None- if self._turn_count <= 1:- base_wait = self._FIRST_TURN_BASE_TIMEOUT- request_timeout = getattr(self._config, "timeout", None)- if request_timeout is not None:- base_wait = min(base_wait, max(0.0, request_timeout))- first_turn_base_deadline = time.monotonic() + max(0.0, base_wait)+ first_turn_base_deadline = (+ time.monotonic() + self._first_turn_wait(self._FIRST_TURN_BASE_TIMEOUT) if self._turn_count <= 1 else None+ )if not self._session_ready():# Only turn 1 may wait for session init; later turns fail open.self._start_session_init_background()- if first_turn_base_deadline is not None:- _init_thread = self._init_thread- if _init_thread is not None:- _init_thread.join(- timeout=max(0.0, first_turn_base_deadline - time.monotonic())- )+ if first_turn_base_deadline is not None and self._init_thread is not None:+ self._init_thread.join(timeout=max(0.0, first_turn_base_deadline - time.monotonic()))if not self._session_ready():# A failed auth init still owes the user the one-time notice.return self._pop_auth_notice()- # First-turn mode suppresses only the base layer; dialectic is independent.- _skip_base = (- self._injection_frequency == "first-turn" and self._turn_count > 1- )-# Trivial turns start no work, but may consume a ready pending result.if self._is_trivial_prompt(query):ready = self._consume_pending_dialectic()return self._truncate_to_budget(ready) if ready else ""- parts = []-# One-time notice, relayed by the model, that auth is dead and memory is paused.- auth_notice = self._pop_auth_notice()- if auth_notice:- parts.append(auth_notice)-- # ----- Layer 1: Base context (representation + card) ------ if not _skip_base:- # The first base fetch gets the remaining turn-1 budget. Later- # refreshes are consumed asynchronously.- with self._base_context_lock:- _first_base_fetch = self._base_context_cache is None- if _first_base_fetch:- self._base_context_cache = ""- self._last_context_turn = self._turn_count- base_context = self._base_context_cache-- if _first_base_fetch and self._manager:- _ctx_holder: dict[str, dict] = {}-- def _fetch_base() -> None:- try:- ctx = self._manager.get_prefetch_context(- self._session_key, query or None- ) or {}- _ctx_holder["ctx"] = ctx- if ctx:- self._manager.set_context_result(self._session_key, ctx)- except Exception as e:- logger.debug("Honcho first-turn base context failed: %s", e)-- _bt = spawn_context_thread(_fetch_base, name="honcho-base-first")- _bt.start()- _base_wait = (- max(0.0, first_turn_base_deadline - time.monotonic())- if first_turn_base_deadline is not None- else 0.0- )- _bt.join(timeout=_base_wait)- _ctx = _ctx_holder.get("ctx")- if _ctx:- self._manager.pop_context_result(self._session_key)- formatted = self._format_first_turn_context(_ctx)- if formatted:- with self._base_context_lock:- self._base_context_cache = formatted- base_context = formatted- elif _bt.is_alive():- logger.debug(- "Honcho first-turn base context still running after %.1fs — "- "will surface on next turn", _base_wait,- )-- # Later turns consume the refresh queued by the previous turn.- if not _first_base_fetch and self._manager:- fresh_ctx = self._manager.pop_context_result(self._session_key)- if fresh_ctx:- formatted = self._format_first_turn_context(fresh_ctx)- if formatted:- with self._base_context_lock:- self._base_context_cache = formatted- base_context = formatted-- if base_context:- parts.append(base_context)-- # ----- Layer 2: Dialectic supplement ------ # Turn 1 may briefly wait for dialectic; unfinished work remains async.- with self._prefetch_lock:- _prewarm_landed = bool(self._prefetch_result)- if _prewarm_landed and self._last_dialectic_turn == -999:- self._last_dialectic_turn = self._turn_count-- if self._last_dialectic_turn == -999 and query:- # Reuse an in-flight prewarm; otherwise start one dialectic. A short- # request timeout may tighten, but never expand, the turn-1 wait.- _dia_wait = self._FIRST_TURN_DIALECTIC_CAP- request_timeout = getattr(self._config, "timeout", None)- if request_timeout is not None:- _dia_wait = min(_dia_wait, max(0.0, request_timeout))- if self._thread_is_live():- _live = self._prefetch_thread- if _live is not None:- _live.join(timeout=_dia_wait)- else:- _first_turn_timeout = _dia_wait- _fired_at = self._turn_count-- def _run_first_turn() -> None:- try:- r = self._run_dialectic_depth(query)- except Exception as exc:- logger.debug("Honcho first-turn dialectic failed: %s", exc)- self._note_dialectic_failure(exc)- return- if r and r.strip():- with self._prefetch_lock:- self._prefetch_result = r- self._prefetch_result_fired_at = _fired_at- # Empty results do not consume the cadence window.- self._last_dialectic_turn = _fired_at- self._dialectic_empty_streak = 0- else:- self._dialectic_empty_streak += 1-- self._prefetch_thread_started_at = time.monotonic()- first_turn_thread = spawn_context_thread(- _run_first_turn, name="honcho-prefetch-first"- )- first_turn_thread.start()- self._prefetch_thread = first_turn_thread- self._prefetch_thread.join(timeout=_first_turn_timeout)- if self._prefetch_thread and self._prefetch_thread.is_alive():- logger.debug(- "Honcho first-turn dialectic still running after %.1fs — "- "will surface on next turn",- _dia_wait,- )-+ parts = [self._pop_auth_notice()]+ # First-turn mode suppresses only the base layer; dialectic is independent.+ if not (self._injection_frequency == "first-turn" and self._turn_count > 1):+ parts.append(self._fetch_base_context_layer(query, first_turn_base_deadline))+ self._first_turn_dialectic_wait(query)# Consume only results that are already ready; later turns never wait.- dialectic_result = self._consume_pending_dialectic()-- if dialectic_result and dialectic_result.strip():- parts.append(dialectic_result)-- if not parts:- return ""-- result = "\n\n".join(parts)-- result = self._truncate_to_budget(result)-- return result+ parts.append(self._consume_pending_dialectic())+ parts = [p for p in parts if p and p.strip()]+ return self._truncate_to_budget("\n\n".join(parts)) if parts else ""def _pop_auth_notice(self) -> str:"""One-time model-facing notice that Honcho auth expired and memory is paused."""- # getattr (not a direct call): test fakes install minimal managers- # without pop_auth_notice; exceptions still propagate.+ # getattr (not a direct call): test fakes install minimal managers without pop_auth_notice.pop = getattr(self._manager, "pop_auth_notice", None)msg = pop() if callable(pop) else Noneif not isinstance(msg, str) or not msg:@@ -915,43 +520,19 @@ class HonchoMemoryProvider(MemoryProvider):self._init_auth_notice_emitted = Truemsg = self._init_auth_failurereturn (- "[Honcho memory status] Authentication with the Honcho memory backend "- "has expired and automatic token refresh failed, so memory sync and "- f"recall are paused. Reason: {msg}\n"- "Tell the user (once) that Honcho memory is paused and that running "- "'hermes honcho setup' to re-authenticate will restore it."+ "[Honcho memory status] Authentication with the Honcho memory backend has expired and automatic "+ f"token refresh failed, so memory sync and recall are paused. Reason: {msg}\n"+ "Tell the user (once) that Honcho memory is paused and that running 'hermes honcho setup' "+ "to re-authenticate will restore it.")- def _consume_pending_dialectic(self) -> str:- """Pop any pending dialectic result, applying the stale-discard guard.-- Returns an empty string when no result is ready or the pending result- is older than the configured cadence window.- """- with self._prefetch_lock:- dialectic_result = self._prefetch_result- fired_at = self._prefetch_result_fired_at- self._prefetch_result = ""- self._prefetch_result_fired_at = -999-- # Drop results that no longer track the current conversational pivot.- stale_limit = self._dialectic_cadence * self._STALE_RESULT_MULTIPLIER- if dialectic_result and fired_at >= 0 and (self._turn_count - fired_at) > stale_limit:- logger.debug(- "Honcho pending dialectic discarded as stale: fired_at=%d, "- "turn=%d, limit=%d", fired_at, self._turn_count, stale_limit,- )- return ""- return dialectic_result if (dialectic_result and dialectic_result.strip()) else ""-def _truncate_to_budget(self, text: str) -> str:- """Truncate text to fit within context_tokens budget if set."""+ """Truncate text to the context_tokens budget (≈4 chars/token) at a word boundary."""if not self._config or not self._config.context_tokens:return text- budget_chars = self._config.context_tokens * 4 # conservative char estimate+ budget_chars = self._config.context_tokens * 4if len(text) <= budget_chars:return text- # Truncate at word boundarytruncated = text[:budget_chars]last_space = truncated.rfind(" ")if last_space > budget_chars * 0.8:@@ -960,28 +541,18 @@ class HonchoMemoryProvider(MemoryProvider):def queue_prefetch(self, query: str, *, session_id: str = "") -> None:"""Fire background prefetch threads for the upcoming turn.-- Context and dialectic refreshes have independent cadence controls.- """- if self._cron_skipped:- return- # Tools-only mode has no automatic prefetch.- if self._recall_mode == "tools":+ Context and dialectic refreshes have independent cadence controls."""+ if self._cron_skipped or self._recall_mode == "tools":return-if not self._session_ready() or not query:self._start_session_init_background()return-# Trivial prompts don't warrant either a context refresh or a dialectic call.if self._is_trivial_prompt(query):return# First-turn-only base context never needs a later refresh.- context_due = (- self._context_cadence <= 1- or (self._turn_count - self._last_context_turn) >= self._context_cadence- )+ context_due = self._context_cadence <= 1 or (self._turn_count - self._last_context_turn) >= self._context_cadenceif self._injection_frequency != "first-turn" and context_due:self._last_context_turn = self._turn_counttry:@@ -989,16 +560,12 @@ class HonchoMemoryProvider(MemoryProvider):except Exception as e:logger.debug("Honcho context prefetch failed: %s", e)- # ----- Dialectic prefetch (supplement layer) ------ # Thread-alive guard with stale-thread recovery: a hung Honcho call- # older than timeout × multiplier is treated as dead so it can't- # block subsequent fires.+ # Dialectic layer: a hung call older than timeout × multiplier counts as dead.if self._thread_is_live():logger.debug("Honcho dialectic prefetch skipped: prior thread still running")return-- # Cadence gate, widened by the empty-streak backoff so a persistently- # silent backend doesn't retry every turn forever.+ # Cadence gate, widened by the empty-streak backoff so a persistently silent+ # backend doesn't retry every turn forever.effective = self._effective_cadence()if (self._turn_count - self._last_dialectic_turn) < effective:logger.debug(@@ -1008,508 +575,119 @@ class HonchoMemoryProvider(MemoryProvider):self._turn_count - self._last_dialectic_turn,)return+ self._spawn_dialectic(+ query, thread_name="honcho-prefetch", fired_at=self._turn_count, log_label="prefetch",+ )- # Cadence advances only on a non-empty result so empty returns- # (transient API error, sparse representation) retry next turn.- _fired_at = self._turn_count-- def _run():- try:- result = self._run_dialectic_depth(query)- except Exception as e:- logger.debug("Honcho prefetch failed: %s", e)- self._note_dialectic_failure(e)- return- if result and result.strip():- with self._prefetch_lock:- self._prefetch_result = result- self._prefetch_result_fired_at = _fired_at- self._last_dialectic_turn = _fired_at- self._dialectic_empty_streak = 0- else:- self._dialectic_empty_streak += 1-- self._prefetch_thread_started_at = time.monotonic()- prefetch_thread = spawn_context_thread(_run, name="honcho-prefetch")- prefetch_thread.start()- self._prefetch_thread = prefetch_thread-- # ----- Dialectic depth: multi-pass .chat() with cold/warm prompts ------- # Proportional reasoning levels per depth/pass when dialecticDepthLevels- # is not configured. The base level is dialecticReasoningLevel.- # Index: (depth, pass) → level relative to base.- _PROPORTIONAL_LEVELS: dict[tuple[int, int], str] = {- # depth 1: single pass at base level- (1, 0): "base",- # depth 2: pass 0 lighter, pass 1 at base- (2, 0): "minimal",- (2, 1): "base",- # depth 3: pass 0 lighter, pass 1 at base, pass 2 one above minimal- (3, 0): "minimal",- (3, 1): "base",- (3, 2): "low",- }-- _LEVEL_ORDER = ("minimal", "low", "medium", "high", "max")-- # Char-count thresholds for the query-length reasoning heuristic.- _HEURISTIC_LENGTH_MEDIUM = 120- _HEURISTIC_LENGTH_HIGH = 400-- # Liveness constants. A thread older than timeout × multiplier is treated- # as dead so a hung Honcho call can't block future retries indefinitely.- _STALE_THREAD_MULTIPLIER = 2.0- # Pending result whose fire-turn is older than cadence × multiplier is- # discarded on read so we don't inject context for a stale conversational- # pivot after a gap of trivial-prompt turns.- _STALE_RESULT_MULTIPLIER = 2- # Cap on the empty-streak backoff so a persistently silent backend- # eventually settles on a ceiling instead of unbounded widening.- _BACKOFF_MAX = 8- # Total turn-1 budget shared by session init and base retrieval.- _FIRST_TURN_BASE_TIMEOUT = 3.0- # Independent turn-1 grace for the slower dialectic path.- _FIRST_TURN_DIALECTIC_CAP = 2.0-- def _thread_is_live(self) -> bool:- """Thread-alive guard that treats threads older than the stale- threshold as dead, so a hung Honcho request can't block new fires."""- if not self._prefetch_thread or not self._prefetch_thread.is_alive():- return False- timeout = (self._config.timeout if self._config and self._config.timeout else 8.0)- age = time.monotonic() - self._prefetch_thread_started_at- if age > timeout * self._STALE_THREAD_MULTIPLIER:- logger.debug(- "Honcho prefetch thread age %.1fs exceeds stale threshold "- "%.1fs — treating as dead", age, timeout * self._STALE_THREAD_MULTIPLIER,- )- return False- return True-- def _effective_cadence(self) -> int:- """Cadence plus empty-streak backoff, capped at _BACKOFF_MAX × base."""- if self._dialectic_empty_streak <= 0:- return self._dialectic_cadence- widened = self._dialectic_cadence + self._dialectic_empty_streak- ceiling = self._dialectic_cadence * self._BACKOFF_MAX- return min(widened, ceiling)-- def _note_dialectic_failure(self, exc: BaseException) -> None:- """Widen the empty-streak backoff after a failed dialectic cycle.-- Auth failures are exempt because waiting cannot fix a dead token.- """- from plugins.memory.honcho.session import HonchoAuthError-- if isinstance(exc, HonchoAuthError):- logger.warning(- "Honcho dialectic auth failure (not counted toward cadence backoff): %s",- exc,- )- return- self._dialectic_empty_streak += 1-- def liveness_snapshot(self) -> dict:- """In-process snapshot of dialectic liveness state for diagnostics.-- Returns current turn, last successful dialectic turn, pending-result- fire turn, empty streak, effective cadence, and thread status.- """- thread_age = None- if self._prefetch_thread and self._prefetch_thread.is_alive():- thread_age = time.monotonic() - self._prefetch_thread_started_at- return {- "turn_count": self._turn_count,- "last_dialectic_turn": self._last_dialectic_turn,- "pending_result_fired_at": self._prefetch_result_fired_at,- "empty_streak": self._dialectic_empty_streak,- "effective_cadence": self._effective_cadence(),- "thread_alive": thread_age is not None,- "thread_age_seconds": thread_age,- }-- def _apply_reasoning_heuristic(self, base: str, query: str) -> str:- """Scale `base` up by query length, clamped at reasoning_level_cap.-- Char-count heuristic: +1 at >=120 chars, +2 at >=400.- """- if not self._reasoning_heuristic or not query:- return base- if base not in self._LEVEL_ORDER:- return base- n = len(query)- if n < self._HEURISTIC_LENGTH_MEDIUM:- bump = 0- elif n < self._HEURISTIC_LENGTH_HIGH:- bump = 1- else:- bump = 2- base_idx = self._LEVEL_ORDER.index(base)- cap_idx = self._LEVEL_ORDER.index(self._reasoning_level_cap)- return self._LEVEL_ORDER[min(base_idx + bump, cap_idx)]-- def _resolve_pass_level(self, pass_idx: int, query: str = "") -> str:- """Resolve reasoning level for a given pass index.-- Precedence:- 1. dialecticDepthLevels (explicit per-pass) — wins absolutely- 2. _PROPORTIONAL_LEVELS table (depth>1 lighter-early passes)- 3. Base level = dialecticReasoningLevel, optionally scaled by the- reasoning heuristic when the mapping falls through to 'base'- """- if self._dialectic_depth_levels and pass_idx < len(self._dialectic_depth_levels):- return self._dialectic_depth_levels[pass_idx]-- base = (self._config.dialectic_reasoning_level if self._config else "low")- mapping = self._PROPORTIONAL_LEVELS.get((self._dialectic_depth, pass_idx))- if mapping is None or mapping == "base":- return self._apply_reasoning_heuristic(base, query)- return mapping-- def _build_dialectic_prompt(self, pass_idx: int, prior_results: list[str], is_cold: bool) -> str:- """Build the prompt for a given dialectic pass.-- Pass 0: cold start (general user query) or warm (session-scoped).- Pass 1: self-audit / targeted synthesis against gaps from pass 0.- Pass 2: reconciliation / contradiction check across prior passes.- """- if pass_idx == 0:- if is_cold:- return (- "Who is this person? What are their preferences, goals, "- "and working style? Focus on facts that would help an AI "- "assistant be immediately useful."- )- return (- "Given what's been discussed in this session so far, what "- "context about this user is most relevant to the current "- "conversation? Prioritize active context over biographical facts."- )- elif pass_idx == 1:- prior = prior_results[-1] if prior_results else ""- return (- f"Given this initial assessment:\n\n{prior}\n\n"- "What gaps remain in your understanding that would help "- "going forward? Synthesize what you actually know about "- "the user's current state and immediate needs, grounded "- "in evidence from recent sessions."- )- else:- # pass 2: reconciliation- return (- f"Prior passes produced:\n\n"- f"Pass 1:\n{prior_results[0] if len(prior_results) > 0 else '(empty)'}\n\n"- f"Pass 2:\n{prior_results[1] if len(prior_results) > 1 else '(empty)'}\n\n"- "Do these assessments cohere? Reconcile any contradictions "- "and produce a final, concise synthesis of what matters most "- "for the current conversation."- )-- @staticmethod- def _signal_sufficient(result: str) -> bool:- """Check if a dialectic pass returned enough signal to skip further passes.-- Heuristic: a response longer than 100 chars with some structure- (section headers, bullets, or an ordered list) is considered sufficient.- """- if not result or len(result.strip()) < 100:- return False- # Structured output with sections/bullets is strong signal- if "\n" in result and (- "##" in result- or "•" in result- or re.search(r"^[*-] ", result, re.MULTILINE)- or re.search(r"^\s*\d+\. ", result, re.MULTILINE)- ):- return True- # Long enough even without structure- return len(result.strip()) > 300-- def _run_dialectic_depth(self, query: str, *, use_query_rewrite: bool = True) -> str:- """Execute up to dialecticDepth .chat() calls with conditional bail-out.-- Cold start (no base context): general user-oriented query.- Warm session (base context exists): session-scoped query.- Each pass is conditional — bails early if prior pass returned strong signal.- Returns the best (usually last) result.- """- if not self._manager or not self._session_key:- return ""-- is_cold = not self._base_context_cache- results: list[str] = []- rewritten_query = ""- if use_query_rewrite and self._query_rewrite_enabled and self._query_rewriter:- try:- rewritten_query = self._query_rewriter(query).strip()- except Exception as exc:- logger.debug("Honcho query rewriter failed: %s", exc)-- for i in range(self._dialectic_depth):- # Dependent prompts require a non-empty prior result.- prior_results = [r for r in results if r and r.strip()]- if i == 0:- prompt = rewritten_query or self._build_dialectic_prompt(- 0, prior_results, is_cold- )- else:- # Skip further passes if prior pass delivered strong signal- if prior_results and self._signal_sufficient(prior_results[-1]):- logger.debug("Honcho dialectic depth %d: pass %d skipped, prior signal sufficient",- self._dialectic_depth, i)- break- if not prior_results:- # Retry the independent base prompt after empty passes.- logger.debug("Honcho dialectic depth %d: pass %d has no non-empty prior — "- "falling back to base prompt", self._dialectic_depth, i)- prompt = rewritten_query or self._build_dialectic_prompt(- 0, prior_results, is_cold- )- else:- prompt = self._build_dialectic_prompt(i, prior_results, is_cold)-- level = self._resolve_pass_level(i, query=query)- logger.debug("Honcho dialectic depth %d: pass %d, level=%s, cold=%s",- self._dialectic_depth, i, level, is_cold)-- result = self._manager.dialectic_query(- self._session_key, prompt,- reasoning_level=level,- peer="user",- )- results.append(result or "")-- # Return the last non-empty result (deepest pass that ran)- for r in reversed(results):- if r and r.strip():- return r- return ""-- # Prompts that carry no semantic signal — trivial acknowledgements, greetings,- # slash commands, empty input. Skipping injection here saves tokens and prevents- # stale user-model context from derailing one-word replies. Classification is- # fully delegated to the shared agent/memory_provider.is_trivial_prompt so the- # provider-side classifier and the core prefetch gate can never drift apart.- _TRIVIAL_PROMPT_RE = TRIVIAL_PROMPT_RE-- @classmethod- def _is_trivial_prompt(cls, text: str) -> bool:- """Return True if the prompt is too trivial to warrant context injection."""- return is_trivial_prompt(text)+ # Shared with the core prefetch gate so the two classifiers can never drift apart.+ _is_trivial_prompt = staticmethod(is_trivial_prompt)def on_turn_start(self, turn_number: int, message: str, **kwargs) -> None:"""Track turn count for cadence and injection_frequency logic."""self._turn_count = turn_number+ # ----- Writes -----+@staticmethoddef _chunk_message(content: str, limit: int) -> list[str]:- """Split content into chunks that fit within the Honcho message limit.-- Splits at paragraph boundaries when possible, falling back to- sentence boundaries, then word boundaries. Each continuation- chunk is prefixed with "[continued] " so Honcho's representation- engine can reconstruct the full message.- """+ """Split content to fit the Honcho message limit, cutting at paragraph, then+ sentence, then word boundaries; continuation chunks get a "[continued] " prefix+ so Honcho's representation engine can reconstruct the full message."""if len(content) <= limit:return [content]prefix = "[continued] "- prefix_len = len(prefix)chunks = []remaining = contentfirst = Truewhile remaining:- effective = limit if first else limit - prefix_len+ effective = limit if first else limit - len(prefix)if len(remaining) <= effective:chunks.append(remaining if first else prefix + remaining)breaksegment = remaining[:effective]-- # Try paragraph break, then sentence, then word- cut = segment.rfind("\n\n")- if cut < effective * 0.3:- cut = segment.rfind(". ")- if cut >= 0:- cut += 2 # include the period and space- if cut < effective * 0.3:- cut = segment.rfind(" ")- if cut < effective * 0.3:- cut = effective # hard cut+ # Paragraph, then sentence (keeping ". "), then word boundary; else a hard cut.+ for sep in ("\n\n", ". ", " "):+ cut = segment.rfind(sep)+ if cut >= 0 and sep == ". ":+ cut += 2+ if cut >= effective * 0.3:+ break+ else:+ cut = effectivechunk = remaining[:cut].rstrip()remaining = remaining[cut:].lstrip()- if not first:- chunk = prefix + chunk- chunks.append(chunk)+ chunks.append(chunk if first else prefix + chunk)first = Falsereturn chunks- def _empty_profile_hint(self, peer: str) -> Dict[str, Any]:- """Build a diagnostic hint when honcho_profile returns an empty card.-- A literal "No profile facts available yet." tells the model nothing- about WHY. The model then often surfaces it to the user as a cryptic- error. This hint enumerates the likely causes so the model can- explain the situation (or retry with a different peer).-- Ordered by likelihood for a typical deployment:- 1. Observation is disabled for this peer- 2. Card hasn't accumulated yet (fresh peer, not enough dialectic- cycles — dialectic cadence runs every N turns)- 3. Self-hosted Honcho backend doesn't support peer cards- (honcho-ai server < 3.x)- """- cfg = self._config- reasons: List[str] = []-- if cfg is not None:- if peer == "user":- observe_me = bool(getattr(cfg, "user_observe_me", True))- observe_others = bool(getattr(cfg, "user_observe_others", True))- else:- observe_me = bool(getattr(cfg, "ai_observe_me", True))- observe_others = bool(getattr(cfg, "ai_observe_others", True))- if not (observe_me or observe_others):- reasons.append(- f"observation is disabled for peer '{peer}' "- f"(user_observe_me/ai_observe_me in config)"- )-- cadence = getattr(self, "_dialectic_cadence", 1)- turn = getattr(self, "_turn_count", 0)- if turn < max(2, cadence):- reasons.append(- f"this session has only {turn} turn(s); peer cards accumulate "- f"as the dialectic layer reasons over conversation history "- f"(cadence every {cadence} turn(s))"- )-- if not reasons:- reasons.append(- "peer card has no facts yet — Honcho's dialectic layer builds "- "this over time from observed turns; self-hosted Honcho < 3.x "- "does not support peer cards at all"- )-- return {- "result": "No profile facts available yet.",- "hint": (- "This is not an error. "- + "; ".join(reasons)- + ". Try honcho_reasoning for a synthesized answer, or "- "honcho_search to query raw conversation excerpts."- ),- }-def sync_turn(self, user_content: str, assistant_content: str, *, session_id: str = "") -> None:- """Record the conversation turn in Honcho (non-blocking).-- Messages exceeding the Honcho API limit (default 25k chars) are- split into multiple messages with continuation markers.-- Honors saveMessages: false — the provider then never persists raw- turns to Honcho (read/tools paths stay fully functional).- """- if self._cron_skipped:- return- # ``saveMessages`` is the operator's hard write gate. Previously it- # was parsed into HonchoClientConfig but never enforced here, so a- # cached hybrid provider kept writing even after containment was set.- if self._config and not getattr(self._config, "save_messages", True):+ """Record the conversation turn in Honcho (non-blocking), chunking messages that+ exceed the Honcho API limit. Honors saveMessages: false."""+ if not self._writes_enabled():returnif _is_internal_gateway_turn(user_content):logger.debug("Honcho sync skipped machine-generated gateway turn")return- if self._recall_mode == "tools" and not self._session_ready():- return- if not self._session_ready():- self._start_session_init_background()+ if not self._ready_or_kick_init():returnmsg_limit = self._config.message_max_chars if self._config else 25000clean_user_content = sanitize_context(user_content or "").strip()clean_assistant_content = sanitize_context(assistant_content or "").strip()- # Skip only when the whole turn is empty. An interrupted or tool-only- # turn can legitimately have an empty assistant side; the user's- # message must still be persisted (the manager already drops- # empty-user turns upstream). Empty sides are skipped per-loop below- # so we never write empty-string messages either.+ # Skip only when the whole turn is empty: an interrupted or tool-only turn can have+ # an empty assistant side, and the user's message must still be persisted.if not clean_user_content and not clean_assistant_content:returndef _sync():- try:- session = self._manager.get_or_create(self._session_key)- if clean_user_content:- for chunk in self._chunk_message(clean_user_content, msg_limit):- session.add_message("user", chunk)- if clean_assistant_content:- for chunk in self._chunk_message(clean_assistant_content, msg_limit):- session.add_message("assistant", chunk)- # Route through save() so writeFrequency is honored —- # _flush_session() directly bypassed "session"/N batching- # and flushed every turn regardless of config.- self._manager.save(session)- except Exception as e:- logger.debug("Honcho sync_turn failed: %s", e)+ session = self._manager.get_or_create(self._session_key)+ for role, content in (("user", clean_user_content), ("assistant", clean_assistant_content)):+ for chunk in self._chunk_message(content, msg_limit) if content else ():+ session.add_message(role, chunk)+ # save() (not _flush_session) so writeFrequency batching is honored.+ self._manager.save(session)if self._sync_thread and self._sync_thread.is_alive():self._sync_thread.join(timeout=5.0)- self._sync_thread = spawn_context_thread(_sync, name="honcho-sync")- self._sync_thread.start()+ self._sync_thread = self._spawn_write(_sync, "honcho-sync", "Honcho sync_turn failed: %s")++ @staticmethod+ def _spawn_write(fn: Callable[[], None], name: str, fail_msg: str) -> threading.Thread:+ """Run a Honcho write off-thread; failures are debug-logged, never raised into the turn."""+ def _run():+ try:+ fn()+ except Exception as e:+ logger.debug(fail_msg, e)++ thread = spawn_context_thread(_run, name=name)+ thread.start()+ return threaddef on_memory_write(- self,- action: str,- target: str,- content: str,- metadata: Optional[Dict[str, Any]] = None,+ self, action: str, target: str, content: str, metadata: Optional[Dict[str, Any]] = None,) -> None:- """Mirror built-in user profile writes as Honcho conclusions.-- ``metadata`` is accepted for compatibility with the write-origin- work landed in main (commit 6a957a74); it's not yet threaded into- the Honcho conclusion payload. Left as a follow-up so this PR- stays focused on the 7-PR consolidation and its review follow-ups.- """+ """Mirror built-in user-profile writes as Honcho conclusions (``metadata`` accepted+ for interface compatibility, not yet threaded into the conclusion payload)."""if action != "add" or target != "user" or not content:return- if self._cron_skipped:+ if not self._writes_enabled() or not self._ready_or_kick_init():return- # ``saveMessages`` is the operator's hard write gate; the memory-tool- # mirror is an automatic Honcho mutation path and must respect it too,- # otherwise containment would only cover conversation turns.- if self._config and not getattr(self._config, "save_messages", True):- return- if self._recall_mode == "tools" and not self._session_ready():- return- if not self._session_ready():- self._start_session_init_background()- return-- def _write():- try:- self._manager.create_conclusion(self._session_key, content)- except Exception as e:- logger.debug("Honcho memory mirror failed: %s", e)-- self._memwrite_thread = spawn_context_thread(_write, name="honcho-memwrite")- self._memwrite_thread.start()+ self._memwrite_thread = self._spawn_write(+ lambda: self._manager.create_conclusion(self._session_key, content),+ "honcho-memwrite", "Honcho memory mirror failed: %s",+ )def on_session_end(self, messages: List[Dict[str, Any]]) -> None:"""Flush all pending messages to Honcho on session end."""- if self._cron_skipped:- return- if not getattr(self._config, "save_messages", True):- return- if not self._manager:+ if not self._writes_enabled() or not self._manager:returnif not self._session_initialized and self._init_thread and self._init_thread.is_alive():return- # Wait for pending syncif self._sync_thread and self._sync_thread.is_alive():self._sync_thread.join(timeout=10.0)try:@@ -1517,152 +695,162 @@ class HonchoMemoryProvider(MemoryProvider):except Exception as e:logger.debug("Honcho session-end flush failed: %s", e)- def get_tool_schemas(self) -> List[Dict[str, Any]]:- """Return tool schemas, respecting recall_mode.+ # ----- Tools ------ Context-only mode exposes no Honcho tools.- """- if self._cron_skipped:- return []- if self._recall_mode == "context":+ def get_tool_schemas(self) -> List[Dict[str, Any]]:+ """Tool schemas by recall_mode; context-only mode exposes no Honcho tools."""+ if self._cron_skipped or self._recall_mode == "context":return []return list(ALL_TOOL_SCHEMAS)+ def _empty_profile_hint(self, peer: str) -> Dict[str, Any]:+ """Diagnostic hint for an empty honcho_profile card, so the model can explain WHY+ instead of surfacing a cryptic "no facts" to the user. Likely causes, in order:+ observation disabled for the peer; card not accumulated yet (fresh peer / few+ dialectic cycles); self-hosted Honcho < 3.x without peer-card support."""+ cfg = self._config+ reasons: List[str] = []+ kind = "user" if peer == "user" else "ai"+ if cfg is not None and not (+ getattr(cfg, f"{kind}_observe_me", True) or getattr(cfg, f"{kind}_observe_others", True)+ ):+ reasons.append(f"observation is disabled for peer '{peer}' (user_observe_me/ai_observe_me in config)")+ cadence, turn = self._dialectic_cadence, self._turn_count+ if turn < max(2, cadence):+ reasons.append(+ f"this session has only {turn} turn(s); peer cards accumulate as the dialectic "+ f"layer reasons over conversation history (cadence every {cadence} turn(s))"+ )+ if not reasons:+ reasons.append(+ "peer card has no facts yet — Honcho's dialectic layer builds this over time from "+ "observed turns; self-hosted Honcho < 3.x does not support peer cards at all"+ )+ return {+ "result": "No profile facts available yet.",+ "hint": (+ "This is not an error. " + "; ".join(reasons)+ + ". Try honcho_reasoning for a synthesized answer, or honcho_search to query raw conversation excerpts."+ ),+ }++ def _tool_profile(self, args: dict) -> str:+ peer = args.get("peer", "user")+ card_update = args.get("card")+ if card_update:+ result = self._manager.set_peer_card(self._session_key, card_update, peer=peer)+ if result is None:+ return tool_error("Failed to update peer card.")+ return json.dumps({"result": f"Peer card updated ({len(result)} facts).", "card": result})+ card = self._manager.get_peer_card(self._session_key, peer=peer)+ if not card:+ return json.dumps(self._empty_profile_hint(peer))+ return json.dumps({"result": card})++ def _tool_search(self, args: dict) -> str:+ query = (args.get("query") or "").strip()+ if not query:+ return tool_error("Missing required parameter: query")+ max_tokens = min(int(args.get("max_tokens", 800)), 2000)+ result = self._manager.search_context(+ self._session_key, query, max_tokens=max_tokens, peer=args.get("peer", "user"),+ )+ return json.dumps({"result": result or "No relevant context found."})++ def _tool_reasoning(self, args: dict) -> str:+ from plugins.memory.honcho.session import HonchoAuthError++ query = (args.get("query") or "").strip()+ if not query:+ return tool_error("Missing required parameter: query")+ try:+ result = self._manager.dialectic_query(+ self._session_key, query,+ reasoning_level=args.get("reasoning_level"),+ peer=args.get("peer", "user"),+ # Explicit reasoning bypasses the automatic-injection cap, and surfaces+ # timeouts/server errors as errors rather than an indistinguishable "no result".+ apply_injection_cap=False,+ raise_errors=True,+ )+ except HonchoAuthError:+ raise # rendered by handle_tool_call's auth-specific handler+ except Exception as e:+ logger.warning("honcho_reasoning failed: %s", e)+ return tool_error(+ f"Honcho reasoning query failed ({e}). This is a backend error, not an empty result — "+ "the peer may still have relevant context. Slow dialectic calls at higher reasoning levels "+ "can exceed the configured timeout; consider a lower reasoning_level or raising the "+ "'timeout' value in honcho.json."+ )+ # Auto-injection respects the cadence gap after an explicit call.+ self._last_dialectic_turn = self._turn_count+ return json.dumps({"result": result or "No result from Honcho."})++ def _tool_context(self, args: dict) -> str:+ ctx = self._manager.get_session_context(self._session_key, peer=args.get("peer", "user"))+ if not ctx:+ return json.dumps({"result": "No context available yet."})+ parts = [+ f"## {header}\n{ctx[key]}"+ for key, header in (("summary", "Summary"), ("representation", "Representation"), ("card", "Card"))+ if ctx.get(key)+ ]+ if ctx.get("recent_messages"):+ msg_str = "\n".join(f" [{m['role']}] {m['content'][:200]}" for m in ctx["recent_messages"][-5:])+ parts.append(f"## Recent messages\n{msg_str}")+ return json.dumps({"result": "\n\n".join(parts) or "No context available."})++ def _tool_conclude(self, args: dict) -> str:+ delete_id = (args.get("delete_id") or "").strip()+ conclusion = args.get("conclusion", "").strip()+ list_mode = bool(args.get("list"))+ peer = args.get("peer", "user")+ if sum([bool(delete_id), bool(conclusion), list_mode]) != 1:+ return tool_error("Exactly one of conclusion, delete_id, or list must be provided.")+ query = (args.get("query") or "").strip()+ if query and not list_mode:+ return tool_error("query is only valid when list is true.")++ if list_mode:+ conclusions = self._manager.list_conclusions(self._session_key, query=query or None, peer=peer)+ return json.dumps({"conclusions": conclusions})+ if delete_id:+ if self._manager.delete_conclusion(self._session_key, delete_id, peer=peer):+ return json.dumps({"result": f"Conclusion {delete_id} deleted."})+ return tool_error(f"Failed to delete conclusion {delete_id}.")+ if self._manager.create_conclusion(self._session_key, conclusion, peer=peer):+ return json.dumps({"result": f"Conclusion saved for {peer}: {conclusion}"})+ return tool_error("Failed to save conclusion.")++ _TOOL_HANDLERS = {+ "honcho_profile": _tool_profile,+ "honcho_search": _tool_search,+ "honcho_reasoning": _tool_reasoning,+ "honcho_context": _tool_context,+ "honcho_conclude": _tool_conclude,+ }+def handle_tool_call(self, tool_name: str, args: dict, **kwargs) -> str:- """Handle a Honcho tool call, with lazy session init for tools-only mode."""+ """Dispatch a Honcho tool call, lazily initializing the session in tools-only mode."""from plugins.memory.honcho.session import HonchoAuthErrorif self._cron_skipped:return tool_error("Honcho is not active (cron context).")-if not self._session_initialized:if self._init_thread and self._init_thread.is_alive():return tool_error("Honcho session is still initializing; try again shortly.")if not self._ensure_session():if self._init_auth_failure:- return tool_error(- f"Honcho memory authentication failed: {self._init_auth_failure}"- )+ return tool_error(f"Honcho memory authentication failed: {self._init_auth_failure}")return tool_error("Honcho session could not be initialized.")-if not self._manager or not self._session_key:return tool_error("Honcho is not active for this session.")-- try:- if tool_name == "honcho_profile":- peer = args.get("peer", "user")- card_update = args.get("card")- if card_update:- result = self._manager.set_peer_card(self._session_key, card_update, peer=peer)- if result is None:- return tool_error("Failed to update peer card.")- return json.dumps({"result": f"Peer card updated ({len(result)} facts).", "card": result})- card = self._manager.get_peer_card(self._session_key, peer=peer)- if not card:- return json.dumps(self._empty_profile_hint(peer))- return json.dumps({"result": card})-- elif tool_name == "honcho_search":- query = (args.get("query") or "").strip()- if not query:- return tool_error("Missing required parameter: query")- max_tokens = min(int(args.get("max_tokens", 800)), 2000)- peer = args.get("peer", "user")- result = self._manager.search_context(- self._session_key, query, max_tokens=max_tokens, peer=peer- )- if not result:- return json.dumps({"result": "No relevant context found."})- return json.dumps({"result": result})-- elif tool_name == "honcho_reasoning":- query = (args.get("query") or "").strip()- if not query:- return tool_error("Missing required parameter: query")- peer = args.get("peer", "user")- reasoning_level = args.get("reasoning_level")- try:- result = self._manager.dialectic_query(- self._session_key, query,- reasoning_level=reasoning_level,- peer=peer,- # Explicit reasoning bypasses the automatic-injection cap.- apply_injection_cap=False,- # Explicit tool call: surface timeouts/server errors as- # errors instead of collapsing them into "no result",- # which is indistinguishable from an empty answer.- raise_errors=True,- )- except HonchoAuthError:- # Let the outer dispatch's auth-specific handler render this.- raise- except Exception as e:- logger.warning("honcho_reasoning failed: %s", e)- return tool_error(- f"Honcho reasoning query failed ({e}). This is a backend "- "error, not an empty result — the peer may still have "- "relevant context. Slow dialectic calls at higher "- "reasoning levels can exceed the configured timeout; "- "consider a lower reasoning_level or raising the "- "'timeout' value in honcho.json."- )- # Update cadence tracker so auto-injection respects the gap after an explicit call- self._last_dialectic_turn = self._turn_count- return json.dumps({"result": result or "No result from Honcho."})-- elif tool_name == "honcho_context":- peer = args.get("peer", "user")- ctx = self._manager.get_session_context(self._session_key, peer=peer)- if not ctx:- return json.dumps({"result": "No context available yet."})- parts = []- if ctx.get("summary"):- parts.append(f"## Summary\n{ctx['summary']}")- if ctx.get("representation"):- parts.append(f"## Representation\n{ctx['representation']}")- if ctx.get("card"):- parts.append(f"## Card\n{ctx['card']}")- if ctx.get("recent_messages"):- msgs = ctx["recent_messages"]- msg_str = "\n".join(- f" [{m['role']}] {m['content'][:200]}"- for m in msgs[-5:] # last 5 for brevity- )- parts.append(f"## Recent messages\n{msg_str}")- return json.dumps({"result": "\n\n".join(parts) or "No context available."})-- elif tool_name == "honcho_conclude":- delete_id = (args.get("delete_id") or "").strip()- conclusion = args.get("conclusion", "").strip()- list_mode = bool(args.get("list"))- peer = args.get("peer", "user")-- has_delete_id = bool(delete_id)- has_conclusion = bool(conclusion)- if sum([has_delete_id, has_conclusion, list_mode]) != 1:- return tool_error("Exactly one of conclusion, delete_id, or list must be provided.")-- query = (args.get("query") or "").strip()- if query and not list_mode:- return tool_error("query is only valid when list is true.")-- if list_mode:- conclusions = self._manager.list_conclusions(- self._session_key, query=query or None, peer=peer- )- return json.dumps({"conclusions": conclusions})- if has_delete_id:- ok = self._manager.delete_conclusion(self._session_key, delete_id, peer=peer)- if ok:- return json.dumps({"result": f"Conclusion {delete_id} deleted."})- return tool_error(f"Failed to delete conclusion {delete_id}.")- ok = self._manager.create_conclusion(self._session_key, conclusion, peer=peer)- if ok:- return json.dumps({"result": f"Conclusion saved for {peer}: {conclusion}"})- return tool_error("Failed to save conclusion.")-+ handler = self._TOOL_HANDLERS.get(tool_name)+ if handler is None:return tool_error(f"Unknown tool: {tool_name}")-+ try:+ return handler(self, args)except HonchoAuthError as e:# Never report an auth failure as an empty result; the model would read it as "no memory".logger.error("Honcho tool %s failed: authentication rejected", tool_name)@@ -1672,36 +860,22 @@ class HonchoMemoryProvider(MemoryProvider):return tool_error(f"Honcho {tool_name} failed: {e}")def shutdown(self) -> None:- for t in (self._prefetch_thread, self._sync_thread, getattr(self, "_memwrite_thread", None)):+ for t in (self._prefetch_thread, self._sync_thread, self._memwrite_thread):if t and t.is_alive():t.join(timeout=5.0)manager = self._manager- if manager and self._init_thread and self._init_thread.is_alive() and not self._session_initialized:- manager = None- # Honors saveMessages: false — skip persistence, but thread cleanup- # still runs: the session manager's async-writer thread must be- # joined either way so daemon threads aren't left blocked in httpx- # I/O during interpreter finalization.- if not getattr(self._config, "save_messages", True):- if manager:- try:- manager.stop_async_writer()- except Exception:- pass+ if not manager or (self._init_thread and self._init_thread.is_alive() and not self._session_initialized):return- if manager:- try:- # manager.shutdown() = flush_all() + join the async-writer- # thread. Previously only flush_all() ran here, leaving the- # writer thread alive at exit.- manager.shutdown()- except Exception:- pass-+ try:+ # saveMessages: false skips persistence, but the async-writer thread must still+ # be joined so daemon threads aren't left blocked in httpx I/O at interpreter exit.+ if getattr(self._config, "save_messages", True):+ manager.shutdown() # flush_all() + join the writer+ else:+ manager.stop_async_writer()+ except Exception:+ pass-# ----------------------------------------------------------------------------# Plugin entry point-# ---------------------------------------------------------------------------def register(ctx) -> None:"""Register Honcho as a memory provider plugin."""diff --git a/plugins/memory/honcho/cli.py b/plugins/memory/honcho/cli.pyindex 74822e3722c..4303fe84d59 100644--- a/plugins/memory/honcho/cli.py+++ b/plugins/memory/honcho/cli.py@@ -14,375 +14,348 @@ from hermes_constants import get_hermes_homefrom plugins.memory.honcho.client import _host_block, profile_host_key, resolve_active_host, resolve_config_path, HOSTfrom hermes_cli.config import cfg_get+RULE = "─" * 40+REASONING_LEVELS = ("minimal", "low", "medium", "high", "max")+_RETRY_HINT = " Re-run 'hermes honcho setup' to retry, or choose an API key instead.\n"++# Settings a new profile host block inherits from the default block.+_INHERITED_KEYS = (+ "recallMode", "writeFrequency", "sessionStrategy", "contextTokens",+ "dialecticReasoningLevel", "dialecticDynamic", "dialecticMaxChars",+ "messageMaxChars", "dialecticMaxInputChars", "saveMessages", "observation",+)+# clone_honcho_for_profile also carries the operator's runtime-to-peer routing intent.+_CLONE_KEYS = _INHERITED_KEYS[:3] + ("sessionPeerPrefix",) + _INHERITED_KEYS[3:] + (+ "pinUserPeer", "userPeerAliases", "runtimePeerPrefix",+)+_IDENTITY_MAPPING_KEYS = ("pinPeerName", "pinUserPeer", "userPeerAliases", "runtimePeerPrefix")+_MODES = {+ "hybrid": "auto-injected context + Honcho tools available (default)",+ "context": "auto-injected context only, Honcho tools hidden",+ "tools": "Honcho tools only, no auto-injected context",+}+_STRATEGIES = {+ "per-session": "each run starts clean, Honcho injects context automatically",+ "per-directory": "reuses session per dir, prior context auto-injected each run",+ "per-repo": "one session per git repository",+ "global": "single session across all directories",+}+++# ── config access ──────────────────────────────────────────────────────────-def clone_honcho_for_profile(profile_name: str) -> bool:- """Auto-clone Honcho config for a new profile from the default host block.+_profile_override: str | None = None- Called during profile creation. If Honcho is configured on the default- host, creates a new host block for the profile with inherited settings- and auto-derived workspace/aiPeer.- Returns True if a host block was created, False if Honcho isn't configured.- """- cfg = _read_config()- if not cfg:- return False-- hosts = cfg.get("hosts", {})- default_block = hosts.get(HOST, {})+def _host_key() -> str:+ """Return the active Honcho host key, derived from the current Hermes profile."""+ if _profile_override:+ if _profile_override in {"default", "custom"}:+ return HOST+ return profile_host_key(_profile_override)+ return resolve_active_host()- # No default host block and no root-level API key = Honcho not configured- has_key = bool(cfg.get("apiKey") or os.environ.get("HONCHO_API_KEY"))- if not default_block and not has_key:- return False- new_host = profile_host_key(profile_name)- if new_host in hosts:- return False # already exists-- # Clone settings from default block, override identity fields.- # Identity-mapping keys (pinUserPeer, userPeerAliases, runtimePeerPrefix)- # carry the operator's runtime-to-peer routing intent from #27371.- new_block = {}- for key in ("recallMode", "writeFrequency", "sessionStrategy",- "sessionPeerPrefix", "contextTokens", "dialecticReasoningLevel",- "dialecticDynamic", "dialecticMaxChars", "messageMaxChars",- "dialecticMaxInputChars", "saveMessages", "observation",- "pinUserPeer", "userPeerAliases", "runtimePeerPrefix"):- val = default_block.get(key)- if val is not None:- new_block[key] = val- # Carry a legacy default-block pinPeerName forward under the canonical key.- if "pinUserPeer" not in new_block and default_block.get("pinPeerName") is not None:- new_block["pinUserPeer"] = default_block["pinPeerName"]-- # Inherit peer name from default- peer_name = default_block.get("peerName") or cfg.get("peerName")- if peer_name:- new_block["peerName"] = peer_name+def _config_path() -> Path:+ """Return the active Honcho config path for reading (instance-local or global)."""+ return resolve_config_path()- # AI peer is profile-specific; workspace is shared so all profiles- # see the same user context, sessions, and project history.- # Use the bare profile name as the peer identity (not the host key)- # because Honcho's peer ID pattern is ^[a-zA-Z0-9_-]+$ (no dots).- new_block["aiPeer"] = profile_name- new_block["workspace"] = default_block.get("workspace") or cfg.get("workspace") or HOST- new_block["enabled"] = default_block.get("enabled", True)- cfg.setdefault("hosts", {})[new_host] = new_block- _write_config(cfg)+def _local_config_path() -> Path:+ """Instance-local write path ($HERMES_HOME/honcho.json). The global+ ~/.honcho/config.json is only a read fallback for cross-app interop."""+ return get_hermes_home() / "honcho.json"- # Eagerly create the peer in Honcho so it exists before first message- _ensure_peer_exists(new_host)- return True+def _read_config() -> dict:+ path = _config_path()+ if path.exists():+ try:+ return json.loads(path.read_text(encoding="utf-8"))+ except Exception:+ pass+ return {}-def _ensure_peer_exists(host_key: str | None = None) -> bool:- """Create the AI peer in Honcho if it doesn't already exist.- Idempotent -- safe to call multiple times. Returns True if the peer- was created or already exists, False on failure.- """- try:- from plugins.memory.honcho.client import HonchoClientConfig, get_honcho_client- hcfg = HonchoClientConfig.from_global_config(host=host_key)- if not hcfg.enabled or not (hcfg.api_key or hcfg.base_url):- return False- client = get_honcho_client(hcfg)- # peer() is idempotent -- creates if missing, returns if exists- client.peer(hcfg.ai_peer)- if hcfg.peer_name:- client.peer(hcfg.peer_name)- return True- except Exception:- return False+def _write_config(cfg: dict, path: Path | None = None) -> None:+ path = path or _local_config_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ from utils import atomic_json_write+ atomic_json_write(path, cfg, mode=0o600)-def cmd_enable(args) -> None:- """Enable Honcho for the active profile."""- cfg = _read_config()- host = _host_key()- label = f"[{host}] " if host != "hermes" else ""- block = cfg.setdefault("hosts", {}).setdefault(host, {})+def _label(host: str) -> str:+ return f"[{host}] " if host != "hermes" else ""- if block.get("enabled") is True:- print(f" {label}Honcho is already enabled.\n")- return- block["enabled"] = True+def _mask(key: str) -> str:+ return f"...{key[-8:]}" if len(key) > 8 else ("set" if key else "not set")- # If this is a new profile host block with no settings, clone from default- if not block.get("aiPeer"):- default_block = cfg_get(cfg, "hosts", HOST, default={})- for key in ("recallMode", "writeFrequency", "sessionStrategy",- "contextTokens", "dialecticReasoningLevel", "dialecticDynamic",- "dialecticMaxChars", "messageMaxChars", "dialecticMaxInputChars",- "saveMessages", "observation"):- val = default_block.get(key)- if val is not None and key not in block:- block[key] = val- peer_name = default_block.get("peerName") or cfg.get("peerName")- if peer_name and "peerName" not in block:- block["peerName"] = peer_name- # Use bare profile name as AI peer, not the host key- ai_peer = host.split(".", 1)[1] if "." in host else host- block.setdefault("aiPeer", ai_peer)- block.setdefault("workspace", default_block.get("workspace") or cfg.get("workspace") or HOST)- _write_config(cfg)- print(f" {label}Honcho enabled.")+def _pref(block: dict, cfg: dict, key: str, default=None):+ """Host-block value, falling back to the root-level value (or ``default``)."""+ return block.get(key) or cfg.get(key, default)- # Create peer eagerly- if _ensure_peer_exists(host):- print(f" {label}Peer '{block.get('aiPeer', host)}' ready.")- else:- print(f" {label}Peer creation deferred (no connection).")- print(f" Saved to {_config_path()}\n")+def _active_block(cfg: dict) -> dict:+ return (cfg.get("hosts") or {}).get(_host_key(), {})-def cmd_disable(args) -> None:- """Disable Honcho for the active profile."""- cfg = _read_config()+def _set_field(cfg: dict, key: str, value, echo: str) -> None:+ """Write one key on the active host block and echo the change."""host = _host_key()- label = f"[{host}] " if host != "hermes" else ""- block = cfg_get(cfg, "hosts", host, default={})+ cfg.setdefault("hosts", {}).setdefault(host, {})[key] = value+ print(f" {_label(host)}{echo}")- if not block or block.get("enabled") is False:- print(f" {label}Honcho is already disabled.\n")- return- block["enabled"] = False+def _save(cfg: dict) -> None:_write_config(cfg)- print(f" {label}Honcho disabled.")print(f" Saved to {_config_path()}\n")-def cmd_sync(args) -> None:- """Sync Honcho config to all existing profiles.+def _default_block_and_key(cfg: dict) -> tuple[dict, bool]:+ """(default host block, whether an API key is configured at root or env)."""+ default_block = cfg_get(cfg, "hosts", HOST, default={})+ has_key = bool(cfg.get("apiKey") or os.environ.get("HONCHO_API_KEY"))+ return default_block, has_key+- Scans all Hermes profiles and creates host blocks for any that don't- have one yet. Inherits settings from the default host block.- """+def _resolve_api_key(cfg: dict) -> str:+ """Resolve API key with host -> root -> env fallback. A self-hosted ``baseUrl``+ without a key yields ``"local"`` so credential guards accept it: the URL is+ scheme-validated (http/https) so ``baseUrl: true`` can't pass, while schemeless+ host:port shapes (legacy ``localhost:8000``) still pass — the SDK rejects them."""+ host_key = _host_block(cfg, _host_key()).get("apiKey")+ key = host_key or cfg.get("apiKey", "") or os.environ.get("HONCHO_API_KEY", "")+ if key:+ return key+ base_url = (cfg.get("baseUrl") or cfg.get("base_url") or os.environ.get("HONCHO_BASE_URL", "") or "").strip()+ if not base_url:+ return key+ from urllib.parse import urlparsetry:- from hermes_cli.profiles import list_profiles- profiles = list_profiles()- except Exception as e:- print(f" Could not list profiles: {e}\n")- return+ parsed = urlparse(base_url)+ except (TypeError, ValueError):+ parsed = None+ if parsed and parsed.scheme in {"http", "https"} and parsed.netloc:+ return "local"+ lowered = base_url.lower()+ if lowered not in {"true", "false", "none", "null"} and any(c in base_url for c in ".:") and not base_url.isdigit():+ return "local"+ return key+++def _prompt(label: str, default: str | None = None, secret: bool = False) -> str:+ suffix = f" [{default}]" if default else ""+ sys.stdout.write(f" {label}{suffix}: ")+ sys.stdout.flush()+ if secret and sys.stdin.isatty():+ from hermes_cli.secret_prompt import masked_secret_prompt+ val = masked_secret_prompt("")+ else: # non-TTY (piped input, test runners) reads plaintext+ val = sys.stdin.readline().strip()+ return val or (default or "")+++def _yes(answer: str) -> bool:+ return answer.strip().lower() in {"y", "yes"}+++# ── Honcho connection ──────────────────────────────────────────────────────++def _connect(host: str | None, *, reset: bool = False):+ """(hcfg, client) for ``host``; imports are lazy so tests can patch client.*."""+ from plugins.memory.honcho.client import HonchoClientConfig, get_honcho_client, reset_honcho_client+ if reset:+ reset_honcho_client()+ hcfg = HonchoClientConfig.from_global_config(host=host)+ return hcfg, get_honcho_client(hcfg)+++def _session_manager(hcfg, client):+ """(manager, session_key) with the session ensured (get_or_create is idempotent)."""+ from plugins.memory.honcho.session import HonchoSessionManager+ mgr = HonchoSessionManager(honcho=client, config=hcfg)+ session_key = hcfg.resolve_session_name()+ mgr.get_or_create(session_key)+ return mgr, session_key+++def _ensure_peer_exists(host_key: str | None = None) -> bool:+ """Create the AI (and user) peer in Honcho if missing. Idempotent; False on failure."""+ try:+ from plugins.memory.honcho.client import HonchoClientConfig, get_honcho_client+ hcfg = HonchoClientConfig.from_global_config(host=host_key)+ if not hcfg.enabled or not (hcfg.api_key or hcfg.base_url):+ return False+ client = get_honcho_client(hcfg)+ client.peer(hcfg.ai_peer)+ if hcfg.peer_name:+ client.peer(hcfg.peer_name)+ return True+ except Exception:+ return False++# ── profile sync ───────────────────────────────────────────────────────────++def _inherit_defaults(block: dict, default_block: dict, cfg: dict, keys: tuple[str, ...]) -> None:+ """Copy ``keys`` (and peerName) from the default host block into ``block`` where unset."""+ for key in keys:+ val = default_block.get(key)+ if val is not None and key not in block:+ block[key] = val+ peer_name = _pref(default_block, cfg, "peerName")+ if peer_name and "peerName" not in block:+ block["peerName"] = peer_name+++def clone_honcho_for_profile(profile_name: str) -> bool:+ """Create a host block for a new profile, cloned from the default host block+ (called during profile creation). False if Honcho isn't configured or the block exists."""cfg = _read_config()if not cfg:- print(" No Honcho config found. Run 'hermes honcho setup' first.\n")- return-+ return Falsehosts = cfg.get("hosts", {})- default_block = hosts.get(HOST, {})- has_key = bool(cfg.get("apiKey") or os.environ.get("HONCHO_API_KEY"))-+ default_block, has_key = _default_block_and_key(cfg)if not default_block and not has_key:- print(" Honcho not configured on default profile. Run 'hermes honcho setup' first.\n")- return-- created = 0- skipped = 0- for p in profiles:- if p.name == "default":- continue- if clone_honcho_for_profile(p.name):- print(f" + {p.name} -> {profile_host_key(p.name)}")- created += 1- else:- skipped += 1+ return False+ new_host = profile_host_key(profile_name)+ if new_host in hosts:+ return False- if created:- print(f"\n {created} profile(s) synced.")- else:- print(" All profiles already have Honcho config.")- if skipped:- print(f" {skipped} profile(s) already configured (skipped).")- print()+ new_block: dict = {}+ _inherit_defaults(new_block, default_block, cfg, _CLONE_KEYS)+ # Carry a legacy default-block pinPeerName forward under the canonical key.+ if "pinUserPeer" not in new_block and default_block.get("pinPeerName") is not None:+ new_block["pinUserPeer"] = default_block["pinPeerName"]+ # AI peer is profile-specific (bare profile name: Honcho peer IDs allow no+ # dots); workspace is shared so all profiles see the same context.+ new_block["aiPeer"] = profile_name+ new_block["workspace"] = _pref(default_block, cfg, "workspace") or HOST+ new_block["enabled"] = default_block.get("enabled", True)+ cfg.setdefault("hosts", {})[new_host] = new_block+ _write_config(cfg)+ _ensure_peer_exists(new_host) # eager so the peer exists before first message+ return True-def sync_honcho_profiles_quiet() -> int:- """Sync Honcho host blocks for all profiles. Returns count of newly created blocks.- Called from `hermes update` -- no output, no exceptions.- """+def _sync_profiles(verbose: bool) -> int:+ """Clone host blocks for profiles lacking one; returns the count created."""+ say = print if verbose else (lambda *a: None)try:from hermes_cli.profiles import list_profilesprofiles = list_profiles()- except Exception:+ except Exception as e:+ say(f" Could not list profiles: {e}\n")return 0-cfg = _read_config()if not cfg:+ say(" No Honcho config found. Run 'hermes honcho setup' first.\n")return 0-- default_block = cfg_get(cfg, "hosts", HOST, default={})- has_key = bool(cfg.get("apiKey") or os.environ.get("HONCHO_API_KEY"))+ default_block, has_key = _default_block_and_key(cfg)if not default_block and not has_key:+ say(" Honcho not configured on default profile. Run 'hermes honcho setup' first.\n")return 0- created = 0+ created = skipped = 0for p in profiles:if p.name == "default":continueif clone_honcho_for_profile(p.name):+ say(f" + {p.name} -> {profile_host_key(p.name)}")created += 1+ else:+ skipped += 1+ say(f"\n {created} profile(s) synced." if created else " All profiles already have Honcho config.")+ if skipped:+ say(f" {skipped} profile(s) already configured (skipped).")+ say()return created-_profile_override: str | None = None---def _host_key() -> str:- """Return the active Honcho host key, derived from the current Hermes profile."""- if _profile_override:- if _profile_override in {"default", "custom"}:- return HOST- return profile_host_key(_profile_override)- return resolve_active_host()---def _config_path() -> Path:- """Return the active Honcho config path for reading (instance-local or global)."""- return resolve_config_path()---def _local_config_path() -> Path:- """Return the instance-local Honcho config path for writing.-- Always returns $HERMES_HOME/honcho.json so each profile/instance gets- its own config file. The global ~/.honcho/config.json is only used as- a read fallback (via resolve_config_path) for cross-app interop.- """- return get_hermes_home() / "honcho.json"-+def cmd_sync(args) -> None:+ """Sync Honcho config to all existing profiles (inherits from the default block)."""+ _sync_profiles(verbose=True)-def _read_config() -> dict:- path = _config_path()- if path.exists():- try:- return json.loads(path.read_text(encoding="utf-8"))- except Exception:- pass- return {}+def sync_honcho_profiles_quiet() -> int:+ """Sync host blocks for all profiles from `hermes update`; no output, no exceptions."""+ return _sync_profiles(verbose=False)-def _write_config(cfg: dict, path: Path | None = None) -> None:- path = path or _local_config_path()- path.parent.mkdir(parents=True, exist_ok=True)- from utils import atomic_json_write- atomic_json_write(path, cfg, mode=0o600)+def cmd_enable(args) -> None:+ """Enable Honcho for the active profile."""+ cfg = _read_config()+ host = _host_key()+ label = _label(host)+ block = cfg.setdefault("hosts", {}).setdefault(host, {})+ if block.get("enabled") is True:+ print(f" {label}Honcho is already enabled.\n")+ return+ block["enabled"] = True-def _resolve_api_key(cfg: dict) -> str:- """Resolve API key with host -> root -> env fallback.-- For self-hosted instances configured with ``baseUrl`` instead of an API- key, returns ``"local"`` so that credential guards throughout the CLI- don't reject a valid configuration. The ``baseUrl`` is scheme-validated- (http/https only) so that a typo like ``baseUrl: true`` can't silently- pass the guard. Schemeless strings that look like host:port (legacy- config shapes, e.g. ``localhost:8000``) still pass — the Honcho SDK- will reject them itself with a clearer error than ours.- """- host_key = _host_block(cfg, _host_key()).get("apiKey")- key = host_key or cfg.get("apiKey", "") or os.environ.get("HONCHO_API_KEY", "")- if not key:- base_url = cfg.get("baseUrl") or cfg.get("base_url") or os.environ.get("HONCHO_BASE_URL", "")- base_url = (base_url or "").strip()- if base_url:- from urllib.parse import urlparse- try:- parsed = urlparse(base_url)- except (TypeError, ValueError):- parsed = None- if parsed and parsed.scheme in {"http", "https"} and parsed.netloc:- return "local"- # Schemeless but looks like a host (contains '.' or ':' and isn't- # a boolean literal): let it through so legacy configs don't- # regress into "no API key configured" when they previously worked.- lowered = base_url.lower()- if lowered not in {"true", "false", "none", "null"} and any(- c in base_url for c in ".:"- ) and not base_url.isdigit():- return "local"- return key+ if not block.get("aiPeer"): # fresh profile block: clone settings from default+ default_block = cfg_get(cfg, "hosts", HOST, default={})+ _inherit_defaults(block, default_block, cfg, _INHERITED_KEYS)+ block.setdefault("aiPeer", host.split(".", 1)[1] if "." in host else host)+ block.setdefault("workspace", _pref(default_block, cfg, "workspace") or HOST)+ _write_config(cfg)+ print(f" {label}Honcho enabled.")+ peer_state = f"Peer '{block.get('aiPeer', host)}' ready." if _ensure_peer_exists(host) else "Peer creation deferred (no connection)."+ print(f" {label}{peer_state}\n Saved to {_config_path()}\n")-_IDENTITY_MAPPING_KEYS = (- "pinPeerName",- "pinUserPeer",- "userPeerAliases",- "runtimePeerPrefix",-)+def cmd_disable(args) -> None:+ """Disable Honcho for the active profile."""+ cfg = _read_config()+ host = _host_key()+ block = cfg_get(cfg, "hosts", host, default={})+ if not block or block.get("enabled") is False:+ print(f" {_label(host)}Honcho is already disabled.\n")+ return+ block["enabled"] = False+ print(f" {_label(host)}Honcho disabled.")+ _save(cfg)-def _resolve_effective_identity_mapping(- cfg: dict, hermes_host: dict-) -> tuple[bool, dict, str, bool, bool]:- """Resolve the effective identity-mapping state for the active host.- Matches the precedence used by ``HonchoClientConfig.from_global_config``- so the wizard reads the same shape the gateway will actually run with.- Without this, root-level overrides and ``pinUserPeer`` (which wins over- ``pinPeerName`` at the same level) are invisible to detection, letting- setup mis-classify the current shape and silently change effective- routing on the next save.+# ── identity mapping (setup wizard) ────────────────────────────────────────- Returns ``(pin, aliases, prefix, aliases_from_root, prefix_from_root)``.- The ``*_from_root`` flags let the write step skip touching host keys- whose value is actually inherited.- """+def _resolve_effective_identity_mapping(cfg: dict, hermes_host: dict) -> tuple[bool, dict, str, bool, bool]:+ """``(pin, aliases, prefix, aliases_from_root, prefix_from_root)`` for the active+ host, mirroring ``HonchoClientConfig.from_global_config`` precedence (root-level+ overrides; ``pinUserPeer`` beats ``pinPeerName``) so setup classifies the shape+ the gateway actually runs with. ``*_from_root`` lets writes skip inherited values."""pin = False- for val in (- hermes_host.get("pinUserPeer"),- hermes_host.get("pinPeerName"),- cfg.get("pinUserPeer"),- cfg.get("pinPeerName"),- ):+ for val in (hermes_host.get("pinUserPeer"), hermes_host.get("pinPeerName"),+ cfg.get("pinUserPeer"), cfg.get("pinPeerName")):if val is not None:pin = bool(val)break- if "userPeerAliases" in hermes_host:- aliases_src = hermes_host.get("userPeerAliases")- aliases_from_root = False- else:- aliases_src = cfg.get("userPeerAliases")- aliases_from_root = aliases_src is not None- aliases = aliases_src if isinstance(aliases_src, dict) else {}-- if "runtimePeerPrefix" in hermes_host:- prefix_src = hermes_host.get("runtimePeerPrefix")- prefix_from_root = False- else:- prefix_src = cfg.get("runtimePeerPrefix")- prefix_from_root = prefix_src is not None- prefix = str(prefix_src or "")+ def _inherit(key):+ if key in hermes_host:+ return hermes_host.get(key), False+ val = cfg.get(key)+ return val, val is not None- return pin, aliases, prefix, aliases_from_root, prefix_from_root+ aliases_src, aliases_from_root = _inherit("userPeerAliases")+ prefix_src, prefix_from_root = _inherit("runtimePeerPrefix")+ aliases = aliases_src if isinstance(aliases_src, dict) else {}+ return pin, aliases, str(prefix_src or ""), aliases_from_root, prefix_from_rootdef _scrub_identity_mapping(hermes_host: dict) -> None:- """Drop every peer-mapping key from the host block.-- Called before the wizard writes a chosen shape so a stale alias, prefix,- or pin from an earlier run can't bleed into the new mapping.- """+ """Drop every peer-mapping key so a stale alias/prefix/pin can't bleed into the new shape."""for key in _IDENTITY_MAPPING_KEYS:hermes_host.pop(key, None)def _migrate_pin_key(block: dict) -> bool:- """Rewrite a legacy ``pinPeerName`` to canonical ``pinUserPeer`` in place.-- ``pinUserPeer`` wins over ``pinPeerName`` in the resolver, so setup writes- only the canonical form and migrates on touch to stop configs carrying- both. Returns True if the block changed.- """+ """Rewrite legacy ``pinPeerName`` to canonical ``pinUserPeer`` in place (the+ resolver prefers the canonical key). Returns True if the block changed."""if "pinPeerName" not in block:return Falselegacy = block.pop("pinPeerName")@@ -392,13 +365,8 @@ def _migrate_pin_key(block: dict) -> bool:def _gateway_platforms() -> list[str] | None:- """Connected gateway platforms, or None if undetectable.-- Identity mapping only affects gateway runtime users, so setup gates the- whole step on this. Best-effort and dependency-free: the memory plugin- must not hard-depend on the gateway package, so the import is lazy and- guarded (matching the idiom hermes_cli already uses for gateway refs).- """+ """Connected gateway platforms, or None if undetectable. Lazy + guarded:+ the memory plugin must not hard-depend on the gateway package."""try:from gateway.config import load_gateway_configreturn [p.value for p in load_gateway_config().get_connected_platforms()]@@ -407,11 +375,10 @@ def _gateway_platforms() -> list[str] | None:def _collect_operator_aliases(existing: dict, peer_target: str) -> dict:- """Prompt for the operator's per-platform runtime IDs, aliasing each to- ``peer_target``. Existing entries are preserved."""+ """Prompt for the operator's per-platform runtime IDs, aliasing each to ``peer_target``."""aliases = dict(existing)- print(f"\n Add runtime IDs that should alias to peer '{peer_target}'.")- print(" Leave blank to skip a platform. Existing aliases are preserved.")+ print(f"\n Add runtime IDs that should alias to peer '{peer_target}'.\n"+ " Leave blank to skip a platform. Existing aliases are preserved.")for platform_label, alias_hint in (("Telegram UID", "e.g. 7654321"),("Discord snowflake", "e.g. 491827364"),@@ -424,9 +391,7 @@ def _collect_operator_aliases(existing: dict, peer_target: str) -> dict:return aliases-def _apply_runtime_prefix(- hermes_host: dict, current_prefix: str, prefix_from_root: bool, label: str-) -> None:+def _apply_runtime_prefix(hermes_host: dict, current_prefix: str, prefix_from_root: bool, label: str) -> None:"""Write a host-level runtimePeerPrefix only when it diverges from aninherited root value; otherwise let the root cascade stand."""new_prefix = _prompt(label, default=current_prefix or "").strip()@@ -435,39 +400,25 @@ def _apply_runtime_prefix(def _echo_identity_mapping(hermes_host: dict) -> None:- """Show the resulting keys so the operator can verify what was written."""aliases = hermes_host.get("userPeerAliases")prefix = hermes_host.get("runtimePeerPrefix")- print(" resolved →")- print(f" pinUserPeer = {bool(hermes_host.get('pinUserPeer'))}")- print(f" userPeerAliases = {aliases if aliases else '{}'}")- print(f" runtimePeerPrefix = {prefix if prefix else '(none)'}")---def _configure_raw_identity_mapping(- hermes_host: dict,- current_pin: bool,- current_aliases: dict,- current_prefix: str,- aliases_from_root: bool,- prefix_from_root: bool,-) -> None:+ print(f" resolved →\n pinUserPeer = {bool(hermes_host.get('pinUserPeer'))}\n"+ f" userPeerAliases = {aliases if aliases else '{}'}\n"+ f" runtimePeerPrefix = {prefix if prefix else '(none)'}")+++def _configure_raw_identity_mapping(hermes_host, current_pin, current_aliases, current_prefix,+ aliases_from_root, prefix_from_root) -> None:"""Power-user escape hatch: set the three resolver knobs directly."""print("\n Raw identity-mapping keys (resolver tries them top-down):")- pin_in = _prompt(- "pinUserPeer — pin all gateway users to your peer? (true/false)",- default=str(bool(current_pin)).lower(),- ).strip().lower()+ pin_in = _prompt("pinUserPeer — pin all gateway users to your peer? (true/false)",+ default=str(bool(current_pin)).lower()).strip().lower()pin = pin_in in {"true", "t", "yes", "y", "1"}_scrub_identity_mapping(hermes_host)hermes_host["pinUserPeer"] = pinif pin:return- aliases = (- dict(current_aliases)- if isinstance(current_aliases, dict) and not aliases_from_root- else {}- )+ aliases = dict(current_aliases) if isinstance(current_aliases, dict) and not aliases_from_root else {}print(" userPeerAliases — 'runtime_id=peer' pairs (blank line to finish):")while True:entry = _prompt(" alias", default="").strip()@@ -479,28 +430,93 @@ def _configure_raw_identity_mapping(aliases[rid] = peerif aliases:hermes_host["userPeerAliases"] = aliases- _apply_runtime_prefix(- hermes_host, current_prefix, prefix_from_root,- "runtimePeerPrefix — namespace for unknown IDs (blank for none)",+ _apply_runtime_prefix(hermes_host, current_prefix, prefix_from_root,+ "runtimePeerPrefix — namespace for unknown IDs (blank for none)")+++def _setup_identity_mapping(cfg: dict, hermes_host: dict, current_peer: str) -> None:+ """Gateway identity mapping step. Only the gateway supplies a runtime user+ ID (CLI/TUI/desktop fall through to peerName), so the step is gated on+ gateway detection."""+ current_pin, current_aliases, current_prefix, aliases_from_root, prefix_from_root = (+ _resolve_effective_identity_mapping(cfg, hermes_host))+ current_shape = "single" if current_pin else "hybrid" if current_aliases else "multi"+ gw_platforms = _gateway_platforms()+ if gw_platforms is None:+ print("\n Gateway identity mapping routes platform users to memory peers.")+ run_mapping = _yes(_prompt("Running the Hermes gateway (Telegram/Discord/etc.)? (y/N)", default="n"))+ elif not gw_platforms:+ print("\n No gateway platforms connected — identity mapping only affects\n"+ " gateway users, so this step doesn't apply here.")+ run_mapping = _yes(_prompt("Configure gateway mapping anyway? (y/N)", default="n"))+ else:+ print(f"\n Gateway platforms detected: {', '.join(gw_platforms)}")+ run_mapping = True+ if not run_mapping:+ return-def _prompt(label: str, default: str | None = None, secret: bool = False) -> str:- suffix = f" [{default}]" if default else ""- sys.stdout.write(f" {label}{suffix}: ")- sys.stdout.flush()- if secret:- if sys.stdin.isatty():- from hermes_cli.secret_prompt import masked_secret_prompt- val = masked_secret_prompt("")- else:- # Non-TTY (piped input, test runners) — read plaintext- val = sys.stdin.readline().strip()+ peer_target = hermes_host.get("peerName") or current_peer or "user"+ default_choice = {"single": "1", "hybrid": "2", "multi": "3"}.get(current_shape, "3")+ print("\n How should gateway users map to memory peers?\n"+ " [1] just me — every non-agent user collapses to your peer\n"+ " [2] me + other people — keep mine pooled, others separate\n"+ " [3] only other people — everyone gets their own peer\n"+ " [s] skip (leave untouched) [e] edit raw keys")+ choice = _prompt("Choice", default=default_choice).strip().lower()++ if choice in {"2", "me+others", "both"}:+ pooled = _prompt(" Keep my own memory pooled across platforms? (Y/n)", default="y").strip().lower()+ shape = "hybrid" if pooled in {"y", "yes", ""} else "multi"else:- val = sys.stdin.readline().strip()- return val or (default or "")+ shape = {"1": "single", "me": "single", "just-me": "single", "3": "multi", "others": "multi",+ "e": "raw", "edit": "raw", "raw": "raw"}.get(choice, "skip")++ # Un-pinning without aliasing strands the pooled peerName history; steer toward pooling.+ if current_pin and shape == "multi":+ print(f"\n ⚠ Un-pinning will orphan memory accumulated under peer\n"+ f" '{peer_target}'. Existing gateway users resolve to fresh,\n"+ f" empty peers.")+ confirm = _prompt(" Pool my own memory instead (alias my IDs to peerName)? (Y/n)", default="y").strip().lower()+ if confirm in {"y", "yes", ""}:+ shape = "hybrid"++ if shape == "skip":+ print(" Identity mapping left untouched.")+ return+ if shape == "raw":+ _configure_raw_identity_mapping(hermes_host, current_pin, current_aliases, current_prefix,+ aliases_from_root, prefix_from_root)+ else:+ # Preserve operator-curated host-level aliases across multi → multi+ # re-runs. Root-sourced aliases cascade naturally and are NOT copied+ # down — an empty host map would mask a root baseline.+ prior_aliases = dict(current_aliases) if isinstance(current_aliases, dict) else {}+ if shape == "multi" and aliases_from_root:+ prior_aliases = {}+ _scrub_identity_mapping(hermes_host) # each shape starts from a clean slate+ hermes_host["pinUserPeer"] = shape == "single"+ if shape == "single":+ print(f" All non-agent gateway users route to '{peer_target}' (pin overrides aliases).")+ elif shape == "multi":+ if prior_aliases:+ hermes_host["userPeerAliases"] = prior_aliases+ _apply_runtime_prefix(hermes_host, current_prefix, prefix_from_root,+ "Runtime peer prefix (e.g. 'telegram_', blank for none)")+ print(" Each gateway user → own peer.")+ else: # hybrid+ merged = _collect_operator_aliases(prior_aliases, peer_target)+ if merged:+ hermes_host["userPeerAliases"] = merged+ _apply_runtime_prefix(hermes_host, current_prefix, prefix_from_root,+ "Runtime peer prefix for unknown users (e.g. 'telegram_', blank for none)")+ print(f" Your runtime IDs → '{peer_target}', others → own peer.")+ _echo_identity_mapping(hermes_host)+# ── setup wizard ───────────────────────────────────────────────────────────+def _ensure_sdk_installed() -> bool:"""Check honcho-ai is importable; offer to install if not. Returns True if ready."""try:@@ -508,443 +524,227 @@ def _ensure_sdk_installed() -> bool:return Trueexcept ImportError:pass-print(" honcho-ai is not installed.")- answer = _prompt("Install it now? (honcho-ai==2.2.0)", default="y")- if answer.lower() not in {"y", "yes"}:+ if not _yes(_prompt("Install it now? (honcho-ai==2.2.0)", default="y")):print(" Skipping install. Run: pip install 'honcho-ai==2.2.0'\n")return False-print(" Installing honcho-ai...", flush=True)- # Environment-aware install: sealed hosted venvs redirect to the durable- # data-volume target instead of writing to /opt/hermes (NS-605).- from tools.lazy_deps import install_specs-+ from tools.lazy_deps import install_specs # env-aware: sealed hosted venvs redirect to the data volumeresult = install_specs(["honcho-ai==2.2.0"])if result.ok:print(" Installed.\n")return True- elif result.blocked:+ if result.blocked:print(f" Cannot install: {result.reason}\n")- return Falseelse:- print(f" Install failed:\n{(result.stderr or '').strip()}")- print(" Run manually: uv pip install 'honcho-ai==2.2.0'\n")+ print(f" Install failed:\n{(result.stderr or '').strip()}\n Run manually: uv pip install 'honcho-ai==2.2.0'\n")+ return False+++def _device_login_available() -> bool:+ """Whether the resolved host offers the RFC 8628 device grant. Fails closed."""+ try:+ from plugins.memory.honcho.oauth_flow import resolve_endpoints, supports_device_login+ return supports_device_login(resolve_endpoints())+ except Exception:return False-def cmd_setup(args) -> None:- """Interactive Honcho setup wizard."""- cfg = _read_config()+def _headless() -> tuple[bool, bool]:+ """(is_remote, can_open_browser) — degrades safely if hermes_cli internals move."""+ try:+ from hermes_cli.auth import _can_open_graphical_browser, _is_remote_session+ return _is_remote_session(), _can_open_graphical_browser()+ except Exception:+ return False, True- write_path = _local_config_path()- read_path = _config_path()- print("\nHoncho memory setup\n" + "─" * 40)- print(" Honcho gives Hermes persistent cross-session memory.")- print(f" Config: {write_path}")- if read_path != write_path and read_path.exists():- print(f" (seeding from existing config at {read_path})")- print()- if not _ensure_sdk_installed():- return+def _apply_grant_to_host(hermes_host: dict, cred) -> None:+ """Store an OAuth grant on the host block; the wizard's final save persists it."""+ hermes_host["apiKey"] = cred.access_token+ hermes_host["oauth"] = cred.oauth_block()+ if cred.consent_peer_name: # default the peer prompt to the consent name+ hermes_host["peerName"] = cred.consent_peer_name- hosts = cfg.setdefault("hosts", {})- hermes_host = hosts.setdefault(_host_key(), {})- # Canonicalize any legacy pinPeerName before detection/writes.- _migrate_pin_key(cfg)- _migrate_pin_key(hermes_host)+def _open_in_browser(url: str) -> None:+ import webbrowser+ webbrowser.open(url)+++def _setup_local_auth(cfg: dict, hermes_host: dict) -> None:+ """Self-hosted Honcho may run with AUTH_USE_AUTH=true; clients then send a+ JWT signed with the server's AUTH_JWT_SECRET as the bearer token. It is+ stored under the host block (not top-level apiKey) so ``get_honcho_client``+ treats it as an explicit local auth opt-in and cloud/hybrid switching is+ unaffected."""+ new_url = _prompt("Base URL", default=cfg.get("baseUrl") or "http://localhost:8000")+ if new_url:+ cfg["baseUrl"] = new_url+ current_host_key = hermes_host.get("apiKey", "")+ print("\n Local Honcho auth (JWT signed with the server's AUTH_JWT_SECRET).\n"+ f" Leave blank if your server runs with AUTH_USE_AUTH=false. Current: {_mask(current_host_key)}")+ new_local_key = _prompt("Local JWT / bearer token (blank to skip / keep current)", secret=True)+ if new_local_key:+ hermes_host["apiKey"] = new_local_key+ elif current_host_key:+ print(" Keeping existing local JWT.")+ elif cfg.get("apiKey", ""):+ print("\n Top-level API key present in config (kept for cloud/hybrid use).\n"+ " Local connections will skip auth automatically until a local JWT is set above.")+ else:+ print("\n No local JWT set. Local no-auth ready.")- # --- 1. Cloud or local? ---- print(" Deployment:")- print(" cloud -- Honcho cloud (api.honcho.dev)")- print(" local -- self-hosted Honcho server")- current_deploy = "local" if any(- h in (cfg.get("baseUrl") or cfg.get("base_url") or "")- for h in ("localhost", "127.0.0.1", "::1")- ) else "cloud"- deploy = _prompt("Cloud or local?", default=current_deploy)- is_local = deploy.lower() in {"local", "l"}-- # Clean up legacy snake_case key- cfg.pop("base_url", None)- if is_local:- # --- Local: ask for base URL, optionally accept a JWT for auth ---- current_url = cfg.get("baseUrl") or ""- new_url = _prompt("Base URL", default=current_url or "http://localhost:8000")- if new_url:- cfg["baseUrl"] = new_url-- # Self-hosted Honcho can run with AUTH_USE_AUTH=true and an- # AUTH_JWT_SECRET on the server side. In that case clients must- # send a JWT signed with that secret as the bearer token (the- # Honcho SDK takes it via ``api_key=``). Cloud users got prompted- # for a key already; the local path historically skipped this and- # forced users to disable auth on the server. Offer the prompt- # here too. We store it under the host block (not the top-level- # apiKey) so ``get_honcho_client`` recognises it as an explicit- # local auth opt-in (see ``_host_has_key`` in client.py) and- # cloud/hybrid switching is unaffected.- current_host_key = hermes_host.get("apiKey", "")- masked = (- f"...{current_host_key[-8:]}"- if len(current_host_key) > 8- else ("set" if current_host_key else "not set")- )- print(- "\n Local Honcho auth (JWT signed with the server's "- "AUTH_JWT_SECRET)."- )- print(- " Leave blank if your server runs with AUTH_USE_AUTH=false. "- f"Current: {masked}"- )- new_local_key = _prompt(- "Local JWT / bearer token (blank to skip / keep current)",- secret=True,+def _setup_device_login(hermes_host: dict, write_path: Path, *, open_browser: bool) -> bool:+ """RFC 8628 device-code sign-in. Returns False if setup must abort."""+ from plugins.memory.honcho.oauth_flow import (+ AccessDenied, AuthorizationTimeout, DeviceCode, DeviceCodeExpired, DeviceFlowError,+ authorize_via_device_code,+ )++ def _show(device: DeviceCode) -> None:+ print("\n To connect, on any device with a browser:")+ print(f"\n 1. Open {device.verification_uri}")+ print(f" 2. Enter {device.user_code}")+ print(f"\n Or open directly:\n\n {device.verification_uri_complete}\n")+ mins = max(1, device.expires_in // 60)+ print(f" Waiting for approval (expires in {mins} min, Ctrl-C to cancel) ", end="", flush=True)++ print("\n Requesting device code…")+ try:+ cred = authorize_via_device_code(+ config_path=write_path, source="hermes-cli", apply_config=False, display=_show,+ open_url=_open_in_browser if open_browser else None,+ on_poll=lambda: print(".", end="", flush=True),)- if new_local_key:- hermes_host["apiKey"] = new_local_key- elif current_host_key:- print(" Keeping existing local JWT.")+ except KeyboardInterrupt:+ print("\n Cancelled. Re-run 'hermes honcho setup' to try again.\n")+ except (AuthorizationTimeout, DeviceCodeExpired):+ print("\n Device code expired before approval.\n Re-run 'hermes honcho setup' to get a new code.\n")+ except AccessDenied:+ print("\n Sign-in was denied on the approval page.\n" + _RETRY_HINT)+ except Exception as e:+ if isinstance(e, DeviceFlowError) and e.error == "http_429":+ print("\n Too many device-code requests — wait a minute and re-run setup.\n")else:- # Surface the top-level key situation for transparency.- top_key = cfg.get("apiKey", "")- if top_key:- print(- "\n Top-level API key present in config (kept for "- "cloud/hybrid use)."- )- print(- " Local connections will skip auth automatically "- "until a local JWT is set above."- )- else:- print("\n No local JWT set. Local no-auth ready.")- use_oauth = False- if not is_local:- # --- Cloud: OAuth (browser), device code, or API key ---- cfg.pop("baseUrl", None) # cloud uses SDK default-- # Detect an existing OAuth grant so re-running setup reflects it instead- # of looking like a fresh connect.- from plugins.memory.honcho.oauth import OAuthCredential- existing_oauth = OAuthCredential.from_host_block(hermes_host)-- device_available = _device_login_available()- is_remote, can_browse = _headless()-- print("\n Auth method:")- if existing_oauth is not None:- print(f" (currently connected via OAuth — client {existing_oauth.client_id})")- print(" oauth -- sign in via browser on this machine (recommended)")+ print(f"\n Device sign-in failed: {e}\n" + _RETRY_HINT)+ else:+ print(" approved")+ _apply_grant_to_host(hermes_host, cred)+ print(" Authorized — token saved. Let's finish configuring.\n")+ return True+ return False+++def _setup_browser_login(hermes_host: dict, write_path: Path) -> bool:+ """Loopback OAuth sign-in, up front — the browser link is the whole point.+ Tokens merge into the in-memory cfg so the wizard's final save keeps them;+ settings stay wizard-owned (apply_config=False). Returns False on abort."""+ from plugins.memory.honcho.oauth_flow import authorize_via_loopback++ def _open(url: str) -> None:+ print(f"\n Open this link to authorize (waiting up to 5 minutes):\n\n {url}\n")+ _open_in_browser(url)++ print("\n Starting browser sign-in…")+ try:+ cred = authorize_via_loopback(config_path=write_path, source="hermes-cli", apply_config=False, open_url=_open)+ except Exception as e:+ print(f" OAuth sign-in failed: {e}\n" + _RETRY_HINT)+ return False+ _apply_grant_to_host(hermes_host, cred)+ print(" Authorized — token saved. Let's finish configuring.\n")+ return True+++def _setup_cloud_auth(cfg: dict, hermes_host: dict, write_path: Path) -> bool:+ """Cloud auth: OAuth (browser), device code, or API key. Returns False on abort."""+ cfg.pop("baseUrl", None) # cloud uses SDK default+ from plugins.memory.honcho.oauth import OAuthCredential+ existing_oauth = OAuthCredential.from_host_block(hermes_host)+ device_available = _device_login_available()+ is_remote, can_browse = _headless()++ print("\n Auth method:")+ if existing_oauth is not None:+ print(f" (currently connected via OAuth — client {existing_oauth.client_id})")+ print(" oauth -- sign in via browser on this machine (recommended)")+ if device_available:+ print(" device -- device code: approve from a browser on another machine (SSH / headless)")+ print(" apikey -- paste an API key from https://app.honcho.dev")++ default_method = "oauth"+ if is_remote or not can_browse:if device_available:- print(" device -- device code: approve from a browser on another machine (SSH / headless)")- print(" apikey -- paste an API key from https://app.honcho.dev")-- default_method = "oauth"- if is_remote or not can_browse:- if device_available:- print(" (no usable local browser detected — device code recommended)")- default_method = "device"- else:- print(" (no usable local browser detected — browser sign-in may need an SSH tunnel to 127.0.0.1:8765)")- prompt_label = "oauth, device, or apikey?" if device_available else "OAuth or API key?"- method = _prompt(prompt_label, default=default_method).strip().lower()- use_oauth = method in {"oauth", "o"}- use_device = device_available and method in {"device", "d"}-- if use_device:- from plugins.memory.honcho.oauth_flow import (- AccessDenied,- AuthorizationTimeout,- DeviceCode,- DeviceCodeExpired,- DeviceFlowError,- authorize_via_device_code,- )-- def _show(device: DeviceCode) -> None:- print("\n To connect, on any device with a browser:")- print(f"\n 1. Open {device.verification_uri}")- print(f" 2. Enter {device.user_code}")- print(f"\n Or open directly:\n\n {device.verification_uri_complete}\n")- mins = max(1, device.expires_in // 60)- print(f" Waiting for approval (expires in {mins} min, Ctrl-C to cancel) ", end="", flush=True)-- def _open_local(url: str) -> None:- import webbrowser-- webbrowser.open(url)-- print("\n Requesting device code…")- try:- cred = authorize_via_device_code(- config_path=write_path,- source="hermes-cli",- apply_config=False,- display=_show,- open_url=_open_local if can_browse and not is_remote else None,- on_poll=lambda: print(".", end="", flush=True),- )- except KeyboardInterrupt:- print("\n Cancelled. Re-run 'hermes honcho setup' to try again.\n")- return- except (AuthorizationTimeout, DeviceCodeExpired):- print("\n Device code expired before approval.")- print(" Re-run 'hermes honcho setup' to get a new code.\n")- return- except AccessDenied:- print("\n Sign-in was denied on the approval page.")- print(" Re-run 'hermes honcho setup' to retry, or choose an API key instead.\n")- return- except DeviceFlowError as e:- if e.error == "http_429":- print("\n Too many device-code requests — wait a minute and re-run setup.\n")- else:- print(f"\n Device sign-in failed: {e}")- print(" Re-run 'hermes honcho setup' to retry, or choose an API key instead.\n")- return- except Exception as e:- print(f"\n Device sign-in failed: {e}")- print(" Re-run 'hermes honcho setup' to retry, or choose an API key instead.\n")- return- print(" approved")- _apply_grant_to_host(hermes_host, cred)- print(" Authorized — token saved. Let's finish configuring.\n")- elif use_oauth:- # Sign in now, up front — the browser link is the whole point, so- # don't bury it behind the identity prompts. The grant's tokens are- # merged into the in-memory cfg so the wizard's final save preserves- # them; settings stay wizard-owned (apply_config=False).- from plugins.memory.honcho.oauth_flow import authorize_via_loopback-- def _open(url: str) -> None:- print(f"\n Open this link to authorize (waiting up to 5 minutes):\n\n {url}\n")- import webbrowser-- webbrowser.open(url)-- print("\n Starting browser sign-in…")- try:- cred = authorize_via_loopback(- config_path=write_path,- source="hermes-cli",- apply_config=False,- open_url=_open,- )- except Exception as e:- print(f" OAuth sign-in failed: {e}")- print(" Re-run 'hermes honcho setup' to retry, or choose an API key instead.\n")- return- _apply_grant_to_host(hermes_host, cred)- print(" Authorized — token saved. Let's finish configuring.\n")+ print(" (no usable local browser detected — device code recommended)")+ default_method = "device"else:- current_key = cfg.get("apiKey", "")- masked = f"...{current_key[-8:]}" if len(current_key) > 8 else ("set" if current_key else "not set")- print(f"\n Current API key: {masked}")- new_key = _prompt("Honcho API key (leave blank to keep current)", secret=True)- if new_key:- cfg["apiKey"] = new_key-- if not cfg.get("apiKey"):- print("\n No API key configured. Get yours at https://app.honcho.dev")- print(" Run 'hermes honcho setup' again once you have a key.\n")- return+ print(" (no usable local browser detected — browser sign-in may need an SSH tunnel to 127.0.0.1:8765)")+ prompt_label = "oauth, device, or apikey?" if device_available else "OAuth or API key?"+ method = _prompt(prompt_label, default=default_method).strip().lower()++ if device_available and method in {"device", "d"}:+ return _setup_device_login(hermes_host, write_path, open_browser=can_browse and not is_remote)+ if method in {"oauth", "o"}:+ return _setup_browser_login(hermes_host, write_path)+ print(f"\n Current API key: {_mask(cfg.get('apiKey', ''))}")+ new_key = _prompt("Honcho API key (leave blank to keep current)", secret=True)+ if new_key:+ cfg["apiKey"] = new_key+ if not cfg.get("apiKey"):+ print("\n No API key configured. Get yours at https://app.honcho.dev\n"+ " Run 'hermes honcho setup' again once you have a key.\n")+ return False+ return True+++def _menu(header: str, *lines: str) -> None:+ print(f"\n {header}:")+ for line in lines:+ print(f" {line}")+- # --- 3. Identity ---- current_peer = hermes_host.get("peerName") or cfg.get("peerName", "")- new_peer = _prompt("Your name (user peer)", default=current_peer or os.getenv("USER", "user"))- if new_peer:- hermes_host["peerName"] = new_peer-- current_ai = hermes_host.get("aiPeer") or cfg.get("aiPeer", "hermes")- new_ai = _prompt("AI peer name", default=current_ai)- if new_ai:- hermes_host["aiPeer"] = new_ai-- current_workspace = hermes_host.get("workspace") or cfg.get("workspace", "hermes")- new_workspace = _prompt("Workspace ID", default=current_workspace)- if new_workspace:- hermes_host["workspace"] = new_workspace-- # --- 3b. Gateway identity mapping ---- # These keys only affect the Hermes GATEWAY (Telegram/Discord/Slack/...),- # the one entrypoint that supplies a runtime user ID. CLI/TUI/desktop/ACP- # sessions have no runtime ID and fall through to peerName, so the step is- # moot off-gateway — gate it behind detection.- #- # Detection mirrors the gateway resolver: root-level config and the- # canonical ``pinUserPeer`` both affect routing, so host-only reads would- # mis-classify a profile that inherits its mapping from root.- (- current_pin,- current_aliases,- current_prefix,- aliases_from_root,- prefix_from_root,- ) = _resolve_effective_identity_mapping(cfg, hermes_host)-- if current_pin:- current_shape = "single"- elif current_aliases:- current_shape = "hybrid"- else:- current_shape = "multi"+def _choice_step(hermes_host, key, current, label, valid, fallback=None) -> None:+ """Prompt for one of ``valid``; an invalid answer writes ``fallback`` (None = keep current)."""+ new = _prompt(label, default=current)+ if new in valid:+ hermes_host[key] = new+ elif fallback is not None:+ hermes_host[key] = fallback- gw_platforms = _gateway_platforms()- if gw_platforms is None:- print("\n Gateway identity mapping routes platform users to memory peers.")- run_mapping = _prompt(- "Running the Hermes gateway (Telegram/Discord/etc.)? (y/N)",- default="n",- ).strip().lower() in {"y", "yes"}- elif not gw_platforms:- print("\n No gateway platforms connected — identity mapping only affects")- print(" gateway users, so this step doesn't apply here.")- run_mapping = _prompt(- "Configure gateway mapping anyway? (y/N)", default="n",- ).strip().lower() in {"y", "yes"}- else:- print(f"\n Gateway platforms detected: {', '.join(gw_platforms)}")- run_mapping = True- if run_mapping:- peer_target = hermes_host.get("peerName") or current_peer or "user"- default_choice = {"single": "1", "hybrid": "2", "multi": "3"}.get(current_shape, "3")- print("\n How should gateway users map to memory peers?")- print(" [1] just me — every non-agent user collapses to your peer")- print(" [2] me + other people — keep mine pooled, others separate")- print(" [3] only other people — everyone gets their own peer")- print(" [s] skip (leave untouched) [e] edit raw keys")- choice = _prompt("Choice", default=default_choice).strip().lower()-- if choice in {"2", "me+others", "both"}:- pooled = _prompt(- " Keep my own memory pooled across platforms? (Y/n)", default="y",- ).strip().lower()- shape = "hybrid" if pooled in {"y", "yes", ""} else "multi"- elif choice in {"1", "me", "just-me"}:- shape = "single"- elif choice in {"3", "others"}:- shape = "multi"- elif choice in {"e", "edit", "raw"}:- shape = "raw"- else:- shape = "skip"-- # Un-pinning a currently-pinned profile without aliasing strands the- # pooled peerName history; steer the operator toward pooling instead.- if current_pin and shape == "multi":- print(- f"\n ⚠ Un-pinning will orphan memory accumulated under peer\n"- f" '{peer_target}'. Existing gateway users resolve to fresh,\n"- f" empty peers."- )- confirm = _prompt(- " Pool my own memory instead (alias my IDs to peerName)? (Y/n)",- default="y",- ).strip().lower()- if confirm in {"y", "yes", ""}:- shape = "hybrid"-- # Each branch scrubs every peer-mapping key first so a stale alias,- # prefix, or pin from an earlier run starts clean.- if shape == "single":- _scrub_identity_mapping(hermes_host)- hermes_host["pinUserPeer"] = True- print(f" All non-agent gateway users route to '{peer_target}' (pin overrides aliases).")- _echo_identity_mapping(hermes_host)- elif shape == "multi":- # Preserve operator-curated host-level aliases across multi → multi- # re-runs. Root-sourced aliases cascade naturally and are NOT- # copied down — an empty host map would mask a root baseline.- prior_aliases = (- dict(current_aliases)- if isinstance(current_aliases, dict) and not aliases_from_root- else {}- )- _scrub_identity_mapping(hermes_host)- hermes_host["pinUserPeer"] = False- if prior_aliases:- hermes_host["userPeerAliases"] = prior_aliases- _apply_runtime_prefix(- hermes_host, current_prefix, prefix_from_root,- "Runtime peer prefix (e.g. 'telegram_', blank for none)",- )- print(" Each gateway user → own peer.")- _echo_identity_mapping(hermes_host)- elif shape == "hybrid":- existing_aliases = dict(current_aliases) if isinstance(current_aliases, dict) else {}- _scrub_identity_mapping(hermes_host)- hermes_host["pinUserPeer"] = False- merged = _collect_operator_aliases(existing_aliases, peer_target)- if merged:- hermes_host["userPeerAliases"] = merged- _apply_runtime_prefix(- hermes_host, current_prefix, prefix_from_root,- "Runtime peer prefix for unknown users (e.g. 'telegram_', blank for none)",- )- print(f" Your runtime IDs → '{peer_target}', others → own peer.")- _echo_identity_mapping(hermes_host)- elif shape == "raw":- _configure_raw_identity_mapping(- hermes_host, current_pin, current_aliases, current_prefix,- aliases_from_root, prefix_from_root,- )- _echo_identity_mapping(hermes_host)- else: # skip- print(" Identity mapping left untouched.")-- # --- 4. Observation mode ---- current_obs = hermes_host.get("observationMode") or cfg.get("observationMode", "directional")- print("\n Observation mode:")- print(" directional -- all observations on, each AI peer builds its own view (default)")- print(" unified -- user observes self, AI observes others only")- new_obs = _prompt("Observation mode", default=current_obs)- if new_obs in {"unified", "directional"}:- hermes_host["observationMode"] = new_obs- else:- hermes_host["observationMode"] = "directional"-- # --- 5. Write frequency ---- current_wf = str(hermes_host.get("writeFrequency") or cfg.get("writeFrequency", "async"))- print("\n Write frequency:")- print(" async -- background thread, no token cost (recommended)")- print(" turn -- sync write after every turn")- print(" session -- batch write at session end only")- print(" N -- write every N turns (e.g. 5)")- new_wf = _prompt("Write frequency", default=current_wf)+def _setup_tuning(cfg: dict, hermes_host: dict) -> None:+ """Wizard steps 4-8: observation, write frequency, recall, budgets, reasoning, strategy."""+ _menu("Observation mode",+ "directional -- all observations on, each AI peer builds its own view (default)",+ "unified -- user observes self, AI observes others only")+ _choice_step(hermes_host, "observationMode", _pref(hermes_host, cfg, "observationMode", "directional"),+ "Observation mode", {"unified", "directional"}, "directional")++ _menu("Write frequency",+ "async -- background thread, no token cost (recommended)",+ "turn -- sync write after every turn",+ "session -- batch write at session end only",+ "N -- write every N turns (e.g. 5)")+ new_wf = _prompt("Write frequency", default=str(_pref(hermes_host, cfg, "writeFrequency", "async")))try:hermes_host["writeFrequency"] = int(new_wf)except (ValueError, TypeError):hermes_host["writeFrequency"] = new_wf if new_wf in {"async", "turn", "session"} else "async"- # --- 6. Recall mode ---- _raw_recall = hermes_host.get("recallMode") or cfg.get("recallMode", "hybrid")- current_recall = "hybrid" if _raw_recall not in {"hybrid", "context", "tools"} else _raw_recall- print("\n Recall mode:")- print(" hybrid -- auto-injected context + Honcho tools available (default)")- print(" context -- auto-injected context only, Honcho tools hidden")- print(" tools -- Honcho tools only, no auto-injected context")- new_recall = _prompt("Recall mode", default=current_recall)- if new_recall in {"hybrid", "context", "tools"}:- hermes_host["recallMode"] = new_recall-- # --- 7. Context token budget ---- current_ctx_tokens = hermes_host.get("contextTokens") or cfg.get("contextTokens")- current_display = str(current_ctx_tokens) if current_ctx_tokens else "uncapped"- print("\n Context injection per turn (hybrid/context recall modes only):")- print(" uncapped -- no limit (default)")- print(" N -- token limit per turn (e.g. 1200)")- new_ctx_tokens = _prompt("Context tokens", default=current_display)+ _menu("Recall mode", *(f"{m:<7} -- {desc}" for m, desc in _MODES.items()))+ raw_recall = _pref(hermes_host, cfg, "recallMode", "hybrid")+ _choice_step(hermes_host, "recallMode", raw_recall if raw_recall in _MODES else "hybrid", "Recall mode", _MODES)++ current_ctx_tokens = _pref(hermes_host, cfg, "contextTokens")+ _menu("Context injection per turn (hybrid/context recall modes only)",+ "uncapped -- no limit (default)",+ "N -- token limit per turn (e.g. 1200)")+ new_ctx_tokens = _prompt("Context tokens", default=str(current_ctx_tokens) if current_ctx_tokens else "uncapped")if new_ctx_tokens.strip().lower() in {"none", "uncapped", "no limit"}:hermes_host.pop("contextTokens", None)- elif new_ctx_tokens.strip() == "":- pass # keep current- else:+ elif new_ctx_tokens.strip():try:val = int(new_ctx_tokens)if val >= 0:@@ -952,13 +752,11 @@ def cmd_setup(args) -> None:except (ValueError, TypeError):pass # keep current- # --- 7b. Dialectic cadence ---- current_dialectic = str(hermes_host.get("dialecticCadence") or cfg.get("dialecticCadence") or "2")- print("\n Dialectic cadence:")- print(" How often Honcho rebuilds its user model (LLM call on Honcho backend).")- print(" 1 = every turn, 2 = every other turn, 3+ = sparser.")- print(" Recommended: 1-5.")- new_dialectic = _prompt("Dialectic cadence", default=current_dialectic)+ _menu("Dialectic cadence",+ "How often Honcho rebuilds its user model (LLM call on Honcho backend).",+ "1 = every turn, 2 = every other turn, 3+ = sparser.",+ "Recommended: 1-5.")+ new_dialectic = _prompt("Dialectic cadence", default=str(_pref(hermes_host, cfg, "dialecticCadence") or "2"))try:val = int(new_dialectic)if val >= 1:@@ -966,119 +764,115 @@ def cmd_setup(args) -> None:except (ValueError, TypeError):hermes_host["dialecticCadence"] = 2- # --- 7c. Dialectic reasoning level ---- current_reasoning = (- hermes_host.get("dialecticReasoningLevel")- or cfg.get("dialecticReasoningLevel")- or "low"- )- print("\n Dialectic reasoning level:")- print(" Depth Honcho uses when synthesizing user context on auto-injected calls.")- print(" minimal -- quick factual lookups")- print(" low -- straightforward questions (default)")- print(" medium -- multi-aspect synthesis")- print(" high -- complex behavioral patterns")- print(" max -- thorough audit-level analysis")- new_reasoning = _prompt("Reasoning level", default=current_reasoning)- if new_reasoning in {"minimal", "low", "medium", "high", "max"}:- hermes_host["dialecticReasoningLevel"] = new_reasoning- else:- hermes_host["dialecticReasoningLevel"] = "low"-- # --- 8. Session strategy ---- current_strat = hermes_host.get("sessionStrategy") or cfg.get("sessionStrategy", "per-session")- print("\n Session strategy:")- print(" per-session -- each run starts clean, Honcho injects context automatically")- print(" per-directory -- reuses session per dir, prior context auto-injected each run")- print(" per-repo -- one session per git repository")- print(" global -- single session across all directories")- new_strat = _prompt("Session strategy", default=current_strat)- if new_strat in {"per-session", "per-repo", "per-directory", "global"}:- hermes_host["sessionStrategy"] = new_strat+ _menu("Dialectic reasoning level",+ "Depth Honcho uses when synthesizing user context on auto-injected calls.",+ "minimal -- quick factual lookups",+ "low -- straightforward questions (default)",+ "medium -- multi-aspect synthesis",+ "high -- complex behavioral patterns",+ "max -- thorough audit-level analysis")+ _choice_step(hermes_host, "dialecticReasoningLevel", _pref(hermes_host, cfg, "dialecticReasoningLevel") or "low",+ "Reasoning level", REASONING_LEVELS, "low")++ _menu("Session strategy", *(f"{s:<13} -- {desc}" for s, desc in _STRATEGIES.items()))+ _choice_step(hermes_host, "sessionStrategy", _pref(hermes_host, cfg, "sessionStrategy", "per-session"),+ "Session strategy", _STRATEGIES)+++def cmd_setup(args) -> None:+ """Interactive Honcho setup wizard."""+ cfg = _read_config()+ write_path = _local_config_path()+ read_path = _config_path()+ print(f"\nHoncho memory setup\n{RULE}\n Honcho gives Hermes persistent cross-session memory.\n Config: {write_path}")+ if read_path != write_path and read_path.exists():+ print(f" (seeding from existing config at {read_path})")+ print()+ if not _ensure_sdk_installed():+ return++ hermes_host = cfg.setdefault("hosts", {}).setdefault(_host_key(), {})+ _migrate_pin_key(cfg) # canonicalize legacy pinPeerName before detection/writes+ _migrate_pin_key(hermes_host)++ # --- 1. Cloud or local? ---+ print(" Deployment:\n cloud -- Honcho cloud (api.honcho.dev)\n local -- self-hosted Honcho server")+ current_url = cfg.get("baseUrl") or cfg.get("base_url") or ""+ current_deploy = "local" if any(h in current_url for h in ("localhost", "127.0.0.1", "::1")) else "cloud"+ is_local = _prompt("Cloud or local?", default=current_deploy).lower() in {"local", "l"}+ cfg.pop("base_url", None) # legacy snake_case key+ if is_local:+ _setup_local_auth(cfg, hermes_host)+ elif not _setup_cloud_auth(cfg, hermes_host, write_path):+ return++ # --- 3. Identity ---+ current_peer = hermes_host.get("peerName") or cfg.get("peerName", "")+ for key, label, default in (+ ("peerName", "Your name (user peer)", current_peer or os.getenv("USER", "user")),+ ("aiPeer", "AI peer name", _pref(hermes_host, cfg, "aiPeer", "hermes")),+ ("workspace", "Workspace ID", _pref(hermes_host, cfg, "workspace", "hermes")),+ ):+ new = _prompt(label, default=default)+ if new:+ hermes_host[key] = new++ _setup_identity_mapping(cfg, hermes_host, current_peer)+ _setup_tuning(cfg, hermes_host)hermes_host["enabled"] = Truehermes_host.setdefault("saveMessages", True)-_write_config(cfg)print(f"\n Config written to {write_path}")- # --- Auto-enable Honcho as memory provider in config.yaml ---- try:+ try: # auto-enable Honcho as memory provider in config.yamlfrom hermes_cli.config import load_config, save_confighermes_config = load_config()hermes_config.setdefault("memory", {})["provider"] = "honcho"save_config(hermes_config)print(" Memory provider set to 'honcho' in config.yaml")except Exception as e:- print(f" Could not auto-enable in config.yaml: {e}")- print(" Run: hermes config set memory.provider honcho")+ print(f" Could not auto-enable in config.yaml: {e}\n Run: hermes config set memory.provider honcho")- # --- Test connection ---print(" Testing connection... ", end="", flush=True)try:- from plugins.memory.honcho.client import HonchoClientConfig, get_honcho_client, reset_honcho_client- reset_honcho_client()- hcfg = HonchoClientConfig.from_global_config(host=_host_key())- get_honcho_client(hcfg)+ hcfg, _client = _connect(_host_key(), reset=True)print("OK")except Exception as e:print(f"FAILED\n Error: {e}")return- print("\n Honcho is ready.")- print(f" Session: {hcfg.resolve_session_name()}")- print(f" Workspace: {hcfg.workspace_id}")- print(f" User: {hcfg.peer_name}")- print(f" AI peer: {hcfg.ai_peer}")- print(f" Observe: {hcfg.observation_mode}")- print(f" Frequency: {hcfg.write_frequency}")- print(f" Recall: {hcfg.recall_mode}")- print(f" Sessions: {hcfg.session_strategy}")- print("\n Honcho tools available in chat:")- print(" honcho_context -- session context: summary, representation, card, messages")- print(" honcho_search -- semantic search over history")- print(" honcho_profile -- peer card, key facts")- print(" honcho_reasoning -- ask Honcho a question, synthesized answer")- print(" honcho_conclude -- persist a user fact to memory")- print("\n Other commands:")- print(" hermes honcho status -- show full config")- print(" hermes honcho mode -- change recall/observation mode")- print(" hermes honcho tokens -- tune context and dialectic budgets")- print(" hermes honcho peer -- update peer names")- print(" hermes honcho map <name> -- map this directory to a session name\n")---def _device_login_available() -> bool:- """Whether the resolved host offers the RFC 8628 device grant. Fails closed."""- try:- from plugins.memory.honcho.oauth_flow import resolve_endpoints, supports_device_login-- return supports_device_login(resolve_endpoints())- except Exception:- return False---def _headless() -> tuple[bool, bool]:- """(is_remote, can_open_browser) — degrades safely if hermes_cli internals move."""- try:- from hermes_cli.auth import _can_open_graphical_browser, _is_remote_session-- return _is_remote_session(), _can_open_graphical_browser()- except Exception:- return False, True---def _apply_grant_to_host(hermes_host: dict, cred) -> None:- """Store an OAuth grant on the host block; the wizard's final save persists it."""- hermes_host["apiKey"] = cred.access_token- hermes_host["oauth"] = cred.oauth_block()- # Default the peer prompt to the name entered at consent.- if cred.consent_peer_name:- hermes_host["peerName"] = cred.consent_peer_name-+ print(f"""+ Honcho is ready.+ Session: {hcfg.resolve_session_name()}+ Workspace: {hcfg.workspace_id}+ User: {hcfg.peer_name}+ AI peer: {hcfg.ai_peer}+ Observe: {hcfg.observation_mode}+ Frequency: {hcfg.write_frequency}+ Recall: {hcfg.recall_mode}+ Sessions: {hcfg.session_strategy}++ Honcho tools available in chat:+ honcho_context -- session context: summary, representation, card, messages+ honcho_search -- semantic search over history+ honcho_profile -- peer card, key facts+ honcho_reasoning -- ask Honcho a question, synthesized answer+ honcho_conclude -- persist a user fact to memory++ Other commands:+ hermes honcho status -- show full config+ hermes honcho mode -- change recall/observation mode+ hermes honcho tokens -- tune context and dialectic budgets+ hermes honcho peer -- update peer names+ hermes honcho map <name> -- map this directory to a session name+""")+++# ── status / peers ─────────────────────────────────────────────────────────def _active_profile_name() -> str:- """Return the active Hermes profile name (respects --target-profile override)."""+ """Active Hermes profile name (respects --target-profile override)."""if _profile_override:return _profile_overridetry:@@ -1089,44 +883,27 @@ def _active_profile_name() -> str:def _all_profile_host_configs() -> list[tuple[str, str, dict]]:- """Return (profile_name, host_key, host_block) for every known profile.-- Reads honcho.json once and maps each profile to its host block.- """+ """(profile_name, host_key, host_block) for every known profile, reading honcho.json once."""try:from hermes_cli.profiles import list_profilesprofiles = list_profiles()except Exception:return [(_active_profile_name(), _host_key(), {})]-cfg = _read_config()- hosts = cfg.get("hosts", {})- results = []-- # Default profile- default_block = hosts.get(HOST, {})- results.append(("default", HOST, default_block))-+ results = [("default", HOST, cfg.get("hosts", {}).get(HOST, {}))]for p in profiles:- if p.name == "default":- continue- h = profile_host_key(p.name)- # _host_block (not hosts.get) so legacy dot-form keys- # ("hermes.work") stay readable per the README's back-compat- # promise — the canonical key resolves first, legacy falls back.- results.append((p.name, h, _host_block(cfg, h)))-+ if p.name != "default":+ h = profile_host_key(p.name)+ # _host_block (not hosts.get) keeps legacy dot-form keys ("hermes.work") readable.+ results.append((p.name, h, _host_block(cfg, h)))return resultsdef cmd_status(args) -> None:"""Show current Honcho config and connection status."""- show_all = getattr(args, "all", False)-- if show_all:+ if getattr(args, "all", False):_cmd_status_all()return-try:import honcho # noqa: F401except ImportError:@@ -1134,63 +911,44 @@ def cmd_status(args) -> None:returncfg = _read_config()-active_path = _config_path()write_path = _local_config_path()-- if not cfg:- # Config file missing — try env var fallback before giving up.+ from plugins.memory.honcho.client import HonchoClientConfig, get_honcho_client+ if not cfg: # config file missing — the env-var fallback may still yield a usable configtry:- from plugins.memory.honcho.client import HonchoClientConfig_env_cfg = HonchoClientConfig.from_global_config(host=_host_key())- if _env_cfg.api_key or _env_cfg.base_url:- # Env var fallback worked — use that config instead.- cfg = {"apiKey": _env_cfg.api_key, "enabled": _env_cfg.enabled}- else:- print(f" No Honcho config found at {active_path}")- print(" Run 'hermes honcho setup' to configure.\n")- return+ cfg = bool(_env_cfg.api_key or _env_cfg.base_url)except Exception:- print(f" No Honcho config found at {active_path}")- print(" Run 'hermes honcho setup' to configure.\n")+ cfg = False+ if not cfg:+ print(f" No Honcho config found at {active_path}\n Run 'hermes honcho setup' to configure.\n")return-try:- from plugins.memory.honcho.client import HonchoClientConfig, get_honcho_clienthcfg = HonchoClientConfig.from_global_config(host=_host_key())except Exception as e:print(f" Config error: {e}\n")return- api_key = hcfg.api_key or ""- masked = f"...{api_key[-8:]}" if len(api_key) > 8 else ("set" if api_key else "not set")-- # Auth line distinguishes an OAuth grant (refreshable) from a static API key- # — the OAuth access token is also stored under apiKey, so masking alone hides it.+ # The OAuth access token is also stored under apiKey, so the auth line+ # distinguishes a refreshable grant from a static key explicitly.from plugins.memory.honcho.oauth import OAuthCredential- host_block = (getattr(hcfg, "raw", None) or {}).get("hosts", {}).get(hcfg.host) or {}- cred = OAuthCredential.from_host_block(host_block)-+ raw = getattr(hcfg, "raw", None) or {}+ cred = OAuthCredential.from_host_block(raw.get("hosts", {}).get(hcfg.host) or {})profile = _active_profile_name()- profile_label = f" [{hcfg.host}]" if profile != "default" else ""- print(f"\nHoncho status{profile_label}\n" + "─" * 40)- if profile != "default":- print(f" Profile: {profile}")- print(f" Host: {hcfg.host}")- print(f" Enabled: {hcfg.enabled}")if cred is not None:import time as _timeremaining = int(cred.expires_at - _time.time())token_state = f"valid {remaining // 60}m" if remaining > 0 else "expired — refreshes on next use"- print(f" Auth: OAuth ({cred.client_id}, token {token_state})")+ auth = f"OAuth ({cred.client_id}, token {token_state})"else:- print(f" Auth: API key ({masked})")- print(f" Workspace: {hcfg.workspace_id}")-- # Config paths — show where config was read from and where writes go+ auth = f"API key ({_mask(hcfg.api_key or '')})"+ print(f"\nHoncho status{f' [{hcfg.host}]' if profile != 'default' else ''}\n" + RULE)+ if profile != "default":+ print(f" Profile: {profile}")+ print(f" Host: {hcfg.host}\n Enabled: {hcfg.enabled}\n Auth: {auth}\n"+ f" Workspace: {hcfg.workspace_id}\n Config: {active_path}")global_path = Path.home() / ".honcho" / "config.json"- print(f" Config: {active_path}")if write_path != active_path:print(f" Write to: {write_path} (profile-local)")if active_path == global_path:@@ -1198,20 +956,18 @@ def cmd_status(args) -> None:elif global_path.exists():print(f" Fallback: {global_path} (exists, cross-app interop)")- print(f" AI peer: {hcfg.ai_peer}")- print(f" User peer: {hcfg.peer_name or 'not set'}")- print(f" Session key: {hcfg.resolve_session_name()}")- print(f" Session strat: {hcfg.session_strategy}")- print(f" Recall mode: {hcfg.recall_mode}")- print(f" Context budget: {hcfg.context_tokens or '(uncapped)'} tokens")- raw = getattr(hcfg, "raw", None) or {}dialectic_cadence = getattr(hcfg, "dialectic_cadence", None) or raw.get("dialecticCadence") or 1- print(f" Dialectic cad: every {dialectic_cadence} turn{'s' if dialectic_cadence != 1 else ''}")reasoning_cap = raw.get("reasoningLevelCap") or hcfg.reasoning_level_cap- heuristic_on = "on" if hcfg.reasoning_heuristic else "off"- print(f" Reasoning: base={hcfg.dialectic_reasoning_level}, cap={reasoning_cap}, heuristic={heuristic_on}")- print(f" Observation: user(me={hcfg.user_observe_me},others={hcfg.user_observe_others}) ai(me={hcfg.ai_observe_me},others={hcfg.ai_observe_others})")- print(f" Write freq: {hcfg.write_frequency}")+ print(f""" AI peer: {hcfg.ai_peer}+ User peer: {hcfg.peer_name or 'not set'}+ Session key: {hcfg.resolve_session_name()}+ Session strat: {hcfg.session_strategy}+ Recall mode: {hcfg.recall_mode}+ Context budget: {hcfg.context_tokens or '(uncapped)'} tokens+ Dialectic cad: every {dialectic_cadence} turn{'s' if dialectic_cadence != 1 else ''}+ Reasoning: base={hcfg.dialectic_reasoning_level}, cap={reasoning_cap}, heuristic={'on' if hcfg.reasoning_heuristic else 'off'}+ Observation: user(me={hcfg.user_observe_me},others={hcfg.user_observe_others}) ai(me={hcfg.ai_observe_me},others={hcfg.ai_observe_others})+ Write freq: {hcfg.write_frequency}""")if hcfg.enabled and (hcfg.api_key or hcfg.base_url):print("\n Connection... ", end="", flush=True)@@ -1222,24 +978,13 @@ def cmd_status(args) -> None:except Exception as e:print(f"FAILED ({e})\n")else:- reason = "disabled" if not hcfg.enabled else "no API key or base URL"- print(f"\n Not connected ({reason})\n")+ print(f"\n Not connected ({'disabled' if not hcfg.enabled else 'no API key or base URL'})\n")def _show_peer_cards(hcfg, client) -> None:- """Fetch and display peer cards for the active profile.-- Uses get_or_create to ensure the session exists with peers configured.- This is idempotent -- if the session already exists on the server it's- just retrieved, not duplicated.- """+ """Fetch and display peer cards for the active profile."""try:- from plugins.memory.honcho.session import HonchoSessionManager- mgr = HonchoSessionManager(honcho=client, config=hcfg)- session_key = hcfg.resolve_session_name()- mgr.get_or_create(session_key)-- # User peer card+ mgr, session_key = _session_manager(hcfg, client)card = mgr.get_peer_card(session_key)if card:print(f"\n User peer card ({len(card)} facts):")@@ -1247,19 +992,11 @@ def _show_peer_cards(hcfg, client) -> None:print(f" - {fact}")if len(card) > 10:print(f" ... and {len(card) - 10} more")-- # AI peer representation- ai_rep = mgr.get_ai_representation(session_key)- ai_text = ai_rep.get("representation", "")+ ai_text = mgr.get_ai_representation(session_key).get("representation", "")if ai_text:- # Truncate to first 200 chars- display = ai_text[:200] + ("..." if len(ai_text) > 200 else "")- print("\n AI peer representation:")- print(f" {display}")-+ print(f"\n AI peer representation:\n {ai_text[:200] + ('...' if len(ai_text) > 200 else '')}")if not card and not ai_text:print("\n No peer data yet (accumulates after first conversation)")-print()except Exception as e:print(f"\n Peer data unavailable: {e}\n")@@ -1270,24 +1007,17 @@ def _cmd_status_all() -> None:rows = _all_profile_host_configs()cfg = _read_config()active = _active_profile_name()-- print(f"\nHoncho profiles ({len(rows)})\n" + "─" * 55)- print(f" {'Profile':<14} {'Host':<22} {'Enabled':<9} {'Recall':<9} {'Write'}")- print(f" {'─' * 14} {'─' * 22} {'─' * 9} {'─' * 9} {'─' * 9}")-+ print(f"\nHoncho profiles ({len(rows)})\n{'─' * 55}\n"+ f" {'Profile':<14} {'Host':<22} {'Enabled':<9} {'Recall':<9} {'Write'}\n"+ f" {'─' * 14} {'─' * 22} {'─' * 9} {'─' * 9} {'─' * 9}")for name, host, block in rows:enabled = block.get("enabled", cfg.get("enabled"))if enabled is None:- has_creds = bool(cfg.get("apiKey") or os.environ.get("HONCHO_API_KEY"))- enabled = has_creds if block else False- enabled_str = "yes" if enabled else "no"-- recall = block.get("recallMode") or cfg.get("recallMode", "hybrid")- write = block.get("writeFrequency") or cfg.get("writeFrequency", "async")-+ enabled = _default_block_and_key(cfg)[1] if block else False+ recall = _pref(block, cfg, "recallMode", "hybrid")+ write = _pref(block, cfg, "writeFrequency", "async")marker = " *" if name == active else ""- print(f" {name + marker:<14} {host:<22} {enabled_str:<9} {recall:<9} {write}")-+ print(f" {name + marker:<14} {host:<22} {'yes' if enabled else 'no':<9} {recall:<9} {write}")print("\n * active profile\n")@@ -1295,35 +1025,28 @@ def cmd_peers(args) -> None:"""Show peer identities across all profiles."""rows = _all_profile_host_configs()cfg = _read_config()-- print(f"\nHoncho peer identities ({len(rows)} profiles)\n" + "─" * 50)- print(f" {'Profile':<14} {'User peer':<16} {'AI peer'}")- print(f" {'─' * 14} {'─' * 16} {'─' * 18}")-+ print(f"\nHoncho peer identities ({len(rows)} profiles)\n{'─' * 50}\n"+ f" {'Profile':<14} {'User peer':<16} {'AI peer'}\n {'─' * 14} {'─' * 16} {'─' * 18}")for name, host, block in rows:- user = block.get("peerName") or cfg.get("peerName") or "(not set)"- ai = block.get("aiPeer") or cfg.get("aiPeer") or host- print(f" {name:<14} {user:<16} {ai}")-+ user = _pref(block, cfg, "peerName") or "(not set)"+ print(f" {name:<14} {user:<16} {_pref(block, cfg, 'aiPeer') or host}")print()+# ── sessions / map ─────────────────────────────────────────────────────────+def cmd_sessions(args) -> None:"""List known directory → session name mappings."""cfg = _read_config()sessions = cfg.get("sessions", {})-if not sessions:- print(" No session mappings configured.\n")- print(" Add one with: hermes honcho map <session-name>")- print(f" Or edit {_config_path()} directly.\n")+ print(f" No session mappings configured.\n\n Add one with: hermes honcho map <session-name>\n"+ f" Or edit {_config_path()} directly.\n")return-cwd = os.getcwd()- print(f"\nHoncho session mappings ({len(sessions)})\n" + "─" * 40)+ print(f"\nHoncho session mappings ({len(sessions)})\n" + RULE)for path, name in sorted(sessions.items()):- marker = " ←" if path == cwd else ""- print(f" {name:<30} {path}{marker}")+ print(f" {name:<30} {path}{' ←' if path == cwd else ''}")print()@@ -1332,194 +1055,125 @@ def cmd_map(args) -> None:if not args.session_name:cmd_sessions(args)return-- cwd = os.getcwd()session_name = args.session_name.strip()-if not session_name:print(" Session name cannot be empty.\n")return-import resanitized = re.sub(r'[^a-zA-Z0-9_-]', '-', session_name).strip('-')if sanitized != session_name:print(f" Session name sanitized to: {sanitized}")session_name = sanitized-+ cwd = os.getcwd()cfg = _read_config()cfg.setdefault("sessions", {})[cwd] = session_name_write_config(cfg)print(f" Mapped {cwd}\n → {session_name}\n")+# ── peer / mode / strategy / tokens ────────────────────────────────────────+def cmd_peer(args) -> None:"""Show or update peer names and dialectic reasoning level."""cfg = _read_config()- changed = False-user_name = getattr(args, "user", None)ai_name = getattr(args, "ai", None)reasoning = getattr(args, "reasoning", None)- REASONING_LEVELS = ("minimal", "low", "medium", "high", "max")-if user_name is None and ai_name is None and reasoning is None:- # Show current values- hosts = cfg.get("hosts", {})- hermes = hosts.get(_host_key(), {})- user = hermes.get('peerName') or cfg.get('peerName') or '(not set)'- ai = hermes.get('aiPeer') or cfg.get('aiPeer') or _host_key()- lvl = hermes.get("dialecticReasoningLevel") or cfg.get("dialecticReasoningLevel") or "low"- max_chars = hermes.get("dialecticMaxChars") or cfg.get("dialecticMaxChars") or 600- print("\nHoncho peers\n" + "─" * 40)- print(f" User peer: {user}")- print(" Your identity in Honcho. Messages you send build this peer's card.")- print(f" AI peer: {ai}")- print(" Hermes' identity in Honcho. Seed with 'hermes honcho identity <file>'.")- print(" Dialectic calls ask this peer questions to warm session context.")- print()- print(f" Dialectic reasoning: {lvl} ({', '.join(REASONING_LEVELS)})")- print(f" Dialectic cap: {max_chars} chars\n")+ hermes = _active_block(cfg)+ print(f"""+Honcho peers+{RULE}+ User peer: {_pref(hermes, cfg, 'peerName') or '(not set)'}+ Your identity in Honcho. Messages you send build this peer's card.+ AI peer: {_pref(hermes, cfg, 'aiPeer') or _host_key()}+ Hermes' identity in Honcho. Seed with 'hermes honcho identity <file>'.+ Dialectic calls ask this peer questions to warm session context.++ Dialectic reasoning: {_pref(hermes, cfg, 'dialecticReasoningLevel') or 'low'} ({', '.join(REASONING_LEVELS)})+ Dialectic cap: {_pref(hermes, cfg, 'dialecticMaxChars') or 600} chars+""")return- host = _host_key()- label = f"[{host}] " if host != "hermes" else ""-if user_name is not None:- cfg.setdefault("hosts", {}).setdefault(host, {})["peerName"] = user_name.strip()- changed = True- print(f" {label}User peer -> {user_name.strip()}")-+ _set_field(cfg, "peerName", user_name.strip(), f"User peer -> {user_name.strip()}")if ai_name is not None:- cfg.setdefault("hosts", {}).setdefault(host, {})["aiPeer"] = ai_name.strip()- changed = True- print(f" {label}AI peer -> {ai_name.strip()}")-+ _set_field(cfg, "aiPeer", ai_name.strip(), f"AI peer -> {ai_name.strip()}")if reasoning is not None:if reasoning not in REASONING_LEVELS:print(f" Invalid reasoning level '{reasoning}'. Options: {', '.join(REASONING_LEVELS)}")return- cfg.setdefault("hosts", {}).setdefault(host, {})["dialecticReasoningLevel"] = reasoning- changed = True- print(f" {label}Dialectic reasoning level -> {reasoning}")+ _set_field(cfg, "dialecticReasoningLevel", reasoning, f"Dialectic reasoning level -> {reasoning}")+ _save(cfg)- if changed:- _write_config(cfg)- print(f" Saved to {_config_path()}\n")--def cmd_mode(args) -> None:- """Show or set the recall mode."""- MODES = {- "hybrid": "auto-injected context + Honcho tools available (default)",- "context": "auto-injected context only, Honcho tools hidden",- "tools": "Honcho tools only, no auto-injected context",- }+def _show_or_set_choice(args, *, attr: str, key: str, noun: str, title: str, choices: dict,+ default: str, width: int) -> None:+ """Shared body of ``mode`` / ``strategy``: list choices, or set one on the active host."""cfg = _read_config()- mode_arg = getattr(args, "mode", None)-- if mode_arg is None:- current = (- (cfg.get("hosts") or {}).get(_host_key(), {}).get("recallMode")- or cfg.get("recallMode")- or "hybrid"- )- print("\nHoncho recall mode\n" + "─" * 40)- for m, desc in MODES.items():- marker = " <-" if m == current else ""- print(f" {m:<10} {desc}{marker}")- print("\n Set with: hermes honcho mode [hybrid|context|tools]\n")+ value = getattr(args, attr, None)+ if value is None:+ current = _pref(_active_block(cfg), cfg, key) or default+ print(f"\nHoncho {title}\n" + RULE)+ for m, desc in choices.items():+ print(f" {m:<{width}} {desc}{' <-' if m == current else ''}")+ print(f"\n Set with: hermes honcho {attr} [{'|'.join(choices)}]\n")return-- if mode_arg not in MODES:- print(f" Invalid mode '{mode_arg}'. Options: {', '.join(MODES)}\n")+ if value not in choices:+ print(f" Invalid {noun} '{value}'. Options: {', '.join(choices)}\n")return-host = _host_key()- label = f"[{host}] " if host != "hermes" else ""- cfg.setdefault("hosts", {}).setdefault(host, {})["recallMode"] = mode_arg+ cfg.setdefault("hosts", {}).setdefault(host, {})[key] = value_write_config(cfg)- print(f" {label}Recall mode -> {mode_arg} ({MODES[mode_arg]})\n")-+ print(f" {_label(host)}{title[0].upper() + title[1:]} -> {value} ({choices[value]})\n")-def cmd_strategy(args) -> None:- """Show or set the session strategy."""- STRATEGIES = {- "per-session": "each run starts clean, Honcho injects context automatically",- "per-directory": "reuses session per dir, prior context auto-injected each run",- "per-repo": "one session per git repository",- "global": "single session across all directories",- }- cfg = _read_config()- strat_arg = getattr(args, "strategy", None)- if strat_arg is None:- current = (- (cfg.get("hosts") or {}).get(_host_key(), {}).get("sessionStrategy")- or cfg.get("sessionStrategy")- or "per-session"- )- print("\nHoncho session strategy\n" + "─" * 40)- for s, desc in STRATEGIES.items():- marker = " <-" if s == current else ""- print(f" {s:<15} {desc}{marker}")- print("\n Set with: hermes honcho strategy [per-session|per-directory|per-repo|global]\n")- return+def cmd_mode(args) -> None:+ """Show or set the recall mode."""+ _show_or_set_choice(args, attr="mode", key="recallMode", noun="mode", title="recall mode",+ choices=_MODES, default="hybrid", width=10)- if strat_arg not in STRATEGIES:- print(f" Invalid strategy '{strat_arg}'. Options: {', '.join(STRATEGIES)}\n")- return- host = _host_key()- label = f"[{host}] " if host != "hermes" else ""- cfg.setdefault("hosts", {}).setdefault(host, {})["sessionStrategy"] = strat_arg- _write_config(cfg)- print(f" {label}Session strategy -> {strat_arg} ({STRATEGIES[strat_arg]})\n")+def cmd_strategy(args) -> None:+ """Show or set the session strategy."""+ _show_or_set_choice(args, attr="strategy", key="sessionStrategy", noun="strategy",+ title="session strategy", choices=_STRATEGIES, default="per-session", width=15)def cmd_tokens(args) -> None:"""Show or set token budget settings."""cfg = _read_config()- hosts = cfg.get("hosts", {})- hermes = hosts.get(_host_key(), {})-context = getattr(args, "context", None)dialectic = getattr(args, "dialectic", None)-if context is None and dialectic is None:- ctx_tokens = hermes.get("contextTokens") or cfg.get("contextTokens") or "(Honcho default)"- d_chars = hermes.get("dialecticMaxChars") or cfg.get("dialecticMaxChars") or 600- d_level = hermes.get("dialecticReasoningLevel") or cfg.get("dialecticReasoningLevel") or "low"- print("\nHoncho budgets\n" + "─" * 40)- print()- print(f" Context {ctx_tokens} tokens")- print(" Raw memory retrieval. Honcho returns stored facts/history about")- print(" the user and session, injected directly into the system prompt.")- print()- print(f" Dialectic {d_chars} chars, reasoning: {d_level}")- print(" AI-to-AI inference. Hermes asks Honcho's AI peer a question")- print(" (e.g. \"what were we working on?\") and Honcho runs its own model")- print(" to synthesize an answer. Used for first-turn session continuity.")- print(" Level controls how much reasoning Honcho spends on the answer.")- print("\n Set with: hermes honcho tokens [--context N] [--dialectic N]\n")+ hermes = _active_block(cfg)+ print(f"""+Honcho budgets+{RULE}++ Context {_pref(hermes, cfg, 'contextTokens') or '(Honcho default)'} tokens+ Raw memory retrieval. Honcho returns stored facts/history about+ the user and session, injected directly into the system prompt.++ Dialectic {_pref(hermes, cfg, 'dialecticMaxChars') or 600} chars, reasoning: {_pref(hermes, cfg, 'dialecticReasoningLevel') or 'low'}+ AI-to-AI inference. Hermes asks Honcho's AI peer a question+ (e.g. "what were we working on?") and Honcho runs its own model+ to synthesize an answer. Used for first-turn session continuity.+ Level controls how much reasoning Honcho spends on the answer.++ Set with: hermes honcho tokens [--context N] [--dialectic N]+""")return- host = _host_key()- label = f"[{host}] " if host != "hermes" else ""- changed = Falseif context is not None:- cfg.setdefault("hosts", {}).setdefault(host, {})["contextTokens"] = context- print(f" {label}context tokens -> {context}")- changed = True+ _set_field(cfg, "contextTokens", context, f"context tokens -> {context}")if dialectic is not None:- cfg.setdefault("hosts", {}).setdefault(host, {})["dialecticMaxChars"] = dialectic- print(f" {label}dialectic cap -> {dialectic} chars")- changed = True+ _set_field(cfg, "dialecticMaxChars", dialectic, f"dialectic cap -> {dialectic} chars")+ _save(cfg)- if changed:- _write_config(cfg)- print(f" Saved to {_config_path()}\n")+# ── identity / migrate ─────────────────────────────────────────────────────def cmd_identity(args) -> None:"""Seed AI peer identity or show both peer representations."""@@ -1527,23 +1181,15 @@ def cmd_identity(args) -> None:if not _resolve_api_key(cfg):print(" No API key configured. Run 'hermes honcho setup' first.\n")return-file_path = getattr(args, "file", None)- show = getattr(args, "show", False)-try:- from plugins.memory.honcho.client import HonchoClientConfig, get_honcho_client- from plugins.memory.honcho.session import HonchoSessionManager- hcfg = HonchoClientConfig.from_global_config(host=_host_key())- client = get_honcho_client(hcfg)- mgr = HonchoSessionManager(honcho=client, config=hcfg)- session_key = hcfg.resolve_session_name()- mgr.get_or_create(session_key)+ hcfg, client = _connect(_host_key())+ mgr, session_key = _session_manager(hcfg, client)except Exception as e:print(f" Honcho connection failed: {e}\n")return- if show:+ if getattr(args, "show", False):from plugins.memory.honcho.session import HonchoAuthErrortry:user_card = mgr.get_peer_card(session_key)@@ -1551,122 +1197,117 @@ def cmd_identity(args) -> None:except HonchoAuthError as e:print(f" Honcho authentication failed: {e}\n")return-- # ── User peer ────────────────────────────────────────────────────────- print(f"\nUser peer ({hcfg.peer_name or 'not set'})\n" + "─" * 40)+ print(f"\nUser peer ({hcfg.peer_name or 'not set'})\n" + RULE)if user_card:for fact in user_card:print(f" {fact}")else:print(" No user peer card yet. Send a few messages to build one.")-- # ── AI peer ──────────────────────────────────────────────────────────- print(f"\nAI peer ({hcfg.ai_peer})\n" + "─" * 40)- if ai_rep.get("representation"):- print(ai_rep["representation"])- elif ai_rep.get("card"):- print(ai_rep["card"])- else:- print(" No representation built yet.")- print(" Run 'hermes honcho identity <file>' to seed one.")+ print(f"\nAI peer ({hcfg.ai_peer})\n" + RULE)+ print(ai_rep.get("representation") or ai_rep.get("card")+ or " No representation built yet.\n Run 'hermes honcho identity <file>' to seed one.")print()returnif not file_path:- print("\nHoncho identity management\n" + "─" * 40)- print(f" User peer: {hcfg.peer_name or 'not set'}")- print(f" AI peer: {hcfg.ai_peer}")- print()- print(" hermes honcho identity --show — show both peer representations")- print(" hermes honcho identity <file> — seed AI peer from SOUL.md or any .md/.txt\n")+ print(f"""+Honcho identity management+{RULE}+ User peer: {hcfg.peer_name or 'not set'}+ AI peer: {hcfg.ai_peer}++ hermes honcho identity --show — show both peer representations+ hermes honcho identity <file> — seed AI peer from SOUL.md or any .md/.txt+""")return- from pathlib import Pathp = Path(file_path).expanduser()if not p.exists():print(f" File not found: {p}\n")return-content = p.read_text(encoding="utf-8").strip()if not content:print(f" File is empty: {p}\n")return-- source = p.name- ok = mgr.seed_ai_identity(session_key, content, source=source)- if ok:- print(f" Seeded AI peer identity from {p.name} into session '{session_key}'")- print(f" Honcho will incorporate this into {hcfg.ai_peer}'s representation over time.\n")+ if mgr.seed_ai_identity(session_key, content, source=p.name):+ print(f" Seeded AI peer identity from {p.name} into session '{session_key}'\n"+ f" Honcho will incorporate this into {hcfg.ai_peer}'s representation over time.\n")else:print(" Failed to seed identity. Check logs for details.\n")-def cmd_migrate(args) -> None:- """Step-by-step migration guide: OpenClaw native memory → Hermes + Honcho."""- from pathlib import Path+def _find_memory_files(names: list[str]) -> list[Path]:+ """Existing files named ``names`` in cwd then ~/.openclaw, deduplicated."""+ found: list[Path] = []+ for name in names:+ for d in (Path(os.getcwd()), Path.home() / ".openclaw"):+ p = d / name+ if p.exists() and p not in found:+ found.append(p)+ return found- # ── Detect OpenClaw native memory files ──────────────────────────────────- cwd = Path(os.getcwd())- openclaw_home = Path.home() / ".openclaw"- # User peer: facts about the user- user_file_names = ["USER.md", "MEMORY.md"]- # AI peer: agent identity / configuration- agent_file_names = ["SOUL.md", "IDENTITY.md", "AGENTS.md", "TOOLS.md", "BOOTSTRAP.md"]+def _migrate_upload(mgr, session_key: str, user_files: list[Path]) -> None:+ dirs_with_files = set(str(f.parent) for f in user_files)+ if any([mgr.migrate_memory_files(session_key, d) for d in dirs_with_files]):+ print(f" Uploaded user memory files from: {', '.join(dirs_with_files)}")+ else:+ print(" Nothing uploaded (files may already be migrated or empty).")- user_files: list[Path] = []- agent_files: list[Path] = []- for name in user_file_names:- for d in [cwd, openclaw_home]:- p = d / name- if p.exists() and p not in user_files:- user_files.append(p)- for name in agent_file_names:- for d in [cwd, openclaw_home]:- p = d / name- if p.exists() and p not in agent_files:- agent_files.append(p)+def _migrate_seed(mgr, session_key: str, agent_files: list[Path]) -> None:+ for f in agent_files:+ content = f.read_text(encoding="utf-8").strip()+ if content:+ ok = mgr.seed_ai_identity(session_key, content, source=f.name)+ print(f" {f.name}: {'seeded' if ok else 'failed'}")+++def _offer(question: str, action, files: list[Path]) -> None:+ """Ask, then run ``action(mgr, session_key, files)`` against a fresh client."""+ if _yes(_prompt(question, default="y")):+ try:+ hcfg, client = _connect(None, reset=True)+ action(*_session_manager(hcfg, client), files)+ except Exception as e:+ print(f" Failed: {e}")+++def cmd_migrate(args) -> None:+ """Step-by-step migration guide: OpenClaw native memory → Hermes + Honcho."""+ user_files = _find_memory_files(["USER.md", "MEMORY.md"]) # facts about the user+ agent_files = _find_memory_files(["SOUL.md", "IDENTITY.md", "AGENTS.md", "TOOLS.md", "BOOTSTRAP.md"])cfg = _read_config()has_key = bool(_resolve_api_key(cfg))print("\nHoncho migration: OpenClaw native memory → Hermes\n" + "─" * 50)- print()- print(" OpenClaw's native memory stores context in local markdown files")- print(" (USER.md, MEMORY.md, SOUL.md, ...) and injects them via QMD search.")- print(" Honcho replaces that with a cloud-backed, LLM-observable memory layer:")- print(" context is retrieved semantically, injected automatically each turn,")- print(" and enriched by a dialectic reasoning layer that builds over time.")- print()-- # ── Step 1: Honcho account ────────────────────────────────────────────────- print("Step 1 Create a Honcho account")- print()+ print("""+ OpenClaw's native memory stores context in local markdown files+ (USER.md, MEMORY.md, SOUL.md, ...) and injects them via QMD search.+ Honcho replaces that with a cloud-backed, LLM-observable memory layer:+ context is retrieved semantically, injected automatically each turn,+ and enriched by a dialectic reasoning layer that builds over time.++Step 1 Create a Honcho account+""")if has_key:- masked = f"...{cfg['apiKey'][-8:]}" if len(cfg["apiKey"]) > 8 else "set"- print(f" Honcho API key already configured: {masked}")- print(" Skip to Step 2.")+ print(f" Honcho API key already configured: {_mask(cfg['apiKey'])}\n Skip to Step 2.")else:- print(" Honcho is a cloud memory service that gives Hermes persistent memory")- print(" across sessions. You need an API key to use it.")- print()- print(" 1. Get your API key at https://app.honcho.dev")- print(" 2. Run: hermes honcho setup")- print(" Paste the key when prompted.")- print()- answer = _prompt(" Run 'hermes honcho setup' now?", default="y")- if answer.lower() in {"y", "yes"}:+ print(""" Honcho is a cloud memory service that gives Hermes persistent memory+ across sessions. You need an API key to use it.++ 1. Get your API key at https://app.honcho.dev+ 2. Run: hermes honcho setup+ Paste the key when prompted.+""")+ if _yes(_prompt(" Run 'hermes honcho setup' now?", default="y")):cmd_setup(args)cfg = _read_config()has_key = bool(cfg.get("apiKey", ""))else:- print()- print(" Run 'hermes honcho setup' when ready, then re-run this walkthrough.")+ print("\n Run 'hermes honcho setup' when ready, then re-run this walkthrough.")- # ── Step 2: Detected files ────────────────────────────────────────────────- print()- print("Step 2 Detected OpenClaw memory files")- print()+ print("\nStep 2 Detected OpenClaw memory files\n")if user_files or agent_files:if user_files:print(f" User memory ({len(user_files)} file(s)) — will go to Honcho user peer:")@@ -1677,300 +1318,174 @@ def cmd_migrate(args) -> None:for f in agent_files:print(f" {f}")else:- print(" No OpenClaw native memory files found in cwd or ~/.openclaw/.")- print(" If your files are elsewhere, copy them here before continuing,")- print(" or seed them manually: hermes honcho identity <path/to/file>")+ print(" No OpenClaw native memory files found in cwd or ~/.openclaw/.\n"+ " If your files are elsewhere, copy them here before continuing,\n"+ " or seed them manually: hermes honcho identity <path/to/file>")- # ── Step 3: Migrate user memory ───────────────────────────────────────────- print()- print("Step 3 Migrate user memory files → Honcho user peer")- print()- print(" USER.md and MEMORY.md contain facts about you that the agent should")- print(" remember across sessions. Honcho will store these under your user peer")- print(" and inject relevant excerpts into the system prompt automatically.")- print()+ print("""+Step 3 Migrate user memory files → Honcho user peer++ USER.md and MEMORY.md contain facts about you that the agent should+ remember across sessions. Honcho will store these under your user peer+ and inject relevant excerpts into the system prompt automatically.+""")if user_files:print(f" Found: {', '.join(f.name for f in user_files)}")- print()- print(" These are picked up automatically the first time you run 'hermes'")- print(" with Honcho configured and no prior session history.")- print(" (Hermes calls migrate_memory_files() on first session init.)")- print()- print(" If you want to migrate them now without starting a session:")- for f in user_files:+ print("""+ These are picked up automatically the first time you run 'hermes'+ with Honcho configured and no prior session history.+ (Hermes calls migrate_memory_files() on first session init.)++ If you want to migrate them now without starting a session:""")+ for _f in user_files:print(" hermes honcho migrate — this step handles it interactively")if has_key:- answer = _prompt(" Upload user memory files to Honcho now?", default="y")- if answer.lower() in {"y", "yes"}:- try:- from plugins.memory.honcho.client import (- HonchoClientConfig,- get_honcho_client,- reset_honcho_client,- )- from plugins.memory.honcho.session import HonchoSessionManager-- reset_honcho_client()- hcfg = HonchoClientConfig.from_global_config()- client = get_honcho_client(hcfg)- mgr = HonchoSessionManager(honcho=client, config=hcfg)- session_key = hcfg.resolve_session_name()- mgr.get_or_create(session_key)- # Upload from each directory that had user files- dirs_with_files = set(str(f.parent) for f in user_files)- any_uploaded = False- for d in dirs_with_files:- if mgr.migrate_memory_files(session_key, d):- any_uploaded = True- if any_uploaded:- print(f" Uploaded user memory files from: {', '.join(dirs_with_files)}")- else:- print(" Nothing uploaded (files may already be migrated or empty).")- except Exception as e:- print(f" Failed: {e}")+ _offer(" Upload user memory files to Honcho now?", _migrate_upload, user_files)else:print(" Run 'hermes honcho setup' first, then re-run this step.")else:print(" No user memory files detected. Nothing to migrate here.")- # ── Step 4: Seed AI identity ──────────────────────────────────────────────- print()- print("Step 4 Seed AI identity files → Honcho AI peer")- print()- print(" SOUL.md, IDENTITY.md, AGENTS.md, TOOLS.md, BOOTSTRAP.md define the")- print(" agent's character, capabilities, and behavioral rules. In OpenClaw")- print(" these are injected via file search at prompt-build time.")- print()- print(" In Hermes, they are seeded once into Honcho's AI peer through the")- print(" observation pipeline. Honcho builds a representation from them and")- print(" from every subsequent assistant message (observe_me=True). Over time")- print(" the representation reflects actual behavior, not just declaration.")- print()+ print("""+Step 4 Seed AI identity files → Honcho AI peer++ SOUL.md, IDENTITY.md, AGENTS.md, TOOLS.md, BOOTSTRAP.md define the+ agent's character, capabilities, and behavioral rules. In OpenClaw+ these are injected via file search at prompt-build time.++ In Hermes, they are seeded once into Honcho's AI peer through the+ observation pipeline. Honcho builds a representation from them and+ from every subsequent assistant message (observe_me=True). Over time+ the representation reflects actual behavior, not just declaration.+""")if agent_files:print(f" Found: {', '.join(f.name for f in agent_files)}")print()if has_key:- answer = _prompt(" Seed AI identity from all detected files now?", default="y")- if answer.lower() in {"y", "yes"}:- try:- from plugins.memory.honcho.client import (- HonchoClientConfig,- get_honcho_client,- reset_honcho_client,- )- from plugins.memory.honcho.session import HonchoSessionManager-- reset_honcho_client()- hcfg = HonchoClientConfig.from_global_config()- client = get_honcho_client(hcfg)- mgr = HonchoSessionManager(honcho=client, config=hcfg)- session_key = hcfg.resolve_session_name()- mgr.get_or_create(session_key)- for f in agent_files:- content = f.read_text(encoding="utf-8").strip()- if content:- ok = mgr.seed_ai_identity(session_key, content, source=f.name)- status = "seeded" if ok else "failed"- print(f" {f.name}: {status}")- except Exception as e:- print(f" Failed: {e}")+ _offer(" Seed AI identity from all detected files now?", _migrate_seed, agent_files)else:print(" Run 'hermes honcho setup' first, then seed manually:")for f in agent_files:print(f" hermes honcho identity {f}")else:- print(" No agent identity files detected.")- print(" To seed manually: hermes honcho identity <path/to/SOUL.md>")-- # ── Step 5: What changes ──────────────────────────────────────────────────- print()- print("Step 5 What changes vs. OpenClaw native memory")- print()- print(" Storage")- print(" OpenClaw: markdown files on disk, searched via QMD at prompt-build time.")- print(" Hermes: cloud-backed Honcho peers. Files can stay on disk as source")- print(" of truth; Honcho holds the live representation.")- print()- print(" Context injection")- print(" OpenClaw: file excerpts injected synchronously before each LLM call.")- print(" Hermes: Honcho context fetched async at turn end, injected next turn.")- print(" First turn has no Honcho context; subsequent turns are loaded.")- print()- print(" Memory growth")- print(" OpenClaw: you edit files manually to update memory.")- print(" Hermes: Honcho observes every message and updates representations")- print(" automatically. Files become the seed, not the live store.")- print()- print(" Honcho tools (available to the agent during conversation)")- print(" honcho_context — session context: summary, representation, card, messages")- print(" honcho_search — semantic search over stored context")- print(" honcho_profile — fast peer card snapshot")- print(" honcho_reasoning — ask Honcho a question, synthesized answer")- print(" honcho_conclude — write a conclusion/fact back to memory")- print()- print(" Session naming")- print(" OpenClaw: no persistent session concept — files are global.")- print(" Hermes: per-session by default — each run gets its own session")- print(" Map a custom name: hermes honcho map <session-name>")-- # ── Step 6: Next steps ────────────────────────────────────────────────────- print()- print("Step 6 Next steps")- print()+ print(" No agent identity files detected.\n To seed manually: hermes honcho identity <path/to/SOUL.md>")++ print("""+Step 5 What changes vs. OpenClaw native memory++ Storage+ OpenClaw: markdown files on disk, searched via QMD at prompt-build time.+ Hermes: cloud-backed Honcho peers. Files can stay on disk as source+ of truth; Honcho holds the live representation.++ Context injection+ OpenClaw: file excerpts injected synchronously before each LLM call.+ Hermes: Honcho context fetched async at turn end, injected next turn.+ First turn has no Honcho context; subsequent turns are loaded.++ Memory growth+ OpenClaw: you edit files manually to update memory.+ Hermes: Honcho observes every message and updates representations+ automatically. Files become the seed, not the live store.++ Honcho tools (available to the agent during conversation)+ honcho_context — session context: summary, representation, card, messages+ honcho_search — semantic search over stored context+ honcho_profile — fast peer card snapshot+ honcho_reasoning — ask Honcho a question, synthesized answer+ honcho_conclude — write a conclusion/fact back to memory++ Session naming+ OpenClaw: no persistent session concept — files are global.+ Hermes: per-session by default — each run gets its own session+ Map a custom name: hermes honcho map <session-name>++Step 6 Next steps+""")if not has_key:- print(" 1. hermes honcho setup — configure API key (required)")- print(" 2. hermes honcho migrate — re-run this walkthrough")+ print(" 1. hermes honcho setup — configure API key (required)\n"+ " 2. hermes honcho migrate — re-run this walkthrough")else:- print(" 1. hermes honcho status — verify Honcho connection")- print(" 2. hermes — start a session")- print(" (user memory files auto-uploaded on first turn if not done above)")- print(" 3. hermes honcho identity --show — verify AI peer representation")- print(" 4. hermes honcho tokens — tune context and dialectic budgets")- print(" 5. hermes honcho mode — view or change memory mode")+ print(""" 1. hermes honcho status — verify Honcho connection+ 2. hermes — start a session+ (user memory files auto-uploaded on first turn if not done above)+ 3. hermes honcho identity --show — verify AI peer representation+ 4. hermes honcho tokens — tune context and dialectic budgets+ 5. hermes honcho mode — view or change memory mode""")print()+# ── dispatch / argparse ────────────────────────────────────────────────────++# (subcommand, help, handler, ((arg, kwargs), ...)); order defines --help order.+_SUBCOMMANDS = (+ ("setup", "Initial Honcho setup (redirects to hermes memory setup)", None, ()),+ ("status", "Show current Honcho config and connection status", cmd_status, (+ ("--all", dict(action="store_true", help="Show config overview across all profiles")),+ )),+ ("peers", "Show peer identities across all profiles", cmd_peers, ()),+ ("sessions", "List known Honcho session mappings", cmd_sessions, ()),+ ("map", "Map current directory to a Honcho session name (no arg = list mappings)", cmd_map, (+ ("session_name", dict(nargs="?", default=None,+ help="Session name to associate with this directory. Omit to list current mappings.")),+ )),+ ("peer", "Show or update peer names and dialectic reasoning level", cmd_peer, (+ ("--user", dict(metavar="NAME", help="Set user peer name")),+ ("--ai", dict(metavar="NAME", help="Set AI peer name")),+ ("--reasoning", dict(metavar="LEVEL", choices=REASONING_LEVELS,+ help="Set default dialectic reasoning level (minimal/low/medium/high/max)")),+ )),+ ("mode", "Show or set recall mode (hybrid/context/tools)", cmd_mode, (+ ("mode", dict(nargs="?", metavar="MODE", choices=tuple(_MODES),+ help="Recall mode to set (hybrid/context/tools). Omit to show current.")),+ )),+ ("strategy", "Show or set session strategy (per-session/per-directory/per-repo/global)", cmd_strategy, (+ ("strategy", dict(nargs="?", metavar="STRATEGY", choices=tuple(_STRATEGIES),+ help="Session strategy to set. Omit to show current.")),+ )),+ ("tokens", "Show or set token budget for context and dialectic", cmd_tokens, (+ ("--context", dict(type=int, metavar="N", help="Max tokens Honcho returns from session.context() per turn")),+ ("--dialectic", dict(type=int, metavar="N", help="Max chars of dialectic result to inject into system prompt")),+ )),+ ("identity", "Seed or show the AI peer's Honcho identity representation", cmd_identity, (+ ("file", dict(nargs="?", default=None, help="Path to file to seed from (e.g. SOUL.md). Omit to show usage.")),+ ("--show", dict(action="store_true", help="Show current AI peer representation from Honcho")),+ )),+ ("migrate", "Step-by-step migration guide from openclaw-honcho to Hermes Honcho", cmd_migrate, ()),+ ("enable", "Enable Honcho for the active profile", cmd_enable, ()),+ ("disable", "Disable Honcho for the active profile", cmd_disable, ()),+ ("sync", "Sync Honcho config to all existing profiles", cmd_sync, ()),+)+_HANDLERS = {name: handler for name, _help, handler, _args in _SUBCOMMANDS if handler}++def honcho_command(args) -> None:"""Route honcho subcommands."""global _profile_override_profile_override = getattr(args, "target_profile", None)-sub = getattr(args, "honcho_command", None)- if sub == "setup":- # Redirect to memory setup — honcho setup goes through the unified path- print("\n Honcho is configured via the memory provider system.")- print(" Running 'hermes memory setup'...\n")+ if sub == "setup": # honcho setup goes through the unified memory-provider path+ print("\n Honcho is configured via the memory provider system.\n Running 'hermes memory setup'...\n")from hermes_cli.memory_setup import cmd_setup_providercmd_setup_provider("honcho")return- elif sub is None:- cmd_status(args)- elif sub == "status":- cmd_status(args)- elif sub == "peers":- cmd_peers(args)- elif sub == "sessions":- cmd_sessions(args)- elif sub == "map":- cmd_map(args)- elif sub == "peer":- cmd_peer(args)- elif sub == "mode":- cmd_mode(args)- elif sub == "strategy":- cmd_strategy(args)- elif sub == "tokens":- cmd_tokens(args)- elif sub == "identity":- cmd_identity(args)- elif sub == "migrate":- cmd_migrate(args)- elif sub == "enable":- cmd_enable(args)- elif sub == "disable":- cmd_disable(args)- elif sub == "sync":- cmd_sync(args)- else:- print(f" Unknown honcho command: {sub}")- print(" Available: status, sessions, map, peer, mode, strategy, tokens, identity, migrate, enable, disable, sync\n")+ handler = cmd_status if sub is None else _HANDLERS.get(sub)+ if handler is None:+ print(f" Unknown honcho command: {sub}\n"+ " Available: status, sessions, map, peer, mode, strategy, tokens, identity, migrate, enable, disable, sync\n")+ return+ handler(args)def register_cli(subparser) -> None:- """Build the ``hermes honcho`` argparse subcommand tree.-- Called by the plugin CLI registration system during argparse setup.- The *subparser* is the parser for ``hermes honcho``.- """-+ """Build the ``hermes honcho`` argparse subcommand tree on the ``hermes honcho`` parser."""subparser.add_argument("--target-profile", metavar="NAME", dest="target_profile",help="Target a specific profile's Honcho config without switching",)subs = subparser.add_subparsers(dest="honcho_command")-- subs.add_parser(- "setup",- help="Initial Honcho setup (redirects to hermes memory setup)",- )-- status_parser = subs.add_parser(- "status", help="Show current Honcho config and connection status",- )- status_parser.add_argument(- "--all", action="store_true", help="Show config overview across all profiles",- )-- subs.add_parser("peers", help="Show peer identities across all profiles")- subs.add_parser("sessions", help="List known Honcho session mappings")-- map_parser = subs.add_parser(- "map", help="Map current directory to a Honcho session name (no arg = list mappings)",- )- map_parser.add_argument(- "session_name", nargs="?", default=None,- help="Session name to associate with this directory. Omit to list current mappings.",- )-- peer_parser = subs.add_parser(- "peer", help="Show or update peer names and dialectic reasoning level",- )- peer_parser.add_argument("--user", metavar="NAME", help="Set user peer name")- peer_parser.add_argument("--ai", metavar="NAME", help="Set AI peer name")- peer_parser.add_argument(- "--reasoning", metavar="LEVEL",- choices=("minimal", "low", "medium", "high", "max"),- help="Set default dialectic reasoning level (minimal/low/medium/high/max)",- )-- mode_parser = subs.add_parser(- "mode", help="Show or set recall mode (hybrid/context/tools)",- )- mode_parser.add_argument(- "mode", nargs="?", metavar="MODE",- choices=("hybrid", "context", "tools"),- help="Recall mode to set (hybrid/context/tools). Omit to show current.",- )-- strategy_parser = subs.add_parser(- "strategy", help="Show or set session strategy (per-session/per-directory/per-repo/global)",- )- strategy_parser.add_argument(- "strategy", nargs="?", metavar="STRATEGY",- choices=("per-session", "per-directory", "per-repo", "global"),- help="Session strategy to set. Omit to show current.",- )-- tokens_parser = subs.add_parser(- "tokens", help="Show or set token budget for context and dialectic",- )- tokens_parser.add_argument(- "--context", type=int, metavar="N",- help="Max tokens Honcho returns from session.context() per turn",- )- tokens_parser.add_argument(- "--dialectic", type=int, metavar="N",- help="Max chars of dialectic result to inject into system prompt",- )-- identity_parser = subs.add_parser(- "identity", help="Seed or show the AI peer's Honcho identity representation",- )- identity_parser.add_argument(- "file", nargs="?", default=None,- help="Path to file to seed from (e.g. SOUL.md). Omit to show usage.",- )- identity_parser.add_argument(- "--show", action="store_true",- help="Show current AI peer representation from Honcho",- )-- subs.add_parser(- "migrate",- help="Step-by-step migration guide from openclaw-honcho to Hermes Honcho",- )- subs.add_parser("enable", help="Enable Honcho for the active profile")- subs.add_parser("disable", help="Disable Honcho for the active profile")- subs.add_parser("sync", help="Sync Honcho config to all existing profiles")-+ for name, help_text, _handler, arguments in _SUBCOMMANDS:+ parser = subs.add_parser(name, help=help_text)+ for flag, kwargs in arguments:+ parser.add_argument(flag, **kwargs)subparser.set_defaults(func=honcho_command)diff --git a/plugins/memory/honcho/client.py b/plugins/memory/honcho/client.pyindex 8a2d019ddfc..4c717b4535b 100644--- a/plugins/memory/honcho/client.py+++ b/plugins/memory/honcho/client.py@@ -1,61 +1,61 @@"""Honcho client initialization and configuration.-Resolution order for config file:- 1. $HERMES_HOME/honcho.json (instance-local, enables isolated Hermes instances)- 2. ~/.honcho/config.json (global, shared across all Honcho-enabled apps)- 3. Environment variables (HONCHO_API_KEY, HONCHO_ENVIRONMENT)--Resolution order for host-specific settings:- 1. Explicit host block fields (always win)- 2. Flat/global fields from config root- 3. Defaults (host name as workspace/peer)+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."""from __future__ import annotations-import json-import os-import loggingimport hashlibimport ipaddress+import json+import logging+import os+import threading as _threadingfrom dataclasses import dataclass, fieldfrom pathlib import Path+from typing import TYPE_CHECKING, Any, Callablefrom urllib.parse import urlparsefrom agent.secret_scope import get_secret-from hermes_constants import get_hermes_homefrom hermes_cli.profiles import _get_default_hermes_home-from plugins.plugin_utils import SingletonSlot-from typing import Any, TYPE_CHECKING+from 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.+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,+)if TYPE_CHECKING:from honcho import Honchologger = logging.getLogger(__name__)+HOST = "hermes"+def _sanitize_url(url: str | None) -> str | None:- """Return url unchanged, or None if it contains non-printable ASCII characters.+ """Return url, or None (with a warning) if it carries non-printable ASCII.- A stray terminal escape sequence (e.g. \x1b from copy-paste) in a URL can- cause upstream SDKs to raise ``Invalid non-printable ASCII character`` at- client construction time. Dropping the bad value keeps Honcho disabled with- a clear warning rather than poisoning startup.+ A stray terminal escape in a pasted URL otherwise makes the SDK raise at+ client construction and poisons startup."""- if url is None:- return None- if all(0x20 <= ord(c) < 0x7F for c in url):+ if url is None or all(0x20 <= ord(c) < 0x7F for c in url):return url- logger.warning(- "Honcho base_url contains non-printable characters and will be ignored: %r",- url,- )+ logger.warning("Honcho base_url contains non-printable characters and will be ignored: %r", url)return None-HOST = "hermes"--def profile_host_key(profile: str | None) -> str:"""Return the safe Honcho host key for a Hermes profile."""if not profile or profile in {"default", "custom"}:@@ -70,48 +70,39 @@ def _host_block(raw: dict, host: str) -> dict:block = hosts.get(host, {})if block or not host.startswith(f"{HOST}_"):return block- legacy = f"{HOST}.{host[len(HOST) + 1:]}"- return hosts.get(legacy, {})+ return hosts.get(f"{HOST}.{host[len(HOST) + 1:]}", {})def resolve_active_host() -> str:- """Derive the Honcho host key from the active Hermes profile.+ """Derive the Honcho host key: HERMES_HONCHO_HOST env, else the active profile.- Resolution order:- 1. HERMES_HONCHO_HOST env var (explicit override)- 2. Active profile name via profiles system -> ``hermes_<profile>``- 3. defaultHost from the active config, but only for the default profile- 4. Fallback: ``"hermes"`` (default profile)+ The config's ``defaultHost`` is honored only for the default profile, so+ named profiles stay isolated instead of all sharing one host."""explicit = os.environ.get("HERMES_HONCHO_HOST", "").strip()if explicit:return explicit-try:from hermes_cli.profiles import get_active_profile_name- profile = get_active_profile_name()- profile_host = profile_host_key(profile)++ profile_host = profile_host_key(get_active_profile_name())except Exception:profile_host = HOST-- # Honcho's generic config can carry a defaultHost (for example "local"),- # but applying it before profile resolution makes every named Hermes- # profile share that same host. Keep named profiles isolated; only the- # default Hermes profile may opt into the config's default host.if profile_host == HOST:try:- path = resolve_config_path()- if path.exists():- raw = json.loads(path.read_text(encoding="utf-8"))- default_host = str(raw.get("defaultHost", "")).strip()- if default_host:- return default_host+ default_host = str(_read_config(resolve_config_path()).get("defaultHost", "")).strip()except Exception:- pass-+ default_host = ""+ if default_host:+ return default_hostreturn profile_host+def _read_config(path: Path) -> dict:+ """Parse a honcho.json; {} when absent (parse/OS errors propagate)."""+ return json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}++def resolve_global_config_path() -> Path:"""Return the shared Honcho config path for the current HOME."""return Path.home() / ".honcho" / "config.json"@@ -120,261 +111,243 @@ def resolve_global_config_path() -> Path:def resolve_config_path() -> Path:"""Return the active Honcho config path.- Resolution order:- 1. $HERMES_HOME/honcho.json (profile-local, if it exists)- 2. ~/.hermes/honcho.json (default profile — shared host blocks live here)- 3. ~/.honcho/config.json (global, cross-app interop)-- Returns the global path if none exist (for first-time setup writes).+ $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-- # Default profile's config — host blocks accumulate here via setup/clonedefault_path = _get_default_hermes_home() / "honcho.json"if default_path != local_path and default_path.exists():return default_path-return resolve_global_config_path()-_RECALL_MODE_ALIASES = {"auto": "hybrid"}-_VALID_RECALL_MODES = {"hybrid", "context", "tools"}-+# --- config coercion --------------------------------------------------------def _normalize_recall_mode(val: str) -> str:- """Normalize legacy recall mode values (e.g. 'auto' → 'hybrid')."""- val = _RECALL_MODE_ALIASES.get(val, val)- return val if val in _VALID_RECALL_MODES else "hybrid"+_RECALL_MODES = ({"auto": "hybrid"}, {"hybrid", "context", "tools"}, "hybrid")+_OBSERVATION_MODES = (+ {"shared": "unified", "separate": "directional", "cross": "directional"},+ {"unified", "directional"},+ "directional",+)+_VALID_REASONING_LEVELS = ("minimal", "low", "medium", "high", "max")+# Granular observation booleans derived from the legacy string mode; explicit+# per-peer config always wins over these presets.+_OBSERVATION_PRESETS = {+ "directional": {"user_observe_me": True, "user_observe_others": True, "ai_observe_me": True, "ai_observe_others": True},+ "unified": {"user_observe_me": True, "user_observe_others": False, "ai_observe_me": False, "ai_observe_others": True},+}-def _resolve_bool(*vals, default: bool) -> bool:- """Resolve a bool config field: first non-None wins, else default.- Variadic to support aliased keys (e.g. ``pinUserPeer`` shadowing- ``pinPeerName`` for backwards compatibility). Pass values in- precedence order: caller's preferred alias first, then fallback- aliases, in (host, root) interleaving as needed.- """- for val in vals:- if val is not None:- return bool(val)- return default+def _normalize_choice(val: str, spec: tuple[dict, set, str]) -> str:+ """Map aliases, then fall back to the default for unknown values."""+ aliases, valid, default = spec+ val = aliases.get(val, val)+ return val if val in valid else default-def _parse_context_tokens(host_val, root_val) -> int | None:- """Parse contextTokens: host wins, then root, then None (uncapped)."""- for val in (host_val, root_val):- if val is not None:- try:- return int(val)- except (ValueError, TypeError):- pass- return None+def _first_set(*vals, default):+ """First non-None value, else default."""+ return next((val for val in vals if val is not None), default)-def _parse_int_config(host_val, root_val, default: int) -> int:- """Parse an integer config: host wins, then root, then default."""- for val in (host_val, root_val):+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 int(val)+ return caster(val)except (ValueError, TypeError):passreturn default-def _parse_float_config(host_val, root_val, default: float) -> float:- """Parse a float config: host wins, then root, then default. Clamped ≥ 0."""- for val in (host_val, root_val):- if val is not None:- try:- return max(0.0, float(val))- except (ValueError, TypeError):- pass- return default+def _positive_float(value: Any) -> float:+ parsed = float(value)+ if parsed <= 0:+ raise ValueError(value)+ return parsed-def _parse_string_map(host_obj: dict, root_obj: dict, key: str) -> dict[str, str]:- """Parse a string-to-string map with host-level whole-map override."""- source = host_obj[key] if key in host_obj else root_obj.get(key)- if not isinstance(source, dict):- return {}+def _resolve_optional_float(*values: Any) -> float | None:+ """First value (blank strings included) that parses as a positive float, else None."""+ return _first_parsed(values, _positive_float, None)- result: dict[str, str] = {}- for raw_key, raw_value in source.items():- alias_key = str(raw_key).strip()- alias_value = str(raw_value).strip() if raw_value is not None else ""- if alias_key and alias_value:- result[alias_key] = alias_value- return result+def _parse_dialectic_depth_levels(vals, depth: int) -> list[str] | None:+ """First list value, validated and padded/truncated to ``depth``; None if unset."""+ for val in vals:+ if isinstance(val, list):+ levels = [lvl if lvl in _VALID_REASONING_LEVELS else "low" for lvl in val[:depth]]+ return levels + ["low"] * (depth - len(levels))+ return None-def _parse_optional_string(- host_obj: dict, root_obj: dict, key: str, default: str = ""-) -> str:- """Parse a string field where host-level empty string can override root."""- if key in host_obj:- value = host_obj.get(key)- else:- value = root_obj.get(key, default)- if value is None:- return default- return str(value).strip()+def _resolve_observation(mode: str, observation_obj: dict | None) -> dict:+ """Per-peer observation booleans: ``observation`` object fields override the mode preset."""+ preset = _OBSERVATION_PRESETS.get(mode, _OBSERVATION_PRESETS["directional"])+ if not isinstance(observation_obj, dict) or not observation_obj:+ return dict(preset)+ return {+ f"{kind}_observe_{who}": (observation_obj.get(kind) or {}).get(json_key, preset[f"{kind}_observe_{who}"])+ for kind in ("user", "ai")+ for who, json_key in (("me", "observeMe"), ("others", "observeOthers"))+ }-def _parse_dialectic_depth(host_val, root_val) -> int:- """Parse dialecticDepth: host wins, then root, then 1. Clamped to 1-3."""- for val in (host_val, root_val):- if val is not None:- try:- return max(1, min(int(val), 3))- except (ValueError, TypeError):- pass- return 1+class _HostLookup:+ """Host-block-over-root field lookups for one honcho.json."""-_VALID_REASONING_LEVELS = ("minimal", "low", "medium", "high", "max")+ def __init__(self, host_block: dict, raw: dict):+ self.host, self.raw = host_block, raw+ def pick(self, key: str, default=None):+ """Truthy host value, else ``raw.get(key, default)``."""+ return self.host.get(key) or self.raw.get(key, default)-def _parse_dialectic_depth_levels(host_val, root_val, depth: int) -> list[str] | None:- """Parse dialecticDepthLevels: optional array of reasoning levels per pass.+ def pick_set(self, key: str, default=None):+ """Non-None host value, else ``raw.get(key, default)``."""+ return _first_set(self.host.get(key), default=self.raw.get(key, default))- Returns None when not configured (use proportional defaults).- When configured, validates each level and truncates/pads to match depth.- """- for val in (host_val, root_val):- if val is not None and isinstance(val, list):- levels = [- lvl if lvl in _VALID_REASONING_LEVELS else "low"- for lvl in val[:depth]- ]- # Pad with "low" if array is shorter than depth- while len(levels) < depth:- levels.append("low")- return levels- return None+ def vals(self, *keys: str) -> list:+ """Host values then root values for the aliased ``keys`` (lookup order)."""+ return [self.host.get(k) for k in keys] + [self.raw.get(k) for k in keys]+ def flag(self, *keys: str, default: bool) -> bool:+ """First non-None value across host-then-root for the aliased ``keys``, as bool."""+ return bool(_first_set(*self.vals(*keys), default=default))-# Default HTTP timeout (seconds) applied when no explicit timeout is-# configured via HonchoClientConfig.timeout, honcho.timeout / requestTimeout,-# or HONCHO_TIMEOUT. Honcho calls happen on the post-response path of-# run_conversation; without a cap the agent can block indefinitely when-# the Honcho backend is unreachable, preventing the gateway from-# delivering the already-generated response.-_DEFAULT_HTTP_TIMEOUT = 30.0+ def parsed(self, key: str, caster: Callable[[Any], Any], default):+ return _first_parsed(self.vals(key), caster, default)++ def present(self, key: str, default=None):+ """Host value if the key is PRESENT there (even empty/None), else root."""+ return self.host[key] if key in self.host else self.raw.get(key, default)++ def string(self, key: str, default: str = "") -> str:+ """String field where a host-level empty string can override root."""+ value = self.present(key, default)+ return default if value is None else str(value).strip()++ def string_map(self, key: str) -> dict[str, str]:+ """String-to-string map; a host-level map replaces the root map wholesale."""+ source = self.present(key)+ if not isinstance(source, dict):+ return {}+ pairs = ((str(k).strip(), str(v).strip() if v is not None else "") for k, v in source.items())+ return {k: v for k, v in pairs if k and v}def _is_local_base_url(base_url: str | None) -> bool:- """Return True for loopback/LAN/VPN self-hosted Honcho URLs.+ """True for loopback/RFC1918/link-local/ULA/CGNAT self-hosted Honcho URLs.- Local Honcho deployments can run without auth, but the SDK requires a- non-empty api_key argument. Treat loopback plus RFC1918/link-local/ULA- and carrier-grade-NAT IPs as local so LAN/VPN URLs such as- ``http://192.168.2.112:8000`` get the same placeholder-key behavior as- localhost.+ 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 False-try:- parsed = urlparse(base_url)- host = (parsed.hostname or "").strip().lower()+ host = (urlparse(base_url).hostname or "").strip().lower()except Exception:host = ""-if host in {"localhost", "127.0.0.1", "::1"}:return True- if not host:- return False-try:ip = ipaddress.ip_address(host)except ValueError:return False-if ip.is_loopback or ip.is_private or ip.is_link_local:return True-# Tailscale/other VPN setups often sit in carrier-grade NAT space.- if ip.version == 4 and ipaddress.ip_address("100.64.0.0") <= ip <= ipaddress.ip_address("100.127.255.255"):- return True-- return False---def _resolve_optional_float(*values: Any) -> float | None:- """Return the first non-empty value coerced to a positive float."""- for value in values:- if value is None:- continue- if isinstance(value, str):- value = value.strip()- if not value:- continue- try:- parsed = float(value)- except (TypeError, ValueError):- continue- if parsed > 0:- return parsed- return None---_VALID_OBSERVATION_MODES = {"unified", "directional"}-_OBSERVATION_MODE_ALIASES = {"shared": "unified", "separate": "directional", "cross": "directional"}---def _normalize_observation_mode(val: str) -> str:- """Normalize observation mode values."""- val = _OBSERVATION_MODE_ALIASES.get(val, val)- return val if val in _VALID_OBSERVATION_MODES else "directional"---# Observation presets — granular booleans derived from legacy string mode.-# Explicit per-peer config always wins over presets.-_OBSERVATION_PRESETS = {- "directional": {- "user_observe_me": True, "user_observe_others": True,- "ai_observe_me": True, "ai_observe_others": True,- },- "unified": {- "user_observe_me": True, "user_observe_others": False,- "ai_observe_me": False, "ai_observe_others": True,- },-}---def _resolve_observation(- mode: str,- observation_obj: dict | None,-) -> dict:- """Resolve per-peer observation booleans.-- Config forms:- String shorthand: ``"observationMode": "directional"``- Granular object: ``"observation": {"user": {"observeMe": true, "observeOthers": true},- "ai": {"observeMe": true, "observeOthers": false}}``-- Granular fields override preset defaults.- """- preset = _OBSERVATION_PRESETS.get(mode, _OBSERVATION_PRESETS["directional"])- if not observation_obj or not isinstance(observation_obj, dict):- return dict(preset)-- user_block = observation_obj.get("user") or {}- ai_block = observation_obj.get("ai") or {}-+ return ip.version == 4 and ipaddress.ip_address("100.64.0.0") <= ip <= ipaddress.ip_address("100.127.255.255")+++def _env_base_url() -> str | None:+ """HONCHO_BASE_URL / HONCHO_URL (the SDK's own var); a deployment setting, so plain os.environ."""+ return os.environ.get("HONCHO_BASE_URL", "").strip() or os.environ.get("HONCHO_URL", "").strip() or None+++def _connection_fields(look: _HostLookup, host: str, path: Path) -> dict[str, Any]:+ """Resolve identity/credential/transport fields (host block -> root -> env)."""+ raw, host_block = look.raw, look.host+ api_key = look.pick("apiKey") or get_secret("HONCHO_API_KEY")+ # 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,+ )+ # 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()+ )return {- "user_observe_me": user_block.get("observeMe", preset["user_observe_me"]),- "user_observe_others": user_block.get("observeOthers", preset["user_observe_others"]),- "ai_observe_me": ai_block.get("observeMe", preset["ai_observe_me"]),- "ai_observe_others": ai_block.get("observeOthers", preset["ai_observe_others"]),+ "workspace_id": look.pick("workspace") or host,+ "ai_peer": look.pick("aiPeer") or host,+ "api_key": api_key,+ "environment": look.pick("environment", "production"),+ "base_url": base_url,+ "timeout": _resolve_optional_float(*look.vals("timeout", "requestTimeout"), os.environ.get("HONCHO_TIMEOUT")),+ # Explicit enabled (host, then root) wins; else auto-enable on key/url.+ "enabled": _first_set(*look.vals("enabled"), default=bool(api_key or base_url)),}-+def _behavior_fields(look: _HostLookup, explicitly_configured: bool) -> dict[str, Any]:+ """Resolve memory-behavior tuning fields (host block -> root -> defaults)."""+ raw_wf = look.pick("writeFrequency") or "async"+ try:+ write_frequency: str | int = int(raw_wf)+ except (TypeError, ValueError):+ write_frequency = str(raw_wf)+ depth = look.parsed("dialecticDepth", lambda v: max(1, min(int(v), 3)), 1)+ # 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,+ )+ return {+ "peer_name": look.pick("peerName"),+ # pinUserPeer is the clearer name; the original pinPeerName stays accepted.+ "pin_peer_name": look.flag("pinUserPeer", "pinPeerName", default=False),+ "user_peer_aliases": look.string_map("userPeerAliases"),+ "runtime_peer_prefix": look.string("runtimePeerPrefix"),+ "save_messages": look.pick_set("saveMessages", True),+ "write_frequency": write_frequency,+ "context_tokens": look.parsed("contextTokens", int, None),+ "dialectic_reasoning_level": look.pick("dialecticReasoningLevel") or "low",+ "dialectic_dynamic": look.flag("dialecticDynamic", default=True),+ "dialectic_max_chars": look.parsed("dialecticMaxChars", int, 600),+ "dialectic_depth": depth,+ "dialectic_depth_levels": _parse_dialectic_depth_levels(look.vals("dialecticDepthLevels"), depth),+ "reasoning_heuristic": look.flag("reasoningHeuristic", default=True),+ "reasoning_level_cap": look.pick("reasoningLevelCap") or "high",+ "message_max_chars": look.parsed("messageMaxChars", int, 25000),+ "dialectic_max_input_chars": look.parsed("dialecticMaxInputChars", int, 10000),+ "recall_mode": _normalize_choice(look.pick("recallMode") or "hybrid", _RECALL_MODES),+ "init_on_session_start": look.flag("initOnSessionStart", default=False),+ "injection_frequency": look.pick("injectionFrequency", "every-turn"),+ "context_cadence": look.parsed("contextCadence", int, 1),+ "dialectic_cadence": look.parsed("dialecticCadence", int, 1),+ "query_rewrite": look.flag("queryRewrite", default=False),+ "first_turn_base_wait": look.parsed("firstTurnBaseWait", lambda v: max(0.0, float(v)), 3.0),+ "first_turn_dialectic_wait": look.parsed("firstTurnDialecticWait", lambda v: max(0.0, float(v)), 2.0),+ "observation_mode": observation_mode,+ **_resolve_observation(observation_mode, look.pick("observation")),+ "session_strategy": look.pick("sessionStrategy", "per-directory"),+ "session_peer_prefix": look.pick_set("sessionPeerPrefix", False),+ }@dataclass@@ -385,88 +358,46 @@ class HonchoClientConfig:workspace_id: str = "hermes"api_key: str | None = Noneenvironment: str = "production"- # Optional base URL for self-hosted Honcho (overrides environment mapping)- base_url: str | None = None- # Optional request timeout in seconds for Honcho SDK HTTP calls- timeout: float | None = None+ base_url: str | None = None # self-hosted override of the environment mapping+ timeout: float | None = None # SDK HTTP timeout, seconds# Identitypeer_name: str | None = Noneai_peer: str = "hermes"- # When True, ``peer_name`` wins over any gateway-supplied runtime- # identity (Telegram UID, Discord ID, …) when resolving the user peer.- # This keeps memory unified across platforms for single-user deployments- # where Honcho's one peer-name is an unambiguous identity — otherwise- # each platform would fork memory into its own peer (#14984). Default- # ``False`` preserves existing multi-user behaviour.+ # True: peer_name wins over gateway runtime identity (Telegram UID, ...), so a+ # single-user deployment keeps one memory across platforms.pin_peer_name: bool = False- # Map gateway runtime user IDs to stable Honcho user peers. Host-level- # config replaces the root map as a whole so profiles can intentionally- # own their identity mappings.+ # Gateway runtime user id -> stable Honcho peer; host map replaces root map.user_peer_aliases: dict[str, str] = field(default_factory=dict)- # Optional prefix for unknown gateway runtime user IDs, e.g. "telegram_".- runtime_peer_prefix: str = ""+ runtime_peer_prefix: str = "" # prefix for unknown runtime user ids, e.g. "telegram_"# Togglesenabled: bool = Falsesave_messages: bool = True- # Write frequency: "async" (background thread), "turn" (sync per turn),- # "session" (flush on session end), or int (every N turns)- write_frequency: str | int = "async"- # Prefetch budget (None = no cap; set to an integer to bound auto-injected context)- context_tokens: int | None = None+ write_frequency: str | int = "async" # "async" | "turn" | "session" | every-N-turns int+ context_tokens: int | None = None # prefetch budget; None = uncapped# Dialectic (peer.chat) settings- # reasoning_level: "minimal" | "low" | "medium" | "high" | "max"- dialectic_reasoning_level: str = "low"- # When true, the model can override reasoning_level per-call via the- # honcho_reasoning tool param (agentic). When false, always uses- # dialecticReasoningLevel and ignores model-provided overrides.- dialectic_dynamic: bool = True- # Automatic-injection cap; explicit honcho_reasoning calls bypass it.- dialectic_max_chars: int = 600- # Dialectic depth: how many .chat() calls per dialectic cycle (1-3).- # Depth 1: single call. Depth 2: self-audit + targeted synthesis.- # Depth 3: self-audit + synthesis + reconciliation.- dialectic_depth: int = 1- # Optional per-pass reasoning level override. Array of reasoning levels- # matching dialectic_depth length. When None, uses proportional defaults- # derived from dialectic_reasoning_level.- dialectic_depth_levels: list[str] | None = None- # When true, the auto-injected dialectic scales reasoning level up on- # longer queries. See HonchoMemoryProvider for thresholds.- reasoning_heuristic: bool = True- # Ceiling for the heuristic-selected reasoning level.+ dialectic_reasoning_level: str = "low" # minimal | low | medium | high | max+ dialectic_dynamic: bool = True # model may override the level via honcho_reasoning+ dialectic_max_chars: int = 600 # auto-injection cap; explicit calls bypass it+ dialectic_depth: int = 1 # .chat() passes per cycle (1-3): audit / synthesis / reconcile+ dialectic_depth_levels: list[str] | None = None # per-pass levels; None = proportional defaults+ reasoning_heuristic: bool = True # scale auto-injected level up on longer queriesreasoning_level_cap: str = "high"- # Honcho API limits — configurable for self-hosted instances- # Max chars per message sent via add_messages() (Honcho cloud: 25000)+ # Honcho API limits (Honcho cloud: 25000 / 10000) — configurable for self-hostsmessage_max_chars: int = 25000- # Max chars for dialectic query input to peer.chat() (Honcho cloud: 10000)dialectic_max_input_chars: int = 10000- # Recall mode: how memory retrieval works when Honcho is active.- # "hybrid" — auto-injected context + Honcho tools available (model decides)- # "context" — auto-injected context only, Honcho tools removed- # "tools" — Honcho tools only, no auto-injected context+ # "hybrid" (context + tools) | "context" (no tools) | "tools" (no auto context)recall_mode: str = "hybrid"- # Eager init in tools mode — when true, initializes session during- # initialize() instead of deferring to first tool call- init_on_session_start: bool = False- # Injection frequency: "every-turn" (default) or "first-turn" (inject only on turn 1)- injection_frequency: str = "every-turn"- # Minimum turns between peer.context() API calls (base layer refresh cadence)- context_cadence: int = 1- # Minimum turns between dialectic prefetch fires (supplement layer cadence)- dialectic_cadence: int = 1- # Rewrite the latest user message into a retrieval query before dialectic.- # Off by default: adds one auxiliary LLM call per dialectic fire- # (model/timeout under auxiliary.memory_query_rewrite in config.yaml).- query_rewrite: bool = False- # Bounded synchronous waits on turn 1, in seconds. 0 disables the wait- # entirely (fully async first turn; context surfaces on later turns).+ init_on_session_start: bool = False # tools mode: init eagerly instead of on first tool call+ injection_frequency: str = "every-turn" # or "first-turn"+ context_cadence: int = 1 # min turns between peer.context() calls+ dialectic_cadence: int = 1 # min turns between dialectic prefetches+ query_rewrite: bool = False # rewrite the user message into a retrieval query (one aux LLM call)+ # Bounded synchronous waits on turn 1, seconds; 0 = fully async first turn.first_turn_base_wait: float = 3.0first_turn_dialectic_wait: float = 2.0- # Observation mode: legacy string shorthand ("directional" or "unified").- # Kept for backward compat; granular per-peer booleans below are preferred.+ # Legacy string shorthand; the granular per-peer booleans below are preferred+ # and map 1:1 to Honcho's SessionPeerConfig.observation_mode: str = "directional"- # Per-peer observation booleans — maps 1:1 to Honcho's SessionPeerConfig.- # Resolved from "observation" object in config, falling back to observation_mode preset.user_observe_me: bool = Trueuser_observe_others: bool = Trueai_observe_me: bool = True@@ -475,74 +406,42 @@ class HonchoClientConfig:session_strategy: str = "per-directory"session_peer_prefix: bool = Falsesessions: dict[str, str] = field(default_factory=dict)- # Raw global config for anything else consumers needraw: dict[str, Any] = field(default_factory=dict)- # True when Honcho was explicitly configured for this host (hosts.hermes- # block exists or enabled was set explicitly), vs auto-enabled from a- # stray HONCHO_API_KEY env var.+ # A hosts.<host> block or explicit enabled flag, vs auto-enabled from a stray env key.explicitly_configured: bool = False- # Provenance: WHERE this config was resolved from, captured at resolution- # time (inside the caller's profile scope). Bound consumers (session- # manager, OAuth refresh paths) use these instead of re-resolving- # resolve_config_path()/get_hermes_home() later — those resolvers read a- # ContextVar that background threads cannot see, so re-resolution from a- # daemon thread silently lands on the DEFAULT profile (#69123, #74065).+ # 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.config_path: Path | None = Nonehermes_home: Path | None = Nonedef bound_config_path(self) -> Path:- """Return the config path this config was resolved from.-- Falls back to ambient resolution only for hand-constructed configs- (tests, env-only setups) that carry no provenance.- """- if self.config_path is not None:- return self.config_path- return resolve_config_path()+ """Config path this was resolved from; ambient fallback for hand-built configs."""+ return self.config_path if self.config_path is not None else resolve_config_path()@classmethod- def from_env(- cls,- workspace_id: str = "hermes",- host: str | None = None,- ) -> HonchoClientConfig:+ def from_env(cls, workspace_id: str = "hermes", host: str | None = None) -> HonchoClientConfig:"""Create config from environment variables (fallback)."""resolved_host = host or resolve_active_host()api_key = get_secret("HONCHO_API_KEY")- # HONCHO_URL is the SDK's own env var (honcho.client resolves it when- # no environment is passed); accept it here so the fallback path- # behaves the same as from_global_config() when no config file exists.- # Read straight from os.environ, matching HONCHO_BASE_URL: a base URL- # is a deployment setting, not a profile-scoped credential.- base_url = _sanitize_url(- os.environ.get("HONCHO_BASE_URL", "").strip()- or os.environ.get("HONCHO_URL", "").strip()- or None- )- timeout = _resolve_optional_float(os.environ.get("HONCHO_TIMEOUT"))- _resolved_path = resolve_config_path()+ base_url = _sanitize_url(_env_base_url())return cls(host=resolved_host,workspace_id=workspace_id,api_key=api_key,environment=os.environ.get("HONCHO_ENVIRONMENT", "production"),base_url=base_url,- timeout=timeout,+ timeout=_resolve_optional_float(os.environ.get("HONCHO_TIMEOUT")),ai_peer=resolved_host,enabled=bool(api_key or base_url),- config_path=_resolved_path,+ config_path=resolve_config_path(),hermes_home=get_hermes_home(),)@classmethod- def from_global_config(- cls,- host: str | None = None,- config_path: Path | None = None,- ) -> HonchoClientConfig:- """Create config from the resolved Honcho config path.-- Resolution: $HERMES_HOME/honcho.json -> ~/.honcho/config.json -> env vars.+ def 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."""resolved_host = host or resolve_active_host()@@ -550,270 +449,22 @@ class HonchoClientConfig:if not path.exists():logger.debug("No global Honcho config at %s, falling back to env", path)return cls.from_env(host=resolved_host)-try:- raw = json.loads(path.read_text(encoding="utf-8"))+ raw = _read_config(path)except (json.JSONDecodeError, OSError) as e:logger.warning("Failed to read %s: %s, falling back to env", path, e)return cls.from_env(host=resolved_host)host_block = _host_block(raw, resolved_host)- # A hosts.hermes block or explicit enabled flag means the user- # intentionally configured Honcho for this host.- _explicitly_configured = bool(host_block) or raw.get("enabled") is True-- # Explicit host block fields win, then flat/global, then defaults- workspace = (- host_block.get("workspace")- or raw.get("workspace")- or resolved_host- )- ai_peer = (- host_block.get("aiPeer")- or raw.get("aiPeer")- or resolved_host- )- api_key = (- host_block.get("apiKey")- or raw.get("apiKey")- or get_secret("HONCHO_API_KEY")- )- # Named-profile host blocks do NOT inherit the default host's apiKey —- # profiles are isolated islands by design (see resolve_active_host).- # But the failure mode is silent: the profile runs unauthenticated and- # every write 401s while tools report "no context". Warn loudly so the- # operator learns the key must be set on THIS host block (#36098, #66125).- if (- not api_key- and host_block- and resolved_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.",- resolved_host, HOST, resolved_host, path,- )-- environment = (- host_block.get("environment")- or raw.get("environment", "production")- )-- # The Honcho SDK's native config format — and what Claude Desktop- # writes — nests the URL at endpoint.baseUrl. Read it first: a user- # who has that block set almost certainly means it, and the flat- # baseUrl / base_url keys below are the Hermes-specific spelling.- 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 os.environ.get("HONCHO_BASE_URL", "").strip()- or os.environ.get("HONCHO_URL", "").strip()- or None- )- # Host config wins over flat/global config and environment.- timeout = _resolve_optional_float(- host_block.get("timeout"),- host_block.get("requestTimeout"),- raw.get("timeout"),- raw.get("requestTimeout"),- os.environ.get("HONCHO_TIMEOUT"),- )-- # Auto-enable when API key or base_url is present (unless explicitly disabled)- # Host-level enabled wins, then root-level, then auto-enable if key/url exists.- host_enabled = host_block.get("enabled")- root_enabled = raw.get("enabled")- if host_enabled is not None:- enabled = host_enabled- elif root_enabled is not None:- enabled = root_enabled- else:- # Not explicitly set anywhere -> auto-enable if API key or base_url exists- enabled = bool(api_key or base_url)-- # write_frequency: accept int or string- raw_wf = (- host_block.get("writeFrequency")- or raw.get("writeFrequency")- or "async"- )- try:- write_frequency: str | int = int(raw_wf)- except (TypeError, ValueError):- write_frequency = str(raw_wf)-- # saveMessages: host wins (None-aware since False is valid)- host_save = host_block.get("saveMessages")- save_messages = host_save if host_save is not None else raw.get("saveMessages", True)-- # sessionStrategy / sessionPeerPrefix: host first, root fallback- session_strategy = (- host_block.get("sessionStrategy")- or raw.get("sessionStrategy", "per-directory")- )- host_prefix = host_block.get("sessionPeerPrefix")- session_peer_prefix = (- host_prefix if host_prefix is not None- else raw.get("sessionPeerPrefix", False)- )-+ explicitly_configured = bool(host_block) or raw.get("enabled") is True+ look = _HostLookup(host_block, raw)return cls(host=resolved_host,- workspace_id=workspace,- api_key=api_key,- environment=environment,- base_url=base_url,- timeout=timeout,- peer_name=host_block.get("peerName") or raw.get("peerName"),- ai_peer=ai_peer,- pin_peer_name=_resolve_bool(- # ``pinUserPeer`` is the clearer name (the resolver pins- # the user-side peer to ``peerName``, ignoring runtime- # identity). ``pinPeerName`` is the original key from- # #14984 and stays accepted for backward compatibility.- # Host-level keys win over root-level; among same-level- # keys, ``pinUserPeer`` wins over ``pinPeerName``.- host_block.get("pinUserPeer"),- host_block.get("pinPeerName"),- raw.get("pinUserPeer"),- raw.get("pinPeerName"),- default=False,- ),- user_peer_aliases=_parse_string_map(- host_block,- raw,- "userPeerAliases",- ),- runtime_peer_prefix=_parse_optional_string(- host_block,- raw,- "runtimePeerPrefix",- ),- enabled=enabled,- save_messages=save_messages,- write_frequency=write_frequency,- context_tokens=_parse_context_tokens(- host_block.get("contextTokens"),- raw.get("contextTokens"),- ),- dialectic_reasoning_level=(- host_block.get("dialecticReasoningLevel")- or raw.get("dialecticReasoningLevel")- or "low"- ),- dialectic_dynamic=_resolve_bool(- host_block.get("dialecticDynamic"),- raw.get("dialecticDynamic"),- default=True,- ),- dialectic_max_chars=_parse_int_config(- host_block.get("dialecticMaxChars"),- raw.get("dialecticMaxChars"),- default=600,- ),- dialectic_depth=_parse_dialectic_depth(- host_block.get("dialecticDepth"),- raw.get("dialecticDepth"),- ),- dialectic_depth_levels=_parse_dialectic_depth_levels(- host_block.get("dialecticDepthLevels"),- raw.get("dialecticDepthLevels"),- depth=_parse_dialectic_depth(host_block.get("dialecticDepth"), raw.get("dialecticDepth")),- ),- reasoning_heuristic=_resolve_bool(- host_block.get("reasoningHeuristic"),- raw.get("reasoningHeuristic"),- default=True,- ),- reasoning_level_cap=(- host_block.get("reasoningLevelCap")- or raw.get("reasoningLevelCap")- or "high"- ),- message_max_chars=_parse_int_config(- host_block.get("messageMaxChars"),- raw.get("messageMaxChars"),- default=25000,- ),- dialectic_max_input_chars=_parse_int_config(- host_block.get("dialecticMaxInputChars"),- raw.get("dialecticMaxInputChars"),- default=10000,- ),- recall_mode=_normalize_recall_mode(- host_block.get("recallMode")- or raw.get("recallMode")- or "hybrid"- ),- init_on_session_start=_resolve_bool(- host_block.get("initOnSessionStart"),- raw.get("initOnSessionStart"),- default=False,- ),- # Host cadence settings override flat/global values.- injection_frequency=(- host_block.get("injectionFrequency")- or raw.get("injectionFrequency", "every-turn")- ),- context_cadence=_parse_int_config(- host_block.get("contextCadence"),- raw.get("contextCadence"),- default=1,- ),- dialectic_cadence=_parse_int_config(- host_block.get("dialecticCadence"),- raw.get("dialecticCadence"),- default=1,- ),- query_rewrite=_resolve_bool(- host_block.get("queryRewrite"),- raw.get("queryRewrite"),- default=False,- ),- first_turn_base_wait=_parse_float_config(- host_block.get("firstTurnBaseWait"),- raw.get("firstTurnBaseWait"),- default=3.0,- ),- first_turn_dialectic_wait=_parse_float_config(- host_block.get("firstTurnDialecticWait"),- raw.get("firstTurnDialecticWait"),- default=2.0,- ),- # Migration guard: existing configs without an explicit- # observationMode keep the old "unified" default so users- # aren't silently switched to full bidirectional observation.- # New installations (no host block, no credentials) get- # "directional" (all observations on) as the new default.- observation_mode=_normalize_observation_mode(- host_block.get("observationMode")- or raw.get("observationMode")- or ("unified" if _explicitly_configured else "directional")- ),- **_resolve_observation(- _normalize_observation_mode(- host_block.get("observationMode")- or raw.get("observationMode")- or ("unified" if _explicitly_configured else "directional")- ),- host_block.get("observation") or raw.get("observation"),- ),- session_strategy=session_strategy,- session_peer_prefix=session_peer_prefix,+ **_connection_fields(look, resolved_host, path),+ **_behavior_fields(look, explicitly_configured),sessions=raw.get("sessions", {}),raw=raw,- explicitly_configured=_explicitly_configured,+ explicitly_configured=explicitly_configured,config_path=path,hermes_home=get_hermes_home(),)@@ -829,45 +480,31 @@ class HonchoClientConfig:capture_output=True, text=True, encoding='utf-8', errors='replace', cwd=cwd, timeout=5,stdin=subprocess.DEVNULL,)- if root.returncode == 0:- return Path(root.stdout.strip()).nameexcept (OSError, subprocess.TimeoutExpired):- pass- return None+ return None+ return Path(root.stdout.strip()).name if root.returncode == 0 else None- # Honcho enforces a 100-char limit on session IDs. Long gateway session keys- # (Matrix "!room:server" + thread event IDs, Telegram supergroup reply- # chains, Slack thread IDs with long workspace prefixes) can overflow this- # limit after sanitization; the Honcho API then rejects every call for that- # session with "session_id too long". See issue #13868.- _HONCHO_SESSION_ID_MAX_LEN = 100- _HONCHO_SESSION_ID_HASH_LEN = 8+ # Honcho rejects session IDs over 100 chars; long gateway keys (Matrix+ # rooms + thread ids, Slack threads) overflow after sanitization.+ _HONCHO_SESSION_ID_MAX_LEN, _HONCHO_SESSION_ID_HASH_LEN = 100, 8@classmethoddef _enforce_session_id_limit(cls, sanitized: str, original: str) -> str:- """Truncate a sanitized session ID to Honcho's 100-char limit.-- The common case (short keys) short-circuits with no modification.- For over-limit keys, keep a prefix of the sanitized ID and append a- deterministic ``-<sha256 prefix>`` suffix so two distinct long keys- that share a leading segment don't collide onto the same truncated ID.- The hash is taken over the *original* pre-sanitization key, so two- inputs that sanitize to the same string still collide intentionally- (same logical session), but two inputs that only share a prefix do not.+ """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)."""- max_len = cls._HONCHO_SESSION_ID_MAX_LEN+ max_len, hash_len = cls._HONCHO_SESSION_ID_MAX_LEN, cls._HONCHO_SESSION_ID_HASH_LENif len(sanitized) <= max_len:return sanitized-- hash_len = cls._HONCHO_SESSION_ID_HASH_LENdigest = hashlib.sha256(original.encode("utf-8")).hexdigest()[:hash_len]- # max_len - hash_len - 1 (for the '-' separator) chars of the sanitized- # prefix, then '-<hash>'. Strip any trailing hyphen from the prefix so- # the result doesn't double up on separators.- prefix_len = max_len - hash_len - 1- prefix = sanitized[:prefix_len].rstrip("-")+ prefix = sanitized[: max_len - hash_len - 1].rstrip("-")return f"{prefix}-{digest}"+ def _with_peer_prefix(self, name: str) -> str:+ return f"{self.peer_name}-{name}" if self.session_peer_prefix and self.peer_name else name+def resolve_session_name(self,cwd: str | None = None,@@ -875,356 +512,56 @@ class HonchoClientConfig:session_id: str | None = None,gateway_session_key: str | None = None,) -> str | None:- """Resolve Honcho session name.-- Resolution order:- 1. Gateway session key (stable per-chat identifier from gateway platforms)- 2. per-session strategy — Hermes session_id ({timestamp}_{hex}); authoritative,- so a generated title never remaps a live conversation- 3. Manual directory override from sessions map- 4. Hermes session title (from /title command; non-per-session)- 5. per-repo strategy — git repo root directory name- 6. per-directory strategy — directory basename- 7. global strategy — workspace name+ """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 re- if not cwd:- cwd = os.getcwd()-- # Gateway per-chat key wins everywhere — gateways (telegram/discord/…)- # need per-chat isolation no cwd/strategy name can provide.- if gateway_session_key:- sanitized = re.sub(r'[^a-zA-Z0-9_-]+', '-', gateway_session_key).strip('-')- if sanitized:- return self._enforce_session_id_limit(sanitized, gateway_session_key)+ def _slug(text: str) -> str:+ return re.sub(r'[^a-zA-Z0-9_-]+', '-', text).strip('-')- # per-session: the run's session_id IS the identity — resolve before the- # cwd map / title so an auto-generated title can't remap a live- # conversation onto a second Honcho session mid-stream.+ cwd = cwd or os.getcwd()+ if gateway_session_key and _slug(gateway_session_key):+ return self._enforce_session_id_limit(_slug(gateway_session_key), gateway_session_key)if self.session_strategy == "per-session" and session_id:- if self.session_peer_prefix and self.peer_name:- return f"{self.peer_name}-{session_id}"- return session_id-- # Manual override (cwd → name), for non-per-session strategies.+ return self._with_peer_prefix(session_id)manual = self.sessions.get(cwd)if manual:return manual-- # /title mid-session remap (non-per-session).- if session_title:- sanitized = re.sub(r'[^a-zA-Z0-9_-]+', '-', session_title).strip('-')- if sanitized:- if self.session_peer_prefix and self.peer_name:- return f"{self.peer_name}-{sanitized}"- return sanitized-- # per-repo: one Honcho session per git repository+ if session_title and _slug(session_title):+ return self._with_peer_prefix(_slug(session_title))if self.session_strategy == "per-repo":- base = self._git_repo_name(cwd) or Path(cwd).name- if self.session_peer_prefix and self.peer_name:- return f"{self.peer_name}-{base}"- return base-- # per-directory: one Honcho session per working directory (default)+ return self._with_peer_prefix(self._git_repo_name(cwd) or Path(cwd).name)if self.session_strategy in {"per-directory", "per-session"}:- base = Path(cwd).name- if self.session_peer_prefix and self.peer_name:- return f"{self.peer_name}-{base}"- return base-- # global: single session across all directories+ return self._with_peer_prefix(Path(cwd).name)return self.workspace_id-_honcho_client_slot: SingletonSlot = SingletonSlot()-# --- per-identity client cache --------------------------------------------# One slot 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 multiplexed gateway, #74065 dashboard).-# The legacy names above are retained only for reset bookkeeping.-import threading as _threading--_client_slots: dict[tuple, SingletonSlot] = {}-_client_slots_lock = _threading.Lock()---def spawn_context_thread(- target,- *,- name: str,- daemon: bool = True,- args: tuple = (),-) -> "_threading.Thread":+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 in multi-profile processes is a ContextVar- (set_hermes_home_override); plain threading.Thread targets start with an- EMPTY context, so any ambient resolution on the thread- (resolve_config_path, resolve_active_host, get_hermes_home) silently- lands on the default profile. Copying the caller's context at spawn time- makes the thread see the profile scope it was created under.+ 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."""import contextvarsctx = contextvars.copy_context()- t = _threading.Thread(- target=lambda: ctx.run(target, *args),- name=name,- daemon=daemon,- )- return t---def _credential_fingerprint(config: HonchoClientConfig | None) -> str:- """Stable identity for the credential a client will be built with.-- OAuth grants rotate their access token in place (apply_token_to_client),- so the fingerprint must NOT change on rotation — it hashes the REFRESH- token, which is stable across access-token rotation but changes on- re-auth or account switch. Static keys hash the key itself. This is what- makes 'hermes honcho setup' account switches produce a NEW cache identity- instead of silently reusing the old account's client (a first-config-wins- hole that per-path keys alone cannot close).- """- try:- if config is not None:- block = _host_block(config.raw or {}, config.host)- oauth_block = block.get("oauth")- if isinstance(oauth_block, dict) and oauth_block.get("refreshToken"):- basis = f"oauth:{oauth_block['refreshToken']}"- elif config.api_key:- basis = f"key:{config.api_key}"- else:- return ""- return hashlib.sha256(basis.encode("utf-8")).hexdigest()[:16]- # Ambient: read the active file so legacy no-config callers still get- # a credential-aware key (correct on main threads; bound configs are- # the supported path for background threads).- path = resolve_config_path()- if path.exists():- raw = json.loads(path.read_text(encoding="utf-8"))- block = _host_block(raw, resolve_active_host())- oauth_block = block.get("oauth")- if isinstance(oauth_block, dict) and oauth_block.get("refreshToken"):- basis = f"oauth:{oauth_block['refreshToken']}"- else:- key = block.get("apiKey") or raw.get("apiKey") or get_secret("HONCHO_API_KEY") or ""- if not key:- return ""- basis = f"key:{key}"- return hashlib.sha256(basis.encode("utf-8")).hexdigest()[:16]- except Exception:- pass- return ""---def _client_cache_key(config: HonchoClientConfig | None) -> tuple:- """Cache identity for a Honcho client build.-- Explicit configs key on the connection identity ``_build`` embeds in the- client (host, workspace, base_url, environment), the provenance paths the- config was resolved from, the effective timeout, and a credential- fingerprint that is stable across OAuth access-token rotation but changes- on re-auth/account switch. The access token itself is deliberately NOT in- the key — in-place rotation must stay within one slot.-- Ambient callers (config=None: CLI one-shots, tests) key on what- from_global_config() would resolve. Ambient resolution reads the profile- ContextVar and is therefore only correct on threads that can see it;- bound configs are the supported path everywhere else.- """- if 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),- )---def _slot_for(key: tuple) -> SingletonSlot:- """Return the slot for ``key``, evicting stale same-identity slots.-- When a (kind, host, config_path/hermes_home) identity reappears with a- DIFFERENT credential fingerprint or timeout, the old slot is dropped so- the replaced client stops being served and its pools can close once the- last holder releases it. Without eviction, credential churn leaks one- pinned client per change — the gap that made #81401's retirement- machinery inert.- """- identity = key[:3] if key[0] == "ambient" else (key[0], key[1], key[5], key[6])- with _client_slots_lock:- slot = _client_slots.get(key)- if slot is None:- stale = [- k for k in _client_slots- if k != key and (- (k[:3] if k[0] == "ambient" else (k[0], k[1], k[5], k[6])) == identity- )- ]- for k in stale:- _client_slots.pop(k, None)- slot = SingletonSlot()- _client_slots[key] = slot- return slot-# Memo for the honcho.json-derived timeout, keyed PER CONFIG PATH on the-# file's mtime_ns so the staleness check on every get_honcho_client() call-# costs one stat() instead of a JSON parse. Path-keyed because multi-profile-# processes resolve different honcho.json files — a single-slot memo would-# thrash between profiles and return profile A's timeout for profile B.-# mtime -1 = file absent. config.yaml needs no such memo:-# load_config_readonly() is internally cached on both the user and managed-# files' signatures, and a bespoke key here would have to duplicate that-# invalidation logic.-_honcho_json_timeout_memo: dict[str, tuple[int, float | None]] = {}---def _config_yaml_timeout() -> float | None:- """Read honcho.timeout / honcho.request_timeout via the cached config loader."""- 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"),- )- return None- except Exception:- return None---def _honcho_json_timeout() -> float | None:- """Read timeout/requestTimeout from honcho.json (host block wins), memoized on mtime."""- try:- path = resolve_config_path()- path_key = str(path)- try:- mtime_ns: int = path.stat().st_mtime_ns- except OSError:- mtime_ns = -1- memo = _honcho_json_timeout_memo.get(path_key)- if memo is not None and memo[0] == mtime_ns:- return memo[1]-- timeout = None- if mtime_ns != -1:- raw = json.loads(path.read_text(encoding="utf-8"))- host_block = _host_block(raw, resolve_active_host())- timeout = _resolve_optional_float(- host_block.get("timeout"),- host_block.get("requestTimeout"),- raw.get("timeout"),- raw.get("requestTimeout"),- )- _honcho_json_timeout_memo[path_key] = (mtime_ns, timeout)- return timeout- except Exception:- return None---def _resolve_timeout_from_sources(config: HonchoClientConfig | None) -> float:- """Mirror the build path's timeout resolution so the staleness check agrees with it.-- With an explicit config this matches ``_build`` (config.timeout, then- config.yaml, then default). With no config it matches what- ``from_global_config`` + ``_build`` would produce: honcho.json host- block/root keys, then HONCHO_TIMEOUT, then config.yaml, then default.- Any source skew here makes the check disagree with the built client- forever and rebuild it on every call.- """- if config is not None:- timeout = config.timeout- else:- timeout = _honcho_json_timeout()- if timeout is None:- timeout = _resolve_optional_float(os.environ.get("HONCHO_TIMEOUT"))- if timeout is None:- timeout = _config_yaml_timeout()- return timeout if timeout is not None else _DEFAULT_HTTP_TIMEOUT---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 API keys or when refresh fails: the stale token stays in- place and the first rejected call triggers the post-401 recovery in- session.py (forced rotation, one retry).- """- try:- from plugins.memory.honcho import oauth-- # Bound path: refresh against the honcho.json this config came from,- # not whatever the current context resolves to. On daemon threads the- # ambient resolver lands on the default profile and a refresh here- # would persist the rotated token into the WRONG profile's file.- token, _ = oauth.ensure_fresh_token(config.bound_config_path(), config.host)- if token:- config.api_key = token- except Exception:- logger.warning("Honcho OAuth pre-build refresh failed", exc_info=True)---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 SDK shape changed and the in-place rotation can't apply, the- client's own slot is reset so the next acquisition rebuilds with the- fresh token.- """- try:- from plugins.memory.honcho import oauth-- if config is not None:- host = config.host- path = config.bound_config_path()- else:- host = resolve_active_host()- path = resolve_config_path()- token, refreshed = oauth.ensure_fresh_token(path, host)- if refreshed and token and not oauth.apply_token_to_client(client, token):- if slot is not None:- slot.reset()- except Exception:- logger.warning("Honcho OAuth cached refresh failed", exc_info=True)+ return _threading.Thread(target=lambda: ctx.run(target, *args), name=name, daemon=daemon)def 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), not per process: multi-profile- processes (gateway multiplexer, dashboard, cron) previously shared one- first-config-wins client, so every profile's memory landed in whichever- workspace initialized first (#69123, #74065).-- When no config is provided, resolves the active honcho.json — correct- only on threads that can see the profile ContextVar; pass a bound config- everywhere else (HonchoSessionManager does).-- Thread-safe: each identity's client is built exactly once even under- concurrent first calls (double-checked locking via SingletonSlot), so- racing threads can't each construct a client and leak the loser's- connection.+ 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)."""key = _client_cache_key(config)slot = _slot_for(key)@@ -1239,8 +576,7 @@ def get_honcho_client(config: HonchoClientConfig | None = None) -> Honcho:if config is None:config = HonchoClientConfig.from_global_config()- # Refresh a near-expiry OAuth grant before the first build so the client- # starts with a live access token rather than 401ing an hour in.+ # Start with a live access token rather than 401ing an hour in._apply_fresh_oauth_token(config)if not config.api_key and not config.base_url:@@ -1251,117 +587,75 @@ def get_honcho_client(config: HonchoClientConfig | None = None) -> Honcho:"For local instances, set HONCHO_BASE_URL instead.")- # Build inside the singleton factory so racing callers share one client.- def _build() -> "Honcho":- # Lazy dependency failures fall through to the canonical import error.+ return slot.get(lambda: _build_client(config))+++def _build_client(config: HonchoClientConfig) -> "Honcho":+ """Construct the SDK client (runs inside the slot factory so racing callers share one)."""+ # Lazy dependency failures fall through to the canonical import error below.+ try:+ from tools.lazy_deps import ensure as _lazy_ensure+ _lazy_ensure("memory.honcho", prompt=False)+ except Exception:+ pass+ try:+ from honcho import Honcho+ except ImportError:+ 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+ if not base_url or timeout is None:try:- from tools.lazy_deps import FeatureUnavailable, ensure as _lazy_ensure- _lazy_ensure("memory.honcho", prompt=False)- except ImportError:- # lazy_deps module missing — fall through to the raw import below.- pass+ from hermes_cli.config import load_config+ honcho_cfg = load_config().get("honcho", {})+ if isinstance(honcho_cfg, dict):+ base_url = base_url or _sanitize_url(honcho_cfg.get("base_url", "").strip() or None)+ if timeout is None:+ timeout = _resolve_optional_float(honcho_cfg.get("timeout"), honcho_cfg.get("request_timeout"))except Exception:- # FeatureUnavailable or unexpected error. Don't crash here; let the- # actual import attempt produce the canonical error message.pass+ # Default so an unconfigured install cannot hang on a stalled request.+ if timeout is None:+ timeout = _DEFAULT_HTTP_TIMEOUT- try:- from honcho import Honcho- except ImportError:- raise ImportError(- "honcho-ai is required for Honcho integration. "- "Install it with: pip install honcho-ai "- "(or run `hermes honcho setup` to configure)."- )-- # Allow config.yaml honcho.base_url to override the SDK's environment- # mapping, enabling remote self-hosted Honcho deployments without- # requiring the server to live on localhost.- resolved_base_url = config.base_url- resolved_timeout = config.timeout- if not resolved_base_url or resolved_timeout is None:- try:- from hermes_cli.config import load_config- hermes_cfg = load_config()- honcho_cfg = hermes_cfg.get("honcho", {})- if isinstance(honcho_cfg, dict):- if not resolved_base_url:- resolved_base_url = _sanitize_url(honcho_cfg.get("base_url", "").strip() or None)- if resolved_timeout is None:- resolved_timeout = _resolve_optional_float(- honcho_cfg.get("timeout"),- honcho_cfg.get("request_timeout"),- )- except Exception:- pass-- # Fall back to the default so an unconfigured install cannot hang- # indefinitely on a stalled Honcho request.- if resolved_timeout is None:- resolved_timeout = _DEFAULT_HTTP_TIMEOUT-- if resolved_base_url:- logger.info("Initializing Honcho client (base_url: %s, workspace: %s)", resolved_base_url, config.workspace_id)- else:- # No base_url resolved, so the SDK falls back to its own- # ENVIRONMENTS map (honcho.client: local -> http://localhost:8000,- # production -> https://api.honcho.dev). Name the target at INFO:- # a self-hosted user whose config wasn't picked up otherwise sees- # a healthy-looking startup and silently talks 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,- )+ if base_url:+ logger.info("Initializing Honcho client (base_url: %s, workspace: %s)", base_url, config.workspace_id)+ 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,+ )- # Local Honcho instances don't require an API key, but the SDK- # expects a non-empty string. Use a placeholder for local URLs.- # For local: honor config.api_key when the user set it EXPLICITLY in- # honcho.json — host block or top-level (#36098 issue 2: the top-level- # key was dropped for the placeholder, 401ing AUTH_USE_AUTH=true- # self-hosts). Only an env-sourced key (HONCHO_API_KEY) is still- # treated as likely-cloud and skipped for local URLs.- _is_local = _is_local_base_url(resolved_base_url)- if _is_local:- _raw = config.raw or {}- _host_block_local = _host_block(_raw, config.host) # uses dot-form legacy fallback (#37436)- _explicit_key = bool(- _host_block_local.get("apiKey") or _raw.get("apiKey")- )- effective_api_key = config.api_key if _explicit_key else "local"- else:- effective_api_key = config.api_key-- # The Honcho SDK's route builders (e.g. routes.workspaces()) already- # include the version prefix (e.g. "/v3/workspaces"). When a user-supplied- # base_url already ends in a version segment (e.g.- # "http://localhost:38000/v3", "https://honcho.my.ts.net/v3"), concatenating- # the two produces "/v3/v3/workspaces" → 404 on every call. This is a pure- # routing concern independent of host, so strip a trailing version segment- # from ANY base_url — loopback, LAN, custom domain, or cloud alike. The- # SDK then appends its own versioned paths correctly.- if resolved_base_url:- import re as _re- resolved_base_url = _re.sub(r"/v\d+/*$", "", resolved_base_url).rstrip("/")-- kwargs: dict = {- "workspace_id": config.workspace_id,- "api_key": effective_api_key,- "environment": config.environment,- }- if resolved_base_url:- kwargs["base_url"] = resolved_base_url- if resolved_timeout is not None:- kwargs["timeout"] = resolved_timeout-- return Honcho(**kwargs)-- return slot.get(_build)+ # 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+ # env-sourced key as likely-cloud, substituting the placeholder.+ api_key = config.api_key+ raw = config.raw or {}+ 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,+ }+ 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/...".+ import re+ kwargs["base_url"] = re.sub(r"/v\d+/*$", "", base_url).rstrip("/")+ return Honcho(**kwargs)def reset_honcho_client() -> None:"""Reset all cached Honcho clients (tests, OAuth re-login)."""with _client_slots_lock:_client_slots.clear()- _honcho_client_slot.reset()_honcho_json_timeout_memo.clear()diff --git a/plugins/memory/honcho/client_cache.py b/plugins/memory/honcho/client_cache.pynew file mode 100644index 00000000000..c5a3d44bd91--- /dev/null+++ b/plugins/memory/honcho/client_cache.py@@ -0,0 +1,231 @@+"""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.+"""++from __future__ import annotations++import hashlib+import json+import logging+import os+import threading+from typing import TYPE_CHECKING++from plugins.plugin_utils import SingletonSlot++if TYPE_CHECKING:+ from honcho import Honcho++ from plugins.memory.honcho.client import HonchoClientConfig++logger = logging.getLogger("plugins.memory.honcho.client")++# Applied when no timeout is configured anywhere: Honcho calls run on the+# post-response path, and an uncapped call can block response delivery forever.+_DEFAULT_HTTP_TIMEOUT = 30.0++_client_slots: dict[tuple, SingletonSlot] = {}+_client_slots_lock = threading.Lock()++# honcho.json-derived timeout, keyed PER CONFIG PATH on mtime_ns (-1 = absent) so+# the per-call staleness check costs one stat(). config.yaml needs no memo:+# load_config_readonly() is already cached on its files' signatures.+_honcho_json_timeout_memo: dict[str, tuple[int, float | None]] = {}+++def _fingerprint_basis(block: dict, key_fn) -> str:+ """OAuth grants hash the REFRESH token (stable across access-token rotation,+ changes on re-auth/account switch); static keys hash the key itself."""+ oauth_block = block.get("oauth")+ if isinstance(oauth_block, dict) and oauth_block.get("refreshToken"):+ return f"oauth:{oauth_block['refreshToken']}"+ key = key_fn()+ return f"key:{key}" if key else ""+++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.+ """+ from plugins.memory.honcho.client import _host_block++ try:+ 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.+ 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]+ except Exception:+ pass+ return ""+++def _ambient_host_block() -> tuple[dict | None, dict]:+ """(raw honcho.json, active host block) for the ambient profile; (None, {}) when absent."""+ from plugins.memory.honcho.client import _host_block, resolve_active_host, resolve_config_path++ path = resolve_config_path()+ if not path.exists():+ return None, {}+ raw = json.loads(path.read_text(encoding="utf-8"))+ return raw, _host_block(raw, resolve_active_host())+++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.+ """+ from plugins.memory.honcho.client import resolve_active_host, resolve_config_path++ if 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),+ )+++def _slot_identity(key: tuple) -> tuple:+ """(kind, host, paths) — the part of a cache key that survives credential/timeout churn."""+ return key[:3] if key[0] == "ambient" else (key[0], key[1], key[5], key[6])+++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.+ """+ identity = _slot_identity(key)+ with _client_slots_lock:+ slot = _client_slots.get(key)+ if slot is None:+ for k in [k for k in _client_slots if k != key and _slot_identity(k) == identity]:+ _client_slots.pop(k, None)+ slot = SingletonSlot()+ _client_slots[key] = slot+ return slot+++def _config_yaml_timeout() -> float | None:+ """Read honcho.timeout / honcho.request_timeout via the cached config loader."""+ from plugins.memory.honcho.client import _resolve_optional_float++ 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"))+ except Exception:+ pass+ return None+++def _honcho_json_timeout() -> float | None:+ """Read timeout/requestTimeout from honcho.json (host block wins), memoized on mtime."""+ from plugins.memory.honcho.client import _HostLookup, _resolve_optional_float, resolve_config_path++ try:+ path = resolve_config_path()+ path_key = str(path)+ try:+ mtime_ns: int = path.stat().st_mtime_ns+ except OSError:+ mtime_ns = -1+ memo = _honcho_json_timeout_memo.get(path_key)+ if memo is not None and memo[0] == mtime_ns:+ return memo[1]+ timeout = None+ if mtime_ns != -1:+ raw, host_block = _ambient_host_block()+ timeout = _resolve_optional_float(*_HostLookup(host_block, raw).vals("timeout", "requestTimeout"))+ _honcho_json_timeout_memo[path_key] = (mtime_ns, timeout)+ return timeout+ except Exception:+ return 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.+ """+ from plugins.memory.honcho.client import _resolve_optional_float++ if config is not None:+ timeout = config.timeout+ else:+ timeout = _honcho_json_timeout()+ if timeout is None:+ timeout = _resolve_optional_float(os.environ.get("HONCHO_TIMEOUT"))+ if timeout is None:+ timeout = _config_yaml_timeout()+ return timeout if timeout is not None else _DEFAULT_HTTP_TIMEOUT+++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.+ """+ try:+ from plugins.memory.honcho import oauth++ token, _ = oauth.ensure_fresh_token(config.bound_config_path(), config.host)+ if token:+ config.api_key = token+ except Exception:+ logger.warning("Honcho OAuth pre-build refresh failed", exc_info=True)+++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.+ """+ from plugins.memory.honcho.client import resolve_active_host, resolve_config_path++ try:+ from plugins.memory.honcho import oauth++ if config is not None:+ host, path = config.host, config.bound_config_path()+ else:+ host, path = resolve_active_host(), resolve_config_path()+ token, refreshed = oauth.ensure_fresh_token(path, host)+ if refreshed and token and not oauth.apply_token_to_client(client, token) and slot is not None:+ slot.reset()+ except Exception:+ logger.warning("Honcho OAuth cached refresh failed", exc_info=True)diff --git a/plugins/memory/honcho/config_schema.py b/plugins/memory/honcho/config_schema.pyindex b5298e20be9..69800f7ceac 100644--- a/plugins/memory/honcho/config_schema.py+++ b/plugins/memory/honcho/config_schema.py@@ -14,311 +14,116 @@ from plugins.memory.config_schema import ()+def _opts(*pairs: tuple[str, str]) -> tuple[ProviderFieldOption, ...]:+ return tuple(ProviderFieldOption(value, label) for value, label in pairs)++# Reasoning effort levels shared by dialectic-related selects.-_REASONING_LEVELS = (- ProviderFieldOption("minimal", "Minimal"),- ProviderFieldOption("low", "Low"),- ProviderFieldOption("medium", "Medium"),- ProviderFieldOption("high", "High"),- ProviderFieldOption("max", "Max"),+_REASONING_LEVELS = _opts(("minimal", "Minimal"), ("low", "Low"), ("medium", "Medium"), ("high", "High"), ("max", "Max"))++_SESSION_STRATEGY_INFO = (+ "Per session: every conversation gets its own Honcho session. "+ "Per directory: conversations from the same working directory share one. "+ "Per repo: conversations from the same git repo share one. "+ "Global: everything shares a single session."+)+_WRITE_FREQUENCY_INFO = (+ "async: write in the background as messages arrive. "+ "turn: flush after each turn. session: flush when the session ends. "+ "A number N flushes every N turns."+)+_RECALL_MODE_INFO = (+ "Hybrid: auto-injected context plus on-demand memory tools. "+ "Context only: injection without tools. "+ "Tools only: the model queries memory explicitly, nothing is injected.")+def _field(key, label, kind, description, *, group, **kw) -> ProviderField:+ return ProviderField(key=key, label=label, kind=kind, description=description, group=group, **kw)+++# Inline fields form the curated compact panel; the rest surface only in the full-config modal.CONFIG_SCHEMA = ProviderConfigSchema(name="honcho",label="Honcho",storage=STORAGE_HONCHO_HOST_BLOCK,docs_url="https://docs.honcho.dev/v3/guides/integrations/hermes",fields=(+ # — Connection (inline) —+ _field("apiKey", "API key", KIND_SECRET, "Authenticate with Honcho Cloud. Not needed for a self-hosted base URL.",+ env_key="HONCHO_API_KEY", placeholder="Enter Honcho API key", inline=True, group="Connection"),+ _field("baseUrl", "Base URL", KIND_TEXT, "Self-hosted Honcho URL. Overrides the environment when set.",+ aliases=("base_url",), env_fallbacks=("HONCHO_BASE_URL",), placeholder="https://… (self-hosted)",+ inline=True, group="Connection", scope="root"),+ _field("environment", "Environment", KIND_SELECT, "Honcho environment. Ignored when a base URL is set.",+ default="production", env_fallbacks=("HONCHO_ENVIRONMENT",),+ options=_opts(("production", "Cloud"), ("local", "Local")), inline=True, group="Connection"),+ _field("workspace", "Workspace", KIND_TEXT, "Honcho workspace ID. Defaults to the profile host.",+ inline=True, group="Connection"),+ # — Identity (inline) —+ _field("peerName", "Peer name", KIND_TEXT, "Your stable user peer. Unifies memory across platforms for single-user setups.",+ placeholder="e.g. eri", inline=True, group="Identity"),+ _field("aiPeer", "AI peer", KIND_TEXT, "The AI-side peer name. Defaults to the profile host.",+ inline=True, group="Identity"),+ # — Session (inline) —+ _field("sessionStrategy", "Session strategy", KIND_SELECT, "How conversations map to Honcho sessions.",+ default="per-directory", info=_SESSION_STRATEGY_INFO,+ options=_opts(("per-session", "Per session"), ("per-directory", "Per directory"),+ ("per-repo", "Per repo"), ("global", "Global")),+ inline=True, group="Session"),# — Connection —- ProviderField(- key="apiKey",- label="API key",- kind=KIND_SECRET,- env_key="HONCHO_API_KEY",- description="Authenticate with Honcho Cloud. Not needed for a self-hosted base URL.",- placeholder="Enter Honcho API key",- inline=True,- group="Connection",- ),- ProviderField(- key="baseUrl",- label="Base URL",- kind=KIND_TEXT,- aliases=("base_url",),- env_fallbacks=("HONCHO_BASE_URL",),- description="Self-hosted Honcho URL. Overrides the environment when set.",- placeholder="https://… (self-hosted)",- inline=True,- group="Connection",- scope="root",- ),- ProviderField(- key="environment",- label="Environment",- kind=KIND_SELECT,- default="production",- env_fallbacks=("HONCHO_ENVIRONMENT",),- description="Honcho environment. Ignored when a base URL is set.",- options=(- ProviderFieldOption("production", "Cloud"),- ProviderFieldOption("local", "Local"),- ),- inline=True,- group="Connection",- ),- ProviderField(- key="workspace",- label="Workspace",- kind=KIND_TEXT,- description="Honcho workspace ID. Defaults to the profile host.",- inline=True,- group="Connection",- ),- # — Identity —- ProviderField(- key="peerName",- label="Peer name",- kind=KIND_TEXT,- description="Your stable user peer. Unifies memory across platforms for single-user setups.",- placeholder="e.g. eri",- inline=True,- group="Identity",- ),- ProviderField(- key="aiPeer",- label="AI peer",- kind=KIND_TEXT,- description="The AI-side peer name. Defaults to the profile host.",- inline=True,- group="Identity",- ),- # — Session —- ProviderField(- key="sessionStrategy",- label="Session strategy",- kind=KIND_SELECT,- default="per-directory",- description="How conversations map to Honcho sessions.",- info=(- "Per session: every conversation gets its own Honcho session. "- "Per directory: conversations from the same working directory share one. "- "Per repo: conversations from the same git repo share one. "- "Global: everything shares a single session."- ),- options=(- ProviderFieldOption("per-session", "Per session"),- ProviderFieldOption("per-directory", "Per directory"),- ProviderFieldOption("per-repo", "Per repo"),- ProviderFieldOption("global", "Global"),- ),- inline=True,- group="Session",- ),- # —————— Full-config-only fields below (inline=False) ——————- # — Connection —- ProviderField(- key="timeout",- label="Request timeout",- kind=KIND_NUMBER,- aliases=("requestTimeout",),- env_fallbacks=("HONCHO_TIMEOUT",),- description="Request timeout in seconds for Honcho HTTP calls. Blank uses the default.",- placeholder="30",- group="Connection",- scope="root",- ),+ _field("timeout", "Request timeout", KIND_NUMBER, "Request timeout in seconds for Honcho HTTP calls. Blank uses the default.",+ aliases=("requestTimeout",), env_fallbacks=("HONCHO_TIMEOUT",), placeholder="30", group="Connection", scope="root"),# — Identity —- ProviderField(- key="pinUserPeer",- label="Pin user peer",- kind=KIND_BOOL,- default="false",- aliases=("pinPeerName",),- description="Pin the user peer to the peer name, ignoring gateway runtime identity. Unifies memory for single-user setups.",- group="Identity",- ),- ProviderField(- key="runtimePeerPrefix",- label="Runtime peer prefix",- kind=KIND_TEXT,- description="Prefix applied to unknown gateway runtime user IDs.",- placeholder="e.g. telegram_",- group="Identity",- ),- ProviderField(- key="userPeerAliases",- label="User peer aliases",- kind=KIND_JSON,- description="Map gateway runtime user IDs to stable Honcho peers.",- placeholder='{"telegram_123": "eri"}',- group="Identity",- ),+ _field("pinUserPeer", "Pin user peer", KIND_BOOL,+ "Pin the user peer to the peer name, ignoring gateway runtime identity. Unifies memory for single-user setups.",+ default="false", aliases=("pinPeerName",), group="Identity"),+ _field("runtimePeerPrefix", "Runtime peer prefix", KIND_TEXT, "Prefix applied to unknown gateway runtime user IDs.",+ placeholder="e.g. telegram_", group="Identity"),+ _field("userPeerAliases", "User peer aliases", KIND_JSON, "Map gateway runtime user IDs to stable Honcho peers.",+ placeholder='{"telegram_123": "eri"}', group="Identity"),# — Session —- ProviderField(- key="sessionPeerPrefix",- label="Session peer prefix",- kind=KIND_BOOL,- default="false",- description="Prefix session peer names with the host.",- group="Session",- ),- ProviderField(- key="sessions",- label="Session overrides",- kind=KIND_JSON,- description="Explicit session ID overrides keyed by resolver.",- placeholder='{"key": "session-id"}',- group="Session",- scope="root",- ),+ _field("sessionPeerPrefix", "Session peer prefix", KIND_BOOL, "Prefix session peer names with the host.",+ default="false", group="Session"),+ _field("sessions", "Session overrides", KIND_JSON, "Explicit session ID overrides keyed by resolver.",+ placeholder='{"key": "session-id"}', group="Session", scope="root"),# — Message writing —- ProviderField(- key="saveMessages",- label="Save messages",- kind=KIND_BOOL,- default="true",- description="Persist conversation messages to Honcho.",- group="Message writing",- ),- ProviderField(- key="writeFrequency",- label="Write frequency",- kind=KIND_TEXT,- default="async",- description="When to flush messages: async, turn, session, or every N turns.",- info=(- "async: write in the background as messages arrive. "- "turn: flush after each turn. session: flush when the session ends. "- "A number N flushes every N turns."- ),- placeholder="async | turn | session | N",- group="Message writing",- ),+ _field("saveMessages", "Save messages", KIND_BOOL, "Persist conversation messages to Honcho.",+ default="true", group="Message writing"),+ _field("writeFrequency", "Write frequency", KIND_TEXT, "When to flush messages: async, turn, session, or every N turns.",+ default="async", info=_WRITE_FREQUENCY_INFO, placeholder="async | turn | session | N", group="Message writing"),# — Dialectic —- ProviderField(- key="dialecticReasoningLevel",- label="Reasoning level",- kind=KIND_SELECT,- default="low",- description="Reasoning effort for dialectic (peer.chat) calls.",- options=_REASONING_LEVELS,- group="Dialectic",- ),- ProviderField(- key="dialecticDynamic",- label="Dynamic reasoning",- kind=KIND_BOOL,- default="true",- description="Let the model override the reasoning level per call.",- group="Dialectic",- ),- ProviderField(- key="dialecticMaxChars",- label="Max result chars",- kind=KIND_NUMBER,- description="Max chars of dialectic result injected into the system prompt.",- placeholder="1200",- group="Dialectic",- ),- ProviderField(- key="dialecticDepth",- label="Depth",- kind=KIND_NUMBER,- description="Dialectic passes per cycle (1–3).",- placeholder="1",- group="Dialectic",- ),- ProviderField(- key="dialecticDepthLevels",- label="Per-pass levels",- kind=KIND_JSON,- description="Reasoning level per pass; array length matches depth.",- placeholder='["low", "medium"]',- group="Dialectic",- ),- ProviderField(- key="dialecticMaxInputChars",- label="Max input chars",- kind=KIND_NUMBER,- description="Max chars of query input sent to peer.chat().",- placeholder="10000",- group="Dialectic",- ),+ _field("dialecticReasoningLevel", "Reasoning level", KIND_SELECT, "Reasoning effort for dialectic (peer.chat) calls.",+ default="low", options=_REASONING_LEVELS, group="Dialectic"),+ _field("dialecticDynamic", "Dynamic reasoning", KIND_BOOL, "Let the model override the reasoning level per call.",+ default="true", group="Dialectic"),+ _field("dialecticMaxChars", "Max result chars", KIND_NUMBER, "Max chars of dialectic result injected into the system prompt.",+ placeholder="1200", group="Dialectic"),+ _field("dialecticDepth", "Depth", KIND_NUMBER, "Dialectic passes per cycle (1–3).", placeholder="1", group="Dialectic"),+ _field("dialecticDepthLevels", "Per-pass levels", KIND_JSON, "Reasoning level per pass; array length matches depth.",+ placeholder='["low", "medium"]', group="Dialectic"),+ _field("dialecticMaxInputChars", "Max input chars", KIND_NUMBER, "Max chars of query input sent to peer.chat().",+ placeholder="10000", group="Dialectic"),# — Reasoning —- ProviderField(- key="reasoningHeuristic",- label="Reasoning heuristic",- kind=KIND_BOOL,- default="true",- description="Scale the reasoning level up on longer queries.",- group="Reasoning",- ),- ProviderField(- key="reasoningLevelCap",- label="Reasoning level cap",- kind=KIND_SELECT,- default="high",- description="Ceiling for the heuristic-selected reasoning level.",- options=_REASONING_LEVELS,- group="Reasoning",- ),+ _field("reasoningHeuristic", "Reasoning heuristic", KIND_BOOL, "Scale the reasoning level up on longer queries.",+ default="true", group="Reasoning"),+ _field("reasoningLevelCap", "Reasoning level cap", KIND_SELECT, "Ceiling for the heuristic-selected reasoning level.",+ default="high", options=_REASONING_LEVELS, group="Reasoning"),# — Recall —- ProviderField(- key="recallMode",- label="Recall mode",- kind=KIND_SELECT,- default="hybrid",- description="How memory retrieval works: hybrid, context-only, or tools-only.",- info=(- "Hybrid: auto-injected context plus on-demand memory tools. "- "Context only: injection without tools. "- "Tools only: the model queries memory explicitly, nothing is injected."- ),- options=(- ProviderFieldOption("hybrid", "Hybrid"),- ProviderFieldOption("context", "Context only"),- ProviderFieldOption("tools", "Tools only"),- ),- group="Recall",- ),- ProviderField(- key="contextTokens",- label="Context token cap",- kind=KIND_NUMBER,- description="Cap on auto-injected context tokens. Blank leaves it uncapped.",- placeholder="(uncapped)",- group="Recall",- ),- ProviderField(- key="initOnSessionStart",- label="Eager init",- kind=KIND_BOOL,- default="false",- description="Initialize the session eagerly in tools mode instead of on first tool call.",- group="Recall",- ),+ _field("recallMode", "Recall mode", KIND_SELECT, "How memory retrieval works: hybrid, context-only, or tools-only.",+ default="hybrid", info=_RECALL_MODE_INFO,+ options=_opts(("hybrid", "Hybrid"), ("context", "Context only"), ("tools", "Tools only")), group="Recall"),+ _field("contextTokens", "Context token cap", KIND_NUMBER, "Cap on auto-injected context tokens. Blank leaves it uncapped.",+ placeholder="(uncapped)", group="Recall"),+ _field("initOnSessionStart", "Eager init", KIND_BOOL,+ "Initialize the session eagerly in tools mode instead of on first tool call.", default="false", group="Recall"),# — Limits —- ProviderField(- key="messageMaxChars",- label="Message max chars",- kind=KIND_NUMBER,- description="Max chars per message sent to Honcho.",- placeholder="25000",- group="Limits",- ),+ _field("messageMaxChars", "Message max chars", KIND_NUMBER, "Max chars per message sent to Honcho.",+ placeholder="25000", group="Limits"),# — Observation —- ProviderField(- key="observationMode",- label="Observation mode",- kind=KIND_SELECT,- default="directional",- description="Per-peer observation preset. Directional observes all directions; unified shares one view.",- options=(- ProviderFieldOption("directional", "Directional"),- ProviderFieldOption("unified", "Unified"),- ),- group="Observation",- ),+ _field("observationMode", "Observation mode", KIND_SELECT,+ "Per-peer observation preset. Directional observes all directions; unified shares one view.",+ default="directional", options=_opts(("directional", "Directional"), ("unified", "Unified")), group="Observation"),),)diff --git a/plugins/memory/honcho/dialectic.py b/plugins/memory/honcho/dialectic.pynew file mode 100644index 00000000000..e9630f6f1ca--- /dev/null+++ b/plugins/memory/honcho/dialectic.py@@ -0,0 +1,215 @@+"""Dialectic layer for HonchoMemoryProvider: multi-pass reasoning, cadence/backoff, liveness."""++from __future__ import annotations++import logging+import re+import threading+import time++from plugins.memory.honcho.client import spawn_context_thread++logger = logging.getLogger("plugins.memory.honcho")+++class DialecticMixin:+ """Dialectic prefetch state machine. State attributes are initialised in+ HonchoMemoryProvider.__init__; this mixin only reads/writes them."""++ # Reasoning level per (depth, pass) when dialecticDepthLevels is not configured;+ # "base" means dialecticReasoningLevel. Early passes of deeper runs are lighter.+ _PROPORTIONAL_LEVELS: dict[tuple[int, int], str] = {+ (1, 0): "base", (2, 0): "minimal", (2, 1): "base", (3, 0): "minimal", (3, 1): "base", (3, 2): "low",+ }++ _LEVEL_ORDER = ("minimal", "low", "medium", "high", "max")++ # Char-count thresholds for the query-length reasoning heuristic.+ _HEURISTIC_LENGTH_MEDIUM = 120+ _HEURISTIC_LENGTH_HIGH = 400++ # A thread older than timeout × multiplier is treated as dead so a hung Honcho+ # call can't block future fires indefinitely.+ _STALE_THREAD_MULTIPLIER = 2.0+ # A pending result fired more than cadence × multiplier turns ago is discarded on+ # read, so a stale conversational pivot isn't injected after trivial-prompt turns.+ _STALE_RESULT_MULTIPLIER = 2+ # Ceiling for the empty-streak backoff (× base cadence).+ _BACKOFF_MAX = 8+ # Turn-1 budgets: session init + base retrieval share the first; dialectic gets the second.+ _FIRST_TURN_BASE_TIMEOUT = 3.0+ _FIRST_TURN_DIALECTIC_CAP = 2.0++ def _thread_is_live(self) -> bool:+ """Thread-alive guard that treats threads past the stale threshold as dead."""+ if not self._prefetch_thread or not self._prefetch_thread.is_alive():+ return False+ timeout = (self._config.timeout if self._config and self._config.timeout else 8.0)+ age = time.monotonic() - self._prefetch_thread_started_at+ stale_after = timeout * self._STALE_THREAD_MULTIPLIER+ if age > stale_after:+ logger.debug("Honcho prefetch thread age %.1fs exceeds stale threshold %.1fs — treating as dead", age, stale_after)+ return False+ return True++ def _effective_cadence(self) -> int:+ """Cadence plus empty-streak backoff, capped at _BACKOFF_MAX × base."""+ if self._dialectic_empty_streak <= 0:+ return self._dialectic_cadence+ return min(self._dialectic_cadence + self._dialectic_empty_streak, self._dialectic_cadence * self._BACKOFF_MAX)++ def _note_dialectic_failure(self, exc: BaseException) -> None:+ """Widen the empty-streak backoff after a failed cycle; auth failures are exempt+ because waiting cannot fix a dead token."""+ from plugins.memory.honcho.session import HonchoAuthError++ if isinstance(exc, HonchoAuthError):+ logger.warning("Honcho dialectic auth failure (not counted toward cadence backoff): %s", exc)+ return+ self._dialectic_empty_streak += 1++ def _spawn_dialectic(+ self, query: str, *, thread_name: str, fired_at: int, log_label: str,+ use_query_rewrite: bool = True,+ ) -> threading.Thread:+ """Start a background dialectic run that publishes into the pending-result slot.++ Only a non-empty result advances ``_last_dialectic_turn`` (so empty returns+ retry next turn) and resets the empty streak; failures widen the backoff.+ """+ def _run() -> None:+ try:+ r = self._run_dialectic_depth(query, use_query_rewrite=use_query_rewrite)+ except Exception as exc:+ logger.debug("Honcho %s failed: %s", log_label, exc)+ self._note_dialectic_failure(exc)+ return+ if r and r.strip():+ with self._prefetch_lock:+ self._prefetch_result = r+ self._prefetch_result_fired_at = fired_at+ self._last_dialectic_turn = fired_at+ self._dialectic_empty_streak = 0+ else:+ self._dialectic_empty_streak += 1++ self._prefetch_thread_started_at = time.monotonic()+ thread = spawn_context_thread(_run, name=thread_name)+ thread.start()+ self._prefetch_thread = thread+ return thread++ def _consume_pending_dialectic(self) -> str:+ """Pop the pending dialectic result, or "" when none is ready or it is stale."""+ with self._prefetch_lock:+ dialectic_result, fired_at = self._prefetch_result, self._prefetch_result_fired_at+ self._prefetch_result, self._prefetch_result_fired_at = "", -999++ stale_limit = self._dialectic_cadence * self._STALE_RESULT_MULTIPLIER+ if dialectic_result and fired_at >= 0 and (self._turn_count - fired_at) > stale_limit:+ logger.debug("Honcho pending dialectic discarded as stale: fired_at=%d, turn=%d, limit=%d",+ fired_at, self._turn_count, stale_limit)+ return ""+ return dialectic_result if (dialectic_result and dialectic_result.strip()) else ""++ def _apply_reasoning_heuristic(self, base: str, query: str) -> str:+ """Scale ``base`` up by query length (+1 at >=120 chars, +2 at >=400), clamped at reasoning_level_cap."""+ if not self._reasoning_heuristic or not query or base not in self._LEVEL_ORDER:+ return base+ n = len(query)+ bump = 0 if n < self._HEURISTIC_LENGTH_MEDIUM else 1 if n < self._HEURISTIC_LENGTH_HIGH else 2+ base_idx = self._LEVEL_ORDER.index(base)+ cap_idx = self._LEVEL_ORDER.index(self._reasoning_level_cap)+ return self._LEVEL_ORDER[min(base_idx + bump, cap_idx)]++ def _resolve_pass_level(self, pass_idx: int, query: str = "") -> str:+ """Reasoning level for a pass: explicit dialecticDepthLevels win, then the+ proportional table, then the base level scaled by the length heuristic."""+ if self._dialectic_depth_levels and pass_idx < len(self._dialectic_depth_levels):+ return self._dialectic_depth_levels[pass_idx]++ base = (self._config.dialectic_reasoning_level if self._config else "low")+ mapping = self._PROPORTIONAL_LEVELS.get((self._dialectic_depth, pass_idx))+ if mapping is None or mapping == "base":+ return self._apply_reasoning_heuristic(base, query)+ return mapping++ def _build_dialectic_prompt(self, pass_idx: int, prior_results: list[str], is_cold: bool) -> str:+ """Pass 0: cold (general) or warm (session-scoped) query; pass 1: gap audit+ against the prior result; pass 2: reconciliation across prior passes."""+ if pass_idx == 0:+ if is_cold:+ return (+ "Who is this person? What are their preferences, goals, and working style? "+ "Focus on facts that would help an AI assistant be immediately useful."+ )+ return (+ "Given what's been discussed in this session so far, what context about this user is most "+ "relevant to the current conversation? Prioritize active context over biographical facts."+ )+ if pass_idx == 1:+ prior = prior_results[-1] if prior_results else ""+ return (+ f"Given this initial assessment:\n\n{prior}\n\n"+ "What gaps remain in your understanding that would help going forward? Synthesize what you "+ "actually know about the user's current state and immediate needs, grounded in evidence from "+ "recent sessions."+ )+ passes = [prior_results[i] if len(prior_results) > i else "(empty)" for i in (0, 1)]+ return (+ f"Prior passes produced:\n\nPass 1:\n{passes[0]}\n\nPass 2:\n{passes[1]}\n\n"+ "Do these assessments cohere? Reconcile any contradictions and produce a final, concise "+ "synthesis of what matters most for the current conversation."+ )++ @staticmethod+ def _signal_sufficient(result: str) -> bool:+ """True when a pass returned enough signal to skip further passes: >100 chars+ with structure (headers/bullets/ordered list), or >300 chars regardless."""+ if not result or len(result.strip()) < 100:+ return False+ structured = "\n" in result and bool(+ "##" in result or "•" in result or re.search(r"^(?:[*-] |\s*\d+\. )", result, re.MULTILINE)+ )+ return structured or len(result.strip()) > 300++ def _run_dialectic_depth(self, query: str, *, use_query_rewrite: bool = True) -> str:+ """Run up to dialecticDepth .chat() passes, bailing early once a pass returns+ strong signal. Returns the last non-empty result."""+ if not self._manager or not self._session_key:+ return ""++ is_cold = not self._base_context_cache+ results: list[str] = []+ rewritten_query = ""+ if use_query_rewrite and self._query_rewrite_enabled and self._query_rewriter:+ try:+ rewritten_query = self._query_rewriter(query).strip()+ except Exception as exc:+ logger.debug("Honcho query rewriter failed: %s", exc)++ for i in range(self._dialectic_depth):+ # Dependent prompts require a non-empty prior result; without one, later+ # passes retry the independent base prompt.+ prior_results = [r for r in results if r and r.strip()]+ if prior_results and self._signal_sufficient(prior_results[-1]):+ logger.debug("Honcho dialectic depth %d: pass %d skipped, prior signal sufficient",+ self._dialectic_depth, i)+ break+ if prior_results:+ prompt = self._build_dialectic_prompt(i, prior_results, is_cold)+ else:+ if i:+ logger.debug("Honcho dialectic depth %d: pass %d has no non-empty prior — "+ "falling back to base prompt", self._dialectic_depth, i)+ prompt = rewritten_query or self._build_dialectic_prompt(0, prior_results, is_cold)++ level = self._resolve_pass_level(i, query=query)+ logger.debug("Honcho dialectic depth %d: pass %d, level=%s, cold=%s",+ self._dialectic_depth, i, level, is_cold)+ result = self._manager.dialectic_query(+ self._session_key, prompt, reasoning_level=level, peer="user",+ )+ results.append(result or "")++ return next((r for r in reversed(results) if r and r.strip()), "")diff --git a/plugins/memory/honcho/oauth.py b/plugins/memory/honcho/oauth.pyindex a51f03cf3e6..8adbd465850 100644--- a/plugins/memory/honcho/oauth.py+++ b/plugins/memory/honcho/oauth.py@@ -1,18 +1,16 @@"""OAuth credential storage and refresh for the Honcho memory provider.-An access token authenticates exactly like a scoped API key, so it is stored-as the host's ``apiKey``; this module exchanges the refresh token before-expiry to keep it live.--Refresh tokens rotate with single-use reuse detection: a replayed stale token-revokes the whole grant. So every refresh must persist the rotated token-atomically and be serialized. A failed exchange never raises into the agent:-transient failures retry once immediately (the server re-rotates a replayed-refresh token only within a short grace window, so waiting for the next-memory call is too late), and a permanent OAuth error such as invalid_grant-marks the grant dead so nothing keeps hitting the token endpoint — callers-surface a re-login prompt instead. A server-side 401 on a locally-valid-token is recovered via ``force_refresh_token``.+An access token authenticates like a scoped API key, so it is stored as the+host's ``apiKey``; the refresh token is exchanged before expiry to keep it live.++Refresh tokens rotate with single-use reuse detection: replaying a stale token+revokes the grant, so every refresh persists the rotated token atomically and is+serialized (in-process lock + cross-process file lock). A failed exchange never+raises into the agent: transient failures retry once immediately (the replay+grace window is short); a permanent error such as invalid_grant marks the grant+dead so nothing keeps hitting the endpoint and callers surface a re-login+prompt. A server-side 401 on a locally-valid token is recovered via+``force_refresh_token``."""from __future__ import annotations@@ -24,44 +22,29 @@ import osimport reimport threadingimport time-from contextlib import contextmanager+from contextlib import contextmanager, suppressfrom dataclasses import dataclassfrom pathlib import Path-from typing import Any, Callable+from typing import Anylogger = logging.getLogger(__name__)ACCESS_TOKEN_PREFIX = "hch-at-"REFRESH_TOKEN_PREFIX = "hch-rt-"-# Refresh this many seconds before the access token actually expires, so an-# in-flight request never races the expiry boundary.-_REFRESH_SKEW_SECONDS = 120--# Default HTTP timeout for the token exchange. Kept short — the refresh happens-# on the path to a memory call, and a stalled auth server must not hang it.-_REFRESH_TIMEOUT_SECONDS = 15.0--# Retry pause, kept short: the server honors a replayed refresh token only briefly after rotating it.-_REFRESH_RETRY_DELAY_SECONDS = 2.0--# Total wall-clock budget for one exchange cycle (first attempt + pause + retry).-# The exchange runs while holding the global refresh locks on the path to a-# memory call, so a stalled token endpoint must not hold them for two full-# HTTP timeouts back to back.+_REFRESH_SKEW_SECONDS = 120 # refresh this early so an in-flight request never races expiry+_REFRESH_TIMEOUT_SECONDS = 15.0 # short: sits on the path to a memory call+_REFRESH_RETRY_DELAY_SECONDS = 2.0 # replayed refresh tokens are honored only briefly after rotation+# Cap for one exchange cycle (attempt + pause + retry): it runs under the global+# refresh locks, so it must not hold them for two full HTTP timeouts._REFRESH_TOTAL_BUDGET_SECONDS = 20.0--# After a transient exchange failure, fail open without re-exchanging for this-# long. Prevents N waiting threads (or turns) from serializing N full exchange-# cycles against an endpoint that just failed.+# After a transient failure, fail open without re-exchanging for this long so N+# waiting threads don't serialize N exchange cycles against a failing endpoint._REFRESH_FAILURE_COOLDOWN_SECONDS = 30.0--# OAuth error codes that a retry can never fix — the grant itself is dead.+# OAuth error codes a retry can never fix — the grant itself is dead._PERMANENT_OAUTH_ERRORS = frozenset({"invalid_grant", "invalid_client", "unauthorized_client"})-# Token values are secret even though their prefixes are not; redact before logging.-# Derived from the canonical prefixes above so a prefix change can't silently-# break redaction.+# Derived from the canonical prefixes so a prefix change can't silently break redaction._TOKEN_VALUE_RE = re.compile(rf"({re.escape(ACCESS_TOKEN_PREFIX)}|{re.escape(REFRESH_TOKEN_PREFIX)})[A-Za-z0-9._~+/=-]+")@@ -72,8 +55,7 @@ def redact_tokens(text: str) -> str:return _TOKEN_VALUE_RE.sub(lambda m: f"{m.group(1)}[redacted]", text)-# Backward-compat alias for oauth-internal call sites and older importers.-_redact_tokens = redact_tokens+_redact_tokens = redact_tokens # backward-compat alias for older importersclass OAuthRefreshError(Exception):@@ -84,37 +66,35 @@ class OAuthRefreshError(Exception):self.error = errorself.permanent = permanent-# Serializes refresh across threads sharing one process's config. Re-checked-# under the lock (double-checked) so racing callers don't replay a rotated-# refresh token and trip reuse detection.++# Serializes refresh across threads; state is re-checked under it so racing+# callers don't replay a rotated refresh token._refresh_lock = threading.Lock()+def _os_lock(fh, lock: bool) -> None:+ if os.name == "nt":+ import msvcrt++ fh.seek(0)+ msvcrt.locking(fh.fileno(), msvcrt.LK_LOCK if lock else msvcrt.LK_UNLCK, 1)+ else:+ import fcntl++ fcntl.flock(fh.fileno(), fcntl.LOCK_EX if lock else fcntl.LOCK_UN)++@contextmanagerdef _config_refresh_lock(path: Path):- """Machine-wide advisory lock around read-refresh-persist.-- The in-process ``_refresh_lock`` can't stop a second process (a sibling- Hermes profile or the desktop app sharing this honcho.json) from replaying- the single-use refresh token and tripping reuse-detection — which revokes- the whole grant. An OS file lock on ``<config>.lock`` serializes rotation- across processes; best-effort, so a platform without flock degrades to- in-process serialization only.- """- lock_path = Path(f"{path}.lock")+ """Machine-wide advisory lock (``<config>.lock``) around read-refresh-persist:+ a sibling process sharing this honcho.json must not replay the single-use+ refresh token. Best-effort — without flock it degrades to in-process only."""fh = Nonetry:+ lock_path = Path(f"{path}.lock")lock_path.parent.mkdir(parents=True, exist_ok=True)fh = open(lock_path, "a+b")- if os.name == "nt":- import msvcrt-- fh.seek(0)- msvcrt.locking(fh.fileno(), msvcrt.LK_LOCK, 1)- else:- import fcntl-- fcntl.flock(fh.fileno(), fcntl.LOCK_EX)+ _os_lock(fh, True)except Exception:logger.debug("Honcho OAuth cross-process lock unavailable; in-process only", exc_info=True)if fh is not None:@@ -124,52 +104,30 @@ def _config_refresh_lock(path: Path):yieldfinally:if fh is not None:- try:- if os.name == "nt":- import msvcrt-- fh.seek(0)- msvcrt.locking(fh.fileno(), msvcrt.LK_UNLCK, 1)- else:- import fcntl-- fcntl.flock(fh.fileno(), fcntl.LOCK_UN)- except Exception:- pass+ with suppress(Exception):+ _os_lock(fh, False)fh.close()-# In-memory expiry cache keyed by (config path, host) → (expires_at, access).-# Lets the hot path (every memory access calls this) skip the honcho.json read-# while the token is comfortably live; disk is only touched near expiry, on a-# cache miss, or when an explicit ``raw`` is supplied. Single-key dict ops are-# atomic under the GIL, so no separate lock is needed. An access token stays-# valid until its own expiry regardless of out-of-band rotation, so a stale-# cache entry can't break auth — it just defers picking up external changes-# until the token nears expiry and disk is read again.-_expiry_cache: dict[tuple[str, str], tuple[float, str]] = {}-# Permanently rejected grants: (config path, host) → sha256 of the dead refresh token; a re-login rotates the token, so the digest check self-clears.+# Per-grant state keyed by (config path, host); single-key dict ops are atomic+# under the GIL, so no separate lock.+# (expires_at, access): lets the hot path skip the honcho.json read while the+# token is well clear of expiry. A stale entry can't break auth (the token stays+# valid until its own expiry); it only defers noticing out-of-band rotation.+_expiry_cache: dict[tuple[str, str], tuple[float, str]] = {}+# sha256 of the permanently rejected refresh token; a re-login rotates the+# token, so the digest comparison self-clears._dead_grants: dict[tuple[str, str], str] = {}--# Last transient exchange failure per grant: key → monotonic timestamp. While-# inside the cooldown window callers fail open to the stale token without-# re-exchanging, so waiting threads don't serialize repeated full exchange-# cycles against an endpoint that just failed.+# monotonic time of the last transient exchange failure (drives the fail-open cooldown)._refresh_failure_at: dict[tuple[str, str], float] = {}+# (config mtime_ns, verdict): reauth_required only changes when the file is+# rewritten, so an unchanged mtime skips the parse.+_reauth_check_cache: dict[tuple[str, str], tuple[int, bool]] = {}def _in_failure_cooldown(key: tuple[str, str]) -> bool:failed_at = _refresh_failure_at.get(key)- return (- failed_at is not None- and (time.monotonic() - failed_at) < _REFRESH_FAILURE_COOLDOWN_SECONDS- )---# Memoized reauth_required verdict per grant: key → (config mtime_ns, result).-# The verdict only changes when the config file is rewritten (re-login), so an-# unchanged mtime short-circuits the read+parse on the dead-grant hot path.-_reauth_check_cache: dict[tuple[str, str], tuple[int, bool]] = {}+ return failed_at is not None and (time.monotonic() - failed_at) < _REFRESH_FAILURE_COOLDOWN_SECONDSdef _refresh_token_digest(cred: OAuthCredential) -> str:@@ -182,8 +140,13 @@ def _grant_is_dead(key: tuple[str, str], cred: OAuthCredential) -> bool:def _mark_grant_dead(key: tuple[str, str], cred: OAuthCredential) -> None:_dead_grants[key] = _refresh_token_digest(cred)- # The verdict changed without a config rewrite; drop any memoized answer.- _reauth_check_cache.pop(key, None)+ _reauth_check_cache.pop(key, None) # verdict changed without a config rewrite+++def _load_cred(path: Path, host: str, raw: dict[str, Any] | None = None) -> OAuthCredential | None:+ """Credential from ``host``'s block in ``raw`` (or the file at ``path``)."""+ source = raw if raw is not None else _read_config(path)+ return OAuthCredential.from_host_block((source.get("hosts") or {}).get(host) or {})def reauth_required(path: Path, host: str) -> bool:@@ -191,8 +154,6 @@ def reauth_required(path: Path, host: str) -> bool:key = (str(path), host)if key not in _dead_grants:return False- # A re-login rewrites the config file, so gate the read+parse on mtime:- # while the file is unchanged the answer cannot change.try:mtime = path.stat().st_mtime_nsexcept OSError:@@ -200,22 +161,25 @@ def reauth_required(path: Path, host: str) -> bool:cached = _reauth_check_cache.get(key)if cached is not None and cached[0] == mtime:return cached[1]- block = (_read_config(path).get("hosts") or {}).get(host) or {}- cred = OAuthCredential.from_host_block(block)+ cred = _load_cred(path, host)result = cred is not None and _grant_is_dead(key, cred)_reauth_check_cache[key] = (mtime, result)return resultdef any_dead_grants() -> bool:- """Cheap predicate: has any grant in this process been marked dead?-- Lets hot-path callers skip config-path resolution entirely in the- overwhelmingly common healthy state.- """+ """Cheap predicate letting hot-path callers skip config resolution when healthy."""return bool(_dead_grants)+def _num(value, cast):+ """``cast(value)``, or ``cast(0)`` when the stored value is malformed."""+ try:+ return cast(value)+ except (TypeError, ValueError):+ return cast(0)++def is_oauth_access_token(value: str | None) -> bool:"""True when ``value`` is an OAuth access token (vs a static API key)."""return bool(value) and value.startswith(ACCESS_TOKEN_PREFIX)@@ -223,11 +187,9 @@ def is_oauth_access_token(value: str | None) -> bool:@dataclassclass OAuthCredential:- """An OAuth grant as stored in a honcho.json host block.-- ``access_token`` mirrors the host's ``apiKey``; the remaining fields live in- the host's ``oauth`` sub-block. ``expires_at`` is absolute epoch seconds.- """+ """An OAuth grant as stored in a honcho.json host block: ``access_token`` is+ the host's ``apiKey``, the rest lives in its ``oauth`` sub-block.+ ``expires_at`` is absolute epoch seconds."""access_token: strrefresh_token: str@@ -246,25 +208,45 @@ class OAuthCredential:access = block.get("apiKey")if not isinstance(oauth, dict) or not is_oauth_access_token(access):return None- refresh = oauth.get("refreshToken")- endpoint = oauth.get("tokenEndpoint")- client_id = oauth.get("clientId")+ refresh, endpoint, client_id = oauth.get("refreshToken"), oauth.get("tokenEndpoint"), oauth.get("clientId")if not (refresh and endpoint and client_id):return None- try:- expires_at = float(oauth.get("expiresAt", 0))- except (TypeError, ValueError):- expires_at = 0.0return cls(access_token=access,refresh_token=str(refresh),- expires_at=expires_at,+ expires_at=_num(oauth.get("expiresAt", 0), float),client_id=str(client_id),token_endpoint=str(endpoint),scope=str(oauth.get("scope", "write")),token_type=str(oauth.get("tokenType", "Bearer")),)+ @classmethod+ def from_token_response(+ cls,+ body: dict[str, Any],+ *,+ now: float,+ client_id: str,+ token_endpoint: str,+ scope: str = "write",+ token_type: str = "Bearer",+ what: str = "grant",+ ) -> "OAuthCredential":+ """Build a credential from an OAuth token response; ``expires_in`` is relative to ``now``."""+ access, refresh = body.get("access_token"), body.get("refresh_token")+ if not is_oauth_access_token(access) or not refresh:+ raise ValueError(f"{what} missing access_token/refresh_token")+ return cls(+ access_token=access,+ refresh_token=str(refresh),+ expires_at=now + _num(body.get("expires_in", 0), int),+ client_id=client_id,+ token_endpoint=token_endpoint,+ scope=str(body.get("scope", scope)),+ token_type=str(body.get("token_type", token_type)),+ )+def oauth_block(self) -> dict[str, Any]:"""The ``oauth`` sub-block to persist (the access token lives in apiKey)."""return {@@ -281,61 +263,39 @@ class OAuthCredential:return now >= (self.expires_at - skew)-# Indirection so tests can drive the exchange without a live server.-def _http_post_form(url: str, data: dict[str, str], timeout: float) -> dict[str, Any]:- """POST form-encoded ``data`` to ``url`` and return the parsed JSON body."""+# HTTP indirection: tests monkeypatch these module attributes, and the refresh+# path looks them up at call time.+def _http_json(method: str, url: str, *, data=None, timeout: float, strict: bool = True) -> tuple[int, Any]:+ """Return ``(status, parsed JSON body)``. ``strict`` raises on non-2xx /+ non-JSON; otherwise a 4xx passes through (RFC 8628 polling reads the OAuth+ error off a 400) and a non-JSON / non-object body parses to ``{}``."""import httpx- resp = httpx.post(url, data=data, timeout=timeout)- resp.raise_for_status()- return resp.json()---def _http_post_form_status(- url: str, data: dict[str, str], timeout: float-) -> tuple[int, dict[str, Any]]:- """POST form-encoded ``data``; return ``(status, parsed JSON body)``.-- Unlike ``_http_post_form``, 4xx does not raise — RFC 8628 polling reads the- OAuth error body off a 400. A non-JSON body parses to ``{}``.- """- import httpx-- resp = httpx.post(url, data=data, timeout=timeout)+ resp = httpx.request(method, url, data=data, timeout=timeout)+ if strict:+ resp.raise_for_status()+ return resp.status_code, resp.json()try:body = resp.json()except ValueError:body = {}- if not isinstance(body, dict):- body = {}- return resp.status_code, body-+ return resp.status_code, body if isinstance(body, dict) else {}-def _http_get_json(url: str, timeout: float) -> dict[str, Any]:- """GET ``url`` and return the parsed JSON body. Raises on non-2xx/non-JSON."""- import httpx- resp = httpx.get(url, timeout=timeout)- resp.raise_for_status()- body = resp.json()- return body if isinstance(body, dict) else {}+def _http_post_form_status(url: str, data: dict[str, str], timeout: float) -> tuple[int, dict[str, Any]]:+ """POST form-encoded ``data``; return ``(status, body)`` without raising on 4xx."""+ return _http_json("POST", url, data=data, timeout=timeout, strict=False)def _exchange_refresh_token(cred: OAuthCredential, *, now: float, timeout: float = _REFRESH_TIMEOUT_SECONDS) -> OAuthCredential:- """Run the refresh_token grant and return the rotated credential.-- Raises ``OAuthRefreshError`` (with the endpoint's error body) on an error- response, transport errors as-is; callers fail open.- """+ """Run the refresh_token grant and return the rotated credential. Raises+ ``OAuthRefreshError`` (with the endpoint's error body) on an error response,+ transport errors as-is; callers fail open."""status, body = _http_post_form_status(cred.token_endpoint,- {- "grant_type": "refresh_token",- "client_id": cred.client_id,- "refresh_token": cred.refresh_token,- },+ {"grant_type": "refresh_token", "client_id": cred.client_id, "refresh_token": cred.refresh_token},timeout,)if status >= 400:@@ -347,34 +307,16 @@ def _exchange_refresh_token(error=error,permanent=error in _PERMANENT_OAUTH_ERRORS,)- access = body.get("access_token")- refresh = body.get("refresh_token")- if not is_oauth_access_token(access) or not refresh:- raise ValueError("refresh response missing access_token/refresh_token")- try:- expires_in = int(body.get("expires_in", 0))- except (TypeError, ValueError):- expires_in = 0- return OAuthCredential(- access_token=access,- refresh_token=str(refresh),- expires_at=now + expires_in,- client_id=cred.client_id,- token_endpoint=cred.token_endpoint,- scope=str(body.get("scope", cred.scope)),- token_type=str(body.get("token_type", cred.token_type)),+ return OAuthCredential.from_token_response(+ body, now=now, client_id=cred.client_id, token_endpoint=cred.token_endpoint,+ scope=cred.scope, token_type=cred.token_type, what="refresh response",)def _exchange_with_retry(cred: OAuthCredential, *, now: float) -> OAuthCredential:- """Exchange the refresh token, retrying once on transient failure.-- The server accepts a replayed token only briefly after rotating it, so the- retry cannot wait — and the whole cycle is capped by- ``_REFRESH_TOTAL_BUDGET_SECONDS`` because it runs under the global refresh- locks: a fast first failure gets a full-timeout retry, a slow (timed-out)- first attempt gets only the remaining budget.- """+ """Exchange the refresh token, retrying once on transient failure. The retry+ cannot wait (replay grace window is short) and the cycle is capped by+ ``_REFRESH_TOTAL_BUDGET_SECONDS`` because it runs under the refresh locks."""deadline = time.monotonic() + _REFRESH_TOTAL_BUDGET_SECONDStry:return _exchange_refresh_token(cred, now=now)@@ -387,14 +329,9 @@ def _exchange_with_retry(cred: OAuthCredential, *, now: float) -> OAuthCredentiaremaining = deadline - time.monotonic() - _REFRESH_RETRY_DELAY_SECONDSif remaining <= 0:raise first- logger.warning(- "Honcho OAuth token exchange failed, retrying once: %s",- _redact_tokens(str(first)),- )+ logger.warning("Honcho OAuth token exchange failed, retrying once: %s", _redact_tokens(str(first)))time.sleep(_REFRESH_RETRY_DELAY_SECONDS)- return _exchange_refresh_token(- cred, now=now, timeout=min(remaining, _REFRESH_TIMEOUT_SECONDS)- )+ return _exchange_refresh_token(cred, now=now, timeout=min(remaining, _REFRESH_TIMEOUT_SECONDS))def _rotate_and_persist(@@ -407,10 +344,8 @@ def _rotate_and_persist(op_label: str = "refresh",) -> OAuthCredential | None:"""Exchange ``cred`` and persist the rotation; ``None`` on failure (logged).-- A permanent OAuth error marks the grant dead so later calls skip the- endpoint until a new login rotates the refresh token.- """+ A permanent OAuth error marks the grant dead so later calls skip the endpoint+ until a new login rotates the refresh token."""try:rotated = _exchange_with_retry(cred, now=now)except OAuthRefreshError as exc:@@ -420,16 +355,13 @@ def _rotate_and_persist("Honcho OAuth grant for host %s is no longer valid (%s); ""run 'hermes honcho setup' to re-authenticate", host, exc,)- else:- _refresh_failure_at[key] = time.monotonic()- logger.warning("Honcho OAuth %s failed for host %s: %s", op_label, host, exc)+ return None+ _refresh_failure_at[key] = time.monotonic()+ logger.warning("Honcho OAuth %s failed for host %s: %s", op_label, host, exc)return Noneexcept Exception as exc:_refresh_failure_at[key] = time.monotonic()- logger.warning(- "Honcho OAuth %s failed for host %s: %s",- op_label, host, _redact_tokens(str(exc)),- )+ logger.warning("Honcho OAuth %s failed for host %s: %s", op_label, host, _redact_tokens(str(exc)))return None_persist_credential(path, host, rotated)return rotated@@ -443,14 +375,13 @@ def _read_config(path: Path) -> dict[str, Any]:def _atomic_write_config(path: Path, raw: dict[str, Any]) -> None:- """Write ``raw`` to ``path`` atomically, preserving 0600 on the new file."""+ """Write ``raw`` to ``path`` atomically with 0600 on the new file."""path.parent.mkdir(parents=True, exist_ok=True)tmp = path.with_name(f".{path.name}.tmp")- text = json.dumps(raw, indent=2) + "\n"fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)try:with os.fdopen(fd, "w", encoding="utf-8") as fh:- fh.write(text)+ fh.write(json.dumps(raw, indent=2) + "\n")except Exception:tmp.unlink(missing_ok=True)raise@@ -467,17 +398,18 @@ def _deep_merge(base: dict[str, Any], overlay: dict[str, Any]) -> dict[str, Any]return base-def _persist_credential(path: Path, host: str, cred: OAuthCredential) -> None:- """Persist ``cred`` into ``host``'s block (apiKey + oauth), leaving all else intact."""- raw = _read_config(path)- hosts = raw.setdefault("hosts", {})- block = hosts.setdefault(host, {})+def _persist_credential(path: Path, host: str, cred: OAuthCredential, raw: dict[str, Any] | None = None) -> None:+ """Write ``cred`` into ``host``'s block (apiKey + oauth) of ``raw`` (default:+ the file's current content), leaving the rest intact; marks the grant live."""+ raw = _read_config(path) if raw is None else raw+ block = raw.setdefault("hosts", {}).setdefault(host, {})block["apiKey"] = cred.access_tokenblock["oauth"] = cred.oauth_block()_atomic_write_config(path, raw)- _expiry_cache[(str(path), host)] = (cred.expires_at, cred.access_token)- _dead_grants.pop((str(path), host), None)- _refresh_failure_at.pop((str(path), host), None)+ key = (str(path), host)+ _expiry_cache[key] = (cred.expires_at, cred.access_token)+ _dead_grants.pop(key, None)+ _refresh_failure_at.pop(key, None)def ensure_fresh_token(@@ -488,49 +420,37 @@ def ensure_fresh_token(now: float | None = None,) -> tuple[str | None, bool]:"""Return ``(access_token, refreshed)`` for ``host``, refreshing if near expiry.-- Returns ``(None, False)`` when the host has no OAuth credential (e.g. a plain- API key) so callers leave the existing token untouched. Refresh failures are- swallowed: the current (possibly stale) token is returned with- ``refreshed=False``, transient failures retry once immediately, and a- permanently rejected grant is marked dead so later calls skip the endpoint.- The 401 recovery in session.py escalates dead grants to the user.- """+ ``(None, False)`` when the host has no OAuth credential (plain API key).+ Refresh failures are swallowed: the current (possibly stale) token comes back+ with ``refreshed=False``; a permanently rejected grant is marked dead and the+ session's 401 recovery escalates it to the user."""now = time.time() if now is None else nowkey = (str(path), host)- # Hot path: trust the cached expiry while the token is well clear of the- # skew window — no disk read. Bypassed when an explicit ``raw`` is supplied.+ # Hot path: trust the cached expiry while well clear of the skew window (no+ # disk read). Bypassed when an explicit ``raw`` is supplied.if raw is None:cached = _expiry_cache.get(key)if cached is not None and now < cached[0] - _REFRESH_SKEW_SECONDS:return cached[1], False- source = raw if raw is not None else _read_config(path)- block = (source.get("hosts") or {}).get(host) or {}- cred = OAuthCredential.from_host_block(block)+ cred = _load_cred(path, host, raw)if cred is None:_expiry_cache.pop(key, None)return None, False_expiry_cache[key] = (cred.expires_at, cred.access_token)- if not cred.is_expired(now=now):- return cred.access_token, False- if _in_failure_cooldown(key):- # An exchange just failed transiently; don't pile on the endpoint.+ if not cred.is_expired(now=now) or _in_failure_cooldown(key):return cred.access_token, Falsewith _refresh_lock, _config_refresh_lock(path):# Re-read under both locks: another thread or process may have just# rotated the token — adopt theirs instead of replaying the old one.- fresh_block = (_read_config(path).get("hosts") or {}).get(host) or {}- current = OAuthCredential.from_host_block(fresh_block) or cred+ current = _load_cred(path, host) or credif not current.is_expired(now=now):return current.access_token, current.access_token != cred.access_token- if _grant_is_dead(key, current):- return current.access_token, False- if _in_failure_cooldown(key):- # The lock holder we waited on just failed; fail open too.+ # The lock holder we waited on may have just failed; fail open too.+ if _grant_is_dead(key, current) or _in_failure_cooldown(key):return current.access_token, Falserotated = _rotate_and_persist(path, host, key, current, now=now)if rotated is None:@@ -540,23 +460,17 @@ def ensure_fresh_token(def force_refresh_token(path: Path, host: str) -> str | None:- """Rotate ``host``'s access token now, ignoring local expiry.-- Recovers a 401 on a token the local clock still thinks is valid.- """+ """Rotate ``host``'s token now, ignoring local expiry (recovers a 401 on a+ token the local clock still thinks is valid)."""now = time.time()key = (str(path), host)with _refresh_lock, _config_refresh_lock(path):- block = (_read_config(path).get("hosts") or {}).get(host) or {}- cred = OAuthCredential.from_host_block(block)+ cred = _load_cred(path, host)if cred is None:_expiry_cache.pop(key, None)return None- if _grant_is_dead(key, cred):- return None- if _in_failure_cooldown(key):- # An exchange just failed transiently; don't force another full- # cycle — callers fail open and retry after the cooldown.+ # Dead grant, or an exchange just failed transiently: callers fail open.+ if _grant_is_dead(key, cred) or _in_failure_cooldown(key):return Nonecached = _expiry_cache.get(key)# Another thread or process already rotated: adopt the newer on-disk token.@@ -580,59 +494,26 @@ def install_grant(apply_config: bool = True,now: float | None = None,) -> OAuthCredential:- """Apply a fresh OAuth grant to ``path`` for ``host``.-- Deep-merges the grant's ``config`` (the manifest default_config) into the- file root — preserving other hosts and root keys — then writes the host's- ``apiKey`` and ``oauth`` block. ``grant`` is an OAuthTokenResponse dict- (access_token, refresh_token, expires_in, scope, config).- ``apply_config=False`` skips the config merge and stores tokens only.- """+ """Apply a fresh OAuth grant (an OAuthTokenResponse dict) to ``path`` for ``host``.+ Deep-merges the grant's ``config`` into the file root (preserving other hosts+ and root keys), then writes the host's ``apiKey`` and ``oauth`` block.+ ``apply_config=False`` stores tokens only."""now = time.time() if now is None else now- access = grant.get("access_token")- refresh = grant.get("refresh_token")- if not is_oauth_access_token(access) or not refresh:- raise ValueError("grant missing access_token/refresh_token")- try:- expires_in = int(grant.get("expires_in", 0))- except (TypeError, ValueError):- expires_in = 0-- cred = OAuthCredential(- access_token=access,- refresh_token=str(refresh),- expires_at=now + expires_in,- client_id=client_id,- token_endpoint=token_endpoint,- scope=str(grant.get("scope", "write")),- token_type=str(grant.get("token_type", "Bearer")),- )-+ cred = OAuthCredential.from_token_response(grant, now=now, client_id=client_id, token_endpoint=token_endpoint)raw = _read_config(path)granted_config = grant.get("config")if isinstance(granted_config, dict):cred.consent_peer_name = granted_config.get("peerName")if apply_config:_deep_merge(raw, granted_config)- _expiry_cache[(str(path), host)] = (cred.expires_at, cred.access_token)- _dead_grants.pop((str(path), host), None)- _refresh_failure_at.pop((str(path), host), None)- hosts = raw.setdefault("hosts", {})- block = hosts.setdefault(host, {})- block["apiKey"] = cred.access_token- block["oauth"] = cred.oauth_block()- _atomic_write_config(path, raw)+ _persist_credential(path, host, cred, raw)return creddef apply_token_to_client(client: Any, token: str) -> bool:- """Rotate the live Honcho client's Bearer in place. Returns success.-- The SDK builds its auth header per request from the HTTP client's- ``api_key``, so mutating it rotates every holder of the singleton without a- rebuild. Guarded: an SDK shape change degrades to False and the caller can- fall back to resetting the client.- """+ """Rotate the live Honcho client's Bearer in place. The SDK builds its auth+ header per request from ``_http.api_key``, so mutating it rotates every+ holder of the singleton. Returns False on an SDK shape change (caller resets)."""http = getattr(client, "_http", None)if http is None or not hasattr(http, "api_key"):return Falsediff --git a/plugins/memory/honcho/oauth_flow.py b/plugins/memory/honcho/oauth_flow.pyindex b1268c02d44..90b784a36ab 100644--- a/plugins/memory/honcho/oauth_flow.py+++ b/plugins/memory/honcho/oauth_flow.py@@ -1,16 +1,16 @@"""Browser sign-in flow for the Honcho memory provider — no CLI step.``begin_authorization`` / ``complete_authorization`` are the transport-agnostic-core: the code can arrive via the loopback listener here or a future-``hermes://`` handler. Endpoints are env-overridable with local-dev defaults-because ``/authorize`` (dashboard) and ``/oauth/token`` (API) live on-different origins.+core (the code can arrive via the loopback listener here or a ``hermes://``+handler). Endpoints are env-overridable because ``/authorize`` (dashboard) and+``/oauth/token`` (API) live on different origins."""from __future__ import annotationsimport base64import hashlib+import htmlimport loggingimport osimport secrets@@ -27,29 +27,33 @@ from plugins.memory.honcho.client import resolve_active_host, resolve_config_patlogger = logging.getLogger(__name__)-# The loopback redirect registered for the Hermes OAuth client. IP-literal so-# the browser can't resolve the advertised host to ::1 and miss the IPv4 bind.+# Loopback redirect registered for the Hermes OAuth client. IP-literal so the+# browser can't resolve the advertised host to ::1 and miss the IPv4 bind.LOOPBACK_HOST = "127.0.0.1"LOOPBACK_PORT = 8765LOOPBACK_REDIRECT_URI = f"http://{LOOPBACK_HOST}:{LOOPBACK_PORT}/callback"-# Pending authorizations live only until their callback returns; keyed by the-# CSRF ``state`` so a stray/forged callback can't complete a grant.+# Pending authorizations are keyed by the CSRF ``state`` so a forged callback+# can't complete a grant; stale entries are swept after this TTL._PENDING_TTL_SECONDS = 600+# Cloud (production) hosts; dashboard serves /authorize, API serves /oauth/token.+_CLOUD_DASHBOARD = "https://app.honcho.dev"+_CLOUD_TOKEN_URL = "https://api.honcho.dev/oauth/token"+_LOCAL_DASHBOARD = "http://localhost:3000"+_LOCAL_TOKEN_URL = "http://localhost:8000/oauth/token"-def _display_config_path(path: object) -> str:- """Home-relative display string for the consent screen.+# One OAuth client for every surface (consent branding varies via ``source``), so+# there is a single grant identity to refresh — no clientId/refresh-token desync.+_DEFAULT_CLIENT_ID = "hermes-agent"- The absolute path (username + home layout) never leaves the machine — it's- only shown to the user. Collapse ``$HOME`` to ``~``; for a path outside- home, send the bare filename rather than leak an arbitrary absolute path.- """- from pathlib import Path as _Path- p = _Path(str(path))+def _display_config_path(path: object) -> str:+ """Home-relative display string for the consent screen (never the write path).+ A path outside ``$HOME`` yields the bare filename rather than leaking it."""+ p = Path(str(path))try:- return "~/" + str(p.relative_to(_Path.home()))+ return "~/" + str(p.relative_to(Path.home()))except ValueError:return p.name@@ -65,31 +69,14 @@ class OAuthEndpoints:device_authorization_url: str = "" # API /oauth/device_authorization-# Cloud (production) hosts; dashboard serves /authorize, API serves /oauth/token.-_CLOUD_DASHBOARD = "https://app.honcho.dev"-_CLOUD_TOKEN_URL = "https://api.honcho.dev/oauth/token"-_LOCAL_DASHBOARD = "http://localhost:3000"-_LOCAL_TOKEN_URL = "http://localhost:8000/oauth/token"--# One OAuth client for every surface. Consent branding/UI adapt via the-# ``source`` query param (not a separate client_id), so there's a single grant-# identity to refresh — no clientId-vs-refresh-token desync to revoke the grant.-_DEFAULT_CLIENT_ID = "hermes-agent"--def _is_loopback_url(url: str | None) -> bool:return bool(url) and any(h in url for h in ("localhost", "127.0.0.1", "::1"))-def resolve_endpoints(- environment: str | None = None, base_url: str | None = None-) -> OAuthEndpoints:- """Resolve OAuth endpoints, zero-config by default.-- Keys off the host's honcho ``environment`` (production → cloud, local →- localhost); a self-hosted ``base_url`` derives the token endpoint from the- API host. Env vars override every field for unusual deployments.- """+def resolve_endpoints(environment: str | None = None, base_url: str | None = None) -> OAuthEndpoints:+ """Resolve OAuth endpoints, zero-config by default: the host's honcho+ ``environment`` picks cloud vs localhost, a self-hosted ``base_url`` derives+ the token endpoint from the API host, and env vars override every field."""if environment is None or base_url is None:try:from plugins.memory.honcho.client import HonchoClientConfig@@ -103,8 +90,7 @@ def resolve_endpoints(is_local = (environment or "").lower() == "local" or _is_loopback_url(base_url)default_dashboard = _LOCAL_DASHBOARD if is_local else _CLOUD_DASHBOARDdefault_token = _LOCAL_TOKEN_URL if is_local else _CLOUD_TOKEN_URL- # Self-hosted API (non-loopback base_url): token rides the same host.- if base_url and not is_local:+ if base_url and not is_local: # self-hosted API: token rides the same hostdefault_token = f"{base_url.rstrip('/')}/oauth/token"dashboard = os.environ.get("HONCHO_OAUTH_DASHBOARD", default_dashboard).rstrip("/")@@ -134,20 +120,10 @@ _pending_lock = threading.Lock()def _pkce() -> tuple[str, str]:"""Return (verifier, S256 challenge) for an authorization-code request."""verifier = secrets.token_urlsafe(64)- challenge = (- base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest())- .rstrip(b"=")- .decode()- )+ challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()return verifier, challenge-def _prune_pending(now: float) -> None:- expired = [s for s, p in _pending.items() if now - p.created_at > _PENDING_TTL_SECONDS]- for state in expired:- _pending.pop(state, None)--def begin_authorization(endpoints: OAuthEndpoints,redirect_uri: str = LOOPBACK_REDIRECT_URI,@@ -157,27 +133,19 @@ def begin_authorization(now: float | None = None,) -> tuple[str, str]:"""Start an authorization: return ``(authorize_url, state)`` and stash PKCE.-- ``source`` tags the authorize link with the initiating surface- (``hermes-desktop`` / ``hermes-cli``) so the consent side can attribute- connects and vary behavior per surface. ``config_path`` is a home-relative- *display* string for the consent screen (never the absolute path); callers- pass the actual write path separately to ``complete_authorization``.- """+ ``source`` tags the initiating surface for consent branding; ``config_path``+ is the home-relative *display* string (the real write path goes to+ ``complete_authorization``)."""now = time.time() if now is None else nowverifier, challenge = _pkce()state = secrets.token_urlsafe(32)with _pending_lock:- _prune_pending(now)+ for stale in [s for s, p in _pending.items() if now - p.created_at > _PENDING_TTL_SECONDS]:+ _pending.pop(stale, None)_pending[state] = _Pending(verifier=verifier, redirect_uri=redirect_uri, created_at=now)params = {- "client_id": endpoints.client_id,- "redirect_uri": redirect_uri,- "scope": endpoints.scope,- "code_challenge": challenge,- "code_challenge_method": "S256",- "response_type": "code",- "state": state,+ "client_id": endpoints.client_id, "redirect_uri": redirect_uri, "scope": endpoints.scope,+ "code_challenge": challenge, "code_challenge_method": "S256", "response_type": "code", "state": state,}if source:params["source"] = source@@ -186,6 +154,34 @@ def begin_authorization(return f"{endpoints.authorize_url}?{urlencode(params)}", state+def _install(+ endpoints: OAuthEndpoints,+ grant: dict,+ *,+ path: Path | None,+ host: str | None,+ apply_config: bool,+ now: float | None,+ kind: str,+) -> oauth.OAuthCredential:+ """Persist ``grant`` for the target host; drop the cached client so the next+ acquisition uses the new token."""+ target_host = host or resolve_active_host()+ cred = oauth.install_grant(+ path or resolve_config_path(),+ target_host,+ grant,+ client_id=endpoints.client_id,+ token_endpoint=endpoints.token_url,+ apply_config=apply_config,+ now=now,+ )+ from plugins.memory.honcho.client import reset_honcho_client+ reset_honcho_client()+ logger.info("Honcho OAuth %sgrant installed for host %s", kind, target_host)+ return cred++def complete_authorization(endpoints: OAuthEndpoints,code: str,@@ -197,71 +193,38 @@ def complete_authorization(now: float | None = None,) -> oauth.OAuthCredential:"""Exchange ``code`` for a grant and persist it. Raises on bad state/exchange.-- ``apply_config=False`` stores the tokens only, skipping the grant's config- block — the CLI path, where settings stay wizard-owned.- """+ ``apply_config=False`` stores tokens only (CLI path: settings stay wizard-owned)."""with _pending_lock:pending = _pending.pop(state, None)if pending is None:raise ValueError("unknown or expired authorization state")- grant = oauth._http_post_form(- endpoints.token_url,- {- "grant_type": "authorization_code",- "client_id": endpoints.client_id,- "code": code,- "redirect_uri": pending.redirect_uri,- "code_verifier": pending.verifier,- },- oauth._REFRESH_TIMEOUT_SECONDS,+ _status_code, grant = oauth._http_json(+ "POST", endpoints.token_url, timeout=oauth._REFRESH_TIMEOUT_SECONDS,+ data={"grant_type": "authorization_code", "client_id": endpoints.client_id, "code": code,+ "redirect_uri": pending.redirect_uri, "code_verifier": pending.verifier},)+ return _install(endpoints, grant, path=config_path, host=host, apply_config=apply_config, now=now, kind="")- path = config_path or resolve_config_path()- target_host = host or resolve_active_host()- cred = oauth.install_grant(- path,- target_host,- grant,- client_id=endpoints.client_id,- token_endpoint=endpoints.token_url,- apply_config=apply_config,- now=now,- )- # Drop the singleton so the next acquisition builds with the new token.- from plugins.memory.honcho.client import reset_honcho_client-- reset_honcho_client()- logger.info("Honcho OAuth grant installed for host %s", target_host)- return cred---_CALLBACK_HTML = (- b"<!doctype html><meta charset=utf-8>"- b"<title>Honcho connected</title>"- b"<body style='font:14px ui-monospace,monospace;background:#0b0e14;color:#c9d1d9;"- b"display:flex;align-items:center;justify-content:center;height:100vh;margin:0'>"- b"<div>Connected to Honcho. You can close this tab and return to Hermes.</div>"-)-_CALLBACK_ERROR_HTML = (- "<!doctype html><meta charset=utf-8>"- "<title>Honcho sign-in failed</title>"+_CALLBACK_STYLE = ("<body style='font:14px ui-monospace,monospace;background:#0b0e14;color:#c9d1d9;""display:flex;align-items:center;justify-content:center;height:100vh;margin:0'>"- "<div>Sign-in was not completed ({error}). You can close this tab and re-run setup.</div>"+)+_CALLBACK_HTML = (+ "<!doctype html><meta charset=utf-8><title>Honcho connected</title>" + _CALLBACK_STYLE+ + "<div>Connected to Honcho. You can close this tab and return to Hermes.</div>"+).encode()+_CALLBACK_ERROR_HTML = (+ "<!doctype html><meta charset=utf-8><title>Honcho sign-in failed</title>" + _CALLBACK_STYLE+ + "<div>Sign-in was not completed ({error}). You can close this tab and re-run setup.</div>")def _bind_loopback_server() -> tuple[HTTPServer, dict[str, str]]:"""Bind the one-shot callback server, returning it and its capture dict.-- Prefers :8765; if that's taken, falls back to an OS-assigned port. groudon's- redirect matcher relaxes the port for loopback hosts, so the fallback still- matches the seeded ``127.0.0.1`` redirect URI — the caller advertises the- actual bound port.- """+ Prefers :8765, else an OS-assigned port (the AS relaxes the port for loopback+ redirect URIs; the caller advertises the bound port)."""captured: dict[str, str] = {}class _Handler(BaseHTTPRequestHandler):@@ -272,18 +235,13 @@ def _bind_loopback_server() -> tuple[HTTPServer, dict[str, str]]:self.end_headers()returnparams = parse_qs(parsed.query)- captured["code"] = (params.get("code") or [""])[0]- captured["state"] = (params.get("state") or [""])[0]- captured["error"] = (params.get("error") or [""])[0]- captured["error_description"] = (params.get("error_description") or [""])[0]+ for k in ("code", "state", "error", "error_description"):+ captured[k] = (params.get(k) or [""])[0]self.send_response(200)self.send_header("Content-Type", "text/html; charset=utf-8")self.end_headers()if captured["error"]:- import html as _html-- page = _CALLBACK_ERROR_HTML.format(error=_html.escape(captured["error"]))- self.wfile.write(page.encode("utf-8"))+ self.wfile.write(_CALLBACK_ERROR_HTML.format(error=html.escape(captured["error"])).encode("utf-8"))else:self.wfile.write(_CALLBACK_HTML)@@ -293,22 +251,16 @@ def _bind_loopback_server() -> tuple[HTTPServer, dict[str, str]]:try:server = HTTPServer((LOOPBACK_HOST, LOOPBACK_PORT), _Handler)except OSError:- server = HTTPServer((LOOPBACK_HOST, 0), _Handler) # OS-assigned fallback+ server = HTTPServer((LOOPBACK_HOST, 0), _Handler)return server, captured-def capture_loopback_code(- server: HTTPServer, captured: dict[str, str], *, timeout: float = 300.0-) -> tuple[str, str]:- """Serve a single ``/callback`` GET on ``server`` and return ``(code, state)``.-- Replies with a close-this-tab page, then stops. Raises ``TimeoutError`` if no- callback arrives within ``timeout``.- """+def capture_loopback_code(server: HTTPServer, captured: dict[str, str], *, timeout: float = 300.0) -> tuple[str, str]:+ """Serve ``/callback`` until our code lands; return ``(code, state)``.+ Loops so a stray probe to another path doesn't end the wait; raises+ ``TimeoutError`` if nothing arrives within ``timeout``."""server.timeout = timeouttry:- # handle_request honors server.timeout; loop until our callback lands so a- # stray probe to another path doesn't end the wait empty-handed.deadline = time.monotonic() + timeoutwhile "code" not in captured and time.monotonic() < deadline:server.handle_request()@@ -317,8 +269,7 @@ def capture_loopback_code(if captured.get("error"):detail = captured.get("error_description")- suffix = f" ({detail})" if detail else ""- raise ValueError(f"authorization denied: {captured['error']}{suffix}")+ raise ValueError(f"authorization denied: {captured['error']}{f' ({detail})' if detail else ''}")if "code" not in captured:raise TimeoutError("no OAuth callback received before timeout")return captured["code"], captured.get("state", "")@@ -333,15 +284,10 @@ def authorize_via_loopback(open_url: Callable[[str], None] | None = None,timeout: float = 300.0,) -> oauth.OAuthCredential:- """Drive the full loopback flow: open browser → capture code → exchange → persist.-- ``open_url`` defaults to the system browser; tests inject a driver that- follows the authorize redirect into the loopback callback. It always- receives the authorize URL, so a CLI caller can also print it for- browserless environments.- """- # Bind first so the advertised redirect_uri carries the actual bound port- # (which may differ from :8765 if it was taken).+ """Full loopback flow: open browser → capture code → exchange → persist.+ ``open_url`` (default: system browser) always receives the authorize URL, so+ a CLI caller can print it for browserless setups."""+ # Bind first so the advertised redirect_uri carries the actual bound port.server, captured = _bind_loopback_server()redirect_uri = f"http://{LOOPBACK_HOST}:{server.server_address[1]}/callback"@@ -353,41 +299,28 @@ def authorize_via_loopback(if open_url is None:import webbrowser-open_url = webbrowser.open- # Browser opens from a short-lived thread; the socket is already bound, so a- # fast redirect can't beat it.- opener = threading.Thread(target=lambda: open_url(authorize_url), daemon=True)- opener.start()+ # Socket is already bound, so a fast redirect can't beat the browser thread.+ threading.Thread(target=lambda: open_url(authorize_url), daemon=True).start()code, returned_state = capture_loopback_code(server, captured, timeout=timeout)if returned_state != state:raise ValueError("OAuth state mismatch — possible CSRF, aborting")return complete_authorization(- endpoints,- code,- returned_state,- config_path=path,- host=host,- apply_config=apply_config,+ endpoints, code, returned_state, config_path=path, host=host, apply_config=apply_config)# — Device authorization grant (RFC 8628), for headless / remote-VM clients —-# The loopback flow needs the browser on the same machine; here the CLI prints-# a short user code, the user approves from any browser (dashboard /device),-# and the device polls the token endpoint until the grant lands.DEVICE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code"-# RFC 8628 §3.5: slow_down adds 5s per response; cap matches the server's-# DEVICE_POLL_INTERVAL_MAX so a misbehaving clock can't inflate past it.+# RFC 8628 §3.5: slow_down adds 5s per response; cap matches the server's DEVICE_POLL_INTERVAL_MAX._SLOW_DOWN_STEP = 5_POLL_INTERVAL_CAP = 60-# RFC 8414 authorization-server metadata; advertising the device grant is what-# distinguishes a host that can do device login from one that can't.+# RFC 8414 metadata; advertising the device grant marks a host as device-login capable._AS_METADATA_PATH = "/.well-known/oauth-authorization-server"@@ -412,6 +345,10 @@ class AuthorizationTimeout(DeviceFlowError):"""Polling ran past the device code's lifetime with no decision."""+# Terminal server outcomes for a device-token poll (RFC 8628 §3.5).+_DEVICE_POLL_ERRORS = {"access_denied": AccessDenied, "expired_token": DeviceCodeExpired}++@dataclass(frozen=True)class DeviceCode:"""RFC 8628 §3.2 device authorization response."""@@ -426,52 +363,38 @@ class DeviceCode:def supports_device_login(endpoints: OAuthEndpoints, *, timeout: float = 5.0) -> bool:"""Whether the host advertises the device grant in its RFC 8414 metadata.-- Fails closed: any connection error, non-200, or missing capability returns- False, so hosts without the device grant simply don't offer the option.- """+ Fails closed on any error / non-200 / missing capability."""origin = endpoints.token_url.rsplit("/oauth/", 1)[0]try:- body = oauth._http_get_json(f"{origin}{_AS_METADATA_PATH}", timeout)+ body = oauth._http_json("GET", f"{origin}{_AS_METADATA_PATH}", timeout=timeout)[1]except Exception:return False- grants = body.get("grant_types_supported")+ grants = body.get("grant_types_supported") if isinstance(body, dict) else Nonereturn isinstance(grants, list) and DEVICE_GRANT_TYPE in grants-def request_device_code(- endpoints: OAuthEndpoints, *, source: str | None = None-) -> DeviceCode:+def request_device_code(endpoints: OAuthEndpoints, *, source: str | None = None) -> DeviceCode:"""Request a device + user code pair (RFC 8628 §3.1)."""if not endpoints.device_authorization_url:raise ValueError("no device authorization endpoint resolved")data = {"client_id": endpoints.client_id, "scope": endpoints.scope}if source:data["source"] = source- status, body = oauth._http_post_form_status(- endpoints.device_authorization_url, data, oauth._REFRESH_TIMEOUT_SECONDS- )+ status, body = oauth._http_post_form_status(endpoints.device_authorization_url, data, oauth._REFRESH_TIMEOUT_SECONDS)if status != 200:- error = str(body.get("error") or f"http_{status}")- raise DeviceFlowError(error, body.get("error_description"))+ raise DeviceFlowError(str(body.get("error") or f"http_{status}"), body.get("error_description"))try:verification_uri = body["verification_uri"]return DeviceCode(device_code=body["device_code"],user_code=body["user_code"],verification_uri=verification_uri,- verification_uri_complete=body.get(- "verification_uri_complete",- f"{verification_uri}?user_code={body['user_code']}",- ),+ verification_uri_complete=body.get("verification_uri_complete", f"{verification_uri}?user_code={body['user_code']}"),expires_in=int(body["expires_in"]),- # RFC 8628 §3.2: interval is optional; clients default to 5s.- interval=int(body.get("interval", 5)),+ interval=int(body.get("interval", 5)), # §3.2: optional, default 5s)except (KeyError, TypeError, ValueError) as e:- raise DeviceFlowError(- "invalid_response", f"malformed device authorization response: {e}"- ) from e+ raise DeviceFlowError("invalid_response", f"malformed device authorization response: {e}") from edef poll_for_token(@@ -482,37 +405,27 @@ def poll_for_token(sleep: Callable[[float], None] = time.sleep,monotonic: Callable[[], float] = time.monotonic,) -> dict[str, object]:- """Poll the token endpoint until the grant is approved (RFC 8628 §3.4/§3.5).-+ """Poll the token endpoint until approved (RFC 8628 §3.4/§3.5).Sleeps ``interval`` before each poll, bumping it on ``slow_down``. Raises- ``AccessDenied`` / ``DeviceCodeExpired`` on the terminal server outcomes and- ``AuthorizationTimeout`` when ``expires_in`` elapses with no decision.- ``sleep`` / ``monotonic`` are injectable for tests.- """+ ``AccessDenied`` / ``DeviceCodeExpired`` on terminal outcomes and+ ``AuthorizationTimeout`` when ``expires_in`` elapses with no decision."""import httpxinterval = max(1, min(device.interval, _POLL_INTERVAL_CAP))deadline = monotonic() + max(1, device.expires_in)while True:if monotonic() + interval >= deadline:- raise AuthorizationTimeout(- "expired_token", "timed out waiting for approval"- )+ raise AuthorizationTimeout("expired_token", "timed out waiting for approval")sleep(interval)if on_poll:on_poll()try:status, body = oauth._http_post_form_status(endpoints.token_url,- {- "grant_type": DEVICE_GRANT_TYPE,- "device_code": device.device_code,- "client_id": endpoints.client_id,- },+ {"grant_type": DEVICE_GRANT_TYPE, "device_code": device.device_code, "client_id": endpoints.client_id},oauth._REFRESH_TIMEOUT_SECONDS,)- except httpx.TransportError as e:- # A network blip mid-poll shouldn't kill a 10-minute wait.+ except httpx.TransportError as e: # a network blip mid-poll shouldn't kill a 10-minute waitlogger.debug("device token poll transport error, retrying: %s", e)continue@@ -521,17 +434,12 @@ def poll_for_token(raise DeviceFlowError("invalid_response", "token response missing access_token")return bodyerror = str(body.get("error") or f"http_{status}")- description = body.get("error_description")if error == "authorization_pending":continueif error == "slow_down":interval = min(interval + _SLOW_DOWN_STEP, _POLL_INTERVAL_CAP)continue- if error == "access_denied":- raise AccessDenied(error, description)- if error == "expired_token":- raise DeviceCodeExpired(error, description)- raise DeviceFlowError(error, description)+ raise _DEVICE_POLL_ERRORS.get(error, DeviceFlowError)(error, body.get("error_description"))def authorize_via_device_code(@@ -545,14 +453,11 @@ def authorize_via_device_code(on_poll: Callable[[], None] | None = None,sleep: Callable[[float], None] = time.sleep,) -> oauth.OAuthCredential:- """Drive the full device flow: request codes → show user code → poll → persist.-- ``display`` shows the user code + verification URL. ``open_url`` (if given)- receives ``verification_uri_complete`` — there is no default browser open,- since the approving browser may be on another machine.- """+ """Full device flow: request codes → show user code → poll → persist.+ ``open_url`` (if given) receives ``verification_uri_complete``; no default+ browser open, since the approving browser may be on another machine."""endpoints = resolve_endpoints()- path = config_path or resolve_config_path()+ path = config_path or resolve_config_path() # resolve NOW so a later ambient lookup can't drifttarget_host = host or resolve_active_host()device = request_device_code(endpoints, source=source)@@ -562,24 +467,11 @@ def authorize_via_device_code(open_url(device.verification_uri_complete)grant = poll_for_token(endpoints, device, on_poll=on_poll, sleep=sleep)- cred = oauth.install_grant(- path,- target_host,- grant,- client_id=endpoints.client_id,- token_endpoint=endpoints.token_url,- apply_config=apply_config,- )- from plugins.memory.honcho.client import reset_honcho_client+ return _install(endpoints, grant, path=path, host=target_host, apply_config=apply_config, now=None, kind="device ")- reset_honcho_client()- logger.info("Honcho OAuth device grant installed for host %s", target_host)- return cred--# — Background launcher + status, for the desktop "Connect" button —-# The flow blocks on a browser round-trip, so the web_server endpoint kicks it-# off in a thread and the UI polls status rather than holding the request open.+# — Background launcher + status, for the desktop "Connect" button — the flow+# blocks on a browser round-trip, so web_server runs it in a thread and the UI polls.@dataclass@@ -629,13 +521,10 @@ def start_loopback_flow_background(timeout: float = 300.0,) -> dict[str, str]:"""Launch the loopback flow in a daemon thread; returns the initial status.-- Idempotent while a flow is pending — a second call is a no-op so a- double-clicked button can't open two browser tabs / bind :8765 twice.- """+ Idempotent while pending, so a double-click can't open two tabs / bind :8765 twice."""global _flow_thread- # Resolve under the caller's profile scope NOW — the worker thread outlives- # the request, where a context-local HERMES_HOME override can't reach.+ # Resolve under the caller's profile scope NOW — a context-local HERMES_HOME+ # override can't reach the worker thread.config_path = config_path or resolve_config_path()host = host or resolve_active_host()with _status_lock:diff --git a/plugins/memory/honcho/session.py b/plugins/memory/honcho/session.pyindex 1ee7dc4fee3..97f3a7e4ad2 100644--- a/plugins/memory/honcho/session.py+++ b/plugins/memory/honcho/session.py@@ -2,18 +2,23 @@from __future__ import annotations-import hashlibimport queue-import reimport loggingimport threading+import timefrom dataclasses import dataclass, fieldfrom datetime import datetime-from pathlib import Path-from typing import Any, Callable, TYPE_CHECKING+from typing import Any, TYPE_CHECKINGfrom plugins.memory.honcho.client import get_honcho_client, spawn_context_thread-from plugins.memory.honcho.oauth import redact_tokens as _redact_tokens+from plugins.memory.honcho.session_auth import ( # noqa: F401 — re-exported public API+ HonchoAuthError,+ SessionAuthMixin,+ _is_auth_error,+)+from plugins.memory.honcho.session_context import SessionContextMixin+from plugins.memory.honcho.session_migration import SessionMigrationMixin+from plugins.memory.honcho.session_peers import SessionPeersMixinif TYPE_CHECKING:from honcho import Honcho@@ -22,63 +27,11 @@ logger = logging.getLogger(__name__)# Sentinel to signal the async writer thread to shut down_ASYNC_SHUTDOWN = object()-_PEER_ID_HASH_LEN = 8-_PEER_ID_HASH_ESCALATION_LENGTHS = (_PEER_ID_HASH_LEN, 12, 16, 24, 32, 64)---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.- """---# Matched narrowly: a false positive spends a token rotation, and a lost rotation revokes the grant.-_AUTH_ERROR_MARKERS = (- "invalid or expired access token",- "authentication failed",- "unauthorized",-)--# A 401 in text counts only with HTTP context ("HTTP 401", "status 401"), never as a bare number.-_HTTP_401_RE = re.compile(r"\b(?:http|status(?:[ _]code)?\s*[:=]?)\s*401\b")---def _is_auth_error(exc: BaseException) -> bool:- status = getattr(exc, "status_code", None) or getattr(exc, "status", None)- if status == 401:- return True- # The transport reported a concrete non-auth status; trust it over text.- if isinstance(status, int) and status not in (0, 401):- return False- text = str(exc).lower()- if _HTTP_401_RE.search(text):- return True- return any(marker in text for marker in _AUTH_ERROR_MARKERS)---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'."- )---_REAUTH_REQUIRED_MESSAGE = (- "Honcho OAuth grant is revoked and cannot be refreshed; "- "re-authenticate with 'hermes honcho setup'."-)@dataclassclass HonchoSession:- """- A conversation session backed by Honcho.-- Provides a local message cache that syncs to Honcho's- AI-native memory system for user modeling.- """+ """A conversation session backed by Honcho: a local message cache that syncs to Honcho."""key: str # channel:chat_iduser_peer_id: str # Honcho peer ID for the user@@ -91,36 +44,23 @@ class HonchoSession:def add_message(self, role: str, content: str, **kwargs: Any) -> None:"""Add a message to the local cache."""- msg = {+ self.messages.append({"role": role,"content": content,"timestamp": datetime.now().isoformat(),**kwargs,- }- self.messages.append(msg)+ })self.updated_at = datetime.now()- def get_history(self, max_messages: int = 50) -> list[dict[str, Any]]:- """Get message history for LLM context."""- recent = (- self.messages[-max_messages:]- if len(self.messages) > max_messages- else self.messages- )- return [{"role": m["role"], "content": m["content"]} for m in recent]-- def clear(self) -> None:- """Clear all messages in the session."""- self.messages = []- self.updated_at = datetime.now()+class HonchoSessionManager(+ SessionAuthMixin, SessionPeersMixin, SessionContextMixin, SessionMigrationMixin,+):+ """Manages conversation sessions using Honcho.-class HonchoSessionManager:- """- Manages conversation sessions using Honcho.-- Runs alongside hermes' existing SQLite state and file-based memory,- adding persistent cross-session user modeling via Honcho's AI-native memory.+ 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."""def __init__(@@ -131,17 +71,9 @@ class HonchoSessionManager:runtime_user_peer_name: str | None = None,runtime_user_peer_name_alt: str | None = None,):- """- Initialize the session manager.-- Args:- honcho: Optional Honcho client. If not provided, uses the singleton.- context_tokens: Max tokens for context() calls (None = Honcho default).- config: HonchoClientConfig from global config (provides peer_name, ai_peer,- write_frequency, observation, etc.).- runtime_user_peer_name: Gateway user identity for per-user memory scoping.- runtime_user_peer_name_alt: Optional stable alternate gateway identity.- """+ """``honcho`` defaults to the per-identity cached client; ``context_tokens`` caps+ context() calls (None = Honcho default); the runtime peer names are the gateway+ user identity (and a stable alternate) for per-user memory scoping."""self._honcho = honchoself._context_tokens = context_tokensself._config = config@@ -151,282 +83,111 @@ class HonchoSessionManager:self._cache_lock = threading.RLock()self._peers_cache: dict[str, Any] = {}self._sessions_cache: dict[str, Any] = {}- # Bumped (under _cache_lock) whenever _force_reauth rebuilds the client.- # In-flight resolvers compare it around their SDK fetch so an object- # bound to the discarded client is never stored into the fresh cache.+ # Bumped (under _cache_lock) whenever _force_reauth rebuilds the client, so an+ # in-flight resolver never stores an object bound to the discarded client.self._client_generation = 0# Set when a call still fails auth after a forced token refresh; cleared on the next success.self._auth_failure: str | None = Noneself._auth_notice_emitted = False- # Write frequency state- write_frequency = (config.write_frequency if config else "async")- self._write_frequency = write_frequency+ # Behavior knobs copied from config (HonchoClientConfig defaults when absent); the+ # observation booleans map 1:1 to Honcho's SessionPeerConfig toggles.+ for name, default in (+ ("write_frequency", "async"), ("dialectic_reasoning_level", "low"), ("dialectic_dynamic", True),+ ("dialectic_max_chars", 600), ("dialectic_max_input_chars", 10000),+ ("user_observe_me", True), ("user_observe_others", True),+ ("ai_observe_me", True), ("ai_observe_others", True),+ ):+ setattr(self, f"_{name}", getattr(config, name) if config else default)self._turn_counter: int = 0- # Prefetch cache: session_key → last context result (consumed once per turn).- # Dialectic results are cached on the plugin side (HonchoMemoryProvider- # ._prefetch_result) so session-start prewarm and turn-driven fires share- # one source of truth; see __init__.py _do_session_init for the prewarm.+ # Prefetch cache: session_key -> last context result (consumed once per turn).+ # Dialectic results are cached on the plugin side (HonchoMemoryProvider._prefetch_result)+ # so session-start prewarm and turn-driven fires share one source of truth.self._context_cache: dict[str, dict] = {}self._prefetch_cache_lock = threading.Lock()- self._dialectic_reasoning_level: str = (- config.dialectic_reasoning_level if config else "low"- )- self._dialectic_dynamic: bool = (- config.dialectic_dynamic if config else True- )- self._dialectic_max_chars: int = (- config.dialectic_max_chars if config else 600- )- self._observation_mode: str = (- config.observation_mode if config else "directional"- )- # Per-peer observation booleans (granular, from config)- self._user_observe_me: bool = config.user_observe_me if config else True- self._user_observe_others: bool = config.user_observe_others if config else True- self._ai_observe_me: bool = config.ai_observe_me if config else True- self._ai_observe_others: bool = config.ai_observe_others if config else True- self._message_max_chars: int = (- config.message_max_chars if config else 25000- )- self._dialectic_max_input_chars: int = (- config.dialectic_max_input_chars if config else 10000- )# Async write queue — the writer thread starts lazily on first enqueue- # (see _ensure_async_writer). Constructing a manager must not spawn- # background work or touch the network: unit tests build managers with- # mocked clients, and an eagerly-started writer raced ahead of the mock- # and wrote test messages to a live local Honcho.- self._async_queue: queue.Queue | None = None+ # (_ensure_async_writer): constructing a manager must not spawn background+ # work or touch the network (unit tests build managers with mocked clients).+ self._async_queue: queue.Queue | None = queue.Queue() if self._write_frequency == "async" else Noneself._async_thread: threading.Thread | None = Noneself._async_thread_lock = threading.Lock()- if write_frequency == "async":- self._async_queue = queue.Queue()@propertydef honcho(self) -> Honcho:"""Get the Honcho client, refreshing a near-expiry OAuth token in place.- Routes every access through ``get_honcho_client`` WITH this manager's- bound config so a long session can't outlive its 1h access token AND- so background threads (async writer, prefetch, sync) acquire the- client for the profile this manager was built under — a bare- ``get_honcho_client()`` re-resolves ambient ContextVar-backed state- that daemon threads cannot see, migrating every access onto the- first-built profile's client (#69123, #74065).+ 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."""self._honcho = get_honcho_client(self._config)return self._honcho- 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,- )- self._auth_failure = detail-- def _clear_auth_failure(self) -> None:- if self._auth_failure is not None:- logger.info("Honcho authentication recovered; memory sync and recall resumed")- self._auth_failure = None- self._auth_notice_emitted = False-- def pop_auth_notice(self) -> str | None:- """Return the pending auth-failure message once; later calls return None."""- if self._auth_failure is None or self._auth_notice_emitted:- return None- self._auth_notice_emitted = True- return self._auth_failure-- def _bound_config_path(self) -> Path:- """Config path for OAuth checks, bound to this manager's profile.-- Falls back to ambient resolution only when the manager was built- without a config (tests) — on the hot path the bound path keeps- background threads reading THIS profile's honcho.json, not the- default profile the ContextVar-blind resolver would land on.- """- 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()-- def _reauth_required(self) -> bool:- """True when the grant is dead and only a new login can fix it.-- Compares the on-disk refresh-token digest, so a new login clears it with no network call.- """- try:- from plugins.memory.honcho import oauth-- # Fast path: no grant in this process is dead — skip config-path- # resolution entirely (this runs before every SDK call).- if not oauth.any_dead_grants():- return False-- host = getattr(self._config, "host", "") or ""- if not host:- return False- return oauth.reauth_required(self._bound_config_path(), host)- except Exception:- return False-- def _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.- """- try:- from plugins.memory.honcho import oauth- from plugins.memory.honcho.client import reset_honcho_client-- host = getattr(self._config, "host", "") or ""- if not host:- return False- token = oauth.force_refresh_token(self._bound_config_path(), host)- if not token:- return False- if not oauth.apply_token_to_client(self.honcho, token):- # SDK shape changed: rebuild the client and drop objects holding the old transport.- reset_honcho_client()- with self._cache_lock:- self._client_generation += 1- self._peers_cache.clear()- self._sessions_cache.clear()- return True- except Exception:- logger.warning("Honcho post-401 token refresh failed", exc_info=True)- return False+ # ----- SDK object caches (generation-guarded against client rebuilds) ------ def _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.- """- if self._reauth_required():- exc = HonchoAuthError(_REAUTH_REQUIRED_MESSAGE)- self._record_auth_failure(exc)- raise exc- try:- result = operation()- except HonchoAuthError:- raise- 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)),- )- if not self._force_reauth():- self._record_auth_failure(e)- raise HonchoAuthError(_auth_error_message(e)) from e- try:- result = operation()- except Exception as retry_exc:- if _is_auth_error(retry_exc):- self._record_auth_failure(retry_exc)- raise HonchoAuthError(_auth_error_message(retry_exc)) from retry_exc- raise- self._clear_auth_failure()- return result-- def _sdk_session(self, session_id: str) -> Any:- """Get or create the SDK session; a client rebuild clears the cache, so re-fetch."""+ def _cached_sdk_object(self, cache: dict[str, Any], key: str, fetch: Any) -> Any:+ """Get-or-fetch from ``cache``; a fetch that straddles a client rebuild is not cached."""while True:with self._cache_lock:- cached = self._sessions_cache.get(session_id)+ if key in cache:+ return cache[key]generation = self._client_generation- if cached is not None:- return cached- sdk_session = self.honcho.session(session_id)+ obj = fetch()with self._cache_lock:if self._client_generation == generation:- return self._sessions_cache.setdefault(session_id, sdk_session)- # The client was rebuilt while we resolved; this object holds the- # discarded transport. Don't cache it — resolve afresh.+ return cache.setdefault(key, obj)+ # Client rebuilt mid-resolve: this object holds the discarded transport. Retry.++ 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),+ )def _get_or_create_peer(self, peer_id: str) -> Any:"""Get or create a Honcho peer (one get-or-create API call, then cached)."""- while True:- with self._cache_lock:- if peer_id in self._peers_cache:- return self._peers_cache[peer_id]- generation = self._client_generation+ return self._cached_sdk_object(+ self._peers_cache, peer_id,+ lambda: self._authed_call("peer setup", lambda: self.honcho.peer(peer_id)),+ )- peer = self._authed_call("peer setup", lambda: self.honcho.peer(peer_id))- with self._cache_lock:- if self._client_generation == generation:- return self._peers_cache.setdefault(peer_id, peer)- # Client rebuilt mid-resolve — drop the stale object and retry.+ # ----- Session creation ------ 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.+ 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).- Returns:- Tuple of (honcho_session, existing_messages).+ Observation booleans are manager-scoped, so the last session init wins.+ Returns False when auth died mid-way (already recorded by _authed_call)."""- 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))-- # Configure per-peer observation from granular booleans.- # These map 1:1 to Honcho's SessionPeerConfig toggles.- auth_dead = False+ peers = (("user", user_peer), ("ai", assistant_peer))try:from honcho.session import SessionPeerConfig- user_config = SessionPeerConfig(- observe_me=self._user_observe_me,- observe_others=self._user_observe_others,- )- ai_config = SessionPeerConfig(- observe_me=self._ai_observe_me,- observe_others=self._ai_observe_others,- )- peer_entries = [(user_peer, user_config), (assistant_peer, ai_config)]-+ peer_entries = [+ (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),)-- # Sync back: server-side config (set via Honcho UI) wins over- # local defaults. Read the effective config after add_peers.- # Note: observation booleans are manager-scoped, not per-session.- # Last session init wins. Fine for CLI; gateway should scope per-session.try:- def _read_server_configs() -> tuple[Any, Any]:- sdk_session = self._sdk_session(session_id)- return (- sdk_session.get_peer_configuration(user_peer),- sdk_session.get_peer_configuration(assistant_peer),- )-- server_user, server_ai = self._authed_call(- "peer configuration read", _read_server_configs+ server_cfgs = self._authed_call(+ "peer configuration read",+ lambda: [self._sdk_session(session_id).get_peer_configuration(peer) for _, peer in peers],)- if server_user.observe_me is not None:- self._user_observe_me = server_user.observe_me- if server_user.observe_others is not None:- self._user_observe_others = server_user.observe_others- if server_ai.observe_me is not None:- self._ai_observe_me = server_ai.observe_me- if server_ai.observe_others is not None:- self._ai_observe_others = server_ai.observe_others+ for (kind, _), server_cfg in zip(peers, server_cfgs):+ for field_name in ("observe_me", "observe_others"):+ 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,@@ -437,231 +198,106 @@ class HonchoSessionManager:except Exception as e:logger.debug("Honcho get_peer_configuration failed (using local config): %s", e)except HonchoAuthError:- # Already recorded by _authed_call; skip the remaining init calls.- auth_dead = True+ return Falseexcept Exception as e:- logger.warning(- "Honcho session '%s' add_peers failed (non-fatal): %s",- session_id, e,- )+ logger.warning("Honcho session '%s' add_peers failed (non-fatal): %s", session_id, e)+ return True- # Load existing messages via context() - single call for messages + metadata- existing_messages = []- if not auth_dead:- try:- ctx = self._authed_call(- "session context load",- lambda: self._sdk_session(session_id).context(- summary=True, tokens=self._context_tokens- ),+ def _load_existing_messages(self, session_id: str) -> list:+ """Load prior messages via context() (one call for messages + metadata), oldest first."""+ try:+ ctx = self._authed_call(+ "session context load",+ 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,+ )+ 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),)- existing_messages = ctx.messages or []+ else:+ logger.info("Honcho session '%s' created (new)", session_id)+ return existing_messages+ except HonchoAuthError:+ logger.warning("Honcho session '%s' loaded without server context: auth failed", session_id)+ except Exception as e:+ logger.warning("Honcho session '%s' loaded (failed to fetch context: %s)", session_id, e)+ return []- # Verify chronological ordering- if existing_messages and 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,- )- existing_messages = sorted(- existing_messages,- key=lambda m: m.created_at or datetime.min,- )+ 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.- if 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)- except HonchoAuthError:- logger.warning(- "Honcho session '%s' loaded without server context: auth failed",- session_id,- )- except Exception as e:- logger.warning(- "Honcho session '%s' loaded (failed to fetch context: %s)",- session_id, e,- )+ Returns (honcho_session, existing_messages); 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 []+ )with self._cache_lock:honcho_session = self._sessions_cache.get(session_id)if honcho_session is None:# A mid-init client rebuild dropped the cached session; resolve a fresh one.- honcho_session = self._authed_call(- "session setup", lambda: self._sdk_session(session_id)- )+ honcho_session = self._authed_call("session setup", lambda: self._sdk_session(session_id))return honcho_session, existing_messages- def _sanitize_id(self, id_str: str) -> str:- """Sanitize an ID to match Honcho's pattern: ^[a-zA-Z0-9_-]+"""- return re.sub(r'[^a-zA-Z0-9_-]', '-', id_str)-- def _runtime_user_ids(self) -> list[str]:- """Return runtime identity candidates in lookup order."""- candidates: list[str] = []- for value in (self._runtime_user_peer_name, self._runtime_user_peer_name_alt):- if value is None:- continue- candidate = str(value).strip()- if candidate and candidate not in candidates:- candidates.append(candidate)- return candidates-- def _session_key_fallback_peer_id(self, key: str) -> str:- parts = key.split(":", 1)- channel = parts[0] if len(parts) > 1 else "default"- chat_id = parts[1] if len(parts) > 1 else key- return self._sanitize_id(f"user-{channel}-{chat_id}")-- def _explicit_user_peer_ids(self) -> set[str]:- """Return sanitized user peer IDs that came from explicit config."""- if self._config is None:- return set()-- explicit_ids: set[str] = set()- peer_name = getattr(self._config, "peer_name", None)- if peer_name:- explicit_ids.add(self._sanitize_id(str(peer_name).strip()))-- aliases = getattr(self._config, "user_peer_aliases", {})- if isinstance(aliases, dict):- for alias in aliases.values():- if isinstance(alias, str) and alias.strip():- explicit_ids.add(self._sanitize_id(alias.strip()))-- return explicit_ids-- def _generated_runtime_peer_id(self, prefix: str, runtime_id: str) -> str:- """Return a stable peer ID for an unknown prefixed runtime user."""- raw_peer_id = f"{prefix}{runtime_id}"- sanitized_peer_id = self._sanitize_id(raw_peer_id)- explicit_ids = self._explicit_user_peer_ids()- if (- sanitized_peer_id != raw_peer_id- or sanitized_peer_id in explicit_ids- ):- digest = hashlib.sha256(raw_peer_id.encode("utf-8")).hexdigest()- for hash_len in _PEER_ID_HASH_ESCALATION_LENGTHS:- candidate = f"{sanitized_peer_id}-{digest[:hash_len]}"- if candidate not in explicit_ids:- return candidate- return f"{sanitized_peer_id}-{digest}"- return sanitized_peer_id-- def _declared_owner_peer_id(self) -> str | None:- """Peer ID of the install owner, or None when no owner is declared.-- The owner is the identity setup writes as ``peerName``. A runtime- gateway identity is the owner only when an alias maps it onto that- peer — which _resolve_user_peer_id already does, so callers can- compare a session's resolved user peer against this value.- """- peer_name = getattr(self._config, "peer_name", None) if self._config else None- if peer_name and str(peer_name).strip():- return self._sanitize_id(str(peer_name).strip())- return None-- def _resolve_user_peer_id(self, key: str) -> str:- """Resolve the Honcho user peer ID for this manager/session."""- pin_peer_name = (- self._config is not None- and bool(getattr(self._config, "peer_name", None))- and getattr(self._config, "pin_peer_name", False) is True- )- if pin_peer_name:- return self._sanitize_id(self._config.peer_name)-- runtime_ids = self._runtime_user_ids()- if runtime_ids:- aliases = getattr(self._config, "user_peer_aliases", {}) if self._config else {}- if not isinstance(aliases, dict):- aliases = {}- for runtime_id in runtime_ids:- alias = aliases.get(runtime_id)- if isinstance(alias, str) and alias.strip():- return self._sanitize_id(alias.strip())-- primary_runtime_id = runtime_ids[0]- prefix = getattr(self._config, "runtime_peer_prefix", "") if self._config else ""- prefix = prefix.strip() if isinstance(prefix, str) else ""- if prefix:- return self._generated_runtime_peer_id(prefix, primary_runtime_id)- return self._sanitize_id(primary_runtime_id)-- if self._config and self._config.peer_name:- return self._sanitize_id(self._config.peer_name)-- return self._session_key_fallback_peer_id(key)-def get_or_create(self, key: str) -> HonchoSession:- """- Get an existing session or create a new one.-- Args:- key: Session key (usually channel:chat_id).-- Returns:- The session.- """+ """Get an existing session or create a new one for ``key`` (usually channel:chat_id)."""with self._cache_lock:if key in self._cache:logger.debug("Local session cache hit: %s", key)return self._cache[key]- # Determine peer IDs — no lock needed (read-only, no shared state mutation).- # Gateway sessions normally use the runtime user identity (the- # platform-native ID: Telegram UID, Discord snowflake, Slack user,- # etc.) so multi-user bots scope memory per user. Config can alias- # known runtime IDs or prefix unknown IDs. For a single-user- # deployment, ``pinPeerName`` still pins all runtime identities to- # ``peerName`` (see #14984).+ # Gateway sessions normally use the platform-native runtime identity so multi-user+ # bots scope memory per user; config can alias/prefix it, or pinPeerName pins all+ # identities to peerName for single-user deployments (see _resolve_user_peer_id).user_peer_id = self._resolve_user_peer_id(key)+ assistant_peer_id = self._sanitize_id(self._config.ai_peer if self._config else "hermes-assistant")- assistant_peer_id = self._sanitize_id(- self._config.ai_peer if self._config else "hermes-assistant"- )-- # All expensive I/O outside the lock — Honcho's persistence is source of truth+ # All expensive I/O outside the lock — Honcho's persistence is source of truth.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)- honcho_session, existing_messages = self._get_or_create_honcho_session(+ _, existing_messages = self._get_or_create_honcho_session(honcho_session_id, user_peer, assistant_peer)- local_messages = []- for msg in existing_messages:- role = "assistant" if msg.peer_id == assistant_peer_id else "user"- local_messages.append({- "role": role,- "content": msg.content,- "timestamp": msg.created_at.isoformat() if msg.created_at else "",- "_synced": True,- })-session = HonchoSession(- key=key,- user_peer_id=user_peer_id,- assistant_peer_id=assistant_peer_id,+ key=key, user_peer_id=user_peer_id, assistant_peer_id=assistant_peer_id,honcho_session_id=honcho_session_id,- messages=local_messages,+ 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,+ }+ for msg in existing_messages+ ],)-- # Write to cache under lock — only one writer winswith self._cache_lock:self._cache[key] = sessionreturn session- def _flush_session(self, session: HonchoSession) -> bool:- """Internal: write unsynced messages to Honcho synchronously."""- if not session.messages:- return True+ # ----- Writes -----+ def _flush_session(self, session: HonchoSession) -> bool:+ """Write unsynced messages to Honcho synchronously."""new_messages = [m for m in session.messages if not m.get("_synced")]if not new_messages:return True@@ -683,55 +319,37 @@ class HonchoSessionManager:return len(honcho_messages)try:- synced = self._authed_call("message sync", _sync_messages)- for msg in new_messages:- msg["_synced"] = True- logger.debug("Synced %d messages to Honcho for %s", synced, session.key)- with self._cache_lock:- self._cache[session.key] = session- return True+ logger.debug("Synced %d messages to Honcho for %s", self._authed_call("message sync", _sync_messages), session.key)+ ok = Trueexcept Exception as e:- for msg in new_messages:- msg["_synced"] = Falselogger.error("Failed to sync messages to Honcho: %s", e)- with self._cache_lock:- self._cache[session.key] = session- return False+ ok = False+ for msg in new_messages:+ msg["_synced"] = ok+ with self._cache_lock:+ self._cache[session.key] = session+ return ok++ def _try_flush(self, session: HonchoSession, level: int, msg: str) -> bool:+ """_flush_session that logs (never raises) a failure; False when the batch didn't land."""+ try:+ if self._flush_session(session):+ return True+ logger.log(level, msg)+ except Exception as e:+ logger.log(level, msg + ": %s", e)+ return Falsedef _async_writer_loop(self) -> None:- """Background daemon thread: drains the async write queue."""+ """Background daemon thread: drains the async write queue, retrying each batch once."""while True:try:item = self._async_queue.get(timeout=5)if item is _ASYNC_SHUTDOWN:break-- first_error: Exception | None = None- try:- success = self._flush_session(item)- except Exception as e:- success = False- first_error = e-- if success:- continue-- if first_error is not None:- logger.warning("Honcho async write failed, retrying once: %s", first_error)- else:- logger.warning("Honcho async write failed, retrying once")-- import time as _time- _time.sleep(2)-- try:- retry_success = self._flush_session(item)- except Exception as e2:- logger.error("Honcho async write retry failed, dropping batch: %s", e2)- continue-- if not retry_success:- logger.error("Honcho async write retry failed, dropping batch")+ if not self._try_flush(item, logging.WARNING, "Honcho async write failed, retrying once"):+ time.sleep(2)+ self._try_flush(item, logging.ERROR, "Honcho async write retry failed, dropping batch")except queue.Empty:continueexcept Exception as e:@@ -740,34 +358,20 @@ class HonchoSessionManager:def save(self, session: HonchoSession) -> None:"""Save messages to Honcho, respecting write_frequency.- write_frequency modes:- "async" — enqueue for background thread (zero blocking, zero token cost)- "turn" — flush synchronously every turn- "session" — defer until flush_session() is called explicitly- N (int) — flush every N turns+ "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_frequency-if wf == "async":if self._async_queue is not None:self._ensure_async_writer()self._async_queue.put(session)- elif wf == "turn":+ elif wf == "turn" or (isinstance(wf, int) and wf > 0 and self._turn_counter % wf == 0):self._flush_session(session)- elif wf == "session":- # Accumulate; caller must call flush_all() at session end- pass- elif isinstance(wf, int) and wf > 0:- if self._turn_counter % wf == 0:- self._flush_session(session)def flush_all(self) -> None:- """Flush all pending unsynced messages for all cached sessions.-- Called at session end for "session" write_frequency, or to force- a sync before process exit regardless of mode.- """+ """Flush unsynced messages for all cached sessions, then drain the async queue inline."""with self._cache_lock:sessions = list(self._cache.values())for session in sessions:@@ -776,7 +380,6 @@ class HonchoSessionManager:except Exception as e:logger.error("Honcho flush_all error for %s: %s", session.key, e)- # Drain async queue synchronously if it existsif self._async_queue is not None:while not self._async_queue.empty():try:@@ -799,173 +402,27 @@ class HonchoSessionManager:self._async_thread.start()def stop_async_writer(self) -> None:- """Stop the async writer thread WITHOUT flushing pending messages.-- Used on shutdown when persistence is disabled (saveMessages: false):- the thread must still be joined so process exit is clean, but nothing- may be written.- """- if self._async_queue is not None:- if self._async_thread is not None and self._async_thread.is_alive():- self._async_queue.put(_ASYNC_SHUTDOWN)- self._async_thread.join(timeout=10)+ """Join the async writer WITHOUT flushing (saveMessages: false must still exit cleanly)."""+ if self._async_queue is not None and self._async_thread is not None and self._async_thread.is_alive():+ self._async_queue.put(_ASYNC_SHUTDOWN)+ self._async_thread.join(timeout=10)def shutdown(self) -> None:- """Gracefully shut down the async writer thread."""+ """Flush everything, then stop the async writer thread."""if self._async_queue is not None:self.flush_all()- if self._async_thread is not None and self._async_thread.is_alive():- self._async_queue.put(_ASYNC_SHUTDOWN)- self._async_thread.join(timeout=10)-- def delete(self, key: str) -> bool:- """Delete a session from local cache."""- with self._cache_lock:- if key in self._cache:- del self._cache[key]- return True- return False-- def new_session(self, key: str) -> HonchoSession:- """- Create a new session, preserving the old one for user modeling.-- Creates a fresh session with a new ID while keeping the old- session's data in Honcho for continued user modeling.- """- import time-- # Hold the reentrant lock across get_or_create so a concurrent caller- # can't observe the (old-popped, new-not-yet-inserted) gap and create- # its own session under the raw key. `_cache_lock` is an RLock so- # nested reacquisition inside get_or_create is safe.- with self._cache_lock:- # Remove old session from caches (but don't delete from Honcho)- old_session = self._cache.pop(key, None)- if old_session:- self._sessions_cache.pop(old_session.honcho_session_id, None)-- # Create new session with timestamp suffix- timestamp = int(time.time())- new_key = f"{key}:{timestamp}"-- # get_or_create will create a fresh session- session = self.get_or_create(new_key)-- # Cache under the original key so callers find it by the expected name- self._cache[key] = session-- logger.info("Created new session for %s (honcho: %s)", key, session.honcho_session_id)- return session-- _REASONING_LEVELS = ("minimal", "low", "medium", "high", "max")-- def _default_reasoning_level(self) -> str:- """Return the configured default reasoning level."""- return self._dialectic_reasoning_level-- def dialectic_query(- self, session_key: str, query: str,- reasoning_level: str | None = None,- peer: str = "user",- apply_injection_cap: bool = True,- raise_errors: bool = False,- ) -> str:- """- Query Honcho's dialectic endpoint about a peer.-- Runs an LLM on Honcho's backend against the target peer's full- representation. Higher latency than context() — callers run this in- a background thread (see HonchoMemoryProvider) to avoid blocking.+ self.stop_async_writer()- Args:- session_key: The session key to query against.- query: Natural language question.- reasoning_level: Override the configured default (dialecticReasoningLevel).- Only honored when dialecticDynamic is true.- If None or dialecticDynamic is false, uses the configured default.- peer: Which peer to query — "user" (default) or "ai".- apply_injection_cap: Clip automatic injections to- ``dialecticMaxChars``. Explicit ``honcho_reasoning`` calls pass- False because Honcho already bounds their output.- raise_errors: Re-raise backend failures instead of returning "".- Explicit tool calls pass True so a timeout or server error- surfaces as an error, not as "no result" (#36098 issue 4:- collapsing failures to "" made auth errors, timeouts, and- genuinely-empty answers indistinguishable).-- Returns:- Honcho's synthesized answer, or empty string on failure.-- Raises:- HonchoAuthError: the backend rejected our credentials and a forced- token refresh plus one retry did not recover.- """- session = self._cache.get(session_key)- if not session:- return ""-- target_peer_id = self._resolve_peer_id(session, peer)- if target_peer_id is None:- return ""-- # Guard: truncate query to Honcho's dialectic input limit- if len(query) > self._dialectic_max_input_chars:- query = query[:self._dialectic_max_input_chars].rsplit(" ", 1)[0]-- if self._dialectic_dynamic and reasoning_level:- level = reasoning_level- else:- level = self._default_reasoning_level()-- def _chat_once() -> str:- if self._ai_observe_others:- # AI peer can observe other peers — use assistant as observer.- ai_peer_obj = self._get_or_create_peer(session.assistant_peer_id)- if target_peer_id == session.assistant_peer_id:- return ai_peer_obj.chat(query, reasoning_level=level) or ""- return ai_peer_obj.chat(- query,- target=target_peer_id,- reasoning_level=level,- ) or ""- # Without cross-observation, each peer queries its own context.- target_peer = self._get_or_create_peer(target_peer_id)- return target_peer.chat(query, reasoning_level=level) or ""-- try:- result = self._authed_call("dialectic query", _chat_once)- # Only automatic injection uses the Hermes-side character cap.- if (- apply_injection_cap- and result- and self._dialectic_max_chars- and len(result) > self._dialectic_max_chars- ):- result = result[:self._dialectic_max_chars].rsplit(" ", 1)[0] + " …"- return result- except HonchoAuthError:- raise- except Exception as e:- logger.warning("Honcho dialectic query failed: %s", e)- if raise_errors:- raise- return ""+ # ----- Prefetch cache -----def prefetch_context(self, session_key: str, user_message: str | None = None) -> None:- """- Fire get_prefetch_context in a background thread, caching the result.-- Non-blocking. Consumed next turn via pop_context_result(). This avoids- a synchronous HTTP round-trip blocking every response.- """+ """Fire get_prefetch_context in a background thread; consumed next turn via pop_context_result()."""def _run():result = self.get_prefetch_context(session_key, user_message)if result:self.set_context_result(session_key, result)- t = spawn_context_thread(_run, name="honcho-context-prefetch")- t.start()+ spawn_context_thread(_run, name="honcho-context-prefetch").start()def set_context_result(self, session_key: str, result: dict[str, str]) -> None:"""Store a prefetched context result in a thread-safe way."""@@ -975,845 +432,6 @@ class HonchoSessionManager:self._context_cache[session_key] = resultdef pop_context_result(self, session_key: str) -> dict[str, str]:- """- Return and clear the cached context result for this session.-- Returns empty dict if no result is ready yet (first turn).- """+ """Return and clear the cached context result ({} if none ready yet)."""with self._prefetch_cache_lock:return self._context_cache.pop(session_key, {})-- def get_prefetch_context(self, session_key: str, user_message: str | None = None) -> dict[str, str]:- """- Pre-fetch user and AI peer context from Honcho.-- Fetches peer_representation and peer_card for both peers, plus the- session summary when available. When user_message is provided, it is- passed as search_query to the peer context call so Honcho returns- conclusions relevant to the session topic rather than the full- observation dump.-- Args:- session_key: The session key to get context for.- user_message: Optional first user message used as search_query for- topic-relevant context retrieval.-- Returns:- Dictionary with 'representation', 'card', 'ai_representation',- 'ai_card', and optionally 'summary' keys.- """- session = self._cache.get(session_key)- if not session:- return {}-- result: dict[str, str] = {}-- # Session summary — provides session-scoped context.- # Fresh sessions (per-session cold start, or first-ever per-directory)- # return null summary — the guard below handles that gracefully.- # Per-directory returning sessions get their accumulated summary.- try:- if session.honcho_session_id in self._sessions_cache:- ctx = self._authed_call(- "session summary fetch",- lambda: self._sdk_session(session.honcho_session_id).context(summary=True),- )- if ctx.summary and getattr(ctx.summary, "content", None):- result["summary"] = ctx.summary.content- except HonchoAuthError:- # Auth is dead; the pop_auth_notice path tells the model why context is missing.- return result- except Exception as e:- logger.debug("Failed to fetch session summary from Honcho: %s", e)-- try:- observer_peer_id, target_peer_id = self._resolve_observer_target(session, "user")- user_ctx = self._fetch_peer_context(observer_peer_id, search_query=user_message or None, target=target_peer_id or session.user_peer_id)- result["representation"] = user_ctx["representation"]- result["card"] = "\n".join(user_ctx["card"])- except HonchoAuthError:- return result- except Exception as e:- logger.warning("Failed to fetch user context from Honcho: %s", e)-- # Also fetch AI peer's own representation so Hermes knows itself.- try:- ai_ctx = self._fetch_peer_context(session.assistant_peer_id, target=session.assistant_peer_id)- result["ai_representation"] = ai_ctx["representation"]- result["ai_card"] = "\n".join(ai_ctx["card"])- except HonchoAuthError:- return result- except Exception as e:- logger.debug("Failed to fetch AI peer context from Honcho: %s", e)-- return result-- def migrate_local_history(self, session_key: str, messages: list[dict[str, Any]]) -> bool:- """- Upload local session history to Honcho as a file.-- Used when Honcho activates mid-conversation to preserve prior context.-- Args:- session_key: The session key (e.g., "telegram:123456").- messages: Local messages (dicts with role, content, timestamp).-- Returns:- True if upload succeeded, False otherwise.- """- session = self._cache.get(session_key)- if not session:- logger.warning("No local session cached for '%s', skipping migration", session_key)- return False-- if session.honcho_session_id not in self._sessions_cache:- logger.warning("No Honcho session cached for '%s', skipping migration", session_key)- return False-- content_bytes = self._format_migration_transcript(session_key, messages)- first_ts = messages[0].get("timestamp") if messages else None-- try:- def _upload() -> None:- user_peer = self._get_or_create_peer(session.user_peer_id)- self._sdk_session(session.honcho_session_id).upload_file(- file=("prior_history.txt", content_bytes, "text/plain"),- peer=user_peer,- metadata={"source": "local_jsonl", "count": len(messages)},- created_at=first_ts,- )-- self._authed_call("history migration upload", _upload)- logger.info("Migrated %d local messages to Honcho for %s", len(messages), session_key)- return True- except Exception as e:- logger.error("Failed to upload local history to Honcho for %s: %s", session_key, e)- return False-- @staticmethod- def _format_migration_transcript(session_key: str, messages: list[dict[str, Any]]) -> bytes:- """Format local messages as an XML transcript for Honcho file upload."""- timestamps = [m.get("timestamp", "") for m in messages]- time_range = f"{timestamps[0]} to {timestamps[-1]}" if timestamps else "unknown"-- lines = [- "<prior_conversation_history>",- "<context>",- "This conversation history occurred BEFORE the Honcho memory system was activated.",- "These messages are the preceding elements of this conversation session and should",- "be treated as foundational context for all subsequent interactions. The user and",- "assistant have already established rapport through these exchanges.",- "</context>",- "",- f'<transcript session_key="{session_key}" message_count="{len(messages)}"',- f' time_range="{time_range}">',- "",- ]- for msg in messages:- ts = msg.get("timestamp", "?")- role = msg.get("role", "unknown")- content = msg.get("content") or ""- lines.append(f"[{ts}] {role}: {content}")-- lines.append("")- lines.append("</transcript>")- lines.append("</prior_conversation_history>")-- return "\n".join(lines).encode("utf-8")-- def migrate_memory_files(self, session_key: str, memory_dir: str) -> bool:- """- Upload MEMORY.md and USER.md to Honcho as files.-- Used when Honcho activates on an instance that already has locally- consolidated memory. Backwards compatible -- skips if files don't exist.-- Args:- session_key: The session key to associate files with.- memory_dir: Path to the memories directory (~/.hermes/memories/).-- Returns:- True if at least one file was uploaded, False otherwise.- """- from pathlib import Path- memory_path = Path(memory_dir)-- if not memory_path.exists():- return False-- session = self._cache.get(session_key)- if not session:- logger.warning("No local session cached for '%s', skipping memory migration", session_key)- return False-- if session.honcho_session_id not in self._sessions_cache:- logger.warning("No Honcho session cached for '%s', skipping memory migration", session_key)- return False-- # Only migrate the owner-describing memory files (MEMORY.md / USER.md)- # when the session's user peer IS the install owner. Otherwise a- # non-owner triggering a new session (e.g. any other human in a shared- # Slack/Discord channel) gets the owner's full profile files uploaded- # under the NON-OWNER's peer, and Honcho's deriver attributes the- # owner's facts to that person. SOUL.md describes the agent, not a- # human, but skipping it here too keeps the migration owner-scoped.- #- # The owner is a CONFIG fact — the declared peerName — never a- # re-resolution of the session's own peer: _resolve_user_peer_id- # answers "who is this session's user", so comparing its output to- # session.user_peer_id compares the triggering user to themselves- # and passes for the non-owner too.- owner_peer_id = self._declared_owner_peer_id()- if owner_peer_id is not None:- session_is_owner = session.user_peer_id == owner_peer_id- else:- # No declared owner. Without a runtime identity this is the- # single-operator path (peer id from config defaults or the- # session key) and the files describe that operator. With a- # runtime identity the session belongs to whoever messaged- # through the gateway — nobody can be proven to be the owner.- session_is_owner = 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",- )- return False-- uploaded = False- files = [- (- "MEMORY.md",- "consolidated_memory.md",- "Long-term agent notes and preferences",- session.user_peer_id,- "user",- ),- (- "USER.md",- "user_profile.md",- "User profile and preferences",- session.user_peer_id,- "user",- ),- (- "SOUL.md",- "agent_soul.md",- "Agent persona and identity configuration",- session.assistant_peer_id,- "ai",- ),- ]-- for filename, upload_name, description, target_peer_id, target_kind in files:- filepath = memory_path / filename- if not filepath.exists():- continue- content = filepath.read_text(encoding="utf-8").strip()- if not content:- continue-- wrapped = (- f"<prior_memory_file>\n"- f"<context>\n"- f"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"- f"\n"- f"{content}\n"- f"</prior_memory_file>\n"- )-- try:- def _upload() -> None:- self._sdk_session(session.honcho_session_id).upload_file(- file=(upload_name, wrapped.encode("utf-8"), "text/plain"),- peer=self._get_or_create_peer(target_peer_id),- metadata={- "source": "local_memory",- "original_file": filename,- "target_peer": target_kind,- },- )-- self._authed_call("memory migration upload", _upload)- logger.info(- "Uploaded %s to Honcho for %s (%s peer)",- filename,- session_key,- target_kind,- )- uploaded = True- except HonchoAuthError:- logger.error("Honcho memory migration stopped after %s: auth failed", filename)- break- except Exception as e:- logger.error("Failed to upload %s to Honcho: %s", filename, e)-- return uploaded-- @staticmethod- def _normalize_card(card: Any) -> list[str]:- """Normalize Honcho card payloads into a plain list of strings."""- if not card:- return []- if isinstance(card, list):- return [str(item) for item in card if item]- return [str(card)]-- def _fetch_peer_card(self, peer_id: str, *, target: str | None = None) -> list[str]:- """Fetch a peer card directly from the peer object.-- This avoids relying on session.context(), which can return an empty- peer_card for per-session messaging sessions even when the peer itself- has a populated card.- """- def _get_card() -> Any:- peer = self._get_or_create_peer(peer_id)- getter = getattr(peer, "get_card", None)- if callable(getter):- return getter(target=target) if target is not None else getter()- legacy_getter = getattr(peer, "card", None)- if callable(legacy_getter):- return legacy_getter(target=target) if target is not None else legacy_getter()- return None-- return self._normalize_card(self._authed_call("peer card fetch", _get_card))-- def _fetch_peer_context(- self,- peer_id: str,- search_query: str | None = None,- *,- target: str | None = None,- ) -> dict[str, Any]:- """Fetch representation + peer card directly from a peer object.-- Raises HonchoAuthError when auth is dead or a 401 survives the forced- refresh; the non-auth fallback chain would just repeat the failure.- """- representation = ""- card: list[str] = []-- try:- context_kwargs: dict[str, Any] = {}- if target is not None:- context_kwargs["target"] = target- if search_query is not None:- context_kwargs["search_query"] = search_query-- def _peer_context() -> Any:- peer = self._get_or_create_peer(peer_id)- return peer.context(**context_kwargs) if context_kwargs else peer.context()-- ctx = self._authed_call("peer context fetch", _peer_context)- representation = (- getattr(ctx, "representation", None)- or getattr(ctx, "peer_representation", None)- or ""- )- card = self._normalize_card(getattr(ctx, "peer_card", None))- except HonchoAuthError:- raise- except Exception as e:- logger.debug("Direct peer.context() failed for '%s': %s", peer_id, e)-- if not representation:- try:- def _peer_representation() -> Any:- peer = self._get_or_create_peer(peer_id)- return peer.representation(target=target) if target is not None else peer.representation()-- representation = self._authed_call(- "peer representation fetch", _peer_representation- ) or ""- except HonchoAuthError:- raise- except Exception as e:- logger.debug("Direct peer.representation() failed for '%s': %s", peer_id, e)-- if not card:- try:- card = self._fetch_peer_card(peer_id, target=target)- except HonchoAuthError:- raise- except Exception as e:- logger.debug("Direct peer card fetch failed for '%s': %s", peer_id, e)-- return {"representation": representation, "card": card}-- def get_session_context(self, session_key: str, peer: str = "user") -> dict[str, Any]:- """Fetch full session context from Honcho including summary.-- Uses the session-level context() API which returns summary,- peer_representation, peer_card, and messages.- Raises HonchoAuthError so callers can tell rejected credentials from no context.- """- session = self._cache.get(session_key)- if not session:- return {}-- if session.honcho_session_id not in self._sessions_cache:- # Fall back to peer-level context, respecting the requested peer- peer_id = self._resolve_peer_id(session, peer)- if peer_id is None:- peer_id = session.user_peer_id- return self._fetch_peer_context(peer_id, target=peer_id)-- try:- observer_peer_id, target_peer_id = self._resolve_observer_target(session, peer)- ctx = self._authed_call(- "session context fetch",- lambda: self._sdk_session(session.honcho_session_id).context(- summary=True,- peer_target=target_peer_id or observer_peer_id,- peer_perspective=observer_peer_id,- ),- )-- result: dict[str, Any] = {}-- # Summary- if ctx.summary:- result["summary"] = ctx.summary.content-- # Peer representation and card- if ctx.peer_representation:- result["representation"] = ctx.peer_representation- if ctx.peer_card:- result["card"] = "\n".join(ctx.peer_card)-- # Messages (last N for context)- if ctx.messages:- recent = ctx.messages[-10:] # last 10 messages- result["recent_messages"] = [- {"role": getattr(m, "peer_id", "unknown"), "content": (m.content or "")[:500]}- for m in recent- ]-- return result- except HonchoAuthError:- raise- except Exception as e:- logger.debug("Session context fetch failed: %s", e)- return {}-- def _resolve_peer_id(self, session: HonchoSession, peer: str | None) -> str:- """Resolve a peer alias or explicit peer ID to a concrete Honcho peer ID.-- Always returns a non-empty string: either a known peer ID or a- sanitized version of the caller-supplied alias/ID.- """- candidate = (peer or "user").strip()- if not candidate:- return session.user_peer_id-- normalized = self._sanitize_id(candidate)- if normalized == self._sanitize_id("user"):- return session.user_peer_id- if normalized == self._sanitize_id("ai"):- return session.assistant_peer_id-- return normalized-- def _resolve_observer_target(- self,- session: HonchoSession,- peer: str | None,- ) -> tuple[str, str | None]:- """Resolve observer and 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:- return session.assistant_peer_id, session.assistant_peer_id-- if self._ai_observe_others:- return session.assistant_peer_id, target_peer_id-- return target_peer_id, None-- def get_peer_card(self, session_key: str, peer: str = "user") -> list[str]:- """- Fetch a peer card — a curated list of key facts.-- Fast, no LLM reasoning. Returns raw structured facts Honcho has- inferred about the target peer (name, role, preferences, patterns).- Empty list if unavailable; raises HonchoAuthError on rejected credentials.- """- session = self._cache.get(session_key)- if not session:- return []-- try:- observer_peer_id, target_peer_id = self._resolve_observer_target(session, peer)- card = self._fetch_peer_card(observer_peer_id, target=target_peer_id)- if card:- return card- # Some backends store cards directly on the target peer, not the- # observer-target slot. Fall back so honcho_profile still works.- if target_peer_id:- return self._fetch_peer_card(target_peer_id)- return []- except HonchoAuthError:- raise- except Exception as e:- logger.debug("Failed to fetch peer card from Honcho: %s", e)- return []-- def search_context(- self,- session_key: str,- query: str,- max_tokens: int = 800,- peer: str = "user",- ) -> str:- """- Search raw messages across every session visible from the target- peer's perspective. Results include all authors and require no LLM- synthesis.-- Args:- session_key: Session whose workspace/peer scope to search within.- query: Search query (hybrid semantic + full-text).- max_tokens: Approximate budget for returned content. Snippets are- accumulated until this budget (≈4 chars/token) is exhausted.- peer: Peer alias or explicit peer ID whose sessions to search.-- Returns:- Ranked message excerpts as a formatted string, or empty string- if none found.-- Raises:- HonchoAuthError: rejected credentials, so no-results is not implied.- """- session = self._cache.get(session_key)- if not session:- return ""-- # peer_perspective spans the target peer's sessions across all authors.- peer_id = self._resolve_peer_id(session, peer)-- # Honcho caps query length for the embedding model; keep well under it.- q = (query or "").strip()- if not q:- return ""- if len(q) > 4000:- q = q[:4000]-- # Approximate four characters per token and a few hundred per result.- char_budget = max(200, int(max_tokens) * 4)- limit = max(3, min(20, char_budget // 300))-- try:- messages = self._authed_call(- "message search",- lambda: self.honcho.search(- q,- filters={"peer_perspective": peer_id},- limit=limit,- ),- )- except HonchoAuthError:- raise- except Exception as e:- logger.debug("Honcho message search failed (peer_perspective=%s): %s", peer_id, e)- # Fall back to peer-authored search if the perspective filter is- # unsupported by the running Honcho version.- try:- messages = self._authed_call(- "peer search",- lambda: self._get_or_create_peer(peer_id).search(q, limit=limit),- )- except HonchoAuthError:- raise- except Exception as e2:- logger.debug("Honcho peer search fallback also failed: %s", e2)- return ""-- if not messages:- return ""-- # Author labels distinguish user-stated facts from assistant-derived ones.- assistant_id = session.assistant_peer_id- lines: list[str] = []- used = 0- for m in messages:- content = (getattr(m, "content", "") or "").strip()- if not content:- continue- author = getattr(m, "peer_id", "") or "unknown"- who = "assistant" if author == assistant_id else author- sess = getattr(m, "session_id", "") or ""- snippet = content[:1200]- entry = f"[{who}{f' · {sess}' if sess else ''}] {snippet}"- separator = "\n\n" if lines else ""- remaining = char_budget - used - len(separator)- if remaining <= 0:- break- if len(entry) > remaining:- entry = entry[:remaining].rstrip()- if not entry:- break- lines.append(entry)- used += len(separator) + len(entry)- break- lines.append(entry)- used += len(separator) + len(entry)-- return "\n\n".join(lines)-- def _conclusions_scope(self, session: Any, target_peer_id: str) -> Any:- """Resolve the ConclusionScope for observing target_peer_id.-- Shared by create/delete/list_conclusions so the observer/observed- routing (self-conclusions vs. AI-observes-others vs. peer-owned)- stays consistent across all three.- """- if target_peer_id == session.assistant_peer_id:- observer = self._get_or_create_peer(session.assistant_peer_id)- return observer.conclusions_of(session.assistant_peer_id)- elif self._ai_observe_others:- observer = self._get_or_create_peer(session.assistant_peer_id)- return observer.conclusions_of(target_peer_id)- else:- target_peer = self._get_or_create_peer(target_peer_id)- return target_peer.conclusions_of(target_peer_id)-- def create_conclusion(self, session_key: str, content: str, peer: str = "user") -> bool:- """Write a conclusion about a target peer back to Honcho.-- Conclusions are facts a peer observes about another peer or itself —- preferences, corrections, clarifications, and project context.- They feed into the target peer's card and representation.-- Args:- session_key: Session to associate the conclusion with.- content: The conclusion text.- peer: Peer alias or explicit peer ID. "user" is the default alias.-- Returns:- True on success, False on failure.- """- if not content or not content.strip():- return False-- session = self._cache.get(session_key)- if not session:- logger.warning("No session cached for '%s', skipping conclusion", session_key)- return False-- try:- target_peer_id = self._resolve_peer_id(session, peer)- if target_peer_id is None:- logger.warning("Could not resolve conclusion peer '%s' for session '%s'", peer, session_key)- return False-- self._authed_call(- "conclusion create",- lambda: self._conclusions_scope(session, target_peer_id).create([{- "content": content.strip(),- "session_id": session.honcho_session_id,- }]),- )- logger.info("Created conclusion about %s for %s: %s", target_peer_id, session_key, content[:80])- return True- except HonchoAuthError:- raise- except Exception as e:- logger.error("Failed to create conclusion: %s", e)- return False-- def delete_conclusion(self, session_key: str, conclusion_id: str, peer: str = "user") -> bool:- """Delete a conclusion by ID. Use only for PII removal.-- Args:- session_key: Session key for peer resolution.- conclusion_id: The conclusion ID to delete.- peer: Peer alias or explicit peer ID.-- Returns:- True on success, False on failure.- """- session = self._cache.get(session_key)- if not session:- return False- try:- target_peer_id = self._resolve_peer_id(session, peer)- self._authed_call(- "conclusion delete",- lambda: self._conclusions_scope(session, target_peer_id).delete(conclusion_id),- )- logger.info("Deleted conclusion %s for %s", conclusion_id, session_key)- return True- except HonchoAuthError:- raise- except Exception as e:- logger.error("Failed to delete conclusion %s: %s", conclusion_id, e)- return False-- def list_conclusions(- self,- session_key: str,- query: str | None = None,- peer: str = "user",- limit: int = 20,- ) -> list[dict]:- """List or semantically search conclusions with their server IDs.-- Args:- session_key: Session key for peer resolution.- query: Optional semantic search query. Omit to list recent conclusions.- peer: Peer alias or explicit peer ID.- limit: Max conclusions to return.-- Returns:- List of {"id": ..., "content": ...} dicts, or [] on failure/no session.- """- session = self._cache.get(session_key)- if not session:- return []- try:- target_peer_id = self._resolve_peer_id(session, peer)- if target_peer_id is None:- return []-- def _list() -> Any:- scope = self._conclusions_scope(session, target_peer_id)- if query:- return scope.query(query, top_k=limit)- return scope.list(size=limit).items-- conclusions = self._authed_call("conclusion list", _list)- return [{"id": c.id, "content": c.content} for c in conclusions]- except HonchoAuthError:- raise- except Exception as e:- logger.debug("Honcho list_conclusions failed: %s", e)- return []-- def set_peer_card(self, session_key: str, card: list[str], peer: str = "user") -> list[str] | None:- """Update a peer's card.-- Args:- session_key: Session key for peer resolution.- card: New peer card as list of fact strings.- peer: Peer alias or explicit peer ID.-- Returns:- Updated card on success, None on failure.- """- session = self._cache.get(session_key)- if not session:- return None- try:- observer_peer_id, target_peer_id = self._resolve_observer_target(session, peer)- if observer_peer_id is None:- logger.warning("Could not resolve peer '%s' for set_peer_card in session '%s'", peer, session_key)- return None-- def _set_card() -> Any:- peer_obj = self._get_or_create_peer(observer_peer_id)- if target_peer_id is not None:- return peer_obj.set_card(card, target=target_peer_id)- return peer_obj.set_card(card)-- result = self._authed_call("peer card update", _set_card)- logger.info(- "Updated peer card observer=%s target=%s (%d facts)",- observer_peer_id,- target_peer_id or observer_peer_id,- len(card),- )- return result- except HonchoAuthError:- raise- except Exception as e:- logger.error("Failed to set peer card: %s", e)- return None-- def seed_ai_identity(self, session_key: str, content: str, source: str = "manual") -> bool:- """- Seed the AI peer's Honcho representation from text content.-- Useful for priming AI identity from SOUL.md, exported chats, or- any structured description. The content is sent as an assistant- peer message so Honcho's reasoning model can incorporate it.-- Args:- session_key: The session key to associate with.- content: The identity/persona content to seed.- source: Metadata tag for the source (e.g. "soul_md", "export").-- Returns:- True on success, False on failure.- """- if not content or not content.strip():- return False-- session = self._cache.get(session_key)- if not session:- logger.warning("No session cached for '%s', skipping AI seed", session_key)- return False-- if session.honcho_session_id not in self._sessions_cache:- logger.warning("No Honcho session cached for '%s', skipping AI seed", session_key)- return False-- try:- wrapped = (- f"<ai_identity_seed>\n"- f"<source>{source}</source>\n"- f"\n"- f"{content.strip()}\n"- f"</ai_identity_seed>"- )-- def _seed() -> None:- assistant_peer = self._get_or_create_peer(session.assistant_peer_id)- self._sdk_session(session.honcho_session_id).add_messages(- [assistant_peer.message(wrapped)]- )-- self._authed_call("identity seed", _seed)- logger.info("Seeded AI identity from '%s' into %s", source, session_key)- return True- except Exception as e:- logger.error("Failed to seed AI identity: %s", e)- return False-- def get_ai_representation(self, session_key: str) -> dict[str, str]:- """- Fetch the AI peer's current Honcho representation.-- Returns:- Dict with 'representation' and 'card' keys, empty strings if unavailable.- """- session = self._cache.get(session_key)- if not session:- return {"representation": "", "card": ""}-- try:- ctx = self._fetch_peer_context(session.assistant_peer_id, target=session.assistant_peer_id)- return {- "representation": ctx["representation"] or "",- "card": "\n".join(ctx["card"]),- }- except HonchoAuthError:- raise- except Exception as e:- logger.debug("Failed to fetch AI representation: %s", e)- return {"representation": "", "card": ""}-- def list_sessions(self) -> list[dict[str, Any]]:- """List all cached sessions."""- return [- {- "key": s.key,- "created_at": s.created_at.isoformat(),- "updated_at": s.updated_at.isoformat(),- "message_count": len(s.messages),- }- for s in self._cache.values()- ]diff --git a/plugins/memory/honcho/session_auth.py b/plugins/memory/honcho/session_auth.pynew file mode 100644index 00000000000..19ce2935b43--- /dev/null+++ b/plugins/memory/honcho/session_auth.py@@ -0,0 +1,169 @@+"""Auth-failure tracking and 401-retry wrapper for HonchoSessionManager."""++from __future__ import annotations++import logging+import re+from pathlib import Path+from typing import Any, Callable++from plugins.memory.honcho.oauth import redact_tokens as _redact_tokens++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.+ """+++# Matched narrowly: a false positive spends a token rotation, and a lost rotation revokes the grant.+_AUTH_ERROR_MARKERS = (+ "invalid or expired access token",+ "authentication failed",+ "unauthorized",+)++# A 401 in text counts only with HTTP context ("HTTP 401", "status 401"), never as a bare number.+_HTTP_401_RE = re.compile(r"\b(?:http|status(?:[ _]code)?\s*[:=]?)\s*401\b")+++def _is_auth_error(exc: BaseException) -> bool:+ status = getattr(exc, "status_code", None) or getattr(exc, "status", None)+ if status == 401:+ return True+ # The transport reported a concrete non-auth status; trust it over text.+ if isinstance(status, int) and status not in (0, 401):+ return False+ text = str(exc).lower()+ if _HTTP_401_RE.search(text):+ return True+ return any(marker in text for marker in _AUTH_ERROR_MARKERS)+++_REAUTH_REQUIRED_MESSAGE = (+ "Honcho OAuth grant is revoked and cannot be refreshed; "+ "re-authenticate with 'hermes honcho setup'."+)+++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'."+ )+++class SessionAuthMixin:+ """Auth state + ``_authed_call`` for HonchoSessionManager (state lives in __init__)."""++ 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,+ )+ self._auth_failure = detail++ def _clear_auth_failure(self) -> None:+ if self._auth_failure is not None:+ logger.info("Honcho authentication recovered; memory sync and recall resumed")+ self._auth_failure = None+ self._auth_notice_emitted = False++ def pop_auth_notice(self) -> str | None:+ """Return the pending auth-failure message once; later calls return None."""+ if self._auth_failure is None or self._auth_notice_emitted:+ return None+ self._auth_notice_emitted = True+ return self._auth_failure++ def _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).+ """+ 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()++ def _reauth_required(self) -> bool:+ """True when the grant is dead and only a new login can fix it (no network call)."""+ try:+ from plugins.memory.honcho import oauth++ # Fast path: runs before every SDK call, so skip path resolution when nothing is dead.+ host = getattr(self._config, "host", "") or ""+ return bool(oauth.any_dead_grants() and host and oauth.reauth_required(self._bound_config_path(), host))+ except Exception:+ return False++ def _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.+ """+ try:+ from plugins.memory.honcho import oauth+ from plugins.memory.honcho.client import reset_honcho_client++ host = getattr(self._config, "host", "") or ""+ if not host:+ return False+ token = oauth.force_refresh_token(self._bound_config_path(), host)+ if not token:+ return False+ if not oauth.apply_token_to_client(self.honcho, token):+ # SDK shape changed: rebuild the client and drop objects holding the old transport.+ reset_honcho_client()+ with self._cache_lock:+ self._client_generation += 1+ self._peers_cache.clear()+ self._sessions_cache.clear()+ return True+ except Exception:+ logger.warning("Honcho post-401 token refresh failed", exc_info=True)+ return False++ def _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.+ """+ if self._reauth_required():+ exc = HonchoAuthError(_REAUTH_REQUIRED_MESSAGE)+ self._record_auth_failure(exc)+ raise exc+ try:+ result = operation()+ except HonchoAuthError:+ raise+ 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)),+ )+ if not self._force_reauth():+ self._record_auth_failure(e)+ raise HonchoAuthError(_auth_error_message(e)) from e+ try:+ result = operation()+ except Exception as retry_exc:+ if not _is_auth_error(retry_exc):+ raise+ self._record_auth_failure(retry_exc)+ raise HonchoAuthError(_auth_error_message(retry_exc)) from retry_exc+ self._clear_auth_failure()+ return resultdiff --git a/plugins/memory/honcho/session_context.py b/plugins/memory/honcho/session_context.pynew file mode 100644index 00000000000..b2dea1b1c3d--- /dev/null+++ b/plugins/memory/honcho/session_context.py@@ -0,0 +1,447 @@+"""Recall/read-path cluster for HonchoSessionManager: context, cards, search, conclusions, dialectic."""++from __future__ import annotations++import logging+from typing import Any, Callable++from plugins.memory.honcho.session_auth import HonchoAuthError++logger = logging.getLogger("plugins.memory.honcho.session")++_EMPTY_REPRESENTATION = {"representation": "", "card": ""}+++class SessionContextMixin:+ """Peer context / card / search / conclusion / dialectic operations against Honcho."""++ def _guarded(self, fn: Callable[[], Any], default: Any, level: int, msg: str, *args: Any) -> Any:+ """Run ``fn``; re-raise HonchoAuthError, log (exc appended to args) and return default otherwise."""+ try:+ return fn()+ except HonchoAuthError:+ raise+ except Exception as e:+ logger.log(level, msg, *args, e)+ return default++ @staticmethod+ def _normalize_card(card: Any) -> list[str]:+ """Normalize Honcho card payloads into a plain list of strings."""+ if not card:+ return []+ if isinstance(card, list):+ return [str(item) for item in card if item]+ return [str(card)]++ @staticmethod+ def _target_kwargs(target: str | None) -> dict[str, str]:+ """SDK peer getters take ``target=`` only when observing another peer."""+ return {} if target is None else {"target": target}++ def _fetch_peer_card(self, peer_id: str, *, target: str | None = None) -> list[str]:+ """Fetch a peer card from the peer object (session.context() can return an empty card)."""+ def _get_card() -> Any:+ peer = self._get_or_create_peer(peer_id)+ for name in ("get_card", "card"): # "card" is the legacy SDK getter+ getter = getattr(peer, name, None)+ if callable(getter):+ return getter(**self._target_kwargs(target))+ return None++ return self._normalize_card(self._authed_call("peer card fetch", _get_card))++ def _fetch_peer_context(+ self, peer_id: str, search_query: str | None = None, *, target: str | None = None,+ ) -> dict[str, Any]:+ """Fetch representation + peer card from a peer object.++ Raises HonchoAuthError when auth is dead or a 401 survives the forced+ refresh; the non-auth fallback chain would just repeat the failure.+ """+ context_kwargs: dict[str, Any] = self._target_kwargs(target)+ if search_query is not None:+ context_kwargs["search_query"] = search_query++ def _peer_context() -> tuple[str, list[str]]:+ ctx = self._authed_call(+ "peer context fetch", lambda: self._get_or_create_peer(peer_id).context(**context_kwargs),+ )+ rep = getattr(ctx, "representation", None) or getattr(ctx, "peer_representation", None) or ""+ return rep, self._normalize_card(getattr(ctx, "peer_card", None))++ def _peer_representation() -> Any:+ return self._get_or_create_peer(peer_id).representation(**self._target_kwargs(target))++ representation, card = self._guarded(+ _peer_context, ("", []), logging.DEBUG, "Direct peer.context() failed for '%s': %s", peer_id,+ )++ if not representation:+ representation = self._guarded(+ lambda: self._authed_call("peer representation fetch", _peer_representation) or "",+ "", logging.DEBUG, "Direct peer.representation() failed for '%s': %s", peer_id,+ )+ if not card:+ card = self._guarded(+ lambda: self._fetch_peer_card(peer_id, target=target),+ [], logging.DEBUG, "Direct peer card fetch failed for '%s': %s", peer_id,+ )+ return {"representation": representation, "card": card}++ def get_prefetch_context(self, session_key: str, user_message: str | None = None) -> dict[str, str]:+ """Pre-fetch user + AI peer context (representation, card) plus the session summary.++ ``user_message`` is passed as search_query so Honcho returns topic-relevant+ conclusions. Stops early (returning what it has) once auth is dead.+ """+ session = self._cache.get(session_key)+ if not session:+ return {}++ result: dict[str, str] = {}++ def _summary() -> None:+ if session.honcho_session_id not in self._sessions_cache:+ return+ ctx = self._authed_call(+ "session summary fetch",+ lambda: self._sdk_session(session.honcho_session_id).context(summary=True),+ )+ if ctx.summary and getattr(ctx.summary, "content", None):+ result["summary"] = ctx.summary.content++ def _user() -> None:+ observer_peer_id, target_peer_id = self._resolve_observer_target(session, "user")+ ctx = self._fetch_peer_context(+ observer_peer_id, search_query=user_message or None,+ target=target_peer_id or session.user_peer_id,+ )+ result["representation"], result["card"] = ctx["representation"], "\n".join(ctx["card"])++ def _ai() -> None:+ ctx = self._fetch_peer_context(session.assistant_peer_id, target=session.assistant_peer_id)+ result["ai_representation"], result["ai_card"] = ctx["representation"], "\n".join(ctx["card"])++ for step, level, msg in (+ (_summary, logging.DEBUG, "Failed to fetch session summary from Honcho: %s"),+ (_user, logging.WARNING, "Failed to fetch user context from Honcho: %s"),+ (_ai, logging.DEBUG, "Failed to fetch AI peer context from Honcho: %s"),+ ):+ try:+ step()+ except HonchoAuthError:+ # Auth is dead; the pop_auth_notice path tells the model why context is missing.+ break+ except Exception as e:+ logger.log(level, msg, e)+ return result++ def get_session_context(self, session_key: str, peer: str = "user") -> dict[str, Any]:+ """Fetch session-level context (summary, representation, card, recent messages).++ Raises HonchoAuthError so callers can tell rejected credentials from no context.+ """+ session = self._cache.get(session_key)+ if not session:+ return {}++ if session.honcho_session_id not in self._sessions_cache:+ # Fall back to peer-level context, respecting the requested peer.+ peer_id = self._resolve_peer_id(session, peer)+ return self._fetch_peer_context(peer_id, target=peer_id)++ def _fetch() -> dict[str, Any]:+ observer_peer_id, target_peer_id = self._resolve_observer_target(session, peer)+ ctx = self._authed_call(+ "session context fetch",+ lambda: self._sdk_session(session.honcho_session_id).context(+ summary=True,+ peer_target=target_peer_id or observer_peer_id,+ peer_perspective=observer_peer_id,+ ),+ )+ result: dict[str, Any] = {}+ if ctx.summary:+ result["summary"] = ctx.summary.content+ if ctx.peer_representation:+ result["representation"] = ctx.peer_representation+ if ctx.peer_card:+ result["card"] = "\n".join(ctx.peer_card)+ if ctx.messages:+ result["recent_messages"] = [+ {"role": getattr(m, "peer_id", "unknown"), "content": (m.content or "")[:500]}+ for m in ctx.messages[-10:]+ ]+ return result++ return self._guarded(_fetch, {}, logging.DEBUG, "Session context fetch failed: %s")++ def get_peer_card(self, session_key: str, peer: str = "user") -> list[str]:+ """Fetch a peer card (curated facts, no LLM). [] if unavailable; raises HonchoAuthError."""+ session = self._cache.get(session_key)+ if not session:+ return []++ def _fetch() -> list[str]:+ observer_peer_id, target_peer_id = self._resolve_observer_target(session, peer)+ card = self._fetch_peer_card(observer_peer_id, target=target_peer_id)+ if card:+ return card+ # Some backends store cards on the target peer, not the observer-target slot.+ return self._fetch_peer_card(target_peer_id) if target_peer_id else []++ return self._guarded(_fetch, [], logging.DEBUG, "Failed to fetch peer card from Honcho: %s")++ def search_context(+ self, session_key: str, query: str, max_tokens: int = 800, peer: str = "user",+ ) -> str:+ """Hybrid search over raw messages visible from ``peer``'s perspective, all sessions.++ Snippets accumulate until ``max_tokens`` (~4 chars/token) is exhausted.+ Returns "" when nothing matches; raises HonchoAuthError on rejected credentials.+ """+ session = self._cache.get(session_key)+ q = (query or "").strip()[:4000] # Honcho caps query length for the embedding model.+ if not session or not q:+ return ""+ peer_id = self._resolve_peer_id(session, peer)++ char_budget = max(200, int(max_tokens) * 4)+ limit = max(3, min(20, char_budget // 300))++ try:+ messages = self._authed_call(+ "message search",+ lambda: self.honcho.search(q, filters={"peer_perspective": peer_id}, limit=limit),+ )+ except HonchoAuthError:+ raise+ except Exception as e:+ logger.debug("Honcho message search failed (peer_perspective=%s): %s", peer_id, e)+ # Older Honcho versions lack the perspective filter; fall back to peer-authored search.+ messages = self._guarded(+ lambda: self._authed_call(+ "peer search", lambda: self._get_or_create_peer(peer_id).search(q, limit=limit),+ ),+ None, logging.DEBUG, "Honcho peer search fallback also failed: %s",+ )+ if not messages:+ return ""++ # Author labels distinguish user-stated facts from assistant-derived ones.+ lines: list[str] = []+ used = 0+ for m in messages:+ content = (getattr(m, "content", "") or "").strip()+ if not content:+ continue+ author = getattr(m, "peer_id", "") or "unknown"+ who = "assistant" if author == session.assistant_peer_id else author+ sess = getattr(m, "session_id", "") or ""+ entry = f"[{who}{f' · {sess}' if sess else ''}] {content[:1200]}"+ separator = "\n\n" if lines else ""+ remaining = char_budget - used - len(separator)+ if remaining <= 0:+ break+ truncated = len(entry) > remaining+ entry = entry[:remaining].rstrip()+ if not entry:+ break+ lines.append(entry)+ used += len(separator) + len(entry)+ if truncated:+ break+ return "\n\n".join(lines)++ def _conclusions_scope(self, session: Any, target_peer_id: str) -> Any:+ """ConclusionScope for observing target_peer_id; shared by create/delete/list."""+ if target_peer_id == session.assistant_peer_id or self._ai_observe_others:+ observer = self._get_or_create_peer(session.assistant_peer_id)+ else:+ observer = self._get_or_create_peer(target_peer_id)+ return observer.conclusions_of(target_peer_id)++ def create_conclusion(self, session_key: str, content: str, peer: str = "user") -> bool:+ """Write a conclusion (durable fact) about ``peer`` back to Honcho."""+ if not content or not content.strip():+ return False+ session = self._cache.get(session_key)+ if not session:+ logger.warning("No session cached for '%s', skipping conclusion", session_key)+ return False++ def _create() -> bool:+ target_peer_id = self._resolve_peer_id(session, peer)+ if target_peer_id is None:+ logger.warning("Could not resolve conclusion peer '%s' for session '%s'", peer, session_key)+ return False+ self._authed_call(+ "conclusion create",+ lambda: self._conclusions_scope(session, target_peer_id).create([{+ "content": content.strip(),+ "session_id": session.honcho_session_id,+ }]),+ )+ logger.info("Created conclusion about %s for %s: %s", target_peer_id, session_key, content[:80])+ return True++ return self._guarded(_create, False, logging.ERROR, "Failed to create conclusion: %s")++ def delete_conclusion(self, session_key: str, conclusion_id: str, peer: str = "user") -> bool:+ """Delete a conclusion by ID. Use only for PII removal."""+ session = self._cache.get(session_key)+ if not session:+ return False++ def _delete() -> bool:+ target_peer_id = self._resolve_peer_id(session, peer)+ self._authed_call(+ "conclusion delete",+ lambda: self._conclusions_scope(session, target_peer_id).delete(conclusion_id),+ )+ logger.info("Deleted conclusion %s for %s", conclusion_id, session_key)+ return True++ return self._guarded(+ _delete, False, logging.ERROR, "Failed to delete conclusion %s: %s", conclusion_id,+ )++ def list_conclusions(+ self, session_key: str, query: str | None = None, peer: str = "user", limit: int = 20,+ ) -> list[dict]:+ """List (or semantically search with ``query``) conclusions as {"id", "content"} dicts."""+ session = self._cache.get(session_key)+ if not session:+ return []++ def _list() -> list[dict]:+ target_peer_id = self._resolve_peer_id(session, peer)+ if target_peer_id is None:+ return []++ def _fetch() -> Any:+ scope = self._conclusions_scope(session, target_peer_id)+ return scope.query(query, top_k=limit) if query else scope.list(size=limit).items++ conclusions = self._authed_call("conclusion list", _fetch)+ return [{"id": c.id, "content": c.content} for c in conclusions]++ return self._guarded(_list, [], logging.DEBUG, "Honcho list_conclusions failed: %s")++ def set_peer_card(self, session_key: str, card: list[str], peer: str = "user") -> list[str] | None:+ """Replace a peer's card. Returns the updated card, or None on failure."""+ session = self._cache.get(session_key)+ if not session:+ return None++ def _update() -> list[str] | None:+ observer_peer_id, target_peer_id = self._resolve_observer_target(session, peer)+ if observer_peer_id is None:+ logger.warning("Could not resolve peer '%s' for set_peer_card in session '%s'", peer, session_key)+ return None++ result = self._authed_call(+ "peer card update",+ lambda: self._get_or_create_peer(observer_peer_id).set_card(card, **self._target_kwargs(target_peer_id)),+ )+ logger.info(+ "Updated peer card observer=%s target=%s (%d facts)",+ observer_peer_id, target_peer_id or observer_peer_id, len(card),+ )+ return result++ return self._guarded(_update, None, logging.ERROR, "Failed to set peer card: %s")++ def seed_ai_identity(self, session_key: str, content: str, source: str = "manual") -> bool:+ """Seed the AI peer's representation from text (SOUL.md, exported chats, ...).++ Sent as an assistant-peer message so Honcho's reasoning model incorporates it.+ """+ if not content or not content.strip():+ return False+ session = self._cache.get(session_key)+ if not session:+ logger.warning("No session cached for '%s', skipping AI seed", session_key)+ return False+ if session.honcho_session_id not in self._sessions_cache:+ logger.warning("No Honcho session cached for '%s', skipping AI seed", session_key)+ return False++ wrapped = f"<ai_identity_seed>\n<source>{source}</source>\n\n{content.strip()}\n</ai_identity_seed>"++ def _seed() -> bool:+ assistant_peer = self._get_or_create_peer(session.assistant_peer_id)+ self._sdk_session(session.honcho_session_id).add_messages([assistant_peer.message(wrapped)])+ logger.info("Seeded AI identity from '%s' into %s", source, session_key)+ return True++ try:+ return self._authed_call("identity seed", _seed)+ except Exception as e:+ logger.error("Failed to seed AI identity: %s", e)+ return False++ def get_ai_representation(self, session_key: str) -> dict[str, str]:+ """Fetch the AI peer's representation + card ("" values if unavailable)."""+ session = self._cache.get(session_key)+ if not session:+ return dict(_EMPTY_REPRESENTATION)++ def _fetch() -> dict[str, str]:+ ctx = self._fetch_peer_context(session.assistant_peer_id, target=session.assistant_peer_id)+ return {"representation": ctx["representation"] or "", "card": "\n".join(ctx["card"])}++ return self._guarded(+ _fetch, dict(_EMPTY_REPRESENTATION), logging.DEBUG, "Failed to fetch AI representation: %s",+ )++ def dialectic_query(+ self, session_key: str, query: str,+ reasoning_level: str | None = None,+ peer: str = "user",+ apply_injection_cap: bool = True,+ raise_errors: bool = False,+ ) -> str:+ """Ask Honcho's dialectic endpoint about a peer (LLM on the backend; run off-thread).++ Args:+ reasoning_level: Override honored only when dialecticDynamic is true.+ apply_injection_cap: Clip to ``dialecticMaxChars`` (automatic injection only).+ raise_errors: Re-raise backend failures instead of returning "" so explicit+ tool calls can tell a timeout from an empty answer.++ Raises:+ HonchoAuthError: credentials rejected after a forced refresh and one retry.+ """+ session = self._cache.get(session_key)+ if not session:+ return ""+ target_peer_id = self._resolve_peer_id(session, peer)+ if target_peer_id is None:+ return ""++ if len(query) > self._dialectic_max_input_chars:+ query = query[:self._dialectic_max_input_chars].rsplit(" ", 1)[0]+ level = reasoning_level if (self._dialectic_dynamic and reasoning_level) else self._dialectic_reasoning_level++ def _chat_once() -> str:+ # The AI peer observes others when allowed; otherwise each peer queries its own context.+ if self._ai_observe_others and target_peer_id != session.assistant_peer_id:+ observer = self._get_or_create_peer(session.assistant_peer_id)+ return observer.chat(query, target=target_peer_id, reasoning_level=level) or ""+ return self._get_or_create_peer(target_peer_id).chat(query, reasoning_level=level) or ""++ try:+ result = self._authed_call("dialectic query", _chat_once)+ cap = self._dialectic_max_chars+ if apply_injection_cap and result and cap and len(result) > cap:+ result = result[:cap].rsplit(" ", 1)[0] + " …"+ return result+ except HonchoAuthError:+ raise+ except Exception as e:+ logger.warning("Honcho dialectic query failed: %s", e)+ if raise_errors:+ raise+ return ""diff --git a/plugins/memory/honcho/session_migration.py b/plugins/memory/honcho/session_migration.pynew file mode 100644index 00000000000..1cad107af38--- /dev/null+++ b/plugins/memory/honcho/session_migration.py@@ -0,0 +1,89 @@+"""One-time upload of local memory files (MEMORY.md / USER.md / SOUL.md) into Honcho."""++from __future__ import annotations++import logging+from pathlib import Path++from plugins.memory.honcho.session_auth import HonchoAuthError++logger = logging.getLogger("plugins.memory.honcho.session")++# (filename, upload name, description, peer kind) — peer kind picks user vs assistant peer.+_MEMORY_FILES = (+ ("MEMORY.md", "consolidated_memory.md", "Long-term agent notes and preferences", "user"),+ ("USER.md", "user_profile.md", "User profile and preferences", "user"),+ ("SOUL.md", "agent_soul.md", "Agent persona and identity configuration", "ai"),+)+++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.+ """+ memory_path = Path(memory_dir)+ if not memory_path.exists():+ return False++ session = self._cache.get(session_key)+ if not session:+ logger.warning("No local session cached for '%s', skipping memory migration", session_key)+ return False+ if session.honcho_session_id not in self._sessions_cache:+ 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_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()+ )+ 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",+ )+ return False++ uploaded = False+ for filename, upload_name, description, target_kind in _MEMORY_FILES:+ filepath = memory_path / filename+ content = filepath.read_text(encoding="utf-8").strip() if filepath.exists() else ""+ if not content:+ continue+ target_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"+ )++ def _upload() -> None:+ self._sdk_session(session.honcho_session_id).upload_file(+ file=(upload_name, wrapped.encode("utf-8"), "text/plain"),+ peer=self._get_or_create_peer(target_peer_id),+ metadata={"source": "local_memory", "original_file": filename, "target_peer": target_kind},+ )++ try:+ self._authed_call("memory migration upload", _upload)+ logger.info("Uploaded %s to Honcho for %s (%s peer)", filename, session_key, target_kind)+ uploaded = True+ except HonchoAuthError:+ logger.error("Honcho memory migration stopped after %s: auth failed", filename)+ break+ except Exception as e:+ logger.error("Failed to upload %s to Honcho: %s", filename, e)++ return uploadeddiff --git a/plugins/memory/honcho/session_peers.py b/plugins/memory/honcho/session_peers.pynew file mode 100644index 00000000000..d8cfee9233c--- /dev/null+++ b/plugins/memory/honcho/session_peers.py@@ -0,0 +1,116 @@+"""Peer-ID resolution for HonchoSessionManager (config aliases, runtime identities, fallbacks)."""++from __future__ import annotations++import hashlib+import logging+import re+from typing import TYPE_CHECKING, Any++if TYPE_CHECKING:+ from plugins.memory.honcho.session import HonchoSession++logger = logging.getLogger("plugins.memory.honcho.session")++_PEER_ID_HASH_ESCALATION_LENGTHS = (8, 12, 16, 24, 32, 64)+++class SessionPeersMixin:+ """Resolve user/assistant/observer peer IDs. Reads ``self._config`` and runtime identities only."""++ def _sanitize_id(self, id_str: str) -> str:+ """Sanitize an ID to match Honcho's pattern: ^[a-zA-Z0-9_-]+"""+ return re.sub(r'[^a-zA-Z0-9_-]', '-', id_str)++ def _cfg(self, name: str, default: Any = None) -> Any:+ return getattr(self._config, name, default) if self._config is not None else default++ def _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++ def _peer_aliases(self) -> dict:+ aliases = self._cfg("user_peer_aliases", {})+ return aliases if isinstance(aliases, dict) else {}++ 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()+ }+ owner = self._declared_owner_peer_id()+ if owner:+ explicit_ids.add(owner)+ return explicit_ids++ def _generated_runtime_peer_id(self, prefix: str, runtime_id: str) -> str:+ """Stable peer ID for an unknown prefixed runtime user; a hash suffix is added when+ sanitizing changed the ID or it collides with an explicitly configured peer."""+ raw_peer_id = f"{prefix}{runtime_id}"+ sanitized_peer_id = self._sanitize_id(raw_peer_id)+ explicit_ids = self._explicit_user_peer_ids()+ if sanitized_peer_id == raw_peer_id and sanitized_peer_id not in explicit_ids:+ return sanitized_peer_id+ digest = hashlib.sha256(raw_peer_id.encode("utf-8")).hexdigest()+ for hash_len in (*_PEER_ID_HASH_ESCALATION_LENGTHS, len(digest)):+ candidate = f"{sanitized_peer_id}-{digest[:hash_len]}"+ if candidate not in explicit_ids or hash_len == len(digest):+ return candidate++ 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++ def _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.+ """+ peer_name = self._cfg("peer_name")+ if peer_name and self._cfg("pin_peer_name", False) is True:+ return self._sanitize_id(peer_name)++ runtime_ids = self._runtime_user_ids()+ if runtime_ids:+ aliases = self._peer_aliases()+ for runtime_id in runtime_ids:+ alias = aliases.get(runtime_id)+ if isinstance(alias, str) and alias.strip():+ return self._sanitize_id(alias.strip())+ prefix = self._cfg("runtime_peer_prefix", "")+ prefix = prefix.strip() if isinstance(prefix, str) else ""+ if prefix:+ return self._generated_runtime_peer_id(prefix, runtime_ids[0])+ return self._sanitize_id(runtime_ids[0])++ if peer_name:+ return self._sanitize_id(peer_name)+ channel, sep, chat_id = key.partition(":")+ return self._sanitize_id(f"user-{channel}-{chat_id}" if sep else f"user-default-{key}")++ def _resolve_peer_id(self, session: HonchoSession, peer: str | None) -> str:+ """Resolve a peer alias ('user'/'ai') or explicit peer ID to a concrete, non-empty peer ID."""+ 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]:+ """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:+ return session.assistant_peer_id, session.assistant_peer_id+ if self._ai_observe_others:+ return session.assistant_peer_id, target_peer_id+ return target_peer_id, Nonediff --git a/plugins/memory/honcho/tool_schemas.py b/plugins/memory/honcho/tool_schemas.pynew file mode 100644index 00000000000..e3780fd8a76--- /dev/null+++ b/plugins/memory/honcho/tool_schemas.py@@ -0,0 +1,180 @@+"""Honcho tool schemas sent to the model — byte-stable (prompt-cache parity).++Profile / search / reasoning / context / conclude, exposed via HonchoMemoryProvider.get_tool_schemas().+"""++_PEER = {+ "type": "string",+ "description": "Peer to query. Built-in aliases: 'user' (default), 'ai'. Or pass any peer ID from this workspace.",+}+++def _tool(name: str, description: str, properties: dict, required: list) -> dict:+ return {+ "name": name,+ "description": description,+ "parameters": {"type": "object", "properties": properties, "required": required},+ }+++PROFILE_SCHEMA = _tool(+ "honcho_profile",+ "Read or write a peer's CARD — a short, curated list of standing facts "+ "about that peer (name, role, preferences, communication style, recurring "+ "patterns). This is the cheapest, fastest Honcho call: no query, no LLM, "+ "just the current card. Pass `card` to overwrite it; omit `card` to read. "+ "An empty read returns a `hint` explaining why (observation disabled, fresh "+ "peer, representation still warming up) — that is NOT an error; the card "+ "accumulates over time from observed conversation. "+ "Related tools: honcho_context for the fuller standing snapshot (card + "+ "representation + summary + recent messages); honcho_search to find "+ "specific things that were actually said; honcho_reasoning for a "+ "synthesized answer to a question.",+ {+ "peer": _PEER,+ "card": {+ "type": "array",+ "items": {"type": "string"},+ "description": "New peer card as a list of fact strings. Omit to read the current card.",+ },+ },+ [],+)++SEARCH_SCHEMA = _tool(+ "honcho_search",+ "Hybrid (semantic + keyword) search over a peer's actual message "+ "history across ALL past sessions they took part in — not just the "+ "current one. Returns RRF-ranked raw message excerpts (what was "+ "literally said, including the assistant's own messages about the "+ "peer), no LLM synthesis. Cheaper and faster than honcho_reasoning. "+ "Use this to recall specific past facts — 'what did I say about X', "+ "'what was the regimen/decision/config we settled on' — and reason "+ "over the excerpts yourself. For nuanced questions needing synthesis, "+ "use honcho_reasoning instead.",+ {+ "query": {+ "type": "string",+ "description": "What to look for — a topic, keyword, name, or natural-language description of the fact you're trying to recall.",+ },+ "max_tokens": {+ "type": "integer",+ "description": "Approximate budget for returned excerpts (default 800, max 2000). Larger budgets return more/longer ranked snippets.",+ },+ "peer": {+ "type": "string",+ "description": "Whose history to search. Built-in aliases: 'user' (default), 'ai'. Or pass any peer ID from this workspace. Spans every session that peer took part in.",+ },+ },+ ["query"],+)++REASONING_SCHEMA = _tool(+ "honcho_reasoning",+ "Ask Honcho's dialectic agent a natural-language question about a peer and "+ "get back a SYNTHESIZED answer. This is the only Honcho tool that runs an "+ "LLM: it agentically searches both raw messages and derived conclusions, "+ "reasons over them, and writes a prose answer — so it is the slowest and "+ "most expensive call (seconds + tokens). Reach for it for nuanced or "+ "open-ended questions ('how does this person prefer to receive feedback?', "+ "'what's their relationship to project X?') where you want Honcho to do the "+ "synthesis. For a specific fact that was stated, prefer honcho_search "+ "(cheap, raw excerpts, you synthesize). For standing profile facts, prefer "+ "honcho_profile / honcho_context (no LLM). "+ "Pass reasoning_level to control depth: minimal (fast/cheap), low (default), "+ "medium, high, max (deep/expensive). Omit for the configured default.",+ {+ "query": {+ "type": "string",+ "description": "A natural language question.",+ },+ "reasoning_level": {+ "type": "string",+ "description": (+ "Override the default reasoning depth. "+ "Omit to use the configured default (typically low).\n"+ "reasoning_level parameter guide:\n"+ "- minimal: use ONLY for a single quick factual lookup (e.g. "+ "'what is the user's name'). Honcho hard-caps this tier's output "+ "at 250 tokens combined with the model's own hidden reasoning "+ "tokens — a multi-part answer can get cut off mid-thought before "+ "it even reaches the final-answer phase, especially on models "+ "with reasoning/thinking enabled.\n"+ "- low/medium/high/max: use for anything requiring a synthesized, "+ "multi-fact, or summary-style answer (e.g. 'summarize known facts "+ "about this peer', 'what are their communication preferences'). "+ "These tiers have no output-token cap of their own (fall back to "+ "Honcho's 8192-token global default), so they don't have "+ "minimal's cutoff failure mode.\n"+ " - low: straightforward questions with clear answers\n"+ " - medium: multi-aspect questions requiring synthesis across observations\n"+ " - high: complex behavioral patterns, contradictions, deep analysis\n"+ " - max: thorough audit-level analysis, leave no stone unturned\n"+ "Default to at least 'low' unless the query is genuinely a single "+ "fact lookup."+ ),+ "enum": ["minimal", "low", "medium", "high", "max"],+ },+ "peer": _PEER,+ },+ ["query"],+)++CONTEXT_SCHEMA = _tool(+ "honcho_context",+ "Retrieve the standing SNAPSHOT Honcho holds for the current session — "+ "session summary, the peer's representation, the peer card, and the most "+ "recent messages — in one call. No query, no LLM synthesis (cheaper than "+ "honcho_reasoning). Use it to orient yourself on what Honcho currently "+ "knows about this conversation and peer. This is a fixed snapshot, not a "+ "search: to look up a specific past fact use honcho_search; to ask a "+ "question and get a synthesized answer use honcho_reasoning; for just the "+ "compact card use honcho_profile.",+ {+ "peer": _PEER,+ },+ [],+)++CONCLUDE_SCHEMA = _tool(+ "honcho_conclude",+ "Write, delete, or list CONCLUSIONS — persistent, derived facts about a peer that "+ "feeds their long-term profile (card + representation). Use this to record "+ "something durable you've learned about the peer (a stable preference, a "+ "correction, a standing constraint) so future sessions carry it forward. "+ "You MUST pass exactly one of `conclusion` (to create), `delete_id` (to "+ "delete), or `list` (to list/search); any other combination is an error. "+ "A deletion ID is an opaque server-generated string: first call with `list=true` "+ "and optionally `query`, then pass the returned ID as `delete_id`. "+ "Deletion exists only for "+ "PII removal — for merely wrong facts, write a corrected conclusion instead; "+ "Honcho self-heals contradictions over time. This is a WRITE tool: to read "+ "the profile use honcho_profile / honcho_context, and to search what was "+ "said use honcho_search.",+ {+ "conclusion": {+ "type": "string",+ "description": "A factual statement to persist. Provide this when creating a conclusion. Do not send it together with delete_id or list.",+ },+ "delete_id": {+ "type": "string",+ "description": "Conclusion ID to delete for PII removal. Provide this when deleting a conclusion. Do not send it together with conclusion or list. Get this id from a prior `list` call — never guess it.",+ },+ "list": {+ "type": "boolean",+ "description": "Set to true to list or search stored conclusions (with their ids) instead of creating or deleting one. Do not send together with conclusion or delete_id.",+ },+ "query": {+ "type": "string",+ "description": "Optional semantic search query, used only when `list` is true. Omit to list the most recent conclusions instead of searching.",+ },+ "peer": {+ "type": "string",+ "description": "The peer the conclusion is ABOUT. Built-in aliases: 'user' (default), 'ai'. Or pass any peer ID from this workspace.",+ },+ },+ [],+)+++ALL_TOOL_SCHEMAS = [PROFILE_SCHEMA, SEARCH_SCHEMA, REASONING_SCHEMA, CONTEXT_SCHEMA, CONCLUDE_SCHEMA]diff --git a/tests/honcho_plugin/test_client.py b/tests/honcho_plugin/test_client.pyindex 630a5bf5cd1..6a4361dd34c 100644--- a/tests/honcho_plugin/test_client.py+++ b/tests/honcho_plugin/test_client.py@@ -637,20 +637,6 @@ class TestResolveSessionNameLengthLimit:assert len(result_b) == self.HONCHO_MAX-class TestResetHonchoClient:- def test_reset_clears_singleton(self):- import plugins.memory.honcho.client as mod-- # Seed the cached client through the slot's public surface, then- # verify reset_honcho_client() clears it. (The client is cached in- # mod._honcho_client_slot, a thread-safe SingletonSlot, not a bare- # module global anymore — see #24759.)- mod._honcho_client_slot.get(lambda: MagicMock())- assert mod._honcho_client_slot.peek() is not None- reset_honcho_client()- assert mod._honcho_client_slot.peek() is None--class TestDialecticDepthParsing:"""Tests for _parse_dialectic_depth and _parse_dialectic_depth_levels."""diff --git a/tests/honcho_plugin/test_session.py b/tests/honcho_plugin/test_session.pyindex 6583fdc800b..66f87abf1d3 100644--- a/tests/honcho_plugin/test_session.py+++ b/tests/honcho_plugin/test_session.py@@ -43,24 +43,6 @@ class TestHonchoSession:assert "timestamp" in session.messages[0]- def test_get_history(self):- session = self._make_session()- session.add_message("user", "msg1")- session.add_message("assistant", "msg2")- history = session.get_history()- assert len(history) == 2- assert history[0] == {"role": "user", "content": "msg1"}- assert history[1] == {"role": "assistant", "content": "msg2"}--- def test_clear(self):- session = self._make_session()- session.add_message("user", "msg1")- session.add_message("user", "msg2")- session.clear()- assert session.messages == []--# ---------------------------------------------------------------------------# HonchoSessionManager._sanitize_id# ---------------------------------------------------------------------------@@ -80,59 +62,6 @@ class TestSanitizeId:assert "!" not in result-# ----------------------------------------------------------------------------# HonchoSessionManager._format_migration_transcript-# ------------------------------------------------------------------------------class TestFormatMigrationTranscript:- def test_basic_transcript(self):- messages = [- {"role": "user", "content": "Hello", "timestamp": "2026-01-01T00:00:00"},- {"role": "assistant", "content": "Hi!", "timestamp": "2026-01-01T00:01:00"},- ]- result = HonchoSessionManager._format_migration_transcript("telegram:123", messages)- assert isinstance(result, bytes)- text = result.decode("utf-8")- assert "<prior_conversation_history>" in text- assert "user: Hello" in text- assert "assistant: Hi!" in text- assert 'session_key="telegram:123"' in text- assert 'message_count="2"' in text---# ----------------------------------------------------------------------------# HonchoSessionManager.delete / list_sessions-# ------------------------------------------------------------------------------class TestManagerCacheOps:- def test_delete_cached_session(self):- mgr = HonchoSessionManager()- session = HonchoSession(- key="test", user_peer_id="u", assistant_peer_id="a",- honcho_session_id="s",- )- mgr._cache["test"] = session- assert mgr.delete("test") is True- assert "test" not in mgr._cache--- def test_list_sessions(self):- mgr = HonchoSessionManager()- s1 = HonchoSession(key="k1", user_peer_id="u", assistant_peer_id="a", honcho_session_id="s1")- s2 = HonchoSession(key="k2", user_peer_id="u", assistant_peer_id="a", honcho_session_id="s2")- s1.add_message("user", "hi")- mgr._cache["k1"] = s1- mgr._cache["k2"] = s2- sessions = mgr.list_sessions()- assert len(sessions) == 2- keys = {s["key"] for s in sessions}- assert keys == {"k1", "k2"}- s1_info = next(s for s in sessions if s["key"] == "k1")- assert s1_info["message_count"] == 1--class TestPeerLookupHelpers:def _make_cached_manager(self):mgr = HonchoSessionManager()@@ -1033,16 +962,6 @@ class TestDialecticLiveness:assert p._effective_cadence() == 4- def test_liveness_snapshot_shape(self):- p = self._make_provider()- snap = p.liveness_snapshot()- for key in (- "turn_count", "last_dialectic_turn", "pending_result_fired_at",- "empty_streak", "effective_cadence", "thread_alive", "thread_age_seconds",- ):- assert key in snap--class TestDialecticLifecycleSmoke:"""End-to-end smoke walking a multi-turn session through prewarm,turn 1 consume, trivial skip, cadence fire, empty-result retry,