The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge remote-tracking branch 'upstream/main' into ethie/pm-clean
ethernet642579db60bd
diff --cc .github/actions/detect-changes/action.ymlindex dcc85959328,6ce85c6b7ba..0f2ef680df4--- a/.github/actions/detect-changes/action.yml+++ b/.github/actions/detect-changes/action.yml@@@ -48,9 -48,9 +48,12 @@@ outputsinstaller:description: Run the PowerShell installer tests on a Windows runner.value: ${{ steps.classify.outputs.installer }}+ bootstrap:+ description: Run the bootstrap installer lane (install.sh sandbox + stamp verification).+ value: ${{ steps.classify.outputs.bootstrap }}+ desktop_updater:+ description: Run the Windows desktop-update hand-off (windows.ps1) integration tests.+ value: ${{ steps.classify.outputs.desktop_updater }}rust:description: Run `cargo test` for the Tauri bootstrap installer.value: ${{ steps.classify.outputs.rust }}diff --cc .github/workflows/ci.yamlindex e148debf07f,aaa8da03863..1b1a3dd300d--- a/.github/workflows/ci.yaml+++ b/.github/workflows/ci.yaml@@@ -49,7 -49,7 +49,8 @@@ jobsuv_lock: ${{ steps.classify.outputs.uv_lock }}npm_lock: ${{ steps.classify.outputs.npm_lock }}installer: ${{ steps.classify.outputs.installer }}+ bootstrap: ${{ steps.classify.outputs.bootstrap }}+ desktop_updater: ${{ steps.classify.outputs.desktop_updater }}rust: ${{ steps.classify.outputs.rust }}docker_meta: ${{ steps.classify.outputs.docker_meta }}mcp_catalog: ${{ steps.classify.outputs.mcp_catalog }}@@@ -76,6 -76,21 +77,7 @@@if: needs.detect.outputs.python == 'true'uses: ./.github/workflows/tests.yml- # macOS + Windows lanes. The main `tests` lane above is Linux-only, and- # the OS-marked tests it collects are skipped there by design (see the- # `_OS_MARKS` comment in tests/conftest.py) — this is where they run.- # Same `python` lane gate: if no Python changed, neither runs.- tests-os:- name: OS-specific tests- needs: detect- if: needs.detect.outputs.python == 'true'- uses: ./.github/workflows/tests-os.yml- with:- # The Windows lane spawns the real desktop-update hand-off script- # (tests/test_desktop_update_windows_*.py) only when that surface- # changed; unit-level windows_only tests always run.- desktop_updater: ${{ needs.detect.outputs.desktop_updater == 'true' }}+lint:name: Python lintsneeds: detectdiff --cc agent/process_bootstrap.pyindex 7760d124e78,323dea85f6e..68b12aae998--- a/agent/process_bootstrap.py+++ b/agent/process_bootstrap.py@@@ -441,9 -542,17 +542,17 @@@ def build_keepalive_http_client``verify`` is forwarded to httpx so auxiliary-client calls (compression,vision, web_extract, title generation, etc.) honor the same per-provider- ``ssl_ca_cert`` / ``ssl_verify`` and ``HERMES_CA_BUNDLE`` settings the main- client uses. It is passed on the client AND on the plain no-proxy mounts+ ``ssl_ca_cert`` / ``ssl_verify`` settings the main client uses. It is+ passed on the client AND on the plain no-proxy mounts(a mounted transport owns the SSL context for its scheme).++ Every call returns a NEW ``httpx.Client`` (per-client close semantics are+ what #10933 pins), but sync clients with the same+ (verify, proxy, happy-eyeballs) identity mount the SAME underlying+ ``HTTPTransport`` through a :class:`_SharedTransport` view, so N delegated+ children share one connection pool + SSL context instead of N. Async+ clients are never shared: an httpcore async pool is bound to the event+ loop that first used it."""try:import httpxdiff --cc agent/prompt_builder.pyindex b62c6782cf8,f1c5ab0890a..781a3caa35a--- a/agent/prompt_builder.py+++ b/agent/prompt_builder.py@@@ -58,6 -59,56 +59,58 @@@ logger = logging.getLogger(__name__from tools.threat_patterns import scan_for_threats as _scan_for_threats+ # Default read deadline for context files (SOUL.md, AGENTS.md, .cursorrules,+ # ...); overridable via ``context_file_read_timeout`` in config.yaml.+ # Intentionally short: network-backed filesystems (iCloud Drive, OneDrive,+ # NFS) can fault-in an evicted file and block a cold read indefinitely, which+ # stalls system-prompt assembly before the first turn.+ _CONTEXT_FILE_READ_TIMEOUT_SECS = 5.0+++ def _get_context_file_read_timeout() -> float:+ """``context_file_read_timeout`` from config.yaml, else the 5s default."""+ try:+ from hermes_cli.config import load_config_readonly++ val = load_config_readonly().get("context_file_read_timeout")+ if isinstance(val, (int, float)) and val > 0:+ return float(val)+ except Exception as e:+ logger.debug("Could not read context_file_read_timeout from config: %s", e)+ return _CONTEXT_FILE_READ_TIMEOUT_SECS++-def _read_text_with_timeout(path: Path, timeout: Optional[float] = None) -> Optional[str]:++def _read_text_with_timeout(++ path: Path, timeout: Optional[float] = None, encoding: str = "utf-8-sig"++) -> Optional[str]:+ """``path.read_text()`` on a daemon thread so a slow file can't stall startup.++ Returns the text, or ``None`` after *timeout* seconds (logged at WARNING;+ the orphaned reader thread finishes on its own). Read errors propagate to+ the caller exactly as a direct ``read_text`` would, so existing+ ``try/except`` handling at each site is unchanged.+ """+ if timeout is None:+ timeout = _get_context_file_read_timeout()+ result: "queue.Queue[tuple[bool, object]]" = queue.Queue(maxsize=1)++ def _reader() -> None:+ try:- result.put((True, path.read_text(encoding="utf-8")))++ result.put((True, path.read_text(encoding=encoding)))+ except Exception as exc: # re-raised on the caller thread+ result.put((False, exc))++ threading.Thread(target=_reader, daemon=True, name=f"context-read:{path.name}").start()+ try:+ ok, value = result.get(timeout=timeout)+ except queue.Empty:+ logger.warning("Context file %s read timed out after %.1fs; skipping", path, timeout)+ return None+ if ok:+ return value # type: ignore[return-value]+ raise value # type: ignore[misc]++def _scan_context_content(content: str, filename: str) -> str:"""Scan context file content for injection. Returns sanitized content.diff --cc agent/ssl_verify.pyindex ee6d06a94a0,c62c6c81da1..d14f395be2f--- a/agent/ssl_verify.py+++ b/agent/ssl_verify.py@@@ -21,7 -3,9 +21,8 @@@ statements about one endpoint, not an afrom __future__ import annotationsimport logging-import osimport ssl+ import threadingfrom pathlib import Pathfrom typing import Any, Optional@@@ -95,64 -67,19 +117,70 @@@ def resolve_httpx_verify)return False- bundle = (ca_bundle or "").strip()- if bundle:- path = Path(bundle).expanduser()+ effective_ca = (+ (ca_bundle or "").strip()+ or os.getenv("HERMES_CA_BUNDLE", "").strip()+ or os.getenv("SSL_CERT_FILE", "").strip()+ or os.getenv("REQUESTS_CA_BUNDLE", "").strip()+ or os.getenv("CURL_CA_BUNDLE", "").strip()+ )+ if effective_ca:- ca_path = str(Path(effective_ca).expanduser())- if os.path.isfile(ca_path):- return _context_for_ca_bundle(ca_path)++ path = Path(effective_ca).expanduser()+ if path.is_file():+ # An explicit bundle REPLACES the platform store for this client.+ # inject_into_ssl() rebinds ssl.SSLContext to truststore's class,+ # which ignores loaded CA files and verifies against the OS store+ # anyway — so build from the ORIGINAL class, which truststore+ # keeps for exactly this purpose. Without it a pinned+ # ssl_ca_cert silently means "trust the machine" instead.+ #+ # Do NOT assign verify_mode/check_hostname here: the stock+ # class's setters resolve ``super(SSLContext, SSLContext)``+ # against the PATCHED module global and recurse to the stack+ # limit. PROTOCOL_TLS_CLIENT already implies CERT_REQUIRED and+ # check_hostname, so there is nothing to set.+ from truststore._ssl_constants import _original_SSLContext++ ctx = _original_SSLContext(ssl.PROTOCOL_TLS_CLIENT)+ ctx.load_verify_locations(cafile=str(path))+ return ctxlogger.warning(- "CA bundle path does not exist: %s — falling back to default certificates",+ "ssl_ca_cert path does not exist: %s — using the OS trust store instead",- bundle,+ effective_ca,)return True+++def resolve_requests_verify(+ *,+ ca_bundle: Optional[str] = None,+ ssl_verify: Any = None,+ base_url: str = "",+) -> bool | str:+ """The same decision for ``requests``, which takes a path, not a context.++ With the platform store installed process-wide, ``True`` already means+ "verify against the OS store" here — urllib3 builds its context through+ the patched ``ssl.SSLContext``.+ """+ install_truststore()++ if _coerce_insecure(ssl_verify):+ logger.warning(+ "TLS certificate verification DISABLED (ssl_verify: false) for %s — "+ "this is intended for local development only and is unsafe on any "+ "network you do not fully control.",+ base_url or "a custom provider endpoint",+ )+ return False++ bundle = (ca_bundle or "").strip()+ if bundle:+ path = Path(bundle).expanduser()+ if path.is_file():+ return str(path)+ logger.warning(+ "ssl_ca_cert path does not exist: %s — using the OS trust store instead",+ bundle,+ )+ return Truediff --cc apps/desktop/electron/main.tsindex 931df474a6e,0e5ec73363f..22fa5eb40f3--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@@ -12641,65 -12602,15 +12894,67 @@@ async function stopPoolBackend(profile}async function teardownPoolBackendAndWait(profile) {- await Promise.all(localProfilePoolKeys(profile).map(key => poolStopper.stop(key)))+ await Promise.all(localProfilePoolKeys(profile).map(key => stopPoolBackend(key)))}- function stopAllPoolBackends() {- return poolStopper.stopAll()+ async function stopAllPoolBackends() {+ const entries = [...backendPool.values()]+ await poolStopper.stopAll()+ entries.forEach(releaseLocalBackendSlot)}+/**+ * Last teardown act on Windows: kill anything still running out of THIS+ * install's roots, so no straggler holds an image open.+ *+ * Two roots, because two install shapes have the same daemon problem:+ *+ * - The artifact resources dir (bundled/MSIX). A live process rooted in the+ * package family pins the family's container silo, and every later+ * activation then fails the job → silo conversion with 0x80070020 — the app+ * never launches again. Live cause on windows-11-arm was the payload's+ * bundled-git gpg-agent, which daemonizes out of our process tree and so is+ * unreachable by taskkill /T.+ * - The managed tool store (mutable install.ps1 / install.sh checkout), where+ * pm stages node, git and uv. A daemonized tool there keeps its own image+ * open, and Windows cannot overwrite a running image — so the next+ * `hermes update` fails to replace exactly those files.+ *+ * HERMES_RUNTIME_DIR is the store when pm is aimed at one (a bundled payload+ * aims it at its own, where the roots overlap harmlessly); otherwise the store+ * is <hermes root>/tools, mirroring pm.paths.store_root().+ *+ * Runs AFTER the graceful backend teardown and skips the pids it owned, so+ * this is only the net for what detached. Best effort throughout: quit must+ * never hang or fail on it. See package-process-reap.ts for the evidence.+ */+function reapInstallRootedStragglers(excludePids: number[]): void {+ if (!IS_WINDOWS) {+ return+ }++ const payloadRoot = isBundledInstall(process.resourcesPath, { fileExists }) ? process.resourcesPath : null+ // HERMES_HOME is already root-normalized by resolveHermesHome().+ const managedStore = process.env.HERMES_RUNTIME_DIR || path.join(HERMES_HOME, 'tools')++ try {+ reapPackageRootedProcesses({+ installRoots: [payloadRoot, managedStore],+ listProcesses: () => listWindowsProcesses((file, args, options) => execFileSync(file, args, {+ ...hiddenWindowsChildOptions({ encoding: 'utf8', timeout: options.timeout }),+ windowsHide: options.windowsHide+ }) as unknown as string),+ killProcess: pid => process.kill(pid, 'SIGKILL'),+ selfPid: process.pid,+ excludePids,+ isWindows: true,+ log: message => rememberLog(message)+ })+ } catch (err) {+ rememberLog(`[package-reap] skipped: ${(err as Error).message}`)+ }+}+const backendShutdown = createBackendShutdownCoordinator(async () => {const primary = backendConnectionState.invalidate()@@@ -17595,121 -17457,25 +17870,137 @@@ ipcMain.handle('hermes:version', asynchermesRoot: resolveUpdateRoot(),bundleOutOfSync: skew.outOfSync,bundleCommitsBehind: skew.desktopCommitsBehind,+ // The install id: sha16 of the canonical install-root path — the key of+ // this install's per-install channel record and its installs/<sha16>/ state+ // folder. Same value `hermes update --install-id` prints; About renders it+ // as `sha16 (path)`.+ installId: installIdForRoot(resolveUpdateRoot(), canonicalizeInstallPath),+ // What this build carries and where an external backend runs from.+ // Bundled artifacts always run their payload; light artifacts have no+ // runtime and only reach remote backends. External builds classify from+ // the install stamp (git/docker/nix), 'unknown' when it can't be told.- hermesRuntime: resolveHermesRuntime()++ hermesRuntime: resolveHermesRuntime(),+ // True when the bundle on disk is not the one this process loaded — a+ // plain app restart (no rebuild, no installer) clears the skew above.+ // Packaged only: a dev `--build-only` rewrites build/install-stamp.json+ // under a running `npm start`, which is a rebuild the developer asked for,+ // not a torn install to offer a restart for.+ bundleSwapPending: IS_PACKAGED && detectBundleSwap(INSTALL_STAMP, loadInstallStamp())}})++ // The About page's "Restart Hermes" button (shown when bundleSwapPending):+ // load the already-swapped bundle without asking the user to quit manually.+ // app.relaunch() re-executes by path, so the fresh process picks up whatever+ // bundle now lives there.+ ipcMain.handle('hermes:app:relaunch', async () => {+ rememberLog('[updates] renderer requested an app relaunch (swapped bundle pending)')+ app.relaunch({ args: buildNoSandboxRelaunchArgs(process.argv.slice(1)) })+ void exitAfterBackendShutdown(0)+ })+/** The latest pm/venv/plugin-operation receipt — the machine-readable+ * surface every medium reads (CLI: `hermes pm status`). Returned as one+ * parsed JSON object: { kind, outcome, venv_rebuild, plugin_bisect,+ * plugin_checks, ... } or null when no operation has run yet. The file+ * lives at <HERMES_HOME>/logs/update_receipts/latest.json — written by+ * pm syncs (bisect disables, failed rebuilds), plugin update checks,+ * and (embedded) updates. */+function readLatestSyncReceipt(): Record<string, unknown> | null {+ const receiptPath = path.join(+ HERMES_HOME,+ 'logs',+ 'update_receipts',+ 'latest.json'+ )+ try {+ const text = fs.readFileSync(receiptPath, 'utf8')+ // tolerate a BOM (hermes writes plain, but editors touch configs)+ const stripped = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text+ return JSON.parse(stripped)+ } catch {+ return null+ }+}++ipcMain.handle('hermes:sync-status', () => readLatestSyncReceipt())++/** Build provenance read from the install stamp — the same facts the CLI+ * reports. Falls back to the bare app version when there's no stamp. */+function resolveHermesVersionInfo() {+ // The baked build-time constant is typed more narrowly than a full stamp+ // loaded from disk; cast to the full shape so every provenance field is+ // readable on either source.+ const stamp = INSTALL_STAMP as InstallStamp | null++ if (stamp) {+ return {+ appVersion: resolveHermesVersion(),+ baseVersion: stamp.baseVersion ?? undefined,+ distance: stamp.distance ?? undefined,+ commit: stamp.commit,+ branch: stamp.branch,+ source: stamp.source ?? undefined,+ distribution: stamp.distribution ?? undefined,+ dirty: stamp.dirty+ }+ }++ return { appVersion: app.getVersion(), baseVersion: app.getVersion() }+}++// Python's Path.resolve() equivalent for install-id derivation: realpath when+// the path exists, plain resolve otherwise. Must stay byte-compatible with+// boot_bootstrap._install_key or the CLI and the app would compute two+// different ids for one install.+function canonicalizeInstallPath(p: string): string {+ try {+ return fs.realpathSync(p)+ } catch {+ return path.resolve(p)+ }+}++/** Classify what this build carries (embedded / light / external). The stamp's+ * `payload` decides the first two; an external build classifies its root via+ * the canonical-root install stamp (desktop-bootstrapped) or the app stamp's+ * `source`, so About's Runtime row names git/docker/nix/desktop-bootstrap+ * instead of a bare "external". */+function resolveHermesRuntime() {+ const stamp = INSTALL_STAMP as InstallStamp | null++ if (stamp?.payload === 'light') {+ return { type: 'light' }+ }++ if (stamp?.payload === 'bundled') {+ return { type: 'embedded' }+ }++ const root = resolveUpdateRoot()+ const canonicalStamp = activeRuntimeState().canonicalInstallStamp++ if (canonicalStamp?.source === 'desktop-bootstrap') {+ return { type: 'desktop-bootstrap', root }+ }++ const source = stamp?.source++ if (source === 'git') {+ return { type: 'git', root }+ }++ if (source === 'nix') {+ return { type: 'nix', root: null }+ }++ if (source === 'docker') {+ return { type: 'docker', root: null }+ }++ return { type: 'unknown' }+}+// ===========================================================================// Uninstall — remove the Chat GUI (and optionally the agent / user data).// ===========================================================================diff --cc apps/desktop/electron/preload.tsindex e1fec035e47,fd9668752b1..28cc94cd5c5--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@@ -496,7 -493,7 +498,8 @@@ contextBridge.exposeInMainWorld('hermesreturn () => ipcRenderer.removeListener('hermes:bootstrap:event', listener)},getVersion: () => ipcRenderer.invoke('hermes:version'),+ getSyncStatus: () => ipcRenderer.invoke('hermes:sync-status'),+ relaunchApp: () => ipcRenderer.invoke('hermes:app:relaunch'),getRemoteDisplayReason: () => ipcRenderer.invoke('hermes:get-remote-display-reason'),uninstall: {summary: () => ipcRenderer.invoke('hermes:uninstall:summary'),diff --cc apps/desktop/src/global.d.tsindex 8f29d581ff2,0362b8ff127..b6587803183--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@@ -504,10 -515,8 +517,12 @@@ declare globalcancelBootstrap: () => Promise<{ ok: boolean; cancelled: boolean }>onBootstrapEvent: (callback: (payload: DesktopBootstrapEvent) => void) => () => voidgetVersion: () => Promise<DesktopVersionInfo>+ /** The latest pm/venv/plugin-operation receipt (machine-readable):+ * bisect disables, failed rebuilds, update-check results. null when+ * no venv operation has run yet. */+ getSyncStatus: () => Promise<DesktopSyncReceipt | null>+ /** Restart the app in place — loads the swapped bundle when bundleSwapPending. */+ relaunchApp?: () => Promise<void>getRemoteDisplayReason?: () => Promise<string | null>updates: {check: () => Promise<DesktopUpdateStatus>@@@ -614,44 -597,11 +629,47 @@@ export interface DesktopVersionInfobundleOutOfSync?: boolean/** Commits under apps/desktop/ the running bundle is missing (null unknown). */bundleCommitsBehind?: null | number+ /** Build provenance from the install stamp (empty for packaged builds with+ * no stamp / a bare `app.getVersion()` fallback). */+ baseVersion?: string+ branch?: string | null+ commit?: string | null+ distance?: number+ dirty?: boolean+ source?: 'build' | 'ci' | 'docker' | 'fallback' | 'git' | 'local' | 'nix' | 'unknown'+ distribution?: 'desktop-app' | 'docker' | 'nix'+ /** sha16 of the canonical install-root path — the per-install channel key and+ * the shape `hermes update --install-id` prints. */+ installId?: string+ /** What this build carries (embedded / light / external) and where an+ * external backend resolved from. Bundled artifacts run their payload; light+ * artifacts have no runtime and only reach remote backends. */+ hermesRuntime?: { type: 'embedded' } | { type: 'light' } | { type: 'external'; source?: RuntimeSource }+ /** True when the bundle on disk is newer than the running process — a plain+ * app restart (no rebuild, no installer) is enough to load it. */+ bundleSwapPending?: boolean}+/** Where an external build's backend came from. Mirrors the resolution ladder+ * in `resolveHermesBackend()`: `git` / `source` / sealed stewards are the+ * Python install methods from `installation.tree.install_method()`; the+ * Electron-only rungs (`hermes-root`, `path`, `system-python`, `bootstrap`)+ * are resolution facts the backend cannot see. Each variant carries the+ * location it resolved from, when there is one. */+export type RuntimeSource =+ | { type: 'hermes-root'; root: string } // HERMES_DESKTOP_HERMES_ROOT — explicit developer override+ | { type: 'git'; root: string } // checkout at a managed install root, $HERMES_HOME/hermes-agent+ | { type: 'source'; root: string } // a git checkout anywhere else+ | { type: 'docker'; root: string | null } // sealed tree stewarded by Docker+ | { type: 'nix'; root: string | null } // sealed tree stewarded by Nix+ | { type: 'desktop-app'; root: string | null } // sealed tree stewarded by the desktop bundle+ | { type: 'desktop-bootstrap'; root: string } // canonical install created by the desktop first-launch bootstrap+ | { type: 'unknown' } // no stamp, no .git — provenance cannot be told+ | { type: 'path'; command: string } // an existing `hermes` CLI found on PATH+ | { type: 'system-python'; command: string } // pip-installed hermes_cli on system Python+ | { type: 'bootstrap' } // nothing usable yet; the first-launch installer runs++export type DesktopUninstallMode = 'full' | 'gui' | 'lite'export interface DesktopUninstallSummary {diff --cc apps/desktop/src/i18n/ar.tsindex b36a33ce31d,295cc157b00..899213afc5e--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@@ -670,6 -666,42 +672,43 @@@ export const ar = defineLocale('updates.nonInteractiveLocalChanges':'عندما يحدّث Hermes نفسه من التطبيق دون موجه طرفية، احتفظ بتعديلات المصدر المحلية أو تجاهلها.'},+ about: {+ heading: 'حول Hermes',+ version: value => `الإصدار ${value}`,+ versionUnavailable: 'الإصدار غير متاح',+ bundleOutOfSync: 'إصدار التطبيق قديم',+ bundleOutOfSyncDesc:+ 'تم تحديث وقت تشغيل Hermes، لكن تطبيق سطح المكتب نفسه لا يزال إصدارًا قديمًا — لن تظهر ميزات الواجهة الجديدة (مثل Bot Mode) حتى يتم تحديث التطبيق. شغّل التحديث أدناه لإعادة بناء التطبيق. إذا لم يختفِ هذا التحذير، فأعد التثبيت من أحدث مثبّت لسطح المكتب.',+ bundleOutOfSyncAction: 'الحصول على المثبّت',+ bundleSwapPending: 'أعد التشغيل لإكمال التحديث',+ bundleSwapPendingDesc:+ 'تم تثبيت التطبيق المحدَّث بالفعل — يكفي إعادة تشغيل Hermes لتحميله. لن تتأثر المحادثات أو الإعدادات.',+ bundleSwapPendingAction: 'إعادة تشغيل Hermes',+ updates: 'التحديثات',+ checkNow: 'التحقق الآن',+ checking: 'جار التحقق...',+ seeWhatsNew: 'عرض الجديد',+ updateNow: 'تحديث الآن',+ releaseNotes: 'ملاحظات الإصدار',+ onLatest: 'أنت على أحدث إصدار',+ installing: 'جار التثبيت...',+ cantUpdate: 'تعذر التحديث',+ cantReach: 'تعذر الوصول لخدمة التحديث',+ tapCheck: 'اضغط للتحقق من التحديثات.',+ updateReady: count => `${count} تحديث متاح`,+ updateReadyUnknown: 'تحديث جديد جاهز.',+ lastChecked: age => `آخر تحقق ${age}`,+ justNowSuffix: 'الآن',+ automaticUpdates: 'التحديثات التلقائية',+ automaticUpdatesDesc: 'اسمح لـ Hermes بالتحقق من التحديثات وتثبيتها.',+ branchCommit: (branch, commit) => `${branch} عند ${commit}`,+ never: 'أبدا',+ justNow: 'الآن',+ minAgo: count => `قبل ${count} دقيقة`,+ hoursAgo: count => `قبل ${count} ساعة`,+ daysAgo: count => `قبل ${count} يوم`+ },++config: {none: 'لا شيء',noneParen: '(لا شيء)',diff --cc apps/desktop/src/store/updates.tsindex e317c234e35,327c31b0a6e..746d8e85649--- a/apps/desktop/src/store/updates.ts+++ b/apps/desktop/src/store/updates.ts@@@ -205,11 -205,13 +205,15 @@@ export function reportInstallMethodWarn* Closing the toast — dismissing it or opening the updates window from it —* (re)starts the cooldown, so a busy upstream branch doesn't re-spam the user* on every new commit. The snooze is persisted, so it survives relaunches too.+ *+ * `target` is the target whose status produced this toast. The overlay has no+ * target switcher, so a client-status toast that opened the backend overlay+ * showed the user a machine they weren't told about, with no way back.*/- export function maybeNotifyUpdateAvailable(status: DesktopUpdateStatus | null) {+ export function maybeNotifyUpdateAvailable(status: DesktopUpdateStatus | null, target: UpdateTarget = 'client') {+ // Either signal means "update ready": behind > 0 (git checkout) or+ // updateAvailable (app-installer, shallow clone).- if (!status || status.supported === false || status.error) {+ if (!status || status.supported === false || status.error || !status.targetSha) {return}diff --cc cron/suggestions.pyindex 675de33bbd5,afbd44dbda1..cd14751cab5--- a/cron/suggestions.py+++ b/cron/suggestions.py@@@ -76,10 -84,11 +84,11 @@@ def _ensure_dir() -> Nonedef _load_raw() -> Dict[str, Any]:- if not SUGGESTIONS_FILE.exists():+ suggestions_file = _current_suggestions_file()+ if not suggestions_file.exists():return {"suggestions": []}try:- with open(SUGGESTIONS_FILE, "r", encoding="utf-8-sig") as f:- with open(suggestions_file, "r", encoding="utf-8") as f:++ with open(suggestions_file, "r", encoding="utf-8-sig") as f:data = json.load(f)except (json.JSONDecodeError, OSError) as e:logger.warning("suggestions.json unreadable (%s); starting empty", e)diff --cc gateway/channel_directory.pyindex 08c5bee54ad,d07a7160762..f46317ed2d5--- a/gateway/channel_directory.py+++ b/gateway/channel_directory.py@@@ -37,10 -51,11 +51,11 @@@ def _aliases_path() -> Pathdef _load_channel_aliases() -> Dict[str, Dict[str, str]]:- if not CHANNEL_ALIASES_PATH.exists():+ aliases_path = _aliases_path()+ if not aliases_path.exists():return {}try:- with open(CHANNEL_ALIASES_PATH, encoding="utf-8-sig") as f:- with open(aliases_path, encoding="utf-8") as f:++ with open(aliases_path, encoding="utf-8-sig") as f:data = json.load(f)return data if isinstance(data, dict) else {}except Exception:@@@ -530,7 -547,7 +547,7 @@@ def load_directory() -> Dict[str, Any]_apply_channel_aliases(base["platforms"])return basetry:- with open(DIRECTORY_PATH, encoding="utf-8-sig") as f:- with open(directory_path, encoding="utf-8") as f:++ with open(directory_path, encoding="utf-8-sig") as f:data = json.load(f)# Re-apply aliases on read so friendly names take effect immediately,# even between timed rebuilds and for brand-new alias entries.diff --cc hermes_cli/config.pyindex a0312d8a439,893cfadd6f9..6483685ecbc--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@@ -6127,30 -6280,14 +6245,34 @@@ def unset_config_value(key: str)returnconfig_path = get_config_path()- # Fail-closed parse via require_readable (unparseable / non-mapping- # refuse-write); returns the mapping so we do not re-parse / collapse.- user_config = require_readable_config_before_write(config_path)+ require_readable_config_before_write(config_path)+ user_config = {}+ if config_path.exists():+ try:+ with open(config_path, encoding="utf-8-sig") as f:+ user_config = fast_safe_load(f) or {}+ except Exception as exc:+ _backup_corrupt_config(config_path)+ msg = (+ f"Refusing to overwrite {config_path}: existing config.yaml is not valid YAML "+ f"({exc}). Fix the file or restore from a .corrupt.*.bak backup first."+ )+ print(f"✗ {msg}", file=sys.stderr)+ raise RuntimeError(msg) from exc+ if not isinstance(user_config, dict):+ _backup_corrupt_config(config_path)+ msg = (+ f"Refusing to overwrite {config_path}: top-level YAML must be a mapping, "+ f"got {type(user_config).__name__}. Fix the file or restore from a "+ f".corrupt.*.bak backup first."+ )+ print(f"✗ {msg}", file=sys.stderr)+ raise RuntimeError(msg)+ # Mirror set_config_value's display.platforms canonicalization (#71047).+ key, _redirect_note = _redirect_platform_display_key(key)+ if _redirect_note:+ print(_redirect_note.replace("saved as", "resolved as"))removed = _unset_nested(user_config, key)# Keep .env in sync for keys that terminal_tool reads directly from env vars.diff --cc hermes_cli/doctor.pyindex 015465d0838,91c26092c8e..4c598863755--- a/hermes_cli/doctor.py+++ b/hermes_cli/doctor.py@@@ -2022,16 -2059,18 +2059,18 @@@ def run_doctor(args)check_ok(f"{_DHH}/memories/ directory exists")memory_file = memories_dir / "MEMORY.md"user_file = memories_dir / "USER.md"- if memory_file.exists():- size = len(memory_file.read_text(encoding="utf-8-sig").strip())- check_ok(f"MEMORY.md exists ({size} chars)")- else:- check_info("MEMORY.md not created yet (will be created when the agent first writes a memory)")- if user_file.exists():- size = len(user_file.read_text(encoding="utf-8-sig").strip())- check_ok(f"USER.md exists ({size} chars)")- else:- check_info("USER.md not created yet (will be created when the agent first writes a memory)")+ if _memory_enabled:+ if memory_file.exists():- size = len(memory_file.read_text(encoding="utf-8").strip())++ size = len(memory_file.read_text(encoding="utf-8-sig").strip())+ check_ok(f"MEMORY.md exists ({size} chars)")+ else:+ check_info("MEMORY.md not created yet (will be created when the agent first writes a memory)")+ if _user_profile_enabled:+ if user_file.exists():- size = len(user_file.read_text(encoding="utf-8").strip())++ size = len(user_file.read_text(encoding="utf-8-sig").strip())+ check_ok(f"USER.md exists ({size} chars)")+ else:+ check_info("USER.md not created yet (will be created when the agent first writes a memory)")else:check_warn(f"{_DHH}/memories/ not found", "(will be created on first use)")if should_fix:diff --cc hermes_cli/linux_desktop_entry.pyindex 53bde536f3c,e33675590ea..00de49c3c7d--- a/hermes_cli/linux_desktop_entry.py+++ b/hermes_cli/linux_desktop_entry.py@@@ -15,18 -15,20 +15,19 @@@ Two values must be absolute for the entcheckout. Do not copy the icon: ``Exec`` already depends on that tree.Cache refresh is best-effort and tool-gated: ``update-desktop-database``- for the freedesktop menu cache, and ``kbuildsycoca6``/``kbuildsycoca5``- for Plasma. Run each tool only when it exists. A missing tool is not an- error.+ for the freedesktop menu cache, ``gtk-update-icon-cache`` for the user+ hicolor tree, and ``kbuildsycoca6``/``kbuildsycoca5`` for Plasma. Run+ each tool only when it exists. A missing tool is not an error.-Import-light and side-effect-free at import time: the uninstaller uses-this without loading the full CLI.+Import-light and side-effect-free at import time: the uninstaller and the+Electron main process both use this without loading the full CLI."""from __future__ import annotations+ import ioimport osimport shutil-import structimport subprocessimport sysfrom pathlib import Pathdiff --cc hermes_cli/profiles.pyindex 669b8fba325,39ad55555c2..dddd96be5cd--- a/hermes_cli/profiles.py+++ b/hermes_cli/profiles.py@@@ -2016,9 -2036,22 +2047,22 @@@ def _stop_gateway_process(profile_dir:returntry:- raw = pid_file.read_text(encoding="utf-8").strip()+ raw = pid_file.read_text(encoding="utf-8-sig").strip()data = json.loads(raw) if raw.startswith("{") else {"pid": int(raw)}pid = int(data["pid"])+ # Cross-profile kill refusal (#89315): the record's hermes_home stamp+ # names the gateway's TRUE owner. A contaminated/poisoned gateway.pid+ # inside this profile dir can point at another profile's live gateway+ # — killing it starts the mutual SIGTERM restart loop from the issue.+ from gateway.status import recorded_gateway_home_conflicts++ if recorded_gateway_home_conflicts(data, expected_home=profile_dir):+ print(+ f"✗ Refusing to stop PID {pid}: its recorded HERMES_HOME "+ f"belongs to a different profile than {profile_dir} "+ "(stale/poisoned PID record, #89315)."+ )+ return# Route through terminate_pid so Windows uses the appropriate# primitive (taskkill / TerminateProcess) — raw os.kill with# _signal.SIGKILL raises AttributeError at import time on Windows,diff --cc hermes_cli/web_routers/profiles.pyindex 843bf0649fb,bf8f463b202..8cc359636cf--- a/hermes_cli/web_routers/profiles.py+++ b/hermes_cli/web_routers/profiles.py@@@ -1052,12 -1094,21 +1094,20 @@@ async def delete_profile_endpoint(name@router.get("/api/profiles/{name}/soul")async def get_profile_soul(name: str):soul_path = _resolve_profile_dir(name) / "SOUL.md"- if soul_path.exists():- try:- return {"content": soul_path.read_text(encoding="utf-8-sig"), "exists": True}- except OSError as e:- raise HTTPException(status_code=500, detail=f"Could not read SOUL.md: {e}")- return {"content": "", "exists": False}-+ def _run():+ # Probe and read in the same hop: two round-trips would also widen the+ # window between the existence check and the read.+ if not soul_path.exists():+ return _MISSING- return soul_path.read_text(encoding="utf-8")++ return soul_path.read_text(encoding="utf-8-sig")++ try:+ content = await run_in_threadpool(_run)+ except OSError as e:+ raise HTTPException(status_code=500, detail=f"Could not read SOUL.md: {e}")+ if content is _MISSING:+ return {"content": "", "exists": False}+ return {"content": content, "exists": True}@router.put("/api/profiles/{name}/soul")@@@ -1251,10 -1323,19 +1322,19 @@@ async def get_profile_desktop_overlay(n"""The desktop appearance/interface overlay bundled with an importedprofile (``desktop.json`` at the profile root), or ``exists: false``."""overlay_path = _resolve_profile_dir(name) / "desktop.json"- if not overlay_path.is_file():- return {"exists": False, "desktop": None}- try:++ def _run():+ if not overlay_path.is_file():+ return _MISSINGimport json as _json- return {"exists": True, "desktop": _json.loads(overlay_path.read_text(encoding="utf-8-sig"))}- return _json.loads(overlay_path.read_text(encoding="utf-8"))++ return _json.loads(overlay_path.read_text(encoding="utf-8-sig"))++ try:+ overlay = await run_in_threadpool(_run)except Exception as e:raise HTTPException(status_code=500, detail=f"Could not read desktop.json: {e}")+ # _MISSING rather than None: an overlay file holding the document ``null``+ # exists, and must not be reported as absent.+ if overlay is _MISSING:+ return {"exists": False, "desktop": None}+ return {"exists": True, "desktop": overlay}diff --cc hermes_constants.pyindex b2d25110c7b,3032ea1ad12..1d426df9d5f--- a/hermes_constants.py+++ b/hermes_constants.py@@@ -146,32 -153,39 +154,59 @@@ def hermes_home_key(path: str | Path |Runtime registries use this key to isolate plugin-owned entries whilekeeping built-in registrations process-global. ``strict=False`` preservesuseful behavior for profiles whose directories have not been created yet.++ The resolved value is remembered per input path. A directory that does+ not exist yet is resolved without touching the cache, because the answer+ can change once it is created, for example when part of the path turns+ out to be a symlink.+ """+ candidate = Path(path) if path is not None else get_hermes_home()+ raw = str(candidate)+ cached = _HOME_KEY_CACHE.get(raw)+ if cached is not None:+ return cached+ expanded = candidate.expanduser()+ try:+ resolved = expanded.resolve(strict=True)+ except OSError:+ # Not on disk yet. Fall back to the lenient resolve and do not store+ # it, so the real answer is picked up once the directory appears.+ return os.path.normcase(str(expanded.resolve(strict=False)))+ key = os.path.normcase(str(resolved))+ _HOME_KEY_CACHE[raw] = key+ return key+++ def reset_hermes_home_key_cache() -> None:+ """Forget every remembered home key.++ For tests that move a home directory around on disk under one path.+ Normal callers never need this: a different home path is a different+ cache key already."""- candidate = Path(path) if path else get_hermes_home()- resolved = candidate.expanduser().resolve(strict=False)- return os.path.normcase(str(resolved))+ _HOME_KEY_CACHE.clear()+def normalize_scope(scope: str | Path | None) -> str | None:+ """Normalize a WRITE-side registry scope key, preserving ``None``.++ Two different contracts live on the same registries — do not unify them:++ * **Write / slot paths** (``register_*``, ``snapshot_registration``,+ ``restore_registration``, tool-registry slot lookup): ``None`` means+ the process-global layer and must stay ``None``. Use this function.+ * **Read paths** (``list_providers``, ``get_provider``): ``None`` means+ "the active home's scope" and must go through :func:`hermes_home_key`+ (falsy input resolves to the active default home). Using this+ function there hides every scoped registration — the exact bug+ fixed after e66a627aa5.++ Both normalize non-None values identically (resolved absolute path,+ normcase on Windows) so writes and reads agree on the key.+ """+ return hermes_home_key(scope) if scope is not None else None++def get_process_hermes_home() -> Path:"""Return the Hermes home for the running process, ignoring task overrides.diff --cc plugins/platforms/photon/adapter.pyindex 341071fb708,f4129cad435..c35ebf1401d--- a/plugins/platforms/photon/adapter.py+++ b/plugins/platforms/photon/adapter.py@@@ -460,8 -423,11 +460,8 @@@ def check_requirements() -> boolif not HTTPX_AVAILABLE:logger.warning("photon: httpx not installed — pip install httpx")return False- if not _node_command("node"):- logger.warning("photon: node binary not found on PATH or in the pm store")- if not shutil.which(_get_scoped_secret("PHOTON_NODE_BIN") or "node"):- logger.warning(- "photon: node binary '%s' not found on PATH",- _get_scoped_secret("PHOTON_NODE_BIN") or "node",- )++ if not (_get_scoped_secret("PHOTON_NODE_BIN") or _node_command("node")):++ logger.warning("photon: node binary not found on PATH, in the pm store, or via PHOTON_NODE_BIN")return Falseif not sidecar_deps_installed():# spectrum-ts not installed yet, or node_modules/ was partially created@@@ -785,9 -751,9 +785,9 @@@ class PhotonAdapter(BasePlatformAdapter_get_scoped_secret("PHOTON_SIDECAR_TOKEN") or secrets.token_hex(16))self._autostart_sidecar = str(- os.getenv("PHOTON_SIDECAR_AUTOSTART", "true")+ _get_scoped_secret("PHOTON_SIDECAR_AUTOSTART", "true")).lower() not in ("0", "false", "no")- self._node_bin = _node_command("node") or "node"- self._node_bin = _get_scoped_secret("PHOTON_NODE_BIN") or shutil.which("node") or "node"++ self._node_bin = _get_scoped_secret("PHOTON_NODE_BIN") or _node_command("node") or "node"# Presence watchdog. spectrum-ts only reconnects when its inbound# iterator throws or ends; a half-open ("zombie") gRPC socket makes thediff --cc scripts/ci/classify_changes.pyindex 415a3307ba9,71afcda6867..4aeb35d4c9b--- a/scripts/ci/classify_changes.py+++ b/scripts/ci/classify_changes.py@@@ -25,8 -25,12 +25,14 @@@ Lanesmust not run it.* ``npm_lock`` — semantic package-lock.json diff PR comment.* ``installer`` — PowerShell installer tests (Windows runner).+* ``bootstrap`` — the bootstrap installer lane: install.sh sandbox install,+ pin-fragment drift check, and shipped version-stamp verification.+ * ``desktop_updater`` — the Windows desktop-update hand-off script and the+ tests that drive the REAL ``windows.ps1`` (``-SelfTestUi`` / pipe drain /+ retry policy). These are integration tests of a PowerShell process on a+ shared runner; running them on every Python PR made their timing noise+ everyone's problem. They still run on push (fail-open) and whenever the+ script, its siblings, or their tests change.* ``rust`` — ``cargo test`` for the Tauri bootstrap installer. ``.rs``lives under ``apps/``, so without this lane a Rust change matched ``frontend``and only the TypeScript matrix ran.@@@ -112,12 -116,16 +118,22 @@@ _MCP_CATALOG_FILES = {"hermes_cli/mcp_c_INSTALLER_PATHS = ("scripts/tests/",)_INSTALLER_FILES = {"scripts/install.ps1", "scripts/install.cmd"}+# Bootstrap installer: the POSIX shell installer, the dev-checkout wrapper+# that carries the same pin fragment, and the Tauri app's non-Rust sources+# (the .rs/Cargo files are the ``rust`` lane's job). Changes here get the+# bootstrap-installer.yml lane — a real sandboxed install + stamp check.+_BOOTSTRAP_PATHS = ("apps/bootstrap-installer/",)+_BOOTSTRAP_FILES = {"scripts/install.sh", "setup-hermes.sh"}+ # Windows desktop-update hand-off (scripts/desktop-update/windows.ps1 + the+ # Electron side that launches it) and the pytest files that spawn it.+ _DESKTOP_UPDATER_PATHS = ("scripts/desktop-update/",)+ _DESKTOP_UPDATER_TEST_PREFIX = "tests/test_desktop_update_"+ _DESKTOP_UPDATER_FILES = {+ "apps/desktop/electron/updater-process.ts",+ "apps/desktop/electron/managed-ssh-update.ts",+ "tests/conftest.py",+ "pyproject.toml",+ }# Rust crates — currently just the Tauri bootstrap installer (Hermes-Setup).# These live under ``apps/``, so before this lane existed a ``.rs`` edit matched@@@ -215,9 -231,7 +239,10 @@@ def classify(files: list[str]) -> dict["uv_lock": any(f in ("pyproject.toml", "uv.lock") for f in files),"npm_lock": npm_lock,"installer": any(_is_installer(f) for f in files),+ "bootstrap": any(+ f.startswith(_BOOTSTRAP_PATHS) or f in _BOOTSTRAP_FILES for f in files+ ),+ "desktop_updater": any(_is_desktop_updater(f) for f in files),"rust": any(_is_rust(f) for f in files),"mcp_catalog": any(_is_mcp_catalog(f) for f in files),"ci_review": any(_is_ci_review(f) for f in files),@@@ -235,7 -249,7 +260,8 @@@ret["uv_lock"] = Trueret["npm_lock"] = Trueret["installer"] = True+ ret["bootstrap"] = True+ ret["desktop_updater"] = Trueret["rust"] = Trueret["nix"] = Trueret["ci_review"] = Truediff --cc scripts/install.ps1index f3c684b716f,6e64bc79c94..9ba37d11f75--- a/scripts/install.ps1+++ b/scripts/install.ps1@@@ -245,102 -3770,1186 +245,995 @@@ function Invoke-BootstrapPm}}-function Test-CuaDriverRuntimeContract {- param([Parameter(Mandatory = $true)][string]$DriverPath)-- try {- $versionOutput = (& $DriverPath --version 2>$null | Out-String).Trim()- if ($LASTEXITCODE -ne 0) {- return $false- }- $versionMatch = [regex]::Match($versionOutput, '(\d+\.\d+\.\d+)')- if (-not $versionMatch.Success) {- return $false- }- if ([version]($versionMatch.Groups[1].Value) -lt [version]'0.20.0') {- return $false- }-- $manifestOutput = (& $DriverPath manifest 2>$null | Out-String).Trim()- if ($LASTEXITCODE -ne 0 -or -not $manifestOutput) {- return $false- }- $manifest = $manifestOutput | ConvertFrom-Json- if (-not $manifest.mcp_invocation.args) {- return $false- }-- $required = @{- mcp = @('--socket', '--grant')- serve = @(- '--socket', '--permission-mode', '--capability-manifest',- '--approve-capability-manifest', '--embedded'- )- stop = @('--socket')- }- foreach ($commandName in $required.Keys) {- $command = $manifest.subcommands | Where-Object { $_.name -eq $commandName }- if (-not $command) {- return $false- }- $argNames = @($command.args | ForEach-Object { $_.name })- foreach ($requiredArg in $required[$commandName]) {- if ($requiredArg -notin $argNames) {- return $false- }- }- }- return $true- } catch {- return $false- }+function Stage-PythonDeps {+ Invoke-BootstrapPm}-# cua-driver powers the computer_use toolset (background desktop control).-# Provision it at install time so enabling the tool later -- via `hermes-# tools`, the dashboard, or the desktop app -- is a config flip, not a-# surprise multi-minute binary fetch. Best-effort and non-fatal: the enable-# paths still lazy-install via install_cua_driver() (hermes_cli/tools_config)-# when this step was skipped or failed.-function Install-CuaDriver {- if ($SkipComputerUse) {- Write-Info "Skipping Computer Use (cua-driver) install (-SkipComputerUse)"- return- }- $existingCuaDriver = Get-Command cua-driver -ErrorAction SilentlyContinue- if ($existingCuaDriver) {- if (Test-CuaDriverRuntimeContract -DriverPath $existingCuaDriver.Source) {- Write-Success "Computer Use driver (cua-driver) already installed and compatible"- return- }- Write-Warn "Existing cua-driver is old or incomplete; repairing it"- }+function Stage-NodeDeps {+ Log "tool dependencies are managed by pm (hermes pm install)"+}- Write-Info "Installing Computer Use driver (cua-driver)..."- $prevEAP = $ErrorActionPreference- $ErrorActionPreference = "Continue"- try {- # Same upstream installer `hermes computer-use install` runs. Bounded- # via a background job: the upstream installer serializes with its own- # lock (600s stale window), so the ceiling sits above that -- matching- # Hermes' _CUA_INSTALLER_TIMEOUT (660s).- $job = Start-Job -ScriptBlock {- Invoke-RestMethod -UseBasicParsing "https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts/install.ps1" | Invoke-Expression- }- if (Wait-Job $job -Timeout 660) {- Receive-Job $job -ErrorAction SilentlyContinue | Out-Null- Remove-Job $job -Force -ErrorAction SilentlyContinue- $installedCuaDriver = Get-Command cua-driver -ErrorAction SilentlyContinue- if ($installedCuaDriver -and (Test-CuaDriverRuntimeContract -DriverPath $installedCuaDriver.Source)) {- Write-Success "Computer Use driver installed (enable via 'hermes tools' -> Computer Use)"- } else {- Write-Warn "Computer Use driver install did not produce a compatible runtime -- repair it before enabling the tool."- Write-Info "Install later with: hermes computer-use install"- }- } else {- Stop-Job $job -ErrorAction SilentlyContinue- Remove-Job $job -Force -ErrorAction SilentlyContinue- Write-Warn "Computer Use driver install timed out -- it will install on demand when you enable the tool."- Write-Info "Install later with: hermes computer-use install"- }- } catch {- Write-Warn "Computer Use driver install failed: $_"- Write-Info "Install later with: hermes computer-use install"- } finally {- $ErrorActionPreference = $prevEAP+function Stage-Path {+ $binDir = Join-Path $HermesHome "bin"+ New-Item -ItemType Directory -Force -Path $binDir | Out-Null+ # Mint the boot launchers (hermes / hermes-acp) bound to the pm STORE+ # python with PYTHONPATH=repo;venv-site-packages — never the venv+ # python (no boot through the venv; pyvenv.cfg is inert dead config).+ # The venv python below is install-time machinery (the materializer),+ # not a boot path. On a fresh install the store interpreter does not+ # exist yet, so a runtime-resolving .cmd delegator is staged;+ # hermes_cli/_install_repair.py upgrades it to an exe once+ # `hermes pm install` materializes the store.+ $venvPython = Join-Path $InstallDir "venv\Scripts\python.exe"+ if (-not (Test-Path $venvPython)) { Fail "venv python missing at $venvPython" }+ Push-Location $InstallDir+ & $venvPython -c "from hermes_cli._launchers import ensure_install_launchers; import sys; written = ensure_install_launchers(r'$InstallDir', r'$binDir'); print(';'.join(written)); sys.exit(0 if written else 1)"+ $code = $LASTEXITCODE+ Pop-Location+ if ($code) { Fail "launcher staging failed" }+ $userPath = [Environment]::GetEnvironmentVariable("Path", "User")+ if ($userPath -notlike "*$binDir*") {+ [Environment]::SetEnvironmentVariable("Path", "$binDir;$userPath", "User")+ Log "added $binDir to your user PATH (new shells pick it up)"}+ Log "hermes command installed at $binDir"}-# Clear the cached Electron download + any half-written unpacked output so the-# next `npm run pack` re-downloads and re-stages from scratch. A corrupt zip in-# the per-user Electron download cache - most often a partial download resumed-# into the same file, leaving concatenated junk - makes electron-builder's-# `app-builder unpack-electron` extract a tree MISSING the electron binary, so-# the final `electron` -> `Hermes` rename dies with ENOENT and every re-run-# repeats the broken extraction forever.-#-# We deliberately do not validate the zip ourselves: the common-# prepended/concatenated-junk corruption slips past naive checks, so a-# self-rolled gate would skip the real-world case. We unconditionally drop the-# cached electron-*.zip (loose copy and any @electron/get hash-subdir copy) plus-# the stale unpacked dir, then let the caller retry once - @electron/get-# re-downloads with its own SHASUM verification, the real source of truth.-#-# Returns the removed paths. Best-effort: never throws.-function Clear-ElectronBuildCache {- param([string]$DesktopDir)- $removed = @()-- # Per-user Electron download cache dirs, honoring the overrides @electron/get- # respects, then the Windows default (%LOCALAPPDATA%\electron\Cache).- $cacheDirs = @()- if ($env:electron_config_cache) { $cacheDirs += $env:electron_config_cache }- if ($env:ELECTRON_CACHE) { $cacheDirs += $env:ELECTRON_CACHE }- if ($env:LOCALAPPDATA) { $cacheDirs += (Join-Path $env:LOCALAPPDATA 'electron\Cache') }- $cacheDirs += (Join-Path $HOME 'AppData\Local\electron\Cache')-- foreach ($dir in $cacheDirs) {- if (-not (Test-Path -LiteralPath $dir)) { continue }- # Recurse: the bad copy may be the top-level zip OR a copy inside an- # @electron/get hash subdir.- $removed += @(Get-ChildItem -LiteralPath $dir -Recurse -Filter 'electron-*.zip' -File -ErrorAction SilentlyContinue | ForEach-Object {- try { Remove-Item -LiteralPath $_.FullName -Force -ErrorAction Stop; $_.FullName } catch { }- })+function Stage-Config {+ foreach ($d in @("cron","sessions","logs","pairing","hooks","image_cache","audio_cache","memories","skills")) {+ New-Item -ItemType Directory -Force -Path (Join-Path $HermesHome $d) | Out-Null}-- # A half-written unpacked dir from an interrupted prior pack poisons the- # rename even after the zip is fixed (win-unpacked / win-arm64-unpacked).- $releaseDir = Join-Path $DesktopDir 'release'- if (Test-Path -LiteralPath $releaseDir) {- $removed += @(Get-ChildItem -LiteralPath $releaseDir -Directory -Filter '*-unpacked' -ErrorAction SilentlyContinue | ForEach-Object {- try { Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction Stop; $_.FullName } catch { }- })+ $envFile = Join-Path $HermesHome ".env"+ if (-not (Test-Path $envFile)) {+ $example = Join-Path $InstallDir ".env.example"+ if (Test-Path $example) { Copy-Item $example $envFile } else { New-Item -ItemType File -Path $envFile | Out-Null }}-- return $removed-}--# Last-resort Electron mirror after GitHub download fails (#47266).-$script:DesktopElectronFallbackMirror = "https://npmmirror.com/mirrors/electron/"--# Electron package dir -- workspace-local nest first, then root hoist.-function Get-ElectronDir {- param([string]$InstallDir)- $desktopLocal = Join-Path $InstallDir 'apps\desktop\node_modules\electron'- if (Test-Path -LiteralPath $desktopLocal) { return $desktopLocal }- return (Join-Path $InstallDir 'node_modules\electron')+ $cfg = Join-Path $HermesHome "config.yaml"+ $cfgExample = Join-Path $InstallDir "cli-config.yaml.example"+ if (-not (Test-Path $cfg) -and (Test-Path $cfgExample)) { Copy-Item $cfgExample $cfg }+ Log "config prepared in $HermesHome"}-# True when dist/ holds a usable Electron binary (#38673 / run-electron-builder.mjs).-function Test-ElectronDist {- param([string]$InstallDir)- $electronDir = Get-ElectronDir -InstallDir $InstallDir- $distExe = Join-Path $electronDir 'dist\electron.exe'- return (Test-Path -LiteralPath $distExe)+function Stage-Setup {+ if ($NonInteractive) { return }+ & (Join-Path $InstallDir "venv\Scripts\python.exe") (Join-Path $InstallDir "hermes") setup}-# Best-effort: run electron/install.js to populate dist/ (optional mirror).-function Restore-ElectronDist {- param([string]$InstallDir, [string]$Mirror)- if (Test-ElectronDist -InstallDir $InstallDir) { return $true }-- $electronDir = Get-ElectronDir -InstallDir $InstallDir- $distExe = Join-Path $electronDir 'dist\electron.exe'- $installer = Join-Path $electronDir 'install.js'- if (-not (Test-Path -LiteralPath $installer)) { return $false }- $node = Get-Command node -ErrorAction SilentlyContinue- if (-not $node) { return $false }-- $distDir = Join-Path $electronDir 'dist'- if (Test-Path -LiteralPath $distDir) {- Remove-Item -LiteralPath $distDir -Recurse -Force -ErrorAction SilentlyContinue- }- Remove-Item -LiteralPath (Join-Path $electronDir 'path.txt') -Force -ErrorAction SilentlyContinue-- $prevMirror = $env:ELECTRON_MIRROR- if ($Mirror) { $env:ELECTRON_MIRROR = $Mirror }- try {- # Out-Host so the downloader's progress shows on the console WITHOUT- # leaking into this function's return value (PowerShell returns every- # object left on the output stream, so a bare pipe here would make the- # boolean below ambiguous).- & $node.Source $installer 2>&1 | ForEach-Object { "$_" } | Out-Host- } catch {- } finally {- $env:ELECTRON_MIRROR = $prevMirror- }- return (Test-Path -LiteralPath $distExe)+function Stage-Gateway {+ if ($NonInteractive) { return }+ & (Join-Path $InstallDir "venv\Scripts\python.exe") (Join-Path $InstallDir "hermes") gateway install}-function Test-ElectronPkgStagedMissingDist {- param([string]$InstallDir)- $electronDir = Get-ElectronDir -InstallDir $InstallDir- return (- (Test-Path -LiteralPath (Join-Path $electronDir 'package.json')) -and- (Test-Path -LiteralPath (Join-Path $electronDir 'install.js')) -and- (-not (Test-ElectronDist -InstallDir $InstallDir))- )+function Stage-Desktop {+ & (Join-Path $InstallDir "venv\Scripts\python.exe") (Join-Path $InstallDir "hermes") desktop build+ if ($LASTEXITCODE) { Fail "desktop build failed" }}-function Try-RestoreElectronDist {- param([string]$InstallDir)- if (Restore-ElectronDist -InstallDir $InstallDir) { return $true }- if ($env:ELECTRON_MIRROR) { return $false }- return Restore-ElectronDist -InstallDir $InstallDir -Mirror $script:DesktopElectronFallbackMirror-}+function Stage-Complete {+ $commit = $Commit+ if (-not $commit) { $commit = git -C $InstallDir rev-parse HEAD 2>$null }+ if ($commit) {+ $marker = [ordered]@{+ schemaVersion = 1+ pinnedCommit = "$commit"+ pinnedBranch = $Branch+ completedAt = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")++ function Install-DesktopVoiceDeps {+ # Desktop ships with working voice out of the box: eagerly install the+ # wake-word + local-STT stacks ([wake] + [voice] extras) instead of+ # leaving them to lazy first-use install. Policy change (Teknium, July+ # 2026, #70509 testing): the first ear-click used to trigger a+ # multi-minute onnxruntime pip install that froze the UI and blew RPC+ # timeouts. Best-effort -- lazy install remains the fallback for anything+ # this step fails to fetch.+ if (-not $script:UvCmd) { Resolve-UvCmd }+ if (-not $script:UvCmd) {+ Write-Warn "uv unavailable -- voice/wake deps will lazy-install at first use instead"+ return+ }+ $env:VIRTUAL_ENV = "$InstallDir\venv"+ Write-Info "Installing voice + wake-word dependencies (onnxruntime, faster-whisper -- 1-3min)..."+ Push-Location $InstallDir+ try {+ Invoke-NativeWithRelaxedErrorAction { & $UvCmd pip install -e ".[wake,voice]" }+ if ($LASTEXITCODE -eq 0) {+ Write-Success "Voice + wake-word dependencies installed"+ } else {+ Write-Warn "Voice/wake dependency install failed (exit $LASTEXITCODE) -- they will lazy-install at first use"+ }+ } finally {+ Pop-Location+ }+ }++ function Install-Desktop {+ # Build apps/desktop into a launchable Hermes.exe. Only called from+ # Stage-Desktop, which is itself only included in the manifest when+ # -IncludeDesktop was passed to install.ps1.+ #+ # The workspace npm install at repo root (done by Install-NodeDeps for+ # browser tools) does NOT pull apps/desktop's dependencies, because the+ # browser-tools workspace at $InstallDir\package.json is a separate+ # workspace from apps/*. We do a full root-level `npm install` here+ # so the workspace resolves apps/desktop's deps (including Electron+ # itself, ~150MB), then run `npm run pack` in apps/desktop which+ # produces the unpacked binary at apps/desktop/release/<os>-unpacked/.+ #+ # The Tauri bootstrap installer's launch_hermes_desktop command+ # resolves apps/desktop/release/win-unpacked/Hermes.exe directly,+ # so an "unpacked" build (electron-builder --dir) is enough -- we+ # don't need to produce an NSIS/MSI artifact here.++ # Always re-resolve Node here. Stages run in separate PowerShell processes,+ # so $script:HasNode from Stage-Node isn't visible; more importantly Test-Node+ # enforces the supported Node lines and prepends the Hermes-managed Node to+ # PATH, so the build never runs on an unsupported system Node -- the cause+ # of the opaque "Build desktop app ... exit code 1" failure (Vite crashes on+ # old Node).+ Test-Node | Out-Null+ if (-not (Get-Command npm -ErrorAction SilentlyContinue)) {+ Write-Warn "Skipping desktop build (Node.js / npm not on PATH)"+ $script:_StageSkippedReason = "Node.js not available"+ return+ }++ $desktopDir = "$InstallDir\apps\desktop"+ if (-not (Test-Path "$desktopDir\package.json")) {+ Write-Warn "Skipping desktop build (apps/desktop not present in checkout)"+ $script:_StageSkippedReason = "apps/desktop not present"+ return+ }++ $npmCmd = Get-Command npm -ErrorAction SilentlyContinue+ if (-not $npmCmd) {+ Write-Warn "Skipping desktop build (npm not on PATH)"+ $script:_StageSkippedReason = "npm not found"+ return+ }+ $npmExe = $npmCmd.Source+ if ($npmExe -like "*.ps1") {+ $sibling = Join-Path (Split-Path $npmExe -Parent) "npm.cmd"+ if (Test-Path $sibling) { $npmExe = $sibling }+ }++ # 1. Workspace-level install so apps/desktop's deps (Electron, Vite,+ # node-pty prebuilds, etc.) actually land in node_modules. This is+ # the SAME `npm install` Install-NodeDeps does for browser tools,+ # but at the root rather than the browser-tools workspace, so all+ # apps/* workspaces resolve.+ Write-Info "Installing desktop workspace dependencies (this includes Electron ~150MB, takes 1-3min)..."+ Push-Location $InstallDir+ $prevEAP = $ErrorActionPreference+ try {+ $ErrorActionPreference = "Continue"+ # Drop --silent so npm emits its full progress + error trail.+ # When this fails on a non-dev box (e.g. native-module build+ # without VS Build Tools, ETARGET on a transitive, etc.), the+ # actual reason needs to reach the Tauri installer's log; with+ # --silent it was completely suppressed and the user just saw+ # "exit 1" with no actionable detail.+ #+ # The streaming sink in bootstrap.rs's run_install_script+ # captures every stdout/stderr line as it's emitted, so we don't+ # need a side TEMP log file -- the installer's bootstrap log+ # IS the artifact a support engineer reads.+ #+ # Prefer `npm ci`: it wipes node_modules and reinstalls from the+ # lockfile, always producing a complete tree. Bare `npm install`+ # can report "up to date" against a stale+ # node_modules\.package-lock.json marker while node_modules is+ # actually empty (Windows workspace-hoisting flake), leaving+ # tsc/typescript unresolved so `npm run pack`'s `tsc -b` dies with+ # no obvious cause. Fall back to `npm install` only if `npm ci`+ # fails (lockfile out of sync / very old npm without ci).+ #+ # Tee the merged output into $npmOut while still emitting every line+ # live. We don't need a side log file (the bootstrap streaming sink+ # is the artifact), but on failure we scan $npmOut for the TLS-trust+ # signature so corporate-proxy users get the NODE_EXTRA_CA_CERTS hint+ # instead of an opaque "exit 1" (issue #38016).+ & $npmExe ci 2>&1 | ForEach-Object { "$_" } | Tee-Object -Variable npmOut+ $code = $LASTEXITCODE+ if ($code -ne 0) {+ Write-Info " npm ci failed (exit $code) -- retrying with npm install..."+ & $npmExe install 2>&1 | ForEach-Object { "$_" } | Tee-Object -Variable npmOut+ $code = $LASTEXITCODE+ }+ $ErrorActionPreference = $prevEAP+ if ($code -ne 0) {+ if (Test-ElectronPkgStagedMissingDist -InstallDir $InstallDir) {+ Write-Warn "Desktop dependency install failed with a missing Electron dist; attempting self-heal..."+ Try-RestoreElectronDist -InstallDir $InstallDir | Out-Null+ } else {+ Show-NpmCertHint ($npmOut -join "`n") | Out-Null+ # Replay npm's own debug log into our stream: the terse+ # summary above rarely contains the postinstall stderr+ # (e.g. Electron's install.js) that explains the failure.+ Write-NpmDebugLogTail -NpmOutput ($npmOut -join "`n")+ throw "desktop workspace npm install failed (exit $code) -- see lines above for cause"+ }+ } else {+ Write-Success "Desktop workspace dependencies installed"+ }+ } catch {+ if ($prevEAP) { $ErrorActionPreference = $prevEAP }+ Pop-Location+ throw+ }+ Pop-Location++ # 2. Build apps/desktop. `npm run pack` runs:+ # assert-root-install + write-build-stamp + stage-native-deps ++ # tsc -b + vite build + electron-builder --dir+ # The --dir mode produces an unpacked Hermes.exe in+ # apps/desktop/release/win-unpacked/ without bundling NSIS/MSI;+ # we don't need a distributable installer artifact, just a+ # launchable binary the Tauri installer can spawn.+ #+ # CSC_IDENTITY_AUTO_DISCOVERY=false tells electron-builder we are+ # NOT signing the output. Combined with signAndEditExecutable=false in+ # apps/desktop/package.json's build.win block, electron-builder never+ # invokes signtool and therefore never fetches/extracts winCodeSign+ # (whose macOS symlinks crash 7-Zip on non-admin Windows -- a dead end we+ # are NOT trying to work around). The Hermes icon + product name are+ # stamped onto Hermes.exe by our own rcedit step (Set-DesktopExeIdentity)+ # AFTER this build, completely decoupled from electron-builder signing.+ #+ # WIN_CSC_LINK and WIN_CSC_KEY_PASSWORD explicitly cleared as+ # belt-and-suspenders: if the user's environment has them set+ # for some other tool, electron-builder would still try to sign.+ Write-Info "Building desktop app (this takes 1-3 minutes)..."+ $buildLog = "$env:TEMP\hermes-desktop-build-$(Get-Random).log"+ # Seed GITHUB_SHA for write-build-stamp.mjs. The stamp prefers CI env vars+ # over `git rev-parse`, so this covers: (1) node can't find git.exe on PATH+ # even though this PowerShell session can, (2) ZIP/init trees that still+ # lack a HEAD after a failed post-extract fetch. Without it the desktop+ # pack dies with "could not determine git commit" (#50823).+ if (-not $env:GITHUB_SHA) {+ if ($Commit) {+ $env:GITHUB_SHA = $Commit+ } else {+ Push-Location $InstallDir+ try {+ $global:LASTEXITCODE = 0+ $resolvedSha = & git -c windows.appendAtomically=false rev-parse HEAD 2>$null+ if ($LASTEXITCODE -ne 0 -or -not $resolvedSha) {+ # ZIP path may have FETCH_HEAD after a fetch even when HEAD is unset.+ $global:LASTEXITCODE = 0+ $resolvedSha = & git -c windows.appendAtomically=false rev-parse FETCH_HEAD 2>$null+ }+ if ($LASTEXITCODE -eq 0 -and $resolvedSha) {+ $env:GITHUB_SHA = ("$resolvedSha").Trim()+ }+ } catch { } finally {+ Pop-Location+ }+ }+ }+ if (-not $env:GITHUB_REF_NAME) {+ $env:GITHUB_REF_NAME = if ($Branch) { $Branch } else { "main" }+ }+ if ($env:GITHUB_SHA) {+ $shaPreview = if ($env:GITHUB_SHA.Length -ge 12) { $env:GITHUB_SHA.Substring(0, 12) } else { $env:GITHUB_SHA }+ Write-Info "Desktop build stamp: $shaPreview ($($env:GITHUB_REF_NAME))"+ } else {+ Write-Warn "Could not resolve a git commit for the desktop stamp -- write-build-stamp will use its non-git fallback"+ }+ Push-Location $desktopDir+ $prevEAP = $ErrorActionPreference+ $prevCSCAuto = $env:CSC_IDENTITY_AUTO_DISCOVERY+ $prevWinCscLink = $env:WIN_CSC_LINK+ $prevWinCscKeyPassword = $env:WIN_CSC_KEY_PASSWORD+ try {+ $ErrorActionPreference = "Continue"+ $env:CSC_IDENTITY_AUTO_DISCOVERY = "false"+ $env:WIN_CSC_LINK = ""+ $env:WIN_CSC_KEY_PASSWORD = ""+ & $npmExe run pack 2>&1 | ForEach-Object { "$_" } | Tee-Object -FilePath $buildLog+ $code = $LASTEXITCODE+ if ($code -ne 0) {+ $purged = @()+ $restored = $false+ if (-not (Test-ElectronDist -InstallDir $InstallDir)) {+ $purged = @(Clear-ElectronBuildCache -DesktopDir $desktopDir)+ $restored = Restore-ElectronDist -InstallDir $InstallDir+ }+ if ($restored) {+ Write-Warn "Desktop build failed - refreshed the Electron download, retrying once:"+ foreach ($p in $purged) { Write-Info " - $p" }+ & $npmExe run pack 2>&1 | ForEach-Object { "$_" } | Tee-Object -FilePath $buildLog+ $code = $LASTEXITCODE+ }+ }+ if ($code -ne 0 -and -not $env:ELECTRON_MIRROR) {+ $mirror = $script:DesktopElectronFallbackMirror+ Write-Warn "Desktop build still failing - the Electron download from GitHub looks blocked."+ Write-Warn "Re-downloading Electron via a public mirror ($mirror), then rebuilding:"+ Write-Info " (set ELECTRON_MIRROR yourself to use a different/trusted mirror)"+ if (-not (Test-ElectronDist -InstallDir $InstallDir)) {+ Restore-ElectronDist -InstallDir $InstallDir -Mirror $mirror | Out-Null+ }+ $prevMirror = $env:ELECTRON_MIRROR+ $env:ELECTRON_MIRROR = $mirror+ try {+ & $npmExe run pack 2>&1 | ForEach-Object { "$_" } | Tee-Object -FilePath $buildLog+ $code = $LASTEXITCODE+ } finally {+ $env:ELECTRON_MIRROR = $prevMirror+ }+ }+ $ErrorActionPreference = $prevEAP+ if ($code -ne 0) {+ $errText = Get-Content $buildLog -Raw -ErrorAction SilentlyContinue+ if ($errText) {+ $snippet = if ($errText.Length -gt 1800) { $errText.Substring(0, 1800) + "..." } else { $errText }+ Write-Info " desktop build output:"+ foreach ($line in $snippet -split "`n") { Write-Host " $line" -ForegroundColor DarkGray }+ Write-Info " Full log: $buildLog"+ }+ # `npm run pack` failures (lifecycle script exits) also land in+ # npm's debug log; replay it so the bootstrap log carries the+ # full evidence even when $buildLog's tail cuts off the cause.+ Write-NpmDebugLogTail -NpmOutput $errText+ throw "apps/desktop build failed (exit $code)"+ }+ Write-Success "Desktop app built"+ Remove-Item -LiteralPath $buildLog -Force -ErrorAction SilentlyContinue+ } catch {+ if ($prevEAP) { $ErrorActionPreference = $prevEAP }+ Pop-Location+ throw+ } finally {+ # Restore env to whatever the caller had -- don't leak our+ # signing-off override into anything install.ps1 invokes later+ # (Stage-PlatformSdks, etc.).+ $env:CSC_IDENTITY_AUTO_DISCOVERY = $prevCSCAuto+ $env:WIN_CSC_LINK = $prevWinCscLink+ $env:WIN_CSC_KEY_PASSWORD = $prevWinCscKeyPassword+ }+ Pop-Location++ # 3. Sanity-check the produced binary. Probe both arches so this works+ # on x64 and arm64 build machines.+ $exeCandidates = @(+ "$desktopDir\release\win-unpacked\Hermes.exe",+ "$desktopDir\release\win-arm64-unpacked\Hermes.exe"+ )+ $found = $false+ $desktopExe = $null+ foreach ($cand in $exeCandidates) {+ if (Test-Path $cand) {+ Write-Success "Desktop ready: $cand"+ $desktopExe = $cand+ $found = $true+ break+ }+ }+ if (-not $found) {+ throw "Desktop build completed but no Hermes.exe was found under $desktopDir\release\*-unpacked\"+ }++ # 3b. The Hermes icon + identity are stamped onto Hermes.exe by the+ # electron-builder `afterPack` hook (apps/desktop/scripts/after-pack.mjs)+ # during `npm run pack` above -- for every build, so the installer's+ # --update rebuild stays branded too. No separate stamp step needed here.+ # electron-builder's own rcedit step stays disabled (signAndEditExecutable+ # =false) because enabling it drags in signtool -> winCodeSign -> the+ # unfixable symlink crash; the afterPack hook runs rcedit directly.++ # 3c. Grant ALL APPLICATION PACKAGES (S-1-15-2-2) RX on the unpacked app+ # directory. Chromium's GPU/renderer sandboxes CHECK-fail with+ # 0x80000003 when this ACE is missing alongside orphan AppContainer+ # SIDs under %LOCALAPPDATA% (electron/electron#51761, hermes-agent#38216).+ # Best-effort -- never fail an otherwise-good install over ACL repair.+ try {+ $appDir = Split-Path -Parent $desktopExe+ & icacls $appDir /grant "*S-1-15-2-2:(OI)(CI)(RX)" /T /C /Q | Out-Null+ if ($LASTEXITCODE -eq 0) {+ Write-Success "Granted AppContainer read access on $appDir"+ } else {+ Write-Warn "icacls AppContainer grant returned exit $LASTEXITCODE for $appDir"+ }+ } catch {+ Write-Warn "Could not grant AppContainer ACL: $($_.Exception.Message)"+ }++ # 4. Create Start Menu + Desktop shortcuts pointing DIRECTLY at the packed+ # Hermes.exe. We deliberately do NOT point them at `hermes desktop`: that+ # command rebuilds (npm install + electron-builder) on every launch,+ # which would cost minutes each time. The packed exe is the consumer --+ # launching it directly is instant, and updates flow through the+ # installer's --update path (which rebuilds once, then relaunches).+ New-DesktopShortcuts -TargetExe $desktopExe+ }++ function New-DesktopShortcuts {+ param([Parameter(Mandatory = $true)][string]$TargetExe)++ # Best-effort: a shortcut failure must never fail an otherwise-good install.+ try {+ $shell = New-Object -ComObject WScript.Shell+ $workDir = Split-Path -Parent $TargetExe++ # Prefer the standalone icon.ico (shipped beside the exe via+ # electron-builder extraResources -> resources/icon.ico) over the exe's+ # embedded resource. An explicit .ico path is more stable across update+ # cycles: pointing at "$TargetExe,0" makes Windows cache the icon it+ # extracted from the exe at shortcut-creation time, and that cached+ # bitmap can persist (showing the OLD/Electron icon) even after the exe+ # is re-stamped on update. A dedicated .ico sidesteps that extraction.+ $iconIco = Join-Path $workDir 'resources\icon.ico'+ if (Test-Path $iconIco) {+ $iconLocation = "$iconIco,0"+ } else {+ $iconLocation = "$TargetExe,0"+ }++ $targets = @(+ (Join-Path ([Environment]::GetFolderPath('Programs')) 'Hermes.lnk'),+ (Join-Path ([Environment]::GetFolderPath('Desktop')) 'Hermes.lnk')+ )++ foreach ($lnkPath in $targets) {+ try {+ $parent = Split-Path -Parent $lnkPath+ if (-not (Test-Path $parent)) {+ New-Item -ItemType Directory -Force -Path $parent | Out-Null+ }+ $sc = $shell.CreateShortcut($lnkPath)+ $sc.TargetPath = $TargetExe+ $sc.WorkingDirectory = $workDir+ $sc.IconLocation = $iconLocation+ $sc.Description = 'Hermes Agent'+ $sc.Save()+ Write-Success "Shortcut created: $lnkPath"+ } catch {+ Write-Warn "Could not create shortcut $lnkPath : $($_.Exception.Message)"+ }+ }++ # Bust the Windows shell icon cache so the desktop/Start-Menu shortcut+ # repaints with the (possibly newly-stamped) icon instead of a stale+ # cached bitmap. Critical on the --update path: the exe was re-stamped+ # with the Hermes icon, but without this the shortcut can keep drawing+ # the old Electron icon until the user manually refreshes / reboots.+ # Best-effort and silent -- never fail the install over a cosmetic cache.+ try {+ & ie4uinit.exe -show 2>$null+ } catch {+ # ie4uinit may be absent/renamed on some SKUs -- ignore.+ }+ } catch {+ Write-Warn "Skipping shortcut creation: $($_.Exception.Message)"+ }+ }++ function Install-PlatformSdks {+ # Ensure messaging-platform SDKs matching tokens the user added to+ # ~/.hermes/.env are importable. Two problems this solves:+ #+ # 1. The tiered `uv pip install` cascade above can fall through to a+ # lower tier when the first fails (common when RL git deps choke),+ # which silently skips some messaging SDKs from [messaging].+ # 2. `uv` creates the venv without pip. If a messaging SDK ends up+ # missing, the user can't `pip install python-telegram-bot` to+ # recover -- pip simply isn't in their venv.+ #+ # Strategy: bootstrap pip via `python -m ensurepip` (idempotent), then+ # for each token set in .env, verify the matching SDK imports. If not,+ # run one targeted `pip install` as last-chance recovery. Keeps fresh+ # Windows installs from hitting silent "python-telegram-bot not installed"+ # at runtime.+ if ($NoVenv) {+ Write-Info "Skipping platform-SDK verification (-NoVenv: no venv to bootstrap)"+ return+ }++ $pythonExe = "$InstallDir\venv\Scripts\python.exe"+ if (-not (Test-Path $pythonExe)) {+ Write-Warn "Skipping platform-SDK verification: $pythonExe not found"+ return+ }++ $envPath = "$HermesHome\.env"+ if (-not (Test-Path $envPath)) { return }+ $envLines = Get-Content $envPath -ErrorAction SilentlyContinue++ # Map: env var set in .env -> (import name, pip spec matching [messaging] extra).+ # Specs mirror pyproject.toml to avoid version drift.+ $sdkMap = @(+ @{ Var = "TELEGRAM_BOT_TOKEN"; Import = "telegram"; Spec = "python-telegram-bot[webhooks]>=22.6,<23" },+ @{ Var = "DISCORD_BOT_TOKEN"; Import = "discord"; Spec = "discord.py[voice]>=2.7.1,<3" },+ @{ Var = "SLACK_BOT_TOKEN"; Import = "slack_sdk"; Spec = "slack-sdk>=3.27.0,<4" },+ @{ Var = "SLACK_APP_TOKEN"; Import = "slack_bolt";Spec = "slack-bolt>=1.18.0,<2" },+ @{ Var = "WHATSAPP_ENABLED"; Import = "qrcode"; Spec = "qrcode>=7.0,<8" }+ )++ # Which tokens are actually set (not placeholder)?+ $needed = @()+ foreach ($sdk in $sdkMap) {+ $match = $envLines | Where-Object {+ $_ -match ("^" + [regex]::Escape($sdk.Var) + "=.+") `+ -and $_ -notmatch "your-token-here" `+ -and $_ -notmatch "^\s*#"+ }+ if ($match) { $needed += $sdk }+ }+ if ($needed.Count -eq 0) { return }++ Write-Host ""+ Write-Info "Verifying platform SDKs for tokens found in $envPath ..."++ # Verify each SDK's import without triggering side-effect imports.+ # Quirk: PowerShell wraps non-zero-exit native stderr as a+ # NativeCommandError that prints even with `2>$null` / `*> $null`+ # unless we set $ErrorActionPreference to SilentlyContinue for the+ # span. Save + restore rather than nuking globally.+ $prevEAP = $ErrorActionPreference+ $ErrorActionPreference = "SilentlyContinue"+ try {+ $missing = @()+ foreach ($sdk in $needed) {+ & $pythonExe -c "import $($sdk.Import)" 2>&1 | Out-Null+ if ($LASTEXITCODE -ne 0) {+ $missing += $sdk+ Write-Warn " $($sdk.Import) NOT importable (needed for $($sdk.Var))"+ } else {+ Write-Success " $($sdk.Import) OK"+ }+ }+ } finally {+ $ErrorActionPreference = $prevEAP+ }+ if ($missing.Count -eq 0) { return }++ # Bootstrap pip into the venv if it isn't there. `uv` creates venvs+ # without pip; ensurepip is the stdlib-blessed way to add it.+ $prevEAP = $ErrorActionPreference+ $ErrorActionPreference = "SilentlyContinue"+ try {+ & $pythonExe -m pip --version 2>&1 | Out-Null+ if ($LASTEXITCODE -ne 0) {+ Write-Info "Bootstrapping pip into venv (uv doesn't ship pip)..."+ & $pythonExe -m ensurepip --upgrade 2>&1 | Out-Null+ if ($LASTEXITCODE -ne 0) {+ Write-Warn "ensurepip failed -- can't auto-install missing SDKs."+ Write-Info "Manual recovery: $UvCmd pip install `"$($missing[0].Spec)`""+ return+ }+ }++ foreach ($sdk in $missing) {+ Write-Info " Installing $($sdk.Spec) ..."+ & $pythonExe -m pip install $sdk.Spec 2>&1 | ForEach-Object { Write-Host " $_" }+ if ($LASTEXITCODE -eq 0) {+ Write-Success " Installed $($sdk.Import)"+ } else {+ Write-Warn " Failed to install $($sdk.Spec). Recover manually: $pythonExe -m pip install `"$($sdk.Spec)`""+ }+ }+ } finally {+ $ErrorActionPreference = $prevEAP+ }+ }++ function Invoke-SetupWizard {+ if ($SkipSetup) {+ Write-Info "Skipping setup wizard (-SkipSetup)"+ return+ }++ if ($NonInteractive) {+ # The setup wizard prompts for API keys, model choice, persona, etc.+ # Non-interactive callers (GUI installer) own that UX themselves; let+ # them drive it after install.ps1 returns.+ Write-Info "Skipping setup wizard (non-interactive). Configure via the GUI or 'hermes setup'."+ return+ }++ Write-Host ""+ Write-Info "Starting setup wizard..."+ Write-Host ""++ Push-Location $InstallDir++ # Run hermes setup using the venv Python directly (no activation needed)+ if (-not $NoVenv) {+ & ".\venv\Scripts\python.exe" -m hermes_cli.main setup+ } else {+ python -m hermes_cli.main setup+ }++ Pop-Location+ }++ function Start-GatewayIfConfigured {+ $envPath = "$HermesHome\.env"+ if (-not (Test-Path $envPath)) { return }++ $hasMessaging = $false+ $content = Get-Content $envPath -ErrorAction SilentlyContinue+ foreach ($var in @("TELEGRAM_BOT_TOKEN", "DISCORD_BOT_TOKEN", "SLACK_BOT_TOKEN", "SLACK_APP_TOKEN", "WHATSAPP_ENABLED")) {+ $match = $content | Where-Object { $_ -match "^${var}=.+" -and $_ -notmatch "your-token-here" }+ if ($match) { $hasMessaging = $true; break }+ }++ if (-not $hasMessaging) { return }++ $hermesCmd = "$InstallDir\venv\Scripts\hermes.exe"+ if (-not (Test-Path $hermesCmd)) {+ $hermesCmd = "hermes"+ }++ # If WhatsApp is enabled but not yet paired, run foreground for QR scan+ $whatsappEnabled = $content | Where-Object { $_ -match "^WHATSAPP_ENABLED=true" }+ $whatsappSession = "$HermesHome\whatsapp\session\creds.json"+ if ($whatsappEnabled -and -not (Test-Path $whatsappSession)) {+ Write-Host ""+ Write-Info "WhatsApp is enabled but not yet paired."+ Write-Info "Running 'hermes whatsapp' to pair via QR code..."+ Write-Host ""+ # Non-interactive callers (GUI installer, CI) skip the QR-pair prompt;+ # WhatsApp pairing requires a human looking at a phone camera, so the+ # downstream UI is responsible for surfacing this when it makes sense.+ if (-not $NonInteractive) {+ $response = Read-Host "Pair WhatsApp now? [Y/n]"+ if ($response -eq "" -or $response -match "^[Yy]") {+ try {+ & $hermesCmd whatsapp+ } catch {+ # Expected after pairing completes+ }+ }+ } else {+ Write-Info "Skipping WhatsApp pairing prompt (non-interactive)."+ }+ }++ Write-Host ""+ Write-Info "Messaging platform token detected!"+ Write-Info "The gateway handles messaging platforms and cron job execution."+ Write-Host ""++ # In non-interactive mode the gateway lifecycle is the caller's problem+ # (the GUI manages its own gateway process, CI doesn't want background+ # services on the build agent, etc.). Treat it like the user declined.+ if ($NonInteractive) {+ Write-Info "Skipping gateway autostart prompt (non-interactive)."+ Write-Info "Start the gateway later with: hermes gateway"+ return+ }++ $response = Read-Host "Would you like to start the gateway now? [Y/n]"++ if ($response -eq "" -or $response -match "^[Yy]") {+ Write-Info "Starting gateway in background..."+ try {+ $logFile = "$HermesHome\logs\gateway.log"+ Start-Process -FilePath $hermesCmd -ArgumentList "gateway" `+ -RedirectStandardOutput $logFile `+ -RedirectStandardError "$HermesHome\logs\gateway-error.log" `+ -WindowStyle Hidden+ Write-Success "Gateway started! Your bot is now online."+ Write-Info "Logs: $logFile"+ Write-Info "To stop: close the gateway process from Task Manager"+ } catch {+ Write-Warn "Failed to start gateway. Run manually: hermes gateway"+ }+ } else {+ Write-Info "Skipped. Start the gateway later with: hermes gateway"+ }+ }++ function Write-Completion {+ Write-Host ""+ Write-Host "+---------------------------------------------------------+" -ForegroundColor Green+ Write-Host "| [OK] Installation Complete! |" -ForegroundColor Green+ Write-Host "+---------------------------------------------------------+" -ForegroundColor Green+ Write-Host ""++ # Show file locations+ Write-Host "* Your files:" -ForegroundColor Cyan+ Write-Host ""+ Write-Host " Config: " -NoNewline -ForegroundColor Yellow+ Write-Host "$HermesHome\config.yaml"+ Write-Host " API Keys: " -NoNewline -ForegroundColor Yellow+ Write-Host "$HermesHome\.env"+ Write-Host " Data: " -NoNewline -ForegroundColor Yellow+ Write-Host "$HermesHome\cron\, sessions\, logs\"+ Write-Host " Code: " -NoNewline -ForegroundColor Yellow+ Write-Host "$HermesHome\hermes-agent\"+ Write-Host ""++ Write-Host "---------------------------------------------------------" -ForegroundColor Cyan+ Write-Host ""+ Write-Host "* Commands:" -ForegroundColor Cyan+ Write-Host ""+ Write-Host " hermes " -NoNewline -ForegroundColor Green+ Write-Host "Start chatting"+ Write-Host " hermes setup " -NoNewline -ForegroundColor Green+ Write-Host "Configure API keys & settings"+ Write-Host " hermes config " -NoNewline -ForegroundColor Green+ Write-Host "View/edit configuration"+ Write-Host " hermes config edit " -NoNewline -ForegroundColor Green+ Write-Host "Open config in editor"+ Write-Host " hermes gateway " -NoNewline -ForegroundColor Green+ Write-Host "Start messaging gateway (Telegram, Discord, etc.)"+ Write-Host " hermes update " -NoNewline -ForegroundColor Green+ Write-Host "Update to latest version"+ Write-Host ""++ Write-Host "---------------------------------------------------------" -ForegroundColor Cyan+ Write-Host ""+ Write-Host "[*] Restart your terminal for PATH changes to take effect" -ForegroundColor Yellow+ Write-Host ""++ if (-not $HasNode) {+ Write-Host "Note: Node.js could not be installed automatically." -ForegroundColor Yellow+ Write-Host "Browser tools need Node.js. Install manually:" -ForegroundColor Yellow+ Write-Host " https://nodejs.org/en/download/" -ForegroundColor Yellow+ Write-Host ""+ }++ if (-not $HasRipgrep) {+ Write-Host "Note: ripgrep (rg) was not installed. For faster file search:" -ForegroundColor Yellow+ Write-Host " winget install BurntSushi.ripgrep.MSVC" -ForegroundColor Yellow+ Write-Host ""+ }+ }++ # ============================================================================+ # Stage protocol+ # ============================================================================+ #+ # install.ps1 supports a small, stable "stage protocol" that lets programmatic+ # callers (the desktop GUI's onboarding wizard, CI, future install.sh, etc.)+ # drive the install one step at a time and surface progress/errors with their+ # own UI. CLI users running the canonical `irm | iex` one-liner never+ # encounter this -- default invocation behaves exactly as before.+ #+ # Entry points:+ #+ # install.ps1 Interactive install (today's behavior).+ # install.ps1 -ProtocolVersion Emit the protocol version integer.+ # install.ps1 -Manifest Emit the stage manifest as JSON.+ # install.ps1 -Stage <name> Run one stage and emit its result.+ # install.ps1 -NonInteractive Disable all Read-Host prompts (also+ # skips the setup wizard and the gateway+ # autostart prompt). Can be combined+ # with default invocation to do a full+ # non-interactive install.+ # install.ps1 -Json Emit machine-readable JSON instead of+ # the human-readable success banner at+ # the end of a full install.+ #+ # Manifest schema (the JSON returned by -Manifest):+ #+ # {+ # "protocol_version": 1,+ # "stages": [+ # {+ # "name": "uv",+ # "title": "Installing uv package manager",+ # "category": "prereqs",+ # "needs_user_input": false+ # },+ # ...+ # ]+ # }+ #+ # Stage result (the JSON written by -Stage <name>):+ #+ # {+ # "stage": "uv",+ # "ok": true,+ # "skipped": false,+ # "reason": null,+ # "duration_ms": 1234+ # }+ #+ # Exit codes:+ #+ # 0 -- success (stage ran, or stage was deliberately skipped).+ # 1 -- generic failure; the stage threw.+ # 2 -- unknown stage name passed to -Stage.+ #+ # Adding a stage:+ #+ # 1. Append an entry to $InstallStages below.+ # 2. Make sure the worker function it points at is idempotent and respects+ # $NonInteractive when it has prompts. Add it before "configure"+ # (the wizard) or "gateway" (autostart) if it should run unconditionally;+ # after those if it's optional post-install glue.+ # 3. Do NOT bump $InstallStageProtocolVersion -- adding stages is additive.+ # Drivers iterate the manifest dynamically.+ #+ # ============================================================================++ # Stage definitions -- the single source of truth. Each entry maps a stable+ # stage name (the API contract drivers depend on) to the worker function that+ # implements it. ``Title`` is what UIs show; ``Category`` lets UIs group+ # stages; ``NeedsUserInput`` tells UIs "this stage prompts -- either skip it+ # or arrange to provide answers another way."+ $InstallStages = @(+ @{ Name = "uv"; Title = "Installing uv package manager"; Category = "prereqs"; NeedsUserInput = $false; Worker = "Stage-Uv" }+ @{ Name = "git"; Title = "Installing Git"; Category = "prereqs"; NeedsUserInput = $false; Worker = "Stage-Git" }+ @{ Name = "node"; Title = "Detecting Node.js"; Category = "prereqs"; NeedsUserInput = $false; Worker = "Stage-Node" }+ @{ Name = "system-packages"; Title = "Installing ripgrep and ffmpeg"; Category = "prereqs"; NeedsUserInput = $false; Worker = "Stage-SystemPackages" }+ @{ Name = "repository"; Title = "Cloning Hermes repository"; Category = "install"; NeedsUserInput = $false; Worker = "Stage-Repository" }+ # Managed Python lives under $InstallDir\.hermes-runtime, so the checkout+ # must exist before this stage creates that directory. Otherwise the later+ # repository stage treats the runtime-only directory as a broken checkout,+ # parks it, and leaves Stage-Venv with no managed interpreter.+ @{ Name = "python"; Title = "Verifying Python $PythonVersion"; Category = "prereqs"; NeedsUserInput = $false; Worker = "Stage-Python" }+ @{ Name = "venv"; Title = "Creating Python virtual environment"; Category = "install"; NeedsUserInput = $false; Worker = "Stage-Venv" }+ @{ Name = "dependencies"; Title = "Installing Python dependencies"; Category = "install"; NeedsUserInput = $false; Worker = "Stage-Dependencies" }+ @{ Name = "node-deps"; Title = "Installing Node.js dependencies"; Category = "install"; NeedsUserInput = $false; Worker = "Stage-NodeDeps" }+ )+ if ($IncludeDesktop) {+ # Insert AFTER node-deps so workspace npm is already installed when+ # the desktop build runs. Inserted only when explicitly requested+ # (Hermes-Setup.exe), never via the irm|iex CLI one-liner.+ $InstallStages += @{ Name = "desktop"; Title = "Building desktop app"; Category = "install"; NeedsUserInput = $false; Worker = "Stage-Desktop" }+ }+ $InstallStages += @(+ @{ Name = "path"; Title = "Adding Hermes to PATH"; Category = "finalize"; NeedsUserInput = $false; Worker = "Stage-Path" }+ @{ Name = "config-templates"; Title = "Writing configuration templates"; Category = "finalize"; NeedsUserInput = $false; Worker = "Stage-ConfigTemplates" }+ @{ Name = "platform-sdks"; Title = "Installing messaging platform SDKs"; Category = "finalize"; NeedsUserInput = $false; Worker = "Stage-PlatformSdks" }+ @{ Name = "bootstrap-marker"; Title = "Marking install complete"; Category = "finalize"; NeedsUserInput = $false; Worker = "Stage-BootstrapMarker" }+ # Interactive stages. In non-interactive mode these become no-ops; the+ # caller (GUI / CI) handles the equivalent UX themselves.+ @{ Name = "configure"; Title = "Configuring API keys and models"; Category = "post-install"; NeedsUserInput = $true; Worker = "Stage-Configure" }+ @{ Name = "gateway"; Title = "Starting messaging gateway"; Category = "post-install"; NeedsUserInput = $true; Worker = "Stage-Gateway" }+ )++ # Stage workers -- thin wrappers that delegate to the existing Install-* /+ # Test-* / Invoke-* functions while preserving their error semantics. Kept+ # as a separate layer so the existing functions remain callable directly+ # (helpful for one-off recovery: ``. install.ps1; Install-Venv``).+ #+ # Stages that depend on uv (anything after Stage-Uv) call Resolve-UvCmd+ # first so they work in cross-process driver mode where $script:UvCmd+ # set by Stage-Uv in a sibling powershell process is not visible here.+ # Resolve-UvCmd is a fast no-op when $script:UvCmd is already populated+ # (the default-invocation case where Main runs everything in one+ # process), and throws cleanly if uv truly isn't installed yet.+ function Stage-Uv { if (-not (Install-Uv)) { throw "uv installation failed" } }+ function Stage-Python { Resolve-UvCmd; if (-not (Test-Python)) { throw "Python $PythonVersion not available" } }+ function Stage-Git {+ if (-not (Install-Git)) {+ if ($script:GitInstallFailureReason) { throw $script:GitInstallFailureReason }+ throw "Git not available and auto-install failed -- install from https://git-scm.com/download/win then re-run"+ }+ }+ # Node is optional (browser tools degrade gracefully without it). Surface+ # failure to the JSON contract as skipped=true / reason rather than ok=true,+ # so a GUI driver consuming the manifest can distinguish "node ready" from+ # "node missing". Install flow continues either way -- matches the+ # existing Write-Completion behavior that prints a "Note: Node.js could+ # not be installed" hint instead of aborting.+ function Stage-Node {+ if (-not (Test-Node)) {+ $script:_StageSkippedReason = "Node.js not available; browser tools will be unavailable until node is installed manually from https://nodejs.org/en/download/"+ }+ }+ function Stage-SystemPackages { Install-SystemPackages }+ function Stage-Repository { Install-Repository }+ function Stage-Venv { Resolve-UvCmd; Install-Venv }+ function Stage-Dependencies { Resolve-UvCmd; Install-Dependencies }+ function Stage-NodeDeps { Install-NodeDeps }+ function Stage-Desktop { Install-DesktopVoiceDeps; Install-Desktop }+ function Stage-Path { Set-PathVariable }+ function Stage-ConfigTemplates { Copy-ConfigTemplates }+ function Stage-PlatformSdks { Resolve-UvCmd; Install-PlatformSdks }+ function Stage-BootstrapMarker { Write-BootstrapMarker }+ function Stage-Configure { Invoke-SetupWizard }+ function Stage-Gateway { Start-GatewayIfConfigured }++ function Get-InstallStage {+ param([string]$Name)+ foreach ($s in $InstallStages) {+ if ($s.Name -eq $Name) { return $s }+ }+ return $null+ }++ function Step-OutOfInstallDir {+ # Windows refuses to delete a directory any shell is currently cd'd+ # inside -- and silently leaves orphan files behind, which then wedge+ # "is this a valid git repo" probes on re-install. Harmless when the+ # caller ran the installer from somewhere else.+ try {+ $currentResolved = (Get-Location).ProviderPath+ $installResolved = $null+ if (Test-Path $InstallDir) {+ $installResolved = (Resolve-Path $InstallDir -ErrorAction SilentlyContinue).ProviderPath+ }+ if ($installResolved -and $currentResolved.ToLower().StartsWith($installResolved.ToLower())) {+ Write-Info "Stepping out of $InstallDir so Windows can replace files there if needed..."+ Set-Location $env:USERPROFILE+ }+ } catch {}+ }++ function Invoke-Stage {+ param(+ [Parameter(Mandatory=$true)] [hashtable]$StageDef+ )++ # Refresh PATH from registry so this stage sees binaries installed by+ # prior stages, even when each stage runs in its own powershell process.+ # No-op in cost-relevant cases (default invocation path syncs once per+ # foreach pass; cross-process drivers get the necessary freshening).+ Sync-EnvPath++ # Per-stage soft-skip channel. A worker can populate+ # $script:_StageSkippedReason to surface "ran, but the thing it was+ # supposed to set up is not available" as skipped=true in the JSON+ # frame, without throwing. Used by Stage-Node so the install flow+ # doesn't abort when an optional capability is missing while still+ # being honest in the protocol contract. Reset before each stage so+ # a prior stage's reason can never leak into a later stage's frame.+ $script:_StageSkippedReason = $null++ $start = [DateTime]::UtcNow+ $result = @{+ stage = $StageDef.Name+ ok = $false+ skipped = $false+ reason = $null+ duration_ms = 0+ }++ try {+ & $StageDef.Worker+ $result.ok = $true+ if ($script:_StageSkippedReason) {+ $result.skipped = $true+ $result.reason = $script:_StageSkippedReason+ }+ } catch {+ $result.ok = $false+ $result.reason = "$_"+ throw+ } finally {+ $result.duration_ms = [int]([DateTime]::UtcNow - $start).TotalMilliseconds+ if ($Json -or $Stage) {+ # In stage-driver mode every stage emits a JSON line so the+ # caller can stream progress. In default interactive mode we+ # stay silent here (the worker already wrote human output).+ $result | ConvertTo-Json -Compress | Write-Output+ # Tell the entry-point catch that we've already emitted a+ # frame for this failure (when $result.ok = $false), so it+ # doesn't double-emit a second JSON object and break the+ # one-line-per-stage contract the driver protocol promises.+ if (-not $result.ok) {+ $script:_StageEmittedErrorFrame = $true+ }}+ $markerPath = Join-Path $InstallDir ".hermes-bootstrap-complete"+ $tmp = "$markerPath.tmp"+ $marker | ConvertTo-Json | Set-Content -Path $tmp -Encoding utf8+ Move-Item -Force $tmp $markerPath}+ Log "install complete. Run: hermes"}-# ============================================================================-# Main-# ============================================================================--function Invoke-AllStages {- Step-OutOfInstallDir- foreach ($s in $InstallStages) {- Invoke-Stage -StageDef $s- }-}--function Invoke-EnsureMode {- param([string]$Deps)- $depList = $Deps -split ","- foreach ($dep in $depList) {- $dep = $dep.Trim()- switch ($dep) {- "node" {- [void](Test-Node)- if (-not $script:HasNode) {- Write-Err "Node.js could not be installed"- exit 1- }- }- "browser" {- [void](Test-Node)- if ($script:HasNode) {- Install-AgentBrowser- } else {- Write-Err "Node.js is required for browser tools but could not be installed"- exit 1- }- }- "ripgrep" {- Write-Info "ripgrep: install manually on Windows (scoop install ripgrep)"- }- "ffmpeg" {- Write-Info "ffmpeg: install manually on Windows (scoop install ffmpeg)"- }- default {- Write-Err "Unknown dependency: $dep"- exit 1- }- }- }-}--function Invoke-PostInstallMode {- Write-Info "Running post-install setup..."- Invoke-EnsureMode -Deps "node,browser"- Write-Info "Post-install complete"-}--function Main {- Write-Banner- Invoke-AllStages- if (-not $Json) {- Write-Completion- } else {- @{ ok = $true; protocol_version = $InstallStageProtocolVersion } | ConvertTo-Json -Compress | Write-Output+function Invoke-StageByName([string]$name) {+ switch ($name) {+ "prerequisites" { Stage-Prerequisites }+ "repository" { Stage-Repository }+ "venv" { Stage-Venv }+ "python-deps" { Stage-PythonDeps }+ "node-deps" { Stage-NodeDeps }+ "path" { Stage-Path }+ "config" { Stage-Config }+ "setup" { Stage-Setup }+ "gateway" { Stage-Gateway }+ "desktop" { Stage-Desktop }+ "complete" { Stage-Complete }+ default { Write-Error "unknown stage: $name"; exit 2 }}}diff --cc tests/ci/test_classify_changes.pyindex 4130a0fd9a7,43e33dd620b..8b20a3e69d6--- a/tests/ci/test_classify_changes.py+++ b/tests/ci/test_classify_changes.py@@@ -41,14 -41,14 +41,15 @@@ DEFAULT ="uv_lock": True,"npm_lock": True,"installer": True,+ "bootstrap": True,+ "desktop_updater": True,"rust": True,"mcp_catalog": False,"ci_review": True,}- def _lanes(python=False, frontend=False, site=False, scan=False, deps=False, uv_lock=False, npm_lock=False, installer=False, bootstrap=False, rust=False, mcp_catalog=False, docker_meta=False, ci_review=False, python_prod=None, nix=None, docker=None) -> dict[str, bool]:-def _lanes(python=False, frontend=False, site=False, scan=False, deps=False, uv_lock=False, npm_lock=False, installer=False, desktop_updater=False, rust=False, mcp_catalog=False, docker_meta=False, ci_review=False, python_prod=None, nix=None, docker=None) -> dict[str, bool]:++def _lanes(python=False, frontend=False, site=False, scan=False, deps=False, uv_lock=False, npm_lock=False, installer=False, bootstrap=False, desktop_updater=False, rust=False, mcp_catalog=False, docker_meta=False, ci_review=False, python_prod=None, nix=None, docker=None) -> dict[str, bool]:# python_prod tracks python except for tests-only diffs; default it to# python so the majority of cases don't need to spell it out.#@@@ -70,7 -70,7 +71,8 @@@"uv_lock": uv_lock,"npm_lock": npm_lock,"installer": installer,+ "bootstrap": bootstrap,+ "desktop_updater": desktop_updater,"rust": rust,"mcp_catalog": mcp_catalog,"ci_review": ci_review,diff --cc tests/gateway/test_feishu.pyindex a834a45e580,2d1783e0511..4120b376cfd--- a/tests/gateway/test_feishu.py+++ b/tests/gateway/test_feishu.py@@@ -1190,12 -1186,12 +1190,12 @@@ class TestAdapterBehavior(unittest.Testwith tempfile.TemporaryDirectory() as temp_home:with patch.dict(os.environ, {"HERMES_HOME": temp_home}, clear=False):first = FeishuAdapter(PlatformConfig())- self.assertFalse(first._is_duplicate("om_same"))+ self.assertFalse(asyncio.run(first._is_duplicate("om_same")))second = FeishuAdapter(PlatformConfig())- self.assertTrue(second._is_duplicate("om_same"))+ self.assertTrue(asyncio.run(second._is_duplicate("om_same")))- @patch.dict(os.environ, {}, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=True)def test_send_document_reply_uses_thread_flag(self):from gateway.config import PlatformConfigfrom plugins.platforms.feishu.adapter import FeishuAdapter@@@ -1627,10 -1622,10 +1627,10 @@@ class TestDedupTTL(unittest.TestCase)with patch.object(adapter, "_persist_seen_message_ids"):adapter._seen_message_ids = {"om_dup": time.time()}adapter._seen_message_order = ["om_dup"]- self.assertTrue(adapter._is_duplicate("om_dup"))+ self.assertTrue(asyncio.run(adapter._is_duplicate("om_dup")))- @patch.dict(os.environ, {}, clear=True)+ @patch.dict(os.environ, _SYS_ENV, clear=True)def test_load_tolerates_malformed_timestamp_values(self):"""Regression #13632 — a non-numeric timestamp in the persisteddedup state must not crash adapter startup. The bad key isdiff --cc tests/hermes_cli/test_desktop_exe_integrity.pyindex 3644e49a681,bdff61e62a4..1defe0f7163--- a/tests/hermes_cli/test_desktop_exe_integrity.py+++ b/tests/hermes_cli/test_desktop_exe_integrity.py@@@ -274,13 -274,17 +274,17 @@@ def _ns(**kw)return argparse.Namespace(**defaults)[email protected]_only[email protected]("windows")def test_build_only_fails_when_pack_produces_corrupt_exe(tmp_path, monkeypatch, capsys):"""The updater chain's contract: a rebuild whose Hermes.exe cannot launch- must exit nonzero (so hermes-setup's retry-once kicks in) and must restore- the previous working build instead of leaving the corrupt one.+ must exit nonzero (so hermes-setup's retry-once kicks in) and must leave+ the previous working build in place instead of installing the corrupt one.++ Stage-and-swap (#86443): the pack lands in a staging dir; the integrity+ gate runs on the STAGED exe and a failure discards staging without ever+ touching the live ``win-unpacked`` tree.- ``windows_only``: the whole chain is Windows-gated — ``win-unpacked``+ ``platforms("windows")``: the whole chain is Windows-gated — ``win-unpacked``candidate discovery in ``_desktop_packaged_executable`` and the integritygate itself both short-circuit off Windows."""diff --cc tests/hermes_cli/test_doctor.pyindex b85e4ca53d1,267388f3691..bd21a462fb4--- a/tests/hermes_cli/test_doctor.py+++ b/tests/hermes_cli/test_doctor.py@@@ -350,7 -356,58 +366,27 @@@ class TestDoctorMemoryProviderSectionassert "Memory Provider" in outassert "Built-in memory active" not in out+ @pytest.mark.parametrize("memory_enabled", [False, True])+ def test_stale_builtin_files_reported_only_when_store_enabled(+ self, monkeypatch, tmp_path, memory_enabled+ ):+ # #100668: disabled built-in stores must not surface stale files as active.+ out = self._run_doctor_and_capture(+ monkeypatch,+ tmp_path,+ provider="mnemosyne",+ memory_config={+ "memory_enabled": memory_enabled,+ "user_profile_enabled": False,+ },+ stale_builtin_files=True,+ )++ assert ("MEMORY.md exists" in out) is memory_enabled+ assert "USER.md exists" not in out+ assert ("Built-in memory files disabled by config" in out) is not memory_enabled+-def test_run_doctor_termux_treats_docker_and_browser_warnings_as_expected(monkeypatch, tmp_path):- helper = TestDoctorMemoryProviderSection()- monkeypatch.setenv("TERMUX_VERSION", "0.118.3")- monkeypatch.setenv("PREFIX", "/data/data/com.termux/files/usr")-- real_which = doctor_mod.shutil.which-- def fake_which(cmd):- if cmd in {"docker", "node", "npm"}:- return None- return real_which(cmd)-- monkeypatch.setattr(doctor_mod.shutil, "which", fake_which)-- out = helper._run_doctor_and_capture(monkeypatch, tmp_path, provider="")-- assert "Docker backend is not available inside Termux" in out- assert "Node.js not found (browser tools are optional in the tested Termux path)" in out- assert "Install Node.js on Termux with: pkg install nodejs" in out- assert "Termux browser setup:" in out- assert "1) pkg install nodejs" in out- assert "2) npm install -g agent-browser" in out- assert "3) agent-browser install" in out- assert "Termux compatibility fallbacks:" in out- assert "use .[termux-all] for broad compatibility" in out- assert "Matrix E2EE extra is excluded on Termux" in out- assert "Local faster-whisper extra is excluded on Termux" in out- assert "STT fallback: use Groq Whisper (set GROQ_API_KEY) or OpenAI Whisper (set VOICE_TOOLS_OPENAI_KEY)." in out- assert "docker not found (optional)" not in out--def test_run_doctor_accepts_named_provider_from_providers_section(monkeypatch, tmp_path):home = tmp_path / ".hermes"home.mkdir(parents=True, exist_ok=True)diff --cc tests/hermes_cli/test_gui_command.pyindex 80fc10dd037,c9f6e483e2d..37f6678ffb7--- a/tests/hermes_cli/test_gui_command.py+++ b/tests/hermes_cli/test_gui_command.py@@@ -99,10 -99,42 +99,44 @@@ def _make_packaged_executable(root: Patreturn exe- @pytest.mark.platforms("linux")+ def _staging_dir_from(cmd) -> Path:+ """Extract the ``-c.directories.output=<dir>`` electron-builder override+ ``cmd_gui`` appends to ``npm run pack`` (stage-and-swap, #86443)."""+ for arg in cmd:+ if isinstance(arg, str) and arg.startswith("-c.directories.output="):+ return Path(arg.split("=", 1)[1])+ raise AssertionError(f"no staging output override in {cmd!r}")+++ def _packaged_exe_rel() -> Path:+ """Packaged-exe path relative to electron-builder's output dir on THIS host."""+ if sys.platform == "darwin":+ return Path("mac-arm64") / "Hermes.app" / "Contents" / "MacOS" / "Hermes"+ if sys.platform == "win32":+ return Path("win-unpacked") / "Hermes.exe"+ return Path("linux-unpacked") / "hermes"+++ def _pack_into_staging(root: Path, content: str = "", returncode: int = 0):+ """``subprocess.run`` side effect mimicking a real ``npm run pack``: lays+ the packaged app down inside the STAGING dir named on the command line+ (never in release/), then returns *returncode*. Non-pack commands (the+ launch) return success."""+ def _run(cmd, **kwargs):+ if len(cmd) >= 3 and cmd[1:3] == ["run", "pack"]:+ exe = _staging_dir_from(cmd) / _packaged_exe_rel()+ exe.parent.mkdir(parents=True, exist_ok=True)+ exe.write_text(content, encoding="utf-8")+ if sys.platform not in ("darwin", "win32"):+ (exe.parent / "chrome-sandbox").write_text("", encoding="utf-8")+ return subprocess.CompletedProcess(cmd, returncode)+ return subprocess.CompletedProcess(cmd, 0)+ return _run++def test_gui_installs_packages_and_launches_desktop_app(tmp_path, monkeypatch):+ # Exercises the npm-pack → packaged-exe launch path; Windows desktop is+ # MSIX-only (Electron autoUpdater) and takes a different launch route.root = _make_desktop_tree(tmp_path)desktop_dir = root / "apps" / "desktop"monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)diff --cc tests/hermes_cli/test_linux_desktop_entry.pyindex 4485f3ab840,acb372b2f88..cc7b0c43063--- a/tests/hermes_cli/test_linux_desktop_entry.py+++ b/tests/hermes_cli/test_linux_desktop_entry.py@@@ -100,11 -116,10 +123,11 @@@ def test_install_prefers_themed_icon_fr# And the icon really landed in the hicolor tree: the fixture icon is# a fake PNG (no valid IHDR), so the size is unknown and the icon- # lands under scalable/.- dest = xdg_home / "icons" / "hicolor" / "scalable" / "apps" / "hermes.png"+ # lands under 256x256/ (indexed; never scalable, which is SVG-only).+ dest = xdg_home / "icons" / "hicolor" / "256x256" / "apps" / "hermes.png"assert dest.is_file()assert dest.read_bytes() == lde.icon_path(root).read_bytes()[email protected]("linux")def test_install_icon_copy_failure_falls_back_to_absolute(diff --cc tests/hermes_cli/test_update_autostash.pyindex 07994d518ec,b86cd898da5..028bbb5ed78--- a/tests/hermes_cli/test_update_autostash.py+++ b/tests/hermes_cli/test_update_autostash.py@@@ -74,8 -91,9 +74,8 @@@ def _setup_update_mocks(monkeypatch, tmmonkeypatch.setattr(hermes_main, "_restore_stashed_changes", lambda *a, **kw: True)monkeypatch.setattr(hermes_config, "get_missing_env_vars", lambda required_only=True: [])monkeypatch.setattr(hermes_config, "get_missing_config_fields", lambda: [])- monkeypatch.setattr(hermes_config, "check_config_version", lambda: (5, 5))+ monkeypatch.setattr(hermes_config, "check_config_version", lambda **_kwargs: (5, 5))monkeypatch.setattr(hermes_config, "migrate_config", lambda **kw: {"env_added": [], "config_added": []})- monkeypatch.setattr(hermes_main, "_upgrade_pip_before_lazy_refresh", lambda *a, **kw: None)monkeypatch.setattr(hermes_main, "_refresh_active_lazy_features", lambda *a, **kw: True)diff --cc tests/state/test_fts_runtime_rebuild.pyindex f8dec25d343,d6f0a6eeeac..0709aee29fa--- a/tests/state/test_fts_runtime_rebuild.py+++ b/tests/state/test_fts_runtime_rebuild.py@@@ -140,50 -140,55 +140,55 @@@ class TestRuntimeFtsRebuild})- def test_foreign_holder_detection_includes_deleted_wal(- self, db, tmp_path, monkeypatch- ):- db_path = tmp_path / "state.db"-- class FakePsutil:- @staticmethod- def process_iter(_attrs):- return iter(- (- SimpleNamespace(- info={- "pid": 111,- "open_files": [SimpleNamespace(path=str(db_path))],- }- ),- SimpleNamespace(- info={- "pid": 222,- "open_files": [- SimpleNamespace(path=f"{db_path}-wal (deleted)")- ],- }- ),- SimpleNamespace(- info={- "pid": 333,- "open_files": [SimpleNamespace(path=str(tmp_path / "other.db"))],- }- ),- )- )-- monkeypatch.setattr(hermes_state, "psutil", FakePsutil)- monkeypatch.setattr(hermes_state, "_IS_WINDOWS", False)- monkeypatch.setattr(hermes_state.os, "getpid", lambda: 111)- # Force the macOS/psutil path even on Linux test runners- monkeypatch.setattr(hermes_state.sys, "platform", "darwin")-- assert db._foreign_state_db_holders() == [- (222, f"{db_path}-wal (deleted)")- ]+ @pytest.mark.parametrize(+ "argv",+ (+ ("journalctl", "-u", "hermes-agent.service"),+ ("grep", "hermes-agent", "/var/log/syslog"),+ (+ "/usr/sbin/tailscaled",+ "be-child",+ "ssh",+ "--cmd=python -m hermes_cli.main gateway",+ ),+ ("tmux", "new-session", "/opt/hermes-agent/.venv/bin/hermes gateway"),+ ("python3", "/opt/hermes-agent/tools/check_state.py"),+ ("hermes-monitor", "gateway"),+ ("hermesctl", "serve"),+ ("python3", "worker.py", "hermes_cli.main"),+ ("python3", "-m", "other.module", "hermes_cli.main"),+ ("python3", "-c", "hermes_cli.main"),+ ("python3", "-Icprint('hermes_cli.main')", "hermes_cli/main.py"),+ ),+ )+ def test_uninspectable_non_hermes_process_is_not_a_holder(self, argv):+ assert not hermes_state_holders._looks_like_hermes(argv)++ @pytest.mark.parametrize(+ "argv",+ (+ ("/usr/local/bin/hermes", "gateway"),+ ("/usr/local/bin/hermes-agent", "serve"),+ ("/usr/local/bin/hermes-acp", "--stdio"),+ ("/usr/bin/python3", "-m", "hermes_cli.main", "gateway"),+ ("/usr/bin/python3", "-m", "acp_adapter"),+ ("/usr/bin/python3", "-Im", "hermes_cli.main", "gateway"),+ ("/usr/bin/python3", "-mhermes_cli.main", "gateway"),+ ("/usr/bin/python3", "-W", "ignore", "-m", "hermes_cli.main"),+ ("/usr/bin/python3", "-Xdev", "-m", "hermes_cli.main"),+ (+ "/opt/hermes-agent/.venv/bin/python",+ "/opt/hermes-agent/hermes_cli/main.py",+ "gateway",+ ),+ ("python.exe", "--", "hermes_cli/main.py", "gateway"),+ ("python3", "/opt/hermes-agent/run_agent.py", "--query", "hello"),+ ),+ )+ def test_uninspectable_hermes_process_remains_a_holder(self, argv):+ assert hermes_state_holders._looks_like_hermes(argv)- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_foreign_holder_detection_proc_readlink_deleted_wal(self, db, tmp_path, monkeypatch):@@@ -223,12 -226,82 +226,24 @@@def _readlink(path):path = path.replace("/proc", str(proc_root))return real_readlink(path)- monkeypatch.setattr(hermes_state.os, "readlink", _readlink)-- holders = db._foreign_state_db_holders()+ monkeypatch.setattr(hermes_state_holders.os, "readlink", _readlink)+ real_stat = os.stat+ def _stat(path, *args, **kwargs):+ path_s = str(path).replace("/proc", str(proc_root))+ if path_s.endswith("/222/fd/3"):+ # A real /proc fd remains statable after unlink and retains+ # the deleted sidecar's filesystem identity: same device as+ # state.db, but an inode no live watched path can reach.+ fields = list(real_stat(db_path))+ fields[1] += 1000+ return os.stat_result(fields)+ return real_stat(path_s, *args, **kwargs)+ monkeypatch.setattr(hermes_state_holders.os, "stat", _stat)++ holders = hermes_state_holders.foreign_state_db_holders(db_path)assert holders == [(222, db_path_wal + " (deleted)")]- @pytest.mark.linux_only- @pytest.mark.parametrize("different_device", (False, True))- def test_foreign_holder_ignores_same_path_with_different_file_identity(- self, db, tmp_path, monkeypatch, different_device- ):- """A namespace peer's different state.db is not a holder of the host's.-- A peer process can appear in /proc with a string-identical path for a- different inode, either on the same filesystem or a different one.- Matching on path alone -- or on device alone -- would defer automatic- FTS maintenance forever while corruption compounds.-- Identity must come from (st_dev, st_ino), not the path text.- """- db_path = tmp_path / "state.db"-- proc_root = tmp_path / "proc"- for pid in (111, 222):- (proc_root / str(pid) / "fd").mkdir(parents=True)- # PID 222 = container process holding ITS OWN state.db, which happens- # to have the identical absolute path inside its mount namespace.- guest_db = tmp_path / "guest_state.db"- guest_db.touch()- os.symlink(str(guest_db), str(proc_root / "222" / "fd" / "3"))-- monkeypatch.setattr(hermes_state_holders.os, "getpid", lambda: 111)-- real_listdir = os.listdir- def _listdir(path):- if isinstance(path, str):- path = path.replace("/proc", str(proc_root))- return real_listdir(path)- monkeypatch.setattr(hermes_state_holders.os, "listdir", _listdir)-- # The guest fd reports the host's path (identical string), which is- # exactly what the kernel shows across mount namespaces.- def _readlink(path):- path = path.replace("/proc", str(proc_root))- if path.endswith(f"{proc_root}/222/fd/3") or "222" in path:- return str(db_path)- return os.readlink(path)- monkeypatch.setattr(hermes_state_holders.os, "readlink", _readlink)-- # ...but stat()ing the descriptor resolves to the peer's own inode.- real_stat = os.stat- def _stat(path, *a, **kw):- path_s = str(path).replace("/proc", str(proc_root))- st = real_stat(path_s, *a, **kw)- if different_device and path_s.endswith("/222/fd/3"):- fields = list(st)- # os.stat_result positional layout: st_dev is index 2.- fields[2] = st.st_dev + 1000- return os.stat_result(fields)- return st- monkeypatch.setattr(hermes_state_holders.os, "stat", _stat)-- assert hermes_state_holders.foreign_state_db_holders(db_path) == []-- @pytest.mark.linux_only+ @pytest.mark.platforms("linux")def test_foreign_holder_uninspectable_process_cmdline_fallback(self, db, tmp_path, monkeypatch):diff --cc tests/tools/test_file_operations.pyindex 1da54771992,88e839f2808..8e602003086--- a/tests/tools/test_file_operations.py+++ b/tests/tools/test_file_operations.py@@@ -437,9 -459,8 +459,9 @@@ class TestSearchPathValidationclass TestSearchFilesFallbackHiddenPaths:def _make_env(self):- return make_real_subprocess_env("/")+ return LocalEnvironment("/")+ @pytest.mark.platforms("linux")def test_hidden_root_with_hidden_ancestor_includes_files(self, tmp_path, monkeypatch):"""Fallback find should include visible files when path is inside hidden root."""root = tmp_path / ".hermes" / "logs"diff --cc tests/tools/test_macos_protected_search.pyindex c0e3ce44e41,20609b6c3bb..035cefb9d4f--- a/tests/tools/test_macos_protected_search.py+++ b/tests/tools/test_macos_protected_search.py@@@ -185,10 -197,10 +197,10 @@@ def test_find_fallback_prunes_protectedops.search("*.txt", path=str(home), target="files")- find_commands = [command for command in env.commands if command.startswith("find ")]+ find_commands = _find_commands(env.commands)assert find_commandsfor command in find_commands:- assert ops._escape_shell_arg(str(home / "Downloads")) in command+ assert _bash_safe_path(str(home / "Downloads")) in commandassert "-prune" in commanddiff --cc tools/file_operations.pyindex cbef8fc1e26,a349e9a2c7f..2644be38a06--- a/tools/file_operations.py+++ b/tools/file_operations.py@@@ -3029,10 -3702,10 +3744,10 @@@ class ShellFileOperations(FileOperationextra = len(per_file) - capreturn shown + (f" (+{extra} more)" if extra > 0 else "")- glob_expr = f" --glob {self._escape_shell_arg(file_glob)}" if file_glob else ""+ glob_expr = f" --glob {self._escape_shell_arg(file_glob, translate_path=False)}" if file_glob else ""probe = self._exec(- f"rg -i --count-matches{glob_expr} "- f"{self._escape_shell_arg(pattern, translate_path=False)} {self._escape_native_tool_arg(path)} "+ f"{rg} -i --count-matches{glob_expr} "+ f"{self._escape_shell_arg(pattern)} {self._escape_native_tool_arg(path)} "f"2>/dev/null | head -50",timeout=30,)diff --cc tools/mcp_tool.pyindex 3ab60301ea3,92c8de67c5c..f7cf11213ab--- a/tools/mcp_tool.py+++ b/tools/mcp_tool.py@@@ -5410,11 -5901,26 +5901,26 @@@ def _snapshot_child_pids() -> set"""my_pid = os.getpid()- # Linux: read from /proc+ # Linux: read from /proc. ``/proc/<pid>/task/<tid>/children`` is+ # per-THREAD — a child forked from thread T is listed only under T's+ # task dir. stdio_client() spawns from the background MCP loop thread,+ # so reading only the main thread's file (``task/<pid>/children``)+ # returned an empty set on every Linux install and left+ # ``_stdio_child_pids`` / ``_stdio_pids`` empty: the #81995 dead-child+ # fast-fail, the #96452 respawn signal, and the killpg shutdown sweep+ # never saw the subprocess. Union the children of every task instead.try:- children_path = f"/proc/{my_pid}/task/{my_pid}/children"- with open(children_path, encoding="utf-8-sig") as f:- return {int(p) for p in f.read().split() if p.strip()}+ task_dir = f"/proc/{my_pid}/task"+ tids = os.listdir(task_dir)+ found: set = set()+ for tid in tids:+ try:- with open(f"{task_dir}/{tid}/children", encoding="utf-8") as f:++ with open(f"{task_dir}/{tid}/children", encoding="utf-8-sig") as f:+ found.update(int(p) for p in f.read().split() if p.strip())+ except (FileNotFoundError, OSError, ValueError):+ # Thread exited between listdir and open — skip it.+ continue+ return foundexcept (FileNotFoundError, OSError, ValueError):passdiff --cc tools/working_diff.pyindex b4886144f87,876bc473393..fd68529c2ad--- a/tools/working_diff.py+++ b/tools/working_diff.py@@@ -23,47 -22,30 +23,57 @@@ import functoolimport osimport shutilimport subprocess-from typing import Dict, List+from typing import Dict, List, Optional+ from hermes_cli._subprocess_compat import harden_git_argv, noninteractive_git_env+_GIT_TIMEOUT = 15_MAX_UNTRACKED_FILES = 50 # sanity cap so a node_modules explosion can't hang usVALID_MODES = ("working", "staged", "all")[email protected]_cache(maxsize=1)+def _git_command() -> Optional[List[str]]:+ """Resolve the git invocation: pm's pinned Git first, then system git.++ pm's git package is the canonical Windows git (Git for Windows,+ pinned in pm/lock.json) — it wins over PATH so a stale or broken+ system git never breaks diff collection. On POSIX pm deliberately+ gaps git (system git by choice), and when pm can't provide it for any+ other reason we fall back to bare ``git`` on PATH. None when git is+ nowhere — the caller reports it unavailable.+ """+ try:+ import pm++ runner = pm.ensure("git")+ for candidate in ("git.exe", "git"):+ resolved = shutil.which(candidate, path=runner.env.get("PATH"))+ if resolved:+ return [resolved]+ except Exception:+ pass+ return ["git"] if shutil.which("git") else None++def _run(args: List[str], cwd: str, timeout: int = _GIT_TIMEOUT):- """Run git, returning (returncode, stdout). Never raises on git failure."""+ """Run git, returning (returncode, stdout). Never raises on git failure.++ Hardened against a malicious repo's ``.git/config`` (GHSA-7x36-8jrh-v4pw):+ ``noninteractive_git_env`` disables fsmonitor/hooks/pager/editor/credential+ sinks, and ``harden_git_argv`` appends ``--no-ext-diff --no-textconv`` to+ the diff-rendering subcommands so attribute-scoped diff/textconv drivers+ can't execute either.+ """+ command = _git_command()+ if command is None:+ return 127, ""proc = subprocess.run(- [*command, "-c", "core.quotePath=false", *args],- ["git", "-c", "core.quotePath=false", *harden_git_argv(args)],++ [*command, "-c", "core.quotePath=false", *harden_git_argv(args)],cwd=cwd, capture_output=True, text=True, timeout=timeout,encoding="utf-8", errors="replace",+ stdin=subprocess.DEVNULL, env=noninteractive_git_env(),)return proc.returncode, proc.stdoutdiff --cc uv.lockindex cfe76c92b59,ec0c477bd2c..428e43ea1a8--- a/uv.lock+++ b/uv.lock@@@ -2097,12 -1990,10 +2097,12 @@@ requires-dist ={ name = "microsoft-teams-apps", marker = "extra == 'teams'", specifier = "==2.0.13.4" },{ name = "mistralai", marker = "extra == 'mistral'", specifier = "==2.4.8" },{ name = "modal", marker = "extra == 'modal'", specifier = "==1.3.4" },- { name = "nemo-relay", marker = "(platform_machine == 'aarch64' and 'android' not in platform_release and sys_platform == 'linux') or (platform_machine == 'x86_64' and 'android' not in platform_release and sys_platform == 'linux') or (platform_machine == 'arm64' and sys_platform == 'darwin') or (platform_machine == 'AMD64' and sys_platform == 'win32') or (platform_machine == 'ARM64' and sys_platform == 'win32')", specifier = ">=0.7.1,<0.8" },- { name = "numpy", marker = "extra == 'audio-io'", specifier = "==2.4.3" },+ { name = "nemo-relay", marker = "(platform_machine == 'aarch64' and 'android' not in platform_release and sys_platform == 'linux') or (platform_machine == 'x86_64' and 'android' not in platform_release and sys_platform == 'linux') or (platform_machine == 'arm64' and sys_platform == 'darwin') or (platform_machine == 'AMD64' and sys_platform == 'win32') or (platform_machine == 'ARM64' and sys_platform == 'win32')", specifier = ">=0.8.3,<0.9" },++{ name = "numpy", marker = "extra == 'voice'", specifier = "==2.4.3" },{ name = "numpy", marker = "extra == 'wake'", specifier = "==2.4.3" },- { name = "onnxruntime", marker = "extra == 'wake'", specifier = "==1.27.0" },+ { name = "onnxruntime", marker = "(platform_machine != 'x86_64' and extra == 'wake') or (sys_platform != 'darwin' and extra == 'wake')", specifier = "==1.27.0" },+ { name = "onnxruntime", marker = "(platform_machine != 'x86_64' and extra == 'wake-openwakeword') or (sys_platform != 'darwin' and extra == 'wake-openwakeword')", specifier = "==1.27.0" },{ name = "openai", specifier = "==2.24.0" },{ name = "opentelemetry-exporter-otlp-proto-http", marker = "extra == 'otlp'", specifier = "==1.39.1" },{ name = "opentelemetry-sdk", marker = "extra == 'otlp'", specifier = "==1.39.1" },