Commit Graph
7960 Commits
Author SHA1 Message Date
teknium1 1038e0fc77 fix: descendant sweep spares the stopper, reports leftovers, and skips subtrees of unkillable roots
Review follow-ups on the #112631 descendant sweep:

- `_posix_descendants` excluded nothing of the caller. `hermes dashboard --stop` /
  `hermes update` run from a shell escape inside the hosted Chat TUI are same-session
  descendants of the backend, so the sweep SIGTERMed its own process mid-run (probe:
  caller in snapshot, backend SIGKILLed, "survived" line never reached) — the POSIX
  twin of the Windows #98814 hazard. The caller, its subtree and its ancestor chain are
  now pruned from the same `ps` snapshot; an ancestor's *other* children (the wedged
  TUI) stay in the sweep.
- Descendants still alive after their SIGKILL grace were silently dropped and the stop
  declared complete; they now land in `failed` so `_kill_stale_dashboard_processes`
  prints them — a wedged ui-tui still holding the deleted WAL is the incident itself.
- The Desktop boot reaper SIGKILLed descendants of roots whose own kill raised
  (EPERM: not ours), orphaning a foreign tree half-way. Descendants now carry their
  root and are skipped when the root is in `failed`. First test of that hunk.
- `_is_detached_session_leader` documents that compute_host / slash_worker children
  are exempt by the same rule and rely on their own ppid watchdogs.
