Files
hermes-agent/tools/context.py
alt-glitch b85ac0f579 refactor(terminal): the terminal backends move from tools/environments/ to terminal_backends/
The terminal backends and their support files leave tools/, which holds
model tools, for a new root package terminal_backends/. base.py becomes
environment.py and its base_* siblings become environment_*;
sandbox_scope.py becomes hosted_scope.py and sandbox_conformance.py
becomes conformance.py. Every other file keeps its stem. Function bodies
are unchanged; only imports and module-name strings follow the move.

tools.environments, tools.environments.local, tools.environments.base
and tools.environments.sudo_password_note keep generated old-path files:
old releases import the first two after an update, an agent process
started on v0.23.2 to v0.23.5 imports the last on its next terminal
command, and the plugin API publishes BaseEnvironment under both
package names. tools.environments.base_output is a compat key for pinned
catalog plugins. terminal_backends joins the tools log component, the
known logger roots and every hand-written package list.

The package is not named sandboxes: on an install whose checkout is
HERMES_HOME that folder holds live sandbox workspaces, and the updater
of a released version deletes or stashes them when a tracked package of
the same name arrives.
2026-12-01 17:49:22 +05:30

531 lines
25 KiB
Python

"""What a running tool call can ask Hermes, read from the thread or context it runs on.
**Interruption.** Interrupt signaling is per thread, so interrupting one agent session does not
kill tools in other sessions (the gateway runs many agents in one process). The agent passes its execution thread id to set_interrupt(); tools call
is_interrupted(), which checks the CURRENT thread.
**Hosted scope.** What a hosted scope may run is an allowlist of tools and one switch for
host-state features. In a hosted scope nothing tenant-supplied may execute on this host or touch its filesystem, and no
agent may read or write state this host keeps for its profile. Two decisions enforce that. Each is
made in one function and is deny-by-default, so a new tool or feature stays off in a hosted scope
until someone shows it acts only through the agent's sandbox:
* :func:`hosted_tool_refusal` — a tool runs in a hosted scope only if it is on
:data:`HOSTED_TOOL_ALLOWLIST`, the tools whose every effect goes through the agent's own sandbox
(``terminal_backends.hosted_scope``). Everything else (memory, recall, todo, vision, browser, web,
MCP, connectors, catalog, delegation, skills, cron, ...) is refused before its handler. The agent
loop asks once per call, in ``agent.tool_executor._dispatch_authorized_once``: the one function every
sequential, concurrent and batched call goes through, whatever executes it (inline agent tools,
memory-provider and context-engine tools, the registry, connectors). The execution primitives also
ask, for callers outside the loop: ``ToolRegistry.dispatch`` (execute_code RPC, the session kernel,
the MCP bridge, plugin ``dispatch_tool``), the inline-executor table and connector dispatch.
* :func:`host_feature_enabled` — the agent features outside tool dispatch that read or write this
host's state for the profile, or run here (:data:`HOST_FEATURES`). Every one is off in a hosted
scope; each site asks this one function. They come back per agent through storage ports.
A local install (no scope, or a local one) is untouched: neither set is consulted, and every
function here answers "allowed", with one exception. The features that start a command the profile's
own files name (:data:`RUNS_PROFILE_COMMANDS`) are also off while a plugin runs this process's
profile elsewhere (``hermes_cli.profiles_run_elsewhere``): that backend writes those files and starts
the commands itself, so no host process does, whichever command asks (``hermes hooks test``,
``hermes mcp test``, a process that was already running when the profile was marked).
**Worker threads.** 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 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.
**Coroutines.** ``run_async`` runs a coroutine from sync code on a loop that stays open (never
``asyncio.run`` per call): cached httpx/AsyncOpenAI clients stay bound to a live loop, so their GC
cleanup can't hit "Event loop is closed". The main thread shares one loop; worker threads own
thread-local loops.
**Progress.** Live progress from inside a running tool call (MCP ``notifications/progress``) goes
onto the agent's ``tool_progress_callback`` as ``tool.progress`` events. The executor binds a relay for each dispatched call (``bound_tool_progress``); a tool reads it on its
own thread with ``current_tool_progress()`` and may invoke the result from any thread (the MCP client
fires it on the MCP event loop). Emission is throttled per call so a chatty server cannot flood the
UI; the first update and the one reaching ``total`` always pass.
**Call identity.** ``CallIds`` holds the ids of one tool call for hooks and middleware.
"""
from __future__ import annotations
import asyncio
import concurrent.futures
import contextlib
import contextvars
import logging
import threading
import time
from collections.abc import Callable, Iterator
from dataclasses import asdict, dataclass
from typing import Optional
from utils import env_var_enabled
logger = logging.getLogger(__name__)
# --- Interruption ---
# Opt-in debug tracing — pairs with HERMES_DEBUG_INTERRUPT in terminal_backends/environment.py.
_DEBUG_INTERRUPT = env_var_enabled("HERMES_DEBUG_INTERRUPT")
# The trace has its own logger, so forcing its level leaves the other sections of this file alone.
_interrupt_trace = logger.getChild("interrupt")
if _DEBUG_INTERRUPT:
# AIAgent's quiet_mode forces the `tools` logger to ERROR on CLI startup;
# force ours back to INFO so the trace is visible in agent.log.
_interrupt_trace.setLevel(logging.INFO)
# Interrupted thread idents + optional user-safe cause (never the user's message text).
_interrupted_threads: set[int] = set()
_interrupt_reasons: dict[int, str] = {}
# Threads asked to YIELD: hand a long-running foreground command to the background
# instead of killing it, so a mid-turn user message is not parked behind it.
_yield_threads: set[int] = set()
_lock = threading.Lock()
# Tool-worker tid a deadline worker acts for. ``run_bounded_sync`` runs its worker under
# ``contextvars.copy_context()``, so a guard chain moved onto that worker still honours
# ``/stop`` aimed at the tool thread that spawned it (``is_interrupted`` checks both).
acting_for_tid: contextvars.ContextVar[int | None] = contextvars.ContextVar(
"hermes_interrupt_acting_for_tid", default=None,
)
def set_interrupt(active: bool, thread_id: int | None = None, *, reason: str | None = None) -> None:
"""Set or clear the interrupt for *thread_id* (default: current thread); ``reason`` is
an optional user-safe cause. Clearing also drops a pending yield request."""
tid = thread_id if thread_id is not None else threading.current_thread().ident
with _lock:
(_interrupted_threads.add if active else _interrupted_threads.discard)(tid)
if active and reason:
_interrupt_reasons[tid] = reason
else:
_interrupt_reasons.pop(tid, None)
if not active:
_yield_threads.discard(tid)
_snapshot = set(_interrupted_threads) if _DEBUG_INTERRUPT else None
if _DEBUG_INTERRUPT:
_interrupt_trace.info(
"[interrupt-debug] set_interrupt(active=%s, target_tid=%s) "
"called_from_tid=%s current_set=%s",
active, tid, threading.current_thread().ident, _snapshot)
def is_interrupted() -> bool:
return is_thread_interrupted(threading.current_thread().ident) or is_thread_interrupted(acting_for_tid.get())
def is_thread_interrupted(thread_id: int | None) -> bool:
"""Whether *thread_id* has an interrupt bit set (``None`` never is). Used when
a wait moves onto a deadline worker (``run_bounded_sync``) so ``/stop``
targeting the original tool-worker tid still kills the subprocess.
See #94285.
"""
if thread_id is None:
return False
with _lock:
return thread_id in _interrupted_threads
def request_yield(thread_id: int) -> None:
"""Ask the tool running on *thread_id* to yield: a foreground terminal command hands
its live process to the background registry and returns at once, so a user's mid-turn
message (``redirect()`` during tool execution) is delivered instead of parked behind it.
The command itself is never killed; that is what ``set_interrupt`` is for."""
with _lock:
_yield_threads.add(thread_id)
def consume_yield(thread_id: int | None) -> bool:
"""Atomically take the pending yield for *thread_id*; True if one was pending."""
if thread_id is None:
return False
with _lock:
if thread_id in _yield_threads:
_yield_threads.discard(thread_id)
return True
return False
def run_if_not_interrupted(callback: Callable[[], None]) -> bool:
"""Run a state transition atomically with current-thread interruption.
Returns ``False`` without calling ``callback`` when the current thread is
already interrupted. The callback runs under the interrupt lock and must
not block or re-enter any interrupt API.
"""
tid = threading.current_thread().ident
with _lock:
if tid in _interrupted_threads:
return False
callback()
return True
def get_interrupt_reason() -> str | None:
"""User-safe interrupt cause for the current thread, if known."""
with _lock:
return _interrupt_reasons.get(threading.current_thread().ident)
def clear_current_thread_interrupt() -> None:
"""Clear any interrupt bit on the CURRENT thread: gives a user-approved command a clean
slate right before it spawns its child, so a stale bit that landed during the blocking
approval-wait cannot SIGINT the just-approved run. A *genuine* interrupt arriving after
this call re-sets the bit and is still observed by the executor's poll loop. Call
directly on the executing thread."""
set_interrupt(False)
# --- Hosted scope ---
# Tools whose every effect goes through the agent's ScopedEnvironment and nothing on this host:
# terminal commands run by env.execute in the sandbox; background spawns via spawn_via_env,
# their records stamped with the sandbox key.
# process_manage acts only on the bound agent's own records (sandbox_visible); polls via its env.
# execute_code always the remote kernel / per-call script in the sandbox, never the host kernel;
# its RPC tool calls re-enter ToolRegistry.dispatch, so they meet this allowlist too.
# read_file, write_file, patch, search_files
# ShellFileOperations over the sandbox env: no host fast path, a lexical path policy,
# no host document extraction; an oversized result spills into the sandbox.
HOSTED_TOOL_ALLOWLIST = frozenset({
"terminal", "process_manage", "execute_code", "read_file", "write_file", "patch", "search_files",
})
# Agent features outside tool dispatch that read or write this host's profile state, or run here.
HOST_FEATURES = frozenset({
"context_files", # AGENTS.md / CLAUDE.md / .cursorrules / SOUL.md in the system prompt
"subdirectory_hints", # AGENTS.md found beside the paths a tool call names
"context_references", # @file / @diff / @url expansion of the user's message
"workspace_snapshot", # git and project facts for the system prompt
"backend_probe", # a throwaway environment built to describe the backend
"builtin_memory", # MEMORY.md / USER.md and external memory providers
"session_recall", # the profile's state.db opened for recall
"background_review", # the post-turn memory/skill review fork
"trajectory_export", # trajectory JSONL in the working directory
"file_mutation_bookkeeping", # host stat of a failed write's target
"checkpoints", # shadow-git checkpoints and rollback of the working directory
"media_processing", # images/video decoded, converted and cached on this host
"skills", # the profile's skill files: index, preload, auto-load, slash commands
"skill_inline_shell", # !`cmd` blocks in a skill body
"cron_scripts", # a cron job's pre-run script
"shell_hooks", # operator shell hooks: a host process fed the event payload
"tool_host_artifacts", # files an allowed tool keeps here about a call: terminal output
# spill, saved blocked scripts, the verification ledger
"mcp_stdio", # a profile MCP server started as a host process
"media_delivery", # a reply attachment named by host path
"transcription", # audio read and speech engines run here
"delegation", # child agents started outside a tool call (/review)
})
# The host features that start a process from a command line or script in the profile's own files.
RUNS_PROFILE_COMMANDS = frozenset({"skill_inline_shell", "cron_scripts", "shell_hooks", "mcp_stdio"})
class HostedToolRefused(PermissionError):
"""A hosted scope asked for something that would run or read on this host, or a profile a
plugin runs elsewhere asked to start one of its own commands here."""
def _hosted() -> bool:
from terminal_backends.hosted_scope import hosted_scope
return hosted_scope() is not None
def _message(what: str, why: str) -> str:
return (f"{what} is not available to a hosted agent: {why}. A hosted agent's tools are "
f"{', '.join(sorted(HOSTED_TOOL_ALLOWLIST))}, all run in its own sandbox.")
def hosted_tool_refusal(tool_name: str) -> Optional[str]:
"""Why a hosted scope may not run *tool_name*, or ``None``. Always ``None`` outside a hosted scope,
where the allowlist is not consulted."""
if not _hosted() or tool_name in HOSTED_TOOL_ALLOWLIST:
return None
return _message(tool_name, "only tools that act solely through the agent's sandbox are enabled")
def _home_elsewhere() -> bool:
"""Whether a plugin runs this process's profile elsewhere (the home a multi-profile host has
bound for the caller). Kept per home, so asking at every hook event is cheap."""
from hermes_cli.profiles_run_elsewhere import home_runs_elsewhere
from hermes_constants import get_hermes_home
return home_runs_elsewhere(get_hermes_home())
def host_feature_enabled(feature: str) -> bool:
"""Whether *feature* (one of :data:`HOST_FEATURES`) may use this host's state now: never inside
a hosted scope; outside one always, except that a feature in :data:`RUNS_PROFILE_COMMANDS` is
off while a plugin runs this process's profile elsewhere."""
if feature not in HOST_FEATURES:
raise KeyError(f"unknown host feature {feature!r}")
return not _hosted() and not (feature in RUNS_PROFILE_COMMANDS and _home_elsewhere())
def host_feature_refusal(feature: str, what: str) -> Optional[str]:
""":func:`host_feature_enabled` as a message for *what*: the refusal in a hosted scope, the
run-elsewhere message for a profile a plugin runs elsewhere, else ``None``."""
if host_feature_enabled(feature):
return None
if not _hosted():
from hermes_cli.profiles_run_elsewhere import run_elsewhere_for_home
from hermes_constants import get_hermes_home
if (elsewhere := run_elsewhere_for_home(get_hermes_home())) is not None:
return elsewhere.message()
return _message(what, f"it uses this host's {feature.replace('_', ' ')}")
def require_host_feature(feature: str, what: str) -> None:
"""Raise :class:`HostedToolRefused` when *feature* is off (a hosted scope); a no-op otherwise."""
if refusal := host_feature_refusal(feature, what):
raise HostedToolRefused(refusal)
# --- Worker threads ---
def prompt_callback_accessors():
"""(getter, setter) pairs for every thread-local prompt callback a tool may need mid-dispatch
(lazy: terminal_tool imports approval.gate at load, so a top-level import risks a cycle).
Add a new per-thread prompt here — a callback missing from this table is silently absent on
every parallel/timeout worker, so the tool believes nobody can answer."""
from agent.vault_backends import unlock as vault_unlock
from tools import terminal_tool as tt
return ((tt._get_approval_callback, tt.set_approval_callback),
(tt._get_sudo_password_callback, tt.set_sudo_password_callback),
(vault_unlock.get_unlock_prompt_callback, vault_unlock.set_unlock_prompt_callback),
(vault_unlock.get_save_login_prompt_callback, vault_unlock.set_save_login_prompt_callback),
(vault_unlock.get_code_prompt_callback, vault_unlock.set_code_prompt_callback),
# The unlock owner: a manager unlocked on a worker must still be released with its session.
(vault_unlock.get_current_session_id, vault_unlock.set_current_session_id),
# A background fork's dispatch-side tool whitelist: without it a parallel batch escapes it.
(_get_tool_whitelist, _set_tool_whitelist))
def _get_tool_whitelist():
"""The thread's ``pre_tool_call`` tool whitelist as ``(allowed, deny_fmt)``, or None."""
from hermes_cli.plugins import _thread_tool_whitelist
allowed = getattr(_thread_tool_whitelist, "allowed", None)
return None if allowed is None else (allowed, getattr(_thread_tool_whitelist, "fmt", None))
def _set_tool_whitelist(state) -> None:
from hermes_cli.plugins import clear_thread_tool_whitelist, set_thread_tool_whitelist
if state is None:
clear_thread_tool_whitelist()
elif state[1] is None:
set_thread_tool_whitelist(state[0])
else:
set_thread_tool_whitelist(*state)
def capture_thread_callbacks() -> tuple:
"""``(setter, callback)`` pairs for the *current thread's* prompt callbacks, to replay on
another thread (empty when none are installed or the API is unavailable). The elicitation
consent hop uses this: ``asyncio.to_thread`` carries neither contextvars nor ``threading.local``,
so the tool wrapper snapshots both at the call site."""
try:
return tuple((setter, cb) for getter, setter in prompt_callback_accessors()
for cb in (getter(),) if cb is not None)
except Exception:
logger.debug("Could not capture prompt callbacks for cross-thread replay",
exc_info=True)
return ()
def propagate_context_to_thread(target: Callable) -> Callable:
"""Wrap *target* to run with the *current* thread's ContextVars and per-thread prompt callbacks
(approval, sudo, password-manager unlock).
Fail-closed: if callback installation raises they stay ``None`` — dangerous commands are then
denied by ``prompt_dangerous_approval`` and the gateway approval queue blocks.
"""
ctx = contextvars.copy_context()
# (setter, parent callback) pairs; None when the callback API could not be captured.
installs = None
try:
installs = tuple((setter, getter()) for getter, setter in prompt_callback_accessors())
except Exception:
logger.debug("Could not capture parent approval/sudo callbacks", exc_info=True)
def _runner(*args, **kwargs):
def _inner():
if installs is None:
return target(*args, **kwargs)
try:
for setter, cb in installs:
if cb is not None:
setter(cb)
except Exception:
logger.debug("Failed to install propagated approval/sudo callbacks; "
"dangerous-command approval will fail closed", exc_info=True)
try:
return target(*args, **kwargs)
finally:
try:
for setter, _cb in installs:
setter(None)
except Exception:
logger.debug("Failed to clear propagated approval/sudo callbacks",
exc_info=True)
return ctx.run(_inner)
return _runner
# --- Coroutines ---
_tool_loop = None # persistent loop for the main (CLI) thread
_tool_loop_lock = threading.Lock()
_worker_thread_local = threading.local() # per-worker-thread persistent loops
def _get_tool_loop():
"""Long-lived event loop for async tool handlers on the main thread."""
global _tool_loop
with _tool_loop_lock:
if _tool_loop is None or _tool_loop.is_closed():
_tool_loop = asyncio.new_event_loop()
return _tool_loop
def _get_worker_loop():
"""Persistent event loop for the current worker thread (thread-local)."""
loop = getattr(_worker_thread_local, 'loop', None)
if loop is None or loop.is_closed():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
_worker_thread_local.loop = loop
return loop
def run_async(coro):
"""Run a coroutine from sync code; safe under a running loop (gateway/RL env)."""
try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = None
if loop and loop.is_running():
# Inside a running loop: run in a fresh thread whose loop we keep a
# reference to, so on timeout we can cancel the task inside it
# (ThreadPoolExecutor.cancel() is a no-op on a running worker).
worker_loop: Optional[asyncio.AbstractEventLoop] = None
loop_ready = threading.Event()
def _run_in_worker():
nonlocal worker_loop
worker_loop = asyncio.new_event_loop()
loop_ready.set()
try:
asyncio.set_event_loop(worker_loop)
return worker_loop.run_until_complete(coro)
finally:
try: # drain tasks still pending after an external cancel
pending = asyncio.all_tasks(worker_loop)
for t in pending:
t.cancel()
if pending:
worker_loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
except Exception:
pass
worker_loop.close()
pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)
# Carry profile + approval/sudo context so get_hermes_home() resolves correctly.
future = pool.submit(propagate_context_to_thread(_run_in_worker))
try:
return future.result(timeout=300)
except concurrent.futures.TimeoutError:
# Cancel inside the worker's own loop so the thread can wind down.
if loop_ready.wait(timeout=1.0) and worker_loop is not None:
try:
for t in asyncio.all_tasks(worker_loop):
worker_loop.call_soon_threadsafe(t.cancel)
except RuntimeError:
pass # loop already closed
raise
finally:
pool.shutdown(wait=False) # never block the caller on a stuck coroutine
if threading.current_thread() is not threading.main_thread():
return _get_worker_loop().run_until_complete(coro)
return _get_tool_loop().run_until_complete(coro)
# --- Progress ---
TOOL_PROGRESS_EVENT = "tool.progress"
_MIN_INTERVAL_S = 0.5
ProgressReporter = Callable[[float, Optional[float], Optional[str]], None]
_current: contextvars.ContextVar[Optional[ProgressReporter]] = contextvars.ContextVar("tool_progress_reporter", default=None)
def _reporter(callback, tool_name: str, tool_call_id: str) -> ProgressReporter:
lock = threading.Lock()
last = [0.0]
def report(progress: float, total: Optional[float] = None, message: Optional[str] = None) -> None:
done = total is not None and total > 0 and progress >= total
now = time.monotonic()
with lock:
if last[0] and not done and now - last[0] < _MIN_INTERVAL_S:
return
last[0] = now
percent = round(min(max(progress / total, 0.0), 1.0) * 100) if total else None
try:
callback(TOOL_PROGRESS_EVENT, tool_name, message or None, None, tool_call_id=tool_call_id,
progress=float(progress), total=None if total is None else float(total), percent=percent)
except Exception: # health: allow BLE001 -- a UI sink failing must never fail the tool call
logger.debug("tool.progress callback failed for %s", tool_name, exc_info=True)
return report
@contextlib.contextmanager
def bound_tool_progress(callback, tool_name: str, tool_call_id: str) -> Iterator[None]:
"""Bind this call's relay for the block (no-op when the agent has no progress callback)."""
token = _current.set(_reporter(callback, tool_name, tool_call_id or "") if callback else None)
try:
yield
finally:
_current.reset(token)
def current_tool_progress() -> Optional[ProgressReporter]:
"""The running call's reporter, or None outside a dispatched tool call."""
return _current.get()
def tool_progress_payload(name: Optional[str], message: Optional[str], kwargs: dict) -> dict:
"""The ``tool.progress`` wire payload every viewer surface publishes (gateway event stream and
the legacy TUI gateway): ``percent`` is 0-100 when the server sent a ``total``, else None."""
return {"tool_id": str(kwargs.get("tool_call_id") or ""), "name": str(name or ""),
"progress": float(kwargs.get("progress") or 0.0), "total": kwargs.get("total"),
"percent": kwargs.get("percent"), "message": str(message) if message else None}
# --- Call identity ---
@dataclass(frozen=True)
class CallIds:
"""Identity fields of one tool call, threaded through hooks and middleware."""
task_id: Optional[str] = None
session_id: Optional[str] = None
tool_call_id: Optional[str] = None
turn_id: Optional[str] = None
api_request_id: Optional[str] = None
conversation_id: Optional[str] = None # compression-stable root (agent.prompt_cache_scope.conversation_id)
def hook_kwargs(self) -> dict[str, str]:
"""Same fields with None -> "" (hook/middleware wire contract)."""
return {k: v or "" for k, v in asdict(self).items()}