Commit Graph

107 Commits

Author SHA1 Message Date
kshitijk4poor
c2b1e4391c refactor(process): one release-once-empty helper; the kernel and slash-worker tests stop racing a loaded host
LSP, the code kernel and the slash worker each had their own "release the group once nothing in
it is left" (a killpg(pgid, 0) probe; the kernel's version also waited for reaps). They are now
one helper, process_identity.release_process_group_once_empty(pgid, proc=, timeout=). It polls
the leader so a zombie leader does not keep the group alive, waits up to `timeout` for killed
members to be reaped by init, and keeps covering a group that still has a member. LSP's async
close path probes once (timeout=0), as before.

The slash worker used to probe exactly once right after SIGKILL. On a loaded macOS host (load
25+) init had not reaped the killed members yet, so a group that was about to be empty stayed
registered (test_close_stops_the_whole_group_then_releases_it, flaky). It now waits up to 1 s,
like the kernel did.

The kernel survivor test raced too: under load the cell child's `trap '' TERM` could land after
the teardown's SIGTERM, and the 5 s escalation could SIGKILL it. The child now signals once its
trap is installed, and the test turns escalation off (the escalation is not what it pins).

New tests/hermes_cli/test_process_identity_release_once_empty.py: an unreaped empty group is
released, a live member keeps it covered, a late exit is waited for, and Windows never releases.
Teeth: forcing the helper to always release, or to never release, turns 5 tests red in the 4
touched files. macOS: the 9 owned-child files, 78 tests, 3 runs in a row, 0 flaky.
2026-10-29 16:58:09 +05:30
kshitijk4poor
3d24fce471 fix(lsp): a language server's whole process tree dies with its Hermes owner (orphans_after_30s 1 -> 0)
Symptom: LSPClient starts every language server in its own session (start_new_session=True) so a
killpg aimed at the server can never reach Hermes. That also took the server's descendants out of
Hermes's kill domain. The server itself exits on stdin EOF when Hermes dies, but a descendant that
neither holds nor watches that pipe (a wrapper's background child, a SIGTERM-ignoring worker)
outlived a SIGKILLed / OOM-killed Hermes forever. The atexit hook and the idle reaper both live
inside the owner, so neither runs on that path.

Change: _spawn hands the server's process group to the per-process owner-death supervisor
(own_process_groups) and records it in the spawn ledger (register_child "lsp-server").
_cleanup_process hands the group back only once nothing in it is left, so a member that survived
teardown stays covered and still dies with Hermes. No new process: the supervisor is shared with
every other owned child. The atexit hook stays: it runs the LSP shutdown/exit handshake on a
clean exit, which the supervisor's TERM/KILL does not replace. Windows path unchanged.

Measured on Linux (Linux), kill -9 of a real owner running LSPClient, survivors of the server
tree after 30 s:
  mock server with a SIGTERM-ignoring child (slow_tree), 3 trials: main 1/2 alive every trial,
  branch 0/2 every trial (gone by +5 s).
  basedpyright, pylsp, typescript-language-server (4 procs), gopls, rust-analyzer: 0 on main and
  branch (they exit on stdin EOF, and their helpers die with them).

Tests (tests/agent/lsp/test_lsp_owned_server.py): owned on spawn + released on shutdown, a
surviving member keeps coverage, a real kill -9-the-owner end to end, and a live-owner control.
Removing the own_process_groups call turns 3 of them red; making the release unconditional turns
the coverage test red.
2026-10-29 16:58:09 +05:30
Teknium
ff6a08c96f fix(lsp): each edit is diagnosed on the bytes it wrote, never on another session's later write
A write's LSP check runs on the LSP loop after the tool result returns, and it re-read
the file from disk when it got there. If another session wrote the same file in
between, the first session's check diagnosed the second session's bytes. With the real
typescript-language-server: session A changes `x: number = 1` to `2` (clean), session
B changes it to `"bad"` (TS2322). Both sessions were told about 2322, each attributed
to its own edit. Session-keyed queues stop takeover, but nothing tied the checked
bytes to the session that owned them.

Each check now carries an immutable snapshot of its edit: the pre-edit content (the
baseline, as before) and the post-edit content the write produced. `_check` syncs
the post-edit snapshot for the verdict, so the verdict only covers bytes that session
wrote. Afterwards the server is re-synced to the newest content written to the file
(recorded when the newest check is scheduled), so editor state and the next check's
baseline still follow the disk. Same-session coalescing is unchanged: a newer edit by
the same session still takes over an unfinished check and diffs against its baseline.
Supplied text is normalized the way the disk read decodes it (BOM, CRLF, undecodable
bytes), so a snapshot and its file sync identically and baseline-cache hits survive.

Test: test_each_session_is_checked_on_the_bytes_it_wrote holds the LSP loop, makes
A's clean edit and B's erroneous edit to one file, then releases. A must hear nothing
and B must get its error. Red on 22a383286c (A gets MOCK001), green here.
2026-10-17 04:23:04 -07:00
Teknium
f8536de78c fix(lsp): late diagnostics stay with the editing session; fixed errors do not come back
Review findings on the deferred edit check:

- Diagnostics reached the wrong session: unfinished checks were keyed by file path alone, so session
  B's edit took over session A's check, A's verdict was dropped and B was told about A's error.
  Checks of one file are still serialized (tail per file), but a check takes over (baseline, carried
  notes, result) only an unfinished check of the SAME session, keyed (session, path).
- Fixed errors returned as warnings: a superseded check with no verdict returned None, losing its
  superseded state, and its callback restored the older note it had withdrawn even though the newer
  check had taken it over; a clean newer verdict then left the stale note queued. Withdrawn notes now
  travel with the check (CheckResult.carry) and are handed back only by the check that ends without a
  verdict and was not superseded; a superseded check never posts or restores.
- Baseline cache always missed: this edit's verdict replaced the file's cache entry before the
  pre-edit verdict was looked up. The lookup now happens first; the new verdict (unfiltered) is
  stored after, so the next edit's baseline is a cache hit (2 -> 1 verdict round trips per edit with
  diagnostics).
