The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: refuse Bot delivery instead of starting a competing runtime
Teknium03f5d8438efa
diff --git a/tests/tools/test_bot_no_fallback.py b/tests/tools/test_bot_no_fallback.pynew file mode 100644index 00000000000..ba1694aa846--- /dev/null+++ b/tests/tools/test_bot_no_fallback.py@@ -0,0 +1,25 @@+"""Unavailable authority is a refusal, never permission for another executor."""+import json+++def test_local_dm_cannot_fall_back_to_a_cli_turn(tmp_path, monkeypatch, capsys):+ from tools import bot_mode_dm as dm+ payload = tmp_path / 'dm.txt'+ payload.write_text('private DM')+ calls = []+ monkeypatch.setattr(dm, '_run_local_turn', lambda *args: calls.append(args) or 0)+ monkeypatch.setattr(dm, '_local_delivery_home', lambda argv: None)+ assert dm._run_delivery(['hermes', '-p', 'missing'], str(payload), stdin_file=False) == 1+ assert calls == []+ assert json.loads(capsys.readouterr().out)['reason'] == 'runtime_unavailable'+ assert payload.read_text() == 'private DM'+++def test_legacy_relay_requires_identity_without_spawning(monkeypatch, tmp_path):+ import tui_gateway.server as srv+ calls = []+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ monkeypatch.setattr('subprocess.run', lambda *a, **kw: calls.append(a))+ result = srv._methods['bot_relay.deliver'](1, {'profile': 'default', 'message': 'hello'})+ assert result['error']['data']['reason'] == 'invalid_params', result+ assert calls == []diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.pyindex f252deaf08b..0171cf2be5e 100644--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@ -488,10 +488,11 @@ def _run_delivery(argv: list[str], dm_file: str, *, stdin_file: bool,return 1if record is not None:return _wait_live_dm(record["profile_home"], record["delivery_id"])+ if not stdin_file:+ print(json.dumps({"reason": "runtime_unavailable", "error": "No canonical Bot Chat authority; payload retained."}))+ return 1try:with _delivery_lock(argv, stdin_file=stdin_file):- if not stdin_file:- return _run_local_turn(argv, dm_file)# Keep the file open until the transport exits; cleanup occurs# after subprocess.run returns, not merely after stdin reaches EOF.with open(dm_file, "r", encoding="utf-8") as stream:diff --git a/tui_gateway/methods_bot_relay.py b/tui_gateway/methods_bot_relay.pyindex df11a0db724..434a23408e1 100644--- a/tui_gateway/methods_bot_relay.py+++ b/tui_gateway/methods_bot_relay.py@@ -7,7 +7,6 @@ the SENDER gateway for its waiter). Plumbing: ``tools/bot_relay.py``; handlers aserver.py's globals (method_ctx.py) and reference ``_ok``/``_err`` bare."""import os-import subprocessfrom pathlib import Pathfrom .method_ctx import HandlerRegistry@@ -29,13 +28,6 @@ TURN_ATTEMPT_TIMEOUT_SECONDS = 600TURN_MAX_ATTEMPTS = 2 # first attempt + the policy-gated re-run-def _run_delivery(profile: str, tmp: str) -> subprocess.CompletedProcess:- from tools.bot_relay import local_delivery_command- return subprocess.run(- local_delivery_command(profile, tmp), capture_output=True, text=True, encoding="utf-8",- errors="replace", timeout=TURN_ATTEMPT_TIMEOUT_SECONDS)--@method("bot_relay.roster.sync")def _(rid, params: dict, _root=_relay_root) -> dict:"""Replace this gateway's view of agents on OTHER connections → ``{count}`` accepted rows@@ -59,88 +51,24 @@ def _(rid, params: dict, _root=_relay_root) -> dict:@method("bot_relay.deliver")-def _(rid, params: dict, _root=_relay_root, _run=_run_delivery) -> dict:- """Deliver a relayed DM (``profile``, attribution-prefixed ``message``) into a Bot Chat ON THIS- GATEWAY via the one-turn ``hermes -p <profile> chat -c "Bot Chat"`` transport local DMs use →- ``{reply}``. Blocking by design (Desktop relay worker; the RPC pool keeps it off the reader)."""- import tempfile- profile = str(params.get("profile") or "").strip()- message = str(params.get("message") or "").strip()- if not profile or not message:- return _err(rid, 4090, "profile and message required")+def _(rid, params: dict, _root=_relay_root) -> dict:+ """Legacy transport bridge only: canonical admission or an explicit refusal."""+ from tools.bot_live_delivery import _delivery_id, authority_delivery+ from tools.bot_relay import _HANDLE_REtry:- from tools.bot_mode_dm import MESSAGE_MAX_CHARS- from tools.bot_relay import acquire_turn_lock- if len(message) > MESSAGE_MAX_CHARS + 200: # + attribution headroom- return _err(rid, 4091, "message too long")- root = _root()- known = {"default"}- if (root / "profiles").is_dir():- known.update(c.name for c in (root / "profiles").iterdir() if c.is_dir())- resolved = "default" if profile.lower() == "hermes" else profile- if resolved not in known:- return _err(rid, 4092, f"no profile '{profile}' on this gateway")-- # When THIS gateway already hosts the target's Bot Chat live, the subprocess transport is- # fenced out by the single-owner lease and the payload dropped. Land the DM in the live- # session via prompt.submit — the composer's choke point, so role alternation, persistence- # and streaming behave as a typed message would.- # (Nested per method_ctx rebinding.) See #100523.- from tools.bot_mode_probe import BOT_CHAT_TITLE- live_home = _profile_home(resolved)- want_home = str(live_home) if live_home is not None else None- live_sid = next((- live_sid for live_sid, record in list(_sessions.items())- if isinstance(record, dict) and (record.get("profile_home") or None) == want_home- and _session_live_title(- record, _session_lookup_key(record, fallback=live_sid)) == BOT_CHAT_TITLE), "")- if live_sid:- # queued=True: a teammate's DM runs as the NEXT turn and never interrupts or steers a- # turn in flight (the default busy mode does); arrivals queue in order.- submitted = _methods["prompt.submit"](rid, {"session_id": live_sid, "text": message, "queued": True})- if "error" in submitted:- return submitted- reply = f"Delivered into @{resolved}'s open Bot Chat; the reply will appear there."- return _ok(rid, {"reply": reply})-- def _detail(p) -> str:- return (p.stderr or p.stdout or "").strip()[-500:]-- fd, tmp = tempfile.mkstemp(prefix="hermes-relay-dm-", suffix=".txt", text=True)- try:- with os.fdopen(fd, "w", encoding="utf-8") as f:- f.write(message)- # Per-profile turn lock serializes with any other delivery turn into this profile and- # covers only the turn window. Worst-case hold is lock wait (bot_mode.turn_wait_seconds,- # default 120s) + the 600s turn timeout, doubled on one retry — callers tolerate ~1320s.- # Worst-case handler hold is lock wait (bot_mode.turn_wait_seconds, default 120s) + the 600s- # turn timeout below — doubled when the retry policy grants one bounded re-run — so clients- # calling bot_relay.deliver must tolerate ~1320s before assuming failure. See #93091.- with acquire_turn_lock(root, resolved):- proc = _run(resolved, tmp)- if proc.returncode != 0:- # Retry policy: transient classes re-run the SAME session once; context_overflow- # too — the retried turn's pre-API compaction pass compacts the over-threshold- # transcript first (no fresh session is minted). Auth/quota/config never retry.- # See #93091.- from tools.bot_failure_reasons import (- RETRY_NONE, classify_agent_error, retry_action)- if retry_action(classify_agent_error(_detail(proc))) != RETRY_NONE:- proc = _run(resolved, tmp)- finally:- with contextlib.suppress(OSError):- os.unlink(tmp)- if proc.returncode != 0:- from tools.bot_failure_reasons import classify_agent_error- detail = _detail(proc)- return _err(rid, 5092, f"delivery turn failed: {detail or proc.returncode}",- data={"reason": classify_agent_error(detail)})- return _ok(rid, {"reply": (proc.stdout or "").strip()})- except subprocess.TimeoutExpired:- return _err(rid, 5093, "delivery turn timed out")- except Exception as e:- # 'target_busy' extends the structured refusal enum.- return _err(rid, 5096 if getattr(e, "reason", "") == "target_busy" else 5094, str(e))+ _delivery_id(params.get('id'))+ profile = params.get('profile')+ if not isinstance(profile, str) or not _HANDLE_RE.fullmatch(profile):+ raise ValueError('invalid profile')+ except ValueError:+ return _err(rid, 4090, 'invalid_params', data={'reason': 'invalid_params'})+ resolved = 'default' if profile == 'hermes' else profile+ root = _root()+ home = root if resolved == 'default' else root / 'profiles' / resolved+ try:+ return _ok(rid, authority_delivery(home, {**params, 'profile': resolved}))+ except Exception as exc:+ return _err(rid, 5094, str(exc), data={'reason': 'runtime_unavailable'})@method("bot_relay.reply")