Skip to content

The agent that grows with you

fix(bot-mode): preserve refusal reasons across local delivery

Teknium549e6aab38c4
diff --git a/cli.py b/cli.py
index 33cbc39c049..3ab970a7b97 100644
--- a/cli.py
+++ b/cli.py
@@ -2956,7 +2956,7 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin, CLITuiMix
if self._active_session_lease is not None:
return True
try:
- from hermes_cli.active_sessions import try_acquire_active_session
+ from hermes_cli.active_sessions import format_refusal_stderr, try_acquire_active_session
lease, message = try_acquire_active_session(
session_id=self.session_id,
@@ -2970,7 +2970,7 @@ class HermesCLI(CLIAgentSetupMixin, CLICommandsMixin, CLIBillingMixin, CLITuiMix
logger.warning("Failed to claim active session slot: %s", exc)
return True
if message:
- print(message, file=sys.stderr) if stderr else self._console_print(f"[bold red]{message}[/]")
+ print(format_refusal_stderr(message), file=sys.stderr) if stderr else self._console_print(f"[bold red]{message}[/]")
return False
self._active_session_lease = lease
with suppress(Exception):
diff --git a/hermes_cli/active_sessions.py b/hermes_cli/active_sessions.py
index a7ba1b7074a..a4ddf414ea4 100644
--- a/hermes_cli/active_sessions.py
+++ b/hermes_cli/active_sessions.py
@@ -127,6 +127,12 @@ class ActiveSessionRefusal(str):
return obj
+def format_refusal_stderr(message: str) -> str:
+ """Keep the refusal contract across the one-shot CLI subprocess boundary."""
+ reason = getattr(message, "reason", "")
+ return f"hermes-refusal-reason: {reason}\n{message}" if reason else str(message)
+
+
def _is_same_writer(entry: dict[str, Any], metadata: Optional[dict[str, Any]]) -> bool:
"""True when an existing lease belongs to the very caller re-acquiring it.
Identity is (pid, live_session_id): pid alone lets two live sessions in one process
diff --git a/tests/tools/test_bot_mode_refusal_contract.py b/tests/tools/test_bot_mode_refusal_contract.py
new file mode 100644
index 00000000000..ebd3e29b262
--- /dev/null
+++ b/tests/tools/test_bot_mode_refusal_contract.py
@@ -0,0 +1,31 @@
+import json
+import sys
+from types import SimpleNamespace
+
+from tools import bot_mode_dm
+
+
+def test_delivery_uses_refusal_code_before_human_wording(tmp_path, capsys):
+ for code, message, busy in (
+ ("SESSION_NOT_OWNED", "Ce chat est occupé.", True),
+ ("SESSION_COORDINATION_UNAVAILABLE", "Cannot verify whether session already has a live owner", False),
+ ("SESSION_NOT_OWNED_EXTRA", "Different failure", False),
+ ):
+ dm = tmp_path / "message.txt"
+ dm.write_text("isolated probe", encoding="utf-8")
+ child = tmp_path / "child.py"
+ child.write_text(f"import sys\nprint({f'hermes-refusal-reason: {code}'!r}, file=sys.stderr)\nprint({message!r}, file=sys.stderr)\nraise SystemExit(1)\n", encoding="utf-8")
+ assert bot_mode_dm._run_delivery([sys.executable, str(child)], str(dm), stdin_file=False) == 1
+ output = capsys.readouterr()
+ assert (json.loads(output.out)["reason"] == "target_busy") if busy else not output.out
+ assert not dm.exists()
+
+
+def test_one_shot_cli_preserves_refusal_reason(monkeypatch, capsys):
+ from cli import HermesCLI
+ from hermes_cli import active_sessions
+ refusal = active_sessions.ActiveSessionRefusal("Ce chat est occupé.", reason=active_sessions.SESSION_NOT_OWNED)
+ monkeypatch.setattr(active_sessions, "try_acquire_active_session", lambda **kwargs: (None, refusal))
+ cli = SimpleNamespace(_active_session_lease=None, session_id="isolated", config={})
+ assert not HermesCLI._claim_active_session(cli, stderr=True)
+ assert "hermes-refusal-reason: SESSION_NOT_OWNED\n" in capsys.readouterr().err
diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.py
index 2151b898c0e..c3543c2fc82 100644
--- a/tools/bot_mode_dm.py
+++ b/tools/bot_mode_dm.py
@@ -368,7 +368,15 @@ def _run_local_turn(argv: list[str], dm_file: str) -> int:
if retry_action(classify_agent_error((proc.stderr or proc.stdout or "").strip()[-500:])) != RETRY_NONE:
proc = _turn()
- if proc.returncode != 0 and "already has a live owner" in (proc.stderr or ""):
+ stderr_text = proc.stderr or ""
+ reason = next((line.removeprefix("hermes-refusal-reason: ").strip()
+ for line in stderr_text.splitlines()
+ if line.startswith("hermes-refusal-reason: ")), None)
+ # A code wins over prose, including unknown codes from newer CLIs.
+ # Only older CLIs without a marker need the historical wording fallback.
+ refused_not_owned = (reason == "SESSION_NOT_OWNED" if reason is not None
+ else "already has a live owner" in stderr_text)
+ if proc.returncode != 0 and refused_not_owned:
# The target's Bot Chat is held live by another surface (Desktop); the turn
# never ran — tell the sender plainly instead of leaking a raw lease error.
# See #100523.
diff --git a/website/docs/user-guide/bot-mode.md b/website/docs/user-guide/bot-mode.md
index 0366feb3422..f3d9ffab789 100644
--- a/website/docs/user-guide/bot-mode.md
+++ b/website/docs/user-guide/bot-mode.md
@@ -122,6 +122,11 @@ Bot-to-bot delivery is per-invocation: the receiving Bot picks the message up wh
### Failed turns retry safely
+Local one-shot delivery preserves the active-session refusal code separately from
+its human-readable message. `SESSION_NOT_OWNED` produces `target_busy`; an
+unreadable coordination registry is not mislabeled as another owner. Older local
+CLIs without the code marker still use the historical refusal wording.
+
A failed delivery turn is retried at most once, and only when a retry can actually help. Transient failures (target runtime offline, delivery timeout, provider rate limit or server error) re-run the same Bot Chat session unchanged. A context-overflow failure also re-runs the same session — the retried turn compacts the over-threshold transcript via the standard context-compression pass before calling the model, so the retry fits where the original didn't. Auth, quota, and configuration failures never auto-retry: a second attempt cannot fix them and only burns quota, so the failure is surfaced immediately. A retried turn never starts a fresh session — your Bot Chat history and context stay intact.
### When a delivery fails: typed reasons