- Cleanup had two owners: edit_check._mark_broken duplicated LSPService._mark_broken_for_file. The
  mark/pop/log steps live once in LSPService._detach_broken; the sync bridge and a new loop-side
  _mark_broken_for_file_async differ only in how they await the shutdown.
- Tests depended on machine timing: the by_content mock server now holds every push until the test
  touches a gate file, so the invariant tests assert order (the tool result returns before any
  verdict exists) with a 20 s wait budget and tests.waiting.wait_until; the native hash test carries
  platforms("posix"). New test: two sessions editing one file each get only their own diagnostics
  (red on f980eca8e4: "session B was told about session A's error").
2026-10-17 04:23:04 -07:00
Teknium
eb8a135063 fix(lsp): type errors reach the model inline or before the turn ends; writes stay under ~0.1s
With 88107d448c the write never waited on the language server: a verdict slower than ~50ms rode the
session's next tool result or next user turn.  Live, a planted TypeScript error made by the turn's
last edit was lost: tsserver pushed its verdict 0.4s after the final tool result, and a one-shot
`hermes chat -q` has no next turn (the model answered TYPE_ERROR_SEEN=no; origin/main saw it, at 10s
per write).

- agent/lsp/sync_diagnostics.py: typescript-language-server answers `typescript.tsserverRequest`
  syntactic/semanticDiagnosticsSync for the synced text (measured ~10-30ms warm), so the edit check asks
  it directly instead of waiting for a push that may never come.  pyright already answers the
  document pull in ~10-90ms.  The inline window is now the whole 80ms write budget, so the warm common
  case is reported in the write's own result.  Servers without a synchronous request keep the push wait.
- agent/lsp/deferred.py + agent/turn_stop_gates.py: checks still running are tracked per session.  When
  the model gives a final answer, the stop gate waits for them (at most 5s) and hands any undelivered
  verdict to the model as a new user-role message, continuing the turn (max 3 per turn).  The message is
  a durable row appended after the answer, so no earlier byte changes and the prompt cache holds.
