The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): deliver Kanban wakes, heartbeats and cron results into local chats
unsupportedpastels65cac9a4c8e8
diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.pyindex 80f5d029f18..b3711eb21b2 100644--- a/cron/scheduler_delivery.py+++ b/cron/scheduler_delivery.py@@ -1892,6 +1892,14 @@ def _deliver_result(if receipt and receipt["status"] == "ambiguous":unverified_targets.append(bot_chat_error)continue+ if target["platform"] == "local":+ from gateway.session_cron import deliver_to_local_chat+ from hermes_constants import get_hermes_home+ local_error = deliver_to_local_chat(get_hermes_home(), target["chat_id"],+ bot_chat_message(job, content), diagnostic=for_failure)+ if local_error:+ delivery_errors.append(local_error)+ continuet = _prepare_target_delivery(job, target, adapters=adapters, loop=loop, config=config,diff --git a/gateway/run_goals.py b/gateway/run_goals.pyindex 99271d77018..18b42c4a437 100644--- a/gateway/run_goals.py+++ b/gateway/run_goals.py@@ -146,7 +146,9 @@ class GatewayGoalsMixin:session_id = currentwatch[quick_key] = (source, session_id)adapter = self._delivery_adapter_for(source)- if adapter is None or not adapter._message_handler:+ from gateway.session_local import LocalSessionAdapter+ # A local chat has no message handler: its owner admits the tick (``admit_heartbeat``).+ if adapter is None or not (adapter._message_handler or isinstance(adapter, LocalSessionAdapter)):returnif getattr(self, 'session_authority', None) is not None:from gateway.run_heartbeat_acceptance import admit_heartbeatdiff --git a/gateway/session_cron.py b/gateway/session_cron.pyindex ae9d16f5f1a..be61f4446ac 100644--- a/gateway/session_cron.py+++ b/gateway/session_cron.py@@ -38,6 +38,35 @@ def owner_for_home(home):return None+async def _admit_local_delivery(authority, chat_id, text, metadata):+ from gateway.config import Platform+ from gateway.session_authorities import owner_scope+ from gateway.session_automation import admit_route_wake+ from gateway.session_local_recovery import local_adapter_map, restore_local_session+ with owner_scope(authority):+ restore_local_session(authority, chat_id) # a chat closed before this fire, as for completions+ source = authority.sessions[chat_id].source+ return await admit_route_wake(authority.runner, local_adapter_map(authority)[Platform.LOCAL], source,+ text, 'cron', metadata)+++def deliver_to_local_chat(home, chat_id, text, *, diagnostic=False):+ """Admit a cron result into local chat *chat_id*'s FIFO, as a Kanban wake. A local chat has no+ push transport (``LocalSessionAdapter.send`` only acknowledges a turn's own output), so only the+ owner in this process can deliver. Called off the owner loop; None once admitted, else the error."""+ owner = owner_for_home(home)+ if owner is None:+ return f"local chat {chat_id}: no gateway in this process owns its session"+ authority, loop = owner+ metadata = {'notification_category': 'diagnostic'} if diagnostic else {}+ try:+ admitted = asyncio.run_coroutine_threadsafe(+ _admit_local_delivery(authority, chat_id, text, metadata), loop).result(timeout=60)+ except (RuntimeStoreError, KeyError, TimeoutError) as exc: # unknown chat, refused admission, stalled owner+ return f"local chat {chat_id}: delivery not confirmed: {exc!r}"+ return None if admitted else f"local chat {chat_id}: delivery refused: the chat has no committed route"++def current_execution():return _execution.get()diff --git a/gateway/session_local.py b/gateway/session_local.pyindex ca5cd0f2f54..0a2ec7cdf79 100644--- a/gateway/session_local.py+++ b/gateway/session_local.py@@ -24,6 +24,9 @@ class LocalSessionAdapter(BasePlatformAdapter):def __init__(self, authority):super().__init__(PlatformConfig(enabled=True), Platform.LOCAL)self.authority = authority+ # Built outside ``_create_adapter``: without its runner a push wake skips the authority FIFO+ # and falls to a message handler this adapter never has (``deliver_wake``).+ self.gateway_runner = getattr(authority, 'runner', None)self.sources = {}self.policies = {}diff --git a/tests/gateway/test_local_chat_delivery.py b/tests/gateway/test_local_chat_delivery.pynew file mode 100644index 00000000000..4d84cdad3ca--- /dev/null+++ b/tests/gateway/test_local_chat_delivery.py@@ -0,0 +1,73 @@+"""Producers that target a local (Desktop/TUI/CLI) chat reach its owner's FIFO (#143547 KB-22, RT-90, CRON-11).++``LocalSessionAdapter`` has no message handler and its ``send()`` only acknowledges (a turn's output+rides the event stream), so a Kanban wake, a due heartbeat or a cron result that took the messaging+adapter path was refused or silently dropped.+"""+import asyncio+import time++import pytest++from tests.gateway.test_session_end_delegations import _local+++def _admissions(authority, ref, needle):+ from hermes_state_runtime import list_session_admissions+ rows = list_session_admissions(authority.db, session_id=ref.session_id, pending_only=False)+ return [row for row in rows if needle in str(row['payload'])]+++async def test_kanban_wake_is_admitted_into_a_local_chat(tmp_path, monkeypatch):+ from gateway.wake import deliver_wake+ runner, authority, ref, _ = await _local(tmp_path, monkeypatch)+ live = authority.sessions[ref.session_id]+ adapter = runner._delivery_adapter_for(live.source)+ await deliver_wake(adapter, text='card t1 done', session_id=ref.session_id, source=live.source)+ assert len(_admissions(authority, ref, 'card t1 done')) == 1+++async def test_due_heartbeat_is_admitted_into_a_local_chat(tmp_path, monkeypatch):+ from gateway.run_heartbeat_restore import restore_heartbeat_watches+ from hermes_cli.heartbeat import HeartbeatManager, load_heartbeat, save_heartbeat+ runner, authority, ref, _ = await _local(tmp_path, monkeypatch)+ HeartbeatManager(ref.session_id).set('status tick', 60)+ state = load_heartbeat(ref.session_id)+ state.created_at = time.time() - 120 # one interval overdue+ save_heartbeat(ref.session_id, state)+ await restore_heartbeat_watches(runner)+ await runner._heartbeat_poll_once(runner._heartbeat_watch)+ from hermes_state_runtime import list_session_admissions+ rows = list_session_admissions(authority.db, session_id=ref.session_id, pending_only=False)+ assert [row for row in rows if row['payload'].get('local_automation_v1', {}).get('heartbeat')]++[email protected]('live_adapters', [False, True], ids=['no-local-adapter-yet', 'in-gateway-ticker'])+async def test_cron_result_for_a_local_origin_is_admitted_not_acknowledged(tmp_path, monkeypatch, live_adapters):+ from cron import scheduler_delivery as sd+ runner, authority, ref, _ = await _local(tmp_path, monkeypatch)+ job = {'id': 'j1', 'name': 'digest', 'deliver': 'origin',+ 'origin': {'platform': 'local', 'chat_id': ref.session_id}}+ # The ticker delivers from its own thread; the owner admits on its loop.+ error = await asyncio.to_thread(sd._deliver_result, job, 'CRON_RESULT_j1',+ adapters=runner.adapters if live_adapters else None,+ loop=asyncio.get_running_loop())+ assert error is None+ assert len(_admissions(authority, ref, 'CRON_RESULT_j1')) == 1+++async def test_cron_result_for_a_local_origin_without_its_owner_is_an_error(tmp_path, monkeypatch):+ from cron import scheduler_delivery as sd+ from gateway.session_cron import unbind_owner+ runner, authority, ref, _ = await _local(tmp_path, monkeypatch)+ unbind_owner(authority) # a standalone `hermes cron run`: no gateway in this process+ job = {'id': 'j1', 'name': 'digest', 'deliver': 'origin',+ 'origin': {'platform': 'local', 'chat_id': ref.session_id}}+ error = await asyncio.to_thread(sd._deliver_result, job, 'CRON_RESULT_j1', adapters=runner.adapters,+ loop=asyncio.get_running_loop())+ assert error and 'local' in error+ assert not _admissions(authority, ref, 'CRON_RESULT_j1')