Skip to content

The agent that grows with you

fix(tools): dial the Bot DM authority from a loop-hosting thread and classify pre-dial deaths

liuhao102421fe9a06808e
diff --git a/tests/tools/test_bot_legacy_producer.py b/tests/tools/test_bot_legacy_producer.py
index e32e212628a..0cea065e57b 100644
--- a/tests/tools/test_bot_legacy_producer.py
+++ b/tests/tools/test_bot_legacy_producer.py
@@ -1,11 +1,11 @@
"""A stale owner advertisement must never create another execution queue."""
import pytest
-from tools.bot_live_delivery import deliver_to_live_owner
+from tools.bot_live_delivery import PreDialError, deliver_to_live_owner
def test_legacy_owner_requires_a_live_authority_before_admission(tmp_path):
owner = dict(profile_home=str(tmp_path), session_id='legacy', lease_id='dead', live_session_id='old-ui')
- with pytest.raises(ValueError, match='authority'):
+ with pytest.raises(PreDialError, match='authority'):
deliver_to_live_owner(tmp_path, owner, 'message', delivery_id='e' * 32)
assert not (tmp_path / 'runtime' / 'bot_live_delivery' / ('e' * 32 + '.json')).exists()
diff --git a/tests/tools/test_bot_live_owner_delivery.py b/tests/tools/test_bot_live_owner_delivery.py
index 61968e12a35..1191f386e01 100644
--- a/tests/tools/test_bot_live_owner_delivery.py
+++ b/tests/tools/test_bot_live_owner_delivery.py
@@ -326,6 +326,45 @@ def test_authority_delivery_dials_from_a_thread_with_a_running_loop(tmp_path, mo
async def tool_call_on_loop():
return mailbox.authority_delivery(tmp_path, {"id": "0" * 64, "message": "probe"})
- with pytest.raises(ValueError, match="profile authority is not ready"):
+ with pytest.raises(mailbox.PreDialError, match="profile authority is not ready"):
asyncio.run(tool_call_on_loop())
assert probed == [tmp_path.resolve()]
+
+
+def _spy_dm_files(bot_mode_dm, monkeypatch):
+ dm_files = []
+ real_write = bot_mode_dm._write_dm_file
+
+ def spy_write(content):
+ path = real_write(content)
+ dm_files.append(path)
+ return path
+
+ monkeypatch.setattr(bot_mode_dm, "_write_dm_file", spy_write)
+ return dm_files
+
+
+def test_pre_dial_failure_is_a_definite_no_send_not_ambiguous(tmp_path, monkeypatch):
+ """#139303: a dial that dies before ``bot_relay.deliver`` reached the socket admits
+ nothing — the pinned intent is dropped and the sender hears 'safe to resend',
+ instead of the old 'ambiguous / do not resend' that stranded the DM."""
+ from tools import bot_live_delivery as live
+ from tools import bot_mode_dm
+
+ def refused(home, params):
+ raise live.PreDialError("dial refused before the RPC went out")
+
+ monkeypatch.setattr(live, "find_canonical_live_owner", lambda home: _owner(tmp_path))
+ monkeypatch.setattr(live, "authority_delivery", refused)
+ dm_files = _spy_dm_files(bot_mode_dm, monkeypatch)
+
+ payload = json.loads(bot_mode_dm._start_delivery(
+ ["hermes", "-p", "researcher"], "hello", "@researcher",
+ stdin_file=False, task_id=None, agent=None, profile_home=tmp_path))
+
+ assert payload["reason"] == "runtime_unavailable"
+ assert "safe to resend" in payload["error"]
+ assert "Do not resend" not in payload["error"]
+ dm_file = Path(dm_files[0])
+ assert not dm_file.exists() # nothing was admitted: no evidence to retain
+ assert not Path(str(dm_file) + ".live.json").exists() # the pinned intent can never settle
diff --git a/tools/bot_live_delivery.py b/tools/bot_live_delivery.py
index ea22bf2996c..b98c2f4f07d 100644
--- a/tools/bot_live_delivery.py
+++ b/tools/bot_live_delivery.py
@@ -62,6 +62,12 @@ def find_canonical_live_owner(profile_home: Path | str) -> dict[str, Any] | None
lease_id=discovery.endpoint.instance_id, live_session_id=tip or '')
+class PreDialError(RuntimeError):
+ """The authority call died before its RPC reached the socket: nothing was admitted, so
+ this is a definite no-send the sender may safely retry — never the ambiguous
+ post-admission state that orders 'do not resend' (#139303)."""
+
+
def authority_delivery(home, params):
"""Call only this home's already-running authority; never start a fallback."""
return _authority_rpc(home, 'bot_relay.deliver', params)
@@ -80,8 +86,10 @@ def _authority_rpc(home, method, params):
from websockets.asyncio.client import connect
home = Path(home).resolve()
+ rpc_started = False
async def request():
+ nonlocal rpc_started
discovery = await asyncio.to_thread(discover_gateway_endpoint, home, timeout=5)
if discovery.state != 'ready' or discovery.endpoint is None:
raise ValueError('profile authority is not ready')
@@ -93,16 +101,22 @@ def _authority_rpc(home, method, params):
if ws.subprotocol != GATEWAY_WS_PROTOCOL:
raise ValueError('authority protocol mismatch')
async with GatewayClient(ws) as client:
+ rpc_started = True # the RPC is going out: past here a failure may have been admitted
return await client.rpc(method, **params)
try:
- asyncio.get_running_loop()
- except RuntimeError:
- return asyncio.run(request())
- # A gateway-hosted tool call runs on a thread with a live loop, where asyncio.run() raises
- # before anything is dialed and message_agent misreports the DM as ambiguous (#139303).
- from model_tools import _run_async
- return _run_async(request())
+ try:
+ asyncio.get_running_loop()
+ except RuntimeError:
+ return asyncio.run(request())
+ # A gateway-hosted tool call runs on a thread with a live loop, where asyncio.run() raises
+ # before anything is dialed (#139303).
+ from model_tools import _run_async
+ return _run_async(request())
+ except Exception as exc:
+ if not rpc_started:
+ raise PreDialError(str(exc)) from exc
+ raise
def _owner(home: Path | str, owner: dict[str, Any]) -> dict[str, str]:
diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.py
index 1b18e55c905..30258e6f131 100644
--- a/tools/bot_mode_dm.py
+++ b/tools/bot_mode_dm.py
@@ -434,8 +434,10 @@ def _dm_delivery_id(dm_file: str | os.PathLike) -> str:
class LiveTargetUnavailableError(RuntimeError):
- """No canonical Bot Chat owner was found BEFORE any intent was pinned: nothing was admitted, so
- this is a definite no-send the sender may retry, not the ambiguous post-admission state."""
+ """The canonical Bot Chat owner could not be reached with anything admitted — before the
+ intent was pinned, or on a dial that died before the deliver RPC went out: nothing was
+ sent, so this is a definite no-send the sender may retry, not the ambiguous
+ post-admission state."""
reason = "runtime_unavailable"
resend = "once the target is up"
@@ -483,7 +485,8 @@ def _held_disposition(record: dict | None) -> bool:
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
+ from tools.bot_live_delivery import (PreDialError, deliver_to_live_owner, find_canonical_live_owner,
+ read_delivery_result)
from utils import fsync_directory
intent: dict[str, Any]
@@ -528,6 +531,12 @@ def _admit_live_dm(profile_home: Path | None, dm_file: str, author: Optional[dic
# Nothing was admitted while that refusal held the owner's lock, but a same-id attempt
# may have admitted since: only the owner's settle decides, under that same lock.
record = settle_held_delivery(home, intent["owner"], intent["message"], **identity)
+ except PreDialError as exc:
+ # The dial died before bot_relay.deliver reached the socket: nothing was admitted
+ # and this intent can never settle, so drop it and report the definite no-send
+ # the sender may retry (#139303).
+ _unlink_dm_file(_live_intent_file(dm_file))
+ raise LiveTargetUnavailableError(f"live authority dial failed before admission ({exc})") from exc
if _held_disposition(record):
# The callers remove the intent and payload (``_settled_no_send``).
raise LiveTargetHeldError("Bot Chat is held by another session writer")