2026-10-17 04:23:04 -07:00
Teknium
fb55eb6d34 fix(file-tools): patch/write_file return in milliseconds; LSP diagnostics no longer block the write
Measured on origin/main with the default LSP config (enabled, document, wait_timeout 5.0), real
handle_function_call, warm servers:
  - a clean .ts edit took 10.1s: the pre-write baseline wait and the post-write wait each ran to the
    full 5.0s, because typescript-language-server publishes nothing when a file's diagnostics stay
    empty and its first push after didOpen is a seed that never counts as fresh;
  - wait_for_diagnostics re-sent textDocument/diagnostic in a tight loop on push-only servers
    (~326k iterations per 15s of waiting on the LSP loop thread);
  - a 16k-line .py edit took 2.9s (pyright's analysis time, paid inline, plus a baseline round trip);
  - even with LSP off every write paid ~100ms for three bash spawns (probe, atomic write, sha256sum),
    and patch ran the syntax lint twice.

Now:
  - the write never waits on the language server.  One coroutine per edit (agent/lsp/edit_check.py)
    syncs the written file and waits for its verdict; only when that verdict has diagnostics does it
    fetch (or reuse) the verdict on the pre-edit text the write already holds, so a clean edit costs
    one round trip.  The write waits for that verdict only while it stays under ~80ms; otherwise the
    verdict is queued for the editing session (agent/lsp/deferred.py) and attached to its NEXT tool
    result, or the next user turn, via the plugin live-notes channel: a new row, never a rewrite of an
    earlier message, so the prompt cache is untouched.
  - checks of one file are serialized and coalesced; a newer check inherits an older one's baseline,
    so errors an earlier edit introduced are still reported unless a later edit fixed them.
  - wait_for_diagnostics sends the pull once and stops pulling on servers that reject it.
  - the local POSIX backend writes, probes and hashes in-process (tools/file_operations_native.py),
    under the native-read gate (HERMES_NATIVE_FILE_READ=0 restores the shell path).
  - patch reuses write_file's lint result instead of re-linting.
2026-10-17 04:23:04 -07:00
Maciej Lisiewski
2ff58849f4 ci: ruff UP037 fixes 2026-10-09 17:34:38 +02:00
Maciej Lisiewski
aff64c3eeb ci: UP007, UP022, UP028, UP031, UP041 linter fixes 2026-10-09 17:31:52 +02:00
Maciej Lisiewski
74f1f17a7e ci: fix RUF017, RUF018, RUF022 2026-10-08 19:54:07 +02:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
kshitijk4poor
da2b64304b fix(lsp): no automatic trust for scheduled work; lock-free trust lookups
Re-review of the trust-anchor follow-up:

- Cron runs and Kanban workers no longer anchor trust. The cronjob tool
  lets the model pick a job's workdir, which becomes the run's session
  cwd, and kanban_create lets it pick a task workspace, which becomes the
  worker's launch dir and TERMINAL_CWD. Either one let an agent-cloned
  repo become trusted. Both now rely on lsp.trusted_workspaces only.
- A repository at or above $HOME never anchors, not only one at $HOME
  exactly.
- Operator roots are recorded only where a tool thread enters
  (enabled_for) and when the service is created. _trusted() is now a pure
  read. Before, it took _state_lock while two of its callers already held
  it, so a change in the roots could deadlock the LSP loop.
- Client lookups go through _live_key(). A multi-root client that
  started while its root was untrusted is still found and released after
  the root becomes trusted, instead of being orphaned.
- `hermes lsp status` stops listing roots that have since become trusted.
  The lint gate reads the cwd the same way the linter subprocess does.
- The path-list parser returns None for a malformed value, and each key
  logs its own warning. The _node_modules_trees docstring no longer
  mentions Vue.
2026-09-29 03:28:46 +05:30
kshitijk4poor
8ee5305fdb refactor(lsp): declare svelte's untrusted switch on the registry and share the path-list parser
svelte goes back to the declarative _server() form with an untrusted_init
option on _simple_spawn instead of a one-caller spawn factory, the two
lsp path-list keys share one parser (only the invalid-value result and the
message differ), and the docs say the allowlisted servers run no project
code rather than that they only parse files (yaml-language-server fetches
the schemas a file names).
2026-09-29 03:28:46 +05:30
kshitijk4poor
09d14ea130 fix(lsp): keep vue-language-server out of untrusted workspaces
Pinning `tsdk` to Hermes's TypeScript does not stop Vue from running
project code: @vue/language-core 2.2.x reads `vueCompilerOptions.plugins`
from the project's tsconfig and require()s each entry resolved against the
project root (lib/utils/ts.js, the 'plugins' case), so a cloned repo naming
"./x.js" there executes it on the first .vue edit. Vue now waits for trust
like the other servers that evaluate project files, and `_spawn_vue` reads
the project's node_modules again (it only ever runs trusted).
2026-09-29 03:28:46 +05:30
kshitijk4poor
e929702021 fix(lsp): trust the workspace the session was opened in, not only the process cwd
The trust anchor was os.getcwd(), which is the user's project only for a
plain `hermes` launched inside a repo. `hermes -w` sets TERMINAL_CWD to its
new worktree without a chdir, the Desktop/TUI backend runs from the install
tree or $HOME with the project bound as the session cwd, the gateway runs
from HERMES_HOME, and cron binds a per-job workdir. All of them lost
pyright's project venv, rust-analyzer/gopls/jdtls/... and the .ts/.rs lint
fallbacks inside the user's own repository.

operator_workspace_roots() now adds the worktree of resolve_agent_cwd()
(session cwd, then TERMINAL_CWD) to the launch dir's; only surfaces set
those, the agent's `cd` moves the terminal env's cwd, not them. $HOME is
never an anchor: a dotfiles repo there would trust every directory below it.
The service remembers every anchor it has seen, because the loop thread
that spawns servers has no session context of its own.

- The lint gate checks only the linter's cwd: npx and rustup resolve the
  toolchain from there (subprocess cwd=env.cwd), not from the file's dir.
  The try/except that wrapped code which cannot fail is gone.
- Trust is computed once per spawn and handed to ServerContext.
- Multi-root servers (pyright) share one process across trusted roots
  only; an untrusted root gets its own, so whichever root spawned first no
  longer decides the interpreter for the others.
2026-09-29 03:28:46 +05:30
John Paul Soliva
59ec281140 fix(lsp): deny by default in an untrusted workspace and skip the toolchain lint fallbacks there
Pinning settings per server left every other server free to run project
code: rust-analyzer runs cargo check (build.rs, proc-macros) on each
didSave despite the disabled init options, and jdtls, kotlin-language-server,
elixir-ls, zls, clojure-lsp and haskell-language-server evaluate build
files when they start.

In an untrusted workspace only UNTRUSTED_SAFE_SERVERS now start (pyright,
typescript, vue, svelte with their pinned settings; bash, yaml,
dockerfile, intelephense, clangd without --query-driver). Every other
built-in or user-declared server is skipped at the spawn chokepoint and
in enabled_for, logged once per root and listed by hermes lsp status.
The rust-analyzer init tweak is gone: it never starts untrusted now.

On a local backend the npx tsc and rustfmt --check fallbacks are skipped
the same way, since npx resolves the repo's node_modules/.bin/tsc (or its
.npmrc registry) and rustup honours its rust-toolchain.toml.
2026-09-29 03:28:46 +05:30
John Paul Soliva
f5c754d436 fix(lsp): never run a cloned repository's own interpreter or TypeScript SDK in an untrusted workspace
Language servers start with no approval on every write_file/patch inside any
git worktree. Hermes pointed pyright at the checkout's own .venv/venv python
(pyright executes it), let Vue and typescript-language-server load the
checkout's node_modules/typescript, and left svelte-language-server and
rust-analyzer loading project config, build scripts and proc-macros.

