forked from NousResearch/hermes-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhermes_constants.py
More file actions
1694 lines (1402 loc) · 64.9 KB
/
Copy pathhermes_constants.py
File metadata and controls
1694 lines (1402 loc) · 64.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Shared constants for Hermes Agent.
Import-safe module with no dependencies — can be imported from anywhere
without risk of circular imports.
"""
import os
import shutil
import stat
import sys
from contextvars import ContextVar, Token
from pathlib import Path
_profile_fallback_warned: bool = False
_UNSET = object()
_HERMES_HOME_OVERRIDE: ContextVar[str | object] = ContextVar(
"_HERMES_HOME_OVERRIDE", default=_UNSET
)
# ── TUI busy-indicator styles ─────────────────────────────────────────
# Single source of truth shared by the CLI /indicator command, the TUI
# gateway config handler, and the /help command registry. Keep in sync
# with ``INDICATOR_STYLES`` / ``DEFAULT_INDICATOR_STYLE`` in
# ``ui-tui/src/app/interfaces.ts`` on the frontend side.
INDICATOR_STYLES: tuple[str, ...] = ("ascii", "emoji", "kaomoji", "unicode")
DEFAULT_INDICATOR_STYLE: str = "kaomoji"
def set_hermes_home_override(path: str | Path | None) -> Token:
"""Set a context-local Hermes home override and return its reset token.
This is for in-process, per-task scoping. It deliberately does not mutate
``os.environ`` because that is shared by every thread in the process.
"""
value: str | object = _UNSET if path is None else str(path)
return _HERMES_HOME_OVERRIDE.set(value)
def reset_hermes_home_override(token: Token) -> None:
"""Restore the previous context-local Hermes home override."""
_HERMES_HOME_OVERRIDE.reset(token)
def get_hermes_home_override() -> str | None:
"""Return the active context-local Hermes home override, if any."""
override = _HERMES_HOME_OVERRIDE.get()
if override is _UNSET or not override:
return None
return str(override)
def _get_platform_default_hermes_home() -> Path:
"""Return the platform-native default Hermes home path."""
if sys.platform == "win32":
local_appdata = os.environ.get("LOCALAPPDATA", "").strip()
base = Path(local_appdata) if local_appdata else Path.home() / "AppData" / "Local"
return base / "hermes"
return Path.home() / ".hermes"
def _hermes_home_from_env() -> Path:
"""Resolve HERMES_HOME from the process environment only.
Reads the ``HERMES_HOME`` env var, falling back to the platform-native
default. Deliberately ignores the context-local override installed by
:func:`set_hermes_home_override`, so this reflects the process/launch
scope rather than a per-task profile. Shared by :func:`get_hermes_home`
and :func:`get_process_hermes_home` so the two never drift.
"""
val = os.environ.get("HERMES_HOME", "").strip()
if val:
return Path(val)
return _get_platform_default_hermes_home()
def _warn_profile_fallback_once() -> None:
"""Warn once when falling back to the default home while a profile is active.
Guard: if a non-default profile is sticky-active but ``HERMES_HOME`` is
unset, the fallback to the default profile is almost certainly wrong.
"""
global _profile_fallback_warned
if _profile_fallback_warned:
return
try:
fallback_home = _get_platform_default_hermes_home()
active_path = fallback_home / "active_profile"
active = active_path.read_text(encoding="utf-8").strip() if active_path.exists() else ""
except (UnicodeDecodeError, OSError):
active = ""
if active and active != "default":
_profile_fallback_warned = True
# Write directly to stderr. We intentionally do NOT route this
# through ``logging`` because (a) this function is called at
# module-import time from 30+ sites, often before logging is
# configured, and (b) root-logger propagation would double-emit
# on consoles where a StreamHandler is already attached.
msg = (
f"[HERMES_HOME fallback] HERMES_HOME is unset but active "
f"profile is {active!r}. Falling back to {fallback_home}, which "
f"is the DEFAULT profile — not {active!r}. Any data this "
f"process writes will land in the wrong profile. The "
f"subprocess spawner should pass HERMES_HOME explicitly "
f"(see issue #18594)."
)
try:
sys.stderr.write(msg + "\n")
sys.stderr.flush()
except Exception:
pass
def get_hermes_home() -> Path:
"""Return the Hermes home directory (default: platform-native path).
Resolution order: context-local override (see
:func:`set_hermes_home_override`) → ``HERMES_HOME`` env var → the
platform-native default. This is the single source of truth — all other
copies should import this.
When ``HERMES_HOME`` is unset but an ``active_profile`` file indicates
a non-default profile is active, logs a loud one-shot warning to
``errors.log`` so cross-profile data corruption is diagnosable instead
of silent. Behavior is unchanged otherwise — we still return
the platform-native default — because raising here would brick 30+ module-level
callers that import this at load time. Subprocess spawners are
expected to propagate ``HERMES_HOME`` explicitly (see the systemd
template in ``hermes_cli/gateway.py`` and the kanban dispatcher in
``hermes_cli/kanban_db.py``). See https://github.com/NousResearch/hermes-agent/issues/18594.
"""
override = get_hermes_home_override()
if override:
return Path(override)
if not os.environ.get("HERMES_HOME", "").strip():
_warn_profile_fallback_once()
return _hermes_home_from_env()
def hermes_home_key(path: str | Path | None = None) -> str:
"""Return a stable key for a Hermes home/profile directory.
Runtime registries use this key to isolate plugin-owned entries while
keeping built-in registrations process-global. ``strict=False`` preserves
useful behavior for profiles whose directories have not been created yet.
"""
candidate = Path(path) if path is not None else get_hermes_home()
resolved = candidate.expanduser().resolve(strict=False)
return os.path.normcase(str(resolved))
def get_process_hermes_home() -> Path:
"""Return the Hermes home for the running process, ignoring task overrides.
Unlike :func:`get_hermes_home`, this never follows the context-local
override set by :func:`set_hermes_home_override`. It resolves only the
process ``HERMES_HOME`` env var (falling back to the platform default),
so it reflects the scope the process was launched under **as long as
nothing mutates ``os.environ`` in-process**.
Use this for machine/process-level dashboard-owned assets — theme YAML,
dashboard plugin manifests — that live under the server's launch home and
must stay visible even while a request is scoped to another profile (e.g.
the embedded ``/chat`` running under ``--open-profile``). Do NOT use it
for genuinely profile-scoped data (memories, backups, checkpoints,
provider config) — those should keep following the override.
"""
return _hermes_home_from_env()
# Process-level memo for get_default_hermes_root(). The function resolves
# HERMES_HOME against the native home on every call (~80us of path
# resolution), and it is called at 31+ sites — every _load_global_auth_store()
# (per provider row in the /model picker), kanban, backup, gateway, update.
# Its result depends only on (HERMES_HOME, platform native home), which are
# compared for free on each call, so the memo is freshness-correct even if a
# test or plugin mutates HERMES_HOME mid-process.
_default_hermes_root_memo: "tuple[str, str, Path] | None" = None
def get_default_hermes_root() -> Path:
"""Return the root Hermes directory for profile-level operations.
In standard deployments this is the platform-native Hermes home
(``~/.hermes`` on POSIX, ``%LOCALAPPDATA%\\hermes`` on native Windows).
In Docker or custom deployments where ``HERMES_HOME`` points outside
``~/.hermes`` (e.g. ``/opt/data``), returns ``HERMES_HOME`` directly
— that IS the root.
In profile mode where ``HERMES_HOME`` is ``<root>/profiles/<name>``,
returns ``<root>`` so that ``profile list`` can see all profiles.
Works both for standard (``~/.hermes/profiles/coder``) and Docker
(``/opt/data/profiles/coder``) layouts.
Import-safe — no dependencies beyond stdlib.
"""
global _default_hermes_root_memo
native_home = _get_platform_default_hermes_home()
env_home = os.environ.get("HERMES_HOME", "")
if _default_hermes_root_memo is not None:
memo_native, memo_env, memo_result = _default_hermes_root_memo
if memo_native == str(native_home) and memo_env == env_home:
return memo_result
if not env_home:
result = native_home
else:
env_path = Path(env_home)
try:
env_path.resolve().relative_to(native_home.resolve())
# HERMES_HOME is under ~/.hermes (normal or profile mode)
result = native_home
except ValueError:
# Docker / custom deployment.
# Check if this is a profile path: <root>/profiles/<name>
# If the immediate parent dir is named "profiles", the root is
# the grandparent — this covers Docker profiles correctly.
if env_path.parent.name == "profiles":
result = env_path.parent.parent
else:
# Not a profile path — HERMES_HOME itself is the root
result = env_path
_default_hermes_root_memo = (str(native_home), env_home, result)
return result
def get_optional_skills_dir(default: Path | None = None) -> Path:
"""Return the optional-skills directory, honoring package-manager wrappers.
Packaged installs may ship ``optional-skills`` outside the Python package
tree and expose it via ``HERMES_OPTIONAL_SKILLS``.
"""
override = os.getenv("HERMES_OPTIONAL_SKILLS", "").strip()
if override:
return Path(override)
if default is not None:
return default
return get_hermes_home() / "optional-skills"
def get_optional_mcps_dir(default: Path | None = None) -> Path:
"""Return the optional-mcps directory, honoring package-manager wrappers.
Mirrors :func:`get_optional_skills_dir` for the MCP catalog (Nous-approved
Model Context Protocol servers shipped with the repo but disabled by
default). Packaged installs may ship ``optional-mcps`` outside the Python
package tree and expose it via ``HERMES_OPTIONAL_MCPS``.
"""
override = os.getenv("HERMES_OPTIONAL_MCPS", "").strip()
if override:
return Path(override)
if default is not None:
return default
return get_hermes_home() / "optional-mcps"
def get_bundled_skills_dir(default: Path | None = None) -> Path:
"""Return the bundled skills directory for source and packaged installs.
Resolution order:
1. ``HERMES_BUNDLED_SKILLS`` env var (Nix wrapper / explicit override)
2. Caller-supplied ``default`` (typically the source-checkout path)
3. ``<HERMES_HOME>/skills`` last-resort
"""
override = os.getenv("HERMES_BUNDLED_SKILLS", "").strip()
if override:
return Path(override)
if default is not None:
return default
return get_hermes_home() / "skills"
def get_hermes_dir(
new_subpath: str,
old_name: str,
*,
home: Path | None = None,
) -> Path:
"""Resolve a Hermes subdirectory with backward compatibility.
New installs get the consolidated layout (e.g. ``cache/images``).
Existing installs that already have the old path (e.g. ``image_cache``)
keep using it — no migration required.
A bare empty ``<old_name>/`` directory does **not** count as "the
legacy install is in use" — install scaffolds, manual ``mkdir`` work,
and cleared-then-abandoned locations all create empty stubs that
would otherwise silently shadow real data populated at
``<new_subpath>/``. See #27602 for the pairing-store regression where
a dormant empty ``pairing/`` orphaned approved-user data in
``platforms/pairing/``.
Args:
new_subpath: Preferred path relative to HERMES_HOME (e.g. ``"cache/images"``).
old_name: Legacy path relative to HERMES_HOME (e.g. ``"image_cache"``).
home: Optional explicit Hermes home. Profile-aware callers that manage
more than one home in the same process use this instead of
temporarily mutating the process or context-local HERMES_HOME.
Returns:
Absolute ``Path`` — legacy location if it exists with content,
otherwise the new location.
"""
home = home or get_hermes_home()
old_path = home / old_name
if _legacy_path_has_content(old_path):
return old_path
return home / new_subpath
def iter_hermes_node_dirs(home: Path | None = None) -> list[Path]:
"""Return Hermes-managed Node.js directories in preferred lookup order.
Windows installs from ``scripts/install.ps1`` unpack portable Node directly
into ``%LOCALAPPDATA%\\hermes\\node``. POSIX installs use
``$HERMES_HOME/node/bin``. Include both shapes on every platform so mixed
or migrated installs still work.
"""
root = home or get_hermes_home()
dirs = [root / "node"]
bin_dir = root / "node" / "bin"
# NOTE: keep this ordering in sync with hermesManagedNodePathEntries() in
# apps/desktop/electron/backend-env.ts — the Electron main process is Node
# and cannot import this module, so the platform-ordering rule is mirrored
# there (once; main.ts imports it rather than keeping its own copy).
if sys.platform == "win32":
return dirs + [bin_dir]
return [bin_dir] + dirs
def _candidate_node_command_names(command: str) -> list[str]:
base = Path(command).name
if sys.platform != "win32" or "." in base:
return [base]
if base.lower() == "npm":
# Prefer npm.cmd. PowerShell may block npm.ps1 by execution policy, and
# CreateProcess cannot launch a bare .ps1 the way it can launch .cmd.
return ["npm.cmd", "npm.exe", "npm"]
if base.lower() == "npx":
return ["npx.cmd", "npx.exe", "npx"]
if base.lower() == "node":
return ["node.exe", "node"]
return [f"{base}.cmd", f"{base}.exe", base]
_HERMES_NODE_TARGET_MAJOR = int(os.environ.get("HERMES_NODE_TARGET_MAJOR", "22"))
_managed_node_heal_attempted = False
_NODE_BOOTSTRAP_SCRIPT = Path(__file__).resolve().parent / "scripts" / "lib" / "node-bootstrap.sh"
def node_tool_runnable(path: str | None) -> bool:
"""Return True only when *path* is a Node/npm/npx binary that actually runs.
Hermes-managed Node trees live under ``$HERMES_HOME/node`` (or a profile's
``HERMES_HOME``). A partial upgrade or interrupted install can leave
``bin/npm`` behind while ``lib/cli.js`` is missing — the wrapper exists but
immediately throws ``MODULE_NOT_FOUND``. ``find_hermes_node_executable``
used to trust file presence alone, so ``hermes update`` would pick that
broken npm and fail the Node refresh / web UI build.
Probe with ``--version`` (same pattern as :func:`agent_browser_runnable`) so
broken managed wrappers are detected before use.
"""
if not path:
return False
candidate = Path(path)
if sys.platform == "win32":
if not candidate.is_file():
return False
elif not os.path.exists(path) or not os.access(path, os.X_OK):
return False
import subprocess
try:
from hermes_cli._subprocess_compat import windows_hide_flags
result = subprocess.run(
[path, "--version"],
capture_output=True,
timeout=10,
env=with_hermes_node_path(),
creationflags=windows_hide_flags(),
)
except (OSError, subprocess.TimeoutExpired, ValueError):
return False
return result.returncode == 0
def hermes_managed_node_tree_present(home: Path | None = None) -> bool:
"""Return True when any Hermes-managed node/npm/npx shim exists on disk."""
names = set()
for command in ("node", "npm", "npx"):
names.update(_candidate_node_command_names(command))
for directory in iter_hermes_node_dirs(home):
for name in names:
candidate = directory / name
if candidate.is_file() and (
sys.platform == "win32" or os.access(candidate, os.X_OK)
):
return True
return False
def _path_under_any(path: str, roots: list[str]) -> bool:
"""Return True when *path* sits inside one of *roots* (same drive).
Windows paths are case-insensitive and psutil / env vars can disagree on
drive-letter casing, so compare through ``normcase`` (a no-op on POSIX).
Each root is evaluated individually so disjoint roots both work.
"""
path_norm = os.path.normcase(os.path.normpath(path))
for root in roots:
root_norm = os.path.normcase(os.path.normpath(root))
try:
if os.path.commonpath([path_norm, root_norm]) == root_norm:
return True
except ValueError:
# Different drives on Windows — commonpath raises.
continue
return False
def managed_node_tree_in_use(home: Path | None = None) -> bool:
"""Return True when any running process executes from the managed Node tree.
Windows locks executables and loaded scripts against deletion or
overwrite while a process runs them, so the updater must not rewrite
``%HERMES_HOME%\\node`` while the desktop app's Node processes hold it —
``PermissionError: [WinError 5]`` on ``npm.cmd`` is the classic symptom
(#80926). Always ``False`` on POSIX, which has no equivalent lock
semantics.
The scan is a fast pre-check that avoids pointless re-downloads in
long-lived processes; the rename-based swap in
:func:`_heal_managed_node_windows` is the authoritative in-use guard.
"""
if sys.platform != "win32":
return False
try:
import psutil
except Exception:
return False
dirs: list[str] = []
for directory in iter_hermes_node_dirs(home):
try:
dirs.append(str(Path(directory).resolve()))
except OSError:
continue
if not dirs:
return False
try:
procs = psutil.process_iter(["exe", "cmdline"])
except Exception:
return False
for proc in procs:
try:
info = proc.info
except Exception:
continue
exe = info.get("exe")
if exe:
try:
exe_path = str(Path(exe).resolve())
except (OSError, ValueError):
exe_path = str(exe)
if _path_under_any(exe_path, dirs):
return True
for arg in info.get("cmdline") or []:
if _path_under_any(arg, dirs):
return True
return False
_managed_node_in_use_notice_printed = False
def _print_managed_node_in_use_notice() -> None:
"""Print the managed-Node deferral notice once per process."""
global _managed_node_in_use_notice_printed
if _managed_node_in_use_notice_printed:
return
_managed_node_in_use_notice_printed = True
print(
"→ Hermes-managed Node.js is in use by a running app; deferring its "
"upgrade until the app is closed (re-run `hermes update` afterwards).",
flush=True,
)
def _heal_managed_node_windows(home: Path | None = None) -> bool | None:
"""Redownload the portable Node zip into ``%HERMES_HOME%\\node`` on Windows.
Returns ``True`` on success, ``False`` on a genuine failure (offline,
download error, bad archive), and ``None`` when the tree is in use and the
heal is deferred — callers must not record the once-per-process attempt
for ``None`` so a later call can retry once the tree is free.
The replacement is staging-first: the new tree is fully downloaded and
extracted to a sibling ``node.new-*`` directory, then the live tree is
renamed aside (``node.old-*``) and the staged tree renamed into place.
The live tree is never deleted before its replacement is ready, so an
interrupted heal cannot gut the running installation. Windows allows
renaming a tree whose executables are running (images are mapped with
``FILE_SHARE_DELETE`` — the same mechanism as the hermes.exe quarantine);
when the OS refuses the rename, that refusal *is* the in-use signal and
the heal defers instead of forcing the write and crashing with
``PermissionError: [WinError 5]`` on ``npm.cmd`` (#80926).
"""
import re
import tempfile
import time
import urllib.request
import uuid
import zipfile
arch = (os.environ.get("PROCESSOR_ARCHITEW6432") or os.environ.get("PROCESSOR_ARCHITECTURE", "")).lower()
if arch in ("amd64", "x86_64"):
node_arch = "x64"
elif arch == "arm64":
node_arch = "arm64"
elif arch in ("x86",):
node_arch = "x86"
else:
return False
home = home or get_hermes_home()
target = home / "node"
# Cheap pre-check: skip the download and staging work when the tree is
# already visibly in use. The rename-based swap below is the
# authoritative guard — this scan only avoids pointless re-downloads for
# long-lived processes whose npm resolution retries.
if managed_node_tree_in_use(home):
_print_managed_node_in_use_notice()
return None
# Best-effort sweep of staging/backup litter from interrupted runs; a
# locked file simply stays for the next attempt. Only dirs older than
# 10 minutes are removed so a concurrent heal's in-flight swap (whose
# staged/backup dirs are seconds old) is never disturbed.
cutoff = time.time() - 600
for stale in home.glob("node.old-*"):
try:
if stale.stat().st_mtime < cutoff:
shutil.rmtree(stale, ignore_errors=True)
except OSError:
continue
for stale in home.glob("node.new-*"):
try:
if stale.stat().st_mtime < cutoff:
shutil.rmtree(stale, ignore_errors=True)
except OSError:
continue
index_url = f"https://nodejs.org/dist/latest-v{_HERMES_NODE_TARGET_MAJOR}.x/"
try:
with urllib.request.urlopen(index_url, timeout=60) as response:
index_html = response.read().decode("utf-8", errors="replace")
except OSError:
return False
match = re.search(
rf"node-v{_HERMES_NODE_TARGET_MAJOR}\.\d+\.\d+-win-{node_arch}\.zip",
index_html,
)
if not match:
return False
zip_name = match.group(0)
download_url = f"{index_url}{zip_name}"
try:
with urllib.request.urlopen(download_url, timeout=300) as response:
zip_bytes = response.read()
except OSError:
return False
token = uuid.uuid4().hex[:8]
staged = home / f"node.new-{token}"
backup = home / f"node.old-{token}"
try:
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = Path(tmp_dir)
zip_path = tmp_path / zip_name
zip_path.write_bytes(zip_bytes)
extract_dir = tmp_path / "extract"
extract_dir.mkdir()
with zipfile.ZipFile(zip_path) as archive:
archive.extractall(extract_dir)
extracted = next(extract_dir.glob("node-v*"), None)
if extracted is None or not extracted.is_dir():
return False
# Move the fully-extracted tree to a sibling staging dir so the
# swap below is a same-volume rename.
shutil.move(str(extracted), str(staged))
except OSError:
return False
if target.exists():
try:
os.replace(str(target), str(backup))
except OSError:
# The OS refuses to move the live tree — a running process holds
# it. Defer; the old tree is untouched and the next resolution
# (e.g. the next update after the app is closed) retries.
_print_managed_node_in_use_notice()
shutil.rmtree(staged, ignore_errors=True)
return None
# A rename preserves the directory's mtime, so a backup renamed from
# a long-lived tree would instantly look older than the litter-sweep
# cutoff to a concurrent heal. Touch it (best-effort — a failure
# must not abort the swap, which already succeeded) so the in-flight
# backup is never swept mid-swap.
try:
os.utime(backup, None)
except OSError:
pass
try:
os.replace(str(staged), str(target))
except OSError:
# Roll the live tree back and report the failure.
try:
os.replace(str(backup), str(target))
except OSError:
pass
shutil.rmtree(staged, ignore_errors=True)
return False
# The old tree is no longer canonical; locked files may keep it on
# disk until the next heal attempt, which is safe.
shutil.rmtree(backup, ignore_errors=True)
else:
try:
os.replace(str(staged), str(target))
except OSError:
shutil.rmtree(staged, ignore_errors=True)
return False
return node_tool_runnable(str(target / "node.exe"))
def _bootstrap_managed_node_posix() -> bool:
"""Install a fresh managed Node under ``$HERMES_HOME/node`` on POSIX.
Shells out to ``_nb_install_bundled_node`` in ``scripts/lib/node-bootstrap.sh``
(the same pinned-nodejs.org path ``install.sh`` uses), so the resulting
tree matches what a normal install would have produced. Runs with
``HERMES_NODE_SKIP_LINKS=1`` so the user's own node/npm on PATH is not
shadowed by ``~/.local/bin`` symlinks.
"""
if not _NODE_BOOTSTRAP_SCRIPT.is_file():
return False
import subprocess
try:
result = subprocess.run(
[
"bash",
"-c",
f'source "{_NODE_BOOTSTRAP_SCRIPT}" && _nb_install_bundled_node',
],
env={
**os.environ,
"HERMES_HOME": str(get_hermes_home()),
# Private provisioning: do not symlink node/npm/npx into
# ~/.local/bin — the user has their own toolchain on PATH and
# this tree must not shadow it.
"HERMES_NODE_SKIP_LINKS": "1",
},
capture_output=True,
timeout=600,
check=False,
)
except (OSError, subprocess.SubprocessError):
return False
return result.returncode == 0
def bootstrap_hermes_managed_node() -> str | None:
"""Install a Hermes-managed Node tree and return its npm path.
Used when the only Node/npm on the machine belongs to the user (system,
nvm, brew, Nix) and cannot satisfy the repo's ``engines`` requirements —
Hermes never modifies a toolchain it does not own, so instead it provisions
its own tree under ``$HERMES_HOME/node`` (the same tree a fresh install
creates) and works with that.
Returns the managed npm executable path on success, ``None`` on failure.
No-ops (returning the existing npm) when a healthy managed tree is already
present.
"""
existing = find_hermes_node_executable("npm")
if existing:
return existing
if sys.platform == "win32":
ok = _heal_managed_node_windows()
else:
ok = _bootstrap_managed_node_posix()
if not ok:
return None
for directory in iter_hermes_node_dirs():
for name in _candidate_node_command_names("npm"):
candidate = directory / name
if candidate.is_file() and (
sys.platform == "win32" or os.access(candidate, os.X_OK)
):
resolved = str(candidate)
if node_tool_runnable(resolved):
return resolved
return None
def heal_hermes_managed_node() -> bool:
"""Redownload Hermes-managed Node when the tree exists but is broken.
Runs at most once per process. POSIX installs shell out to
``heal_managed_node`` in ``scripts/lib/node-bootstrap.sh``; Windows
downloads the portable zip directly (same source as ``install.ps1``).
A Windows deferral (the tree is in use by a running app) does NOT record
the attempt, so a later call — or the next process — can heal once the
tree is free (#80926).
"""
global _managed_node_heal_attempted
if _managed_node_heal_attempted:
return False
if not hermes_managed_node_tree_present():
return False
if sys.platform == "win32":
result = _heal_managed_node_windows()
if result is None:
# In-use deferral: leave the attempt flag clear so a later call
# in this process can heal after the app releases the tree.
return False
_managed_node_heal_attempted = True
return bool(result)
_managed_node_heal_attempted = True
if not _NODE_BOOTSTRAP_SCRIPT.is_file():
return False
import subprocess
try:
result = subprocess.run(
[
"bash",
"-c",
f'source "{_NODE_BOOTSTRAP_SCRIPT}" && heal_managed_node',
],
env={**os.environ, "HERMES_HOME": str(get_hermes_home())},
capture_output=True,
timeout=300,
check=False,
)
except (OSError, subprocess.SubprocessError):
return False
return result.returncode == 0
def _managed_node_tree_outdated(home: Path | None = None) -> bool:
"""Return True when the managed tree's node runs but is below the target major.
An outdated managed Node (e.g. a 22 tree from an older install) heals the
same way a broken one does: :func:`find_hermes_node_executable` triggers
the once-per-process heal, which redownloads
``latest-v{_HERMES_NODE_TARGET_MAJOR}.x`` — so existing users are upgraded
on next launch, not just on the next installer re-run. Mirrors
``_nb_managed_node_outdated`` in ``scripts/lib/node-bootstrap.sh``.
"""
import subprocess
for directory in iter_hermes_node_dirs(home):
for name in _candidate_node_command_names("node"):
candidate = directory / name
if not candidate.is_file() or (
sys.platform != "win32" and not os.access(candidate, os.X_OK)
):
continue
try:
from hermes_cli._subprocess_compat import windows_hide_flags
result = subprocess.run(
[str(candidate), "--version"],
capture_output=True,
timeout=10,
creationflags=windows_hide_flags(),
)
major = int(result.stdout.decode().strip().lstrip("v").split(".")[0])
except (OSError, subprocess.TimeoutExpired, ValueError, IndexError):
return False # broken, not outdated — the runnable probe handles it
return major < _HERMES_NODE_TARGET_MAJOR
return False
def find_hermes_node_executable(command: str) -> str | None:
"""Return a Hermes-managed Node/npm executable path, healing broken trees.
Outdated trees (node major below ``_HERMES_NODE_TARGET_MAJOR``) heal the
same way broken ones do — the once-per-process heal redownloads the target
major, upgrading existing users on next launch rather than next reinstall.
When the heal fails (offline, download error), an outdated-but-runnable
tree is still returned: old Node beats no Node.
"""
names = _candidate_node_command_names(command)
def _first_runnable() -> tuple[str | None, bool]:
broken = False
for directory in iter_hermes_node_dirs():
for name in names:
candidate = directory / name
if candidate.is_file() and (
sys.platform == "win32" or os.access(candidate, os.X_OK)
):
resolved = str(candidate)
if node_tool_runnable(resolved):
return resolved, broken
broken = True
return None, broken
resolved, broken_present = _first_runnable()
needs_heal = broken_present or (
resolved is not None and _managed_node_tree_outdated()
)
if needs_heal and heal_hermes_managed_node():
healed, _ = _first_runnable()
if healed:
return healed
return resolved
def find_node_executable_on_path(command: str) -> str | None:
"""Return a Node/npm executable from PATH with Windows shim ordering.
``shutil.which("npm")`` can resolve an extensionless npm shim before the
``.cmd`` shim on Windows. Python's CreateProcess cannot execute that shim
directly, so prefer the launchable variants explicitly for Hermes-owned
subprocesses.
"""
if sys.platform != "win32":
return shutil.which(command)
command_str = str(command)
has_path_separator = any(
sep and sep in command_str for sep in (os.sep, os.altsep, "/", "\\")
)
if has_path_separator:
return command_str if Path(command_str).is_file() else None
for name in _candidate_node_command_names(command_str):
for directory in os.environ.get("PATH", "").split(os.pathsep):
if not directory:
continue
candidate = Path(directory) / name
if candidate.is_file():
return str(candidate)
return None
def find_node_executable(command: str) -> str | None:
"""Resolve a Node.js command, preferring healthy Hermes-managed installs.
This is for Hermes-owned subprocesses that should not be broken by a bad,
missing, or elevation-triggering system Node/npm on PATH. When a managed
tree exists but cannot be healed, returns ``None`` instead of falling back
to system npm on PATH.
"""
managed = find_hermes_node_executable(command)
if managed:
return managed
if hermes_managed_node_tree_present():
return None
return find_node_executable_on_path(command)
def with_hermes_node_path(env: dict[str, str] | None = None) -> dict[str, str]:
"""Return *env* with Hermes-managed Node directories prepended to PATH."""
merged = dict(os.environ if env is None else env)
existing = merged.get("PATH", "")
parts = [p for p in existing.split(os.pathsep) if p]
managed = [str(path) for path in iter_hermes_node_dirs() if path.is_dir()]
for entry in reversed(managed):
if entry not in parts:
parts.insert(0, entry)
merged["PATH"] = os.pathsep.join(parts)
return merged
def agent_browser_runnable(path: str | None) -> bool:
"""Return True only when *path* is an agent-browser CLI that actually runs.
A bare presence check (``shutil.which`` / ``Path.exists``) is not enough:
agent-browser's npm ``postinstall`` re-points a *global* install symlink
(e.g. ``/opt/homebrew/bin/agent-browser``) at our local
``node_modules/agent-browser/bin/...`` binary, which then disappears on the
next ``hermes update`` — leaving a **dangling symlink** that ``which`` still
reports but exec fails on with exit 127 (issue #48521). Callers that trust
such a path silently break every browser tool.
This validates the candidate by resolving it to a real, executable file and
running ``--version`` with a short timeout. Returns True only on a clean
(exit 0) run, so a dead/wrong-arch/hung binary is rejected and the caller
can fall through to the next resolution candidate.
Special cases:
* ``None`` / empty → False.
* The ``"npx agent-browser"`` fallback form (contains a space, not a real
file) → True; npx resolves and validates the package at run time, so
there is nothing to stat here.
"""
if not path:
return False
# The npx fallback is a two-token command string, not a filesystem path.
if " " in path and path.split()[0].endswith("npx"):
return True
# exists() follows symlinks — a dangling link returns False here, so we
# never even spawn a subprocess for the broken-link case.
if not os.path.exists(path) or not os.access(path, os.X_OK):
return False
import subprocess
try:
from hermes_cli._subprocess_compat import windows_hide_flags
result = subprocess.run(
[path, "--version"],
capture_output=True,
timeout=10,
env=with_hermes_node_path(),
creationflags=windows_hide_flags(),
)
except (OSError, subprocess.TimeoutExpired, ValueError):
return False
return result.returncode == 0
def _legacy_path_has_content(path: Path) -> bool:
"""Return ``True`` iff ``path`` exists and has content worth honouring.
A populated *directory* (any entry inside) counts. A non-directory
file at ``path`` also counts — the consumer presumably wrote it.
An empty directory does **not** count, so a stale empty
legacy stub falls through to the new layout. If the path cannot be
inspected (``PermissionError`` on ``stat``/``iterdir``, or any other
``OSError`` short of "not found"), assume occupied so we don't
accidentally orphan legacy data. Only a genuine
``FileNotFoundError`` counts as absent.
Symlinks are resolved before judging content: a symlink pointing at a
populated directory (or any existing non-directory target) counts, but
a **dangling** symlink (broken target) does **not** — it must not be
allowed to shadow populated new-layout data, matching the old
``exists()`` gate's behaviour for broken links.
"""
try:
st = path.lstat()
except FileNotFoundError:
return False
except OSError:
# PermissionError on a parent, or any other inspection failure:
# treat as occupied rather than silently orphaning legacy data.
return True
if stat.S_ISLNK(st.st_mode):
# Resolve the link's target. A dangling symlink has no content and
# must not shadow the new layout; a valid one is judged on its target.
try:
target_st = path.stat() # follows the link
except FileNotFoundError:
return False # dangling symlink → fall through to new layout
except OSError:
return True # can't resolve → assume occupied, don't orphan data
if not stat.S_ISDIR(target_st.st_mode):
return True
# target is a directory — fall through to the iterdir() emptiness check
elif not stat.S_ISDIR(st.st_mode):
return True
try:
next(path.iterdir())
except StopIteration:
return False
except OSError:
return True
return True
def display_hermes_home() -> str:
"""Return a user-friendly display string for the current HERMES_HOME.
Uses ``~/`` shorthand for readability::
default: ``~/.hermes``
profile: ``~/.hermes/profiles/coder``
custom: ``/opt/hermes-custom``