Commit Graph

70 Commits

Author SHA1 Message Date
kshitijk4poor
dd7a47917b chore(process): mark the browser/desktop spawns that must stay detached, with the reason
The detached-spawn check flags every start_new_session outside spawn_owned. Three in this family are
deliberate, and each line now says why:

- tools/bot_desktop/runtime.py (Bot Desktop launcher: Xvnc + Xfce per profile). The screen outlives
  whichever CLI or gateway started it. `hermes computer-use screen start` exits right after start(),
  launcher.pid records (pid, create_time) so any later process reports or stops it, and the gateway's
  display watcher idle-stops it (b41c8ddfc4, 71971e9205). Owning it would kill every CLI-started screen
  the moment the CLI exits.
- hermes_cli/browser_connect.py (/browser connect launching the user's debug Chrome). It is the user's
  browser: the connection persists in BROWSER_CDP_URL and a later session re-attaches to it, and Hermes
  never stops it (d1ee4915f3 made the detach explicit on both platforms).
- tools/bot_desktop/install.py (apt/dnf under sudo). Short-lived and awaited. The group exists only so
  the timeout kill reaches the package manager.

Comments only; no behaviour change.
2026-10-29 16:58:09 +05:30
kshitijk4poor
de5f56c92a refactor(deadline): one poll_until for check-until-deadline loops
Twenty loops across 17 files hand-wrote the same thing:

    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        if condition(): return ...
        time.sleep(interval)

with small drifts between copies: some re-checked once after the loop,
some did not, one slept before its first check, and update_cmd_windows
kept a private _poll_until. A copy without the final check can miss a
condition that becomes true during the last sleep.

agent/deadline.py (already the home of clamp_timeout / run_bounded_*)
gains poll_until(predicate, timeout, interval): checks at once, cuts the
last sleep to the time left, checks again at the deadline, and returns
the predicate's last value so callers that wait for a pid / row /
identity get it back directly. timeout <= 0 is one check.

Converted: outbound_webhooks.flush, cron delivery wait and jobs flock,
host_attach channel wait, browser profile unlock, data-cleanup drain,
gateway dbus/bus waits, launchd fresh-pid and supervision waits,
supervised restart, gateway_migrate live-gateway wait, Windows
drain/absent waits, kanban init lock, local-runtime boot wait,
update_cmd_windows (private helper deleted), bot desktop start/stop
waits, TUI browser connect.

Left as is: loops whose body does more than check (progress callbacks,
interrupt handling, two distinct exits) and one site whose blind except
the health gate would reject once moved.

Behaviour changes, all small:
- loops that stopped at the deadline without re-checking now make one
  more check there;
- loops that already re-checked after a full last sleep now cut that
  sleep to the time left, so the check lands at the deadline (up to one
  interval sooner);
- a timeout <= 0 now means one check (some loops made none);
- the local-runtime boot wait checks before its first sleep instead of
  after it;
- _wait_for_user_dbus_socket also exports the user systemd env when the
  socket appears on that final check (before, that path returned True
  without it).

update_cmd_windows is imported by update_cmd on every OS, so the
fresh-source-install acceptance fixture (which keeps agent/ out of the
update path) now copies the stdlib-only agent/deadline.py too.

Tests: 4 pins for poll_until (two red against the classic
no-final-check variant), plus the existing suites for every touched
module.
2026-10-27 16:30:14 +05:30
Teknium
855f03e3f7 feat(browser): Python Chromium launcher + browser_session layer (API for browser_exec-only)
New tools/ runtime that replaces agent-browser's one job for browser_exec:
- tools/browser_launcher.py: launch/track/stop the packaged Chromium
  (--remote-debugging-port=0 + DevToolsActivePort, per-(home, key)
  ephemeral user-data-dir, headless default, sandbox-bypass detection),
  parent-first stop, host-wide launch records + identity-checked orphan reap,
  attach to a Chromium already running on a persistent profile.
- tools/browser_session.py (+ _lifecycle, _cloud, _cdp, _real_profile,
  _sandbox): session cache per cache key with the existing creation
  precedence; every session carries cdp_url.
- tools/browser_url_policy.py: URL safety + SSRF helpers.
- browser_lightpanda: using_lightpanda_engine / lightpanda_engine_status.
- bot_desktop.browser reads browser.executable_path / browser.user_data_dir;
  env_for_agent is gone (the launcher passes binary + profile explicitly).
2026-10-23 01:41:23 -07:00
Teknium
d99af4187b refactor: move the Singularity terminal backend out of core into the singularity catalog plugin
The Singularity/Apptainer backend (tools/environments/singularity.py) now ships
as the official 'singularity' plugin in NousResearch/hermes-official-plugins,
registered through the terminal-environment provider seam under the same
backend name and config keys (terminal.backend: singularity,
terminal.singularity_image / TERMINAL_SINGULARITY_IMAGE, terminal.container_*).

- 'singularity' leaves BUILTIN_BACKEND_NAMES so the plugin can register it;
  every hardcoded classification set drops it (the provider declares
  is_remote/is_container/supports_streams instead).
- LEFT_CORE gains a singularity row: homes whose terminal.backend (or .env
  TERMINAL_ENV) is singularity get the catalog plugin once, on hermes update
  or agent/gateway start. An unknown-backend error for 'singularity' names
  the install command (new row field terminal_backend).
- A plugin backend receives its per-task '<backend>_image' override; batch
  runs register one for the active backend.
- BaseEnvironment's sudo-probe knob is renamed _passwordless_sudo_probe_supported:
  plugin backends set it, and the old spelling trips the install scanner.
- Core's scratch-dir disk warning and process-exit sweep were Singularity-only
  and move to the plugin; the singularity setup row, dashboard probe/row and
  config defaults/bridges go too. Docs point at the plugin.
2026-10-22 05:26:10 -07:00
unsupportedpastels
71633f762d fix(terminal): review follow-ups for plugin cwd and stream hooks
- A declared absolute default_cwd is stamped as the sandbox home even
  when terminal.cwd starts the environment elsewhere, so a cd under that
  home survives to the next command (Greptile).
- The file tools' plugin-home lookup shares _ssh_remote_home's guarded
  bring-up: a failed connect is remembered for 30s instead of being
  retried by every path resolution in one tool call (Greptile). When it
  can't connect, relative paths fall back to the process cwd and the file
  operation itself fails on the same connection (Teknium).
- streams.sandbox_temp_dir(): Bot Desktop and the sandboxed browser use
  the environment's get_temp_dir() when it has one, else the BaseEnvironment
  default, so a plugin environment that doesn't subclass BaseEnvironment can
  host the screen (Greptile).
- A plugin exec_prefix() that returns a string, not a list, is refused as
  "can't stream" instead of being split into one-character argv words
  (Teknium).
- The missing-desktop-stack messages no longer name a terminal.<plugin>_image
  key for plugin backends; they point at the plugin's own image setting
  (Teknium).
2026-10-20 16:17:56 -04:00
unsupportedpastels
e166392fec feat(terminal): let plugin backends set their start dir and host Bot Desktop
Two opt-in additions to TerminalEnvironmentProvider; plugins that set
neither behave exactly as before.

- default_cwd: where commands start when terminal.cwd is unset, or is a
  host path the container guard discards, instead of the generic /root.
  Either an absolute in-sandbox path, or "~" for each sandbox's own home:
  it stays "~" (never expanded on the host), create_environment receives
  cwd="~", and the home the environment resolved is stamped on that
  environment. A recorded cwd under that home is kept for later commands
  instead of being dropped as a host /home/... path, and the file tools
  anchor relative paths at the same home.
- supports_streams: the backend's environments implement
  exec_prefix(*, user=None, interactive=True), a local argv that runs
  its remainder inside the sandbox with stdio open. streams.exec_prefix
  uses it for non-built-in environments, and bot_desktop placement
  treats such a backend like docker/ssh/singularity instead of refusing,
  so the screen, computer_use and the browser follow the terminal in.
  Under plugins.isolation: host the environment reaches Hermes as an
  opaque placeholder, so placement refuses with a reason naming the
  setting.
2026-10-20 16:17:56 -04:00
Maciej Lisiewski
0006a5e229 ci: fix PLW1509, PLW1510, PLW2101 linter errors 2026-10-10 15:20:13 +02:00
Maciej Lisiewski
2ff58849f4 ci: ruff UP037 fixes 2026-10-09 17:34:38 +02:00
Maciej Lisiewski
c0fc687685 ci: address code review comments 2026-10-08 18:04:50 +02:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
kshitijk4poor
43800d55f2 fix(child-env): the bot desktop and gmail-triage scripts start from the scrubbed env
Two more spawns inherited the gateway's full environment. The bot
desktop launcher copied os.environ minus the display variables; the
agent drives that desktop and its dock opens xfce4-terminal, so every
provider key and bot token was one click away. The Telegram gmail-triage
buttons ran HERMES_HOME/scripts/gmail-triage/*.sh with no env at all, a
path the agent can write. The desktop now builds from
served_profile_child_env() like the agent browser (keeping the user's
HOME); the triage scripts use build_subprocess_env like cron and
webhook-filter scripts.
2026-09-29 02:06:58 +05:30
Teknium
399d956903 feat(bot_desktop): Bot Screen, computer_use and the browser run inside the terminal backend (#121169)
* feat(docker): publish nousresearch/hermes-sandbox:desktop for terminal backends

The terminal backends (docker, modal, daytona, singularity) all default to
nikolaik/python-nodejs:python3.11-nodejs20, a bare Python+Node base. For Bot
Screen, computer_use and the browser to run INSIDE that sandbox instead of on
the gateway host, the sandbox image needs the display stack.

docker/sandbox-desktop.Dockerfile is that base plus:
  - the everyday tools it lacked (jq, ripgrep, fd, tmux, less, nano, vim,
    zip, rsync, tree, procps, htop, sudo for the base's uid-1000 `pn`)
  - the exact package set the Hermes -desktop image installs (TigerVNC,
    Xfce components, dbus, xauth, fonts)
  - Playwright's headed Chromium (same build as the -desktop image)
  - cua-driver 0.28.2 from its pinned release tarball

No Hermes inside; the default user stays root like the base so nothing
changes for people who just switch docker_image. Desktop processes run as
`pn`. 4.27 GB on amd64.

docker.yml gains a `sandbox` variant with its own cache scope and repository
(nousresearch/hermes-sandbox:desktop, :main-desktop, :<release>-desktop);
the docker-integration suite is skipped for it (no Hermes to test) and
docker/sandbox-desktop-smoke.sh runs instead: as `pn`, every launcher and
cua-driver binary resolves, the real launcher.sh publishes :20, the RFB
socket completes the 3.8 handshake relayed over `docker exec -i` stdio, and
a headed Chromium maps a window on that display. hadolint lints the new
Dockerfile in docker-lint.yml.

* feat(docker): sandbox desktop base on python3.13-nodejs26

Matches the Hermes image (Python 3.13 / Node 26) and the top of requires-python;
the default docker_image tag it inherited was Python 3.11 / Node 20. Same pn
uid 1000, Debian 13; smoke (launcher, RFB relay, headed Chromium) passes.

* feat(docker): bake agent-browser into hermes-sandbox:desktop

The browser tools drive the agent-browser CLI; when the browser follows the
terminal backend that CLI has to exist inside the sandbox. Pinned to the same
^0.26.0 range the gateway resolves, --ignore-scripts like the gateway's npx path.

* feat(bot_desktop): the screen, computer_use and the browser follow the terminal backend

A user who sandboxes `terminal` (docker/ssh/singularity) had the agent's
screen, cua-driver and Chromium running on the gateway HOST beside that
sandbox: Bot Screen gave a headless host a display, the Xfce panel carries
xfce4-terminal, and `computer_use` could open a shell outside the boundary
the sandbox exists for.

Now the desktop lives where the terminal lives:

- tools/environments/streams.py: one primitive per spawn-per-call backend, the
  local argv prefix that runs its remainder inside the sandbox with stdio open
  (`docker exec -i`, `ssh`, `apptainer exec`). SDK backends (modal, daytona,
  vercel) have none and report so.
- tools/bot_desktop/sandbox_host.py: launcher.sh runs inside the sandbox as
  the image's `pn`; the pane's RFB bytes ride a 12-line python relay over that
  prefix; `cua-driver mcp` is the prefix + the sandbox image's own driver.
- tools/bot_desktop/placement.py + `bot_desktop.placement` (auto|terminal|
  gateway). `auto` follows the backend; a sandbox that cannot host a screen
  REFUSES with the opt-in named instead of silently using the host.
- runtime.start/stop/status/published_env branch on placement; the pane,
  lease, epoch fencing and CLI are unchanged.
- cua_backend: the MCP invocation is the sandbox one when the screen is
  there; the host driver's runtime contract is irrelevant then; check_fn is
  true under a terminal placement without a host binary.
- browser_tool_session: agent-browser invocations are wrapped in the prefix
  with the daemon, socket dir and profile inside the sandbox; screenshots are
  fetched back so MEDIA: paths keep working; recycle closes the sandbox
  daemon.
- web_routers/display.py: the bridge pumps a relay's stdio when the screen is
  in a sandbox, a unix socket otherwise.

Live on docker with nousresearch/hermes-sandbox:desktop: start/observe/RFB
handshake through the dashboard bridge, human takeover fences the agent
(HumanHasControl) and keystrokes reach the sandbox Xvnc, handback restores,
three start/stop rounds leave zero desktop processes; computer_use capture
and list_windows see only the sandbox's Xfce; browser_navigate/snapshot/
vision run with Chromium and agent-browser inside the container and zero
host processes on the bot profile; modal + auto refuses naming the opt-in.

* feat(desktop): Screen pane shows where a sandbox-placed screen runs; Install is host-only

DesktopStatus gains placement ('gateway' | 'terminal:<backend>'). A sandbox
image lacking the stack is a blocker naming hermes-sandbox:desktop, shown in
place of Start; install_command stays None there because the pane's Install
button runs the package manager on the gateway host, the wrong machine, and
display.install refuses for the same reason. The pane header carries
'Screen runs inside the docker sandbox, with the terminal' (4 locales).

* fix(bot_desktop): "is the screen in the sandbox" is a disk check on hot paths, never a config read

Every browser command and CUA spawn asked in_sandbox(), which resolves placement by
loading config, which initializes HERMES_HOME. Under a test's fake home that raised
HomeInitializationError from _run_browser_command; on a real host it read config per
click. Hot paths now ask sandbox_screen_running(): the start marker on disk, written
only by a sandbox start. Policy (in_sandbox) stays for start/install, where config is
the question. display.observe gates on "an RFB endpoint exists" for either placement.

* test(moa): late-accounting sink test asserts the wedged slot's row, not sink order

Under CI load the poll loop can see the interrupt before collecting the fast slot, so the
fast slot also arrives late and first; the test then failed on sink_calls[0]. The
contract is that the wedged slot's real usage reaches the sink.

* chore: retrigger CI (zero-job dispatch failure, auto-heal)

* fix(bot_desktop): a sandbox that died under a live screen fails loudly, never falls to the host

sandbox_screen_running() drops a start marker whose terminal environment is no longer
registered (stale after a process restart). When the environment object outlives its
container, the browser's sandbox wrap now checks the published DISPLAY and raises
"the screen inside the terminal backend's sandbox is gone; start it again" instead of
KeyError('AGENT_BROWSER_PROFILE'). Live: fresh sandbox navigate ok; docker rm -f the
container; next navigate returns that error; zero host Chromium either way.

* feat(terminal): nousresearch/hermes-sandbox:desktop is the default container sandbox

Every container backend (docker, modal, daytona, singularity) now defaults to the
sandbox image with the desktop stack, so Bot Screen, computer_use and the browser
run inside the sandbox for everyone who never chose an image; Python 3.13 / Node 26
match the Hermes image. One constant (DEFAULT_SANDBOX_IMAGE) replaces six copies of
the old literal. Migration 47 moves saved configs still holding the OLD default and
never touches an image the user pinned. Docker reuse recreates a container built
from another image, or the flip would silently never take effect for anyone with a
persisted container (live: old container removed, new one on 3.13 / Node 26 with
Xvnc, cua-driver, agent-browser present).

* chore: retrigger CI (zero-job dispatch failure)

* chore: retrigger CI (zero-job dispatch failure, auto-heal)

* chore: retrigger CI (zero-job dispatch failure, auto-heal)

* chore(config): template stamps v47 and shows the new default sandbox image

The template is what install.sh / docker / doctor --fix seed; a stamp behind
DEFAULT_CONFIG makes every fresh install migrate on first run.

* feat(sandbox): the default image change is a decision, not a surprise

A persisted Docker sandbox on another image is kept when docker_image is unset;
only a written docker_image (an explicit pin) recreates it. The pin verdict
travels as TERMINAL_DOCKER_IMAGE_PINNED through both terminal bridges (process
env and per-profile scope) and the container-config allowlist.

Approval surfaces, all through hermes_cli.sandbox_image_switch: the interactive
CLI asks once at startup (y = pin the new image, n = pin the current one, Enter =
ask later); the Screen pane shows the same choice with Switch / Keep buttons via
display.switchSandboxImage; `hermes config set terminal.docker_image …` is the
same answer from any shell. Gateways and cron never decide: they keep the sandbox
and log the notice.

Migration 47 now unsets a saved image equal to the OLD default instead of
rewriting it to the new one — that value was the template copied, not a pin, and
rewriting it would have made the runtime recreate existing sandboxes unasked.

Modal restores its snapshot and Daytona reuses its labeled sandbox regardless of
the configured image, so existing sandboxes there were already untouched.

* fix(config): both plain defaults that preceded the desktop sandbox image are template copies

main pinned nikolaik/python-nodejs:python3.14-nodejs22 (cd0f97f833) without a migration;
a saved config holding either literal is unset by migration 47, so it follows the default
and existing sandboxes get the keep-or-switch decision instead of a silent recreate.

* ci(docker): build the sandbox image on release/dispatch, not every main push

Leaves docker.yml exactly as on main. The sandbox image carries no Hermes code,
so two 4 GB multi-arch builds per merge bought nothing. sandbox-image.yml builds
and smokes on a PR that edits its own Dockerfile/smoke, and publishes only on a
release or a manual dispatch with publish=true. Stable tag stays :desktop.

* fix(config): keep main's config.py/config_defaults.py edits under the sandbox-image delta

The rebase resolved both files wholesale with the branch side, dropping main's move to
hermes_yaml (the 3.14 runtime venv has no PyYAML) and the 3.14 base pin. This is main's
version plus exactly the branch's own changes: DEFAULT_SANDBOX_IMAGE, the pin verdict in the
env bridge, placement defaults and the v47 stamp.

* test: sandbox-image tests read config.yaml through hermes_yaml (no PyYAML on the 3.14 runtime)

* fix(bot_desktop): read the sandbox marker BOM-tolerantly (windows footgun lint)

* fix(bot_desktop): placement is the authority; sandbox screen survives restarts

Review findings on the sandbox-hosted Bot Screen, each reproduced live first.

Authority. The browser preflight and the CUA invocation keyed off screen
LIVENESS, so `placement: terminal` with the screen not yet up handed the tool an
unchanged host command. `runtime.tool_placement()` is now the one resolver:
terminal placement starts the sandbox screen on demand (no auto_start opt-in
inside the user's own sandbox), refused placement raises its reason, and neither
ever yields the host. placement.resolve() answers a local backend from env alone
so the common case costs no config load on the spawn path.

Restart. sandbox_screen_running() deleted the marker whenever the process-local
terminal registry was empty, i.e. after every gateway restart, while Xvnc kept
running in the container; stop() then returned False and left it. The marker
now records the owning container; liveness comes from `docker inspect` on it,
stop/status re-attach to the recorded owner (even after the placement setting
moved), and only a container that is gone drops the marker.

SSH. remote_argv emitted `bash -c <script>` as three words; OpenSSH joins them
and the remote login shell ran `bash -c export` and the rest itself. The script
travels as one quoted word for ssh (remote_command knows the backend); docker
and apptainer keep argv.

CDP reach. agent-browser inside the sandbox reports the sandbox's loopback;
the Browser Use harness, browser_exec and the vault supervisor connect from the
host and got connection refused. streams.forward_port() proxies a local port
over the exec stream (same relay as the RFB bridge) and the CDP URL is rewritten
to the local end.

pids limit. --pids-limit 256 counts threads; measured on the desktop image the
desktop stack is 44, one Chromium tab 212, the agent's browser with two tabs
488. Past the cap every further docker exec died with "procReady not received".
Default is 2048 with the measurements in the comment.

Replacement. An approved image switch force-removed the old container before
`docker run` tried the new image; a private tag or registry outage left nothing.
The image is inspected/pulled first and the old container kept on failure.

Desktop integration. The sandbox start never passed the dock's browser launcher
(no Browser icon) and the thumbnail needed a host launcher pid + host ImageGrab
(always None). The dock runs the sandbox's Playwright Chromium on the shared
profile; the thumbnail is grabbed inside the sandbox (Pillow baked into the
image). The browser profile moves from /tmp — a 512 MB tmpfs emptied on every
container stop — to the desktop user's home, so logins follow the container.

Pin provenance. A TERMINAL_DOCKER_IMAGE written in a routed profile's .env is a
pin even when it spells the default; the scope compared values before.

* docs(bot-screen): no literal tmp path in the profile-location note

* fix(bot_desktop): docker inspect liveness probe closes stdin (TUI subprocess guard)

* fix(bot_desktop): adopting a screen the sandbox kept records the marker

Live ssh probe: after the host's state was lost while the sandbox kept its
Xvnc, start() took the idempotent early return (display already published)
and never wrote the host marker, so status/thumbnail/stop lost the screen.
Record the adopted display like a fresh launch.

Docs: what an ssh host of your own must carry, and why a Dockerfile ENV is
not enough for a login session (PLAYWRIGHT_BROWSERS_PATH via /etc/environment).

* docker(sandbox-desktop): login sessions find the browser (PLAYWRIGHT_BROWSERS_PATH via /etc/environment)

* docs(bot-screen): what the Apptainer path inherits from the image and what it does not

* chore(config): sandbox-image migration is 47→48 (main took 47 for compression.threshold_tokens)

* chore: retrigger CI (zero-job dispatch failure, auto-heal)
2026-09-28 03:34:07 -07:00
ethernet
2be53ecd7b fix(encoding): read kernel pseudo-files as plain utf-8
utf-8-sig exists to tolerate BOMs that Windows tooling adds to files
users edit. /proc and /sys files are generated by the Linux kernel, never
BOM'd and absent on Windows, so -sig there only muddies the read/write
policy. Switch every literal /proc/ and /sys/ read to utf-8 and teach
the footgun read rule that string literals starting with /proc/ or
/sys/ are exempt (user-edited files keep utf-8-sig).
2026-09-24 11:50:30 -04:00
ethernet
66d54ebf51 Merge remote-tracking branch 'origin/main' into ethie/pm-clean
# Conflicts:
#	.github/workflows/docker.yml
#	Dockerfile
#	apps/desktop/src/app/settings/about-settings.tsx
#	docker/stage2-hook.sh
2026-09-24 02:23:44 -04:00
ethernet
a5721b1de2 fix(bot-desktop): choose PM headed Chromium despite headless override 2026-09-24 01:40:31 -04:00
IAvecilla
686c34d3f6 feat(bot_desktop): ship Bot Screen on hosted images (-desktop tags)
The published image had no Xvnc/Xfce because nothing set the Dockerfile's
HERMES_BOT_DESKTOP argument, and a hosted instance (unprivileged, no sudo,
sealed /opt/hermes) cannot install at run time. The image layer is the only
delivery path.

- docker.yml: variant axis [slim, desktop]. :latest / :main / :v* stay the
  image they are today; :latest-desktop / :main-desktop / :v*-desktop carry
  the packages plus Playwright's headed Chromium. Slim owns the build cache
  scope; one manifest per variant so a desktop publish failure never skips
  slim's :latest.
- Dockerfile / stage2-hook.sh: XDG_RUNTIME_DIR=/tmp/hermes-runtime seeded
  0700 as hermes (containers have no logind; the $HOME/.cache fallback was
  the shared /opt/data volume), refused when foreign-owned; deterministic
  Chromium discovery exporting the headless shell for ordinary browsing.
- bot_desktop: memory gate reads the cgroup working set (usage minus
  inactive_file) so it cannot tighten over uptime and refuse to restart a
  screen idle-stop just stopped; installable() gives three distinct dead-end
  messages instead of a sudo line nobody there can run; env_for_agent
  replaces a headless-shell pin so agent and dock share one Chromium.

Squash of IAvecilla/hermes-agent:bot-desktop-cloud-image (#112381, 13
commits), which GitHub auto-closed when its base branch merged as #108914.
Review fixes from pefontana (cache scope, per-variant merge, red browser
test) are included.

Co-authored-by: pefontana <pefontana@users.noreply.github.com>
2026-09-23 19:54:47 -07:00
ethernet
3f4b8840f1 Merge remote-tracking branch 'origin/main' into ethie/pm-clean
# Conflicts:
#	pyproject.toml
#	tests/fixtures/resolution_allowlist.json
2026-09-23 07:36:31 -04:00
teknium1
59a81c49ca chore(bot-desktop): mark the X11 lock/socket paths for main's no-/tmp-literal guard
Main now rejects literal /tmp paths in favour of the scratch-dir resolver. The
X11 protocol fixes .X<n>-lock and .X11-unix/X<n> under /tmp; these lines detect
or document that location, they do not pick scratch space.
2026-09-19 23:13:10 -07:00
teknium1
56cf995545 docs(bot-screen): lease.py states the fence is tool-level, matching the threat model (#110040) 2026-09-18 21:07:18 -07:00
teknium1
9be0e710d5 fix(bot-screen): the orphan reaper finds a lock-less X server through the socket it binds
_reap_orphaned_server only knew the orphan via /tmp/.X<n>-lock, so a launcher
SIGKILLed while a /tmp cleaner also took the lock (case B of #109941) — or a
failed start() that dropped <sd>/display — left one live Xvnc leaked per
occurrence; the allocator merely moved to the next number. When the lock names
nothing alive, the reaper now scans for the Xvnc whose command line binds this
profile's rfb.sock (the same ownership proof it already required), and skips the
lock unlink when no number is recorded.
2026-09-18 19:20:01 -07:00
teknium1
b428634d63 fix(bot-screen): a watcher's SetDesktopSize is dropped, not forwarded to Xvnc
Framing client message 251 (so the stream no longer dies) is kept, but the
message resizes the bot's framebuffer under a working agent — Xvnc runs
-AcceptSetDesktopSize — so forwarding it from a viewer that does not hold the
lease was a fail-open flip for a server-mutating message. The shipped pane
sets resizeSession=false anyway; SetDesktopSize now sits in _INPUT_TYPES and
only the lease holder's resize reaches the server. Test covers both legs.
2026-09-18 19:20:01 -07:00
teknium1
ada0538199 fix(bot-screen): only a real headed browser command auto-starts the screen; the env builder stays pure
_build_browser_env() is shared by the npx cache warmer (hermes update / doctor
--fix), the lazy Chromium auto-installer, the Lightpanda engine's env and
browser_use_cli. Hooking bot_desktop.auto_start there made every one of those
block up to 15 s spawning Xvnc+Xfce with browser.headed on, against
desktop_env()'s own "never starts anything" contract.

The hook now sits where a headed Chromium is actually spawned for a tool
action, mirroring computer_use dispatch: _spawn_and_collect (the first
agent-browser command forks the daemon; Lightpanda engine excluded), the Chrome
fallback from Lightpanda, and the real-profile Chrome launch. The regression
test asserts both halves: the env builder never starts the screen, the headed
Chromium spawn does, a headless or Lightpanda spawn does not.
2026-09-18 19:20:01 -07:00
teknium1
3c53adbc1e fix(bot-screen): the RFB bridge forwards SetDesktopSize instead of dropping the viewer's stream
launcher.sh starts Xvnc with -AcceptSetDesktopSize so the viewer can fit the
screen to its pane, but rfb_filter.py had no frame for client message type 251
and raised "unknown RFB client message type 251", closing the WebSocket on the
first resize request.

SetDesktopSize (u8 type, pad, u16 width, u16 height, u8 nScreens, pad, then 16
bytes per screen) is framed like the other variable-length client messages and
forwarded intact; it carries no input, so watchers without the lease send it too.
A truncated message waits for the remaining bytes.

Closes #110039
2026-09-18 19:20:01 -07:00
teknium1
56613ebf2b fix(bot-screen): AGENT_BROWSER_PROFILE honours ~ and relative paths instead of silently ignoring them
profile_dir() accepted only an absolute AGENT_BROWSER_PROFILE; `~/pin` and `pin`
fell back to the default user-data-dir while the docs said setting the variable
pins your own. The dock's Browser icon and agent-browser both derive their
identity from profile_dir(), so the silent fallback was at least confusing and,
combined with any other consumer of the raw value, a way to end up on two jars.

`~` is expanded and a relative path is anchored at the profile's HERMES_HOME (the
same root runtime.state_dir() uses), so per-profile pins stay per-profile. The
docstring and the bot-screen docs state the resolution rule.

Contributor PR #112708 (@Rook-CodeVolt) proposed documenting "absolute only";
this takes the behavioural fix instead.

Closes #110029
2026-09-18 19:20:01 -07:00
teknium1
bead012b91 fix(bot-screen): computer-use screen status redacts the lease holder's viewer id like every RPC surface
The CLI printed lease.get().as_dict() (--json) and "human (<viewer_id>)" while
display.status, the display.lease broadcast and both lease mutations replaced the
id with its 12-hex sha256 prefix. The viewer id is a capability (whoever presents
it co-drives or releases the lease), and the CLI leaked the one string the rest of
the feature deliberately hides.

The redaction now has one owner, tools.bot_desktop.lease.public_view(); the RPC
handlers, the lease watcher and the CLI all call it, so there is no second hash
implementation to drift. The human-readable line shows "human (viewer <hash>)".

Closes #110006
2026-09-18 19:20:01 -07:00
teknium1
dea71ed925 fix(bot-screen): a live X server whose lock file was reaped no longer gets its display re-allocated
_display_in_use() keyed only on /tmp/.X<n>-lock naming a live pid. A /tmp reaper
removes that lock while Xvnc keeps running; the allocator then handed the number
out, the new launcher died with "server already running", and because the
profile's recorded `display` file was never cleared, _pick_display() returned the
same number on every retry — the profile wedged until someone killed Xvnc by hand.

- _x_socket_bound(): parse /proc/net/unix for a bound (@)/tmp/.X11-unix/X<n>
  socket, which the kernel holds for the server's whole life, and OR it into
  _display_in_use(). Module-level _X_UNIX_TABLE so tests point it at a fixture.
- start(): a failed launch (launcher exit / readiness timeout) unlinks the
  recorded `display` so the next attempt allocates afresh.

Live-verified with a real Xvnc :77: after `rm /tmp/.X77-lock` the base module
reported _display_in_use(77) False while Xvnc was alive; this head reports True,
and False again once Xvnc exits.

Closes #109941
2026-09-18 19:20:01 -07:00
teknium1
36e9ddeff2 fix(bot-desktop): re-admit secret writes after a prompt; recover pre-marker dock launchers
- browser_vault_enter_code blocks on the user's code INSIDE the handler-level
  fence, so a takeover during that (human-length) wait was only detected
  afterwards by the epoch check, which discards the result: the code had
  already been written into the page the human was typing into. The
  supervisor write path now re-admits against the lease immediately before
  evaluating; a human lease refuses the write itself.
- Profiles seeded before `.hermes-browser-launcher` existed never got their
  Browser Exec= rewritten after `hermes profile rename`. The launcher recovers
  the marker from its own Name=Browser entry (bash builtins only; the seed
  runs on a minimal PATH).
- Threat model: Chromium's DevTools port is reachable by any local user, not
  only the gateway's OS user; documented (a Chromium property, no per-UID
  switch exists).

Reported by @thelonewander3r (round 6, re-surfaced at e4f591d1b0).
2026-09-18 14:06:15 -07:00
teknium1
e8473ae5e4 fix(bot-desktop): cap the dock browser's disk cache
The per-profile browser profile is persistent on purpose (logins survive
handoffs); its HTTP cache is not worth a gateway's disk. Uncapped, Chromium
lets it grow for months toward a hosted instance's 6 GB. 256 MB.
2026-09-16 17:22:14 -07:00
teknium1
71971e9205 feat(bot-desktop): memory gate and idle auto-stop for small hosts
Hosted instances come in 4 GB and 8 GB packages; a headed desktop plus the
browser a human opens during a takeover costs 1.1-1.5 GB on top of the
gateway (measured in the official image: gateway 304 MiB, +Xvnc/Xfce 520,
+Chromium on one page 1,073). Left unguarded, the loser of that squeeze is
Chromium mid-login or the gateway itself.

- runtime.start() refuses while the host, or its cgroup when tighter, has
  less than bot_desktop.min_free_memory_mb free (default 1536); status()
  carries `blocker` plus memory_available_mb/memory_limit_mb so the pane
  shows the reason in place of Start and the CLI prints it. A running
  screen is never reported blocked: the gate guards the allocation.
- A screen nobody used for bot_desktop.idle_stop_minutes (default 30) is
  stopped by the gateway's display watcher and comes back on the next
  use. "Use" = a computer_use dispatch, a browser/cua spawn onto the
  screen, an attached viewer (stamped from the RFB bridge at most once a
  minute), or start itself; a human holding the lease is never timed out.

Both knobs are 0-disableable; the contract gains the three status fields.
2026-09-16 17:22:14 -07:00
teknium1
1b121d1b0b fix(bot-screen): install single-flight holds across processes
The gateway (Install card) and the CLI (`screen install`) are separate processes; the in-process
set let both drive dpkg for one profile at once. The slot is now also a non-blocking flock on
<state_dir>/install.lock held for the life of the install.
2026-09-14 17:35:23 -07:00
teknium1
855928a9bd fix(bot-screen): hold the host-wide display-allocation lock only until Xvnc claims the number
start() held _ALLOC_LOCK across the whole Xfce bring-up (up to wait_seconds), serializing every
profile's start behind one desktop launch and letting a hung launcher block them all. The lock
exists for the pick -> /tmp/.X<n>-lock window; it is dropped the moment the X lock appears.
2026-09-14 17:35:22 -07:00
teknium1
4ffa767127 fix(bot-screen): no-op lease transitions do not bump the epoch
release() on an agent-held lease and a same-viewer re-acquire rewrote the record and bumped the
epoch, so an admitted in-flight agent action looked overtaken and was voided by a double-clicked
Hand back or a stray CLI stop; the re-acquire also reset `since` and wiped the on-screen reason.
2026-09-14 17:35:21 -07:00
teknium1
069465f3b5 fix(bot-screen): dock Browser follows the agent-browser sandbox policy in containers too
dock_argv added the sandbox-bypass flags only for root, while agent-browser's policy also covers Docker
and AppArmor-userns hosts. In the official image (gateway as uid 10000 inside Docker) the agent's own
Chromium ran but the dock icon died with 'No usable sandbox!'. Same binary, same profile, same
container: one policy (_needs_chromium_sandbox_bypass) decides for both.
2026-09-13 20:15:03 -07:00
teknium1
25b5a4884c fix(bot-screen): a headless-shell AGENT_BROWSER_EXECUTABLE_PATH is not a headed browser
The official Docker image ships only Playwright's chrome-headless-shell and its boot hook exports that
path as AGENT_BROWSER_EXECUTABLE_PATH. executable() trusted the override, so in the Cloud shape
display.status.browser named a windowless binary and the dock's Browser icon pointed at something that
can never open a window. A headless shell is skipped; a real headed Chromium elsewhere still wins.
2026-09-13 20:11:34 -07:00
teknium1
807de3a43f fix(bot-screen): reap the launcher we kill so a later gateway's stop leaves no zombie
The launcher is Popen'd by the gateway that started it; a gateway started later holds no Popen for it,
so after stop() the dead leader sat as a zombie in our table and killpg(pgid, 0) kept reporting the
group alive. waitpid(WNOHANG) on the leader during and after the kill sequence.
2026-09-13 15:06:40 -07:00
teknium1
8b0774550a fix(bot-screen): process-group cleanup waits for the whole group, not the leader
_kill_group_then_wait (runtime) and _kill_group (install) returned once the leader had exited, so a
TERM-ignoring descendant in the same group (a stuck dpkg, a display client) survived the KILL round
with the display or the dpkg lock. Both now poll killpg(pgid, 0) until nobody is left. The installer
also kills the group when the drain raises (a failing output sink), since the slot is released either way.
2026-09-13 14:49:25 -07:00
teknium1
745f88ae49 fix(bot-screen): refusing a bare release/stop under a human is one lease transition
display.stop and a viewer-less display.lease.release read human_holds() and then released in a second
step; a takeover landing in between was acknowledged to the human and silently revoked. lease.release
gains unless_human, decided under the file lock inside the same transition; the handlers read the
returned holder instead of pre-checking.
2026-09-13 14:47:29 -07:00
teknium1
6c406fd53c fix(bot-screen): dock Browser entry follows the profile path after a rename
The panel layout is seeded once on purpose (a human may have rearranged it), but the Browser launcher's
Exec= line bound the bot's user-data-dir by absolute path, so after 'hermes profile rename' the dock
opened a browser with an empty jar while agent-browser used the renamed one. The launcher now records
which dock slot is the Browser and rewrites only that Exec= line on every start; the layout is untouched.
2026-09-13 14:45:28 -07:00
teknium1
88bd29213b refactor(bot-screen): drop the agent-side handoff actions; takeover is always human-initiated
`computer_use` carried two Bot Screen actions, `request_handoff` and `wait_for_human`, that let
the model ask for the screen and then block a tool call until the human handed it back. Both only
make sense when a person is guaranteed to be watching the Desktop pane; from Telegram, the CLI or
a cron worker the request lands nowhere and the wait burns minutes before returning. The blocking
wait also fought the sequential tool deadline (600 s default vs 420 s), so the model saw a timeout
before the wait returned while the thread stayed parked.

The agent now simply says what it needs in its reply and ends the turn; the user takes over from
the pane, does the step, hands back and tells it to continue. Take over / hand back and every fence
(actions refused with human_has_control, epoch-voided results, suppressed thumbnails) are
unchanged. Removes the handoff module, the schema entries and their host-conditional rewriter,
the lease's pending_handoff field and wait helpers, and the "Bot needs you" badge in the pane.
2026-09-13 09:30:43 -07:00
teknium1
f1df96b629 Merge branch 'bs5-c' into hermes/hermes-b802e898
# Conflicts:
#	tests/tools/test_bot_desktop_install.py
2026-09-13 06:07:11 -07:00
teknium1
36fbb370e6 Merge branch 'bs5-a' into hermes/hermes-b802e898 2026-09-13 06:06:56 -07:00
teknium1
7fd5f59ba2 fix(bot-screen): dock Browser entry quotes its Exec= line, so spaced paths work
launcher.sh received the dock browser as one shell line and recovered the
executable with `${3%% *}`: a Chromium under '/opt/Google Chrome/' or a
profile dir under a HERMES_HOME with a space split at the first blank, the
existence check failed or Exec= became garbage, and the dock had no working
Browser icon.

Python now hands the launcher the bare executable (HERMES_BD_BROWSER_EXEC, for
the `command -v` check) and a ready-made Exec= line
(HERMES_BD_BROWSER_EXEC_LINE) built by `browser.dock_exec_line`: each argument
double-quoted, reserved characters backslash-escaped inside the quotes and the
backslashes string-escaped once more, per the Desktop Entry spec. `dock_argv`
is the single source of the dock's arguments (incl. the root sandbox flags).

Test: tests/tools/test_bot_desktop_browser.py — a spaced executable and a
spaced, quote-bearing profile dir produce a correctly quoted Exec= line
(AttributeError on the previous commit); the launcher seed test keeps running
the real script (`bash -n` clean).
2026-09-13 06:04:43 -07:00
teknium1
dff8929194 fix(bot-screen): dock Browser picks a browser that can start, and status says when there is none
`browser.executable()` always preferred Playwright's bundled Chromium. Its
`chrome_sandbox` is not setuid, so for a non-root user on Ubuntu 23.10+
(`kernel.apparmor_restrict_unprivileged_userns=1`) the dock's Browser icon died
with `FATAL: No usable sandbox!` even when a distro chromium with the sandbox
helper was installed. And when the only bundle is chromium_headless_shell (the
official image) `executable()` is None and launcher.sh silently skipped the
dock entry — nothing anywhere said "no headed browser".

Now: non-root under the userns restriction tries a system chrome/chromium first
and falls back to the Playwright build (no --no-sandbox for non-root, by
ruling: a loud failure beats a sandbox-less browser). `DesktopStatus.browser`
carries the resolved executable (None = no headed browser) through `as_dict()`
so the pane and `hermes computer-use screen status --json` can show it.

The root sandbox-bypass flags are ONE list, `browser_tool_session.
CHROMIUM_SANDBOX_BYPASS_ARGS`: agent-browser gets it via AGENT_BROWSER_ARGS and
the dock command appends the same flags as root, so the human's click and the
agent's launch start the same binary the same way. The sysctl reader is shared
as `apparmor_restricts_unprivileged_userns()`.

Tests: tests/tools/test_bot_desktop_browser.py — restricted non-root prefers
the system chromium and keeps Playwright's when alone (AttributeError on
bc36ddb5f9); root dock args are a superset of the agent's (dock lacked
--no-sandbox); status exposes browser / None (field missing).
2026-09-13 06:02:35 -07:00
teknium1
a047156df7 fix(bot-screen): hygiene — private alloc lock, private lease files, cookie off argv, real Fedora packages
Four small exposures, none a same-UID boundary (which the design does not claim), all
about other local users and wrong install hints:

- The host-wide display-allocation lock sat at a predictable name in world-writable
  /tmp, where any local user could pre-create or squat it. It now lives under
  XDG_RUNTIME_DIR (else ~/.cache), created 0700; still host-wide, outside every profile
  home, because all profiles allocate from one band.
- lease.py hand-rolled mkdir + plain writes, so a takeover recorded before start() ever
  ran left bot-desktop/ 0755 and lease.json / lease.lock 0644 under the umask — who
  holds the screen and the lock the RFB bridge serialises on, readable by everyone. It
  now uses secure_parent_dir and creates every file 0600 via an opener; the fcntl-less
  (Windows) fallback is untouched.
- launcher.sh passed the X cookie on xauth's argv, visible in ps to other local UIDs.
  The cookie is now fed on stdin through `xauth source -`.
- The Fedora map named tigervnc-server-minimal (only a Provides of tigervnc-x11-server,
  which actually ships Xvnc) and dbus-x11 for dbus-run-session (dbus-daemon owns it;
  dbus-x11 ships dbus-launch). Both BINARY_PACKAGES and PACKAGES are corrected together.
2026-09-13 05:59:54 -07:00
teknium1
5b1089a19c fix(bot-screen): install works as root and names the host command when sudo is absent
Two dead ends on hosts without a sudo binary. As root (the official Docker
image is uid 0, no sudo): `runtime.install_command()` hardcoded `sudo <pm>`,
`_run` asserted argv[0] == "sudo", `sudo -n true` failed, so the password card
was raised for a user who already IS root and the install was cancelled. As an
unprivileged user in a minimal container the same card was raised although no
password could ever satisfy it.

`install_command()` now omits `sudo` when euid is 0 (one builder, so the pane's
shown command and the executed command stay the same line); `_run` runs the
package manager directly when the command carries no sudo, and when it does but
`shutil.which("sudo")` is None it streams the exact command to run on the host
as root and returns `install.NO_SUDO` instead of asking. `hermes computer-use
screen install` prints that command.

Tests: tests/tools/test_bot_desktop_install.py — euid 0: ask_password is never
called and argv[0] is the package manager; euid 1000 + no sudo: NO_SUDO, no
Popen, the apt-get line is in the stream (both raised the password card on
bc36ddb5f9).
2026-09-13 05:58:05 -07:00
teknium1
717e4c2fe7 fix(bot-screen): Xvnc cut-text cap matches the bridge, NOPASSWD install covered, bridge design notes
- launcher.sh passes -MaxCutText 262144 so Xvnc's own cut-text bound equals the
  bridge filter's _MAX_CUT_TEXT (rfb_filter.py); before, only the bridge capped
  and the two could drift apart silently. Comments on both sides name each
  other; the existing launcher argv test asserts the flag equals the constant.
- Install: a host with passwordless sudo must run the package command without
  popping the masked password card (it would block the install on an answer
  nobody needs to give). Covered with a fake Popen; sabotaging the
  _sudo_nopasswd() branch turns the test red.
- web_routers/display.py docstring records two deliberate rulings that read
  like defects: the display ticket rides in the query string because noVNC's
  Websock cannot negotiate subprotocols or headers and the ticket is
  single-use / 30 s; _LEASE_REFRESH_S (250 ms) bounds how long another
  process's takeover can go unseen by the sync input gate.
2026-09-13 05:55:19 -07:00
teknium1
004b43f15c fix(bot-screen): install timeout releases the profile slot even when a root child survives
The install runs `sudo <pm> ...` in its own session and drained stdout with a
blocking `for line in proc.stdout`; the timeout only `killpg(SIGKILL)`ed the
group. From an unprivileged Hermes that signal reaches the sudo leader but not
the root-owned apt/dnf child, which keeps the pipe's write end open: the drain
never saw EOF, `install_packages` never returned, and the per-profile install
slot stayed taken until the gateway restarted (every later Install click:
"an install is already running").

Now the drain is readiness-polled against the deadline, so it ends on time
regardless of what survived; the group gets SIGTERM (dpkg can finish its
transaction) then SIGKILL after a grace; `install timed out` is streamed to the
pane; the leader is reaped best effort and the slot is released by the
existing finally.

Test: tests/tools/test_bot_desktop_install.py — a stand-in leader whose
grandchild sits in its own session holding our stdout; install_packages must
return within 3 s, report the timeout, and leave the slot claimable (hung
3.0 s on bc36ddb5f9).
2026-09-13 05:55:06 -07:00
teknium1
85d0b15325 fix(bot-screen): a start() that times out takes its launcher down instead of leaving it to publish later
_spawn_and_wait raised on the readiness deadline and walked away from the launcher it
had just spawned. Xvnc and Xfce kept coming up; a moment later the launcher published
DISPLAY and rfb.sock, and a screen whose start() had reported failure was now "running"
under a pid the caller never learned about. A retry then saw it as already up and returned
it, so the failure message described a state that no longer existed.

On timeout the launch's process group (the launcher is its own session leader, so the
group is exactly this launch) gets SIGTERM, then SIGKILL after a grace period, the child
is reaped, and only that launch's launcher.pid / env / rfb.sock are removed before the
error propagates.
2026-09-13 05:53:59 -07:00
teknium1
809169b7d0 fix(bot-screen): reap the X server a dead launcher leaves behind instead of starting a second one
status() and stop() keyed only on the launcher pid. When the launcher was SIGKILLed
(OOM, a stray kill, a crashed supervisor) its Xvnc kept running in the launcher's
session, holding the display number and rfb.sock, while status() reported stopped.
The next start() then allocated a fresh display and spawned a second server whose
launcher unlinked and re-bound the same rfb.sock path — two X servers, one socket,
and the orphan leaked forever because stop() never reached it.

The X lock of the recorded display names that server. When no live launcher exists,
start() and stop() now check it: a process in the dead launcher's process group, or
an Xvnc whose command line binds THIS profile's rfb.sock, is ours and is killed
(SIGTERM, then SIGKILL) before the stale state is dropped and a new launch proceeds.
A server that merely reused our display number is never touched. _pid_alive also
stops treating a zombie as alive: the gateway reaps a killed launcher lazily, and the
zombie made status() claim a running screen whose server nobody owned.
2026-09-13 05:53:09 -07:00
teknium1
21d3c77300 fix(bot-screen): quiet xkbcomp keysym noise, log an ignored release, hide Chrome-for-Testing infobars
Fourth review round (@dadhalfdev): launcher.log opened with dozens of "Could not resolve keysym
XF86..." lines that read like a failure and buried real errors; a lease.release() by a non-holder
was silently ignored (correct, but invisible to a caller that drops the return value); the dock
browser showed the "Chrome for Testing" and unsupported-flag infobars in the human's takeover view.
2026-09-12 19:00:10 -07:00