A workspace is now trusted only when it is the git worktree Hermes was
launched in or sits under an lsp.trusted_workspaces entry. Elsewhere pyright
keeps VIRTUAL_ENV or the Hermes-managed python, TypeScript/Vue are pinned to
the Hermes-side SDK, svelte gets isTrusted:false and rust-analyzer runs
without build scripts or proc-macros.
2026-09-29 03:28:46 +05:30
dsad
ea2dae4f4e fix(lsp): strip credentials from installer env
npm and go install run third-party package code; they now start from
hermes_subprocess_env() instead of a full os.environ copy (go keeps
GOBIN, npm keeps the Hermes-managed Node path).

Ported from #55556 onto current main; the pip path now provisions
through pm.ensure_python_tool and is not part of this change.
2026-09-29 02:06:58 +05:30
Andrex Ibiza, MBA
75a97dfcfe fix(child-env): keep the scrub authoritative for the compute host and LSP servers
The compute-host supervisor spread os.environ over
hermes_subprocess_env(inherit_credentials=True), restoring every Tier-1
secret the scrub had just removed. LSP servers (third-party binaries a
write_file can start) were spawned from a full os.environ copy.

The compute host now keeps the scrubbed env plus its explicit
overrides; language servers start from hermes_subprocess_env() plus
their configured env, still wrapped by the delegation scrub.

Ported from #77528 onto current main; #70351 is the earlier fix of the
compute-host half.

