Skip to content

The agent that grows with you

merge: upstream/main into ethie/pm-clean

ethernetc35a6d65c946
diff --cc .github/workflows/docker.yml
index c0db414b5d2,7e6b916f2ae..6f7f722a911
--- a/.github/workflows/docker.yml
+++ b/.github/workflows/docker.yml
@@@ -94,8 -94,8 +94,10 @@@ jobs
- name: Checkout code
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ - name: Write install stamp
+ run: python3 scripts/write_install_stamp.py --output install-stamp.json --distribution docker --update-mechanism external --source ci
+ - name: Reject profile exports in the build context
+ run: python3 scripts/ci/check_profile_archive_boundary.py
# Retry once on transient Docker Hub / buildkit pull failures
# (connection reset, auth token timeout, rate limiting). The action
@@@ -207,8 -209,8 +209,10 @@@
- name: Checkout trusted source
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ - name: Write install stamp
+ run: python3 scripts/write_install_stamp.py --output install-stamp.json --distribution docker --update-mechanism external --source ci
+ - name: Reject profile exports in the build context
+ run: python3 scripts/ci/check_profile_archive_boundary.py
# Retry once on transient Docker Hub / buildkit pull failures.
# See build job for rationale; same pattern.
diff --cc agent/estop.py
index d012aac127b,b62fc378d64..89b0abee875
--- a/agent/estop.py
+++ b/agent/estop.py
@@@ -112,13 -155,27 +155,27 @@@ def get_state() -> Optional[dict]
return None
reason = None
engaged_at = None
- try:
- raw = json.loads(path.read_text(encoding="utf-8-sig"))
- if isinstance(raw, dict):
- reason = raw.get("reason") or None
- engaged_at = raw.get("engaged_at") or None
- except (OSError, ValueError):
- pass
+ found = False
+ for path in _candidate_sentinel_paths():
+ try:
+ exists = path.exists()
+ except OSError:
+ return {"reason": None, "engaged_at": None}
+ except AttributeError:
+ continue
+ if not exists:
+ continue
+ found = True
+ try:
- raw = json.loads(path.read_text(encoding="utf-8"))
++ raw = json.loads(path.read_text(encoding="utf-8-sig"))
+ if isinstance(raw, dict):
+ reason = raw.get("reason") or None
+ engaged_at = raw.get("engaged_at") or None
+ break
+ except (OSError, ValueError, AttributeError):
+ continue
+ if not found:
+ return None
return {"reason": reason, "engaged_at": engaged_at}
diff --cc apps/desktop/scripts/run-electron-builder.mjs
index 1b94a91b195,61a42424431..a5f2bf22d82
--- a/apps/desktop/scripts/run-electron-builder.mjs
+++ b/apps/desktop/scripts/run-electron-builder.mjs
@@@ -12,52 -11,54 +12,90 @@@ import { createRequire } from 'node:mod
const require = createRequire(import.meta.url)
+function electronBuilderCli() {
+ const entry = require.resolve('electron-builder')
+ let dir = path.dirname(entry)
+ while (!fs.existsSync(path.join(dir, 'package.json'))) {
+ const parent = path.dirname(dir)
+ if (parent === dir) {
+ throw new Error('electron-builder package root not found')
+ }
+ dir = parent
+ }
+ const bin = require(path.join(dir, 'package.json')).bin
+ const rel = typeof bin === 'string' ? bin : bin['electron-builder']
+ return path.join(dir, rel)
+}
+
++// Resolve electronDist at runtime (#38673, #47917): electron-builder 26.8.x can
++// re-unpack a broken Electron.app; reusing the installed dist dodges that.
++// npm workspace hoisting is non-deterministic — require.resolve finds electron
++// wherever it landed.
+ function electronDistDir() {
+ try {
- return path.join(path.dirname(require.resolve("electron/package.json")), "dist")
++ return path.join(path.dirname(require.resolve('electron/package.json')), 'dist')
+ } catch {
+ return null
+ }
+ }
+
+ function distBinary(dist) {
- if (process.platform === "darwin") {
- return path.join(dist, "Electron.app", "Contents", "MacOS", "Electron")
++ if (process.platform === 'darwin') {
++ return path.join(dist, 'Electron.app', 'Contents', 'MacOS', 'Electron')
+ }
- if (process.platform === "win32") {
- return path.join(dist, "electron.exe")
++ if (process.platform === 'win32') {
++ return path.join(dist, 'electron.exe')
+ }
- return path.join(dist, "electron")
++ return path.join(dist, 'electron')
+ }
+
-function electronBuilderCli() {
- const pkgJson = require.resolve("electron-builder/package.json")
- const bin = require(pkgJson).bin
- const rel = typeof bin === "string" ? bin : bin["electron-builder"]
- return path.join(path.dirname(pkgJson), rel)
+const args = [...process.argv.slice(2)]
+
+// package.json has no "build" field. Name the config file or electron-builder
+// would look for one and silently use defaults.
+if (!args.some(a => a === '--config' || a.startsWith('--config='))) {
+ args.push('--config', 'electron-builder.config.cjs')
+}
+
+// Never let electron-builder publish. On a CI tag build it auto-detects
+// GitHub and demands GH_TOKEN after the artifacts are already built.
- // The release workflow uploads artifacts in its own step.
++// The release workflow uploads artifacts in its own step. (Also: the npm
++// lifecycle env sets CI=1, and electron-builder treats CI=1 as a signal to
++// implicitly resolve a publish target, which reads <projectDir>/.git/config —
++// apps/desktop has no .git of its own, so pin publish to "never".)
+if (!args.includes('--publish') && !args.some(a => a.startsWith('-p'))) {
+ args.push('--publish', 'never')
}
++// Reuse the installed Electron dist when present so a broken app is not
++// re-unpacked from a fresh download; otherwise electron-builder fetches via
++// @electron/get (electronVersion + ELECTRON_MIRROR).
+ const dist = electronDistDir()
-// Local `hermes desktop` builds only ever package (--dir or dist), never
-// publish a GitHub release — no CI workflow drives this script. But the npm
-// lifecycle env sets CI=1 (so esbuild's postinstall doesn't try interactive
-// animations), and electron-builder treats CI=1 as a signal to implicitly
-// resolve a publish target. That resolution reads <projectDir>/.git/config
-// directly — projectDir here is apps/desktop, which has no .git of its own
-// (only the repo root does) and no "repository" field in its package.json —
-// so it fails with "Cannot detect repository by .git/config". Pin publish to
-// "never" so electron-builder skips that lookup entirely.
-const args = ["--publish", "never"]
+ if (dist && fs.existsSync(distBinary(dist))) {
+ args.push(`-c.electronDist=${dist}`)
+ } else {
+ console.warn(
- "[run-electron-builder] no local electron dist; electron-builder will fetch " +
- "via @electron/get (electronVersion + ELECTRON_MIRROR)."
++ '[run-electron-builder] no local electron dist; electron-builder will fetch ' +
++ 'via @electron/get (electronVersion + ELECTRON_MIRROR).'
+ )
+ }
-args.push(...process.argv.slice(2))
+
-const result = spawnSync(process.execPath, [electronBuilderCli(), ...args], {
- stdio: "inherit",
+if (args.includes('--win') && process.env.AZURE_SIGN_ENDPOINT && process.env.AZURE_CLIENT_ID) {
+ console.log(
+ `[run-electron-builder] Windows signing: Azure Trusted Signing at ${process.env.AZURE_SIGN_ENDPOINT}`
+ )
+}
+
+// Cap concurrent fs.open calls in the electron-builder process.
+// @electron/osx-sign walks the whole .app with Promise.all and no
+// concurrency bound. The payload (lark_oapi alone is thousands of files)
+// exhausts the macOS table: EMFILE on a random .py. Raising ulimit only
+// moves the ceiling. --require, not an import: isbinaryfile captures
+// promisify(fs.open) at its own load.
+const preload = path.join(import.meta.dirname, 'fs-open-limit.cjs')
+
+const result = spawnSync(process.execPath, ['--require', preload, electronBuilderCli(), ...args], {
+ stdio: 'inherit'
})
if (result.error) {
console.error(`[run-electron-builder] spawn failed: ${result.error.message}`)
diff --cc apps/desktop/src/i18n/en.ts
index 7f348973cf1,7799845db07..a5d8dc2d9bb
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@@ -1145,12 -1139,22 +1151,25 @@@ export const en: Translations =
unifiedMemory: 'Unified memory',
modelsTitle: 'Models',
recommended: 'Recommended',
+ /* The Recommended badge's tooltip, keyed by the resolver branch that
+ made the pick. Qualitative on purpose: predictions order candidates,
+ they are not promises to print. */
+ recommendedReason: {
+ 'best-quality-resident':
+ 'The highest-quality model that runs entirely on your GPU at full speed. Picks weigh quality against predicted speed on this hardware.',
+ 'speed-gated-quality':
+ 'A higher-quality model fits this machine but would respond too slowly on its memory bandwidth — this is the best model that stays fast.',
+ 'fastest-resident':
+ 'No model reaches full speed on this hardware; this one comes closest while running entirely in GPU memory.',
+ 'least-painful-spilled':
+ 'No model fits entirely in GPU memory here — this one runs best from system RAM.'
+ } as Record<string, string>,
downloaded: 'Downloaded',
downloadAction: size => `Download · ${size}`,
- downloadProgress: (done, total) => `Downloading ${done} of ${total}`,
+ downloadProgress: (done, total) => `${done} of ${total}`,
+ downloadPausedLabel: 'Paused',
+ downloadPauseAction: 'Pause',
+ downloadResumeAction: 'Resume',
downloadDoneToast: model => `${model} is ready.`,
installDoneToast: 'Local runtime installed and ready.',
quickstartTitle: 'Run a model on this machine',
diff --cc apps/desktop/src/i18n/ja.ts
index 5a2f2f79bbc,aa971d9759c..11d9326f8b5
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@@ -1043,12 -1045,19 +1051,22 @@@ export const ja = defineLocale(
unifiedMemory: 'ユニファイドメモリ',
modelsTitle: 'モデル',
recommended: 'おすすめ',
+ recommendedReason: {
+ 'best-quality-resident':
+ 'GPU に完全に載り、フルスピードで動くモデルの中で最高品質です。おすすめは品質とこのハードウェアでの予測速度を両立させて選ばれます。',
+ 'speed-gated-quality':
+ 'より高品質なモデルもこのマシンに載りますが、メモリ帯域の制約で応答が遅くなります — これは速度を保てる最良のモデルです。',
+ 'fastest-resident':
+ 'このハードウェアでフルスピードに達するモデルはありません。GPU メモリ内で動くものの中で最速です。',
+ 'least-painful-spilled':
+ 'GPU メモリに完全に収まるモデルはありません — システム RAM からの実行で最も快適なモデルです。'
+ } as Record<string, string>,
downloaded: 'ダウンロード済み',
downloadAction: size => `ダウンロード · ${size}`,
- downloadProgress: (done, total) => `ダウンロード中 ${done} / ${total}`,
+ downloadProgress: (done, total) => `${done} / ${total}`,
+ downloadPausedLabel: '一時停止中',
+ downloadPauseAction: '一時停止',
+ downloadResumeAction: '再開',
downloadDoneToast: model => `${model} の準備ができました。`,
installDoneToast: 'ローカルランタイムのインストールが完了しました。',
useAction: '使用する',
diff --cc apps/desktop/src/i18n/zh-hant.ts
index fe422398c5b,5d2bdd57cd6..9fc59f86f76
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@@ -1007,12 -1007,15 +1013,18 @@@ export const zhHant = defineLocale(
unifiedMemory: '統一記憶體',
modelsTitle: '模型',
recommended: '推薦',
+ recommendedReason: {
+ 'best-quality-resident': '在完全駐留 GPU 且保持全速的模型中品質最高。推薦會在品質與該硬體的預計速度之間權衡。',
+ 'speed-gated-quality': '有更高品質的模型可以裝入這台機器,但受記憶體頻寬限制回應會太慢——這是保持流暢的最佳模型。',
+ 'fastest-resident': '沒有模型能在該硬體上達到全速;這是完全駐留 GPU 記憶體中最快的一個。',
+ 'least-painful-spilled': '沒有模型能完全裝入 GPU 記憶體——這是從系統記憶體執行表現最好的一個。'
+ } as Record<string, string>,
downloaded: '已下載',
downloadAction: size => `下載 · ${size}`,
- downloadProgress: (done, total) => `正在下載 ${done} / ${total}`,
+ downloadProgress: (done, total) => `${done} / ${total}`,
+ downloadPausedLabel: '已暫停',
+ downloadPauseAction: '暫停',
+ downloadResumeAction: '繼續',
downloadDoneToast: model => `${model} 已就緒。`,
installDoneToast: '本地執行環境已安裝就緒。',
useAction: '使用',
diff --cc apps/desktop/src/i18n/zh.ts
index 94c0ce8ea80,523dc9da76f..48bf174f6ca
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@@ -1347,12 -1342,15 +1353,18 @@@ export const zh: Translations =
unifiedMemory: '统一内存',
modelsTitle: '模型',
recommended: '推荐',
+ recommendedReason: {
+ 'best-quality-resident': '在完全驻留 GPU 且保持全速的模型中质量最高。推荐会在质量与该硬件的预计速度之间权衡。',
+ 'speed-gated-quality': '有更高质量的模型可以装入这台机器,但受内存带宽限制响应会太慢——这是保持流畅的最佳模型。',
+ 'fastest-resident': '没有模型能在该硬件上达到全速;这是完全驻留 GPU 内存中最快的一个。',
+ 'least-painful-spilled': '没有模型能完全装入 GPU 内存——这是从系统内存运行表现最好的一个。'
+ } as Record<string, string>,
downloaded: '已下载',
downloadAction: size => `下载 · ${size}`,
- downloadProgress: (done, total) => `正在下载 ${done} / ${total}`,
+ downloadProgress: (done, total) => `${done} / ${total}`,
+ downloadPausedLabel: '已暂停',
+ downloadPauseAction: '暂停',
+ downloadResumeAction: '继续',
downloadDoneToast: model => `${model} 已就绪。`,
installDoneToast: '本地运行时已安装就绪。',
useAction: '使用',
diff --cc apps/desktop/src/store/notifications.test.ts
index 69ad268916d,c33860e4a49..60e20100811
--- a/apps/desktop/src/store/notifications.test.ts
+++ b/apps/desktop/src/store/notifications.test.ts
@@@ -56,28 -56,15 +56,41 @@@ test('session storage write failure is
expect(lastMessage()).toMatch(/Disk full/i)
})
+test('notifyError posts the full error to desktop.log, not the summary', () => {
+ const logLine = vi.fn()
+
+ const previous = (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
+
+ ;(window as unknown as { hermesDesktop: { logLine: typeof logLine } }).hermesDesktop = { logLine }
+
+ try {
+ const error = new Error('sqlite3.OperationalError: database is locked')
+ error.stack = 'Error: sqlite3.OperationalError: database is locked\n at saveSession (session.ts:12)'
+
+ notifyError(error, 'Prompt failed')
+
+ expect(logLine).toHaveBeenCalledTimes(1)
+ expect(logLine.mock.calls[0][0]).toContain('Prompt failed')
+ expect(logLine.mock.calls[0][0]).toContain('database is locked')
+ expect(logLine.mock.calls[0][0]).toContain('session.ts:12')
+ } finally {
+ if (previous === undefined) {
+ delete (window as unknown as { hermesDesktop?: unknown }).hermesDesktop
+ } else {
+ ;(window as unknown as { hermesDesktop: unknown }).hermesDesktop = previous
+ }
+ }
+})
++
+ test('code-skew 503 unwraps to a restart-required summary, not raw IPC JSON', () => {
+ notifyError(
+ new Error(
+ 'Error invoking remote method \'hermes:api\': Error: 503: {"detail":"Restart required: This process is running code from 08b4875f4a but the checkout on disk is now 48d2528066."}'
+ ),
+ 'Could not load models'
+ )
+
+ expect(lastMessage()).toMatch(/running old code after an update/i)
+ expect(lastMessage()).not.toMatch(/hermes:api/)
+ expect(lastMessage()).not.toMatch(/systemctl/)
+ })
diff --cc hermes_cli/doctor.py
index 7e5bfea5e3c,1af14d38820..ee90cf5fd30
--- a/hermes_cli/doctor.py
+++ b/hermes_cli/doctor.py
@@@ -2574,9 -2583,45 +2574,39 @@@ def run_doctor(args)
f"Install with: cd {PROJECT_ROOT} && "
"npx playwright install --with-deps chromium"
)
- elif _is_termux():
- check_info("Node.js not found (browser tools are optional in the tested Termux path)")
- check_info("Install Node.js on Termux with: pkg install nodejs")
- check_info("Termux browser setup:")
- for step in _termux_browser_setup_steps(node_installed=False):
- check_info(step)
else:
check_warn("Node.js not found", "(optional, needed for browser tools)")
-
+
+ # Lightpanda engine (browser.engine / AGENT_BROWSER_ENGINE). Independent
+ # of Node: Browser Use mode spawns ``lightpanda serve`` itself.
+ try:
+ from tools.browser_tool import _using_lightpanda_engine, lightpanda_engine_status
+ from tools.browser_lightpanda import LIGHTPANDA_INSTALL_HINT, find_lightpanda_binary
+ except Exception:
+ pass
+ else:
+ # _using_lightpanda_engine() is a cached config read — a failure
+ # there would be exceptional, not something to silently hide.
+ if _using_lightpanda_engine():
+ try:
+ _lp_used, _lp_reason = lightpanda_engine_status()
+ except Exception as e:
+ _lp_used, _lp_reason = False, f"status check failed: {e}"
+ if not _lp_used:
+ check_warn("browser.engine=lightpanda is shadowed", f"({_lp_reason})")
+ check_info(
+ "Fix: pick Lightpanda in `hermes tools` → Browser Automation, "
+ "or set browser.engine: auto"
+ )
+ elif find_lightpanda_binary():
+ check_ok("Lightpanda", f"({_lp_reason})")
+ else:
+ check_warn(
+ "Lightpanda selected but binary not found",
+ "(browser tools will fail until it is installed)",
+ )
+ check_info(LIGHTPANDA_INSTALL_HINT)
+
# npm audit for all Node.js packages
_npm_bin = _safe_which("npm")
if _npm_bin:
diff --cc hermes_cli/main.py
index ad541a72004,8a43b23745c..2a201db1758
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@@ -4866,6 -5219,8 +4938,7 @@@ _LAZY_COMMAND_EXPORTS =
"_sync_with_upstream_if_needed",
"_update_node_dependencies",
"_update_via_zip",
+ "_warn_orphaned_update_autostashes",
- "_upgrade_pip_before_lazy_refresh",
"_validate_critical_files_syntax",
"_validate_critical_modules_import",
"_venv_core_imports_healthy",
diff --cc hermes_cli/update_cmd.py
index 000c1f03699,0452f63a8b7..5aafacef0b5
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@@ -560,6 -674,68 +675,66 @@@ _INSTALL_DEFINING_FILES =
"uv.lock",
)
+ def _editable_install_is_current(git_cmd, cwd, pre_pull_sha: str | None) -> bool:
+ """True when the pulled commits cannot have invalidated the editable install.
+
+ ``uv pip install -e .`` never audits an editable target — it reinstalls on
+ every invocation, and every reinstall rewrites the console-script shims.
+ On Windows that rewrite is the only reason the running ``hermes.exe`` has
+ to be quarantined, and a quarantine that loses its race is the whole
+ ``os error 32`` family. Not reinstalling when the reinstall provably
+ cannot change anything removes that risk outright for the common update,
+ rather than trying to make the rename win more often.
+
+ Skipping is safe because Hermes pins its editable finder to a *static*
+ module list (``[tool.setuptools] py-modules`` plus
+ ``packages.find.include``). The one source-only change that would stale
+ that finder is a new top-level module or package, and it cannot land
+ without a ``pyproject.toml`` diff. Dependencies and ``[project.scripts]``
+ live there too. New submodules inside an already-mapped package resolve
+ through the real package directory and need no reinstall.
+
+ Fails closed: an unresolvable pre-pull SHA (shallow checkout, ZIP swap)
+ or a failed ``git diff`` returns False and the install runs as before.
+ """
+ if not pre_pull_sha:
+ return False
+ try:
+ result = subprocess.run(
+ git_cmd
+ + ["diff", "--name-only", f"{pre_pull_sha}..HEAD", "--"]
+ + list(_INSTALL_DEFINING_FILES),
+ cwd=cwd,
+ capture_output=True,
+ text=True, encoding="utf-8", errors="replace",
+ )
+ except OSError:
+ return False
+ if result.returncode != 0:
+ return False
+ return not result.stdout.strip()
+
+ def _validate_python_files_syntax(
+ root, relpaths
+ ) -> tuple[bool, str | None, str | None]:
+ """Compile *relpaths* under *root* without writing bytecode into the tree."""
+ import py_compile
+ import tempfile
+
+ root = Path(root)
+ with tempfile.TemporaryDirectory(prefix="hermes-syntax-check-") as tmpdir:
+ for relpath in relpaths:
+ path = root / relpath
+ if not path.exists():
+ continue
+ cfile = Path(tmpdir) / (str(relpath).replace("/", "__") + "c")
+ try:
+ py_compile.compile(str(path), cfile=str(cfile), doraise=True)
+ except py_compile.PyCompileError as exc:
+ return False, str(path), str(exc)
+ except OSError as exc:
+ return False, str(path), f"could not read: {exc}"
+ return True, None, None
-
-
def _validate_critical_files_syntax(root) -> tuple[bool, str | None, str | None]:
"""Compile each file in ``_UPDATE_CRITICAL_FILES`` to catch SyntaxErrors.
@@@ -7595,31 -8580,14 +8561,36 @@@ def _cmd_update_impl(args, gateway_mode
if swept:
print(" (removed %d aborted-fetch pack temp file(s))" % len(swept))
+ # target_ref is the reference that we count against, fast-forward to,
+ # and reset to. On the main channel it is origin/<branch>. That is the
+ # historical behavior. On the stable channel it is the commit of the
+ # newest release tag. The current branch pointer fast-forwards to the
+ # release. Thus the checkout keeps its branch shape (no detached HEAD).
+ # The next stable update then fast-forward merges to the next tag.
+ target_ref = f"origin/{branch}"
+ stable_tag = None
+ if _stable_channel_active(args):
+ print("→ Update channel: stable (tagged releases)")
+ stable_tag, _stable_tag_sha = _resolve_latest_release_tag(
+ git_cmd, _m().PROJECT_ROOT
+ )
+ if stable_tag is None:
+ print("✗ No release tags found on origin. An update on the stable channel is not possible.")
+ print(" Switch channels with: hermes update --set-channel main")
+ _m()._resume_windows_gateways_after_update(_windows_gateway_resume)
+ sys.exit(1)
+ print(f"→ Latest release: {stable_tag}")
+ target_ref = stable_tag
+
+ # Surface autostash entries left behind by earlier updates (#63717
+ # problem 6) — parked --keep-stash runs and failed restores preserve
+ # the stash but nothing ever mentioned it again.
+ _m()._warn_orphaned_update_autostashes(git_cmd, _m().PROJECT_ROOT)
+
print("→ Fetching updates...")
+ fetch_target = ["tag", stable_tag] if stable_tag else [branch]
fetch_result = subprocess.run(
- git_cmd + ["fetch", "origin", branch],
+ git_cmd + ["fetch", "origin", *fetch_target],
cwd=_m().PROJECT_ROOT,
capture_output=True,
text=True, encoding="utf-8", errors="replace",
@@@ -7991,7 -8995,18 +8981,8 @@@
if upstream_checked
else "✓ Up to date with your fork (official repo not checked)."
),
+ had_desktop_app_before_update=had_desktop_app_before_update,
)
- if runtime_repaired is not None and not _m()._is_windows():
- print()
- print(
- "⚠ Restart required to finish the managed Python runtime repair."
- )
- print(
- " Any running Hermes gateways, Desktop backends, or other "
- "long-lived processes still use the previous runtime."
- )
- print(" Restart each of them to pick up the repaired runtime.")
_m()._resume_windows_gateways_after_update(_windows_gateway_resume)
# Git is current, but a prior pull may still owe the fleet a
# restart (#95294). Catch up even on the "Already up to date"
diff --cc plugins/platforms/buzz/adapter.py
index e10a2b0dfee,74abfe29bc8..aa74bb897d9
--- a/plugins/platforms/buzz/adapter.py
+++ b/plugins/platforms/buzz/adapter.py
@@@ -245,8 -537,40 +537,40 @@@ def _resolve_cli_path(configured: str
return str(fallback) if fallback.is_file() else ""
+ def _credentials_candidates(extra: Optional[dict] = None) -> List[Path]:
+ # Scope-aware read (#98738/#95216): inside a secondary profile scope the
+ # scope is authoritative (a miss falls to the profile's own config extra,
+ # never the default profile's os.environ); unscoped reads keep env
+ # precedence plus the external-secret rung.
+ configured = str(_get_scoped_secret("BUZZ_CREDENTIALS_FILE", "") or "").strip() or str(
+ (extra or {}).get("credentials_file", "") or ""
+ ).strip()
+ if configured:
+ return [Path(configured).expanduser()]
+ if _is_multiplex_active():
+ return []
+ try:
+ return sorted(_DEFAULT_CREDENTIALS_DIR.glob("*credentials*.json"))
+ except OSError:
+ return []
+
+
+ def _resolve_credentials_data(extra: Optional[dict] = None) -> dict:
+ """Load the first credential record containing a private key."""
+ for path in _credentials_candidates(extra):
+ try:
- data = json.loads(path.read_text(encoding="utf-8"))
++ data = json.loads(path.read_text(encoding="utf-8-sig"))
+ except (OSError, ValueError):
+ continue
+ if not isinstance(data, dict):
+ continue
+ if any(isinstance(data.get(field), str) and data[field].strip() for field in ("nsec", "private_key_hex", "private_key")):
+ return data
+ return {}
+
+
def _resolve_private_key(extra: Optional[dict] = None) -> str:
- """Resolve the Nostr private key: env first, then a credentials JSON.
+ """Resolve the Nostr private key: scoped secret first, then credentials JSON.
NEVER log the return value.
"""
diff --cc pyproject.toml
index 429b2559359,fbd324439c5..4d98fe6ba51
--- a/pyproject.toml
+++ b/pyproject.toml
@@@ -495,11 -438,125 +499,129 @@@ exclude-newer = "14 days
# The pin bump WAS the review; exclude-newer adds zero float protection to
# an exact pin and would only delay the reviewed version 14 days.
#
+ # Every other exact-pinned package below: the release-day brick shape
+ # (observed 2026-08-29 updating three long-running installs v0.20.0 ->
+ # v0.20.6 — one Termux, two Linux servers). Each release exact-pins at least
+ # one dependency to a version published days before the release (v0.20.6
+ # pinned snowballstemmer==3.1.1 and psutil==7.2.2 in core, plus fastapi /
+ # uvicorn / python-telegram-bot pins across extras). For two weeks after
+ # release the cutoff filters those versions out, so any venv that predates
+ # the release bricks on `hermes update` ("no version of
+ # snowballstemmer==3.1.1") until the window passes. Same zero-float-
+ # protection logic as setuptools/pillow/mcp above; enforced for every exact
+ # pin by
+ # tests/test_packaging_metadata.py::test_exact_pinned_deps_exempt_from_exclude_newer.
+ #
+ # maturin, setuptools-rust: build-system.requires of the cryptography pin
+ # above. cryptography itself is exempted, but on wheel-less platforms
+ # (Termux/Android) it must build from sdist, and the isolated build
+ # environment resolves under the same cutoff ("Failed to resolve
+ # requirements from build-system.requires ... maturin>=1.9,<2").
++#
+# google-cloud-pubsub: same exact-pin shape (==2.39.2, google-chat adapter).
+# The pin bump WAS the review; exclude-newer only filters it because the
+# 14-day window is younger than the reviewed release.
- exclude-newer-package = { vercel = false, nemo-relay = false, huggingface_hub = false, h2 = false, aiohttp = false, cryptography = false, defusedxml = false, python-olm = false, unpaddedbase64 = false, setuptools = false, pillow = false, mcp = false, firecrawl-anydoc = false, google-cloud-pubsub = false }
+ [tool.uv.exclude-newer-package]
+ agent-client-protocol = false
+ ai-edge-litert = false
+ aiohttp = false
+ aiohttp-socks = false
+ aiosqlite = false
+ alibabacloud-dingtalk = false
+ anthropic = false
+ asyncpg = false
+ azure-identity = false
+ boto3 = false
+ brotlicffi = false
+ certifi = false
+ concurrent-log-handler = false
+ croniter = false
+ cryptography = false
+ daytona = false
+ debugpy = false
+ defusedxml = false
+ dingtalk-stream = false
+ discord-py = false
+ edge-tts = false
+ elevenlabs = false
+ exa-py = false
+ fal-client = false
+ fastapi = false
+ faster-whisper = false
+ fire = false
+ firecrawl-anydoc = false
+ firecrawl-py = false
+ google-api-python-client = false
+ google-auth = false
+ google-auth-httplib2 = false
+ google-auth-oauthlib = false
++google-cloud-pubsub = false
+ h2 = false
+ hindsight-client = false
+ honcho-ai = false
+ httplib2 = false
+ httpx = false
+ httpx2 = false
+ huggingface_hub = false
+ jinja2 = false
+ lark-oapi = false
+ markdown = false
+ maturin = false
+ mautrix = false
+ mcp = false
+ mem0ai = false
+ microsoft-teams-apps = false
+ mistralai = false
+ modal = false
+ nemo-relay = false
+ numpy = false
+ onnxruntime = false
+ openai = false
+ opentelemetry-exporter-otlp-proto-http = false
+ opentelemetry-sdk = false
+ openwakeword = false
+ packaging = false
+ parallel-web = false
+ pathspec = false
+ pillow = false
+ prompt-toolkit = false
+ psutil = false
+ pvporcupine = false
+ pyasn1 = false
+ pydantic = false
+ pyjwt = false
+ pytest = false
+ pytest-asyncio = false
+ python-dotenv = false
+ python-multipart = false
+ python-olm = false
+ python-telegram-bot = false
+ pyyaml = false
+ qrcode = false
+ requests = false
+ rich = false
+ ruamel-yaml = false
+ ruff = false
+ sentencepiece = false
+ setuptools = false
+ setuptools-rust = false
+ wheel = false
+ sherpa-onnx = false
+ slack-bolt = false
+ slack-sdk = false
+ snowballstemmer = false
+ sounddevice = false
+ starlette = false
+ supermemory = false
+ tenacity = false
+ ty = false
+ tzdata = false
+ unpaddedbase64 = false
+ uvicorn = false
+ vercel = false
+ websockets = false
+ youtube-transcript-api = false
-
[tool.setuptools]
# Top-level single-file modules (not packages). Without this, uv2nix's
# sealed venv is missing hermes_constants, run_agent, etc.
diff --cc tests/hermes_cli/test_doctor.py
index 211448a4757,9e37dc2cc2f..f440bbc689b
--- a/tests/hermes_cli/test_doctor.py
+++ b/tests/hermes_cli/test_doctor.py
@@@ -1586,60 -1666,38 +1586,96 @@@ class TestMacOSTCCGrants
assert "stable" not in out
+class TestPmVenvActive:
+ """_pm_venv_active() resolves the runtime venv from pm's facts/store,
+ not from sys.prefix sniffing (which degrades under
+ no-boot-through-venv, where sys.prefix == sys.base_prefix always and
+ VIRTUAL_ENV is unset in bundled installs)."""
+
+ def test_pm_provisioned_venv_is_active_without_virtual_env(self, tmp_path, monkeypatch):
+ import json
+
+ payload = tmp_path / "payload"
+ store = payload / "tools"
+ (payload / "venv").mkdir(parents=True)
+ store.mkdir(parents=True, exist_ok=True)
+ (payload / "manifest.json").write_text("{}", encoding="utf-8")
+ (store / "facts.json").write_text(
+ json.dumps(
+ {"schema": 1, "packages": {"venv": {"stamp": "abc", "extras": []}}}
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))
+ monkeypatch.delenv("VIRTUAL_ENV", raising=False)
+ # No sys.prefix venv: the legacy probe alone would say False.
+ monkeypatch.setattr(doctor_mod.sys, "prefix", "/usr")
+ monkeypatch.setattr(doctor_mod.sys, "base_prefix", "/usr")
+
+ assert doctor_mod._pm_venv_active() is True
+
+ def test_no_venv_fact_falls_back_to_legacy_probe(self, tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "no-such-store"))
+ monkeypatch.delenv("VIRTUAL_ENV", raising=False)
+ monkeypatch.setattr(doctor_mod.sys, "prefix", "/usr")
+ monkeypatch.setattr(doctor_mod.sys, "base_prefix", "/usr")
+
+ assert doctor_mod._pm_venv_active() is False
+
+ monkeypatch.setattr(doctor_mod.sys, "prefix", "/some/venv")
+ assert doctor_mod._pm_venv_active() is True
+
+ def test_bundled_venv_fact_without_venv_dir_is_not_active(self, tmp_path, monkeypatch):
+ import json
+
+ payload = tmp_path / "payload"
+ store = payload / "tools"
+ store.mkdir(parents=True)
+ (payload / "manifest.json").write_text("{}", encoding="utf-8")
+ (store / "facts.json").write_text(
+ json.dumps(
+ {"schema": 1, "packages": {"venv": {"stamp": "abc", "extras": []}}}
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(store))
+ monkeypatch.setattr(doctor_mod.sys, "prefix", "/usr")
+ monkeypatch.setattr(doctor_mod.sys, "base_prefix", "/usr")
+
+ assert doctor_mod._pm_venv_active() is False
++
+ def test_run_doctor_reports_shadowed_lightpanda_engine(monkeypatch, tmp_path):
+ helper = TestDoctorMemoryProviderSection()
+ import tools.browser_tool as bt
+
+ monkeypatch.setattr(bt, "_using_lightpanda_engine", lambda: True)
+ monkeypatch.setattr(
+ bt, "lightpanda_engine_status",
+ lambda: (False, "cloud provider Browserbase is selected"),
+ )
+ out = helper._run_doctor_and_capture(monkeypatch, tmp_path)
+ assert "browser.engine=lightpanda is shadowed" in out
+ assert "Browserbase" in out
+
+
+ def test_run_doctor_reports_lightpanda_ok(monkeypatch, tmp_path):
+ helper = TestDoctorMemoryProviderSection()
+ import tools.browser_tool as bt
+
+ monkeypatch.setattr(bt, "_using_lightpanda_engine", lambda: True)
+ monkeypatch.setattr(bt, "lightpanda_engine_status", lambda: (True, "Browser Use mode"))
+ monkeypatch.setattr("tools.browser_lightpanda.find_lightpanda_binary", lambda: "/opt/lightpanda")
+ out = helper._run_doctor_and_capture(monkeypatch, tmp_path)
+ assert "Lightpanda" in out
+ assert "shadowed" not in out
+
+
+ def test_run_doctor_warns_when_lightpanda_binary_missing(monkeypatch, tmp_path):
+ helper = TestDoctorMemoryProviderSection()
+ import tools.browser_tool as bt
+
+ monkeypatch.setattr(bt, "_using_lightpanda_engine", lambda: True)
+ monkeypatch.setattr(bt, "lightpanda_engine_status", lambda: (True, "Browser Use mode"))
+ monkeypatch.setattr("tools.browser_lightpanda.find_lightpanda_binary", lambda: None)
+ out = helper._run_doctor_and_capture(monkeypatch, tmp_path)
+ assert "Lightpanda selected but binary not found" in out
diff --cc tests/hermes_cli/test_update_autostash.py
index 9be7aa8207c,f7147dfa5ca..07994d518ec
--- a/tests/hermes_cli/test_update_autostash.py
+++ b/tests/hermes_cli/test_update_autostash.py
@@@ -12,17 -12,62 +12,45 @@@ from hermes_cli import main as hermes_m
# ---------------------------------------------------------------------------
# Managed-uv compatibility for tests that patch shutil.which
# ---------------------------------------------------------------------------
-# The production code now uses ``ensure_uv()`` / ``update_managed_uv()``
-# instead of ``shutil.which("uv")``. Many tests in this file patch
-# ``shutil.which`` to control whether uv is "available" — these autouse
-# fixtures make the managed_uv functions delegate to the patched
-# ``shutil.which`` so the existing test setup keeps working without
-# per-test changes.
+# The production code resolves uv through ``pm.uv()`` instead of
+# ``shutil.which("uv")``. Many tests in this file patch ``shutil.which``
+# to control whether uv is "available" — this autouse fixture makes
+# pm.uv delegate to the patched ``shutil.which`` so the existing test
+# setup keeps working without per-test changes.
@pytest.fixture(autouse=True)
-def _patch_managed_uv(request):
- """Make managed_uv helpers follow shutil.which mocking in tests."""
- import shutil
-
- # resolve_uv delegates to shutil.which("uv") so that test patches
- # on shutil.which flow through naturally.
- def _fake_resolve_uv(**kwargs):
- return shutil.which("uv")
-
- def _fake_ensure_uv(**kwargs):
- return shutil.which("uv")
-
- def _fake_update_managed_uv(**kwargs):
- return None # never actually self-update in tests
-
- with patch("hermes_cli.managed_uv.resolve_uv", side_effect=_fake_resolve_uv), \
- patch("hermes_cli.managed_uv.ensure_uv", side_effect=_fake_ensure_uv), \
- patch("hermes_cli.managed_uv.update_managed_uv", side_effect=_fake_update_managed_uv):
- yield
+def _patch_managed_uv(request, patch_pm_uv_to_shutil_which):
+ """Make pm.uv follow shutil.which mocking in tests."""
+ yield
+ @pytest.fixture(autouse=True)
+ def _patch_gateway_discovery():
+ """Keep cmd_update's gateway auto-restart phase off this machine's gateways.
+
+ Tests in this file that reach the full success path (e.g. the #87694
+ orphan-history rescue-ref tests) would otherwise hit real gateway
+ discovery: an unmocked ``find_gateway_pids`` on a box with a live gateway
+ reaches the conftest live-system guard and turns into a spurious
+ ``sys.exit(1)`` (#78574). Discovery returning nothing makes the phase a
+ clean no-op — none of the tests here assert on gateway restarts.
+
+ ``_purge_stale_hermes_modules`` must also be stubbed: it evicts
+ ``hermes_cli.gateway`` from ``sys.modules`` mid-update, and the restart
+ phase's fresh ``from hermes_cli.gateway import ...`` then loads an
+ UNPATCHED copy of the module — silently discarding every mock here and
+ letting real gateway discovery (and real ``os.kill``) run on the dev box.
+ """
+ with patch("hermes_cli.gateway.find_gateway_pids", return_value=[]), \
+ patch("hermes_cli.gateway.supports_systemd_services", return_value=False), \
+ patch("hermes_cli.gateway.find_profile_gateway_processes", return_value=[]), \
+ patch("hermes_cli.update_inventory.collect_runtime_inventory", return_value=None), \
+ patch("hermes_cli.update_inventory.report_unaccounted_runtimes", return_value=False), \
+ patch.object(hermes_main, "_fleet_probe_expected_runtimes", lambda *a, **kw: False), \
+ patch.object(hermes_main, "_purge_stale_hermes_modules", lambda *a, **kw: None), \
+ patch("hermes_cli.update_receipt.collect_fleet_versions", return_value=[]):
+ yield
+
+
diff --cc tests/test_managed_runtime_resolution.py
index c94cae28be1,e3943e351ac..5938c6c2464
--- a/tests/test_managed_runtime_resolution.py
+++ b/tests/test_managed_runtime_resolution.py
@@@ -210,8 -226,8 +210,8 @@@ def test_managed_node_helpers_exist(hel
def test_managed_uv_helpers_exist():
- from pm import ensure, run, uv
- from hermes_cli.managed_uv import ensure_uv, managed_uv_path, resolve_uv
++ from pm import ensure, env_for, uv
- assert callable(resolve_uv)
- assert callable(ensure_uv)
- assert managed_uv_path().parent.name == "bin"
+ assert callable(uv)
+ assert callable(ensure)
- assert callable(run)
++ assert callable(env_for)
diff --cc tools/browser_tool.py
index 3303500213c,87337b0c197..27fb443aabe
--- a/tools/browser_tool.py
+++ b/tools/browser_tool.py
@@@ -5739,9 -5929,28 +5904,28 @@@ def _cleanup_single_browser_session(tas
if os.path.isfile(pid_file):
try:
from tools.process_registry import ProcessRegistry
- daemon_pid = int(Path(pid_file).read_text(encoding="utf-8").strip())
+ daemon_pid = int(Path(pid_file).read_text(encoding="utf-8-sig").strip())
- ProcessRegistry._terminate_host_pid(daemon_pid)
- logger.debug("Killed daemon pid %s for %s", daemon_pid, session_name)
+ # The .pid file lives in a world-writable temp dir and
+ # PIDs recycle: verify this really is our daemon for
+ # this session before tree-killing, and pin the
+ # identity with a start-time fingerprint so the kill
+ # refuses if the PID is swapped between check and kill.
+ if _verify_reapable_browser_daemon(
+ daemon_pid, socket_dir, session_name):
+ from gateway.status import get_process_start_time
+ daemon_start = get_process_start_time(daemon_pid)
+ if daemon_start is not None:
+ ProcessRegistry._terminate_host_pid(
+ daemon_pid, daemon_start)
+ logger.debug("Killed daemon pid %s for %s", daemon_pid, session_name)
+ else:
+ logger.debug(
+ "Skipped daemon kill for %s: no start-time "
+ "fingerprint for pid %s", session_name, daemon_pid)
+ else:
+ logger.debug(
+ "Skipped daemon kill for %s: pid %s failed identity "
+ "verification", session_name, daemon_pid)
except (ProcessLookupError, ValueError, PermissionError, OSError):
logger.debug("Could not kill daemon pid for %s (already dead or inaccessible)", session_name)
shutil.rmtree(socket_dir, ignore_errors=True)
diff --cc uv.lock
index 375aafc7172,cadbe3f3f55..5f663dffb06
--- a/uv.lock
+++ b/uv.lock
@@@ -12,20 -12,104 +12,105 @@@ exclude-newer = "0001-01-01T00:00:00Z"
exclude-newer-span = "P14D"
[options.exclude-newer-package]
-elevenlabs = false
--setuptools = false
- huggingface-hub = false
- vercel = false
- pillow = false
- unpaddedbase64 = false
- google-cloud-pubsub = false
- h2 = false
- defusedxml = false
-modal = false
-pyyaml = false
-maturin = false
-numpy = false
-pvporcupine = false
-google-auth = false
++agent-client-protocol = false
++ai-edge-litert = false
aiohttp = false
-starlette = false
-mistralai = false
-firecrawl-py = false
-parallel-web = false
-markdown = false
-opentelemetry-sdk = false
-prompt-toolkit = false
-fastapi = false
++aiohttp-socks = false
++aiosqlite = false
++alibabacloud-dingtalk = false
+ anthropic = false
-pathspec = false
-openwakeword = false
-defusedxml = false
-ruff = false
-exa-py = false
-mcp = false
-python-olm = false
-wheel = false
-websockets = false
-pytest = false
-pillow = false
-setuptools-rust = false
-tenacity = false
-pyjwt = false
-slack-bolt = false
-fal-client = false
+ asyncpg = false
++azure-identity = false
+ boto3 = false
-ruamel-yaml = false
-sherpa-onnx = false
-huggingface-hub = false
-pytest-asyncio = false
-slack-sdk = false
-unpaddedbase64 = false
-discord-py = false
-honcho-ai = false
-faster-whisper = false
++brotlicffi = false
+ certifi = false
++concurrent-log-handler = false
++croniter = false
+cryptography = false
- mcp = false
- python-olm = false
++daytona = false
+ debugpy = false
-packaging = false
-rich = false
-supermemory = false
-youtube-transcript-api = false
-h2 = false
++defusedxml = false
++dingtalk-stream = false
++discord-py = false
+ edge-tts = false
-microsoft-teams-apps = false
-aiohttp-socks = false
-ai-edge-litert = false
-onnxruntime = false
-croniter = false
-opentelemetry-exporter-otlp-proto-http = false
-azure-identity = false
-lark-oapi = false
-sentencepiece = false
++elevenlabs = false
++exa-py = false
++fal-client = false
++fastapi = false
++faster-whisper = false
++fire = false
firecrawl-anydoc = false
++firecrawl-py = false
+ google-api-python-client = false
-brotlicffi = false
-mem0ai = false
-qrcode = false
-vercel = false
-aiosqlite = false
-tzdata = false
-python-dotenv = false
-daytona = false
-uvicorn = false
-nemo-relay = false
-requests = false
++google-auth = false
++google-auth-httplib2 = false
++google-auth-oauthlib = false
++google-cloud-pubsub = false
++h2 = false
++hindsight-client = false
++honcho-ai = false
+ httplib2 = false
+ httpx = false
++httpx2 = false
++huggingface_hub = false
++jinja2 = false
++lark-oapi = false
++markdown = false
++maturin = false
++mautrix = false
++mcp = false
++mem0ai = false
++microsoft-teams-apps = false
++mistralai = false
++modal = false
+nemo-relay = false
++numpy = false
++onnxruntime = false
++openai = false
++opentelemetry-exporter-otlp-proto-http = false
++opentelemetry-sdk = false
++openwakeword = false
++packaging = false
++parallel-web = false
++pathspec = false
++pillow = false
++prompt-toolkit = false
++psutil = false
++pvporcupine = false
+ pyasn1 = false
-snowballstemmer = false
-concurrent-log-handler = false
-cryptography = false
+ pydantic = false
-agent-client-protocol = false
-fire = false
-httpx2 = false
-google-auth-oauthlib = false
++pyjwt = false
++pytest = false
++pytest-asyncio = false
++python-dotenv = false
+ python-multipart = false
-ty = false
-openai = false
-mautrix = false
-google-auth-httplib2 = false
++python-olm = false
+ python-telegram-bot = false
-psutil = false
-jinja2 = false
-hindsight-client = false
++pyyaml = false
++qrcode = false
++requests = false
++rich = false
++ruamel-yaml = false
++ruff = false
++sentencepiece = false
++setuptools = false
++setuptools-rust = false
++sherpa-onnx = false
++slack-bolt = false
++slack-sdk = false
++snowballstemmer = false
+ sounddevice = false
-alibabacloud-dingtalk = false
-dingtalk-stream = false
++starlette = false
++supermemory = false
++tenacity = false
++ty = false
++tzdata = false
++unpaddedbase64 = false
++uvicorn = false
++vercel = false
++websockets = false
++wheel = false
++youtube-transcript-api = false
[manifest]
overrides = [