Commit Graph

5051 Commits

Author SHA1 Message Date
Teknium
8819d88308 test(mcp): a same-named stdio server gets its own child per profile
With the served HERMES_HOME pinned into the stdio child env, two profiles
running the same server no longer share one child: the shared child ran in
the first profile's home, which is the bug this PR fixes. Approved by
Teknium (per-profile children over cross-profile reuse).
2026-11-02 13:31:06 -08:00
dev-agent
439a42e6e2 test(mcp): lock stdio child env to the active profile's HERMES_HOME
Red on base: `_build_safe_env(None)` raises KeyError('HERMES_HOME') under a served
profile scope. Green with the pin. Also asserts an explicit server env.HERMES_HOME wins.
2026-11-02 13:31:06 -08:00
Teknium
e1f0ccb1e1 test(delegation): join the worker before asserting the dispatch context is released
A finished record (active_count()==0) only proves bookkeeping ran; the
worker thread can still be inside the Contexts it copied. Shut down the
executor with wait=True before gc.collect so the assertion observes real
teardown, and drop the polling sleep (HX013).
2026-11-01 22:05:14 -08:00
Teknium
e48531be29 fix(delegation): completed async records stop pinning the dispatching turn's Context
A finished background delegation stays in tools.async_delegation._records (up to 50
completed records), and each kept the contextvars.Context copied at dispatch. That
Context is only needed to force-finalize a stalled ACTIVE record, but while retained it
pins the dispatching turn's bindings: a closure whose cell holds the parent AIAgent with
its conversation, interrupt Events and callbacks, after the session closed and the agent
cache evicted it. Drop it when the record turns terminal, alongside the interrupt/progress
closures _finalize already clears.
2026-11-01 22:05:14 -08:00
Teknium
a7b8d34f55 test(docker): join teardown workers of dropped envs before the fakes unwind
tests/tools/test_docker_ownership_handback.py lets several DockerEnvironment
objects go out of scope (the reclaim scenarios' env/retry, the persist
scenarios' reattached env). BaseEnvironment.__del__ calls cleanup(), which
starts a daemon "hermes-cleanup-<cid>" worker, and nothing joined it. The
worker then ran after monkeypatch had unwound: against the real docker CLI
(the env captured /usr/bin/docker), the real sandbox dir and the home-I/O
guard. On CI one of them was still printing its traceback when the file's
interpreter exited with its stderr pipe busy, which aborts Python with
"_enter_buffered_busy: could not acquire lock for <stderr> at interpreter
shutdown" (SIGABRT, file reported CRASHED with 26 passed).

An autouse fixture now collects dropped envs and asserts every teardown
worker finished (DockerEnvironment.wait_for_all_teardowns) before
monkeypatch unwinds, so each worker runs entirely under its own test's
fakes. Production is unchanged: terminal_tool's atexit drain already joins
these workers; this test never imports terminal_tool.
2026-11-01 21:13:04 -08:00
Teknium
b847741865 fix(delegation): give each lost-copy re-offer its own lease and count held copies as live
Review of #147748 (should-fix 1 and 2) and Greptile "New waits violate test rules":

- A consumer that keeps handing the copy back was re-offered on every 30 s sweep tick with a
  WARNING each time, because a re-offer touches no ledger column. The sweep now remembers when it
  last re-offered each row (in process memory, no schema change) and leaves it alone for a whole
  _CLAIM_LEASE_S; only the first re-offer of a row warns, later ones log at DEBUG.
- A copy a TUI poller holds between take_ready and its requeue was invisible to the queue
  snapshot, so another session's sweep added a duplicate. New in-process registry
  async_delegation.mark_copy_held / unmark_copy_held (keyed by delegation id, counted);
  take_ready marks under the queue's mutex and release unmarks after any requeue, and the sweep
  reads the held ids inside each queue's mutex, so a moving copy is always seen queued or held.
- The new tests wait with tests.waiting.wait_until instead of sleep loops.
2026-11-01 21:12:28 -08:00
Teknium
8a10a3cbef fix(delegation): re-offer a pending completion only when its copy is provably lost
Builds on the salvaged #140721 sweep change. Dropping the owner-liveness
skip outright would hand a second copy of every row owned by another live
process (whose queue this one cannot see) and duplicate a copy that is
still queued under the watcher's refusal backoff.

The sweep now re-offers a row whose owner is alive, or that this process
already offered, only when:
- the owner is THIS process (or this process made the offer);
- no final-result copy sits in the target queue or the producers'
  completion_queue (read under each queue's mutex); and
- nobody claimed, deferred or released the row for a whole claim lease,
  the same span after which a silent claim counts as abandoned.

Dead-owner rows keep the 60 s orphan rule. An offered copy discarded
without return_completion_offer no longer pins the row until the next
restart. claim_completion_delivery stays the atomic gate. The main test
that pins "a live owner's queued row is never swept" is restored
unchanged and still passes.

Fixes #140718, #144563.

Co-authored-by: NyllRE <nyll.redeast@gmail.com>
2026-11-01 21:12:28 -08:00
KoNit-K
6a065c1a58 fix: reoffer stale live-owner delegation completions 2026-11-01 21:12:28 -08:00
Teknium
557254faa2 fix(skills): lock guard resolves variables and relative inline code, lets reads through
- Shell variables in write targets expand from the environment plus `p=...` / `export p=...`
  assignments earlier in the command.
- Inline interpreter code that writes is refused when its working directory is inside a
  locked skill (relative paths), not only when it names the skill.
- A recursive delete/move of a directory holding the lock record is refused even when the only
  locked skill lives in skills.external_dirs.
- Reads are no longer refused: inline code counts as writing only for write-mode open(),
  write/delete/rename/copy calls and shell write forms; `find -exec` is refused only when the
  executed command itself writes.
- locked_skill_dirs resolves every lock in one walk of the skills dirs instead of one
  _find_skill search per locked name.
2026-11-01 15:47:21 -08:00
Teknium
a639ed0ae4 fix(skills): close terminal lock bypasses; curator honours locks by display name
- Newlines separate commands (shlex read them as whitespace, so a second-line `sed -i` hid
  behind an `echo`).
- Wrapper options that take a value (`sudo -u root`, `xargs -n 1`) are skipped, reusing
  self_repo_guard's wrapper table.
- `( ... )` subshells restore the working directory when they close.
- `cp/mv/install/ln -t DIR` and `--target-directory=DIR` are the write destination.
- Recursive copies (`cp -r`, rsync) and archive extraction into a directory above a locked skill,
  inside a skills root, are refused: they can merge into it.
- Globs expand against the filesystem like the shell does, so `sed -i ... ops/*/SKILL.md` is
  judged by what it matches.
- The curator's auto-archive check resolves rows (frontmatter names) to the directory-keyed lock
  via tools/skill_lock.is_locked_skill.
2026-11-01 15:47:21 -08:00
Teknium
91c51e04f4 feat(skills): a locked skill can't be changed by the agent through any write path
Builds on the per-skill lock record (`hermes curator lock`): the lock now holds against the
agent everywhere, not only the background passes.

- skill_manage refuses every mutating action on a locked skill for every origin (normal turns,
  cron, subagents, review fork, curator); a corrupt sidecar still fails closed only for the
  autonomous passes so one broken file can't freeze every skill edit.
- write_file / patch hard-refuse any path inside a locked skill's directory and the lock
  record (skills/.usage.json) while any skill is locked (tools/skill_lock.path_refusal, wired
  into _check_sensitive_path).
- terminal refuses, before approvals and under --yolo, commands that write into a locked skill:
  redirections/tee, cp/mv/rm/touch/mkdir/chmod, sed/perl -i, git changes in its tree, archive
  extraction into it, inline python/bash code naming it, including after a cd into it; and the
  agent running `hermes curator unlock`. Reads and running the skill's own scripts still work.
- The curator never auto-archives a locked skill.
- Docs: "Locking a skill" rewritten for the new contract.
2026-11-01 15:47:21 -08:00
Davis Ford
b694c7d907 feat(skills): per-skill content lock against autonomous writes (#25083)
`hermes curator lock <skill>` records `locked: true` beside `pinned` in the
active profile's skills/.usage.json. While locked, skill_manage refuses
patch/edit/write_file/remove_file/delete on that skill when the write origin
is the background review fork or the curator consolidation pass, for the
whole skill directory and on both the single-op and the batch path. The
skill stays readable, listed and auto-loadable; foreground user-directed
writes are not gated; unlocked siblings keep learning.

- tools/skill_usage.py: set_locked / is_locked (strict: a corrupt sidecar
  raises instead of reading as unlocked) / locked_skill_names
- tools/skill_manager_guards.py: _locked_guard, wired into
  _background_review_preflight ahead of the delete guard; fails closed on
  an unreadable sidecar instead of silently relaxing the lock
- hermes_cli/curator.py: `curator lock|unlock`, locked list in `status`
- agent/background_review.py: one prompt sentence so the fork does not
  retry or recreate a refused locked skill
- docs: curator.md "Locking a skill's content" section, line 47 corrected
  (pins block deletion only, #141673), skills.md pointer

Related: #140332, #142933, #89961
2026-11-01 15:47:21 -08:00
kshitijk4poor
09d2e686f9 fix(browser): raw CDP metadata check reads the host after userinfo
`)`, `]`, `<` and `>` are legal in a URL's userinfo, but the URL literal
scan stopped at them, so `http://1.1.1.1)@169.254.169.254/` was read as
`http://1.1.1.1` while a browser fetches the metadata host; the same held
for scheme-relative `//x]@169.254.169.254/` and for a raw `url` param that
urlsplit cannot parse. When a literal stops inside its authority and an `@`
follows before the authority ends (`/ ? # \`, quote, whitespace),
url_literals now also returns the host after the last `@`, next to the
literal as cut, so an unquoted `href=` followed by a mail address keeps its
own check. Both the metadata floor and the guard-on private check see it.

Root cause: the literal regex ends a URL at these delimiters even inside
the authority. Not a regression: main's scan stops at the same characters.
browser_exec keeps its own literal regex, with the same gap, for a
separate change.
2026-10-31 14:33:38 +05:30
kshitijk4poor
e20007e4e7 fix(browser): raw CDP URL scan reads bracketed IPv6 and scheme-relative hosts
The URL literal scan behind raw CDP's private guard and metadata floor
now reads a bracketed host such as https://[2606:4700:4700::1111]/ as one
literal, so a public IPv6 URL is no longer refused on guarded backends
and an IPv4-mapped metadata address (http://[::ffff:a9fe:a9fe]/) is
refused with the guard off. The metadata floor also reads scheme-relative
//host, ///host and \\host literals, which browsers load with the page's
scheme. They are judged by their literal host without a DNS lookup,
decimal, hex and octal IPv4 spellings (//2852039166/, //0xa9fea9fe/)
included, so a //TODO comment costs no resolver call. A // comment, an
a//b path or a // inside another URL's path or query is not taken for a
second target, and the private guard keeps screening http(s) literals
only.
A scheme-relative literal carrying a control character
(//169.254.169.254 followed by U+0001, which a browser strips) is
refused like its http(s) spelling.

Root cause: the literal regex stopped at the first ], cutting a
bracketed host in two (the head failed to parse, the tail was never
checked), and it only knew http(s):// prefixes.

The public IPv6 refusal is a regression from f4aa77a467 (#146100,
@teknium1, 2026-10-28); the mapped-address and scheme-relative gaps
are older bugs.
2026-10-31 14:33:38 +05:30
kshitijk4poor
1c11a23f0f fix(browser): raw CDP blocklist, interception and cookie calls work on guarded backends
Network.setBlockedURLs, Network.setRequestInterception, Fetch.enable,
Page.handleJavaScriptDialog and the cookie setters no longer have their
URL params screened as fetch targets, so request blocking and
interception work again on cloud browsers, /browser connect endpoints and
container terminals, and blocking the metadata address itself is allowed.
These calls only match, label or scope URLs; none of them makes the
browser fetch one. Each fetchable URL is also checked once instead of
twice (a url value was extracted whole and again as a literal).

Root cause: the guard-on scan of unlisted methods resolved every http(s)
literal in every string param, so wildcard patterns failed DNS and
loopback or metadata patterns read as private targets.

Regression from f4aa77a467 (#146100, @teknium1, 2026-10-28).
2026-10-31 14:33:38 +05:30
kshitijk4poor
adecc40244 test(terminal): build the profile-home fixtures under the isolated native root
The new container-key tests set HOME and used <tmp>/.hermes as the Hermes
root. On Windows the native root comes from LOCALAPPDATA and is named
`hermes`, so nested and loose homes would sit outside it and the lookup
would answer "default" instead of "custom" (Greptile, #147090). Build the
homes under the per-test native root conftest already isolates
(`hermes_constants._get_platform_default_hermes_home()`), which is right on
every OS, and stop touching HOME.
2026-10-31 11:33:57 +05:30
kshitijk4poor
e10765f7c3 fix(terminal): key a named profile's unnamed chats by its name too
A gateway launched as a named profile (`hermes -p work gateway`) stamps
no profile on its own chats, so their persistent-Docker key fell back to
"default", while the same profile's Desktop sessions (which name it) used
`profile:work`. The previous commit moved session-less cron and kanban
work onto `profile:work`, which in that setup would have split it from
the chats it used to share "default" with.

A session naming no profile now takes the home's profile name, so
chats, Desktop sessions, cron and kanban workers of a named profile all
land on one container. The name comes from one helper,
`terminal_tool_config.home_profile_name`: the same lookup the TUI stamps
on its sessions and Docker labels its containers with, now shared by the
container key, the container label and the file panel's sandbox names
(whose candidates are unchanged), and memoized per home because it runs
on every key resolution. The default profile and a home outside the
Hermes root stay "default"; a home inside the root that is not a
`profiles/<name>` home (nested, dot-named) gets `profile:custom` for all
of them, which its Desktop sessions already used. Peter's tests now run
against real profile homes instead of a stubbed name lookup.

Profile-routed children were already keyed by the bound profile and are
unchanged. The docs note where the old `default` sandbox is.
2026-10-31 11:33:57 +05:30
Peter Taras
149e3f5539 fix(terminal): reuse the profile container for sessionless workers
A named-profile process with no session key collapsed onto "default"
and missed that profile's sandbox. Dispatcher workers set HERMES_HOME
and clear the session vars, so they are not a routed-home override.

Persistent Docker now reuses profile:<name> for that process. The
default profile, a non-persistent backend, and a home that is not a
named profile stay on "default".
2026-10-31 11:33:57 +05:30
Ben Barclay
e924f75176 fix(redact): the log formatter reads no config
RedactingFormatter resolved a routed profile's redaction policy per
record from config, under the logging handler's lock. It now reads only
in-memory state: the live secret scope, and the policy recorded when that
profile's .env or config is loaded, or when log routing is set up for it
(resolve_profile_policy). Unknown means redact, the secure default.

This removes load_config_readonly_nowait() and the no-boot read scope.
2026-10-30 11:13:02 -04:00
kshitijk4poor
4f45619643 fix(projects): keep an unmounted Docker chat's project
With the cwd mount off, a Desktop session now registers an empty cwd
(cwd_source "process") so its host folder never becomes the container's
working directory. project_tools reads that same override as "the chat's
workspace", so project_list reported active_id None instead of the
folder's project, and did not fall back to the profile pointer either.

Keep the session's folder in the override as host_workspace (only when
it was the session's own) and let project_tools read it. The terminal
and file layers read only cwd, so their behaviour is unchanged.
2026-10-30 15:45:49 +05:30
Gille
7750d1a1d2 fix(docker): keep unmounted Desktop sessions on the profile sandbox
With persistent Docker and host-workspace mounting disabled, a Desktop
session could select `default:ws:<digest>` while CLI kept using
`default`. The two sessions then saw different persistent workspace
directories, despite belonging to the same profile.

`_workspace_container_key` now checks the scope-aware mounting flag
before deriving a workspace key. Unmounted sessions retain their original
profile sandbox; host-mounted sessions retain separate containers for
different workspaces.

Desktop cwd registration also keeps the host workspace out of an
unmounted Docker execution cwd, using the owning profile's terminal
policy: after selecting the original container, Desktop still passed its
host path to `cd` inside that container. The configured container cwd
and later in-container `cd` remain authoritative. This fixes selection
and execution without moving, copying, or deleting existing sandbox data.
2026-10-30 15:45:49 +05:30
Jeffrey Quesnelle
fcc26fbd9f Merge pull request #145222 from NousResearch/fix/terminal-scope-managed-overlay
fix(terminal): per-turn terminal scope applies managed scope last
2026-10-29 10:18:17 -04:00
kshitijk4poor
d404615296 fix(bot-desktop): the idle stop of an abandoned human lease releases that lease
Once a human lease lapses (four windows, ten minutes at least) the screen is stopped, but lease.json still
named the human, so computer_use and the browser refused with "a human has control" before anything
started the next screen: the docs' "the next use starts it again" did not hold. After that stop the
lease is released, but only the generation judged abandoned: lease.release() takes the epoch read before
the stop and does nothing if the lease changed since, so a takeover made while the screen was stopping
(another viewer, or the same viewer handing back and taking over again) is kept, and an abandoned lease
with no viewer id never turns into a bare release.
2026-10-29 19:03:57 +05:30
kshitijk4poor
dacca6272f fix(bot-desktop): a killed sleep or check no longer ends the screen's self-stop
The watch loop inherited the launcher's set -e. A sleep killed from outside (a stray pkill, the OOM
killer) made wait fail and ended the loop silently, so that screen never stopped itself again. The
loop now runs with set +e: a killed sleep goes straight to the check, a failed check retries in 300 s.
A sleep that fails on its own (it cannot sleep at all) still ends the loop rather than spinning the check.
2026-10-29 19:03:57 +05:30
kshitijk4poor
8f40eac438 fix(bot-desktop): an infinite idle window is off and never fails start()
idle_stop_minutes: .inf meant "never stop" before the self-stop. start() now computes the launcher's
first-check delay from the window, and next_check_in overflowed on an infinite one, so the screen
could not start. A non-finite or non-positive window now reads as off, like 0.
2026-10-29 19:03:57 +05:30
kshitijk4poor
186a114d68 test(bot-desktop): the lock-race test runs on POSIX hosts only
Review (Greptile P1): test_an_idle_check_that_waited_on_the_lock_never_stops_the_replacement_screen
takes the real start.lock through runtime._flocked, which imports fcntl, so it cannot run on
Windows; tests/AGENTS.md asks host-specific tests to carry a platforms marker, as the other lock
tests in the file do. Marker only.
2026-10-29 19:03:57 +05:30
kshitijk4poor
ea25df6e57 fix(bot-desktop): a short idle window never times out a human between two viewer stamps
Review (Greptile P1): the human lease lapses after four idle windows, but an attached viewer stamps
activity at most once a minute (and the panel clock repaints once a minute), so stamps can be about
two minutes apart. With a short window (idle_stop_minutes: 0.1, four windows = 24 s) the idle stop
could close a screen a human was using between two stamps. The lapse is now four windows and never
less than 10 minutes (HUMAN_LEASE_ABANDONED_MIN_S). The default 30-minute window is unchanged (its
four windows are 2 h). Docs say so.

Test: with a 6 s window a human lease 150 s since the last stamp keeps the screen, and one past the
floor stops it; fails with the four-window lapse alone.
2026-10-29 19:03:57 +05:30
kshitijk4poor
848b14d183 test(bot-desktop): the human-lease assertion message matches the four-window rule
Review: in test_idle_screen_is_stopped_but_a_used_or_held_one_is_not the
idle age moved from 3600 s to 1200 s when a human lease started lapsing
after four windows, but the message still said a human mid-login is
"never" timed out. It now says "not timed out within four windows". The
assertion itself is unchanged.
2026-10-29 19:03:57 +05:30
kshitijk4poor
ed5384a11e fix(bot-desktop): stop() also removes the idle check's output file
Review: _stop_locked dropped launcher.pid, env and activity, but
bot-desktop/idle-watch.out (the launcher's idle check output, one
integer) survived every stop, including the self-stop of an abandoned
screen.

Fix: remove it with the other runtime files of the stopped screen.

Tests: stopping a running launcher leaves the state directory empty, and
the end-to-end abandoned-screen test now waits for idle-watch.out (and
activity) to be gone as well. Both fail with the file left behind before
the fix.
2026-10-29 19:03:57 +05:30
kshitijk4poor
279f89e994 fix(bot-desktop): a stale idle check never writes into the next screen's log
Review: the idle check runs in a session of its own, so it can outlive
its screen, e.g. after waiting on start.lock while a replacement started.
_spawn_and_wait opened launcher.log with "wb", truncating the same inode
the stale check still held at its old offset. Its late write left a long
run of NUL bytes in the replacement's log, followed by "changed while the
idle stop waited; kept" / "screen kept" lines that read as if they were
about the new screen.

Fix: unlink launcher.log before opening it, so each start gets a new
file (still one log per launch) and a stale check writes only to the
old, unlinked one.

Test: a descriptor held on the old log at its end (as the launcher's
non-append stderr is) writes after a start; the new log stays empty.
Before the fix it held the NUL run and the stale line. The spawn helper
is shared with the installation-command test.
2026-10-29 19:03:57 +05:30
kshitijk4poor
99ebab609d test(bot-desktop): the human-lease self-stop check keeps a wide margin
Review: test_a_screen_in_use_is_kept_and_a_returning_gateway_reattaches
aged activity to 3.2 s with a 3 s window and then needed two "screen
kept" checks before the human lease lapsed at 12 s idle: about 9 s for
two checks at a 3 s cadence plus an interpreter start each, which timed
out once in a loaded parallel run.

Fix: a 0.1-minute window (the lease lapses at 24 s idle), and the test
first syncs on a check that just kept the screen in use before writing
the human lease. The next check then starts a full window later and is
certain to judge the human-held, past-the-window screen, so one kept
check proves the rule (the second one only covered a check that might
already have been in flight). That leaves about 11 s of slack instead of
under one.

The assertion is as strong as before: with the human lease honoured for
only one window, the test fails waiting for the kept check.
2026-10-29 19:03:57 +05:30
kshitijk4poor
7de36168ef fix(bot-desktop): the idle check runs through the install's stable command
Review: the update fallback only fired when the starter's interpreter was
gone, and then probed venv/.venv. On an installer (store) install that
interpreter is the versioned store tool, which survives an update; the
check found its dependencies only through the PYTHONPATH generation it
inherited at spawn. Once that generation is collected every check fails
with ModuleNotFoundError and is retried every 300 s for the rest of the
screen's life, so the long-lived screens this targets never stop. The
venv/.venv order was also arbitrary on migrated hosts.

Fix: runtime.py hands the launcher the install's own command for the
check, installation_command(src_root, module="tools.bot_desktop.idle_watch"),
shell-quoted in HERMES_BD_IDLE_CMD. On a store install that is the
"<root>/.hermes/bin/hermes --run-module ..." launcher, which drops the
inherited PYTHONPATH, follows Python pin changes and loads the current
dependency generation on every run; elsewhere it is runtime_command. The
launcher runs it with eval "set -- ..." and appends its pid, so
sys.argv[1:] is still [pid]. The venv/.venv probing and HERMES_BD_PYTHON /
HERMES_BD_SRC_ROOT are gone.

Tests: a unit test checks that the command handed to the launcher equals
installation_command(...) for a store layout. The end-to-end update test
now starts the screen with the starter's interpreter removed and its
inherited PYTHONPATH pointing at a collected generation, from a root
whose path needs quoting; the screen stops itself through the install's
launcher, which saw exactly "--run-module tools.bot_desktop.idle_watch
<launcher pid>". Both fail on the previous launcher.
2026-10-29 19:03:57 +05:30
kshitijk4poor
5bdd6c9cf4 fix(bot-desktop): a screen started before an update still stops itself
Review nit: the launcher's idle check ran tools.bot_desktop.idle_watch with
HERMES_BD_PYTHON, the interpreter of the process that started the screen.
`hermes update` can rebuild the environment at a new path, so that
interpreter is gone by the next check: every check then failed, was retried
in 300 s, forever, and an abandoned screen never stopped.

Each check now falls back to the install's current interpreter when the
starter's is no longer executable: HERMES_BD_SRC_ROOT/venv/bin/python, then
HERMES_BD_SRC_ROOT/.venv/bin/python (both layouts are in the wild). It is
re-evaluated per check, so an update between checks is picked up.

Test: an abandoned screen whose starter interpreter no longer exists, in an
install whose environment lives in venv or .venv, stops itself after the
idle window, and the check ran with the install's current interpreter.
2026-10-29 19:03:57 +05:30
kshitijk4poor
33803072c7 fix(bot-desktop): a human lease nothing uses for four windows lapses
stop_if_idle skips a screen whose lease says a human holds it, and
nothing ever expires that lease: the viewer bridge deliberately keeps it
when the link drops (laptop lid, Wi-Fi), and a corrupt lease file reads
as human. A screen abandoned in that state, with no gateway coming back,
ran until reboot, the case the launcher's self-stop exists to close.

An attached viewer stamps activity on the updates it receives (at most
once a minute, and the panel clock repaints every minute), so a human
watching keeps it fresh. A human lease with no stamp for four idle
windows (two hours at the default) is now treated as abandoned and the
screen stops like any idle one. The docs state the rule.
2026-10-29 19:03:57 +05:30
kshitijk4poor
653057deae fix(bot-desktop): the launcher's first idle check waits a window
The watch loop checked first and slept second, so every screen launch
paid for an interpreter start while Xfce was still coming up, to read
an activity stamp the launcher had just written. That check could
never stop anything and raced start-up.

runtime.py now passes the first delay (one idle window, the same value
the check itself would return at age 0) and the loop sleeps before
each check.
2026-10-29 19:03:57 +05:30
kshitijk4poor
653603aac5 fix(bot-desktop): a self-stop no longer waits out the kill grace
The launcher's watch loop ran the idle check as `delay=$(check)`. When
that check decides to stop the screen, stop() TERMs the launcher's
process group, which includes the loop; bash defers the loop's TERM
trap until the command substitution returns, but the check is itself
waiting for the group to empty. Every self-stop therefore sat out
stop()'s 5 s grace, ended in SIGKILL, and held start.lock the whole
time, so an agent action or the pane's Start blocked behind it.

The check now runs in the background with its output in a file and is
waited on with `wait`, which a trapped signal interrupts, so the loop
exits at once and the check (in its own session) finishes the stop.
2026-10-29 19:03:57 +05:30
kshitijk4poor
1f14014710 fix(bot-desktop): a waiting idle check never stops the replacement screen
stop_if_idle decided "idle" before stop() took start.lock, and
_stop_locked then killed whatever launcher.pid named once the lock was
free. A check that waited on the lock while the screen was stopped and
started again (a Desktop Stop/Start, `screen stop && start`, or the
gateway watcher and the launcher's check firing together) killed the new
screen the moment it got the lock, whatever its idle age.

The decision is now taken again under start.lock, and nothing is killed
if it no longer holds. The launcher passes its own pid to the check,
which pins it to that launcher's (pid, create_time), so the check only
ever stops the screen that ran it. Without an identity (the gateway
watcher) the rule is unchanged apart from the re-check.
2026-10-29 19:03:57 +05:30
kshitijk4poor
b5e47a0225 fix(bot-desktop): an abandoned screen stops itself after the idle window
A Bot Desktop screen outlives the gateway that started it on purpose, so a
restarted gateway re-attaches to it. Both things that stop it (the display
watcher's stop_if_idle and the orphan sweep at the next start) run inside a
gateway, so when no gateway comes back the screen (Xvnc, Xfce and any browser
left open) runs until reboot.

launcher.sh now runs tools/bot_desktop/idle_watch.py in a loop. Each run
calls the existing runtime.stop_if_idle() (same idle_stop_minutes window,
same activity stamp, never while a human holds the screen) and prints the
seconds until the screen could next be due. Nothing stays resident between
checks; a check costs about 0.4 s of CPU. The check runs in a session of its
own so it survives stop()'s group kill and finishes the stop. The launcher
stamps activity when it starts, so a stale stamp from an earlier screen
cannot stop the new one, and retries a failed check every 5 minutes instead
of exiting. runtime.py passes the interpreter, source root and profile home.
The sandbox-hosted screen gets no interpreter and is unchanged.

Follow-up to #137057.
2026-10-29 19:03:57 +05:30
kshitijk4poor
b197ffca1e fix(process): a failed yield-to-background handoff gives the foreground wait its group back
Review (Greptile P1): adopt_local moved the command's supervised group to the new job before the
job's reader thread started. If the reader could not start, the exception reached the caller,
which resumes its foreground wait, but the group stayed with the discarded session: in a gateway
it had already been released, so the still-running command lost owner-death cover; elsewhere the
dead session kept it, so the foreground completion could not release it and a child the command
left running on purpose could be killed when Hermes later exited. On that failure the group now
goes back to the Popen (re-covered by the supervisor), so the foreground wait releases it as
usual.

Test: with the reader failing to start, both in a process that owns its jobs and in a gateway,
the Popen holds its group again and it is covered; fails without the hand-back.
2026-10-29 16:58:09 +05:30
kshitijk4poor
e51a19c1ca test(browser): the harness kill -9 test fails fast on a tree without ownership
Review (minor): the restored end-to-end test's stand-in daemon inherited the owner's stdout, so on
a tree where the owner died before printing the daemon pid, readline() waited out the daemon's
300 s sleep and the run ended with no result (and a leaked daemon). The daemon's stdout now goes to
DEVNULL: an owner that fails hands the test EOF at once. With the ownership call missing the test
fails in seconds; at head it passes.
2026-10-29 16:58:09 +05:30
kshitijk4poor
2730ebe7eb fix(process): a thread that cannot start never escapes spawn_owned; the idle grace falls back to an immediate release
Review (CI red on the idle-grace commit): _update_supervised_pgids promises that losing the safety
net never fails a live child, but the idle-grace Timer and the supervisor's waiter thread were
started outside that guard. A process that cannot start a thread (a thread limit, interpreter
shutdown, tests that patch threading.Thread) got the exception out of spawn_owned after its Popen,
so the caller lost the child's handle; six process-registry tests failed on CI. Both starts are now
guarded: with no timer the supervisor is released at once, as before the grace; with no waiter it
still works and is only reaped at exit. The list-exit probe, which is itself the subreaper whose
final wait collects every descendant, pins the grace to 0.

Test: with Thread.start failing, spawn_owned returns its child and the release closes the
supervisor at once (fails without the guard, as do the six CI tests).
2026-10-29 16:58:09 +05:30
kshitijk4poor
2a845db458 perf(process): an idle supervisor stays for a 30 s grace instead of exiting with every command
Gate (efficiency): a gateway owns no background jobs, so its supervised set is usually empty, and
every foreground command owned and released its group: the release closed the supervisor and the
next command spawned a new /bin/sh under _supervisor_lock. The supervisor now exits only after the
set has stayed empty for _SUPERVISOR_IDLE_EXIT_S (30 s); a registration inside the grace cancels
it and reuses the same supervisor. It still exits on its own once idle, so nothing stays resident
for the life of a quiet gateway.

Measured on macOS arm64, 20 own/run/release cycles of `true`: 5.6 ms per command with the
immediate release, 3.5 ms with the grace.

Tests: two commands in a row share one supervisor, which then exits and is reaped after the grace
(fails with the immediate release). The protocol tests that assert the release itself pin the
grace to 0.
2026-10-29 16:58:09 +05:30
kshitijk4poor
5abba578ca test(browser): restore the end-to-end SIGKILL test for the harness daemon; fix a stale example
Gate (quality): the port onto main's browser rewrite dropped
test_a_sigkilled_owner_takes_its_harness_daemon_with_it with the agent-browser and exit-path tests,
though it uses only browser_use_cli surface that is still here. It is the only end-to-end proof
through the real supervisor that a kill -9'd Hermes takes its harness daemon along; restored
unchanged (fails when _own_harness_daemon stops handing the group to the supervisor). The
process_identity comment's example of a child something else spawns named the agent-browser
daemon's Chromium, which nothing owns any more; it names the browser-harness daemon.
2026-10-29 16:58:09 +05:30
kshitijk4poor
e579e9b98e perf(browser): the in-call ownership check stops once the daemon can never be ours
Gate (2c, efficiency): the 0.5 s check while browser_exec runs stopped only once this process
owned the daemon. On Windows, in a managed worker, or for a daemon another Hermes started it can
never be owned, so it ran every tick for the whole call (up to ~600 short threads in a 300 s call;
for another Hermes's daemon each tick also read its cmdline, uids, sid and environ).
_own_harness_daemon now answers True (owned), False (never ours) or None (nothing to own yet), and
the check stops on anything but None. The managed-worker comment now gives the real reason: a
killed worker must not take the next turn's browser along; its clean exit still runs main's atexit
browser cleanup.

Tests: for another Hermes's daemon and in a managed worker the check answers stop; both fail with
the old owned-only stop rule.
2026-10-29 16:58:09 +05:30
kshitijk4poor
309d551c84 refactor(browser): port the harness-daemon ownership onto main's browser rewrite
main deleted agent-browser and the browser_tool_* modules and replaced them with a Python Chromium
launcher (tools/browser_launcher.py) and a browser_session layer. On this base:

- The agent-browser family (daemon + Chromium ownership) and the old lightpanda / real-profile
  ownership have nothing left to apply to; their tests are dropped.
- main's atexit handler (browser_session_lifecycle.emergency_cleanup_all_sessions) now always runs
  cleanup_all_browsers, which stops every harness daemon this process drove. The owned-only exit
  step (stop_owned_harness_daemons) had no caller left and is removed; a harness daemon this
  process started is still owned and dies with it on an ungraceful exit.
- The launcher's Chromium and lightpanda serve start detached by design: a shared-profile Chromium
  outlives its launcher for its other holders, and a crashed owner's throwaway Chromium or
  lightpanda server is reaped from its launch record by the next Hermes. Both spawns are marked
  with that reason; owning the throwaway ones is a follow-up.
- The long-first-call test drives main's browser_exec routing (_route_exec_current).
2026-10-29 16:58:09 +05:30
kshitijk4poor
aa6b60e3e4 fix(browser): Windows exit stops no harness daemon again
Review (W4): on main, the atexit handler reached harness daemons only through
cleanup_all_browsers when _active_sessions was non-empty, so a browser_exec-only process never
stopped them on Windows. This branch's exit step fell back to stop_harness_daemons() off POSIX,
so every Windows exit --reloaded every daemon it had driven: a shared "default" daemon another
live Hermes was using (the cross-owner stop this branch fixes on POSIX) plus up to 15 s of exit
latency per daemon. Windows records no ownership, so the owned-only exit step now does nothing
there, as main did.

Test: with os.name "nt" and a driven daemon, the exit step reloads nothing; fails with the fallback.
2026-10-29 16:58:09 +05:30
kshitijk4poor
ebbe223a41 fix(browser): a managed per-turn worker never owns its browser daemons
Review (W3): agent/managed_worker.py documents that a worker keeps its background processes,
sandbox and browser between turns, and _owns_job exempts managed-worker jobs for that reason.
The browser daemons had no such exemption: a Browser Use harness daemon or an agent-browser
daemon (and its Chromium) started by one turn's worker was owned by it, so the supervisor killed
it when that worker exited and the next turn got a fresh browser (a Browser Use cloud browser lost
its state). _own_harness_daemon and _own_local_daemon now return early in a worker process
(agent.runtime_session_store.is_worker_process), mirroring _owns_job.

Tests: in a worker process neither family registers its daemon; both fail without the check.
2026-10-29 16:58:09 +05:30
kshitijk4poor
2b36e8cd58 fix(browser): a long first browser command owns its daemon while it still runs
Greptile on d1d8bc2e19: browser_exec handed the harness daemon to the owner-death supervisor only
after the CLI call returned, and agent-browser did the same for its daemon and Chromium. The first
call starts them and can run for minutes (navigation, user code); a Hermes killed during it left
them running, as on main. Both waits now run inside registering_meanwhile(), which calls the same
ownership check (_own_harness_daemon / _own_local_daemon) every 0.5 s on a helper thread while the
command runs and stops (joined) before the caller's own post-call check. A command shorter than
0.5 s never triggers it; the check is the existing one, so a daemon another Hermes started is still
never registered. _owns_local_daemon names the local-session predicate both agent-browser call sites
now share.

Tests: a browser_exec and an agent-browser command that block until their daemon was owned (both
fail when the wrapper is removed); registering_meanwhile stops with its block and swallows a failing
registration.
2026-10-29 16:58:09 +05:30
kshitijk4poor
ea08389a2d fix(browser): exit reloads an owned harness daemon only while its name still publishes our pid
Greptile on d1d8bc2e19: stop_owned_harness_daemons trusted the cached ownership entry and stopped the
daemon by name (--reload). If our daemon had exited and another live Hermes had since started its
replacement under the same name, _own_harness_daemon never saw it (no command ran here after), so
exiting this Hermes stopped the other Hermes's browser. The exit path now reads the name's published
pid (one resolver, _published_daemon_pid, shared with _own_harness_daemon) and reloads only names
that still publish the pid we own; for the rest it forgets the entry and releases our old group once
empty. The exit test now uses a real per-test runtime dir instead of resolving under $HOME.

Test: with the name republished by another pid, exit reloads nothing and releases ours; the control
half (still our pid) reloads it. Fails when the published-pid check is removed.
2026-10-29 16:58:09 +05:30
kshitijk4poor
aae69cfaf4 fix(browser): Windows still stops its harness daemons at exit; a known agent-browser pid is still a group leader
Round-2 review of the exit-path fold:
- Windows records no ownership (_own_harness_daemon is POSIX-only), so the owned-only exit stop
  would have stopped nothing there. stop_owned_harness_daemons stops every driven daemon on
  Windows, as the exit path did before.
- _own_local_daemon keeps its one-syscall group-leader check for an already-owned pid, so a stale
  pid file whose pid was recycled is never treated as the owned daemon.
- The ddgs marker now says the worker runs until its search returns, which is unbounded if primp hangs.
- test_mcp_stdio_init_timeout still patched tools.mcp_tool._get_mcp_stderr_log (dropped in the
  previous commit); the replaced-daemon test uses a reaped child's pid instead of a fixed 4242; the
  two browser kill -9 tests treat macOS's EPERM for a zombie-only group as gone.

cleanup_all_browsers keeps stopping every driven daemon: /browser connect|disconnect call it so the
next call runs on the new endpoint, and a daemon latches its endpoint when it starts
(TestBackendSwapRetargetsDaemons). Its reload of a daemon another Hermes started on the same name
is main's behaviour, unchanged here.
2026-10-29 16:58:09 +05:30