The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: send local Bot DMs to the discovered canonical authority
Teknium47ba694e291d
diff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex 97065cd8aff..d95179b8161 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -68,7 +68,7 @@ async def _record_reply(authority, home, key, future):async def deliver(connection, params):authority, actor = connection.authority, connection.actorhome = _home(authority, actor, params.get('profile'))- if set(params) - {'id', 'profile', 'message'}:+ if set(params) - {'id', 'profile', 'message', 'session_id'}:raise RuntimeStoreError('invalid_params')try:key = _delivery_id(params.get('id'))@@ -89,6 +89,8 @@ async def deliver(connection, params):if record is not None:raise RuntimeStoreError('unknown_execution')ref, live, entry = _target(authority, actor)+ if params.get('session_id', entry.session_id) != entry.session_id:+ raise RuntimeStoreError('admission_conflict')event = MessageEvent(text=message, source=live.source, internal=True,message_id='bot:' + key, metadata={'gateway_session_key': live.route,'gateway_session_id': entry.session_id})diff --git a/tests/gateway/fixtures/bot_authority_peer.py b/tests/gateway/fixtures/bot_authority_peer.pyindex ecf8e1b96f6..940e8502ada 100644--- a/tests/gateway/fixtures/bot_authority_peer.py+++ b/tests/gateway/fixtures/bot_authority_peer.py@@ -49,6 +49,13 @@ def probe(base):await wait(lambda: rows()[0]['status'] == 'terminal')await rpc(ws, 'prompt.submit', session_id=sid, input_id='hold', text='HOLD_AUTOMATION')assert await asyncio.to_thread(model.blocked.wait, 20)+ from tools.bot_mode_dm import _admit_live_dm+ dm = home / 'local-dm.txt'+ dm.write_text('[Message from @local-sender] LOCAL_DM_ONCE')+ local = await asyncio.to_thread(_admit_live_dm, home, str(dm))+ assert local is not None and local['status'] == 'queued', local+ same = await asyncio.to_thread(_admit_live_dm, home, str(dm))+ assert same['admission_id'] == local['admission_id'], sameparams = {'id': 'a' * 32, 'profile': 'default', 'message': '[Message from @sender] BOT_DM_ONCE'}wrong = await rpc(ws, 'bot_relay.deliver', **{**params, 'profile': 'wrong-profile'})assert wrong['error']['message'] == 'profile_mismatch', wrongdiff --git a/tools/bot_live_delivery.py b/tools/bot_live_delivery.pyindex 7a195377900..0012ddc8c2c 100644--- a/tools/bot_live_delivery.py+++ b/tools/bot_live_delivery.py@@ -25,33 +25,52 @@ _TERMINAL = frozenset({"settled", "failed", "cancelled", "ambiguous"})def find_canonical_live_owner(profile_home: Path | str) -> dict[str, Any] | None:- """Resolve exact Bot Chat's compression tip without creating/migrating its DB.-- Capability advertisement is mandatory; old Desktop/TUI processes must not- receive work they cannot consume. Registry errors propagate, failing closed.- """- from hermes_cli.active_sessions import active_session_registry_snapshot+ """Discover the profile authority and exact Bot Chat without acquiring a lease."""+ from hermes_cli.gateway_runtime import discover_gateway_endpointfrom hermes_state import SessionDBhome = Path(profile_home).resolve()- if not (home / "state.db").is_file():+ discovery = discover_gateway_endpoint(home, timeout=5)+ if discovery.state != 'ready' or discovery.endpoint is None:+ raise ValueError('profile authority is not ready')+ if not (home / 'state.db').is_file():return None- db = SessionDB(db_path=home / "state.db", read_only=True)+ db = SessionDB(db_path=home / 'state.db', read_only=True)try:- row = db.get_session_by_title("Bot Chat")- session_id = db.get_compression_tip(row["id"]) if row else None+ row = db.get_session_by_title('Bot Chat')+ tip = db.get_compression_tip(row['id']) if row else Nonefinally:db.close()- if not session_id:+ if not tip:return None- for entry in active_session_registry_snapshot(registry_home=home):- meta = entry.get("metadata") or {}- if (entry["session_id"] == session_id- and meta.get("bot_live_delivery_consumer") is True- and meta.get("live_session_id")):- return dict(profile_home=str(home), session_id=session_id,- lease_id=entry["lease_id"], live_session_id=meta["live_session_id"])- return None+ return dict(profile_home=str(home), session_id=tip, canonical=True,+ lease_id=discovery.endpoint.instance_id, live_session_id=tip)+++def authority_delivery(home, params):+ """Call only this home's already-running authority; never start a fallback."""+ import asyncio+ from hermes_cli.gateway_runtime import discover_gateway_endpoint+ from hermes_cli.gateway_client import GatewayClient, _session_ticket+ from websockets.asyncio.client import connect++ home = Path(home).resolve()++ async def request():+ discovery = await asyncio.to_thread(discover_gateway_endpoint, home, timeout=5)+ if discovery.state != 'ready' or discovery.endpoint is None:+ raise ValueError('profile authority is not ready')+ endpoint = discovery.endpoint+ ticket = await asyncio.to_thread(_session_ticket, home, endpoint)+ url = endpoint.api_origin.replace('http:', 'ws:').replace('https:', 'wss:') + '/api/ws'+ async with connect(url, subprotocols=['hermes-gateway-v1', 'hermes-gateway-ticket.' + ticket],+ open_timeout=10) as ws:+ if ws.subprotocol != 'hermes-gateway-v1':+ raise ValueError('authority protocol mismatch')+ async with GatewayClient(ws) as client:+ return await client.rpc('bot_relay.deliver', **params)++ return asyncio.run(request())def _owner(home: Path | str, owner: dict[str, Any]) -> dict[str, str]:@@ -129,6 +148,11 @@ def deliver_to_live_owner(state. Reusing an id with a different payload is an error, never an overwrite."""pinned = _owner(profile_home, owner)+ if owner.get("canonical"):+ home = Path(profile_home).resolve()+ return authority_delivery(home, dict(id=_delivery_id(delivery_id or uuid.uuid4().hex),+ profile=home.name if home.parent.name == "profiles" else "default",+ message=message, session_id=pinned["session_id"]))if not isinstance(message, str):raise ValueError("message must be a string")key = _delivery_id(delivery_id if delivery_id is not None else uuid.uuid4().hex)@@ -220,4 +244,9 @@ def complete_delivery(def read_delivery_result(profile_home: Path | str, delivery_id: str) -> dict[str, Any] | None:"""Read admission/claim/terminal state without waiting or deleting its receipt."""- return _read(_root(profile_home) / f"{_delivery_id(delivery_id)}.json")+ record = _read(_root(profile_home) / f"{_delivery_id(delivery_id)}.json")+ if record is not None and record.get('admission_id'):+ home = Path(profile_home).resolve()+ return authority_delivery(home, dict(id=delivery_id,+ profile=home.name if home.parent.name == 'profiles' else 'default', message=record['message']))+ return recorddiff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.pyindex db3587acf59..f252deaf08b 100644--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@ -413,7 +413,7 @@ def _admit_live_dm(profile_home: Path | None, dm_file: str) -> dict | None:assert profile_home is not Noneowner = find_canonical_live_owner(profile_home)if owner is None:- return None+ raise ValueError("canonical Bot Chat target is unavailable; no local fallback")intent = dict(owner=owner, message=Path(dm_file).read_text(encoding="utf-8"),delivery_id=hashlib.sha256(str(Path(dm_file).resolve()).encode()).hexdigest())try:@@ -428,7 +428,7 @@ def _admit_live_dm(profile_home: Path | None, dm_file: str) -> dict | None:_fsync_dir(intent_path.parent)home = intent["owner"]["profile_home"]record = read_delivery_result(home, intent["delivery_id"])- if record is None:+ if record is None or intent["owner"].get("canonical"):record = deliver_to_live_owner(home, intent["owner"], intent["message"],delivery_id=intent["delivery_id"])return record