The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge remote-tracking branch 'origin/main' into ethie/pm-clean
ethernete1576d06a69e
diff --cc .github/workflows/lint.ymlindex 033ffc05e6f,83c064eabde..e606d48b4a0--- a/.github/workflows/lint.yml+++ b/.github/workflows/lint.yml@@@ -174,8 -185,16 +174,16 @@@ jobs- name: Forbid in-tree use of plugin-compat pointersrun: python scripts/check_compat_pointers.py+ # /tmp is not portable (Termux has none, native Windows has none, macOS aliases it to+ # /private/tmp, Linux mounts it as a small tmpfs). Production code resolves scratch space+ # through the scratch-dir helper; skills, docs and prompts must not teach the model a+ # literal /tmp either. `no-tmp: ok — <why>` marks a deliberate line; _BASELINE in the+ # script is the burn-down list of pre-existing hits.+ - name: Forbid literal /tmp paths outside the baseline+ run: python scripts/check_no_tmp_literals.py+# The OS lanes import only files carrying the matching marker, so a test that fakes- # macOS (is_macos -> True, sys.platform -> "darwin") without `macos_only` is green on+ # macOS (is_macos -> True, sys.platform -> "darwin") without `platforms("macos")` is green on# Linux over a faked branch and never runs on macOS (#111866, AGENTS.md § Don't fake the host OS).- name: Forbid unmarked macOS fakes in testsrun: python scripts/ci/check_os_marker_fakes.pydiff --cc acp_adapter/entry.pyindex 2ea29719e2f,0851ad16766..c3aacb14a59--- a/acp_adapter/entry.py+++ b/acp_adapter/entry.py@@@ -133,18 -135,36 +133,26 @@@ def _run_setup() -> None_run_setup_browser(assume_yes=False)-_SETUP_BROWSER_STEPS = (- ("node", "Node.js installation failed — cannot proceed with browser tools."),- ("browser", "Browser tools installation failed."),-)--def _run_setup_browser(assume_yes: bool = False) -> int:- """Bootstrap agent-browser + Chromium via dep_ensure -> install.{sh,ps1}- --ensure (shared with the runtime lazy installer). Returns 0 on success, 1 on failure."""- from hermes_cli.dep_ensure import ensure_dependency+ """The setup command is an explicit request for PM's browser closure."""+ import pmtry:- for dep, failure_msg in _SETUP_BROWSER_STEPS:- if not ensure_dependency(dep, interactive=not assume_yes):- print(failure_msg, file=sys.stderr)- return 1- return 0- except OSError as exc:- print(f"Browser bootstrap failed: {exc}", file=sys.stderr)+ pm.ensure("agent-browser", explicit=True)+ except (pm.InstallError, OSError) as exc:+ print(f"Browser setup failed: {exc}", file=sys.stderr)return 1+ return 0+ def _warm_memory_provider_import(logger: logging.Logger) -> None:+ """Import ``memory.provider``'s module + numpy (no provider instance) before the ACP threads start."""+ from plugins.memory import import_memory_provider_module++ if not import_memory_provider_module():+ logger.debug("memory provider not warmed (none configured or import failed; agent init reports that)")++def main(argv: list[str] | None = None) -> None:"""Entry point: load env, configure logging, run the ACP agent."""args = _parse_args(argv)diff --cc agent/model_metadata.pyindex 1efc77351eb,34e6e8309a7..890f0b51663--- a/agent/model_metadata.py+++ b/agent/model_metadata.py@@@ -1696,13 -1781,13 +1731,13 @@@ def _fetch_codex_oauth_context_lengths_cached = _codex_oauth_context_cache.get(cache_key)if cached is not None and now - cached[1] < _CODEX_OAUTH_CONTEXT_CACHE_TTL:return cached[0], False- headers = {"Authorization": f"Bearer {access_token}"}- acct_id = _extract_chatgpt_account_id(access_token)- if acct_id:- headers["ChatGPT-Account-Id"] = acct_id+ # Without ChatGPT-Account-ID /backend-api/codex/models returns ``{"models":[]}`` (HTTP 200) and+ # the probe silently falls back; residency-enforced workspaces 401 without the residency header.+ from agent.codex_headers import codex_account_headers+ headers = {"Authorization": f"Bearer {access_token}", **codex_account_headers(access_token)}try:- _ensure_requests()- resp = requests.get(CODEX_MODELS_CATALOG_URL, headers=headers, timeout=(5, 10), verify=_resolve_requests_verify())++ resp = model_metadata_http.get(CODEX_MODELS_CATALOG_URL, headers=headers, timeout=(5, 10), verify=model_metadata_http.resolve_verify())if resp.status_code != 200:logger.debug("Codex /models probe returned HTTP %s; falling back to hardcoded defaults", resp.status_code)return {}, Falsediff --cc apps/desktop/README.mdindex 2af352c8011,09a0aa98ed9..efff5407727--- a/apps/desktop/README.md+++ b/apps/desktop/README.md@@@ -87,9 -84,9 +87,9 @@@ Point the app at a specific source chec```bash# throwaway HERMES_HOME, separate Electron userData, distinct app name to avoid the single-instance lock-../scripts/dev-sandbox.sh npm run dev+../../scripts/dev-sandbox.sh npm run devHERMES_DESKTOP_HERMES_ROOT=/path/to/clone npm run dev- HERMES_HOME=/tmp/throwaway npm run dev+ HERMES_HOME=$HOME/.hermes/cache/scratch/throwaway npm run devnpm run dev:fake-boot # exercise the startup overlay with deterministic delays```diff --cc apps/desktop/e2e/group-create-gate-remote-roster.spec.tsindex 3d2e596d1b7,917144f563b..aac3847b1d0--- a/apps/desktop/e2e/group-create-gate-remote-roster.spec.ts+++ b/apps/desktop/e2e/group-create-gate-remote-roster.spec.ts@@@ -10,18 -10,21 +10,20 @@@import { type ChildProcess, spawn, spawnSync } from 'node:child_process'import * as fs from 'node:fs'import * as net from 'node:net'+ import * as os from 'node:os'import * as path from 'node:path'+ import { startMockServer } from '../../../tests-js/scripts/mock-server'++import { writeEnvFile, writeMockProviderConfig } from '../../../tests-js/scripts/mock-provider-config'import {buildAppEnv,createSandbox,launchDesktop,type MockBackendFixture,type Sandbox,- waitForAppReady,- writeEnvFile,- writeMockProviderConfig,+ waitForAppReady} from './fixtures'- import { startMockServer } from '../../../tests-js/scripts/mock-server'import { type ElectronApplication, expect, type Page, test } from './test'const DESKTOP_ROOT = path.resolve(import.meta.dirname, '..')diff --cc apps/desktop/electron-builder.config.cjsindex 933881b95d8,00000000000..3e4e6a3d7e9mode 100644,000000..100644--- a/apps/desktop/electron-builder.config.cjs+++ b/apps/desktop/electron-builder.config.cjs@@@ -1,325 -1,0 +1,329 @@@+// THE electron-builder configuration — the whole thing, one file. There is+// no "build" field in package.json: run-electron-builder.mjs always passes+// --config for this file, so a stray package.json field would be silently+// ignored anyway, and splitting the config across JSON + this overlay is+// how the two halves drift.+//+// A .cjs module (not JSON) so the variant is decided at require time:+// HERMES_DESKTOP_VARIANT=light builds "Hermes Light". The whole config+// derives from that one flag.+// @ts-check+'use strict'++const fs = require('node:fs')+const path = require('node:path')+const feedContract = require('./update-feed.cjs')+const { createMacSigner } = require('./scripts/mac-sign.mjs')++const {+ light,+ store,+ storeMsix,+ displayName,+ appId,+ appNamePascal,+ artifactNamePascal,+ windowsExecutableName,+ channel,+ msixAppIdWithOrg+} = require('./product-identity.cjs')++// `storeMsix` is optional on the identity type but guaranteed present when+// `store` is true (product-identity.cjs spreads it only in that branch).+// The `store` flag is typed `boolean` in the identity, so checkJs cannot+// correlate the two; `mustStoreMsix` is the single assertion point and the+// invariant lives in product-identity.cjs:33-34/58-68.+/** @type {NonNullable<typeof storeMsix> | undefined} */+const storeMsixWhenStore = storeMsix++/**+ * The store MSIX packaging identity. Callers must only invoke this when+ * `store` is true (see the invariant note above).+ * @param {NonNullable<typeof storeMsix> | undefined} value+ * @returns {NonNullable<typeof storeMsix>}+ */+function mustStoreMsix(value) {+ return /** @type {NonNullable<typeof storeMsix>} */ (value)+}++// The out-of-store MSIX publisher (ATS cert subject) — single source, shared+// with the .appinstaller generator so the manifest and the App Installer can+// never drift (see scripts/msix-shared.mjs).+const { OUT_OF_STORE_PUBLISHER, channelBuildRequest, stageChannelManifest } = require('../../scripts/msix-shared.mjs')+const channelRequest = channelBuildRequest()++/** @typedef {import("app-builder-lib").Configuration} Configuration */++const [owner, repo] = (process.env.GITHUB_REPOSITORY || 'NousResearch/hermes-agent').split('/')+if (!owner || !repo) {+ throw new Error(`invalid GITHUB_REPOSITORY ${process.env.GITHUB_REPOSITORY}`)+}+const electronVersion = require('./package.json').devDependencies.electron+if (!/^\d+\.\d+\.\d+$/.test(electronVersion)) {+ throw new Error(`invalid electron version ${electronVersion} in package.json`)+}++const macFeed = channelRequest ? null : feedContract.darwinFeed(channel === 'canary' || channel === 'light-canary' ? 'canary' : 'stable', light)+const publicUrl = process.env.CLOUDFLARE_R2_PUBLIC_URL?.replace(/\/+$/, '')++/** @satisfies {Configuration} */+module.exports = {+ electronVersion,+ appId,+ productName: displayName,+ executableName: displayName,+ protocols: [+ {+ name: `${displayName} Protocol`,+ schemes: ['hermes']+ }+ ],+ // A store build is archived, never served to a feed — prefix its artifact+ // so it can't collide with the out-of-store MSIX of the same tag/arch, and+ // the release pipeline can keep the two apart.+ artifactName: `${store ? 'Store-' : ''}${artifactNamePascal}-\${version}-\${os}-\${arch}.\${ext}`,+ icon: 'assets/icon',+ // The electron-updater feed. CI builds set CLOUDFLARE_R2_PUBLIC_URL (the R2+ // public bucket / custom domain) and publish there — the feed yml, blockmaps+ // and installers all live in the same flat R2 bucket, and electron-updater+ // resolves the yml's relative artifact paths against it. Builds without the+ // var (local, or a fork without the R2 vars) keep the github provider, which+ // is exactly today's behavior. The store build has no feed at all (the Store+ // owns its distribution and updates).+ publish: channelRequest ? null : !channel+ ? null+ : [+ process.env.CLOUDFLARE_R2_PUBLIC_URL+ ? { provider: 'generic', url: process.env.CLOUDFLARE_R2_PUBLIC_URL.replace(/\/+$/, ''), channel }+ : { provider: 'github', owner, repo, channel }+ ],+ extraMetadata: {+ name: appNamePascal,+ // Electron bootstrap reads package.productName before main.ts. Keep the+ // shipped stable default, but isolate nonstable userData from first access.+ ...(channelRequest || appNamePascal !== artifactNamePascal ? { productName: displayName } : {}),+ desktopName: appId+ },+ directories: {+ output: 'release'+ },+ files: ['dist/**', 'assets/**', 'public/**', 'package.json'],+ beforeBuild: channelRequest ? async () => {+ await require(path.join(__dirname, 'scripts/before-build.mjs')).default()+ stageChannelManifest(__dirname, channelRequest)+ return false+ } : 'scripts/before-build.mjs',+ beforePack: 'scripts/before-pack.mjs',++ // The exe identity stamp runs here, on the pristine electron.exe, because++ // ASAR integrity rewrites the PE later and rcedit cannot commit to that++ // rewritten file (#105629). afterPack keeps the signing/payload work.++ afterExtract: 'scripts/after-extract.mjs',+ afterPack: 'scripts/after-pack.mjs',+ ...(process.platform === 'darwin' ? { afterSign: 'scripts/notarize.mjs' } : {}),+ extraResources: [+ {+ from: 'build/install-stamp.json',+ to: 'install-stamp.json'+ },+ ...(['bundled', 'store'].includes(process.env.HERMES_DESKTOP_VARIANT || '')+ ? [{ from: 'build/agent-payload', to: 'agent-payload' }]+ : []),+ {+ from: 'assets/icon.ico',+ to: 'icon.ico'+ }+ ],+ asar: {+ unpack: ['**/*.node', '**/prebuilds/**', 'dist/**']+ },+ mac: {+ // The afterSign hook owns notarization, including keychain-profile builds.+ notarize: false,+ // The packaged client reads this generated app-update.yml by default.+ publish: channelRequest?.receiverCandidate+ ? [{ provider: 'generic', url: `${channelRequest.publicBase}/releases/darwin/stable/`, channel: 'stable' }]+ : channelRequest+ ? [{ provider: 'generic', url: `${channelRequest.publicBase}/releases/channel-builds/${channelRequest.buildId}/darwin/`, channel: 'latest' }]+ : publicUrl && channel && macFeed+ ? [{ provider: 'generic', url: `${publicUrl}/${macFeed.directory}/`, channel: macFeed.channel }]+ : null,+ category: 'public.app-category.developer-tools',+ extendInfo: {+ CFBundleDisplayName: displayName,+ CFBundleExecutable: displayName,+ CFBundleName: displayName,+ LSRequiresNativeExecution: true,+ NSAudioCaptureUsageDescription: `${displayName} uses audio capture for voice conversations.`,+ NSCameraUsageDescription: `${displayName} uses the camera when a plugin or feature you enable requests it.`,+ NSMicrophoneUsageDescription: `${displayName} uses the microphone for voice input and voice conversations.`,+ NSCalendarsUsageDescription: `${displayName} needs access to Calendar to provide requested meeting and scheduling support.`,+ NSCalendarsFullAccessUsageDescription: `${displayName} needs full access to Calendar to read and manage events when explicitly requested.`,+ NSRemindersUsageDescription: `${displayName} needs access to Reminders to provide requested personal-assistant and scheduling support.`,+ NSRemindersFullAccessUsageDescription: `${displayName} needs full access to Reminders to read and manage reminders when explicitly requested.`,+ NSScreenCaptureUsageDescription: `${displayName} captures the screen when you ask the agent to screenshot or record it.`,+ NSLocalNetworkUsageDescription: `${displayName} connects to devices on your local network when a plugin or feature you enable requests it.`,+ NSAppleMusicUsageDescription: `${displayName} accesses your music library when a plugin or feature you enable requests it.`+ },+ target: ['dmg', 'zip'],+ sign: createMacSigner({+ entitlements: path.join(__dirname, 'electron/entitlements.mac.plist'),+ entitlementsInherit: path.join(__dirname, 'electron/entitlements.mac.inherit.plist'),+ hardenedRuntime: true,+ ignore: (/** @type {string} */ file) => {+ try {+ if (fs.lstatSync(file).isDirectory()) {+ return false+ }+ return !isMachO(file)+ } catch {+ return true+ }+ }+ })+ },+ dmg: {+ // Avoid the failing optional APFS shrink pass; keep compressed conversion.+ shrink: false,+ title: 'Hermes Agent Installer',+ // A prebuilt .tiff on purpose, not a PNG plus a @2x sibling: dmg-builder's+ // PNG path runs `tiffutil -cathidpicheck`, which on macOS 26 rewrites both+ // frames to 72 dpi and silently drops the 2x representation. A .tiff is+ // handed to dmgbuild untouched (dmg-builder/dist/dmgUtil.js), and living+ // outside assets/ keeps it out of the app bundle via the `files` whitelist.+ background: 'packaging/nous-dmg-2b.tiff',+ iconSize: 96,+ iconTextSize: 11,+ window: {+ width: 660,+ height: 400+ },+ contents: [+ {+ x: 253,+ y: 238,+ type: 'file'+ },+ {+ x: 512,+ y: 235,+ type: 'link',+ path: '/Applications'+ }+ ]+ },+ win: {+ executableName: windowsExecutableName,+ legalTrademarks: displayName,+ target: ['msix'],+ ...windowsSigning()+ },+ msix: {+ // A store build uses the Partner Center packaging identity (the Store+ // re-signs + rewrites the publisher on submission); everything else uses+ // the out-of-store ATS-cert identity.+ identityName: store ? mustStoreMsix(storeMsixWhenStore).identityName : msixAppIdWithOrg,+ applicationId: appNamePascal,+ displayName,+ publisher: store ? mustStoreMsix(storeMsixWhenStore).publisher : OUT_OF_STORE_PUBLISHER,+ publisherDisplayName: store ? mustStoreMsix(storeMsixWhenStore).publisherDisplayName : 'Nous Research',+ // Sideload canary MSIX versions are `X.Y.Z.<minutes-since-stable>` (see+ // scripts/msix-shared.mjs). setBuildNumber makes getVersionInWeirdWindowsForm+ // use the BUILD_NUMBER env (4th component) instead of hardcoding ".0" — a+ // stable build sets no BUILD_NUMBER and stays X.Y.Z.0, a canary build sets+ // it via scripts/bundles/desktop.py so App Installer updates over equal+ // canary-over-canary versions instead of refusing them.+ setBuildNumber: !store && !channelRequest,+ // Store versions are baked into a build-time template. App semver and+ // artifact filenames stay unchanged; the Store reserves revision zero.+ // Floor Windows 11 22H2. Below build 18307 the manifest schema caps+ // AppExtension Name at 39 chars and Microsoft's own+ // "com.microsoft.windows.copilotkeyprovider" is 40 (makeappx+ // 0x80080204 — A/B-verified against the 26100 kit; 18307 exactly+ // still failed on it, 22621 passes), and 22621 is the documented+ // Copilot hardware key floor anyway.+ minVersion: '10.0.22621.0',+ maxVersionTested: '10.0.26100.0',+ // Static path: the file itself is written by scripts/before-build.mjs at+ // build time (see the comment on the hook) — never at config require+ // time, so typecheck/test imports don't touch the filesystem.+ customExtensionsPath: 'build/msix-extensions.xml',+ customManifestPath: store ? 'build/store-msix-manifest.xml'+ : channelRequest || appNamePascal !== artifactNamePascal ? 'build/msix-manifest.xml' : 'assets/msix-manifest.xml',+ // Hermes state is deliberately shared with unpackaged CLI/gateway+ // processes. Pair the manifest's disabled virtualization properties with+ // the restricted capability that permits unvirtualized AppData/HKCU writes.+ capabilities: ['unvirtualizedResources'],+ showNameOnTiles: true+ },+ linux: {+ category: 'Development',+ maintainer: 'Nous Research <[email protected]>',+ synopsis: light+ ? 'Remote-only desktop client for Hermes Agent.'+ : 'Native desktop shell for Hermes Agent.',+ target: ['AppImage']+ }+}++if (channelRequest) {+ Object.assign(module.exports, { buildVersion: channelRequest.version })+ Object.assign(module.exports.extraMetadata, {+ version: channelRequest.version,+ shortVersion: channelRequest.windowsVersion,+ shortVersionWindows: channelRequest.windowsVersion+ })+ Object.assign(module.exports.mac, {+ bundleVersion: channelRequest.version,+ bundleShortVersion: channelRequest.version+ })+}++// MSIX build-time staging (build/appx icons + build/msix-extensions.xml)+// lives in scripts/before-build.mjs — an electron-builder lifecycle hook —+// NOT here at require time, so importing this config for typecheck/tests+// never writes to the filesystem.++// Azure Trusted Signing. The hook signs the .msix package itself and the+// product exe (after electron-builder's rcedit — the batch in afterPack runs+// too early for the exe); every other payload binary is batch-signed in+// afterPack via scripts/batch-sign-binaries.mjs, which this hook acknowledges+// with `true` so electron-builder never re-signs one-by-one. The package+// signature is all Windows install validation checks; inner Authenticode+// covers SmartScreen/WDAC tree scans. See batch-sign-binaries.mjs for the+// ordering contract.+const MACHO_MAGICS = new Set([+ 0xfeedface,+ 0xcefaedfe,+ 0xfeedfacf,+ 0xcffaedfe,+ 0xcafebabe,+ 0xbebafeca+])++/** @param {string} file */+function isMachO(file) {+ const buf = Buffer.alloc(4)+ const fd = fs.openSync(file, 'r')+ try {+ if (fs.readSync(fd, buf, 0, 4, 0) !== 4) {+ return false+ }+ } finally {+ fs.closeSync(fd)+ }+ return MACHO_MAGICS.has(buf.readUInt32BE(0))+}++function windowsSigning() {+ if (!process.env.AZURE_SIGN_ENDPOINT || !process.env.AZURE_CLIENT_ID) {+ return {}+ }+ return {+ sign: {+ type: 'signtool',+ sign: './scripts/batch-sign-binaries.mjs',+ signingHashAlgorithms: ['sha256'],+ publisherName: process.env.AZURE_SIGN_PUBLISHER+ }+ }+}diff --cc apps/desktop/scripts/after-extract.test.mjsindex 00000000000,eee0852f46f..f5f987fa16amode 000000,100644..100644--- a/apps/desktop/scripts/after-extract.test.mjs+++ b/apps/desktop/scripts/after-extract.test.mjs@@@ -1,0 -1,44 +1,44 @@@+ import assert from 'node:assert/strict'+ import path from 'node:path'+ import { createRequire } from 'node:module'+ import { fileURLToPath } from 'node:url'+ import { test, vi } from 'vitest'++ const stampExeIdentity = vi.hoisted(() => vi.fn().mockResolvedValue(undefined))+ vi.mock('./set-exe-identity.mjs', () => ({ stampExeIdentity }))++ const { default: afterExtract } = await import('./after-extract.mjs')++ const require = createRequire(import.meta.url)+ const desktopRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')-const desktopPackage = require(path.join(desktopRoot, 'package.json'))++// The builder config is electron-builder.config.cjs (package.json carries no `build` block).++const builderConfig = require(path.join(desktopRoot, 'electron-builder.config.cjs'))++ // #105629: the identity stamp must run BEFORE electron-builder's ASAR-integrity+ // rewrite of the exe (beforeCopyExtraFiles), i.e. from afterExtract, never from+ // afterPack — rcedit cannot commit changes to the resedit-rewritten PE. And the+ // fix must keep the integrity check on (no disableAsarIntegrity workaround).-test('the exe identity stamp is wired to afterExtract, not afterPack, with ASAR integrity kept on', () => {- assert.equal(desktopPackage.build.afterExtract, 'scripts/after-extract.mjs')- assert.equal(desktopPackage.build.afterPack, undefined)- assert.equal(desktopPackage.build.disableAsarIntegrity, undefined)++test('the exe identity stamp is wired to afterExtract with ASAR integrity kept on', () => {++ assert.equal(builderConfig.afterExtract, 'scripts/after-extract.mjs')++ assert.equal(builderConfig.disableAsarIntegrity, undefined)+ })++ test('stamps the stock electron.exe on win32 only, before it is renamed to Hermes.exe', async () => {+ stampExeIdentity.mockClear()+ const appOutDir = path.join('tmp', 'win-unpacked')++ await afterExtract({+ appOutDir,+ electronPlatformName: 'win32',+ packager: { appInfo: { productFilename: 'Hermes' } }+ })+ assert.deepEqual(stampExeIdentity.mock.calls, [[path.join(appOutDir, 'electron.exe'), desktopRoot]])++ stampExeIdentity.mockClear()+ await afterExtract({+ appOutDir: path.join('tmp', 'linux-unpacked'),+ electronPlatformName: 'linux',+ packager: { appInfo: { productFilename: 'Hermes' } }+ })+ assert.equal(stampExeIdentity.mock.calls.length, 0)+ })diff --cc apps/desktop/scripts/after-pack.mjsindex 2036de06a21,00000000000..504f7d4faafmode 100644,000000..100644--- a/apps/desktop/scripts/after-pack.mjs+++ b/apps/desktop/scripts/after-pack.mjs@@@ -1,107 -1,0 +1,94 @@@+/**+ * after-pack.mjs — electron-builder afterPack hook.+ *- * Stamps the Hermes icon + identity onto the packed Windows Hermes.exe via- * rcedit (delegated to set-exe-identity.mjs). This runs for EVERY packed build- * — first install, `hermes desktop`, the installer's --update rebuild, and a- * dev's manual `npm run pack` — so the branded exe can never silently revert- * to the stock "Electron" icon/name (the bug when the stamp lived only in- * install.ps1, which the update path doesn't use).- *- * Windows-only: rcedit edits PE resources, irrelevant on macOS/Linux where the- * app identity comes from the bundle Info.plist / desktop entry. Best-effort:- * a stamp failure must never fail an otherwise-good build (worst case is the- * stock icon, not a broken app), so we log and resolve rather than throw.++ * Per-platform post-pack work on the unpacked app: payload relocation, nested++ * Chromium + wheel signing on macOS, PE signature sanitizing and batch signing++ * on Windows. The exe identity stamp lives in after-extract.mjs (#105629).+ *+ * electron-builder passes a context with:+ * - electronPlatformName: 'win32' | 'darwin' | 'linux'+ * - appOutDir: the unpacked app directory for this target+ * - packager.appInfo.productFilename: the exe basename (e.g. 'Hermes')+ */++import path from 'node:path'+import fs from 'node:fs'+import { runPython } from '../../../scripts/build/python.mjs'++import { batchSignAppTree } from './batch-sign-binaries.mjs'+import { rehashPayloadDigests } from './payload-digests.mjs'+import { resolveSigningIdentity, signNestedChromium } from './sign-nested-chromium.mjs'+import { signWheelZipMembers } from './sign-wheel-zips.mjs'+import { sanitizeTree } from './sanitize-pe-signatures.mjs'- import { stampExeIdentity } from './set-exe-identity.mjs'++export default async function afterPack(context) {+ const platform = context.electronPlatformName+ const resources = platform === 'darwin'+ ? path.join(context.appOutDir, `${context.packager.appInfo.productFilename}.app`, 'Contents', 'Resources')+ : path.join(context.appOutDir, 'resources')+ const payload = path.join(resources, 'agent-payload')+ if (platform !== 'win32' && fs.existsSync(path.join(payload, 'manifest.json'))) {+ runPython([+ path.resolve(import.meta.dirname, '../../../scripts/bundles/payload.py'), 'relocate', payload], { stdio: 'inherit' })+ }+ if (platform === 'darwin') {+ if (fs.existsSync(payload)) {+ const entitlements = path.join(import.meta.dirname, '..', 'electron', 'entitlements.mac.inherit.plist')+ const { identity, keychain } = await resolveSigningIdentity(context.packager)+ const nested = signNestedChromium(payload, { entitlements, identity, keychain })+ console.log(+ `[after-pack] repaired ${nested.repaired} framework links; signed ${nested.signed} nested chromium targets` ++ (identity ? ` as ${identity}` : ' (no Developer ID in the builder keychain)')+ )+ // uv-cache wheel zips carry Mach-O members the notary validates but+ // electron-osx-sign cannot reach; sign them in place (see module doc).+ const wheels = signWheelZipMembers(payload, { identity, keychain })+ if (wheels.signed > 0) {+ console.log(+ `[after-pack] signed ${wheels.signed} Mach-O members across ${wheels.wheels} payload wheel zips` ++ (identity ? ` as ${identity}` : ' (no Developer ID in the builder keychain)'))+ }+ // The macOS signer refreshes this again before sealing the outer app.+ // Unsigned builds end here and still need final-byte facts.+ rehashPayloadDigests(payload)+ }+ return+ }+ if (platform === 'linux') {+ return+ }+ if (platform !== 'win32') {+ return+ }++ const productName = context.packager?.appInfo?.productFilename || 'Hermes'+ const exe = path.join(context.appOutDir, `${productName}.exe`)- const desktopRoot = path.resolve(import.meta.dirname, '..')++ // Repair dangling PE certificate tables BEFORE electron-builder signs the+ // tree. A stripped-but-still-declared signature makes signtool reject the+ // file with 0x800700C1, and AppxSIP inspects every PE inside the MSIX, so+ // one bad payload DLL fails the whole package. Unlike the stamp below this+ // is NOT best-effort: shipping past it means shipping an unsignable bundle.+ // this is a hack until https://github.com/astral-sh/python-build-standalone/pull/1217 is merged.+ const { scanned, repaired } = sanitizeTree(context.appOutDir)+ console.log(`[after-pack] ${scanned} PEs scanned, ${repaired.length} dangling certificate tables cleared`)+ for (const file of repaired) {+ console.log(` ${file}`)+ }+- try {- await stampExeIdentity(exe, desktopRoot)- } catch (err) {- // Never fail the build over a cosmetic stamp.- console.warn(`[after-pack] exe identity stamp failed (${err.message}); Hermes.exe keeps the stock Electron icon`)- }++ // The identity stamp already ran from afterExtract on the pristine exe++ // (scripts/after-extract.mjs, #105629); rcedit cannot commit to the++ // ASAR-integrity-rewritten PE we hold here.++ // Batch-sign every payload binary AFTER sanitize (above) and the rcedit+ // stamp: a dangling certificate table or a subsequent resource edit would+ // invalidate the signature. The product exe is excluded here and signed+ // per-file by the customSign hook (scripts/batch-sign-binaries.mjs) after+ // electron-builder's own rcedit + fuses pass. No-op with a loud warning when+ // the AZURE_SIGN_* environment is absent (unsigned/fork/canary lanes).+ await batchSignAppTree(context.appOutDir, exe, {+ config: context.packager.config,+ resourcesDir: context.packager.buildResourcesDir,+ })+ rehashPayloadDigests(payload)+}diff --cc apps/desktop/scripts/stage-native-deps.mjsindex 241902b74f4,e6c1282f510..bb56593f51a--- a/apps/desktop/scripts/stage-native-deps.mjs+++ b/apps/desktop/scripts/stage-native-deps.mjs@@@ -650,32 -691,22 +697,24 @@@ export function stageGetWindows{platform = process.platform,arch = process.arch,- resolveRoot = resolveGetWindowsRoot,+ source = resolve(projectRoot, '../..'),+ out = join(source, 'apps/desktop/dist/node_modules'),- resolveRoot = () => resolveGetWindowsRoot(join(source, 'apps/desktop'))++ resolveRoot = () => resolveGetWindowsRoot(join(source, 'apps/desktop')),+ findHalfInstalledDir = findHalfInstalledGetWindowsDir} = {}) {const srcRoot = resolveRoot()- const destRoot = resolve(projectRoot, 'dist/node_modules/get-windows')+ const destRoot = join(out, 'get-windows')if (!srcRoot) {- // npm may omit an optional dependency whose install script fails. That is- // expected on Linux and win32-arm64 because get-windows 9.3.0 publishes no- // native prebuilt for either target. The runtime import already fails soft,- // so disable only window enumeration instead of failing the Desktop build.- // Other Windows architectures and macOS have supported native payloads and- // remain fail-closed so a broken package cannot ship silently.- const canDegrade = platform === 'linux' || (platform === 'win32' && arch === 'arm64')- if (canDegrade) {- console.warn(- `[stage-native-deps] get-windows not installed (optional dep skipped for ${platform}-${arch}); ` +- 'read_window_below will be unavailable in this build'- )- return undefined- }- throw new Error(- `[stage-native-deps] get-windows is not installed; cannot stage its ${platform}-${arch} native payload`+ // npm may omit an optional dependency whose install script fails, or an in-place+ // update may fail to extract it due to file locks (#90829). The runtime import+ // already fails soft, so we disable only window enumeration instead of failing+ // the entire Desktop build (which would strand users on an old version).+ console.warn(+ missingGetWindowsWarning({ platform, arch, halfInstalledDir: findHalfInstalledDir() }))+ return undefined}// Only a win32 host can produce the win32 binding, so a cross-platform packdiff --cc hermes_bootstrap.pyindex 6afac1b9a13,e36a662ba1a..30d8ff3ded9--- a/hermes_bootstrap.py+++ b/hermes_bootstrap.py@@@ -302,48 -302,41 +302,63 @@@ def harden_import_path(src_root: str |sys.path.insert(0, root)-def activate_durable_lazy_target() -> None:- """Put the durable lazy-install dir (``HERMES_LAZY_INSTALL_TARGET``) on ``sys.path``.-- Immutable Docker images seal the venv and redirect lazy installs to the data volume;- packages installed there on a previous run must be importable before any backend- imports its SDK. Appends to the END of ``sys.path`` so the core venv always wins name- collisions (see ``tools.lazy_deps``). Never raises; unset target is a no-op.- """- if not os.environ.get("HERMES_LAZY_INSTALL_TARGET", "").strip():- return- try:- from tools import lazy_deps- lazy_deps.activate_durable_lazy_target()- except Exception:- pass # a failed activation just leaves the backend reporting itself unavailable--+ def export_scratch_tmp_env() -> None:+ """Point ``TMPDIR``/``TMP``/``TEMP`` at ``HERMES_HOME/cache/scratch`` unless the user set them.++ System temp is tmpfs on most Linux hosts and containers; Hermes' browser profiles, PTY+ probes and every ``tempfile`` default a child script makes would eat RAM there. Runs at+ import so every entry point and every child they spawn inherits it; ``hermes_cli.main``+ re-runs it after ``--profile`` re-homes the process. Never raises.+ """+ try:+ from hermes_constants import export_scratch_tmp_env as _export+ _export()+ except Exception:+ pass # a missing/unwritable home just leaves the system temp dir in place++-# Apply on import — entry points only need ``import hermes_bootstrap`` first.+# Apply on import — entry points just need ``import hermes_bootstrap``+# (or ``from hermes_bootstrap import apply_windows_utf8_bootstrap``) at+# the very top of their module, before importing anything else. The+# import side effect does the right thing.apply_windows_utf8_bootstrap()suppress_platform_ver_console()-activate_durable_lazy_target()++# Every entry point imports this module before its dependency graph.+from pathlib import Path+from pm.environments import activate_dependencies+from hermes_cli._early_recovery import recover_if_needed++from hermes_cli._parser import command_argv++_root = Path(__file__).resolve().parent+# Repair needs only stdlib. Do not activate the damaged tree to reach it.+_pm_repair = command_argv(sys.argv[1:])[:2] == ["pm", "repair"]+if not _pm_repair:+ from hermes_cli.venv_sync import prepare_launch, relaunch_command++ try:+ _launch_python = prepare_launch(_root, sys.argv[1:])+ if _launch_python is not None:+ _main_spec = getattr(sys.modules.get("__main__"), "__spec__", None)+ _command = relaunch_command(+ _launch_python, _root, sys.argv, sys.orig_argv,+ getattr(_main_spec, "name", None),+ )+ if os.name == "nt":+ import subprocess++ raise SystemExit(subprocess.call(_command))+ os.execv(str(_launch_python), _command)+ except Exception as exc:+ print(f"hermes: source-update completion failed: {exc}", file=sys.stderr)+ raise SystemExit(1) from None+ recover_if_needed(_root)+ try:+ activate_dependencies(_root)+ except (RuntimeError, OSError) as exc:+ if command_argv(sys.argv[1:])[:1] != ["pm"]:+ print(f"hermes: {exc}; run `hermes pm repair`", file=sys.stderr)+ raise SystemExit(1) from Noneinstall_happy_eyeballs_socket_connect()-+ export_scratch_tmp_env()diff --cc hermes_cli/cli_commands_mixin.pyindex bfe3178f161,997c8bfaacd..00d7602e8a9--- a/hermes_cli/cli_commands_mixin.py+++ b/hermes_cli/cli_commands_mixin.py@@@ -27,9 -28,10 +27,10 @@@ from rich import box as rich_bofrom rich.markup import escape as _escapefrom rich.panel import Panel-from hermes_constants import display_hermes_home, is_termux as _is_termux_environment+from hermes_constants import display_hermes_homefrom hermes_state_ids import new_session_id as mint_session_idfrom agent.turn_context import extract_api_content_sidecar+ from hermes_cli.cli_agent_setup_mixin import _retire_agentfrom hermes_cli.browser_connect import (DEFAULT_BROWSER_CDP_URL, discover_local_cdp_url, find_free_debug_port, is_browser_debug_ready,launch_chrome_debug, local_port_in_use, manual_chrome_debug_command)diff --cc hermes_cli/codex_runtime_plugin_migration.pyindex eea2366d7e2,8305a37129a..45631b3beb6--- a/hermes_cli/codex_runtime_plugin_migration.py+++ b/hermes_cli/codex_runtime_plugin_migration.py@@@ -430,12 -472,10 +472,10 @@@ def migratetranslated[HERMES_TOOLS_MCP_SERVER_NAME] = _build_hermes_tools_mcp_entry()if HERMES_TOOLS_MCP_SERVER_NAME not in report.migrated:report.migrated.append(HERMES_TOOLS_MCP_SERVER_NAME)- managed_block = render_codex_toml_section(- translated, plugins=plugins, default_permission_profile=default_permission_profile)- new_text = managed_block+ without_managed = ""if target.exists():try:- existing = target.read_text(encoding="utf-8")+ existing = target.read_text(encoding="utf-8-sig")except Exception as exc:report.errors.append(f"could not read {target}: {exc}")return reportdiff --cc hermes_cli/main.pyindex 199f8ee6889,564ae1b782b..26a96e3fe77--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@@ -599,13 -626,15 +601,21 @@@ def _apply_profile_override() -> None_apply_profile_override()+ # ``-p``/active_profile re-homed the process after hermes_bootstrap ran: re-point the temp vars+ # at THIS home's scratch dir (a user-set TMPDIR is still left alone).+ try:+ from hermes_constants import export_scratch_tmp_env as _export_scratch_tmp_env++ _export_scratch_tmp_env()+ except Exception:+ pass # an unwritable home leaves the system temp dir in place; never block startup+# PM runs after profile resolution but before application dependency imports.+if sys.argv[1:2] == ["pm"]:+ from pm.cli import main as _pm_main++ raise SystemExit(_pm_main(sys.argv[2:]))+# Windows launcher self-heal — the ``hermes`` command is a COPY of the venv# console script staged into the managed bin dir (outside the checkout, since# ``hermes update``'s autostash once swept ``<checkout>\bin`` copies off disk;diff --cc hermes_cli/tools_config_post_setup.pyindex f9b5a0e98eb,089b6622363..95dc0b15225--- a/hermes_cli/tools_config_post_setup.py+++ b/hermes_cli/tools_config_post_setup.py@@@ -262,7 -411,8 +323,8 @@@ _POST_SETUP_HOOKS: dict ="spotify": _post_setup_spotify,"langfuse": _post_setup_langfuse,"xai_grok": _post_setup_xai_grok,+ "openai_codex": _post_setup_openai_codex,- **{key: (lambda spec=spec: _post_setup_pip(spec)) for key, spec in _PIP_POST_SETUP_HOOKS.items()},+ **{key: (lambda spec=spec: _post_setup_python(spec)) for key, spec in _PYTHON_POST_SETUP_HOOKS.items()},}@@@ -371,11 -545,10 +433,11 @@@ def _cloud_agent_browser_installed() -# post_setup_key -> predicate(): True when the install side-effect is satisfied. Used by# ``provider_readiness_status`` to mark a keyless post_setup row "ready" vs "needs_setup"; mirrors the- # installed-checks the hooks perform. ``xai_grok`` is absent — a credential bootstrap handled as an- # auth check. Late-bound lambdas so tests can monkeypatch the underlying predicates.+ # installed-checks the hooks perform. Credential bootstraps (``xai_grok``, ``openai_codex``) are absent —+ # they live in ``_POST_SETUP_AUTH_READY`` as auth checks. Late-bound lambdas so tests can monkeypatch the underlying predicates._POST_SETUP_READY: dict = {- **{key: (lambda m=module: _module_installed(m)) for key, (module, _args) in _RESTORABLE_PYTHON_TOOL_DEPENDENCIES.items()},+ **{key: (lambda m=spec["module"]: _module_installed(m)) for key, spec in _PYTHON_POST_SETUP_HOOKS.items()},+ "langfuse": lambda: _module_installed("langfuse"),"agent_browser": lambda: _agent_browser_installed(),"browserbase": lambda: _cloud_agent_browser_installed(),"camofox": lambda: _camofox_installed(),diff --cc hermes_cli/update_cmd_zip.pyindex e1db20496ba,efb8b99948a..d04b7c6c09c--- a/hermes_cli/update_cmd_zip.py+++ b/hermes_cli/update_cmd_zip.py@@@ -12,8 -11,11 +12,8 @@@ import shutiimport subprocessimport sysfrom pathlib import Path- from typing import Optional+ from typing import Collection, Optional-from hermes_cli.update_cmd_common import _best_effort-from hermes_constants import project_venv_dir-# Log-record parity with the origin module.logger = logging.getLogger("hermes_cli.update_cmd")diff --cc scripts/profile-tui.pyindex 6c0fa2d4330,d13fb70cac9..678ade61e59--- a/scripts/profile-tui.py+++ b/scripts/profile-tui.py@@@ -516,8 -517,8 +517,8 @@@ def main() -> intif not path.exists():print(f"\n⚠ no baseline at {path} — run with --save {args.compare} first")else:- before = json.loads(path.read_text(encoding="utf-8"))+ before = json.loads(path.read_text(encoding="utf-8-sig"))- print(f"\n═══ A/B diff vs /tmp/perf-{args.compare}.json ═══")+ print(f"\n═══ A/B diff vs {path} ═══")print(format_diff(before, metrics))if not data["react"] and not data["frame"]:diff --cc scripts/run_tests_parallel.pyindex 6a3e3f351f6,af1c08f626d..8e2facc0d7emode 100644,100755..100644--- a/scripts/run_tests_parallel.py+++ b/scripts/run_tests_parallel.pydiff --cc tests/gateway/test_model_picker_persist.pyindex 9c285280e9c,719db5697b8..079701a8b7f--- a/tests/gateway/test_model_picker_persist.py+++ b/tests/gateway/test_model_picker_persist.py@@@ -19,9 -19,10 +19,10 @@@ callback and assert ``config.yaml`` isclosure the PR changed, against a real temp ``HERMES_HOME``."""+ import asyncioimport types-import yaml+import hermes_yaml as yamlimport pytestfrom gateway.config import Platformdiff --cc tests/gateway/test_runtime_footer.pyindex 5f382964466,1dae4d68ed9..e56b7b40200--- a/tests/gateway/test_runtime_footer.py+++ b/tests/gateway/test_runtime_footer.py@@@ -324,5 -315,27 +324,27 @@@ def test_default_build_footer_line_igno)baseline = build_footer_line(**common)with_timing = build_footer_line(**common, turn_seconds=125.0)- assert baseline == "gpt-5.4 · 5% · /var/data"+ assert baseline == f"gpt-5.4 · 5% · {_VAR_DATA}"assert with_timing == baseline+++ def test_format_footer_served_model_is_opt_in_and_skips_same_model():+ """#54864: `served_model` renders `alias → served` only when listed AND the served model+ differs from the requested one; the default field set never shows it."""+ # Default fields: served model is invisible.+ assert "→" not in format_runtime_footer(+ model="hermes-router", context_tokens=0, context_length=None, cwd="/x",+ served_model="gpt-4o-2024-11-20")+ line = format_runtime_footer(+ model="hermes-router", context_tokens=0, context_length=None, cwd="/x",+ served_model="gpt-4o-2024-11-20", fields=["served_model"])+ assert line == "hermes-router → gpt-4o-2024-11-20"+ # Hermes fallback route: requested primary → active model.+ line = format_runtime_footer(+ model="qwen/qwen3.8-max", context_tokens=0, context_length=None, cwd="/x",+ requested_model="gpt-5.6-sol", served_model="qwen/qwen3.8-max", fields=["served_model"])+ assert line == "gpt-5.6-sol → qwen/qwen3.8-max"+ # Served == requested (no header, no fallback): field skipped, nothing empty rendered.+ assert format_runtime_footer(+ model="gpt-5.4", context_tokens=0, context_length=None, cwd="/x",+ served_model=None, fields=["served_model"]) == ""diff --cc tools/environments/base.pyindex 8c349c43af0,f3e3627c6a1..2b33e534e69--- a/tools/environments/base.py+++ b/tools/environments/base.py@@@ -171,13 -164,9 +171,13 @@@ class BaseEnvironment(ABC)_profile_scoped_passthrough: bool = Falsedef get_temp_dir(self) -> str:- """Backend temp directory for session artifacts (``/tmp`` in sandboxes;- LocalEnvironment overrides for Termux where only ``TMPDIR`` is writable)."""+ """Return the backend temp directory used for session artifacts.++ Most sandboxed backends use ``/tmp`` inside the target environment.+ LocalEnvironment overrides this on hosts where ``/tmp`` may be missing+ and ``TMPDIR`` is the portable writable location.+ """- return "/tmp"+ return "/tmp" # no-tmp: ok — sandbox-side (remote container) temp dir, not the hostdef __init__(self, cwd: str, timeout: int, env: dict = None):self.cwd = cwddiff --cc tools/environments/local.pyindex eba0f0378a9,f75bcabc75a..69910e8c8ec--- a/tools/environments/local.py+++ b/tools/environments/local.py@@@ -836,40 -825,13 +837,17 @@@ class LocalEnvironment(BaseEnvironment)self.init_session()def get_temp_dir(self) -> str:- """Return a shell-safe writable temp dir for local execution.-- Some Unix hosts do not provide /tmp but do export a POSIX TMPDIR.- Prefer POSIX-style env vars when available, keep using /tmp on regular- Unix systems, and only fall back to tempfile.gettempdir() when it also- resolves to a POSIX path.-- Check the environment configured for this backend first so callers can- override the temp root explicitly (for example via terminal.temp_dir,- terminal.env, or a custom TMPDIR), then fall back to the host process- environment.-- **Default (no override set):** a dedicated cache dir under- ``HERMES_HOME`` (``~/.hermes/cache/terminal``) rather than ``/tmp``.- On several distros (Arch and friends) ``/tmp`` is a small RAM-backed- tmpfs, and Hermes session artifacts — background-process logs,- code-execution sandboxes, spilled tool results — can fill it under- load. Real storage is the safer default; stale artifacts are pruned- by ``cleanup_terminal_temp_cache`` (gateway housekeeping + a- once-per-process best-effort sweep) since we no longer get tmpfs- reboot wipes for free.-- **Windows:** hardcoded ``/tmp`` is wrong in two ways — native Python- can't open the path, and the Windows default temp (``%TEMP%``) often- contains spaces (``C:\\Users\\Some Name\\AppData\\Local\\Temp``) that- break unquoted bash interpolations. Use a dedicated cache dir under- ``HERMES_HOME`` instead — single-word path, guaranteed to exist, same- string resolves in both Git Bash and native Python.- """+ """Shell-safe writable temp dir. Precedence: ``TERMINAL_TEMP_DIR``, TMPDIR/TMP/TEMP+ (Termux has no system temp dir), ``HERMES_HOME/cache/terminal`` (real storage: a+ tmpfs system temp dir fills under Hermes load; pruned by ``cleanup_terminal_temp_cache``),+ ``tempfile.gettempdir()``; backend env before process env so terminal.env+ overrides work. Windows: ``%TEMP%`` often has spaces that break unquoted bash,+ so always the HERMES_HOME cache dir with forward slashes (bash- and Python-valid)."""if _IS_WINDOWS:+ for key in ("TERMINAL_TEMP_DIR", "TMPDIR"):+ candidate = self.env.get(key) or os.environ.get(key)+ if candidate and os.path.isabs(candidate) and os.path.isdir(candidate):+ return Path(candidate).as_posix()cache_dir = (_default_terminal_temp_dir()or Path(tempfile.gettempdir()) / "hermes_terminal")cache_dir.mkdir(parents=True, exist_ok=True)diff --cc website/docs/user-guide/features/cron.mdindex a226adbe8c5,006d346c16b..36c43c1f772--- a/website/docs/user-guide/features/cron.md+++ b/website/docs/user-guide/features/cron.md@@@ -1241,10 -1258,10 +1258,10 @@@ cronjob(action="create", name="process-**External-flag gate** — only run when some other process has signalled readiness (e.g. a deploy hook drops a file, a CI job sets a value in your state store).```bash-#!/bin/bash+#!/usr/bin/env bash# ~/.hermes/scripts/flag-ready.sh- if test -f /tmp/new-data-ready; then- rm -f /tmp/new-data-ready+ if test -f ~/.hermes/cache/scratch/new-data-ready; then+ rm -f ~/.hermes/cache/scratch/new-data-readyecho '{"wakeAgent": true}'elseecho '{"wakeAgent": false}'