2026-09-17 09:04:11 -07:00
teknium1 f3bdcd0877 fix: dashboard stop sweeps the wedged descendants that outlive the SIGKILLed backend
`hermes dashboard --stop` / `hermes update` signal only the backend PIDs. When the
lifespan teardown wedges (stop_hosted_room_service, PTY close_all never reached) the
10s grace loses, SIGKILL lands mid-teardown, and the hosted ui-tui / tui_gateway.entry
child is reparented to init still holding the state.db-wal inode; the next start
refuses with DeletedWalGenerationError (#112631, residual of #111912). No finite
root grace covers an unbounded teardown.

_kill_pids_posix now snapshots the dashboard-owned descendant tree BEFORE the kill
(the PPID link is gone once the root dies), and after the root phase SIGTERM→SIGKILLs
the descendants that are still alive, waiting for the tree to be gone before
returning. Descendants are re-checked against their snapshotted start-time
fingerprint (the same PID-reuse guard _kill_pids_windows uses) — no `ps -o lstart`
per system PID.

Detached session leaders without a controlling terminal are pruned from the sweep
with their subtrees: those are the messaging-gateway bots and profile actions the
dashboard launched with start_new_session from /api/gateway/*, which belong to the
user, not the dashboard. A hosted TUI is a session leader too (pty.fork) but owns
the pts whose master the dashboard held, so its tty column is set and it is swept.

The Desktop boot reaper (_reap_orphaned_desktop_local_serves) SIGKILLs the same
class of backend after 1.5s and had the same hole; it now SIGKILLs the surviving
snapshotted descendants (no second grace: the boot path runs under a 10s probe).

Live: pyteman hermes-111912 wedged leg on origin/main
`child_orphan_alive=True deleted_sidecar_holders=2 guard=FATAL DeletedWalGenerationError`,
on this head `child_orphan_alive=False deleted_sidecar_holders=0 guard=clean`; the
start_new_session control sibling survives on both.
2026-09-17 09:04:11 -07:00
teknium1 3f80dc9a5a fix(plugins): stream observer hooks and event subscribers fail-report once, not per event
Two per-call WARNING surfaces were still outside the warn-once reporter:

- agent/plugin_stream_hooks.py::_worker — the on_stream_start/on_stream_delta/
  on_stream_end consumer, which fires once per streaming delta (far more often than
  per tool call). A mis-declared callback (signature naming tool_data) logged
  "Hook ... raised" at WARNING on every delta: 20 deltas -> 20 WARNING lines.
- hermes_cli/plugins_dispatch.py::_deliver_event — plugin event subscribers that
  raise identically were warned on every emit.

Both now go through PluginManager._report_hook_failure (keyed by module/qualname,
cleared on unload): the first failure warns and names the fields the hook/event
provides, identical repeats are DEBUG. Skip-and-continue semantics are unchanged.

Part of #111922
2026-09-17 09:03:29 -07:00
teknium1 0f98d5a1d9 fix(plugins): execution-chain middleware failures are reported once, not per call
The warn-once reporter added for hooks (and for PluginManager.invoke_middleware)
left the execution chain out: hermes_cli/middleware.py::_run_execution_chain — the
tool_execution / llm_execution frames that run once per tool or LLM call — still
logged "Middleware '%s' callback %s raised" at WARNING on every invocation. A
mis-declared callback (e.g. a signature naming tool_data) therefore flooded the
log exactly like the hook case #111922 reported: 5 calls -> 5 WARNING lines.

Route the frame's except through the manager's _report_hook_failure with the
"Middleware" surface label, so the first failure warns (listing the fields the
middleware does provide) and identical repeats go to DEBUG; the set is already
forgotten on plugin reload. The frame's skip-and-continue semantics are unchanged.

Part of #111922
2026-09-17 09:03:29 -07:00
abc56351aa fix(vision): delegated subagents stop re-loading the same image on the native fast path
A delegate_task child asked to transcribe five screenshots called vision_analyze 158
times on those files (full loads alternating with region crops) until its provider
quota ran out; every native load bakes the image into history and is re-sent on each
later API call, and nothing refused the repeat (#112095).

tools/vision_tools_history_budget.py now keeps a per-(session id, resolved source)
embed counter. Region crops share their file's key. When the cap is reached
_vision_analyze_native returns a tool error that says the image has already been loaded
N times and to answer from what is visible or ask the user, instead of another embed.
Only successful embeds count, so a failed read never eats the budget.

Default: `vision.max_calls_per_image` unset caps only delegated subagents
(agent.delegation_context.is_delegated_child_process_context) at 3 — they run
unattended and CLI /steer targets the parent — while the main agent stays unlimited;
an explicit value applies everywhere and 0 means unlimited.

Co-authored-by: Evi Nova <66773372+Tranquil-Flow@users.noreply.github.com>
Co-authored-by: gumclaw <gumclaw@gumroad.com>
2026-09-17 09:02:55 -07:00
Mohamad Kanso f37336522b feat(vision): vision.embed_target_bytes replaces the hardcoded 256 KB native embed budget
The native vision_analyze fast path (and the browser screenshot twins) downscaled every
embed to a fixed _EMBED_TARGET_BYTES = 256 KB. That is fine for photos but turns a
1080x2340 phone screenshot of a table into 540x1170, which the model then reads as
"unreadable" and re-requests (#112095).

The budget is now `vision.embed_target_bytes` in config.yaml (default unchanged: 256 KB,
clamped to 64 KiB..4 MiB so one setting cannot make every later request a multi-megabyte
resend), resolved in the new topical sibling tools/vision_tools_history_budget.py and read
by vision_analyze, browser_vision and browser_exec screenshots alike.

Ported from #112947 by @MohamadKanso (resolver + clamp), relocated out of the facade.
2026-09-17 09:02:55 -07:00
teknium1 d6add16059 fix(auth): dead OAuth logins are reported once and leave rotation; hints point at hermes auth
A terminally rejected refresh token (invalid_grant / invalid_token /
refresh_token_reused) is the moment a login is lost. Three gaps remained
after #113197 (which added the WARNING for Codex/xAI/Nous):

- Anthropic: the token endpoint's HTTPError carried no classifiable code,
  so a dead Anthropic / Claude Code grant fell through to a transient
  'exhausted' bench at DEBUG and was replayed every hour. The endpoint
  error is now a structured AnthropicOAuthError (status + OAuth error
  code); _recover_failed_refresh logs one WARNING with the repair command
  and marks the row DEAD. A dead grant is not replayed at the fallback
  endpoint. The auxiliary Claude Code refresher (sibling path) warns the
  same way. Claude Code's own credentials file is never touched.
- Codex/xAI/Nous: _quarantine_sources drops only singleton-seeded rows, so
  an independent `hermes auth add` (manual:*) login survived unmarked and
  re-fired the WARNING on every later refresh attempt. The survivor is now
  marked DEAD (leaves rotation until a write-side re-auth clears it).
- Hints on live Hermes paths (anthropic 401 troubleshooting block, the
  no-credentials error) recommended an external CLI's login command,
  which cannot repair Hermes' own login; they now say
  `hermes auth add anthropic` / `hermes auth list anthropic`.

Docs: credential-pools.md documents the dead-login behaviour.
Part of #113023.
2026-09-17 09:02:26 -07:00
teknium1 931b5ff9e7 fix(opencode): every credential-resolution surface keys off the model it will send; family heal only for built-in providers
Closes the remaining atoms of #112600.

A) The CLI startup path already passes `-m` as target_model (c358a6fba0), but
   its siblings still resolved credentials against config's `default`: the CLI
   auth-fallback rung, `--resume` credential re-resolution, the gateway
   provider-override helper (channel overrides, persisted /model switches,
   API-server provider refresh), the gateway fallback chain, the TUI /model
   switch-from runtime and ACP agent construction. With a `*-free` default the
   OpenCode free-tier rung fired first and a Go-only model was built against
   the keyless Zen relay ("Model mimo-v2.5 is not supported"). Each now passes
   the effective model; `_resolve_runtime_agent_kwargs_for_provider` grows an
   optional `target_model` and the two test stubs of it accept the kwarg.

B) normalize_opencode_base_url rewrote the /zen vs /zen/go segment for ANY
   provider matched by opencode_provider_family, including custom providers
   merely named after a family (`opencode-go-bridge`, #85589) whose relay the
   user declared explicitly in `providers:`. The family heal now applies to the
   built-in canonical providers only; custom prefix-named providers keep their
   per-model api_mode routing and /v1 handling. Documented in the providers
   guide.

C) Same function: the official-host check uses parsed.hostname (a port no
   longer defeats the heal) and only the path is edited, so query/fragment
   round-trip instead of being dropped.

Fixes #112600
2026-09-17 08:59:22 -07:00
teknium1 f7631c0ee7 fix: fold a duplicate custom_providers row at the match level so its own models still route
Dropping an identity-equal legacy `custom_providers` entry from the candidate list also dropped the
models only that entry declared: `/model gpt-5.4-mini` (declared by the legacy row but not by
providers.relay) fell through to the current provider (openrouter) instead of routing to the shared
endpoint — a fail-open flip versus the pre-#112788 behaviour, which routed it to custom:relay.

Keep every entry as a candidate and credit a duplicate's hits to the providers row it duplicates, so
the collapse loses no declaration. `_duplicates_configured_row` now returns the owning slug.

Also require credential equality (not just endpoint) in the raw-list `provider_key` shortcut: a
hand-written entry stamped `provider_key: relay` on the same URL but a different key_env is a
distinct route and stays ambiguous, matching the issue's "preserve ambiguity when credential differs"
criterion.
2026-09-17 08:55:04 -07:00
teknium1andKoNit-K 01d2e6c3d1 fix: /model collapses compat views of one configured provider by identity, keeps custom:<slug> sessions
`_configured_provider_matches` now drops a `custom_providers` entry when it is a second view of a
`providers.<slug>` row: either that row's compat projection (provider_key names the slug AND the
endpoint matches) or a legacy duplicate with the same provider identity (normalized name, endpoint,
credential identity, api_mode — read through the same normalizer that builds the compat view).
Any difference in endpoint, credential or wire protocol keeps two rows distinct.

Why: the first pass (#113103) only filtered entries whose provider_key equalled a providers slug.
A hand-migrated config that kept the same endpoint in both sections was still reported as
"declared by multiple configured providers (custom:relay, relay)", and on the raw-list fallback
(gateway/agent_init pass cfg['custom_providers'] verbatim when the compat view fails) a hand-written
provider_key pointing at a different endpoint was silently hidden instead of ambiguous.

`_route_configured_provider` treats `custom:<name>` of a projected row as an alias of its slug when
checking whether the session is already on the matched provider, so a session running on
`custom:relay` that types a model providers.relay declares stays on `custom:relay` instead of
flipping target_provider/explicit_provider to `relay`.

Closes the remaining atoms of #112788. Identity-tuple approach ported from the
`_configured_provider_identity` hunk of #112794.

Co-authored-by: KoNit-K <124019182+KoNit-K@users.noreply.github.com>
2026-09-17 08:55:04 -07:00
teknium1 3187d68b49 fix(kanban): goal_mode workers keep the live tool feed in their worker log
The dispatcher forced `-Q` on goal_mode cards because cli.py only ran the
kanban judge loop in the fully-quiet one-shot branch. `-Q` strips every tool
callback, so the dashboard's Worker log (and `hermes kanban log`) stayed
blank for the whole run while non-goal cards logged normally; users read
that as "the worker is doing nothing" (Discord report, Sep 2026).

Run the judge loop on the `-q` path too, driving follow-up turns through
cli.chat so each turn's tool activity lands on stdout (= the worker log),
and print each judge verdict there as well. The dispatcher spawns goal_mode
and one-shot workers with the identical argv; the mode travels only in
HERMES_KANBAN_GOAL_MODE. The `-Q` hook stays for manual quiet runs.

Live A/B (real `hermes kanban dispatch` + spawned worker against a scripted
loopback provider that answers a terminal tool call then text, judge always
"continue", --goal-max-turns 2): base log = 94 bytes, 0 tool-feed lines,
0 verdict lines; fix log = 1910 bytes, 4 tool-feed lines, 3 verdict lines;
both arms end blocked "exhausted 2/2 turns" (loop behaviour unchanged).
2026-09-17 08:55:01 -07:00
teknium1 d1c6786d1e fix(models): custom providers can inherit a vendor catalog; unknown models get no synthesized output cap
A metadata-only model_overrides entry on a custom provider (only context_window set) took the
unknown-model branch of get_model_capabilities and reported max_output_tokens=8192 from the
_UNKNOWN_MODEL_BASE template; /model info showed "Max output: 8,192 tokens" for a model nobody
knows. The output limit is now left unknown (ModelCapabilities.max_output_tokens=None,
ModelInfo.max_output=0), matching the fail-open treatment #113146 gave supports_vision and
supports_reasoning. Consumers already handle a missing value: the dashboard only renders a
positive limit and the /model card only prints a truthy max_output.

There was also no way for a custom provider that resells a catalogued vendor's models (a
gateway/proxy) to reach _BUILTIN_MODEL_METADATA or the models.dev catalog, which is what forced
the metadata-only override in the first place. providers.<name>.catalog_provider (also honoured
on legacy custom_providers[] rows) names that vendor; models_dev resolves the catalog id through
it for capabilities, context, model info and provider info. It affects metadata lookups only,
never routing or credentials, and an explicit model_overrides entry still wins.

Closes the remaining atoms of #112649 (docs: providers page).
2026-09-17 08:53:48 -07:00
teknium1 cdc4fc4c8f fix(kanban): only a handoff to a different profile lifts the active_pr guard
The handoff exemption treated ANY `assigned` event after the PR comment as a
handoff. A no-op same-profile assign (`hermes kanban assign <id> dev`,
dashboard PATCH /tasks/{id}, `reassign --reclaim`), an unassign
(`assignee: null`), and the dispatcher's own `kanban.default_assignee`
fill-in all record an `assigned` event without changing the owner — and each
lifted `active_pr` for the very implementer that opened the PR, re-spawning
it against its own PR. That is the duplicate-work protection #111910 says
must be preserved.

`assign_task` now records `from` in the payload and the guard counts an
`assigned` event as a handoff only when it moves the card to a different,
non-null profile and was not written by the default-assignee pass. Events
without `from` (pre-existing rows) are not trusted — fail closed.

Docs sentence qualified accordingly.
2026-09-17 08:52:53 -07:00
teknium1 2e805005ea fix(kanban): active_pr respawn guard no longer holds a card handed to a closer or back to its implementer
A ready card whose recent comment links a GitHub PR is held by the
``active_pr`` respawn guard for every assignee. That stopped exactly the
spawns the PR evidence calls for: an operator reassigning the card to a
closer/recovery profile, and a reviewer's changes-requested verdict
routing it back to the implementer to fix that PR — the card sat in
``ready`` as ``respawn_guarded=active_pr`` with zero workers (#111910).

``check_respawn_guard`` now lifts ``active_pr`` when a handoff event
(``assigned``, ``changes_requested``, ``review_reopened``) was recorded
strictly after the newest PR comment: the handoff names the profile that
must work on that PR, so it is not a duplicate implementation. Duplicate
protection is kept: no handoff (a crash/reclaim is not one) leaves the
opener guarded, a newer PR comment after the handoff guards again,
same-second ties stay guarded, and ``recent_success`` is untouched. The
review-lane exemption from a235d1917e stands unchanged.

Docs: the kanban respawn-guard section names both supported routes
(``request-review`` and ``assign``).
2026-09-17 08:52:53 -07:00
kshitijk4poor 38870824ad docs(config): the config RLock comment names its real reason
The comment said the lock is an RLock because save_config internally
calls read_raw_config. After the previous fix that is no longer true:
save_config takes its raw mapping from require_readable_config_before_write
and never re-enters the lock through read_raw_config.

The reentrancy that still exists is external: hermes_cli/plugins.py holds
_CONFIG_LOCK across its read-modify-write and then calls save_config(),
which acquires the lock again. Name that, and leave the RLock as is.
2026-09-17 21:19:47 +05:30
kshitijk4poor 8b9c0b63e7 fix(config): save_config takes explicit paths from the fail-closed read
save_config() called require_readable_config_before_write() -- which parses
config.yaml fresh, uncached, and returns the mapping -- then threw that
mapping away and re-read the file through the cached read_raw_config().
That second read can return {} while the file is intact:
_read_raw_config_impl returns {} from its two swallowed-error paths (the
`except (FileNotFoundError, OSError)` around stat and the `except Exception`
around open/parse), so a transient stat/open error on an intact file yields
{} for this call. A {} here leaves _strip_default_values with no
explicit-path evidence, so every user section whose value matches a schema
default is dropped: the 32 -> 7 section collapse in #113301.

Use the mapping the fail-closed read already returned as _raw_for_paths.
One read, one authority, and a truly empty or missing file still behaves
as a first install (only explicit keys written, no raise).

Reported via #113321 (@kvnloo, first submitter) and #113323 (@nolanchic);
both proposed a different mechanism (skip strip-defaults / raise) -- see
PR. Skipping the strip pass writes every schema default into config.yaml;
raising when the cached read is empty would break edit_config's save over
an empty file and a fresh install. The per-save sys._getframe caller log
from #113323 is out of scope (#96571) and not taken here.

Fixes #113301
Credit: #113321 (@kvnloo), #113323 (@nolanchic)
2026-09-17 21:19:47 +05:30
teknium1andHarry Riddle 1539a1a9da fix: goal loop names the Nous auth failure instead of an opaque judge error
With auxiliary.goal_judge.provider pinned to nous and a dead refresh token
(invalid_grant), the status line read "judge error: RuntimeError": the ladder's
_resolve_nous_runtime_api swallowed the resolver's AuthError at DEBUG and the
generic "no API key" RuntimeError was reduced to its type name by judge_goal.
Users were sent to context-length / model debugging instead of `hermes model`.

Now the failure is remembered in agent/auxiliary_unavailable.py (one WARNING per
distinct message, preferring the persisted quarantine marker because the pool
rung wipes the dead tokens before the auth-store resolver runs), the ladder
raises AuxiliaryClientUnavailable carrying that detail for provider=nous, and
judge_goal maps it to
"goal_judge auxiliary client unavailable: Nous Portal runtime credentials
unavailable: Invalid refresh token. Run `hermes model` to re-authenticate.
(code: invalid_grant)" while still failing open with the same 5-tuple contract.

Slim redo of #42179 for the current call_llm-based judge_goal.

Fixes #42177

Co-authored-by: Harry Riddle <ntconguit@gmail.com>
2026-09-17 08:49:38 -07:00
kshitijk4poor 2cf1351779 fix(config): the custom-top-level footer prints only for top-level keys
_print_unknown_key_notice always appended "Custom top-level keys are supported and bridged to
the environment". Before the unseeded-key change no nested path reached this notice; now
`stt.provider` or `agent.max_turnz` did and were told they are env-bridged, which they are not.
Nested paths get only the --force hint.
2026-09-17 21:19:22 +05:30
kshitijk4poor c107114652 fix(config): a structural wrong-prefix match beats a fuzzy sibling suggestion
In _validate_config_key the fuzzy same-level sibling (cutoff 0.6) was tried before the
structural "path minus its wrong prefix is a known key" check. While every unknown sub-key was
refused that order did not matter; now that only the wrong-prefix case is refused, a path whose
stray middle segment fuzzy-matched a sibling was WRITTEN with a misleading did-you-mean:
`agent.gateway.strict` -> (False, 'agent.gateway_timeout') instead of being refused as
`gateway.strict`. A structural match is proof, a fuzzy match is a guess; check it first.
2026-09-17 21:19:22 +05:30
kshitijk4poor f537076738 docs(config): config set docs describe the wrong-prefix-only refusal
The CLI reference, the configuration guide and the set_config_value
docstring still said that any unknown path under a known section is
refused with a did-you-mean. After b47f40e699 only a path whose suffix is
itself a known key (gateway.discord.foo -> discord.foo) is refused; every
other unknown path under a known section — a same-section typo or an
unseeded runtime-read key — is written with a did-you-mean notice, because
DEFAULT_CONFIG is an incomplete schema and cannot tell the two apart.

Reword all three sites to state the refusal that actually exists and the
write-with-notice fallback, so users are not told a typo will be blocked.
2026-09-17 21:19:22 +05:30
KoNit-K 6f11f45852 fix(config): allow unseeded runtime config keys 2026-09-17 21:19:22 +05:30
kshitijk4poor 3132ecb640 docs(sessions): recency wording matches the freshest-of rule
Prune recency is now the freshest of last_activity_at / latest message /
started_at (via _sql_session_last_active), but four doc sites still said
"latest message, else started_at": the list_prune_candidates docstring,
the --older-than/--newer-than help in session_filters, and two comments
in config_defaults. Reword them to the phrasing archive_stale_sessions
already uses so operators are not told live activity is ignored.

Also make archive_stale_sessions use the module constant _LAST_ACTIVE_SQL
instead of an inline _sql_session_last_active("s") call — same alias,
identical SQL, one fewer place to drift.
2026-09-17 21:17:15 +05:30
Gustavo Payano 06387ae8d3 fix(title): keep the derived title while skipping the model upgrade (#85194)
`auxiliary.title_generation.enabled: false` turned off both title stages, so an
operator who only wanted to stop the background model call (unavailable or
metered endpoint) also lost the instant derived title. `model_upgrade_enabled:
false` keeps the derived title and starts no `auto-title` thread; missing keeps
the two-stage default and `enabled: false` still disables both.

Salvaged from #85401 onto current main: the gate reuses `_title_config()` and
sits before `spawn_context_thread` (the thread seam moved off `threading.Thread`).
2026-09-17 08:45:08 -07:00
teknium1 290bdc3c76 fix(update): let the Windows repoint run; refuse a minor-line jump
The self-lock/holder preflight (#99711) deferred the repair on the theory
that the updater's own mapped python.exe makes the venv rename impossible.
Live on windows-latest, a process executing from venv\Scripts\python.exe
(and the repo's real .venv with cp311 .pyd extensions loaded) does NOT block
the rename; what blocks it with WinError 5 is any ordinary handle under the
tree: a process cwd, an open file, a sync client. Since sys.executable is
always under the venv on Windows, the deferral fired on every run and no
Windows install could repair from `hermes update`. Retire it and its tests;
the pyvenv.cfg repoint needs no rename and has none of that exposure. The
wine2e lane now runs the cutover probes instead.

The repoint keeps the live venv's site-packages, so provisioning's
fall-forward to the next minor (3.11 -> 3.12, #76106) must not be pointed at
a cp311 tree: refuse before touching pyvenv.cfg. The live Windows test holds
the venv the way the field does (a child with cwd inside it), asserts the
rename path fails (the symptom) and the repoint succeeds; the rollback and
minor-guard tests run on every host.
2026-09-17 08:44:33 -07:00
Gille 5a49d1de3d fix(update): repoint Windows managed runtime without renaming live venv
Cherry-pick of helix4u's #88836 (75742db5a42) resolved onto current main.

The POSIX runtime cutover parks the live venv with a directory rename. On
Windows that can never succeed from `hermes update`: the updater executes
from venv\Scripts\python.exe and Windows keeps that image mapped, so the
rename fails with WinError 5 on every attempt (#93032). Instead, atomically
replace the live venv's pyvenv.cfg with the candidate's: Scripts\python.exe
is a launcher that reads `home` on every start, so every fresh process runs
the new generation while nothing touches the locked directory. A failed
post-cutover smoke restores the original config; a failed rollback keeps
the generation the live config now references.
2026-09-17 08:44:33 -07:00
teknium1 032cf8438f fix(update): scope the installed-bundle refresh to macOS, keep the signature, never swap under a live app
Rework of the salvaged #59942 hook so it fixes the whole #52339 class without
regressing what the Desktop updater already gets right:

- macOS only. The Windows arm rmtree'd a possibly-running NSIS install
  (partial deletion under a lock) and windows.ps1 already owns that swap;
  Linux packages stay with their package manager.
- No re-sign. The rebuilt release/ bundle already carries the stable local
  signing identity from _desktop_macos_relaunchable_fixup; a deep `codesign -s -`
  on the installed copy replaced it with a fresh ad-hoc cdhash and reset every
  TCC grant. ditto preserves the signature, so nothing is signed here.
- Running bundles are reported, not swapped: Electron loads app.asar and helper
  apps lazily, so renaming the bundle away and deleting the old tree crashes
  the live app. The detached updater waits for exit; a terminal `hermes update`
  with the app open now prints what to do instead.
- Failures are printed as warnings; the old `Path | None` return read every
  failure as "Desktop app up to date".
- The refresh also runs on the "build stamp current" path, so a stale
  /Applications copy left by an earlier update heals on the next `hermes update`
  even when there is nothing to rebuild.
- Core is host-independent (_install_rebuilt_macos_bundles takes paths as data);
  the two invariant tests run on every OS instead of `skipif(darwin)` tests that
  ran nowhere.

Covers the Desktop-button path too: posix.sh runs `hermes update`, so an app
running from apps/desktop/release/ now refreshes the /Applications copy Finder
launches (the Discord report: new shell right after the update, old shell on
the next Dock launch).
2026-09-17 08:44:06 -07:00
Yingliang Zhang d49fda1d15 fix(desktop): install rebuilt app to system location after CLI hermes update
Port of #59942 onto post-#102117 main. The refactor moved the desktop
helpers from hermes_cli/main.py into hermes_cli/main_desktop.py, so the
new install machinery (_app_asar_hash, _macos_adhoc_sign_bundle,
_desktop_bundle_install_supported, _swap_in_new_macos_bundle,
_install_rebuilt_desktop_app) lives there now, re-exported through
main.py's frozen updater surface block so _m() resolves them.

_rebuild_desktop_after_update (hermes_cli/update_cmd_deps.py) now, on a
successful --build-only build, installs the rebuilt bundle to the
system location (macOS .app via ditto staged copy + atomic swap with
rollback; Windows via copytree), skipping when the installed app.asar
hash already matches. Linux stays owned by its package mechanism.

Without this, a CLI hermes update leaves the installed app stale —
the in-app updater covers its own path, but the CLI path never swapped
the installed bundle.

Tests: 17/17 ported suite (import/patch targets repointed to
main_desktop) + test_cmd_update.py 47/47 green.
2026-09-17 08:44:06 -07:00
kshitijk4poor ffab36579a refactor(gateway): idle gates live in run_idle_gates; row semantics live with loops/heartbeat
The probe helpers had been appended to the gateway/run.py facade and the three watchers each
carried their own copy of the "probe → fail open → offload" shell, with gateway code parsing
loop/heartbeat rows itself. One sibling now owns the gate shape (_gate + off_loop_gate), and
hermes_cli.loops.store_has_active_loop / hermes_cli.heartbeat.store_has_active_heartbeat own
what an ACTIVE row is (heartbeat gains the _META_PREFIX loops already had). One fail-open layer
per read: has_pending_handoffs is a bare bounded query, the gate catches. The loop watcher calls
its executor hop directly — it already did so unconditionally for the scan, so the
"runner without a hop" fallback there was dead.
2026-09-17 20:56:27 +05:30
kshitijk4poor 6b4aaaf2e2 refactor(config): load_env is a thin wrapper over the memoised tokenizer
load_env() kept its own (path, file_signature) memo on top of load_env_file(), which now memoises
on the same key: two stat calls and two caches to keep coherent for one answer. Drop the outer
layer; invalidate_env_cache() stays as the writers' knob and forwards to the one memo.
2026-09-17 20:56:27 +05:30
Alexander Russell 0d6fec59d4 fix(secret_scope): memoise the shared .env tokenizer once per file change
load_env_file() is now the canonical .env tokenizer after c849bc383a collapsed
six hand parsers onto it. Profile scopes, dashboard boundary discovery, skill
secret capture, managed .env and setup readers share the same decoding and
parsing rules, but direct calls still re-read and re-parse the whole file.

build_profile_secret_scope() puts that work on the gateway's hottest paths:
every turn, every cron job, MCP and browser lifecycle adoption, the TUI prompt
turn, and the 60s housekeeping drain of the durable cron delivery queue.
Memoising the shared tokenizer now removes redundant work for the consolidated
readers as well as the motivating profile-scope path.

config.load_env() keeps its existing outer memo over a call that is now itself
memoised; this leaves its menu-render shortcut intact without redesigning it.

Freshness is the hard part, because a stale credential map is a far worse
failure than a slow one. Every load_env_file() call still OPENS the file and
keys on os.fstat() of that descriptor rather than os.stat() of the path:

  * the open preserves close-to-open revalidation on NFS;
  * an open or read failure returns {} without caching it, and drops any warm
    entry so a transient EACCES cannot become a persistent empty profile;
  * the descriptor pins one inode, so a symlink repointed mid-read cannot file
    one file's contents under another file's identity.

The key is (mtime_ns, size, inode, device), re-checked on the same descriptor
after reading. A rewrite through that inode is not stored under the pre-read
fingerprint. Unavailable metadata means "do not cache", never "cannot read".
A generation counter checked under the lock prevents a slow reader from
repopulating an entry that a writer invalidated while the read was in flight.

Read bytes from the open descriptor and preserve upstream's decoding exactly:
strip a UTF-8 BOM before trying UTF-8, then fall back to latin-1 for invalid
UTF-8. Both the cached reader and the uncached reference use that decoder and
the shared text parser. Invalid UTF-8 is a cacheable result, not a read error.
The value and inline-comment helpers remain local to secret_scope.

invalidate_env_cache() clears this memo too, so save_env_value,
remove_env_value and sanitize_env_file invalidate both layers. The per-path
LRU holds at most 64 entries and every caller gets its own dict.

Accepted limitation: a write keeping length, inode and nanosecond mtime all
identical is not detected without explicit invalidation. This is a new
limitation for previously uncached readers. Parsed secrets also remain
reachable in memory between use and eviction for up to 64 paths, where the
outer config memo holds one.

The pre-rebase measurement on a 508-line, 25432-byte .env was 0.868 ms ->
0.011 ms per call. That measurement predates the shared binary decoder.

Add decode/cache invariants for BOM and plain files, latin-1 fallback,
same-size writes switching UTF-8 -> latin-1 -> UTF-8, and agreement with the
uncached reference. All eight decoding, cache and freshness mutations fail
the new tests, and all 40 cache tests pass after restoration.

The requested agent, CLI, cron and gateway suites report 30,168 passed,
479 failed and 303 skipped in the restricted local environment. All 140
failing files were checked against upstream/main at 5eb99eb284: all 479
failed-test IDs and 210 collection/setup/teardown error IDs match exactly.
2026-09-17 20:56:27 +05:30
Ayush Nangia 3277a6b22e fix(dashboard): route search hits to their owning profile 2026-09-17 20:33:31 +05:30
kshitijk4poor 1e32d86ee4 refactor(cli): gate the macOS file-url read on one clipboard-info listing
The save path ran `the clipboard as «class furl»` unconditionally after
`clipboard info` had already shown no bitmap, so a text-only clipboard
cost one extra osascript spawn per save (3 vs 2 on main) — and that
spawn is a pasteboard *content* read, the access class behind the
macOS "pasted from" banner (#75150). `_macos_osascript` now lists the
pasteboard once and dispatches: bitmap → PNGf script, furl → file copy.

Also: one `_osascript` helper replaces two hand-rolled run/swallow
bodies; `_macos_has_bitmap` takes the listing (no fetch-if-None mode);
`os.path.isfile` replaces the try/except around `Path.is_file`; drop the
speculative `.strip('"')` (osascript prints POSIX paths unquoted);
`shutil.copyfile` instead of read_bytes/write_bytes; the Windows
file-drop extension literal is derived from the shared set.
2026-09-17 18:36:22 +05:30
xxxigm 045778e3f9 fix(cli): attach macOS clipboard images copied as files
Finder copies only put a file URL on the clipboard, so /paste and Ctrl+V
reported no image while other apps could still paste it.
2026-09-17 18:36:22 +05:30
teknium1 a08dee94c1 fix: read plugin-home config through the loader; register update export
The config-read guard forbids raw yaml loads of config.yaml outside owner
modules, and hermes_cli.main's frozen lazy-export surface must list every
update_cmd symbol it proxies.
2026-09-17 00:11:27 -07:00
teknium1 6ac3ff8867 feat(plugins validate): fail trees with nothing to load; check dependency declarations
A plugin.yaml with no __init__.py, desktop/plugin.js or plugin.json beside it
installs "successfully" and does nothing (pip-layout repos whose code sits under
src/ behind an entry point). The validator and catalog CI now fail that shape
and check declared Python dependencies parse and are index specs; direct-URL
requirements warn.

Tests: conflicting candidate refused with peers untouched; post-update re-apply
drops only the culprit and keeps the memory provider. Loader wording test
updated to the new hint.
2026-09-17 00:11:27 -07:00
teknium1 96e8a23222 feat(plugins): install declared Python dependencies and re-apply them after hermes update
A directory plugin's pyproject.toml [project].dependencies (or manifest
python_dependencies) are now installed into the Hermes venv on install/enable/
update, resolved under a constraints file built from Hermes' own pinned
dependencies together with every enabled peer's declarations. A candidate that
cannot resolve is refused before its tree is moved into place; nothing is
installed and no other plugin is touched. --no-deps opts a single install out.

hermes update rebuilds the venv from Hermes' lock and strips everything else, so
its git, zip and both repair paths now re-apply the union of every profile's
enabled plugins. When the union no longer resolves, each plugin is resolved on
its own so only culprits are dropped (never an alphabetical neighbour); a
plugin-vs-plugin conflict peels non-memory plugins first because a Hermes that
boots without memory reads as data loss. Dropped plugins are disabled through
the real config writer with a loud message naming the fix.

python_runtime: external lets sidecar-venv plugins (Mnemosyne's shape) opt out
of the union; hermes-agent self-dependencies and direct-URL requirements are
never installed (the latter are surfaced for the user to install by hand).
2026-09-17 00:11:27 -07:00
teknium1 bec8924594 fix(update): hand-off carries sibling snapshots + Windows pause token on both paths; child pinned to the parent's home
Independent review of the post-swap hand-off found state that did not cross or was
handled by the wrong side:

- update_cmd_config._LAST_SIBLING_SNAPSHOTS is rebound by the pre-update backup in the
  parent; the child read an empty dict and the sibling-profile cron/model-settings safety
  nets silently did nothing. It now rides in the payload.
- The ZIP path handed off without the Windows pause token, and the parent's finally/atexit
  resumed the paused gateways while the child was reinstalling the venv. The token now
  crosses on both paths; the parent flips resume_needed off only after a child actually ran.
- The child inherits HERMES_HOME but re-read the sticky active_profile, finishing a
  `-p default` update inside another profile's home. _apply_profile_override keeps the
  parent's resolved home for the post-swap child.
- The child env now also sets HERMES_UPDATE_REEXEC so cmd_update's Windows hard-exit tail
  covers it and the shim re-exec can never fire a second time from inside it; the
  hand-off pid is only claimed when no upstream updater (Tauri/Electron) already named
  one.
- Popen + wait instead of subprocess.run: Ctrl-C no longer kills the child (which owns the
  receipt and the gateway resume) 250 ms after the interrupt.
- A child that cannot start: the parent takes the receipt back, records the failed step,
  writes .update-incomplete and the gateway exit code, exits 1.
- The child consumes the hand-off file and builds git_cmd without re-running the checkout
  preflight (no second fork banner).
2026-09-17 00:02:09 -07:00
teknium1 32d958bcda docs(update): describe the post-swap hand-off; add its live A/B harness
hermes_cli/AGENTS.md: the update pipeline no longer runs pulled code in the pre-pull
interpreter; the receipt crosses the hand-off; purge/reload/isolate fixes are not to be
reintroduced. Stale comments in update_receipt / update_abort_recovery / update_cmd_maint
that explained the old shape are rewritten to say why the code is the way it is now.

evals/update_pipeline/post_swap_handoff_ab.sh: installs a real clone at a given SHA,
publishes a target commit whose new module-level import (a symbol added to a module the
old updater kept cached) and tagged completion line show which interpreter ran the tail,
runs `hermes update` against a disposable HOME with no npm and --no-gateway-restart, and
prints one VERDICT line. base (6005aa1f): exit 1, "Could not check config version", old
completion line. fix: exit 0, config check runs, "[completion printed by: pulled-code]",
one receipt carrying post_swap_pid.
2026-09-17 00:02:09 -07:00
teknium1 ae71d85bba fix(update): startup hint no longer blames an update that did restart the fleet
`hermes` printed "A previous `hermes update` pulled new code but did not restart
running gateways" on every launch after an update whose receipt was `failed` for a
post-restart crash: `fleet` was empty (the matrix never ran), so the check fell back to
the pre-pull `plan.runtimes[].code_sha` against today's checkout and the live gateway,
correctly restarted onto the pulled commit, still read as "not restarted" once a manual
`git pull` had moved the checkout again. Reproduced on the maintainer's box against the
#112604 receipt: gateway on the update's `post_update.sha`, checkout two pulls ahead.

The startup hint now holds a receipt whose restart phase completed (`gateway_restart`
present, `incomplete` false, no `phase_error`) to the code it actually pulled: every owed
gateway serving `post_update.sha` discharges the update. Later drift is
`gateway/code_skew.py`'s job, not a warning that misreports the update. The catch-up
predicate `hermes update` itself runs keeps its checkout semantics (the fleet must reach
HEAD), so the same box still gets its gateway restarted on the next update.

`_live_fleet_covers_receipt` compares stamped `code_sha` against the expected sha for
`current` AND `stale` rows (both labels are relative to the checkout, not to what the
update owed); `unknown`/`down` rows still never cover.
2026-09-17 00:02:09 -07:00
teknium1 94ced1a2b2 fix(update): finish hermes update in an interpreter born on the pulled code
`hermes update` started in an interpreter that had imported the PRE-pull tree, then
kept running every post-swap phase (dependency sync, Node/web/Desktop builds,
maintenance, config migration, fleet restart, verification, receipt) in that same
process, lazily importing NEW source into an OLD `sys.modules` graph. Any rename
between the two commits surfaced as an ImportError/AttributeError inside the updater
after the code swap had already succeeded (#87134, #111271, #112465, #112558, #112604).
Each incident added another purge, reload list or per-step isolation, and each moved
the crash to the next module nobody had listed.

The pre-pull process now stops at the swap: it writes the open receipt, the pre-update
fleet plan, the pre-update version/active features and the Windows pause token to a
hand-off file and re-executes `hermes update <same flags> --post-swap <file>` under the
venv interpreter. The child imports exclusively from the pulled tree, resumes the
receipt and owns the rest of the run; the parent relays its exit code. Git and ZIP paths
both hand off. On Windows, when the updater runs from `hermes.exe`, the child is spawned
detached exactly as the shim hand-off already did (the shim cannot be awaited while the
sync must replace it).

With no pulled code ever executing in a pre-pull interpreter, the stale-module layer is
dead and removed: `_purge_stale_hermes_modules`, `_stale_purge_prefixes`,
`_evict_module`, `_STALE_PURGE_*`, `_reload_updated_runtime_modules`,
`_reload_process_scan_modules`, `_reload_config_modules`, `_UPDATE_RUNTIME_RELOAD_MODULES`
and their tests. `_run_config_check_fresh` / `_run_migrate_config_fresh` keep their names
and simply call the config API.

Tests: the hand-off boundary (child argv/env, detached receipt + plan in the payload,
exit-code relay) and the child side (receipt resumed with its history, plan rebuilt,
pre-update snapshots taken from the payload). Mocked updater flows run the tail
in-process through the same payload round-trip (autouse fixture; opt out with
`@pytest.mark.real_post_swap_handoff`).
2026-09-17 00:02:09 -07:00
kshitijk4poor f7da523ae6 refactor(nous): one is_anonymous_agent seam for the five identity reads
The same two-getattr expression was spelled three ways across turn_recovery, turn_api_call
and turn_response_check. Pass _Ctx.anonymous by keyword, and rename the guard's flag now
that it means "anonymous", not "welcome route".
2026-09-17 12:28:25 +05:30
Robin Fernandes 165271fceb fix(nous): keep anonymous errors exclusive to anonymous users 2026-09-17 12:28:25 +05:30
98745df3b9 fix(serve): hold work admission through cooperative retirement
Fence accepted RPCs, side agents, continuations, delegation and cron before issuing process-bound retirement permits.

Co-authored-by: chelsealong <chelsealong@126.com>
Co-authored-by: Mark Sheppard <mark@orchardstreetpress.com>
2026-09-17 00:34:50 -05:00
Austin Pickett 3eface06f7 fix(serve): expose turn_in_flight as an idle proof for pooled backends
The Desktop pool caps local `hermes serve` children and holds each child's
slot lease for its lifetime. Its renderer refreshes lastActiveAt every 60s
for every open socket, so a bot-tile-pinned resident is keepalive-fresh
forever: occupied is not busy, and the pool cannot tell the difference. The
renderer's own turn bookkeeping cannot see cron fires (HERMES_DESKTOP=1 runs
the in-process ticker), messaging turns served by a pooled backend, or a
session blocked on an approval, so it is not a safe proof either.

Add `GET /api/health/idle` (token-gated; whether a turn is running is
activity recon, unlike the public liveness route) returning
`idle: true|false|null` from `hermes_cli/web_server_idle_proof.py`. It
reuses the SSH idle-exit primitive `turn_in_flight()` (running gateway
sessions + running cron jobs) and adds the human-input ledgers: open
server->client requests (`server_requests.open_request_count`) and queued
gateway approvals (`approval.pending_gateway_approval_count`). Any ledger
that cannot be read yields `null`, which the Desktop treats as busy.

Tests: unit invariants over the fail-closed table and the real ledgers, and
a live test that boots three desktop-shaped children (HERMES_DESKTOP=1,
per-child HERMES_HOME, port 0), holds one busy in the cron running-job
ledger, and probes all three over HTTP. RED on base: every child 404s.
2026-09-17 00:34:50 -05:00
Jeffrey Quesnelle abc19b1349 Merge pull request #111002 from codeJRV/jibinv/improve-hermes-desktop-loading
perf(desktop): reduce Windows startup I/O and blocking checks
2026-09-17 00:32:12 -04:00
emozilla 2094265047 fix(desktop): preserve source freshness and console diagnostics
Remove metadata-only source caching so mapped edits and transient read
failures cannot leave stale rebuild decisions. Keep directory pruning,
lazy npm lookup, renderer manifests and the COM scheduler query.

Separate stdout and stderr logging, decode bounded logical lines before
redaction, and route desktop records to the GUI log. Add real-child,
mapped-write and temporary-read-lock regressions.

Verified by independent review, targeted Windows/Linux suites, renderer
tests and packaged Windows manual checks. Existing Windows logging
failures reproduce on the parent; no end-to-end startup percentage is
claimed for this corrected version.
2026-09-16 23:13:20 -04:00
Jeffrey Quesnelle 6005aa1fd9 Merge pull request #112443 from RyanUnderhill/codex/fix-runtime-archive-cache
fix(local-runtime): reject incomplete downloads before caching
2026-09-16 21:32:45 -04:00
teknium1 391a7007fb fix(cli): hermes -z exits non-zero for partial, failed and interrupted runs even when text was printed
`hermes -z` judged the run by whether stdout was non-empty: a turn that hit the
iteration budget, ended `partial`, failed on the provider, or was interrupted
still exited 0 as long as it printed an explanation, so scripts treated a
half-done job (or a 401 summary) as success. The `-q`/`-Q` paths already got
one result-derived contract in 23863ccbafe0d; this is the same class on the
scripted one-shot entry point (#111770).

- `hermes_cli/oneshot.py::_oneshot_exit_code`: 0 only when the turn completed;
  130 interrupted; 2 failed / partial / completed:false; 1 a completed turn
  with no text (unchanged message).
- `--usage-file` now also reports `partial`, `interrupted` and
  `turn_exit_reason`, so a pipeline can tell a budget stop from a Ctrl-C.
- Docs: `hermes -z` exit-code table + usage-file fields in cli-commands.md.

Live probe (run_oneshot with a stubbed _run_agent): partial-with-text 0 -> 2,
budget-with-text 0 -> 2, interrupted-with-text 0 -> 130, failed-with-text 0 -> 2;
completed 0 -> 0 (control), partial-no-text 2 -> 2 (unchanged).
2026-09-16 18:12:34 -07:00
beardthelion c347e50936 fix(setup): let SSH wizard reset a saved port back to 22
The port prompt deliberately skips saving the default, but skipping the
save never removed a previously stored TERMINAL_SSH_PORT, so answering
"22" silently left the stale port in .env while the wizard's own
connection test used the entered value. Remove the env value when the
user enters the default so the runtime default applies.
2026-09-16 17:57:48 -07:00
teknium1 2452b882ad fix(cli): no false "[HERMES_HOME fallback] wrong profile" warning on every command
Users who set a sticky profile with `hermes profile use <name>` saw
`[HERMES_HOME fallback] HERMES_HOME is unset but active profile is '<name>'
... Any data this process writes will land in the wrong profile` printed by
EVERY `hermes` invocation (`--version`, `update`, `gateway restart`), even
though the CLI re-homes to that profile a few lines later and nothing lands
in the wrong place.

`main._apply_profile_override` scans argv with `top_level_value_flag_sets()`,
which builds the real parser BEFORE the override sets HERMES_HOME. Since
23036e20a6 the `--no-config` help string spells the config path through
`display_hermes_home()` -> `get_hermes_home()`, and that lookup fires the
one-shot fallback warning for a throwaway help string.

`display_hermes_home()` takes an optional `home`; the parser's `_cfg_path()`
passes `get_process_hermes_home()`, which reads HERMES_HOME without the
warning and, after the override, IS the profile home — so `hermes -p coder
--help` still shows `~/.hermes/profiles/coder/config.yaml`. The genuine
warning (a process that really runs under the wrong home) is untouched.

Fixes #112319
Part of #112839
2026-09-16 17:51:11 -07:00