Commit Graph

6709 Commits

Author SHA1 Message Date
dev-agent
9d8efb3504 fix(mcp): pin the active profile's HERMES_HOME into stdio child env
The MCP stdio spawner built its child env from an allowlist (_SAFE_ENV_KEYS)
that omits HERMES_HOME, so every stdio MCP child was launched with no
HERMES_HOME at all. Under a multiplexed host / dashboard-desktop backend
serving `--open-profile` (e.g. hermes-serve-dev.service, host home = default,
opened profile = dev) those children resolved to the platform-default home
instead of the served profile:

  - any Python child importing hermes_constants tripped
    _warn_profile_fallback_once() -> "[HERMES_HOME fallback] HERMES_HOME is
    unset but active profile is 'dev' ... Any data this process writes will
    land in the wrong profile" (issue #18594);
  - children that DO write (caches/state) landed under the default home.

Pin the ACTIVE profile's home at spawn time via get_hermes_home() (honours the
served-profile contextvar, which does not cross the process boundary;
os.environ only holds the launch profile's home). An explicit server
`env.HERMES_HOME` still wins (applied after).

Verified: tests/tools/test_mcp_stability.py,
tests/tools/test_mcp_connect_secret_scope.py -> 20 passed.
Probe: served scope (override=dev) now yields child HERMES_HOME=.../profiles/dev.
2026-11-02 13:31:06 -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
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
b8e0f9ed29 test(gateway): pin the shared-owner /bg delegation join
Review finding "Shared-owner fix lacks test coverage": prompt.background
runs a background delegate_task through _side_scope; the new test drives
a real owner daemon and asserts the child's answer lands in
background.complete with no async_delegations row. It fails when
async_delivery=False is dropped from _side_scope.

Also list "a /bg background task" in the terminal tool's async-unsupported
note (tool result only, matching the delegate note) and drop the blank
lines the method move left in gateway/run_turn.py.
2026-11-01 21:11:06 -08:00
Teknium
2d0bf91f11 fix: every /bg entry point joins its background delegations in the run
The gateway /bg fix above covered messaging chats only. The shared-owner
/bg (prompt.background, used by the CLI, TUI and Desktop) and the classic
local CLI /bg run the same detached bg_* side agent, and on main a
background delegate_task there also leaves a completed ledger row pending
forever: nothing wakes or drains a bg_* session. Their side agents now
declare the channel stateless, so the batch runs inline and the result is
in the one answer /bg reports. The sync-fallback note names /bg.

Refs #140569.

Co-authored-by: milnerrad <302432023+milnerrad@users.noreply.github.com>
2026-11-01 21:11:06 -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
Teknium
a4994d4ead fix(clarify): choices that display alike stay distinct so a pick maps back to its own raw
The clarify display copy maps a picked choice back to its raw text by its
display string. Two raw choices that sanitize or redact to the same display
(two secrets both shown as `***`, a literal "\u202e" beside a real U+202E)
collided, and the model got the other raw choice. Suffix repeats with " (2)",
" (3)" so every display choice is unique.
2026-10-31 23:05:03 -07:00
Teknium
7c8dd94f1f fix(clarify): show questions and choices with a prose-safe display pass
Clarify questions went through the command escaper, so ordinary prose
showed VS16, ZWJ and ZWNJ as escapes ("⚠\ufe0f Which branch?", Persian
words split by \u200c). sanitize_command_for_display/redact_approval_display
gain prose=True: it still surfaces controls, bidi embeddings/overrides/
isolates, line/paragraph separators and padding, and leaves emoji and
script joiners alone. Choices now get the same display copy; a picked
choice maps back to its raw text by position, so the model still receives
the raw question and answer. Commands keep the strict escaper.
2026-10-31 23:05:03 -07:00
Teknium
33bce7b26d fix(approval): show hidden characters on the remaining first-render prompt surfaces
The tool-progress line under the approval prompt, the ACP edit-approval
title, the clarify question's first render and the human-input observer
prompt now go through redact_approval_display like the approval prompt
itself. Display copies only: the executed command, the clarify tool result
and its answer values, and the ACP diff path stay byte-identical.

Selected plugin transports already receive the display copy of command and
description; the new invariant test pins that too.
2026-10-31 23:05:03 -07:00
Teknium
3f5612cde6 feat(approval): show hidden characters and padding in approval prompts
A dangerous command can carry content that renders as nothing: zero-width
and bidi-override characters, the U+E0000 tag block, raw ANSI/OSC escapes
or a bare carriage return, or a few hundred (ASCII or Unicode) spaces that
push the real tail off screen or past the 200-char chat preview. The human
then approves something other than what runs.