Co-authored-by: zapabob <130830376+zapabob@users.noreply.github.com>
2026-09-29 02:06:58 +05:30
Teknium
a5bd246865 Old pre-decomposition import paths are gone: plugin compat layer removed on schedule (#126164)
* refactor(plugins): remove the Sep 2026 decomposition compat layer on schedule

The PLUGIN-COMPAT layer (2776813df3 + d63e380324 + 0a5164cebe) kept pre-#102117 import paths
alive for external plugins until 2026-09-14. That window closed two weeks ago; since then the loader
has already been skipping plugins that use the old paths. This removes the layer itself:

- 328 appended `PLUGIN-COMPAT` blocks (lazy `__getattr__` pointer tables, re-exported third-party
  names, restored dead definitions) and the three re-export stub modules
  (gateway/startup_watchdog, hermes_cli/observability/relay_runtime, tools/environments/modal_utils)
- COMPAT_MANIFEST.md, compat_manifest.json, scripts/check_compat_pointers.py and its lint step
- the reporting surfaces: CLI banner notice, `hermes plugins compat`, the `hermes doctor` section,
  the post-update notice, the Desktop one-time dialog, the loader's pre-import skip and the
  `plugins.allow_deprecated_imports` escape hatch

An external plugin that still imports an old path now fails to load with its ImportError as the
reason in `hermes plugins list`, the same path as any broken plugin.

hermes_cli/plugin_compat.py stays as three inert stubs (compat_report, removal_in_effect,
summary_lines): an already-running pre-removal `hermes update` lazy-imports them after the checkout
swap (tests/compat/old_updater_surface.json).

In-tree fallout, both already dead: hermes_cli/setup.py::_check_espeak_ng (no callers; its
`shutil` came from a compat block) and gateway/config.py::SessionResetPolicy ("retained solely for
the scheduled plugin-compat window"). Two test_run_agent patches targeted the removed
`run_agent.handle_function_call` pointer; they now patch `model_tools.handle_function_call`, the
seam production reads, like every sibling test in that file.

* chore: retrigger CI (zero-job startup_failure phantom)

* test: drop resolution allowlist rows for the two deleted which() sites

hermes_cli/setup.py::_check_espeak_ng (dead) and tools/skillevaluator_scan.py::scanner_available
(a restored definition inside a PLUGIN-COMPAT block) no longer exist; the stale-row gate requires
their allowlist entries go with them.
2026-09-28 10:21:41 -07:00
teknium1
b63c138d78 fix: Hermes never falls back to the user's node/npm/npx/uv
Maintainer ruling: only Hermes and only its packaged package managers
(uv/pip/node/npm) are ever used; no PATH fallback when the managed tool is
missing, no "prefer the user's if new enough".

- hermes_constants.find_node_executable: node/npm/npx resolve to PM's
  installed copy or None. Every caller already pm.ensure()s on None, so a
  missing runtime is now provisioned instead of silently borrowing the
  user's Node (native-addon ABI / npm cache mismatches).
- agent/lsp/install._install_npm: pm.ensure('npm') when PM npm is absent,
  instead of failing over to whatever npm is on PATH.
- gateway._append_node_dir_for_service: stop baking the invoker's PATH node
  dir into generated systemd/launchd units.
- main_install_repair._resolve_node_runtime_npm: drop the PATH re-scan for
  another npm.
- source_build.source_product_current: run the freshness reader only with
  PM's node.
- doctor: Node/npm rows and npm audit use PM's copies (Termux APT distro
  keeps its system Node).
- install.sh ensure_uv / install.ps1 Get-Uv: always stage the pinned uv
  artifact; delete the "uv on PATH if new enough" developer shortcut.
2026-09-27 22:04:26 -07:00
ahisblessed
77b9ea0831 fix(agent): route every model-visible elision through the non-imitable compression marker (#121548)
The #83714 fix hardened only the tool-call args renderer; five other
renderers (plus three same-idiom siblings) still composed the bare
truncation marker, which the model imitated from replayed context into
new durable writes (#83435).

This routes all model-visible elision in agent/ through shared helpers
in agent/compression_marker.py:

- elide(text, limit): head + marker cap with accurate omitted/total counts
- elide_middle(text, head, tail): kept head/tail with the middle elided

The elision marker's first sentence is byte-identical to the args marker's,
so the existing _COMPRESSION_MARKER_RE (and the dispatch-boundary guard in
tool_dispatch_helpers) rejects a copied marker regardless of which renderer
leaked it; only the tool-call-specific second sentence is dropped so the
marker still fits small caps (the clarify summary cap is 199 chars).

Routed sites:
- context_compressor.py: static-fallback turn renderer, _sum_clarify(),
  summarizer prompt builder (middle elision), active-task snapshot,
  lean user-message quotes (2 sites)
- skill_preprocessing.py: inline-shell output embedded into skill bodies
- lsp/reporter.py: truncate() for <diagnostics> tool output
- verification_stop.py: verify-on-stop nudge output summary

Regression test asserts the imitable idiom appears nowhere in agent/
strings (comments excluded), so a new open-coded renderer cannot land
silently.

Fixes #121548

(cherry picked from commit 69c63d50b4ababedf4fb4ff88c08f5d1e144a79f)
2026-09-26 23:49:25 +05:30
ethernet
0f65d698d0 Merge remote-tracking branch 'origin/main' into ethie/pm-clean 2026-09-24 13:10:14 -04:00
kshitijk4poor
42a5ae67f4 refactor(lsp): inline the one-caller subprocess stream-limit helper into LSPClient (#31417)
Co-authored-by: leavedrop <1433810735@qq.com>
2026-09-24 22:25:06 +05:30
konsisumer
d516575df3 fix(lsp): raise LSP subprocess StreamReader limit to 16 MiB
(cherry picked from commit 0768510a14693cc5cf521373e330858a5aba576f)
2026-09-24 22:25:06 +05:30
ethernet
9f2ba1b74d merge origin/main (779 commits) into ethie/pm-clean
Branch semantics kept where main and PM disagree: update_cmd_deps.py,
constraints-termux.txt, the Electron update-api-check module and the
post-swap hand-off test stay deleted; the pending-fleet-restart catch-up
and the local_runtime tag/download ladder stay retired (PM owns engines).

Ported from main onto the branch's shape: profile_scoped_chore for the
auto-archive and plugin-update housekeeping chores, the local-runtime
cross-process boot lock and residency cap, the checkpoint tmp_pack sweep,
the cua daemon-liveness status probe, the remote-served Desktop update
flag (posix.sh / windows.ps1), sign-in for env-pinned remote gateways
(urlDisabled on RemoteSetupFields), the uvloop extra split (uvicorn
without [standard]), and the umask-scoping spawn test.

uv.lock regenerated with pm.build_env --lock-only; new utf-8 reads from
main switched to utf-8-sig (check-windows-footguns).
2026-09-21 00:58:39 -04:00
teknium1
c545272568 fix(lsp): one stalled request no longer silences a workspace for good — retry window, cold-root warm-up budget, per-root exclusion
A language server that missed its budget once marked its (server, root) pair broken for the
process lifetime, the same 5 s steady-state budget was applied to a cold server that also had
to spawn, initialize and build its program, and the only escape (servers.<id>.disabled) switched
the server off for every workspace.  Three new keys under the existing `lsp` block, all defaulting
to today's behaviour:

- lsp.broken_retry_seconds (0 = lifetime): the broken set stores a monotonic retry deadline per
  pair; an expired pair gets one more try, and the INFO skip line names the retry time.
- lsp.warmup_timeout (0 = wait_timeout): the first request against a root with no running client
  waits up to this budget (outer join budget follows); warm requests keep wait_timeout.
- lsp.exclude_roots ([]): glob patterns matched against the resolved project root (a bare path
  also covers everything beneath it); a matching root never spawns, logged once at INFO.  A
  non-list value fails closed — WARNING naming the expected shape, every root skipped — because
  silently excluding nothing would re-pay the stall the key was meant to avoid.

Part of #116446 (the diagnosability slice landed in #116839, salvage of #116459 by @kokhlo).
2026-09-20 18:54:24 -07:00
teknium1
81faca2f1c fix: failed initialize keeps the LSP error type instead of raising TypeError (review follow-up)
The failure-details rewrap re-instantiated the caught exception with a single
string; LSPRequestError takes (code, message, data), so a JSON-RPC error to
`initialize` surfaced to log_spawn_failed as a TypeError with none of the exit
status / stderr details. Attach the details to the original exception in place
and re-raise. Adds an `init_error` mock-server script and one invariant test
(red on the previous head).
2026-09-20 13:54:58 -07:00
teknium1
d15b17adf5 fix(lsp): log at INFO when a request is skipped because its root is marked broken
After one timeout `_mark_broken_for_file` disables the whole (server, root)
pair for the life of the process, and every later request returned [] with no
log line at all — at default levels a skipped file and a clean file
(`log_clean` is DEBUG) looked identical, so a workspace that silently lost
TypeScript feedback was indistinguishable from a healthy one (#116446, ask 3).

`LSPService.enabled_for` — the gate every production path (snapshot,
get_diagnostics_sync, file_operations_lint) runs through — now emits
`eventlog.log_skipped_broken`: INFO once per (server, root), DEBUG on repeats,
same dedup bucket pattern as the other announce-once events.
2026-09-20 13:54:58 -07:00
Konstantin Khlopkov
b4f0553f8e fix(lsp): report server exit status and stderr tail on a failed initialize (#116446) 2026-09-20 13:54:58 -07:00
teknium1
1e9d402e07 fix: LSP tree-kill runs off the event loop (review follow-up)
kill_process_tree is synchronous (taskkill /T /F with a 15s timeout on
Windows), so the hard-kill in _cleanup_process blocked the loop for the
duration. Run it via asyncio.to_thread. The graceful path is unchanged:
shutdown() already waits SHUTDOWN_GRACE on proc.wait() after `exit`, so a
well-behaved server exits 0 before cleanup ever reaches the kill (probe:
returncode 0, no kill_process_tree call).
2026-09-20 12:54:18 -07:00
fangliquan
b773bcf271 fix(lsp): hard-kill failed server trees before reaping 2026-09-20 12:54:18 -07:00
fangliquan
bf52a9519a fix(lsp): reap servers cancelled during startup 2026-09-20 12:54:18 -07:00
liuzikaii
d23d6e8218 fix(lsp): use UTF-16 units for document replacement ranges 2026-09-20 10:24:17 -07:00
ethernet
ff92976317 fix: read package.json with encoding=utf-8-sig in the vue LSP probe (from main) 2026-09-19 13:45:57 -04:00
ethernet
d29da5fe20 Merge remote-tracking branch 'origin/main' into ethie/pm-clean
Conflicts resolved toward the branch: PM owns dependency preparation, the
Windows shim re-exec/hand-off path stays retired (main's shim-parent wait,
gateway-resume env token and update_cmd_deps tests dropped), docs describe
the PM update flow. The docker workflow parks install-stamp.json around the
toolchain step instead of deleting it so tests/docker can compare provenance.
2026-09-19 13:45:07 -04:00
teknium1
1c21a50254 fix(lsp): cap the workspace-root cache and the eventlog announce buckets (#62950)
Both are process-lifetime per-path structures with the same growth shape as the caches
this PR already bounds: _workspace_cache only cleared on service shutdown, the
(server_id, file_path) dedup bucket never. Each resets past a fixed cap (512); for the
stat cache that costs a few re-stats, for the dedup bucket one re-fired INFO line per
key, and a single clear() keeps the lock-free stat cache thread-safe.
2026-09-19 01:55:38 -07:00
teknium1
83200b359e fix(lsp): take _state_lock in _set_delta_baseline; pin the cap through the production call sites
The pop/insert/evict sequence mutates the process-wide baseline dict from arbitrary
gateway/subagent threads; on main the write was a single atomic assignment, so the cap
introduced a race (RuntimeError/KeyError past 256 entries) that would surface in the
write-tool path. Callers never hold the lock, so the helper takes it.

The cap test now drives snapshot_baseline and _apply_delta instead of the helper, so
reverting either production call site to a direct assignment is red, and asserts every
mutation runs under the lock.
2026-09-19 01:55:38 -07:00
Tikkanaditya Siddartha Jyothi
539b82698e fix: bound the LSP document cache, delta baselines, TUI fuzzy cache and the tool-call logger (#62950)
Long-running gateway/TUI processes grew four in-memory structures for their
whole lifetime:

- agent/lsp/client.py: `_docs` pinned every opened file's full text (and the
  server's mirror) until the idle reaper killed the client. Now an
  insertion-ordered LRU capped at MAX_TRACKED_FILES=64; evicted files are
  didClose'd and re-didOpen'ed on their next touch.
- agent/lsp/manager.py: `_delta_baseline` kept a pre-write snapshot for every
  path ever written; capped at 256 with write-recency eviction.
- tui_gateway/methods_complete_helpers.py: `_fuzzy_cache` only checked its TTL
  on read, so a root queried once (one .worktrees/<id> per worktree flow) was
  pinned forever; the write path now sweeps expired roots under the lock.
- gateway/run_turn.py: `logging.getLogger(f"hermes.tool_calls.{id(log_queue)}")`
  registered one permanent Logger per logged turn; a single fixed-name Logger
  with one RotatingFileHandler is shared by all turns.

Salvaged from #62934 by @Vissirexa, re-targeted onto the decomposed modules.
The per-task file-tool tracker hunks were dropped: f7a422ee4a already pops
them in AIAgent.close()/cleanup_vm via clear_file_ops_cache.

(cherry picked from commit 668f43b2ea9)
2026-09-19 01:55:38 -07:00
teknium1
06e76129cd fix(lsp): surface the pnpm failure reason and document the exotic-subdep block
pnpm prints ERR_PNPM_* to stdout, so the install warning showed an empty
reason. The composite live pass hit ERR_PNPM_EXOTIC_SUBDEP installing
@vue/language-server@2 (git-hosted transitive dep) with lsp.package_manager: pnpm;
the policy stays fail-closed, the docs now say why and how to opt out.
2026-09-19 01:55:28 -07:00
teknium1
6cf2f066a8 fix(lsp): unknown lsp.package_manager fails closed; yarn uses the global --cwd form
Review follow-up: an unknown `lsp.package_manager` value (a typo such as `pnmp`)
warned and then ran npm anyway, bypassing exactly the pnpm/yarn supply-chain
policy the option exists to enforce. It now warns with the allowed set and skips
the install, the same outcome as a configured-but-missing manager.

Yarn's argv moves to the global `yarn --cwd <staging> add ...` form, which both
Yarn Classic (1.x) and Yarn Berry (2+) accept (`add --cwd` is Classic-only), and
the docs note that Berry's default PnP linker writes no `node_modules/.bin`, so
the staging dir needs `nodeLinker: node-modules`. The test moves above the
`__main__` guard and now covers the yarn argv and the fail-closed typo case.
2026-09-19 01:55:28 -07:00
teknium1
c484be0123 feat(lsp): lsp.package_manager picks npm, pnpm or yarn for language-server installs
`_install_npm` hard-coded npm, so users who standardise on pnpm/yarn for their
supply-chain policy (minimumReleaseAge, allowBuilds, ...) could not extend it
to the LSP install path (#35448). `lsp.package_manager: npm|pnpm|yarn` (npm
default) selects the manager; the argv table `_NODE_PM_ARGV` keeps every
install inside <HERMES_HOME>/lsp/node_modules. A configured manager that is
not installed skips the install with a warning rather than silently using
npm; unknown values warn and use npm.

Ports the config shape of #70001 (@tupe12334); the request and the first
implementation (#35475, `terminal.npmCommand`) are @temalo's.

Fixes #35448
Co-authored-by: Ofek Gabay <tupe12334@users.noreply.github.com>
Co-authored-by: temalo <temalo@users.noreply.github.com>
2026-09-19 01:55:28 -07:00
teknium1
6b3005c4c8 fix(lsp): eventlog path shortener survives a removed process cwd
relpath() calls getcwd(); with the cwd deleted it raised OSError from the
DEBUG log line inside get_diagnostics_sync, so the write now succeeded but its
diagnostics were silently dropped for the rest of the process lifetime (found by
the composite live pass with real pyright). Same class as the resolver guard.
2026-09-19 01:32:28 -07:00
teknium1
311123a8da fix(lsp): inline the deleted-cwd guard and keep one real-cwd invariant test
Salvage trim of #115355: the one-line try/except lives in
resolve_workspace_for_file itself instead of a _current_dir helper, and the
regression test chdirs into a real directory and removes it (no monkeypatched
os.getcwd), so it exercises the kernel behaviour the report describes. The
helper's own change-detector test goes with the helper.
2026-09-19 01:32:28 -07:00
Konstantin Khlopkov
570b3c1a6c fix(lsp): treat a deleted process cwd as no anchor so write diagnostics never fail a landed write
resolve_workspace_for_file evaluated os.getcwd() unguarded, so after a scratch
workspace is removed under a running worker, every write_file/patch reported
[Errno 2] from the LSP enrichment step even though the write landed and
hash-verified. The resolver now reads a removed cwd as "no cwd anchor" and falls
through to the file's own worktree; _maybe_lsp_diagnostics gates through the
guarded _lsp_will_handle helper like the rest of the lint tier, so a
workspace-resolution failure degrades to "no LSP for this write".

Fixes #115342

(cherry picked from commit 6277d2a036b75881ea529e3268832a3f6262b139)
2026-09-19 01:32:28 -07:00
Sasan Sotoodehfar
51283072ad fix(lsp,gateway): give servers a grace period after exit and keep shutdown diagnostics off GNU-only tools (#72944)
- LSPClient.shutdown: after the protocol `exit` notification wait up to
  SHUTDOWN_GRACE for the server to leave on its own before SIGTERM. Every
  well-behaved server was being SIGTERMed on top of a clean exit (returncode
  -15 on Linux); on Darwin the reaped PID can already belong to another
  process.
- gateway shutdown diagnostic: run without GNU `timeout` when the host has
  neither `timeout` nor `gtimeout` (stock macOS) instead of skipping the
  diagnostic entirely; sort the `ps` listing with `sort` rather than the GNU
  `--sort` flag; fall back to `sysctl vm.loadavg` when `/proc/loadavg` is
  absent.
- s6 skeleton: chmod after chown so the setgid bit on event/ survives.

Salvages the still-open atoms of #72932 by @sasan1200 (LSP grace, portable
diagnostics, chown ordering); the BASHPID and /private/var/folders atoms
had already landed (911d380296, d4cec15b47).
2026-09-19 01:31:49 -07:00
teknium1
966959da08 fix(lsp): pin Windows wrapper resolution through _existing_binary and the pyright sibling
Review follow-up on the Windows .cmd fix: the only always-on test drove the
`_native_binary_candidates` helper directly, so reverting the production wiring
(`_existing_binary` probing npm's bin dir, wrapper-first order, `_spawn_pyright`
keeping the resolved suffix) stayed green on every non-Windows lane.

`is_windows` is now threaded as data through `_first_existing`/`_existing_binary`
(no sys.platform patch), and the test drives the production entry over an npm-shaped
staging tree (POSIX shim + `.cmd` pair under `lsp/node_modules/.bin`) and asserts
`_spawn_pyright` picks `pyright-langserver.cmd` when handed `pyright.cmd`. Each of
the three wiring reverts turns it red; the windows_only live test stays as-is.
2026-09-19 01:30:13 -07:00
BrierAinz
d6e5cda29c fix(lsp): probe Windows .cmd/.exe/.bat wrappers before npm's POSIX shim (#86445)
npm writes a POSIX `#!/bin/sh` shim under the bare binary name next to its
`.cmd` wrapper. `_native_binary_candidates` listed the bare name first and
`os.access(X_OK)` is always true on Windows, so `_existing_binary` handed the
shell script to CreateProcess (WinError 193) and `_install_npm` staged the
shim instead of the wrapper. Python/TS/YAML diagnostics were silently gone
for the whole session on native Windows.

- wrappers first, bare name last; the ordering takes `is_windows` as data so
  the invariant is testable on every host
- npm's `%~dp0`-relative `.cmd`/`.bat` wrappers stay in `node_modules/.bin`
  (a copy in `lsp/bin/` points at nothing); `_existing_binary` probes there
- PATH probing tries the wrappers before the bare name too
- pyright: the langserver sibling keeps the resolved binary's suffix

Salvages #73088 by @BrierAinz (same diagnosis and staging fix, rebuilt on
the current install.py shape).
2026-09-19 01:30:13 -07:00
teknium1
d4d9b76d8c feat(lsp): route .blade.php to laravel-lsp; plain .php stays on intelephense
`_file_ext_or_basename` used `os.path.splitext`, so `home.blade.php` became
`.php` and Blade templates went to the plain-PHP server (or nowhere useful).
Recognise compound extensions first (`_COMPOUND_EXTS`), register `laravel-lsp`
(`laravel-lsp lsp`, manual install via `composer global require laravel/lsp`)
ahead of intelephense for `.blade.php` only, languageId `blade`.

Salvages #75720 by @timoteo7 (stale against the rewritten registry; same
design: compound-extension match + manual-install entry before intelephense).

Fixes #75718
Co-authored-by: timoteo7 <timoteo7@users.noreply.github.com>
2026-09-19 01:29:55 -07:00
teknium1
894ba961cf fix(lsp): pre-write capture sees config-declared servers; e2e test goes through create_from_config
- `FileOperations._lsp_handles_extension` asks the active `LSPService`
  (`handles_extension`: config-declared servers + the built-in registry) and
  falls back to the static `SERVERS` only when no service is running. Why: it
  read `SERVERS` alone, so a file whose extension is claimed only by a
  custom server never had its pre-write content captured and the stale-
  diagnostic line-shift remap was degraded for exactly the servers #100257 adds.
- `test_service_gets_diagnostics_from_config_declared_server` now writes an
  `lsp.servers.panache` block into a temp `HERMES_HOME/config.yaml` and builds
  the service via `LSPService.create_from_config()` — the only production path
  from config to a running server — so dropping `extra_servers=custom_servers(
  servers)` from `create_from_config` goes red (it stayed green before). The
  custom-extension capture case rides in the same test.

Review follow-up on #115714.
2026-09-19 01:29:37 -07:00
teknium1
8420737a82 feat(lsp): declare custom language servers in config (lsp.servers.<id> with extensions)
An `lsp.servers` key that names no built-in server and carries `command` +
`extensions` now becomes a ServerDef (optional `root_markers`, `language_id`,
`description`; `env` / `initialization_options` work as for built-ins).
Custom entries are consulted BEFORE the registry so they can claim an
extension; malformed entries are logged and skipped. `hermes lsp status|list`
show them; no auto-install (the command must resolve on PATH or as a path).

Why: users integrating a server that is not (yet) first-party had to edit
agent/lsp/servers.py and carry merge conflicts (#100257).

Salvages the shape of #103372 (custom servers ahead of built-ins, per-entry
language_id) without its unrelated client.py / lint changes.

Fixes #100257
Co-authored-by: Zhang ChuanJin <ZHCHJ888@users.noreply.github.com>
2026-09-19 01:29:37 -07:00