The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bot-relay): the reply waiter is a runner entrypoint, so it starts under single-query deny
John Paul Solivaa28d038d480f
diff --git a/tests/tools/test_bot_relay.py b/tests/tools/test_bot_relay.pyindex 33aae69f810..2119ba45691 100644--- a/tests/tools/test_bot_relay.py+++ b/tests/tools/test_bot_relay.py@@ -164,11 +164,25 @@ def test_write_reply_reason_passthrough_and_classification(root):assert data["reason"] == "" and data["reply"] == "ok"-def test_waiter_command_quotes_and_targets_reply_file(root):+def test_waiter_is_a_runner_entrypoint_the_approval_gate_lets_through(root):+ """The waiter is spawned through terminal_tool from the SENDER's turn. When a bot replies to a+ teammate from its own one-shot delivery turn, that turn runs under ``approvals.single_query_mode``+ (default ``deny``), and inline interpreter code is a flagged pattern — so the reply waiter was+ refused exactly when bots talked to each other, and the reply never woke the sender."""+ import shlex++ from tools.approval import detect_dangerous_command+env = {"id": "b" * 32, "target_handle": "researcher", "target_connection": "ssh-vps"}cmd = bot_relay.waiter_command(root, env)- assert ("b" * 32) in cmd and "-c" in cmd- assert "rm -rf" not in cmd # sanity: single quoted -c payload+ parts = shlex.split(cmd)++ assert detect_dangerous_command(cmd)[0] is False, cmd+ assert parts[1].endswith("bot_mode_dm.py") and parts[2] == "--wait-reply"+ assert parts[3] == str(bot_relay.relay_root(root) / bot_relay.REPLIES_DIR / f"{'b' * 32}.json")+ assert parts[4:] == ["@researcher on ssh-vps", str(bot_relay.REPLY_WAIT_SECONDS)]+ # The shape this replaces, for the record: flagged, hence refused under deny.+ assert detect_dangerous_command("python3 -c 'import json'")[0] is Truedef test_waiter_outlives_the_desktop_deliver_deadline():@@ -184,15 +198,34 @@ def test_waiter_outlives_the_desktop_deliver_deadline():assert bot_relay.REPLY_WAIT_SECONDS > desktop_budget_s-def test_waiter_give_up_message_states_the_real_budget(root):- import shlex+ ("reply_file", "expected_code", "expected_lines"),+ [+ ({"reply": "pong"}, 0, ["Reply from @researcher on ssh-vps:", "pong"]),+ ({"reply": ""}, 0, ["Reply from @researcher on ssh-vps:", "(empty reply)"]),+ ({"error": "turn failed", "reason": "provider_rate_limit"}, 1,+ ["Delivery to @researcher on ssh-vps failed [reason: provider_rate_limit]: turn failed"]),+ ({"error": "turn failed"}, 1, ["Delivery to @researcher on ssh-vps failed: turn failed"]),+ (None, 1, ["No reply from @researcher on ssh-vps within 0.3s. The message may still be delivered "+ "when the Desktop reconnects; do not resend blindly."]),+ ],+ ids=["reply", "empty-reply", "typed-error", "untyped-error", "gave-up"],+)+def test_waiter_prints_the_completion_notification_the_sender_wakes_on(root, capsys, reply_file, expected_code, expected_lines):+ """The waiter's stdout IS the sender's completion notification: the reply, a typed failure the+ sender can branch on without parsing prose (#93091), or an honest give-up that names the budget."""+ from tools import bot_mode_dmenv = {"id": "d" * 32, "target_handle": "researcher", "target_connection": "ssh-vps"}- parts = shlex.split(bot_relay.waiter_command(root, env))- code = parts[parts.index("-c") + 1]- assert f"deadline = time.time() + {bot_relay.REPLY_WAIT_SECONDS}\n" in code- assert f"within {bot_relay.REPLY_WAIT_SECONDS}s" in code- assert "within 900s" not in code+ reply_path = bot_relay.relay_root(root) / bot_relay.REPLIES_DIR / f"{env['id']}.json"+ reply_path.parent.mkdir(parents=True, exist_ok=True)+ if reply_file is not None:+ reply_path.write_text(json.dumps(reply_file), encoding="utf-8")++ code = bot_mode_dm._delivery_main(["--wait-reply", str(reply_path), "@researcher on ssh-vps", "0.3"])++ assert (code, capsys.readouterr().out.splitlines()) == (expected_code, expected_lines)+ assert bot_mode_dm._delivery_main(["--wait-reply", str(reply_path)]) == 2def test_waiter_picks_up_reply_within_a_sub_second_cadence(root):@@ -236,38 +269,25 @@ def test_roster_rejects_connection_id_outside_handle_charset(root):assert bot_relay.write_remote_roster(root, [good]) == 1-def test_waiter_command_repr_encodes_hostile_connection_id(root):- import ast+def test_hostile_roster_fields_ride_as_argv_data(root):+ """Envelope fields come from the Desktop-pushed roster — untrusted. They must never become+ source text: the waiter takes them as argv, so a payload shaped like Python is a label."""import shlex+ import subprocessinj = "x'); open(r'/tmp/pwned','w').write('pwned'); print('x"- env = {- "id": "c" * 32,- "target_handle": "researcher",- "target_connection": inj,- }+ env = {"id": "c" * 32, "target_handle": "researcher", "target_connection": inj}cmd = bot_relay.waiter_command(root, env)parts = shlex.split(cmd)- code = parts[parts.index("-c") + 1]- compile(code, "<waiter>", "exec")- tree = ast.parse(code)- opens = [- n- for n in ast.walk(tree)- if isinstance(n, ast.Call)- and isinstance(n.func, ast.Name)- and n.func.id == "open"- ]- # Only json.load(open(p, ...)) is a real open(); the payload must stay data.- assert len(opens) == 1- # A quote in the id used to SyntaxError the waiter. It must compile.- quoted = bot_relay.waiter_command(- root,- {"id": "a" * 32, "target_handle": "h", "target_connection": "foo'bar"},- )- qcode = shlex.split(quoted)[shlex.split(quoted).index("-c") + 1]- compile(qcode, "<waiter-quote>", "exec")+ assert "-c" not in parts+ assert parts[4] == f"@researcher on {inj}"+ reply_path = bot_relay.relay_root(root) / bot_relay.REPLIES_DIR / f"{env['id']}.json"+ reply_path.parent.mkdir(parents=True, exist_ok=True)+ reply_path.write_text(json.dumps({"reply": "pong"}), encoding="utf-8")+ proc = subprocess.run(parts, capture_output=True, text=True, timeout=30)++ assert proc.returncode == 0 and proc.stdout.splitlines() == [f"Reply from @researcher on {inj}:", "pong"]# ── message_agent integration: relay route + legacy-SOUL gate fix ───────────diff --git a/tests/tools/test_bot_relay_windows_paths.py b/tests/tools/test_bot_relay_windows_paths.pyindex e6123a7371f..6e489a18b04 100644--- a/tests/tools/test_bot_relay_windows_paths.py+++ b/tests/tools/test_bot_relay_windows_paths.py@@ -2,15 +2,12 @@ r"""Windows-path viability and venv CLI resolution for bot relay (#93590).Two failures on a Windows desktop install talking to a remote gateway:-1. ``waiter_command`` embeds the reply path into generated ``python -c``- source with ``!r``. repr escapes each backslash, but the Windows- execution layer the waiter runs under folds ``\\`` back to ``\`` —- ``\\U`` in ``C:\\Users\\...`` then parses as a unicode escape and- SyntaxErrors the whole script. The raw-string prefix keeps the folded- single backslash a literal; POSIX paths contain no backslashes, so it- is a no-op there, and ``\\'`` inside a raw literal still cannot- terminate the string, so the injection defense from #93091's- python -c hardening is unchanged.+1. ``waiter_command`` used to embed the reply path into generated ``python -c``+ source, where the Windows execution layer's backslash folding turned+ ``C:\\Users`` into a unicode escape and SyntaxErrored the script. The waiter+ is now a runner entrypoint (``bot_mode_dm.py --wait-reply``) that takes the+ path as argv, rewritten to forward slashes the way the delivery runner's+ argv is — the tracked local backend runs commands through Git Bash there.2. ``local_delivery_command`` hardcoded ``"hermes"``, relying on PATH —which service contexts (systemd units, desktop launchers, non-login@@ -22,7 +19,6 @@ Two failures on a Windows desktop install talking to a remote gateway:the per-profile lock."""-import astimport shlexfrom pathlib import Path@@ -33,59 +29,15 @@ import tools.bot_relay as bot_relayENV = {"id": "d" * 32, "target_handle": "researcher", "target_connection": "ssh-vps"}-def _waiter_code(root, env=None) -> str:- cmd = bot_relay.waiter_command(root, env or ENV)- parts = shlex.split(cmd)- return parts[parts.index("-c") + 1]---def test_waiter_windows_path_compiles_after_backslash_folding():- """A Windows reply path must survive the execution layer folding the- repr-escaped double backslash back to a single one — the exact shape- that SyntaxErrored with ``\\U`` on #93590's reporter setup."""- code = _waiter_code("C:\\Users\\joshu\\.hermes")- assert "C:" in code # sanity: the Windows path made it into the payload- folded = code.replace("\\\\", "\\")- # Raw literals: `p = r'C:\Users\joshu\...'` — no unicode-escape crash.- compile(folded, "<waiter>", "exec")---def test_waiter_posix_path_and_label_values_roundtrip():- """On POSIX (backslash-free paths) the raw prefix changes nothing."""- root = Path("/tmp/hermes-home")- code = _waiter_code(root)- assigns = {- t.targets[0].id: t.value- for t in ast.parse(code).body- if isinstance(t, ast.Assign) and isinstance(t.targets[0], ast.Name)- }- expected = str(root / "bot_relay" / "replies" / f"{ENV['id']}.json")- assert assigns["p"].value == expected- assert assigns["label"].value == "@researcher on ssh-vps"- # The literals are raw-prefixed in the generated source.- assert "\np = r'" in code- assert "\nlabel = r'" in code---def test_waiter_raw_prefix_keeps_injection_defense():- """Hostile roster fields must stay data under the raw prefix too."""- inj = {- "id": "e" * 32,- "target_handle": "researcher",- "target_connection": "x'); __import__('sys').exit(2); print('x",- }- code = _waiter_code(Path("/tmp/hermes-home"), inj)- compile(code, "<waiter>", "exec")- calls = [- n.func.id- for n in ast.walk(ast.parse(code))- if isinstance(n, ast.Call) and isinstance(n.func, ast.Name)- ]- # The generated waiter only calls str/print/compile-free builtins by- # name; the payload's __import__ must remain a string literal, not a- # live call — parse it back and confirm it stayed data.- assert "__import__" not in calls- assert "x'); __import__('sys').exit(2); print('x" in code+def test_waiter_argv_uses_forward_slashes_on_windows(monkeypatch):+ """On native Windows the reply path rides as a forward-slash argv element, like the delivery+ runner's paths: Git Bash runs those, and parses a backslash path as a command name."""+ monkeypatch.setattr(bot_relay.sys, "platform", "win32")+ parts = shlex.split(bot_relay.waiter_command("C:\\Users\\joshu\\.hermes", ENV))++ assert "-c" not in parts and "--wait-reply" in parts+ assert parts[parts.index("--wait-reply") + 1] == f"C:/Users/joshu/.hermes/bot_relay/replies/{ENV['id']}.json"+ assert not any("\\" in part for part in parts)def test_local_delivery_resolves_sibling_hermes(tmp_path, monkeypatch):diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.pyindex 2d49db65b82..4a761678cc0 100644--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@ -729,8 +729,41 @@ def _persist_reply_when_done(proc_id: str, agent: Any) -> bool:return True+def _wait_reply_main(reply_path: str, label: str, budget_seconds: str) -> int:+ """The relay reply waiter (``tools/bot_relay.waiter_command``): block until the sender-side+ reply file exists, print it as the completion notification the sender wakes on, exit 1 on a+ delivery error or when the budget runs out. Stdlib only: this runs as a background process+ from any bot turn, and the sender's completion notification is exactly its stdout."""+ try:+ deadline = time.time() + float(budget_seconds)+ except ValueError:+ return 2+ while time.time() < deadline:+ if os.path.exists(reply_path):+ with open(reply_path, encoding="utf-8") as fh:+ d = json.load(fh)+ if d.get("error"):+ # Typed reason code rides ahead of the free text so the sender can branch on it+ # without parsing provider prose. See #93091.+ code = str(d.get("reason") or "").strip()+ tag = f" [reason: {code}]" if code else ""+ print(f"Delivery to {label} failed{tag}: {d['error']}")+ return 1+ print(f"Reply from {label}:")+ print(d.get("reply") or "(empty reply)")+ return 0+ # 250ms cadence: stat is cheap and a longer sleep is pure dead air.+ time.sleep(0.25)+ print(f"No reply from {label} within {budget_seconds}s. The message may still be delivered when "+ "the Desktop reconnects; do not resend blindly.")+ return 1++def _delivery_main(args: list[str]) -> int:- """Runner entry for the argv ``_delivery_command`` builds. Malformed argv exits 2 without touching the DM file."""+ """Runner entry for the argv ``_delivery_command`` and ``bot_relay.waiter_command`` build.+ Malformed argv exits 2 without touching the DM file."""+ if args[:1] == ["--wait-reply"]:+ return _wait_reply_main(*args[1:]) if len(args) == 4 else 2if not args or args[0] != "--run-delivery":return 2rest, author = args[1:], Nonediff --git a/tools/bot_relay.py b/tools/bot_relay.pyindex fc706877305..9944652262e 100644--- a/tools/bot_relay.py+++ b/tools/bot_relay.py@@ -345,42 +345,24 @@ def cleanup_bot_relay_artifacts(max_age_hours: float | None = None) -> int:def waiter_command(root: Path | str, envelope: dict) -> str:"""Shell command that blocks until the reply file appears, then prints it; spawnedvia ``terminal_tool(background=True, notify_on_complete=True)`` so its stdout arrives- as the same completion notification local DMs use. Stdlib-only."""+ as the same completion notification local DMs use.++ A ``tools/bot_mode_dm.py --wait-reply`` entrypoint, like the local delivery runner — not+ ``python -c``. The approval gate flags inline interpreter code ("script execution via -e/-c+ flag"), and ``approvals.single_query_mode`` defaults to ``deny`` for the one-shot ``-Q`` turn a+ bot replies from, so the reply waiter was refused exactly when a bot answered a teammate: the+ message was delivered, the reply never woke the sender. Roster fields ride as argv (``shlex``+ quoted), never as source text, so a hostile handle or connection id stays data.+ """reply_path = str(relay_root(root) / REPLIES_DIR / f"{envelope['id']}.json")label = f"@{envelope.get('target_handle', '')} on {envelope.get('target_connection', '')}"- # !r keeps roster fields from breaking out of the generated python -c source.- # The r-prefix keeps Windows paths viable: the Windows execution layer folds- # repr's "\\" back to "\", turning "\U" into an invalid unicode escape; a- # raw literal parses the folded backslash literally. No-op on POSIX, and \'- # still cannot terminate a raw literal, so the injection defense holds.- code = (- # Encode label with !r so roster fields cannot break out of the generated python -c source (quotes,- # parens, or extra statements in connection_id). See #93590.- "import json,os,sys,time\n"- f"p = r{reply_path!r}\n"- f"label = r{label!r}\n"- f"deadline = time.time() + {REPLY_WAIT_SECONDS}\n"- "while time.time() < deadline:\n"- " if os.path.exists(p):\n"- " d = json.load(open(p, encoding='utf-8'))\n"- " if d.get('error'):\n"- # Typed reason code rides ahead of the free text so the sender can- # branch on it without parsing provider prose.- # See #93091.- " code = str(d.get('reason') or '').strip()\n"- " tag = ' [reason: ' + code + ']' if code else ''\n"- " print('Delivery to ' + label + ' failed' + tag + ': ' + d['error'])\n"- " sys.exit(1)\n"- " print('Reply from ' + label + ':')\n"- " print(d.get('reply') or '(empty reply)')\n"- " sys.exit(0)\n"- # 250ms cadence: stat is cheap and a longer sleep is pure dead air.- " time.sleep(0.25)\n"- f"print('No reply from ' + label + ' within {REPLY_WAIT_SECONDS}s. The message may "- "still be delivered when the Desktop reconnects; do not resend blindly.')\n"- "sys.exit(1)\n"- )- return f"{shlex.quote(sys.executable or 'python3')} -c {shlex.quote(code)}"+ runner = str(Path(__file__).resolve().with_name("bot_mode_dm.py"))+ argv = [sys.executable or "python3", runner, "--wait-reply", reply_path, label, str(REPLY_WAIT_SECONDS)]+ if sys.platform == "win32":+ # Same rewrite as the delivery runner: the tracked local backend uses Git Bash on native+ # Windows, where forward-slash drive paths run and backslash paths parse as command names.+ argv = [part.replace("\\", "/") for part in argv]+ return shlex.join(argv)def _hermes_cli() -> str:diff --git a/website/docs/user-guide/bot-mode.md b/website/docs/user-guide/bot-mode.mdindex e3511d35804..e188bc5d0c8 100644--- a/website/docs/user-guide/bot-mode.md+++ b/website/docs/user-guide/bot-mode.md@@ -216,7 +216,7 @@ A failed bot turn or relay delivery carries a machine-readable `reason` code aloEvery gateway you register in **Settings → Connections** — local, remote URL, SSH, Hermes Cloud, docker — is a persistent line the Desktop holds open, and Bot Mode uses those lines for messaging automatically. No extra setup:- **Rosters propagate on their own.** While the Desktop runs, it periodically tells each connected gateway which agents live on the *other* connections. Every Bot Chat's teammate roster then lists them ("Teammates on OTHER connected machines"), with names, roles, and which machine they're on — and the roster refreshes when agents appear, disappear, or get renamed (capability epoch).-- **`message_agent` reaches them directly.** A Bot on your laptop messages the cloud agent with `message_agent(target="moxie", …)` exactly like a local teammate. If the same handle exists on several machines, disambiguate with `target="moxie@<connection>"` (the tool's error tells the Bot the exact forms). Delivery rides the Desktop: the sending gateway queues the message, the Desktop relays it to the target connection's own gateway, the target Bot runs a turn in its canonical Bot Chat, and the reply comes back to the sender as the same background completion notification local DMs use. Messages to different Bots are delivered side by side, so one Bot's long turn never delays another Bot's mail (or ages it past `bot_mode.envelope_ttl_seconds`); messages to the *same* Bot are delivered in order, one turn at a time.+- **`message_agent` reaches them directly.** A Bot on your laptop messages the cloud agent with `message_agent(target="moxie", …)` exactly like a local teammate. If the same handle exists on several machines, disambiguate with `target="moxie@<connection>"` (the tool's error tells the Bot the exact forms). Delivery rides the Desktop: the sending gateway queues the message, the Desktop relays it to the target connection's own gateway, the target Bot runs a turn in its canonical Bot Chat, and the reply comes back to the sender as the same background completion notification local DMs use (the process that waits for it is a Hermes entrypoint, so it starts under `approvals.single_query_mode: deny` — the default for a Bot's one-shot reply turn — too). Messages to different Bots are delivered side by side, so one Bot's long turn never delays another Bot's mail (or ages it past `bot_mode.envelope_ttl_seconds`); messages to the *same* Bot are delivered in order, one turn at a time.- **The Desktop is the courier.** Cross-connection delivery works while a Desktop that knows both connections is running (it holds the sockets and the credentials — gateways never see each other's auth). If the Desktop is closed mid-delivery, the sender's Bot is told the reply didn't arrive rather than left hanging. For always-on machine-to-machine messaging with no Desktop in the loop, register a peer (`hermes peer`, below) — the two routes coexist.### Bot-initiated DMs across machines (`hermes peer`)