* feat(docker): publish nousresearch/hermes-sandbox:desktop for terminal backends
The terminal backends (docker, modal, daytona, singularity) all default to
nikolaik/python-nodejs:python3.11-nodejs20, a bare Python+Node base. For Bot
Screen, computer_use and the browser to run INSIDE that sandbox instead of on
the gateway host, the sandbox image needs the display stack.
docker/sandbox-desktop.Dockerfile is that base plus:
- the everyday tools it lacked (jq, ripgrep, fd, tmux, less, nano, vim,
zip, rsync, tree, procps, htop, sudo for the base's uid-1000 `pn`)
- the exact package set the Hermes -desktop image installs (TigerVNC,
Xfce components, dbus, xauth, fonts)
- Playwright's headed Chromium (same build as the -desktop image)
- cua-driver 0.28.2 from its pinned release tarball
No Hermes inside; the default user stays root like the base so nothing
changes for people who just switch docker_image. Desktop processes run as
`pn`. 4.27 GB on amd64.
docker.yml gains a `sandbox` variant with its own cache scope and repository
(nousresearch/hermes-sandbox:desktop, :main-desktop, :<release>-desktop);
the docker-integration suite is skipped for it (no Hermes to test) and
docker/sandbox-desktop-smoke.sh runs instead: as `pn`, every launcher and
cua-driver binary resolves, the real launcher.sh publishes :20, the RFB
socket completes the 3.8 handshake relayed over `docker exec -i` stdio, and
a headed Chromium maps a window on that display. hadolint lints the new
Dockerfile in docker-lint.yml.
* feat(docker): sandbox desktop base on python3.13-nodejs26
Matches the Hermes image (Python 3.13 / Node 26) and the top of requires-python;
the default docker_image tag it inherited was Python 3.11 / Node 20. Same pn
uid 1000, Debian 13; smoke (launcher, RFB relay, headed Chromium) passes.
* feat(docker): bake agent-browser into hermes-sandbox:desktop
The browser tools drive the agent-browser CLI; when the browser follows the
terminal backend that CLI has to exist inside the sandbox. Pinned to the same
^0.26.0 range the gateway resolves, --ignore-scripts like the gateway's npx path.
* feat(bot_desktop): the screen, computer_use and the browser follow the terminal backend
A user who sandboxes `terminal` (docker/ssh/singularity) had the agent's
screen, cua-driver and Chromium running on the gateway HOST beside that
sandbox: Bot Screen gave a headless host a display, the Xfce panel carries
xfce4-terminal, and `computer_use` could open a shell outside the boundary
the sandbox exists for.
Now the desktop lives where the terminal lives:
- tools/environments/streams.py: one primitive per spawn-per-call backend, the
local argv prefix that runs its remainder inside the sandbox with stdio open
(`docker exec -i`, `ssh`, `apptainer exec`). SDK backends (modal, daytona,
vercel) have none and report so.
- tools/bot_desktop/sandbox_host.py: launcher.sh runs inside the sandbox as
the image's `pn`; the pane's RFB bytes ride a 12-line python relay over that
prefix; `cua-driver mcp` is the prefix + the sandbox image's own driver.
- tools/bot_desktop/placement.py + `bot_desktop.placement` (auto|terminal|
gateway). `auto` follows the backend; a sandbox that cannot host a screen
REFUSES with the opt-in named instead of silently using the host.
- runtime.start/stop/status/published_env branch on placement; the pane,
lease, epoch fencing and CLI are unchanged.
- cua_backend: the MCP invocation is the sandbox one when the screen is
there; the host driver's runtime contract is irrelevant then; check_fn is
true under a terminal placement without a host binary.
- browser_tool_session: agent-browser invocations are wrapped in the prefix
with the daemon, socket dir and profile inside the sandbox; screenshots are
fetched back so MEDIA: paths keep working; recycle closes the sandbox
daemon.
- web_routers/display.py: the bridge pumps a relay's stdio when the screen is
in a sandbox, a unix socket otherwise.
Live on docker with nousresearch/hermes-sandbox:desktop: start/observe/RFB
handshake through the dashboard bridge, human takeover fences the agent
(HumanHasControl) and keystrokes reach the sandbox Xvnc, handback restores,
three start/stop rounds leave zero desktop processes; computer_use capture
and list_windows see only the sandbox's Xfce; browser_navigate/snapshot/
vision run with Chromium and agent-browser inside the container and zero
host processes on the bot profile; modal + auto refuses naming the opt-in.
* feat(desktop): Screen pane shows where a sandbox-placed screen runs; Install is host-only
DesktopStatus gains placement ('gateway' | 'terminal:<backend>'). A sandbox
image lacking the stack is a blocker naming hermes-sandbox:desktop, shown in
place of Start; install_command stays None there because the pane's Install
button runs the package manager on the gateway host, the wrong machine, and
display.install refuses for the same reason. The pane header carries
'Screen runs inside the docker sandbox, with the terminal' (4 locales).
* fix(bot_desktop): "is the screen in the sandbox" is a disk check on hot paths, never a config read
Every browser command and CUA spawn asked in_sandbox(), which resolves placement by
loading config, which initializes HERMES_HOME. Under a test's fake home that raised
HomeInitializationError from _run_browser_command; on a real host it read config per
click. Hot paths now ask sandbox_screen_running(): the start marker on disk, written
only by a sandbox start. Policy (in_sandbox) stays for start/install, where config is
the question. display.observe gates on "an RFB endpoint exists" for either placement.
* test(moa): late-accounting sink test asserts the wedged slot's row, not sink order
Under CI load the poll loop can see the interrupt before collecting the fast slot, so the
fast slot also arrives late and first; the test then failed on sink_calls[0]. The
contract is that the wedged slot's real usage reaches the sink.
* chore: retrigger CI (zero-job dispatch failure, auto-heal)
* fix(bot_desktop): a sandbox that died under a live screen fails loudly, never falls to the host
sandbox_screen_running() drops a start marker whose terminal environment is no longer
registered (stale after a process restart). When the environment object outlives its
container, the browser's sandbox wrap now checks the published DISPLAY and raises
"the screen inside the terminal backend's sandbox is gone; start it again" instead of
KeyError('AGENT_BROWSER_PROFILE'). Live: fresh sandbox navigate ok; docker rm -f the
container; next navigate returns that error; zero host Chromium either way.
* feat(terminal): nousresearch/hermes-sandbox:desktop is the default container sandbox
Every container backend (docker, modal, daytona, singularity) now defaults to the
sandbox image with the desktop stack, so Bot Screen, computer_use and the browser
run inside the sandbox for everyone who never chose an image; Python 3.13 / Node 26
match the Hermes image. One constant (DEFAULT_SANDBOX_IMAGE) replaces six copies of
the old literal. Migration 47 moves saved configs still holding the OLD default and
never touches an image the user pinned. Docker reuse recreates a container built
from another image, or the flip would silently never take effect for anyone with a
persisted container (live: old container removed, new one on 3.13 / Node 26 with
Xvnc, cua-driver, agent-browser present).
* chore: retrigger CI (zero-job dispatch failure)
* chore: retrigger CI (zero-job dispatch failure, auto-heal)
* chore: retrigger CI (zero-job dispatch failure, auto-heal)
* chore(config): template stamps v47 and shows the new default sandbox image
The template is what install.sh / docker / doctor --fix seed; a stamp behind
DEFAULT_CONFIG makes every fresh install migrate on first run.
* feat(sandbox): the default image change is a decision, not a surprise
A persisted Docker sandbox on another image is kept when docker_image is unset;
only a written docker_image (an explicit pin) recreates it. The pin verdict
travels as TERMINAL_DOCKER_IMAGE_PINNED through both terminal bridges (process
env and per-profile scope) and the container-config allowlist.
Approval surfaces, all through hermes_cli.sandbox_image_switch: the interactive
CLI asks once at startup (y = pin the new image, n = pin the current one, Enter =
ask later); the Screen pane shows the same choice with Switch / Keep buttons via
display.switchSandboxImage; `hermes config set terminal.docker_image …` is the
same answer from any shell. Gateways and cron never decide: they keep the sandbox
and log the notice.
Migration 47 now unsets a saved image equal to the OLD default instead of
rewriting it to the new one — that value was the template copied, not a pin, and
rewriting it would have made the runtime recreate existing sandboxes unasked.
Modal restores its snapshot and Daytona reuses its labeled sandbox regardless of
the configured image, so existing sandboxes there were already untouched.
* fix(config): both plain defaults that preceded the desktop sandbox image are template copies
main pinned nikolaik/python-nodejs:python3.14-nodejs22 (cd0f97f833) without a migration;
a saved config holding either literal is unset by migration 47, so it follows the default
and existing sandboxes get the keep-or-switch decision instead of a silent recreate.
* ci(docker): build the sandbox image on release/dispatch, not every main push
Leaves docker.yml exactly as on main. The sandbox image carries no Hermes code,
so two 4 GB multi-arch builds per merge bought nothing. sandbox-image.yml builds
and smokes on a PR that edits its own Dockerfile/smoke, and publishes only on a
release or a manual dispatch with publish=true. Stable tag stays :desktop.
* fix(config): keep main's config.py/config_defaults.py edits under the sandbox-image delta
The rebase resolved both files wholesale with the branch side, dropping main's move to
hermes_yaml (the 3.14 runtime venv has no PyYAML) and the 3.14 base pin. This is main's
version plus exactly the branch's own changes: DEFAULT_SANDBOX_IMAGE, the pin verdict in the
env bridge, placement defaults and the v47 stamp.
* test: sandbox-image tests read config.yaml through hermes_yaml (no PyYAML on the 3.14 runtime)
* fix(bot_desktop): read the sandbox marker BOM-tolerantly (windows footgun lint)
* fix(bot_desktop): placement is the authority; sandbox screen survives restarts
Review findings on the sandbox-hosted Bot Screen, each reproduced live first.
Authority. The browser preflight and the CUA invocation keyed off screen
LIVENESS, so `placement: terminal` with the screen not yet up handed the tool an
unchanged host command. `runtime.tool_placement()` is now the one resolver:
terminal placement starts the sandbox screen on demand (no auto_start opt-in
inside the user's own sandbox), refused placement raises its reason, and neither
ever yields the host. placement.resolve() answers a local backend from env alone
so the common case costs no config load on the spawn path.
Restart. sandbox_screen_running() deleted the marker whenever the process-local
terminal registry was empty, i.e. after every gateway restart, while Xvnc kept
running in the container; stop() then returned False and left it. The marker
now records the owning container; liveness comes from `docker inspect` on it,
stop/status re-attach to the recorded owner (even after the placement setting
moved), and only a container that is gone drops the marker.
SSH. remote_argv emitted `bash -c <script>` as three words; OpenSSH joins them
and the remote login shell ran `bash -c export` and the rest itself. The script
travels as one quoted word for ssh (remote_command knows the backend); docker
and apptainer keep argv.
CDP reach. agent-browser inside the sandbox reports the sandbox's loopback;
the Browser Use harness, browser_exec and the vault supervisor connect from the
host and got connection refused. streams.forward_port() proxies a local port
over the exec stream (same relay as the RFB bridge) and the CDP URL is rewritten
to the local end.
pids limit. --pids-limit 256 counts threads; measured on the desktop image the
desktop stack is 44, one Chromium tab 212, the agent's browser with two tabs
488. Past the cap every further docker exec died with "procReady not received".
Default is 2048 with the measurements in the comment.
Replacement. An approved image switch force-removed the old container before
`docker run` tried the new image; a private tag or registry outage left nothing.
The image is inspected/pulled first and the old container kept on failure.
Desktop integration. The sandbox start never passed the dock's browser launcher
(no Browser icon) and the thumbnail needed a host launcher pid + host ImageGrab
(always None). The dock runs the sandbox's Playwright Chromium on the shared
profile; the thumbnail is grabbed inside the sandbox (Pillow baked into the
image). The browser profile moves from /tmp — a 512 MB tmpfs emptied on every
container stop — to the desktop user's home, so logins follow the container.
Pin provenance. A TERMINAL_DOCKER_IMAGE written in a routed profile's .env is a
pin even when it spells the default; the scope compared values before.
* docs(bot-screen): no literal tmp path in the profile-location note
* fix(bot_desktop): docker inspect liveness probe closes stdin (TUI subprocess guard)
* fix(bot_desktop): adopting a screen the sandbox kept records the marker
Live ssh probe: after the host's state was lost while the sandbox kept its
Xvnc, start() took the idempotent early return (display already published)
and never wrote the host marker, so status/thumbnail/stop lost the screen.
Record the adopted display like a fresh launch.
Docs: what an ssh host of your own must carry, and why a Dockerfile ENV is
not enough for a login session (PLAYWRIGHT_BROWSERS_PATH via /etc/environment).
* docker(sandbox-desktop): login sessions find the browser (PLAYWRIGHT_BROWSERS_PATH via /etc/environment)
* docs(bot-screen): what the Apptainer path inherits from the image and what it does not
* chore(config): sandbox-image migration is 47→48 (main took 47 for compression.threshold_tokens)
* chore: retrigger CI (zero-job dispatch failure, auto-heal)
238 lines
11 KiB
Python
238 lines
11 KiB
Python
"""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``, a ContextVar holds the active
|
|
profile's COMPLETE ``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`.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
from contextlib import contextmanager
|
|
from contextvars import ContextVar, Token
|
|
from pathlib import Path
|
|
from typing import Any, Dict, Iterator, Optional
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# None = no scope bound (process-env behavior); dict = complete policy; Refusal = resolution failed.
|
|
_terminal_scope_var: ContextVar = ContextVar("hermes_terminal_scope", default=None)
|
|
|
|
# Keys whose default lives in terminal_tool.py, not DEFAULT_CONFIG (which wins on overlap);
|
|
# without them the projection is not total.
|
|
_TOOL_LEVEL_DEFAULTS: Dict[str, Any] = {
|
|
"cwd": ".", "ssh_host": "", "ssh_user": "", "ssh_port": 22, "ssh_key": "",
|
|
"docker_orphan_reaper": True, "docker_persist_across_processes": True,
|
|
"sandbox_dir": "", "lifetime_seconds": 300, "docker_shared_container_key": "",
|
|
"home_mode": "auto",
|
|
}
|
|
|
|
|
|
class TerminalPolicyUnavailable(Exception):
|
|
"""The routed profile's ``.env``/``config.yaml`` exists but cannot be read/parsed."""
|
|
|
|
|
|
class TerminalPolicyRefusal(Dict[str, str]):
|
|
"""Marker scope (empty dict subclass) installed when policy resolution failed."""
|
|
|
|
def __init__(self, reason: str) -> None:
|
|
super().__init__()
|
|
self.reason = reason
|
|
|
|
|
|
def set_terminal_scope(mapping: Optional[Dict[str, str]]) -> Token:
|
|
"""Install *mapping* as the current context's terminal policy."""
|
|
return _terminal_scope_var.set(mapping)
|
|
|
|
|
|
def reset_terminal_scope(token: Token) -> None:
|
|
_terminal_scope_var.reset(token)
|
|
|
|
|
|
def get_terminal_scope() -> Optional[Dict[str, str]]:
|
|
"""The active scope mapping/refusal, or ``None`` when no scope is bound."""
|
|
return _terminal_scope_var.get()
|
|
|
|
|
|
def enforce_no_refusal() -> None:
|
|
"""Raise when the active scope is a refusal scope (fail closed).
|
|
|
|
Execution paths (terminal tool, execute_code) call this before spawning anything: under a refusal scope
|
|
the profile's terminal policy could not be resolved, and running with the launch process's ambient
|
|
policy is exactly the authority leak this module closes (#68559 requires refusal, not fallback).
|
|
Non-scoped and policy-scoped contexts pass silently.
|
|
"""
|
|
scope = _terminal_scope_var.get()
|
|
if isinstance(scope, TerminalPolicyRefusal):
|
|
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.
|
|
"""
|
|
scope = _terminal_scope_var.get()
|
|
if scope is None:
|
|
return os.environ.get(name, default)
|
|
enforce_no_refusal()
|
|
value = scope.get(name)
|
|
return default if value is None else str(value)
|
|
|
|
|
|
def build_profile_terminal_scope(
|
|
hermes_home: "Any", *, env_overlay: Optional[Dict[str, str]] = None) -> Dict[str, str]:
|
|
"""Build the COMPLETE effective ``TERMINAL_*`` policy for a profile home.
|
|
|
|
Projection: ``DEFAULT_CONFIG['terminal']`` <- profile ``.env`` TERMINAL_* <- *env_overlay*
|
|
<- profile ``config.yaml`` ``terminal:``. Total by construction, so a bound scope never
|
|
widens back to ambient authority. Raises :class:`TerminalPolicyUnavailable` if a present
|
|
file is unreadable.
|
|
|
|
*env_overlay* is a TRUSTED ``TERMINAL_*`` mapping captured from the launch process before
|
|
multiplexing began (``tui_gateway/launch_profile_policy.py``): the launch profile's
|
|
env-only policy (``TERMINAL_ENV=ssh`` from systemd, ``op run``, a launcher bridge) has no
|
|
file to rebuild it from, and reading live ``os.environ`` here is the leak this module
|
|
closes. It sits where the process env sits in the standalone bridge — explicit YAML keys
|
|
still win (``apply_terminal_config_to_env``).
|
|
"""
|
|
from hermes_cli.config import TERMINAL_CONFIG_ENV_MAP, _terminal_env_value
|
|
from hermes_cli.config_defaults import DEFAULT_CONFIG
|
|
|
|
home = Path(hermes_home)
|
|
scope: Dict[str, str] = {}
|
|
|
|
def _apply(mapping: Dict[str, Any]) -> None:
|
|
for cfg_key, value in mapping.items():
|
|
# cwd placeholders are resolved per-surface later; not a policy value.
|
|
if value is None or (cfg_key == "cwd" and str(value).strip() in {".", "auto", "cwd"}):
|
|
continue
|
|
env_var = TERMINAL_CONFIG_ENV_MAP.get(cfg_key)
|
|
if env_var:
|
|
# List/dict config values must be JSON (same contract as
|
|
# apply_terminal_config_to_env). str() yields Python repr, which
|
|
# json.loads in terminal_tool rejects.
|
|
scope[env_var] = _terminal_env_value(value)
|
|
|
|
_apply({**_TOOL_LEVEL_DEFAULTS, **(DEFAULT_CONFIG.get("terminal") or {})})
|
|
default_image = scope.get("TERMINAL_DOCKER_IMAGE")
|
|
env_path = home / ".env"
|
|
if env_path.exists():
|
|
# load_env_file swallows OSError by design (secret scope fails soft); an unreadable
|
|
# profile .env must fail closed here.
|
|
try:
|
|
env_path.read_bytes()
|
|
except Exception as exc:
|
|
raise TerminalPolicyUnavailable(f"cannot read {env_path}: {exc}") from exc
|
|
from agent.secret_scope import load_env_file
|
|
|
|
profile_env = load_env_file(env_path)
|
|
scope.update((k, str(v)) for k, v in profile_env.items() if k.startswith("TERMINAL_"))
|
|
# Provenance, not value: an image WRITTEN in the profile's .env is the user's choice even when
|
|
# it spells the default (same rule apply_terminal_config_to_env applies to a set env var).
|
|
image_pinned = "TERMINAL_DOCKER_IMAGE" in profile_env
|
|
else:
|
|
image_pinned = False
|
|
if env_overlay:
|
|
scope.update((k, str(v)) for k, v in env_overlay.items()
|
|
if k.startswith("TERMINAL_") and k != "TERMINAL_DOCKER_IMAGE_PINNED")
|
|
# The overlay is the LAUNCHER's environment: its pin verdict is about the launcher's profile and
|
|
# is never inherited, and the bridge backfills TERMINAL_DOCKER_IMAGE for defaults too, so only a
|
|
# value that differs from the default can prove a choice made there.
|
|
if env_overlay.get("TERMINAL_DOCKER_IMAGE") not in (None, default_image):
|
|
image_pinned = True
|
|
# Read config.yaml directly, not via read_raw_config() (which collapses "missing" and
|
|
# "unparseable" into {}): present-but-unparseable must fail closed.
|
|
config_path = home / "config.yaml"
|
|
try:
|
|
config_exists = config_path.exists()
|
|
except Exception as exc:
|
|
raise TerminalPolicyUnavailable(f"cannot resolve terminal config in {home}: {exc}") from exc
|
|
if config_exists:
|
|
from utils import load_yaml_file_readonly
|
|
|
|
try:
|
|
# Signature-cached: a scope is rebuilt per routed turn/poll, the file rarely changes.
|
|
raw = load_yaml_file_readonly(config_path)
|
|
except Exception as exc:
|
|
raise TerminalPolicyUnavailable(f"cannot parse {config_path}: {exc}") from exc
|
|
raw_terminal = raw.get("terminal") if isinstance(raw, dict) else None
|
|
if isinstance(raw_terminal, dict):
|
|
_apply(raw_terminal)
|
|
image_pinned = image_pinned or "docker_image" in raw_terminal
|
|
scope["TERMINAL_DOCKER_IMAGE_PINNED"] = "1" if image_pinned else "0"
|
|
_resolve_scope_cwd_placeholder(scope)
|
|
return scope
|
|
|
|
|
|
def _resolve_scope_cwd_placeholder(scope: Dict[str, str]) -> None:
|
|
"""Give a scope with no explicit ``terminal.cwd`` the same resolved ``TERMINAL_CWD`` a standalone
|
|
gateway computes at import (``gateway/run.py``: local backend → ``$HOME``; docker with the
|
|
workspace mount → the host cwd signal; other backends → unset). Without it a routed turn's
|
|
``resolve_agent_cwd()`` falls back to the multiplexer PROCESS cwd (wherever ``hermes gateway``
|
|
was launched), so the system prompt, context-file discovery and the local terminal all run in
|
|
a directory the profile's standalone gateway would never have used."""
|
|
if scope.get("TERMINAL_CWD"):
|
|
return
|
|
from gateway.cwd_placeholder import resolve_placeholder_terminal_cwd
|
|
|
|
resolved = resolve_placeholder_terminal_cwd(
|
|
configured_cwd="", terminal_backend=scope.get("TERMINAL_ENV", ""),
|
|
messaging_cwd=None,
|
|
docker_mount_cwd_to_workspace=scope.get(
|
|
"TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", "false").strip().lower() in {"true", "1", "yes"},
|
|
home_fallback=str(Path.home()),
|
|
)
|
|
if resolved:
|
|
scope["TERMINAL_CWD"] = resolved
|
|
|
|
|
|
def install_profile_terminal_scope(
|
|
hermes_home: "Any", *, env_overlay: Optional[Dict[str, str]] = None) -> Token:
|
|
"""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, env_overlay=env_overlay))
|
|
except TerminalPolicyUnavailable as exc:
|
|
logger.warning("terminal policy unavailable: %s", exc)
|
|
return _terminal_scope_var.set(TerminalPolicyRefusal(str(exc)))
|
|
|
|
|
|
@contextmanager
|
|
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:
|
|
yield
|
|
finally:
|
|
reset_terminal_scope(token)
|
|
|
|
|
|
# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
|
|
# Names external plugins imported from this module before the Sep 2026 decomposition.
|
|
# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
|
|
# The whole block is removed by reverting the commit that added it.
|
|
|
|
def install_refusal_scope(reason: str) -> Token:
|
|
"""Install a refusal scope after :class:`TerminalPolicyUnavailable`.
|
|
|
|
Terminal execution under this scope is rejected (fail closed) instead of
|
|
running under the launch process's ambient policy.
|
|
"""
|
|
return _terminal_scope_var.set(TerminalPolicyRefusal(reason))
|
|
|
|
@contextmanager
|
|
def terminal_scope(mapping: Optional[Dict[str, str]]) -> Iterator[None]:
|
|
"""Context manager form of set/reset_terminal_scope."""
|
|
token = set_terminal_scope(mapping)
|
|
try:
|
|
yield
|
|
finally:
|
|
reset_terminal_scope(token)
|
|
# ---- END PLUGIN-COMPAT ----
|