Skip to content

The agent that grows with you

fix(approval): withdrawn gateway approval prompts no longer read as a user deny

teknium16332216384b7
diff --git a/tests/tools/test_approval_cancelled_attribution.py b/tests/tools/test_approval_cancelled_attribution.py
new file mode 100644
index 00000000000..6d45a0e9f04
--- /dev/null
+++ b/tests/tools/test_approval_cancelled_attribution.py
@@ -0,0 +1,94 @@
+"""A gateway approval wait that ends without a user answer must not be reported as a user deny.
+
+Teardown paths (a parent's ``delegate_task`` finishing, ``unregister_gateway_notify`` at turn
+end, a ``/stop``) end the wait fail-closed, but the tool result carries ``outcome="cancelled"``
+and the cause instead of "denied by user" (#112026, #22992).
+"""
+import os
+import threading
+
+import pytest
+
+from tools import approval as mod
+from tools import approval_context
+from tools.interrupt import set_interrupt
+
+SESSION_KEY = "test-cancelled-attribution"
+
+
+def gateway_session(monkeypatch):
+ mod._gateway_queues.clear()
+ mod._gateway_notify_cbs.clear()
+ mod._session_approved.clear()
+ for k in ("HERMES_CRON_SESSION", "HERMES_YOLO_MODE", "HERMES_INTERACTIVE"):
+ monkeypatch.delenv(k, raising=False)
+ monkeypatch.setenv("HERMES_GATEWAY_SESSION", "1")
+ monkeypatch.setenv("HERMES_SESSION_KEY", SESSION_KEY)
+ monkeypatch.setattr(approval_context, "_get_approval_config", lambda: {"mode": "manual", "timeout": 60})
+ hooks = []
+ original = approval_context._fire_approval_hook
+ monkeypatch.setattr(approval_context, "_fire_approval_hook",
+ lambda name, **kw: (hooks.append((name, kw)), original(name, **kw)))
+ yield hooks
+ mod._gateway_queues.clear()
+ mod._gateway_notify_cbs.clear()
+
+
+def _run_gate_until_pending():
+ """Start the real command gate on a worker thread and return (thread, tid, result_holder)
+ once the prompt has been handed to the gateway notifier."""
+ notified = threading.Event()
+ mod.register_gateway_notify(SESSION_KEY, lambda _data: notified.set())
+ holder = {}
+
+ def worker():
+ holder["tid"] = threading.get_ident()
+ holder["result"] = mod.check_all_command_guards("rm -rf .git", "local")
+
+ thread = threading.Thread(target=worker)
+ thread.start()
+ assert notified.wait(timeout=5), "approval was never enqueued"
+ return thread, holder
+
+
+def _assert_withdrawn(result, cause):
+ assert result["approved"] is False
+ assert result.get("user_consent") is False
+ assert result["outcome"] == "cancelled"
+ assert "denied by user" not in result["message"].lower()
+ assert cause in result["message"]
+ assert "NOT consented" in result["message"] # still fail-closed for the model
+
+
+def test_teardown_interrupt_reports_cause_not_user_deny(gateway_session):
+ """A delegation teardown raises the child's interrupt bit with a fixed cause; the approval
+ result relays that cause and does not claim the user denied the command."""
+ thread, holder = _run_gate_until_pending()
+ set_interrupt(True, holder["tid"], reason="parent delegation ended")
+ try:
+ thread.join(timeout=10)
+ finally:
+ set_interrupt(False, holder["tid"])
+ assert not thread.is_alive()
+ _assert_withdrawn(holder["result"], "parent delegation ended")
+ posts = [kw for name, kw in gateway_session if name == "post_approval_response"]
+ assert posts[-1]["choice"] == "cancelled"
+ assert not mod.has_blocking_approval(SESSION_KEY)
+
+
+def test_turn_end_unregister_reports_withdrawn_prompt(gateway_session):
+ """``unregister_gateway_notify`` at turn end wakes the wait with no decision: the result is
+ a withdrawn prompt, while an explicit /deny on the same gate still reads as a user deny."""
+ thread, holder = _run_gate_until_pending()
+ mod.unregister_gateway_notify(SESSION_KEY)
+ thread.join(timeout=10)
+ assert not thread.is_alive()
+ _assert_withdrawn(holder["result"], "the turn ended before the prompt was answered")
+
+ thread, holder = _run_gate_until_pending()
+ mod.resolve_gateway_approval(SESSION_KEY, "deny")
+ thread.join(timeout=10)
+ denied = holder["result"]
+ assert denied["outcome"] == "denied"
+ assert "denied by user" in denied["message"]
diff --git a/tests/tools/test_approval_interrupt.py b/tests/tools/test_approval_interrupt.py
index 3db0fcc2d13..23b7f2341d9 100644
--- a/tests/tools/test_approval_interrupt.py
+++ b/tests/tools/test_approval_interrupt.py
@@ -114,7 +114,10 @@ class TestApprovalInterrupt:
elapsed = time.monotonic() - start
assert not t.is_alive(), "approval wait did not return after interrupt"
- assert result_holder["result"] == {"resolved": True, "choice": "deny", "reason": None}
+ result = result_holder["result"]
+ assert (result["resolved"], result["choice"], result["reason"]) == (True, "deny", None)
+ # A bare interrupt bit (no cause published) is still reported as a withdrawn prompt.
+ assert result["cancelled"] == "turn interrupted"
# Must be far below the 300s timeout — the interrupt, not the deadline,
# is what released the wait.
assert elapsed < 10, f"interrupt path too slow ({elapsed:.1f}s)"
diff --git a/tools/approval.py b/tools/approval.py
index cd1a74b085d..29db8b4f748 100644
--- a/tools/approval.py
+++ b/tools/approval.py
@@ -482,6 +482,7 @@ _USER_SUMMARIES = {
"denied": "You denied this {noun} — it did not run.",
"timeout": "No answer within {minutes} — the {noun} did not run.",
"notify_failed": "The approval request could not be delivered — the {noun} did not run.",
+ "cancelled": "The approval prompt was withdrawn before you answered — the {noun} did not run.",
"blocked": "This {noun} is not allowed in an unattended session — it did not run.",
}
@@ -850,6 +851,12 @@ def _human_decision(spec: _GateSpec, *, command: str, description: str,
# halt — both produce a BLOCKED outcome. ``/deny <reason>`` free text is
# relayed verbatim so the agent can adapt rather than only hearing "denied".
choice, deny_reason = decision["choice"], decision.get("reason")
+ if decision.get("cancelled"):
+ # The prompt was withdrawn (turn interrupted or ended) before anyone answered:
+ # still fail closed, but do not attribute a refusal to the user.
+ return deny(spec.gateway_refused, "cancelled",
+ reason=f"approval was withdrawn before the user answered ({decision['cancelled']})",
+ reason_addendum="", timeout_addendum="", deny_reason=None)
if not decision["resolved"]:
return deny(spec.gateway_refused, "timeout", reason="timed out without user response",
reason_addendum="", timeout_addendum=" Silence is not consent.",
diff --git a/tools/approval_gateway_wait.py b/tools/approval_gateway_wait.py
index 63edb738162..5f454b8e1df 100644
--- a/tools/approval_gateway_wait.py
+++ b/tools/approval_gateway_wait.py
@@ -15,7 +15,7 @@ import threading
import time
import uuid
-from tools.interrupt import is_interrupted
+from tools.interrupt import get_interrupt_reason, is_interrupted
from tools import approval_context as _ctx
from tools.approval_human_wait import activity_heartbeat, human_wait_window
@@ -47,11 +47,11 @@ def _poll_event(event: threading.Event, session_key: str, *, interrupt_log: str)
responding (mirrors ``_wait_for_process()`` cadence). The loop is recorded as
human-wait time so the concurrent batch deadline excludes it.
- ``is_interrupted()`` deliberately does NOT distinguish a deliberate /stop from
- a gateway inactivity timeout — both resolve as 'deny' (not outcome='timeout').
- The per-thread interrupt flag carries no stable machine-checkable cause, so a
- fail-closed deny preserves the historical semantics; changing this needs a
- dedicated interrupt-cause channel, not string matching."""
+ Any interrupt (/stop, inactivity timeout, delegation teardown) ends the wait
+ fail-closed: the command does not run. Who caused it is read from the
+ per-thread interrupt-cause channel (``get_interrupt_reason()``, a trusted fixed
+ category), never inferred from message text, so the caller can report a
+ withdrawn prompt without inventing a user refusal."""
deadline = time.monotonic() + max(_ctx._get_approval_timeout(), 0)
heartbeat = activity_heartbeat("waiting for user approval")
with human_wait_window(session_key):
@@ -70,11 +70,27 @@ def _poll_event(event: threading.Event, session_key: str, *, interrupt_log: str)
heartbeat()
+def _cancel_cause(state: str, result: str | None) -> str | None:
+ """Why the wait ended with nobody answering: the turn was interrupted (cause from the
+ per-thread channel — a user /stop or a parent's delegation teardown) or the turn ended
+ under the prompt (notifier unregistered, result never set). ``None`` for a real answer
+ or a plain timeout."""
+ if state == "interrupted":
+ return get_interrupt_reason() or "turn interrupted"
+ if state == "set" and result is None:
+ return "the turn ended before the prompt was answered"
+ return None
+
+
def _finish(payload: dict, resolved: bool, choice: str | None, reason, **extra) -> dict:
"""Fire the post hook and build the decision dict. Unresolved (timeout) and
- a None choice both mean the user never answered."""
- _ctx._fire_approval_hook("post_approval_response", **payload,
- choice="timeout" if not resolved else (choice or "timeout"), **extra)
+ a None choice both mean the user never answered; ``cancelled`` carries the
+ cause when the prompt was withdrawn rather than answered."""
+ if extra.get("cancelled"):
+ hook_choice = "cancelled"
+ else:
+ hook_choice = "timeout" if not resolved else (choice or "timeout")
+ _ctx._fire_approval_hook("post_approval_response", **payload, choice=hook_choice, **extra)
return {"resolved": resolved, "choice": choice, "reason": reason, **extra}
@@ -89,8 +105,9 @@ def _await_coalesced_leader(session_key: str, leader, payload: dict):
so observers see the follower's lifecycle without a duplicate prompt."""
_ctx._fire_approval_hook("pre_approval_request", **payload, coalesced=True)
state = _poll_event(leader.event, session_key,
- interrupt_log="Coalesced approval wait interrupted by user signal — "
+ interrupt_log="Coalesced approval wait interrupted — "
"returning deny for session %s")
+ cancelled = _cancel_cause(state, leader.result)
if state == "interrupted":
# Deny only OUR follower; the leader thread handles its own signal.
choice, resolved = "deny", True
@@ -102,7 +119,8 @@ def _await_coalesced_leader(session_key: str, leader, payload: dict):
if choice == "once":
# The post hook fires for the fresh prompt's own lifecycle, not here.
return None
- return _finish(payload, resolved, choice, getattr(leader, "reason", None), coalesced=True)
+ extra = {"cancelled": cancelled} if cancelled else {}
+ return _finish(payload, resolved, choice, getattr(leader, "reason", None), coalesced=True, **extra)
def _await_gateway_decision(session_key: str, notify_cb, approval_data: dict, *, surface: str = "gateway") -> dict:
@@ -168,9 +186,11 @@ def _await_gateway_decision(session_key: str, notify_cb, approval_data: dict, *,
return {"resolved": False, "choice": None, "notify_failed": True}
state = _poll_event(entry.event, session_key,
- interrupt_log="Approval wait interrupted by user signal — returning deny for session %s")
+ interrupt_log="Approval wait interrupted — returning deny for session %s")
+ cancelled = _cancel_cause(state, entry.result)
if state == "interrupted":
entry.result = "deny"
entry.event.set()
_drop_entry("answered" if state == "set" else state)
- return _finish(payload, state != "timeout", entry.result, entry.reason)
+ extra = {"cancelled": cancelled} if cancelled else {}
+ return _finish(payload, state != "timeout", entry.result, entry.reason, **extra)
diff --git a/tools/approval_prompt.py b/tools/approval_prompt.py
index c1e7f93c935..f4151eaba69 100644
--- a/tools/approval_prompt.py
+++ b/tools/approval_prompt.py
@@ -298,8 +298,8 @@ def request_elicitation_consent(message: str, description: str, *,
return "decline"
if decision.get("notify_failed"):
return "decline"
- if not decision.get("resolved"):
- return "cancel"
+ if not decision.get("resolved") or decision.get("cancelled"):
+ return "cancel" # nobody answered (timeout / prompt withdrawn) — not a user refusal
return _consent(decision.get("choice"), "decline")
# allow_permanent=False: elicitation is a per-call confirmation — no pattern to remember.
diff --git a/tools/delegate_tool_child_run.py b/tools/delegate_tool_child_run.py
index 037cffee570..0d8a39e1a94 100644
--- a/tools/delegate_tool_child_run.py
+++ b/tools/delegate_tool_child_run.py
@@ -75,7 +75,8 @@ def _attach_child(parent_agent: Any, child: Any) -> None:
message = getattr(parent_agent, "_interrupt_message", None)
hard = getattr(parent_agent, "_hard_interrupt_requested", None)
if hard is None or hard.is_set():
- _signal_child_stop(child, message or "parent agent interrupted")
+ _signal_child_stop(child, message or "parent agent interrupted",
+ tool_reason=getattr(parent_agent, "_tool_interrupt_reason", None) or "parent agent interrupted")
else:
with _quiet("Failed to propagate interrupt to late child: %s"):
child.interrupt(message)
@@ -89,10 +90,12 @@ def _detach_child(parent_agent: Any, child: Any) -> None:
except (ValueError, UnboundLocalError) as e:
logger.debug("Could not remove child from active_children: %s", e)
-def _signal_child_stop(child: Any, *reason: str) -> None:
- """Cooperative interrupt so the child's worker thread can exit cleanly."""
+def _signal_child_stop(child: Any, *reason: str, tool_reason: str = "parent delegation ended") -> None:
+ """Cooperative interrupt so the child's worker thread can exit cleanly. ``tool_reason`` is the
+ fixed cause the child's tools see (a pending approval wait reports it instead of a user deny)."""
with _quiet(None):
- if child is not None and not request_hard_interrupt(child, *reason) and hasattr(child, "_interrupt_requested"):
+ if (child is not None and not request_hard_interrupt(child, *reason, tool_reason=tool_reason)
+ and hasattr(child, "_interrupt_requested")):
child._interrupt_requested = True
# ── 0-API-call timeout diagnostic ────────────────────────────────────────────
diff --git a/tools/file_tools_write_guards.py b/tools/file_tools_write_guards.py
index a1a59792a3d..9288e64d3d7 100644
--- a/tools/file_tools_write_guards.py
+++ b/tools/file_tools_write_guards.py
@@ -295,6 +295,8 @@ def _request_protected_instruction_approval(reasons: list[str], task_id: str = "
decision = _await_gateway_decision(session_key, notify_cb, approval_data, surface="gateway")
if decision.get("notify_failed"):
return blocked.format(why="requires approval but the approval request could not be delivered.")
+ if decision.get("cancelled"):
+ return blocked.format(why=f"approval was withdrawn before the user answered ({decision['cancelled']}).")
choice, timed = decision.get("choice"), not decision.get("resolved")
else:
# CLI surface: per-thread approval callback (prompt_toolkit panel).
diff --git a/website/docs/developer-guide/observer-hooks.md b/website/docs/developer-guide/observer-hooks.md
index 30b912dda13..5c223a88869 100644
--- a/website/docs/developer-guide/observer-hooks.md
+++ b/website/docs/developer-guide/observer-hooks.md
@@ -206,7 +206,8 @@ Common fields include `command`, `description`, `pattern_key`,
`pattern_keys`, `session_key`, and `surface`.
`post_approval_response` also includes `choice`, with values such as `once`,
-`session`, `always`, `deny`, and `timeout`.
+`session`, `always`, `deny`, `timeout`, and `cancelled` (prompt withdrawn before an
+answer — turn interrupted or ended).
Approval hooks are observer-only. Plugins cannot pre-answer or veto approvals
from these hooks. To prevent a tool from reaching approval, use
diff --git a/website/docs/user-guide/features/hooks.md b/website/docs/user-guide/features/hooks.md
index 67add32eae8..e635add680e 100644
--- a/website/docs/user-guide/features/hooks.md
+++ b/website/docs/user-guide/features/hooks.md
@@ -1351,7 +1351,7 @@ def register(ctx):
### `post_approval_response`
-Fires after a prompted or smart approval decision, after a prompt times out, or when the gateway cannot deliver the approval notification. Notification failure emits `choice="notify_failed"` before any approval decision exists.
+Fires after a prompted or smart approval decision, after a prompt times out or is withdrawn (turn interrupted or ended before an answer), or when the gateway cannot deliver the approval notification. Notification failure emits `choice="notify_failed"` before any approval decision exists.
**Callback signature:**
@@ -1372,7 +1372,7 @@ Same kwargs as `pre_approval_request`, plus:
| Parameter | Type | Description |
|-----------|------|-------------|
-| `choice` | `str` | Prompted surfaces use `"once"`, `"session"`, `"always"`, `"deny"`, `"timeout"`, or `"notify_failed"`; smart decisions use `"smart_approve"` or `"smart_deny"` |
+| `choice` | `str` | Prompted surfaces use `"once"`, `"session"`, `"always"`, `"deny"`, `"timeout"`, `"cancelled"` (the prompt was withdrawn before anyone answered — turn interrupted or ended; the command did not run), or `"notify_failed"`; smart decisions use `"smart_approve"` or `"smart_deny"` |
| `decided_by` | `str` | `"aux_llm"` for smart decisions; absent on prompted surfaces |
**Return value:** ignored.