Skip to content

The agent that grows with you

refactor(approval): densify leaf call sites and signatures, drop single-pass prompt loop (1462->1375)

Teknium16056b5d5160
diff --git a/tools/approval_context.py b/tools/approval_context.py
index 8433012e0db..52febefabcf 100644
--- a/tools/approval_context.py
+++ b/tools/approval_context.py
@@ -97,11 +97,8 @@ def set_current_observability_context(
*, turn_id: str = "", tool_call_id: str = "", session_id: str = "",
) -> _Tokens:
"""Bind active tool correlation IDs to approval hooks."""
- return (
- _approval_turn_id.set(turn_id or ""),
- _approval_tool_call_id.set(tool_call_id or ""),
- _approval_session_id.set(session_id or ""),
- )
+ return (_approval_turn_id.set(turn_id or ""), _approval_tool_call_id.set(tool_call_id or ""),
+ _approval_session_id.set(session_id or ""))
def reset_current_observability_context(tokens: _Tokens) -> None:
@@ -219,12 +216,8 @@ def _normalize_approval_mode(mode) -> str:
if normalized in _VALID_MODES:
return normalized
if normalized:
- logger.warning(
- "Unknown approvals.mode %r — defaulting to 'manual'. "
- "Valid values: %s",
- mode,
- ", ".join(_VALID_MODES),
- )
+ logger.warning("Unknown approvals.mode %r — defaulting to 'manual'. "
+ "Valid values: %s", mode, ", ".join(_VALID_MODES))
return "manual"
@@ -276,12 +269,8 @@ def _get_approval_timeout() -> int:
# Fail CLOSED: the raw value would re-open the overflow this prevents.
safe_cap = 365 * 24 * 3600
if raw > safe_cap:
- logger.warning(
- "approvals.timeout=%s exceeds the platform-safe maximum; "
- "clamping to %ss",
- raw,
- safe_cap,
- )
+ logger.warning("approvals.timeout=%s exceeds the platform-safe maximum; "
+ "clamping to %ss", raw, safe_cap)
return safe_cap
return raw
@@ -333,9 +322,9 @@ def _get_approval_transport_config() -> tuple[str, str | None]:
"""Return explicitly selected transport and fail-closed fallback mode."""
try:
from hermes_cli.config import load_config_readonly
- approval_config = ((load_config_readonly() or {}).get("security") or {}).get("approval") or {}
- selected = str(approval_config.get("transport") or "builtin").strip().lower()
- fallback = str(approval_config.get("transport_fallback") or "").strip().lower()
+ cfg = ((load_config_readonly() or {}).get("security") or {}).get("approval") or {}
+ selected = str(cfg.get("transport") or "builtin").strip().lower()
+ fallback = str(cfg.get("transport_fallback") or "").strip().lower()
except Exception:
# An unreadable/malformed selection must not silently materialize a
# prompt on a built-in surface the operator may not be watching.
diff --git a/tools/approval_gateway_wait.py b/tools/approval_gateway_wait.py
index eb75982203b..8ebea355fe6 100644
--- a/tools/approval_gateway_wait.py
+++ b/tools/approval_gateway_wait.py
@@ -80,10 +80,8 @@ def _finish(payload: dict, resolved: bool, choice: str | None, reason, **extra)
"""Fire the post hook and build the decision dict. Unresolved (timeout) and
a None choice both mean the user never answered."""
from tools.approval import _fire_approval_hook
- _fire_approval_hook(
- "post_approval_response", **payload,
- choice="timeout" if not resolved else (choice or "timeout"), **extra,
- )
+ _fire_approval_hook("post_approval_response", **payload,
+ choice="timeout" if not resolved else (choice or "timeout"), **extra)
return {"resolved": resolved, "choice": choice, "reason": reason, **extra}
@@ -100,11 +98,9 @@ def _await_coalesced_leader(session_key: str, leader, payload: dict):
"""
from tools.approval import _fire_approval_hook
_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 — "
- "returning deny for session %s",
- )
+ state = _poll_event(leader.event, session_key,
+ interrupt_log="Coalesced approval wait interrupted by user signal — "
+ "returning deny for session %s")
if state == "interrupted":
# Deny only OUR follower; the leader thread handles its own signal.
choice, resolved = "deny", True
@@ -143,17 +139,13 @@ def _await_gateway_decision(session_key: str, notify_cb, approval_data: dict,
"description": approval_data.get("description", ""),
"pattern_key": primary_key,
"pattern_keys": list(approval_data.get("pattern_keys", [primary_key])),
- "session_key": session_key,
- "surface": surface,
+ "session_key": session_key, "surface": surface,
}
keys = list(approval_data.get("pattern_keys") or [])
with _approval._lock:
- leader = next(
- (e for e in _approval._gateway_queues.get(session_key, [])
- if e.data.get("command") == approval_data.get("command")
- and list(e.data.get("pattern_keys") or []) == keys),
- None,
- )
+ leader = next((e for e in _approval._gateway_queues.get(session_key, [])
+ if e.data.get("command") == approval_data.get("command")
+ and list(e.data.get("pattern_keys") or []) == keys), None)
if leader is not None:
adopted = _await_coalesced_leader(session_key, leader, payload)
if adopted is not None:
@@ -182,11 +174,9 @@ def _await_gateway_decision(session_key: str, notify_cb, approval_data: dict,
_approval._fire_approval_hook("post_approval_response", **payload, choice="notify_failed")
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",
- )
+ state = _poll_event(entry.event, session_key,
+ interrupt_log="Approval wait interrupted by user signal — "
+ "returning deny for session %s")
if state == "interrupted":
entry.result = "deny"
entry.event.set()
diff --git a/tools/approval_prompt.py b/tools/approval_prompt.py
index 8a7b859d3e7..cf33c57855f 100644
--- a/tools/approval_prompt.py
+++ b/tools/approval_prompt.py
@@ -17,12 +17,9 @@ from tools.interrupt import is_interrupted
logger = logging.getLogger("tools.approval")
-def prompt_dangerous_approval(command: str, description: str,
- timeout_seconds: int | None = None,
- allow_permanent: bool = True,
- approval_callback=None,
- *, allow_session: bool = True,
- smart_denied: bool = False) -> str:
+def prompt_dangerous_approval(command: str, description: str, timeout_seconds: int | None = None,
+ allow_permanent: bool = True, approval_callback=None,
+ *, allow_session: bool = True, smart_denied: bool = False) -> str:
"""Prompt the user to approve a dangerous command (CLI only).
Args:
@@ -85,12 +82,9 @@ def _read_choice(prompt: str, timeout_seconds: int) -> str | None:
return None if thread.is_alive() else result["choice"]
-def _prompt_dangerous_approval_inner(command: str, description: str,
- timeout_seconds: int,
- allow_permanent: bool = True,
- approval_callback=None,
- *, allow_session: bool = True,
- smart_denied: bool = False) -> str:
+def _prompt_dangerous_approval_inner(command: str, description: str, timeout_seconds: int,
+ allow_permanent: bool = True, approval_callback=None,
+ *, allow_session: bool = True, smart_denied: bool = False) -> str:
# Redact before any user-visible rendering; the original `command` is
# still what executes after approval. Same redactor as memory/log
# sanitization so tokens mask consistently across surfaces.
@@ -124,8 +118,7 @@ def _prompt_dangerous_approval_inner(command: str, description: str,
logger.warning(
"Dangerous-command approval requested on a thread with no "
"approval callback while prompt_toolkit is active; denying "
- "to avoid stdin deadlock. command=%r description=%r",
- command, description,
+ "to avoid stdin deadlock. command=%r description=%r", command, description,
)
return "deny"
except Exception:
@@ -140,23 +133,18 @@ def _prompt_dangerous_approval_inner(command: str, description: str,
else ("approval.prompt_long", "approval.choose_long") if allow_permanent
else ("approval.prompt_short", "approval.choose_short")
)
- print()
- print(f" {t('approval.dangerous_header', description=display_description)}")
- print(f" {display_command}")
- print()
- print(t(menu_key))
- print()
+ print(f"\n {t('approval.dangerous_header', description=display_description)}"
+ f"\n {display_command}\n\n{t(menu_key)}\n")
sys.stdout.flush()
choice = _read_choice(t(prompt_key), timeout_seconds)
if choice is None:
print("\n" + t("approval.timeout"))
return "timeout" # distinct from deny: the user never answered
if once_only:
- choice_map = {
+ decision = {
**dict.fromkeys(t("approval.smart_deny_once_inputs").split(","), "once"),
**dict.fromkeys(t("approval.smart_deny_deny_inputs").split(","), "deny"),
- }
- decision = choice_map.get(choice, "deny")
+ }.get(choice, "deny")
else:
decision = _CLI_CHOICE_ALIASES.get(choice, "deny")
if decision == "always" and not allow_permanent:
@@ -187,17 +175,9 @@ def _attempt(name: str, choice, failure, fallback) -> dict:
return {"selected": True, "choice": choice, "failure": failure, "fallback": fallback, "name": name}
-def _present_with_selected_transport(
- *,
- command: str,
- description: str,
- pattern_key: str,
- pattern_keys: list[str],
- session_key: str,
- surface: str,
- allow_session: bool,
- allow_permanent: bool,
-) -> dict:
+def _present_with_selected_transport(*, command: str, description: str, pattern_key: str,
+ pattern_keys: list[str], session_key: str, surface: str,
+ allow_session: bool, allow_permanent: bool) -> dict:
"""Present through an explicitly selected plugin transport, if any.
A selected transport replaces every built-in prompt surface; detection,
@@ -228,12 +208,8 @@ def _present_with_selected_transport(
request = ApprovalRequest.create(
command=redact_sensitive_text(command, force=True),
description=redact_sensitive_text(description, force=True),
- pattern_key=pattern_key,
- pattern_keys=tuple(pattern_keys),
- session_key=session_key,
- surface=surface,
- allow_session=allow_session,
- allow_permanent=allow_permanent,
+ pattern_key=pattern_key, pattern_keys=tuple(pattern_keys), session_key=session_key,
+ surface=surface, allow_session=allow_session, allow_permanent=allow_permanent,
timeout_seconds=timeout_seconds,
)
except Exception:
@@ -243,14 +219,9 @@ def _present_with_selected_transport(
logger.warning("Could not build redacted plugin approval request")
return _attempt(name, "deny", "error", None)
hook_kwargs = dict(
- command=request.command,
- description=request.description,
- pattern_key=pattern_key,
- pattern_keys=list(pattern_keys),
- session_key=session_key,
- surface=f"transport:{name}",
- request_id=request.request_id,
- request_digest=request.digest,
+ command=request.command, description=request.description, pattern_key=pattern_key,
+ pattern_keys=list(pattern_keys), session_key=session_key, surface=f"transport:{name}",
+ request_id=request.request_id, request_digest=request.digest,
)
_a._fire_approval_hook("pre_approval_request", **hook_kwargs)
try:
@@ -287,21 +258,16 @@ def _transport_choice(attempt: dict, *, pattern_key: str, description: str):
if not failure:
return attempt.get("choice"), None
if attempt.get("fallback") == "builtin":
- logger.warning(
- "Approval transport %r failed (%s); using explicit builtin fallback",
- attempt.get("name"),
- failure,
- )
+ logger.warning("Approval transport %r failed (%s); using explicit builtin fallback",
+ attempt.get("name"), failure)
return None, None
from tools import approval as _a
breaker_addendum = _a._denial_breaker_addendum(_a.get_current_session_key())
return None, _a._denied(
f"BLOCKED: Selected approval transport failed ({failure}); the user "
"has NOT consented to this action. Do NOT retry this command or "
- "attempt the same outcome through another route."
- f"{breaker_addendum}",
- pattern_key=pattern_key, description=description,
- outcome=f"transport_{failure}",
+ f"attempt the same outcome through another route.{breaker_addendum}",
+ pattern_key=pattern_key, description=description, outcome=f"transport_{failure}",
)
@@ -312,13 +278,9 @@ def _consent(choice, unresolved: str) -> str:
return unresolved if choice == "timeout" else "decline"
-def request_elicitation_consent(
- message: str,
- description: str,
- *,
- timeout_seconds: int | None = None,
- surface: str = "mcp-elicitation",
-) -> str:
+def request_elicitation_consent(message: str, description: str, *,
+ timeout_seconds: int | None = None,
+ surface: str = "mcp-elicitation") -> str:
"""Route an MCP elicitation request to the surface owning the active session.
Gateway sessions go through ``_await_gateway_decision``; CLI/TUI through
@@ -337,22 +299,13 @@ def request_elicitation_consent(
if _a._is_gateway_approval_context():
notify_cb = _a._gateway_notify_cb(session_key)
if notify_cb is None:
- logger.warning(
- "Elicitation requested in gateway session %s but no "
- "notify_cb is registered — failing closed",
- session_key,
- )
+ logger.warning("Elicitation requested in gateway session %s but no "
+ "notify_cb is registered — failing closed", session_key)
return "decline"
- approval_data = {
- "command": message,
- "description": description,
- "pattern_key": "mcp_elicitation",
- "pattern_keys": ["mcp_elicitation"],
- }
+ approval_data = {"command": message, "description": description,
+ "pattern_key": "mcp_elicitation", "pattern_keys": ["mcp_elicitation"]}
try:
- decision = _a._await_gateway_decision(
- session_key, notify_cb, approval_data, surface=surface,
- )
+ decision = _a._await_gateway_decision(session_key, notify_cb, approval_data, surface=surface)
except Exception as exc:
logger.error("Elicitation gateway dispatch failed: %s", exc, exc_info=True)
return "decline"
diff --git a/tools/approval_smart.py b/tools/approval_smart.py
index 4c675dd1421..b1b60ce9396 100644
--- a/tools/approval_smart.py
+++ b/tools/approval_smart.py
@@ -109,14 +109,9 @@ def _smart_approve(command: str, description: str) -> str:
"Respond with exactly one word: APPROVE, DENY, or ESCALATE"
)
response = call_llm(
- task="approval",
- messages=[
- {"role": "system", "content": system_prompt},
- {"role": "user", "content": user_prompt},
- ],
- temperature=0,
- max_tokens=16,
- timeout=smart_timeout,
+ task="approval", temperature=0, max_tokens=16, timeout=smart_timeout,
+ messages=[{"role": "system", "content": system_prompt},
+ {"role": "user", "content": user_prompt}],
)
logger.debug("Smart approvals: LLM call completed in %.1fs", time.monotonic() - _smart_t0)
answer = (response.choices[0].message.content or "").strip().upper()
@@ -124,12 +119,8 @@ def _smart_approve(command: str, description: str) -> str:
except Exception as e:
# WARNING, not DEBUG: a failed/blocked guardian call is a real event
# the operator needs to see (the hang was invisible at DEBUG).
- logger.warning(
- "Smart approvals: LLM call failed after %.1fs (%s: %s), escalating",
- time.monotonic() - _smart_t0,
- type(e).__name__,
- e,
- )
+ logger.warning("Smart approvals: LLM call failed after %.1fs (%s: %s), escalating",
+ time.monotonic() - _smart_t0, type(e).__name__, e)
return "escalate"
@@ -146,10 +137,8 @@ def _smart_verdict(command: str, description: str, pattern_key: str,
payload = {
"command": redact_sensitive_text(command, force=True),
"description": redact_sensitive_text(description, force=True),
- "pattern_key": pattern_key,
- "pattern_keys": list(pattern_keys),
- "session_key": session_key,
- "surface": "smart",
+ "pattern_key": pattern_key, "pattern_keys": list(pattern_keys),
+ "session_key": session_key, "surface": "smart",
}
except Exception as exc:
logger.debug("Smart approval hook redaction failed: %s", exc)
@@ -158,7 +147,6 @@ def _smart_verdict(command: str, description: str, pattern_key: str,
_a._fire_approval_hook("pre_approval_request", **payload)
verdict = _a._smart_approve(command, description)
if payload is not None and verdict in {"approve", "deny"}:
- _a._fire_approval_hook(
- "post_approval_response", **payload, choice=f"smart_{verdict}", decided_by="aux_llm",
- )
+ _a._fire_approval_hook("post_approval_response", **payload,
+ choice=f"smart_{verdict}", decided_by="aux_llm")
return verdict