The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(bot_desktop): Bot Screen, computer_use and the browser run inside the terminal backend (#121169)
Teknium399d9569036d
diff --git a/apps/desktop/src/plugins/hermes-bots/i18n.ts b/apps/desktop/src/plugins/hermes-bots/i18n.tsindex 7916da55fc9..43c3ee196a4 100644--- a/apps/desktop/src/plugins/hermes-bots/i18n.ts+++ b/apps/desktop/src/plugins/hermes-bots/i18n.ts@@ -394,6 +394,11 @@ type BotsMessages = {autoOpenOffToast: (name: string) => stringstoppedTitle: stringstoppedBody: string+ placementSandbox: (backend: string) => string+ imageSwitchTitle: string+ imageSwitchBody: (current: string, target: string) => string+ imageSwitchApprove: string+ imageSwitchKeep: stringstart: stringattaching: stringstreamLost: string@@ -828,6 +833,11 @@ const en: BotsMessages = {autoOpenOffToast: name => `${name}’s Screen stays closed until you open it`,stoppedTitle: 'Screen is off',stoppedBody: 'Start this bot\u2019s desktop to watch what it does and take over when it needs you.',+ placementSandbox: backend => `Screen runs inside the ${backend} sandbox, with the terminal`,+ imageSwitchTitle: 'New sandbox image available',+ imageSwitchBody: (current, target) => `Your sandbox still runs ${current}, which has no desktop. Switching to ${target} recreates the container the next time the bot uses its terminal: files in /root and /workspace stay on this machine, packages installed inside the container are reinstalled on demand.`,+ imageSwitchApprove: 'Switch image',+ imageSwitchKeep: 'Keep current image',start: 'Start screen',attaching: 'Connecting to the screen\u2026',streamLost: 'Screen stream ended',@@ -1262,6 +1272,11 @@ const ja: BotsMessages = {autoOpenOffToast: name => `${name} の Screen は手動で開くまで閉じたままです`,stoppedTitle: '画面はオフです',stoppedBody: 'このボットのデスクトップを起動すると、動作を見守り、必要なときに操作を引き継げます。',+ placementSandbox: backend => `画面は ${backend} サンドボックス内(ターミナルと同じ場所)で動作します`,+ imageSwitchTitle: '新しいサンドボックスイメージがあります',+ imageSwitchBody: (current, target) => `サンドボックスはまだ ${current} で動作しており、デスクトップがありません。${target} に切り替えると、ボットが次にターミナルを使うときにコンテナが再作成されます。/root と /workspace のファイルはこのマシンに残り、コンテナ内にインストールしたパッケージは必要に応じて再インストールされます。`,+ imageSwitchApprove: 'イメージを切り替える',+ imageSwitchKeep: '現在のイメージを使い続ける',start: '画面を起動',attaching: '画面に接続中…',streamLost: '画面ストリームが終了しました',@@ -1680,6 +1695,11 @@ const zh: BotsMessages = {autoOpenOffToast: name => `${name} 的屏幕将保持关闭,直到你手动打开`,stoppedTitle: '屏幕已关闭',stoppedBody: '启动此机器人的桌面,观看它的操作,并在需要时接管。',+ placementSandbox: backend => `屏幕运行在 ${backend} 沙箱内,与终端同处`,+ imageSwitchTitle: '有新的沙箱镜像',+ imageSwitchBody: (current, target) => `沙箱仍在运行 ${current},其中没有桌面。切换到 ${target} 后,机器人下次使用终端时会重建容器:/root 和 /workspace 中的文件保留在本机,容器内安装的软件包会按需重新安装。`,+ imageSwitchApprove: '切换镜像',+ imageSwitchKeep: '保留当前镜像',start: '启动屏幕',attaching: '正在连接屏幕…',streamLost: '屏幕流已结束',@@ -2098,6 +2118,11 @@ const zhHant: BotsMessages = {autoOpenOffToast: name => `${name} 的螢幕將保持關閉,直到你手動開啟`,stoppedTitle: '螢幕已關閉',stoppedBody: '啟動此機器人的桌面,觀看它的操作,並在需要時接手。',+ placementSandbox: backend => `畫面在 ${backend} 沙箱內執行,與終端同處`,+ imageSwitchTitle: '有新的沙箱映像',+ imageSwitchBody: (current, target) => `沙箱仍在執行 ${current},其中沒有桌面。切換到 ${target} 後,機器人下次使用終端時會重建容器:/root 和 /workspace 中的檔案保留在本機,容器內安裝的套件會按需重新安裝。`,+ imageSwitchApprove: '切換映像',+ imageSwitchKeep: '保留目前映像',start: '啟動螢幕',attaching: '正在連線至螢幕…',streamLost: '螢幕串流已結束',diff --git a/apps/desktop/src/plugins/hermes-bots/screen-pane.tsx b/apps/desktop/src/plugins/hermes-bots/screen-pane.tsxindex d8451f3022e..e9f4b6c9c8a 100644--- a/apps/desktop/src/plugins/hermes-bots/screen-pane.tsx+++ b/apps/desktop/src/plugins/hermes-bots/screen-pane.tsx@@ -348,6 +348,24 @@ export function BotScreenPane({ bot }: { bot: RosterRow }) {}}, [bot])+ // The pending default-image switch: both answers pin an image server-side, so the card+ // disappears after either; approve leaves the container to be recreated on next terminal use.+ const decideImageSwitch = useCallback(+ async (approve: boolean) => {+ setBusy(true)++ try {+ const next = await displayRequest<DisplayStatus>(bot, 'display.switchSandboxImage', { approve })+ setScreenStatus(bot, next)+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err))+ } finally {+ setBusy(false)+ }+ },+ [bot]+ )+const takeOver = useCallback(async () => {// The button is disabled without a viewer; the guard keeps a keyboard-activated// stale closure from sending an empty viewer_id the server rejects.@@ -410,6 +428,29 @@ export function BotScreenPane({ bot }: { bot: RosterRow }) {return <ScreenInstallCard bot={bot} onInstalled={next => setScreenStatus(bot, next)} status={status} />}+ if (status && !status.running && status.image_switch) {+ const sw = status.image_switch++ return (+ <div className="grid min-h-48 place-items-center p-6 text-center">+ <div className="flex max-w-md flex-col items-center gap-2">+ <div className="text-sm font-medium">{t.screen.imageSwitchTitle}</div>+ <div className="text-xs text-muted-foreground">{t.screen.imageSwitchBody(sw.current_image, sw.target_image)}</div>+ <div className="flex gap-2">+ <Button disabled={busy} onClick={() => void decideImageSwitch(true)} size="sm">+ {busy ? <GlyphSpinner /> : <Codicon name="arrow-swap" />}+ {t.screen.imageSwitchApprove}+ </Button>+ <Button disabled={busy} onClick={() => void decideImageSwitch(false)} size="sm" variant="ghost">+ {t.screen.imageSwitchKeep}+ </Button>+ </div>+ {error ? <div className="text-xs text-red-500">{error}</div> : null}+ </div>+ </div>+ )+ }+if (status && !status.running) {return (<div className="grid min-h-48 place-items-center p-6 text-center">@@ -438,6 +479,13 @@ export function BotScreenPane({ bot }: { bot: RosterRow }) {{status.display} · {status.geometry}</span>) : null}+ {status?.placement?.startsWith('terminal:') ? (+ // Where the desktop lives matters for what a takeover can reach: inside the terminal's sandbox,+ // not on the gateway host.+ <span className="rounded bg-(--ui-bg-tertiary) px-1.5 py-0.5 text-muted-foreground">+ {t.screen.placementSandbox(status.placement.slice('terminal:'.length))}+ </span>+ ) : null}<span className="grow" />{lease?.holder === 'human' && lease.reason ? (// Why control was taken stays readable while the human acts.diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 59ee1b628b6..7548bf292a9 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -1146,9 +1146,17 @@ export interface DisplayStatus {blocker?: string | nullmemory_available_mb?: number | nullmemory_limit_mb?: number | null+ placement?: string+ image_switch?: DisplayImageSwitch | nulllease: DisplayLeaseprofile_key: string}+/** A persisted Docker sandbox kept on the previous default image; the user decides the switch. */+export interface DisplayImageSwitch {+ current_image: string+ target_image: string+ containers: number+}/** ``tools/bot_desktop/lease.py::Lease`` as clients may see it: the holder's viewer id is a capability and never leaves the gateway; ``viewer_hash`` lets the holder recognise itself. */export interface DisplayLease {holder: LeaseHolder@@ -1183,6 +1191,8 @@ export interface DisplayStopResult {blocker?: string | nullmemory_available_mb?: number | nullmemory_limit_mb?: number | null+ placement?: string+ image_switch?: DisplayImageSwitch | nulllease: DisplayLeaseprofile_key: stringstopped: boolean@@ -1206,12 +1216,39 @@ export interface DisplayObserveResult {blocker?: string | nullmemory_available_mb?: number | nullmemory_limit_mb?: number | null+ placement?: string+ image_switch?: DisplayImageSwitch | nulllease: DisplayLeaseprofile_key: stringticket: stringpath: stringviewer_id: string}+export interface DisplaySwitchSandboxImageParams {+ profile?: string | null+ approve?: boolean+}+export interface DisplaySwitchSandboxImageResult {+ profile: string+ supported: boolean+ installed: boolean+ missing: string[]+ running: boolean+ pid?: number | null+ display?: string | null+ socket?: string | null+ geometry: string+ install_command?: string | null+ browser?: string | null+ blocker?: string | null+ memory_available_mb?: number | null+ memory_limit_mb?: number | null+ placement?: string+ image_switch?: DisplayImageSwitch | null+ lease: DisplayLease+ profile_key: string+ docker_image: string+}export interface DisplayInstallResult {started: booleancommand?: string | null@@ -4310,6 +4347,8 @@ export interface DisplayStatusPayload {blocker?: string | nullmemory_available_mb?: number | nullmemory_limit_mb?: number | null+ placement?: string+ image_switch?: DisplayImageSwitch | nulllease: DisplayLeaseprofile_key: string}@@ -4802,6 +4841,8 @@ export interface RpcMethods {'display.status': { params: ProfileParams; result: DisplayStatus }/** Stop the screen. Refused (5300, code viewer_mismatch) while a human holds unless force. */'display.stop': { params: DisplayStopParams; result: DisplayStopResult }+ /** Decide the pending default sandbox image switch for this profile; refused when none is pending. */+ 'display.switchSandboxImage': { params: DisplaySwitchSandboxImageParams; result: DisplaySwitchSandboxImageResult }/** One JPEG grab of the bot's screen; read-only, never changes the lease. */'display.thumbnail': { params: ProfileParams; result: DisplayThumbnailResult }/** Stage a non-image file into the session workspace and hand back its @file: ref. */@@ -5229,6 +5270,7 @@ export const RPC_METHODS = ['display.start','display.status','display.stop',+ 'display.switchSandboxImage','display.thumbnail','file.attach','free_tier.ack_notice',diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 4a92d2b62a8..bcb93cda2e7 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -942,6 +942,24 @@}}},+ {+ "name": "display.switchSandboxImage",+ "summary": "Decide the pending default sandbox image switch for this profile; refused when none is pending.",+ "params": [+ {+ "name": "params",+ "schema": {+ "$ref": "#/components/schemas/DisplaySwitchSandboxImageParams"+ }+ }+ ],+ "result": {+ "name": "result",+ "schema": {+ "$ref": "#/components/schemas/DisplaySwitchSandboxImageResult"+ }+ }+ },{"name": "display.thumbnail","summary": "One JPEG grab of the bot's screen; read-only, never changes the lease.",@@ -12079,6 +12097,31 @@"title": "DispatchType","type": "string"},+ "DisplayImageSwitch": {+ "additionalProperties": false,+ "description": "A persisted Docker sandbox kept on the previous default image; the user decides the switch.",+ "properties": {+ "current_image": {+ "title": "Current Image",+ "type": "string"+ },+ "target_image": {+ "title": "Target Image",+ "type": "string"+ },+ "containers": {+ "title": "Containers",+ "type": "integer"+ }+ },+ "required": [+ "current_image",+ "target_image",+ "containers"+ ],+ "title": "DisplayImageSwitch",+ "type": "object"+ },"DisplayInstallDonePayload": {"additionalProperties": false,"properties": {@@ -12486,6 +12529,22 @@"default": null,"title": "Memory Limit Mb"},+ "placement": {+ "default": "gateway",+ "title": "Placement",+ "type": "string"+ },+ "image_switch": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/DisplayImageSwitch"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },"lease": {"$ref": "#/components/schemas/DisplayLease"},@@ -12649,6 +12708,22 @@"default": null,"title": "Memory Limit Mb"},+ "placement": {+ "default": "gateway",+ "title": "Placement",+ "type": "string"+ },+ "image_switch": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/DisplayImageSwitch"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },"lease": {"$ref": "#/components/schemas/DisplayLease"},@@ -12796,6 +12871,22 @@"default": null,"title": "Memory Limit Mb"},+ "placement": {+ "default": "gateway",+ "title": "Placement",+ "type": "string"+ },+ "image_switch": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/DisplayImageSwitch"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },"lease": {"$ref": "#/components/schemas/DisplayLease"},@@ -12974,6 +13065,22 @@"default": null,"title": "Memory Limit Mb"},+ "placement": {+ "default": "gateway",+ "title": "Placement",+ "type": "string"+ },+ "image_switch": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/DisplayImageSwitch"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },"lease": {"$ref": "#/components/schemas/DisplayLease"},@@ -13000,6 +13107,198 @@"title": "DisplayStopResult","type": "object"},+ "DisplaySwitchSandboxImageParams": {+ "additionalProperties": false,+ "properties": {+ "profile": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Profile"+ },+ "approve": {+ "default": true,+ "title": "Approve",+ "type": "boolean"+ }+ },+ "title": "DisplaySwitchSandboxImageParams",+ "type": "object"+ },+ "DisplaySwitchSandboxImageResult": {+ "additionalProperties": false,+ "properties": {+ "profile": {+ "title": "Profile",+ "type": "string"+ },+ "supported": {+ "title": "Supported",+ "type": "boolean"+ },+ "installed": {+ "title": "Installed",+ "type": "boolean"+ },+ "missing": {+ "items": {+ "type": "string"+ },+ "title": "Missing",+ "type": "array"+ },+ "running": {+ "title": "Running",+ "type": "boolean"+ },+ "pid": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Pid"+ },+ "display": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Display"+ },+ "socket": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Socket"+ },+ "geometry": {+ "title": "Geometry",+ "type": "string"+ },+ "install_command": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Install Command"+ },+ "browser": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Browser"+ },+ "blocker": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Blocker"+ },+ "memory_available_mb": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Memory Available Mb"+ },+ "memory_limit_mb": {+ "anyOf": [+ {+ "type": "integer"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Memory Limit Mb"+ },+ "placement": {+ "default": "gateway",+ "title": "Placement",+ "type": "string"+ },+ "image_switch": {+ "anyOf": [+ {+ "$ref": "#/components/schemas/DisplayImageSwitch"+ },+ {+ "type": "null"+ }+ ],+ "default": null+ },+ "lease": {+ "$ref": "#/components/schemas/DisplayLease"+ },+ "profile_key": {+ "title": "Profile Key",+ "type": "string"+ },+ "docker_image": {+ "title": "Docker Image",+ "type": "string"+ }+ },+ "required": [+ "profile",+ "supported",+ "installed",+ "missing",+ "running",+ "geometry",+ "lease",+ "profile_key",+ "docker_image"+ ],+ "title": "DisplaySwitchSandboxImageResult",+ "type": "object"+ },"DisplayThumbnailResult": {"additionalProperties": false,"description": "``data_url`` is null while the screen is stopped or while a human holds the lease\n(``suppressed``): the frame may show what they are typing.",diff --git a/cli-config.yaml.example b/cli-config.yaml.exampleindex ee68877fc20..bf4ea78b9b9 100644--- a/cli-config.yaml.example+++ b/cli-config.yaml.example@@ -7,7 +7,7 @@# Schema version of this file. The installers copy it to seed config.yaml, and# `hermes update` uses it to know which one-time migrations the file already# has. Hermes manages it: do not copy it into another config.-_config_version: 47+_config_version: 48# =============================================================================# Database Configuration@@ -459,7 +459,7 @@ terminal:# cwd: "/workspace" # Path INSIDE the container (default: /)# timeout: 180# lifetime_seconds: 300-# docker_image: "nikolaik/python-nodejs:python3.11-nodejs20"+# docker_image: "nousresearch/hermes-sandbox:desktop"# docker_mount_cwd_to_workspace: true # Explicit opt-in: mount your launch cwd into /workspace# # Optional: run the container as your host user's uid:gid so files written# # into bind-mounted dirs are owned by you, not root. Drops SETUID/SETGID@@ -489,7 +489,7 @@ terminal:# cwd: "/workspace" # Path INSIDE the container (default: /root)# timeout: 180# lifetime_seconds: 300-# singularity_image: "docker://nikolaik/python-nodejs:python3.11-nodejs20"+# singularity_image: "docker://nousresearch/hermes-sandbox:desktop"# -----------------------------------------------------------------------------# OPTION 5: Modal cloud execution@@ -501,7 +501,7 @@ terminal:# cwd: "/workspace" # Path INSIDE the sandbox (default: /root)# timeout: 180# lifetime_seconds: 300-# modal_image: "nikolaik/python-nodejs:python3.11-nodejs20"+# modal_image: "nousresearch/hermes-sandbox:desktop"# -----------------------------------------------------------------------------# OPTION 6: Daytona cloud execution@@ -514,7 +514,7 @@ terminal:# cwd: "~"# timeout: 180# lifetime_seconds: 300-# daytona_image: "nikolaik/python-nodejs:python3.11-nodejs20"+# daytona_image: "nousresearch/hermes-sandbox:desktop"# container_disk: 10240 # Daytona max is 10GB per sandbox#diff --git a/hermes_cli/cli_config_load.py b/hermes_cli/cli_config_load.pyindex 78fa2ba3504..b8c5b301561 100644--- a/hermes_cli/cli_config_load.py+++ b/hermes_cli/cli_config_load.py@@ -184,7 +184,7 @@ def _mirror_config_to_env(defaults, _file_has_terminal_config):def _cli_config_defaults():"""Built-in defaults for every config key the CLI reads (the file overlays these)."""- img = "nikolaik/python-nodejs:python3.11-nodejs20"+ from hermes_cli.config_defaults import DEFAULT_SANDBOX_IMAGE as imgreturn {"model": {"default": "", "base_url": "", "provider": "auto"},"terminal": {diff --git a/hermes_cli/cli_tui_runtime_mixin.py b/hermes_cli/cli_tui_runtime_mixin.pyindex 9eeb62a6310..10f502ea164 100644--- a/hermes_cli/cli_tui_runtime_mixin.py+++ b/hermes_cli/cli_tui_runtime_mixin.py@@ -249,6 +249,15 @@ class CLITuiRuntimeMixin:self._maybe_offer_first_run_setup()except Exception:logger.debug("first-run setup offer failed", exc_info=True)+ # A persisted Docker sandbox on the previous default image is kept until the user says+ # so; this TTY is where they can. Either answer pins an image, so it is asked once.+ if sys.stdin.isatty():+ try:+ from hermes_cli.sandbox_image_switch import offer_interactive+ from cli import _cprint+ offer_interactive(cprint=_cprint)+ except Exception:+ logger.debug("sandbox image switch offer failed", exc_info=True)if self._resumed and self._preload_resumed_session():self._display_resumed_history()diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex da860f6d9bf..8bf52ecef40 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -2167,6 +2167,14 @@ def apply_terminal_config_to_env(if not (config is not None or "backend" in raw_terminal_cfg):backend_sources = backend_sources[::-1] # env wins when the file did not set backendterminal_backend = str(backend_sources[0] or backend_sources[1] or "")+ # Whether docker_image is the user's choice (config.yaml key, or TERMINAL_DOCKER_IMAGE set before+ # any bridge ran) or the shipped default. DockerEnvironment recreates a persisted container on+ # image mismatch only for a pinned image; a default flip keeps the user's sandbox and asks.+ # Children inherit both vars, so a launcher's verdict is kept unless the file pins it.+ if should_override and "docker_image" in explicit_keys:+ target["TERMINAL_DOCKER_IMAGE_PINNED"] = "1"+ elif "TERMINAL_DOCKER_IMAGE_PINNED" not in target:+ target["TERMINAL_DOCKER_IMAGE_PINNED"] = "1" if "TERMINAL_DOCKER_IMAGE" in target else "0"for cfg_key, env_var in TERMINAL_CONFIG_ENV_MAP.items():if cfg_key not in terminal_cfg:@@ -2968,7 +2976,7 @@ def _show_terminal_section(config: Dict[str, Any]) -> None:print(f" Timeout: {terminal.get('timeout', 60)}s")configured = lambda *names: 'configured' if all(get_env_value(n) for n in names) else '(not set)' # noqa: E731- default_img = 'nikolaik/python-nodejs:python3.14-nodejs22'+ from hermes_cli.config_defaults import DEFAULT_SANDBOX_IMAGE as default_imgbackend_lines = {'docker': lambda: [f" Docker image: {terminal.get('docker_image', default_img)}"],'singularity': lambda: [f" Image: {terminal.get('singularity_image', 'docker://' + default_img)}"],diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 9f605c65ec7..1e60ed36130 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -5,6 +5,15 @@ docs of config.yaml."""+#: Image every container terminal backend (docker/modal/daytona/singularity) uses unless the+#: user pins one. LEGACY_SANDBOX_IMAGES are the plain defaults that preceded the desktop stack+#: (the 3.14 pin shipped between the two without a migration); a saved config still holding one+#: is the template copied, and the config migration unsets it, never a user's own pin.+DEFAULT_SANDBOX_IMAGE = "nousresearch/hermes-sandbox:desktop"+LEGACY_SANDBOX_IMAGES = ("nikolaik/python-nodejs:python3.11-nodejs20", "nikolaik/python-nodejs:python3.14-nodejs22")+LEGACY_SANDBOX_IMAGE = LEGACY_SANDBOX_IMAGES[0]++def _aux(timeout, *, reasoning_effort=True, **extra):"""Standard auxiliary-task model block (see DEFAULT_CONFIG["auxiliary"]).@@ -335,15 +344,18 @@ DEFAULT_CONFIG = {# go first because n/nvm/asdf write PATH exports there without an interactivity guard. Turn# off if an rc file misbehaves when sourced non-interactively (exits on TTY check)."auto_source_bashrc": True,- "docker_image": "nikolaik/python-nodejs:python3.14-nodejs22",+ # The default sandbox for every container backend: the nikolaik/python-nodejs base+ # (Python 3.13 / Node 26) plus a display stack, so Bot Screen, computer_use and the+ # bot's browser run INSIDE the sandbox and the pane can watch them (see bot_desktop).+ "docker_image": DEFAULT_SANDBOX_IMAGE,"docker_forward_env": [],# Exact key-value env pairs set inside Docker containers (unlike docker_forward_env, which# reads host values) — useful under systemd without the user's shell env. Example:# {"SSH_AUTH_SOCK": "/run/user/1000/ssh-agent.sock"}"docker_env": {},- "singularity_image": "docker://nikolaik/python-nodejs:python3.14-nodejs22",- "modal_image": "nikolaik/python-nodejs:python3.14-nodejs22",- "daytona_image": "nikolaik/python-nodejs:python3.14-nodejs22",+ "singularity_image": f"docker://{DEFAULT_SANDBOX_IMAGE}",+ "modal_image": DEFAULT_SANDBOX_IMAGE,+ "daytona_image": DEFAULT_SANDBOX_IMAGE,"vercel_runtime": "node24", # vercel_sandbox backend only: node24 | node22 | python3.13# Container limits (docker, singularity, modal, daytona, vercel_sandbox; not local/ssh)."container_cpu": 1,@@ -2507,6 +2519,16 @@ DEFAULT_CONFIG = {# long; it restarts on the next use. Idle Xvnc + Xfce hold ~220 MB, an abandoned browser far more.# 0 keeps screens up until stopped."idle_stop_minutes": 30,+ # Where the screen (and with it computer_use and the bot's browser) runs.+ # auto follow the terminal backend: inside the docker / ssh / singularity sandbox when one is+ # configured, on the gateway host when terminal.backend is local. A sandbox backend that+ # cannot host a screen (modal, daytona, vercel) REFUSES rather than quietly running the+ # desktop on the host beside the sandbox you chose for the agent.+ # terminal always inside the terminal backend (error when it cannot host one).+ # gateway always on the gateway host, even with a sandbox terminal: the agent's screen, browser+ # and computer_use then act OUTSIDE the terminal sandbox. Explicit opt-in.+ # The sandbox image needs the desktop stack: nousresearch/hermes-sandbox:desktop.+ "placement": "auto",},"computer_use": {# cua-driver's upstream PostHog telemetry defaults ON; Hermes sets@@ -2680,7 +2702,7 @@ DEFAULT_CONFIG = {# Extra ports detection probes for an external llama-server (besides 8080)."detect_ports": [],},- "_config_version": 47, # Config schema version - bump this when adding new required fields+ "_config_version": 48, # Config schema version - bump this when adding new required fields}diff --git a/hermes_cli/config_migrations.py b/hermes_cli/config_migrations.pyindex 1f087fee1e5..3455f2ec37b 100644--- a/hermes_cli/config_migrations.py+++ b/hermes_cli/config_migrations.py@@ -631,6 +631,29 @@ def _migrate_to_46(results: Dict[str, Any], quiet: bool) -> None:f" ✓ Turned off MCP servers the profile editor had marked disabled: {names}.")+def _migrate_to_48(results: Dict[str, Any], quiet: bool) -> None:+ # 47 → 48: the container sandbox default gains a display stack (nousresearch/hermes-sandbox:+ # desktop) so Bot Screen / computer_use / the browser run inside the sandbox. A saved value+ # still equal to the OLD default is the template copied, not a choice: the key is DROPPED so+ # the file follows the default. It is not rewritten to the new image, because a written image+ # is a pin and a pin recreates a persisted Docker container without asking; unpinned, the+ # runtime keeps an existing sandbox and the CLI / Screen pane ask first. A pinned image stays.+ from hermes_cli.config_defaults import DEFAULT_SANDBOX_IMAGE, LEGACY_SANDBOX_IMAGES+ for legacy in LEGACY_SANDBOX_IMAGES:+ for key, old in (+ ("docker_image", legacy),+ ("modal_image", legacy),+ ("daytona_image", legacy),+ ("singularity_image", f"docker://{legacy}"),+ ):+ _rewrite_stale_default(+ section="terminal", key=key, old=old, new=None,+ added=f"terminal.{key} unset (follows the default, {DEFAULT_SANDBOX_IMAGE})",+ message=f" ✓ terminal.{key}: was the old default; now follows the default sandbox image "+ f"({DEFAULT_SANDBOX_IMAGE})",+ )(results, quiet)++#: Registry of (target_version, step), strictly ascending; simple default-flip steps are#: declared inline via _rewrite_stale_default / _rewrite_key partials. Later steps observe#: earlier steps' writes via read_raw_config() (filesystem state). v12 is the support floor:@@ -765,6 +788,8 @@ MIGRATIONS: Tuple[Tuple[int, Callable[[Dict[str, Any], bool], None]], ...] = (" ✓ Removed compression.threshold_tokens: 256000 — the old default. Compaction ""follows compression.threshold (50% of the window) again. Set threshold_tokens ""to a token count to cap it on purpose."))),+ # 47 → 48: a saved old-default sandbox image is dropped so the file follows the new default (see _migrate_to_48).+ (48, _migrate_to_48),)#: Steps triggered by a legacy key or identifier (a renamed or retired key, a removed plugin ordiff --git a/hermes_cli/sandbox_image_switch.py b/hermes_cli/sandbox_image_switch.pynew file mode 100644index 00000000000..b5bbdb81a42--- /dev/null+++ b/hermes_cli/sandbox_image_switch.py@@ -0,0 +1,142 @@+"""Approval gate for the default sandbox image change (nikolaik base → hermes-sandbox:desktop).++A persisted Docker sandbox is state the user built up; a default flip must not replace it under+them. ``DockerEnvironment`` keeps a container whose image differs from an UNPINNED default and+this module is where the user decides: approve (pin the new image; the next terminal use+recreates the container — ``/root`` and ``/workspace`` are host mounts and carry over, system+packages get reinstalled, 3.11 venvs need a rebuild) or keep (pin the image the container runs,+which also ends the notice). Surfaces: the interactive CLI startup offer here, the Screen pane's+switch action (``display.switchSandboxImage``) and the plain ``hermes config set``. Headless+surfaces (gateway, cron) never decide; they keep the sandbox and log.++Modal restores its snapshot and Daytona reuses its labeled sandbox regardless of the configured+image, so existing sandboxes there are untouched without any gate; only fresh ones get the new+image.+"""++from __future__ import annotations++import logging+import os+from dataclasses import dataclass, field+from typing import Optional++logger = logging.getLogger(__name__)+++@dataclass+class PendingSwitch:+ current_image: str # what the persisted container runs+ target_image: str # the effective default it would move to+ containers: list[str] = field(default_factory=list) # names, for the notice+++def pending() -> Optional[PendingSwitch]:+ """The switch this profile still has to decide, or None: backend is docker, the image is the+ unpinned default, and a container labeled for this profile runs another image. ``docker`` is+ consulted (one ``ps``); any failure is "nothing pending"."""+ from hermes_cli.config import load_config_readonly+ from tools.environments.docker import _container_identity, _docker_query, find_docker++ terminal = (load_config_readonly() or {}).get("terminal") or {}+ if terminal.get("backend") != "docker":+ return None+ if _image_pinned(terminal):+ return None+ target = str(terminal.get("docker_image") or "")+ docker = find_docker()+ if not docker or not target:+ return None+ listing = _docker_query(+ [docker, "ps", "-a", "--filter", "label=hermes-agent=1",+ "--filter", f"label=hermes-profile={_container_identity(str(terminal.get('docker_shared_container_key') or ''))}",+ "--format", "{{.Names}}\t{{.Image}}"],+ timeout=10, fail="sandbox image switch probe failed: %s", nonzero="docker ps exited %s: %s")+ if listing is None:+ return None+ stale: dict[str, list[str]] = {}+ for line in listing.stdout.splitlines():+ name, _, image = line.partition("\t")+ if image and image != target:+ stale.setdefault(image, []).append(name)+ if not stale:+ return None+ current = max(stale, key=lambda img: len(stale[img]))+ return PendingSwitch(current_image=current, target_image=target,+ containers=sorted(n for names in stale.values() for n in names))+++def _image_pinned(terminal_cfg: dict) -> bool:+ """Same verdict the runtime uses. The file's own key first; then the bound terminal scope+ (a routed profile: recomputed per turn, never the launch profile's ``os.environ``); else the+ launch env, where an operator's ``TERMINAL_DOCKER_IMAGE`` differing from the effective value+ is their choice."""+ from hermes_cli.config import read_raw_config+ from tools.terminal_scope import get_terminal_scope+ raw = read_raw_config().get("terminal")+ if isinstance(raw, dict) and "docker_image" in raw:+ return True+ scope = get_terminal_scope()+ if scope is not None:+ return scope.get("TERMINAL_DOCKER_IMAGE_PINNED") == "1"+ env_image = os.environ.get("TERMINAL_DOCKER_IMAGE")+ return bool(env_image) and env_image != str(terminal_cfg.get("docker_image") or "")+++def decide(switch: PendingSwitch, approve: bool) -> str:+ """Pin ``terminal.docker_image`` to the target (approve) or the current image (keep) and+ re-bridge the live process so a long-running gateway/TUI backend acts on it without a+ restart. Returns the image now pinned."""+ from hermes_cli.config import apply_terminal_config_to_env, load_config, save_config+ image = switch.target_image if approve else switch.current_image+ config = load_config()+ terminal = config.setdefault("terminal", {})+ terminal["docker_image"] = image+ save_config(config, preserve_keys={("terminal", "docker_image")})+ apply_terminal_config_to_env(env=None, override=True)+ if approve:+ # The cached environment object still points at the old container; drop it so the next+ # terminal call reattaches, sees the pin and recreates. The container itself keeps running+ # until then (persistent), nothing is removed here.+ from tools.terminal_tool_lifecycle import _evict_environment_for_task+ _evict_environment_for_task(None)+ return image+++def explain_lines(switch: PendingSwitch) -> list[str]:+ n = len(switch.containers)+ return [+ f"Your Docker sandbox ({n} container{'s' if n != 1 else ''}) runs {switch.current_image}.",+ f"The default sandbox image is now {switch.target_image}: Python 3.13, Node 26, and a desktop",+ "so Bot Screen, computer_use and the browser run inside the sandbox instead of on this machine.",+ "Switching recreates the container on the next terminal call. Files in /root and /workspace",+ "stay (they live on this machine); packages installed with apt/pip/npm -g inside the container",+ "are reinstalled on demand; Python 3.11 virtualenvs need a rebuild.",+ ]+++def offer_interactive(*, cprint, ask=input) -> Optional[bool]:+ """TTY startup offer. Either answer pins an image, so the question is asked once. Returns the+ decision, or None when nothing was pending / the user skipped (asked again next start)."""+ switch = pending()+ if switch is None:+ return None+ cprint("")+ cprint("☤ A new default sandbox image is available.")+ for line in explain_lines(switch):+ cprint(f" {line}")+ try:+ answer = ask(" Switch now? [y = switch / n = keep the current image / Enter = ask later]: ").strip().lower()+ except (KeyboardInterrupt, EOFError):+ print()+ return None+ if answer in {"y", "yes"}:+ decide(switch, approve=True)+ cprint(f" ✓ terminal.docker_image = {switch.target_image}; the sandbox is recreated on its next use.")+ return True+ if answer in {"n", "no"}:+ decide(switch, approve=False)+ cprint(f" ✓ terminal.docker_image = {switch.current_image}; unset it in config.yaml to be asked again.")+ return False+ cprint(" Later. `hermes config set terminal.docker_image <image>` decides it any time.")+ return Nonediff --git a/hermes_cli/setup_terminal.py b/hermes_cli/setup_terminal.pyindex f7381270fcf..077f6a7950e 100644--- a/hermes_cli/setup_terminal.py+++ b/hermes_cli/setup_terminal.py@@ -13,7 +13,7 @@ from hermes_cli import nous_subscriptionlogger = logging.getLogger("hermes_cli.setup")-_SANDBOX_IMAGE = "nikolaik/python-nodejs:python3.11-nodejs20"+from hermes_cli.config_defaults import DEFAULT_SANDBOX_IMAGE as _SANDBOX_IMAGE_RUN_KW = dict(capture_output=True, text=True, encoding="utf-8", errors="replace")diff --git a/hermes_cli/status.py b/hermes_cli/status.pyindex aeaa2ebcac7..9dfa30ca2b3 100644--- a/hermes_cli/status.py+++ b/hermes_cli/status.py@@ -13,6 +13,7 @@ PROJECT_ROOT = Path(__file__).parent.parent.resolve()from hermes_cli.auth import AuthError, resolve_providerfrom hermes_cli.colors import Colors, colorfrom hermes_cli.config import get_env_path, get_env_value, get_hermes_home, load_config+from hermes_cli.config_defaults import DEFAULT_SANDBOX_IMAGEfrom hermes_cli.models import provider_labelfrom hermes_cli.runtime_provider import resolve_requested_providerfrom hermes_cli.vercel_auth import describe_vercel_auth@@ -107,8 +108,8 @@ def _estop_status_line():# Simple env-driven terminal backends: (label, env var, default, empty-counts-as-unset)._TERMINAL_ENV_ROWS = {"ssh": (("SSH Host:", "TERMINAL_SSH_HOST", "(not set)", True), ("SSH User:", "TERMINAL_SSH_USER", "(not set)", True)),- "docker": (("Docker Image:", "TERMINAL_DOCKER_IMAGE", "python:3.11-slim", False),),- "daytona": (("Daytona Image:", "TERMINAL_DAYTONA_IMAGE", "nikolaik/python-nodejs:python3.11-nodejs20", False),),+ "docker": (("Docker Image:", "TERMINAL_DOCKER_IMAGE", DEFAULT_SANDBOX_IMAGE, False),),+ "daytona": (("Daytona Image:", "TERMINAL_DAYTONA_IMAGE", DEFAULT_SANDBOX_IMAGE, False),),}_PLATFORMS = { # name -> (token env var, home-channel env var or None)diff --git a/hermes_cli/web_routers/display.py b/hermes_cli/web_routers/display.pyindex 62e78ce3526..9278775ff84 100644--- a/hermes_cli/web_routers/display.py+++ b/hermes_cli/web_routers/display.py@@ -89,6 +89,34 @@ async def display_ws(ws: WebSocket) -> None:await _bridge(ws, info)+async def _open_rfb(profile_home: Path):+ """``(reader, writer, relay)`` for THIS profile's Xvnc. Gateway-hosted screen: its unix socket. Screen inside+ the terminal backend: a ``docker exec`` / ``ssh`` relay whose stdio IS the RFB stream (``relay`` is that+ Popen; None for a socket). Raises OSError when nothing is running."""+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override+ from tools.bot_desktop import runtime as _bd_runtime+ token = set_hermes_home_override(profile_home)+ try:+ if _bd_runtime.sandbox_screen_running():+ relay = _bd_runtime.open_rfb_stream()+ else:+ sock = profile_home / "bot-desktop" / "rfb.sock"+ if not sock.exists():+ raise OSError("rfb.sock missing")+ reader, writer = await asyncio.open_unix_connection(str(sock))+ return reader, writer, None+ finally:+ reset_hermes_home_override(token)+ loop = asyncio.get_running_loop()+ reader = asyncio.StreamReader()+ await loop.connect_read_pipe(lambda: asyncio.StreamReaderProtocol(reader), relay.stdout)+ # StreamReaderProtocol (not the bare FlowControlMixin) so ``writer.wait_closed()`` in the bridge's teardown has+ # a close waiter to await; on the bare mixin it raises NotImplementedError.+ w_transport, w_protocol = await loop.connect_write_pipe(lambda: asyncio.StreamReaderProtocol(asyncio.StreamReader()), relay.stdin)+ writer = asyncio.StreamWriter(w_transport, w_protocol, None, loop)+ return reader, writer, relay++async def _bridge(ws: WebSocket, info: dict) -> None:"""Pump RFB bytes between the viewer socket (already accepted) and THIS profile's Xvnc, gated bythe lease."""@@ -97,18 +125,14 @@ async def _bridge(ws: WebSocket, info: dict) -> None:from tools.bot_desktop.rfb_filter import RfbClientFilterfrom pathlib import Path- sock = Path(info["hermes_home"]) / "bot-desktop" / "rfb.sock"profile_home = str(info["hermes_home"])profile_key = hermes_home_key(profile_home)viewer_id = str(info.get("viewer_id") or info.get("user_id") or "viewer")- if not sock.exists():- await ws.close(code=_CLOSE_DESKTOP_GONE, reason="Bot Desktop is not running")- returntry:- reader, writer = await asyncio.open_unix_connection(str(sock))+ reader, writer, relay = await _open_rfb(Path(profile_home))except OSError as exc:- _log.warning("display ws: cannot reach RFB socket %s: %s", sock, exc)- await ws.close(code=_CLOSE_DESKTOP_GONE, reason="Bot Desktop socket unreachable")+ _log.warning("display ws: cannot reach RFB endpoint for %s: %s", profile_home, exc)+ await ws.close(code=_CLOSE_DESKTOP_GONE, reason="Bot Desktop is not running")returnloop = asyncio.get_running_loop()@@ -207,6 +231,8 @@ async def _bridge(ws: WebSocket, info: dict) -> None:await writer.wait_closed()except OSError: # Xvnc already gone (ECONNRESET / EPIPE on the FIN)pass+ if relay is not None:+ relay.kill() # the exec client; Xvnc inside the sandbox stays up# Closing the viewer window hands control back. A DROPPED link (laptop lid, Wi-Fi, 1006)# keeps the human's exclusion: they may be mid-login on that screen and the agent must not# resume into it. The Desktop reconnects into the same lease, or the human hands back.diff --git a/tests/agent/test_moa_loop_mode.py b/tests/agent/test_moa_loop_mode.pyindex 59639c0b084..67e49db0f69 100644--- a/tests/agent/test_moa_loop_mode.py+++ b/tests/agent/test_moa_loop_mode.py@@ -1019,6 +1019,7 @@ def test_late_completing_interrupted_reference_feeds_accounting_sink(monkeypatch"""A reference still in flight at interrupt time gets a placeholder inthe results, but its eventual REAL accounting must reach the sink."""import threading+ import timefrom agent import moa_loop@@ -1065,10 +1066,14 @@ def test_late_completing_interrupted_reference_feeds_accounting_sink(monkeypatch# …then completes late; its real billed usage must reach the sink.release.set()- assert sink_seen.wait(timeout=5), "late accounting sink never called"- label, acct = sink_calls[0]- assert "wedged" in label- assert acct.usage.input_tokens == 21+ # Under load the poll loop can see the interrupt before it collects the fast slot too, so fast may+ # also arrive late and first; the contract is about the wedged slot's row, not sink ordering.+ deadline = time.monotonic() + 5+ while not any("wedged" in label for label, _ in sink_calls) and time.monotonic() < deadline:+ sink_seen.wait(timeout=0.2)+ wedged = [acct for label, acct in sink_calls if "wedged" in label]+ assert wedged, f"late accounting for the wedged slot never reached the sink: {[l for l, _ in sink_calls]}"+ assert wedged[0].usage.input_tokens == 21def test_facade_does_not_cache_interrupted_reference_results(monkeypatch, tmp_path):diff --git a/tests/hermes_cli/test_config_migration_48_sandbox_image.py b/tests/hermes_cli/test_config_migration_48_sandbox_image.pynew file mode 100644index 00000000000..f09ab6ffd77--- /dev/null+++ b/tests/hermes_cli/test_config_migration_48_sandbox_image.py@@ -0,0 +1,41 @@+"""Migration 47→48: the container sandbox default becomes nousresearch/hermes-sandbox:desktop.++Contract: a saved image still equal to the OLD default is dropped, so the file follows the new+default at read time but the runtime still sees it as "not pinned" (an existing persisted Docker+sandbox is kept and the user is asked before it is replaced). An image the user pinned+themselves is never touched. Driven through ``run_migrations`` against a temp home.+"""++import os+from unittest.mock import patch++import hermes_yaml as yaml+++def _run(tmp_path, config):+ from hermes_cli.config_migrations import run_migrations++ (tmp_path / "config.yaml").write_text(yaml.safe_dump(config), encoding="utf-8")+ with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):+ run_migrations(46, {"env_added": [], "config_added": [], "warnings": []}, quiet=True)+ return yaml.safe_load((tmp_path / "config.yaml").read_text(encoding="utf-8"))["terminal"]+++def test_stale_default_is_dropped_and_a_user_pin_survives(tmp_path):+ from hermes_cli.config import load_config+ from hermes_cli.config_defaults import DEFAULT_SANDBOX_IMAGE, LEGACY_SANDBOX_IMAGE, LEGACY_SANDBOX_IMAGES++ terminal = _run(tmp_path, {"_config_version": 46, "terminal": {+ "backend": "docker",+ "docker_image": LEGACY_SANDBOX_IMAGE,+ "daytona_image": LEGACY_SANDBOX_IMAGES[1], # the 3.14 pin that shipped between the two, unmigrated+ "singularity_image": f"docker://{LEGACY_SANDBOX_IMAGE}",+ "modal_image": "ghcr.io/me/custom:1",+ }})+ assert "docker_image" not in terminal, "the old default is the template copied, not a pin: drop it"+ assert "singularity_image" not in terminal+ assert "daytona_image" not in terminal, "both plain defaults are template copies"+ assert terminal["modal_image"] == "ghcr.io/me/custom:1", "a user's own image must never be rewritten"+ with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):+ merged = load_config()["terminal"]+ assert merged["docker_image"] == DEFAULT_SANDBOX_IMAGE, "the dropped key follows the new default"diff --git a/tests/hermes_cli/test_sandbox_image_switch.py b/tests/hermes_cli/test_sandbox_image_switch.pynew file mode 100644index 00000000000..4a66eb797e5--- /dev/null+++ b/tests/hermes_cli/test_sandbox_image_switch.py@@ -0,0 +1,204 @@+"""The default sandbox image change is a decision, not a surprise.++Two contracts, exercised through the real config loader, both env bridges and the module the CLI+startup offer and the Screen pane call:++* ``TERMINAL_DOCKER_IMAGE_PINNED`` tells the runtime whether ``docker_image`` is the user's+ choice (config.yaml key, or TERMINAL_DOCKER_IMAGE set before any bridge) or the shipped+ default — for the launch-profile bridge and for a routed profile's terminal scope alike.+* ``sandbox_image_switch``: a pending switch exists only for docker + unpinned + a labeled+ container on another image; approve pins the target, keep pins the current image, and either+ answer ends the offer. A fake ``docker`` binary on PATH stands in for the daemon.+"""++import os+import stat+from pathlib import Path+import pytest+import hermes_yaml as yaml+++def home(tmp_path, monkeypatch):+ h = tmp_path / ".hermes"+ h.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(h))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ for var in ("TERMINAL_ENV", "TERMINAL_DOCKER_IMAGE", "TERMINAL_DOCKER_IMAGE_PINNED"):+ monkeypatch.delenv(var, raising=False)+ return h+++def _write(home: Path, terminal: dict) -> None:+ (home / "config.yaml").write_text(yaml.safe_dump({"terminal": terminal}), encoding="utf-8")+++# ── pin verdict, launch-profile bridge ──────────────────────────────────────────────────────────++def test_bridge_marks_default_image_unpinned_and_file_key_pinned(home):+ from hermes_cli.config import apply_terminal_config_to_env+ from hermes_cli.config_defaults import DEFAULT_SANDBOX_IMAGE++ _write(home, {"backend": "docker"})+ env = apply_terminal_config_to_env(env={})+ assert env["TERMINAL_DOCKER_IMAGE"] == DEFAULT_SANDBOX_IMAGE+ assert env["TERMINAL_DOCKER_IMAGE_PINNED"] == "0"++ # Pinning to the value that EQUALS the default is still a pin: the approval writes exactly this.+ _write(home, {"backend": "docker", "docker_image": DEFAULT_SANDBOX_IMAGE})+ env = apply_terminal_config_to_env(env={}, override=True)+ assert env["TERMINAL_DOCKER_IMAGE_PINNED"] == "1"+++def test_bridge_treats_a_preset_env_image_as_pinned_and_keeps_a_launcher_verdict(home):+ from hermes_cli.config import apply_terminal_config_to_env++ _write(home, {"backend": "docker"})+ env = apply_terminal_config_to_env(env={"TERMINAL_DOCKER_IMAGE": "ghcr.io/me/mine:1"})+ assert env["TERMINAL_DOCKER_IMAGE_PINNED"] == "1", "an operator's env var is their choice"++ # A child inherits the launcher's bridged image AND its verdict; the child bridge keeps it.+ env = apply_terminal_config_to_env(env={"TERMINAL_DOCKER_IMAGE": "whatever", "TERMINAL_DOCKER_IMAGE_PINNED": "0"})+ assert env["TERMINAL_DOCKER_IMAGE_PINNED"] == "0"+++# ── pin verdict, routed profile scope ───────────────────────────────────────────────────────────++def test_terminal_scope_recomputes_the_pin_per_profile(home, tmp_path):+ from tools.terminal_scope import build_profile_terminal_scope+ from hermes_cli.config_defaults import DEFAULT_SANDBOX_IMAGE++ _write(home, {"backend": "docker"})+ scope = build_profile_terminal_scope(home, env_overlay={"TERMINAL_DOCKER_IMAGE_PINNED": "1"})+ assert scope["TERMINAL_DOCKER_IMAGE"] == DEFAULT_SANDBOX_IMAGE+ assert scope["TERMINAL_DOCKER_IMAGE_PINNED"] == "0", "the launch overlay's verdict is never inherited"++ other = tmp_path / "profiles" / "b"+ other.mkdir(parents=True)+ _write(other, {"backend": "docker", "docker_image": "ghcr.io/me/mine:1"})+ scope = build_profile_terminal_scope(other)+ assert scope["TERMINAL_DOCKER_IMAGE_PINNED"] == "1"++ (other / ".env").write_text("TERMINAL_DOCKER_IMAGE=ghcr.io/me/env:2\n", encoding="utf-8")+ _write(other, {"backend": "docker"})+ assert build_profile_terminal_scope(other)["TERMINAL_DOCKER_IMAGE_PINNED"] == "1"+++# ── the switch module against a fake docker ─────────────────────────────────────────────────────++def test_terminal_scope_pins_an_image_written_in_the_profile_env_even_when_it_spells_the_default(home):+ """Provenance, not value: the approval writes the default's exact tag, and a profile whose .env carries+ TERMINAL_DOCKER_IMAGE chose it. The scope must agree with the bridge's verdict for the same input."""+ from tools.terminal_scope import build_profile_terminal_scope+ from hermes_cli.config_defaults import DEFAULT_SANDBOX_IMAGE++ _write(home, {"backend": "docker"})+ (home / ".env").write_text(f"TERMINAL_DOCKER_IMAGE={DEFAULT_SANDBOX_IMAGE}\n", encoding="utf-8")+ scope = build_profile_terminal_scope(home)+ assert scope["TERMINAL_DOCKER_IMAGE"] == DEFAULT_SANDBOX_IMAGE+ assert scope["TERMINAL_DOCKER_IMAGE_PINNED"] == "1"++ (home / ".env").write_text("TERMINAL_DOCKER_IMAGE=ghcr.io/me/mine:1\n", encoding="utf-8")+ assert build_profile_terminal_scope(home)["TERMINAL_DOCKER_IMAGE_PINNED"] == "1"+ (home / ".env").write_text("OTHER=1\n", encoding="utf-8")+ assert build_profile_terminal_scope(home)["TERMINAL_DOCKER_IMAGE_PINNED"] == "0"++def _fake_docker(tmp_path, monkeypatch, ps_output: str) -> Path:+ bin_dir = tmp_path / "bin"+ bin_dir.mkdir(exist_ok=True)+ exe = bin_dir / "docker"+ exe.write_text("#!/bin/sh\n"+ "case \"$1\" in ps) printf '%s' \"$PS_OUTPUT\";; *) exit 0;; esac\n", encoding="utf-8")+ exe.chmod(exe.stat().st_mode | stat.S_IXUSR)+ monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ.get('PATH', '')}")+ monkeypatch.setenv("PS_OUTPUT", ps_output)+ from tools.environments import docker as docker_env+ monkeypatch.setattr(docker_env, "_docker_executable", None)+ return exe+++def test_pending_needs_docker_backend_unpinned_and_a_stale_container(home, tmp_path, monkeypatch):+ from hermes_cli import sandbox_image_switch as sw+ from hermes_cli.config_defaults import DEFAULT_SANDBOX_IMAGE, LEGACY_SANDBOX_IMAGE++ _fake_docker(tmp_path, monkeypatch, f"hermes-abc\t{LEGACY_SANDBOX_IMAGE}\nhermes-def\t{DEFAULT_SANDBOX_IMAGE}\n")++ _write(home, {"backend": "local"})+ assert sw.pending() is None, "local backend has no sandbox to switch"++ _write(home, {"backend": "docker", "docker_image": LEGACY_SANDBOX_IMAGE})+ assert sw.pending() is None, "a pinned image is a decision already made"++ _write(home, {"backend": "docker"})+ p = sw.pending()+ assert p is not None+ assert (p.current_image, p.target_image, p.containers) == (LEGACY_SANDBOX_IMAGE, DEFAULT_SANDBOX_IMAGE, ["hermes-abc"])++ _fake_docker(tmp_path, monkeypatch, f"hermes-def\t{DEFAULT_SANDBOX_IMAGE}\n")+ assert sw.pending() is None, "every container already on the target: nothing to ask"+++def test_decide_pins_and_either_answer_ends_the_offer(home, tmp_path, monkeypatch):+ from hermes_cli import sandbox_image_switch as sw+ from hermes_cli.config_defaults import DEFAULT_SANDBOX_IMAGE, LEGACY_SANDBOX_IMAGE++ _fake_docker(tmp_path, monkeypatch, f"hermes-abc\t{LEGACY_SANDBOX_IMAGE}\n")+ _write(home, {"backend": "docker"})+ evicted = []+ monkeypatch.setattr("tools.terminal_tool_lifecycle._evict_environment_for_task", lambda task: evicted.append(task))++ p = sw.pending()+ assert p is not None+ assert sw.decide(p, approve=False) == LEGACY_SANDBOX_IMAGE+ raw = yaml.safe_load((home / "config.yaml").read_text(encoding="utf-8"))+ assert raw["terminal"]["docker_image"] == LEGACY_SANDBOX_IMAGE, "keep = pin the running image"+ assert sw.pending() is None and evicted == []++ # Unpinning is a config edit + restart in real life: a fresh process has no bridged env.+ for var in ("TERMINAL_DOCKER_IMAGE", "TERMINAL_DOCKER_IMAGE_PINNED"):+ monkeypatch.delenv(var, raising=False)+ _write(home, {"backend": "docker"})+ p = sw.pending()+ assert p is not None+ assert sw.decide(p, approve=True) == DEFAULT_SANDBOX_IMAGE+ raw = yaml.safe_load((home / "config.yaml").read_text(encoding="utf-8"))+ assert raw["terminal"]["docker_image"] == DEFAULT_SANDBOX_IMAGE, \+ "approve = pin the target even though it equals the default (a pin is what recreates)"+ assert os.environ["TERMINAL_DOCKER_IMAGE_PINNED"] == "1", "the live process is re-bridged"+ assert evicted == [None], "the cached env is dropped so the next terminal call recreates"+ assert sw.pending() is None+++def test_interactive_offer_writes_only_on_a_yes_or_no(home, tmp_path, monkeypatch):+ from hermes_cli import sandbox_image_switch as sw+ from hermes_cli.config_defaults import DEFAULT_SANDBOX_IMAGE, LEGACY_SANDBOX_IMAGE++ _fake_docker(tmp_path, monkeypatch, f"hermes-abc\t{LEGACY_SANDBOX_IMAGE}\n")+ monkeypatch.setattr("tools.terminal_tool_lifecycle._evict_environment_for_task", lambda task: None)+ _write(home, {"backend": "docker"})+ printed = []++ assert sw.offer_interactive(cprint=printed.append, ask=lambda _p: "") is None+ assert "docker_image" not in (yaml.safe_load((home / "config.yaml").read_text())["terminal"]), "Enter = ask later"+ assert any("/root and /workspace" in line for line in printed), "the offer states what carries over"++ assert sw.offer_interactive(cprint=printed.append, ask=lambda _p: "y") is True+ assert yaml.safe_load((home / "config.yaml").read_text())["terminal"]["docker_image"] == DEFAULT_SANDBOX_IMAGE++ assert sw.offer_interactive(cprint=printed.append, ask=lambda _p: "y") is None, "pinned: never asked again"+++def test_pending_reads_a_bound_terminal_scope_not_the_launch_env(home, tmp_path, monkeypatch):+ from hermes_cli import sandbox_image_switch as sw+ from hermes_cli.config_defaults import LEGACY_SANDBOX_IMAGE+ from tools.terminal_scope import reset_terminal_scope, set_terminal_scope++ _fake_docker(tmp_path, monkeypatch, f"hermes-abc\t{LEGACY_SANDBOX_IMAGE}\n")+ _write(home, {"backend": "docker"})+ monkeypatch.setenv("TERMINAL_DOCKER_IMAGE", "ghcr.io/launch-profile/pinned:1")+ assert sw.pending() is None, "launch env pin"+ token = set_terminal_scope({"TERMINAL_ENV": "docker", "TERMINAL_DOCKER_IMAGE_PINNED": "0"})+ try:+ assert sw.pending() is not None, "the routed profile's scope says unpinned; the launch env is not consulted"+ finally:+ reset_terminal_scope(token)diff --git a/tests/tools/test_bot_desktop_placement.py b/tests/tools/test_bot_desktop_placement.pynew file mode 100644index 00000000000..89e7d03f993--- /dev/null+++ b/tests/tools/test_bot_desktop_placement.py@@ -0,0 +1,337 @@+"""Bot Desktop placement: the screen (and with it computer_use and the browser) follows the terminal backend.++Two invariants, both about the boundary a sandboxed user chose:+ 1. A sandbox backend that cannot host a screen never falls back to the gateway host silently; it refuses+ unless ``bot_desktop.placement: gateway`` opts in. Docker/ssh/singularity resolve to the sandbox.+ 2. Every RFB byte between the pane and a sandbox-hosted Xvnc, and cua-driver's MCP stdio, go through the+ terminal backend's exec prefix, never a host socket or a host binary.+"""+from __future__ import annotations++import json+import subprocess++import pytest++from tools.bot_desktop import placement, runtime+from tools.environments import streams+++ ("setting", "backend", "expected"),+ [+ ("auto", "local", placement.GATEWAY),+ ("auto", "docker", placement.TERMINAL),+ ("auto", "ssh", placement.TERMINAL),+ ("auto", "singularity", placement.TERMINAL),+ ("auto", "modal", placement.REFUSED),+ ("auto", "daytona", placement.REFUSED),+ ("gateway", "modal", placement.GATEWAY),+ ("gateway", "docker", placement.GATEWAY),+ ("terminal", "docker", placement.TERMINAL),+ ("terminal", "local", placement.GATEWAY),+ ],+)+def test_placement_follows_the_terminal_backend_and_refuses_unhostable_sandboxes(monkeypatch, setting, backend, expected):+ monkeypatch.setattr(placement, "_setting", lambda: setting)+ monkeypatch.setattr(placement, "_terminal_backend", lambda: backend)+ where = placement.resolve()+ assert where.where == expected+ if expected == placement.REFUSED:+ assert backend in where.reason and "placement: gateway" in where.reason+++def test_refused_placement_blocks_start_and_names_the_opt_in(monkeypatch):+ monkeypatch.setattr(placement, "_setting", lambda: "auto")+ monkeypatch.setattr(placement, "_terminal_backend", lambda: "modal")+ with pytest.raises(RuntimeError, match="placement: gateway"):+ runtime.start()+++class _FakeDocker:+ """Stand-in for DockerEnvironment: only what ``streams.exec_prefix`` reads."""+ _docker_exe = "docker"+ _container_id = "c0ffee"++ def get_temp_dir(self):+ return "/tmp" # no-tmp: ok — sandbox-side path+++def test_sandbox_rfb_and_cua_ride_the_exec_prefix(monkeypatch):+ from tools.environments.docker import DockerEnvironment+ env = _FakeDocker()+ monkeypatch.setattr(streams, "exec_prefix", lambda e, *, user=None, interactive=True:+ ["docker", "exec", "-i", "-u", user, e._container_id] if user else ["docker", "exec", "-i", e._container_id])+ spawned: list[list[str]] = []++ class _P:+ stdin = stdout = None+ def kill(self):+ pass++ monkeypatch.setattr(subprocess, "Popen", lambda argv, **kw: spawned.append(argv) or _P())+ from tools.bot_desktop import sandbox_host+ monkeypatch.setattr(sandbox_host, "_user_for", lambda e: "pn")+ sandbox_host.open_rfb_stream(env, "p1")+ assert spawned[0][:6] == ["docker", "exec", "-i", "-u", "pn", "c0ffee"]+ assert "rfb.sock" in spawned[0][-1] and "python3" in spawned[0][-1]++ command, args = sandbox_host.cua_mcp_invocation(env, "p1", {"DISPLAY": ":20"})+ assert command == "docker" and args[:5] == ["exec", "-i", "-u", "pn", "c0ffee"]+ assert "cua-driver mcp" in args[-1] and "export DISPLAY=:20" in args[-1]+ assert not isinstance(env, DockerEnvironment) # the fake never touched a real daemon+++def test_sandbox_status_offers_the_image_switch_instead_of_a_config_hint(monkeypatch):+ """A docker sandbox kept on the previous default image (no desktop stack) is the common+ upgraded-install case: the blocker becomes the switch offer and ``image_switch`` carries what+ the pane needs to approve it. Without a pending switch the plain image hint stands."""+ from hermes_cli import sandbox_image_switch as sw+ from tools.bot_desktop import sandbox_host++ monkeypatch.setattr(placement, "_setting", lambda: "auto")+ monkeypatch.setattr(placement, "_terminal_backend", lambda: "docker")+ monkeypatch.setattr(placement, "terminal_environment", lambda *, create=True: _FakeDocker())+ monkeypatch.setattr(sandbox_host, "missing_binaries", lambda env: ["Xvnc"])+ monkeypatch.setattr(sandbox_host, "published_env", lambda env, profile: {})++ monkeypatch.setattr(sw, "pending", lambda: sw.PendingSwitch("old/base:1", "nousresearch/hermes-sandbox:desktop", ["hermes-a"]))+ st = runtime.status()+ assert st.image_switch == {"current_image": "old/base:1", "target_image": "nousresearch/hermes-sandbox:desktop", "containers": 1}+ assert "old/base:1" in st.blocker and "/root and /workspace" in st.blocker+ assert st.installed and not st.running++ monkeypatch.setattr(sw, "pending", lambda: None)+ st = runtime.status()+ assert st.image_switch is None+ assert "Xvnc" in st.blocker and "placement: gateway" in st.blocker+++def test_remote_command_survives_the_ssh_remote_shell_reparse():+ """OpenSSH joins the words after the host with spaces and the remote login shell splits them again, so+ the ``bash -c <script>`` must travel as ONE quoted word there; docker/apptainer pass argv through and+ must not get that extra quoting. Both shapes are executed through a real bash the way each client's+ remote side would run them."""+ from tools.environments.ssh import SSHEnvironment++ class _FakeSSH(SSHEnvironment):+ def __init__(self): # no daemon, no key: only the exec prefix is exercised+ self.host, self.user, self.port = "sandbox.example", "pn", 22++ def _build_ssh_command(self, extra_args=None, send_env=()):+ return ["ssh", f"{self.user}@{self.host}"]++ argv = ["printf", "%s|%s", "hello world", "it's $HOME"]+ child_env = {"DISPLAY": ":20", "AGENT_BROWSER_ARGS": "--a=1,--b='x y'"}++ over_ssh = streams.remote_command(_FakeSSH(), argv, child_env=child_env)+ assert over_ssh[:2] == ["ssh", "[email protected]"] and len(over_ssh) == 3+ remote_word = " ".join(over_ssh[2:]) # what sshd hands the login shell+ out = subprocess.run(["bash", "-c", remote_word], capture_output=True, text=True, check=True).stdout+ assert out == "hello world|it's $HOME"+ env_out = subprocess.run(["bash", "-c", " ".join(streams.remote_command(+ _FakeSSH(), ["sh", "-c", 'printf "%s" "$AGENT_BROWSER_ARGS"'], child_env=child_env)[2:])],+ capture_output=True, text=True, check=True).stdout+ assert env_out == "--a=1,--b='x y'"++ docker_shape = streams.remote_argv(["docker", "exec", "-i", "c0ffee"], argv, env=child_env)+ assert docker_shape[:6] == ["docker", "exec", "-i", "c0ffee", "bash", "-c"] and len(docker_shape) == 7+ out = subprocess.run(["bash", "-c", docker_shape[6]], capture_output=True, text=True, check=True).stdout+ assert out == "hello world|it's $HOME"+++def isolated_home(tmp_path, monkeypatch):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(runtime, "state_dir", lambda: home / "bot-desktop" / "default")+ return home+++def _placed(monkeypatch, setting, backend):+ monkeypatch.setattr(placement, "_setting", lambda: setting)+ monkeypatch.setattr(placement, "_terminal_backend", lambda: backend)+++def test_terminal_placement_starts_the_sandbox_screen_instead_of_running_on_the_host(monkeypatch, isolated_home):+ """The placement boundary is policy, not liveness: with ``placement: terminal`` and the screen not yet+ up, the browser preflight and the CUA invocation bring the sandbox screen up (no ``auto_start`` opt-in+ needed inside the user's own sandbox) and route there. Neither hands the tool a host command."""+ from tools import browser_tool_session as bts+ from tools.computer_use import cua_backend as cb++ _placed(monkeypatch, "terminal", "docker")+ started: list[str] = []+ monkeypatch.setattr(runtime, "sandbox_screen_running", lambda: bool(started))+ monkeypatch.setattr(runtime, "published_env", lambda: {"DISPLAY": ":20", "XAUTHORITY": "/x"} if started else {})+ monkeypatch.setattr(runtime, "start", lambda **kw: started.append("started"))+ monkeypatch.setattr(runtime, "_sandbox_env", lambda *, create: _FakeDocker())+ monkeypatch.setattr(runtime, "touch_activity", lambda: None)++ assert bts._browser_command_preflight() == {"browser_cmd": "agent-browser"}+ assert started == ["started"]++ from tools.bot_desktop import sandbox_host+ monkeypatch.setattr(sandbox_host, "_user_for", lambda e: "pn")+ monkeypatch.setattr(streams, "exec_prefix", lambda e, *, user=None, interactive=True:+ ["docker", "exec", "-i", "-u", user, e._container_id])+ (command, args), child_env = cb.sandbox_mcp_invocation()+ assert command == "docker" and "cua-driver mcp" in args[-1] and "export DISPLAY=:20" in args[-1]+ assert set(child_env) == {"PATH"} # the host driver's env never reaches the sandbox driver+++def test_refused_placement_never_falls_back_to_the_host(monkeypatch, isolated_home):+ from tools import browser_tool_session as bts+ from tools.computer_use import cua_backend as cb++ _placed(monkeypatch, "auto", "modal")+ res = bts._browser_command_preflight()+ assert res["success"] is False and "placement: gateway" in res["error"]+ with pytest.raises(RuntimeError, match="placement: gateway"):+ cb.sandbox_mcp_invocation()+++def test_sandbox_screen_that_cannot_come_up_is_an_error_not_a_host_browser(monkeypatch, isolated_home):+ from tools import browser_tool_session as bts++ _placed(monkeypatch, "terminal", "docker")+ monkeypatch.setattr(runtime, "sandbox_screen_running", lambda: False)+ monkeypatch.setattr(runtime, "published_env", lambda: {})++ def _boom(**kw):+ raise RuntimeError("Bot Desktop needs Xvnc inside the terminal backend's sandbox")+ monkeypatch.setattr(runtime, "start", _boom)+ res = bts._browser_command_preflight()+ assert res["success"] is False and "Xvnc" in res["error"]+++def test_start_adopting_a_screen_the_sandbox_kept_records_the_marker(monkeypatch, isolated_home):+ """Host state can vanish while the sandbox keeps its Xvnc (fresh HERMES_HOME, a stop() whose kill missed+ the launcher). start() finding the display already published must record it like a fresh launch, or+ status/thumbnail/stop never learn the screen is ours (found live against an ssh sandbox)."""+ from tools.bot_desktop import sandbox_host++ monkeypatch.setattr(sandbox_host, "_published", lambda env, rdir: {"DISPLAY": ":20", "XAUTHORITY": f"{rdir}/Xauthority"})+ monkeypatch.setattr(sandbox_host, "_remote_dir", lambda env, profile: f"/scratch/hermes-bot-desktop/{profile}")+ env = _FakeDocker()+ assert sandbox_host.start(env, "default", geometry="1280x800")["DISPLAY"] == ":20"+ marker = json.loads(sandbox_host._marker().read_text())+ assert marker["display"] == ":20" and marker["container"] == env._container_id and marker["profile"] == "default"+++def test_marker_survives_a_gateway_restart_while_the_container_lives(monkeypatch, isolated_home):+ """After a restart the process-local terminal registry is empty but the persisted container (and the+ Xvnc in it) is still running. The marker must NOT be dropped on that observation: liveness comes from+ the recorded container, stop() re-attaches to it, and only a container that is gone drops the marker."""+ from tools.bot_desktop import sandbox_host++ _placed(monkeypatch, "terminal", "docker")+ sandbox_host._marker().parent.mkdir(parents=True)+ sandbox_host._marker().write_text('{"display": ":20", "dir": "/tmp/hermes-bot-desktop/default", "profile": "default", '+ '"backend": "DockerEnvironment", "container": "c0ffee", "docker": "docker"}')+ inspected: list[list[str]] = []+ alive = {"running": True}++ def _inspect(argv, **kw):+ inspected.append(argv)+ return subprocess.CompletedProcess(argv, 0 if alive["running"] else 1, "true\n" if alive["running"] else "", "")+ monkeypatch.setattr(sandbox_host.subprocess, "run", _inspect)+ sandbox_host._ALIVE_CACHE.clear()++ created: list[bool] = []++ def _env(*, create):+ created.append(create)+ return _FakeDocker() if create else None # nothing registered in this (fresh) process+ monkeypatch.setattr(runtime, "_sandbox_env", _env)++ assert runtime.sandbox_screen_running() is True+ assert sandbox_host._marker().exists() and inspected[0][:3] == ["docker", "inspect", "-f"]++ stopped: list[object] = []+ monkeypatch.setattr(sandbox_host, "stop", lambda env, profile: stopped.append(env) or True)+ assert runtime.stop() is True+ assert isinstance(stopped[0], _FakeDocker) and created[-1] is True # re-attached, then stopped THAT sandbox+ assert not sandbox_host._marker().exists()++ # The container was removed out from under us: the marker is stale and goes; nothing is (re)built.+ sandbox_host._marker().write_text('{"display": ":20", "backend": "DockerEnvironment", "container": "dead00", "docker": "docker"}')+ alive["running"] = False+ sandbox_host._ALIVE_CACHE.clear()+ created.clear()+ assert runtime.sandbox_screen_running() is False+ assert not sandbox_host._marker().exists() and True not in created+++def test_stop_and_status_follow_the_recorded_owner_not_the_current_setting(monkeypatch, isolated_home):+ """Placement moved to ``gateway`` while a sandbox screen is still up: status keeps reporting the sandbox+ screen and stop() takes it down there, instead of both looking at the (empty) host."""+ from tools.bot_desktop import sandbox_host++ _placed(monkeypatch, "gateway", "docker")+ sandbox_host._marker().parent.mkdir(parents=True)+ sandbox_host._marker().write_text('{"display": ":20", "backend": "DockerEnvironment", "container": "c0ffee", "docker": "docker"}')+ monkeypatch.setattr(sandbox_host, "marker_sandbox_alive", lambda marker: True)+ monkeypatch.setattr(runtime, "_sandbox_env", lambda *, create: _FakeDocker())+ monkeypatch.setattr(sandbox_host, "missing_binaries", lambda env: [])+ monkeypatch.setattr(sandbox_host, "published_env", lambda env, profile: {"DISPLAY": ":20"})++ st = runtime.status()+ assert st.running and st.display == ":20" and st.placement.startswith("terminal:")++ stopped: list[object] = []+ monkeypatch.setattr(sandbox_host, "stop", lambda env, profile: stopped.append(env) or True)+ assert runtime.stop() is True and len(stopped) == 1+++def test_forward_port_carries_bytes_both_ways_through_the_exec_stream(monkeypatch):+ """The sandbox's loopback (Chromium's CDP port) is reached from the host through a local listener whose+ connections ride an exec stream running the in-sandbox relay. An empty exec prefix runs that relay+ locally, so the whole path (listener → Popen relay → TCP target → back) is real."""+ import socket+ import threading++ monkeypatch.setattr(streams, "exec_prefix", lambda env, *, user=None, interactive=True: [])+ monkeypatch.setattr(streams, "shell_joined", lambda env: False)++ srv = socket.socket(); srv.bind(("127.0.0.1", 0)); srv.listen(1)+ target_port = srv.getsockname()[1]++ def echo_upper():+ conn, _ = srv.accept()+ with conn:+ while True:+ data = conn.recv(65536)+ if not data:+ break+ conn.sendall(data.upper())+ threading.Thread(target=echo_upper, daemon=True).start()++ env = _FakeDocker()+ local = streams.forward_port(env, target_port)+ assert local != target_port+ assert streams.forward_port(env, target_port) == local, "one listener per (env, port)"++ with socket.create_connection(("127.0.0.1", local), timeout=10) as c:+ c.sendall(b"GET /json/version HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n")+ c.settimeout(10)+ got = b""+ while b"\r\n\r\n" not in got:+ got += c.recv(65536)+ assert got.startswith(b"GET /JSON/VERSION HTTP/1.1")+++def test_sandbox_cdp_endpoint_is_rewritten_to_the_forwarded_local_port(monkeypatch):+ from tools import browser_use_cli as buc+ from tools import browser_tool_session as bts++ monkeypatch.setattr(bts, "_browser_in_sandbox", lambda: True)+ monkeypatch.setattr(runtime, "_sandbox_env", lambda *, create: _FakeDocker())+ from tools.bot_desktop import sandbox_host+ monkeypatch.setattr(sandbox_host, "_user_for", lambda e: "pn")+ monkeypatch.setattr(streams, "forward_port", lambda env, port, *, remote_host="127.0.0.1", user=None: 45000 + port % 7)+ assert buc._reach_sandbox_cdp("ws://127.0.0.1:9223/devtools/browser/abc") == "ws://127.0.0.1:45004/devtools/browser/abc"+ assert buc._reach_sandbox_cdp("wss://cloud.example/session/1") == "wss://cloud.example/session/1"+ monkeypatch.setattr(bts, "_browser_in_sandbox", lambda: False)+ assert buc._reach_sandbox_cdp("ws://127.0.0.1:9223/x") == "ws://127.0.0.1:9223/x"diff --git a/tests/tools/test_docker_network_config.py b/tests/tools/test_docker_network_config.pyindex 5af4af9098a..8fdd69e61a3 100644--- a/tests/tools/test_docker_network_config.py+++ b/tests/tools/test_docker_network_config.py@@ -63,7 +63,8 @@ def test_every_sandbox_creator_passes_the_full_container_config(monkeypatch):def _reuse_guard_harness(- monkeypatch, *, existing_mode: str, network: bool, extra_args=None+ monkeypatch, *, existing_mode: str, network: bool, extra_args=None, existing_image: str = "python:3.11",+ image_pinned: bool = False, image_pullable: bool = True,):"""Drive DockerEnvironment through the cross-process reuse path with afake existing container whose NetworkMode is *existing_mode*.@@ -86,7 +87,13 @@ def _reuse_guard_harness(# missing label as "<no value>".Result.stdout = "existing-container-id\trunning\t<no value>\n"elif len(cmd) > 1 and cmd[1] == "inspect":- Result.stdout = f"{existing_mode}\n"+ # Two probes share `inspect`: image identity (must match for reuse) and network mode.+ Result.stdout = f"{existing_image}\n" if ".Config.Image" in cmd[3] else f"{existing_mode}\n"+ elif len(cmd) > 2 and cmd[1:3] == ["image", "inspect"]:+ Result.returncode = 1 # never in the local store: the replacement must go through `pull`+ elif len(cmd) > 1 and cmd[1] == "pull":+ Result.returncode = 0 if image_pullable else 1+ Result.stderr = "" if image_pullable else "pull access denied"elif len(cmd) > 1 and cmd[1] == "run":Result.stdout = "fresh-container-id\n"return Result()@@ -103,6 +110,7 @@ def _reuse_guard_harness(network=network,extra_args=extra_args,persist_across_processes=True,+ image_pinned=image_pinned,)return commands@@ -129,11 +137,57 @@ def test_reuse_skips_inspect_when_network_enabled(monkeypatch):# Default-network config never churns containers, even air-gapped ones# (operators may have created them via docker_extra_args).- assert not any(cmd[1] == "inspect" for cmd in commands)+ assert not any(cmd[1] == "inspect" and ".HostConfig.NetworkMode" in cmd[3] for cmd in commands)assert not any(cmd[1] == "rm" for cmd in commands)assert not any(cmd[1] == "run" for cmd in commands)+def test_reuse_recreates_container_built_from_another_image_when_pinned(monkeypatch):+ """The user changed docker_image (config.yaml / TERMINAL_DOCKER_IMAGE): the old container is not+ their sandbox any more and must be replaced, or the new image never takes effect."""+ commands = _reuse_guard_harness(monkeypatch, existing_mode="bridge", network=True,+ existing_image="old/image:1", image_pinned=True)++ assert any(cmd[1:3] == ["rm", "-f"] for cmd in commands), "container from another image must be removed"+ assert any(len(cmd) > 2 and cmd[1:3] == ["run", "-d"] for cmd in commands)+++def test_reuse_pulls_the_replacement_before_removing_the_old_container(monkeypatch):+ """The old container's writable layer is the user's sandbox; it goes only once the image replacing it+ is in the local store, so a private/misspelled tag or a registry outage never leaves them with+ nothing."""+ commands = _reuse_guard_harness(monkeypatch, existing_mode="bridge", network=True,+ existing_image="old/image:1", image_pinned=True)+ kinds = [tuple(c[1:3]) for c in commands]+ assert kinds.index(("pull", "python:3.11")) < kinds.index(("rm", "-f"))+++def test_reuse_keeps_the_old_container_when_the_replacement_cannot_be_pulled(monkeypatch, caplog):+ import logging+ with caplog.at_level(logging.WARNING, logger=docker_env.logger.name):+ commands = _reuse_guard_harness(monkeypatch, existing_mode="bridge", network=True,+ existing_image="old/image:1", image_pinned=True, image_pullable=False)++ assert any(cmd[1] == "pull" for cmd in commands)+ assert not any(cmd[1:3] == ["rm", "-f"] for cmd in commands), "nothing to replace it with: keep the sandbox"+ assert not any(len(cmd) > 2 and cmd[1:3] == ["run", "-d"] for cmd in commands)+ assert "could not be pulled" in caplog.text and "keeping the current sandbox" in caplog.text+++def test_reuse_keeps_container_built_from_another_image_when_default_flipped(monkeypatch, caplog):+ """A DEFAULT flip (nikolaik base -> hermes-sandbox:desktop) must not replace a sandbox the user has+ state in: the existing container is kept and the log names the approval command. Same rule Modal+ (snapshot wins) and Daytona (labeled sandbox wins) already apply."""+ import logging+ with caplog.at_level(logging.WARNING, logger=docker_env.logger.name):+ commands = _reuse_guard_harness(monkeypatch, existing_mode="bridge", network=True,+ existing_image="old/image:1", image_pinned=False)++ assert not any(cmd[1:3] == ["rm", "-f"] for cmd in commands), "an unpinned default never removes a sandbox"+ assert not any(len(cmd) > 2 and cmd[1:3] == ["run", "-d"] for cmd in commands), "existing container reused"+ assert "hermes config set terminal.docker_image python:3.11" in caplog.text++def test_extra_args_network_none_emits_flag_once(monkeypatch):"""docker_network=false plus an operator ``--network none`` (either spelling) must emit theflag ONCE: Docker rejects a repeated --network with exit 125, so both together made every@@ -154,3 +208,23 @@ def test_contradictory_network_request_fails_closed(monkeypatch):with pytest.raises(RuntimeError, match="docker_network"):_reuse_guard_harness(monkeypatch, existing_mode="bridge", network=False, extra_args=["--network=host"])+++def test_pin_verdict_reaches_docker_environment_through_the_terminal_tool(monkeypatch):+ """TERMINAL_DOCKER_IMAGE_PINNED must survive the terminal tool's config shaping+ (``_CONTAINER_KEYS`` is an allowlist): a pinned image that the builder never sees is a pin+ the runtime never honours, and the approval would silently do nothing."""+ from tools import terminal_tool as tt+ from tools.terminal_tool_backends import _build_docker_env, _container_config_from_config++ seen = {}+ monkeypatch.setattr("tools.terminal_tool_backends._DockerEnvironment",+ lambda **kw: seen.update(kw) or object())+ monkeypatch.setattr(tt, "_maybe_reap_docker_orphans", lambda cc: None)+ monkeypatch.setattr(tt, "_docker_session_isolation_enabled", lambda: False)+ for pinned in ("1", "0"):+ monkeypatch.setenv("TERMINAL_ENV", "docker")+ monkeypatch.setenv("TERMINAL_DOCKER_IMAGE_PINNED", pinned)+ cc = _container_config_from_config(tt._get_env_config())+ _build_docker_env(image="x", cwd="/root", timeout=5, cc=cc, task_id="default", host_cwd=None)+ assert seen["image_pinned"] is (pinned == "1")diff --git a/tests/tui_gateway/test_display_methods.py b/tests/tui_gateway/test_display_methods.pyindex 2d87fdb3eab..edb0ecbd813 100644--- a/tests/tui_gateway/test_display_methods.py+++ b/tests/tui_gateway/test_display_methods.py@@ -240,3 +240,29 @@ def test_thumbnail_grabbed_across_a_takeover_is_suppressed(monkeypatch, _fresh_lmonkeypatch.setattr(thumbnail, "thumbnail_data_url", grab_while_human_takes_over)result = _call(server, "display.thumbnail", {})["result"]assert result["data_url"] is None and result["suppressed"] == "human_has_control", result+++def test_switch_sandbox_image_decides_only_a_pending_switch(monkeypatch, tmp_path):+ """The pane's button: refused when nothing is pending (a stale pane cannot rewrite config);+ otherwise the decision is made through the same module the CLI offer uses and the fresh+ status rides back."""+ import tui_gateway.server as server+ from hermes_cli import sandbox_image_switch as sw+ from tools.bot_desktop import runtime++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setattr(sw, "pending", lambda: None)+ resp = _call(server, "display.switchSandboxImage", {"approve": True})+ assert "error" in resp and "pending" in resp["error"]["message"]++ decided = []+ switch = sw.PendingSwitch("old/base:1", "nousresearch/hermes-sandbox:desktop", ["hermes-a"])+ monkeypatch.setattr(sw, "pending", lambda: switch)+ monkeypatch.setattr(sw, "decide", lambda s, approve: decided.append((s, approve)) or s.target_image)+ monkeypatch.setattr(runtime, "status", lambda profile=None: runtime.DesktopStatus(+ profile="default", supported=True, installed=True, missing=[], running=False, pid=None, display=None,+ socket=None, geometry="1280x800", install_command=None, browser=None))+ resp = _call(server, "display.switchSandboxImage", {"approve": False})+ assert decided == [(switch, False)]+ assert resp["result"]["docker_image"] == "nousresearch/hermes-sandbox:desktop"+ assert resp["result"]["running"] is False and "lease" in resp["result"]diff --git a/tools/bot_desktop/browser.py b/tools/bot_desktop/browser.pyindex d95c8007d19..80e4f265d34 100644--- a/tools/bot_desktop/browser.py+++ b/tools/bot_desktop/browser.py@@ -86,7 +86,7 @@ def dock_launch() -> Optional[Tuple[str, str]]:return (exe, str(profile_dir())) if exe else None-def dock_argv(exe: str, user_data_dir: str) -> list[str]:+def dock_argv(exe: str, user_data_dir: str, *, sandbox_bypass: Optional[bool] = None) -> list[str]:"""Command the dock's Browser icon runs. ``--remote-debugging-port=0`` makes a human-startedinstance attachable (Chromium writes the chosen port to ``<user-data-dir>/DevToolsActivePort``);first-run / default-browser dialogs would sit between the human and the bot's tabs."""@@ -100,10 +100,11 @@ def dock_argv(exe: str, user_data_dir: str) -> list[str]:# gateway's disk: uncapped it grows for months toward a hosted instance's 6 GB.return [exe, f"--user-data-dir={user_data_dir}", "--remote-debugging-port=0", "--no-first-run","--no-default-browser-check", "--test-type", f"--disk-cache-size={DISK_CACHE_BYTES}",- *(CHROMIUM_SANDBOX_BYPASS_ARGS if _needs_chromium_sandbox_bypass() else ())]+ *(CHROMIUM_SANDBOX_BYPASS_ARGS if (_needs_chromium_sandbox_bypass() if sandbox_bypass is None+ else sandbox_bypass) else ())]-def dock_exec_line(exe: str, user_data_dir: str) -> str:+def dock_exec_line(exe: str, user_data_dir: str, *, sandbox_bypass: Optional[bool] = None) -> str:"""The ``Exec=`` line of the dock's ``.desktop`` entry. Every argument is double-quoted per theDesktop Entry spec (a browser under ``/opt/Google Chrome/`` or a profile under a spaced HERMES_HOMEotherwise splits into garbage): inside the quotes ``" ` $ \\`` are backslash-escaped, and because the@@ -111,7 +112,7 @@ def dock_exec_line(exe: str, user_data_dir: str) -> str:def quote(arg: str) -> str:quoted = "".join("\\" + ch if ch in '"`$\\' else ch for ch in arg)return '"' + quoted.replace("\\", "\\\\") + '"'- return "Exec=" + " ".join(quote(arg) for arg in dock_argv(exe, user_data_dir))+ return "Exec=" + " ".join(quote(arg) for arg in dock_argv(exe, user_data_dir, sandbox_bypass=sandbox_bypass))def running_instance_cdp_port(user_data_dir: str, *, exclude_session: Optional[str] = None) -> Optional[int]:diff --git a/tools/bot_desktop/placement.py b/tools/bot_desktop/placement.pynew file mode 100644index 00000000000..86c50dd4131--- /dev/null+++ b/tools/bot_desktop/placement.py@@ -0,0 +1,80 @@+"""Where this profile's desktop lives: the gateway host or inside the configured terminal backend.++``bot_desktop.placement``:+ ``auto`` (default) follow the terminal backend when it is a sandbox that can host a stream+ (docker / ssh / singularity); the gateway host when ``terminal.backend`` is local. A+ sandbox backend that CANNOT host one (modal, daytona, vercel) resolves to ``refused``:+ the user chose a sandbox for the agent's actions, so quietly running the screen, cua-driver+ and the browser on the host beside it would hand the agent a desktop outside that sandbox.+ ``terminal`` always the terminal backend; error when it cannot host one.+ ``gateway`` always the gateway host (the pre-#108914 behaviour for sandboxed users, now an explicit+ opt-in because it is the boundary-crossing shape).++``resolve()`` is pure config + backend-class reasoning: it never starts a sandbox. ``terminal_environment()``+does acquire the profile's terminal environment (creating the container if needed) because a screen cannot+exist before the sandbox does.+"""+from __future__ import annotations++import logging+from dataclasses import dataclass+from typing import Any, Optional++logger = logging.getLogger(__name__)++GATEWAY = "gateway"+TERMINAL = "terminal"+REFUSED = "refused"+_STREAM_BACKENDS = ("docker", "ssh", "singularity")+++@dataclass(frozen=True)+class Placement:+ where: str # GATEWAY | TERMINAL | REFUSED+ backend: str # terminal.backend as configured+ reason: str = "" # human sentence when REFUSED (or why TERMINAL was not possible)+++def _setting() -> str:+ from hermes_cli.config import load_config_readonly+ cfg = load_config_readonly().get("bot_desktop") or {}+ value = str(cfg.get("placement") or "auto").strip().lower()+ return value if value in ("auto", TERMINAL, GATEWAY) else "auto"+++def _terminal_backend() -> str:+ from tools.terminal_tool import _get_env_config+ return str(_get_env_config().get("env_type") or "local")+++def resolve() -> Placement:+ # Backend first (env only): a local terminal IS the gateway host whatever the setting says, and that is+ # the common case — it must not cost a config load (this runs on every browser / cua-driver spawn).+ backend = _terminal_backend()+ if backend == "local":+ return Placement(GATEWAY, backend, "terminal.backend is local, so the terminal IS the gateway host")+ setting = _setting()+ if setting == GATEWAY:+ return Placement(GATEWAY, backend)+ if backend in _STREAM_BACKENDS:+ return Placement(TERMINAL, backend)+ reason = (f"terminal.backend is {backend}, which cannot host a screen yet, and running the desktop on the "+ f"gateway host would put the agent's screen, browser and computer_use outside the sandbox you chose "+ f"for it. Set bot_desktop.placement: gateway to allow that explicitly.")+ return Placement(REFUSED, backend, reason)+++def terminal_environment(*, create: bool = True) -> Optional[Any]:+ """This profile's terminal environment object (the one ``terminal`` runs commands in). ``create=False``+ only returns an already-running one."""+ from tools import terminal_tool as tt+ task_id = tt._resolve_container_task_id(None)+ with tt._env_lock:+ env = tt._lookup_active_env(task_id, None)+ if env is not None or not create:+ return env+ # Acquire through the same planner the terminal tool uses so the container carries the same mounts,+ # limits and identity label; a trivial command warms it.+ tt.terminal_tool("true", task_id=None)+ with tt._env_lock:+ return tt._lookup_active_env(task_id, None)diff --git a/tools/bot_desktop/runtime.py b/tools/bot_desktop/runtime.pyindex b0e1d878b62..69121b8bfec 100644--- a/tools/bot_desktop/runtime.py+++ b/tools/bot_desktop/runtime.py@@ -27,6 +27,7 @@ from pathlib import Pathfrom typing import Dict, Optionalfrom hermes_constants import get_hermes_home+from tools.bot_desktop import placementlogger = logging.getLogger(__name__)@@ -144,6 +145,8 @@ class DesktopStatus:blocker: Optional[str] = None # why start() would refuse right now (memory); None = may startmemory_available_mb: Optional[int] = Nonememory_limit_mb: Optional[int] = None+ placement: str = "gateway" # "gateway" | "terminal:<backend>" — where Xvnc runs+ image_switch: Optional[Dict[str, object]] = None # pending default-image switch the pane can approvedef as_dict(self) -> Dict[str, object]:return dict(self.__dict__)@@ -354,13 +357,26 @@ def desktop_env(base_env: Optional[Dict[str, str]] = None) -> Dict[str, str]:def ensure_started_for_tool() -> None:- """Tool-boundary hook (``computer_use`` dispatch and the headed Chromium spawn sites of the browser tool): with- ``bot_desktop.auto_start`` (opt-in, default off) a Linux host that has NO display and the packages installed gets- its screen started on first use, so a headless gateway works the first time instead of answering "no DISPLAY is- set". Failure is not an error here; the tool's own "no display" diagnosis is the right message then."""- if published_env():+ """Tool-boundary hook (``computer_use`` dispatch and the headed Chromium spawn sites of the browser tool).++ Under ``terminal`` placement the sandbox screen is brought up on first use unconditionally: the sandbox is+ the boundary the user chose, a screen inside it touches nothing outside it, and the tools below refuse+ rather than run on the host when it is not up. On the gateway host, ``bot_desktop.auto_start`` (opt-in,+ default off) starts a Linux host's screen when it has NO display and the packages installed, so a headless+ gateway works the first time. Host failure is not an error here (the tool's own "no display" diagnosis is+ the right message then); a sandbox start failure is logged and left for :func:`tool_placement` to raise."""+ if published_env().get("DISPLAY"):touch_activity()return+ where = placement.resolve()+ if where.where == placement.REFUSED:+ return # tool_placement() raises the reason at the spawn site+ if where.where == placement.TERMINAL:+ try:+ start()+ except Exception as exc:+ logger.info("Bot Desktop sandbox start deferred to the tool: %s", exc)+ returnif not _should_auto_start(os.environ):returntry:@@ -369,6 +385,22 @@ def ensure_started_for_tool() -> None:logger.info("Bot Desktop auto-start skipped: %s", exc)+def tool_placement() -> str:+ """Where the browser / cua-driver a tool is about to spawn MUST run: ``placement.GATEWAY`` or+ ``placement.TERMINAL``. Policy first, liveness second: a ``terminal`` placement whose screen is down gets+ it started here (raising with the blocker when it cannot come up) and a ``refused`` placement raises its+ reason. Neither ever yields the host — a screen that happens to be down is not permission to run the+ agent's browser outside the sandbox the user chose."""+ where = placement.resolve()+ if where.where == placement.REFUSED:+ raise RuntimeError(where.reason)+ if where.where == placement.GATEWAY:+ return placement.GATEWAY+ if not sandbox_screen_running() or not published_env().get("DISPLAY"):+ start()+ return placement.TERMINAL++def _should_auto_start(env: Dict[str, str]) -> bool:if not is_supported_host() or env.get("DISPLAY") or env.get("WAYLAND_DISPLAY"):return False@@ -421,7 +453,7 @@ def stop_if_idle() -> bool:"""Stop this profile's screen when it has been idle past the limit and no human holds it. True whenit was stopped."""limit = idle_stop_seconds()- if limit <= 0 or _launcher_pid() is None:+ if limit <= 0 or not is_running():return Falseidle = idle_seconds()if idle is None or idle < limit:@@ -434,7 +466,14 @@ def stop_if_idle() -> bool:def published_env() -> Dict[str, str]:- """Variables the launcher wrote once Xfce's private bus existed; empty when the desktop is down."""+ """Variables the launcher wrote once Xfce's private bus existed; empty when the desktop is down.++ Pure file reads on the common path: this is called from every browser / cua-driver env builder, so it+ must not load config (that initializes HERMES_HOME). A sandbox-hosted screen leaves a host-side marker at+ start; only its presence routes to the sandbox probe."""+ from tools.bot_desktop import sandbox_host+ if sandbox_host._read_marker():+ return _sandbox_published_env()if _launcher_pid() is None:return {}raw = _read(state_dir() / "env")@@ -449,10 +488,68 @@ def published_env() -> Dict[str, str]:def rfb_socket_path() -> Optional[Path]:+ """Host path of the RFB socket; None when down OR when the screen lives in a sandbox (use+ :func:`open_rfb_stream` there: the socket is not on this filesystem)."""+ from tools.bot_desktop import sandbox_host+ if sandbox_host._read_marker():+ return Nonesock = state_dir() / "rfb.sock"return sock if _launcher_pid() is not None and sock.exists() else None+def in_sandbox() -> bool:+ """True when this profile's screen is placed inside the terminal backend (policy; reads config)."""+ return placement.resolve().where == placement.TERMINAL+++def sandbox_screen_running() -> bool:+ """True when a sandbox-hosted screen is UP for this profile: the start marker exists AND the sandbox it+ names is alive — registered in this process, or (after a gateway restart emptied the registry) the+ marker's recorded container still running. Only a sandbox that is provably gone (its container removed+ out from under us) drops the marker, so the next start rebuilds instead of the browser exec-ing into a+ dead container; an unregistered-but-alive one is re-attached by ``_sandbox_env(create=True)`` at the+ next spawn (the terminal planner reuses the persisted container by label)."""+ from tools.bot_desktop import sandbox_host+ marker = sandbox_host._read_marker()+ if not marker:+ return False+ if _sandbox_env(create=False) is not None:+ return True+ if sandbox_host.marker_sandbox_alive(marker):+ return True+ sandbox_host._marker().unlink(missing_ok=True)+ return False+++def _owned_sandbox_env():+ """The environment hosting the screen the marker records, re-attaching after a restart when the recorded+ sandbox is still alive; None when there is no marker or its sandbox is gone. Never builds a sandbox for+ a screen that is not there."""+ from tools.bot_desktop import sandbox_host+ marker = sandbox_host._read_marker()+ if not marker:+ return None+ env = _sandbox_env(create=False)+ if env is not None:+ return env+ if sandbox_host.marker_sandbox_alive(marker):+ return _sandbox_env(create=True)+ return None+++def is_running() -> bool:+ return bool(published_env().get("DISPLAY"))+++def open_rfb_stream() -> "subprocess.Popen":+ """Popen whose stdin/stdout carry RFB bytes for a sandbox-hosted screen (``in_sandbox()`` only)."""+ from tools.bot_desktop import sandbox_host+ env = _sandbox_env(create=False)+ if env is None:+ raise RuntimeError("the sandbox hosting this screen is not running")+ return sandbox_host.open_rfb_stream(env, _profile_name())++def geometry() -> str:from hermes_cli.config import load_config_readonlycfg = load_config_readonly().get("bot_desktop") or {}@@ -462,6 +559,12 @@ def geometry() -> str:def status(profile: Optional[str] = None) -> DesktopStatus:from tools.bot_desktop import browser as _bd_browserfrom tools.bot_desktop import resources+ from tools.bot_desktop import sandbox_host+ where = placement.resolve()+ if where.where == placement.TERMINAL or sandbox_host._read_marker():+ # A screen already running inside a sandbox is reported (and stoppable) even after the placement+ # setting moved: the recorded owner wins over the current policy until it is stopped.+ return _sandbox_status(profile, where)missing: list[str] = missing_binaries() if is_supported_host() else list(REQUIRED_BINARIES)pid = _launcher_pid()env = published_env()@@ -486,6 +589,53 @@ def status(profile: Optional[str] = None) -> DesktopStatus:)+def _sandbox_status(profile: Optional[str], where) -> DesktopStatus:+ """Status of a sandbox-placed screen. Package presence is only known once the sandbox exists; before+ that the pane shows "installed" with the image hint carried in ``install_command`` so Start can explain."""+ from tools.bot_desktop import sandbox_host+ env = _owned_sandbox_env() or _sandbox_env(create=False)+ missing = sandbox_host.missing_binaries(env) if env is not None else []+ published = sandbox_host.published_env(env, profile or _profile_name()) if env is not None else {}+ running = bool(published.get("DISPLAY"))+ # No install_command: the pane's Install button runs apt on the HOST, which is the wrong machine here.+ # A sandbox missing the stack is a blocker (shown in place of Start) naming the image that has it.+ blocker = None+ image_switch = None+ if missing:+ blocker = (f"The terminal backend's sandbox image lacks {', '.join(missing)}. Use "+ f"{sandbox_host.SANDBOX_IMAGE_HINT} as terminal.{where.backend}_image (the default sandbox base "+ f"plus the desktop stack), or set bot_desktop.placement: gateway.")+ if where.backend == "docker":+ # The usual reason on an upgraded install: the persisted container predates the default+ # flip and was kept on purpose. The pane offers the switch instead of a config hint.+ from hermes_cli.sandbox_image_switch import pending+ sw = pending()+ if sw is not None:+ image_switch = {"current_image": sw.current_image, "target_image": sw.target_image,+ "containers": len(sw.containers)}+ blocker = (f"Your sandbox container still runs {sw.current_image}, which has no desktop. "+ f"Switch it to {sw.target_image}: files in /root and /workspace stay, packages "+ f"installed inside the container are reinstalled on demand.")+ return DesktopStatus(+ profile=profile or _profile_name(),+ supported=True,+ installed=True,+ missing=missing,+ running=running,+ pid=None,+ display=published.get("DISPLAY"),+ socket=None,+ geometry=geometry(),+ install_command=None,+ browser=None,+ blocker=blocker,+ memory_available_mb=None,+ memory_limit_mb=None,+ placement=f"{placement.TERMINAL}:{where.backend}",+ image_switch=image_switch,+ )++def _profile_name() -> str:try:from hermes_cli.profiles import get_active_profile_name@@ -504,11 +654,20 @@ def start(*, wait_seconds: float = 15.0) -> DesktopStatus:"""Start this profile's desktop (idempotent). Blocks until the launcher publishes its env file or``wait_seconds`` pass; raises ``RuntimeError`` naming the blocker.+ ``bot_desktop.placement`` decides WHERE: inside the configured terminal backend (docker/ssh/singularity;+ ``sandbox_host``), or on the gateway host (the rest of this function). A sandbox backend that cannot host+ a screen refuses rather than silently falling back to the host beside it.+Two locks: the per-profile ``start.lock``, held from the running-check to the launcher's publish so twostart() calls for one profile spawn one launcher (the loser sees it running), and the host-widedisplay-allocation lock, held only until this Xvnc has written ``/tmp/.X<n>-lock`` (a second profilepicking the same number before that would fail and its stale-lock cleanup could remove our socket).Holding it for the whole Xfce bring-up serialized every profile's start behind one desktop launch."""+ where = placement.resolve()+ if where.where == placement.REFUSED:+ raise RuntimeError(where.reason)+ if where.where == placement.TERMINAL:+ return _start_in_sandbox(wait_seconds)if not is_supported_host():raise RuntimeError("Bot Desktop runs on Linux gateway hosts only")missing = missing_binaries()@@ -608,9 +767,55 @@ def _spawn_and_wait(sd: Path, wait_seconds: float) -> DesktopStatus:raise RuntimeError(f"Bot Desktop did not publish its display within {wait_seconds:.0f}s (see {sd / 'launcher.log'})")+def _sandbox_env(*, create: bool):+ """The terminal environment hosting this profile's screen, or None. ``create=False`` for status probes+ (a status call must never build a container)."""+ return placement.terminal_environment(create=create)+++def _start_in_sandbox(wait_seconds: float) -> DesktopStatus:+ from tools.bot_desktop import sandbox_host+ env = _sandbox_env(create=True)+ if env is None:+ raise RuntimeError("the terminal backend's sandbox could not be started, so there is nowhere to put the screen")+ sd = state_dir()+ sd.mkdir(parents=True, exist_ok=True)+ os.chmod(sd, 0o700)+ with _flocked(sd / "start.lock"):+ # The dock's Browser icon runs the sandbox's own Playwright Chromium on the profile agent-browser+ # uses there: the human's browser is the bot's browser, as on the host.+ from tools.bot_desktop.browser import dock_exec_line+ exe = sandbox_host.chromium_executable(env)+ browser = (exe, dock_exec_line(exe, sandbox_host.browser_profile_dir(env), sandbox_bypass=True)) if exe else (None, None)+ published = sandbox_host.start(env, _profile_name(), geometry=geometry(), wait_seconds=max(wait_seconds, 20.0),+ browser_exec=browser[0], browser_exec_line=browser[1])+ (sd / "env").write_text("".join(f"{k}={v}\n" for k, v in published.items()), encoding="utf-8")+ touch_activity()+ return status()+++def _sandbox_published_env() -> Dict[str, str]:+ """Published env of a sandbox-hosted screen (the caller saw the host-side marker written at start)."""+ from tools.bot_desktop import sandbox_host+ env = _sandbox_env(create=False)+ if env is None:+ return {}+ return sandbox_host.published_env(env, _profile_name())++def stop() -> bool:"""Stop this profile's desktop; True when a running launcher (or the X server a dead one left behind)was signalled."""+ from tools.bot_desktop import sandbox_host+ if sandbox_host._read_marker() or placement.resolve().where == placement.TERMINAL:+ # The marker names the sandbox that owns the screen; stop THAT one (re-attaching after a restart),+ # whatever the placement setting says now. A marker whose sandbox is gone is simply dropped.+ env = _owned_sandbox_env()+ stopped = sandbox_host.stop(env, _profile_name()) if env is not None else False+ sandbox_host._marker().unlink(missing_ok=True)+ for name in ("env", "activity"):+ (state_dir() / name).unlink(missing_ok=True)+ return stoppedif not is_supported_host():return Falsesd = state_dir()diff --git a/tools/bot_desktop/sandbox_host.py b/tools/bot_desktop/sandbox_host.pynew file mode 100644index 00000000000..45cbeef5ab5--- /dev/null+++ b/tools/bot_desktop/sandbox_host.py@@ -0,0 +1,314 @@+"""Bot Desktop hosted INSIDE the configured terminal backend (docker / ssh / singularity).++Same launcher, same lease, same pane: only WHERE Xvnc + Xfce run changes. ``runtime`` decides between the+gateway host and this module via ``placement()``; callers keep using ``runtime.start/stop/status/desktop_env``.++Layout inside the sandbox, under ``<sandbox tmp>/hermes-bot-desktop/<profile>/``: ``launcher.sh`` (copied in+at start), ``env`` (published DISPLAY/XAUTHORITY/DBUS), ``rfb.sock`` (Xvnc's unix socket), ``launcher.pid``.+Host-side state under ``<HERMES_HOME>/bot-desktop/``: ``sandbox.json`` = ``{"env_key": ..., "display": ...}``+so status() knows which terminal environment owns the screen without re-deriving it.++The Desktop pane never sees a socket path: ``open_rfb_stream()`` returns a Popen whose stdin/stdout ARE the+RFB byte stream, relayed by a 15-line Python script inside the sandbox (python3 is in every sandbox image;+socat is not). cua-driver runs the same way: ``cua_mcp_argv()`` is the docker/ssh prefix + ``cua-driver mcp``.+"""+from __future__ import annotations++import base64+import json+import logging+import shlex+import subprocess+import time+from pathlib import Path+from typing import Any, Dict, Optional++from hermes_constants import get_hermes_home+from tools.environments import streams++logger = logging.getLogger(__name__)++# The user desktop processes run as inside the sandbox image. nikolaik (and hermes-sandbox:desktop on top of+# it) ships uid 1000 `pn`; a root Xvnc/Chromium/cua-driver is the wrong shape (Chromium refuses the sandbox,+# AT-SPI wants a user session). Falls back to the exec default when the image has no such user.+DESKTOP_USER = "pn"+_REQUIRED = ("Xvnc", "xfwm4", "xfce4-panel", "xfdesktop", "xfsettingsd", "dbus-run-session", "xauth", "xdpyinfo", "xprop")+SANDBOX_IMAGE_HINT = "nousresearch/hermes-sandbox:desktop"++_RELAY = (+ "import os,socket,sys,threading\n"+ "s=socket.socket(socket.AF_UNIX);s.connect(sys.argv[1])\n"+ "def up():\n"+ " while True:\n"+ " d=os.read(0,65536)\n"+ " if not d: break\n"+ " s.sendall(d)\n"+ " s.shutdown(socket.SHUT_WR)\n"+ "threading.Thread(target=up,daemon=True).start()\n"+ "while True:\n"+ " d=s.recv(65536)\n"+ " if not d: break\n"+ " os.write(1,d)\n"+)+++def _marker() -> Path:+ return get_hermes_home() / "bot-desktop" / "sandbox.json"+++def _read_marker() -> Dict[str, Any]:+ try:+ return json.loads(_marker().read_text(encoding="utf-8-sig"))+ except (OSError, ValueError):+ return {}+++def _owner_identity(env: Any) -> Dict[str, Any]:+ """What the marker records about the sandbox hosting the screen, so a restarted gateway (empty terminal+ registry) can tell a still-running sandbox from one that was removed."""+ ident: Dict[str, Any] = {"backend": type(env).__name__}+ container = getattr(env, "_container_id", None)+ if container:+ ident["container"] = container+ ident["docker"] = getattr(env, "_docker_exe", "docker")+ return ident+++_ALIVE_CACHE: Dict[str, tuple[float, bool]] = {}+++def marker_sandbox_alive(marker: Dict[str, Any]) -> bool:+ """Whether the sandbox a marker names still exists. Docker: ``docker inspect`` on the recorded container+ (cached a few seconds; this sits on the browser's per-command path). Other backends (ssh host, apptainer+ instance) cannot be probed from here without their environment object: the re-attach's own+ ``published_env`` probe decides, so they read as alive."""+ container = marker.get("container")+ if not container:+ return True+ now = time.monotonic()+ cached = _ALIVE_CACHE.get(container)+ if cached and now - cached[0] < 5.0:+ return cached[1]+ try:+ proc = subprocess.run([marker.get("docker") or "docker", "inspect", "-f", "{{.State.Running}}", container],+ capture_output=True, text=True, timeout=15, check=False, stdin=subprocess.DEVNULL)+ alive = proc.returncode == 0 and proc.stdout.strip() == "true"+ except (OSError, subprocess.TimeoutExpired):+ alive = False+ _ALIVE_CACHE[container] = (now, alive)+ return alive+++def _remote_dir(env: Any, profile: str) -> str:+ return f"{env.get_temp_dir().rstrip('/')}/hermes-bot-desktop/{profile}"+++def desktop_home(env: Any) -> str:+ """``$HOME`` of the user the desktop and the browser run as inside ``env`` (cached on the env). This+ is where state that must outlive a container stop goes: ``/tmp`` in the Docker backend is a 512 MB+ tmpfs that is emptied on every stop and shared with the sandbox's scratch, so a browser profile+ (logins, cookies) there would vanish and grow into that cap."""+ cached = getattr(env, "_bd_desktop_home", None)+ if cached:+ return cached+ proc = streams.run_in(env, ["bash", "-c", 'printf %s "$HOME"'], user=_user_for(env), timeout=15)+ home = proc.stdout.decode("utf-8", "replace").strip() if proc.returncode == 0 else ""+ if not home or not home.startswith("/"):+ home = f"/home/{DESKTOP_USER}" if _user_for(env) else "/root"+ env._bd_desktop_home = home+ return home+++def browser_profile_dir(env: Any) -> str:+ """The ONE ``--user-data-dir`` the agent's agent-browser and the dock's Browser icon share inside the+ sandbox (same rule as the host: two profiles would mean the human logs into a jar the bot never sees)."""+ return f"{desktop_home(env).rstrip('/')}/.hermes/bot-desktop/browser-profile"+++_CHROMIUM_PROBE = (+ 'for d in "${PLAYWRIGHT_BROWSERS_PATH:-}" /opt/playwright "$HOME/.cache/ms-playwright"; do'+ ' [ -n "$d" ] || continue;'+ ' for c in "$d"/chromium-*/chrome-linux/chrome "$d"/chromium-*/chrome-linux64/chrome; do'+ ' [ -x "$c" ] && { printf %s "$c"; exit 0; }; done; done; exit 1'+)+++def chromium_executable(env: Any) -> Optional[str]:+ """Path of the Playwright Chromium agent-browser uses inside ``env`` (the dock's Browser icon must run+ the same binary), or None when the image has none. Cached on the env."""+ cached = getattr(env, "_bd_chromium", "unset")+ if cached != "unset":+ return cached+ proc = streams.run_in(env, ["bash", "-c", _CHROMIUM_PROBE], user=_user_for(env), timeout=20)+ exe = proc.stdout.decode("utf-8", "replace").strip() if proc.returncode == 0 else ""+ env._bd_chromium = exe or None+ return env._bd_chromium+++_GRAB_SCRIPT = """+import io, sys+from PIL import ImageGrab+img = ImageGrab.grab(xdisplay=sys.argv[1])+img.thumbnail((int(sys.argv[2]), int(sys.argv[3])))+buf = io.BytesIO()+img.convert("RGB").save(buf, "JPEG", quality=int(sys.argv[4]), optimize=True)+sys.stdout.buffer.write(buf.getvalue())+"""+++def grab_jpeg(env: Any, published: Dict[str, str], max_size: tuple[int, int], quality: int) -> Optional[bytes]:+ """One JPEG of the sandbox screen, grabbed INSIDE the sandbox (the X socket and its cookie live there).+ Needs Pillow in the image (the published desktop image ships it); None when the grab fails."""+ display = published.get("DISPLAY")+ if not display:+ return None+ child_env = {k: v for k, v in published.items() if k in ("DISPLAY", "XAUTHORITY")}+ try:+ proc = streams.run_in(env, ["python3", "-c", _GRAB_SCRIPT, display, str(max_size[0]), str(max_size[1]),+ str(quality)], child_env=child_env, user=_user_for(env), timeout=20)+ except (OSError, subprocess.SubprocessError) as exc:+ logger.debug("sandbox screen grab failed: %s", exc)+ return None+ if proc.returncode != 0 or not proc.stdout.startswith(b"\xff\xd8"):+ logger.debug("sandbox screen grab failed: %s", proc.stderr.decode("utf-8", "replace")[-300:])+ return None+ return proc.stdout+++def _user_for(env: Any) -> Optional[str]:+ """DESKTOP_USER when the sandbox has it, else None (exec default). Cached on the env object."""+ cached = getattr(env, "_bd_desktop_user", "unset")+ if cached != "unset":+ return cached+ probe = streams.run_in(env, ["id", "-u", DESKTOP_USER], timeout=15)+ user = DESKTOP_USER if probe.returncode == 0 else None+ env._bd_desktop_user = user+ return user+++def missing_binaries(env: Any) -> list[str]:+ script = "for b in " + " ".join(_REQUIRED) + '; do command -v "$b" >/dev/null 2>&1 || echo "$b"; done'+ proc = streams.run_in(env, ["bash", "-c", script], user=_user_for(env), timeout=20)+ return [b for b in proc.stdout.decode("utf-8", "replace").split() if b]+++def _published(env: Any, rdir: str) -> Dict[str, str]:+ proc = streams.run_in(env, ["bash", "-c", f"kill -0 $(cat {shlex.quote(rdir)}/launcher.pid 2>/dev/null) 2>/dev/null "+ f"&& test -S {shlex.quote(rdir)}/rfb.sock && cat {shlex.quote(rdir)}/env"],+ user=_user_for(env), timeout=15)+ if proc.returncode != 0:+ return {}+ out: Dict[str, str] = {}+ for line in proc.stdout.decode("utf-8", "replace").splitlines():+ k, sep, v = line.partition("=")+ if sep:+ out[k.strip()] = v.strip()+ return out+++def published_env(env: Any, profile: str) -> Dict[str, str]:+ return _published(env, _remote_dir(env, profile))+++def start(env: Any, profile: str, *, geometry: str, wait_seconds: float = 20.0,+ browser_exec: Optional[str] = None, browser_exec_line: Optional[str] = None) -> Dict[str, str]:+ """Bring the screen up inside ``env`` (idempotent); returns the published env. Raises RuntimeError naming+ the blocker."""+ rdir = _remote_dir(env, profile)+ live = _published(env, rdir)+ if live.get("DISPLAY"):+ # Adopting a screen the sandbox kept while this host's state was lost (fresh HERMES_HOME, a stop()+ # whose kill missed): without the marker, status/thumbnail/stop would not know it is ours.+ return _record(env, rdir, profile, live)+ stop(env, profile) # a dead launcher may have left Xvnc holding :20; the relaunch needs it gone+ missing = missing_binaries(env)+ if missing:+ raise RuntimeError(+ f"Bot Desktop needs {', '.join(missing)} inside the terminal backend's sandbox. The configured image "+ f"does not have them; use {SANDBOX_IMAGE_HINT} (the default sandbox base plus the desktop stack) as "+ f"terminal.docker_image / modal_image / singularity_image, or set bot_desktop.placement: gateway.")+ user = _user_for(env)+ launcher = (Path(__file__).with_name("launcher.sh").read_bytes())+ wallpaper = Path(__file__).with_name("wallpaper.png").read_bytes()+ seed = (+ f"set -e; rm -rf {shlex.quote(rdir)}; mkdir -p {shlex.quote(rdir)}; cd {shlex.quote(rdir)};"+ f" echo {shlex.quote(base64.b64encode(launcher).decode())} | base64 -d > launcher.sh;"+ f" echo {shlex.quote(base64.b64encode(wallpaper).decode())} | base64 -d > wallpaper.png;"+ " chmod 0700 . launcher.sh"+ )+ proc = streams.run_in(env, ["bash", "-c", seed], user=user, timeout=30)+ if proc.returncode != 0:+ raise RuntimeError(f"could not seed the sandbox desktop dir: {proc.stderr.decode('utf-8', 'replace')[-500:]}")+ num = 20 # one profile per sandbox; the launcher's stale-lock logic handles a leftover :20+ child_env = {+ "HERMES_BD_PROFILE": profile, "HERMES_BD_DISPLAY_NUM": str(num), "HERMES_BD_SOCKET": f"{rdir}/rfb.sock",+ "HERMES_BD_XAUTH": f"{rdir}/Xauthority", "HERMES_BD_ENV_FILE": f"{rdir}/env",+ "HERMES_BD_CONFIG_HOME": f"{rdir}/xdg", "HERMES_BD_GEOMETRY": geometry, "HERMES_BD_WALLPAPER": f"{rdir}/wallpaper.png",+ }+ if browser_exec and browser_exec_line:+ child_env["HERMES_BD_BROWSER_EXEC"] = browser_exec+ child_env["HERMES_BD_BROWSER_EXEC_LINE"] = browser_exec_line+ # The launcher must outlive this exec (docker exec / ssh) and be its own session so stop() can take the+ # whole group (Xvnc, dbus, Xfce) with one kill. `setsid -f` forks, so `$!` would be the wrong pid: the+ # launcher records ITS OWN pid (= its session id) before doing anything else.+ spawn = (f"cd {shlex.quote(rdir)} && setsid -f bash -c "+ f"'echo $$ > launcher.pid; exec bash launcher.sh' > launcher.log 2>&1 < /dev/null; "+ f"for _ in 1 2 3 4 5 6 7 8 9 10; do [ -s launcher.pid ] && break; sleep 0.1; done; [ -s launcher.pid ]")+ proc = streams.run_in(env, ["bash", "-c", spawn], child_env=child_env, user=user, timeout=30)+ if proc.returncode != 0:+ raise RuntimeError(f"sandbox desktop launcher did not start: {proc.stderr.decode('utf-8', 'replace')[-500:]}")+ deadline = time.monotonic() + wait_seconds+ while time.monotonic() < deadline:+ live = _published(env, rdir)+ if live.get("DISPLAY"):+ logger.info("Bot Desktop for profile %s up inside %s on %s", profile, type(env).__name__, live["DISPLAY"])+ return _record(env, rdir, profile, live)+ time.sleep(0.25)+ tail = streams.run_in(env, ["tail", "-c", "2000", f"{rdir}/launcher.log"], user=user, timeout=10).stdout+ stop(env, profile)+ raise RuntimeError(f"sandbox desktop did not publish its display within {wait_seconds:.0f}s:\n"+ f"{tail.decode('utf-8', 'replace')}")+++def _record(env: Any, rdir: str, profile: str, live: Dict[str, str]) -> Dict[str, str]:+ _marker().parent.mkdir(parents=True, exist_ok=True)+ _marker().write_text(json.dumps({"display": live["DISPLAY"], "dir": rdir, "profile": profile,+ **_owner_identity(env)}), encoding="utf-8")+ return live+++def stop(env: Any, profile: str) -> bool:+ """Kill the launcher's session (Xvnc, dbus, Xfce, anything the desktop spawned) and, as a backstop, every+ process still holding this profile's rfb.sock or Xauthority path (a launcher that lost its pid file left+ an Xvnc that 'Server is already active for display 20' on the next start). True when something was live."""+ rdir = _remote_dir(env, profile)+ q = shlex.quote(rdir)+ script = f"""+live=0+p=$(cat {q}/launcher.pid 2>/dev/null)+if [ -n "$p" ] && kill -0 "$p" 2>/dev/null; then live=1; kill -TERM -- -"$p" 2>/dev/null || kill -TERM "$p" 2>/dev/null; fi+for pid in $(pgrep -f -- {shlex.quote(rdir + "/")} 2>/dev/null); do [ "$pid" != "$$" ] && {{ live=1; kill -TERM "$pid" 2>/dev/null; }}; done+sleep 0.5+for pid in $(pgrep -f -- {shlex.quote(rdir + "/")} 2>/dev/null); do [ "$pid" != "$$" ] && kill -KILL "$pid" 2>/dev/null; done+rm -f {q}/env {q}/launcher.pid {q}/rfb.sock+[ "$live" = 1 ]+"""+ proc = streams.run_in(env, ["bash", "-c", script], user=_user_for(env), timeout=30)+ _marker().unlink(missing_ok=True)+ return proc.returncode == 0+++def open_rfb_stream(env: Any, profile: str) -> subprocess.Popen:+ """Popen whose stdin/stdout carry the RFB bytes of the sandbox's Xvnc."""+ rdir = _remote_dir(env, profile)+ return streams.open_stream(env, ["python3", "-c", _RELAY, f"{rdir}/rfb.sock"], user=_user_for(env))+++def cua_mcp_invocation(env: Any, profile: str, published: Dict[str, str]) -> tuple[str, list[str]]:+ """``(command, args)`` for ``StdioServerParameters``: the backend's exec prefix running ``cua-driver mcp`` on+ the sandbox display."""+ argv = streams.remote_command(env, ["cua-driver", "mcp", "--no-overlay"], child_env=published,+ user=_user_for(env), interactive=True)+ if argv is None:+ raise RuntimeError(f"{type(env).__name__} cannot host cua-driver")+ return argv[0], argv[1:]diff --git a/tools/bot_desktop/thumbnail.py b/tools/bot_desktop/thumbnail.pyindex eeb61b57892..2ae3ffa2154 100644--- a/tools/bot_desktop/thumbnail.py+++ b/tools/bot_desktop/thumbnail.py@@ -22,7 +22,14 @@ def thumbnail_data_url(max_size: tuple[int, int] = THUMB_MAX, quality: int = 72)"""``data:image/jpeg;base64,...`` of the running screen, or ``None`` when no screen is up."""env = runtime.published_env()display = env.get("DISPLAY")- if not display or runtime._launcher_pid() is None:+ if not display:+ return None+ if runtime.sandbox_screen_running():+ from tools.bot_desktop import sandbox_host+ sandbox = runtime._owned_sandbox_env()+ jpeg = sandbox_host.grab_jpeg(sandbox, env, max_size, quality) if sandbox is not None else None+ return "data:image/jpeg;base64," + base64.b64encode(jpeg).decode("ascii") if jpeg else None+ if runtime._launcher_pid() is None:return Nonefrom PIL import ImageGrab # Pillow is a hard dependency; import lazily to keep status calls cheapdiff --git a/tools/browser_tool.py b/tools/browser_tool.pyindex 5bc7d626f66..69f13533c25 100644--- a/tools/browser_tool.py+++ b/tools/browser_tool.py@@ -1215,11 +1215,19 @@ def _capture_vision_screenshot(effective_task_id: str, annotate: bool, screenshoresult = _lp._annotate_lightpanda_fallback({"success": True, "data": {"path": str(screenshot_path)}}, _LP_VISION_FALLBACK_REASON)else:- screenshot_args = (["--annotate"] if annotate else []) + ["--full", str(screenshot_path)]+ # In the sandbox the CLI writes to ITS filesystem; the file is fetched back below.+ remote_path = _session.sandbox_screenshot_path(screenshot_path)+ screenshot_args = (["--annotate"] if annotate else []) + ["--full", remote_path or str(screenshot_path)]# A failed Lightpanda pre-route forces Chrome so _run_browser_command# doesn't trigger a redundant LP fallback.result = _session._run_browser_command(effective_task_id, "screenshot", screenshot_args,_engine_override="auto" if lp_prerouted else None)+ if remote_path and result.get("success"):+ try:+ _session.fetch_sandbox_file(str((result.get("data") or {}).get("path") or remote_path), screenshot_path)+ result.setdefault("data", {})["path"] = str(screenshot_path)+ except Exception as exc: # noqa: BLE001 — reported as the missing-file error below+ logger.warning("could not fetch the sandbox screenshot %s: %s", remote_path, exc)if not result.get("success"):return result, screenshot_path, _json_with_fallback(_err(f"Failed to take screenshot ({_vision._vision_mode_label()} mode): {result.get('error', 'Unknown error')}"diff --git a/tools/browser_tool_session.py b/tools/browser_tool_session.pyindex 85ba45bfb3a..7405c44f072 100644--- a/tools/browser_tool_session.py+++ b/tools/browser_tool_session.py@@ -498,6 +498,15 @@ def _recycle_local_session(task_id: str, session_info: Dict[str, Any], task_sock_bt._browser_session_backend(task_id).mark_suspect(reason)session_name = str(session_info.get("session_name") or "")+ if _browser_in_sandbox():+ # The daemon lives in the sandbox: no host pid, no host socket. Ask the CLI there to close it, evict the record.+ _sandbox_close_daemon(session_name)+ with _bt._cleanup_lock:+ if _bt._active_sessions.get(task_id) is session_info:+ _bt._active_sessions.pop(task_id, None)+ _bt._session_last_activity.pop(task_id, None)+ _bt._suspect_browser_sessions.pop(task_id, None)+ returndaemon_pid = _read_browser_daemon_pid(task_socket_dir, session_name) if session_name else Nonedaemon_alive = (daemon_pid is not None@@ -518,6 +527,49 @@ def _recycle_local_session(task_id: str, session_info: Dict[str, Any], task_sock_bt._suspect_browser_sessions.pop(task_id, None)+def _sandbox_close_daemon(session_name: str) -> None:+ """``agent-browser --session <name> close`` inside the sandbox (best effort; the daemon's own idle timer and+ the sandbox's lifetime bound it otherwise)."""+ from tools.bot_desktop import runtime as _bd_runtime, sandbox_host+ from tools.environments import streams+ env = _bd_runtime._sandbox_env(create=False)+ if env is None or not session_name:+ return+ try:+ streams.run_in(env, [_SANDBOX_AGENT_BROWSER, "--session", session_name, "close"],+ child_env={"AGENT_BROWSER_SOCKET_DIR": _sandbox_socket_dir(env)}, user=sandbox_host._user_for(env),+ timeout=15)+ except (OSError, subprocess.SubprocessError) as exc:+ _bt.logger.debug("sandbox browser close for %s failed: %s", session_name, exc)+++def _sandbox_socket_dir(env) -> str:+ return f"{env.get_temp_dir().rstrip('/')}/hermes-bot-desktop/agent-browser"+++def sandbox_screenshot_path(host_path: "Path") -> Optional[str]:+ """Where the sandboxed CLI should write a screenshot (its own tmp), or None on a gateway-hosted browser."""+ if not _browser_in_sandbox():+ return None+ from tools.bot_desktop import runtime as _bd_runtime+ env = _bd_runtime._sandbox_env(create=False)+ if env is None:+ return None+ return f"{env.get_temp_dir().rstrip('/')}/hermes-bot-desktop/shots/{host_path.name}"+++def fetch_sandbox_file(remote_path: str, local_dest: "Path", *, max_bytes: int = 16 * 1024 * 1024) -> bool:+ """Copy a file the sandboxed browser wrote (a screenshot) to the host; False when not in sandbox mode."""+ if not _browser_in_sandbox():+ return False+ from tools.bot_desktop import runtime as _bd_runtime+ env = _bd_runtime._sandbox_env(create=False)+ if env is None:+ return False+ env.fetch_file(remote_path, local_dest, max_bytes=max_bytes)+ return True++def _is_recoverable_local_backend_failure(session_info: Dict[str, Any], result: Dict[str, Any]) -> bool:"""True when a finished command failed at the agent-browser level — nonzero exit (101 =the CLI panicked against a stale session daemon), or empty/non-JSON output from a dead@@ -573,9 +625,71 @@ def _interpret_browser_command_output(command: str, stdout: str, stderr: str, rereturn parsed+_SANDBOX_AGENT_BROWSER = "agent-browser" # the CLI baked into nousresearch/hermes-sandbox:desktop+_SANDBOX_ENV_KEYS = ("AGENT_BROWSER_SOCKET_DIR", "AGENT_BROWSER_IDLE_TIMEOUT_MS", "AGENT_BROWSER_ARGS",+ "AGENT_BROWSER_PROFILE", "AGENT_BROWSER_EXECUTABLE_PATH", "AGENT_BROWSER_HEADED",+ "DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS", "ANONYMIZED_TELEMETRY", "TMPDIR")+++def _browser_in_sandbox() -> bool:+ """The bot's browser runs INSIDE the terminal backend when its screen is PLACED there (policy, not+ liveness: same Chromium a human takes over in the pane, same profile, and the host is never touched by a+ page the model chose — whether or not the screen happens to be up right now). ``_browser_command_preflight``+ is where the screen is brought up or the command refused."""+ from tools.bot_desktop import placement+ return placement.resolve().where == placement.TERMINAL+++def _sandbox_wrap(cmd_parts: List[str], browser_env: Dict[str, str], task_socket_dir: str) -> "tuple[List[str], Dict[str, str]]":+ """Rewrite one agent-browser invocation to run inside the sandbox: exec prefix + the CLI by name, with the+ browser-relevant variables exported there (the daemon's socket dir mirrors the host path so the host-side+ liveness probes keep their shape) and a screen-published DISPLAY. Identity on a gateway-hosted screen."""+ if not _browser_in_sandbox():+ return cmd_parts, browser_env+ from tools.bot_desktop import runtime as _bd_runtime, sandbox_host+ from tools.environments import streams+ env = _bd_runtime._sandbox_env(create=True)+ if env is None:+ raise RuntimeError("the terminal backend's sandbox is not running, so there is nowhere to run the browser")+ published = _bd_runtime.published_env()+ if not published.get("DISPLAY"):+ # The sandbox died under a live screen (container removed, ssh host rebooted). Fail here rather than+ # let a DISPLAY-less agent-browser run headless inside a dead sandbox or, worse, fall back to the host.+ raise RuntimeError("the screen inside the terminal backend's sandbox is gone; start it again")+ remote_env = {k: v for k, v in browser_env.items() if k in _SANDBOX_ENV_KEYS}+ remote_env.update(published)+ remote_env["AGENT_BROWSER_SOCKET_DIR"] = _sandbox_socket_dir(env)+ remote_env.pop("AGENT_BROWSER_EXECUTABLE_PATH", None) # the sandbox image's Playwright Chromium, not a host path+ remote_env["AGENT_BROWSER_PROFILE"] = sandbox_host.browser_profile_dir(env) # persists with the container, not its tmpfs+ remote_env["TMPDIR"] = env.get_temp_dir()+ if not getattr(env, "_bd_browser_dirs_ready", False):+ streams.run_in(env, ["mkdir", "-p", _sandbox_socket_dir(env), f"{env.get_temp_dir().rstrip('/')}/hermes-bot-desktop/shots",+ remote_env["AGENT_BROWSER_PROFILE"]], user=sandbox_host._user_for(env), timeout=15)+ env._bd_browser_dirs_ready = True+ remote_env["AGENT_BROWSER_ARGS"] = ",".join(CHROMIUM_SANDBOX_BYPASS_ARGS) # container: no userns for Chromium's own sandbox+ # cmd_parts = <agent-browser argv0 (+npx spec)> + backend args + command; keep everything after argv0.+ tail = cmd_parts[len(_agent_browser_argv(cmd_parts[0])):]+ wrapped = streams.remote_command(env, [_SANDBOX_AGENT_BROWSER, *tail], child_env=remote_env,+ user=sandbox_host._user_for(env), interactive=True)+ if wrapped is None:+ raise RuntimeError(f"{type(env).__name__} cannot host the browser")+ host_env = {"PATH": browser_env.get("PATH", os.environ.get("PATH", "")), "HOME": os.environ.get("HOME", "")}+ return wrapped, host_env++def _browser_command_preflight() -> Dict[str, Any]:"""Fail fast before spawning (missing CLI, Termux gap, interrupt, no Chromium in localmode — else every call hangs for command_timeout). Error result, or ``{"browser_cmd": path}``."""+ from tools.bot_desktop import placement, runtime as _bd_runtime+ try:+ where = _bd_runtime.tool_placement() # starts the sandbox screen on demand; raises for refused / down+ except RuntimeError as e:+ return {"success": False, "error": f"The browser cannot run here: {e}"}+ if where == placement.TERMINAL:+ from tools.interrupt import is_interrupted+ if is_interrupted():+ return {"success": False, "error": "Interrupted"}+ return {"browser_cmd": _SANDBOX_AGENT_BROWSER} # resolved inside the sandbox, not on this hosttry:browser_cmd = _install._find_agent_browser()except FileNotFoundError as e:@@ -624,6 +738,7 @@ def _spawn_and_collect(stdout_path = os.path.join(task_socket_dir, f"_stdout_{command}")stderr_path = os.path.join(task_socket_dir, f"_stderr_{command}")+ cmd_parts, browser_env = _sandbox_wrap(cmd_parts, browser_env, task_socket_dir)proc = _popen_agent_browser(cmd_parts, browser_env, task_socket_dir, command, stdin_payload)try:diff --git a/tools/browser_use_cli.py b/tools/browser_use_cli.pyindex 10cfbcb9a68..2f6c2e6fea4 100644--- a/tools/browser_use_cli.py+++ b/tools/browser_use_cli.py@@ -355,6 +355,31 @@ def _resolve_lightpanda_cdp(env: dict, task_id: Optional[str], session_name: strreturn err+def _reach_sandbox_cdp(cdp: str) -> str:+ """A CDP endpoint agent-browser reported from INSIDE the terminal backend's sandbox is that sandbox's+ loopback: unreachable from this host (Docker bridge / ssh remote). The harness, the vault supervisor+ and ``browser_exec`` all connect from here, so forward the port over the sandbox's exec stream and hand+ them the local end. Chromium's DevTools accepts any loopback ``Host`` header, port included."""+ try:+ from tools.browser_tool_session import _browser_in_sandbox+ if not _browser_in_sandbox():+ return cdp+ from urllib.parse import urlsplit, urlunsplit+ from tools.bot_desktop import runtime as _bd_runtime, sandbox_host+ from tools.environments import streams+ parts = urlsplit(cdp)+ if parts.hostname not in ("127.0.0.1", "localhost") or not parts.port:+ return cdp+ sandbox = _bd_runtime._sandbox_env(create=True)+ if sandbox is None:+ return cdp+ local = streams.forward_port(sandbox, parts.port, user=sandbox_host._user_for(sandbox))+ return urlunsplit(parts._replace(netloc=f"127.0.0.1:{local}"))+ except Exception as e: # a failed forward degrades to the unreachable endpoint's own error+ logger.debug("sandbox CDP forward unavailable: %s", e)+ return cdp++def _resolve_managed_chromium_cdp(env: dict, task_id: Optional[str], session_name: str = "") -> Optional[str]:"""Point the harness at Hermes' packaged Chromium, launched through agent-browser for this cache key —the same browser the built-in tools drive. Left alone, the harness discovers the user's INSTALLED@@ -375,6 +400,7 @@ def _resolve_managed_chromium_cdp(env: dict, task_id: Optional[str], session_namif not cdp:return (f"The local browser could not be started: {(res or {}).get('error') or 'agent-browser returned no CDP endpoint'} ""Run `hermes tools` → Browser Automation to (re)install Chromium, or switch backends.")+ cdp = _reach_sandbox_cdp(cdp)_set_cdp_env(env, cdp)env[_PRIVATE_BROWSER_SENTINEL] = "1" # one Chromium per cache key: nothing to share a tab withenv[_BOT_DESKTOP_BROWSER_SENTINEL] = "1"diff --git a/tools/computer_use/cua_backend.py b/tools/computer_use/cua_backend.pyindex 57f05a8913a..0d1a78ce053 100644--- a/tools/computer_use/cua_backend.py+++ b/tools/computer_use/cua_backend.py@@ -150,6 +150,28 @@ def cua_driver_child_env(base_env: Optional[Dict[str, str]] = None) -> Dict[str,env[_CUA_NATIVE_WAYLAND_ENV_VAR] = "1"return env+def sandbox_mcp_invocation() -> Optional[Tuple[Tuple[str, List[str]], Dict[str, str]]]:+ """``((command, args), child_env)`` spawning ``cua-driver mcp`` INSIDE the terminal backend when the Bot+ Desktop is placed there (the driver in the sandbox image drives the sandbox's own screen); None on a+ gateway-hosted desktop, where the local driver is used. Placement is the authority: a ``terminal``+ placement gets its screen started here and a ``refused`` one raises — the host driver is never the+ fallback for a sandbox whose screen is down."""+ from tools.bot_desktop import placement, runtime as _bd_runtime+ if _bd_runtime.tool_placement() == placement.GATEWAY:+ return None+ published = _bd_runtime.published_env()+ if not published.get("DISPLAY"):+ raise RuntimeError("the screen inside the terminal backend's sandbox is gone; start it again")+ from tools.bot_desktop import sandbox_host+ env = _bd_runtime._sandbox_env(create=True)+ if env is None:+ raise RuntimeError("the terminal backend's sandbox is not running, so there is nowhere to run cua-driver")+ command, args = sandbox_host.cua_mcp_invocation(env, _bd_runtime._profile_name(),+ {**published, _CUA_TELEMETRY_ENV_VAR: "0"})+ _bd_runtime.touch_activity()+ return (command, args), {"PATH": os.environ.get("PATH", "")}++def sanitized_cua_driver_env() -> Dict[str, str]:"""``cua_driver_child_env()`` with Hermes provider secrets stripped — cua-driver is a third-party binary and mustnever inherit API keys. Falls back to the unsanitized telemetry env if the sanitizer can't import."""@@ -256,12 +278,17 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend):self._clear_active_target()def start(self) -> None:- # Runtime acquisition is on-demand, never the explicit install command+ # Driver inside the terminal backend: the sandbox image pins its own cua-driver; the host+ # binary (if any) is not the one that will run, so neither its acquisition nor its contract+ # matters. On the host, runtime acquisition is on-demand, never the explicit install command# (which may elevate for host setup and bypass the lazy-install gate).- if not os.environ.get(_CUA_DRIVER_CMD_ENV, "").strip():- from pm import ensure- ensure("cua-driver")- contract = cua_driver_runtime_contract_status()+ if sandbox_mcp_invocation() is not None:+ contract = {"ready": True}+ else:+ if not os.environ.get(_CUA_DRIVER_CMD_ENV, "").strip():+ from pm import ensure+ ensure("cua-driver")+ contract = cua_driver_runtime_contract_status()if not contract.get("ready"):raise RuntimeError(f"cua-driver is not ready: {contract.get('reason') or 'runtime contract is incomplete'}. "+ ("Update the binary selected by HERMES_CUA_DRIVER_CMD or remove that override."@@ -408,7 +435,6 @@ class CuaDriverBackend(_CaptureMixin, _InputMixin, ComputerUseBackend):# 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.from pathlib import PureWindowsPath # noqa: F401,E402-from typing import Tuple # noqa: F401,E402import asyncio # noqa: F401,E402import base64 # noqa: F401,E402import concurrent.futures # noqa: F401,E402diff --git a/tools/computer_use/cua_backend_session.py b/tools/computer_use/cua_backend_session.pyindex 94e7ee52be1..3ccf36df30d 100644--- a/tools/computer_use/cua_backend_session.py+++ b/tools/computer_use/cua_backend_session.py@@ -223,13 +223,13 @@ class _CuaDriverSession:self._startup_phase = "binary-check"try:driver_cmd = _driver.resolve_cua_driver_cmd()- if not driver_cmd:+ if not driver_cmd and _cb.sandbox_mcp_invocation() is None:raise RuntimeError(_driver.cua_driver_install_hint())self._startup_phase = "manifest-discovery"daemon = self._embedded_daemon(command, args), child_env = ((daemon.proxy_invocation(), daemon.child_env()) if daemon is not None- else (_driver._resolve_mcp_invocation(driver_cmd), _cb.cua_driver_child_env()))+ else _cb.sandbox_mcp_invocation() or (_driver._resolve_mcp_invocation(driver_cmd), _cb.cua_driver_child_env()))_t_manifest = _time.monotonic()# Telemetry policy first (default: disabled), then strip Hermes secrets.params = StdioServerParameters(command=command, args=args, env=_sanitize_subprocess_env(child_env))diff --git a/tools/computer_use/tool.py b/tools/computer_use/tool.pyindex 8c53f361fd6..b5015af041a 100644--- a/tools/computer_use/tool.py+++ b/tools/computer_use/tool.py@@ -891,7 +891,13 @@ def check_computer_use_requirements() -> bool:if sys.platform not in ("darwin", "win32", "linux"):return Falsefrom tools.computer_use.cua_backend_driver import cua_driver_binary_available- return cua_driver_binary_available()+ if cua_driver_binary_available():+ return True+ # No host driver: the tool is still real when the desktop is placed inside a terminal backend whose image+ # carries cua-driver (nousresearch/hermes-sandbox:desktop). Placement is config; the binary is probed lazily+ # at first use, so this stays a cheap check_fn.+ from tools.bot_desktop import placement+ return placement.resolve().where == placement.TERMINALdef get_computer_use_schema() -> Dict[str, Any]:from tools.computer_use.schema import COMPUTER_USE_SCHEMAdiff --git a/tools/environments/docker.py b/tools/environments/docker.pyindex 4fed39fcc7f..1cfd06de414 100644--- a/tools/environments/docker.py+++ b/tools/environments/docker.py@@ -263,7 +263,14 @@ _BASE_SECURITY_ARGS = ["--tmpfs", "/tmp:rw,nosuid,size=512m", # no-tmp: ok — container tmpfs mount spec"--tmpfs", "/var/tmp:rw,noexec,nosuid,size=256m"]-_DEFAULT_PIDS_LIMIT = "256" # applied only when the pids cgroup controller is available+# Fork-bomb guard, applied only when the pids cgroup controller is available. The pids cgroup counts+# THREADS, and a sandbox that hosts the Bot Screen runs a desktop in here: measured on+# hermes-sandbox:desktop, the idle container is 2 tasks, Xvnc + Xfce + dbus 44, one Chromium with one+# tab 212, plus the agent's own agent-browser Chromium with two tabs 488. The old 256 was hit in normal+# use and every further `docker exec` (browser command, cua-driver, thumbnail, CDP forward) died with+# runc's "procReady not received". 2048 leaves room for a working browser and is still three orders of+# magnitude under the host's pid_max.+_DEFAULT_PIDS_LIMIT = "2048"# Docker's 64 MB /dev/shm default crashes Chromium/Playwright tabs and PyTorch# DataLoader workers. tmpfs is lazily allocated so a 1g ceiling costs nothing@@ -597,7 +604,8 @@ class DockerEnvironment(BaseEnvironment):persist_across_processes: bool = True,shm_size: str = _DEFAULT_SHM_SIZE,shared_container_key: str = "",- snap_compat: bool = False):+ snap_compat: bool = False,+ image_pinned: bool = False):if cwd == "~":cwd = "/root"super().__init__(cwd=cwd, timeout=timeout)@@ -678,6 +686,7 @@ class DockerEnvironment(BaseEnvironment):_EGRESS_LABEL_KEY: egress_label}# Saved for container recreation on "No such container" recovery.self._image = image+ self._image_pinned = image_pinnedself._image_uses_s6_init = image_uses_s6_initself._all_run_args = all_run_args@@ -842,6 +851,40 @@ class DockerEnvironment(BaseEnvironment):if existing is None:return Falsecontainer_id, state = existing+ # A container built from another image. Explicitly configured image (config.yaml /+ # TERMINAL_DOCKER_IMAGE): the user changed it, so the old container is not their sandbox any+ # more — recreate (the image is immutable after creation). Default image: a default flip+ # (nikolaik base -> hermes-sandbox:desktop) must not replace a sandbox someone has state in;+ # keep it and let the CLI / Screen pane ask. Same rule Modal (snapshot wins) and Daytona+ # (labeled sandbox wins) already apply.+ actual_image = self._container_image(container_id)+ if actual_image is not None and actual_image != self._image:+ if not self._image_pinned:+ logger.warning(+ "Existing container %s runs image %s; the default docker_image is now %s. Keeping "+ "the existing sandbox — approve the switch with `hermes config set "+ "terminal.docker_image %s` (files in /root and /workspace carry over) or pin the "+ "current image to stop this notice (task=%s, profile=%s).",+ container_id[:12], actual_image, self._image, self._image, task_label, profile_name)+ elif not self._image_available_locally():+ # The replacement image cannot be had (private/misspelled tag, registry down, pull past+ # its timeout). Removing the old container first would throw away its writable layer with+ # nothing to put in its place, so keep running the sandbox the user has and retry the+ # switch next time the image resolves.+ logger.warning(+ "Existing container %s runs image %s; docker_image is %s but that image could not be "+ "pulled — keeping the current sandbox until it can (task=%s, profile=%s).",+ container_id[:12], actual_image, self._image, task_label, profile_name)+ else:+ logger.warning(+ "Existing container %s runs image %s but docker_image is %s — removing it and "+ "starting fresh (task=%s, profile=%s).",+ container_id[:12], actual_image, self._image, task_label, profile_name)+ try:+ run_capture([self._docker_exe, "rm", "-f", container_id], timeout=30)+ except (subprocess.TimeoutExpired, OSError) as e:+ logger.warning("Failed to remove mismatched container %s: %s", container_id[:12], e)+ return Falseif not network:actual_mode = self._container_network_mode(container_id)if actual_mode != "none":@@ -870,6 +913,20 @@ class DockerEnvironment(BaseEnvironment):container_id[:12], task_label, profile_name, state)return True+ def _image_available_locally(self) -> bool:+ """True once ``self._image`` is in the local image store, pulling it when it is not. Called BEFORE a+ container replacement removes anything: a pull that fails must leave the old sandbox intact."""+ try:+ probe = run_capture([self._docker_exe, "image", "inspect", self._image, "--format", "{{.Id}}"],+ timeout=30)+ if probe.returncode == 0:+ return True+ pull = run_capture([self._docker_exe, "pull", self._image], timeout=900)+ return pull.returncode == 0+ except (subprocess.SubprocessError, OSError) as e:+ logger.warning("Docker: could not pull %s: %s", self._image, e)+ return False+def _start_container(self, container_id: str) -> Exception | None:"""``docker start`` a stopped container; returns the failure instead of raising."""try:@@ -1082,6 +1139,15 @@ class DockerEnvironment(BaseEnvironment):logger.debug("Docker --storage-opt support: %s", _storage_opt_ok)return _storage_opt_ok or False+ def _container_image(self, container_id: str) -> Optional[str]:+ """The image reference a container was created from (``Config.Image``: the tag as given+ to ``docker run``, so it compares directly with ``docker_image``), or ``None`` when+ inspection fails (callers then keep the container: a failed probe must not churn)."""+ result = _docker_query(+ [self._docker_exe, "inspect", "--format", "{{.Config.Image}}", container_id], timeout=10,+ fail="docker inspect Image failed: %s", nonzero="docker inspect Image returned %d: %s")+ return (result.stdout.strip() or None) if result is not None else None+def _container_network_mode(self, container_id: str) -> Optional[str]:"""``HostConfig.NetworkMode`` of a container, or ``None`` when inspection fails (callerstreat ``None`` as a mismatch under lockdown, so a failed inspect fails closed)."""diff --git a/tools/environments/streams.py b/tools/environments/streams.pynew file mode 100644index 00000000000..41ace989d56--- /dev/null+++ b/tools/environments/streams.py@@ -0,0 +1,213 @@+"""A long-lived process INSIDE a terminal backend with both stdio pipes open.++``BaseEnvironment.execute`` is request/response: it captures output and returns. The desktop that+follows the terminal backend needs three things that are not: the RFB byte stream between the+Desktop pane and the sandbox's Xvnc, cua-driver's MCP-over-stdio server, and agent-browser+invocations whose daemon must outlive the call. All three are "spawn argv in the sandbox, keep+stdin/stdout as pipes". Each spawn-per-call backend has a local argv prefix that gives exactly that+(``docker exec -i``, ``ssh``, ``apptainer exec``); this module is the one place that knows it.++SDK backends (modal, daytona, vercel) have no argv prefix: ``exec_prefix`` returns None there and+the desktop stays on the gateway host (or refuses, per ``bot_desktop.placement``).+"""+from __future__ import annotations++import shlex+import socket+import subprocess+import threading+from typing import Optional, Sequence++from tools.environments.base import BaseEnvironment+++def exec_prefix(env: BaseEnvironment, *, user: Optional[str] = None, interactive: bool = True) -> Optional[list[str]]:+ """Local argv that runs its remainder inside ``env``, or None for backends without one.++ ``user`` selects the sandbox-side account (docker only; ssh runs as the configured login, apptainer as+ the caller). ``interactive`` keeps stdin open (``docker exec -i``); ssh and apptainer always do.+ """+ from tools.environments.docker import DockerEnvironment+ from tools.environments.singularity import SingularityEnvironment+ from tools.environments.ssh import SSHEnvironment++ if isinstance(env, DockerEnvironment):+ container = getattr(env, "_container_id", None)+ if not container:+ return None+ argv = [env._docker_exe, "exec"]+ if interactive:+ argv.append("-i")+ if user:+ argv += ["-u", user]+ return argv + [container]+ if isinstance(env, SSHEnvironment):+ return env._build_ssh_command()+ if isinstance(env, SingularityEnvironment):+ if not getattr(env, "_instance_started", False):+ return None+ return [env.executable, "exec", f"instance://{env.instance_id}"]+ return None+++def supports_streams(env: BaseEnvironment) -> bool:+ return exec_prefix(env, interactive=True) is not None+++def remote_argv(prefix: Sequence[str], argv: Sequence[str], *, env: Optional[dict] = None,+ shell_joined: bool = False) -> list[str]:+ """``prefix`` + a ``bash -c`` that exports ``env`` and execs ``argv``.++ The script is built once, then delivered the way the client needs it: argv-preserving clients (docker,+ apptainer) get ``["bash", "-c", script]``; ``shell_joined`` clients (OpenSSH joins the words after the host+ with spaces and the remote login shell splits them again) get the whole ``bash -c '<script>'`` as ONE+ quoted word, or the remote side runs ``bash -c export`` and hands the rest to the login shell+ (``SSHEnvironment.run_bash`` quotes for the same reason). Prefer :func:`remote_command`, which knows."""+ exports = " ".join(f"export {k}={shlex.quote(v)};" for k, v in (env or {}).items())+ script = f"{exports} exec {' '.join(shlex.quote(a) for a in argv)}"+ if shell_joined:+ return [*prefix, shlex.join(["bash", "-c", script])]+ return [*prefix, "bash", "-c", script]+++def shell_joined(env: BaseEnvironment) -> bool:+ from tools.environments.ssh import SSHEnvironment+ return isinstance(env, SSHEnvironment)+++def remote_command(env: BaseEnvironment, argv: Sequence[str], *, child_env: Optional[dict] = None,+ user: Optional[str] = None, interactive: bool = True) -> Optional[list[str]]:+ """Full local argv running ``argv`` inside ``env`` with ``child_env`` exported, quoted for that backend's+ client; None for a backend without an exec prefix."""+ prefix = exec_prefix(env, user=user, interactive=interactive)+ if prefix is None:+ return None+ return remote_argv(prefix, argv, env=child_env, shell_joined=shell_joined(env))+++def open_stream(env: BaseEnvironment, argv: Sequence[str], *, child_env: Optional[dict] = None,+ user: Optional[str] = None, stderr=subprocess.DEVNULL) -> subprocess.Popen:+ """Spawn ``argv`` inside ``env`` with stdin and stdout as pipes (bytes). Raises ``RuntimeError`` for a+ backend that cannot host a stream."""+ command = remote_command(env, argv, child_env=child_env, user=user, interactive=True)+ if command is None:+ raise RuntimeError(f"{type(env).__name__} cannot host a long-lived stdio stream")+ return subprocess.Popen( # windows-footgun: ok — the prefix is a Linux sandbox's client (docker/ssh/apptainer)+ command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr, close_fds=True)+++def run_in(env: BaseEnvironment, argv: Sequence[str], *, child_env: Optional[dict] = None, user: Optional[str] = None,+ timeout: float = 30.0, stdin: Optional[bytes] = None) -> subprocess.CompletedProcess:+ """One short command inside ``env`` with captured bytes output (probes: ``command -v``, ``cat env``)."""+ command = remote_command(env, argv, child_env=child_env, user=user, interactive=stdin is not None)+ if command is None:+ raise RuntimeError(f"{type(env).__name__} cannot exec argv")+ return subprocess.run( # windows-footgun: ok — Linux sandbox client+ command, input=stdin, capture_output=True, timeout=timeout, check=False)+++# ── TCP port forwarding through the exec stream ──────────────────────────────────────────────────────+# A sandbox's loopback ports (Chromium's CDP endpoint, a dev server) are unreachable from the gateway host:+# Docker bridge / ssh remote / apptainer netns. Rather than teach every client a backend-specific tunnel+# (`docker port` needs a published port at create time; ssh -L is ssh-only), a local listener proxies each+# accepted connection over ONE exec stream running a tiny relay inside the sandbox — the same mechanism+# the Bot Screen's RFB relay uses, so it works on every backend that can exec.++_TCP_RELAY = (+ "import os,socket,sys,threading\n"+ "s=socket.create_connection((sys.argv[1],int(sys.argv[2])))\n"+ "def up():\n"+ " while True:\n"+ " d=os.read(0,65536)\n"+ " if not d: break\n"+ " s.sendall(d)\n"+ " s.shutdown(socket.SHUT_WR)\n"+ "threading.Thread(target=up,daemon=True).start()\n"+ "while True:\n"+ " d=s.recv(65536)\n"+ " if not d: break\n"+ " os.write(1,d)\n"+)++_forwards: dict[tuple[int, str, int], "PortForward"] = {}+_forwards_lock = threading.Lock()+++class PortForward:+ """Local ``127.0.0.1:<local_port>`` whose connections land on ``remote_host:remote_port`` inside ``env``."""++ def __init__(self, env: BaseEnvironment, remote_host: str, remote_port: int, *, user: Optional[str]):+ self.env, self.remote_host, self.remote_port, self.user = env, remote_host, remote_port, user+ self._server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ self._server.bind(("127.0.0.1", 0))+ self._server.listen(16)+ self.local_port: int = self._server.getsockname()[1]+ self._closed = False+ threading.Thread(target=self._accept_loop, name=f"port-forward-{self.local_port}", daemon=True).start()++ def _accept_loop(self) -> None:+ while not self._closed:+ try:+ conn, _ = self._server.accept()+ except OSError:+ return+ threading.Thread(target=self._serve, args=(conn,), daemon=True).start()++ def _serve(self, conn: socket.socket) -> None:+ try:+ proc = open_stream(self.env, ["python3", "-c", _TCP_RELAY, self.remote_host, str(self.remote_port)],+ user=self.user)+ except Exception:+ conn.close()+ return++ def to_remote() -> None:+ try:+ while True:+ data = conn.recv(65536)+ if not data:+ break+ proc.stdin.write(data)+ proc.stdin.flush()+ except (OSError, ValueError):+ pass+ finally:+ try:+ proc.stdin.close()+ except OSError:+ pass++ threading.Thread(target=to_remote, daemon=True).start()+ try:+ while True:+ data = proc.stdout.read1(65536) if hasattr(proc.stdout, "read1") else proc.stdout.read(65536)+ if not data:+ break+ conn.sendall(data)+ except OSError:+ pass+ finally:+ try:+ conn.close()+ finally:+ proc.kill()++ def close(self) -> None:+ self._closed = True+ try:+ self._server.close()+ except OSError:+ pass+++def forward_port(env: BaseEnvironment, remote_port: int, *, remote_host: str = "127.0.0.1",+ user: Optional[str] = None) -> int:+ """Local port on 127.0.0.1 that reaches ``remote_host:remote_port`` inside ``env``; one listener per+ (env, host, port) is kept for the process lifetime (daemon threads, nothing to clean up)."""+ key = (id(env), remote_host, int(remote_port))+ with _forwards_lock:+ fwd = _forwards.get(key)+ if fwd is None or fwd._closed:+ fwd = _forwards[key] = PortForward(env, remote_host, int(remote_port), user=user)+ return fwd.local_portdiff --git a/tools/terminal_scope.py b/tools/terminal_scope.pyindex a7cf9ba644e..4d7e16ade9f 100644--- a/tools/terminal_scope.py+++ b/tools/terminal_scope.py@@ -121,6 +121,7 @@ def build_profile_terminal_scope(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@@ -131,10 +132,21 @@ def build_profile_terminal_scope(raise TerminalPolicyUnavailable(f"cannot read {env_path}: {exc}") from excfrom agent.secret_scope import load_env_file- scope.update((k, str(v)) for k, v in load_env_file(env_path).items()- if k.startswith("TERMINAL_"))+ 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 = Falseif env_overlay:- scope.update((k, str(v)) for k, v in env_overlay.items() if k.startswith("TERMINAL_"))+ 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"@@ -153,6 +165,8 @@ def build_profile_terminal_scope(raw_terminal = raw.get("terminal") if isinstance(raw, dict) else Noneif 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 scopediff --git a/tools/terminal_tool.py b/tools/terminal_tool.pyindex be1496847b6..859bc2e6c4e 100644--- a/tools/terminal_tool.py+++ b/tools/terminal_tool.py@@ -695,7 +695,7 @@ def _resolve_config_cwd(env_type: str, mount_docker_cwd: bool) -> tuple:def _get_env_config() -> Dict[str, Any]:"""Resolve the terminal configuration dict from TERMINAL_* env vars."""- default_image = "nikolaik/python-nodejs:python3.11-nodejs20"+ from hermes_cli.config_defaults import DEFAULT_SANDBOX_IMAGE as default_image_ensure_terminal_env_bridged()env_type = _tenv("TERMINAL_ENV", "local")mount_docker_cwd = _tenv_bool("TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", "false")@@ -725,6 +725,7 @@ def _get_env_config() -> Dict[str, Any]:"env_type": env_type,"modal_mode": coerce_modal_mode(_tenv("TERMINAL_MODAL_MODE", "auto")),"docker_image": _tenv("TERMINAL_DOCKER_IMAGE", default_image),+ "docker_image_pinned": _tenv("TERMINAL_DOCKER_IMAGE_PINNED", "0") == "1","docker_forward_env": docker_forward_env,"singularity_image": _tenv("TERMINAL_SINGULARITY_IMAGE", f"docker://{default_image}"),"modal_image": _tenv("TERMINAL_MODAL_IMAGE", default_image),diff --git a/tools/terminal_tool_backends.py b/tools/terminal_tool_backends.pyindex 4515eaef029..5a5df1c5ed5 100644--- a/tools/terminal_tool_backends.py+++ b/tools/terminal_tool_backends.py@@ -66,6 +66,7 @@ _CONTAINER_KEYS = (("docker_env", {}), ("docker_run_as_host_user", False), ("docker_extra_args", []),("docker_shm_size", "1g"), ("docker_network", True), ("docker_persist_across_processes", True),("docker_shared_container_key", ""), ("docker_orphan_reaper", True), ("docker_snap_compat", False),+ ("docker_image_pinned", False),)_DOCKER_KWARGS = (("volumes", "docker_volumes", []), ("auto_mount_cwd", "docker_mount_cwd_to_workspace", False),@@ -73,7 +74,7 @@ _DOCKER_KWARGS = (("run_as_host_user", "docker_run_as_host_user", False), ("network", "docker_network", True),("extra_args", "docker_extra_args", []), ("persist_across_processes", "docker_persist_across_processes", True),("shared_container_key", "docker_shared_container_key", ""), ("shm_size", "docker_shm_size", "1g"),- ("snap_compat", "docker_snap_compat", False),+ ("snap_compat", "docker_snap_compat", False), ("image_pinned", "docker_image_pinned", False),)diff --git a/tui_gateway/contracts/display.py b/tui_gateway/contracts/display.pyindex 6f9f471db11..7f36f342773 100644--- a/tui_gateway/contracts/display.py+++ b/tui_gateway/contracts/display.py@@ -34,6 +34,14 @@ class DisplayLease(Result):reason: str = ""+class DisplayImageSwitch(Result):+ """A persisted Docker sandbox kept on the previous default image; the user decides the switch."""++ current_image: str+ target_image: str+ containers: int++class DisplayStatus(Result):"""``tools/bot_desktop/runtime.py::DesktopStatus`` plus the lease and the profile it speaks for."""@@ -51,6 +59,8 @@ class DisplayStatus(Result):blocker: str | None = None # why display.start would refuse now (host memory); the pane shows it instead of Startmemory_available_mb: int | None = Nonememory_limit_mb: int | None = None+ placement: str = "gateway" # "gateway" | "terminal:<backend>" — where Xvnc runs (bot_desktop.placement)+ image_switch: DisplayImageSwitch | None = None # a default-image switch the pane may approve (docker placement)lease: DisplayLeaseprofile_key: str@@ -109,6 +119,18 @@ class DisplayInstallResult(Result):profile_key: str+class DisplaySwitchSandboxImageParams(ProfileParams):+ approve: bool = True # true: pin the new image (container recreated on next use); false: keep the current one+++class DisplaySwitchSandboxImageResult(DisplayStatus):+ docker_image: str # the image now pinned in terminal.docker_image+++method("display.switchSandboxImage", params=DisplaySwitchSandboxImageParams, result=DisplaySwitchSandboxImageResult,+ doc="Decide the pending default sandbox image switch for this profile; refused when none is pending.")++method("display.install", params=ProfileParams, result=DisplayInstallResult,doc="Run the distro package install on the gateway host; progress streams as display.install.log/.done.")diff --git a/tui_gateway/methods_display.py b/tui_gateway/methods_display.pyindex c3bbebb5484..9b7c780fb06 100644--- a/tui_gateway/methods_display.py+++ b/tui_gateway/methods_display.py@@ -156,7 +156,8 @@ def _(rid, params: dict) -> dict:from hermes_cli.dashboard_auth.ws_tickets import mint_ticketfrom tools.bot_desktop import runtime as _bd_runtimetry:- if _bd_runtime.rfb_socket_path() is None:+ # The bridge dials either the host RFB socket or the sandbox relay; neither exists before start.+ if _bd_runtime.rfb_socket_path() is None and not _bd_runtime.sandbox_screen_running():return _err(rid, _DISPLAY_ERR, "this profile's Bot Desktop is not running; call display.start first")viewer_id = _mint_viewer_id(str(params.get("viewer_id") or "").strip())ticket = mint_ticket(user_id=f"display:{viewer_id}", provider="bot-desktop",@@ -167,6 +168,20 @@ def _(rid, params: dict) -> dict:return _err(rid, _DISPLAY_ERR, str(e))+@method("display.switchSandboxImage")+@_profile_scoped+def _(rid, params: dict) -> dict:+ """The Screen pane's answer to the pending default-image switch: ``approve`` true pins the new+ image (the container is recreated on the next terminal call), false pins the current one. Both+ end the offer. Refused when nothing is pending, so a stale pane cannot rewrite the config."""+ from hermes_cli.sandbox_image_switch import decide, pending+ sw = pending()+ if sw is None:+ return _err(rid, _DISPLAY_ERR, "no sandbox image switch is pending for this profile")+ image = decide(sw, approve=bool(params.get("approve", True)))+ return _ok(rid, {"docker_image": image, **_display_snapshot()})++@method("display.install")@_profile_scopeddef _(rid, params: dict) -> dict:@@ -176,6 +191,10 @@ def _(rid, params: dict) -> dict:from tools.bot_desktop import install as _bd_install, runtime as _bd_runtimeif not _bd_runtime.is_supported_host():return _err(rid, _DISPLAY_ERR, "Bot Desktop runs on Linux gateway hosts only")+ if _bd_runtime.in_sandbox():+ return _err(rid, _DISPLAY_ERR, "this profile's screen lives inside the terminal backend's sandbox; give that "+ "sandbox an image with the desktop stack (nousresearch/hermes-sandbox:desktop) "+ "instead of installing on the gateway host")if _bd_runtime.install_command() is None:return _err(rid, _DISPLAY_ERR, "no supported package manager (apt-get, dnf, pacman) on this host")profile_key = hermes_home_key()diff --git a/website/docs/guides/secure-hermes-on-a-work-machine.md b/website/docs/guides/secure-hermes-on-a-work-machine.mdindex 2f8d230b0c0..2ecf8cc20fa 100644--- a/website/docs/guides/secure-hermes-on-a-work-machine.md+++ b/website/docs/guides/secure-hermes-on-a-work-machine.md@@ -86,7 +86,7 @@ The strongest isolation is not running commands on your machine at all. The term```yamlterminal:backend: docker- docker_image: "nikolaik/python-nodejs:python3.11-nodejs20"+ docker_image: "nousresearch/hermes-sandbox:desktop"docker_forward_env: [] # Explicit allowlist only; empty keeps secrets out of the container```diff --git a/website/docs/guides/team-telegram-assistant.md b/website/docs/guides/team-telegram-assistant.mdindex 31218f3db33..2b57ea8fbad 100644--- a/website/docs/guides/team-telegram-assistant.md+++ b/website/docs/guides/team-telegram-assistant.md@@ -375,7 +375,7 @@ On a shared team bot, use Docker as the terminal backend so agent commands run i```bash# In ~/.hermes/.envTERMINAL_ENV=docker-TERMINAL_DOCKER_IMAGE=nikolaik/python-nodejs:python3.11-nodejs20+TERMINAL_DOCKER_IMAGE=nousresearch/hermes-sandbox:desktop```Or in `~/.hermes/config.yaml`:diff --git a/website/docs/reference/environment-variables.md b/website/docs/reference/environment-variables.mdindex 571e4e284e8..fc1b5e313fc 100644--- a/website/docs/reference/environment-variables.md+++ b/website/docs/reference/environment-variables.md@@ -250,7 +250,7 @@ These variables configure the [Tool Gateway](../user-guide/features/tool-gateway|----------|-------------|| `TERMINAL_ENV` | Backend: `local`, `docker`, `ssh`, `singularity`, `modal`, `daytona`, `vercel_sandbox` || `HERMES_DOCKER_BINARY` | Override the container binary Hermes shells out to (e.g. `podman`, `/usr/local/bin/docker`). When unset, Hermes auto-discovers `docker` or `podman` on `PATH`. Needed when both are installed and you want the non-default, or when the binary lives outside `PATH`. |-| `TERMINAL_DOCKER_IMAGE` | Docker image (default: `nikolaik/python-nodejs:python3.11-nodejs20`) |+| `TERMINAL_DOCKER_IMAGE` | Docker image (default: `nousresearch/hermes-sandbox:desktop`) || `TERMINAL_DOCKER_FORWARD_ENV` | JSON array of env var names to explicitly forward into Docker terminal sessions. Note: skill-declared `required_environment_variables` are forwarded automatically — you only need this for vars not declared by any skill. || `TERMINAL_DOCKER_VOLUMES` | Additional Docker volume mounts (comma-separated `host:container` pairs) || `TERMINAL_DOCKER_ENV` | JSON object of extra env vars to set inside Docker terminal sessions (e.g. `{"FOO":"bar"}`) |diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 23aaa7fc5f7..8e99de51529 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -232,9 +232,9 @@ terminal:home_mode: auto # auto | real | profile — subprocess HOME policyenv_passthrough: [] # Env var names to forward to sandboxed execution (terminal + execute_code)sync_back_max_bytes: 2147483648 # Remote backends: refuse to extract a state archive larger than this (bytes)- singularity_image: "docker://nikolaik/python-nodejs:python3.11-nodejs20" # Container image for Singularity backend- modal_image: "nikolaik/python-nodejs:python3.11-nodejs20" # Container image for Modal backend- daytona_image: "nikolaik/python-nodejs:python3.11-nodejs20" # Container image for Daytona backend+ singularity_image: "docker://nousresearch/hermes-sandbox:desktop" # Container image for Singularity backend+ modal_image: "nousresearch/hermes-sandbox:desktop" # Container image for Modal backend+ daytona_image: "nousresearch/hermes-sandbox:desktop" # Container image for Daytona backend````terminal.temp_dir` controls where Hermes puts session temp artifacts on the@@ -354,7 +354,12 @@ Runs commands inside a Docker container with security hardening (all capabilitie```yamlterminal:backend: docker- docker_image: "nikolaik/python-nodejs:python3.11-nodejs20"+ # Default: nikolaik/python-nodejs (Python 3.13 / Node 26) plus a display stack, so Bot Screen,+ # computer_use and the browser run INSIDE this sandbox (Bot Screen → "Where the screen runs").+ # Any other image works for shell work; the screen then needs bot_desktop.placement: gateway.+ # Writing this key is a decision: a persisted container on another image is recreated on the next+ # terminal call. Left unset, an existing container is kept and the CLI / Screen pane ask first.+ docker_image: "nousresearch/hermes-sandbox:desktop"docker_mount_cwd_to_workspace: false # Mount launch dir into /workspacedocker_run_as_host_user: false # See "Running container as host user" belowdocker_snap_compat: false # See "Snap-packaged Docker (AppArmor)" below@@ -583,7 +588,7 @@ Runs commands in a [Singularity/Apptainer](https://apptainer.org) container. Des```yamlterminal:backend: singularity- singularity_image: "docker://nikolaik/python-nodejs:python3.11-nodejs20"+ singularity_image: "docker://nousresearch/hermes-sandbox:desktop"container_cpu: 1 # CPU corescontainer_memory: 5120 # MBcontainer_persistent: true # Writable overlay persists across sessionsdiff --git a/website/docs/user-guide/features/bot-screen.md b/website/docs/user-guide/features/bot-screen.mdindex 141c6d2e050..1f90b8f7dcf 100644--- a/website/docs/user-guide/features/bot-screen.md+++ b/website/docs/user-guide/features/bot-screen.md@@ -11,7 +11,11 @@ browser act on, streamed live into Hermes Desktop. Watch what the bot does,**take over** when it hits a login, 2FA prompt, CAPTCHA or payment step, then**hand control back** and let it continue with the session you just signed into. The bot keeps working after you close the app or turn off your laptop; the-screen lives on the gateway host, not on your machine.+screen lives on the gateway host, not on your machine. If the gateway runs its+`terminal` in a sandbox (`terminal.backend: docker`, `ssh` or `singularity`),+the screen lives **inside that sandbox** instead, alongside the shell, so the+bot's `computer_use` and browser never act outside the boundary you drew (see+[Where the screen runs](#where-the-screen-runs)).Every Hermes profile ("bot") has its own screen, its own browser profile andits own cookies. Screens are work surfaces, not security boundaries: the bots@@ -222,6 +226,109 @@ hermes computer-use screen install [-y] # apt/dnf/pacman the packageshermes -p research computer-use screen start # another bot's screen```+## Where the screen runs++`computer_use`, the bot's browser and the screen they act on always run in the+same place. `bot_desktop.placement` decides where:++| `terminal.backend` | `placement: auto` (default) | What that means |+|---|---|---|+| `local` | gateway host | The terminal, the screen, the browser and `computer_use` all share the machine running the gateway. |+| `docker`, `ssh`, `singularity` | **inside the sandbox** | Xvnc + Xfce, Chromium and cua-driver run in the container / on the SSH host, spawned through the same `docker exec` / `ssh` channel the terminal uses. The pane streams the sandbox's screen; nothing of the host desktop is reachable. |+| `modal`, `daytona`, `vercel_sandbox` | **refused** | These backends cannot host a display yet. Rather than quietly running the screen on the host beside the sandbox you chose for the agent, `Start` explains and points at `placement: gateway`. |++`placement: gateway` forces the pre-existing behaviour (screen on the gateway+host even with a sandboxed terminal) as an explicit opt-in; `placement:+terminal` forces the sandbox and errors when it cannot host one (with a+`local` backend the terminal *is* the gateway host, so it resolves there).++Placement is policy, not a snapshot of what happens to be running. When the+screen is placed in the sandbox, the first browser or `computer_use` call+brings it up there on demand (no `auto_start` opt-in needed: the sandbox is+the boundary you chose, and a screen inside it touches nothing outside it),+and when it cannot come up the call fails with the reason. The host is never+the fallback for a sandbox whose screen is down. A gateway restart does not+lose the screen either: the host-side marker records which container owns+it, so the restarted gateway re-attaches to a still-running sandbox, and+`Stop` takes down the screen where it actually runs even if you changed+`placement` in the meantime.++### The sandbox image++The sandbox needs the desktop stack. `nousresearch/hermes-sandbox:desktop` is+the default image for every container backend (Docker, Modal, Daytona,+Singularity): the `nikolaik/python-nodejs` base (Python 3.13 / Node 26) plus+TigerVNC, the Xfce components, a headed Chromium, `agent-browser`, `cua-driver`+and the everyday tools that base lacked (jq, ripgrep, fd, tmux, rsync, sudo for+the image's `pn` user). Its default user is root, like the old default, so+shell workflows do not change. An image you pinned yourself is left alone, and+the screen then tells you it needs this image or `bot_desktop.placement: gateway`:++```yaml+terminal:+ backend: docker+ docker_image: nousresearch/hermes-sandbox:desktop+```++With a plain image the Screen pane reports the missing binaries and names+this tag.++Under Singularity/Apptainer the same image is converted to a SIF+(`docker://nousresearch/hermes-sandbox:desktop`); Dockerfile `ENV` survives the+conversion, the image's `USER` does not: everything runs as you, so the browser+profile lands in your `$HOME` inside the container, which is the persistent+overlay by default. The instance runs `--containall`, so its temp dir (where the+screen's runtime state lives) is Apptainer's session tmpfs, 64 MiB unless your+admin raised `sessiondir max size`. This path is verified against the Apptainer+documentation, not exercised live.++An SSH host is whatever you point the backend at, so it carries the stack+itself: the same binaries (TigerVNC, Xfce, `cua-driver`, `agent-browser` with a+Chromium it can find), reachable from a **non-interactive login session**. That+last part is where a host built from the desktop image differs from `docker exec`:+a Dockerfile `ENV` never reaches an ssh session, so the image also writes+`PLAYWRIGHT_BROWSERS_PATH` to `/etc/environment` for PAM to apply. A host of+your own needs the equivalent, or `agent-browser` reports "Chrome not found"+over ssh while working in a local shell.++**Upgrading from the previous default.** A Docker sandbox you already have is+kept, not replaced: when `docker_image` is unset and a persisted container runs+another image (the old default, `nikolaik/python-nodejs:python3.11-nodejs20`),+the terminal keeps using that container and you decide the switch. The+interactive CLI asks once at startup; the Screen pane shows the same choice+with **Switch image** / **Keep current image**; `hermes config set+terminal.docker_image nousresearch/hermes-sandbox:desktop` is the same answer+from any shell. Either answer writes `terminal.docker_image`, and a written+image is a decision: the container is recreated on the next terminal call only+when you chose the new image, and only once the new image has been pulled (a+private or misspelled tag, or a registry outage, keeps your current container+running instead of leaving you with nothing). What a switch means: files under `/root` and+`/workspace` stay (they are host directories under `~/.hermes/sandboxes/`),+packages installed inside the container with `apt`/`pip`/`npm -g` are+reinstalled on demand, and Python 3.11 virtualenvs need a rebuild on 3.13.+Gateways and cron never decide; they keep the sandbox and log the notice.+Configs that literally held the old default were unset on upgrade (that value+was the template copied, not a pin). Modal restores its snapshot and Daytona+reuses its labeled sandbox regardless of the configured image, so an existing+sandbox there is untouched and only a fresh one gets the new image. Desktop processes run as the image's unprivileged `pn` (uid 1000);+Chromium gets `--no-sandbox` inside containers (Docker's seccomp profile+denies the user namespaces its own sandbox needs; the container is the+sandbox).++Runtime state inside the sandbox (X socket, cookie, launcher log) lives under+`<sandbox tmp>/hermes-bot-desktop/<profile>/`; the host keeps only a marker under+`<HERMES_HOME>/bot-desktop/`. The browser profile (logins, cookies) lives in the+desktop user's home inside the sandbox, `~/.hermes/bot-desktop/browser-profile`,+shared by the agent's browser and the dock's **Browser** icon. It follows the+container's own persistence: kept across stops and restarts of a persisted+container, gone with an ephemeral one or when you approve an image switch (the+container's writable layer is what a switch replaces). It is deliberately not+under the container's temp dir, which Docker mounts as a small tmpfs that is emptied on every stop.+Screenshots the browser tools take are copied back to the host so `MEDIA:`+paths keep working, the pane's thumbnail is grabbed inside the sandbox, and+`browser_exec` / the vault autofill reach the sandbox's Chromium through a port+forwarded over the same `docker exec` / `ssh` channel.+## Configuration```yaml@@ -230,6 +337,7 @@ bot_desktop:auto_start: false # set true to start on the first computer_use call or headed browser usemin_free_memory_mb: 1536 # refuse to start below this much free memory (0 = never check)idle_stop_minutes: 30 # stop a screen nobody used for this long (0 = keep it up)+ placement: auto # auto | terminal | gateway — see "Where the screen runs"````auto_start` is off by default. Start the screen from the Desktop's Screendiff --git a/website/docs/user-guide/features/computer-use.md b/website/docs/user-guide/features/computer-use.mdindex c5fc3512679..d8649e42a43 100644--- a/website/docs/user-guide/features/computer-use.md+++ b/website/docs/user-guide/features/computer-use.md@@ -39,6 +39,19 @@ For the underlying contract — *why* background mode matters, theno-foreground invariant, click-dispatch internals — see**[cua.ai/docs/explanation/the-no-foreground-contract](https://cua.ai/docs/explanation/the-no-foreground-contract)**.+## Which machine it drives++`computer_use` acts on the same machine the bot's screen lives on, never on+the machine running Hermes Desktop. On a gateway with `terminal.backend:+local` that is the gateway host. With a sandboxed terminal (`docker`, `ssh`,+`singularity`) the driver runs **inside the sandbox** on the sandbox's own+display, so it can only ever touch what the terminal can; the sandbox image+must carry `cua-driver` (`nousresearch/hermes-sandbox:desktop` does). Modal,+Daytona and Vercel sandboxes cannot host a display yet, so with those+backends `computer_use` refuses unless `bot_desktop.placement: gateway` opts+into driving the host. Details: [Bot Screen → Where the screen+runs](./bot-screen.md#where-the-screen-runs).+## Enabling**The driver ships with Hermes.** `cua-driver` is pinned in `pm/lock.json`diff --git a/website/docs/user-guide/security.md b/website/docs/user-guide/security.mdindex db9f86be7ce..72b52af6cae 100644--- a/website/docs/user-guide/security.md+++ b/website/docs/user-guide/security.md@@ -563,7 +563,7 @@ Container resources are configurable in `~/.hermes/config.yaml`:```yamlterminal:backend: docker- docker_image: "nikolaik/python-nodejs:python3.11-nodejs20"+ docker_image: "nousresearch/hermes-sandbox:desktop"docker_forward_env: [] # Explicit allowlist only; empty keeps secrets out of the containercontainer_cpu: 1 # CPU corescontainer_memory: 5120 # MB (default 5GB)