The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bot-mode): message_agent CLI-runner ack is queued + delivery_id like the other branches
teknium1250bdcc31152
diff --git a/tests/tools/test_bot_mode_dm.py b/tests/tools/test_bot_mode_dm.pyindex a2883bbdaa3..f927faba522 100644--- a/tests/tools/test_bot_mode_dm.py+++ b/tests/tools/test_bot_mode_dm.py@@ -274,7 +274,7 @@ def test_local_delivery_command_and_ack(tmp_path, monkeypatch):agent=agent,))- assert result["status"] == "sent"+ assert result["status"] == "queued"assert result["to"] == "@researcher"assert result["process_id"] == "proc_test1234"assert "do NOT wait" in result["detail"]@@ -313,7 +313,7 @@ def test_local_delivery_command_and_ack(tmp_path, monkeypatch):def test_cli_runner_ack_is_a_dispatch_ack_that_names_the_completion_notification(tmp_path, monkeypatch):- """``status: sent`` is returned before the background runner has delivered anything; the+ """``status: queued`` is returned before the background runner has delivered anything; thedetail (and the schema text the model reads) must say the completion notification carriesthe outcome, so a runner that dies at exec is never read as a delivered message."""_capture_spawn(monkeypatch)@@ -321,7 +321,7 @@ def test_cli_runner_ack_is_a_dispatch_ack_that_names_the_completion_notificationresult = json.loads(bot_mode_dm.message_agent_tool(target="researcher", message="hi", agent=_FakeAgent(home, title="Bot Chat")))- assert result["status"] == "sent"+ assert result["status"] == "queued"assert "not a delivery receipt" in result["detail"]assert "completion notification" in result["detail"]assert "delivery failure" in result["detail"]@@ -329,6 +329,36 @@ def test_cli_runner_ack_is_a_dispatch_ack_that_names_the_completion_notificationassert "dispatch acknowledgement" in description and "not a delivery receipt" in description+def test_cli_runner_ack_is_queued_with_the_runner_delivery_id(tmp_path, monkeypatch):+ """The CLI-runner ack speaks the same vocabulary as the live-owner and relay branches:+ ``queued`` + ``delivery_id`` (+ ``process_id``). The id is the one the runner itself pins+ for the same DM file when it admits to a live owner, so a sender can correlate both."""+ import hashlib++ calls = _capture_spawn(monkeypatch)+ home = _managed_home(tmp_path, teammates=("researcher",))+ result = json.loads(bot_mode_dm.message_agent_tool(+ target="researcher", message="hi", agent=_FakeAgent(home, title="Bot Chat")))++ assert result["status"] == "queued"+ assert result["process_id"] == "proc_test1234"+ _, dm_file, _ = _runner_parts(calls[0]["command"])+ assert result["delivery_id"] == hashlib.sha256(str(Path(dm_file).resolve()).encode()).hexdigest()+++def test_relay_ack_is_queued_with_the_envelope_id(tmp_path, monkeypatch):+ _capture_spawn(monkeypatch)+ home = _managed_home(tmp_path)+ bot_relay.write_remote_roster(home, [+ {"profile": "default", "handle": "hermes", "connection_id": "cloud-1", "connection_label": "Hermes Cloud"},+ ])+ result = json.loads(bot_mode_dm.message_agent_tool(target="hermes", message="ping", agent=_FakeAgent(home)))++ assert result["status"] == "queued"+ (envelope,) = bot_relay.claim_pending_envelopes(home)+ assert result["delivery_id"] == envelope["id"]++def _rename(home: Path, folder: str, *, display_name: str = "", title: str = "") -> None:lines = ["description: teammate for tests", "ui_meta:", " hermes-bots:", " shape: cloud"]if title:@@ -353,7 +383,7 @@ def test_friendly_names_and_desktop_slugs_resolve_to_folder_ids(tmp_path, monkeyresult = json.loads(bot_mode_dm.message_agent_tool(target=target, message="ping", agent=_FakeAgent(home)))- assert result["status"] == "sent", result+ assert result["status"] == "queued", resultassert result["to"] == f"@{expected}"_mode, _dm_file, argv = _runner_parts(calls[0]["command"])assert argv[1:3] == ["-p", expected]@@ -399,7 +429,7 @@ def test_peer_delivery_command_pins_registry_profile_for_secondary_bots(result = json.loads(bot_mode_dm.message_agent_tool(target="spark", message="ping", agent=agent))- assert result["status"] == "sent"+ assert result["status"] == "queued"mode, _dm_file, transport_argv = _runner_parts(calls[0]["command"])assert mode == "stdin"# The registry the tool validated against is the machine root's β the@@ -417,7 +447,7 @@ def test_peer_delivery_command(tmp_path, monkeypatch):result = json.loads(bot_mode_dm.message_agent_tool(target="spark/researcher", message="ping", agent=agent))- assert result["status"] == "sent"+ assert result["status"] == "queued"assert "spark" in result["to"]mode, _dm_file, transport_argv = _runner_parts(calls[0]["command"])assert mode == "stdin"@@ -429,7 +459,7 @@ def test_peer_delivery_command(tmp_path, monkeypatch):result2 = json.loads(bot_mode_dm.message_agent_tool(target="spark", message="ping", agent=agent))- assert result2["status"] == "sent"+ assert result2["status"] == "queued"mode, _dm_file, transport_argv = _runner_parts(calls[1]["command"])assert mode == "stdin"assert transport_argv == ["hermes", "-p", "default", "peer", "dm", "spark"]@@ -453,7 +483,7 @@ def test_delivery_pins_the_hermes_entrypoint_beside_this_interpreter(tmp_path, mresult = json.loads(bot_mode_dm.message_agent_tool(target="researcher", message="ping", agent=agent))- assert result["status"] == "sent"+ assert result["status"] == "queued"mode, _dm_file, transport_argv = _runner_parts(calls[0]["command"])assert mode == "query-file"assert transport_argv[0] == str(hermes_entry)@@ -463,7 +493,7 @@ def test_delivery_pins_the_hermes_entrypoint_beside_this_interpreter(tmp_path, mresult2 = json.loads(bot_mode_dm.message_agent_tool(target="spark", message="ping", agent=agent))- assert result2["status"] == "sent"+ assert result2["status"] == "queued"mode, _dm_file, transport_argv = _runner_parts(calls[1]["command"])assert mode == "stdin"assert transport_argv == [str(hermes_entry), "-p", "default", "peer", "dm", "spark"]@@ -477,8 +507,8 @@ def test_peer_delivery_author_carries_the_sender_hostname_and_local_stays_bare(thome = _managed_home(tmp_path, teammates=("researcher", "coder"), peers=("spark",))agent = _FakeAgent(home / "profiles" / "coder", title="Bot Chat")- assert json.loads(bot_mode_dm.message_agent_tool(target="spark", message="ping", agent=agent))["status"] == "sent"- assert json.loads(bot_mode_dm.message_agent_tool(target="researcher", message="ping", agent=agent))["status"] == "sent"+ assert json.loads(bot_mode_dm.message_agent_tool(target="spark", message="ping", agent=agent))["status"] == "queued"+ assert json.loads(bot_mode_dm.message_agent_tool(target="researcher", message="ping", agent=agent))["status"] == "queued"assert _runner_author(calls[0]["command"]) == {"id": "bot:erimac.local/coder", "name": "coder", "is_bot": True}assert _runner_author(calls[1]["command"]) == {"id": "bot:coder", "name": "coder", "is_bot": True}@@ -495,14 +525,14 @@ def test_renamed_primary_signs_with_its_friendly_name_and_is_reachable_by_it(tmp(home / "profile.yaml").write_text("display_name: Maia\n", encoding="utf-8")result = json.loads(bot_mode_dm.message_agent_tool(target="coder", message="hi", agent=_FakeAgent(home)))- assert result["status"] == "sent"+ assert result["status"] == "queued"_mode, dm_file, _argv = _runner_parts(calls[0]["command"])assert Path(dm_file).read_text(encoding="utf-8").startswith("Message from π€ Maia (@hermes): ")coder = _FakeAgent(home / "profiles" / "coder")for target in ("maia", "@maia", "@hermes"):result = json.loads(bot_mode_dm.message_agent_tool(target=target, message="pong", agent=coder))- assert result["status"] == "sent", (target, result)+ assert result["status"] == "queued", (target, result)_mode, _dm_file, argv = _runner_parts(calls[-1]["command"])assert argv[1:3] == ["-p", "default"], (target, argv)@@ -524,7 +554,7 @@ def test_named_profile_sender_prefix(tmp_path, monkeypatch):result = json.loads(bot_mode_dm.message_agent_tool(target="researcher", message="hi", agent=agent))- assert result["status"] == "sent"+ assert result["status"] == "queued"_mode, dm_file, _transport_argv = _runner_parts(calls[0]["command"])assert Path(dm_file).read_text(encoding="utf-8").startswith("Message from π€ coder (@coder): "@@ -973,7 +1003,7 @@ def test_successful_spawn_transfers_cleanup_to_runner(tmp_path, monkeypatch):))- assert result["status"] == "sent"+ assert result["status"] == "queued"assert dm_file.exists(), "the parent must not delete before the background runner reads"diff --git a/tests/tools/test_bot_relay.py b/tests/tools/test_bot_relay.pyindex d56d6ea950c..33aae69f810 100644--- a/tests/tools/test_bot_relay.py+++ b/tests/tools/test_bot_relay.py@@ -348,15 +348,15 @@ def test_relay_route_queues_envelope_and_spawns_waiter(tmp_path, monkeypatch):spawned = {}- def _fake_spawn(command, label, *, task_id, agent):+ def _fake_spawn(command, label, *, task_id, agent, **_):spawned["command"] = commandspawned["label"] = label- return json.dumps({"status": "sent", "to": label})+ return json.dumps({"status": "queued", "to": label})monkeypatch.setattr("tools.bot_mode_dm._spawn_delivery", _fake_spawn)agent = _FakeAgent(home)out = json.loads(message_agent_tool(target="hermes", message="ping", agent=agent))- assert out.get("status") == "sent"+ assert out.get("status") == "queued"assert "Hermes Cloud" in spawned["label"]# envelope landed in the outbox with attribution prefixedpending = bot_relay.claim_pending_envelopes(home)@@ -376,14 +376,14 @@ def test_relay_route_ambiguous_target_errors_with_forms(tmp_path, monkeypatch):])monkeypatch.setattr("tools.bot_mode_dm._spawn_delivery",- lambda *a, **k: json.dumps({"status": "sent"}),+ lambda *a, **k: json.dumps({"status": "queued"}),)agent = _FakeAgent(home)out = json.loads(message_agent_tool(target="scout", message="hi", agent=agent))assert "scout@cloud-1" in out.get("error", "") and "scout@ssh-vps" in out["error"]# connection-qualified form goes throughout2 = json.loads(message_agent_tool(target="scout@ssh-vps", message="hi", agent=agent))- assert out2.get("status") == "sent"+ assert out2.get("status") == "queued"def test_unknown_target_error_mentions_connected_machines(tmp_path):@@ -620,7 +620,7 @@ def test_message_agent_surfaces_runtime_offline_refusal(tmp_path, monkeypatch):])monkeypatch.setattr("tools.bot_mode_dm._spawn_delivery",- lambda *a, **k: json.dumps({"status": "sent"}),+ lambda *a, **k: json.dumps({"status": "queued"}),)agent = _FakeAgent(home)out = json.loads(message_agent_tool(target="hermes", message="ping", agent=agent))diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.pyindex 5b92d8cfbe6..bfff60ec10f 100644--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@ -69,8 +69,8 @@ def message_agent_tool_schema() -> dict:"asynchronous, like texting: it validates the target against the live ""roster, delivers your message into that agent's own Bot Chat with your ""attribution automatically prefixed, and returns immediately with a "- "dispatch acknowledgement (the hand-off to a background delivery process, "- "not a delivery receipt). It does NOT return their reply and you must "+ "dispatch acknowledgement β status queued plus a delivery_id (the hand-off to a background "+ "delivery process, not a delivery receipt). It does NOT return their reply and you must ""not wait or poll for one β send it, finish your turn, and that process's ""completion notification wakes you with the outcome: their reply, or the ""delivery failure. COMPOSE the message yourself: write what YOU want to say to "@@ -306,7 +306,7 @@ def _try_relay_delivery(root: Path, raw_target: str, content: str, me: str, *,# per the #93091 reason enum).return json.dumps({"error": str(exc), "reason": exc.reason})label = f"@{match['handle']} on {match['connection_label'] or match['connection_id']}"- raw = _spawn_delivery(waiter_command(root, envelope), label, task_id=task_id, agent=agent)+ raw = _spawn_delivery(waiter_command(root, envelope), label, delivery_id=envelope["id"], task_id=task_id, agent=agent)waiter_error = json.loads(raw).get("error")if not waiter_error:return raw@@ -315,7 +315,7 @@ def _try_relay_delivery(root: Path, raw_target: str, content: str, me: str, *,# sender resend and deliver the message twice. Same shape as the live-owner branch of# _start_delivery: queued + notification_error.return json.dumps({- "status": "queued", "to": label, "notification_error": waiter_error,+ "status": "queued", "delivery_id": envelope["id"], "to": label, "notification_error": waiter_error,"detail": (f"Message queued for {label}; the relay delivers it on its own, but the reply ""waiter did not start, so the reply will NOT wake you. Do NOT resend."),})@@ -455,6 +455,12 @@ def _run_local_turn(argv: list[str], dm_file: str, *, env: Optional[dict[str, streturn proc.returncode+def _dm_delivery_id(dm_file: "str | os.PathLike") -> str:+ """One delivery id per DM file: the dispatch ack, the live-owner intent and every retry+ of the runner derive it the same way, so the sender can correlate all of them."""+ return hashlib.sha256(str(Path(dm_file).resolve()).encode()).hexdigest()++def _admit_live_dm(profile_home: Path | None, dm_file: str, author: Optional[dict] = None) -> dict | None:"""Pin intent before admission; retries may inspect, never change transport."""from tools.bot_live_delivery import deliver_to_live_owner, find_canonical_live_owner, read_delivery_result@@ -470,7 +476,7 @@ def _admit_live_dm(profile_home: Path | None, dm_file: str, author: Optional[dicif owner is None:return Noneintent = dict(owner=owner, message=Path(dm_file).read_text(encoding="utf-8"),- delivery_id=hashlib.sha256(str(Path(dm_file).resolve()).encode()).hexdigest(),+ delivery_id=_dm_delivery_id(dm_file),**({"author": author} if author else {}))try:fd = os.open(intent_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)@@ -544,8 +550,7 @@ def _run_delivery(argv: list[str], dm_file: str, *, stdin_file: bool,try:record = _admit_live_dm(home, dm_file, author)except Exception as exc:- print(json.dumps({"status": "ambiguous", "delivery_id": hashlib.sha256(- str(Path(dm_file).resolve()).encode()).hexdigest(),+ print(json.dumps({"status": "ambiguous", "delivery_id": _dm_delivery_id(dm_file),"error": f"Live admission outcome unknown: {exc}. Do not resend.","evidence_file": dm_file}))return 1@@ -594,8 +599,7 @@ def _start_delivery(argv: list[str], content: str, label: str, *, stdin_file: botry:record = _admit_live_dm(profile_home, dm_file, author)except Exception as exc:- return json.dumps({"status": "ambiguous", "delivery_id": hashlib.sha256(- str(Path(dm_file).resolve()).encode()).hexdigest(),+ return json.dumps({"status": "ambiguous", "delivery_id": _dm_delivery_id(dm_file),"error": f"Live delivery admission could not be confirmed: {exc}. Do not resend.","evidence_file": dm_file})if record is not None:@@ -616,11 +620,13 @@ def _start_delivery(argv: list[str], content: str, label: str, *, stdin_file: boreturn _spawn_delivery(command, label, dm_file=dm_file, task_id=task_id, agent=agent)-def _spawn_delivery(command: str, label: str, *, dm_file: Optional[str] = None,+def _spawn_delivery(command: str, label: str, *, dm_file: Optional[str] = None, delivery_id: Optional[str] = None,task_id: Optional[str], agent: Any) -> str:"""Launch the cleanup-owning runner and transfer file ownership on ack. ``dm_file``is None for relay deliveries (the waiter watches a reply file; envelope artifacts- are owned/swept by ``tools/bot_relay.py``)."""+ are owned/swept by ``tools/bot_relay.py``), which pass the envelope id as ``delivery_id``+ instead. The ack is ``queued`` + ``delivery_id`` like the live-owner branch: hand-off+ to a background process, never a delivery receipt."""transferred = Falsetry:from tools.terminal_tool import terminal_tool@@ -645,15 +651,16 @@ def _spawn_delivery(command: str, label: str, *, dm_file: Optional[str] = None,# From here the background runner owns the file (removed after the consumer finishes).transferred = Truereturn json.dumps({- "status": "sent",+ "status": "queued",+ "delivery_id": delivery_id or (_dm_delivery_id(dm_file) if dm_file else ""),"to": label,- "detail": (f"Message dispatched to {label}: this acknowledges the hand-off to a "+ "detail": (f"Message queued for {label}: this acknowledges the hand-off to a ""background delivery process, not a delivery receipt β do NOT wait or poll. ""Finish your turn now; that process's completion notification carries the ""delivery outcome β the reply (relay it then, attributed to that agent) or ""the delivery failure (report it; the message was NOT delivered)."),"process_id": proc_id,- "sent_at": int(time.time()),+ "queued_at": int(time.time()),})except Exception as exc:logger.error("message_agent delivery spawn failed: %s", exc, exc_info=True)diff --git a/website/docs/user-guide/bot-mode.md b/website/docs/user-guide/bot-mode.mdindex 5af735f1870..6fc6499952a 100644--- a/website/docs/user-guide/bot-mode.md+++ b/website/docs/user-guide/bot-mode.md@@ -152,7 +152,7 @@ Bots message each other with attribution, and you can hand work off from any cha- **@mentions** β type `@researcher have a look at this` in any chat and the composer's `@` autocomplete helps you pick the right Bot; on send, the mention is resolved against the live roster and the active Bot is told exactly who you mean (profile, friendly name, and device for cross-connection Bots). The Bot then composes its own message and sends it with `message_agent` β your text is never forwarded verbatim, and the reply comes back attributed to that agent. An email address or an unknown `@` passes through untouched. Bots on other connected machines are reachable the same way: the Desktop relays the message over that connection's own socket (see *Bots across machines* below).- **Renamed Bots keep their tags in sync** β give a Bot a friendly name (the pencil in its chat header, or `hermes profile rename`) and it becomes taggable by that name: a Bot titled *Research Buddy* answers to `@research-buddy` (and `@researchbuddy`), in regular chats and in group rooms alike. The composer's `@` autocomplete offers the renamed tag and also matches when you type the old profile name, which keeps resolving too. This includes the primary Bot: rename it *Maia* and group-turn prompts introduce it as `@maia`, its inter-agent messages sign as `Message from π€ Maia (@hermes)`, and teammates can `message_agent(target="maia")` it β `@hermes` stays a working alias.-- **Direct messages** β every Bot Chat carries the `message_agent` tool: a Bot messages a teammate by calling `message_agent(target="researcher", message="β¦")`. The target is the teammate's profile name, its friendly name (`hermes profile rename` or the Bot Mode title β `Scribe`, `Dr. Foo`) or the `@`-tag the Desktop inserts for it (`@scribe`, `@dr-foo`, `@drfoo`); `@hermes` always means the primary Bot. A profile name is matched first, so it can never be hijacked by another Bot's friendly name, and a friendly name shared by two Bots is refused with the roster instead of guessing. The tool validates the target against the live roster, prefixes the sender's `Message from π€ <friendly name> (@<handle>):` attribution automatically, and delivers into the teammate's canonical Bot Chat. Delivery is **fire-and-forget**: the sender gets a *dispatch* acknowledgement (`status: sent` means the message was handed to a background delivery process, not that it was delivered), finishes its turn, and that process's completion notification carries the outcome β the reply, or the delivery failure. The message travels as a real parameter (nothing shell-interpreted β quotes, `$(...)`, and backticks arrive verbatim), and the Bot composes its own message rather than forwarding your words. The teammate roster β names **and roles** from each profile's title/description β is part of every Bot Chat's system prompt, so Bots know who does what before choosing a recipient. The tool exists **only** in canonical Bot Chat sessions on Bot-Mode-managed installs; regular chats, group-room member sessions, and CLI sessions never see it.+- **Direct messages** β every Bot Chat carries the `message_agent` tool: a Bot messages a teammate by calling `message_agent(target="researcher", message="β¦")`. The target is the teammate's profile name, its friendly name (`hermes profile rename` or the Bot Mode title β `Scribe`, `Dr. Foo`) or the `@`-tag the Desktop inserts for it (`@scribe`, `@dr-foo`, `@drfoo`); `@hermes` always means the primary Bot. A profile name is matched first, so it can never be hijacked by another Bot's friendly name, and a friendly name shared by two Bots is refused with the roster instead of guessing. The tool validates the target against the live roster, prefixes the sender's `Message from π€ <friendly name> (@<handle>):` attribution automatically, and delivers into the teammate's canonical Bot Chat. Delivery is **fire-and-forget**: the sender gets a *dispatch* acknowledgement (`status: queued` plus a `delivery_id` β and a `process_id` for the background delivery process β means the message was handed to that process, not that it was delivered), finishes its turn, and that process's completion notification carries the outcome β the reply, or the delivery failure. The message travels as a real parameter (nothing shell-interpreted β quotes, `$(...)`, and backticks arrive verbatim), and the Bot composes its own message rather than forwarding your words. The teammate roster β names **and roles** from each profile's title/description β is part of every Bot Chat's system prompt, so Bots know who does what before choosing a recipient. The tool exists **only** in canonical Bot Chat sessions on Bot-Mode-managed installs; regular chats, group-room member sessions, and CLI sessions never see it.Local messages also reach a Bot Chat that stays open in Desktop or the TUI. The receiving backend keeps ownership: it reads durable ingress on its existing notification poller, admits immediately when idle, or waits until the running turn and already queued human prompts finish. A `queued` acknowledgement confirms durable admission, **not** a completed reply. The target profile retains the delivery ID and receipt under `runtime/bot_live_delivery/`; `settled` confirms completion. A crashed or cancelled imported turn is not automatically replayed, and pending work pinned to a departed owner remains inspectable rather than being silently rerun. Do not resend a delivery whose outcome is unknown. Older backends without live-delivery capability retain the existing ownership refusal; restart that backend after upgrading.