The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webhook): make delivery mirroring opt-in and profile-scoped
teknium18eda97cafb92
diff --git a/gateway/platforms/webhook.py b/gateway/platforms/webhook.pyindex d9590ffd53d..a10bcbfb602 100644--- a/gateway/platforms/webhook.py+++ b/gateway/platforms/webhook.py@@ -4,7 +4,7 @@ or any gateway platform). Routes live under platforms.webhook.extra.routes: evensecret (REQUIRED; "INSECURE_NO_AUTH" skips validation, loopback only), prompt template, skills,deliver/deliver_extra, deliver_only (rendered prompt IS the message), cron_job (fire an existing cronjob per event; the rendered prompt is transient per-run context; exclusive with deliver_only), mirror_to_session-(default on: a delivered response is also written into the target chat's transcript so follow-ups there have+(opt-in: a delivered response is also written into the target chat's transcript so follow-ups there havecontext). Per-route rate limiting,idempotency cache, body-size caps checked before reading. Generic HMAC V2 binds a timestamp forreplay protection; body-only V1 is deprecated but accepted with a warning."""@@ -485,7 +485,7 @@ class WebhookAdapter(BasePlatformAdapter):delivery = {"deliver": route_config.get("deliver", "log"), "payload": payload, "profile": profile,"deliver_extra": self._render_delivery_extra(route_config.get("deliver_extra", {}), payload),"route": route_name,- "mirror": route_config.get("mirror_to_session", True) is not False}+ "mirror": route_config.get("mirror_to_session") is True}logger.info("[webhook] direct-deliver event=%s route=%s target=%s msg_len=%d delivery=%s", event_type,route_name, delivery["deliver"], len(prompt), delivery_id)failed = {"status": "error", "error": "Delivery failed", "delivery_id": delivery_id}@@ -656,7 +656,7 @@ class WebhookAdapter(BasePlatformAdapter):"deliver": route_config.get("deliver", "log"), "profile": profile,"deliver_extra": self._render_delivery_extra(route_config.get("deliver_extra", {}), payload),"route": route_name,- "mirror": route_config.get("mirror_to_session", True) is not False}+ "mirror": route_config.get("mirror_to_session") is True}self._delivery_info_created[session_chat_id] = nowself._delivery_info_order.append((now, session_chat_id))self._prune_delivery_info(now)@@ -899,9 +899,13 @@ class WebhookAdapter(BasePlatformAdapter):agent has no idea it sent anything. Same path and USER-role convention as cron briefs(``cron.scheduler_delivery._maybe_mirror_cron_delivery``, #2221): the text is not the targetsession's agent speaking, and a labelled user turn merges safely on strict-alternation providers.- Route opt-out: ``mirror_to_session: false``. Never raises — a delivered message must not be- reported failed because the mirror broke."""- if not delivery.get("mirror", True):+ Opt-in per route (``mirror_to_session: true``), default off like cron's ``mirror_delivery``: the text+ lands with user authority in a chat the route author may not own, and on ``deliver_only`` routes it is+ the raw rendered payload. Called inside the routed profile's scope so the lookup hits THAT profile's+ state.db — a DM chat_id is the user's id on every bot, so an unscoped mirror lands in another+ profile's DM with the same person. Never raises — a delivered message must not be reported failed+ because the mirror broke."""+ if delivery.get("mirror") is not True:returnroute = delivery.get("route") or "webhook"try:diff --git a/hermes_cli/subcommands/webhook.py b/hermes_cli/subcommands/webhook.pyindex 625fb691112..7870a22dfab 100644--- a/hermes_cli/subcommands/webhook.py+++ b/hermes_cli/subcommands/webhook.py@@ -37,6 +37,10 @@ def build_webhook_parser(subparsers, *, cmd_webhook: Callable) -> None:help="Skip the agent — deliver the rendered prompt directly as the ""message. Zero LLM cost. Requires --deliver to be a real target ""(not 'log').")+ wh_sub.add_argument(+ "--mirror-to-session", action="store_true",+ help="Also write each delivered message into the target chat's session, so replying to it "+ "in that chat has context. Only for sources whose content you trust in your conversation.")wh_sub.add_argument("--script", default="",help="Filter/transform script under ~/.hermes/scripts/. The route "diff --git a/hermes_cli/webhook.py b/hermes_cli/webhook.pyindex 2a8458f95f9..de280053768 100644--- a/hermes_cli/webhook.py+++ b/hermes_cli/webhook.py@@ -160,6 +160,8 @@ def _cmd_subscribe(args):"(telegram, discord, slack, github_comment, etc.) — not 'log'.")returnroute["deliver_only"] = True+ if getattr(args, "mirror_to_session", False):+ route["mirror_to_session"] = Truecron_job = (getattr(args, "cron_job", "") or "").strip()if cron_job:# Validate the reference up-front so a typo surfaces here, not on the first inbound event.@@ -189,6 +191,8 @@ def _cmd_subscribe(args):print(f" Deliver: {route['deliver']}")if route.get("deliver_only"):print(" Mode: direct delivery (no agent, zero LLM cost)")+ if route.get("mirror_to_session"):+ print(" Replies: each delivery is mirrored into the target chat's session")if route.get("cron_job"):print(f" Mode: cron-job trigger — fires job '{route['cron_job']}' on each event")if route.get("prompt"):diff --git a/skills/autonomous-ai-agents/hermes-agent/references/webhooks.md b/skills/autonomous-ai-agents/hermes-agent/references/webhooks.mdindex bd52ea68f22..78b0d12c4b7 100644--- a/skills/autonomous-ai-agents/hermes-agent/references/webhooks.md+++ b/skills/autonomous-ai-agents/hermes-agent/references/webhooks.md@@ -186,6 +186,10 @@ The POST returns `200 OK` on successful delivery, `502` on target failure — soRequires `--deliver` to be a real target (telegram, discord, slack, github_comment, etc.) — `--deliver log` is rejected because log-only direct delivery is pointless.+### Let the user reply to a delivery++Each event runs in its own session, so by default the agent in the target chat has no record of what a route delivered ("what are you referring to?"). Add `--mirror-to-session` and each delivered message is also written into that chat's session as `[Webhook delivery: <route>]` + the text. Off by default: the text enters the conversation as if the user had sent it (on `--deliver-only` routes it is the raw payload), so only use it for sources the user trusts. Skipped when the chat has no session yet.+## Security- Each subscription gets an auto-generated HMAC-SHA256 secret (or provide your own with `--secret`)diff --git a/tests/gateway/test_webhook_adapter.py b/tests/gateway/test_webhook_adapter.pyindex 18b61dcb237..73786d24eb3 100644--- a/tests/gateway/test_webhook_adapter.py+++ b/tests/gateway/test_webhook_adapter.py@@ -820,82 +820,86 @@ class TestDeliverCrossPlatformThreadId:class TestCrossPlatformDeliveryMirror:- """A delivered response is mirrored into the TARGET chat's session so a follow-up reply there has- context (the text otherwise only lives in the ephemeral webhook:<route>:<id> session)."""+ """An opted-in route's delivered response is appended to the TARGET chat's session (real state.db),+ so a follow-up reply there has context; without the opt-in the target transcript is untouched."""- def _setup(self, send_result=None):- adapter = _make_adapter()- mock_target = AsyncMock()- mock_target.send = AsyncMock(return_value=send_result or SendResult(success=True))- mock_runner = MagicMock()- mock_runner.adapters = {Platform("telegram"): mock_target}- mock_runner.config.get_home_channel.return_value = None- adapter.gateway_runner = mock_runner- return adapter, mock_target+ _CHAT = "5135545282"- @pytest.mark.asyncio- async def test_successful_delivery_is_mirrored_as_labelled_user_turn(self):- adapter, _ = self._setup()- delivery = {"route": "ambush-nfl", "deliver_extra": {"chat_id": "5135545282", "thread_id": "7"}}- with patch("gateway.mirror.mirror_to_session", return_value=True) as mirror:- result = await adapter._deliver_cross_platform("telegram", "Henderson OUT Wednesday", delivery)- assert result.success is True- mirror.assert_called_once_with(- "telegram", "5135545282", "[Webhook delivery: ambush-nfl]\nHenderson OUT Wednesday",- source_label="webhook", thread_id="7", role="user")-- @pytest.mark.asyncio- async def test_home_channel_fallback_is_mirrored_to_that_chat(self):- adapter, _ = self._setup()- adapter.gateway_runner.config.get_home_channel.return_value = MagicMock(chat_id="home-1")- with patch("gateway.mirror.mirror_to_session", return_value=True) as mirror:- await adapter._deliver_cross_platform("telegram", "hi", {"route": "r", "deliver_extra": {}})- assert mirror.call_args.args[:2] == ("telegram", "home-1")+ @staticmethod+ def _seed_dm(home, sid, chat):+ from hermes_state import SessionDB+ db = SessionDB(db_path=home / "state.db")+ db.create_session(sid, source="telegram")+ db._conn.execute("UPDATE sessions SET session_key=?, chat_id=?, user_id=? WHERE id=?",+ (f"agent:main:telegram:dm:{chat}", chat, chat, sid))+ db._conn.commit()+ db.close()- @pytest.mark.asyncio- async def test_failed_delivery_is_not_mirrored(self):- adapter, _ = self._setup(SendResult(success=False, error="boom"))- with patch("gateway.mirror.mirror_to_session") as mirror:- result = await adapter._deliver_cross_platform(- "telegram", "hi", {"route": "r", "deliver_extra": {"chat_id": "1"}})- assert result.success is False- mirror.assert_not_called()+ @staticmethod+ def _transcript(home, sid):+ from hermes_state import SessionDB+ db = SessionDB(db_path=home / "state.db")+ rows = db._conn.execute("SELECT role, content FROM messages WHERE session_id=? ORDER BY id", (sid,)).fetchall()+ db.close()+ return [(r[0], r[1]) for r in rows]++ @pytest.fixture+ def homes(self, tmp_path, monkeypatch):+ from pathlib import Path+ import hermes_state+ from hermes_cli.profiles import get_profile_dir+ default_home = tmp_path / ".hermes"+ default_home.mkdir()+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setenv("HERMES_HOME", str(default_home))+ # The hermetic conftest pins DEFAULT_DB_PATH when hermes_state is already imported; un-pin it so+ # state.db resolves from the active (profile-scoped) home at call time, as in production.+ monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", hermes_state._IMPORT_DEFAULT_DB_PATH)+ work_home = get_profile_dir("work")+ work_home.mkdir(parents=True)+ # A DM chat_id is the user's id on every bot, so both profiles hold a session for it.+ self._seed_dm(default_home, "dm-default", self._CHAT)+ self._seed_dm(work_home, "dm-work", self._CHAT)+ return default_home, work_home- @pytest.mark.asyncio- async def test_route_can_opt_out(self):- adapter, _ = self._setup()- with patch("gateway.mirror.mirror_to_session") as mirror:- await adapter._deliver_cross_platform(- "telegram", "hi", {"route": "r", "mirror": False, "deliver_extra": {"chat_id": "1"}})- mirror.assert_not_called()+ @staticmethod+ def _attach_target(adapter):+ target = AsyncMock()+ target.send = AsyncMock(return_value=SendResult(success=True))+ adapter.gateway_runner = MagicMock()+ adapter.gateway_runner._authorization_adapter = lambda platform, profile=None: target+ return adapter@pytest.mark.asyncio- async def test_mirror_failure_never_fails_the_delivery(self):- adapter, mock_target = self._setup()- with patch("gateway.mirror.mirror_to_session", side_effect=RuntimeError("db locked")):- result = await adapter._deliver_cross_platform(- "telegram", "hi", {"route": "r", "deliver_extra": {"chat_id": "1"}})+ async def test_opted_in_delivery_mirrors_into_the_routed_profiles_chat_session(self, homes):+ default_home, work_home = homes+ adapter = self._attach_target(_make_adapter())+ delivery = {"deliver": "telegram", "route": "ambush-nfl", "profile": "work", "mirror": True,+ "deliver_extra": {"chat_id": self._CHAT}}+ result = await adapter._deliver_cross_platform("telegram", "Henderson OUT Wednesday", delivery)assert result.success is True- mock_target.send.assert_awaited_once()+ assert self._transcript(work_home, "dm-work") == [+ ("user", "[Webhook delivery: ambush-nfl]\nHenderson OUT Wednesday")]+ assert self._transcript(default_home, "dm-default") == []@pytest.mark.asyncio- async def test_delivery_info_records_route_and_mirror_flag(self):- """The route name and opt-out reach send() through delivery_info for both agent-run and- deliver_only routes."""- routes = {- "agent": {"secret": _INSECURE_NO_AUTH, "prompt": "p"},- "quiet": {"secret": _INSECURE_NO_AUTH, "prompt": "p", "mirror_to_session": False},- }+ async def test_route_without_opt_in_never_touches_the_target_transcript(self, homes):+ default_home, _ = homes+ routes = {"plain": {"secret": _INSECURE_NO_AUTH, "prompt": "p", "deliver": "telegram",+ "deliver_extra": {"chat_id": self._CHAT}},+ "yaml-str": {"secret": _INSECURE_NO_AUTH, "prompt": "p", "deliver": "telegram",+ "deliver_extra": {"chat_id": self._CHAT}, "mirror_to_session": "false"}}adapter = _make_adapter(routes=routes)adapter.handle_message = AsyncMock()- app = _create_app(adapter)- async with TestClient(TestServer(app)) as cli:- r1 = await cli.post("/webhooks/agent", json={"a": 1}, headers={"X-Request-ID": "d1"})- r2 = await cli.post("/webhooks/quiet", json={"a": 1}, headers={"X-Request-ID": "d2"})- assert r1.status == 202 and r2.status == 202- assert adapter._delivery_info["webhook:agent:d1"]["route"] == "agent"- assert adapter._delivery_info["webhook:agent:d1"]["mirror"] is True- assert adapter._delivery_info["webhook:quiet:d2"]["mirror"] is False+ async with TestClient(TestServer(_create_app(adapter))) as cli:+ for route in routes:+ resp = await cli.post(f"/webhooks/{route}", json={"a": 1}, headers={"X-Request-ID": route})+ assert resp.status == 202+ self._attach_target(adapter)+ for route in routes:+ delivery = adapter._delivery_info[f"webhook:{route}:{route}"]+ assert (await adapter._deliver_cross_platform("telegram", "hi", delivery)).success is True+ assert self._transcript(default_home, "dm-default") == []class TestInsecureNoAuthSafetyRail:diff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.mdindex 075005479ed..b89def1a0af 100644--- a/website/docs/reference/cli-commands.md+++ b/website/docs/reference/cli-commands.md@@ -958,6 +958,7 @@ hermes webhook subscribe <name> [options]| `--deliver-chat-id` | Target chat/channel ID for cross-platform delivery. || `--secret` | Custom HMAC secret. Auto-generated if omitted. || `--deliver-only` | Skip the agent — deliver the rendered `--prompt` as the literal message. Zero LLM cost, sub-second delivery. Requires `--deliver` to be a real target (not `log`). |+| `--mirror-to-session` | Also write each delivered message into the target chat's session, so replying to it in that chat has context. Off by default; only enable it for sources whose content you trust in your conversation. || `--script` | Filter/transform script under `~/.hermes/scripts/`. The webhook payload is passed as JSON on stdin; JSON stdout replaces the payload, and empty stdout, `[SILENT]`, or a nonzero exit code ignores the webhook. See [Script Filters and Transforms](../user-guide/messaging/webhooks.md#script-filters-and-transforms). || `--route-profile` | Bind the route to a multiplexed profile: it is then reachable only at `/p/<profile>/webhooks/<name>` and the agent runs as that profile. Validated against existing profiles; kept on update when omitted. Not the same as the global `-p/--profile`, which selects the gateway whose subscriptions file is written. See [Multi-profile gateways](../user-guide/multi-profile-gateways.md). |diff --git a/website/docs/user-guide/messaging/webhooks.md b/website/docs/user-guide/messaging/webhooks.mdindex 8f194ab9788..55c70f41a1a 100644--- a/website/docs/user-guide/messaging/webhooks.md+++ b/website/docs/user-guide/messaging/webhooks.md@@ -91,7 +91,7 @@ Routes define how different webhook sources are handled. Each route is a named e| `deliver_only` | No | If `true`, skip the agent entirely — the rendered `prompt` template becomes the literal message that gets delivered. Zero LLM cost, sub-second delivery. See [Direct Delivery Mode](#direct-delivery-mode) for use cases. Requires `deliver` to be a real target (not `log`). || `cron_job` | No | Fire an existing cron job (by ID or name) on each event instead of starting a fresh webhook agent session. The rendered `prompt` becomes transient per-run context; the job's own prompt, skills, model, and delivery settings apply. Mutually exclusive with `deliver_only`. See [Event-Triggered Cron Jobs](#event-triggered-cron-jobs). || `coalesce` | No | Debounce rapid distinct events on the same logical entity into one agent run. Block with a required `key` (payload field or template identifying the entity, e.g. `pull_request.number`), optional `window_seconds` (quiet window, default 30) and `max_wait_seconds` (dispatch cap, default 300). See [Event Coalescing](#event-coalescing). Mutually exclusive with `deliver_only` and `cron_job`. |-| `mirror_to_session` | No | Default `true`. After a successful delivery to a chat platform, the delivered message is also written into that chat's session transcript (as a labelled user turn, the same way cron briefs are), so when you reply in that chat the agent knows what it just sent you. Set `false` to keep the target chat's history untouched. |+| `mirror_to_session` | No | Default `false`. When `true`, after a successful delivery to a chat platform the delivered message is also written into that chat's session transcript (as a labelled user turn, the same way continuable cron briefs are), so when you reply in that chat the agent knows what it just sent you. See [Replying to a delivery](#replying-to-a-delivery). |### Full example@@ -360,7 +360,13 @@ The `deliver` field controls where the agent's response goes after processing thFor cross-platform delivery, the target platform must also be enabled and connected in the gateway. If no `chat_id` is provided in `deliver_extra`, the response is sent to that platform's configured home channel.-A delivered response is mirrored into the target chat's session transcript as `[Webhook delivery: <route>]` followed by the message, so a follow-up reply in that chat ("so he's out?") has the context of what the webhook run said. The mirror is best-effort: it never fails the delivery, and it is skipped when the chat has no gateway session yet (nobody has talked to the agent there). Set `mirror_to_session: false` on the route to disable it.+### Replying to a delivery {#replying-to-a-delivery}++By default a delivery is fire-and-forget: each webhook event runs in its own session, so if you reply to the delivered message in that chat, the agent there has no record of what was sent. Set `mirror_to_session: true` on the route (or pass `--mirror-to-session` to `hermes webhook subscribe`) and the delivered text is also appended to the target chat's session as `[Webhook delivery: <route>]` followed by the message, so a follow-up ("so he's out?") has the context.++- The mirror is best-effort: it never fails the delivery, and it is skipped when the chat has no gateway session yet (nobody has talked to the agent there).+- On a `/p/<profile>/` route it is written into that profile's session for the chat, never another profile's.+- The mirrored text enters the chat's history as if you had sent it. On a [`deliver_only`](#direct-delivery-mode) route it is the raw rendered payload, so only enable it for sources whose content you trust to sit in your conversation (your own services, not a public issue tracker).---