Skip to content

The agent that grows with you

refactor(tools): trim subagent_worktree/terminal_scope/terminal_hints/thread_context/slash_confirm — drop no-op HERMES_HOME override, inline single-use constants, unify probes, compact docstrings

Teknium922083ab9318
diff --git a/tools/slash_confirm.py b/tools/slash_confirm.py
index e465cff5800..b7bdbe3f3a5 100644
--- a/tools/slash_confirm.py
+++ b/tools/slash_confirm.py
@@ -1,14 +1,12 @@
"""Generic slash-command confirmation primitive (gateway-side).
-Slash commands with an expensive side effect worth surfacing (currently only
-``/reload-mcp``, which invalidates the provider prompt cache) route through
-here. Adapters with button UIs render Approve Once / Always Approve / Cancel
-and call ``resolve()`` from the callback; text-only adapters get a prompt and
-the gateway intercepts ``/approve``, ``/always``, ``/cancel`` replies.
-
-State is module-level (like ``tools.approval``) so adapters can resolve
-callbacks without a ``GatewayRunner`` backreference. The CLI has its own
-synchronous variant (``_prompt_slash_confirm`` in ``cli.py``).
+Slash commands with an expensive side effect (currently only ``/reload-mcp``,
+which invalidates the provider prompt cache) route through here. Button-UI
+adapters render Approve Once / Always Approve / Cancel and call ``resolve()``;
+text-only adapters get a prompt and the gateway intercepts ``/approve``,
+``/always``, ``/cancel``. State is module-level (like ``tools.approval``) so
+adapters can resolve without a ``GatewayRunner`` backreference. The CLI has its
+own synchronous variant (``_prompt_slash_confirm`` in ``cli.py``).
"""
from __future__ import annotations
@@ -24,9 +22,8 @@ logger = logging.getLogger(__name__)
_pending: Dict[str, Dict[str, Any]] = {}
_lock = threading.RLock()
-# A pending confirm older than this is discarded when the next message
-# arrives for the same session (buttons live as long as the adapter keeps
-# the callback_data).
+# A pending confirm older than this is discarded when the next message arrives
+# for the same session (buttons live as long as the adapter keeps callback_data).
DEFAULT_TIMEOUT_SECONDS = 300
@@ -38,12 +35,8 @@ def register(
) -> None:
"""Register a pending confirm, superseding any prior one for the session."""
with _lock:
- _pending[session_key] = {
- "confirm_id": confirm_id,
- "command": command,
- "handler": handler,
- "created_at": time.time(),
- }
+ _pending[session_key] = {"confirm_id": confirm_id, "command": command,
+ "handler": handler, "created_at": time.time()}
def get_pending(session_key: str) -> Optional[Dict[str, Any]]:
@@ -83,7 +76,6 @@ async def resolve(
Returns the handler's output string, or None if the confirm was stale,
already resolved, or the confirm_id doesn't match (superseded prompt).
- Safe from an asyncio button callback or the gateway's message intercept.
"""
with _lock:
entry = _pending.get(session_key)
@@ -102,9 +94,6 @@ async def resolve(
try:
result = await handler(choice)
except Exception as exc:
- logger.error(
- "Slash-confirm handler for /%s raised: %s",
- command, exc, exc_info=True,
- )
+ logger.error("Slash-confirm handler for /%s raised: %s", command, exc, exc_info=True)
return f"❌ Error handling confirmation: {exc}"
return result if isinstance(result, str) else None
diff --git a/tools/subagent_worktree.py b/tools/subagent_worktree.py
index ae987598391..edeb76dbe1e 100644
--- a/tools/subagent_worktree.py
+++ b/tools/subagent_worktree.py
@@ -1,18 +1,14 @@
-"""Opt-in git worktree isolation for delegated subagents (clean-room port of
-Muse Code's documented ``--subagent-worktree-isolation`` semantics).
-Enable with ``delegation.worktree_isolation: true`` (default false).
-
-Contract: git-only — in a non-git workspace the setting is ignored without
-error and children share the parent's cwd. One worktree per child, branched
-from the parent's ``HEAD`` under ``<repo>/.worktrees/subagent-<id>`` on branch
-``hermes-subagent/<id>``. The parent reviews/merges: each result entry reports
-path, branch, commit count and dirty state. A worktree is pruned only on
-affirmative proof (zero commits AND clean tree, both probes succeeded); if a
-probe fails the state is unknown, so it is kept and the entry carries
-``inspection_failed`` + ``note``.
-
+"""Opt-in git worktree isolation for delegated subagents
+(``delegation.worktree_isolation: true``, default false).
+
+Git-only: in a non-git workspace the setting is ignored and children share
+the parent's cwd. One worktree per child, branched from the parent's ``HEAD``
+under ``<repo>/.worktrees/subagent-<id>`` on branch ``hermes-subagent/<id>``.
+Each result entry reports path, branch, commit count and dirty state; a
+worktree is pruned only on affirmative proof (zero commits AND clean tree, both
+probes succeeded) — otherwise it is kept with ``inspection_failed`` + ``note``.
Local terminal backend only: on docker/ssh/modal the host worktree is invisible
-inside the sandbox, so isolation is skipped (debug log) rather than half-applied.
+inside the sandbox, so isolation is skipped rather than half-applied.
"""
from __future__ import annotations
@@ -29,18 +25,14 @@ from hermes_cli._subprocess_compat import harden_git_argv, noninteractive_git_en
logger = logging.getLogger(__name__)
_GIT_TIMEOUT = 30
-_WORKTREES_DIRNAME = ".worktrees"
-_BRANCH_NAMESPACE = "hermes-subagent"
def _run_git(args, cwd: str, timeout: int = _GIT_TIMEOUT):
- """Run a git command, capturing output. Never raises on non-zero exit.
+ """Run git capturing output; never raises on non-zero exit.
- Runs under :func:`noninteractive_git_env` (GHSA-7x36-8jrh-v4pw): worktree
- isolation runs automatically for delegated subagents against whatever repo
- the parent sits in, and ``worktree add`` runs checkout hooks. Disabling the
- fsmonitor/hooks/pager/credential config sinks keeps a malicious ``.git/config``
- from executing on the host.
+ Runs under :func:`noninteractive_git_env` (GHSA-7x36-8jrh-v4pw): this runs
+ automatically against whatever repo the parent sits in and ``worktree add``
+ runs checkout hooks, so a malicious ``.git/config`` must not execute.
"""
return subprocess.run(["git", *harden_git_argv(args)], cwd=cwd, capture_output=True,
text=True, encoding="utf-8", errors="replace", timeout=timeout,
@@ -77,29 +69,26 @@ def resolve_repo_root(path: Optional[str]) -> Optional[str]:
def _ensure_gitignore_entry(repo_root: str) -> None:
"""Best-effort: keep ``.worktrees/`` out of git status."""
gitignore = Path(repo_root) / ".gitignore"
- entry = f"{_WORKTREES_DIRNAME}/"
try:
existing = gitignore.read_text(encoding="utf-8-sig", errors="replace") if gitignore.exists() else ""
- if entry not in existing.splitlines():
+ if ".worktrees/" not in existing.splitlines():
with open(gitignore, "a", encoding="utf-8") as f:
if existing and not existing.endswith("\n"):
f.write("\n")
- f.write(f"{entry}\n")
+ f.write(".worktrees/\n")
except Exception as exc:
logger.debug("subagent worktree: could not update .gitignore: %s", exc)
def create_subagent_worktree(parent_cwd: Optional[str], subagent_id: Optional[str] = None) -> Optional[Dict[str, str]]:
- """Create an isolated worktree for one child agent. Returns
- ``path``/``branch``/``repo_root``/``base_commit``, or ``None`` when not a git
- repo or creation fails — absence of git downgrades silently to shared workspace."""
+ """Create an isolated worktree for one child; None (silent downgrade) when not a git repo or on failure."""
repo_root = resolve_repo_root(parent_cwd)
if not repo_root:
return None
wt_name = f"subagent-{(subagent_id or uuid.uuid4().hex[:8]).replace('/', '-')}"
- branch = f"{_BRANCH_NAMESPACE}/{wt_name}"
- wt_path = Path(repo_root) / _WORKTREES_DIRNAME / wt_name
+ branch = f"hermes-subagent/{wt_name}"
+ wt_path = Path(repo_root) / ".worktrees" / wt_name
try:
wt_path.parent.mkdir(parents=True, exist_ok=True)
@@ -136,14 +125,11 @@ def mark_worktree_payload_unproven(
) -> Dict[str, Any]:
"""Flag a worktree result payload as un-inspected, in place.
- A failed probe proves nothing, so the fields it would have filled keep
- their defaults. The parent only sees this dict (not logs), so the
- uncertainty must travel in the payload or "0 commits, clean" reads as "the
- child produced nothing". *unmeasured* names only the fields actually left
- unproven: one probe can succeed while the other fails, and calling a
- measured value UNKNOWN would be its own misreport. Shared by
- ``finalize_subagent_worktree`` and ``delegate_tool``'s finalize-raised
- fallback so the two producers of this schema cannot drift.
+ The parent only sees this dict, so the uncertainty must travel in it or
+ "0 commits, clean" reads as "the child produced nothing". *unmeasured*
+ names only the fields actually left unproven (one probe can succeed while
+ the other fails). Shared by ``finalize_subagent_worktree`` and
+ ``delegate_tool``'s fallback so the two producers cannot drift.
"""
path = payload.get("path", "")
branch = payload.get("branch", "")
@@ -159,19 +145,18 @@ def mark_worktree_payload_unproven(
def unproven_worktree_payload(info: Dict[str, str], reason: str) -> Dict[str, Any]:
- """Complete un-inspected payload for callers that never got one back
- (``delegate_tool``'s fallback when ``finalize_subagent_worktree`` raises).
- Emits exactly the parent-facing schema, WITHOUT ``repo_root``/``base_commit``."""
+ """Complete un-inspected payload for ``delegate_tool`` when ``finalize_subagent_worktree`` raises."""
return mark_worktree_payload_unproven(_base_payload(info), reason)
def finalize_subagent_worktree(info: Dict[str, str], *, prune: bool = True) -> Dict[str, Any]:
"""Inspect (and possibly prune) a child worktree after the child finishes.
- Returns path, branch, ``commits`` ahead of base, ``dirty``, ``pruned``. Prunes
- only when *prune*, commits==0, clean tree AND both git probes succeeded. If a
- probe exits non-zero or raises, the worktree/branch are kept and the payload
- carries ``inspection_failed: True`` + ``note``; ``commits``/``dirty`` are then
- defaults, NOT measurements."""
+
+ Prunes only when *prune*, commits==0, clean tree AND both git probes
+ succeeded. If a probe exits non-zero or raises the worktree/branch are kept
+ and the payload carries ``inspection_failed`` + ``note``; ``commits`` /
+ ``dirty`` are then defaults, NOT measurements.
+ """
path = info.get("path", "")
branch = info.get("branch", "")
base_commit = info.get("base_commit", "")
@@ -189,19 +174,18 @@ def finalize_subagent_worktree(info: Dict[str, str], *, prune: bool = True) -> D
failed: list = []
unmeasured: list = []
+ probes = (
+ ("commits", "rev-list", ["rev-list", "--count", f"{base_commit}..HEAD"], lambda out: int(out or 0)),
+ ("dirty", "status", ["status", "--porcelain"], bool),
+ )
try:
- counted = _run_git(["rev-list", "--count", f"{base_commit}..HEAD"], cwd=path)
- if counted.returncode == 0:
- payload["commits"] = int(counted.stdout.strip() or 0)
- else:
- failed.append(f"rev-list exit {counted.returncode}: {counted.stderr.strip()[:200]}")
- unmeasured.append("commits")
- status = _run_git(["status", "--porcelain"], cwd=path)
- if status.returncode == 0:
- payload["dirty"] = bool(status.stdout.strip())
- else:
- failed.append(f"status exit {status.returncode}: {status.stderr.strip()[:200]}")
- unmeasured.append("dirty")
+ for field, label, args, parse in probes:
+ res = _run_git(args, cwd=path)
+ if res.returncode == 0:
+ payload[field] = parse(res.stdout.strip())
+ else:
+ failed.append(f"{label} exit {res.returncode}: {res.stderr.strip()[:200]}")
+ unmeasured.append(field)
except Exception as exc:
# Timeout, OSError or non-numeric rev-list stdout: which probe raised is
# unknowable, so neither value is trustworthy — keep the worktree.
diff --git a/tools/terminal_hints.py b/tools/terminal_hints.py
index 213c3d2b9b5..071808fad49 100644
--- a/tools/terminal_hints.py
+++ b/tools/terminal_hints.py
@@ -1,14 +1,11 @@
"""Output-pattern failure hints for the terminal tool.
-Extends the exit-code semantics table in ``terminal_tool`` with an
-output-pattern tier: a bounded scan of failed-command output mapped to one
-short, actionable recovery hint.
-
-Rules (keep when adding patterns): only fires on non-zero exit; at most ONE
-hint, first match wins, patterns ordered by observed production frequency;
-scans only the first ``_SCAN_CHARS`` so hints key on error headers, not deep
-context; hints state the *next action* in 1-2 sentences, not a diagnosis;
-pure function, no I/O or config reads.
+Extends the exit-code semantics table in ``terminal_tool`` with a bounded scan
+of failed-command output mapped to ONE short, actionable recovery hint.
+Rules: only fires on non-zero exit; first match wins, patterns ordered by
+observed production frequency; scans only the first ``_SCAN_CHARS`` so hints
+key on error headers, not deep context; hints state the *next action* in 1-2
+sentences; pure function, no I/O or config reads.
"""
from __future__ import annotations
@@ -16,13 +13,11 @@ from __future__ import annotations
import re
from typing import Callable, Optional
-# Bounded scan window: error headers appear early; deep output is noise.
_SCAN_CHARS = 4000
def _regex_hint(pattern: str, message: str | Callable[[str], str], flags: int = 0) -> Callable[[str, str], Optional[str]]:
- """Build a hint that fires when ``pattern`` matches; ``{0}`` = first capture group,
- or ``message(group1)`` when a callable is given."""
+ """Hint firing when ``pattern`` matches; ``{0}`` = first group, or ``message(group1)`` if callable."""
rx = re.compile(pattern, flags)
def hint(command: str, output: str) -> Optional[str]:
@@ -103,8 +98,8 @@ _OUTPUT_HINTS: list[Callable[[str, str], Optional[str]]] = [
),
]
-# Exit-code-only hints for codes the semantics table in terminal_tool does
-# not cover per-command. Checked after output patterns.
+# Exit-code-only hints for codes the terminal_tool semantics table does not
+# cover per-command. Checked after output patterns.
_EXIT_CODE_HINTS: dict[int, str] = {
126: "Exit 126: the file was found but is not executable — `chmod +x` it or invoke it via its interpreter (e.g. `bash script.sh`).",
137: "Exit 137: the process was SIGKILLed — usually out-of-memory or an external kill. Reduce memory use or check `dmesg | tail` before retrying.",
@@ -112,14 +107,10 @@ _EXIT_CODE_HINTS: dict[int, str] = {
}
-# ---------------------------------------------------------------------------
-# Masked-success detection (exit 0 that probably isn't a success)
-# ---------------------------------------------------------------------------
-# `cargo build 2>&1 | tail -20` exits with tail's 0 (no pipefail) and
-# `cargo build || echo FAILED` exits with echo's 0, so the model can conclude
-# a build passed while the output says it failed. Conservative: BOTH the
-# command shape (top-level pipe into a passthrough consumer, or `|| <cheap
-# fallback>`) AND a strong tool-specific failure shape must hold, and
+# Masked-success detection: `cargo build 2>&1 | tail -20` exits with tail's 0
+# (no pipefail) and `cargo build || echo FAILED` with echo's 0, so the model can
+# conclude a build passed while the output says it failed. Conservative: BOTH a
+# masking command shape AND a strong tool-specific failure shape must hold, and
# read-only heads (`grep ... | head`) are excluded because their output
# legitimately contains error text. Advisory only — exit_code is never changed.
@@ -174,8 +165,8 @@ _FAILURE_SHAPES = re.compile(
def _first_token(command: str) -> str:
+ """Basename of the command head, skipping leading env-var assignments."""
for tok in (command or "").strip().split():
- # Skip env-var assignments and common wrappers.
if "=" in tok and not tok.startswith(("=", "./", "/")):
continue
return tok.rsplit("/", 1)[-1]
@@ -183,15 +174,10 @@ def _first_token(command: str) -> str:
def annotate_masked_success(command: str, output: str) -> Optional[str]:
- """Return a warning note when an exit-0 result likely masks a failure.
-
- Caller gates on exit_code == 0. Advisory only; returns None otherwise.
- """
+ """Warning note when an exit-0 result likely masks a failure (caller gates on exit 0)."""
cmd = command or ""
window = (output or "")[:_SCAN_CHARS]
- if not cmd or not window or _first_token(cmd) in _READONLY_HEADS:
- return None
- if not _FAILURE_SHAPES.search(window):
+ if not cmd or not window or _first_token(cmd) in _READONLY_HEADS or not _FAILURE_SHAPES.search(window):
return None
return next((note for rx, note in _MASKING_SHAPES if rx.search(cmd)), None)
@@ -201,12 +187,11 @@ def annotate_failure(command: str, exit_code: int, output: str) -> Optional[str]
if exit_code == 0:
return None
window = (output or "")[:_SCAN_CHARS]
- if window:
- for fn in _OUTPUT_HINTS:
- try:
- hint = fn(command or "", window)
- except Exception:
- continue
- if hint:
- return hint
+ for fn in _OUTPUT_HINTS if window else ():
+ try:
+ hint = fn(command or "", window)
+ except Exception:
+ continue
+ if hint:
+ return hint
return _EXIT_CODE_HINTS.get(exit_code)
diff --git a/tools/terminal_scope.py b/tools/terminal_scope.py
index d47164a64b7..1cd8807b578 100644
--- a/tools/terminal_scope.py
+++ b/tools/terminal_scope.py
@@ -1,20 +1,13 @@
"""Per-turn terminal scope: profile-scoped TERMINAL_* policy.
-Multiplexed surfaces (gateway, dashboard/TUI, cron) serve several profiles
-from one process; mirroring terminal settings into ``os.environ`` let the
-first profile pin its backend onto everyone else (sandbox escape). Like
-``agent/secret_scope.py`` for credentials, a ContextVar holds the active
-profile's COMPLETE effective ``TERMINAL_*`` policy, installed at each
-in-process profile boundary.
-
-- **Authoritative projection.** While a scope is bound, ``terminal_env``
- resolves ONLY from the policy (defaults + profile ``.env`` + its
- ``config.yaml``); omitted keys yield the defined default, never ambient
- ``os.environ`` (#68559).
-- **Fail closed.** If the policy cannot be resolved, callers install a
- *refusal* scope and terminal execution under it raises
- :class:`TerminalPolicyUnavailable` instead of falling back to ambient
- authority.
+Multiplexed surfaces (gateway, dashboard/TUI, cron) serve several profiles from
+one process; mirroring terminal settings into ``os.environ`` let the first
+profile pin its backend onto everyone else (sandbox escape). Like
+``agent/secret_scope.py``, a ContextVar holds the active profile's COMPLETE
+effective ``TERMINAL_*`` policy. While bound, ``terminal_env`` resolves ONLY
+from it (omitted keys -> defined default, never ambient env). If the policy
+cannot be resolved a *refusal* scope is installed and terminal execution raises
+:class:`TerminalPolicyUnavailable` instead of falling back to ambient authority.
"""
from __future__ import annotations
@@ -28,12 +21,13 @@ from typing import Any, Dict, Iterator, Optional
logger = logging.getLogger(__name__)
-# None = no scope bound (historical process-env behavior); dict = the active
-# profile's complete policy; TerminalPolicyRefusal = resolution failed.
+# None = no scope bound (process-env behavior); dict = active profile's complete
+# policy; TerminalPolicyRefusal = resolution failed.
_terminal_scope_var: ContextVar = ContextVar("hermes_terminal_scope", default=None)
-# Terminal keys whose config default lives in the consuming tool
-# (terminal_tool.py) rather than DEFAULT_CONFIG; DEFAULT_CONFIG wins on overlap.
+# Terminal keys whose config default lives in terminal_tool.py rather than
+# DEFAULT_CONFIG (DEFAULT_CONFIG wins on overlap). Without them the projection
+# is not total.
_TOOL_LEVEL_DEFAULTS: Dict[str, Any] = {
"cwd": ".",
"ssh_host": "",
@@ -80,23 +74,23 @@ def get_terminal_scope() -> Optional[Dict[str, str]]:
return _terminal_scope_var.get()
-def _raise_if_refusal(scope: Any) -> None:
+def enforce_no_refusal() -> None:
+ """Raise when the active scope is a refusal scope (fail closed)."""
+ scope = _terminal_scope_var.get()
if isinstance(scope, TerminalPolicyRefusal):
- raise TerminalPolicyUnavailable(
- f"terminal policy unavailable for this profile: {scope.reason}"
- )
+ raise TerminalPolicyUnavailable(f"terminal policy unavailable for this profile: {scope.reason}")
def terminal_env(name: str, default: str = "") -> str:
"""Authoritative read of a ``TERMINAL_*`` variable.
- No scope: process env, then *default*. Refusal scope: raise. Policy
- scope: ONLY the policy; a missing key yields *default*, never os.environ.
+ No scope: process env, then *default*. Refusal scope: raise. Policy scope:
+ ONLY the policy; a missing key yields *default*, never os.environ.
"""
scope = _terminal_scope_var.get()
if scope is None:
return os.environ.get(name, default)
- _raise_if_refusal(scope)
+ enforce_no_refusal()
value = scope.get(name)
return default if value is None else str(value)
@@ -104,9 +98,9 @@ def terminal_env(name: str, default: str = "") -> str:
def build_profile_terminal_scope(hermes_home: "Any") -> Dict[str, str]:
"""Build the COMPLETE effective ``TERMINAL_*`` policy for a profile home.
- Projection: ``DEFAULT_CONFIG['terminal']`` <- profile ``.env`` TERMINAL_*
- <- profile ``config.yaml`` ``terminal:`` keys. Total by construction, so a
- bound scope never widens back to ambient process authority. Raises
+ Projection: ``DEFAULT_CONFIG['terminal']`` <- profile ``.env`` TERMINAL_* <-
+ profile ``config.yaml`` ``terminal:`` keys. Total by construction, so a bound
+ scope never widens back to ambient authority. Raises
:class:`TerminalPolicyUnavailable` when either file exists but cannot be
read/parsed.
"""
@@ -116,7 +110,6 @@ def build_profile_terminal_scope(hermes_home: "Any") -> Dict[str, str]:
from hermes_cli.config_defaults import DEFAULT_CONFIG
defaults = DEFAULT_CONFIG.get("terminal") if isinstance(DEFAULT_CONFIG, dict) else None
- # Without the tool-level defaults the projection is not total.
defaults = {**_TOOL_LEVEL_DEFAULTS, **(defaults if isinstance(defaults, dict) else {})}
scope: Dict[str, str] = {}
@@ -146,22 +139,12 @@ def build_profile_terminal_scope(hermes_home: "Any") -> Dict[str, str]:
if key.startswith("TERMINAL_"):
scope[key] = str(value)
- # Read config.yaml through the HERMES_HOME override so the profile's own
- # file is consulted; a present-but-unparseable file fails closed.
- from hermes_constants import (
- get_hermes_home_override,
- reset_hermes_home_override,
- set_hermes_home_override,
- )
-
- override_token = None
- if get_hermes_home_override() != str(home):
- override_token = set_hermes_home_override(home)
+ # The profile's own config.yaml is read directly (not read_raw_config(): it
+ # collapses "missing" and "unparseable" into {}); present-but-unparseable
+ # fails closed.
try:
config_path = home / "config.yaml"
if config_path.exists():
- # Not read_raw_config(): it collapses "missing" and "unparseable"
- # into {}; the file exists, so a parse failure must fail closed.
from hermes_cli.config import fast_safe_load
try:
@@ -177,18 +160,12 @@ def build_profile_terminal_scope(hermes_home: "Any") -> Dict[str, str]:
raise
except Exception as exc:
raise TerminalPolicyUnavailable(f"cannot resolve terminal config in {home}: {exc}") from exc
- finally:
- if override_token is not None:
- reset_hermes_home_override(override_token)
return scope
def install_profile_terminal_scope(hermes_home: "Any") -> Token:
- """Build AND install a profile's policy; on failure install the refusal scope.
-
- Never raises. Returns the token for ``reset_terminal_scope``.
- """
+ """Build AND install a profile's policy; on failure install the refusal scope. Never raises."""
try:
return set_terminal_scope(build_profile_terminal_scope(hermes_home))
except TerminalPolicyUnavailable as exc:
@@ -196,15 +173,8 @@ def install_profile_terminal_scope(hermes_home: "Any") -> Token:
return install_refusal_scope(str(exc))
-def enforce_no_refusal() -> None:
- """Raise when the active scope is a refusal scope (fail closed, #68559)."""
- _raise_if_refusal(_terminal_scope_var.get())
-
-
@contextmanager
-def install_and_reset_profile_terminal_scope(
- hermes_home: "Any",
-) -> Iterator[None]:
+def install_and_reset_profile_terminal_scope(hermes_home: "Any") -> Iterator[None]:
"""Install the profile's terminal policy for a bounded turn/fire. Never raises."""
token = install_profile_terminal_scope(hermes_home)
try:
diff --git a/tools/thread_context.py b/tools/thread_context.py
index 2a535892124..b48867fa984 100644
--- a/tools/thread_context.py
+++ b/tools/thread_context.py
@@ -1,29 +1,13 @@
-#!/usr/bin/env python3
"""Propagate agent-turn context into worker threads that dispatch Hermes tools.
-A bare ``threading.Thread`` / ``ThreadPoolExecutor`` worker starts with an empty
-``contextvars.Context`` and no thread-local approval/sudo callbacks, so tool
-dispatch inside it silently loses:
-
- * the approval session/platform ContextVars (``tools.approval`` /
- ``gateway.session_context``) — gateway sessions then fall into
- ``check_dangerous_command``'s non-interactive auto-approve branch and
- dangerous commands run without prompting;
- * the thread-local CLI approval/sudo callbacks (``tools.terminal_tool``) —
- ``prompt_dangerous_approval`` then cannot reach the user (GHSA-qg5c-hvr5-hjgr).
-
-One audited capture/install/clear lifecycle for every place that fans tool
-dispatch onto worker threads (``agent.tool_executor``, ``execute_code`` RPC threads).
-
-Call :func:`propagate_context_to_thread` **on the parent thread** (it snapshots
-the parent's ContextVars and callbacks at call time) and use the result as the
-worker target::
-
- t = threading.Thread(target=propagate_context_to_thread(loop_fn), args=(...))
- executor.submit(propagate_context_to_thread(worker_fn), *args)
-
-Callbacks are installed for the worker's lifetime and **always cleared on exit**,
-so a recycled thread never holds a stale reference to a disposed CLI instance.
+A bare ``threading.Thread`` / ``ThreadPoolExecutor`` worker starts with an
+empty ``contextvars.Context`` and no thread-local approval/sudo callbacks, so
+tool dispatch inside it silently loses the approval ContextVars (gateway
+sessions then auto-approve dangerous commands) and the CLI approval/sudo
+callbacks (``prompt_dangerous_approval`` cannot reach the user,
+GHSA-qg5c-hvr5-hjgr). Call :func:`propagate_context_to_thread` **on the parent
+thread** (it snapshots at call time) and use the result as the worker target.
+Callbacks are installed for the worker's lifetime and always cleared on exit.
"""
from __future__ import annotations
@@ -38,8 +22,8 @@ logger = logging.getLogger(__name__)
def _callback_api():
"""Resolve the terminal_tool callback getters/setters.
- Imported lazily: ``tools.terminal_tool`` imports ``tools.approval`` at module
- load, so a top-level import would risk a cycle for callers in ``tools.approval``.
+ Lazy: ``tools.terminal_tool`` imports ``tools.approval`` at module load, so a
+ top-level import would risk a cycle for callers in ``tools.approval``.
"""
from tools.terminal_tool import (
_get_approval_callback,
@@ -47,22 +31,15 @@ def _callback_api():
set_approval_callback,
set_sudo_password_callback,
)
- return (
- _get_approval_callback,
- _get_sudo_password_callback,
- set_approval_callback,
- set_sudo_password_callback,
- )
+ return (_get_approval_callback, _get_sudo_password_callback, set_approval_callback, set_sudo_password_callback)
def propagate_context_to_thread(target: Callable) -> Callable:
- """Wrap *target* so it runs on a worker thread with the *current* thread's
- ContextVars and approval/sudo callbacks. The wrapper forwards args/kwargs.
+ """Wrap *target* to run with the *current* thread's ContextVars and approval/sudo callbacks.
Fail-closed: if callback installation raises, the callbacks stay unset
- (``None``) — ``prompt_dangerous_approval`` denies dangerous commands with no
- callback in an interactive context, and the gateway approval queue blocks
- when its notify callback is absent.
+ (``None``) — ``prompt_dangerous_approval`` then denies dangerous commands
+ and the gateway approval queue blocks.
"""
ctx = contextvars.copy_context()
parent_approval_cb = parent_sudo_cb = None
@@ -86,11 +63,8 @@ def propagate_context_to_thread(target: Callable) -> Callable:
if parent_sudo_cb is not None:
set_sudo(parent_sudo_cb)
except Exception:
- logger.debug(
- "Failed to install propagated approval/sudo callbacks; "
- "dangerous-command approval will fail closed",
- exc_info=True,
- )
+ logger.debug("Failed to install propagated approval/sudo callbacks; "
+ "dangerous-command approval will fail closed", exc_info=True)
try:
return target(*args, **kwargs)
finally:
@@ -98,10 +72,7 @@ def propagate_context_to_thread(target: Callable) -> Callable:
set_approval(None)
set_sudo(None)
except Exception:
- logger.debug(
- "Failed to clear propagated approval/sudo callbacks",
- exc_info=True,
- )
+ logger.debug("Failed to clear propagated approval/sudo callbacks", exc_info=True)
return ctx.run(_inner)