Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions agent/agent_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ def init_agent(
prefill_messages: List[Dict[str, Any]] = None,
platform: str = None,
user_id: str = None,
user_id_alt: str = None,
user_name: str = None,
chat_id: str = None,
chat_name: str = None,
Expand Down Expand Up @@ -265,6 +266,7 @@ def init_agent(
agent.ephemeral_system_prompt = ephemeral_system_prompt
agent.platform = platform # "cli", "telegram", "discord", "whatsapp", etc.
agent._user_id = user_id # Platform user identifier (gateway sessions)
agent._user_id_alt = user_id_alt # Optional stable alternate platform identifier
agent._user_name = user_name
agent._chat_id = chat_id
agent._chat_name = chat_name
Expand Down Expand Up @@ -1089,6 +1091,8 @@ def init_agent(
# Thread gateway user identity for per-user memory scoping
if agent._user_id:
_init_kwargs["user_id"] = agent._user_id
if agent._user_id_alt:
_init_kwargs["user_id_alt"] = agent._user_id_alt
if agent._user_name:
_init_kwargs["user_name"] = agent._user_name
if agent._chat_id:
Expand Down
1 change: 1 addition & 0 deletions agent/memory_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ def initialize(self, session_id: str, **kwargs) -> None:
- agent_workspace (str): Shared workspace name (e.g. "hermes").
- parent_session_id (str): For subagents, the parent's session_id.
- user_id (str): Platform user identifier (gateway sessions).
- user_id_alt (str): Optional alternate stable platform user identifier.
"""

def system_prompt_block(self) -> str:
Expand Down
45 changes: 45 additions & 0 deletions gateway/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -11436,6 +11436,7 @@ def run_sync():
session_id=task_id,
platform=platform_key,
user_id=source.user_id,
user_id_alt=source.user_id_alt,
user_name=source.user_name,
chat_id=source.chat_id,
chat_name=source.chat_name,
Expand Down Expand Up @@ -14672,6 +14673,29 @@ def _extract_cache_busting_config(cls, user_config: dict | None) -> dict:
out["tools.registry_generation"] = getattr(registry, "_generation", None)
except Exception:
out["tools.registry_generation"] = None

# Honcho identity-mapping keys live in honcho.json, not user_config.
# HonchoSessionManager freezes the resolved peer_name / ai_peer /
# pin / aliases / prefix at construction; without busting here,
# mid-flight honcho.json edits go unread until the next unrelated
# cache eviction.
try:
from plugins.memory.honcho.client import HonchoClientConfig

hcfg = HonchoClientConfig.from_global_config()
out["honcho.peer_name"] = hcfg.peer_name
out["honcho.ai_peer"] = hcfg.ai_peer
out["honcho.pin_peer_name"] = bool(hcfg.pin_peer_name)
out["honcho.runtime_peer_prefix"] = hcfg.runtime_peer_prefix or ""
aliases = hcfg.user_peer_aliases or {}
out["honcho.user_peer_aliases"] = sorted(aliases.items()) if isinstance(aliases, dict) else []
except Exception:
out["honcho.peer_name"] = None
out["honcho.ai_peer"] = None
out["honcho.pin_peer_name"] = None
out["honcho.runtime_peer_prefix"] = None
out["honcho.user_peer_aliases"] = None

return out

@staticmethod
Expand All @@ -14681,6 +14705,8 @@ def _agent_config_signature(
enabled_toolsets: list,
ephemeral_prompt: str,
cache_keys: dict | None = None,
user_id: str | None = None,
user_id_alt: str | None = None,
) -> str:
"""Compute a stable string key from agent config values.

Expand All @@ -14694,6 +14720,20 @@ def _agent_config_signature(
the output of ``_extract_cache_busting_config(user_config)`` so
edits to model.context_length / compression.* in config.yaml are
picked up on the next gateway message without a manual restart.

``user_id`` and ``user_id_alt`` are the runtime user identities
carried by the current message's gateway source. They participate
in the cache key because the Honcho memory provider freezes them
into ``HonchoSessionManager`` at first-message init (see
``plugins/memory/honcho/__init__.py::_do_session_init``). Without
them in the signature, a shared-thread session_key (one in which
``build_session_key`` intentionally omits the participant ID,
e.g. ``thread_sessions_per_user=False``) would reuse the cached
AIAgent across distinct users, causing the second user's messages
to be attributed to the first user's resolved Honcho peer. This
broke #27371's per-user-peer contract in multi-user gateways.
Per-user agent rebuilds in shared threads trade prompt-cache
warmth for correct memory attribution.
"""
import hashlib, json as _j

Expand All @@ -14718,6 +14758,8 @@ def _agent_config_signature(
# cached agent and doesn't affect system prompt or tools.
ephemeral_prompt or "",
_cache_keys_sorted,
str(user_id or ""),
str(user_id_alt or ""),
],
sort_keys=True,
default=str,
Expand Down Expand Up @@ -16259,6 +16301,8 @@ def _interim_assistant_cb(text: str, *, already_streamed: bool = False) -> None:
enabled_toolsets,
combined_ephemeral,
cache_keys=self._extract_cache_busting_config(user_config),
user_id=getattr(source, "user_id", None),
user_id_alt=getattr(source, "user_id_alt", None),
)
agent = None
_cache_lock = getattr(self, "_agent_cache_lock", None)
Expand Down Expand Up @@ -16302,6 +16346,7 @@ def _interim_assistant_cb(text: str, *, already_streamed: bool = False) -> None:
session_id=session_id,
platform=platform_key,
user_id=source.user_id,
user_id_alt=source.user_id_alt,
user_name=source.user_name,
chat_id=source.chat_id,
chat_name=source.chat_name,
Expand Down
35 changes: 35 additions & 0 deletions plugins/memory/honcho/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,41 @@ For every key, resolution order is: **host block > root > env var > default**.
| `peerName` | string | — | User peer identity |
| `aiPeer` | string | host key | AI peer identity |

### Identity Mapping (Gateway Multi-User)

In gateway deployments (Telegram, Discord, Slack, etc.) each user arrives with a platform-native runtime ID (Telegram UID, Discord snowflake, Slack user). These three keys control how those runtime IDs map to Honcho peers. The resolver is config-driven and deterministic — no automatic merging or runtime inference.

| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `pinUserPeer` | bool | `false` | When `true`, every gateway runtime user collapses to `peerName`. Single-operator deployments where you want all your platforms (and any other users) to share one peer. Also accepted as `pinPeerName` |
| `pinPeerName` | bool | `false` | Alias for `pinUserPeer`; same effect |
| `userPeerAliases` | object | `{}` | Map of runtime IDs to peer IDs (`{"86701400": "eri"}`). Many-to-one is the intended pattern — alias all your runtime IDs to one peer name. One-to-many is not supported; one runtime ID resolves to exactly one peer |
| `runtimePeerPrefix` | string | `""` | Prepended to unknown runtime IDs to namespace them (e.g. `"telegram_"` → `telegram_86701400`). Used only when no alias matches. Prevents collisions between platforms whose runtime IDs share the same shape |

**Resolver ladder** (first match wins):

```
1. pinUserPeer / pinPeerName=true → return peerName (ignore runtime ID)
2. userPeerAliases[runtime_id] → return aliased peer
3. userPeerAliases[runtime_id_alt] → check alt-ID too (Telegram UID + username, etc.)
4. runtimePeerPrefix + runtime_id → namespaced peer, with sha256 collision escalation
5. raw sanitized runtime_id → fallback peer
6. peerName → no runtime ID at all (CLI/TUI)
7. session-key fallback → no config either
```

**Why no `pinAiPeer`?** The AI peer is already pinned by construction — `aiPeer` is the only AI-side identity setting and the resolver never overrides it. Only the user-side peer has the runtime-vs-config tension that `pinUserPeer` resolves.

**Host vs root semantics.** All three keys are accepted at both root and `hosts.<host>` levels. Host-level wins. For maps and prefixes, host-level *replaces* the root value as a whole (not merge), so a host can intentionally own its identity universe or wipe it with `userPeerAliases: {}` / `runtimePeerPrefix: ""`.

**Deployment shapes** (`hermes honcho setup` asks one prompt to set these):

- **Single-operator** — `pinUserPeer: true`. All gateway users → `peerName`. Recommended for personal use where you connect Hermes to your own Telegram/Discord/etc.
- **Multi-user gateway** — `pinUserPeer: false`, optional `runtimePeerPrefix`. Each runtime user → own peer. Recommended for bots serving many humans.
- **Hybrid** — `pinUserPeer: false`, `userPeerAliases` mapping the operator's runtime IDs to `peerName`. Multi-user gateway where YOU are routed but others stay distinct.

**Migrating single → multi.** Flipping `pinUserPeer` from `true` to `false` does not migrate data. Memory accumulated under `peerName` while pinned stays there; runtime users now resolve to fresh, empty peers. To preserve your own continuity, use the **hybrid** shape — alias your runtime IDs back to `peerName` so your turns keep landing on the pooled history while other users get their own peers. The setup wizard offers this path automatically when it detects a single → multi transition.

### Memory & Recall

| Key | Type | Default | Description |
Expand Down
7 changes: 3 additions & 4 deletions plugins/memory/honcho/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -321,10 +321,8 @@ def initialize(self, session_id: str, **kwargs) -> None:
except Exception as e:
logger.debug("Honcho cost-awareness config parse error: %s", e)

# ----- Port #1969: aiPeer sync from SOUL.md — REMOVED -----
# SOUL.md is persona content, not identity config. aiPeer should
# only come from honcho.json (host block or root) or the default.
# See scratch/memory-plugin-ux-specs.md #10 for rationale.
# aiPeer comes from honcho.json (host block or root) only.
# SOUL.md is persona content, not identity config.

# ----- Port #1957: lazy session init for tools-only mode -----
if self._recall_mode == "tools":
Expand Down Expand Up @@ -360,6 +358,7 @@ def _do_session_init(self, cfg, session_id: str, **kwargs) -> None:
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,
)

# ----- B3: resolve_session_name -----
Expand Down
Loading
Loading