agent/redact.py gains sanitize_command_for_display() (hidden characters ->
visible \uXXXX / \xNN escapes, padding -> an explicit marker, legit
indentation and tabs/newlines untouched) and redact_approval_display()
(secret redaction + sanitize). Every approval mint site uses it: the CLI
prompt and its callbacks, the gateway notify payload, the execute_code
pending body, plugin approval transports, and gateway.run's
_redact_approval_command seam, which feeds messaging cards, TUI/Desktop
and the API server. Display-only: the executed command, smart assessment
and allowlist keys are unchanged.
2026-10-31 23:05:03 -07: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
a7c6f729be docs(gateway): scope comments say what the off-loop reads depend on
The retired-session comment covered only a pop while the read waited; retire_live_sessions pops on the
loop without the event lock, so it can land mid-projection too. prepare_profile_terminal_scope reads the
managed-scope overlay under the home override, not the secret scope.
2026-10-31 12:56:22 +05:30
kshitijk4poor
86cc60932f fix(gateway): retired-session polls answer not_found; one scope build path
Review follow-ups on the off-loop RPC scope and ancillary projection:

- session_ancillary: the projection re-indexes authority.sessions
  (_require_current_route, physical_target, _owner_objects). Running in a
  worker, it can now see a session that retire_live_sessions popped on the
  loop while the read waited for a worker or the event lock. That surfaced
  as an uncaught KeyError, i.e. -32603 plus a "ws dispatch crash" traceback,
  instead of not_found. A KeyError for a session that is no longer the one
  the read started on now maps to not_found. A KeyError from a live session
  still raises.
- session_authorities._prepare_owner_scope now enters the real
  _profile_runtime_scope(home, hydrate_secrets=False) in the worker and
  reads back the bound secrets and terminal scope. The scope entry order
  (home override, then secrets, then terminal policy) has one definition
  instead of a hand-kept mirror.
- terminal_scope.prepare_profile_terminal_scope docstring: the build reads
  under the caller's home override and secret scope.
- tests: the ancillary test uses the real projection with a recording event
  lock rather than patching the projection out. Added a retired-mid-read
  not_found test and a live-session KeyError test. The scope parity
  snapshot is keyed by name.
2026-10-31 12:56:22 +05:30
kshitijk4poor
8e13a8090a fix(gateway): read the RPC owner scope and ancillary polls off the event loop
Clients poll per open session: the classic CLI asks subagent.list once a
second while a turn runs, Ink asks subagent.list and process.list every 1.5 s,
and Desktop every 5 s per visible pane. On a multiplexed gateway (the default)
every one of those RPCs did two things synchronously on the loop:

- session_controls.dispatch entered owner_scope(authority), which builds the
  owner's secret scope (.env, managed env, realpath of the home) and terminal
  policy (.env, config.yaml) from files.
- the projection itself (session_ancillary.read) held the session's
  event_stream.lock, which every streamed token takes from the agent thread.
  Under that lock it walked the compression lineage with get_session, read the
  local receipt and control meta from state.db, and read the process registry
  under its lock.

A py-spy profile of a real gateway (multiplex on, 16 long-lived sessions
polling like the classic CLI) put 23% of loop-thread time in owner-scope
construction, 16.6 s of it under dispatch. With 32 sessions and no multiplex,
the ancillary projection was about a quarter of the busy loop time.

Changes:
- tools/terminal_scope: prepare_profile_terminal_scope builds the policy (or
  the refusal scope) without installing it. install_and_reset_profile_terminal_scope
  takes prepared=; install_profile_terminal_scope is unchanged in behaviour.
- gateway/run._profile_runtime_scope takes prepared_terminal_scope.
- gateway/session_authorities.async_owner_scope: under multiplex, builds the
  secrets and terminal policy in one worker hop (under the home override, the
  policy under the secret scope, as _profile_runtime_scope does) and only sets
  the context variables on the loop. A single-profile gateway, a symbolic owner
  or a missing home falls back to owner_scope, so it binds exactly what it
  bound before.
- session_controls.dispatch uses async_owner_scope.
- session_ancillary.read runs its projection (_read_projection) in a worker
  thread, which inherits the dispatch's scope.
