The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bot-mode): a teammate's reply reaches the sender whole, and a cut completion says so
John Paul Solivaeccc9ab49a95
diff --git a/tests/tools/test_bot_mode_dm.py b/tests/tools/test_bot_mode_dm.pyindex e577bab6549..56b1b7f8c63 100644--- a/tests/tools/test_bot_mode_dm.py+++ b/tests/tools/test_bot_mode_dm.py@@ -284,6 +284,8 @@ def test_local_delivery_command_and_ack(tmp_path, monkeypatch):assert call["background"] is Trueassert call["notify_on_complete"] is Trueassert call["_host_local"] is True+ # The completion notification IS the reply: sized like a message, not a build log's 2000-char tail.+ assert call["_completion_output_chars"] == bot_mode_dm.REPLY_COMPLETION_CHARS == bot_mode_dm.MESSAGE_MAX_CHARS + 2000assert Path(call["workdir"]) == Path(bot_mode_dm.__file__).resolve().parent.parentcommand = call["command"]mode, dm_file, transport_argv = _runner_parts(command)diff --git a/tests/tools/test_notify_on_complete.py b/tests/tools/test_notify_on_complete.pyindex 27817cc4bf5..c1f423d0ee1 100644--- a/tests/tools/test_notify_on_complete.py+++ b/tests/tools/test_notify_on_complete.py@@ -108,6 +108,23 @@ class TestCompletionQueue:completion = registry.completion_queue.get_nowait()assert len(completion["output"]) == 2000+ # A consumer that relays the output must know it is not whole.+ assert completion["output_cut"] == 3000++ def test_completion_output_is_sized_per_process(self, registry):+ """A spawner whose output IS the payload (a bot DM's reply, tools/bot_mode_dm.py) asks for a+ larger completion; the tail cap stays the default for everything else, and a completion+ that carries the whole output declares no cut."""+ s = _make_session(notify_on_complete=True, output="x" * 5000)+ s.completion_output_chars = 6000+ s.exited, s.exit_code = True, 0+ registry._running[s.id] = s+ with patch.object(registry, "_write_checkpoint"):+ registry._move_to_finished(s)++ completion = registry.completion_queue.get_nowait()+ assert len(completion["output"]) == 5000+ assert "output_cut" not in completiondef test_multiple_completions_queued(self, registry):"""Multiple notify processes all push to the same queue."""@@ -146,6 +163,22 @@ class TestCheckpointNotify:assert len(data) == 1assert data[0]["notify_on_complete"] is True+ def test_checkpoint_round_trips_completion_output_chars(self, registry, tmp_path):+ """A recovered delivery process still reports its reply whole."""+ checkpoint = tmp_path / "procs.json"+ with patch("tools.process_registry.CHECKPOINT_PATH", checkpoint):+ s = _make_session(notify_on_complete=True)+ s.completion_output_chars = 18000+ registry._running[s.id] = s+ registry._write_checkpoint()+ data = json.loads(checkpoint.read_text())+ assert data[0]["completion_output_chars"] == 18000+ data[0].update(pid=os.getpid(), command="sleep 999")+ checkpoint.write_text(json.dumps(data))+ fresh = ProcessRegistry()+ assert fresh.recover_from_checkpoint() == 1+ assert fresh.get(s.id).completion_output_chars == 18000+def test_recover_defaults_false(self, registry, tmp_path):"""Old checkpoint entries without the field default to False."""@@ -192,6 +225,24 @@ class TestTerminalSchema:_, kwargs = mock_tt.call_argsassert kwargs["notify_on_complete"] is True+ def test_completion_output_chars_reaches_the_spawner(self):+ """terminal_tool's internal ``_completion_output_chars`` is handed to spawn_background_process."""+ from tools import terminal_tool as tt+ with patch("tools.terminal_tool.spawn_background_process", return_value='{"ok":true}') as spawn:+ tt.terminal_tool("echo hi", background=True, notify_on_complete=True, task_id="t1",+ _host_local=True, _completion_output_chars=18000)+ assert spawn.call_args.kwargs["completion_output_chars"] == 18000++ def test_cut_completion_says_so_and_points_at_the_log(self):+ """The rendered notice names the cut and the process log; a whole output renders as before."""+ from tools.process_registry_notifications import format_process_notification+ base = {"type": "completion", "session_id": "proc_abc", "command": "hermes peer dm mini",+ "exit_code": 0, "output": "Reply from mini:\ntail"}+ cut = format_process_notification({**base, "output_cut": 3000})+ assert "first 3000 characters cut" in cut and 'process(action="log", session_id="proc_abc")' in cut+ assert cut.endswith("Reply from mini:\ntail]")+ assert "cut" not in format_process_notification(base)+# =========================================================================# Code execution blocked paramsdiff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.pyindex 4a761678cc0..2c753fcba0a 100644--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@ -41,6 +41,9 @@ MESSAGE_AGENT_TOOL_NAME = "message_agent"# Message body cap — generous for real work, small enough that a runaway paste can't# turn one DM into a context bomb on the recipient.MESSAGE_MAX_CHARS = 16000+# The delivery process's completion notification IS the reply: size it like a message, plus the+# runner's header and failure prose, instead of the 2000-char tail a build log gets.+REPLY_COMPLETION_CHARS = MESSAGE_MAX_CHARS + 2000# A runner owns and removes each DM file; this bounds residual plaintext lifetime if# the machine dies between spawn ack and the runner's finally._DM_DIR_NAME = "hermes-dm"@@ -639,7 +642,8 @@ def _spawn_delivery(command: str, label: str, *, dm_file: Optional[str] = None,from tools.terminal_tool import terminal_toolraw = terminal_tool(command, background=True, notify_on_complete=True, task_id=task_id,- workdir=str(Path(__file__).resolve().parent.parent), _host_local=True)+ workdir=str(Path(__file__).resolve().parent.parent), _host_local=True,+ _completion_output_chars=REPLY_COMPLETION_CHARS)try:parsed = json.loads(raw)except (ValueError, TypeError):diff --git a/tools/process_registry.py b/tools/process_registry.pyindex d300eaed215..8706f5a63d4 100644--- a/tools/process_registry.py+++ b/tools/process_registry.py@@ -51,6 +51,9 @@ def _checkpoint_path() -> Path:return CHECKPOINT_PATH if CHECKPOINT_PATH != _CHECKPOINT_PATH_AT_IMPORT else get_hermes_home() / "processes.json"MAX_OUTPUT_CHARS = 200_000 # rolling output buffer+# Tail of the output a completion notification carries. Right for a build log; a spawner whose+# output IS the payload (a bot DM's reply) asks for more per process (completion_output_chars).+COMPLETION_OUTPUT_CHARS = 2000FINISHED_TTL_SECONDS = 1800 # keep finished processes 30 minutesMAX_PROCESSES = 64 # max tracked processes (LRU pruning)@@ -519,6 +522,7 @@ class ProcessSession:# session was closed at a user boundary (/new) instead of injecting into the NEW one.parent_session_id: str = ""notify_on_complete: bool = False # Queue agent notification on exit+ completion_output_chars: int = 0 # Output chars the completion carries; 0 = COMPLETION_OUTPUT_CHARSwatch_patterns: List[str] = field(default_factory=list)_watch_hits: int = field(default=0, repr=False) # total matches delivered_watch_suppressed: int = field(default=0, repr=False) # matches dropped by rate limit@@ -558,7 +562,7 @@ _CHECKPOINT_FIELDS = ("command", "pid", "pid_scope", "host_start_time", "systemd_unit", "cwd","started_at", "task_id", "owner_task_id", "session_key",*(f"watcher_{k}" for k in _WATCHER_ROUTE_KEYS), "watcher_interval",- "parent_session_id", "notify_on_complete", "watch_patterns")+ "parent_session_id", "notify_on_complete", "completion_output_chars", "watch_patterns")_CHECKPOINT_DEFAULTS = {f.name: ([] if f.name == "watch_patterns" else f.default)for f in ProcessSession.__dataclass_fields__.values()@@ -1447,6 +1451,8 @@ class ProcessRegistry(ProcessCheckpointMixin):self._release_finished_handles(session)self._write_checkpoint()if was_running and session.notify_on_complete:+ limit = session.completion_output_chars or COMPLETION_OUTPUT_CHARS+ cut = len(session.output_buffer) - limitnotification = {"type": "completion","session_id": session.id,@@ -1456,7 +1462,9 @@ class ProcessRegistry(ProcessCheckpointMixin):"command": session.command,**({"handoff_note": session.handoff_note} if session.handoff_note else {}),**self._exit_fields(session),- "output": _output_tail(session, 2000),+ "output": _output_tail(session, limit),+ # A consumer that relays the output (a bot DM's reply) must know it is not whole.+ **({"output_cut": cut} if cut > 0 else {}),# Stable producer identity across checkpoint recovery (unlike a# consumer-observed completion timestamp)."started_at": session.started_at,diff --git a/tools/process_registry_notifications.py b/tools/process_registry_notifications.pyindex d7d9e47c0b3..e6ebb1b5925 100644--- a/tools/process_registry_notifications.py+++ b/tools/process_registry_notifications.py@@ -415,6 +415,10 @@ def format_process_notification(evt: dict) -> "str | None":"...(output trimmed — subagent-owned process; see the ""delegation's live transcript for full output)\n"+ _out[-600:])+ elif evt.get("output_cut"):+ # Say so where the output is the payload (a teammate's reply): a silent tail reads as whole.+ _out = (f"...(first {evt['output_cut']} characters cut — process(action=\"log\", "+ f"session_id=\"{_sid}\") has the full output)\n{_out}")return (f"[IMPORTANT: Background process {_sid} {_completion_status(evt)} (exit code {_exit}{_signal}).\n"f"{attribution}Command: {_cmd}\nOutput:\n{_out}]")diff --git a/tools/terminal_tool.py b/tools/terminal_tool.pyindex a8f354bc19a..0fd053439ce 100644--- a/tools/terminal_tool.py+++ b/tools/terminal_tool.py@@ -1233,6 +1233,7 @@ def terminal_tool(notify_on_complete: bool = False,watch_patterns: Optional[List[str]] = None,_host_local: bool = False,+ _completion_output_chars: int = 0,) -> str:"""Execute *command* in the configured terminal environment; returns a JSON string.@@ -1244,6 +1245,8 @@ def terminal_tool(is hard rate-limited (1 notification / 15s / process) and auto-disabledafter repeated strikes or a lifetime cap, promoting to notify_on_complete —use it only for rare one-shot signals on long-lived processes.+ ``_completion_output_chars`` (internal) sizes the completion notification's output for a+ spawner whose output is the payload (a bot DM's reply); 0 keeps the usual tail.``_host_local`` forces the local backend for Hermes-owned control-planechildren (kept in a separate env cache from the configured backend)."""@@ -1308,6 +1311,7 @@ def terminal_tool(effective_pty=pty and not pty_disabled, notify_on_complete=notify_on_complete,watch_patterns=watch_patterns, approval_note=verdict.note,pty_disabled_reason=_PTY_DISABLED_REASON if pty_disabled else None,+ completion_output_chars=_completion_output_chars,)if plan.promoted_from_foreground_timeout is not None:result = _with_promoted_note(result, plan.promoted_from_foreground_timeout)diff --git a/tools/terminal_tool_background.py b/tools/terminal_tool_background.pyindex 63ebd8f2b49..7ec5b735846 100644--- a/tools/terminal_tool_background.py+++ b/tools/terminal_tool_background.py@@ -142,6 +142,7 @@ def spawn_background_process(*, command: str, env: Any, env_type: str, effective_task_id: str, task_id: Optional[str],session_key: str, workdir: Optional[str], cwd: str, effective_pty: bool,notify_on_complete: bool, watch_patterns: Optional[List[str]], approval_note: Optional[str],+ completion_output_chars: int = 0,pty_disabled_reason: Optional[str],) -> str:"""Spawn *command* as a tracked background process and return the JSON result.@@ -187,6 +188,8 @@ def spawn_background_process(if notify_on_complete:proc_session.notify_on_complete = Trueresult_data["notify_on_complete"] = True+ if completion_output_chars:+ proc_session.completion_output_chars = int(completion_output_chars)if proc_session.watcher_platform:_register_completion_watcher(process_registry, proc_session, session_key)from agent.delegation_context import is_delegated_child_contextdiff --git a/website/docs/user-guide/bot-mode.md b/website/docs/user-guide/bot-mode.mdindex cc88f1292e8..ebe846c21b8 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: 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. On surfaces that cannot receive completion notifications (an `api_server` session, one-shot runners) the acknowledgement instead carries `reply_delivery: poll`: the sender retrieves the outcome with `process(action="wait", session_id=…)` before ending its turn, and the outcome is also saved into the sender's session transcript as a delivery row when the process exits, so the reply is never silently lost. 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. On surfaces that cannot receive completion notifications (an `api_server` session, one-shot runners) the acknowledgement instead carries `reply_delivery: poll`: the sender retrieves the outcome with `process(action="wait", session_id=…)` before ending its turn, and the outcome is also saved into the sender's session transcript as a delivery row when the process exits, so the reply is never silently lost. The notification carries the reply whole up to the message size limit (16,000 characters); a longer one arrives as its tail and says how much was cut (`process(action="log", session_id=…)` has the rest). 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.