The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bot-mode): non-push senders get the poll ack on the live-owner branch too, and the reply is persisted as a delivery row
teknium1a6ac73a02711
diff --git a/tests/tools/test_bot_mode_dm.py b/tests/tools/test_bot_mode_dm.pyindex 6c3873a2c68..e577bab6549 100644--- a/tests/tools/test_bot_mode_dm.py+++ b/tests/tools/test_bot_mode_dm.py@@ -1189,3 +1189,65 @@ def test_ack_names_poll_return_path_when_session_cannot_receive_completions(tmp_assert result["reply_delivery"] == "poll"assert "completion notification carries" not in result["detail"]assert "process(action='wait', session_id='proc_np1')" in result["detail"]+ assert "if wait returns status=timeout, call wait again" in result["detail"]+++def test_live_owner_ack_carries_the_poll_return_path_when_session_cannot_receive_completions(tmp_path, monkeypatch):+ """#101142 sibling: a live-owner (Desktop) target still runs the same tracked runner whose+ stdout carries the reply. On a non-push sender the live-owner ack must propagate+ ``reply_delivery="poll"`` and the wait instruction instead of 'finish your turn'."""+ from tools import bot_live_delivery as live+ import tools.terminal_tool as terminal_tool_module++ home = _managed_home(tmp_path)+ target = home / "profiles" / "researcher"+ owner = dict(profile_home=str(target), session_id="bot", lease_id="lease", live_session_id="live")+ monkeypatch.setattr(live, "find_canonical_live_owner", lambda h: owner if Path(h) == target else None)+ monkeypatch.setattr(bot_mode_dm, "_dm_dir", lambda: tmp_path)+ monkeypatch.setattr(terminal_tool_module, "terminal_tool", lambda command, **kw: json.dumps({+ "output": "Background process started", "session_id": "proc_np2", "notify_on_complete": False}))++ result = json.loads(bot_mode_dm.message_agent_tool("researcher", "hello", agent=_FakeAgent(home)))+ assert result["status"] == "queued"+ assert result["process_id"] == "proc_np2"+ assert result["reply_delivery"] == "poll"+ assert "process(action='wait', session_id='proc_np2')" in result["detail"]+ assert "finish your turn" not in result["detail"].lower()+++def test_poll_reply_is_persisted_as_a_delivery_row_when_the_runner_exits(tmp_path, monkeypatch):+ """#101142 durable leg: with no completion notification the sender may end its turn without+ polling; the tracked runner's exit must still land the reply in the sender's session transcript+ as a DELIVERY row (``display_kind=process_complete``), so nothing is silently lost."""+ import tools.terminal_tool as terminal_tool_module+ from tools.process_registry import process_registry++ reply = json.dumps({"status": "settled", "reply": "PAYLOAD_SENTINEL_42", "delivery_id": "d1"})+ procs = []++ def fake_terminal_tool(command, **kw):+ popen = subprocess.Popen([sys.executable, "-c", f"import json; print({reply!r})"],+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)+ procs.append(process_registry.adopt_local(popen, command=command, cwd=str(tmp_path), notify_on_complete=False))+ return json.dumps({"output": "Background process started", "session_id": procs[-1].id,+ "notify_on_complete": False})++ monkeypatch.setattr(terminal_tool_module, "terminal_tool", fake_terminal_tool)+ home = _managed_home(tmp_path, teammates=("researcher",))+ agent = _FakeAgent(home, title="Bot Chat")+ rows = []+ agent._session_db.append_message = lambda session_id, role, **kw: rows.append((session_id, role, kw)) or 1++ result = json.loads(bot_mode_dm.message_agent_tool(target="researcher", message="hi", agent=agent))+ assert result["reply_delivery"] == "poll"+ assert "transcript" in result["detail"]+ deadline = time.monotonic() + 10+ while not rows and time.monotonic() < deadline:+ time.sleep(0.05)+ assert len(rows) == 1+ session_id, role, kw = rows[0]+ assert (session_id, role) == ("sess-1", "user")+ assert kw["display_kind"] == "process_complete"+ assert "PAYLOAD_SENTINEL_42" in kw["content"]+ assert procs[0].id in kw["content"]+ assert kw["display_metadata"]["display_text"].startswith("Background Process Finished")diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.pyindex 18029a86720..2d49db65b82 100644--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@ -26,6 +26,7 @@ import statimport subprocessimport sysimport tempfile+import threadingimport timefrom pathlib import Pathfrom typing import Any, Optional@@ -73,7 +74,8 @@ def message_agent_tool_schema() -> dict:"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 "+ "delivery failure — unless the ack returns reply_delivery=\"poll\", in which case "+ "follow its process(action=\"wait\") instruction before ending the turn. COMPOSE the message yourself: write what YOU want to say to ""that agent (lead with the point; include the concrete ask or result). ""Never paste the user's words verbatim — paraphrase the actionable ""substance, and keep private 1:1 chat content private. Message one "@@ -611,6 +613,11 @@ def _start_delivery(argv: list[str], content: str, label: str, *, stdin_file: boresult["notification_error"] = notification["error"]elif notification.get("process_id"):result["process_id"] = notification["process_id"]+ result["reply_delivery"] = notification.get("reply_delivery", "notification")+ if result["reply_delivery"] == "poll":+ # Same runner, same stdout-borne reply (#101142): a non-push sender must get+ # the poll instruction here too, not 'finish your turn'.+ result["detail"] = f"Durably queued for the live Bot Chat owner. Do NOT resend. {notification['detail']}"return json.dumps(result)try:command = _delivery_command(argv, dm_file, stdin_file=stdin_file, profile_home=profile_home, author=author)@@ -658,7 +665,11 @@ def _spawn_delivery(command: str, label: str, *, dm_file: Optional[str] = None,"cannot receive completion notifications, so the reply will NOT arrive on its own. "f"Before ending your turn, retrieve the outcome with process(action='wait', "f"session_id='{proc_id}') — its output is the reply (relay it, attributed to that "- "agent) or the delivery failure (report it; the message was NOT delivered).")+ "agent) or the delivery failure (report it; the message was NOT delivered); "+ "if wait returns status=timeout, call wait again until the process exits.")+ if _persist_reply_when_done(proc_id, agent):+ detail += (" Its outcome is also saved into this session's transcript as a delivery row "+ "when the process exits, so it survives even if the turn ends first.")else: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. "@@ -682,6 +693,42 @@ def _spawn_delivery(command: str, label: str, *, dm_file: Optional[str] = None,_unlink_dm_file(dm_file)+def _persist_reply_when_done(proc_id: str, agent: Any) -> bool:+ """#101142 durable leg. A non-push sender (api_server, one-shot runner) gets no completion+ notification, so once the tracked runner exits its stdout — the recipient's reply or the+ delivery failure — is appended to the sender's session transcript as a DELIVERY row+ (``display_kind="process_complete"``, the shape push surfaces persist for the same+ completion; mirrors gateway.wake.persist_delegation_delivery). A sender that already read+ the outcome via process(action='wait'/'log') is not told twice. Returns False (nothing+ armed) when the sender has no session transcript or the process is not tracked here."""+ from tools.process_registry import process_registry++ db, session_id = getattr(agent, "_session_db", None), getattr(agent, "session_id", None)+ proc = process_registry.get(proc_id)+ if proc is None or not session_id or not callable(getattr(db, "append_message", None)):+ return False++ def _run() -> None:+ from tools.process_registry_notifications import (+ format_process_notification, process_completion_display_text,+ )++ proc._completion_event.wait()+ if process_registry.is_completion_consumed(proc_id):+ return+ evt = {"type": "completion", "session_id": proc_id, **process_registry._exit_snapshot(proc, "exited")}+ try:+ db.append_message(session_id, "user", content=format_process_notification(evt),+ display_kind="process_complete",+ display_metadata={"display_text": process_completion_display_text([evt])})+ except Exception as exc:+ logger.warning("message_agent: could not persist the reply of %s into session %s: %s",+ proc_id, session_id, exc)++ threading.Thread(target=_run, name=f"message-agent-reply-{proc_id}", daemon=True).start()+ return True++def _delivery_main(args: list[str]) -> int:"""Runner entry for the argv ``_delivery_command`` builds. Malformed argv exits 2 without touching the DM file."""if not args or args[0] != "--run-delivery":