2026-10-31 12:56:22 +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
Teknium
ee394bd921 feat(cron): a stopped or removed run books 'cancelled'; each job picks its missed-run policy
Stopping a live run:
- Removing a job while it runs now cancels that run (cancel marker on its execution)
  instead of letting it burn tokens until a lost fire claim discards the result (#123045).
- An operator-cancelled run (hermes cron cancel, the new POST
  /api/cron/jobs/{id}/cancel, cronjob action=cancel, remove) records a terminal
  'cancelled' ledger row with its reason; the job's last_status is 'cancelled', with no
  failure alert and no failure-streak bump. The cancel check runs before claim-loss
  handling, so a removed job books the cancel, not "fire claim ownership lost".

Missed runs:
- New optional per-job `catch_up` (true = one catch-up run, false = skip). Unset,
  recurring jobs keep following cron.catch_up_missed and one-shots keep the 120s grace
  rule (#93526); a one-shot that opts in fires once late.
- Every skipped or collapsed slot is booked as ONE 'missed xN' ledger row, shown by
  `hermes cron runs` and the dashboard/Desktop run history.
- The execution ledger's status CHECK is widened in place (one-time table rebuild under
  BEGIN IMMEDIATE) to admit 'cancelled' and 'missed'.

The fast-forward and one-shot retire gates move from cron/jobs.py into
cron/missed_runs.py; the cancel-event types move next to the marker in
cron/cancellation.py, keeping both facades at or under their size baseline.

Prior art: #44617 (@LeonSGP43) first proposed stopping in-flight runs on pause/shutdown;
its in-process agent registry no longer applies now that runs execute in the
restart-safe worker, so the cancel rides #133169's per-execution marker instead.
name.

Co-authored-by: LeonSGP43 <LeonSGP43@users.noreply.github.com>
Co-authored-by: fangliquanflq <fangliquanflq@users.noreply.github.com>
2026-10-30 05:54:35 -07:00
kokhlo
8c228c5b89 feat(cron): hermes cron cancel stops a job's live run
pause only suppresses future fires, so a wedged run had no operator
 recourse: wait out HERMES_CRON_TIMEOUT, or hunt the process group by hand.

The kill path already exists — _run_job_script polls a cancel_event and
tears down the whole tree via kill_process_tree, and an agent run
interrupts at the same seam. What is missing is a signal an operator can
reach, and it cannot be an in-memory Event: run_one_job hands the attempt
to a detached external worker before anything executes in-process.

So the request is a marker file per execution id, joined to the existing
_FireOwnership cancel seam as a third source. Keyed by execution id, only
the run it was written for can read it, so a leftover marker cannot bleed
into the job's next fire. Resolving the live attempt through
live_inflight_execution() keeps a dead owner's stale row a clean no-op
instead of a marker nobody would ever read.

An operator cancel is deliberately not folded into transport_cancel:
only a transport cancel counts as claim loss for bookkeeping, while a
cancel is a real outcome the run records itself — which also fixes the
"explicit stop requested"-style wording, since the recorded reason now
comes from whichever source actually fired.
2026-10-30 05:54:35 -07:00
kshitijk4poor
e864515d26 fix(projects): write host_workspace only for the session's own folder
The blanked override always carried host_workspace, as "" when the cwd
was a process fallback rather than the session's folder. Write the key
only when there is one, and document it on register_task_env_overrides
as host-side state the terminal never reads.
2026-10-30 15:45:49 +05:30
kshitijk4poor
fdb71a95a2 fix(terminal): keep the :ws: key idempotent and test the unmounted key gate
The mount gate in _workspace_container_key ran before the short-circuit
that maps an already-resolved <base>:ws:<digest> key to itself, which
the docstring promises (ensure_task_env re-resolves the key it got).
Check the gate after it. Its comment named ACP, whose cwd override
carries no cwd_source and never produced a :ws: key; say what it guards.

The gate had no test of its own: both writers of cwd_source "session"
are already gated, so reverting it left every test green. Pin it with a
registered session workspace under an unmounted persistent policy.
2026-10-30 15:45:49 +05:30
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
a88398c07f docs(bot-desktop): comments match the human-lease lapse and the stable idle command
The idle check's module docstring and the launcher still said a human holding the screen is never timed
out (the four-window lapse changed that) and that the launcher runs `python -m`; stop()'s docstring said
the re-check always runs under start.lock (a sandbox screen's does not); the pinning note now says it
holds on a store install. Comments only.
2026-10-29 19:03:57 +05:30
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
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
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
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
935c08f2d4 chore(bot-desktop): the screen spawn's comment names the idle stop, not one caller of it
Review (minor): the comment said the display watcher idle-stops the screen. The follow-up that has
the launcher run the same idle rule itself would leave that stale; naming the rule
(idle_stop_minutes) stays true either way. Comment only.
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
10b430de5e docs(process): _owns_job says which surfaces actually own their background jobs
Review (W1): the docstring (and the PR description) read as if CLI, TUI and foreground-gateway
background jobs were owned. Every gateway boot runs recover_from_checkpoint, which sets
_jobs_outlive_host whether or not a checkpoint exists, and the classic CLI, the TUI, the Desktop,
ACP, cron and messaging all run their tools in a gateway, so their background jobs are not owned,
exactly as on main. Only a process that is not a gateway owns its jobs; foreground commands are
owned everywhere. Whether an idle-exit CLI gateway that recovered nothing should own its jobs is a
behaviour change with its own risk (an idle exit would then kill a user's `npm run dev &`), so it is
left for a separate change. Docstring only.
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