Skip to content

The agent that grows with you

merge: local-models (upstream/feat/local-models) onto the pm-clean stack

etherneta9be133aea33
diff --cc .github/workflows/desktop-bundled-release.yml
index af1a6cd6813,00000000000..7c078f216bd
mode 100644,000000..100644
--- a/.github/workflows/desktop-bundled-release.yml
+++ b/.github/workflows/desktop-bundled-release.yml
@@@ -1,675 -1,0 +1,689 @@@
+name: Desktop Bundled Release
+
+# Builds the bundled desktop installer for each (os, arch) target.
+#
+# tag admission (shape + pyproject lockstep + ancestry-on-origin/main,
+# resolved to an IMMUTABLE full SHA) → 6-target matrix → pm bundle
+# → stage artifacts to R2 (releases/tag/<tag>/) → finalize job merges
+# the darwin feeds (releases/darwin/<ch>/<channel>-mac.yml + dmg/zip),
+# the msixbundle job stages the win32 App Installer feeds
+# (releases/win32/<ch>/*.appinstaller + *.msixbundle) → builds table.
+# The GitHub release keeps the notes only — no binaries.
+#
+# Feed layout (matches apps/desktop/electron/app-updater.ts's arms):
+# releases/win32/<stable|nightly>/<ch>.appinstaller App Installer feed
+# releases/win32/<stable|nightly>/*.msixbundle (msixbundle job)
+# releases/darwin/<stable|nightly>/*-mac.yml electron-updater (dmg/zip)
+# The finalize + msixbundle jobs write the feeds ONCE after the whole matrix
+# is green, so a failed leg can never publish a partial channel.
+#
+# Payload staging is `hermes pm bundle` on the native runner. There is
+# no cross-target staging. Signing and notarization are a later commit;
+# this file produces unsigned artifacts on forks. When the
+# release-signing environment has the Apple and Azure identifiers,
+# the same job signs and notarizes.
+#
+# scripts/build-bundled-desktop.mjs is the one driver. Local and CI run
+# the same command. This workflow adds caching and upload only.
+#
+# Triggers: workflow_dispatch with an explicit tag. A tag push does not
+# start this workflow (a bot-pushed nightly tag would never fire).
+#
+# R2 secrets (repo-level or the release-signing environment): the R2
+# account id + an R2 API token (S3-compatible) with read/write on the
+# release bucket; CLOUDFLARE_R2_BUCKET and CLOUDFLARE_R2_PUBLIC_URL are
+# non-secret vars. scripts/r2-release.mjs derives the S3 endpoint from
+# the account id and needs only node — no npm ci, no extra deps.
+
+on:
+ workflow_dispatch:
+ inputs:
+ tag:
+ description: 'Release tag to bundle (vX.Y.Z or vX.Y.0-nightly.YYYYMMDDHHMMSS). Must exist on the repo.'
+ required: true
+ type: string
+ upload_release:
+ description: 'Upload artifacts to the R2 release bucket (staging + feeds)'
+ required: false
+ type: boolean
+ default: false
+
+permissions:
+ contents: write
+ id-token: write
+
+concurrency:
+ group: desktop-bundled-release-${{ inputs.tag }}
+ cancel-in-progress: false
+
+jobs:
+ validate:
+ name: Validate the tag
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ outputs:
+ # The tag's commit, resolved ONCE here and exported as a full SHA.
+ # Every privileged job checks out THIS — never the tag ref, which a
+ # force-push can move between the validate and build jobs.
+ sha: ${{ steps.admission.outputs.sha }}
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ ref: ${{ inputs.tag }}
+ # Full history: the admission gate below runs merge-base against
+ # origin/main, which needs the shared ancestry, not a depth-1 tip.
+ fetch-depth: 0
+ fetch-tags: true
+
+ - name: Validate tag shape, pyproject lockstep, and ancestry on origin/main
+ id: admission
+ env:
+ TAG: ${{ inputs.tag }}
+ run: |
+ case "$TAG" in
+ v[0-9]*.[0-9]*.[0-9]*-nightly.20[0-9][0-9][0-9][0-9][0-9][0-9]*)
+ echo "nightly tag: $TAG"
+ ;;
+ v[0-9]*.[0-9]*.[0-9]*)
+ echo "tag: $TAG"
+ PYVER=$(sed -n 's/^version = "\([^"]*\)"/\1/p' pyproject.toml | head -1)
+ if [ "$TAG" != "v$PYVER" ]; then
+ echo "::error::tag $TAG does not match pyproject.toml version $PYVER"
+ exit 1
+ fi
+ ;;
+ *)
+ echo "::error::'$TAG' is not a release tag (vX.Y.Z or vX.Y.0-nightly.YYYYMMDDHHMMSS)"
+ exit 1
+ ;;
+ esac
+ SHA="$(git rev-parse --verify "$TAG^{commit}")"
+ if [ -z "$SHA" ]; then
+ echo "::error::could not resolve $TAG to a commit"
+ exit 1
+ fi
+ # A correctly-shaped tag on an unreviewed commit is NOT a valid
+ # build input for a release-signing workflow: only a commit that
+ # is already an ancestor of origin/main may be built.
+ git fetch origin main
+ if ! git merge-base --is-ancestor "$SHA" origin/main; then
+ echo "::error::tag $TAG (${SHA:0:12}) is not an ancestor of origin/main — refusing to build from an unreviewed commit"
+ exit 1
+ fi
+ echo "tag $TAG resolves to $SHA (on origin/main)"
+ echo "sha=$SHA" >> "$GITHUB_OUTPUT"
+
+ build:
+ name: bundled ${{ matrix.target.label }}
+ needs: validate
+ runs-on: ${{ matrix.target.runner }}
+ environment: release-signing
+ timeout-minutes: 90
+ strategy:
+ fail-fast: false
+ matrix:
+ target:
+ - label: linux-x64
+ runner: ubuntu-24.04
+ - label: linux-arm64
+ runner: ubuntu-24.04-arm
+ - label: darwin-arm64
+ runner: macos-15
+ - label: darwin-x64
+ runner: macos-15-intel
+ - label: win32-x64
+ runner: windows-2025
+ - label: win32-arm64
+ runner: windows-11-arm
+ env:
+ HERMES_DESKTOP_VARIANT: bundled
+ HERMES_PAYLOAD_TAG: ${{ inputs.tag }}
+ ELECTRON_BUILDER_CACHE: ${{ github.workspace }}/.cache/electron-builder
+ ELECTRON_CACHE: ${{ github.workspace }}/.cache/electron
+ electron_config_cache: ${{ github.workspace }}/.cache/electron
+ CLOUDFLARE_R2_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_R2_ACCOUNT_ID }}
+ CLOUDFLARE_R2_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_ACCESS_KEY_ID }}
+ CLOUDFLARE_R2_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_SECRET_ACCESS_KEY }}
+ CLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}
+ CLOUDFLARE_R2_PUBLIC_URL: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}
+ steps:
+ - name: Disable Spotlight indexing and XProtect
+ if: startsWith(matrix.target.label, 'darwin-')
+ shell: bash
+ run: |
+ sudo mdutil -a -i off || true
+ sudo pkill -9 XProtect >/dev/null || true
+ while pgrep XProtect; do sleep 3; done
+
+ - name: Exclude build write paths from Defender scanning
+ if: startsWith(matrix.target.label, 'win32-')
+ shell: powershell
+ run: |
+ $paths = @(
+ $env:GITHUB_WORKSPACE,
+ $env:RUNNER_TEMP,
+ (npm config get cache)
+ )
+ foreach ($p in $paths) {
+ try {
+ Add-MpPreference -ExclusionPath $p
+ Write-Host "Defender exclusion added for $p"
+ } catch {
+ Write-Host "Defender exclusion not applied for $p ($($_.Exception.Message)) - continuing"
+ }
+ }
+ try {
+ Set-MpPreference -DisableRealtimeMonitoring $true
+ } catch {
+ Write-Host "Could not disable windows defender"
+ }
+
+ # Check out the SHA the validate job admitted — never the tag ref,
+ # which a force-push can move between jobs. This is the privileged
+ # (release-signing) build; it must run the reviewed bytes.
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ ref: ${{ needs.validate.outputs.sha }}
+ fetch-tags: true
+
+ - name: Resolve toolchain pins from pm/lock.json
+ id: pins
+ shell: bash
+ # The host toolchain that BUILDS the artifact comes from the same
+ # pin table as the embedded runtimes (pm/lock.json), so gate == pin
+ # by construction in build-bundled-desktop.mjs's toolchain gates.
+ run: |
+ python -c '
+ import json
+ pkgs = json.load(open("pm/lock.json"))["packages"]
+ for tool in ("node", "npm", "uv"):
+ print(tool + "=" + pkgs[tool]["version"])
+ ' >> "$GITHUB_OUTPUT"
+
+ - name: Resolve toolchain cache key
+ id: toolchain
+ shell: bash
+ run: |
+ node -e '
+ const l = require("./package-lock.json")
+ const el = l.packages["apps/desktop/node_modules/electron"].version
+ const eb = l.packages["node_modules/electron-builder"].version
+ if (!el || !eb) process.exit(1)
+ console.log(`electron=${el}`)
+ console.log(`builder=${eb}`)
+ ' >> "$GITHUB_OUTPUT"
+
+ - uses: actions/[email protected] # immutable release. safe to pin.
+ with:
+ node-version: ${{ steps.pins.outputs.node }}
+ cache: npm
+
+ - name: Install pinned npm
+ shell: bash
+ env:
+ NPM_PIN: ${{ steps.pins.outputs.npm }}
+ run: npm --version | grep -qx "$NPM_PIN" || npm i -g "npm@$NPM_PIN"
+
+ - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # 9.0.0
+ with:
+ version: ${{ steps.pins.outputs.uv }}
+ enable-cache: false
+
+ - name: Cache vcpkg OpenSSL (arm64)
+ if: matrix.target.label == 'win32-arm64'
+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ with:
+ path: C:\vcpkg\installed\arm64-windows-static-md
+ key: vcpkg-openssl-arm64-windows-static-md-${{ runner.os }}
+
+ - name: Install OpenSSL (arm64)
+ if: matrix.target.label == 'win32-arm64'
+ shell: bash
+ run: |
+ if [ ! -f "/c/vcpkg/installed/arm64-windows-static-md/lib/libcrypto.lib" ]; then
+ "$VCPKG_INSTALLATION_ROOT/vcpkg" install openssl:arm64-windows-static-md
+ fi
+ {
+ printf 'OPENSSL_DIR=C:\\vcpkg\\installed\\arm64-windows-static-md\n'
+ printf 'OPENSSL_STATIC=1\n'
+ } >> "$GITHUB_ENV"
+
+ - name: Cache pm store
+ # Tag-dispatched runs (every nightly) scope actions/cache under the
+ # dispatch ref, which GitHub mangles to refs/heads/refs/tags/<tag> —
+ # a different scope per tag, so an exact key can never be restored
+ # by a later nightly. The content key below is stable across tags
+ # when pm/lock.json + uv.lock are unchanged; the restore-keys prefix
+ # (which ignores the tag entirely) rescues the previous nightly's
+ # store when the locks DID move.
+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ with:
+ path: apps/desktop/build/agent-payload/tools
+ key: pm-store-${{ matrix.target.label }}-${{ hashFiles('pm/lock.json', 'uv.lock') }}
+ restore-keys: |
+ pm-store-${{ matrix.target.label }}-
+
+ - name: Resolve electron's default download cache path
+ shell: bash
+ run: |
+ # @electron/get does NOT honor ELECTRON_CACHE/electron_config_cache:
+ # the electron-builder build's electron zip download uses the
+ # default env-paths cache root. It must be in the actions/cache
+ # path list or every build re-downloads electron (~115MB).
+ case "$RUNNER_OS" in
+ Windows) echo "ELECTRON_DEFAULT_CACHE=$LOCALAPPDATA/electron/Cache" >> "$GITHUB_ENV" ;;
+ macOS) echo "ELECTRON_DEFAULT_CACHE=$HOME/Library/Caches/electron" >> "$GITHUB_ENV" ;;
+ *) echo "ELECTRON_DEFAULT_CACHE=$HOME/.cache/electron" >> "$GITHUB_ENV" ;;
+ esac
+
+ - name: Cache electron + electron-builder toolchain
+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ with:
+ path: |
+ ${{ github.workspace }}/.cache/electron-builder
+ ${{ github.workspace }}/.cache/electron
+ ${{ env.ELECTRON_DEFAULT_CACHE }}
+ # eb2: bumped from eb- (2026-08-28) — the old eb- caches never
+ # contained the electron zip (it lives in @electron/get's default
+ # cache root, which wasn't in the path list), so every build
+ # re-downloaded electron. The new key forces a fresh save that
+ # includes the default cache root.
+ key: eb2-${{ runner.os }}-${{ runner.arch }}-electron-${{ steps.toolchain.outputs.electron }}-builder-${{ steps.toolchain.outputs.builder }}
+ # An electron/builder bump misses the exact key, but the previous
+ # dist is still mostly reusable (electron's postinstall skips the
+ # download when dist/ exists) — restore it and let npm ci top up.
+ restore-keys: |
+ eb2-${{ runner.os }}-${{ runner.arch }}-
+
+ - name: Cache node_modules
+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ with:
+ path: |
+ node_modules
+ apps/*/node_modules
+ ui-tui/node_modules
+ ui-tui/packages/*/node_modules
+ web/node_modules
+ tests-js/node_modules
+ key: node-modules-${{ matrix.target.label }}-node${{ steps.pins.outputs.node }}-npm${{ steps.pins.outputs.npm }}-${{ hashFiles('package-lock.json') }}
+ # npm ci rm -rf's node_modules before installing, so a restore is
+ # never shipped stale — but a restore-key hit still makes the
+ # reinstall incremental (postinstall outputs like node-pty's
+ # prebuilds/ and esbuild's platform binary survive in place).
+ # The build-bundled install-stamp gate (lock sha + node + npm +
+ # target) is the real guard against stale trees shipping.
+ restore-keys: |
+ node-modules-${{ matrix.target.label }}-node${{ steps.pins.outputs.node }}-npm${{ steps.pins.outputs.npm }}-
+
+ - name: Cache node-pty prebuilds (postinstall output, emulated-gyp tax on arm64)
+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ with:
+ path: |
+ node_modules/node-pty/prebuilds
+ node_modules/node-pty/build
+ key: node-pty-prebuilds-${{ matrix.target.label }}-${{ hashFiles('package-lock.json') }}
+ restore-keys: |
+ node-pty-prebuilds-${{ matrix.target.label }}-
+
+ - name: Azure login (OIDC)
+ if: startsWith(matrix.target.label, 'win32-') && vars.AZURE_CLIENT_ID != ''
+ uses: azure/login@f5d393ae46f8fde4be8b75f32e3fc50e654ad0ca # v3.0.1
+ with:
+ client-id: ${{ vars.AZURE_CLIENT_ID }}
+ tenant-id: ${{ vars.AZURE_TENANT_ID }}
+ allow-no-subscriptions: true
+
+ - name: Mint federated token for the signing dlib
+ if: startsWith(matrix.target.label, 'win32-') && vars.AZURE_CLIENT_ID != ''
+ shell: bash
+ run: |
+ file="$RUNNER_TEMP/azure-federated-token"
+ mint() {
+ curl -sSf -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
+ "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=api://AzureADTokenExchange" \
+ | jq -r .value > "$file.tmp" && mv -f "$file.tmp" "$file"
+ }
+ mint
+ ( while sleep 240; do mint || true; done ) &
+ echo "AZURE_FEDERATED_TOKEN_FILE=$file" >> "$GITHUB_ENV"
+
+ - name: Write App Store Connect key for notarytool
+ if: startsWith(matrix.target.label, 'darwin-')
+ shell: bash
+ env:
+ APPLE_API_KEY_P8: ${{ secrets.APPLE_API_KEY_P8 }}
+ run: |
+ if [ -n "$APPLE_API_KEY_P8" ]; then
+ printf '%s\n' "$APPLE_API_KEY_P8" > "$RUNNER_TEMP/apple-api-key.p8"
+ echo "APPLE_API_KEY=$RUNNER_TEMP/apple-api-key.p8" >> "$GITHUB_ENV"
+ else
+ echo "APPLE_API_KEY_P8 secret not set — notarization will be skipped"
+ fi
+
++ - name: Pin CMake < 4 for sdist builds
++ # python-olm (matrix extra) builds libolm from sdist on non-Linux
++ # targets, and its libolm/CMakeLists.txt requires CMake < 3.5
++ # compat (removed in CMake 4, which the darwin + win32 runners
++ # ship). Pin a CMake 3.x first on PATH for those legs so the sdist
++ # build configures. Linux uses the manylinux wheel — no build, no
++ # cmake needed. The pip cmake package ships a binary wheel for
++ # every non-Linux target (macos universal2, win_amd64, win_arm64).
++ if: startsWith(matrix.target.label, 'darwin-') || startsWith(matrix.target.label, 'win32-')
++ shell: bash
++ run: |
++ uv tool install cmake==3.31.6
++ echo "$(uv tool dir --bin)" >> "$GITHUB_PATH"
++
+ - name: Build and package
+ shell: bash
+ timeout-minutes: 85
+ env:
+ PYTHONUTF8: '1'
+ CC_aarch64_pc_windows_msvc: ${{ matrix.target.label == 'win32-arm64' && 'clang' || '' }}
+ DEBUG: 'electron-osx-sign*,electron-notarize*'
+ APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
+ APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
+ CSC_LINK: ${{ secrets.CSC_LINK }}
+ CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
+ AZURE_SIGN_ENDPOINT: ${{ vars.AZURE_SIGN_ENDPOINT }}
+ AZURE_SIGN_ACCOUNT: ${{ vars.AZURE_SIGN_ACCOUNT }}
+ AZURE_SIGN_PROFILE: ${{ vars.AZURE_SIGN_PROFILE }}
+ AZURE_SIGN_PUBLISHER: ${{ vars.AZURE_SIGN_PUBLISHER }}
+ AZURE_CLIENT_ID: ${{ vars.AZURE_CLIENT_ID }}
+ AZURE_TENANT_ID: ${{ vars.AZURE_TENANT_ID }}
+ AZURE_TOKEN_CREDENTIALS: prod
+ run: |
+ if [ "$RUNNER_OS" = "macOS" ]; then
+ ulimit -n 16384 2>/dev/null || true
+ echo "file descriptor limit: soft=$(ulimit -Sn) hard=$(ulimit -Hn)"
+ fi
+ node scripts/build-bundled-desktop.mjs --tag="$HERMES_PAYLOAD_TAG" --variant=bundled
+ # The Store-submission MSIX is the same bundled payload re-packed
+ # with the Partner Center packaging identity (msixbundle job uploads
+ # it to the tag archive; it never enters a feed dir).
+ if [ "$RUNNER_OS" = "Windows" ]; then
+ node scripts/build-bundled-desktop.mjs --tag="$HERMES_PAYLOAD_TAG" --variant=store
+ fi
+
+ # Smoke the bundled payload on its native linux runner before it is
+ # packed into the desktop artifact: the staged interpreter boots
+ # hermes_cli out of the payload with no network and no PYTHONPATH.
+ # This is the ONE linux build+smoke place — pm-bundle.yml no longer
+ # stages or uploads a duplicate linux payload.
+ - name: Smoke test the payload
+ if: startsWith(matrix.target.label, 'linux-')
+ shell: bash
+ run: bash scripts/smoke-payload.sh apps/desktop/build/agent-payload
+
+ - name: Audit bundle architecture
+ shell: bash
+ run: |
+ MATRIX_LABEL="${{ matrix.target.label }}"
+ node apps/desktop/scripts/audit-bundle-arch.mjs \
+ --arch="${MATRIX_LABEL##*-}" --root=apps/desktop/release
+
+ - name: Upload artifacts
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
+ with:
+ # The mac feed ymls for finalize + (win32 legs) the actual .msix +
+ # Store-.msix binaries for the msixbundle job to bundle and stage.
+ # The mac/linux/AppImage binaries go straight to R2 from each leg.
+ name: hermes-bundled-${{ matrix.target.label }}-${{ inputs.tag }}
+ path: |
+ apps/desktop/release/*-mac.yml
+ apps/desktop/release/*.msix
+ retention-days: 30
+ if-no-files-found: warn
+
+ - name: Stage to Cloudflare R2
+ if: inputs.upload_release == true
+ shell: bash
+ # Every artifact goes to releases/tag/<tag>/ (immutable staging).
+ # The finalize job (below) merges these into the win32/darwin feed
+ # dirs after the whole matrix is green — never from a leg, so a
+ # failed leg cannot publish a partial feed.
+ run: |
+ shopt -s nullglob
+ # Store-*.msix are archived by the dedicated loop below — exclude
+ # them here so they are not uploaded twice.
+ files=(apps/desktop/release/*.dmg apps/desktop/release/*.zip \
+ apps/desktop/release/*.msix \
+ apps/desktop/release/*.AppImage \
+ apps/desktop/release/*.blockmap apps/desktop/release/latest*.yml \
+ apps/desktop/release/nightly*.yml)
+ if [ ${#files[@]} -eq 0 ]; then
+ echo "::error::no release artifacts found"; exit 1
+ fi
+ for f in "${files[@]}"; do
+ case "$f" in
+ */Store-*) continue ;; # archived by the Store loop below
+ esac
+ node scripts/r2-release.mjs put \
+ --tag "$HERMES_PAYLOAD_TAG" --key "$(basename "$f")" --file "$f"
+ done
+ # The Store-submission MSIX (built by the win legs) goes to the tag
+ # archive too — hidden from the builds table and never a feed dir.
+ for f in apps/desktop/release/Store-*.msix; do
+ [ -f "$f" ] || continue
+ node scripts/r2-release.mjs put \
+ --tag "$HERMES_PAYLOAD_TAG" --key "$(basename "$f")" --file "$f"
+ done
+
+ finalize:
+ name: Publish feeds to R2
+ needs: [validate, build]
+ if: inputs.upload_release == true
+ runs-on: ubuntu-24.04
+ environment: release-signing
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ # Privileged job: pin to the SHA validate admitted, not the tag.
+ ref: ${{ needs.validate.outputs.sha }}
+ # Full checkout: r2-release.mjs imports ./msix-shared.mjs, so a
+ # sparse checkout of scripts/r2-release.mjs alone would die with
+ # ERR_MODULE_NOT_FOUND before the finalize run starts.
+ - name: Download staged artifacts
+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
+ with:
+ pattern: hermes-bundled-*-${{ inputs.tag }}
+ path: staged
+ merge-multiple: true
+ - name: Finalize feeds
+ env:
+ HERMES_PAYLOAD_TAG: ${{ inputs.tag }}
+ CLOUDFLARE_R2_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_R2_ACCOUNT_ID }}
+ CLOUDFLARE_R2_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_ACCESS_KEY_ID }}
+ CLOUDFLARE_R2_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_SECRET_ACCESS_KEY }}
+ CLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}
+ run: node scripts/r2-release.mjs finalize --tag "$HERMES_PAYLOAD_TAG" --dir staged
+
+ msixbundle:
+ name: Bundle the win32 MSIX feeds
+ needs: [validate, build]
+ if: inputs.upload_release == true
+ runs-on: windows-2025
+ environment: release-signing
+ timeout-minutes: 45
+ env:
+ HERMES_PAYLOAD_TAG: ${{ inputs.tag }}
+ ELECTRON_BUILDER_CACHE: ${{ github.workspace }}/.cache/electron-builder
+ CLOUDFLARE_R2_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_R2_ACCOUNT_ID }}
+ CLOUDFLARE_R2_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_ACCESS_KEY_ID }}
+ CLOUDFLARE_R2_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_SECRET_ACCESS_KEY }}
+ CLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}
+ CLOUDFLARE_R2_PUBLIC_URL: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}
+ AZURE_SIGN_ENDPOINT: ${{ vars.AZURE_SIGN_ENDPOINT }}
+ AZURE_SIGN_ACCOUNT: ${{ vars.AZURE_SIGN_ACCOUNT }}
+ AZURE_SIGN_PROFILE: ${{ vars.AZURE_SIGN_PROFILE }}
+ AZURE_SIGN_PUBLISHER: ${{ vars.AZURE_SIGN_PUBLISHER }}
+ steps:
+ # Full checkout: stage-msixbundle.mjs imports ./msix-shared.mjs and the
+ # job runs it with no checkout at all today — ERR_MODULE_NOT_FOUND.
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ # Privileged job: pin to the SHA validate admitted, not the tag.
+ ref: ${{ needs.validate.outputs.sha }}
+ # stage-msixbundle derives the nightly MSIX build number as
+ # minutes-since-the-last-stable from git tags — must see them.
+ fetch-tags: true
+
+ - name: Resolve toolchain pins from pm/lock.json
+ id: pins
+ shell: bash
+ run: |
+ python -c '
+ import json
+ pkgs = json.load(open("pm/lock.json"))["packages"]
+ for tool in ("node", "npm", "uv"):
+ print(tool + "=" + pkgs[tool]["version"])
+ ' >> "$GITHUB_OUTPUT"
+
+ - name: Resolve toolchain cache key
+ id: toolchain
+ shell: bash
+ run: |
+ node -e '
+ const l = require("./package-lock.json")
+ const el = l.packages["apps/desktop/node_modules/electron"].version
+ const eb = l.packages["node_modules/electron-builder"].version
+ if (!el || !eb) process.exit(1)
+ console.log(`electron=${el}`)
+ console.log(`builder=${eb}`)
+ ' >> "$GITHUB_OUTPUT"
+
+ # makeappx + signtool live in the winCodeSign toolset that
+ # electron-builder downloads into its cache during the build legs; the
+ # msixbundle job runs on a fresh runner, so restore the same eb2 cache
+ # the win32 legs saved. The path list MUST match the build legs'
+ # byte-for-byte — actions/cache derives the version hash from the paths
+ # input, so a shorter list computes a different version and the restore
+ # misses ("Cache not found") even with the identical key.
+ - name: Resolve electron's default download cache path
+ shell: bash
+ run: |
+ case "$RUNNER_OS" in
+ Windows) echo "ELECTRON_DEFAULT_CACHE=$LOCALAPPDATA/electron/Cache" >> "$GITHUB_ENV" ;;
+ macOS) echo "ELECTRON_DEFAULT_CACHE=$HOME/Library/Caches/electron" >> "$GITHUB_ENV" ;;
+ *) echo "ELECTRON_DEFAULT_CACHE=$HOME/.cache/electron" >> "$GITHUB_ENV" ;;
+ esac
+
+ - name: Cache electron + electron-builder toolchain
+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ with:
+ path: |
+ ${{ github.workspace }}/.cache/electron-builder
+ ${{ github.workspace }}/.cache/electron
+ ${{ env.ELECTRON_DEFAULT_CACHE }}
+ key: eb2-${{ runner.os }}-${{ runner.arch }}-electron-${{ steps.toolchain.outputs.electron }}-builder-${{ steps.toolchain.outputs.builder }}
+ restore-keys: |
+ eb2-${{ runner.os }}-${{ runner.arch }}-
+
+ - name: Download win legs' MSIX
+ uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
+ with:
+ pattern: hermes-bundled-win32-*-${{ inputs.tag }}
+ path: apps/desktop/release
+ merge-multiple: true
+
+ - name: Azure login (OIDC)
+ uses: azure/login@f5d393ae46f8fde4be8b75f32e3fc50e654ad0ca # v3.0.1
+ with:
+ client-id: ${{ vars.AZURE_CLIENT_ID }}
+ tenant-id: ${{ vars.AZURE_TENANT_ID }}
+ allow-no-subscriptions: true
+
+ - name: Mint federated token for the signing dlib
+ shell: bash
+ run: |
+ file="$RUNNER_TEMP/azure-federated-token"
+ mint() {
+ curl -sSf -H "Authorization: bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \
+ "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=api://AzureADTokenExchange" \
+ | jq -r .value > "$file.tmp" && mv -f "$file.tmp" "$file"
+ }
+ mint
+ ( while sleep 240; do mint || true; done ) &
+ echo "AZURE_FEDERATED_TOKEN_FILE=$file" >> "$GITHUB_ENV"
+
+ - name: Bundle + stage the MSIX feeds
+ shell: bash
+ env:
+ AZURE_TOKEN_CREDENTIALS: prod
+ AZURE_CLIENT_ID: ${{ vars.AZURE_CLIENT_ID }}
+ AZURE_TENANT_ID: ${{ vars.AZURE_TENANT_ID }}
+ run: |
+ # Out-of-store feed (bundled variant): universal .msixbundle +
+ # .appinstaller per channel; plus re-upload the Store-submission
+ # .msix to the tag archive (never a feed dir).
+ node scripts/stage-msixbundle.mjs --tag "$HERMES_PAYLOAD_TAG" --variant bundled
+
+ builds-pending:
+ name: Mark the builds table as in progress
+ if: inputs.upload_release == true
+ runs-on: ubuntu-24.04
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ - name: Render the placeholder
+ env:
+ GH_TOKEN: ${{ github.token }}
+ HERMES_PAYLOAD_TAG: ${{ inputs.tag }}
+ RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
+ run: |
+ if ! gh release view "$HERMES_PAYLOAD_TAG" >/dev/null 2>&1; then
+ echo "::error::no release exists for $HERMES_PAYLOAD_TAG — cannot mark the builds table"
+ exit 1
+ fi
+ python3 scripts/render-builds-table.py \
+ --tag "$HERMES_PAYLOAD_TAG" --repo "$GITHUB_REPOSITORY" \
+ --pending-run-url "$RUN_URL"
+
+ builds-table:
+ name: Render the release builds table
+ needs: [validate, build, msixbundle, finalize]
+ if: inputs.upload_release == true
+ runs-on: ubuntu-24.04
+ environment: release-signing
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ # Privileged job: pin to the SHA validate admitted. A bare checkout
+ # here would land on the dispatch branch, not the release bytes.
+ ref: ${{ needs.validate.outputs.sha }}
+ - name: Render
+ env:
+ GH_TOKEN: ${{ github.token }}
+ HERMES_PAYLOAD_TAG: ${{ inputs.tag }}
+ CLOUDFLARE_R2_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_R2_ACCOUNT_ID }}
+ CLOUDFLARE_R2_ACCESS_KEY_ID: ${{ secrets.CLOUDFLARE_R2_ACCESS_KEY_ID }}
+ CLOUDFLARE_R2_SECRET_ACCESS_KEY: ${{ secrets.CLOUDFLARE_R2_SECRET_ACCESS_KEY }}
+ CLOUDFLARE_R2_BUCKET: ${{ vars.CLOUDFLARE_R2_BUCKET }}
+ CLOUDFLARE_R2_PUBLIC_URL: ${{ vars.CLOUDFLARE_R2_PUBLIC_URL }}
+ run: |
+ if ! gh release view "$HERMES_PAYLOAD_TAG" >/dev/null 2>&1; then
+ echo "::error::no release exists for $HERMES_PAYLOAD_TAG — cannot render the builds table"
+ exit 1
+ fi
+ python3 scripts/render-builds-table.py \
+ --tag "$HERMES_PAYLOAD_TAG" --repo "$GITHUB_REPOSITORY"
+
+ publish-nightly:
+ name: Publish the nightly release
+ needs: [build, builds-table, msixbundle, finalize]
+ if: |
+ always()
+ && inputs.upload_release == true
+ && contains(inputs.tag, '-nightly.')
+ && needs.build.result == 'success'
+ && needs.builds-table.result == 'success'
+ && needs.msixbundle.result == 'success'
+ && needs.finalize.result == 'success'
+ runs-on: ubuntu-24.04
+ steps:
+ - name: Publish
+ env:
+ GH_TOKEN: ${{ github.token }}
+ TAG: ${{ inputs.tag }}
+ run: |
+ gh release edit "$TAG" --repo "$GITHUB_REPOSITORY" --draft=false
+ echo "Published $TAG"
diff --cc .github/workflows/pm-bundle.yml
index 841aba748a9,00000000000..c0a69c1aa26
mode 100644,000000..100644
--- a/.github/workflows/pm-bundle.yml
+++ b/.github/workflows/pm-bundle.yml
@@@ -1,124 -1,0 +1,138 @@@
+name: PM Bundle
+
+# Stages the self-contained agent payload for each (os, arch) target with
+# `hermes pm bundle`: repo snapshot + tool store + facts + a relocatable
+# venv built on the staged python-build-standalone interpreter. Each
+# payload is smoke-tested on its native runner — the staged interpreter
+# boots hermes_cli out of the payload with no network and no PYTHONPATH —
+# as a pre-merge check for the pm tooling itself.
+#
+# Staging is native per target (no cross-target wheel tables anywhere):
+# the runner IS the target. pm's arch guard fails the job if any staged
+# mismatches, before anything ships.
+
+on:
+ workflow_dispatch:
+ inputs:
+ ref:
+ description: 'Git ref to bundle (default: the triggering ref)'
+ required: false
+ type: string
+ pull_request:
+ paths:
+ - 'pm/**'
+ - 'uv.lock'
+ - 'pyproject.toml'
+ - '.github/workflows/pm-bundle.yml'
+
+permissions:
+ contents: read
+
+concurrency:
+ group: pm-bundle-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ bundle:
+ name: bundle ${{ matrix.target.label }}
+ runs-on: ${{ matrix.target.runner }}
+ timeout-minutes: 45
+ strategy:
+ fail-fast: false
+ matrix:
+ target:
+ - label: linux-x64
+ runner: ubuntu-24.04
+ - label: linux-arm64
+ runner: ubuntu-24.04-arm
+ - label: darwin-arm64
+ runner: macos-15
+ - label: darwin-x64
+ runner: macos-15-intel
+ - label: win32-x64
+ runner: windows-2025
+ - label: win32-arm64
+ runner: windows-11-arm
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ ref: ${{ inputs.ref || github.ref }}
+ fetch-tags: true
+
+ # The host uv only bootstraps a python to run pm itself; every
+ # payload tool (uv included) is staged by pm from pm/lock.json.
+ - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # 9.0.0
+ with:
+ enable-cache: false
+
+ # One cache for the pm store: keyed on the lockfile, so a pin bump
+ # rotates it. pm verifies every restored entry against the lock
+ # (hash-named fetches, verify() on entries) — the cache is an
+ # optimization, never a proof.
+ - name: Cache pm store
+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ with:
+ path: build/agent-payload/tools
+ key: pm-store-${{ matrix.target.label }}-${{ hashFiles('pm/lock.json', 'uv.lock') }}
+
+ # win32-arm64 builds cryptography from sdist (no win_arm64 wheel);
+ # its Rust core links OpenSSL statically from vcpkg.
+ - name: Cache vcpkg OpenSSL (arm64)
+ if: matrix.target.label == 'win32-arm64'
+ uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ with:
+ path: C:\vcpkg\installed\arm64-windows-static-md
+ key: vcpkg-openssl-arm64-windows-static-md-${{ runner.os }}
+
+ - name: Install OpenSSL (arm64)
+ if: matrix.target.label == 'win32-arm64'
+ shell: bash
+ run: |
+ if [ ! -f "/c/vcpkg/installed/arm64-windows-static-md/lib/libcrypto.lib" ]; then
+ "$VCPKG_INSTALLATION_ROOT/vcpkg" install openssl:arm64-windows-static-md
+ fi
+ {
+ printf 'OPENSSL_DIR=C:\\vcpkg\\installed\\arm64-windows-static-md\n'
+ printf 'OPENSSL_STATIC=1\n'
+ } >> "$GITHUB_ENV"
+
++ - name: Pin CMake < 4 for sdist builds
++ # python-olm (matrix extra) builds libolm from sdist on non-Linux
++ # targets, and its libolm/CMakeLists.txt requires CMake < 3.5
++ # compat (removed in CMake 4, which the darwin + win32 runners
++ # ship). Pin a CMake 3.x first on PATH for those legs so the sdist
++ # build configures. Linux uses the manylinux wheel — no build, no
++ # cmake needed. The pip cmake package ships a binary wheel for
++ # every non-Linux target (macos universal2, win_amd64, win_arm64).
++ if: startsWith(matrix.target.label, 'darwin-') || startsWith(matrix.target.label, 'win32-')
++ shell: bash
++ run: |
++ uv tool install cmake==3.31.6
++ echo "$(uv tool dir --bin)" >> "$GITHUB_PATH"
++
+ - name: Stage the payload
+ shell: bash
+ env:
+ # Windows runners default to cp1252; pm prints UTF-8 (✓/✗).
+ PYTHONUTF8: '1'
+ # ring/obstore's C sources need clang, not MSVC, on windows-arm64.
+ # Scoped to the cargo target triple so every other sdist keeps MSVC.
+ CC_aarch64_pc_windows_msvc: ${{ matrix.target.label == 'win32-arm64' && 'clang' || '' }}
+ run: |
+ # The bootstrap interpreter tracks the payload interpreter's
+ # minor version — one authority (pm/lock.json), no drift.
+ PYVER=$(python3 -c "import json; v=json.load(open('pm/lock.json'))['packages']['python']['version']; print('.'.join(v.split('+')[0].split('.')[:2]))" 2>/dev/null || python -c "import json; v=json.load(open('pm/lock.json'))['packages']['python']['version']; print('.'.join(v.split('+')[0].split('.')[:2]))")
+ # Archive what actions/checkout actually checked out. On
+ # pull_request events github.sha names a merge commit that a
+ # force-push invalidates mid-run ("not a tree object").
+ uv run --no-project --python "$PYVER" python -m pm.cli bundle \
+ --out build/agent-payload \
+ --ref HEAD
+
+ # The payload must boot with nothing from this checkout: the staged
+ # venv's interpreter, cwd at the staged REPO (the desktop spawn
+ # convention — sys.path[0] from cwd survives relocation where the
+ # editable install's absolute path would not), no PYTHONPATH.
+ - name: Smoke test the payload
+ shell: bash
+ run: bash scripts/smoke-payload.sh build/agent-payload
diff --cc agent/anthropic_credentials.py
index 00000000000,a40cdcb298e..e778e2a306b
mode 000000,100644..100644
--- a/agent/anthropic_credentials.py
+++ b/agent/anthropic_credentials.py
@@@ -1,0 -1,1124 +1,1124 @@@
+ """Anthropic credential sources, OAuth flows, and token resolution.
+
+ Extracted from ``agent/anthropic_adapter.py``: the adapter is a message/HTTP
+ translation layer, while everything below owns *where an Anthropic credential
+ comes from* and *how a rotated one is committed*. Keeping the two apart means
+ the refresh transaction has a single home instead of being interleaved with
+ request building.
+
+ Sources, in the order ``resolve_anthropic_token()`` consults them:
+
+ 1. ``ANTHROPIC_TOKEN`` / ``CLAUDE_CODE_OAUTH_TOKEN`` (explicit OAuth env)
+ 2. ``ANTHROPIC_API_KEY`` (explicit API key)
+ 3. ``~/.hermes/.anthropic_oauth.json`` (Hermes PKCE login)
+ 4. ``~/.claude/.credentials.json`` / macOS Keychain (Claude Code)
+ 5. the credential pool in ``auth.json``
+
+ Sources 3 and 4 are *singletons*: ``credential_pool._seed_from_singletons()``
+ re-reads them on every ``load_pool()`` and writes what it finds over the pool
+ row, which is why a failed write here is a failed refresh (see
+ ``CredentialPersistError``) rather than a best-effort cache miss.
+
+ ``agent.anthropic_adapter`` re-exports every public name below, so existing
+ ``from agent.anthropic_adapter import resolve_anthropic_token`` imports keep
+ working.
+ """
+
+ import json
+ import logging
+ import os
+ import platform
+ import secrets
+ import stat
+ import subprocess
+ import threading
+ from collections import OrderedDict
+ from pathlib import Path
+ from typing import Any, Dict, Optional
+
+ from hermes_constants import get_hermes_home
+ from agent.secret_scope import get_secret as _get_secret
+
+ logger = logging.getLogger(__name__)
+
+
+ def _getenv(name: str, default: str = "") -> str:
+ """Profile-scoped replacement for os.getenv on credential reads.
+
+ Routes through the secret scope (Workstream A): identical to os.getenv
+ when multiplexing is off, scope-aware (and fail-closed on an unscoped
+ read) when on. Mirrors the same wrapper in hermes_cli/runtime_provider.py.
+ """
+ val = _get_secret(name, default)
+ return val if val is not None else default
+
+
+ def _is_oauth_token(key: str) -> bool:
+ """Check if the key is an Anthropic OAuth/setup token.
+
+ Positively identifies Anthropic OAuth tokens by their key format:
+ - ``sk-ant-`` prefix (but NOT ``sk-ant-api``) → setup tokens, managed keys
+ - ``eyJ`` prefix → JWTs from the Anthropic OAuth flow
+ - ``cc-`` prefix → Claude Code OAuth access tokens (from CLAUDE_CODE_OAUTH_TOKEN)
+
+ Non-Anthropic keys (MiniMax, Alibaba, etc.) don't match any pattern
+ and correctly return False.
+ """
+ if not key:
+ return False
+ # Regular Anthropic Console API keys — x-api-key auth, never OAuth
+ if key.startswith("sk-ant-api"):
+ return False
+ # Anthropic-issued tokens (setup-tokens sk-ant-oat-*, managed keys)
+ if key.startswith("sk-ant-"):
+ return True
+ # JWTs from Anthropic OAuth flow
+ if key.startswith("eyJ"):
+ return True
+ # Claude Code OAuth access tokens (opaque, from CLAUDE_CODE_OAUTH_TOKEN)
+ if key.startswith("cc-"):
+ return True
+ return False
+
+
+
+ class CredentialPersistError(RuntimeError):
+ """A rotated single-use credential could not be durably committed.
+
+ Anthropic OAuth refresh tokens are single-use: a successful refresh POST
+ consumes the old refresh token server-side and returns a replacement. The
+ replacement exists only in memory until it reaches its authoritative
+ on-disk store (``~/.claude/.credentials.json`` for ``claude_code``,
+ ``~/.hermes/.anthropic_oauth.json`` for ``hermes_pkce``).
+
+ If that write fails and the caller reports success anyway, the on-disk
+ (already consumed) pair survives and is re-seeded on the next
+ ``load_pool()``, so the following refresh replays a spent token and fails
+ with ``invalid_grant`` / ``refresh_token_reused``. Callers must therefore
+ treat this as a failed refresh, not a successful one, and fail closed.
+ """
+
+ def __init__(self, path: Any, cause: BaseException) -> None:
+ super().__init__(
+ f"failed to durably persist rotated Anthropic credentials to {path}: {cause}"
+ )
+ self.path = path
+
+
+ # Fingerprints of Anthropic secrets whose refresh POST succeeded (so the
+ # server-side pair was rotated and the old refresh token is spent) but whose
+ # replacement never reached its authoritative store. The pre-rotation pair
+ # survives on disk and is re-seeded on the next ``load_pool()``, so without an
+ # explicit verdict the resolver happily hands that already-consumed credential
+ # back from a later source and the caller reads a silent success.
+ #
+ # Kept as non-reversible digests and bounded: a spent secret is spent forever,
+ # so entries never need clearing (a re-auth mints new tokens with new
+ # fingerprints).
+ #
+ # The registry has TWO scopes, because the credential it protects does:
+ # * process-local (this OrderedDict) — fast path, always recorded;
+ # * durable sidecar file next to the shared credential source — the
+ # authority boundary of ``claude_code``/``hermes_pkce`` is the shared
+ # singleton file, which other Hermes processes/profiles read with fresh
+ # interpreters. A process-local verdict only stops the process that
+ # lost the commit from lying to itself; the sidecar stops every OTHER
+ # process from leasing the stale pair or re-POSTing the spent refresh
+ # token. The sidecar stores only one-way fingerprints (never secrets)
+ # and is written under the same path-keyed cross-process lock that
+ # serializes refreshes of that source.
+ _SPENT_ROTATION_LOCK = threading.Lock()
+ _SPENT_ROTATION_FINGERPRINTS: "OrderedDict[str, None]" = OrderedDict()
+ _SPENT_ROTATION_MAX_TRACKED = 64
+ _SPENT_ROTATION_SIDECAR_VERSION = 1
+
+
+ def _spent_rotation_sidecar_path(source_path: Path) -> Path:
+ """Sidecar registry path for a shared credential source file."""
+ return source_path.with_name(source_path.name + ".hermes-spent-rotations.json")
+
+
+ def spent_rotation_source_path(source: Any) -> Optional[Path]:
+ """Map a pool-entry source to the shared singleton file it borrows from.
+
+ Only singleton-backed sources have a cross-process authority boundary;
+ profile-owned rows are already protected by the process-local registry
+ plus the pool quarantine.
+ """
+ if source == "claude_code":
+ return claude_code_credentials_path()
+ if source == "hermes_pkce":
+ return _get_hermes_oauth_file()
+ return None
+
+
+ def _read_spent_rotation_sidecar(source_path: Optional[Path]) -> set:
+ if source_path is None:
+ return set()
+ try:
+ raw = json.loads(
- _spent_rotation_sidecar_path(source_path).read_text(encoding="utf-8")
++ _spent_rotation_sidecar_path(source_path).read_text(encoding="utf-8-sig")
+ )
+ except (OSError, ValueError):
+ return set()
+ fingerprints = raw.get("fingerprints") if isinstance(raw, dict) else None
+ if not isinstance(fingerprints, list):
+ return set()
+ return {fp for fp in fingerprints if isinstance(fp, str) and fp}
+
+
+ def _append_spent_rotation_sidecar(source_path: Path, fingerprints: list) -> None:
+ """Merge fingerprints into the sidecar registry (atomic replace).
+
+ Callers on the refresh path already hold the path-keyed cross-process
+ lock for ``source_path``, so concurrent merge-writes are serialized.
+ Fail-soft: a sidecar write failure must never mask the fail-closed
+ verdict already recorded in the process-local registry.
+ """
+ sidecar = _spent_rotation_sidecar_path(source_path)
+ try:
+ merged = _read_spent_rotation_sidecar(source_path)
+ merged.update(fingerprints)
+ bounded = sorted(merged)[-_SPENT_ROTATION_MAX_TRACKED * 4 :]
+ payload = json.dumps(
+ {
+ "version": _SPENT_ROTATION_SIDECAR_VERSION,
+ "comment": (
+ "Non-secret one-way fingerprints of Anthropic OAuth "
+ "credentials whose rotation was consumed server-side but "
+ "never durably committed. Written by Hermes so sibling "
+ "processes sharing this credential source fail closed "
+ "instead of replaying a spent single-use refresh token."
+ ),
+ "fingerprints": bounded,
+ },
+ indent=2,
+ )
+ sidecar.parent.mkdir(parents=True, exist_ok=True)
+ tmp = sidecar.with_name(sidecar.name + ".tmp")
+ tmp.write_text(payload, encoding="utf-8")
+ os.replace(tmp, sidecar)
+ except Exception:
+ logger.debug(
+ "Failed to persist spent-rotation fingerprints to %s", sidecar,
+ exc_info=True,
+ )
+
+
+ def mark_rotation_consumed_uncommitted(
+ *secrets: Any, source_path: Optional[Path] = None
+ ) -> None:
+ """Record secrets consumed by a refresh whose replacement never committed.
+
+ Called from every commit-failure path (the direct resolver here and
+ ``CredentialPool._fail_closed_unpersisted_rotation``). Recording the
+ *pre-rotation* pair is what lets later resolution steps recognise the stale
+ copy they read back off disk as unusable rather than as a working token.
+
+ When ``source_path`` names the shared singleton file the credential was
+ borrowed from, the verdict is additionally persisted to that source's
+ sidecar registry so other processes/profiles sharing the file adopt it too.
+ """
+ from agent.credential_persistence import fingerprint_secret_value
+
+ recorded: list = []
+ with _SPENT_ROTATION_LOCK:
+ for secret in secrets:
+ value = str(secret or "").strip()
+ if not value:
+ continue
+ fingerprint = fingerprint_secret_value(value)
+ if not fingerprint:
+ continue
+ recorded.append(fingerprint)
+ _SPENT_ROTATION_FINGERPRINTS.pop(fingerprint, None)
+ _SPENT_ROTATION_FINGERPRINTS[fingerprint] = None
+ while len(_SPENT_ROTATION_FINGERPRINTS) > _SPENT_ROTATION_MAX_TRACKED:
+ _SPENT_ROTATION_FINGERPRINTS.popitem(last=False)
+ if recorded and source_path is not None:
+ _append_spent_rotation_sidecar(source_path, recorded)
+
+
+ def is_rotation_consumed_uncommitted(
+ secret: Any, *, source_path: Optional[Path] = None
+ ) -> bool:
+ """True when *secret* belongs to a rotation that was spent but not committed.
+
+ Checks the process-local registry first, then (when ``source_path`` is
+ given) the durable sidecar registry of the shared credential source, so a
+ fresh interpreter in another process still sees the terminal verdict.
+ """
+ from agent.credential_persistence import fingerprint_secret_value
+
+ value = str(secret or "").strip()
+ if not value:
+ return False
+ fingerprint = fingerprint_secret_value(value)
+ if not fingerprint:
+ return False
+ with _SPENT_ROTATION_LOCK:
+ if fingerprint in _SPENT_ROTATION_FINGERPRINTS:
+ return True
+ return fingerprint in _read_spent_rotation_sidecar(source_path)
+
+
+ def _read_claude_code_credentials_from_keychain() -> Optional[Dict[str, Any]]:
+ """Read Claude Code OAuth credentials from the macOS Keychain.
+
+ Claude Code >=2.1.114 stores credentials in the macOS Keychain under the
+ service name "Claude Code-credentials" rather than (or in addition to)
+ the JSON file at ~/.claude/.credentials.json.
+
+ The password field contains a JSON string with the same claudeAiOauth
+ structure as the JSON file.
+
+ Returns dict with {accessToken, refreshToken?, expiresAt?} or None.
+ """
+ if platform.system() != "Darwin":
+ return None
+
+ try:
+ # Read the "Claude Code-credentials" generic password entry
+ result = subprocess.run(
+ ["security", "find-generic-password",
+ "-s", "Claude Code-credentials",
+ "-w"],
+ capture_output=True,
+ text=True, encoding='utf-8', errors='replace',
+ timeout=5,
+ stdin=subprocess.DEVNULL,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ logger.debug("Keychain: security command not available or timed out")
+ return None
+
+ if result.returncode != 0:
+ logger.debug("Keychain: no entry found for 'Claude Code-credentials'")
+ return None
+
+ raw = result.stdout.strip()
+ if not raw:
+ return None
+
+ try:
+ data = json.loads(raw)
+ except json.JSONDecodeError:
+ logger.debug("Keychain: credentials payload is not valid JSON")
+ return None
+
+ oauth_data = data.get("claudeAiOauth")
+ if oauth_data and isinstance(oauth_data, dict):
+ access_token = oauth_data.get("accessToken", "")
+ if access_token:
+ return {
+ "accessToken": access_token,
+ "refreshToken": oauth_data.get("refreshToken", ""),
+ "expiresAt": oauth_data.get("expiresAt", 0),
+ "source": "macos_keychain",
+ }
+
+ return None
+
+
+ def claude_code_credentials_path() -> Path:
+ """Location Claude Code CLI writes its shared OAuth credentials file.
+
+ This file is not profile-owned: every Hermes profile's credential pool
+ reads and writes the *same* path, so cross-profile refresh races on a
+ ``claude_code`` pool entry must be serialized against this exact path
+ (see ``CredentialPool._claude_code_credentials_lock`` in
+ ``agent/credential_pool.py``).
+ """
+ return Path.home() / ".claude" / ".credentials.json"
+
+
+ def _read_claude_code_credentials_from_file() -> Optional[Dict[str, Any]]:
+ """Read Claude Code OAuth credentials from ~/.claude/.credentials.json.
+
+ Returns dict with {accessToken, refreshToken?, expiresAt?, source} or None.
+ """
+ cred_path = claude_code_credentials_path()
+ if not cred_path.exists():
+ return None
+ try:
- data = json.loads(cred_path.read_text(encoding="utf-8"))
++ data = json.loads(cred_path.read_text(encoding="utf-8-sig"))
+ except (json.JSONDecodeError, OSError, IOError) as e:
+ logger.debug("Failed to read ~/.claude/.credentials.json: %s", e)
+ return None
+
+ oauth_data = data.get("claudeAiOauth")
+ if not (oauth_data and isinstance(oauth_data, dict)):
+ return None
+ access_token = oauth_data.get("accessToken", "")
+ if not access_token:
+ return None
+ return {
+ "accessToken": access_token,
+ "refreshToken": oauth_data.get("refreshToken", ""),
+ "expiresAt": oauth_data.get("expiresAt", 0),
+ "source": "claude_code_credentials_file",
+ }
+
+
+ def read_claude_code_credentials() -> Optional[Dict[str, Any]]:
+ """Read refreshable Claude Code OAuth credentials.
+
+ Reads from two possible sources and reconciles them:
+ 1. macOS Keychain (Darwin only) — "Claude Code-credentials" entry
+ 2. ~/.claude/.credentials.json file
+
+ Selection rules when both are present:
+ - If exactly one is non-expired, prefer that one. (Handles the case
+ where Claude Code refreshes one source but not the other — observed
+ in the wild on Claude Code 2.1.x.)
+ - Otherwise, prefer the source with the later ``expiresAt`` so that
+ any subsequent refresh uses the most recent ``refreshToken``.
+
+ This intentionally excludes ~/.claude.json primaryApiKey. Opencode's
+ subscription flow is OAuth/setup-token based with refreshable credentials,
+ and native direct Anthropic provider usage should follow that path rather
+ than auto-detecting Claude's first-party managed key.
+
+ Returns dict with {accessToken, refreshToken?, expiresAt?, source} or None.
+ """
+ kc_creds = _read_claude_code_credentials_from_keychain()
+ file_creds = _read_claude_code_credentials_from_file()
+
+ if kc_creds and file_creds:
+ kc_valid = is_claude_code_token_valid(kc_creds)
+ file_valid = is_claude_code_token_valid(file_creds)
+ if kc_valid and not file_valid:
+ return kc_creds
+ if file_valid and not kc_valid:
+ return file_creds
+ # Both valid or both expired: prefer the later expiresAt so the
+ # downstream refresh path uses the freshest refresh_token.
+ kc_exp = kc_creds.get("expiresAt", 0) or 0
+ file_exp = file_creds.get("expiresAt", 0) or 0
+ return kc_creds if kc_exp >= file_exp else file_creds
+
+ return kc_creds or file_creds
+
+
+ def is_claude_code_token_valid(creds: Dict[str, Any]) -> bool:
+ """Check if Claude Code credentials have a non-expired access token."""
+ import time
+
+ expires_at = creds.get("expiresAt", 0)
+ if not expires_at:
+ # No expiry set (managed keys) — valid if token is present
+ return bool(creds.get("accessToken"))
+
+ # expiresAt is in milliseconds since epoch
+ now_ms = int(time.time() * 1000)
+ # Allow 60 seconds of buffer
+ return now_ms < (expires_at - 60_000)
+
+
+ def refresh_anthropic_oauth_pure(refresh_token: str, *, use_json: bool = False) -> Dict[str, Any]:
+ """Refresh an Anthropic OAuth token without mutating local credential files."""
+ import time
+ import urllib.parse
+ import urllib.request
+
+ if not refresh_token:
+ raise ValueError("refresh_token is required")
+
+ client_id = "9d1c250a-e61b-44d9-88ed-5944d1962f5e"
+ if use_json:
+ data = json.dumps({
+ "grant_type": "refresh_token",
+ "refresh_token": refresh_token,
+ "client_id": client_id,
+ }).encode()
+ content_type = "application/json"
+ else:
+ data = urllib.parse.urlencode({
+ "grant_type": "refresh_token",
+ "refresh_token": refresh_token,
+ "client_id": client_id,
+ }).encode()
+ content_type = "application/x-www-form-urlencoded"
+
+ token_endpoints = [
+ "https://platform.claude.com/v1/oauth/token",
+ "https://console.anthropic.com/v1/oauth/token",
+ ]
+ last_error = None
+ for endpoint in token_endpoints:
+ req = urllib.request.Request(
+ endpoint,
+ data=data,
+ headers={
+ "Content-Type": content_type,
+ "User-Agent": _OAUTH_TOKEN_USER_AGENT,
+ },
+ method="POST",
+ )
+ try:
+ with urllib.request.urlopen(req, timeout=10) as resp:
+ result = json.loads(resp.read().decode())
+ except Exception as exc:
+ last_error = exc
+ logger.debug("Anthropic token refresh failed at %s: %s", endpoint, exc)
+ continue
+
+ access_token = result.get("access_token", "")
+ if not access_token:
+ raise ValueError("Anthropic refresh response was missing access_token")
+ next_refresh = result.get("refresh_token", refresh_token)
+ expires_in = result.get("expires_in", 3600)
+ return {
+ "access_token": access_token,
+ "refresh_token": next_refresh,
+ "expires_at_ms": int(time.time() * 1000) + (expires_in * 1000),
+ }
+
+ if last_error is not None:
+ raise last_error
+ raise ValueError("Anthropic token refresh failed")
+
+
+ def _refresh_oauth_token(creds: Dict[str, Any]) -> Optional[str]:
+ """Attempt to refresh an expired Claude Code OAuth token.
+
+ Claude Code's OAuth refresh tokens are single-use: a successful refresh
+ rotates the pair and invalidates the old refresh token. Claude Code itself
+ also refreshes on its own schedule (IDE/CLI activity), so by the time
+ Hermes notices an expired token, Claude Code may have already rotated it.
+ POSTing our now-stale refresh token in that window races Claude Code and
+ fails with ``invalid_grant``.
+
+ So before refreshing, re-read the live credential sources. If Claude Code
+ has already produced a valid token, adopt it and skip the POST entirely.
+ Only fall back to refreshing ourselves when no fresh credential is found.
+ """
+ # Claude Code may have already refreshed — adopt its token rather than
+ # racing it with our (possibly already-rotated) refresh token. The read,
+ # decision, POST, and write-back all belong to the shared credentials
+ # source, so hold the same path-keyed cross-process lock used by the pool.
+ # Without this direct resolver path, two profiles can still spend one
+ # single-use refresh token even though CredentialPool is serialized.
+ try:
+ from hermes_cli.auth import AUTH_LOCK_TIMEOUT_SECONDS, _auth_store_lock, env_float
+
+ refresh_timeout_seconds = env_float(
+ "HERMES_ANTHROPIC_REFRESH_TIMEOUT_SECONDS", 20
+ )
+ lock_timeout_seconds = max(
+ float(AUTH_LOCK_TIMEOUT_SECONDS),
+ float(refresh_timeout_seconds) + 5.0,
+ )
+ with _auth_store_lock(
+ timeout_seconds=lock_timeout_seconds,
+ target_path=claude_code_credentials_path(),
+ ):
+ # Only adopt when the live re-read produced a DIFFERENT token with
+ # a real future expiry: re-adopting the same credential we were
+ # just handed would be a no-op, and a 0/absent ``expiresAt`` means
+ # "managed key / unknown expiry" (see is_claude_code_token_valid).
+ current = read_claude_code_credentials()
+ if current:
+ current_token = current.get("accessToken", "")
+ current_exp = current.get("expiresAt", 0) or 0
+ if (
+ current_token
+ and current_token != creds.get("accessToken", "")
+ and current_exp > 0
+ and is_claude_code_token_valid(current)
+ ):
+ logger.debug("Adopted Claude Code's already-refreshed OAuth token")
+ return current_token
+
+ refresh_token = (
+ (current or {}).get("refreshToken", "")
+ or creds.get("refreshToken", "")
+ )
+ if not refresh_token:
+ logger.debug("No refresh token available — cannot refresh")
+ return None
+
+ # Another process may have spent this refresh token and lost the
+ # commit; its durable sidecar verdict is authoritative for the
+ # shared source. POSTing it again would just burn the family into
+ # ``invalid_grant``.
+ if is_rotation_consumed_uncommitted(
+ refresh_token, source_path=claude_code_credentials_path()
+ ):
+ logger.debug(
+ "Refresh token was already consumed by an uncommitted rotation "
+ "- refusing to replay it; re-run 'claude setup-token'"
+ )
+ return None
+
+ try:
+ refreshed = refresh_anthropic_oauth_pure(refresh_token, use_json=False)
+ except Exception as e:
+ logger.debug("Failed to refresh Claude Code token: %s", e)
+ return None
+
+ # The POST above already consumed ``refresh_token`` server-side.
+ # Writing the replacement pair is the commit step of that
+ # transaction, not a cache update: if it fails, the rotation is
+ # unrecoverable and the pair still on disk is spent. Fail closed
+ # rather than handing back an access token whose refresh half was
+ # lost — reporting success here is what lets a later load replay
+ # the consumed token and produce ``invalid_grant``.
+ try:
+ _write_claude_code_credentials(
+ refreshed["access_token"],
+ refreshed["refresh_token"],
+ refreshed["expires_at_ms"],
+ )
+ except Exception as e:
+ logger.error(
+ "Anthropic OAuth refresh rotated the single-use token but could not "
+ "commit it to %s (%s) — treating the refresh as failed; "
+ "re-run 'claude setup-token' to reauthenticate",
+ claude_code_credentials_path(),
+ e,
+ )
+ # The POST already spent ``refresh_token`` server-side and the
+ # replacement is gone. The pre-rotation pair is still on disk,
+ # so mark it: without this, source 5 re-reads it through the
+ # pool and returns the consumed credential as a success.
+ mark_rotation_consumed_uncommitted(
+ refresh_token,
+ creds.get("accessToken", ""),
+ (current or {}).get("accessToken", ""),
+ (current or {}).get("refreshToken", ""),
+ source_path=claude_code_credentials_path(),
+ )
+ return None
+
+ logger.debug("Successfully refreshed Claude Code OAuth token")
+ return refreshed["access_token"]
+ except Exception as e:
+ # Lock acquisition/read failures should preserve the resolver's
+ # existing fail-soft contract rather than taking down agent startup.
+ logger.debug("Failed to acquire Claude Code refresh lock: %s", e)
+ return None
+
+
+ def _write_claude_code_credentials(
+ access_token: str,
+ refresh_token: str,
+ expires_at_ms: int,
+ *,
+ scopes: Optional[list] = None,
+ ) -> None:
+ """Write refreshed credentials back to ~/.claude/.credentials.json.
+
+ The optional *scopes* list (e.g. ``["user:inference", "user:profile", ...]``)
+ is persisted so that Claude Code's own auth check recognises the credential
+ as valid. Claude Code >=2.1.81 gates on the presence of ``"user:inference"``
+ in the stored scopes before it will use the token.
+
+ Raises ``CredentialPersistError`` when the rotated pair does not reach the
+ file. This write is the commit step of the refresh transaction, not a
+ best-effort cache update: a swallowed failure leaves the consumed
+ pre-rotation pair on disk to be re-seeded and replayed (see
+ ``CredentialPersistError``).
+ """
+ cred_path = claude_code_credentials_path()
+ try:
+ # Read existing file to preserve other fields
+ existing = {}
+ if cred_path.exists():
- existing = json.loads(cred_path.read_text(encoding="utf-8"))
++ existing = json.loads(cred_path.read_text(encoding="utf-8-sig"))
+
+ oauth_data: Dict[str, Any] = {
+ "accessToken": access_token,
+ "refreshToken": refresh_token,
+ "expiresAt": expires_at_ms,
+ }
+ if scopes is not None:
+ oauth_data["scopes"] = scopes
+ elif "claudeAiOauth" in existing and "scopes" in existing["claudeAiOauth"]:
+ # Preserve previously-stored scopes when the refresh response
+ # does not include a scope field.
+ oauth_data["scopes"] = existing["claudeAiOauth"]["scopes"]
+
+ existing["claudeAiOauth"] = oauth_data
+
+ cred_path.parent.mkdir(parents=True, exist_ok=True)
+ # Per-process random suffix avoids collisions between concurrent
+ # writers and stale leftovers from a prior crashed write.
+ _tmp_cred = cred_path.with_suffix(f".tmp.{os.getpid()}.{secrets.token_hex(4)}")
+ try:
+ # Create the temp file atomically at 0o600. The previous
+ # write_text + post-replace chmod opened a TOCTOU window where
+ # both the temp file and the destination briefly inherited the
+ # process umask (commonly 0o644 = world-readable), exposing
+ # Claude Code OAuth tokens to other local users between create
+ # and chmod. Mirrors agent/google_oauth.py (#19673) and
+ # tools/mcp_oauth.py (#21148). Parent dir (~/.claude/) is
+ # owned by Claude Code itself, so we leave its mode alone.
+ fd = os.open(
+ str(_tmp_cred),
+ os.O_WRONLY | os.O_CREAT | os.O_EXCL,
+ stat.S_IRUSR | stat.S_IWUSR,
+ )
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
+ json.dump(existing, fh, indent=2)
+ fh.flush()
+ os.fsync(fh.fileno())
+ os.replace(_tmp_cred, cred_path)
+ except OSError:
+ try:
+ _tmp_cred.unlink(missing_ok=True)
+ except OSError:
+ pass
+ raise
+ except (OSError, IOError, ValueError) as e:
+ # ValueError covers a corrupt existing file (JSONDecodeError): the
+ # merge-read is part of the commit, so failing it means the rotated
+ # pair never landed either.
+ logger.error("Failed to write refreshed credentials to %s: %s", cred_path, e)
+ raise CredentialPersistError(cred_path, e) from e
+
+
+ def _resolve_claude_code_token_from_credentials(creds: Optional[Dict[str, Any]] = None) -> Optional[str]:
+ """Resolve a token from Claude Code credential files, refreshing if needed."""
+ creds = creds or read_claude_code_credentials()
+ if creds and is_rotation_consumed_uncommitted(
+ creds.get("accessToken", ""), source_path=claude_code_credentials_path()
+ ):
+ # This process already rotated this pair and failed to commit the
+ # replacement. The file still holds the spent copy; treating it as
+ # usable is exactly the silent success this transaction fails closed
+ # to prevent.
+ logger.debug(
+ "Claude Code credentials hold a rotated-but-uncommitted token - refusing"
+ )
+ return None
+ if creds and is_claude_code_token_valid(creds):
+ logger.debug("Using Claude Code credentials (auto-detected)")
+ return creds["accessToken"]
+ if creds:
+ logger.debug("Claude Code credentials expired — attempting refresh")
+ refreshed = _refresh_oauth_token(creds)
+ if refreshed:
+ return refreshed
+ logger.debug("Token refresh failed — re-run 'claude setup-token' to reauthenticate")
+ return None
+
+
+ def _prefer_refreshable_claude_code_token(env_token: str, creds: Optional[Dict[str, Any]]) -> Optional[str]:
+ """Prefer Claude Code creds when a persisted env OAuth token would shadow refresh.
+
+ Hermes historically persisted setup tokens into ANTHROPIC_TOKEN. That makes
+ later refresh impossible because the static env token wins before we ever
+ inspect Claude Code's refreshable credential file. If we have a refreshable
+ Claude Code credential record, prefer it over the static env OAuth token.
+ """
+ if not env_token or not _is_oauth_token(env_token) or not isinstance(creds, dict):
+ return None
+ if not creds.get("refreshToken"):
+ return None
+
+ resolved = _resolve_claude_code_token_from_credentials(creds)
+ if resolved and resolved != env_token:
+ logger.debug(
+ "Preferring Claude Code credential file over static env OAuth token so refresh can proceed"
+ )
+ return resolved
+ return None
+
+
+ def _resolve_anthropic_pool_token() -> Optional[str]:
+ """Return the first available Anthropic OAuth token from credential_pool.
+
+ Read-only: enumerates with ``clear_expired=False, refresh=False`` so a bare
+ token *resolve* (which runs from diagnostic/read-only call sites such as
+ ``account_usage`` and ``hermes models``) never mutates ``~/.hermes/auth.json``
+ or makes a network refresh call. Refresh-on-expiry is owned by the API call
+ path's pool recovery, not the resolver.
+ """
+ try:
+ from agent.credential_pool import AUTH_TYPE_OAUTH, load_pool
+ except Exception:
+ return None
+
+ try:
+ pool = load_pool("anthropic")
+ # Enumerate read-only (clear_expired=False, refresh=False): never persist
+ # to auth.json or trigger a network refresh from a bare resolve. select()
+ # is deliberately NOT used — it runs clear_expired=True, refresh=True,
+ # which would violate this read-only contract.
+ entries, _pending = pool._available_entries(clear_expired=False, refresh=False)
+ except Exception:
+ logger.debug("Failed to read Anthropic credential_pool", exc_info=True)
+ return None
+
+ for entry in entries:
+ if getattr(entry, "auth_type", None) != AUTH_TYPE_OAUTH:
+ continue
+ # access_token is a declared field but a persisted entry can carry an
+ # explicit null (or a partially-written OAuth entry), so coerce before
+ # strip — a bare None.strip() here would escape the try/excepts above
+ # and crash the whole resolver, taking down the source #5 fallback too.
+ # Matches the aux-client analog (auxiliary_client.py: str(key or "")).
+ token = (getattr(entry, "access_token", None) or "").strip()
+ if not token:
+ continue
+ # ``load_pool()`` re-seeds pool rows from the singleton files, so a
+ # rotation that was consumed upstream but never committed comes back
+ # here looking healthy. Enumeration is deliberately read-only
+ # (refresh=False), which means nothing on this path would otherwise
+ # notice that the credential is spent. Singleton-backed sources also
+ # consult the durable sidecar registry: the failed commit may have
+ # happened in a DIFFERENT process, whose process-local verdict this
+ # interpreter never saw.
+ entry_source_path = spent_rotation_source_path(getattr(entry, "source", None))
+ if is_rotation_consumed_uncommitted(
+ token, source_path=entry_source_path
+ ) or is_rotation_consumed_uncommitted(
+ getattr(entry, "refresh_token", None), source_path=entry_source_path
+ ):
+ logger.debug(
+ "Skipping Anthropic pool entry %s: rotated-but-uncommitted credential",
+ getattr(entry, "id", "?"),
+ )
+ continue
+ return token
+
+ return None
+
+
+ def resolve_anthropic_token() -> Optional[str]:
+ """Resolve an Anthropic token from all available sources.
+
+ Priority:
+ 1. ANTHROPIC_TOKEN env var (OAuth/setup token saved by Hermes)
+ 2. CLAUDE_CODE_OAUTH_TOKEN env var
+ 3. ANTHROPIC_API_KEY env var (explicit regular API key)
+ 4. Claude Code credentials (~/.claude.json or ~/.claude/.credentials.json)
+ — with automatic refresh if expired and a refresh token is available
+ 5. Anthropic credential_pool OAuth entry (~/.hermes/auth.json)
+
+ Returns the token string or None.
+ """
+ creds: Optional[Dict[str, Any]] = None
+ creds_loaded = False
+
+ def _read_creds() -> Optional[Dict[str, Any]]:
+ nonlocal creds, creds_loaded
+ if not creds_loaded:
+ creds = read_claude_code_credentials()
+ creds_loaded = True
+ return creds
+
+ # 1. Hermes-managed OAuth/setup token env var
+ token = _getenv("ANTHROPIC_TOKEN").strip()
+ if token:
+ preferred = _prefer_refreshable_claude_code_token(token, _read_creds())
+ if preferred:
+ return preferred
+ return token
+
+ # 2. CLAUDE_CODE_OAUTH_TOKEN (used by Claude Code for setup-tokens)
+ cc_token = _getenv("CLAUDE_CODE_OAUTH_TOKEN").strip()
+ if cc_token:
+ preferred = _prefer_refreshable_claude_code_token(cc_token, _read_creds())
+ if preferred:
+ return preferred
+ return cc_token
+
+ # 3. Regular API key. An explicit user-configured key must not be shadowed
+ # by auto-discovered Claude Code or credential-pool OAuth credentials.
+ api_key = _getenv("ANTHROPIC_API_KEY").strip()
+ if api_key:
+ return api_key
+
+ # 4. Claude Code credential file
+ resolved_claude_token = _resolve_claude_code_token_from_credentials(_read_creds())
+ if resolved_claude_token:
+ return resolved_claude_token
+
+ # 5. Hermes credential_pool OAuth entry.
+ resolved_pool_token = _resolve_anthropic_pool_token()
+ if resolved_pool_token:
+ return resolved_pool_token
+
+ return None
+
+
+ def run_oauth_setup_token() -> Optional[str]:
+ """Run 'claude setup-token' interactively and return the resulting token.
+
+ Checks multiple sources after the subprocess completes:
+ 1. Claude Code credential files (may be written by the subprocess)
+ 2. CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_TOKEN env vars
+
+ Returns the token string, or None if no credentials were obtained.
+ Raises FileNotFoundError if the 'claude' CLI is not installed.
+ """
+ import shutil
+ import subprocess
+
+ claude_path = shutil.which("claude")
+ if not claude_path:
+ raise FileNotFoundError(
+ "The 'claude' CLI is not installed. "
+ "Install it with: npm install -g @anthropic-ai/claude-code"
+ )
+
+ # Run interactively — stdin/stdout/stderr inherited so the user can
+ # complete the OAuth login prompt. Must keep inherited stdin; the TUI-EOF
+ # concern does not apply to an interactive login the user explicitly
+ # invokes. noqa: subprocess-stdin
+ try:
+ subprocess.run([claude_path, "setup-token"])
+ except (KeyboardInterrupt, EOFError):
+ return None
+
+ # Check if credentials were saved to Claude Code's config files
+ creds = read_claude_code_credentials()
+ if creds and is_claude_code_token_valid(creds):
+ return creds["accessToken"]
+
+ # Check env vars that may have been set
+ for env_var in ("CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_TOKEN"):
+ val = _getenv(env_var).strip()
+ if val:
+ return val
+
+ return None
+
+
+ # ── Hermes-native PKCE OAuth flow ────────────────────────────────────────
+ # Mirrors the flow used by Claude Code, pi-ai, and OpenCode.
+ # Stores credentials in ~/.hermes/.anthropic_oauth.json (our own file).
+
+ _OAUTH_CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e"
+ # Anthropic migrated the OAuth token endpoint to platform.claude.com;
+ # console.anthropic.com now 404s. Callers should iterate _OAUTH_TOKEN_URLS
+ # (new host first, console fallback). _OAUTH_TOKEN_URL is kept as the primary
+ # for backward compatibility with existing imports and now points at the live host.
+ _OAUTH_TOKEN_URLS = [
+ "https://platform.claude.com/v1/oauth/token",
+ "https://console.anthropic.com/v1/oauth/token",
+ ]
+ _OAUTH_TOKEN_URL = _OAUTH_TOKEN_URLS[0]
+ # User-Agent sent on the OAuth *token endpoint* (login exchange + refresh).
+ # Anthropic rate-limits (HTTP 429) any token-endpoint request whose UA starts
+ # with ``claude-code/`` — verified empirically against platform.claude.com:
+ # ``claude-code/2.1.200`` and ``Mozilla/5.0`` -> 429; ``axios/*``, ``node``,
+ # and SDK-style UAs -> 400 (reached code validation). The real Claude Code CLI
+ # exchanges the auth code with a bare axios client (``axios/<ver>``), NOT its
+ # ``claude-code/`` inference UA. We mirror that here. NOTE: the *inference* path
+ # (build_anthropic_kwargs) still uses the ``claude-code/`` UA + ``x-app: cli`` —
+ # that fingerprint is required there and is NOT throttled on the messages API.
+ _OAUTH_TOKEN_USER_AGENT = "axios/1.7.9"
+ _OAUTH_REDIRECT_URI = "https://console.anthropic.com/oauth/code/callback"
+ _OAUTH_SCOPES = "org:create_api_key user:profile user:inference"
+ def _get_hermes_oauth_file() -> Path:
+ return get_hermes_home() / ".anthropic_oauth.json"
+
+
+ def _generate_pkce() -> tuple:
+ """Generate PKCE code_verifier and code_challenge (S256)."""
+ import base64
+ import hashlib
+ import secrets
+
+ verifier = base64.urlsafe_b64encode(secrets.token_bytes(32)).rstrip(b"=").decode()
+ challenge = base64.urlsafe_b64encode(
+ hashlib.sha256(verifier.encode()).digest()
+ ).rstrip(b"=").decode()
+ return verifier, challenge
+
+
+ def run_hermes_oauth_login_pure() -> Optional[Dict[str, Any]]:
+ """Run Hermes-native OAuth PKCE flow and return credential state."""
+ import secrets
+ import time
+ import webbrowser
+
+ verifier, challenge = _generate_pkce()
+ oauth_state = secrets.token_urlsafe(32)
+
+ params = {
+ "code": "true",
+ "client_id": _OAUTH_CLIENT_ID,
+ "response_type": "code",
+ "redirect_uri": _OAUTH_REDIRECT_URI,
+ "scope": _OAUTH_SCOPES,
+ "code_challenge": challenge,
+ "code_challenge_method": "S256",
+ "state": oauth_state,
+ }
+ from urllib.parse import urlencode
+
+ auth_url = f"https://claude.ai/oauth/authorize?{urlencode(params)}"
+
+ print()
+ print("Authorize Hermes with your Claude Pro/Max subscription.")
+ print()
+ print("╭─ Claude Pro/Max Authorization ────────────────────╮")
+ print("│ │")
+ print("│ Open this link in your browser: │")
+ print("╰───────────────────────────────────────────────────╯")
+ print()
+ print(f" {auth_url}")
+ print()
+
+ try:
+ from hermes_cli.auth import _can_open_graphical_browser as _can_open_gui
+ except Exception:
+ _can_open_gui = lambda: True # noqa: E731 — degrade to prior behavior
+
+ if _can_open_gui():
+ try:
+ webbrowser.open(auth_url)
+ print(" (Browser opened automatically)")
+ except Exception:
+ pass
+
+ print()
+ print("After authorizing, you'll see a code. Paste it below.")
+ print()
+ try:
+ auth_code = input("Authorization code: ").strip()
+ except (KeyboardInterrupt, EOFError):
+ return None
+
+ if not auth_code:
+ print("No code entered.")
+ return None
+
+ splits = auth_code.split("#")
+ code = splits[0]
+ received_state = splits[1] if len(splits) > 1 else ""
+
+ # Validate state to prevent CSRF (RFC 6749 §10.12)
+ if received_state != oauth_state:
+ logger.warning("OAuth state mismatch — possible CSRF, aborting")
+ return None
+
+ try:
+ import urllib.request
+
+ exchange_data = json.dumps({
+ "grant_type": "authorization_code",
+ "client_id": _OAUTH_CLIENT_ID,
+ "code": code,
+ "state": received_state,
+ "redirect_uri": _OAUTH_REDIRECT_URI,
+ "code_verifier": verifier,
+ }).encode()
+
+ # Anthropic migrated the OAuth token endpoint to platform.claude.com;
+ # console.anthropic.com now 404s. Try the new host first, then fall
+ # back to console for older deployments (mirrors the refresh path).
+ # UA is _OAUTH_TOKEN_USER_AGENT (a non-claude-code UA) — see the
+ # constant's definition for why the token endpoint must not send
+ # claude-code/ (429 UA-prefix block).
+ result = None
+ last_error = None
+ for endpoint in _OAUTH_TOKEN_URLS:
+ req = urllib.request.Request(
+ endpoint,
+ data=exchange_data,
+ headers={
+ "Content-Type": "application/json",
+ "User-Agent": _OAUTH_TOKEN_USER_AGENT,
+ },
+ method="POST",
+ )
+ try:
+ with urllib.request.urlopen(req, timeout=15) as resp:
+ result = json.loads(resp.read().decode())
+ break
+ except Exception as exc:
+ last_error = exc
+ logger.debug("Anthropic token exchange failed at %s: %s", endpoint, exc)
+ continue
+
+ if result is None:
+ raise last_error if last_error is not None else ValueError(
+ "Anthropic token exchange failed"
+ )
+ except Exception as e:
+ print(f"Token exchange failed: {e}")
+ return None
+
+ access_token = result.get("access_token", "")
+ refresh_token = result.get("refresh_token", "")
+ expires_in = result.get("expires_in", 3600)
+
+ if not access_token:
+ print("No access token in response.")
+ return None
+
+ expires_at_ms = int(time.time() * 1000) + (expires_in * 1000)
+ return {
+ "access_token": access_token,
+ "refresh_token": refresh_token,
+ "expires_at_ms": expires_at_ms,
+ }
+
+
+ def read_hermes_oauth_credentials() -> Optional[Dict[str, Any]]:
+ """Read Hermes-managed OAuth credentials from ~/.hermes/.anthropic_oauth.json."""
+ oauth_file = _get_hermes_oauth_file()
+ if oauth_file.exists():
+ try:
- data = json.loads(oauth_file.read_text(encoding="utf-8"))
++ data = json.loads(oauth_file.read_text(encoding="utf-8-sig"))
+ if data.get("accessToken"):
+ return data
+ except (json.JSONDecodeError, OSError, IOError) as e:
+ logger.debug("Failed to read Hermes OAuth credentials: %s", e)
+ return None
+
+
+ def _write_hermes_oauth_credentials(
+ access_token: str,
+ refresh_token: Optional[str],
+ expires_at_ms: Optional[int],
+ ) -> None:
+ """Write refreshed hermes_pkce tokens back to ~/.hermes/.anthropic_oauth.json.
+
+ Without this, a successful pool-level refresh of a ``hermes_pkce``-sourced
+ entry is invisible to this singleton file. The next ``load_pool()`` call
+ runs ``_seed_from_singletons()``, which reads the stale file and
+ overwrites the freshly-rotated pool entry with the pre-refresh (and, for
+ single-use Anthropic refresh tokens, already-consumed) token pair.
+
+ Raises ``CredentialPersistError`` when the rotated pair does not reach the
+ file, for the same reason ``_write_claude_code_credentials`` does: this is
+ the commit step of the refresh transaction.
+ """
+ oauth_file = _get_hermes_oauth_file()
+ try:
+ oauth_data = {
+ "accessToken": access_token,
+ "refreshToken": refresh_token,
+ "expiresAt": expires_at_ms,
+ }
+ oauth_file.parent.mkdir(parents=True, exist_ok=True)
+ _tmp_oauth = oauth_file.with_suffix(f".tmp.{os.getpid()}.{secrets.token_hex(4)}")
+ try:
+ fd = os.open(
+ str(_tmp_oauth),
+ os.O_WRONLY | os.O_CREAT | os.O_EXCL,
+ stat.S_IRUSR | stat.S_IWUSR,
+ )
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
+ json.dump(oauth_data, fh, indent=2)
+ fh.flush()
+ os.fsync(fh.fileno())
+ os.replace(_tmp_oauth, oauth_file)
+ except OSError:
+ try:
+ _tmp_oauth.unlink(missing_ok=True)
+ except OSError:
+ pass
+ raise
+ except (OSError, IOError, ValueError) as e:
+ logger.error(
+ "Failed to write refreshed Hermes OAuth credentials to %s: %s", oauth_file, e
+ )
+ raise CredentialPersistError(oauth_file, e) from e
+
diff --cc agent/auxiliary_client.py
index e342c06c3be,d02073cc922..74b20374583
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@@ -9303,6 -9390,49 +9390,49 @@@ def _is_streaming_rejected_error(exc: E
)
+ _MANAGED_LOCAL_STATE_TTL_S = 15.0
+ _managed_local_cache: "tuple[float, str]" = (0.0, "")
+
+
+ def _managed_local_netloc() -> str:
+ """host:port of the managed local llama-server, or "" when none.
+
+ Read from the supervisor's state file (written at spawn, removed on
+ stop) with a short TTL so per-request checks don't hit the disk. The
+ state file is the same source provider resolution uses, so the match
+ is exact — no false positives on other localhost endpoints.
+ """
+ global _managed_local_cache
+ now = time.monotonic()
+ ts, cached = _managed_local_cache
+ if now - ts < _MANAGED_LOCAL_STATE_TTL_S:
+ return cached
+ netloc = ""
+ try:
+ from hermes_cli.local_runtime.supervisor import state_path
+
- raw = state_path().read_text(encoding="utf-8")
++ raw = state_path().read_text(encoding="utf-8-sig")
+ base = str((json.loads(raw) or {}).get("base_url", ""))
+ netloc = urlparse(base).netloc.lower()
+ except Exception:
+ netloc = ""
+ _managed_local_cache = (now, netloc)
+ return netloc
+
+
+ def _is_managed_local_endpoint(base_url: Optional[str]) -> bool:
+ """True when *base_url* targets the llama-server this Hermes manages."""
+ if not base_url:
+ return False
+ managed = _managed_local_netloc()
+ if not managed:
+ return False
+ try:
+ return urlparse(str(base_url)).netloc.lower() == managed
+ except Exception:
+ return False
+
+
def _provider_requires_stream(provider: str, base_url: Optional[str]) -> bool:
"""Detect providers that only accept streaming (non-stream = HTTP 400).
diff --cc agent/chat_completion_helpers.py
index 936d1d7463b,bb9279dc05f..69b717606a6
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@@ -1045,6 -1055,59 +1055,59 @@@ def should_use_direct_api_call(agent) -
_DIRECT_API_ACTIVITY_HEARTBEAT_SECONDS = 15.0
+ def _managed_local_load_notice(agent, api_kwargs: dict) -> "Optional[str]":
+ """A live phase notice while the managed local server works before the
+ first token, or None when neither phase (nor the managed server) applies:
+
+ - "⏳ loading <model> into memory — N%" (weights streaming off disk;
+ real per-tensor percent from the router's SSE stream)
+ - "⚙ processing prompt — N of ~M tokens (P%)" (prefill; live counter
+ from /slots, denominator estimated from the request body)
+
+ A cold local model spends ~tens of seconds loading and a long-context
+ turn spends tens more in prefill; without this, both windows render as
+ the generic "no output yet (provider may be slow or overloaded)" stall
+ warning — alarming copy for healthy, expected phases.
+ """
+ try:
+ base = str(getattr(agent, "base_url", "") or "")
+ if not base:
+ return None
+ import json as _json
+ from urllib.parse import urlparse
+
+ from hermes_cli.local_runtime.load_progress import (
+ get_loading_progress,
+ get_prefill_progress,
+ )
+ from hermes_cli.local_runtime.supervisor import state_path
+
- state = _json.loads(state_path().read_text(encoding="utf-8"))
++ state = _json.loads(state_path().read_text(encoding="utf-8-sig"))
+ managed = urlparse(str(state.get("base_url", ""))).netloc.lower()
+ if not managed or urlparse(base).netloc.lower() != managed:
+ return None
+ model = str(api_kwargs.get("model", ""))
+ progress = get_loading_progress().get(model)
+ if progress is not None:
+ return (
+ f"⏳ loading {model} into memory — {progress['percent']}% "
+ "(responses start once the model is loaded)"
+ )
+ prefill = get_prefill_progress(model)
+ if prefill is not None:
+ processed = int(prefill["processed"])
+ total = estimate_request_context_tokens(api_kwargs)
+ if total and total >= processed:
+ pct = max(0, min(100, round(processed / total * 100)))
+ return f"⚙ processing prompt — {pct}%"
+ # Counter past the estimate (estimator undercounted): no honest
+ # denominator, so no percent — the UI shows label-only.
+ return "⚙ processing prompt"
+ return None
+ except Exception: # noqa: BLE001 — a status nicety must never break a call
+ return None
+
+
def _resolve_direct_stale_timeout(agent, api_kwargs: dict) -> float:
"""Stale budget for the inline non-streaming call.
diff --cc agent/review_idle_queue.py
index 00000000000,2d31501c8e4..45012ec3cc6
mode 000000,100644..100644
--- a/agent/review_idle_queue.py
+++ b/agent/review_idle_queue.py
@@@ -1,0 -1,291 +1,291 @@@
+ """Idle deferral for background reviews on the managed local runtime.
+
+ The post-turn review fork replays the whole conversation on the review
+ runtime. On a cloud provider that costs seconds and runs concurrently
+ with whatever the user does next. When the review runtime IS the managed
+ llama-server, the same fork monopolizes the GPU the user's next prompt
+ needs, for minutes — and the next live turn cancels it, so an active
+ session tends to pay the decode cost AND lose the learning.
+
+ This module keeps the decision to learn exactly where it was (turn end,
+ nudge intervals, full-strength model, full transcript) and moves only
+ the execution moment: reviews bound for the managed local endpoint are
+ queued and dispatched when the machine is quiet. Everything else runs
+ immediately, as before.
+
+ Policy (auxiliary.background_review.defer):
+ auto (default) — defer exactly when the resolved review runtime
+ targets the managed local server.
+ never — old behavior everywhere.
+ Explicit /refine (focus set) never defers: an explicit ask runs now,
+ matching its bypass of the enabled gate.
+
+ Queue semantics:
+ - One slot per session, newest snapshot wins. A review replays the whole
+ conversation, so a newer snapshot strictly supersedes an older one —
+ coalescing is deduplication, not loss.
+ - Preempted (cancelled-by-live-turn) reviews are requeued by the spawn
+ wrapper observing the run token's cancel flag, not killed-and-forgotten.
+ - Aged-out events (defer_max_age_s, default 30 min) dispatch regardless
+ of idleness — deferral may delay learning, never lose it.
+ - In-memory, best-effort: dropped on process exit, the same durability
+ contract the immediate daemon-thread fork always had.
+
+ Idle truth comes from the supervisor's /slots (machine-level: it sees
+ every client of the managed server, including other Hermes profiles) and
+ must hold for a settle window so a review is not launched into the gap
+ between two quick prompts. Local in-process turn liveness is tracked via
+ note_turn_started/note_turn_finished from run_conversation.
+ """
+
+ from __future__ import annotations
+
+ import json
+ import logging
+ import threading
+ import time
+ import urllib.request
+ from typing import Any, Callable, Dict, List, Optional
+
+ logger = logging.getLogger(__name__)
+
+ # Sustained-quiet window before dispatch. Long enough that "typed two
+ # prompts back to back" does not look idle; short enough that walking
+ # away for coffee runs the queue.
+ _IDLE_SETTLE_S = 15.0
+ # Poll cadence while the queue is non-empty. The thread parks when empty.
+ _POLL_INTERVAL_S = 5.0
+ # Age at which a queued review dispatches regardless of idleness.
+ _MAX_AGE_DEFAULT_S = 30.0 * 60.0
+
+
+ def defer_mode(task_cfg: Optional[Dict[str, Any]]) -> str:
+ """'auto' (default) or 'never' from auxiliary.background_review.defer."""
+ raw = str((task_cfg or {}).get("defer", "auto")).strip().lower()
+ return raw if raw in ("auto", "never") else "auto"
+
+
+ def defer_max_age_s(task_cfg: Optional[Dict[str, Any]]) -> float:
+ raw = (task_cfg or {}).get("defer_max_age_s", _MAX_AGE_DEFAULT_S)
+ try:
+ value = float(raw)
+ except (TypeError, ValueError):
+ return _MAX_AGE_DEFAULT_S
+ return value if value > 0 else _MAX_AGE_DEFAULT_S
+
+
+ def review_targets_managed_local(agent: Any,
+ task_cfg: Optional[Dict[str, Any]]) -> bool:
+ """Would this review fork decode on the llama-server WE manage?
+
+ Resolves the review runtime the same way the fork itself will and
+ exact-matches its netloc against the supervisor state file — the
+ matcher that cannot false-positive on external local servers. Any
+ failure reads False: immediate spawn is always the safe default.
+
+ Order matters: the netloc probe (one TTL-cached state-file read)
+ runs FIRST, so machines with no managed server — every cloud-only
+ install — return False without resolving the review runtime at all.
+ This wrapper runs on the turn's tail; runtime resolution belongs on
+ that path only when a managed server actually exists.
+ """
+ try:
+ from agent.auxiliary_client import (
+ _is_managed_local_endpoint,
+ _managed_local_netloc,
+ )
+
+ if not _managed_local_netloc():
+ return False
+ from agent.background_review import _resolve_review_runtime
+
+ runtime = _resolve_review_runtime(agent, task_cfg)
+ return _is_managed_local_endpoint(runtime.get("base_url"))
+ except Exception: # noqa: BLE001
+ return False
+
+
+ class _PendingReview:
+ __slots__ = ("agent", "kwargs", "enqueued_at", "session_key")
+
+ def __init__(self, agent: Any, session_key: str, kwargs: Dict[str, Any]):
+ self.agent = agent
+ self.session_key = session_key
+ self.kwargs = kwargs
+ self.enqueued_at = time.monotonic()
+
+
+ class ReviewIdleQueue:
+ """Session-coalescing queue + idle-gated dispatcher thread."""
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._pending: Dict[str, _PendingReview] = {}
+ self._wake = threading.Event()
+ self._thread: Optional[threading.Thread] = None
+ self._live_turns = 0
+ self._quiet_since: Optional[float] = None
+ # Test seams — replaced by unit tests, never in production.
+ self._now: Callable[[], float] = time.monotonic
+ self._server_idle: Callable[[], bool] = _managed_server_idle
+
+ # ── turn liveness (this process) ────────────────────────────
+
+ def note_turn_started(self) -> None:
+ with self._lock:
+ self._live_turns += 1
+ self._quiet_since = None
+
+ def note_turn_finished(self) -> None:
+ with self._lock:
+ self._live_turns = max(0, self._live_turns - 1)
+ if self._live_turns == 0:
+ self._quiet_since = self._now()
+ self._wake.set()
+
+ # ── queue ────────────────────────────────────────────────────
+
+ def enqueue(self, agent: Any, session_key: str,
+ kwargs: Dict[str, Any]) -> None:
+ """Add (or replace — newest snapshot wins) a session's pending review."""
+ with self._lock:
+ existing = self._pending.get(session_key)
+ item = _PendingReview(agent, session_key, kwargs)
+ # Stamp through the queue's clock (test seam); keep the ORIGINAL
+ # enqueue time on coalesce so a busy session cannot push its
+ # review's age-out forever.
+ item.enqueued_at = (existing.enqueued_at if existing is not None
+ else self._now())
+ self._pending[session_key] = item
+ self._ensure_thread()
+ self._wake.set()
+ logger.info("Background review deferred (session=%s, queued=%d)",
+ session_key[-12:], len(self._pending))
+
+ def pending_count(self) -> int:
+ with self._lock:
+ return len(self._pending)
+
+ # ── dispatcher ───────────────────────────────────────────────
+
+ def _ensure_thread(self) -> None:
+ with self._lock:
+ if self._thread is None or not self._thread.is_alive():
+ self._thread = threading.Thread(
+ target=self._run, daemon=True, name="bg-review-idle-queue")
+ self._thread.start()
+
+ def _quiet_for(self) -> float:
+ """Seconds this process has been turn-free (0 while a turn runs)."""
+ with self._lock:
+ if self._live_turns > 0 or self._quiet_since is None:
+ return 0.0
+ return self._now() - self._quiet_since
+
+ def _pop_dispatchable(self) -> Optional[_PendingReview]:
+ """Oldest aged-out item, else any item once quiet+idle hold."""
+ with self._lock:
+ if not self._pending:
+ return None
+ items = sorted(self._pending.values(),
+ key=lambda p: p.enqueued_at)
+ aged = [p for p in items
+ if self._now() - p.enqueued_at
+ >= defer_max_age_s(p.kwargs.get("task_cfg"))]
+ candidate = aged[0] if aged else None
+ if candidate is None:
+ if self._quiet_for() < _IDLE_SETTLE_S:
+ return None
+ if not self._server_idle():
+ return None
+ with self._lock:
+ if not self._pending:
+ return None
+ candidate = min(self._pending.values(),
+ key=lambda p: p.enqueued_at)
+ with self._lock:
+ return self._pending.pop(candidate.session_key, None)
+
+ def _run(self) -> None:
+ while True:
+ self._wake.wait()
+ with self._lock:
+ if not self._pending:
+ self._wake.clear()
+ continue
+ item = None
+ try:
+ item = self._pop_dispatchable()
+ if item is not None:
+ if not self._still_enabled(item):
+ logger.info(
+ "Deferred background review dropped: reviews "
+ "were disabled while it was queued (session=%s)",
+ item.session_key[-12:])
+ continue
+ logger.info(
+ "Dispatching deferred background review "
+ "(session=%s, waited=%.0fs, queued=%d)",
+ item.session_key[-12:],
+ self._now() - item.enqueued_at,
+ self.pending_count())
+ item.agent._spawn_background_review_now(**item.kwargs)
+ except Exception: # noqa: BLE001 — dispatcher must survive anything
+ logger.warning("Deferred review dispatch failed",
+ exc_info=True)
+ if item is None:
+ time.sleep(_POLL_INTERVAL_S)
+
+ @staticmethod
+ def _still_enabled(item: _PendingReview) -> bool:
+ """Re-check the enabled gate at DISPATCH time.
+
+ The entry wrapper gates at enqueue time, but minutes may pass in
+ the queue — a user who sets background_review.enabled: false while
+ a review waits means it, and the dispatch must not resurrect it.
+ Fail-open like the gate itself (a broken config never silently
+ disables reviews)."""
+ try:
+ from agent.background_review import load_background_review_settings
+
+ enabled, _ = load_background_review_settings()
+ return enabled
+ except Exception: # noqa: BLE001
+ return True
+
+
+ def _managed_server_idle() -> bool:
+ """Machine-level idle: no processing slot on any loaded model of the
+ managed router. Unreachable/no state file reads idle (nothing to
+ contend with). One /models + one /slots call per loaded model."""
+ try:
+ from hermes_cli.local_runtime.supervisor import state_path
+
- state = json.loads(state_path().read_text(encoding="utf-8"))
++ state = json.loads(state_path().read_text(encoding="utf-8-sig"))
+ base = str(state.get("base_url", "")).rsplit("/v1", 1)[0]
+ key = str(state.get("api_key", ""))
+ if not base:
+ return True
+ headers = {"Authorization": f"Bearer {key}"}
+ req = urllib.request.Request(f"{base}/models", headers=headers)
+ with urllib.request.urlopen(req, timeout=3) as r:
+ models = json.loads(r.read())
+ loaded = [m["id"] for m in models.get("data", [])
+ if (m.get("status") or {}).get("value") in ("loaded", "ready")]
+ from urllib.parse import quote
+
+ for mid in loaded:
+ req = urllib.request.Request(f"{base}/slots?model={quote(mid)}",
+ headers=headers)
+ with urllib.request.urlopen(req, timeout=3) as r:
+ slots = json.loads(r.read())
+ if any(s.get("is_processing") for s in slots
+ if isinstance(s, dict)):
+ return False
+ return True
+ except Exception: # noqa: BLE001
+ return True
+
+
+ # Module singleton — one queue per process, like the load-progress watcher.
+ QUEUE = ReviewIdleQueue()
diff --cc apps/desktop/electron/preload.ts
index 949832691c8,8017435b891..ed36b06f9c7
--- a/apps/desktop/electron/preload.ts
+++ b/apps/desktop/electron/preload.ts
@@@ -269,12 -270,14 +270,20 @@@ contextBridge.exposeInMainWorld('hermes
setDisableF12: blocked => ipcRenderer.send('hermes:devtools:disable-f12', blocked),
setPreviewShortcutActive: active => ipcRenderer.send('hermes:previewShortcutActive', Boolean(active)),
openExternal: url => ipcRenderer.invoke('hermes:openExternal', url),
+ onExternalOpenFailed: callback => {
+ const listener = (_event, payload) => callback(payload)
+ ipcRenderer.on('hermes:external-open-failed', listener)
+
+ return () => ipcRenderer.removeListener('hermes:external-open-failed', listener)
+ },
+ mcpOauth: {
+ // One-shot loopback listener for MCP OAuth against remote backends: bind
+ // on this machine, hand redirectUri to mcp.servers.oauth.start, then wait
+ // for the provider redirect and relay code/state via oauth.callback.
+ listen: () => ipcRenderer.invoke('hermes:mcp-oauth:listen'),
+ wait: (id, timeoutMs) => ipcRenderer.invoke('hermes:mcp-oauth:wait', id, timeoutMs),
+ cancel: id => ipcRenderer.invoke('hermes:mcp-oauth:cancel', id)
+ },
openPreviewInBrowser: url => ipcRenderer.invoke('hermes:openPreviewInBrowser', url),
reachPreviewUrl: url => ipcRenderer.invoke('hermes:preview:reach', url),
setActiveConnectionRoute: route => ipcRenderer.send('hermes:connection:active-route', route),
diff --cc apps/desktop/src/api/local-models.ts
index 00000000000,d2cbce5f2c8..c8b5f164976
mode 000000,100644..100644
--- a/apps/desktop/src/api/local-models.ts
+++ b/apps/desktop/src/api/local-models.ts
@@@ -1,0 -1,166 +1,184 @@@
+ import type {
+ LocalCatalogModel,
+ LocalHardware,
+ LocalModelsStatus,
+ LocalRuntimeJob
+ } from '@/types/hermes'
+
+ import { hermesApi, profileScoped } from './client'
+
+ // The desktop surface of the managed llama.cpp runtime: status/catalog
+ // reads, download/install/activate jobs, and server control.
+
+ export function getLocalModelsStatus(): Promise<LocalModelsStatus> {
+ return hermesApi<LocalModelsStatus>({
+ ...profileScoped(),
+ path: '/api/local-models/status'
+ })
+ }
+
+ export function getLocalHardware(): Promise<LocalHardware> {
+ return hermesApi<LocalHardware>({
+ ...profileScoped(),
+ path: '/api/local-models/hardware'
+ })
+ }
+
+ export function getLocalCatalog(): Promise<{ models: LocalCatalogModel[] }> {
+ return hermesApi<{ models: LocalCatalogModel[] }>({
+ ...profileScoped(),
+ path: '/api/local-models/catalog'
+ })
+ }
+
+ export function installLocalRuntime(backend?: string): Promise<{ backend: string; job_id: string; tag: string }> {
+ return hermesApi<{ backend: string; job_id: string; tag: string }>({
+ ...profileScoped(),
+ body: { backend: backend ?? null },
+ method: 'POST',
+ path: '/api/local-models/runtime/install'
+ })
+ }
+
+ export interface QuickstartResponse {
+ display_name: string
+ download_bytes: number
+ job_id: string
+ model_id: string
+ needs_download: boolean
+ needs_runtime: boolean
+ }
+
+ export function quickstartLocalModels(modelId?: string): Promise<QuickstartResponse> {
+ return hermesApi<QuickstartResponse>({
+ ...profileScoped(),
+ body: { model_id: modelId ?? null },
+ method: 'POST',
+ path: '/api/local-models/quickstart'
+ })
+ }
+
+ export function downloadLocalModel(modelId: string): Promise<{ already_downloaded?: boolean; job_id: null | string }> {
+ return hermesApi<{ already_downloaded?: boolean; job_id: null | string }>({
+ ...profileScoped(),
+ body: { model_id: modelId },
+ method: 'POST',
+ path: '/api/local-models/download'
+ })
+ }
+
++export function pauseLocalModelDownload(jobId: string): Promise<{ ok: boolean; paused: boolean }> {
++ return hermesApi<{ ok: boolean; paused: boolean }>({
++ ...profileScoped(),
++ body: { job_id: jobId },
++ method: 'POST',
++ path: '/api/local-models/download/pause'
++ })
++}
++
++export function resumeLocalModelDownload(jobId: string): Promise<{ ok: boolean; resumed: boolean }> {
++ return hermesApi<{ ok: boolean; resumed: boolean }>({
++ ...profileScoped(),
++ body: { job_id: jobId },
++ method: 'POST',
++ path: '/api/local-models/download/resume'
++ })
++}
++
+ export function deleteLocalModel(modelId: string): Promise<{ ok: boolean }> {
+ return hermesApi<{ ok: boolean }>({
+ ...profileScoped(),
+ method: 'DELETE',
+ path: `/api/local-models/models/${encodeURIComponent(modelId)}`
+ })
+ }
+
+ export function getLocalRuntimeJob(jobId: string): Promise<LocalRuntimeJob> {
+ return hermesApi<LocalRuntimeJob>({
+ ...profileScoped(),
+ path: `/api/local-models/jobs/${encodeURIComponent(jobId)}`
+ })
+ }
+
+ export function getLocalModelsJobs(): Promise<{ jobs: LocalRuntimeJob[] }> {
+ return hermesApi<{ jobs: LocalRuntimeJob[] }>({
+ ...profileScoped(),
+ path: '/api/local-models/jobs'
+ })
+ }
+
+ export function activateLocalModel(modelId: string): Promise<{ job_id: string }> {
+ return hermesApi<{ job_id: string }>({
+ ...profileScoped(),
+ body: { model_id: modelId },
+ method: 'POST',
+ path: '/api/local-models/activate'
+ })
+ }
+
+ export function ejectLocalModel(modelId: string): Promise<{ ok: boolean }> {
+ return hermesApi<{ ok: boolean }>({
+ ...profileScoped(),
+ body: { model_id: modelId },
+ method: 'POST',
+ path: '/api/local-models/eject'
+ })
+ }
+
+ export function setLocalServer(action: 'start' | 'stop'): Promise<{ ok: boolean }> {
+ return hermesApi<{ ok: boolean }>({
+ ...profileScoped(),
+ body: { action },
+ method: 'POST',
+ path: '/api/local-models/server'
+ })
+ }
+
+ // ── Hugging Face browser + sideload ─────────────────────────────
+
+ export interface HFSearchHit {
+ repo: string
+ downloads: number
+ likes: number
+ updated: string
+ gated: boolean
+ }
+
+ export interface HFFileGroup {
+ label: string
+ paths: string[]
+ total_bytes: number
+ fit: 'fits-gpu' | 'needs-ram' | 'too-big' | 'unknown'
+ }
+
+ export function searchHFModels(q: string, limit = 20): Promise<{ hits: HFSearchHit[] }> {
+ return hermesApi<{ hits: HFSearchHit[] }>({
+ ...profileScoped(),
+ path: `/api/local-models/search?q=${encodeURIComponent(q)}&limit=${limit}`
+ })
+ }
+
+ export function listHFRepoFiles(repo: string): Promise<{ files: HFFileGroup[] }> {
+ return hermesApi<{ files: HFFileGroup[] }>({
+ ...profileScoped(),
+ path: `/api/local-models/search/files?repo=${encodeURIComponent(repo)}`
+ })
+ }
+
+ export function downloadBrowsedModel(repo: string, paths: string[]): Promise<{ already_downloaded?: boolean; job_id: null | string; model_id: string }> {
+ return hermesApi<{ already_downloaded?: boolean; job_id: null | string; model_id: string }>({
+ ...profileScoped(),
+ body: { paths, repo },
+ method: 'POST',
+ path: '/api/local-models/download-browsed'
+ })
+ }
+
+ export function sideloadLocalModel(path: string): Promise<{ already_present?: boolean; model_id: string; ok: boolean }> {
+ return hermesApi<{ already_present?: boolean; model_id: string; ok: boolean }>({
+ ...profileScoped(),
+ body: { path },
+ method: 'POST',
+ path: '/api/local-models/sideload'
+ })
+ }
diff --cc apps/desktop/src/app/settings/about-settings.tsx
index bcc0bada290,fa358a08dcf..74a5aa64a74
--- a/apps/desktop/src/app/settings/about-settings.tsx
+++ b/apps/desktop/src/app/settings/about-settings.tsx
@@@ -33,21 -99,111 +33,21 @@@ export function AboutSettings()
return (
<SettingsContent>
- <div className="flex flex-col items-center gap-3 pt-6 pb-2 text-center">
- <BrandMark className="size-16" />
- <div>
- <h2 className="text-lg font-semibold tracking-tight">{a.heading}</h2>
- <p className="mt-1 text-xs text-muted-foreground">
- {version?.appVersion ? a.version(version.appVersion) : a.versionUnavailable}
- </p>
- </div>
- {version?.bundleOutOfSync && (
- <div className="mx-auto w-full max-w-2xl rounded-xl border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-left text-sm">
- <div className="flex items-start gap-2">
- <AlertTriangle className="mt-0.5 size-4 shrink-0 text-amber-600 dark:text-amber-400" />
- <div className="min-w-0">
- <p className="font-medium">{a.bundleOutOfSync}</p>
- <p className="mt-1 text-xs text-muted-foreground">{a.bundleOutOfSyncDesc}</p>
- <Button asChild className="mt-2" size="sm" variant="textStrong">
- <a
- href={INSTALLER_URL}
- onClick={event => {
- event.preventDefault()
- void window.hermesDesktop?.openExternal?.(INSTALLER_URL)
- }}
- rel="noreferrer"
- target="_blank"
- >
- <ExternalLink className="size-3" />
- {a.bundleOutOfSyncAction}
- </a>
- </Button>
- </div>
- </div>
- </div>
- )}
- </div>
+ <VersionHero version={version} />
<div className="mx-auto mt-4 w-full max-w-2xl">
- <SectionHeading icon={RefreshCw} title={u.updatesSection} />
- <SectionHeading icon={RefreshCw} title={a.updates} />
-
- <div
- className={cn(
- 'rounded-xl border px-4 py-3 text-sm',
- statusTone === 'available' && 'border-primary/30 bg-primary/5 text-foreground',
- statusTone === 'error' && 'border-destructive/35 bg-destructive/5 text-destructive',
- statusTone === 'idle' && 'border-border/70 bg-muted/20 text-foreground'
- )}
- >
- <div className="flex items-start gap-2">
- {statusTone === 'available' ? (
- <Codicon className="mt-0.5 size-4 shrink-0 text-primary" name="cloud-download" size="1rem" />
- ) : statusTone === 'error' ? null : (
- <CheckCircle2 className="mt-0.5 size-4 shrink-0 text-emerald-600 dark:text-emerald-400" />
- )}
- <div className="min-w-0">
- <p className="font-medium">{statusLine}</p>
- <p className="mt-1 text-xs text-muted-foreground">
- {a.lastChecked(relativeTime(status?.fetchedAt, a))}
- {justChecked && !checking ? a.justNowSuffix : ''}
- </p>
- </div>
- </div>
-
- <div className="mt-3 flex flex-wrap items-center gap-4">
- <Button
- disabled={checking || applying || !supported}
- onClick={() => void handleCheck()}
- size="sm"
- variant="textStrong"
- >
- {checking ? <Loader2 className="size-3 animate-spin" /> : <RefreshCw className="size-3" />}
- {checking ? a.checking : a.checkNow}
- </Button>
-
- {updateAvailable && supported && !applying && (
- <>
- <Button onClick={() => startActiveUpdate()} size="sm">
- {a.updateNow}
- </Button>
- <Button onClick={() => openUpdatesWindow()} size="sm" variant="textStrong">
- {a.seeWhatsNew}
- </Button>
- </>
- )}
-
- <Button asChild className="ml-auto" size="sm" variant="text">
- <a
- href={RELEASE_NOTES_URL}
- onClick={event => {
- event.preventDefault()
- void window.hermesDesktop?.openExternal?.(RELEASE_NOTES_URL)
- }}
- rel="noreferrer"
- target="_blank"
- >
- <ExternalLink className="size-3" />
- {a.releaseNotes}
- </a>
- </Button>
- </div>
++ <SectionHeading icon={RefreshCw} title={t.settings.about.updates} />
+
+ <div className="grid gap-3">
+ <UpdateStatusCard target="client" />
+ {/* The desktop client and a remote backend update independently — in
+ remote mode the statusbar shows both pills, so About shows both
+ states too. The backend has no GitHub release notes link of its
+ own; the client card already carries it. */}
+ {remote && <UpdateStatusCard showReleaseNotes={false} target="backend" />}
</div>
- <ListRow
- description={a.automaticUpdatesDesc}
- hint={a.branchCommit(status?.branch ?? 'unknown', status?.currentSha?.slice(0, 7) ?? 'unknown')}
- title={a.automaticUpdates}
- />
+ {version && <VersionDetails version={version} />}
<UninstallSection />
</div>
diff --cc apps/desktop/src/app/settings/local-models-settings.tsx
index 00000000000,504a9fbb173..7b5f655490f
mode 000000,100644..100644
--- a/apps/desktop/src/app/settings/local-models-settings.tsx
+++ b/apps/desktop/src/app/settings/local-models-settings.tsx
@@@ -1,0 -1,1105 +1,1138 @@@
+ import { useStore } from '@nanostores/react'
+ import { useCallback, useEffect, useRef, useState } from 'react'
+ import { useNavigate } from 'react-router'
+
+ import { NEW_CHAT_ROUTE } from '@/app/routes'
+ import { Button } from '@/components/ui/button'
+ import { Tip } from '@/components/ui/tooltip'
+ import {
+ activateLocalModel,
+ deleteLocalModel,
+ downloadBrowsedModel,
+ downloadLocalModel,
+ ejectLocalModel,
+ getLocalCatalog,
+ getLocalHardware,
+ getLocalModelsStatus,
+ type HFFileGroup,
+ type HFSearchHit,
+ installLocalRuntime,
+ listHFRepoFiles,
++ pauseLocalModelDownload,
+ quickstartLocalModels,
++ resumeLocalModelDownload,
+ searchHFModels,
+ setLocalServer,
+ sideloadLocalModel
+ } from '@/hermes'
+ import { useI18n } from '@/i18n'
-import { Check, CheckCircle2, Cpu, Download, Eject, FolderOpen, Loader2, Monitor, Package, Search, StopFilled, Trash2, Zap } from '@/lib/icons'
++import { Check, CheckCircle2, Cpu, Download, Eject, FolderOpen, Loader2, Monitor, Package, Pause, Play, Search, StopFilled, Trash2, Zap } from '@/lib/icons'
+ import { cn } from '@/lib/utils'
+ import {
+ $localRuntimeJobs,
+ runningDownloadFor,
+ runningRuntimeInstall,
+ watchLocalRuntimeJobs
+ } from '@/store/local-runtime-jobs'
+ import { notify, notifyError } from '@/store/notifications'
+ import type { LocalCatalogModel, LocalHardware, LocalModelsStatus } from '@/types/hermes'
+
+ import { ListRow, Pill, SettingsContent, SettingsSection, SettingsSkeleton } from './primitives'
+
+ function ProgressBar({ percent }: { percent: number | undefined }) {
+ return (
+ <div className="h-1.5 w-full overflow-hidden rounded-full bg-(--ui-bg-tertiary)">
+ <div
+ className="h-full rounded-full bg-primary transition-[width] duration-300"
+ style={{ width: `${Math.max(2, Math.min(100, percent ?? 2))}%` }}
+ />
+ </div>
+ )
+ }
+
+ function gbLabel(bytes: number | null | undefined): string {
+ if (!bytes) {
+ return '—'
+ }
+
+ return `${(bytes / (1 << 30)).toFixed(1)} GB`
+ }
+
+ // Catalog display order: what runs well leads. Resident (all on GPU)
+ // first, then spilled (works, slower), then doesn't-fit; catalog order
+ // (recommended first) holds within each band.
+ function fitRank(model: LocalCatalogModel): number {
+ if (model.fits && !model.spilled) {
+ return 0
+ }
+
+ if (model.fits) {
+ return 1
+ }
+
+ return 2
+ }
+
+ export function LocalModelsSettings() {
+ const { t } = useI18n()
+ const copy = t.settings.localModels
+ const [status, setStatus] = useState<LocalModelsStatus | null>(null)
+ const [hardware, setHardware] = useState<LocalHardware | null>(null)
+ const [catalog, setCatalog] = useState<LocalCatalogModel[] | null>(null)
+ const [deleting, setDeleting] = useState<null | string>(null)
+ const [serverBusy, setServerBusy] = useState(false)
+ // Quickstart escape hatch: true once the user asks for the full pane
+ // (model list, HF browser) instead of the one-button setup card.
+ const [configure, setConfigure] = useState(false)
+ // Jobs live in the app-level store (they must survive this pane
+ // unmounting); the pane just renders the slice it cares about.
+ const jobs = useStore($localRuntimeJobs)
+
+ const refresh = useCallback(() => {
+ void getLocalModelsStatus()
+ .then(setStatus)
+ .catch(() => setStatus(null))
+ void getLocalCatalog()
+ .then(data => setCatalog(data.models))
+ .catch(() => setCatalog([]))
+ }, [])
+
+ // Snappy first paint: status + catalog immediately; hardware (may shell out
+ // to nvidia-smi) backfills and pops in-place. The job watcher also kicks
+ // here so reopening the pane rediscovers work started before.
+ useEffect(() => {
+ refresh()
+ watchLocalRuntimeJobs()
+ void getLocalHardware()
+ .then(setHardware)
+ .catch(() => setHardware(null))
+ }, [refresh])
+
+ // The pane is LIVE while visible: residency changes without user action
+ // (boot warm finishing, idle sweep unloading, another surface ejecting),
+ // and a stale snapshot here reads as a broken feature — 'VRAM full but
+ // the pane says Not in memory'. The status route is built cheap for
+ // polling; setTimeout chain, never overlapping.
+ useEffect(() => {
+ let cancelled = false
+ let timer: number | undefined
+
+ const tick = async () => {
+ try {
+ const next = await getLocalModelsStatus()
+
+ if (!cancelled) {
+ setStatus(next)
+ }
+ } catch {
+ // Backend briefly unreachable — keep the last snapshot.
+ }
+
+ if (!cancelled) {
+ timer = window.setTimeout(() => void tick(), 4_000)
+ }
+ }
+
+ timer = window.setTimeout(() => void tick(), 4_000)
+
+ return () => {
+ cancelled = true
+
+ if (timer !== undefined) {
+ window.clearTimeout(timer)
+ }
+ }
+ }, [])
+
+ // A job finishing (download done, install done) changes what status/catalog
+ // should show — refresh whenever the running set shrinks.
+ const runningCount = jobs.filter(j => j.status === 'running').length
+ useEffect(() => {
+ refresh()
+ }, [refresh, runningCount])
+
+ async function handleInstallRuntime() {
+ try {
+ await installLocalRuntime()
+ watchLocalRuntimeJobs()
+ } catch (err) {
+ notifyError(err, copy.installFailed)
+ }
+ }
+
+ async function handleQuickstart() {
+ try {
+ await quickstartLocalModels()
+ watchLocalRuntimeJobs()
+ } catch (err) {
+ notifyError(err, copy.quickstartFailed)
+ }
+ }
+
+ async function handleDownload(model: LocalCatalogModel) {
+ try {
+ const res = await downloadLocalModel(model.id)
+
+ if (res.already_downloaded || !res.job_id) {
+ refresh()
+
+ return
+ }
+
+ watchLocalRuntimeJobs()
+ } catch (err) {
+ notifyError(err, copy.downloadFailed(model.display_name))
+ }
+ }
+
+ async function handleActivate(target: null | string, displayName: string) {
+ if (!target) {
+ return
+ }
+
+ try {
+ await activateLocalModel(target)
+ watchLocalRuntimeJobs()
+ } catch (err) {
+ notifyError(err, copy.activateFailed(displayName))
+ }
+ }
+
+ async function handleEject(modelId: string) {
+ try {
+ await ejectLocalModel(modelId)
+ notify({ durationMs: 3_000, kind: 'success', message: copy.ejected, title: copy.title })
+ refresh()
+ } catch (err) {
+ notifyError(err, copy.ejectFailed)
+ }
+ }
+
+ async function handleServer(action: 'start' | 'stop') {
+ setServerBusy(true)
+
+ try {
+ await setLocalServer(action)
+ notify({
+ durationMs: 3_500,
+ kind: 'success',
+ message: action === 'stop' ? copy.serverStopped : copy.serverStarted,
+ title: copy.title
+ })
+ refresh()
+ } catch (err) {
+ notifyError(err, action === 'stop' ? copy.serverStopFailed : copy.serverStartFailed)
+ } finally {
+ setServerBusy(false)
+ }
+ }
+
+ async function handleDelete(target: string, rowId: string) {
+ if (!window.confirm(copy.deleteConfirm(target))) {
+ return
+ }
+
+ setDeleting(rowId)
+
+ try {
+ await deleteLocalModel(target)
+ notify({ durationMs: 2_500, kind: 'success', message: copy.deleted(target), title: copy.title })
+ refresh()
+ } catch (err) {
+ notifyError(err, copy.deleteFailed)
+ } finally {
+ setDeleting(null)
+ }
+ }
+
+ // Setup flows end at the action, not the settings pane: when quickstart
+ // finishes while the user is still HERE watching it, land them on a new
+ // chat with the model ready to try. Unmount cancels the intent — a user
+ // who navigated away mid-download keeps their place (no focus theft).
+ // (Lives above the loading return: hooks run unconditionally.)
+ const navigate = useNavigate()
+ const seenQuickstarts = useRef(new Set<string>())
+
+ const runningQuickstart = jobs.find(
+ j => j.kind === 'quickstart' && j.status === 'running'
+ )
+
+ useEffect(() => {
+ // Event detection, not value mirroring: the ref only remembers which
+ // job ids THIS mount saw running, so a 'done' already in the list on
+ // mount (stale history) never triggers a navigation.
+ const seen = seenQuickstarts.current
+
+ for (const j of jobs) {
+ if (j.kind !== 'quickstart') {
+ continue
+ }
+
+ if (j.status === 'running') {
+ seen.add(j.job_id)
+ } else if (j.status === 'done' && seen.has(j.job_id)) {
+ seen.delete(j.job_id)
+ navigate(NEW_CHAT_ROUTE)
+ }
+ }
+ }, [jobs, navigate])
+
+ if (!status || catalog === null) {
+ return <SettingsSkeleton sections={[{ rows: 2 }, { rows: 4 }]} />
+ }
+
+ const rJob = runningRuntimeInstall(jobs)
+ const lastError = jobs.find(j => j.status === 'error')
+
+ const sortedCatalog = [...catalog].sort((a, b) => fitRank(a) - fitRank(b))
+
+ // ── Quickstart: the dummy-proof front door ──
+ // Until something is servable (runtime + at least one model), the pane
+ // leads with a hero that does everything in one click; the full pane
+ // stays one 'Configure…' click away. A running quickstart pins this
+ // view so its progress has a home even after a remount.
+ const qJob = runningQuickstart ?? null
+
+ const needsSetup = !status.runtime_installed || status.models.length === 0
+ const heroModel = catalog.find(c => c.recommended && c.fits) ?? catalog.find(c => c.fits) ?? null
+
+ if (qJob || (needsSetup && !configure && heroModel)) {
+ // Stage rail derived from the job phase: engine -> model -> finish.
+ const phase = qJob?.phase ?? ''
+
+ const stageIndex = ['starting-server', 'setting-default'].includes(phase)
+ ? 2
+ : phase === 'downloading'
+ ? 1
+ : 0
+
+ const stages = [copy.quickstartStageEngine, copy.quickstartStageModel, copy.quickstartStageFinish]
+
+ // The model-download leg blanks job.detail on purpose (pane rows
+ // render their own byte counter) — compose one here instead of
+ // falling back to runtime copy that would misname the stage.
+ const liveDetail =
+ qJob &&
+ (qJob.detail ||
+ (qJob.total_bytes
+ ? copy.downloadProgress(gbLabel(qJob.done_bytes), gbLabel(qJob.total_bytes))
+ : copy.installing))
+
+ return (
+ <SettingsContent>
+ <div className="flex min-h-[60dvh] items-center justify-center">
+ <div className="w-full max-w-md text-center">
+ <div className="mx-auto mb-5 flex size-14 items-center justify-center rounded-2xl bg-primary/10">
+ {qJob ? (
+ <Loader2 className="size-7 animate-spin text-primary" />
+ ) : (
+ <Cpu className="size-7 text-primary" />
+ )}
+ </div>
+
+ <h2 className="text-lg font-semibold text-foreground">
+ {qJob ? qJob.target : (heroModel?.display_name ?? '')}
+ </h2>
+
+ {qJob ? (
+ <>
+ <p className="mt-2 min-h-10 text-[0.8rem] leading-5 text-muted-foreground">
+ {liveDetail}
+ </p>
+
+ <div className="mt-5">
+ <ProgressBar percent={qJob.percent} />
+ </div>
+
+ {/* Stage rail: engine -> model -> finish. */}
+ <div className="mt-5 flex items-center justify-center gap-5">
+ {stages.map((label, i) => (
+ <span
+ className={cn(
+ 'inline-flex items-center gap-1.5 text-[0.72rem]',
+ i < stageIndex && 'text-(--ui-text-tertiary)',
+ i === stageIndex && 'font-medium text-foreground',
+ i > stageIndex && 'text-(--ui-text-tertiary) opacity-60'
+ )}
+ key={label}
+ >
+ {i < stageIndex ? (
+ <CheckCircle2 className="size-3.5 text-primary" />
+ ) : i === stageIndex ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : (
+ <span className="size-1.5 rounded-full bg-current" />
+ )}
+ {label}
+ </span>
+ ))}
+ </div>
+ </>
+ ) : heroModel ? (
+ <>
+ <p className="mt-2 text-[0.8rem] leading-5 text-muted-foreground">
+ {heroModel.downloaded
+ ? copy.quickstartDetailReady(heroModel.display_name)
+ : copy.quickstartDetail(heroModel.display_name, heroModel.size_label)}
+ </p>
+
+ <div className="mt-6 flex items-center justify-center gap-3">
+ <Button onClick={() => setConfigure(true)} size="sm" variant="outline">
+ {copy.quickstartConfigure}
+ </Button>
+ <Button onClick={() => void handleQuickstart()} size="default">
+ <Zap />
+ {copy.quickstartAction}
+ </Button>
+ </div>
+ </>
+ ) : null}
+
+ {lastError?.kind === 'quickstart' && !qJob && (
+ <p className="mt-4 text-[0.75rem] text-destructive">{lastError.error}</p>
+ )}
+ </div>
+ </div>
+ </SettingsContent>
+ )
+ }
+
+ // Up to date = the authority (status) says the configured tag is what's
+ // serving. Shown whenever true — not only right after an update.
+ const updateApplied =
+ status.runtime_installed && !status.update_available && status.tag === status.configured_tag
+
+ return (
+ <SettingsContent>
+ {/* ── Runtime ── */}
+ <SettingsSection
+ aside={
+ status.runtime_installed ? (
+ <Pill tone="primary">
+ {status.server_running ? copy.serverRunning : copy.runtimeReady(status.runtime_backend ?? '')}
+ </Pill>
+ ) : undefined
+ }
+ icon={Zap}
+ meta={status.tag}
+ title={copy.runtimeTitle}
+ >
+ {status.runtime_installed ? (
+ <ListRow
+ action={
+ status.server_running ? (
+ <Button
+ className={cn(serverBusy && '[&_svg]:animate-spin')}
+ disabled={serverBusy}
+ onClick={() => void handleServer('stop')}
+ size="sm"
+ variant="outline"
+ >
+ {serverBusy ? <Loader2 /> : <StopFilled />}
+ {copy.stopServer}
+ </Button>
+ ) : (
+ <Button
+ className={cn(serverBusy && '[&_svg]:animate-spin')}
+ disabled={serverBusy}
+ onClick={() => void handleServer('start')}
+ size="sm"
+ variant="outline"
+ >
+ {serverBusy ? <Loader2 /> : <Zap />}
+ {copy.startServer}
+ </Button>
+ )
+ }
+ description={
+ status.server_running
+ ? copy.runtimeRunningDetail
+ : copy.runtimeInstalledDetail(status.tag, status.runtime_backend ?? 'cpu')
+ }
+ title={copy.runtimeInstalled}
+ />
+ ) : rJob ? (
+ <ListRow
+ below={<ProgressBar percent={rJob.percent} />}
+ description={rJob.detail || copy.installing}
+ title={
+ <span className="inline-flex items-center gap-2">
+ <Loader2 className="size-3.5 animate-spin" />
+ {copy.installing}
+ </span>
+ }
+ />
+ ) : (
+ <ListRow
+ action={
+ <Button onClick={() => void handleInstallRuntime()} size="sm">
+ <Download />
+ {copy.installAction}
+ </Button>
+ }
+ description={copy.installDetail}
+ title={copy.installTitle}
+ />
+ )}
+
+ {status.update_available && !rJob && (
+ <ListRow
+ action={
+ <Button onClick={() => void handleInstallRuntime()} size="sm">
+ <Download />
+ {copy.updateAction}
+ </Button>
+ }
+ description={copy.updateDetail(status.configured_tag, status.tag)}
+ title={copy.updateTitle}
+ />
+ )}
+
+ {rJob && status.runtime_installed && (
+ <ListRow
+ below={<ProgressBar percent={rJob.percent} />}
+ description={rJob.detail || copy.updating}
+ title={
+ <span className="inline-flex items-center gap-2">
+ <Loader2 className="size-3.5 animate-spin" />
+ {copy.updating}
+ </span>
+ }
+ />
+ )}
+
+ {updateApplied && (
+ <ListRow
+ description={copy.upToDateDetail(status.tag, status.runtime_backend ?? 'cpu')}
+ title={
+ <span className="inline-flex items-center gap-2">
+ <CheckCircle2 className="size-4 text-emerald-600 dark:text-emerald-400" />
+ {copy.upToDateTitle}
+ </span>
+ }
+ />
+ )}
+
+ {lastError?.kind === 'runtime-install' && (
+ <p className="text-[0.75rem] text-destructive">{lastError.error}</p>
+ )}
+ </SettingsSection>
+
+ {/* ── This machine ── */}
+ <SettingsSection icon={Monitor} title={copy.hardwareTitle}>
+ {hardware ? (
+ <div className="flex flex-wrap items-center gap-x-5 gap-y-1 py-1 text-[length:var(--conversation-caption-font-size)] text-muted-foreground">
+ {hardware.gpu_name && (
+ <span className="inline-flex items-center gap-1.5">
+ <Zap className="size-3.5" />
+ {hardware.gpu_name}
+ </span>
+ )}
+
+ <span className="inline-flex items-center gap-1.5">
+ <Cpu className="size-3.5" />
+ {copy.vram(gbLabel(hardware.vram_total_bytes))}
+ </span>
+
+ <span className="inline-flex items-center gap-1.5">
+ <Package className="size-3.5" />
+ {copy.ram(gbLabel(hardware.ram_total_bytes))}
+ </span>
+
+ {hardware.uma && <Pill>{copy.unifiedMemory}</Pill>}
+ </div>
+ ) : (
+ <p className="py-1 text-[length:var(--conversation-caption-font-size)] text-muted-foreground">
+ {copy.hardwareLoading}
+ </p>
+ )}
+ </SettingsSection>
+
+ {/* ── Models ── */}
+ <SettingsSection icon={Download} meta={`${catalog.length}`} title={copy.modelsTitle}>
+ <div className="grid gap-1">
+ {sortedCatalog.map(model => {
+ const dJob = runningDownloadFor(jobs, model.id)
+ const anyDownloadRunning = jobs.some(j => j.kind === 'model-download' && j.status === 'running')
+ const activateTarget = model.downloaded_model_id ?? model.model_id
+ const isActive = Boolean(activateTarget && status.active_model_id === activateTarget)
+ const residency = activateTarget ? status.loaded_models[activateTarget] : undefined
+ const isLoaded = residency === 'loaded' || residency === 'ready'
+ const isLoadingNow = residency === 'loading'
+ const livePlacement = activateTarget ? status.placement?.[activateTarget] : undefined
+
+ const aJob = jobs.find(
+ j => j.kind === 'model-activate' && j.status === 'running' && j.model_id === activateTarget
+ )
+
+ const anyActivateRunning = jobs.some(j => j.kind === 'model-activate' && j.status === 'running')
+
+ return (
+ <ListRow
+ action={
+ model.downloaded ? (
+ <div className="flex items-center justify-end gap-2">
+ {isLoaded && livePlacement && (
+ <Tip
+ label={
+ livePlacement.spilled
+ ? copy.placementSpilledTip
+ : copy.placementResidentTip
+ }
+ >
+ <Pill tone={livePlacement.spilled ? 'warn' : 'success'}>
+ <Cpu className="mr-1 size-3" />
+ {livePlacement.granted_window_label ?? livePlacement.window_label ?? ''}
+ {' · '}
+ {livePlacement.spilled ? copy.placementSpilled : copy.placementResident}
+ </Pill>
+ </Tip>
+ )}
+ {isLoaded && !livePlacement && <Pill>{copy.loadedPill}</Pill>}
+
+ {isLoadingNow && (
+ <Pill>
+ <Loader2 className="mr-1 size-3 animate-spin" />
+ {copy.loadingPill}
+ </Pill>
+ )}
+
+ {isActive ? (
+ <Tip label={copy.activeDetail}>
+ <Pill tone="primary">
+ <Check className="mr-1 size-3" />
+ {copy.activePill}
+ </Pill>
+ </Tip>
+ ) : (
+ <Button
+ className={cn(aJob && '[&_svg]:animate-spin')}
+ disabled={anyActivateRunning}
+ onClick={() => void handleActivate(activateTarget ?? null, model.display_name)}
+ size="sm"
+ >
+ {aJob ? <Loader2 /> : <Check />}
+ {aJob ? copy.activating : copy.useAction}
+ </Button>
+ )}
+
+ {isLoaded && (
+ <Tip label={copy.ejectTip}>
+ <Button
+ onClick={() => void handleEject(activateTarget ?? model.id)}
+ size="icon"
+ variant="ghost"
+ >
+ <Eject />
+ </Button>
+ </Tip>
+ )}
+
+ <Tip label={copy.deleteAction}>
+ <Button
+ className={cn(deleting === model.id && '[&_svg]:animate-spin')}
+ onClick={() => void handleDelete(model.downloaded_model_id ?? model.id, model.id)}
+ size="icon"
+ variant="ghost"
+ >
+ {deleting === model.id ? <Loader2 /> : <Trash2 />}
+ </Button>
+ </Tip>
+ </div>
+ ) : dJob ? undefined : (
+ <Button
+ disabled={!model.fits || anyDownloadRunning || !status.runtime_installed}
+ onClick={() => void handleDownload(model)}
+ size="sm"
+ variant="outline"
+ >
+ <Download />
+ {copy.downloadAction(model.size_label)}
+ </Button>
+ )
+ }
+ below={
+ dJob ? (
+ <div className="mt-2 grid gap-1">
+ <ProgressBar percent={dJob.percent} />
+
- <p className="text-[0.68rem] text-muted-foreground">
- {!dJob.done_bytes && dJob.detail
- ? dJob.detail
- : copy.downloadProgress(gbLabel(dJob.done_bytes), gbLabel(dJob.total_bytes))}
- </p>
++ <div className="flex items-center justify-between gap-2">
++ <p className="text-[0.68rem] text-muted-foreground">
++ {dJob.status === 'paused' ? (
++ <>
++ {copy.downloadPausedLabel} ·{' '}
++ {copy.downloadProgress(gbLabel(dJob.done_bytes), gbLabel(dJob.total_bytes))}
++ </>
++ ) : !dJob.done_bytes && dJob.detail ? (
++ dJob.detail
++ ) : (
++ copy.downloadProgress(gbLabel(dJob.done_bytes), gbLabel(dJob.total_bytes))
++ )}
++ </p>
++
++ {dJob.kind === 'model-download' ? (
++ dJob.status === 'paused' ? (
++ <Button
++ onClick={() => void resumeLocalModelDownload(dJob.job_id).catch(err => notifyError(err, copy.downloadResumeAction))}
++ size="sm"
++ variant="ghost"
++ >
++ <Play />
++ {copy.downloadResumeAction}
++ </Button>
++ ) : (
++ <Button
++ onClick={() => void pauseLocalModelDownload(dJob.job_id).catch(err => notifyError(err, copy.downloadPauseAction))}
++ size="sm"
++ variant="ghost"
++ >
++ <Pause />
++ {copy.downloadPauseAction}
++ </Button>
++ )
++ ) : undefined}
++ </div>
+ </div>
+ ) : undefined
+ }
+ description={
+ <>
+ {model.description}
+
+ <span className="mt-1.5 flex flex-wrap items-center gap-1.5">
+ {/* Memory: the traffic light. Green = runs fully on
+ the GPU; amber = spills to system RAM (works,
+ slower); red = doesn't fit this machine at all.
+ Detail prose lives in the tooltip. */}
+ {!model.fits ? (
+ <Tip label={model.fit_detail ?? model.fit_summary}>
+ <Pill tone="destructive">
+ <Cpu className="mr-1 size-3" />
+ {copy.pillTooBig}
+ </Pill>
+ </Tip>
+ ) : model.spilled ? (
+ <Tip label={model.quant_reason ?? model.fit_summary}>
+ <Pill tone="warn">
+ <Cpu className="mr-1 size-3" />
+ {copy.pillUsesRam}
+ </Pill>
+ </Tip>
+ ) : (
+ <Tip label={model.quant_reason ?? model.fit_summary}>
+ <Pill tone="success">
+ <Cpu className="mr-1 size-3" />
+ {copy.pillFitsGpu}
+ </Pill>
+ </Tip>
+ )}
+
+ {/* Context: one pill. Green 'Full X context' only when
+ the model earned its complete window resident on the
+ GPU — a big context served from system RAM is slow,
+ and a green badge there would sell exactly the wrong
+ model, so a spilled full window goes gray. Anything
+ starting below its native window gets one quiet
+ 'Up to' pill instead of a start/grow pair. */}
+ {model.fits && model.start_window_label && (
+ model.start_window && model.start_window >= model.native_context ? (
+ <Tip label={copy.pillFullContextTip}>
+ <Pill tone={model.spilled ? 'muted' : 'success'}>
+ {copy.pillFullContext(model.native_context_label)}
+ </Pill>
+ </Tip>
+ ) : (
+ <Tip label={copy.pillGrowsTip}>
+ <Pill>{copy.pillUpTo(model.native_context_label)}</Pill>
+ </Tip>
+ )
+ )}
+
+ {!model.fits && (
+ <Pill>{copy.pillUpTo(model.native_context_label)}</Pill>
+ )}
+
+ {model.vision && <Pill>{copy.pillVision}</Pill>}
+ </span>
+
+ {isActive && !isLoaded && !isLoadingNow && status.server_running && (
+ <span className="mt-0.5 block text-(--ui-text-tertiary)">{copy.activeNotLoaded}</span>
+ )}
+ </>
+ }
+ key={model.id}
+ title={
+ <span className="inline-flex items-center gap-2">
+ {model.display_name}
+
+ {model.recommended && <Pill tone="primary">{copy.recommended}</Pill>}
+ </span>
+ }
+ />
+ )
+ })}
+
+ {status.models
+ .filter(m => !catalog.some(c => c.downloaded_model_id === m.id || c.model_id === m.id))
+ .map(m => {
+ const isActive = status.active_model_id === m.id
+ const residency = status.loaded_models[m.id]
+ const isLoaded = residency === 'loaded' || residency === 'ready'
+ const isLoadingNow = residency === 'loading'
+ const livePlacement = status.placement?.[m.id]
+
+ const aJob = jobs.find(
+ j => j.kind === 'model-activate' && j.status === 'running' && j.model_id === m.id
+ )
+
+ const anyActivateRunning = jobs.some(j => j.kind === 'model-activate' && j.status === 'running')
+
+ return (
+ <ListRow
+ action={
+ <div className="flex items-center justify-end gap-2">
+ {isLoaded && livePlacement && (
+ <Tip
+ label={livePlacement.spilled ? copy.placementSpilledTip : copy.placementResidentTip}
+ >
+ <Pill tone={livePlacement.spilled ? 'warn' : 'success'}>
+ <Cpu className="mr-1 size-3" />
+ {livePlacement.granted_window_label ?? livePlacement.window_label ?? ''}
+ {' · '}
+ {livePlacement.spilled ? copy.placementSpilled : copy.placementResident}
+ </Pill>
+ </Tip>
+ )}
+ {isLoaded && !livePlacement && <Pill>{copy.loadedPill}</Pill>}
+
+ {isLoadingNow && (
+ <Pill>
+ <Loader2 className="mr-1 size-3 animate-spin" />
+ {copy.loadingPill}
+ </Pill>
+ )}
+
+ {isActive ? (
+ <Pill tone="primary">
+ <CheckCircle2 className="mr-1 size-3" />
+ {copy.activePill}
+ </Pill>
+ ) : (
+ <Button
+ className={cn(aJob && '[&_svg]:animate-spin')}
+ disabled={anyActivateRunning}
+ onClick={() => void handleActivate(m.id, m.id)}
+ size="sm"
+ >
+ {aJob ? <Loader2 /> : <Check />}
+ {copy.useAction}
+ </Button>
+ )}
+
+ {isLoaded && (
+ <Tip label={copy.ejectTip}>
+ <Button onClick={() => void handleEject(m.id)} size="icon" variant="ghost">
+ <Eject />
+ </Button>
+ </Tip>
+ )}
+
+ <Tip label={copy.deleteAction}>
+ <Button
+ className={cn(deleting === m.id && '[&_svg]:animate-spin')}
+ onClick={() => void handleDelete(m.id, m.id)}
+ size="icon"
+ variant="ghost"
+ >
+ {deleting === m.id ? <Loader2 /> : <Trash2 />}
+ </Button>
+ </Tip>
+ </div>
+ }
+ description={<span>{copy.addedByYou}</span>}
+ key={m.id}
+ title={
+ <span className="inline-flex items-center gap-2">
+ <span className="truncate font-mono text-[0.8rem]">{m.id}</span>
+
+ <span className="text-[0.68rem] font-normal text-muted-foreground">{m.size_label}</span>
+ </span>
+ }
+ />
+ )
+ })}
+ </div>
+
+ {lastError?.kind === 'model-download' && (
+ <p className="text-[0.75rem] text-destructive">{lastError.error}</p>
+ )}
+ </SettingsSection>
+
+ <BrowseSection onChanged={refresh} />
+ </SettingsContent>
+ )
+ }
+
+ function fitTone(fit: HFFileGroup['fit']): 'destructive' | 'muted' | 'success' | 'warn' {
+ if (fit === 'fits-gpu') {
+ return 'success'
+ }
+
+ if (fit === 'needs-ram') {
+ return 'warn'
+ }
+
+ if (fit === 'too-big') {
+ return 'destructive'
+ }
+
+ return 'muted'
+ }
+
+ function browsedModelId(group: HFFileGroup): string {
+ // Mirrors the backend's derivation: first file's name, split-part
+ // suffix stripped — the id the download job carries.
+ const first = group.paths[0].split('/').pop() ?? group.paths[0]
+
+ return first.replace(/-\d{5}-of-\d{5}\.gguf$/i, '').replace(/\.gguf$/i, '')
+ }
+
+ function BrowseSection({ onChanged }: { onChanged: () => void }) {
+ const { t } = useI18n()
+ const copy = t.settings.localModels
+ const jobs = useStore($localRuntimeJobs)
+ const [query, setQuery] = useState('')
+ const [hits, setHits] = useState<HFSearchHit[]>([])
+ const [searching, setSearching] = useState(false)
+ const [openRepo, setOpenRepo] = useState<null | string>(null)
+ const [files, setFiles] = useState<HFFileGroup[]>([])
+ const [listing, setListing] = useState(false)
+ const [error, setError] = useState<null | string>(null)
+ // Guard against the past: a stale search result must never overwrite a
+ // newer query's hits (the desktop guide's out-of-order rule).
+ const searchSeq = useRef(0)
+
+ useEffect(() => {
+ const q = query.trim()
+
+ if (q.length < 2) {
+ setHits([])
+ setSearching(false)
+
+ return
+ }
+
+ const seq = ++searchSeq.current
+ setSearching(true)
+
+ const handle = setTimeout(() => {
+ searchHFModels(q)
+ .then(r => {
+ if (searchSeq.current === seq) {
+ setHits(r.hits)
+ setError(null)
+ }
+ })
+ .catch((e: Error) => {
+ if (searchSeq.current === seq) {
+ setError(e.message)
+ }
+ })
+ .finally(() => {
+ if (searchSeq.current === seq) {
+ setSearching(false)
+ }
+ })
+ }, 350)
+
+ return () => clearTimeout(handle)
+ }, [query])
+
+ const openFiles = useCallback((repo: string) => {
+ setOpenRepo(repo)
+ setFiles([])
+ setListing(true)
+ listHFRepoFiles(repo)
+ .then(r => setFiles(r.files))
+ .catch((e: Error) => setError(e.message))
+ .finally(() => setListing(false))
+ }, [])
+
+ const startBrowsedDownload = useCallback(
+ (repo: string, group: HFFileGroup) => {
+ downloadBrowsedModel(repo, group.paths)
+ .then(r => {
+ if (r.already_downloaded) {
+ notify({ durationMs: 3_000, kind: 'info', message: copy.browseAlreadyDownloaded, title: copy.browseTitle })
+
+ return
+ }
+
+ // Same feedback loop as catalog downloads: the job store polls
+ // and the tile renders live progress from it.
+ watchLocalRuntimeJobs()
+ notify({
+ durationMs: 3_000,
+ kind: 'info',
+ message: copy.browseDownloadStarted.replace('{name}', r.model_id),
+ title: copy.browseTitle
+ })
+ onChanged()
+ })
+ .catch((e: Error) => notifyError(e, copy.browseTitle))
+ },
+ [copy.browseAlreadyDownloaded, copy.browseDownloadStarted, copy.browseTitle, onChanged]
+ )
+
+ const sideload = useCallback(() => {
+ window.hermesDesktop
+ .selectPaths({ filters: [{ extensions: ['gguf'], name: 'GGUF models' }], title: copy.sideloadTitle })
+ .then(paths => {
+ if (!paths.length) {
+ return
+ }
+
+ return sideloadLocalModel(paths[0]).then(r => {
+ notify({
+ durationMs: 3_000,
+ kind: 'success',
+ message: r.already_present ? copy.sideloadAlreadyPresent : copy.sideloadDone.replace('{name}', r.model_id),
+ title: copy.browseTitle
+ })
+ onChanged()
+ })
+ })
+ .catch((e: Error) => notifyError(e, copy.browseTitle))
+ }, [copy.browseTitle, copy.sideloadAlreadyPresent, copy.sideloadDone, copy.sideloadTitle, onChanged])
+
+ return (
+ <SettingsSection
+ aside={
+ <Button onClick={sideload} size="sm" variant="outline">
+ <FolderOpen className="mr-1 size-3.5" />
+ {copy.sideloadButton}
+ </Button>
+ }
+ icon={Search}
+ title={copy.browseTitle}
+ >
+ <p className="text-[0.75rem] text-muted-foreground">{copy.browseHint}</p>
+
+ <div className="relative">
+ <Search className="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />
+ <input
+ className="w-full rounded-md border border-(--ui-border) bg-transparent py-1.5 pl-8 pr-3 text-[0.8rem] outline-none placeholder:text-muted-foreground focus:border-primary"
+ onChange={e => setQuery(e.target.value)}
+ placeholder={copy.browsePlaceholder}
+ value={query}
+ />
+ </div>
+
+ {searching && (
+ <p className="flex items-center gap-2 text-[0.75rem] text-muted-foreground">
+ <Loader2 className="size-3 animate-spin" />
+ {copy.browseSearching}
+ </p>
+ )}
+
+ {error && <p className="text-[0.75rem] text-destructive">{error}</p>}
+
+ <div className="grid gap-1">
+ {hits.map(hit => (
+ <div key={hit.repo}>
+ <ListRow
+ action={
+ <Button onClick={() => openFiles(hit.repo)} size="sm" variant="ghost">
+ {openRepo === hit.repo ? copy.browseRefresh : copy.browseShowFiles}
+ </Button>
+ }
+ description={
+ <span>
+ {Intl.NumberFormat().format(hit.downloads)} {copy.browseDownloads}
+ {' · '}
+ {Intl.NumberFormat().format(hit.likes)} {copy.browseLikes}
+ {hit.gated ? ` · ${copy.browseGated}` : ''}
+ </span>
+ }
+ title={<span className="font-mono text-[0.8rem]">{hit.repo}</span>}
+ />
+
+ {openRepo === hit.repo && (
+ <div className="ml-4 grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-1.5 border-l border-(--ui-border) py-1 pl-3">
+ {listing && (
+ <p className="col-span-full flex items-center gap-2 py-1 text-[0.75rem] text-muted-foreground">
+ <Loader2 className="size-3 animate-spin" />
+ {copy.browseListing}
+ </p>
+ )}
+
+ {!listing && files.length === 0 && (
+ <p className="col-span-full py-1 text-[0.75rem] text-muted-foreground">{copy.browseNoGguf}</p>
+ )}
+
+ {files.map(group => {
+ const dJob = runningDownloadFor(jobs, browsedModelId(group))
+
+ return (
+ <div
+ className={cn(
+ 'flex flex-col gap-1 rounded-md border border-(--ui-border) px-2.5 py-1.5',
+ group.fit === 'too-big' && 'opacity-45'
+ )}
+ key={group.label}
+ >
+ <span className="flex w-full items-center justify-between gap-2">
+ <span className="truncate font-mono text-[0.75rem]">
+ {group.label}
+ {group.paths.length > 1 ? ` ×${group.paths.length}` : ''}
+ </span>
+
+ <Button
+ aria-label={copy.browseDownloadAria.replace('{name}', group.label)}
+ className="h-6 shrink-0 px-2"
+ disabled={group.fit === 'too-big' || Boolean(dJob)}
+ onClick={() => startBrowsedDownload(hit.repo, group)}
+ size="sm"
+ variant="ghost"
+ >
+ {dJob ? <Loader2 className="size-3.5 animate-spin" /> : <Download className="size-3.5" />}
+ </Button>
+ </span>
+
+ {dJob ? (
+ <>
+ <ProgressBar percent={dJob.percent} />
+
+ <span className="text-[0.68rem] text-muted-foreground">
+ {!dJob.done_bytes && dJob.detail
+ ? dJob.detail
+ : copy.downloadProgress(gbLabel(dJob.done_bytes), gbLabel(dJob.total_bytes))}
+ </span>
+ </>
+ ) : (
+ <span className="flex items-center justify-between gap-2">
+ <Pill tone={fitTone(group.fit)}>
+ <Cpu className="mr-1 size-3" />
+ {group.fit === 'fits-gpu'
+ ? copy.pillFitsGpu
+ : group.fit === 'needs-ram'
+ ? copy.pillUsesRam
+ : group.fit === 'too-big'
+ ? copy.pillTooBig
+ : copy.browseFitUnknown}
+ </Pill>
+
+ <span className="shrink-0 text-[0.7rem] text-muted-foreground">{gbLabel(group.total_bytes)}</span>
+ </span>
+ )}
+ </div>
+ )
+ })}
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ </SettingsSection>
+ )
+ }
diff --cc apps/desktop/src/global.d.ts
index 1ea6a627d43,d3d00e635f6..0f7de789be1
--- a/apps/desktop/src/global.d.ts
+++ b/apps/desktop/src/global.d.ts
@@@ -299,7 -300,18 +300,19 @@@ declare global
setDisableF12?: (blocked: boolean) => void
setPreviewShortcutActive?: (active: boolean) => void
openExternal: (url: string) => Promise<void>
+ onExternalOpenFailed?: (callback: (payload: ExternalOpenFailedPayload) => void) => () => void
+ /** One-shot loopback callback listener for MCP OAuth against remote
+ * backends (electron/mcp-oauth-callback-ipc.ts): bind on THIS machine,
+ * pass redirectUri as client_redirect_uri to mcp.servers.oauth.start,
+ * await the provider redirect, relay code/state via oauth.callback. */
+ mcpOauth?: {
+ listen: () => Promise<{ id: string; redirectUri: string }>
+ wait: (
+ id: string,
+ timeoutMs?: number
+ ) => Promise<{ code: null | string; error: null | string; state: null | string }>
+ cancel: (id: string) => Promise<boolean>
+ }
openPreviewInBrowser?: (url: string) => Promise<void>
fetchLinkTitle: (url: string) => Promise<string>
/** A site's icon as a data URL, or '' when it has none we can read.
diff --cc apps/desktop/src/i18n/ar.ts
index 4bb839974d7,6dc8da5d494..4994a2c8768
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@@ -1983,42 -2009,6 +1984,41 @@@ export const ar = defineLocale(
tryAgain: 'إعادة المحاولة',
notAvailableTitle: 'التحديث غير متاح',
unsupportedMessage: 'لا يمكن لهذا الإصدار من Hermes تحديث نفسه من داخل التطبيق.',
+ appName: 'Hermes Desktop',
+ version: value => `الإصدار ${value}`,
+ versionUnavailable: 'الإصدار غير متاح',
+ bundleOutOfSync: 'إصدار التطبيق قديم',
+ bundleOutOfSyncDesc:
+ 'تم تحديث وقت تشغيل Hermes، لكن تطبيق سطح المكتب نفسه لا يزال إصدارًا قديمًا — لن تظهر ميزات الواجهة الجديدة (مثل Bot Mode) حتى يتم تحديث التطبيق. شغّل التحديث أدناه لإعادة بناء التطبيق. إذا لم يختفِ هذا التحذير، فأعد التثبيت من أحدث مثبّت لسطح المكتب.',
+ bundleOutOfSyncAction: 'الحصول على المثبّت',
- updatesSection: 'التحديثات',
+ checkNow: 'التحقق الآن',
+ checkingShort: 'جار التحقق...',
+ seeWhatsNew: 'عرض الجديد',
+ releaseNotes: 'ملاحظات الإصدار',
+ installing: 'جار التثبيت...',
+ cantReach: 'تعذر الوصول لخدمة التحديث',
+ tapCheck: 'اضغط للتحقق من التحديثات.',
+ updateReady: count => `${count} تحديث متاح`,
+ updateReadyUnknown: 'تحديث جديد جاهز.',
+ lastChecked: age => `آخر تحقق ${age}`,
+ justNowSuffix: 'الآن',
+ never: 'أبدا',
+ justNow: 'الآن',
+ minAgo: count => `قبل ${count} دقيقة`,
+ hoursAgo: count => `قبل ${count} ساعة`,
+ daysAgo: count => `قبل ${count} يوم`,
+ versionDetailsTitle: 'تفاصيل الإصدار',
+ versionDetailsBody: 'هذا التثبيت مُدار خارج التطبيق. حدّثه بالطريقة نفسها التي استخدمتها لتثبيته.',
+ versionDetailsVersion: 'الإصدار',
+ versionDetailsCommit: 'الالتزام',
+ versionDetailsBuildOrigin: 'مصدر البناء',
+ versionDetailsDistribution: 'التوزيع',
+ versionDetailsDistributionDesktop: 'تطبيق سطح المكتب',
+ versionDetailsRuntimeEmbedded: 'وقت تشغيل مضمّن',
+ versionDetailsRuntimeExternal: 'خارجي (يستخدم وقت تشغيل الجهاز)',
+ versionDetailsRuntime: 'وقت التشغيل',
+ versionDetailsInstallId: 'معرّف التثبيت',
+ versionDetailsUncommittedChanges: '(+ تغييرات غير ملتزمة)',
connectionRetry: 'تحقق من اتصالك وأعد المحاولة.',
latestBody: 'أنت تستخدم أحدث إصدار.',
latestBodyBackend: 'الواجهة الخلفية تعمل بأحدث إصدار.',
@@@ -2028,7 -2018,6 +2028,7 @@@
availableTitleBackend: 'يتوفر تحديث للواجهة الخلفية',
availableBodyBackend: 'إصدار أحدث من واجهة Hermes الخلفية المتصلة جاهز للتثبيت.',
availableBodyNoChangelog: 'إصدار أحدث جاهز. ملاحظات الإصدار غير متاحة لنوع التثبيت هذا.',
- availableBodyRelease: tag => `Hermes ${tag} جاهز للتثبيت.`,
++ availableBodyRelease: (tag: string) => `Hermes ${tag} جاهز للتثبيت.`,
updateNow: 'التحديث الآن',
maybeLater: 'ربما لاحقا',
moreChanges: count => `+ ${count} تغيير${count === 1 ? '' : 'ات'} إضافي مُضمَّن.`,
diff --cc apps/desktop/src/i18n/en.ts
index d318b5c35fd,601c3819af1..7f348973cf1
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@@ -3,6 -3,6 +3,12 @@@ import { FIELD_DESCRIPTIONS, FIELD_LABE
import type { Translations } from './types'
export const en: Translations = {
++ externalOpenFailed: {
++ title: 'Couldn’t open this link',
++ message: 'No browser is registered to open this address. Copy the link and open it manually.',
++ copyUrl: 'Copy link',
++ close: 'Close'
++ },
common: {
apply: 'Apply',
back: 'Back',
@@@ -100,6 -100,6 +106,9 @@@
back: 'Back',
openLogs: 'Open logs',
repairHint: 'Repair re-runs the installer and can take a few minutes on a fresh machine.',
++ bundledReinstallHint:
++ 'This bundled install can’t repair itself from inside the app — reinstall the app to restore its backend.',
++ reinstallApp: 'Reinstall the app',
remoteSignInHint: signInLabel =>
`Signs out of the saved remote browser session, then opens ${signInLabel}. Use local gateway to switch to the bundled backend instead.`,
signOutAndSignIn: 'Sign out & sign in',
@@@ -688,6 -687,6 +698,7 @@@
tapCheck: 'Tap "Check now" to look for updates.',
updateReady: count => `A new update is ready (${count} change${count === 1 ? '' : 's'} included).`,
updateReadyUnknown: 'A new update is ready.',
++ availableBodyRelease: tag => `Version ${tag} is ready to install.`,
lastChecked: age => `Last checked ${age}`,
justNowSuffix: ' · just now',
automaticUpdates: 'Automatic updates',
@@@ -1113,6 -1112,108 +1124,111 @@@
curator: { label: 'Curator', hint: 'Skill-usage review' }
}
},
+ localModels: {
+ title: 'Local Models',
+ runtimeTitle: 'Local runtime',
+ runtimeReady: backend => `Ready · ${backend}`,
+ serverRunning: 'Running',
+ runtimeInstalled: 'llama.cpp runtime installed',
+ runtimeInstalledDetail: (tag, backend) =>
+ `Build ${tag}, ${backend} backend. Hermes starts and manages the server for you.`,
+ installTitle: 'Install the local runtime',
+ installDetail:
+ 'Downloads the llama.cpp inference engine (a few hundred MB). Models you download run entirely on this machine — no account, nothing leaves your computer.',
+ installAction: 'Install runtime',
+ installing: 'Installing runtime…',
+ installFailed: 'Runtime install failed',
+ hardwareTitle: 'This machine',
+ hardwareLoading: 'Checking your hardware…',
+ vram: label => `${label} GPU memory`,
+ ram: label => `${label} RAM`,
+ unifiedMemory: 'Unified memory',
+ modelsTitle: 'Models',
+ recommended: 'Recommended',
+ downloaded: 'Downloaded',
+ downloadAction: size => `Download · ${size}`,
+ 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',
+ quickstartDetail: (model, size) =>
+ `One click sets everything up: the local engine, ${model} (${size} download), and your default for new chats. Nothing leaves this computer.`,
+ quickstartDetailReady: model => `One click makes ${model} your default for new chats. Everything runs on this machine.`,
+ quickstartAction: 'Set up for me',
+ quickstartConfigure: 'Configure…',
+ quickstartDoneToast: model => `${model} is set up — new chats run on this machine.`,
+ quickstartFailed: 'Local model setup failed',
+ quickstartStageEngine: 'Engine',
+ quickstartStageModel: 'Model',
+ quickstartStageFinish: 'Finish',
+ useAction: 'Use',
+ activePill: 'Default',
+ updateTitle: 'Engine update available',
+ updateDetail: (next, current) => `A newer llama.cpp build (${next}) is ready to install — you're on ${current}. Models keep working during the download.`,
+ updateAction: 'Update engine',
+ updating: 'Updating engine…',
+ upToDateTitle: 'Engine up to date',
+ upToDateDetail: (tag, backend) => `Running llama.cpp ${tag} (${backend}) — the latest build Hermes ships.`,
+ updateToast: next => `A newer local engine build (${next}) is available. Update from Settings → Local Models.`,
+ activeDetail: 'New chats use this model — it loads when you send your first message',
+ activeNotLoaded: 'Loads on your first message',
+ loadedPill: 'In memory',
+ placementResident: 'all on GPU',
+ placementSpilled: 'partly in RAM',
+ placementResidentTip: 'Running entirely in GPU memory at this context window — full speed.',
+ placementSpilledTip:
+ 'Part of this model runs from system RAM — it works, but slower. A more compact build or a smaller context would fit fully.',
+ loadingPill: 'Loading…',
+ ejectTip: 'Free GPU memory (loads again on the next message)',
+ ejected: 'Model unloaded — GPU memory freed.',
+ ejectFailed: 'Could not unload the model',
+ stopServer: 'Turn off',
+ startServer: 'Turn on',
+ runtimeRunningDetail: 'The local server is running. Turning it off frees all GPU memory and stops new chats from using local models until you turn it back on.',
+ serverStopped: 'Local server stopped — GPU memory freed.',
+ serverStarted: 'Local server running.',
+ serverStopFailed: 'Could not stop the local server',
+ serverStartFailed: 'Could not start the local server',
+ activating: 'Starting…',
+ activateFailed: model => `Could not switch to ${model}`,
+ activateDoneToast: model => `New chats use ${model}.`,
+ downloadFailed: model => `Download of ${model} failed`,
+ pillFitsGpu: 'Fits your GPU',
+ pillUsesRam: 'Uses system RAM',
+ pillTooBig: 'Too big for this machine',
+ browseTitle: 'Find more models',
+ browseHint: 'Search all of Hugging Face. Models you download here are sized to your machine automatically, but not tested by us.',
+ browsePlaceholder: 'Search models by name or author…',
+ browseSearching: 'Searching Hugging Face',
+ browseListing: 'Reading model files',
+ browseShowFiles: 'Show files',
+ browseRefresh: 'Refresh',
+ browseDownloads: 'downloads',
+ browseLikes: 'likes',
+ browseGated: 'requires Hugging Face sign-in',
+ browseNoGguf: 'No compatible model files found.',
+ browseFitUnknown: 'Fit unknown',
+ browseAlreadyDownloaded: 'Already downloaded.',
+ addedByYou: 'Added by you',
+ browseDownloadStarted: 'Downloading {name}',
+ browseDownloadAria: 'Download {name}',
+ sideloadButton: 'Add model file',
+ sideloadTitle: 'Choose a GGUF model file',
+ sideloadDone: 'Added {name}.',
+ sideloadAlreadyPresent: 'Already in your library.',
+ pillFullContext: max => `Full ${max} context`,
+ pillFullContextTip: "Runs at the model's complete context window from the start",
+ pillUpTo: max => `Up to ${max} context`,
+ pillGrowsTip: 'Grows automatically as your conversation needs more room',
+ pillVision: 'Sees images',
+ deleteAction: 'Delete model',
+ deleteConfirm: model => `Delete ${model} from disk?`,
+ deleted: model => `${model} deleted.`,
+ deleteFailed: 'Delete failed'
+ },
providers: {
connectAccount: 'Connect an account',
haveApiKey: 'Have an API key instead?',
@@@ -2653,7 -2757,7 +2780,47 @@@
notAvailable: 'Update not available for this backend.',
failed: 'Backend update failed.',
noReturn: 'Backend didn’t come back online. The update may not have completed — check the backend host.'
-- }
++ },
++ // Update-status overlay + version-details (mechanism-aware update UI).
++ appName: 'Hermes',
++ version: (value: string) => `Version ${value}`,
++ versionUnavailable: 'Version unavailable',
++ checkNow: 'Check now',
++ seeWhatsNew: "See what's new",
++ releaseNotes: 'Release notes',
++ onLatest: "You're on the latest version.",
++ installing: 'An update is currently installing.',
++ cantReach: "We couldn't reach the update server.",
++ tapCheck: 'Tap "Check now" to look for updates.',
++ updateReady: count => `A new update is ready (${count} change${count === 1 ? '' : 's'} included).`,
++ updateReadyUnknown: 'A new update is ready.',
++ availableBodyRelease: tag => `Version ${tag} is ready to install.`,
++ lastChecked: age => `Last checked ${age}`,
++ never: 'never',
++ justNow: 'just now',
++ minAgo: count => `${count} min ago`,
++ hoursAgo: count => `${count}h ago`,
++ daysAgo: count => `${count}d ago`,
++ justNowSuffix: ' · just now',
++ bundleOutOfSync: 'App build out of date',
++ bundleOutOfSyncDesc:
++ 'The Hermes runtime was updated, but the desktop app itself is still an older build. Update it to pick up the latest fixes.',
++ bundleOutOfSyncAction: 'Get the installer',
++ checkingShort: 'Checking…',
++ releaseAvailable: tag => `Version ${tag} is available.`,
++ versionDetailsTitle: 'Version details',
++ versionDetailsBody:
++ 'This install is managed outside the app. Update it the same way you installed it.',
++ versionDetailsVersion: 'Version',
++ versionDetailsCommit: 'Commit',
++ versionDetailsBuildOrigin: 'Build Origin',
++ versionDetailsDistribution: 'Distribution',
++ versionDetailsDistributionDesktop: 'Desktop app (MSIX)',
++ versionDetailsRuntime: 'Runtime',
++ versionDetailsRuntimeEmbedded: 'Embedded runtime',
++ versionDetailsRuntimeExternal: 'External (uses the machine runtime)',
++ versionDetailsInstallId: 'Install ID',
++ versionDetailsUncommittedChanges: 'uncommitted changes'
},
install: {
@@@ -2675,11 -2779,11 +2842,20 @@@
setupChoiceTitle: 'Set up Hermes Desktop',
setupChoiceDesc:
'Connect this app to a Hermes gateway you already run, or install Hermes locally on this computer.',
++ setupChoiceDescLocal:
++ 'Install Hermes on this computer, or connect to a Hermes gateway you already run.',
connectExistingTitle: 'Connect to existing Hermes',
connectExistingShort: 'Connect existing',
connectExistingDesc: 'Use a remote backend with a session token or browser sign-in. No local install will start.',
installLocalTitle: 'Install Hermes locally',
installLocalDesc: 'Download Hermes, create its Python environment, and run the backend on this computer.',
++ useLocalTitle: 'Use Hermes on this computer',
++ useLocalDesc: 'A Hermes runtime is already installed here — start it with one click. Nothing downloads.',
++ bundledLocalDesc: 'Use the Hermes runtime included with this app — the bundled backend is the local install.',
++ bundledDamagedTitle: 'Use Hermes bundled with this app',
++ bundledDamagedDesc:
++ "The Hermes backend bundled with this app is missing or damaged — reinstall the app to restore it.",
++ reinstallApp: 'Reinstall the app',
localStartUnavailable: 'Local installation could not start. Restart Hermes Desktop and try again.',
remoteSetupTitle: 'Connect to existing Hermes',
remoteSetupDesc: 'Enter your gateway URL. Hermes Desktop will detect whether it needs a token or browser sign-in.',
@@@ -2889,6 -2998,6 +3070,7 @@@
update: 'update',
updateInProgress: 'Update in progress',
commitsBehind: (count, branch) => `${count} commit${count === 1 ? '' : 's'} behind ${branch}`,
++ releaseAvailable: (tag: string) => `Version ${tag} is available.`,
desktopVersion: version => `Hermes Desktop v${version}`,
backendVersion: version => `Backend v${version}`,
clientLabel: version => `client v${version}`,
diff --cc apps/desktop/src/i18n/ja.ts
index e2d47a65881,0691a435ca7..5a2f2f79bbc
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@@ -3,6 -3,6 +3,12 @@@ import { defineFieldCopy } from '@/app/
import { defineLocale } from './define-locale'
export const ja = defineLocale({
++ externalOpenFailed: {
++ title: 'このリンクを開けませんでした',
++ message: 'このアドレスを開くブラウザが登録されていません。リンクをコピーして手動で開いてください。',
++ copyUrl: 'リンクをコピー',
++ close: '閉じる'
++ },
common: {
apply: '適用',
back: '戻る',
@@@ -1015,6 -1016,96 +1022,99 @@@
curator: { label: 'キュレーター', hint: 'スキル使用レビュー' }
}
},
+ localModels: {
+ title: 'ローカルモデル',
+ runtimeTitle: 'ローカルランタイム',
+ runtimeReady: backend => `準備完了 · ${backend}`,
+ serverRunning: '実行中',
+ runtimeInstalled: 'llama.cpp ランタイムをインストール済み',
+ runtimeInstalledDetail: (tag, backend) =>
+ `ビルド ${tag}、${backend} バックエンド。サーバーは Hermes が起動・管理します。`,
+ installTitle: 'ローカルランタイムをインストール',
+ installDetail:
+ 'llama.cpp 推論エンジン(数百 MB)をダウンロードします。ダウンロードしたモデルはすべてこのマシン上で動作します——アカウント不要、データが外部に送られることはありません。',
+ installAction: 'ランタイムをインストール',
+ installing: 'ランタイムをインストール中…',
+ installFailed: 'ランタイムのインストールに失敗しました',
+ hardwareTitle: 'このマシン',
+ hardwareLoading: 'ハードウェアを確認中…',
+ vram: label => `GPU メモリ ${label}`,
+ ram: label => `RAM ${label}`,
+ unifiedMemory: 'ユニファイドメモリ',
+ modelsTitle: 'モデル',
+ recommended: 'おすすめ',
+ downloaded: 'ダウンロード済み',
+ downloadAction: size => `ダウンロード · ${size}`,
+ downloadProgress: (done, total) => `${done} / ${total}`,
++ downloadPausedLabel: '一時停止中',
++ downloadPauseAction: '一時停止',
++ downloadResumeAction: '再開',
+ downloadDoneToast: model => `${model} の準備ができました。`,
+ installDoneToast: 'ローカルランタイムのインストールが完了しました。',
+ useAction: '使用する',
+ activePill: 'デフォルト',
+ updateTitle: 'エンジンの更新があります',
+ updateDetail: (next, current) => `新しい llama.cpp ビルド(${next})をインストールできます——現在は ${current} です。ダウンロード中もモデルは引き続き使えます。`,
+ updateAction: 'エンジンを更新',
+ updating: 'エンジンを更新中…',
+ upToDateTitle: 'エンジンは最新です',
+ upToDateDetail: (tag, backend) => `llama.cpp ${tag}(${backend})で動作中——Hermes が提供する最新ビルドです。`,
+ updateToast: next => `ローカルエンジンの新しいビルド(${next})があります。設定 → ローカルモデル から更新できます。`,
+ activeDetail: '新しいチャットはこのモデルを使用——最初のメッセージ送信時に読み込みます',
+ activeNotLoaded: '最初のメッセージで読み込みます',
+ loadedPill: '読み込み済み',
+ placementResident: 'すべて GPU 上',
+ placementSpilled: '一部 RAM 上',
+ placementResidentTip: 'このコンテキストウィンドウで GPU メモリ内で完全に動作しています — フルスピード。',
+ placementSpilledTip: 'モデルの一部がシステム RAM から動作しています — 動作しますが遅くなります。よりコンパクトなビルドか小さいコンテキストなら完全に収まります。',
+ loadingPill: '読み込み中…',
+ ejectTip: 'GPU メモリを解放(必要時に再読み込み)',
+ ejected: 'モデルをアンロードしました——GPU メモリを解放しました。',
+ ejectFailed: 'モデルをアンロードできませんでした',
+ stopServer: 'オフにする',
+ startServer: 'オンにする',
+ runtimeRunningDetail: 'ローカルサーバーが実行中です。オフにすると GPU メモリを全て解放し、再度オンにするまで新しいチャットはローカルモデルを使用しません。',
+ serverStopped: 'ローカルサーバーを停止しました——GPU メモリを解放しました。',
+ serverStarted: 'ローカルサーバー実行中。',
+ serverStopFailed: 'ローカルサーバーを停止できませんでした',
+ serverStartFailed: 'ローカルサーバーを起動できませんでした',
+ activating: '起動中…',
+ activateFailed: model => `${model} への切り替えに失敗しました`,
+ activateDoneToast: model => `新しいチャットは ${model} を使用します。`,
+ downloadFailed: model => `${model} のダウンロードに失敗しました`,
+ pillFitsGpu: 'GPU に完全に収まります',
+ pillUsesRam: 'システム RAM を使用',
+ pillTooBig: 'このマシンには大きすぎます',
+ browseTitle: 'さらにモデルを探す',
+ browseHint: 'Hugging Face 全体を検索できます。ここでダウンロードしたモデルは自動でマシンに合わせて動作しますが、当方でのテストは行われていません。',
+ browsePlaceholder: 'モデル名または作者で検索…',
+ browseSearching: 'Hugging Face を検索中',
+ browseListing: 'モデルファイルを読み込み中',
+ browseShowFiles: 'ファイルを表示',
+ browseRefresh: '更新',
+ browseDownloads: 'ダウンロード',
+ browseLikes: 'いいね',
+ browseGated: 'Hugging Face へのサインインが必要',
+ browseNoGguf: '互換性のあるモデルファイルが見つかりません。',
+ browseFitUnknown: '適合状況は不明',
+ browseAlreadyDownloaded: 'ダウンロード済みです。',
+ addedByYou: 'あなたが追加',
+ browseDownloadStarted: '{name} をダウンロード中',
+ browseDownloadAria: '{name} をダウンロード',
+ sideloadButton: 'モデルファイルを追加',
+ sideloadTitle: 'GGUF モデルファイルを選択',
+ sideloadDone: '{name} を追加しました。',
+ sideloadAlreadyPresent: '既にライブラリにあります。',
+ pillFullContext: max => `フル ${max} コンテキスト`,
+ pillFullContextTip: '最初からモデルの完全なコンテキストウィンドウで動作します',
+ pillUpTo: max => `最大 ${max} コンテキスト`,
+ pillGrowsTip: '会話が必要とするにつれて自動的に拡張します',
+ pillVision: '画像対応',
+ deleteAction: 'モデルを削除',
+ deleteConfirm: model => `${model} をディスクから削除しますか?`,
+ deleted: model => `${model} を削除しました。`,
+ deleteFailed: '削除に失敗しました'
+ },
providers: {
connectAccount: 'アカウントを接続',
haveApiKey: 'API キーをお持ちですか?',
diff --cc apps/desktop/src/i18n/types.ts
index 0c27bbfdf38,783635694d1..f1417b015f4
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@@ -51,6 -51,6 +51,12 @@@ interface AuxTaskCopy
}
export interface Translations {
++ externalOpenFailed: {
++ title: string
++ message: string
++ copyUrl: string
++ close: string
++ }
common: {
apply: string
back: string
@@@ -145,6 -145,6 +151,8 @@@
back: string
openLogs: string
repairHint: string
++ bundledReinstallHint: string
++ reinstallApp: string
remoteSignInHint: (signInLabel: string) => string
signOutAndSignIn: string
remoteFailureHint: string
@@@ -572,6 -572,6 +581,7 @@@
tapCheck: string
updateReady: (count: number) => string
updateReadyUnknown: string
++ availableBodyRelease: (tag: string) => string
lastChecked: (age: string) => string
justNowSuffix: string
automaticUpdates: string
@@@ -961,6 -961,104 +971,107 @@@
notInCatalog: string
tasks: Record<string, AuxTaskCopy>
}
+ localModels: {
+ title: string
+ runtimeTitle: string
+ runtimeReady: (backend: string) => string
+ serverRunning: string
+ runtimeInstalled: string
+ runtimeInstalledDetail: (tag: string, backend: string) => string
+ installTitle: string
+ installDetail: string
+ installAction: string
+ installing: string
+ installFailed: string
+ hardwareTitle: string
+ hardwareLoading: string
+ vram: (label: string) => string
+ ram: (label: string) => string
+ unifiedMemory: string
+ modelsTitle: string
+ recommended: string
+ downloaded: string
+ downloadAction: (size: string) => string
+ downloadProgress: (done: string, total: string) => string
++ downloadPausedLabel: string
++ downloadPauseAction: string
++ downloadResumeAction: string
+ downloadDoneToast: (model: string) => string
+ installDoneToast: string
+ quickstartTitle: string
+ quickstartDetail: (model: string, size: string) => string
+ quickstartDetailReady: (model: string) => string
+ quickstartAction: string
+ quickstartConfigure: string
+ quickstartDoneToast: (model: string) => string
+ quickstartFailed: string
+ quickstartStageEngine: string
+ quickstartStageModel: string
+ quickstartStageFinish: string
+ useAction: string
+ activePill: string
+ updateTitle: string
+ updateDetail: (next: string, current: string) => string
+ updateAction: string
+ updating: string
+ upToDateTitle: string
+ upToDateDetail: (tag: string, backend: string) => string
+ updateToast: (next: string) => string
+ activeDetail: string
+ activeNotLoaded: string
+ loadedPill: string
+ placementResident: string
+ placementSpilled: string
+ placementResidentTip: string
+ placementSpilledTip: string
+ loadingPill: string
+ ejectTip: string
+ ejected: string
+ ejectFailed: string
+ stopServer: string
+ startServer: string
+ runtimeRunningDetail: string
+ serverStopped: string
+ serverStarted: string
+ serverStopFailed: string
+ serverStartFailed: string
+ activating: string
+ activateFailed: (model: string) => string
+ activateDoneToast: (model: string) => string
+ downloadFailed: (model: string) => string
+ pillFitsGpu: string
+ pillUsesRam: string
+ pillTooBig: string
+ browseTitle: string
+ browseHint: string
+ browsePlaceholder: string
+ browseSearching: string
+ browseListing: string
+ browseShowFiles: string
+ browseRefresh: string
+ browseDownloads: string
+ browseLikes: string
+ browseGated: string
+ browseNoGguf: string
+ browseFitUnknown: string
+ browseAlreadyDownloaded: string
+ addedByYou: string
+ browseDownloadStarted: string
+ browseDownloadAria: string
+ sideloadButton: string
+ sideloadTitle: string
+ sideloadDone: string
+ sideloadAlreadyPresent: string
+ pillFullContext: (max: string) => string
+ pillFullContextTip: string
+ pillUpTo: (max: string) => string
+ pillGrowsTip: string
+ pillVision: string
+ deleteAction: string
+ deleteConfirm: (model: string) => string
+ deleted: (model: string) => string
+ deleteFailed: string
+ }
providers: {
connectAccount: string
haveApiKey: string
@@@ -2247,6 -2352,6 +2370,45 @@@
failed: string
noReturn: string
}
++ /** Update-status overlay + version-details (mechanism-aware update UI):
++ * the overlay reads these off t.updates directly. */
++ appName: string
++ version: (value: string) => string
++ versionUnavailable: string
++ checkNow: string
++ seeWhatsNew: string
++ releaseNotes: string
++ onLatest: string
++ installing: string
++ cantReach: string
++ tapCheck: string
++ updateReady: (count: number) => string
++ updateReadyUnknown: string
++ availableBodyRelease: (tag: string) => string
++ lastChecked: (age: string) => string
++ never: string
++ justNow: string
++ minAgo: (count: number) => string
++ hoursAgo: (count: number) => string
++ daysAgo: (count: number) => string
++ justNowSuffix: string
++ bundleOutOfSync: string
++ bundleOutOfSyncDesc: string
++ bundleOutOfSyncAction: string
++ checkingShort: string
++ releaseAvailable: (tag: string) => string
++ versionDetailsTitle: string
++ versionDetailsBody: string
++ versionDetailsVersion: string
++ versionDetailsCommit: string
++ versionDetailsBuildOrigin: string
++ versionDetailsDistribution: string
++ versionDetailsDistributionDesktop: string
++ versionDetailsRuntime: string
++ versionDetailsRuntimeEmbedded: string
++ versionDetailsRuntimeExternal: string
++ versionDetailsInstallId: string
++ versionDetailsUncommittedChanges: string
}
install: {
@@@ -2260,11 -2365,11 +2422,18 @@@
retryAfterRun: string
setupChoiceTitle: string
setupChoiceDesc: string
++ setupChoiceDescLocal: string
connectExistingTitle: string
connectExistingShort: string
connectExistingDesc: string
installLocalTitle: string
installLocalDesc: string
++ useLocalTitle: string
++ useLocalDesc: string
++ bundledLocalDesc: string
++ bundledDamagedTitle: string
++ bundledDamagedDesc: string
++ reinstallApp: string
localStartUnavailable: string
remoteSetupTitle: string
remoteSetupDesc: string
@@@ -2450,6 -2560,6 +2624,7 @@@
update: string
updateInProgress: string
commitsBehind: (count: number, branch: string) => string
++ releaseAvailable: (tag: string) => string
desktopVersion: (version: string) => string
backendVersion: (version: string) => string
clientLabel: (version: string) => string
diff --cc apps/desktop/src/i18n/zh-hant.ts
index 23fbcf75906,c343b337bb8..fe422398c5b
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@@ -3,6 -3,6 +3,12 @@@ import { defineFieldCopy } from '@/app/
import { defineLocale } from './define-locale'
export const zhHant = defineLocale({
++ externalOpenFailed: {
++ title: '無法開啟此連結',
++ message: '沒有註冊用於開啟此位址的瀏覽器。請複製連結並手動開啟。',
++ copyUrl: '複製連結',
++ close: '關閉'
++ },
common: {
apply: '套用',
back: '返回',
@@@ -980,6 -981,95 +987,98 @@@
curator: { label: '策展器', hint: '技能使用審查' }
}
},
+ localModels: {
+ title: '本地模型',
+ runtimeTitle: '本地執行環境',
+ runtimeReady: backend => `就緒 · ${backend}`,
+ serverRunning: '執行中',
+ runtimeInstalled: '已安裝 llama.cpp 執行環境',
+ runtimeInstalledDetail: (tag, backend) => `組建 ${tag},${backend} 後端。Hermes 會為您啟動並管理伺服器。`,
+ installTitle: '安裝本地執行環境',
+ installDetail:
+ '下載 llama.cpp 推理引擎(數百 MB)。下載的模型完全在本機執行——無需帳號,資料不會離開您的電腦。',
+ installAction: '安裝執行環境',
+ installing: '正在安裝執行環境…',
+ installFailed: '執行環境安裝失敗',
+ hardwareTitle: '本機配置',
+ hardwareLoading: '正在檢測硬體…',
+ vram: label => `${label} 顯示記憶體`,
+ ram: label => `${label} 記憶體`,
+ unifiedMemory: '統一記憶體',
+ modelsTitle: '模型',
+ recommended: '推薦',
+ downloaded: '已下載',
+ downloadAction: size => `下載 · ${size}`,
+ downloadProgress: (done, total) => `${done} / ${total}`,
++ downloadPausedLabel: '已暫停',
++ downloadPauseAction: '暫停',
++ downloadResumeAction: '繼續',
+ downloadDoneToast: model => `${model} 已就緒。`,
+ installDoneToast: '本地執行環境已安裝就緒。',
+ useAction: '使用',
+ activePill: '預設',
+ updateTitle: '引擎有可用更新',
+ updateDetail: (next, current) => `新的 llama.cpp 組建(${next})可以安裝——目前為 ${current}。下載期間模型仍可正常使用。`,
+ updateAction: '更新引擎',
+ updating: '正在更新引擎…',
+ upToDateTitle: '引擎已是最新',
+ upToDateDetail: (tag, backend) => `正在執行 llama.cpp ${tag}(${backend})——Hermes 提供的最新組建。`,
+ updateToast: next => `本地引擎有新組建(${next})。可在 設定 → 本地模型 中更新。`,
+ activeDetail: '新對話使用此模型——傳送首條訊息時載入',
+ activeNotLoaded: '首條訊息時載入',
+ loadedPill: '已載入',
+ placementResident: '全部在 GPU',
+ placementSpilled: '部分在記憶體',
+ placementResidentTip: '完全在 GPU 記憶體中以此上下文視窗執行——全速。',
+ placementSpilledTip: '模型的一部分從系統記憶體執行——可用但較慢。更緊湊的版本或更小的上下文可以完全放入顯示記憶體。',
+ loadingPill: '載入中…',
+ ejectTip: '釋放顯示記憶體(需要時重新載入)',
+ ejected: '模型已卸載——顯示記憶體已釋放。',
+ ejectFailed: '無法卸載模型',
+ stopServer: '關閉',
+ startServer: '開啟',
+ runtimeRunningDetail: '本地伺服器執行中。關閉後將釋放全部顯示記憶體,新對話將不再使用本地模型,直到您重新開啟。',
+ serverStopped: '本地伺服器已停止——顯示記憶體已釋放。',
+ serverStarted: '本地伺服器執行中。',
+ serverStopFailed: '無法停止本地伺服器',
+ serverStartFailed: '無法啟動本地伺服器',
+ activating: '啟動中…',
+ activateFailed: model => `無法切換到 ${model}`,
+ activateDoneToast: model => `新對話將使用 ${model}。`,
+ downloadFailed: model => `${model} 下載失敗`,
+ pillFitsGpu: '完全在 GPU 上執行',
+ pillUsesRam: '使用系統記憶體',
+ pillTooBig: '超出本機記憶體',
+ browseTitle: '發現更多模型',
+ browseHint: '搜尋整個 Hugging Face。在這裡下載的模型會自動適配你的機器,但未經我們測試。',
+ browsePlaceholder: '按名稱或作者搜尋模型…',
+ browseSearching: '正在搜尋 Hugging Face',
+ browseListing: '正在讀取模型檔案',
+ browseShowFiles: '查看檔案',
+ browseRefresh: '重新整理',
+ browseDownloads: '次下載',
+ browseLikes: '個讚',
+ browseGated: '需要登入 Hugging Face',
+ browseNoGguf: '未找到相容的模型檔案。',
+ browseFitUnknown: '適配情況未知',
+ browseAlreadyDownloaded: '已下載。',
+ addedByYou: '由你新增',
+ browseDownloadStarted: '正在下載 {name}',
+ browseDownloadAria: '下載 {name}',
+ sideloadButton: '新增模型檔案',
+ sideloadTitle: '選擇 GGUF 模型檔案',
+ sideloadDone: '已新增 {name}。',
+ sideloadAlreadyPresent: '已在你的庫中。',
+ pillFullContext: max => `完整 ${max} 上下文`,
+ pillFullContextTip: '從一開始就以模型的完整上下文視窗執行',
+ pillUpTo: max => `最高 ${max} 上下文`,
+ pillGrowsTip: '隨著對話需要更多空間自動增長',
+ pillVision: '識圖',
+ deleteAction: '刪除模型',
+ deleteConfirm: model => `從磁碟刪除 ${model}?`,
+ deleted: model => `已刪除 ${model}。`,
+ deleteFailed: '刪除失敗'
+ },
providers: {
connectAccount: '連結帳號',
haveApiKey: '改用 API 金鑰?',
diff --cc apps/desktop/src/i18n/zh.ts
index ab91a251c01,bc3cf1c3105..94c0ce8ea80
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@@ -3,6 -3,6 +3,12 @@@ import { defineFieldCopy } from '@/app/
import type { Translations } from './types'
export const zh: Translations = {
++ externalOpenFailed: {
++ title: '无法打开此链接',
++ message: '没有注册用于打开此地址的浏览器。请复制链接并手动打开。',
++ copyUrl: '复制链接',
++ close: '关闭'
++ },
common: {
apply: '应用',
back: '返回',
@@@ -98,6 -98,6 +104,9 @@@
back: '返回',
openLogs: '打开日志',
repairHint: '修复会重新运行安装器,在新机器上可能需要几分钟。',
++ bundledReinstallHint:
++ '捆绑安装无法从应用内部自修复——重新安装 Hermes Desktop 以恢复其后端。',
++ reinstallApp: '重新安装 Hermes Desktop',
remoteSignInHint: signInLabel =>
`先退出已保存的远程浏览器会话,然后打开${signInLabel}。也可以使用本地网关切换到随应用提供的后端。`,
signOutAndSignIn: '退出并重新登录',
@@@ -899,7 -899,7 +909,8 @@@
justNow: '刚刚',
minAgo: count => `${count} 分钟前`,
hoursAgo: count => `${count} 小时前`,
-- daysAgo: count => `${count} 天前`
++ daysAgo: count => `${count} 天前`,
++ availableBodyRelease: (tag: string) => `版本 ${tag} 已可安装。`,
},
config: {
none: '无',
@@@ -1306,6 -1306,105 +1317,108 @@@
curator: { label: '维护器', hint: '技能使用审查' }
}
},
+ localModels: {
+ title: '本地模型',
+ runtimeTitle: '本地运行时',
+ runtimeReady: backend => `就绪 · ${backend}`,
+ serverRunning: '运行中',
+ runtimeInstalled: '已安装 llama.cpp 运行时',
+ runtimeInstalledDetail: (tag, backend) => `构建 ${tag},${backend} 后端。Hermes 会为您启动并管理服务器。`,
+ installTitle: '安装本地运行时',
+ installDetail: '下载 llama.cpp 推理引擎(几百 MB)。下载的模型完全在本机运行——无需账号,数据不会离开您的电脑。',
+ installAction: '安装运行时',
+ installing: '正在安装运行时…',
+ installFailed: '运行时安装失败',
+ quickstartTitle: '在本机运行模型',
+ quickstartDetail: (model, size) =>
+ `一键完成所有设置:本地引擎、${model}(需下载 ${size}),并设为新会话的默认模型。数据不会离开这台电脑。`,
+ quickstartDetailReady: model => `一键将 ${model} 设为新会话的默认模型。所有内容都在本机运行。`,
+ quickstartAction: '为我设置',
+ quickstartConfigure: '自定义…',
+ quickstartDoneToast: model => `${model} 已就绪——新会话将在本机运行。`,
+ quickstartFailed: '本地模型设置失败',
+ quickstartStageEngine: '引擎',
+ quickstartStageModel: '模型',
+ quickstartStageFinish: '完成',
+ hardwareTitle: '本机配置',
+ hardwareLoading: '正在检测硬件…',
+ vram: label => `${label} 显存`,
+ ram: label => `${label} 内存`,
+ unifiedMemory: '统一内存',
+ modelsTitle: '模型',
+ recommended: '推荐',
+ downloaded: '已下载',
+ downloadAction: size => `下载 · ${size}`,
+ downloadProgress: (done, total) => `${done} / ${total}`,
++ downloadPausedLabel: '已暂停',
++ downloadPauseAction: '暂停',
++ downloadResumeAction: '继续',
+ downloadDoneToast: model => `${model} 已就绪。`,
+ installDoneToast: '本地运行时已安装就绪。',
+ useAction: '使用',
+ activePill: '默认',
+ updateTitle: '引擎有可用更新',
+ updateDetail: (next, current) => `新的 llama.cpp 构建(${next})可以安装——当前为 ${current}。下载期间模型仍可正常使用。`,
+ updateAction: '更新引擎',
+ updating: '正在更新引擎…',
+ upToDateTitle: '引擎已是最新',
+ upToDateDetail: (tag, backend) => `正在运行 llama.cpp ${tag}(${backend})——Hermes 提供的最新构建。`,
+ updateToast: next => `本地引擎有新构建(${next})。可在 设置 → 本地模型 中更新。`,
+ activeDetail: '新对话使用此模型——发送首条消息时加载',
+ activeNotLoaded: '首条消息时加载',
+ loadedPill: '已加载',
+ placementResident: '全部在 GPU',
+ placementSpilled: '部分在内存',
+ placementResidentTip: '完全在 GPU 显存中以此上下文窗口运行——全速。',
+ placementSpilledTip: '模型的一部分从系统内存运行——可用但较慢。更紧凑的版本或更小的上下文可以完全放入显存。',
+ loadingPill: '加载中…',
+ ejectTip: '释放显存(需要时重新加载)',
+ ejected: '模型已卸载——显存已释放。',
+ ejectFailed: '无法卸载模型',
+ stopServer: '关闭',
+ startServer: '开启',
+ runtimeRunningDetail: '本地服务器正在运行。关闭后将释放全部显存,新对话将不再使用本地模型,直到您重新开启。',
+ serverStopped: '本地服务器已停止——显存已释放。',
+ serverStarted: '本地服务器运行中。',
+ serverStopFailed: '无法停止本地服务器',
+ serverStartFailed: '无法启动本地服务器',
+ activating: '启动中…',
+ activateFailed: model => `无法切换到 ${model}`,
+ activateDoneToast: model => `新对话将使用 ${model}。`,
+ downloadFailed: model => `${model} 下载失败`,
+ pillFitsGpu: '完全在 GPU 上运行',
+ pillUsesRam: '使用系统内存',
+ pillTooBig: '超出本机内存',
+ browseTitle: '发现更多模型',
+ browseHint: '搜索整个 Hugging Face。在这里下载的模型会自动适配你的机器,但未经我们测试。',
+ browsePlaceholder: '按名称或作者搜索模型…',
+ browseSearching: '正在搜索 Hugging Face',
+ browseListing: '正在读取模型文件',
+ browseShowFiles: '查看文件',
+ browseRefresh: '刷新',
+ browseDownloads: '次下载',
+ browseLikes: '个赞',
+ browseGated: '需要登录 Hugging Face',
+ browseNoGguf: '未找到兼容的模型文件。',
+ browseFitUnknown: '适配情况未知',
+ browseAlreadyDownloaded: '已下载。',
+ addedByYou: '由你添加',
+ browseDownloadStarted: '正在下载 {name}',
+ browseDownloadAria: '下载 {name}',
+ sideloadButton: '添加模型文件',
+ sideloadTitle: '选择 GGUF 模型文件',
+ sideloadDone: '已添加 {name}。',
+ sideloadAlreadyPresent: '已在你的库中。',
+ pillFullContext: max => `完整 ${max} 上下文`,
+ pillFullContextTip: '从一开始就以模型的完整上下文窗口运行',
+ pillUpTo: max => `最高 ${max} 上下文`,
+ pillGrowsTip: '随着对话需要更多空间自动增长',
+ pillVision: '识图',
+ deleteAction: '删除模型',
+ deleteConfirm: model => `从磁盘删除 ${model}?`,
+ deleted: model => `已删除 ${model}。`,
+ deleteFailed: '删除失败'
+ },
providers: {
connectAccount: '连接账号',
haveApiKey: '改用 API 密钥?',
@@@ -2823,6 -2928,6 +2947,47 @@@
failed: '后端更新失败。',
noReturn: '后端未恢复在线。更新可能未完成——请检查后端主机。'
}
++ ,
++ // Update-status overlay + version-details (mechanism-aware update UI).
++ appName: 'Hermes',
++ version: value => `版本 ${value}`,
++ versionUnavailable: '版本不可用',
++ checkNow: '立即检查',
++ seeWhatsNew: '查看更新内容',
++ releaseNotes: '发行说明',
++ onLatest: '已是最新版本。',
++ installing: '正在安装更新。',
++ cantReach: '无法连接更新服务器。',
++ tapCheck: '点击“立即检查”以查找更新。',
++ updateReady: count => `新更新已就绪(包含 ${count} 项变更)。`,
++ updateReadyUnknown: '新更新已就绪。',
++ availableBodyRelease: (tag: string) => `版本 ${tag} 已可安装。`,
++ lastChecked: age => `上次检查 ${age}`,
++ never: '从未',
++ justNow: '刚刚',
++ minAgo: count => `${count} 分钟前`,
++ hoursAgo: count => `${count} 小时前`,
++ daysAgo: count => `${count} 天前`,
++ justNowSuffix: ' · 刚刚',
++ bundleOutOfSync: '应用版本过旧',
++ bundleOutOfSyncDesc:
++ 'Hermes 运行时已更新,但桌面应用仍是较旧的构建。请更新以获取最新修复。',
++ bundleOutOfSyncAction: '获取安装程序',
++ checkingShort: '检查中…',
++ releaseAvailable: tag => `版本 ${tag} 可用。`,
++ versionDetailsTitle: '版本详情',
++ versionDetailsBody:
++ '此安装在应用外部管理。请使用与安装时相同的方式更新。',
++ versionDetailsVersion: '版本',
++ versionDetailsCommit: '提交',
++ versionDetailsBuildOrigin: '构建来源',
++ versionDetailsDistribution: '发行版',
++ versionDetailsDistributionDesktop: '桌面应用 (MSIX)',
++ versionDetailsRuntime: '运行时',
++ versionDetailsRuntimeEmbedded: '嵌入式(捆绑)',
++ versionDetailsRuntimeExternal: '外部',
++ versionDetailsInstallId: '安装 ID',
++ versionDetailsUncommittedChanges: '未提交的变更'
},
install: {
@@@ -2846,8 -2951,8 +3011,18 @@@
connectExistingTitle: '连接到现有 Hermes',
connectExistingShort: '连接现有环境',
connectExistingDesc: '使用会话令牌或浏览器登录连接远程后端。不会启动本地安装。',
++ setupChoiceDescLocal:
++ '在这台电脑上安装 Hermes,或连接到已在运行的 Hermes 网关。',
++
installLocalTitle: '本地安装 Hermes',
installLocalDesc: '下载 Hermes,创建 Python 环境,并在这台电脑上运行后端。',
++ useLocalTitle: '使用这台电脑上的 Hermes',
++ useLocalDesc: '此电脑已安装 Hermes 运行时——一键启动,无需下载。',
++ bundledLocalDesc: '此应用自带 Hermes 运行时——捆绑后端即本地安装。',
++ bundledDamagedTitle: '捆绑后端不可用',
++ bundledDamagedDesc:
++ '此应用捆绑的 Hermes 运行时未能加载。重新安装 Hermes Desktop 以恢复。',
++ reinstallApp: '重新安装 Hermes Desktop',
localStartUnavailable: '无法启动本地安装。请重启 Hermes Desktop 后重试。',
remoteSetupTitle: '连接到现有 Hermes',
remoteSetupDesc: '输入网关 URL。Hermes Desktop 会检测需要令牌还是浏览器登录。',
@@@ -3049,6 -3159,6 +3229,7 @@@
updateInProgress: '正在更新',
commitsBehind: (count, branch) => `落后 ${branch} ${count} 个提交`,
desktopVersion: version => `Hermes Desktop v${version}`,
++ releaseAvailable: tag => `版本 ${tag} 可用。`,
backendVersion: version => `后端 v${version}`,
clientLabel: version => `客户端 v${version}`,
connectionSsh: host => `SSH: ${host}`,
diff --cc apps/desktop/src/store/local-runtime-jobs.ts
index 00000000000,64c343f483d..ed08f6f52bd
mode 000000,100644..100644
--- a/apps/desktop/src/store/local-runtime-jobs.ts
+++ b/apps/desktop/src/store/local-runtime-jobs.ts
@@@ -1,0 -1,169 +1,179 @@@
+ import { atom } from 'nanostores'
+
+ import { getLocalModelsJobs, getLocalModelsStatus } from '@/hermes'
+ import { translateNow } from '@/i18n'
+ import { notify, notifyError } from '@/store/notifications'
+ import type { LocalRuntimeJob } from '@/types/hermes'
+
+ // App-level tracker for local-runtime jobs (runtime installs, model
+ // downloads). The AUTHORITY is the backend job registry — this store is a
+ // cache of it (desktop guide: server truth is cached, not owned). Living at
+ // the store layer, not in the settings pane, is what makes a download
+ // survive the pane unmounting: anything can start a job, the poller follows
+ // it to completion, and completion/failure notify app-wide exactly once.
+
+ export const $localRuntimeJobs = atom<readonly LocalRuntimeJob[]>([])
+
+ const POLL_ACTIVE_MS = 700
+ let timer: null | number = null
+ let polling = false
+ // Jobs we've already toasted for, so a poll race can't double-notify.
+ const settledNotified = new Set<string>()
+
+ function jobsEqual(a: readonly LocalRuntimeJob[], b: readonly LocalRuntimeJob[]) {
+ if (a.length !== b.length) {
+ return false
+ }
+
+ return a.every((job, i) => {
+ const other = b[i]
+
+ return (
+ job.job_id === other.job_id &&
+ job.status === other.status &&
+ job.phase === other.phase &&
+ job.done_bytes === other.done_bytes
+ )
+ })
+ }
+
+ function notifySettled(previous: readonly LocalRuntimeJob[], next: readonly LocalRuntimeJob[]) {
+ const wasRunning = new Set(previous.filter(j => j.status === 'running').map(j => j.job_id))
+
+ for (const job of next) {
+ if (job.status === 'running' || !wasRunning.has(job.job_id) || settledNotified.has(job.job_id)) {
+ continue
+ }
+
+ settledNotified.add(job.job_id)
+
+ if (job.status === 'done') {
+ notify({
+ durationMs: 6_000,
+ kind: 'success',
+ title: translateNow('settings.localModels.title'),
+ message:
+ job.kind === 'model-download'
+ ? translateNow('settings.localModels.downloadDoneToast', job.target)
+ : job.kind === 'model-activate'
+ ? translateNow('settings.localModels.activateDoneToast', job.target)
+ : job.kind === 'quickstart'
+ ? translateNow('settings.localModels.quickstartDoneToast', job.target)
+ : translateNow('settings.localModels.installDoneToast')
+ })
+ } else {
+ notifyError(
+ new Error(job.error ?? job.detail ?? 'failed'),
+ job.kind === 'model-download'
+ ? translateNow('settings.localModels.downloadFailed', job.target)
+ : job.kind === 'model-activate'
+ ? translateNow('settings.localModels.activateFailed', job.target)
+ : job.kind === 'quickstart'
+ ? translateNow('settings.localModels.quickstartFailed')
+ : translateNow('settings.localModels.installFailed')
+ )
+ }
+ }
+ }
+
+ async function poll() {
+ try {
+ const { jobs } = await getLocalModelsJobs()
+ const previous = $localRuntimeJobs.get()
+
+ if (!jobsEqual(previous, jobs)) {
+ notifySettled(previous, jobs)
+ $localRuntimeJobs.set(jobs)
+ }
+ } catch {
+ // Backend unreachable — keep the last snapshot; the next poll retries.
+ }
+
- const anyRunning = $localRuntimeJobs.get().some(j => j.status === 'running')
++ const anyRunning = $localRuntimeJobs.get().some(j => j.status === 'running' || j.status === 'paused')
+
+ if (anyRunning) {
+ timer = window.setTimeout(() => void poll(), POLL_ACTIVE_MS)
+ } else {
+ polling = false
+ timer = null
+ }
+ }
+
+ // Idempotent kick: start (or keep) the poll loop while work is in flight.
+ // Call after starting a job AND on app boot (to rediscover work started
+ // before a reload).
+ export function watchLocalRuntimeJobs() {
+ if (polling) {
+ return
+ }
+
+ polling = true
+
+ if (timer !== null) {
+ window.clearTimeout(timer)
+ }
+
+ void poll()
+ }
+
+ // Selector: the running download job for a catalog model id, if any.
+ export function runningDownloadFor(jobs: readonly LocalRuntimeJob[], modelId: string): LocalRuntimeJob | null {
- return jobs.find(j => j.kind === 'model-download' && j.status === 'running' && j.model_id === modelId) ?? null
++ // Paused downloads stay "the job for this model" — the row keeps its
++ // progress and shows Resume instead of Pause.
++ return (
++ jobs.find(
++ j =>
++ j.kind === 'model-download' &&
++ (j.status === 'running' || j.status === 'paused') &&
++ j.model_id === modelId
++ ) ?? null
++ )
+ }
+
+ // Selector: every model on its way to the library right now — plain
+ // downloads plus quickstart runs while they are still fetching bytes
+ // (later quickstart phases mean the model is staged and activating).
+ // The model picker renders these as disabled progress rows.
+ const DOWNLOAD_PHASES = new Set(['starting', 'installing-runtime', 'downloading'])
+
+ export function runningModelDownloads(jobs: readonly LocalRuntimeJob[]): LocalRuntimeJob[] {
+ return jobs.filter(
+ j =>
- j.status === 'running' &&
++ // Paused downloads stay visible in the picker's in-flight rows too.
++ (j.status === 'running' || j.status === 'paused') &&
+ (j.kind === 'model-download' || (j.kind === 'quickstart' && DOWNLOAD_PHASES.has(j.phase)))
+ )
+ }
+
+ export function runningRuntimeInstall(jobs: readonly LocalRuntimeJob[]): LocalRuntimeJob | null {
+ return jobs.find(j => j.kind === 'runtime-install' && j.status === 'running') ?? null
+ }
+
+ // One engine-update toast per app session: checked at boot (after the
+ // gateway is ready), only when the user runs the local engine. The
+ // download itself is always a button click in Local Models — this is a
+ // pointer, not an installer.
+ let updateNotified = false
+
+ export async function checkLocalRuntimeUpdate() {
+ if (updateNotified) {
+ return
+ }
+
+ try {
+ const status = await getLocalModelsStatus()
+
+ if (status.enabled && status.update_available) {
+ updateNotified = true
+ notify({
+ durationMs: 10_000,
+ kind: 'info',
+ title: translateNow('settings.localModels.title'),
+ message: translateNow('settings.localModels.updateToast', status.configured_tag)
+ })
+ }
+ } catch {
+ // Backend without the endpoint (older runtime) or transient failure —
+ // silently skip; the pane still shows the update row when opened.
+ }
+ }
diff --cc apps/desktop/src/types/hermes.ts
index 4f39fca3bc9,f15dda135df..8f83577bea5
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@@ -1220,6 -1226,93 +1226,93 @@@ export interface StatusResponse
version: string
}
+ // ── Managed local runtime (llama.cpp) ──────────────────────────
+
+ export interface LocalModelPlacement {
+ window?: number
+ window_label?: string
+ spilled?: boolean
+ granted_window?: number
+ granted_window_label?: string
+ }
+
+ export interface LocalModelLoadProgress {
+ stage: string
+ value: number
+ percent: number
+ }
+
+ export interface LocalModelsStatus {
+ enabled: boolean
+ tag: string
+ configured_tag: string
+ update_available: boolean
+ runtime_installed: boolean
+ runtime_backend: string | null
+ server_running: boolean
+ server_base_url: string | null
+ active_model_id: string | null
+ loaded_models: Record<string, string>
+ /** Models loading into memory right now: real per-tensor load percent. */
+ loading?: Record<string, LocalModelLoadProgress>
+ placement?: Record<string, LocalModelPlacement>
+ models: { id: string; size_bytes: number; size_label: string }[]
+ models_dir: string
+ }
+
+ export interface LocalHardware {
+ uma: boolean
+ vram_total_bytes: number
+ vram_usable_bytes: number
+ ram_total_bytes: number
+ ram_available_bytes: number
+ vram_label: string
+ gpu_name: string | null
+ gpu_util_percent: number | null
+ vram_used_bytes: number | null
+ }
+
+ export interface LocalCatalogModel {
+ id: string
+ display_name: string
+ description: string
+ size_bytes: number
+ size_label: string
+ native_context: number
+ native_context_label: string
+ recommended: boolean
+ downloaded: boolean
+ downloaded_model_id?: string | null
+ downloaded_quant?: string | null
+ mtp: boolean
+ vision?: boolean
+ fits: boolean
+ fit_summary: string
+ fit_detail?: string
+ model_id?: string
+ quant?: string
+ quant_reason?: string
+ quant_validated?: boolean
+ variant_count?: number
+ start_window?: number
+ start_window_label?: string
+ spilled?: boolean
+ }
+
+ export interface LocalRuntimeJob {
+ job_id: string
+ kind: 'model-activate' | 'model-download' | 'quickstart' | 'runtime-install'
+ target: string
+ model_id: string | null
- status: 'running' | 'done' | 'error'
++ status: 'paused' | 'running' | 'done' | 'error'
+ phase: string
+ detail: string
+ total_bytes: number | null
+ done_bytes: number
+ percent?: number
+ error: string | null
+ }
+
export interface ActionResponse {
name: string
ok: boolean
diff --cc gateway/run.py
index d5db2e1f70f,7aa6cf7930a..f818ceb722f
--- a/gateway/run.py
+++ b/gateway/run.py
@@@ -3601,7 -3812,7 +3812,7 @@@ def _skill_slug_from_frontmatter(skill_
can't be read or lacks a ``name:`` in its frontmatter.
"""
try:
-- content = skill_md.read_text(encoding="utf-8", errors="replace")
++ content = skill_md.read_text(encoding="utf-8-sig", errors="replace")
except Exception:
return None, None
content = content.lstrip("\ufeff") # tolerate UTF-8 BOM (Windows editors)
@@@ -3751,7 -3962,7 +3962,7 @@@ def _load_gateway_config(config_path: "
try:
if config_path.exists():
import yaml
-- with open(config_path, 'r', encoding='utf-8') as f:
++ with open(config_path, 'r', encoding='utf-8-sig') as f:
raw = yaml.safe_load(f) or {}
except Exception:
logger.debug("Could not load gateway config from %s", config_path)
@@@ -7657,7 -7911,7 +7911,7 @@@ class GatewayRunner(GatewayAuthorizatio
def _load_voice_modes(self) -> Dict[str, str]:
try:
-- data = json.loads(self._VOICE_MODE_PATH.read_text(encoding="utf-8"))
++ data = json.loads(self._VOICE_MODE_PATH.read_text(encoding="utf-8-sig"))
except (FileNotFoundError, json.JSONDecodeError, OSError):
return {}
@@@ -9583,7 -9858,7 +9858,7 @@@
logger.warning("Prefill messages file not found: %s", path)
return []
try:
-- with open(path, "r", encoding="utf-8") as f:
++ with open(path, "r", encoding="utf-8-sig") as f:
data = json.load(f)
if not isinstance(data, list):
logger.warning("Prefill messages file must contain a JSON array: %s", path)
@@@ -11565,7 -11840,7 +11840,7 @@@
path = _hermes_home / self._STUCK_LOOP_FILE
try:
-- counts = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
++ counts = json.loads(path.read_text(encoding="utf-8-sig")) if path.exists() else {}
except Exception:
counts = {}
@@@ -11595,7 -11870,7 +11870,7 @@@
return 0
try:
-- counts = json.loads(path.read_text(encoding="utf-8"))
++ counts = json.loads(path.read_text(encoding="utf-8-sig"))
except Exception:
return 0
@@@ -11643,7 -11918,7 +11918,7 @@@
if not path.exists():
return
try:
-- counts = json.loads(path.read_text(encoding="utf-8"))
++ counts = json.loads(path.read_text(encoding="utf-8-sig"))
if session_key in counts:
del counts[session_key]
if counts:
@@@ -22084,7 -22594,7 +22594,7 @@@
self._booted_from_restart = False
return True
return False
-- data = json.loads(marker_path.read_text(encoding="utf-8"))
++ data = json.loads(marker_path.read_text(encoding="utf-8-sig"))
except Exception:
return False
@@@ -24797,7 -25309,7 +25309,7 @@@
for path in (claimed_path, pending_path):
if path.exists():
try:
-- pending = json.loads(path.read_text(encoding="utf-8"))
++ pending = json.loads(path.read_text(encoding="utf-8-sig"))
platform_str = pending.get("platform")
chat_id = pending.get("chat_id")
chat_type = pending.get("chat_type")
@@@ -24898,7 -25410,7 +25410,7 @@@
# Send final status
try:
-- exit_code_raw = exit_code_path.read_text(encoding="utf-8").strip() or "1"
++ exit_code_raw = exit_code_path.read_text(encoding="utf-8-sig").strip() or "1"
exit_code = int(exit_code_raw)
if exit_code == 0:
await adapter.send(
@@@ -24952,7 -25464,7 +25464,7 @@@
and _up_pending_state.persistent.update_prompt_pending
)):
try:
-- prompt_data = json.loads(prompt_path.read_text(encoding="utf-8"))
++ prompt_data = json.loads(prompt_path.read_text(encoding="utf-8-sig"))
prompt_text = prompt_data.get("prompt", "")
default = prompt_data.get("default", "")
if prompt_text:
@@@ -25050,7 -25562,7 +25562,7 @@@
elif not claimed_path.exists():
return True
-- pending = json.loads(claimed_path.read_text(encoding="utf-8"))
++ pending = json.loads(claimed_path.read_text(encoding="utf-8-sig"))
platform_str = pending.get("platform")
chat_id = pending.get("chat_id")
chat_type = pending.get("chat_type")
@@@ -25064,7 -25576,7 +25576,7 @@@
claimed_path.replace(pending_path)
return False
-- exit_code_raw = exit_code_path.read_text(encoding="utf-8").strip() or "1"
++ exit_code_raw = exit_code_path.read_text(encoding="utf-8-sig").strip() or "1"
exit_code = int(exit_code_raw)
# Read the captured update output
@@@ -25146,7 -25658,7 +25658,7 @@@
return None
try:
-- data = json.loads(notify_path.read_text(encoding="utf-8"))
++ data = json.loads(notify_path.read_text(encoding="utf-8-sig"))
platform_str = data.get("platform")
chat_id = data.get("chat_id")
chat_type = data.get("chat_type")
@@@ -32269,45 -32814,10 +32814,45 @@@ def main()
config = None
if args.config:
import yaml
-- with open(args.config, encoding="utf-8") as f:
++ with open(args.config, encoding="utf-8-sig") as f:
data = yaml.safe_load(f) or {}
config = GatewayConfig.from_dict(data)
-
+
+
+ # Post-update boot bootstrap: when this install's code changed since the
+ # last boot (app-updater swap, docker/nix image change, git pull without
+ # `hermes update`), run the idempotent user-state steps (config
+ # migration, skills sync, state.db guard) before platforms connect.
+ # Two file reads when nothing changed; never raises.
+ try:
+ from pathlib import Path as _Path
+
+ from hermes_cli.boot_bootstrap import maybe_run_boot_bootstrap
+
+ maybe_run_boot_bootstrap(_Path(__file__).resolve().parents[1])
+ except Exception as exc:
+ # maybe_run_boot_bootstrap itself never raises and logs internally;
+ # this guard covers the import/lookup path. Don't hide it silently.
+ logger.warning("boot bootstrap setup failed (continuing boot): %s", exc)
+
+ # pm startup: same contract as the CLI dispatch path (hermes_cli/main.py)
+ # — the gateway daemon never passes through CLI dispatch, so without this
+ # it would boot without the store's tools (git/bash/ffmpeg/...) on PATH.
+ # O(1) stamp checks, no network, no installs; warns, never blocks.
+ try:
+ import pm
+
+ pm.adopt()
+ problems = pm.check()
+ if problems:
+ logger.warning(
+ "install out of sync (%s) — run `hermes pm install`",
+ "; ".join(problems),
+ )
+ else:
+ pm.activate()
+ except Exception:
+ logger.debug("pm startup check failed", exc_info=True)
# start_gateway() performs the full graceful teardown (adapters
# disconnected, sessions saved + flushed, SQLite closed, cron/MCP stopped,
# PID file + runtime lock released) before it returns OR raises SystemExit
diff --cc hermes_cli/browser_connect.py
index cabdf692308,558f59a3423..910b44e4fc0
--- a/hermes_cli/browser_connect.py
+++ b/hermes_cli/browser_connect.py
@@@ -861,6 -1004,37 +1004,37 @@@ def snapshot_real_profile(browser: str
except OSError as e:
logger.debug("real-profile snapshot: skipped Local State: %s", e)
+ # The copy contains ONLY the mirrored Default dir (that is where the
+ # pinned/active profile's auth was mirrored into), but a verbatim
+ # Local State still names the SOURCE profile (e.g. last_used="Profile
+ # 2", info_cache listing Profile 2/4/7). Chrome therefore opens a
+ # missing profile dir and starts SIGNED OUT. Rewrite Local State so
+ # the copy's only profile is Default and it is the last-used one.
+ # CRITICAL: Default's identity entry must be the SOURCE profile's
+ # entry (name + Google account), not the source's own "Default"
+ # entry — the Default DIR holds the source profile's cookies. A
+ # mismatch (cookies belong to profile B, info_cache names profile A) makes Chrome
+ # demand a "Continue as <name>" profile-sign-in reconciliation on
+ # every launch and treat the profile as mid-sign-in.
+ try:
+ import json as _json
+
- with open(ls_dst, encoding="utf-8") as fh:
++ with open(ls_dst, encoding="utf-8-sig") as fh:
+ state = _json.load(fh)
+ prof = state.get("profile")
+ if isinstance(prof, dict):
+ cache = prof.get("info_cache")
+ if isinstance(cache, dict):
+ src_entry = cache.get(source_profile) or cache.get("Default")
+ if src_entry:
+ prof["info_cache"] = {"Default": src_entry}
+ prof["last_used"] = "Default"
+ prof["last_active_profiles"] = ["Default"]
+ with open(ls_dst, "w", encoding="utf-8") as fh:
+ _json.dump(state, fh)
+ except (OSError, ValueError) as e:
+ logger.debug("real-profile snapshot: could not normalize Local State: %s", e)
+
if not populated:
# Fresh (or torn-and-rebuilding): drop any partial Default and copy
# the ACTIVE profile's full dir (minus caches AND the locked auth
diff --cc hermes_cli/config_defaults.py
index 864e9fe6899,eb10c2a1758..0ecd5a7ad50
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@@ -3897,6 -3936,29 +3936,30 @@@ DEFAULT_CONFIG =
"region": "global",
},
+ # Managed llama.cpp local runtime (see docs: user-guide/local-models).
+ # Hermes downloads official llama.cpp release binaries, then spawns and
+ # supervises one llama-server in router mode. Context sizing is policy,
+ # not preference: there are deliberately no context/VRAM knobs here.
+ "local_runtime": {
+ # Master switch for the managed runtime. Off = detection-only
+ # (Hermes still finds an external llama-server you run yourself).
+ "enabled": False,
- # Pinned llama.cpp release tag (rolling bNNNN). Bumped by Hermes
- # releases after the validation suite re-runs, not tracked live.
- "tag": "b10679",
++ # The llama.cpp build is pinned in pm/lock.json (url + sha256 per
++ # platform), not here: bumping it is a release-time pin refresh,
++ # which is what makes the download verifiable instead of resolved
++ # at runtime. `hermes pm doctor` reports what is installed.
+ # Inference backend: auto = CUDA on NVIDIA, Metal on macOS, Vulkan on
+ # other GPUs, else CPU. Explicit values: cuda|metal|vulkan|hip|cpu.
+ "backend": "auto",
+ # Router process: how many models may be resident at once.
+ "models_max": 4,
+ # Port for the managed server. 0 = pick a free port at spawn.
+ "port": 0,
+ # Extra ports detection probes for an external llama-server, in
+ # addition to the default 8080.
+ "detect_ports": [],
+ },
+
# Config schema version - bump this when adding new required fields
"_config_version": 39,
}
diff --cc hermes_cli/doctor.py
index ca447e87495,717ed5830fb..7e5bfea5e3c
--- a/hermes_cli/doctor.py
+++ b/hermes_cli/doctor.py
@@@ -67,10 -67,15 +67,11 @@@ _PROVIDER_ENV_HINTS =
"COMMANDCODE_API_KEY",
"XIAOMI_API_KEY",
"TOKENHUB_API_KEY",
+ "TOKENPLAN_API_KEY",
)
-
-from hermes_constants import is_termux as _is_termux
-
-
def _python_install_cmd() -> str:
- return "python -m pip install" if _is_termux() else "uv pip install"
+ return "uv pip install"
def _system_package_install_cmd(pkg: str) -> str:
diff --cc hermes_cli/install_identity.py
index 00000000000,264f827ff25..d0cb329d659
mode 000000,100644..100644
--- a/hermes_cli/install_identity.py
+++ b/hermes_cli/install_identity.py
@@@ -1,0 -1,153 +1,153 @@@
+ """Stable opaque identity shared by every profile in one Hermes install."""
+
+ from __future__ import annotations
+
+ import contextlib
+ import os
+ from pathlib import Path
+ import re
+ import tempfile
+ import threading
+ from typing import Optional
+ import uuid
+
+ from hermes_constants import get_default_hermes_root
+
+ _INSTALL_ID_FILENAME = "install_id"
+ _INSTALL_ID_RE = re.compile(r"^[0-9a-f]{32}$")
+ _INSTALL_ID_CACHE: dict[str, Optional[str]] = {"root": None, "value": None}
+ _INSTALL_ID_LOCK = threading.Lock()
+ _INSTALL_ID_PUBLICATION_LOCK = threading.Lock()
+
+
+ @contextlib.contextmanager
+ def _install_id_file_lock(root: Path):
+ """Serialize identity publication across processes on POSIX and Windows."""
+ lock_path = root / ".install_id.lock"
+ fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o600)
+ windows = os.name == "nt"
+ try:
+ if windows:
+ import msvcrt
+
+ if os.fstat(fd).st_size == 0:
+ os.write(fd, b"\0")
+ os.fsync(fd)
+ os.lseek(fd, 0, os.SEEK_SET)
+ msvcrt.locking(fd, msvcrt.LK_LOCK, 1)
+ else:
+ import fcntl
+
+ fcntl.flock(fd, fcntl.LOCK_EX)
+ yield
+ finally:
+ try:
+ if windows:
+ import msvcrt
+
+ os.lseek(fd, 0, os.SEEK_SET)
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
+ else:
+ import fcntl
+
+ fcntl.flock(fd, fcntl.LOCK_UN)
+ finally:
+ os.close(fd)
+
+
+ def _fsync_directory(path: Path) -> None:
+ """Best-effort durability for the directory entry after replace."""
+ if os.name == "nt":
+ return
+ try:
+ fd = os.open(path, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
+ except OSError:
+ return
+ try:
+ os.fsync(fd)
+ except OSError:
+ pass
+ finally:
+ os.close(fd)
+
+
+ def read_or_create_install_id(root: Path | None = None) -> Optional[str]:
+ """Read or atomically mint the opaque id for the physical install.
+
+ ``None`` means the id could neither be read nor persisted. Returning an
+ ephemeral id would violate the authority and connection-registry contract.
+ """
+ root = get_default_hermes_root() if root is None else root
+ path = root / _INSTALL_ID_FILENAME
+ try:
- existing = path.read_text(encoding="utf-8").strip().lower()
++ existing = path.read_text(encoding="utf-8-sig").strip().lower()
+ if _INSTALL_ID_RE.fullmatch(existing):
+ return existing
+ except FileNotFoundError:
+ pass
+ except (OSError, UnicodeDecodeError):
+ return None
+
+ try:
+ root.mkdir(parents=True, exist_ok=True)
+ except OSError:
+ return None
+
+ try:
+ # Windows byte-range locks can report a same-process lock conflict
+ # instead of waiting for another thread. Serialize threads here, then
+ # retain the file lock as the cross-process publication fence.
+ with _INSTALL_ID_PUBLICATION_LOCK, _install_id_file_lock(root):
+ try:
- existing = path.read_text(encoding="utf-8").strip().lower()
++ existing = path.read_text(encoding="utf-8-sig").strip().lower()
+ if _INSTALL_ID_RE.fullmatch(existing):
+ return existing
+ except FileNotFoundError:
+ pass
+ except (OSError, UnicodeDecodeError):
+ return None
+
+ minted = uuid.uuid4().hex
+ fd, tmp_name = tempfile.mkstemp(dir=str(root), prefix=".install_id-")
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ handle.write(minted + "\n")
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.replace(tmp_name, path)
+ _fsync_directory(root)
+ except BaseException:
+ with contextlib.suppress(OSError):
+ os.unlink(tmp_name)
+ raise
+
- committed = path.read_text(encoding="utf-8").strip().lower()
++ committed = path.read_text(encoding="utf-8-sig").strip().lower()
+ return committed if _INSTALL_ID_RE.fullmatch(committed) else None
+ except OSError:
+ return None
+
+
+ def get_install_id(
+ *,
+ cache: dict[str, Optional[str]] | None = None,
+ ) -> Optional[str]:
+ """Return the process-cached stable id for the active Hermes root."""
+ root = get_default_hermes_root()
+ root_key = str(root)
+ target_cache = _INSTALL_ID_CACHE if cache is None else cache
+ cached = target_cache.get("value")
+ if cached and target_cache.get("root") in (None, root_key):
+ return cached
+
+ with _INSTALL_ID_LOCK:
+ cached = target_cache.get("value")
+ if cached and target_cache.get("root") in (None, root_key):
+ return cached
+ value = read_or_create_install_id(root)
+ if value:
+ target_cache["root"] = root_key
+ target_cache["value"] = value
+ return value
+
+
+ __all__ = ["get_install_id", "read_or_create_install_id"]
diff --cc hermes_cli/kanban_transfer.py
index 00000000000,a5bf3aaab43..9d2e50ce688
mode 000000,100644..100644
--- a/hermes_cli/kanban_transfer.py
+++ b/hermes_cli/kanban_transfer.py
@@@ -1,0 -1,478 +1,478 @@@
+ """Kanban board export / import — move a whole board between machines.
+
+ Backs ``hermes kanban export|import``, the matching ``/boards/{slug}/export``
+ and ``/boards/import`` REST endpoints, and the desktop board switcher's
+ Export/Import items.
+
+ Archive layout (``<slug>.tar.gz``, one top-level directory named for the
+ source board's slug)::
+
+ <slug>/
+ manifest.json format + version + provenance + row counts
+ board.json display metadata, machine-local fields stripped
+ kanban.db consistent snapshot of the board database
+ attachments/<task>/… attachment blobs (unless --no-attachments)
+ logs/<task>.log worker logs (only with --include-logs)
+
+ Two things make this more than a ``tar czf`` of the board directory.
+
+ **The database is live.** Kanban runs in WAL mode and a dispatcher may be
+ mid-write, so copying ``kanban.db`` off the filesystem yields a torn
+ snapshot that is missing whatever still sits in the ``-wal`` file. Export
+ goes through SQLite's online-backup API instead, which produces a
+ consistent single-file image of a database that is being written to.
+
+ **Rows carry machine-local state.** Claims, PIDs, heartbeats, absolute
+ workspace and attachment paths, gateway chat subscriptions, and session
+ ids are all meaningful only on the machine that wrote them. Shipping them
+ verbatim is how an imported board arrives holding claims owned by a
+ process on somebody else's laptop, or starts pushing task events into a
+ stranger's Telegram thread. Everything machine-local is scrubbed on the
+ export side (so the archive itself never carries it) and defensively
+ re-scrubbed on import; see :func:`_scrub_local_state` and
+ :func:`_relocate_imported_rows`.
+
+ Imports always land as a **new** board — the slug auto-suffixes on
+ collision — so an import can never mutate a board that is already there.
+ That also means an imported board is never ``default``, which is what
+ lets the import side ignore the default board's split on-disk layout
+ (``<root>/kanban.db`` beside ``<root>/kanban/attachments/``) and put
+ everything inside one ``boards/<slug>/`` directory.
+ """
+
+ from __future__ import annotations
+
+ import contextlib
+ import json
+ import shutil
+ import sqlite3
+ import tempfile
+ import time
+ from pathlib import Path
+ from typing import Any, Optional
+
+ from hermes_cli import kanban_db as kb
+ from hermes_cli.archive_safe import (
+ archive_root_dirs,
+ copy_regular_files,
+ make_targz,
+ safe_extract_targz,
+ )
+
+ ARCHIVE_FORMAT = "hermes-kanban-board"
+ ARCHIVE_FORMAT_VERSION = 1
+
+ # Statuses from which the dispatcher can still act on a task. A task whose
+ # workspace cannot be rebuilt on this machine is parked in ``triage`` only
+ # if it is in one of these — terminal and already-parked tasks are left
+ # alone rather than having their history rewritten.
+ _DISPATCHABLE_STATUSES = ("ready", "running", "todo", "scheduled")
+
+
+ # ---------------------------------------------------------------------------
+ # Export
+ # ---------------------------------------------------------------------------
+
+ def _snapshot_db(source: Path, target: Path) -> None:
+ """Write a consistent copy of ``source`` to ``target``.
+
+ Uses SQLite's online-backup API rather than a file copy: in WAL mode
+ a just-committed page can still live in the ``-wal`` sidecar, so
+ copying only ``kanban.db`` loses recent writes and can produce a
+ torn image if the dispatcher commits mid-copy.
+ """
+ src = sqlite3.connect(str(source))
+ try:
+ dst = sqlite3.connect(str(target))
+ try:
+ src.backup(dst)
+ finally:
+ dst.close()
+ finally:
+ src.close()
+
+
+ def _scrub_local_state(conn: sqlite3.Connection) -> None:
+ """Strip machine-local runtime state. Caller owns the transaction.
+
+ Runs on the export side so the archive itself never carries another
+ machine's claims, PIDs, or — the one that actually matters for a
+ board shared with someone else — the gateway chat ids subscribed to
+ its task events. Repeated on import because an archive is untrusted
+ input.
+ """
+ conn.execute("DELETE FROM kanban_notify_subs")
+ conn.execute(
+ """
+ UPDATE tasks
+ SET claim_lock = NULL,
+ claim_expires = NULL,
+ worker_pid = NULL,
+ current_run_id = NULL,
+ last_heartbeat_at = NULL,
+ session_id = NULL,
+ project_id = NULL,
+ consecutive_failures = 0,
+ last_failure_error = NULL
+ """
+ )
+ # A task caught mid-run is not running anywhere the importer can see.
+ # Send it back to the queue rather than shipping a phantom claim.
+ conn.execute("UPDATE tasks SET status = 'ready' WHERE status = 'running'")
+ conn.execute(
+ """
+ UPDATE task_runs
+ SET status = 'released',
+ outcome = COALESCE(outcome, 'reclaimed'),
+ ended_at = COALESCE(ended_at, ?),
+ last_heartbeat_at = NULL
+ WHERE status = 'running'
+ """,
+ (int(time.time()),),
+ )
+ conn.execute("UPDATE task_runs SET claim_lock = NULL, worker_pid = NULL")
+
+
+ def _write_json(path: Path, payload: dict[str, Any]) -> None:
+ path.write_text(
+ json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
+ )
+
+
+ def _count_rows(conn: sqlite3.Connection) -> dict[str, int]:
+ tables = (
+ "tasks", "task_links", "task_comments",
+ "task_events", "task_runs", "task_attachments",
+ )
+ return {
+ t: int(conn.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0])
+ for t in tables
+ }
+
+
+ def export_board(
+ board: Optional[str],
+ output_path: str,
+ *,
+ include_attachments: bool = True,
+ include_logs: bool = False,
+ ) -> dict[str, Any]:
+ """Export ``board`` to a ``tar.gz`` archive. Returns a summary dict.
+
+ ``output_path`` may be given with or without the ``.tar.gz`` suffix.
+ Workspaces are never included: they are git worktrees and scratch
+ trees that are large, machine-local, and rebuilt on demand.
+ """
+ slug = kb._normalize_board_slug(board) or kb.get_current_board()
+ if not kb.board_exists(slug):
+ raise ValueError(f"board {slug!r} does not exist")
+
+ db_path = kb.kanban_db_path(slug)
+ if not db_path.exists():
+ raise FileNotFoundError(f"board {slug!r} has no database at {db_path}")
+
+ output = Path(output_path).expanduser()
+ base = str(output).removesuffix(".tar.gz").removesuffix(".tgz")
+ Path(base).parent.mkdir(parents=True, exist_ok=True)
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ staged = Path(tmpdir) / slug
+ staged.mkdir(parents=True)
+
+ _snapshot_db(db_path, staged / "kanban.db")
+ # The snapshot is a private file with no other writers, so plain
+ # commit/close is enough — no need for the board DB's WAL dance.
+ with contextlib.closing(sqlite3.connect(str(staged / "kanban.db"))) as snapshot:
+ _scrub_local_state(snapshot)
+ snapshot.commit()
+ counts = _count_rows(snapshot)
+
+ meta = kb.read_board_metadata(slug)
+ # Both name a location on the exporting machine; the importer
+ # resolves its own.
+ meta.pop("db_path", None)
+ meta["default_workdir"] = None
+ meta["project_id"] = None
+ _write_json(staged / "board.json", meta)
+
+ attachments = 0
+ if include_attachments:
+ attachments = copy_regular_files(
+ kb.attachments_root(slug), staged / "attachments"
+ )
+ logs = 0
+ if include_logs:
+ logs = copy_regular_files(
+ kb.worker_logs_dir(slug), staged / "logs"
+ )
+
+ try:
+ from hermes_cli import __version__ as hermes_version
+ except Exception:
+ hermes_version = ""
+
+ manifest = {
+ "format": ARCHIVE_FORMAT,
+ "format_version": ARCHIVE_FORMAT_VERSION,
+ "board": slug,
+ "board_name": meta.get("name") or slug,
+ "exported_at": int(time.time()),
+ "hermes_version": str(hermes_version),
+ "includes": {
+ "attachments": bool(include_attachments),
+ "logs": bool(include_logs),
+ },
+ "counts": {**counts, "attachment_files": attachments, "log_files": logs},
+ }
+ _write_json(staged / "manifest.json", manifest)
+
+ archive = make_targz(base, tmpdir, slug)
+
+ return {
+ "board": slug,
+ "archive": archive,
+ "size": Path(archive).stat().st_size,
+ "counts": manifest["counts"],
+ }
+
+
+ # ---------------------------------------------------------------------------
+ # Import
+ # ---------------------------------------------------------------------------
+
+ def _available_slug(preferred: str) -> str:
+ """Return ``preferred``, or the first free ``<preferred>-N`` variant.
+
+ ``default`` always reports as existing, so an archive exported from a
+ default board naturally lands as ``default-2`` instead of colliding
+ with the importer's own default board.
+ """
+ if not kb.board_exists(preferred):
+ return preferred
+ # Leave headroom for the suffix inside the 64-char slug limit.
+ stem = preferred[:58].rstrip("-_") or "board"
+ n = 2
+ while True:
+ candidate = f"{stem}-{n}"
+ if not kb.board_exists(candidate):
+ return candidate
+ n += 1
+
+
+ def _read_manifest(root: Path) -> dict[str, Any]:
+ path = root / "manifest.json"
+ if not path.exists():
+ raise ValueError(
+ "archive is not a Hermes kanban board export (no manifest.json)"
+ )
+ try:
- manifest = json.loads(path.read_text(encoding="utf-8"))
++ manifest = json.loads(path.read_text(encoding="utf-8-sig"))
+ except json.JSONDecodeError as exc:
+ raise ValueError(f"archive manifest is not valid JSON: {exc}") from exc
+ if not isinstance(manifest, dict) or manifest.get("format") != ARCHIVE_FORMAT:
+ raise ValueError(
+ "archive is not a Hermes kanban board export "
+ f"(format={manifest.get('format') if isinstance(manifest, dict) else None!r})"
+ )
+ version = manifest.get("format_version")
+ if not isinstance(version, int) or version > ARCHIVE_FORMAT_VERSION:
+ raise ValueError(
+ f"archive format version {version!r} is newer than this Hermes "
+ f"understands (max {ARCHIVE_FORMAT_VERSION}) — update Hermes and retry"
+ )
+ return manifest
+
+
+ def _read_board_metadata(path: Path) -> dict[str, Any]:
+ """Read an archive's ``board.json``, tolerating a missing/broken file."""
+ try:
- raw = json.loads(path.read_text(encoding="utf-8"))
++ raw = json.loads(path.read_text(encoding="utf-8-sig"))
+ except (OSError, json.JSONDecodeError):
+ return {}
+ return raw if isinstance(raw, dict) else {}
+
+
+ def _relocate_imported_rows(
+ conn: sqlite3.Connection, slug: str
+ ) -> tuple[dict[str, int], list[str]]:
+ """Re-anchor an imported board's rows to this machine.
+
+ Returns ``(stats, warnings)``. Three things move:
+
+ * Attachment rows are repointed at this board's attachments tree.
+ Rows whose blob did not travel (an export made with
+ ``--no-attachments``) are dropped, because a row pointing at a file
+ that does not exist breaks download in every UI that lists it.
+ * Workspace paths are cleared. ``scratch`` tasks regenerate one under
+ this board on the next claim, so they are simply reset. ``dir`` and
+ ``worktree`` tasks cannot be resolved without a path that means
+ something here, so any that are still dispatchable are parked in
+ ``triage`` — otherwise the dispatcher claims them, fails to build a
+ workspace, and burns them straight into the failure breaker.
+ * Runtime state is scrubbed again. Export already did this, but an
+ archive is an untrusted input and the cost is one UPDATE.
+ """
+ warnings: list[str] = []
+ now = int(time.time())
+ attachments_dir = kb.attachments_root(slug)
+
+ with kb.write_txn(conn):
+ _scrub_local_state(conn)
+
+ dropped = 0
+ rehomed = 0
+ for row in conn.execute(
+ "SELECT id, task_id, stored_path FROM task_attachments"
+ ).fetchall():
+ landed = attachments_dir / row["task_id"] / Path(row["stored_path"]).name
+ if landed.is_file():
+ conn.execute(
+ "UPDATE task_attachments SET stored_path = ? WHERE id = ?",
+ (str(landed), row["id"]),
+ )
+ rehomed += 1
+ else:
+ conn.execute(
+ "DELETE FROM task_attachments WHERE id = ?", (row["id"],)
+ )
+ dropped += 1
+ if dropped:
+ warnings.append(
+ f"{dropped} attachment record(s) dropped — the files were not "
+ f"in the archive"
+ )
+
+ parked = [
+ r["id"]
+ for r in conn.execute(
+ "SELECT id FROM tasks WHERE workspace_kind IN ('dir', 'worktree') "
+ f"AND status IN ({', '.join('?' * len(_DISPATCHABLE_STATUSES))})",
+ _DISPATCHABLE_STATUSES,
+ ).fetchall()
+ ]
+ conn.execute("UPDATE tasks SET workspace_path = NULL, branch_name = NULL")
+ if parked:
+ conn.execute(
+ f"UPDATE tasks SET status = 'triage' "
+ f"WHERE id IN ({', '.join('?' * len(parked))})",
+ parked,
+ )
+ warnings.append(
+ f"{len(parked)} task(s) moved to triage — their workspace was a "
+ f"directory or git worktree on the exporting machine and needs "
+ f"to be pointed somewhere on this one"
+ )
+
+ for row in conn.execute("SELECT id FROM tasks").fetchall():
+ conn.execute(
+ "INSERT INTO task_events (task_id, run_id, kind, payload, created_at) "
+ "VALUES (?, NULL, 'imported', ?, ?)",
+ (
+ row["id"],
+ json.dumps(
+ {
+ "board": slug,
+ "parked": row["id"] in parked,
+ },
+ ensure_ascii=False,
+ ),
+ now,
+ ),
+ )
+
+ return {"attachments": rehomed, "parked": len(parked)}, warnings
+
+
+ def import_board(
+ archive_path: str,
+ slug: Optional[str] = None,
+ *,
+ activate: bool = False,
+ ) -> dict[str, Any]:
+ """Import a board archive as a new board. Returns a summary dict.
+
+ ``slug`` overrides the name from the archive. Either way the final
+ slug auto-suffixes if it is taken, so an import never merges into or
+ overwrites an existing board.
+ """
+ archive = Path(archive_path).expanduser()
+ if not archive.exists():
+ raise FileNotFoundError(f"archive not found: {archive}")
+
+ roots = archive_root_dirs(archive)
+ if len(roots) != 1:
+ raise ValueError(
+ "a kanban board archive must contain exactly one top-level directory"
+ )
+ archive_root = roots.pop()
+
+ with tempfile.TemporaryDirectory() as tmpdir:
+ staging = Path(tmpdir)
+ safe_extract_targz(archive, staging)
+ extracted = staging / archive_root
+
+ manifest = _read_manifest(extracted)
+ staged_db = extracted / "kanban.db"
+ if not staged_db.is_file():
+ raise ValueError("archive is missing kanban.db")
+
+ requested = kb._normalize_board_slug(
+ slug or manifest.get("board") or archive_root
+ )
+ if not requested:
+ raise ValueError(
+ "cannot determine a board name from the archive — pass one "
+ "explicitly with --as <slug>"
+ )
+ target = _available_slug(requested)
+
+ staged_meta = _read_board_metadata(extracted / "board.json")
+
+ board_root = kb.board_dir(target)
+ board_root.mkdir(parents=True, exist_ok=True)
+ shutil.move(str(staged_db), str(board_root / "kanban.db"))
+ for tree in ("attachments", "logs"):
+ src = extracted / tree
+ if src.is_dir():
+ shutil.move(str(src), str(board_root / tree))
+
+ # Rewritten rather than moved across: the archive's copy names a slug
+ # and a workdir that belong to the exporting machine.
+ name = str(staged_meta.get("name") or manifest.get("board_name") or target)
+ kb.write_board_metadata(
+ target,
+ name=name,
+ description=str(staged_meta.get("description") or ""),
+ icon=str(staged_meta.get("icon") or ""),
+ color=str(staged_meta.get("color") or ""),
+ archived=False,
+ )
+ # Bring the imported schema up to this install's version before the
+ # relocation pass writes to it.
+ kb.init_db(board=target)
+
+ with kb.connect_closing(board=target) as conn:
+ stats, warnings = _relocate_imported_rows(conn, target)
+ counts = _count_rows(conn)
+
+ if activate:
+ kb.set_current_board(target)
+
+ return {
+ "board": target,
+ "requested_board": requested,
+ "renamed": target != requested,
+ "name": name,
+ "path": str(kb.board_dir(target)),
+ "db_path": str(kb.kanban_db_path(target)),
+ "source": {
+ "board": manifest.get("board"),
+ "exported_at": manifest.get("exported_at"),
+ "hermes_version": manifest.get("hermes_version"),
+ },
+ "counts": counts,
+ "attachments_restored": stats["attachments"],
+ "tasks_parked": stats["parked"],
+ "warnings": warnings,
+ "activated": bool(activate),
+ }
diff --cc hermes_cli/local_runtime/__init__.py
index 00000000000,9793970b5f1..a69afb4ca4b
mode 000000,100644..100644
--- a/hermes_cli/local_runtime/__init__.py
+++ b/hermes_cli/local_runtime/__init__.py
@@@ -1,0 -1,55 +1,56 @@@
+ """Managed llama.cpp runtime.
+
+ Hermes downloads, verifies, supervises, and updates one llama-server, and
+ decides per machine which model build and context window to run. Key
+ modules:
+
-- ``binaries`` — resolve/download/verify official llama.cpp release zips
- into ``$HERMES_HOME/runtimes/llamacpp/<tag>/``.
++- ``binaries`` — which backend build this machine runs (the binaries
++ themselves are pm packages, in pm's machine-wide store)
++ and where the runtime's own state lives.
+ - ``supervisor``— spawn and supervise one llama-server in router mode;
+ readiness is a touch generation, never health-200 alone.
+ - ``detect`` — find an already-running llama-server (external or ours).
+ - ``estimator`` / ``context_policy`` / ``growth`` — price context memory
+ per architecture and run the window ladder (zero-spill start, grow
+ toward native max, compress only at the top).
+ - ``catalog`` / ``presets`` — the curated model list and the per-model
+ launch flags that carry policy decisions to the router.
+
+ Everything is driven by the ``local_runtime`` section of config.yaml.
+ """
+
+ from hermes_cli.local_runtime.binaries import ( # noqa: F401
+ BinaryResolutionError,
- ensure_runtime_installed,
- resolve_assets,
++ ensure_engine,
++ installed_backends,
+ select_backend,
+ )
+ from hermes_cli.local_runtime.bootstrap import ( # noqa: F401
+ ensure_local_runtime,
+ shutdown_local_runtime,
+ )
+ from hermes_cli.local_runtime.context_policy import ( # noqa: F401
+ FLOOR,
+ growth_decision,
+ initial_window,
+ ladder,
+ launch_args,
+ )
+ from hermes_cli.local_runtime.growth import ( # noqa: F401
+ clear_window_override,
+ load_window_overrides,
+ maybe_grow_window,
+ save_window_override,
+ )
+ from hermes_cli.local_runtime.detect import detect_server # noqa: F401
+ from hermes_cli.local_runtime.endpoint import resolve_llamacpp_endpoint # noqa: F401
+ from hermes_cli.local_runtime.estimator import ( # noqa: F401
+ HardwareBudget,
+ ctx_bytes,
+ physics_check,
+ profile_from_gguf,
+ )
+ from hermes_cli.local_runtime.gguf import read_gguf_header # noqa: F401
+ from hermes_cli.local_runtime.hardware import probe_budget # noqa: F401
+ from hermes_cli.local_runtime.presets import generate_presets # noqa: F401
+ from hermes_cli.local_runtime.supervisor import LlamaServerSupervisor # noqa: F401
diff --cc hermes_cli/local_runtime/binaries.py
index 00000000000,bcd7d32a1d7..eedc58f4ba1
mode 000000,100644..100644
--- a/hermes_cli/local_runtime/binaries.py
+++ b/hermes_cli/local_runtime/binaries.py
@@@ -1,0 -1,351 +1,193 @@@
-"""Binary acquisition for the managed llama.cpp runtime.
++"""Which llama.cpp build this machine runs, and where its state lives.
+
-llama.cpp publishes per-tag assets (rolling ``bNNNN`` tags, no semver).
-Backends are dlopen'd plugins, so a runtime = CPU/base zip + backend zip
-extracted into one directory, plus the cudart runtime zip on Windows CUDA
-(end users have no CUDA toolkit). We pin the tag in config, sha256-verify
-every download, and keep the previous tag for rollback (N-1).
++The engine BINARIES are pm packages (``llamacpp-cuda`` and friends): pm owns
++the urls, digests, download, extraction, and the machine-wide store, exactly
++as it does for node, ripgrep, and the browser. This module answers only the
++questions the build cannot:
+
-Layout: ``$HERMES_HOME/runtimes/llamacpp/<tag>/<backend>/<binaries>``
-with a ``manifest.json`` recording zips, sha256s, and the verified
-llama-server version string.
++- which backend this machine's hardware can use, and
++- where the runtime's own STATE goes (presets, server endpoint, api key,
++ window overrides) — state is not bytes and does not belong in the store.
+ """
+
+ from __future__ import annotations
+
-import hashlib
-import json
+ import logging
-import platform
-import shutil
-import subprocess
-import urllib.request
-import zipfile
-from dataclasses import dataclass, field
+ from pathlib import Path
-from typing import Callable
-
-from hermes_constants import get_hermes_home
+
+ logger = logging.getLogger(__name__)
+
-RELEASE_URL = "https://github.com/ggml-org/llama.cpp/releases/download/{tag}/{asset}"
-
-# Windows CUDA zips ship per CUDA major; the runtime zip must be paired with
-# its cudart zip so end users need no toolkit. 13.3 verified on 13.1 and
-# 13.2 drivers.
-_WIN_CUDA_VERSION = "13.3"
-# arm64 Windows CUDA prebuilts landed upstream (~b1036x) on CUDA 13.4 —
-# verified against live asset lists (b10362, b10630, b10679). Tags at or before
-# b10290 don't have them; resolution succeeds and the download 404s
-# honestly on such tags, which only arises if a user pins backward.
-_WIN_CUDA_VERSION_ARM64 = "13.4"
-
-
-# Fallback when the config section is missing entirely (deep-merge normally
-# guarantees the key). Single source: DEFAULT_CONFIG owns the shipped tag.
-def default_tag() -> str:
- from hermes_cli.config_defaults import DEFAULT_CONFIG
++# Backend -> pm package. Backends are dlopen'd plugins built into separate
++# release archives, so each is its own optional package; upstream's gaps
++# (no prebuilt Linux CUDA, no win-arm64 vulkan) are declared there and
++# surface as an honest refusal instead of a 404 mid-download.
++BACKEND_PACKAGES = {
++ "cuda": "llamacpp-cuda",
++ "vulkan": "llamacpp-vulkan",
++ "metal": "llamacpp-metal",
++ "cpu": "llamacpp-cpu",
++}
+
- return DEFAULT_CONFIG["local_runtime"]["tag"]
++# Preference order when the configured backend is unavailable here.
++_LADDER = ("cuda", "metal", "vulkan", "cpu")
+
+
+ class BinaryResolutionError(RuntimeError):
- """No usable asset combination for this platform/backend."""
++ """No usable llama.cpp build for this platform/backend."""
+
+
-@dataclass
-class AssetPlan:
- """The exact zips one runtime install needs, in extraction order."""
++def runtime_state_root() -> Path:
++ """Machine-scoped, deliberately NOT profile-scoped. Presets, the server
++ endpoint, and the api key describe this machine's hardware and its one
++ managed server (stable port) — a second profile fighting over the port
++ would be the bug. Profile-scoped things (which model is the default,
++ enabled) live in each profile's config.yaml as ever.
+
- tag: str
- backend: str # cuda | metal | vulkan | hip | cpu
- assets: list[str] = field(default_factory=list)
-
- @property
- def install_dir(self) -> Path:
- return runtimes_root() / self.tag / self.backend
-
-
-def runtimes_root() -> Path:
- """Machine-scoped, deliberately NOT profile-scoped. Engine binaries,
- presets, and server state describe this machine's hardware and its one
- managed server (stable port) — a second profile re-downloading the
- engine or fighting over the port would be the bug. Profile-scoped
- things (which model is the default, enabled) live in each profile's
- config.yaml as ever."""
++ Only STATE lives here; the binaries are in pm's store, shared the same
++ way and garbage-collected by `hermes pm gc`.
++ """
+ from hermes_constants import get_default_hermes_root
+
+ return get_default_hermes_root() / "runtimes" / "llamacpp"
+
+
-def installed_tags() -> list[str]:
- """Tags with a verified install (manifest carries verified_version),
- newest first by release number. The boot ladder and the update check
- both read installed-ness from here — one resolver, every caller."""
- root = runtimes_root()
- if not root.exists():
- return []
- found: list[str] = []
- for entry in root.iterdir():
- if not entry.is_dir() or entry.name == "downloads":
- continue
- for manifest in entry.glob("*/manifest.json"):
- try:
- if json.loads(manifest.read_text(encoding="utf-8")).get("verified_version"):
- found.append(entry.name)
- break
- except (json.JSONDecodeError, OSError):
- continue
-
- def _release_number(tag: str) -> int:
- digits = "".join(ch for ch in tag if ch.isdigit())
- return int(digits) if digits else 0
-
- return sorted(set(found), key=_release_number, reverse=True)
-
-
-def _host_os_arch() -> tuple[str, str]:
- """(os, arch) normalized to release-asset vocabulary.
-
- PITFALL: PROCESSOR_ARCHITECTURE lies under x64 emulation on
- ARM64 Windows. platform.machine() reads the same env on some Pythons, so
- on Windows prefer PROCESSOR_IDENTIFIER's text when present.
- """
- system = platform.system().lower()
- os_name = {"windows": "win", "darwin": "macos", "linux": "ubuntu"}.get(system, system)
- machine = platform.machine().lower()
- arch = "arm64" if machine in ("arm64", "aarch64") else "x64"
- if os_name == "win":
- import os as _os
- ident = _os.environ.get("PROCESSOR_IDENTIFIER", "")
- if "armv8" in ident.lower() or "arm " in ident.lower():
- arch = "arm64"
- return os_name, arch
++def models_root() -> Path:
++ """Machine-scoped for the same reason: a 20 GB GGUF is a machine asset,
++ and every profile shares the one managed server that serves it."""
++ from hermes_constants import get_default_hermes_root
++
++ return get_default_hermes_root() / "models"
+
+
+ def select_backend(gpu_vendor: str | None, os_name: str | None = None) -> str:
+ """Backend choice per design: CUDA if NVIDIA, Metal on macOS, Vulkan if
+ a non-NVIDIA GPU is present, else CPU. ``--list-devices`` validates the
+ choice post-install; the supervisor's touch generation is ground truth."""
++ import sys
++
+ if os_name is None:
- os_name, _ = _host_os_arch()
++ os_name = "macos" if sys.platform == "darwin" else "other"
+ if os_name == "macos":
+ return "metal"
+ vendor = (gpu_vendor or "").lower()
+ if "nvidia" in vendor:
+ return "cuda"
+ if vendor in ("amd", "intel") or "radeon" in vendor or "arc" in vendor:
+ return "vulkan"
+ return "cpu"
+
+
-def resolve_assets(tag: str, backend: str, os_name: str | None = None,
- arch: str | None = None) -> AssetPlan:
- """Compose the asset list for (tag, backend, platform).
-
- Raises BinaryResolutionError for combinations the release does not ship
- (a platform/backend pair upstream publishes no artifact for). Callers
- fall back down the backend ladder: cuda -> vulkan -> cpu.
- """
- host_os, host_arch = _host_os_arch()
- os_name = os_name or host_os
- arch = arch or host_arch
- plan = AssetPlan(tag=tag, backend=backend)
-
- if os_name == "macos":
- # macOS tarballs are unified (Metal built in).
- plan.assets = [f"llama-{tag}-bin-macos-{arch}.tar.gz"]
- return plan
-
- if os_name == "ubuntu":
- if backend == "cuda":
- # No prebuilt Linux CUDA zips at current tags — Linux CUDA users
- # build from source or use vulkan; resolver is honest about it.
- raise BinaryResolutionError(
- f"no prebuilt linux CUDA asset at {tag}; use vulkan/cpu or a source build")
- suffix = {"vulkan": f"vulkan-{arch}", "hip": f"rocm-7.2-{arch}",
- "cpu": arch}.get(backend)
- if suffix is None:
- raise BinaryResolutionError(f"unsupported linux backend {backend}")
- plan.assets = [f"llama-{tag}-bin-ubuntu-{suffix}.tar.gz"]
- return plan
-
- if os_name == "win":
- if backend == "cuda":
- cuda_ver = _WIN_CUDA_VERSION_ARM64 if arch == "arm64" else _WIN_CUDA_VERSION
- plan.assets = [
- f"llama-{tag}-bin-win-cuda-{cuda_ver}-{arch}.zip",
- f"cudart-llama-bin-win-cuda-{cuda_ver}-{arch}.zip",
- ]
- elif backend == "vulkan":
- if arch == "arm64":
- raise BinaryResolutionError(f"no win-vulkan-arm64 asset at {tag}")
- plan.assets = [f"llama-{tag}-bin-win-vulkan-x64.zip"]
- elif backend == "hip":
- plan.assets = [f"llama-{tag}-bin-win-hip-radeon-x64.zip"]
- elif backend == "cpu":
- plan.assets = [f"llama-{tag}-bin-win-cpu-{arch}.zip"]
- else:
- raise BinaryResolutionError(f"unsupported windows backend {backend}")
- return plan
-
- raise BinaryResolutionError(f"unsupported platform {os_name}-{arch}")
-
-
-def _sha256(path: Path) -> str:
- h = hashlib.sha256()
- with open(path, "rb") as f:
- for chunk in iter(lambda: f.read(1 << 22), b""):
- h.update(chunk)
- return h.hexdigest()
-
-
-def _download(url: str, dest: Path,
- progress: "Callable[[int, int], None] | None" = None) -> None:
- """Stream url -> dest. ``progress(done_bytes, total_bytes)`` ticks per
- chunk (total 0 when the server sends no Content-Length) — a several-
- hundred-MB archive on a slow line must never look hung."""
- logger.info("downloading %s", url)
- tmp = dest.with_suffix(dest.suffix + ".part")
- with urllib.request.urlopen(url, timeout=120) as r, open(tmp, "wb") as f:
- total = int(r.headers.get("Content-Length") or 0)
- done = 0
- while True:
- chunk = r.read(1 << 20)
- if not chunk:
- break
- f.write(chunk)
- done += len(chunk)
- if progress is not None:
- progress(done, total)
- tmp.replace(dest)
-
-
-def _extract(archive: Path, dest: Path,
- progress: "Callable[[int, int], None] | None" = None) -> None:
- """Extract member by member so ``progress(done, total)`` can tick in
- uncompressed bytes — big archives take real time on laptop disks."""
- if archive.name.endswith(".zip"):
- with zipfile.ZipFile(archive) as z:
- members = z.infolist()
- total = sum(m.file_size for m in members)
- done = 0
- for m in members:
- z.extract(m, dest)
- done += m.file_size
- if progress is not None:
- progress(done, total)
- else:
- import tarfile
- with tarfile.open(archive) as t:
- members = t.getmembers()
- total = sum(m.size for m in members)
- done = 0
- for m in members:
- t.extract(m, dest, filter="data")
- done += m.size
- if progress is not None:
- progress(done, total)
-
-
-def server_binary(install_dir: Path) -> Path:
- """Locate llama-server within an extracted runtime (zips differ in
- whether they nest a build/bin directory)."""
- names = ("llama-server.exe", "llama-server")
- for name in names:
- direct = install_dir / name
- if direct.exists():
- return direct
- for name in names:
- hits = sorted(install_dir.rglob(name))
- if hits:
- return hits[0]
- raise BinaryResolutionError(f"llama-server not found under {install_dir}")
-
-
-def verify_install(install_dir: Path, tag: str) -> str:
- """Run --version; require the tag's build number in the output.
- (The binary prints the tag WITHOUT the 'b' prefix.)"""
- exe = server_binary(install_dir)
- out = subprocess.run([str(exe), "--version"], capture_output=True,
- text=True, encoding="utf-8", errors="replace",
- timeout=60, cwd=str(exe.parent))
- text = (out.stdout + out.stderr).strip()
- if tag.lstrip("b") not in text:
- raise BinaryResolutionError(
- f"version check failed for {exe}: expected {tag}, got: {text[:120]}")
- return text.splitlines()[0] if text else ""
-
-
-def prune_old_tags(keep: list[str]) -> None:
- """Retain only the tags in ``keep`` (current + previous — N-1 rollback).
- The shared ``downloads/`` archive cache is not a tag and always survives."""
- root = runtimes_root()
- if not root.exists():
- return
- for entry in root.iterdir():
- if entry.is_dir() and entry.name != "downloads" and entry.name not in keep:
- shutil.rmtree(entry, ignore_errors=True)
- logger.info("pruned old runtime %s", entry.name)
-
-
-def ensure_runtime_installed(tag: str, backend: str,
- expected_sha256: dict[str, str] | None = None,
- progress: "Callable[[str, int, int, str], None] | None" = None) -> Path:
- """Idempotent: resolve, download, verify, extract, version-check.
-
- ``expected_sha256`` maps asset name -> hash when the catalog pins them;
- without pins the computed hash is recorded in the manifest (trust on
- first download, verified on every reinstall).
- ``progress(stage, done_bytes, total_bytes, label)`` ticks through the
- slow parts — stage is "download" | "extract" | "verify", label is the
- asset counter ("1/2") when the plan has several archives.
- Returns the install directory containing llama-server.
++def unavailable_reason(backend: str) -> str | None:
++ """Why this backend cannot run here, or None when it can. The reason is
++ the pin table's own declared gap, quoted verbatim — an unpinned
++ combination is knowable before any download starts."""
++ from pm.registry import get_package
++ from pm.store import current_target
++
++ name = BACKEND_PACKAGES.get(backend)
++ if name is None:
++ return f"unknown backend {backend}"
++ return get_package(name).missing_reason(current_target())
++
++
++def resolve_backend(backend: str) -> str:
++ """The backend to actually install: the requested one when this
++ platform has a build, else the best available rung below it. Raises
++ when nothing is available (which the pin table makes impossible in
++ practice — every target has a cpu build)."""
++ tried = [backend] + [b for b in _LADDER if b != backend]
++ reasons = []
++ for candidate in tried:
++ reason = unavailable_reason(candidate)
++ if reason is None:
++ if candidate != backend:
++ logger.info("backend %s unavailable here; using %s", backend, candidate)
++ return candidate
++ reasons.append(f"{candidate}: {reason}")
++ raise BinaryResolutionError("; ".join(reasons))
++
++
++def installed_backends() -> list[str]:
++ """Backends with an engine on disk, in ladder order. Deliberately NOT
++ version-gated: an engine from a previous pin still serves, and the
++ boot ladder must keep working after a lockfile bump. One resolver —
++ the boot ladder and the status pane both read from here."""
++ from pm.ensure import _facts, _store
++
++ facts = _facts()
++ root = _store().root
++ return [
++ b for b in _LADDER if facts.installed(BACKEND_PACKAGES[b], None, root)
++ ]
++
++
++def engine_update_pending() -> bool:
++ """True when an installed engine is older than the pinned one. The
++ lockfile is the version authority, so an update arrives with a Hermes
++ release; installing it is a button click, never automatic."""
++ from pm.ensure import is_installed
++
++ installed = installed_backends()
++ return bool(installed) and not all(
++ is_installed(BACKEND_PACKAGES[b]) for b in installed
++ )
++
++
++def engine_version() -> str | None:
++ """The pinned llama.cpp release tag (bNNNN). The lockfile is the one
++ version authority; there is no user-settable tag to disagree with it."""
++ from pm.ensure import _lockfile
++
++ version = _lockfile().version("llamacpp-cpu")
++ return f"b{version}" if version else None
++
++
++def installed_engine_version(backend: str) -> str | None:
++ """The release tag of an installed backend's engine, or None."""
++ from pm.ensure import _facts
++
++ fact = _facts().get(BACKEND_PACKAGES.get(backend, ""))
++ return f"b{fact['version']}" if fact else None
++
++
++def server_binary(backend: str) -> Path:
++ """llama-server for an INSTALLED backend. Never installs — callers that
++ want an install call ensure_engine()."""
++ from pm.ensure import _facts, _store
++ from pm.registry import get_package
++ from pm.store import current_target
++
++ name = BACKEND_PACKAGES.get(backend)
++ if name is None:
++ raise BinaryResolutionError(f"unknown backend {backend}")
++ fact = _facts().get(name)
++ if fact is None:
++ raise BinaryResolutionError(f"llama.cpp {backend} build is not installed")
++ binary = get_package(name).binary(_store().entry(fact["entry"]), current_target())
++ if binary is None or not binary.is_file():
++ raise BinaryResolutionError(f"llama.cpp {backend} entry is missing its binary")
++ return binary
++
++
++def ensure_engine(backend: str, progress=None) -> tuple[str, Path]:
++ """Install (if needed) and return ``(backend, llama-server path)``.
++
++ Idempotent, digest-verified, and shared machine-wide — all of that is
++ pm's. ``progress(stage, done, total, label)`` ticks through the slow
++ parts for the install pane.
++
++ Marked explicit: every caller is a deliberate "install the engine"
++ click, which is exactly the consent the lazy-install policy asks for.
++ A sealed payload still refuses — asking a bundle for more than it
++ shipped is a packaging bug, not something a download can fix. Nothing
++ on the boot path calls this; boot serves what is already installed.
+ """
- plan = resolve_assets(tag, backend)
- install_dir = plan.install_dir
- manifest_path = install_dir / "manifest.json"
- if manifest_path.exists():
- try:
- manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
- if manifest.get("verified_version"):
- return install_dir
- except (json.JSONDecodeError, OSError):
- pass # damaged manifest -> reinstall
-
- install_dir.mkdir(parents=True, exist_ok=True)
- downloads = runtimes_root() / "downloads"
- downloads.mkdir(parents=True, exist_ok=True)
-
- recorded: dict[str, str] = {}
- n_assets = len(plan.assets)
- for i, asset in enumerate(plan.assets, 1):
- label = f"{i}/{n_assets}" if n_assets > 1 else ""
- archive = downloads / asset
- if not archive.exists():
- _download(RELEASE_URL.format(tag=tag, asset=asset), archive,
- progress=(lambda d, t, _l=label: progress("download", d, t, _l))
- if progress is not None else None)
- if progress is not None:
- progress("verify", 0, 0, label)
- digest = _sha256(archive)
- expected = (expected_sha256 or {}).get(asset)
- if expected and digest != expected:
- archive.unlink(missing_ok=True)
- raise BinaryResolutionError(
- f"sha256 mismatch for {asset}: expected {expected}, got {digest}")
- recorded[asset] = digest
- _extract(archive, install_dir,
- progress=(lambda d, t, _l=label: progress("extract", d, t, _l))
- if progress is not None else None)
-
- if progress is not None:
- progress("verify", 0, 0, "")
- version = verify_install(install_dir, tag)
- manifest_path.write_text(json.dumps({
- "tag": tag, "backend": plan.backend, "assets": recorded,
- "verified_version": version,
- }, indent=2), encoding="utf-8")
- logger.info("installed llama.cpp %s (%s): %s", tag, backend, version)
- return install_dir
++ from pm.ensure import ensure
++ from pm.package import InstallError
++
++ resolved = resolve_backend(backend)
++ try:
++ ensure(BACKEND_PACKAGES[resolved], progress=progress, explicit=True)
++ except InstallError as exc:
++ raise BinaryResolutionError(str(exc)) from exc
++ return resolved, server_binary(resolved)
diff --cc hermes_cli/local_runtime/bootstrap.py
index 00000000000,9d440e83d8e..a6ad24c07e0
mode 000000,100644..100644
--- a/hermes_cli/local_runtime/bootstrap.py
+++ b/hermes_cli/local_runtime/bootstrap.py
@@@ -1,0 -1,321 +1,320 @@@
+ """Bootstrap for the managed runtime: config -> installed binaries ->
+ running supervised server.
+
+ One public call, ``ensure_local_runtime(config)``, safe to call at any
+ session start:
+ - disabled or already-running (state file answers /health) -> no-op
+ - enabled -> install binaries if missing (idempotent), spawn supervisor
+
+ Kept import-light: callers gate on config before importing this module so
+ sessions with local_runtime disabled never pay the import.
+ """
+
+ from __future__ import annotations
+
+ import logging
+ import os
+ import subprocess
+ import time
+ from pathlib import Path
+
+ from hermes_constants import get_hermes_home # noqa: F401 — config paths
+
-from hermes_cli.local_runtime.binaries import runtimes_root
++from hermes_cli.local_runtime.binaries import runtime_state_root
+
+ logger = logging.getLogger(__name__)
+
+ _SUPERVISOR = None # process-wide singleton; one router per Hermes process
+
+
+ def _detect_gpu_vendor() -> str | None:
+ """Best-effort GPU vendor for backend selection. NVIDIA via nvidia-smi
+ (resolved by the hardware probe's PATH-independent ladder — a stripped
+ service PATH must not demote an NVIDIA box to vulkan/cpu); anything
+ else defers to select_backend's fallback ladder."""
+ from hermes_cli.local_runtime.hardware import _nvidia_smi_path
+
+ smi = _nvidia_smi_path()
+ if smi is None:
+ return None
+ try:
+ out = subprocess.run(
+ [smi, "--query-gpu=name", "--format=csv,noheader"],
+ capture_output=True, text=True, timeout=10)
+ if out.returncode == 0 and out.stdout.strip():
+ return "nvidia " + out.stdout.strip().splitlines()[0]
+ except (OSError, subprocess.TimeoutExpired):
+ pass
+ return None
+
+
+ def models_dir() -> Path:
+ """Machine-scoped, deliberately NOT profile-scoped: a 20 GB GGUF is a
+ machine asset, and every profile shares the one managed server that
- serves it. See runtimes_root() for the same rule on the engine."""
- from hermes_constants import get_default_hermes_root
++ serves it. See runtime_state_root() for the same rule on the engine."""
++ from hermes_cli.local_runtime.binaries import models_root
+
- return get_default_hermes_root() / "models"
++ return models_root()
+
+
+ def assets_dir() -> Path:
+ """Non-model companion files (mmproj vision projectors, spec-decode
+ draft models). A subdirectory so the router's model listing — and our
+ staged_models() — never mistakes an asset for a servable model."""
+ return models_dir() / "assets"
+
+
+ def staged_models() -> "list[Path]":
+ """Servable staged models: single-file GGUFs count when present; a
+ split GGUF counts once, by its first part, and only when EVERY part
+ is on disk — a mid-download split is not servable and must not
+ surface anywhere as a model. Continuation parts and assets/ never
+ count."""
+ import re
+
+ part = re.compile(r"-(\d{5})-of-(\d{5})\.gguf$")
+ files = sorted(models_dir().glob("*.gguf"))
+ names = {p.name for p in files}
+ out = []
+ for p in files:
+ m = part.search(p.name)
+ if m is None:
+ out.append(p)
+ continue
+ if m.group(1) != "00001":
+ continue
+ stem = p.name[: m.start()]
+ total = int(m.group(2))
+ if all(f"{stem}-{i:05d}-of-{m.group(2)}.gguf" in names
+ for i in range(2, total + 1)):
+ out.append(p)
+ return out
+
+
+ def staged_model_ids() -> "list[str]":
+ import re
+
+ return [re.sub(r"-\d{5}-of-\d{5}$", "", p.stem) for p in staged_models()]
+
+
+ def _presets_stale() -> bool:
+ """True when a staged model has no section in the preset INI — it
+ would autoload with stock fit instead of a policy decision."""
+ try:
+ from hermes_cli.local_runtime.presets import read_preset_decisions
+
+ known = set(read_preset_decisions())
+ return any(mid not in known for mid in staged_model_ids())
+ except Exception: # noqa: BLE001
+ return False
+
+
+ def _stop_state_server(state: dict) -> None:
+ """Best-effort stop of the server the state file points at (an
+ incumbent this process doesn't supervise). The state pid is ours by
+ contract — the file only ever describes the managed server."""
+ pid = state.get("pid")
+ if not pid:
+ return
+ try:
+ import signal
+
+ os.kill(int(pid), signal.SIGTERM)
+ except (OSError, ValueError):
+ return
++ # Liveness probe: do NOT use os.kill(pid, 0) here — on Windows that
++ # TERMINATES the process instead of probing (see endpoint.py). Use
++ # psutil.pid_exists, which is a safe existence check on all platforms.
++ import psutil # type: ignore
++
+ # Give it a moment to release the port and the GPU.
+ for _ in range(50):
- try:
- os.kill(int(pid), 0)
- except OSError:
++ if not psutil.pid_exists(int(pid)):
+ return
+ time.sleep(0.1)
+
+
+ def refresh_local_runtime() -> bool:
+ """Restart the managed server so it rescans the models directory.
+
+ The router's model list is SPAWN-ONLY: a GGUF added after start is
+ invisible to GET /models and 400s on completion, so anything that
+ changes the staged set while the server runs must bounce it. Covers
+ both ownership shapes: a supervised server restarts in-process; an
+ ADOPTED server (started by a previous backend session — the normal
+ shape after any restart) is stopped via its state-file pid and
+ replaced with a supervised boot. Without the adopted branch, every
+ download/delete in a post-restart session silently no-ops the bounce
+ and the router serves a stale catalog. Returns False when there is
+ nothing to refresh (no server anywhere; next boot scans fresh).
+ """
+ global _SUPERVISOR
+ try:
+ from hermes_cli.config import load_config
+
+ if _SUPERVISOR is None:
+ from hermes_cli.local_runtime.endpoint import _state_endpoint
+
+ state = _state_endpoint()
+ if state is None:
+ return False
+ logger.info("bouncing adopted llama-server (pid=%s) to rescan models",
+ state.get("pid"))
+ _stop_state_server(state)
+ else:
+ shutdown_local_runtime()
+ return ensure_local_runtime(load_config(), force=True) is not None
+ except Exception as exc: # noqa: BLE001
+ logger.warning("local runtime refresh failed: %s", exc)
+ return False
+
+
+ def ensure_local_runtime(config: dict, force: bool = False) -> "object | None":
+ """Idempotent boot of the managed runtime. Returns the supervisor (or
+ None when disabled/unavailable). Never raises into a session start —
+ failures log and return None; chat falls back to configured providers.
+
+ ``force=True`` skips the enabled gate — used by the explicit "Use this
+ model" action, where the click IS the opt-in (the caller records it in
+ config so future boots auto-start).
+ """
+ global _SUPERVISOR
+ section = (config or {}).get("local_runtime") or {}
+ if not force and not section.get("enabled"):
+ return None
+ if _SUPERVISOR is not None:
+ return _SUPERVISOR
+
+ # Residency: no staged models means nothing to serve — don't boot an
+ # empty server. The walked-away story handled with zero configuration
+ # (delete your last model and boots stop); Use force-boots as ever.
+ if not force and not staged_models():
+ logger.info("local runtime enabled but no models staged; not booting")
+ return None
+
+ # Another Hermes process may already be supervising — reuse via state,
+ # but ONLY while its launch policy still covers every staged model. A
+ # server whose preset file predates a download serves the new model
+ # with no policy at all (--models-autoload + stock fit: f16 KV at max
+ # context, no placement — the silent-demotion busy-wait on WDDM). A
+ # stale incumbent gets stopped and replaced by a fresh boot with
+ # regenerated presets; sessions ride through exactly like any other
+ # supervised restart (stable port + persisted key).
+ from hermes_cli.local_runtime.endpoint import _state_endpoint
+
+ state = _state_endpoint()
+ if state is not None:
+ if not _presets_stale():
+ logger.info("managed llama-server already running (another process)")
+ return None
+ logger.info("running server's presets predate the staged models; "
+ "replacing it so every model launches with a policy")
+ _stop_state_server(state)
+
+ try:
+ from hermes_cli.local_runtime.binaries import (
- ensure_runtime_installed,
++ installed_backends,
++ resolve_backend,
+ select_backend,
++ server_binary,
+ )
+ from hermes_cli.local_runtime.hardware import probe_budget
+ from hermes_cli.local_runtime.presets import generate_presets
+ from hermes_cli.local_runtime.supervisor import LlamaServerSupervisor
+
+ backend = section.get("backend", "auto")
+ if backend == "auto":
+ backend = select_backend(_detect_gpu_vendor())
- # Boot ladder: serve what is INSTALLED, never download here. The
- # configured tag (config root-of-trust; deep-merge supplies the
- # Hermes-release default when unpinned) is preferred; when it isn't
- # installed yet, the newest installed tag serves and the status
- # endpoint reports the pending update — the download is a deliberate
- # button click in the pane, not a boot-path surprise (a multi-minute
- # inline download here is exactly how the onboarding bounce returns).
- from hermes_cli.local_runtime.binaries import default_tag, installed_tags
-
- tag = section.get("tag") or default_tag()
- have = installed_tags()
- if tag not in have:
++ backend = resolve_backend(backend)
++ # Boot ladder: serve what is INSTALLED, never download here. A
++ # multi-minute inline engine download at session start is exactly
++ # how the onboarding bounce returns — installing is a deliberate
++ # button click in the Local Models pane.
++ have = installed_backends()
++ if backend not in have:
+ if not have:
- logger.info("local runtime enabled but no build installed; "
++ logger.info("local runtime enabled but no engine installed; "
+ "install happens in the Local Models pane")
+ return None
- logger.info("configured tag %s not installed; serving %s "
- "(update is a click in Local Models)", tag, have[0])
- tag = have[0]
- install_dir = ensure_runtime_installed(tag, backend)
++ logger.info("%s engine not installed; serving the %s build", backend, have[0])
++ backend = have[0]
++ server_exe = server_binary(backend)
+
+ mdir = models_dir()
+ mdir.mkdir(parents=True, exist_ok=True)
+
+ # Context policy: one launch decision per staged model, carried to
+ # the router via the preset INI. Priced against CAPACITY, not live
+ # free VRAM: this runs while the outgoing server instance may still
+ # hold the card (restart, refresh after a download), and its memory
+ # is freed before the new instance loads anything. Pricing against
+ # live-free here once pinned a fitting model's weights to CPU
+ # because the probe saw the predecessor's VRAM as gone.
- preset_path = runtimes_root() / "presets.ini"
++ preset_path = runtime_state_root() / "presets.ini"
+ try:
+ entries = generate_presets(mdir, probe_budget(planning=True), preset_path)
+ for entry in entries:
+ if entry.refusal:
+ logger.warning("model refused by physics check: %s", entry.refusal)
+ except Exception as exc: # noqa: BLE001 — policy failure must not block serving
+ # Degradation ladder: a STALE policy still beats no policy —
+ # stock fit (f16 KV at max context, no placement) is the
+ # silent-busy-wait failure on Windows. Keep serving with the
+ # previous INI when one exists; only a first boot with no INI
+ # at all falls to stock fit.
+ if preset_path.exists():
+ logger.error("preset generation failed (%s); serving with the "
+ "PREVIOUS launch policies — models staged since "
+ "the last successful generation run unpoliced "
+ "until this is fixed", exc)
+ else:
+ logger.error("preset generation failed (%s) and no previous "
+ "policy file exists; router runs stock fit", exc)
+ preset_path = None
+
+ sup = LlamaServerSupervisor(
- install_dir, mdir,
++ server_exe, mdir,
+ models_max=int(section.get("models_max", 4)),
+ port=int(section.get("port", 0)) or None,
+ preset_path=preset_path,
+ )
+ sup.start()
+ _SUPERVISOR = sup
- logger.info("managed llama-server up at %s (backend=%s tag=%s)",
- sup.base_url, backend, tag)
++ logger.info("managed llama-server up at %s (backend=%s)",
++ sup.base_url, backend)
+ _start_idle_sweeper(sup)
+ return sup
+ except Exception as exc: # noqa: BLE001 — never break session start
+ logger.warning("managed local runtime unavailable: %s", exc)
+ return None
+
+
+ def shutdown_local_runtime() -> None:
+ global _SUPERVISOR
+ if _SUPERVISOR is not None:
+ _SUPERVISOR.stop()
+ _SUPERVISOR = None
+
+
+ def get_supervisor():
+ """The process-local supervisor, or None (server may still be running
+ under another process — check the state file)."""
+ return _SUPERVISOR
+
+
+ def _start_idle_sweeper(sup) -> None:
+ """Idle-residency loop: every couple of minutes, unload non-primary
+ models idle past the supervisor's threshold. Daemon thread tied to the
+ supervisor's lifetime — exits when the server stops."""
+ import threading
+
+ def _loop():
+ while sup.proc is not None and sup.proc.poll() is None:
+ time.sleep(120)
+ try:
+ sup.sweep_idle()
+ except Exception as exc: # noqa: BLE001
+ logger.debug("idle sweep skipped: %s", exc)
+
+ threading.Thread(target=_loop, daemon=True,
+ name="local-runtime-idle-sweep").start()
diff --cc hermes_cli/local_runtime/endpoint.py
index 00000000000,b80a663d031..e69d617e681
mode 000000,100644..100644
--- a/hermes_cli/local_runtime/endpoint.py
+++ b/hermes_cli/local_runtime/endpoint.py
@@@ -1,0 -1,194 +1,185 @@@
+ """Endpoint resolution for llamacpp-alias requests (provider integration).
+
+ The seam between the existing provider mechanism and the managed runtime:
+ ``provider: llamacpp`` with no explicit base_url resolves, in order, to
+
+ 1. the managed server this Hermes is supervising (state file written by
+ LlamaServerSupervisor.start, removed on stop, staleness-checked), or
+ 2. a detected external llama-server.
+
+ Returns None when neither exists — the caller falls through to the normal
+ custom-provider path and its own error reporting.
+ """
+
+ from __future__ import annotations
+
+ import json
+ import logging
+ import threading
+ import time
+ import urllib.error
+ import urllib.request
+
+ LLAMACPP_ALIASES = frozenset({"llamacpp", "llama.cpp", "llama-cpp"})
+
+ logger = logging.getLogger(__name__)
+
+
+ def _pid_alive(pid: int) -> bool:
+ """Liveness for the state file's supervisor-child pid.
+
+ psutil when available; otherwise fall back to True (optimistic) — on
+ Windows ``os.kill(pid, 0)`` TERMINATES the process, so it must never be
+ used as a probe (windows-git-bash interop pitfall).
+ """
+ if not pid or pid < 0:
+ return False
+ try:
+ import psutil # type: ignore
+
+ return psutil.pid_exists(pid)
+ except Exception: # noqa: BLE001
+ return True
+
+
+ def _state_endpoint() -> dict | None:
+ from hermes_cli.local_runtime.supervisor import state_path
+
+ path = state_path()
+ if not path.exists():
+ return None
+ try:
- state = json.loads(path.read_text(encoding="utf-8"))
++ state = json.loads(path.read_text(encoding="utf-8-sig"))
+ except (json.JSONDecodeError, OSError):
+ return None
+ base_url = state.get("base_url", "")
+ if not base_url:
+ return None
+ endpoint = {"base_url": base_url, "api_key": state.get("api_key", "")}
+ # Ownership proof: the stable port means a SECOND install (different
+ # HERMES_HOME — a scratch profile, say) can own 127.0.0.1:18434 with a
+ # different api key while this install's state file still points there.
+ # /health is a public route, so it answers 200 for ANYONE's server —
+ # trusting it alone sent every chat request and the load-progress
+ # watcher at a server that 401s our key, silently. The recorded
+ # supervisor pid is the tiebreaker: health-200 from a server whose
+ # recorded child is DEAD is someone else's server, never a starting one.
+ pid_ok = _pid_alive(int(state.get("pid") or 0))
+ # Healthy server: done (when it's ours).
+ try:
+ health = base_url.rsplit("/v1", 1)[0] + "/health"
+ with urllib.request.urlopen(health, timeout=3) as r:
+ if r.status == 200:
+ return endpoint if pid_ok else None
+ except (urllib.error.URLError, OSError, TimeoutError):
+ pass
+ # Not healthy YET: a live supervisor child is a STARTING server (state
+ # is written at spawn; llama-server takes seconds to listen). Resolve
+ # optimistically so readiness probes racing the boot see a configured
+ # provider, not missing credentials. A dead pid is a crashed-without-
+ # cleanup leftover — ignore it so requests don't blackhole.
+ if pid_ok:
+ return endpoint
+ return None
+
+
+ def resolve_llamacpp_endpoint(config: dict | None = None,
+ wait_for_boot_s: float = 8.0) -> dict | None:
+ """Managed-first, detection-second endpoint for llamacpp aliases.
+
+ Returns {"base_url", "api_key"} or None. api_key is empty for keyless
+ external servers (callers substitute the SDK placeholder).
+
+ Boot-race rung: on a fresh backend start there is NO state file yet —
+ the lifespan boot thread is still spawning the server (config load +
+ preset generation + spawn ≈ 1-3 s) while the desktop's readiness probe
+ fires the moment the WebSocket connects. When the runtime is enabled
+ and installed, a missing endpoint means BOOTING, not unconfigured:
+ poll briefly for the state file instead of failing the probe (twice
+ observed as 'no usable credentials' → onboarding on restart).
+ """
+ managed = _state_endpoint()
+ if managed:
+ return managed
+
+ from hermes_cli.local_runtime.detect import detect_server
+
+ extra = ()
+ if config:
+ ports = (config.get("local_runtime") or {}).get("detect_ports") or []
+ extra = tuple(int(p) for p in ports)
+ hit = detect_server(extra_ports=extra)
+ if hit and not hit.auth_required:
+ return {"base_url": hit.base_url, "api_key": ""}
+
+ if wait_for_boot_s > 0 and _boot_in_flight(config):
+ _kick_managed_boot(config)
+ deadline = time.monotonic() + wait_for_boot_s
+ while time.monotonic() < deadline:
+ time.sleep(0.25)
+ managed = _state_endpoint()
+ if managed:
+ return managed
+ return None
+
+
+ _KICK_LOCK = threading.Lock()
+
+
+ def _kick_managed_boot(config: dict | None) -> None:
+ """Actively start the managed server when resolution finds it missing.
+
+ The wait loop above assumes some OTHER thread is bringing the server
+ up — true only at backend start (the lifespan boot thread). A router
+ that dies LATER leaves no boot in flight: the backend process was
+ killed with the router as part of its tree, or another install took
+ the stable port and the ownership guard rightly refused it. In those
+ states the wait just expired and agent init failed with 'no provider
+ configured', even though the fix is the same idempotent ensure call
+ the lifespan makes. Kick it here, off-thread (the resolver's wait
+ stays bounded; ensure's own state checks make a concurrent lifespan
+ boot harmless) and non-reentrant (racing resolutions kick once).
+ """
+ if not _KICK_LOCK.acquire(blocking=False):
+ return # a kick is already in flight
+
+ def _boot() -> None:
+ try:
+ cfg = config
+ if cfg is None:
+ from hermes_cli.config import load_config
+
+ cfg = load_config()
+ from hermes_cli.local_runtime.bootstrap import ensure_local_runtime
+
+ ensure_local_runtime(cfg)
+ except Exception: # noqa: BLE001 — best-effort; resolution falls back
+ logger.warning("on-demand managed-server boot failed", exc_info=True)
+ finally:
+ _KICK_LOCK.release()
+
+ threading.Thread(target=_boot, daemon=True,
+ name="lr-on-demand-boot").start()
+
+
+ def _boot_in_flight(config: dict | None) -> bool:
+ """True when the managed runtime is enabled and installed — the state
+ a lifespan boot thread is (or is about to be) bringing up.
+
- Installed-ness is a verified-manifest scan under runtimes_root(), NOT a
- server_binary() call — that helper requires an install_dir argument, and
- calling it bare made this gate throw-and-return-False forever, silently
- disabling the boot wait (the regression
- test had monkeypatched this function instead of exercising it).
++ Installed-ness is pm's own answer (a lockfile-version comparison against
++ the recorded install), NOT a filesystem scan or a bare server_binary()
++ call — the latter needed an argument this gate never had, so it threw
++ and returned False forever, silently disabling the boot wait.
+ """
+ try:
+ if config is None:
+ from hermes_cli.config import load_config
+
+ config = load_config()
+ if not ((config or {}).get("local_runtime") or {}).get("enabled"):
+ return False
- import json as _json
++ from hermes_cli.local_runtime.binaries import installed_backends
+
- from hermes_cli.local_runtime.binaries import runtimes_root
-
- for manifest in runtimes_root().glob("*/*/manifest.json"):
- try:
- if _json.loads(manifest.read_text(encoding="utf-8")).get("verified_version"):
- return True
- except (ValueError, OSError):
- continue
- return False
++ return bool(installed_backends())
+ except Exception: # noqa: BLE001
+ return False
diff --cc hermes_cli/local_runtime/growth.py
index 00000000000,484f2ff9f50..099cc447b95
mode 000000,100644..100644
--- a/hermes_cli/local_runtime/growth.py
+++ b/hermes_cli/local_runtime/growth.py
@@@ -1,0 -1,143 +1,143 @@@
+ """In-session context growth for the managed llama.cpp runtime.
+
+ The live half of the window ladder (context_policy.growth_decision): when a
+ session reaches the edge of its granted window, Hermes grows the window
+ toward the model's native max INSTEAD of compressing. Compression becomes
+ what the design says it is — the move of last resort, once the window is at
+ native (or the speed floor / physics say stop).
+
+ Mechanism: growth is re-prefill. A per-model window
+ override is persisted, presets regenerate with the bigger window, the
+ supervised server bounces, and the next request autoloads the model at the
+ new window and re-prefills the conversation. Nothing about the Hermes
+ conversation mutates — no prompt-cache or role-alternation risk; the whole
+ operation is server-side.
+
+ Scope guard: only a server THIS process supervises grows. Detected external
+ servers and other-process supervisors keep their own policies.
+ """
+
+ from __future__ import annotations
+
+ import json
+ import logging
+
+ logger = logging.getLogger(__name__)
+
+
+ def window_overrides_path():
- from hermes_cli.local_runtime.binaries import runtimes_root
++ from hermes_cli.local_runtime.binaries import runtime_state_root
+
- return runtimes_root() / "window_overrides.json"
++ return runtime_state_root() / "window_overrides.json"
+
+
+ def load_window_overrides() -> dict:
+ """model_id -> granted window (int). Empty on any read problem."""
+ try:
- with open(window_overrides_path(), encoding="utf-8") as fh:
++ with open(window_overrides_path(), encoding="utf-8-sig") as fh:
+ data = json.load(fh)
+ return {str(k): int(v) for k, v in data.items()}
+ except Exception: # noqa: BLE001
+ return {}
+
+
+ def save_window_override(model_id: str, window: int) -> None:
+ overrides = load_window_overrides()
+ overrides[model_id] = int(window)
+ path = window_overrides_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(overrides, indent=1), encoding="utf-8")
+
+
+ def clear_window_override(model_id: str) -> None:
+ """Drop a model's growth state (delete/re-download paths)."""
+ overrides = load_window_overrides()
+ if model_id in overrides:
+ del overrides[model_id]
+ window_overrides_path().write_text(
+ json.dumps(overrides, indent=1), encoding="utf-8")
+
+
+ def is_managed_endpoint(base_url: str) -> bool:
+ """True when base_url is the server this process's state file points at."""
+ try:
+ from hermes_cli.local_runtime.endpoint import _state_endpoint
+
+ state = _state_endpoint()
+ if state is None:
+ return False
+ return (base_url or "").rstrip("/") == str(
+ state.get("base_url", "")).rstrip("/")
+ except Exception: # noqa: BLE001
+ return False
+
+
+ def maybe_grow_window(model_id: str, *, base_url: str, session_tokens: int,
+ current_window: int,
+ measured_decode_tok_s: float | None = None) -> int | None:
+ """One growth evaluation + execution. Returns the NEW window when the
+ ladder granted a bigger one, else None (hold / compress / not ours).
+
+ The caller sits at a request boundary by construction (the pre-API
+ compression gate), so re-prefill growth is safe at any call: the next
+ request rebuilds server state from scratch in the larger window —
+ nothing rewinds.
+ """
+ from hermes_cli.local_runtime.bootstrap import (
+ get_supervisor,
+ refresh_local_runtime,
+ staged_models,
+ )
+ from hermes_cli.local_runtime.context_policy import growth_decision
+ from hermes_cli.local_runtime.estimator import profile_from_gguf
+ from hermes_cli.local_runtime.gguf import read_gguf_header
+ from hermes_cli.local_runtime.hardware import probe_budget
+
+ sup = get_supervisor()
+ if sup is None or not is_managed_endpoint(base_url):
+ return None
+
+ gguf = next((p for p in staged_models()
+ if p.stem.startswith(model_id) or model_id in p.stem), None)
+ if gguf is None:
+ return None
+
+ try:
+ profile = profile_from_gguf(read_gguf_header(gguf))
+ except (ValueError, OSError) as exc:
+ logger.debug("growth skip %s: unreadable gguf (%s)", model_id, exc)
+ return None
+
+ try:
+ server_idle = sup.is_idle(model_id)
+ except Exception: # noqa: BLE001
+ server_idle = False
+
+ decision = growth_decision(
+ # Capacity budget, not live-free: growth executes via a server
+ # bounce, so the grown instance loads onto a freed card. Live-free
+ # here is distorted by the very model being grown — it reads its
+ # own residency as unavailable and vetoes rungs that fit.
+ profile, probe_budget(planning=True),
+ current_window=current_window,
+ session_tokens=session_tokens,
+ measured_decode_tok_s=measured_decode_tok_s,
+ server_idle=server_idle,
+ # The caller IS the occupancy signal: this runs from the agent's
+ # compression gate, which fired on its own threshold. Two
+ # separately-derived edges must not deadlock into
+ # compress-before-grow.
+ occupancy_confirmed=True,
+ )
+ if decision.action != "grow" or not decision.next_window:
+ logger.debug("growth %s: %s (%s)", model_id, decision.action, decision.reason)
+ return None
+
+ logger.info("context growth %s: %s", model_id, decision.reason)
+ save_window_override(model_id, decision.next_window)
+ if not refresh_local_runtime():
+ # The override still lands at the next boot; report no growth NOW
+ # so the caller compresses instead of overflowing a stale window.
+ logger.warning("growth %s: server refresh failed; compression proceeds", model_id)
+ return None
+ return decision.next_window
diff --cc hermes_cli/local_runtime/hardware.py
index 00000000000,c4a3b3b71fb..ef083a7320d
mode 000000,100644..100644
--- a/hermes_cli/local_runtime/hardware.py
+++ b/hermes_cli/local_runtime/hardware.py
@@@ -1,0 -1,347 +1,342 @@@
+ """Live hardware budget probe.
+
+ Budget-source rule: discrete cards may trust the device query (measured
+ honest within rounding); unified-memory devices must budget from OS free
+ physical memory minus headroom — their device queries have been observed
+ off by 3x in both directions. The probe classifies the device and
+ constructs the right HardwareBudget for the estimator.
+
+ Vendor probe quirk (WDDM carve-out): on unified-memory NVIDIA devices
+ under Windows, nvidia-smi answers from the legacy dedicated-VRAM
+ carve-out — a fraction of the pool the CUDA allocator actually
+ addresses uniformly at full bandwidth. The CUDA driver API is
+ the tiebreaker: cuDeviceGetAttribute(INTEGRATED) is the vendor's own
+ declaration and always wins — 1 budgets unified, 0 stays discrete no
+ matter what any other number says. Only when the driver API is
+ unreachable does the engine's --list-devices view apply, and then only
+ behind two independent conditions no discrete card can meet.
+
+ Every probe here must work under a stripped PATH — gateway and service
+ sessions don't inherit the interactive environment. nvcuda/libcuda load
+ through the system loader (PATH plays no part), so classification never
+ depends on PATH; nvidia-smi resolves through an explicit candidate
+ ladder (PATH first, then the driver's known install locations) and its
+ absence only softens the live number, never the verdict.
+ """
+
+ from __future__ import annotations
+
+ import logging
+ import os
+ import re
+ import shutil
+ import subprocess
+ import time
+ from pathlib import Path
+
+ from hermes_cli.local_runtime.estimator import HardwareBudget
+
+ logger = logging.getLogger(__name__)
+
+ _GIB = 1 << 30
+ # Reserve carved off the card before any grant: the desktop's own
+ # co-residents (compositor, browser, Electron) measure ~2-2.5 GiB on a
+ # working machine, and a window granted into that space demotes silently
+ # under WDDM. 7% covers big cards; the 2 GiB floor is what the margin's
+ # old 512 MiB floor failed to cover in practice (a 221K grant measured
+ # 31.9/32.6 GiB with the desktop running — 'fits' by the math, demoted
+ # in reality). Small cards give up window to this; spill mode is their
+ # path to big models regardless.
+ _MARGIN_FLOOR = 2 << 30
+ _MARGIN_FRACTION = 0.09
+ # UMA headroom: on unified-memory machines (Apple Silicon, unified-memory
+ # NVIDIA) the model shares physical memory with the OS and every app, so
+ # budget from RAM minus this fraction.
+ _UMA_HEADROOM_FRACTION = 0.20
+
+ # Engine-fallback gates for the unified-pool quirk — BOTH must hold, and
+ # no discrete card can meet either: (1) the allocator's pool exceeds the
+ # smi report by well past rounding/ECC slack (discrete cards agree within
+ # ~2%; carve-out disagreement runs to whole multiples), and (2) the pool is
+ # system-RAM-sized — a workstation card in a RAM-matched box fails (1)
+ # because its smi and allocator AGREE, and a big discrete card in a
+ # bigger box fails (2). The driver's INTEGRATED attribute, when
+ # readable, bypasses both gates in whichever direction it points.
+ _POOL_DISAGREEMENT_FACTOR = 1.5
+ _POOL_RAM_FRACTION = 0.75
+
+ # cuDeviceGetAttribute enum: device is integrated with host memory.
+ _CU_DEVICE_ATTRIBUTE_INTEGRATED = 18
+
+ # One probe per process once a device answers (silicon doesn't change);
+ # a miss retries after this long so a runtime installed mid-session gets
+ # picked up by the engine fallback.
+ _POOL_NEGATIVE_TTL_S = 60.0
+ _pool_probe_cache: tuple[float, "tuple[int, bool | None] | None"] | None = None
+
+ # ' CUDA0: NVIDIA Example Device (1234-core Example GPU) (46464 MiB, 46284 MiB free)'
+ # — greedy .* pins the LAST parenthesized group, so device names carrying
+ # their own parentheses parse correctly.
+ _DEVICE_LINE_RE = re.compile(r"CUDA\d+:.*\((\d+)\s*MiB,\s*\d+\s*MiB free\)\s*$")
+
+
+ def _ram_bytes() -> tuple[int, int]:
+ """(total, available) physical memory, cross-platform stdlib."""
+ try:
+ import ctypes
+
+ class MEMORYSTATUSEX(ctypes.Structure):
+ _fields_ = [("dwLength", ctypes.c_ulong),
+ ("dwMemoryLoad", ctypes.c_ulong),
+ ("ullTotalPhys", ctypes.c_ulonglong),
+ ("ullAvailPhys", ctypes.c_ulonglong),
+ ("ullTotalPageFile", ctypes.c_ulonglong),
+ ("ullAvailPageFile", ctypes.c_ulonglong),
+ ("ullTotalVirtual", ctypes.c_ulonglong),
+ ("ullAvailVirtual", ctypes.c_ulonglong),
+ ("ullAvailExtendedVirtual", ctypes.c_ulonglong)]
+
+ stat = MEMORYSTATUSEX()
+ stat.dwLength = ctypes.sizeof(MEMORYSTATUSEX)
+ ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))
+ return stat.ullTotalPhys, stat.ullAvailPhys
+ except (AttributeError, OSError):
+ pass
+ # POSIX
+ try:
+ page = int(subprocess.run(["getconf", "PAGE_SIZE"], capture_output=True,
+ text=True, timeout=5).stdout or 4096)
+ total = int(subprocess.run(["getconf", "_PHYS_PAGES"], capture_output=True,
+ text=True, timeout=5).stdout or 0) * page
+ avail = total // 2 # conservative when _AVPHYS is unavailable
+ try:
+ avail = int(subprocess.run(["getconf", "_AVPHYS_PAGES"],
+ capture_output=True, text=True,
+ timeout=5).stdout or 0) * page or avail
+ except (OSError, ValueError):
+ pass
+ return total, avail
+ except (OSError, ValueError):
+ return 0, 0
+
+
+ # nvidia-smi lives at a fixed path under the driver install; PATH presence
+ # varies by session type (services and gateways often run with a minimal
+ # environment) and by driver generation (legacy NVSMI dir was never on
+ # PATH). Resolution result is cached: the driver doesn't move mid-process.
+ _smi_path_cache: "tuple[str | None] | None" = None
+
+
+ def _nvidia_smi_path() -> str | None:
+ """Absolute path to nvidia-smi, or None. PATH first (respects user
+ overrides), then the driver's known install locations on Windows;
+ on Linux/WSL the PATH lookup is the whole ladder."""
+ global _smi_path_cache
+ if _smi_path_cache is not None:
+ return _smi_path_cache[0]
+ found = shutil.which("nvidia-smi")
+ if found is None and os.name == "nt":
+ windir = os.environ.get("SystemRoot", r"C:\Windows")
+ for candidate in (
+ # DCH drivers (every modern install) place it in System32.
+ Path(windir) / "System32" / "nvidia-smi.exe",
+ # Legacy standalone drivers used NVSMI, never on PATH.
+ Path(os.environ.get("ProgramFiles", r"C:\Program Files"))
+ / "NVIDIA Corporation" / "NVSMI" / "nvidia-smi.exe",
+ ):
+ if candidate.exists():
+ found = str(candidate)
+ break
+ _smi_path_cache = (found,)
+ return found
+
+
+ def _nvidia_vram() -> tuple[int, int] | None:
+ """(total, free) MiB->bytes from nvidia-smi, or None."""
+ exe = _nvidia_smi_path()
+ if exe is None:
+ return None
+ try:
+ out = subprocess.run(
+ [exe, "--query-gpu=memory.total,memory.free",
+ "--format=csv,noheader,nounits"],
+ capture_output=True, text=True, timeout=10)
+ if out.returncode != 0 or not out.stdout.strip():
+ return None
+ total_mib, free_mib = (int(x) for x in out.stdout.strip().splitlines()[0].split(","))
+ return total_mib << 20, free_mib << 20
+ except (OSError, ValueError, subprocess.TimeoutExpired):
+ return None
+
+
+ def _cuda_driver_pool() -> "tuple[int, bool | None] | None":
+ """(allocator_total_bytes, integrated_or_None) from the CUDA driver
+ API, or None when unreachable. ctypes against the driver's own DLL/SO
+ — no toolkit, no subprocess, ~ms. INTEGRATED is the vendor's own
+ unified-memory declaration; total is the pool the allocator will
+ actually hand out (on carve-out devices, several times what
+ nvidia-smi reports)."""
+ import ctypes
+
+ for name in ("nvcuda.dll", "libcuda.so.1", "libcuda.so"):
+ try:
+ cuda = ctypes.CDLL(name)
+ break
+ except OSError:
+ continue
+ else:
+ return None
+ try:
+ if cuda.cuInit(0) != 0:
+ return None
+ dev = ctypes.c_int()
+ if cuda.cuDeviceGet(ctypes.byref(dev), 0) != 0:
+ return None
+ total = ctypes.c_size_t()
+ getter = getattr(cuda, "cuDeviceTotalMem_v2", None) or cuda.cuDeviceTotalMem
+ if getter(ctypes.byref(total), dev) != 0 or total.value <= 0:
+ return None
+ integrated: bool | None = None
+ attr = ctypes.c_int()
+ if cuda.cuDeviceGetAttribute(
+ ctypes.byref(attr), _CU_DEVICE_ATTRIBUTE_INTEGRATED, dev) == 0:
+ integrated = bool(attr.value)
+ return total.value, integrated
+ except (OSError, AttributeError):
+ return None
+
+
+ def _engine_device_pool() -> "tuple[int, bool | None] | None":
+ """(engine_total_bytes, None) from the installed runtime's own
+ --list-devices, or None. The fallback truth source when the driver
+ API is unreachable: asks the exact binary that will do the
+ allocating. Carries no integrated verdict — callers must gate it."""
+ try:
+ from hermes_cli.local_runtime.binaries import (
- installed_tags,
- runtimes_root,
++ installed_backends,
+ server_binary,
+ )
+
- tags = installed_tags()
- if not tags:
++ backends = installed_backends()
++ if not backends:
+ return None
- tag_dir = runtimes_root() / tags[0]
- backend_dirs = [d for d in tag_dir.iterdir() if d.is_dir()]
- if not backend_dirs:
- return None
- exe = server_binary(backend_dirs[0])
++ exe = server_binary(backends[0])
+ out = subprocess.run([str(exe), "--list-devices"], capture_output=True,
+ text=True, timeout=30, cwd=str(exe.parent))
+ if out.returncode != 0:
+ return None
+ for line in (out.stdout + out.stderr).splitlines():
+ m = _DEVICE_LINE_RE.search(line)
+ if m:
+ return int(m.group(1)) << 20, None
+ return None
+ except Exception: # noqa: BLE001 — a probe miss must never block budgeting
+ return None
+
+
+ def _device_pool_view() -> "tuple[int, bool | None] | None":
+ """Best available allocator-side view, cached: a hit is permanent for
+ the process, a miss retries after a short TTL (the engine binary can
+ appear mid-session via a pane install)."""
+ global _pool_probe_cache
+ now = time.monotonic()
+ if _pool_probe_cache is not None:
+ stamp, view = _pool_probe_cache
+ if view is not None or now - stamp < _POOL_NEGATIVE_TTL_S:
+ return view
+ view = _cuda_driver_pool() or _engine_device_pool()
+ _pool_probe_cache = (now, view)
+ return view
+
+
+ def _unified_pool_bytes(smi_total: int, ram_total: int) -> int | None:
+ """The real pool size when this NVIDIA device is unified memory behind
+ a WDDM carve-out, else None (trust nvidia-smi as ever).
+
+ The driver's INTEGRATED attribute decides when readable — in BOTH
+ directions (0 pins discrete even if the numbers look weird; a driver
+ that declares integrated is believed even at modest pool sizes). Only
+ an attribute-less view (engine fallback) needs the two numeric gates;
+ both must hold and no discrete card meets either.
+ """
+ view = _device_pool_view()
+ if view is None:
+ return None
+ pool, integrated = view
+ if integrated is False:
+ return None
+ if integrated is True:
+ return pool
+ if (smi_total > 0 and pool >= int(smi_total * _POOL_DISAGREEMENT_FACTOR)
+ and ram_total > 0 and pool >= int(ram_total * _POOL_RAM_FRACTION)):
+ return pool
+ return None
+
+
+ def probe_budget(*, planning: bool = False) -> HardwareBudget:
+ """Construct the budget per the source rules above.
+
+ ``planning=False`` (default): LIVE budget — free VRAM right now. The
+ right input for launch-time fit decisions and growth re-grants.
+
+ ``planning=True``: CAPACITY budget — what this machine can run once
+ the runtime manages placement (total device memory minus the margin).
+ The right input for catalog pricing and quant selection: pricing
+ against live-free while a model is already loaded made every row read
+ 'larger than your GPU memory' and degraded quant picks to Q2 on a
+ 32 GiB card. The managed server
+ unloads/relaunches models itself, so at load time the capacity is
+ genuinely available.
+ """
+ ram_total, ram_avail = _ram_bytes()
+ vram = _nvidia_vram()
+
+ # Unified-memory NVIDIA: the CUDA allocator pool is the real
+ # capacity. Classification comes from the driver API/engine — it
+ # must not require nvidia-smi (stripped-PATH sessions lose smi but
+ # nvcuda loads via the system loader regardless). Crossing the
+ # carve-out costs nothing (effective bandwidth is flat through the
+ # boundary; smi's used/total merely saturate at it) — the carve-out
+ # is an OS accounting knob, not a GPU limit. Deliberately NOT
+ # clamped to OS RAM: carved-out memory is invisible to
+ # GlobalMemoryStatusEx (the OS reports correspondingly less total
+ # RAM), so a RAM clamp would throw away exactly the carved capacity.
+ unified = _unified_pool_bytes(vram[0] if vram else 0, ram_total)
+ if unified is not None:
+ logger.info(
+ "unified-memory NVIDIA device: allocator pool %.1f GiB "
+ "(nvidia-smi carve-out: %s); budgeting from the pool",
+ unified / _GIB,
+ f"{vram[0] / _GIB:.1f} GiB" if vram else "unavailable")
+ if planning:
+ base = unified
+ else:
+ # Live: dedicated-free plus what the OS can still give. smi's
+ # free saturates at the carve-out so this under-counts a bit —
+ # the safe direction (the pool edge is a measured soft cliff:
+ # decode collapses ~3.5x when concurrent demand hits it).
+ # Without smi, OS-available alone is the honest floor.
+ live = (vram[1] + ram_avail) if vram else ram_avail
+ base = min(unified, live)
+ usable = max(0, int(base * (1 - _UMA_HEADROOM_FRACTION)))
+ return HardwareBudget(usable_vram_bytes=usable,
+ total_device_bytes=unified,
+ ram_available_bytes=0, uma=True)
+
+ if vram is None:
+ # No NVIDIA device visible: Metal/Vulkan/CPU paths budget from RAM
+ # as UMA (Apple Silicon) — conservative for discrete AMD until a
+ # vendor probe lands (E3 hardware).
+ base = ram_total if planning else ram_avail
+ usable = max(0, int(base * (1 - _UMA_HEADROOM_FRACTION)))
+ return HardwareBudget(usable_vram_bytes=usable,
+ total_device_bytes=ram_total,
+ ram_available_bytes=0, uma=True)
+
+ total, free = vram
+ margin = max(_MARGIN_FLOOR, int(total * _MARGIN_FRACTION))
+ base = total if planning else free
+ return HardwareBudget(usable_vram_bytes=max(0, base - margin),
+ total_device_bytes=total,
+ ram_available_bytes=ram_avail if not planning else ram_total,
+ uma=False)
diff --cc hermes_cli/local_runtime/presets.py
index 00000000000,a5aa96cfa3b..9c9ca784684
mode 000000,100644..100644
--- a/hermes_cli/local_runtime/presets.py
+++ b/hermes_cli/local_runtime/presets.py
@@@ -1,0 -1,265 +1,265 @@@
+ """Per-model preset generation (--models-preset INI) — the router-side
+ carrier for context-policy launch decisions.
+
+ The INI shape is what the router itself generates per child: a
+ [model-id] section whose keys are long-form
+ llama-server flag names without the leading dashes.
+ """
+
+ from __future__ import annotations
+
+ import logging
+ from dataclasses import dataclass
+ from pathlib import Path
+
+ from hermes_cli.local_runtime.context_policy import (
+ RUNTIME_OVERHEAD_BYTES,
+ WindowDecision,
+ initial_window,
+ launch_args,
+ ub_logits_bytes,
+ )
+ from hermes_cli.local_runtime.estimator import (
+ HardwareBudget,
+ PhysicsRefusal,
+ profile_from_gguf,
+ )
+ from hermes_cli.local_runtime.gguf import read_gguf_header
+
+ logger = logging.getLogger(__name__)
+
+ # args list -> INI keys. Flags the policy owns; everything else stays out
+ # of the preset (recipe sampling defaults merge in a later pass).
+ _FLAG_TO_KEY = {
+ "-c": "ctx-size",
+ "-b": "batch-size",
+ "-ub": "ubatch-size",
+ "-ctk": "cache-type-k",
+ "-ctv": "cache-type-v",
+ "-fa": "flash-attn",
+ "-ot": "override-tensor",
+ "--spec-type": "spec-type",
+ "--spec-draft-n-max": "spec-draft-n-max",
+ }
+
+
+ @dataclass
+ class PresetEntry:
+ model_id: str
+ window: int
+ spilled: bool
+ refusal: str | None = None
+ keys: dict[str, str] | None = None
+
+
+ def _args_to_keys(args: list[str]) -> dict[str, str]:
+ keys: dict[str, str] = {}
+ i = 0
+ while i < len(args):
+ flag = args[i]
+ key = _FLAG_TO_KEY.get(flag)
+ if key is None:
+ i += 1
+ continue
+ keys[key] = args[i + 1]
+ i += 2
+ return keys
+
+
+ def generate_presets(models_dir: Path, budget: HardwareBudget,
+ preset_path: Path,
+ mtp_capable: set[str] | None = None) -> list[PresetEntry]:
+ """Walk the staged models, run the launch decision per model, and
+ write one INI. Refused models get no section (the router simply won't
+ have policy for them; the picker surfaces the refusal + smaller-quant
+ suggestion from the returned entries).
+
+ Catalog-declared companions merge in here: sampling defaults (policy
+ keys always win), the vision projector when present, and a spec-decode
+ draft model iff the decision spilled — the rule: speculative
+ decode is a spill amplifier, so a resident draft accelerates a spilled
+ main model; a zero-spill model doesn't pay the draft's memory."""
+ from hermes_cli.local_runtime.bootstrap import assets_dir
+ from hermes_cli.local_runtime.catalog import find_entry_for_model
+
+ entries: list[PresetEntry] = []
+ sections: list[str] = []
+ for gguf in _staged_in(models_dir):
+ model_id = _strip_part(gguf.stem)
+ try:
+ header = read_gguf_header(gguf)
+ profile = profile_from_gguf(header)
+ except (ValueError, OSError) as exc:
+ logger.warning("preset skip %s: %s", gguf.name, exc)
+ continue
+ # Overhead beyond weights+KV: runtime buffers, the vision projector
+ # when this model ships one, and the logits buffers of whichever
+ # microbatch/MTP posture launch_args will choose — flag and price
+ # decided together, from the same facts.
+ hit = find_entry_for_model(model_id)
+ entry = hit[0] if hit is not None else None
+ is_mtp = (entry.mtp if entry is not None
+ else model_id in (mtp_capable or set()))
+ if is_mtp and profile.kv_scale == 1.0:
+ # Header-derived profiles don't know about MTP's draft
+ # context; apply the calibrated KV multiplier here so the
+ # launch fit prices what the server will actually allocate.
+ import dataclasses
+
+ profile = dataclasses.replace(profile, kv_scale=1.2)
+ mmproj_bytes = 0
+ if entry is not None and entry.mmproj is not None:
+ mmproj_path = assets_dir() / entry.mmproj.local_name
+ if mmproj_path.exists():
+ mmproj_bytes = entry.mmproj.size_bytes
+ # MTP posture ladder — window first, prefill second: price the
+ # launch under both postures and keep whichever grants the larger
+ # window (the stacked posture's bigger compute buffer buys ~3x
+ # short-prompt prefill but costs ~2 GiB that would otherwise be
+ # window; measured at 256K the ub512 posture still prefills at
+ # 2.7K tok/s, so window wins ties only one way: never trade
+ # context away for prefill). Same window -> stacked.
+ mtp_prefill = False
+ logits_bytes = ub_logits_bytes(profile.n_vocab, mtp_capable=is_mtp)
+ if is_mtp:
+ stacked_logits = ub_logits_bytes(profile.n_vocab, mtp_capable=True,
+ mtp_prefill=True)
+ stacked_probe = initial_window(
+ profile, budget,
+ overhead_bytes=(RUNTIME_OVERHEAD_BYTES + mmproj_bytes
+ + stacked_logits))
+ plain_probe = initial_window(
+ profile, budget,
+ overhead_bytes=(RUNTIME_OVERHEAD_BYTES + mmproj_bytes
+ + logits_bytes))
+ if (not isinstance(stacked_probe, PhysicsRefusal)
+ and not stacked_probe.spilled
+ and (isinstance(plain_probe, PhysicsRefusal)
+ or stacked_probe.window >= plain_probe.window)):
+ mtp_prefill = True
+ logits_bytes = stacked_logits
+ decision = initial_window(
+ profile, budget,
+ overhead_bytes=RUNTIME_OVERHEAD_BYTES + mmproj_bytes + logits_bytes)
+ if isinstance(decision, PhysicsRefusal):
+ entries.append(PresetEntry(model_id=model_id, window=0,
+ spilled=False, refusal=decision.message))
+ continue
+
+ # Session growth (growth.py): a persisted override lifts the launch
+ # window to where the ladder last grew it — capped at native, and
+ # only when physics still clears the bigger window on THIS boot's
+ # budget (a smaller-VRAM day re-fits honestly back down).
+ try:
+ from hermes_cli.local_runtime.estimator import ctx_bytes
+ from hermes_cli.local_runtime.growth import load_window_overrides
+
+ override = load_window_overrides().get(model_id)
+ native = profile.n_ctx_train or decision.window
+ if override and override > decision.window:
+ target = min(int(override), native)
+ kv = ctx_bytes(profile, target)
+ need = (profile.weights_bytes + kv
+ + RUNTIME_OVERHEAD_BYTES + mmproj_bytes + logits_bytes)
+ if need <= budget.usable_vram_bytes + budget.ram_available_bytes:
+ spill = max(0, need - budget.usable_vram_bytes)
+ decision = WindowDecision(
+ window=target, spill_bytes=spill,
+ kv_on_gpu=kv <= budget.usable_vram_bytes,
+ reasons=[f"grown window restored ({target // 1024}K)"])
+ except Exception as exc: # noqa: BLE001 — overrides are advisory
+ logger.debug("window override skipped for %s: %s", model_id, exc)
+
+ # (entry and is_mtp resolved above, where the overhead was priced —
+ # the launch flags below MUST match that pricing.)
+ args = launch_args(profile, decision, mtp_capable=is_mtp,
+ mtp_draft_depth=(entry.mtp_draft_depth
+ if entry is not None else 3),
+ uma=budget.uma, mtp_prefill=mtp_prefill)
+ keys = _args_to_keys(args)
+
+ if entry is not None and is_mtp:
+ # Integrated-MTP targets sample on the backend, and so does
+ # the draft (pairing validated against the vendor's published
+ # llama.cpp recipes for these models).
+ keys["backend-sampling"] = "on"
+ keys["spec-draft-backend-sampling"] = "on"
+
+ # Sampling deference ladder, under the policy keys (policy wins
+ # on clash). The GGUF's own general.sampling.* metadata is the
+ # publisher's recommendation — it arrives with the file, updates
+ # with every re-upload, and covers models the catalog has never
+ # heard of. Catalog sampling applies only where the file is
+ # silent; a model carrying neither runs llama.cpp defaults.
+ for k, v in header.sampling_defaults.items():
+ keys.setdefault(k, v)
+ if entry is not None:
+ for k, v in (entry.sampling or {}).items():
+ keys.setdefault(k, v)
+ if entry.mmproj is not None:
+ mmproj_path = assets_dir() / entry.mmproj.local_name
+ if mmproj_path.exists():
+ keys["mmproj"] = str(mmproj_path)
+ if entry.draft is not None and decision.spilled:
+ draft_path = assets_dir() / entry.draft.local_name
+ if draft_path.exists():
+ keys["model-draft"] = str(draft_path)
+ keys["spec-type"] = "draft-dspark"
+ # Unsloth's measured cliff: acceptance 83% at 2-3
+ # drafts, collapses at 4.
+ keys["spec-draft-n-max"] = "3"
+
+ entries.append(PresetEntry(model_id=model_id, window=decision.window,
+ spilled=decision.spilled, keys=keys))
+ body = "\n".join(f"{k} = {v}" for k, v in keys.items())
+ sections.append(f"[{model_id}]\n{body}\n")
+
+ preset_path.parent.mkdir(parents=True, exist_ok=True)
+ preset_path.write_text("\n".join(sections), encoding="utf-8")
+ logger.info("wrote %d preset sections to %s", len(sections), preset_path)
+ return entries
+
+
+ def read_preset_decisions(preset_path: Path | None = None) -> dict[str, PresetEntry]:
+ """The launch decisions the running server was actually given, read
+ back from the preset INI (the INI is the record — it's what spawned
+ the children). Missing/unparseable file returns {}."""
+ import configparser
+
+ if preset_path is None:
- from hermes_cli.local_runtime.binaries import runtimes_root
++ from hermes_cli.local_runtime.binaries import runtime_state_root
+
- preset_path = runtimes_root() / "presets.ini"
++ preset_path = runtime_state_root() / "presets.ini"
+ out: dict[str, PresetEntry] = {}
+ try:
+ parser = configparser.ConfigParser()
+ parser.read(preset_path, encoding="utf-8")
+ for section in parser.sections():
+ window = parser.getint(section, "ctx-size", fallback=0)
+ spilled = parser.has_option(section, "override-tensor")
+ out[section] = PresetEntry(model_id=section, window=window,
+ spilled=spilled)
+ except Exception as exc: # noqa: BLE001
+ logger.debug("preset read-back failed: %s", exc)
+ return out
+
+
+ def _strip_part(stem: str) -> str:
+ import re
+
+ return re.sub(r"-\d{5}-of-\d{5}$", "", stem)
+
+
+ def _staged_in(models_dir: Path) -> "list[Path]":
+ """Servable models in an arbitrary directory (split first-parts only) —
+ the validation harness points at non-default dirs."""
+ import re
+
+ part = re.compile(r"-(\d{5})-of-\d{5}\.gguf$")
+ out = []
+ for p in sorted(models_dir.glob("*.gguf")):
+ m = part.search(p.name)
+ if m and m.group(1) != "00001":
+ continue
+ out.append(p)
+ return out
diff --cc hermes_cli/local_runtime/supervisor.py
index 00000000000,53ef6056356..f181e7f83bf
mode 000000,100644..100644
--- a/hermes_cli/local_runtime/supervisor.py
+++ b/hermes_cli/local_runtime/supervisor.py
@@@ -1,0 -1,493 +1,493 @@@
+ """Supervision of one llama-server in router mode.
+
+ The router process is ours (restart with backoff on crash); router children
+ are its problem — child failures surface via GET /models exit_code, never
+ auto-retried here.
+
+ Readiness rules (each learned the hard way on real hardware):
+ - health-200 is NOT readiness; every readiness claim requires a touch
+ generation (temp-0, expected token, generous budget, reasoning_content
+ scanned).
+ - Always dial 127.0.0.1 — resolving localhost adds ~2s per request on
+ Windows via IPv6 fallback.
+ - /metrics is opt-in (--metrics) and carries no KV-usage metric;
+ idleness = requests_processing == 0 and no slot is_processing.
+ - The router's LRU eviction has no pin for the primary model: until an
+ upstream pin exists, keep_primary_loaded re-touches the primary after
+ any other model load.
+ """
+
+ from __future__ import annotations
+
+ import json
+ import logging
+ import secrets
+ import socket
+ import subprocess
+ import threading
+ import time
+ import urllib.error
+ import urllib.request
+ from pathlib import Path
+
-from hermes_cli.local_runtime.binaries import server_binary, runtimes_root
++from hermes_cli.local_runtime.binaries import runtime_state_root
+
+ logger = logging.getLogger(__name__)
+
+ TOUCH_PROMPT = "Reply with exactly one word: the capital of France."
+ TOUCH_EXPECT = "paris"
+ _RESTART_BACKOFF_S = (1, 5, 15, 60)
+
+
+ def state_path() -> Path:
+ """Endpoint state for other Hermes processes (provider resolution reads
+ this to route llamacpp-alias requests at the managed server)."""
- return runtimes_root() / "server.json"
++ return runtime_state_root() / "server.json"
+
+
+ def _free_port() -> int:
+ with socket.socket() as s:
+ s.bind(("127.0.0.1", 0))
+ return s.getsockname()[1]
+
+
+ # Default port for the managed server, chosen once and reused across
+ # restarts. Sessions persist the resolved base_url; an ephemeral port
+ # would strand every resumed session on a dead endpoint after each
+ # restart. Deliberately NOT 8080 so we never collide with a user's own
+ # llama-server/Ollama-adjacent stack.
+ _DEFAULT_PORT = 18434
+
+
+ def _stable_port() -> int:
+ """The stable default port, falling back to an ephemeral one only when
+ something else already listens there (and it isn't a leftover managed
+ server, which stop() would have cleaned up)."""
+ try:
+ with socket.socket() as s:
+ s.bind(("127.0.0.1", _DEFAULT_PORT))
+ return _DEFAULT_PORT
+ except OSError:
+ logger.warning(
+ "port %d busy; managed llama-server falling back to an ephemeral "
+ "port — existing sessions may need a model re-pick", _DEFAULT_PORT)
+ return _free_port()
+
+
+ def _stable_api_key() -> str:
+ """One key for the life of the install, persisted beside the runtimes.
+
+ Endpoint identity must survive restarts as a UNIT — sessions persist the
+ resolved base_url + api_key, so a per-boot key strands every resumed
+ session on HTTP 401 exactly the way a per-boot port would strand them
+ on connection errors. Rotating it buys nothing: the key exists to stop
+ other loopback processes free-riding, and it lives on the same disk as
+ the state file that would leak it. Delete the file to rotate manually.
+ """
- key_path = runtimes_root() / ".api_key"
++ key_path = runtime_state_root() / ".api_key"
+ try:
- existing = key_path.read_text(encoding="utf-8").strip()
++ existing = key_path.read_text(encoding="utf-8-sig").strip()
+ if len(existing) >= 16:
+ return existing
+ except OSError:
+ pass
+ key = secrets.token_urlsafe(24)
+ try:
+ key_path.parent.mkdir(parents=True, exist_ok=True)
+ key_path.write_text(key, encoding="utf-8")
+ except OSError as exc:
+ logger.warning("could not persist api key (%s); sessions will need "
+ "a re-pick after restart", exc)
+ return key
+
+
+ class LlamaServerSupervisor:
+ """Own one llama-server router process for the life of a Hermes session.
+
+ Usage::
+
- sup = LlamaServerSupervisor(install_dir, models_dir)
++ sup = LlamaServerSupervisor(server_exe, models_dir)
+ sup.start() # spawn + wait healthy
+ sup.ensure_model_ready(name) # load + touch-generate
+ ... sup.base_url is the /v1 endpoint, sup.api_key its key ...
+ sup.stop()
+ """
+
- def __init__(self, install_dir: Path, models_dir: Path, *,
++ def __init__(self, server_exe: Path, models_dir: Path, *,
+ models_max: int = 4, port: int | None = None,
+ extra_args: list[str] | None = None,
+ log_path: Path | None = None,
+ preset_path: Path | None = None):
- self.install_dir = Path(install_dir)
++ self.server_exe = Path(server_exe)
+ self.models_dir = Path(models_dir)
+ self.models_max = models_max
+ self.port = port or _stable_port()
+ self.api_key = _stable_api_key()
+ self.extra_args = list(extra_args or [])
+ self.log_path = log_path or (self.models_dir.parent / "logs" / "llama-server.log")
+ self.preset_path = preset_path
+ self.proc: subprocess.Popen | None = None
+ self.primary_model: str | None = None
+ self._restarts = 0
+ self._stopping = False
+ self._watchdog: threading.Thread | None = None
+ self._log_handle = None
+ self._idle_since: dict[str, float] = {}
+
+ # ── endpoints ────────────────────────────────────────────
+
+ @property
+ def base_url(self) -> str:
+ return f"http://127.0.0.1:{self.port}/v1"
+
+ def _url(self, route: str) -> str:
+ return f"http://127.0.0.1:{self.port}{route}"
+
+ def _request(self, route: str, body: dict | None = None, timeout_s: int = 30) -> dict:
+ req = urllib.request.Request(
+ self._url(route),
+ data=json.dumps(body).encode() if body is not None else None,
+ headers={"Content-Type": "application/json",
+ "Authorization": f"Bearer {self.api_key}"},
+ )
+ with urllib.request.urlopen(req, timeout=timeout_s) as r:
+ raw = r.read()
+ return json.loads(raw) if raw else {}
+
+ # ── lifecycle ────────────────────────────────────────────
+
+ def _spawn(self) -> None:
- exe = server_binary(self.install_dir)
++ exe = self.server_exe
+ cmd = [
+ str(exe),
+ "--host", "127.0.0.1",
+ "--port", str(self.port),
+ "--api-key", self.api_key,
+ "--models-dir", str(self.models_dir),
+ "--models-max", str(self.models_max),
+ # The residency contract at the layer that sees every message:
+ # a chat request to a staged-but-unloaded model loads it (slow
+ # first token) instead of failing with 'model not found' —
+ # without this flag, chat after an eject is a bare 400/404.
+ "--models-autoload",
+ "--metrics", # opt-in flag; supervisor telemetry needs it
+ "--slots", # /slots endpoint is also opt-in; is_idle reads it
+ "--no-webui",
+ "--jinja",
+ # Direct I/O on model load: bypasses the page cache, so a
+ # multi-GB load doesn't evict half the OS cache — measured
+ # faster loads on NVMe, and our router bounces (download/
+ # delete/activate) reload models often enough to care.
+ "-dio",
+ ]
+ if self.preset_path and self.preset_path.exists():
+ cmd += ["--models-preset", str(self.preset_path)]
+ cmd += [
+ *self.extra_args,
+ ]
+ self.log_path.parent.mkdir(parents=True, exist_ok=True)
+ self._log_handle = open(self.log_path, "a", encoding="utf-8", errors="replace")
+ self._log_handle.write(f"\n# spawn: {cmd}\n")
+ self._log_handle.flush()
+ # list-args, never a shell: spaced paths (user homes) must survive.
+ self.proc = subprocess.Popen(cmd, stdout=self._log_handle,
+ stderr=subprocess.STDOUT, cwd=str(exe.parent))
+ logger.info("llama-server router spawned pid=%s port=%s", self.proc.pid, self.port)
+ # State goes down at SPAWN, not after health: endpoint resolution
+ # treats a live-pid-but-not-yet-healthy server as "starting" rather
+ # than "unconfigured", so a readiness probe racing the boot doesn't
+ # throw the app back to onboarding (observed on first restart test).
+ self._write_state()
+
+ def start(self, timeout_s: int = 120) -> None:
+ self._stopping = False
+ self._spawn()
+ self._wait_health(timeout_s)
+ self._write_state()
+ self._watchdog = threading.Thread(target=self._watch, daemon=True,
+ name="llamacpp-supervisor")
+ self._watchdog.start()
+
+ def _write_state(self) -> None:
+ path = state_path()
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps({
+ "base_url": self.base_url,
+ "api_key": self.api_key,
+ "pid": self.proc.pid if self.proc else None,
+ }), encoding="utf-8")
+
+ def _wait_health(self, timeout_s: int) -> None:
+ deadline = time.monotonic() + timeout_s
+ while time.monotonic() < deadline:
+ if self.proc and self.proc.poll() is not None:
+ raise RuntimeError(
+ f"llama-server exited rc={self.proc.returncode} during startup "
+ f"(log: {self.log_path})")
+ try:
+ with urllib.request.urlopen(self._url("/health"), timeout=3) as r:
+ if r.status == 200:
+ return
+ except (urllib.error.URLError, OSError, TimeoutError):
+ pass
+ time.sleep(1)
+ raise TimeoutError(f"llama-server not healthy after {timeout_s}s (log: {self.log_path})")
+
+ def _watch(self) -> None:
+ """Restart the router (not its children) on crash, with backoff."""
+ while not self._stopping:
+ proc = self.proc
+ if proc is None:
+ return
+ rc = proc.poll()
+ if rc is None:
+ time.sleep(2)
+ continue
+ if self._stopping:
+ return
+ backoff = _RESTART_BACKOFF_S[min(self._restarts, len(_RESTART_BACKOFF_S) - 1)]
+ logger.warning("llama-server exited rc=%s; restart #%s in %ss",
+ rc, self._restarts + 1, backoff)
+ time.sleep(backoff)
+ self._restarts += 1
+ try:
+ self._reap_orphaned_children()
+ self._spawn()
+ self._wait_health(120)
+ if self.primary_model:
+ self.ensure_model_ready(self.primary_model)
+ except Exception as exc: # noqa: BLE001
+ logger.error("llama-server restart failed: %s", exc)
+
+ def stop(self) -> None:
+ self._stopping = True
+ state_path().unlink(missing_ok=True)
+ if self.proc and self.proc.poll() is None:
+ self._terminate_tree(self.proc)
+ if self._log_handle:
+ self._log_handle.close()
+ self._log_handle = None
+
+ @staticmethod
+ def _terminate_tree(proc: subprocess.Popen) -> None:
+ """Terminate the router AND its model children.
+
+ The router spawns one child llama-server per loaded model, each
+ holding gigabytes of VRAM. Terminating only the router (on
+ Windows, TerminateProcess — no signal handlers, no cleanup pass)
+ orphans those children: the port goes quiet but the weights stay
+ resident, and the next spawn re-loads models alongside a ghost
+ still holding the memory. Enumerate children FIRST (the parent
+ must be alive to walk them), then terminate parent and children
+ together, escalating to kill for stragglers.
+ """
+ children: list = []
+ try:
+ import psutil
+
+ children = psutil.Process(proc.pid).children(recursive=True)
+ except Exception: # noqa: BLE001 — no psutil view; still stop the router
+ children = []
+ proc.terminate()
+ for child in children:
+ try:
+ child.terminate()
+ except Exception: # noqa: BLE001
+ pass
+ try:
+ proc.wait(timeout=15)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ for child in children:
+ try:
+ if child.is_running():
+ child.kill()
+ except Exception: # noqa: BLE001
+ pass
+
+ def _reap_orphaned_children(self) -> None:
+ """Kill model children orphaned by a router crash, before respawn.
+
+ A crashed router can't clean up its children, and a dead parent
+ can't be walked — so match by identity instead: any process
+ running OUR llama-server binary whose parent is gone is an
+ orphan of a previous router. Their VRAM must come back before
+ the new router loads models next to the ghosts. External
+ llama-servers (different binary path) never match.
+ """
+ try:
+ import psutil
+
- exe = str(server_binary(self.install_dir))
++ exe = str(self.server_exe)
+ except Exception: # noqa: BLE001
+ return
+ for p in psutil.process_iter(["exe", "ppid"]):
+ try:
+ if p.info.get("exe") != exe:
+ continue
+ if self.proc is not None and p.pid == self.proc.pid:
+ continue
+ ppid = p.info.get("ppid") or 0
+ if ppid and psutil.pid_exists(ppid):
+ continue
+ logger.warning("reaping orphaned llama-server child pid=%s", p.pid)
+ p.kill()
+ except (psutil.NoSuchProcess, psutil.AccessDenied):
+ continue
+
+ # ── model management (router endpoints) ──────────────────
+
+ def models(self) -> dict:
+ """{model_id: status_value} from GET /models."""
+ data = self._request("/models")
+ return {m["id"]: m.get("status", {}).get("value", "unknown")
+ for m in data.get("data", [])}
+
+ def model_failures(self) -> dict:
+ """{model_id: exit_code} for children that died — surfaced to the
+ UI, never auto-retried (design: router children are its problem)."""
+ data = self._request("/models")
+ out = {}
+ for m in data.get("data", []):
+ status = m.get("status", {})
+ if status.get("value") == "failed" or status.get("exit_code"):
+ out[m["id"]] = status.get("exit_code")
+ return out
+
+ def load_model(self, model_id: str, timeout_s: int = 600) -> None:
+ self._request("/models/load", {"model": model_id}, timeout_s=timeout_s)
+
+ def unload_model(self, model_id: str) -> None:
+ """Free the child's VRAM now. Route existence verified empirically
+ on b10290 (POST /models/unload; bogus name -> 400 'model is not
+ found'). Momentary action: never touches primary_model — the
+ declaration is durable, an eject is not (residency design).
+
+ Settle before returning: for a few seconds after unload returns,
+ the router still routes to the dying child and answers chat with
+ 500 'proxy error: Could not establish connection' (probed on
+ b10362). Waiting for the model to report unloaded means the next
+ message autoloads cleanly instead of racing the teardown.
+ """
+ self._request("/models/unload", {"model": model_id}, timeout_s=120)
+ deadline = time.monotonic() + 15
+ while time.monotonic() < deadline:
+ try:
+ if self.models().get(model_id) not in ("loaded", "ready", "unloading"):
+ return
+ except Exception: # noqa: BLE001
+ return
+ time.sleep(0.3)
+
+ # ── idle residency (non-primary models) ──────────────────
+
+ # A model that has gone quiet gets its VRAM back after this long. A
+ # constant, not a knob: long enough that an active conversation never
+ # trips it, short enough that a wandered-off session frees ~20 GiB
+ # within the hour. No exemptions (residency v2): demand reloads
+ # anything the user comes back to.
+ IDLE_UNLOAD_S = 15 * 60
+
+ def sweep_idle(self, now: float | None = None) -> list[str]:
+ """Unload models idle past IDLE_UNLOAD_S. Returns the model ids
+ unloaded. Idle means no busy slots and no queued work, tracked
+ per model across calls; a model seen busy resets its clock."""
+ now = time.monotonic() if now is None else now
+ unloaded: list[str] = []
+ try:
+ statuses = self.models()
+ except Exception: # noqa: BLE001
+ return unloaded
+ for model_id, status in statuses.items():
+ if status not in ("loaded", "ready"):
+ self._idle_since.pop(model_id, None)
+ continue
+ if not self.is_idle(model_id):
+ self._idle_since.pop(model_id, None)
+ continue
+ first_idle = self._idle_since.setdefault(model_id, now)
+ if now - first_idle >= self.IDLE_UNLOAD_S:
+ try:
+ self.unload_model(model_id)
+ self._idle_since.pop(model_id, None)
+ unloaded.append(model_id)
+ logger.info("idle-unloaded %s (idle %ds)", model_id,
+ int(now - first_idle))
+ except Exception as exc: # noqa: BLE001
+ logger.warning("idle unload of %s failed: %s", model_id, exc)
+ return unloaded
+
+ def touch_generate(self, model_id: str, timeout_s: int = 300) -> bool:
+ """The readiness proof. Generous budget + reasoning_content scan —
+ small token budgets false-fail reasoning models, which spend their
+ first tokens thinking."""
+ try:
+ resp = self._request("/v1/chat/completions", {
+ "model": model_id,
+ "messages": [{"role": "user", "content": TOUCH_PROMPT}],
+ "max_tokens": 512, "temperature": 0,
+ }, timeout_s=timeout_s)
+ msg = resp["choices"][0]["message"]
+ blob = (msg.get("content") or "") + " " + (msg.get("reasoning_content") or "")
+ return TOUCH_EXPECT in blob.lower()
+ except Exception as exc: # noqa: BLE001
+ logger.warning("touch generation failed for %s: %s", model_id, exc)
+ return False
+
+ def ensure_model_ready(self, model_id: str, timeout_s: int = 600) -> bool:
+ """Load if needed, then prove readiness with a touch generation."""
+ status = self.models().get(model_id)
+ if status is None:
+ raise KeyError(f"model {model_id} not present in models dir")
+ if status not in ("loaded", "ready"):
+ self.load_model(model_id, timeout_s=timeout_s)
+ return self.touch_generate(model_id)
+
+ def actual_n_ctx(self, model_id: str) -> int | None:
+ """/props reconciliation: the granted window as the child reports
+ it — the compressor's budget and the picker's 'running at 87K of
+ 262K' both read THIS value, never the request (design step 4)."""
+ try:
+ props = self._request(f"/props?model={model_id}")
+ return props.get("default_generation_settings", {}).get("n_ctx")
+ except Exception: # noqa: BLE001
+ return None
+
+ def keep_primary_loaded(self) -> None:
+ """The router's LRU eviction has no pin, so after any other load
+ re-touch the primary to keep it most-recently-used. Best-effort
+ under bursty multi-model load — replaced when an upstream pin
+ exists."""
+ if self.primary_model and self.models().get(self.primary_model) in (
+ "loaded", "ready"):
+ self.touch_generate(self.primary_model, timeout_s=60)
+
+ # ── telemetry ────────────────────────────────────────────
+
+ def is_idle(self, model_id: str | None = None) -> bool:
+ """No processing requests and no busy slots. Router quirk: /slots
+ and /metrics are per-child and require ?model= (bare calls 400),
+ and no KV-usage metric exists. With ``model_id`` checks that one
+ child; without, every loaded child."""
+ try:
+ if model_id is not None:
+ loaded = [model_id]
+ else:
+ loaded = [m for m, status in self.models().items()
+ if status in ("loaded", "ready")]
+ for mid in loaded:
+ slots = self._request(f"/slots?model={mid}")
+ if any(s.get("is_processing") for s in slots):
+ return False
+ req = urllib.request.Request(
+ self._url(f"/metrics?model={mid}"),
+ headers={"Authorization": f"Bearer {self.api_key}"})
+ with urllib.request.urlopen(req, timeout=10) as r:
+ text = r.read().decode()
+ for line in text.splitlines():
+ if line.startswith("llamacpp:requests_processing"):
+ if float(line.split()[-1]) != 0.0:
+ return False
+ return True
+ except Exception: # noqa: BLE001
+ return False
diff --cc hermes_cli/web_routers/local_models.py
index 00000000000,a9f4c433e21..c8a75d418c3
mode 000000,100644..100644
--- a/hermes_cli/web_routers/local_models.py
+++ b/hermes_cli/web_routers/local_models.py
@@@ -1,0 -1,1402 +1,1326 @@@
+ """Local-models dashboard routes — the desktop's window into the managed
+ llama.cpp runtime.
+
+ Everything here is designed for a first-run user on an RTX laptop: every
+ payload carries plain-language, pre-formatted facts the UI can show verbatim
+ (what will this model do ON THIS MACHINE, how big is the download, what is
+ the runtime doing right now), never raw internals the renderer would have to
+ interpret.
+
+ Long jobs (runtime install, model download) follow the repo's job pattern:
-start-POST -> {job_id} -> GET poll with byte progress. Downloads are
-byte-size checked against the catalog (no hash verification by design);
-a short download deletes the file and reports it plainly.
++start-POST -> {job_id} -> GET poll with byte progress. Model downloads run
++through the shared resumable downloader (pm.downloader): 8-way parallel,
++durable-partial resume, and no hash verification by design (catalog sizes
++may lag an upstream re-upload), so completeness is judged against the
++server's declared total, never the catalog. A running download can pause
++and resume via /api/local-models/download/pause and .../resume.
+ """
+
+ from __future__ import annotations
+
+ import json
+ import logging
+ import threading
+ import time
+ import urllib.parse
+ import urllib.request
+ import uuid
+ from pathlib import Path
+ from typing import Any, Dict, Optional
+
+ from fastapi import APIRouter, HTTPException
+ from pydantic import BaseModel
+
++from pm.downloader import Download, DownloadPaused, Source
++
+ from hermes_cli.local_runtime.endpoint import _state_endpoint
+
+ logger = logging.getLogger(__name__)
+
+ router = APIRouter()
+
+ _GIB = 1 << 30
+ _JOBS: Dict[str, Dict[str, Any]] = {}
+ _JOBS_LOCK = threading.Lock()
++# Live download handles + the resume callable per job_id. Kept OFF the job
++# dict so the JSON-serializable poll payload never carries a Download object.
++_RUNNING: Dict[str, Dict[str, Any]] = {}
+
+
+ def _human_gb(n: int | float) -> str:
+ return f"{n / _GIB:.1f} GB"
+
+
+ def _job(kind: str, target: str, model_id: str | None = None) -> Dict[str, Any]:
+ job = {
+ "job_id": uuid.uuid4().hex[:12],
+ "kind": kind, # "runtime-install" | "model-download"
+ "target": target,
+ "model_id": model_id, # catalog id for downloads; None otherwise
- "status": "running", # running | done | error
++ "status": "running", # running | done | error | paused
+ "phase": "starting", # human-readable step name
+ "detail": "",
+ "total_bytes": None,
+ "done_bytes": 0,
+ "started_at": time.time(),
+ "error": None,
+ }
+ with _JOBS_LOCK:
+ _JOBS[job["job_id"]] = job
+ return job
+
+
-# ── fast download: ranged parallel streams ───────────────────
-
-# One TCP stream to a CDN rarely fills a fast line; 8 ranged connections
-# writing into a preallocated file saturate consumer gigabit.
-_DOWNLOAD_CONNECTIONS = 8
-_CHUNK = 4 << 20
-
-
-def _probe_range_support(url: str) -> int:
- """Total size when the server honors Range requests, else 0.
-
- Auth-shaped failures raise with a plain-language message — a 401/403
- from the CDN means the repo is gated or the catalog entry names a
- wrong repo, and the user deserves better than a bare status code.
- """
- req = urllib.request.Request(url, headers={"Range": "bytes=0-0"})
- try:
- with urllib.request.urlopen(req, timeout=60) as r:
- if r.status == 206:
- content_range = r.headers.get("Content-Range", "")
- if "/" in content_range:
- return int(content_range.rsplit("/", 1)[1])
- except urllib.error.HTTPError as exc:
- if exc.code in (401, 403):
- raise RuntimeError(
- "The model host refused the download (gated or moved). "
- "This is a catalog problem, not yours — please report it.") from exc
- raise
- except Exception: # noqa: BLE001
- pass
- return 0
++# Model downloads run through the shared resumable downloader
++# (pm.downloader): 8-way parallel, durable partial bitmap, optional-hash
++# (models opt out of hashing — catalog sizes may lag upstream re-uploads).
+
+
+ def _model_id_for(gguf: Path) -> str:
+ """Variant model id for a staged file (strips split-part suffixes)."""
+ import re
+
+ return re.sub(r"-\d{5}-of-\d{5}$", "", gguf.stem)
+
+
+ def _variant_files_on_disk(model_id: str) -> "list[Path]":
+ """Every local file belonging to a staged model: all split parts plus
+ its catalog-declared assets (mmproj/draft) when present."""
+ from hermes_cli.local_runtime.bootstrap import assets_dir
+ from hermes_cli.local_runtime.catalog import find_entry_for_model
+
+ mdir = _models_dir()
+ files = [p for p in mdir.glob("*.gguf") if _model_id_for(p) == model_id]
+ hit = find_entry_for_model(model_id)
+ if hit is not None:
+ entry, _variant = hit
+ for asset in (entry.mmproj, entry.draft):
+ if asset is not None:
+ p = assets_dir() / asset.local_name
+ if p.exists():
+ files.append(p)
+ return files
+
+
-def download_file(url: str, dest: Path, job: Dict[str, Any],
- *,
- base_done: int = 0, keep_totals: bool = False) -> None:
- """Download url -> dest with byte progress on ``job``.
++def _download_job(job: Dict[str, Any], plan) -> None:
++ """Run a plan of (url, dest, size) downloads as ONE resumable Download.
+
- Ranged-parallel when the server supports it, single-stream fallback
- otherwise. There is no integrity check against the CATALOG by
- design: catalog sizes may lag an upstream re-upload, and a
- newer file than we know about must download fine. Completeness is
- checked only against what the SERVER declared for this transfer
- (range-probe total / Content-Length) — self-consistent and always
- current — so a dropped connection still errors instead of staging a
- truncated file. Never leaves a .part behind.
-
- Multi-file variants: ``base_done`` offsets the progress so this file's
- bytes accumulate onto the files before it, and ``keep_totals=True``
- stops the per-file size from overwriting the variant's total.
++ Completion and range progress feed the job dict (done_bytes /
++ total_bytes / ranges — the bar reads the aggregate, the detail view
++ reads the bitmap; both come from the same callback). Sources carry NO
++ hash by design: catalog sizes may lag an upstream re-upload, so
++ completeness is judged by the downloader against the server's declared
++ total, never the catalog. On pause the downloader raises
++ DownloadPaused; the job is marked 'paused' with its partials intact
++ for a later resume.
+ """
- import shutil
- import threading as _threading
-
- tmp = dest.with_suffix(".part")
- dest.parent.mkdir(parents=True, exist_ok=True)
- file_done = [0]
- progress_lock = _threading.Lock()
++ dl = Download([Source(url, dest) for url, dest, _ in plan])
++ _RUNNING.setdefault(job["job_id"], {})["dl"] = dl
+
- def bump(n: int) -> None:
- with progress_lock:
- file_done[0] += n
- job["done_bytes"] = base_done + file_done[0]
++ def tick(done: int, total: int, ranges: dict) -> None:
++ job["done_bytes"] = done
++ job["total_bytes"] = total
++ job["ranges"] = ranges
+
+ try:
- # The probe and the preallocation both take real seconds on a
- # 20+ GB file — narrate them, or the pane shows a dead '— of X GB'
- # until the first ranged byte lands.
- job["detail"] = "Connecting"
- total = _probe_range_support(url)
- if total:
- if not keep_totals:
- job["total_bytes"] = total
- # Preallocate so each worker writes at its own offset.
- job["detail"] = f"Reserving {_human_gb(total)} of disk space"
- with open(tmp, "wb") as f:
- f.truncate(total)
- job["detail"] = ""
- errors: list[Exception] = []
- bounds = [(i * total // _DOWNLOAD_CONNECTIONS,
- (i + 1) * total // _DOWNLOAD_CONNECTIONS - 1)
- for i in range(_DOWNLOAD_CONNECTIONS)]
-
- def fetch_range(start: int, end: int) -> None:
- try:
- req = urllib.request.Request(
- url, headers={"Range": f"bytes={start}-{end}"})
- with urllib.request.urlopen(req, timeout=120) as r, \
- open(tmp, "r+b") as f:
- f.seek(start)
- while True:
- chunk = r.read(_CHUNK)
- if not chunk:
- break
- f.write(chunk)
- bump(len(chunk))
- except Exception as exc: # noqa: BLE001
- errors.append(exc)
-
- threads = [_threading.Thread(target=fetch_range, args=b, daemon=True,
- name=f"lm-dl-{i}")
- for i, b in enumerate(bounds)]
- for t in threads:
- t.start()
- for t in threads:
- t.join()
- if errors:
- raise errors[0]
- if file_done[0] != total:
- raise RuntimeError(
- f"download incomplete ({file_done[0]} of {total} bytes)")
- else:
- # No range support: single stream, large chunks. Completeness
- # is judged by the server's own Content-Length when it sent
- # one — never by the catalog, which may lag a re-upload.
- with urllib.request.urlopen(url, timeout=120) as r, open(tmp, "wb") as f:
- length = int(r.headers.get("Content-Length") or 0)
- if length and not keep_totals:
- job["total_bytes"] = length
- while True:
- chunk = r.read(_CHUNK)
- if not chunk:
- break
- f.write(chunk)
- bump(len(chunk))
- if length and file_done[0] != length:
- raise RuntimeError(
- f"Download ended at {file_done[0]:,} bytes but the server "
- f"said {length:,} — connection dropped? Removed; try again")
-
- shutil.move(str(tmp), str(dest))
- except Exception:
- tmp.unlink(missing_ok=True)
++ dl.run(progress=tick)
++ except DownloadPaused:
++ job["status"] = "paused"
+ raise
++ finally:
++ _RUNNING.get(job["job_id"], {}).pop("dl", None)
+
+
+ def _models_dir() -> Path:
+ from hermes_cli.local_runtime.bootstrap import models_dir
+
+ return models_dir()
+
+
+ def _engine_too_old(min_engine: str) -> bool:
- """True when the installed llama.cpp predates a model's requirement.
- Tags are release numbers (b10362); no engine installed compares as
- too old only when the model states a requirement."""
++ """True when the pinned llama.cpp predates a model's requirement.
++ Tags are release numbers (b10362); the lockfile is the one version
++ authority, so this compares against the pin, not against config."""
+ if not min_engine:
+ return False
+ try:
- from hermes_cli.local_runtime.binaries import default_tag, installed_tags
++ from hermes_cli.local_runtime.binaries import engine_version
+
- tags = installed_tags() or [default_tag()]
- newest = max(int(t.lstrip("b")) for t in tags if t.lstrip("b").isdigit())
- return newest < int(min_engine.lstrip("b"))
++ pinned = (engine_version() or "").lstrip("b")
++ if not pinned.isdigit():
++ return False
++ return int(pinned) < int(min_engine.lstrip("b"))
+ except Exception: # noqa: BLE001
+ return False
+
+
+ def _load_config() -> dict:
+ from hermes_cli.config import load_config
+
+ try:
+ return load_config()
+ except Exception: # noqa: BLE001
+ return {}
+
+
+ def _runtime_section() -> dict:
+ return (_load_config() or {}).get("local_runtime") or {}
+
+
+ # ── status: the one call the pane opens with ─────────────────
+
+
+ @router.get("/api/local-models/status")
+ async def local_models_status():
+ """Cheap, immediate, never blocks on probes (responsiveness standard):
+ config state + installed runtime + staged models + supervisor state.
+ GPU facts come from /api/local-models/hardware (slower, polled)."""
+ from hermes_cli.local_runtime.binaries import (
- default_tag,
- installed_tags,
- runtimes_root,
- server_binary,
++ engine_update_pending,
++ engine_version,
++ installed_backends,
++ installed_engine_version,
+ )
+
+ section = _runtime_section()
- configured_tag = section.get("tag") or default_tag()
- have = installed_tags()
++ have = installed_backends()
+
- # The tag actually serving (boot ladder: configured if installed, else
- # newest installed). Present tense for the pane header.
- tag = configured_tag if configured_tag in have else (have[0] if have else configured_tag)
++ # The tag actually serving, else the pinned one. Present tense for the
++ # pane header.
++ runtime_backend = have[0] if have else None
++ tag = (installed_engine_version(runtime_backend) if runtime_backend
++ else None) or engine_version()
+
+ # A pending engine update exists when the user runs the local engine
- # (enabled + something installed) and the configured tag — pinned or
- # the Hermes-release default — is newer than anything on disk. The
- # download is a button click, never automatic.
- update_available = bool(
- section.get("enabled") and have and configured_tag not in have)
-
- runtime_installed = False
- runtime_backend = None
- root = runtimes_root() / tag
- if root.exists():
- for backend_dir in sorted(p for p in root.iterdir() if p.is_dir()):
- try:
- server_binary(backend_dir)
- runtime_installed = True
- runtime_backend = backend_dir.name
- break
- except Exception: # noqa: BLE001
- continue
++ # (enabled + something installed) and the pin — refreshed by a Hermes
++ # release — is newer than what is on disk. Installing is a button
++ # click, never automatic.
++ update_available = bool(section.get("enabled") and engine_update_pending())
++
++ runtime_installed = bool(have)
+
+ staged = []
+ mdir = _models_dir()
+ if mdir.exists():
+ from hermes_cli.local_runtime.bootstrap import staged_models
+
+ # Split models: report the whole variant's bytes, not one part's.
+ from hermes_cli.local_runtime.catalog import find_entry_for_model
+
+ for gguf in staged_models():
+ model_id = _model_id_for(gguf)
+ size = gguf.stat().st_size
+ hit = find_entry_for_model(model_id)
+ if hit is not None:
+ size = hit[1].size_bytes
+ staged.append({
+ "id": model_id,
+ "size_bytes": size,
+ "size_label": _human_gb(size),
+ })
+
+ running = _state_endpoint()
+
+ # Which staged models are resident right now (loaded in VRAM). Read
+ # from the live router when it's up; {} when down. Feeds the pane's
+ # Loaded pills and eject buttons.
+ loaded: Dict[str, str] = {}
+ placement: Dict[str, Any] = {}
+ if running is not None:
+ try:
+ import urllib.request as _url
+
+ req = _url.Request(
+ running["base_url"].rsplit("/v1", 1)[0] + "/models",
+ headers={"Authorization": f"Bearer {running.get('api_key', '')}"})
+ with _url.urlopen(req, timeout=3) as r:
+ data = json.loads(r.read())
+ loaded = {
+ m["id"]: m.get("status", {}).get("value", "unknown")
+ for m in data.get("data", [])
+ # Everything resident or becoming resident: 'loading' renders
+ # as its own state in the pane (a 20-GB load in flight is the
+ # single most important thing the pane can show).
+ if m.get("status", {}).get("value") in ("loaded", "ready", "loading")
+ }
+ # How each loaded model is actually running: the granted window
+ # from the child itself, and the plan's spill facts from the
+ # preset decision. The pane shows this verbatim — placement is
+ # the difference between 'fast' and 'why is my CPU busy', so it
+ # must be inspectable, not inferred from Task Manager.
+ from hermes_cli.local_runtime.presets import read_preset_decisions
+
+ decisions = read_preset_decisions()
+ for model_id in loaded:
+ entry_facts: Dict[str, Any] = {}
+ plan = decisions.get(model_id)
+ if plan is not None:
+ entry_facts["window"] = plan.window
+ entry_facts["window_label"] = f"{plan.window // 1024}K"
+ entry_facts["spilled"] = plan.spilled
+ if loaded[model_id] in ("loaded", "ready"):
+ try:
+ preq = _url.Request(
+ running["base_url"].rsplit("/v1", 1)[0]
+ + f"/props?model={model_id}",
+ headers={"Authorization":
+ f"Bearer {running.get('api_key', '')}"})
+ with _url.urlopen(preq, timeout=3) as pr:
+ props = json.loads(pr.read())
+ n_ctx = (props.get("default_generation_settings", {})
+ .get("n_ctx"))
+ if n_ctx:
+ entry_facts["granted_window"] = int(n_ctx)
+ entry_facts["granted_window_label"] = f"{int(n_ctx) // 1024}K"
+ except Exception: # noqa: BLE001
+ pass
+ if entry_facts:
+ placement[model_id] = entry_facts
+ except Exception as exc: # noqa: BLE001
+ # Never silent: an empty dict here renders as 'Not in memory'
+ # on a machine whose VRAM is visibly full.
+ logger.warning("loaded-models read failed: %r", exc)
+ loaded = {}
+
+ # The active main model, when it is one of ours (config authority: the
+ # same model.provider + model.default that /api/model/set writes).
+ active_model_id = None
+ try:
+ config = _load_config()
+ model_section = (config or {}).get("model") or {}
+ if str(model_section.get("provider", "")).strip().lower() in (
+ "llamacpp", "llama.cpp", "llama-cpp"):
+ active_model_id = str(
+ model_section.get("default") or model_section.get("name") or ""
+ ).strip() or None
+ except Exception: # noqa: BLE001
+ pass
+
+ return {
+ "enabled": bool(section.get("enabled")),
+ "tag": tag,
- "configured_tag": configured_tag,
++ # The pinned build. Equal to "tag" unless an older engine is
++ # installed and its update has not been clicked yet.
++ "configured_tag": engine_version(),
+ "update_available": update_available,
+ "runtime_installed": runtime_installed,
+ "runtime_backend": runtime_backend,
+ "server_running": running is not None,
+ "server_base_url": (running or {}).get("base_url"),
+ "active_model_id": active_model_id,
+ "loaded_models": loaded,
+ # Live load progress per model (SSE-fed): {model_id: {stage, value,
+ # percent}}. The chat's loading bar and the picker rows poll this.
+ "loading": _loading_progress(),
+ "placement": placement,
+ "models": staged,
+ "models_dir": str(mdir),
+ }
+
+
+ def _loading_progress() -> Dict[str, Any]:
+ try:
+ from hermes_cli.local_runtime.load_progress import get_loading_progress
+
+ return get_loading_progress()
+ except Exception: # noqa: BLE001 — progress is garnish, never a 500
+ return {}
+
+
+ # ── hardware: what this machine can do ───────────────────────
+
+
+ @router.get("/api/local-models/hardware")
+ async def local_models_hardware():
+ """The budget as plain facts. Polled by the pane and the statusbar
+ resource item (throttled client-side)."""
+ from hermes_cli.local_runtime.hardware import probe_budget, _nvidia_vram, _ram_bytes
+
+ budget = probe_budget()
+ ram_total, ram_avail = _ram_bytes()
+ out = {
+ "uma": budget.uma,
+ "vram_total_bytes": budget.total_device_bytes,
+ "vram_usable_bytes": budget.usable_vram_bytes,
+ "ram_total_bytes": ram_total,
+ "ram_available_bytes": ram_avail,
+ "vram_label": _human_gb(budget.total_device_bytes),
+ "gpu_name": None,
+ "gpu_util_percent": None,
+ "vram_used_bytes": None,
+ }
+ # GPU identity + live utilization (NVIDIA; other vendors degrade to None
+ # and the UI hides those readouts).
+ try:
+ import subprocess
+
+ from hermes_cli.local_runtime.hardware import _nvidia_smi_path
+
+ smi_exe = _nvidia_smi_path()
+ smi = subprocess.run(
+ [smi_exe, "--query-gpu=name,utilization.gpu,memory.used",
+ "--format=csv,noheader,nounits"],
+ capture_output=True, text=True, timeout=5) if smi_exe else None
+ if smi and smi.returncode == 0 and smi.stdout.strip():
+ name, util, used_mib = (x.strip() for x in smi.stdout.strip().splitlines()[0].split(","))
+ out["gpu_name"] = name
+ out["gpu_util_percent"] = int(util)
+ out["vram_used_bytes"] = int(used_mib) << 20
+ except Exception: # noqa: BLE001
+ pass
+ return out
+
+
+ # ── catalog: priced for THIS machine before download ─────────
+
+
+ @router.get("/api/local-models/catalog")
+ async def local_models_catalog():
+ """Every entry answers the user's three questions up front: how big is
+ the download, will it fit, and what context/speed shape will I get —
+ computed from the catalog's measured numbers + this machine's
+ budget. Hardware-aware quant selection: the row advertises the BEST
+ build for this machine (highest quality that runs fully on the GPU at
+ the 64K floor; else the smallest that works, spilled and priced). No
+ entry is hidden; unaffordable models show WHY."""
+ from hermes_cli.local_runtime.catalog import (
+ CATALOG,
+ recommended_id,
+ refresh_catalog_soon,
+ select_variant,
+ )
+ from hermes_cli.local_runtime.context_policy import (
+ RUNTIME_OVERHEAD_BYTES,
+ initial_window,
+ ub_logits_bytes,
+ )
+ from hermes_cli.local_runtime.estimator import PhysicsRefusal
+ from hermes_cli.local_runtime.hardware import probe_budget
+
+ # This request serves the catalog already in memory; a TTL-gated
+ # background fetch from the repo lands new entries for the next one
+ # (day-0 models reach the pane without an app release).
+ refresh_catalog_soon()
+
+ # Planning budget: price against machine capacity, not live-free VRAM.
+ # A loaded model must not make the catalog call every row unaffordable.
+ budget = probe_budget(planning=True)
+ # The default pick for THIS machine: quality-ranked, fit- and
+ # speed-gated (recommended_entry). Engine-gated entries can't be
+ # activated today, so they can't be the recommendation either.
+ eligible = tuple(e for e in CATALOG if not _engine_too_old(e.min_engine))
+ recommended = recommended_id(budget, eligible)
+ # Completeness-checked staging (split parts all present) — the same
+ # answer the picker and the router see, so a mid-download model never
+ # reads as downloaded here.
+ from hermes_cli.local_runtime.bootstrap import staged_model_ids
+
+ staged_ids = set(staged_model_ids())
+ entries = []
+ for entry in CATALOG:
+ choice = select_variant(entry, budget)
+ # Any variant of this family already on disk counts as downloaded
+ # (split variants stage under their first part).
+ downloaded_variant = next(
+ (v for v in entry.variants if v.model_id in staged_ids), None)
+ row: Dict[str, Any] = {
+ "id": entry.id,
+ "display_name": entry.display_name,
+ "description": entry.description,
+ "native_context": entry.n_ctx_train,
+ "native_context_label": f"{entry.n_ctx_train // 1024}K",
+ "recommended": entry.id == recommended,
+ "downloaded": downloaded_variant is not None,
+ "downloaded_model_id": downloaded_variant.model_id if downloaded_variant else None,
+ "downloaded_quant": downloaded_variant.quant if downloaded_variant else None,
+ "mtp": entry.mtp,
+ "vision": entry.mmproj is not None,
+ # Day-0 architectures need the llama.cpp release where their
+ # support landed. True gates download/activate in the pane
+ # until the engine updates; the row still renders (visible +
+ # explained beats hidden).
+ "needs_engine": _engine_too_old(entry.min_engine),
+ "min_engine": entry.min_engine or None,
+ }
+ if choice is None:
+ smallest = min(entry.variants, key=lambda v: v.size_bytes)
+ smallest_total = entry.download_bytes(smallest)
+ row.update({
+ "fits": False,
+ "size_bytes": smallest_total,
+ "size_label": _human_gb(smallest_total),
+ "fit_summary": "Needs more memory than this machine has",
+ "fit_detail": (f"even the most compact build ({smallest.quant}, "
+ f"{_human_gb(smallest_total)}) exceeds GPU + system memory"),
+ })
+ entries.append(row)
+ continue
+
+ variant = choice.variant
+ profile = entry.profile(variant)
+ # Same overhead the launch decision prices (runtime buffers +
+ # vision projector + the microbatch/MTP logits buffers): the row
+ # must advertise the window the model will actually get, not a
+ # paper number the server's own fit then shaves down.
+ overhead = (RUNTIME_OVERHEAD_BYTES
+ + (entry.mmproj.size_bytes if entry.mmproj else 0)
+ + ub_logits_bytes(entry.n_vocab, mtp_capable=entry.mtp))
+ decision = initial_window(profile, budget, overhead_bytes=overhead)
+ download_total = entry.download_bytes(variant)
+ row.update({
+ "fits": True,
+ "model_id": variant.model_id,
+ "quant": variant.quant,
+ "quant_validated": variant.validated,
+ "size_bytes": download_total,
+ "size_label": _human_gb(download_total),
+ "variant_count": len(entry.variants),
+ })
+ if choice.reason_key == "best-large-window":
+ row["quant_reason"] = (
+ f"Recommended build ({variant.quant}) — the quant class this "
+ "engine is optimized for; runs fully on your GPU with a "
+ "large context window")
+ elif choice.reason_key == "best-fits":
+ row["quant_reason"] = (
+ f"Recommended build ({variant.quant}) — the quant class this "
+ "engine is optimized for; runs fully on your GPU")
+ else:
+ row["quant_reason"] = (
+ f"Compact build sized for this machine ({variant.quant}) — "
+ "larger than GPU memory, runs slower")
+ if not isinstance(decision, PhysicsRefusal):
+ row["start_window"] = decision.window
+ row["start_window_label"] = f"{decision.window // 1024}K"
+ row["spilled"] = decision.spilled
+ if decision.window >= entry.n_ctx_train:
+ shape = f"runs at its full {row['native_context_label']} context"
+ else:
+ shape = (f"starts at {row['start_window_label']} and grows toward "
+ f"{row['native_context_label']} as you use it")
+ if decision.spilled:
+ shape += " (larger than your GPU memory — runs slower)"
+ row["fit_summary"] = shape
+ else:
+ row["fit_summary"] = row["quant_reason"]
+ entries.append(row)
+ return {"models": entries}
+
+
+ # ── runtime install (job) ────────────────────────────────────
+
+
+ class RuntimeInstallBody(BaseModel):
+ backend: Optional[str] = None # None/auto -> detect
+
+
+ def _runtime_progress_hook(job: Dict[str, Any]):
- """Adapter: ensure_runtime_installed's progress stream -> job fields.
++ """Adapter: pm's install progress stream -> job fields.
+
+ Throttled to ~4 updates/s; each stage restarts the byte counters so
- the bar reflects the CURRENT stage (download then unpack per asset).
++ the bar reflects the CURRENT stage (download then unpack per archive).
+ Slow lines sit in the download stage for minutes — the counters are
+ what proves liveness, so they must move on every tick."""
+ state = {"last": 0.0}
+
+ def hook(stage: str, done: int, total: int, label: str) -> None:
+ now = time.monotonic()
+ if now - state["last"] < 0.25 and done < total:
+ return
+ state["last"] = now
+ suffix = f" ({label})" if label else ""
+ if stage == "download":
+ job["phase"] = "downloading-runtime"
+ if total:
+ job["detail"] = (f"Downloading the local engine{suffix} — "
+ f"{_human_gb(done)} of {_human_gb(total)}")
+ else:
+ job["detail"] = (f"Downloading the local engine{suffix} — "
+ f"{_human_gb(done)}")
- elif stage == "extract":
++ else:
+ job["phase"] = "unpacking-runtime"
+ job["detail"] = f"Unpacking the engine{suffix}"
- else: # verify
- job["phase"] = "verifying-runtime"
- job["detail"] = "Verifying the engine"
+ job["done_bytes"] = done
+ job["total_bytes"] = total or None
+
+ return hook
+
+
+ @router.post("/api/local-models/runtime/install")
+ async def local_models_runtime_install(body: RuntimeInstallBody):
+ from hermes_cli.local_runtime.binaries import (
- default_tag,
- resolve_assets,
++ engine_version,
++ resolve_backend,
+ select_backend,
++ unavailable_reason,
+ )
+ from hermes_cli.local_runtime.bootstrap import _detect_gpu_vendor
+
+ section = _runtime_section()
- tag = section.get("tag") or default_tag()
++ tag = engine_version()
+ backend = body.backend or section.get("backend", "auto")
+ if backend == "auto":
+ backend = select_backend(_detect_gpu_vendor())
- # Resolve first so an impossible combination fails the POST, not the job.
++ # An unpinned combination is knowable before any work starts, so an
++ # explicitly requested backend that this platform has no build for
++ # fails the POST with the pin table's own reason. "auto" instead walks
++ # down the ladder — the user asked for "whatever works here".
++ if body.backend:
++ reason = unavailable_reason(backend)
++ if reason is not None:
++ raise HTTPException(status_code=400, detail=reason)
+ try:
- plan = resolve_assets(tag, backend)
++ backend = resolve_backend(backend)
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(status_code=400, detail=str(exc))
+
+ job = _job("runtime-install", f"llama.cpp {tag} ({backend})")
+
+ def _run():
+ try:
+ from hermes_cli.local_runtime.binaries import (
- ensure_runtime_installed,
- installed_tags,
- prune_old_tags,
++ ensure_engine,
++ installed_backends,
+ )
+
- previous = installed_tags()
++ was_installed = backend in installed_backends()
+ job["phase"] = "downloading"
- job["detail"] = f"Fetching {len(plan.assets)} package(s) for {backend}"
- ensure_runtime_installed(tag, backend,
- progress=_runtime_progress_hook(job))
++ job["detail"] = f"Fetching the {backend} engine"
++ ensure_engine(backend, progress=_runtime_progress_hook(job))
+
- # Engine update path: a server already running on an older tag
- # moves to the new one now — the click was the consent. Fresh
- # installs (no server) skip this; Use/boot handles their start.
++ # Engine update path: a server already running on an older
++ # build moves to the new one now — the click was the consent.
++ # Fresh installs (no server) skip this; Use/boot starts them.
+ restarted = False
+ try:
+ from hermes_cli.local_runtime.bootstrap import (
+ ensure_local_runtime,
+ get_supervisor,
+ shutdown_local_runtime,
+ )
+
+ sup = get_supervisor()
- if sup is not None and previous and tag not in previous:
++ if sup is not None and was_installed:
+ job["phase"] = "restarting"
+ job["detail"] = "Switching the running server to the new build"
+ shutdown_local_runtime()
+ ensure_local_runtime(_load_config(), force=True)
+ restarted = True
+ except Exception as exc: # noqa: BLE001
+ # The new build is installed either way; the next boot serves
+ # it. Never fail the job on the restart nicety.
+ logger.warning("post-update restart skipped: %s", exc)
+
- # N-1 retention, only after the new tag verified: keep it and the
- # newest previous build as the rollback pin target.
- try:
- keep = [tag] + [t for t in previous if t != tag][:1]
- prune_old_tags(keep)
- except Exception as exc: # noqa: BLE001
- logger.warning("runtime prune skipped: %s", exc)
-
++ # No retention pass here. Store entries are keyed
++ # (package, version, target) and shared across profiles and
++ # installs, so deleting the superseded build is `hermes pm gc`'s
++ # call to make, not one install job's.
+ job["phase"] = "done"
+ job["status"] = "done"
+ job["detail"] = (f"llama.cpp {tag} ready ({backend})"
+ + (" — server restarted on the new build" if restarted else ""))
+ except Exception as exc: # noqa: BLE001
+ logger.warning("runtime install failed: %s", exc)
+ job["status"] = "error"
+ job["error"] = str(exc)
+
+ threading.Thread(target=_run, daemon=True, name="lr-runtime-install").start()
+ return {"job_id": job["job_id"], "backend": backend, "tag": tag}
+
+
+ # ── model download (job with byte progress) ──────────────────
+
+
+ class ModelDownloadBody(BaseModel):
+ model_id: str
+
+
+ @router.post("/api/local-models/download")
+ async def local_models_download(body: ModelDownloadBody):
+ """Accepts either a family id (downloads this machine's selected
+ variant) or an exact variant model_id."""
+ from hermes_cli.local_runtime.catalog import (
+ CATALOG,
+ catalog_by_id,
+ select_variant,
+ )
+ from hermes_cli.local_runtime.hardware import probe_budget
+
+ entry = catalog_by_id().get(body.model_id)
+ variant = None
+ if entry is not None:
+ if _engine_too_old(entry.min_engine):
+ raise HTTPException(
+ status_code=409,
+ detail=(f"{entry.display_name} needs llama.cpp {entry.min_engine} "
+ f"or newer — update the engine first"))
+ # Same planning budget as the catalog — the user downloads exactly
+ # the build the row advertised.
+ choice = select_variant(entry, probe_budget(planning=True))
+ if choice is None:
+ raise HTTPException(status_code=409,
+ detail=f"no variant of {entry.id} fits this machine")
+ variant = choice.variant
+ else:
+ for candidate in CATALOG:
+ for v in candidate.variants:
+ if v.model_id == body.model_id:
+ entry, variant = candidate, v
+ break
+ if variant:
+ break
+ if entry is None or variant is None:
+ raise HTTPException(status_code=404, detail=f"unknown model {body.model_id}")
+
+ from hermes_cli.local_runtime.bootstrap import assets_dir, staged_model_ids
+
+ if variant.model_id in staged_model_ids():
+ return {"job_id": None, "already_downloaded": True, "model_id": variant.model_id}
+
+ # Everything this variant needs: split parts + mmproj/draft assets.
+ plan = [] # (url, dest, bytes)
+ for asset in variant.files:
+ plan.append((f"https://huggingface.co/{entry.repo}/resolve/main/{asset.path}",
+ _models_dir() / asset.local_name, asset.size_bytes))
+ for asset in (entry.mmproj, entry.draft):
+ if asset is not None:
+ plan.append((f"https://huggingface.co/{entry.repo}/resolve/main/{asset.path}",
+ assets_dir() / asset.local_name, asset.size_bytes))
+
+ total = sum(p[2] for p in plan)
+ job = _job("model-download", f"{entry.display_name} ({variant.quant})",
+ model_id=entry.id)
+ job["total_bytes"] = total
+
+ def _run():
+ try:
+ job["phase"] = "downloading"
+ job["detail"] = f"{entry.display_name} — {_human_gb(total)}"
- done_before = 0
- for url, dest, size in plan:
- if dest.exists():
- done_before += size
- job["done_bytes"] = done_before
- continue
- download_file(url, dest, job,
- base_done=done_before, keep_totals=True)
- job["phase"] = "downloading"
- done_before += size
- job["done_bytes"] = done_before
++ _download_job(job, plan)
+ job["phase"] = "done"
+ job["status"] = "done"
+ job["detail"] = f"{entry.display_name} ready"
+ # A running router only scans models at spawn —
+ # bounce it so the new model is servable
+ # immediately instead of 400ing until the next app restart.
+ try:
+ from hermes_cli.local_runtime.bootstrap import refresh_local_runtime
+
+ refresh_local_runtime()
+ except Exception: # noqa: BLE001
+ logger.debug("post-download runtime refresh skipped", exc_info=True)
++ except DownloadPaused:
++ pass # status already "paused"; partials kept for resume
+ except Exception as exc: # noqa: BLE001
+ logger.warning("model download failed: %s", exc)
+ job["status"] = "error"
+ job["error"] = str(exc)
++ finally:
++ if job["status"] != "paused":
++ _RUNNING.pop(job["job_id"], None)
+
++ _RUNNING[job["job_id"]] = {"resume": _run, "dl": None}
+ threading.Thread(target=_run, daemon=True, name="lr-model-download").start()
+ return {"job_id": job["job_id"], "model_id": variant.model_id}
+
+
++class JobIdBody(BaseModel):
++ job_id: str
++
++
[email protected]("/api/local-models/download/pause")
++async def local_models_download_pause(body: JobIdBody):
++ """Pause a running model download. The downloader's live handle is
++ checked off the job dict (which stays JSON-serializable for the poll
++ route); when none is active (already done/paused) this is a no-op."""
++ running = _RUNNING.get(body.job_id)
++ if running is None:
++ raise HTTPException(status_code=404, detail="unknown download job")
++ dl = running.get("dl")
++ if dl is None:
++ return {"ok": True, "paused": False}
++ dl.pause()
++ return {"ok": True, "paused": True}
++
++
[email protected]("/api/local-models/download/resume")
++async def local_models_download_resume(body: JobIdBody):
++ """Resume a paused model download. Completed files are skipped and
++ partials resume from their byte-range bitmap (the downloader owns that
++ — the route just re-runs the job body)."""
++ job = _JOBS.get(body.job_id)
++ running = _RUNNING.get(body.job_id)
++ if job is None or running is None or running.get("resume") is None:
++ raise HTTPException(status_code=404, detail="unknown or finished download job")
++ if job["status"] != "paused":
++ return {"ok": True, "resumed": False}
++ job["status"] = "running"
++ threading.Thread(target=running["resume"], daemon=True,
++ name="lm-dl-resume").start()
++ return {"ok": True, "resumed": True}
++
++
+ @router.delete("/api/local-models/models/{model_id}")
+ async def local_models_delete(model_id: str):
+ """Remove a staged model: every split part plus its private assets.
+ A running router keeps serving from its spawn-time scan, so bounce it
+ off the request thread — deleting the active file mid-serve is the
+ kind of stale state the refresh exists for."""
+ files = _variant_files_on_disk(model_id)
+ if not files:
+ raise HTTPException(status_code=404, detail="model not found")
+ for path in files:
+ path.unlink(missing_ok=True)
+ # Growth state dies with the model: a re-download starts back at its
+ # zero-spill window instead of inheriting a stale grown one.
+ try:
+ from hermes_cli.local_runtime.growth import clear_window_override
+
+ clear_window_override(model_id)
+ except Exception: # noqa: BLE001
+ logger.debug("window-override clear skipped", exc_info=True)
+
+ def _refresh():
+ try:
+ from hermes_cli.local_runtime.bootstrap import refresh_local_runtime
+
+ refresh_local_runtime()
+ except Exception: # noqa: BLE001
+ logger.debug("post-delete runtime refresh skipped", exc_info=True)
+
+ threading.Thread(target=_refresh, daemon=True, name="lr-post-delete").start()
+ return {"ok": True}
+
+
+ # ── server lifecycle: turn the engine on/off ─────────────────
+
+
+ class ServerActionBody(BaseModel):
+ action: str # "stop" | "start"
+
+
+ # ── quickstart: one click from nothing to a working default ──
+
+
+ class QuickstartBody(BaseModel):
+ model_id: str | None = None # default: the catalog's recommended entry
+
+
+ # One quickstart at a time: the job sequences installs, downloads, a
+ # server bounce, and a config write — two racing runs would interleave
+ # all four. Held for the job's lifetime, released in the worker.
+ _QUICKSTART_LOCK = threading.Lock()
+
+
+ @router.post("/api/local-models/quickstart")
+ async def local_models_quickstart(body: QuickstartBody):
+ """The dummy-proof path: one job that installs the runtime (if
+ missing), downloads this machine's build of the recommended model
+ (if missing), and makes it the default for new chats. Each leg is
+ the same code the individual routes run — this route only sequences
+ them, so 'Configure' (the existing pane) and quickstart can never
+ disagree about what gets installed.
+
+ Preflight rejects (no servable entry, engine too old) fail the POST
+ synchronously so the button can explain itself; everything slow runs
+ in the job with the usual phase/byte progress.
+ """
+ from hermes_cli.local_runtime.binaries import (
- default_tag,
- installed_tags,
- resolve_assets,
++ installed_backends,
++ resolve_backend,
+ select_backend,
+ )
+ from hermes_cli.local_runtime.bootstrap import (
+ _detect_gpu_vendor,
+ assets_dir,
+ staged_model_ids,
+ )
+ from hermes_cli.local_runtime.catalog import (
+ CATALOG,
+ catalog_by_id,
+ recommended_entry,
+ select_variant,
+ )
+ from hermes_cli.local_runtime.hardware import probe_budget
+
+ # Resolve the target entry: explicit id, else this machine's
+ # recommendation (quality-ranked, fit- and speed-gated), else the
+ # first catalog entry this machine can serve.
+ budget = probe_budget(planning=True)
+ entry = None
+ if body.model_id:
+ entry = catalog_by_id().get(body.model_id)
+ if entry is None:
+ raise HTTPException(status_code=404,
+ detail=f"unknown model {body.model_id}")
+ candidates = [entry]
+ else:
+ eligible = tuple(e for e in CATALOG if not _engine_too_old(e.min_engine))
+ best = recommended_entry(budget, eligible)
+ candidates = ([best] if best is not None else []) + [
+ e for e in CATALOG if best is None or e.id != best.id]
+ chosen = None
+ for candidate in candidates:
+ choice = select_variant(candidate, budget)
+ if choice is not None and not _engine_too_old(candidate.min_engine):
+ chosen = (candidate, choice.variant)
+ break
+ if chosen is None:
+ raise HTTPException(
+ status_code=409,
+ detail="no catalog model fits this machine — open Local Models "
+ "to browse for a smaller build")
+ entry, variant = chosen
+
+ section = _runtime_section()
- tag = section.get("tag") or default_tag()
+ backend = section.get("backend", "auto")
+ if backend == "auto":
+ backend = select_backend(_detect_gpu_vendor())
- need_runtime = not installed_tags()
- if need_runtime:
- # Same preflight as /runtime/install: impossible combos fail the POST.
- try:
- resolve_assets(tag, backend)
- except Exception as exc: # noqa: BLE001
- raise HTTPException(status_code=400, detail=str(exc))
++ need_runtime = not installed_backends()
++ # Same preflight as /runtime/install: a platform with no usable build
++ # fails the POST rather than the job.
++ try:
++ backend = resolve_backend(backend)
++ except Exception as exc: # noqa: BLE001
++ raise HTTPException(status_code=400, detail=str(exc))
+
+ need_download = variant.model_id not in staged_model_ids()
+ download_plan = [] # (url, dest, bytes)
+ if need_download:
+ for asset in variant.files:
+ download_plan.append(
+ (f"https://huggingface.co/{entry.repo}/resolve/main/{asset.path}",
+ _models_dir() / asset.local_name, asset.size_bytes))
+ for asset in (entry.mmproj, entry.draft):
+ if asset is not None:
+ download_plan.append(
+ (f"https://huggingface.co/{entry.repo}/resolve/main/{asset.path}",
+ assets_dir() / asset.local_name, asset.size_bytes))
+
+ if not _QUICKSTART_LOCK.acquire(blocking=False):
+ raise HTTPException(status_code=409,
+ detail="Setup is already running")
+
+ job = _job("quickstart", entry.display_name, model_id=entry.id)
+ job["total_bytes"] = sum(p[2] for p in download_plan) or None
+
+ def _run():
+ try:
+ if need_runtime:
- from hermes_cli.local_runtime.binaries import ensure_runtime_installed
++ from hermes_cli.local_runtime.binaries import ensure_engine
+
+ job["phase"] = "installing-runtime"
+ job["detail"] = "Installing the local engine"
- ensure_runtime_installed(tag, backend,
- progress=_runtime_progress_hook(job))
++ ensure_engine(backend, progress=_runtime_progress_hook(job))
+
+ if need_download:
+ job["phase"] = "downloading"
+ total = sum(p[2] for p in download_plan)
+ # The runtime leg repurposed the byte counters for its own
+ # stages — reset them to the model plan before download.
+ job["done_bytes"] = 0
+ job["total_bytes"] = total
+ job["detail"] = f"{entry.display_name} — {_human_gb(total)}"
- done_before = 0
- for url, dest, size in download_plan:
- if dest.exists():
- done_before += size
- job["done_bytes"] = done_before
- continue
- download_file(url, dest, job,
- base_done=done_before, keep_totals=True)
- job["phase"] = "downloading"
- done_before += size
- job["done_bytes"] = done_before
++ _download_job(job, download_plan)
+
+ # Activate: same sequence as /activate's job body.
+ from hermes_cli.config import load_config, save_config
+ from hermes_cli.local_runtime.bootstrap import (
+ ensure_local_runtime,
+ refresh_local_runtime,
+ )
+
+ job["phase"] = "starting-server"
+ job["detail"] = "Starting the local server"
+ config = load_config()
+ config.setdefault("local_runtime", {})["enabled"] = True
+ save_config(config)
+ sup = ensure_local_runtime(config, force=True)
+ if sup is None and _state_endpoint() is None:
+ raise RuntimeError(
+ "The local server could not start — open Local Models for details")
+ if sup is not None:
+ try:
+ if variant.model_id not in sup.models():
+ job["detail"] = "Refreshing the local server"
+ refresh_local_runtime()
+ except Exception: # noqa: BLE001
+ logger.debug("quickstart rescan check skipped", exc_info=True)
+
+ job["phase"] = "setting-default"
+ job["detail"] = "Making it your default"
+ from hermes_cli.web_deps import late
+
+ late("_apply_model_assignment_sync")(
+ "main", "llamacpp", variant.model_id, "", "", "")
+
+ job["phase"] = "done"
+ job["status"] = "done"
+ job["detail"] = f"{entry.display_name} is ready — new chats use it"
++ except DownloadPaused:
++ pass # status already "paused"; partials kept for resume
+ except Exception as exc: # noqa: BLE001
+ logger.warning("quickstart failed: %s", exc)
+ job["status"] = "error"
+ job["error"] = str(exc)
+ finally:
++ if job["status"] != "paused":
++ _RUNNING.pop(job["job_id"], None)
+ _QUICKSTART_LOCK.release()
+
++ _RUNNING[job["job_id"]] = {"resume": _run, "dl": None}
+ threading.Thread(target=_run, daemon=True, name="lr-quickstart").start()
+ return {
+ "job_id": job["job_id"],
+ "model_id": entry.id,
+ "display_name": entry.display_name,
+ "needs_runtime": need_runtime,
+ "needs_download": need_download,
+ "download_bytes": sum(p[2] for p in download_plan),
+ }
+
+
+ @router.post("/api/local-models/server")
+ async def local_models_server(body: ServerActionBody):
+ """Turn the local engine off (stop the server, free ALL GPU memory,
+ and disable auto-start) or back on. The off switch is the whole-engine
+ counterpart of per-model eject — and unlike eject it IS durable: the
+ user said off, so boots stay off until they say on."""
+ import asyncio
+
+ from hermes_cli.config import load_config, save_config
+
+ action = (body.action or "").strip().lower()
+ if action not in ("stop", "start"):
+ raise HTTPException(status_code=400, detail="action must be 'stop' or 'start'")
+
+ def _stop():
+ from hermes_cli.local_runtime.bootstrap import (
+ get_supervisor,
+ shutdown_local_runtime,
+ )
+
+ sup = get_supervisor()
+ if sup is not None:
+ shutdown_local_runtime()
+ else:
+ # Server owned by another process (or an orphan): best-effort
+ # terminate via the state file's pid, then clear the state.
+ endpoint = _state_endpoint()
+ if endpoint is not None:
+ try:
+ import psutil # type: ignore
+
+ from hermes_cli.local_runtime.supervisor import state_path
+
- state = json.loads(state_path().read_text(encoding="utf-8"))
++ state = json.loads(state_path().read_text(encoding="utf-8-sig"))
+ pid = int(state.get("pid") or 0)
+ if pid > 0 and psutil.pid_exists(pid):
+ psutil.Process(pid).terminate()
+ state_path().unlink(missing_ok=True)
+ except Exception: # noqa: BLE001
+ pass
+ config = load_config()
+ config.setdefault("local_runtime", {})["enabled"] = False
+ save_config(config)
+
+ def _start():
+ from hermes_cli.local_runtime.bootstrap import ensure_local_runtime
+
+ config = load_config()
+ config.setdefault("local_runtime", {})["enabled"] = True
+ save_config(config)
+ sup = ensure_local_runtime(config, force=True)
+ if sup is None and _state_endpoint() is None:
+ raise RuntimeError("The local server could not start — check the "
+ "runtime is installed")
+
+ try:
+ await asyncio.to_thread(_stop if action == "stop" else _start)
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(status_code=502, detail=str(exc)) from exc
+ return {"ok": True, "action": action}
+
+
+ # ── activate: make a downloaded model THE model ──────────────
+
+
+ class ModelEjectBody(BaseModel):
+ model_id: str
+
+
+ @router.post("/api/local-models/eject")
+ async def local_models_eject(body: ModelEjectBody):
+ """Free a loaded model's GPU memory now. Nothing reloads it except
+ demand — the next message to it (residency v2: no automatic loading
+ exists anywhere)."""
+ from hermes_cli.local_runtime.bootstrap import get_supervisor
+
+ sup = get_supervisor()
+ if sup is not None:
+ try:
+ sup.unload_model(body.model_id)
+ return {"ok": True}
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(status_code=502, detail=str(exc)) from exc
+
+ # Server owned by another process (or state-file only): drive the
+ # router directly with the persisted endpoint.
+ endpoint = _state_endpoint()
+ if endpoint is None:
+ raise HTTPException(status_code=409, detail="local server is not running")
+ try:
+ import urllib.request as _url
+
+ req = _url.Request(
+ endpoint["base_url"].rsplit("/v1", 1)[0] + "/models/unload",
+ data=json.dumps({"model": body.model_id}).encode(),
+ headers={"Content-Type": "application/json",
+ "Authorization": f"Bearer {endpoint.get('api_key', '')}"},
+ method="POST")
+ with _url.urlopen(req, timeout=120):
+ pass
+ return {"ok": True}
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(status_code=502, detail=str(exc)) from exc
+
+
+ class ModelActivateBody(BaseModel):
+ model_id: str # exact variant id (a staged .gguf stem)
+
+
+ @router.post("/api/local-models/activate")
+ async def local_models_activate(body: ModelActivateBody):
+ """Make a downloaded model the default for new chats. Pure selection
+ (residency v2): a config write through the same machinery as
+ /api/model/set, plus making sure the server is up. NO model loading —
+ models load on first inference, always; an empty router costs nothing.
+ Fast enough to be synchronous-feeling, but kept as a job for UI
+ continuity."""
+ # Split variants stage under their first part — resolve like the rest
+ # of the routes instead of assuming a single flat file.
+ from hermes_cli.local_runtime.bootstrap import staged_model_ids
+
+ if body.model_id not in staged_model_ids():
+ raise HTTPException(status_code=404, detail=f"{body.model_id} is not downloaded")
+
+ job = _job("model-activate", body.model_id, model_id=body.model_id)
+
+ def _run():
+ try:
+ from hermes_cli.config import load_config, save_config
+ from hermes_cli.local_runtime.bootstrap import (
+ ensure_local_runtime,
+ refresh_local_runtime,
+ )
+
+ job["phase"] = "starting-server"
+ job["detail"] = "Starting the local server"
+ config = load_config()
+ sup = ensure_local_runtime(config, force=True)
+ if sup is None:
+ if _state_endpoint() is None:
+ raise RuntimeError(
+ "The local server could not start — check the runtime is installed")
+
+ # Self-heal a stale router: the model list is spawn-only, so a
+ # server started before this model finished downloading can't
+ # serve it. If the router doesn't know the model, bounce it.
+ if sup is not None:
+ try:
+ if body.model_id not in sup.models():
+ job["detail"] = "Refreshing the local server"
+ refresh_local_runtime()
+ except Exception: # noqa: BLE001
+ logger.debug("activate rescan check skipped", exc_info=True)
+
+ job["phase"] = "setting-default"
+ job["detail"] = "Making it your default"
+ config = load_config()
+ config.setdefault("local_runtime", {})["enabled"] = True
+ save_config(config)
+ from hermes_cli.web_deps import late
+
+ late("_apply_model_assignment_sync")(
+ "main", "llamacpp", body.model_id, "", "", "")
+
+ job["phase"] = "done"
+ job["status"] = "done"
+ job["detail"] = f"{body.model_id} is the default for new chats"
+ except Exception as exc: # noqa: BLE001
+ logger.warning("model activate failed: %s", exc)
+ job["status"] = "error"
+ job["error"] = str(exc)
+
+ threading.Thread(target=_run, daemon=True, name="lr-model-activate").start()
+ return {"job_id": job["job_id"]}
+
+
+ # ── job polling ──────────────────────────────────────────────
+
+
+ @router.get("/api/local-models/jobs")
+ async def local_models_jobs():
+ """All recent jobs, running first — the pane and the app-level poller
+ rediscover in-flight work here after a remount or app restart."""
+ with _JOBS_LOCK:
+ jobs = sorted(_JOBS.values(),
+ key=lambda j: (j["status"] != "running", -j["started_at"]))
+ out = []
+ for job in jobs[:20]:
+ entry = dict(job)
+ if entry["total_bytes"]:
+ entry["percent"] = min(100, round(entry["done_bytes"] / entry["total_bytes"] * 100))
+ out.append(entry)
+ return {"jobs": out}
+
+
+ @router.get("/api/local-models/jobs/{job_id}")
+ async def local_models_job(job_id: str):
+ with _JOBS_LOCK:
+ job = _JOBS.get(job_id)
+ if job is None:
+ raise HTTPException(status_code=404, detail="job not found")
+ out = dict(job)
+ if out["total_bytes"]:
+ out["percent"] = min(100, round(out["done_bytes"] / out["total_bytes"] * 100))
+ return out
+
+
+ # ── Hugging Face browser: search, repo files, arbitrary download ─
+
+
+ @router.get("/api/local-models/search")
+ async def local_models_search(q: str, limit: int = 20):
+ """Full-text HF search over GGUF models — the firehose behind the
+ curated catalog. The pane's per-quant fit pills come from the
+ repo-files call once the user opens a hit."""
+ from starlette.concurrency import run_in_threadpool
+
+ from hermes_cli.local_runtime.hf_browse import search_models
+
+ if not q.strip():
+ return {"hits": []}
+ try:
+ hits = await run_in_threadpool(search_models, q, limit)
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(status_code=502,
+ detail=f"Hugging Face search unavailable: {exc}") from exc
+ return {"hits": [h.__dict__ for h in hits]}
+
+
+ @router.get("/api/local-models/search/files")
+ async def local_models_search_files(repo: str):
+ """The servable GGUFs in one HF repo with a rough pre-download fit
+ verdict per quant (file size + conservative fill-ins — the GGUF
+ header refines it after download)."""
+ from starlette.concurrency import run_in_threadpool
+
+ from hermes_cli.local_runtime.hardware import probe_budget
+ from hermes_cli.local_runtime.hf_browse import priced_repo_files
+
+ try:
+ groups = await run_in_threadpool(
+ priced_repo_files, repo, probe_budget(planning=True))
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(status_code=502,
+ detail=f"Could not list {repo}: {exc}") from exc
+ return {"files": [dict(g.__dict__, paths=list(g.paths)) for g in groups]}
+
+
+ class BrowsedDownloadBody(BaseModel):
+ repo: str
+ paths: list[str] # one GGUF, or every part of a split, in order
+
+
+ @router.post("/api/local-models/download-browsed")
+ async def local_models_download_browsed(body: BrowsedDownloadBody):
+ """Download an arbitrary HF GGUF (browsed or pasted) into the managed
+ models dir. From the moment it lands it is a normal staged model: the
+ post-download bounce regenerates presets from its real header and the
+ fit policy owns its launch. No catalog entry — it serves 'unverified',
+ capabilities answered from the live server only."""
+ import re as _re
+
+ from hermes_cli.local_runtime.bootstrap import staged_model_ids
+
+ paths = [p for p in (body.paths or []) if p.lower().endswith(".gguf")]
+ if not paths:
+ raise HTTPException(status_code=422, detail="no .gguf files given")
+ first = paths[0].rsplit("/", 1)[-1]
+ model_id = _re.sub(r"-\d{5}-of-\d{5}\.gguf$", "", first, flags=_re.IGNORECASE)
+ model_id = model_id[:-5] if model_id.lower().endswith(".gguf") else model_id
+ if model_id in staged_model_ids():
+ return {"job_id": None, "already_downloaded": True, "model_id": model_id}
+
+ job = _job("model-download", f"{model_id} (from {body.repo})",
+ model_id=model_id)
+
+ def _run():
+ try:
+ job["phase"] = "downloading"
++ plan = []
+ for p in paths:
+ url = (f"https://huggingface.co/{body.repo}"
+ f"/resolve/main/{urllib.parse.quote(p)}")
+ dest = _models_dir() / p.rsplit("/", 1)[-1]
- if dest.exists():
- continue
- download_file(url, dest, job,
- base_done=int(job.get("done_bytes") or 0),
- keep_totals=bool(job.get("total_bytes")))
- job["phase"] = "downloading"
++ plan.append((url, dest, 0))
++ _download_job(job, plan)
+ job["phase"] = "done"
+ job["status"] = "done"
+ job["detail"] = f"{model_id} ready"
+ try:
+ from hermes_cli.local_runtime.bootstrap import refresh_local_runtime
+
+ refresh_local_runtime()
+ except Exception: # noqa: BLE001
+ logger.debug("post-download runtime refresh skipped", exc_info=True)
++ except DownloadPaused:
++ pass # status already "paused"; partials kept for resume
+ except Exception as exc: # noqa: BLE001
+ job["status"] = "error"
+ job["error"] = str(exc)
++ finally:
++ if job["status"] != "paused":
++ _RUNNING.pop(job["job_id"], None)
+
++ _RUNNING[job["job_id"]] = {"resume": _run, "dl": None}
+ threading.Thread(target=_run, daemon=True, name="lm-download-browsed").start()
+ return {"job_id": job["job_id"], "model_id": model_id}
+
+
+ class SideloadBody(BaseModel):
+ path: str # absolute path to a .gguf on this machine
+
+
+ @router.post("/api/local-models/sideload")
+ async def local_models_sideload(body: SideloadBody):
+ """Register a GGUF that already exists on this machine: link it into
+ the managed models dir (copy only when linking is impossible) and
+ bounce the router so it serves immediately. The original stays where
+ it is; delete-from-Hermes removes only our link."""
+ import os
+ import shutil
+
+ from starlette.concurrency import run_in_threadpool
+
+ src = Path(body.path)
+ if not src.is_file() or src.suffix.lower() != ".gguf":
+ raise HTTPException(status_code=422, detail="Pick a .gguf model file")
+ dest = _models_dir() / src.name
+ if dest.exists():
+ return {"ok": True, "model_id": dest.stem, "already_present": True}
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ os.link(src, dest) # hardlink: instant, no extra disk
+ except OSError:
+ try:
+ os.symlink(src, dest) # cross-volume fallback
+ except OSError:
+ await run_in_threadpool(shutil.copyfile, src, dest)
+ try:
+ from hermes_cli.local_runtime.bootstrap import refresh_local_runtime
+
+ refresh_local_runtime()
+ except Exception: # noqa: BLE001
+ logger.debug("post-sideload runtime refresh skipped", exc_info=True)
+ return {"ok": True, "model_id": dest.stem}
diff --cc plugins/model-providers/router/__init__.py
index 00000000000,6e5b21dc2de..e1f1fa83489
mode 000000,100644..100644
--- a/plugins/model-providers/router/__init__.py
+++ b/plugins/model-providers/router/__init__.py
@@@ -1,0 -1,395 +1,395 @@@
+ """Ramp Router (router.com) provider plugin for Hermes Agent.
+
+ Provider profile for `Ramp Router <https://docs.router.com>`_, Ramp's LLM
+ gateway: one OpenAI Responses-compatible endpoint at
+ ``https://api.router.com/v1`` that routes each request across upstream
+ providers (OpenAI, Anthropic, xAI, Fireworks, ...) and handles fallbacks and
+ spend controls server-side.
+
+ Wire notes (verified live against api.router.com, Aug 2026):
+
+ * **Responses API is the native wire.** Router serves ``GET /v1/models``
+ and ``POST /v1/responses``; ``POST /v1/chat/completions`` is only a
+ minimal compatibility shim (added Aug 2026) that translates onto
+ Responses. Per-model reasoning-effort validation, reasoning summaries,
+ and prompt caching are Responses-surface features, so
+ ``api_mode="codex_responses"`` plus the ``api.router.com`` host mandate
+ in ``hermes_cli/providers.py`` keep every path on the native wire —
+ the same shape as the ``api.openai.com`` mandate.
+ * **Account-scoped catalog.** Valid model IDs are whatever the key's
+ ``GET /v1/models`` returns (BYOK accounts see extra entries), so this
+ profile ships **no** ``fallback_models`` — the picker relies on the live
+ fetch, per Router's own guidance to never hardcode model names.
+ * **Strict reasoning-effort validation.** Router validates
+ ``reasoning.effort`` against each model's catalog-declared vocabulary and
+ returns HTTP 400 ``invalid-argument`` on a level the model does not accept
+ (e.g. ``max`` on grok-4.6), and 400 ``unsupported_parameter`` when a
+ non-reasoning model (gpt-4.1 family, gpt-4o, ...) receives any reasoning
+ field. The catalog publishes the vocabulary per model
+ (``router.capabilities.reasoning``), so ``supported_reasoning_efforts``
+ below feeds the codex transport's clamp from a cached copy of it.
+ * **Everything else passes through.** ``store: false``, ``prompt_cache_key``,
+ ``include: ["reasoning.encrypted_content"]``, and ``reasoning.summary`` are
+ accepted on all models (ignored where a backend cannot honor them), tools /
+ ``parallel_tool_calls`` / streaming SSE work across backends, and encrypted
+ reasoning replay round-trips on OpenAI-served models — so the generic
+ Responses transport path needs no Router-specific request surgery.
+
+ The capability cache mirrors the OpenRouter reasoning-caps design in
+ ``hermes_cli/models.py``: cache-only lookups on the per-request hot path
+ (never HTTP), seeded for free whenever ``fetch_models()`` runs (picker,
+ setup, doctor), hydrated from a disk mirror across processes, and refreshed
+ by a background warmer when cold or stale.
+ """
+
+ from __future__ import annotations
+
+ import json
+ import logging
+ import os
+ import threading
+ import time
+ from pathlib import Path
+ from typing import Any, Optional
+
+ from hermes_cli import __version__ as _HERMES_VERSION
+ from providers import register_provider
+ from providers.base import ProviderProfile, _profile_user_agent
+
+ logger = logging.getLogger(__name__)
+
+ ROUTER_DEFAULT_BASE_URL = "https://api.router.com/v1"
+
+ #: Efforts-by-model cache: ``model id -> list of accepted effort levels``.
+ #: ``[]`` means the catalog says the model accepts NO reasoning parameters
+ #: (``reasoning.supported: false``) — the transport must omit reasoning
+ #: entirely. A model absent from the dict is unknown (custom/BYOK route or
+ #: vocabulary not published) and callers fall back to their defaults.
+ _efforts_cache: Optional[dict[str, list[str]]] = None
+ _efforts_lock = threading.Lock()
+ _warm_started = False
+ _disk_checked = False
+
+ #: Disk-mirror staleness bound. Vocabularies change rarely; a stale verdict
+ #: beats no verdict, so a past-TTL mirror is still served while a background
+ #: refresh runs (same policy as the OpenRouter caps mirror).
+ _DISK_TTL_SECONDS = 24 * 60 * 60
+
+
+ def _base_url() -> str:
+ """Allow a base-URL override via ``RAMP_ROUTER_BASE_URL``."""
+ return os.getenv("RAMP_ROUTER_BASE_URL", "").strip().rstrip("/") or ROUTER_DEFAULT_BASE_URL
+
+
+ def _resolve_api_key() -> str:
+ """Resolve the Router key from .env / environment, preferring dotenv.
+
+ ``RAMP_ROUTER_API_KEY`` is Router's documented variable;
+ ``ROUTER_API_KEY`` is accepted as a convenience alias. Falls back to the
+ raw environment when the hermes_cli helper is unavailable (e.g. stripped
+ test environments).
+ """
+ resolvers = []
+ try:
+ from hermes_cli.config import get_env_value_prefer_dotenv
+
+ resolvers.append(get_env_value_prefer_dotenv)
+ except Exception:
+ pass
+ resolvers.append(lambda var: os.environ.get(var, ""))
+ for resolve in resolvers:
+ for var in ("RAMP_ROUTER_API_KEY", "ROUTER_API_KEY"):
+ try:
+ value = str(resolve(var) or "").strip()
+ except Exception:
+ value = ""
+ if value:
+ return value
+ return ""
+
+
+ def _parse_efforts(items: Any) -> Optional[dict[str, list[str]]]:
+ """Parse a Router ``/v1/models`` ``data`` array into the efforts map.
+
+ Returns None when the array has no usable entries, which callers treat
+ as a failed fetch rather than caching an empty verdict.
+ """
+ if not isinstance(items, list):
+ return None
+ try:
+ from agent.reasoning_effort import EFFORT_LADDER
+
+ known_levels = set(EFFORT_LADDER)
+ except Exception:
+ known_levels = None
+ efforts_by_id: dict[str, list[str]] = {}
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ mid = str(item.get("id") or "").strip()
+ if not mid:
+ continue
+ router_meta = item.get("router")
+ reasoning = None
+ if isinstance(router_meta, dict):
+ capabilities = router_meta.get("capabilities")
+ if isinstance(capabilities, dict):
+ reasoning = capabilities.get("reasoning")
+ if not isinstance(reasoning, dict):
+ continue
+ if reasoning.get("supported") is False:
+ # Definitive negative: any reasoning field 400s on this model.
+ efforts_by_id[mid] = []
+ continue
+ levels = [
+ str(entry.get("value") or "").strip()
+ for entry in reasoning.get("efforts") or []
+ if isinstance(entry, dict) and str(entry.get("value") or "").strip()
+ ]
+ if known_levels is not None:
+ # clamp_effort silently ignores ladder-unknown levels, and an
+ # all-unknown vocabulary would pass the requested effort through
+ # unclamped straight to a Router 400 — so a new vendor tier is
+ # dropped at ingest and fails loudly here instead.
+ unknown = [level for level in levels if level not in known_levels]
+ if unknown:
+ logger.info(
+ "router: model %s publishes unrecognized reasoning effort "
+ "level(s) %s; ignoring them (update agent/reasoning_effort "
+ "EFFORT_LADDER to adopt new vendor tiers)",
+ mid,
+ unknown,
+ )
+ levels = [level for level in levels if level in known_levels]
+ if levels:
+ efforts_by_id[mid] = levels
+ # supported=True with no (recognized) vocabulary -> leave the model
+ # out (unknown), so the transport keeps its default clamp behavior.
+ return efforts_by_id or None
+
+
+ def _disk_path() -> Optional[Path]:
+ try:
+ from hermes_constants import get_hermes_home
+
+ return get_hermes_home() / "cache" / "router_catalog.json"
+ except Exception:
+ return None
+
+
+ def _save_disk(efforts_by_id: dict[str, list[str]]) -> None:
+ path = _disk_path()
+ if path is None:
+ return
+ try:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_suffix(".tmp")
+ tmp.write_text(
+ json.dumps({"ts": time.time(), "efforts": efforts_by_id}),
+ encoding="utf-8",
+ )
+ tmp.replace(path)
+ except Exception as exc:
+ logger.debug("router: caps disk mirror write failed: %s", exc)
+
+
+ def _load_disk() -> tuple[Optional[dict[str, list[str]]], float]:
+ path = _disk_path()
+ if path is None:
+ return None, 0.0
+ try:
- data = json.loads(path.read_text(encoding="utf-8"))
++ data = json.loads(path.read_text(encoding="utf-8-sig"))
+ efforts = data.get("efforts")
+ if not isinstance(efforts, dict) or not efforts:
+ return None, 0.0
+ parsed = {
+ str(mid): [str(level) for level in levels]
+ for mid, levels in efforts.items()
+ if isinstance(levels, list)
+ }
+ try:
+ age = max(0.0, time.time() - float(data.get("ts") or 0))
+ except (TypeError, ValueError):
+ age = float(_DISK_TTL_SECONDS)
+ return (parsed or None), age
+ except Exception:
+ return None, 0.0
+
+
+ def _seed_efforts(items: Any) -> Optional[dict[str, list[str]]]:
+ """Seed memory + disk caches from a ``/v1/models`` payload."""
+ global _efforts_cache
+ parsed = _parse_efforts(items)
+ if parsed is None:
+ return None
+ with _efforts_lock:
+ _efforts_cache = parsed
+ _save_disk(parsed)
+ return parsed
+
+
+ def _fetch_catalog_items(
+ *, api_key: str = "", base_url: str = "", timeout: float = 8.0
+ ) -> Optional[list]:
+ """Fetch the raw ``/v1/models`` ``data`` array. None on any failure."""
+ url = (base_url or _base_url()).rstrip("/") + "/models"
+ import urllib.request
+
+ from hermes_cli.urllib_security import open_credentialed_url
+
+ req = urllib.request.Request(url)
+ key = api_key or _resolve_api_key()
+ if key:
+ req.add_header("Authorization", f"Bearer {key}")
+ req.add_header("Accept", "application/json")
+ # Router sits behind a WAF that rejects the default Python-urllib UA.
+ req.add_header("User-Agent", _profile_user_agent())
+ try:
+ with open_credentialed_url(req, timeout=timeout) as resp:
+ data = json.loads(resp.read().decode())
+ except Exception as exc:
+ logger.debug("router: catalog fetch failed: %s", exc)
+ return None
+ items = data if isinstance(data, list) else data.get("data", [])
+ return items if isinstance(items, list) else None
+
+
+ def _efforts_cache_only() -> Optional[dict[str, list[str]]]:
+ """Memory, else the disk mirror. Never HTTP (hot-path safe)."""
+ global _efforts_cache, _disk_checked
+ with _efforts_lock:
+ cached = _efforts_cache
+ if cached is not None:
+ return cached
+ if _disk_checked:
+ return None
+ _disk_checked = True
+ parsed, age = _load_disk()
+ if parsed is None:
+ return None
+ with _efforts_lock:
+ if _efforts_cache is None:
+ _efforts_cache = parsed
+ cached = _efforts_cache
+ if age >= _DISK_TTL_SECONDS:
+ _warm_efforts_async()
+ return cached
+
+
+ def _warm_efforts_async() -> None:
+ """Refresh the efforts cache in the background, at most once per process."""
+ global _warm_started
+ if os.environ.get("PYTEST_CURRENT_TEST"):
+ # Match the canonical caps warmer (hermes_cli/models.py): a mid-suite
+ # background fetch would make cache state timing-dependent in tests.
+ return
+ with _efforts_lock:
+ if _warm_started:
+ return
+ _warm_started = True
+ if not _resolve_api_key():
+ # Without a key the fetch would 401; the first authenticated
+ # fetch_models() (picker/setup/doctor) seeds the cache instead.
+ return
+
+ def _refresh() -> None:
+ items = _fetch_catalog_items()
+ if items is not None:
+ _seed_efforts(items)
+
+ try:
+ threading.Thread(
+ target=_refresh, name="router-caps-warm", daemon=True
+ ).start()
+ except Exception as exc:
+ logger.debug("router: caps warmer failed to start: %s", exc)
+
+
+ class RouterProfile(ProviderProfile):
+ """Ramp Router — Responses-only gateway with catalog-declared efforts."""
+
+ def fetch_models(
+ self,
+ *,
+ api_key: Optional[str] = None,
+ base_url: Optional[str] = None,
+ timeout: float = 8.0,
+ ) -> Optional[list[str]]:
+ """Fetch the live, key-scoped catalog and seed the caps cache.
+
+ One request serves both consumers: the picker gets the model IDs and
+ the reasoning-vocabulary mirror is left warm at no extra network
+ cost (the same document carries both).
+ """
+ items = _fetch_catalog_items(
+ api_key=api_key or "", base_url=base_url or "", timeout=timeout
+ )
+ if items is None:
+ return None
+ _seed_efforts(items)
+ # Deduped but not sorted: Router's listing order is deliberate
+ # presentation (featured/current models first), so the picker keeps it.
+ ids = list(
+ dict.fromkeys(
+ str(item["id"])
+ for item in items
+ if isinstance(item, dict) and item.get("id")
+ )
+ )
+ return ids or None
+
+ def supported_reasoning_efforts(
+ self, model: Optional[str]
+ ) -> Optional[tuple[str, ...]]:
+ """Catalog-declared effort vocabulary for *model* (cache-only).
+
+ Router 400s on efforts outside a model's published set and on any
+ reasoning field for non-reasoning models, so the codex transport
+ clamps (or suppresses) from this verdict. Cold cache returns None —
+ the transport keeps its defaults — and kicks a background warmer so
+ the next turn is covered.
+ """
+ mid = str(model or "").strip()
+ if not mid:
+ return None
+ efforts_by_id = _efforts_cache_only()
+ if efforts_by_id is None:
+ _warm_efforts_async()
+ return None
+ levels = efforts_by_id.get(mid)
+ if levels is None:
+ return None
+ return tuple(levels)
+
+
+ router = RouterProfile(
+ name="router",
+ aliases=("ramp-router", "ramp", "router.com"),
+ api_mode="codex_responses",
+ display_name="Ramp Router",
+ description="Ramp Router (router.com) — routes each request to the cheapest model that clears your quality bar",
+ signup_url="https://app.router.com/keys",
+ # RAMP_ROUTER_API_KEY is Router's documented variable; ROUTER_API_KEY is
+ # a convenience alias. RAMP_ROUTER_BASE_URL overrides the endpoint
+ # (auth.py picks it up as the registry's base_url_env_var).
+ env_vars=("RAMP_ROUTER_API_KEY", "ROUTER_API_KEY", "RAMP_ROUTER_BASE_URL"),
+ base_url=_base_url(),
+ auth_type="api_key",
+ # Identify Hermes traffic to the gateway (Router attributes coding-agent
+ # clients by User-Agent prefix, the way it already recognizes OpenCode's
+ # versioned UA) — and Router's WAF rejects blank/default client UAs.
+ default_headers={"User-Agent": f"Hermes-Agent/{_HERMES_VERSION}"},
+ # Most of the catalog's frontier routes accept image input; capability is
+ # still model-dependent and governed by the live catalog.
+ supports_vision=True,
+ # Cheap, reasoning-capable, and vision-capable — safe for auxiliary tasks
+ # (compaction, titles, vision) when Router is the main provider. Also the
+ # model Router's own docs use as their example.
+ default_aux_model="gpt-5.4-mini",
+ # Deliberately empty: model IDs are account-scoped (BYOK accounts see
+ # extra entries) and Router's docs say to read the catalog at runtime
+ # rather than hardcode names. The picker uses fetch_models() above.
+ fallback_models=(),
+ )
+
+ register_provider(router)
diff --cc pm/cli.py
index ae1898630b1,00000000000..5a1ea4e2c6f
mode 100644,000000..100644
--- a/pm/cli.py
+++ b/pm/cli.py
@@@ -1,558 -1,0 +1,563 @@@
+"""hermes pm: lock / install / env / doctor / gc / bundle."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import shutil
+import subprocess
+import sys
+import threading
+from pathlib import Path
+from typing import Optional
+
+from pm.ensure import _facts, _lockfile, _store, ensure
+from pm.ensure import uv as pm_uv
+from pm.package import InstallError
+from pm.registry import get_package
+from pm.store import ALL_TARGETS, current_target, hash_url
+
+
+def cmd_lock(args) -> int:
+ """--bump <name> <version>: resolve every target's archives, hash them,
+ write. A target with one archive pins the object; several pin a list.
+ Target-independent urls collapse to one "any" artifact."""
+ lockfile = _lockfile()
+ package = get_package(args.name)
+ artifacts: dict[str, object] = {}
+
+ def pin(url: str) -> dict:
+ print(f" {url}")
+ digest = package.known_sha256(args.version, url) or hash_url(url)
+ print(f" sha256 {digest}")
+ return {"url": url, "sha256": digest}
+
+ urls = {
+ target: package.fetch_urls(args.version, target)
+ for target in ALL_TARGETS
+ if package.missing_reason(target) is None
+ }
+ distinct = {tuple(u) for u in urls.values()}
+ if len(distinct) == 1:
+ print(" any:")
+ pinned = [pin(url) for url in next(iter(urls.values()))]
+ artifacts["any"] = pinned[0] if len(pinned) == 1 else pinned
+ else:
+ for target, target_urls in urls.items():
+ print(f" {target}:")
+ pinned = [pin(url) for url in target_urls]
+ artifacts[target] = pinned[0] if len(pinned) == 1 else pinned
+ lockfile.set_pin(args.name, args.version, artifacts)
+ lockfile.save()
+ print(f"pinned {args.name} {args.version} ({len(artifacts)} targets)")
+ return 0
+
+
+def _fmt_bytes(n: int) -> str:
+ return f"{n / (1024 * 1024):.1f} MiB"
+
+
+def _live_progress(name: str):
+ """Per-package progress for ensure(): download as % + MiB, unpack as a
+ phase line. Throttled to ~4 MiB steps — a slow line proves it's moving
+ in a piped (CI) log without flooding it (a 1 MiB tick on a 1.5 GiB
+ model would be ~1,500 lines)."""
+ last = 0
+
+ def report(stage: str, done: int, total: int, label: str) -> None:
+ nonlocal last
+ if stage == "unpack":
+ last = 0
+ print(f" {name}: unpacking{(' ' + label) if label else ''}", flush=True)
+ return
+ if total <= 0:
+ return
+ if done >= total or done - last >= 4 * 1024 * 1024:
+ last = done
+ print(
+ f" {name}: {done / total * 100:5.1f}% {_fmt_bytes(done)} / {_fmt_bytes(total)}",
+ flush=True,
+ )
+
+ return report
+
+
+def _install_names(names: list[str]) -> int:
+ failed = 0
+ for name in names:
+ try:
+ ensure(name, explicit=True, progress=_live_progress(name))
+ print(f"✓ {name}", flush=True)
+ except InstallError as e:
+ print(f"✗ {e}", flush=True)
+ failed += 1
+ return failed
+
+
+
+def _bundle_package_names() -> list[str]:
+ names = [
+ n
+ for n in _lockfile().names()
+ if not get_package(n).internal or n == "uv"
+ ]
+ if "python" not in names:
+ names.append("python")
+ return names
+
+
+def _drop_unloadable_runtime_files(store_dir: Path) -> None:
+ """Drop the x64 VC runtime that python-build-standalone ships beside ARM64 Python."""
+ if current_target() != "win32-arm64":
+ return
+ facts = _facts()
+ facts.reload()
+ python = facts.get("python")
+ if python and "entry" in python:
+ (store_dir / python["entry"] / "vcruntime140_1.dll").unlink(missing_ok=True)
+
+
+def cmd_install(args) -> int:
+ names = args.names or [
+ n for n in _lockfile().names() if not get_package(n).optional
+ ]
+ failed = _install_names(names)
+ if not args.names:
+ from pm.ensure import sync_venv
+
+ try:
- sync_venv(explicit=True)
++ # Default the venv to the [all] feature set — the same thing
++ # `hermes update` force-syncs on every run (update_cmd.py) and
++ # the installers' old `--extra all` did. sync_venv unions, so
++ # any lazy extras already recorded survive this; it only makes
++ # a fresh bootstrap match what the first update would do.
++ sync_venv(["all"], explicit=True)
+ print("✓ venv")
+ except InstallError as e:
+ print(f"✗ {e}")
+ failed += 1
+ return 1 if failed else 0
+
+
+def cmd_env(args) -> int:
+ from pm.ensure import env_for
+
+ names = args.names or _lockfile().names()
+ print(json.dumps(env_for(*names), indent=2, sort_keys=True))
+ return 0
+
+
+def cmd_doctor(args) -> int:
+ from pm.ensure import _identity
+ from pm.store import tree_digest
+
+ lockfile = _lockfile()
+ facts = _facts()
+ store = _store()
+ target = current_target()
+ bad = 0
+ for name in lockfile.names():
+ package = get_package(name)
+ reason = package.missing_reason(target)
+ if reason is not None:
+ print(f"- {name}: n/a on {target} ({reason})")
+ continue
+ fact = facts.get(name)
+ soft = package.optional or package.internal
+ identity = _identity(lockfile, name, target)
+ if (
+ fact is not None
+ and identity is not None
+ and ("target" not in fact or "artifacts" not in fact)
+ ):
+ # Legacy fact: pre-dates digest-bound identity; installed()
+ # treats it as not installed and forces one reinstall.
+ print(f"{'?' if soft else '✗'} {name}: legacy fact: no recorded identity, run `hermes pm install`")
+ bad += 0 if soft else 1
+ continue
+ if not facts.installed(name, lockfile.version(name), store.root, identity):
+ state = "not installed" if fact is None else "outdated"
+ print(f"{'?' if soft else '✗'} {name}: {state}")
+ bad += 0 if soft else 1
+ continue
+ entry = store.entry(fact["entry"])
+ reason = package.verify(entry, target)
+ if reason:
+ print(f"✗ {name}: installed but failed verification: {reason}")
+ bad += 1
+ continue
+ recorded = fact.get("digest")
+ if recorded is not None and tree_digest(entry) != recorded:
+ # Doctor is the expensive-path tool: re-hash the realized
+ # bytes. Boot checks stay O(1) json compares.
+ print(f"✗ {name}: realized bytes do not match recorded digest")
+ bad += 1
+ continue
+ print(f"✓ {name} {fact['version']}")
+ return 1 if bad else 0
+
+
+def _venv_site_packages(venv_dir: Path, win: bool) -> Optional[Path]:
+ """The site-packages dir uv sync fills inside the venv (the venv stays
+ a dependency target; it is never where `python` resolves)."""
+ if win:
+ candidate = venv_dir / "Lib" / "site-packages"
+ return candidate if candidate.is_dir() else None
+ for candidate in sorted(venv_dir.glob("lib/python3.*/site-packages")):
+ if candidate.is_dir():
+ return candidate
+ return None
+
+
+def _develop_env(names: list[str]) -> Optional[dict]:
+ """The `pm develop` subshell environment. `python` resolves to the pm
+ STORE python (its bin dir first on PATH); imports come from
+ PYTHONPATH=<repo>;<venv>/site-packages (repo first — the venv stays a
+ dependency target only). VIRTUAL_ENV and the venv bin dir are
+ deliberately absent: nothing in the devshell boots through the venv
+ (pm work item 3; pyvenv.cfg is inert dead config). Returns None when
+ the store interpreter has not been materialized (`hermes pm install`)."""
+ import os
+
+ from pm import paths
+ from pm.ensure import env_for
+
+ facts = _facts()
+ python_fact = facts.get("python")
+ target = current_target()
+ if not python_fact or "entry" not in python_fact:
+ return None
+ python_bin = get_package("python").binary(
+ _store().entry(python_fact["entry"]), target
+ )
+ if python_bin is None or not python_bin.is_file():
+ return None
+
+ env = env_for(*names, base_env=dict(os.environ))
+ repo = paths.repo_root()
+ venv_dir = repo / (".venv" if (repo / ".venv").is_dir() else "venv")
+ win = target.startswith("win32")
+ venv_bin = venv_dir / ("Scripts" if win else "bin")
+ env.pop("VIRTUAL_ENV", None)
+ env.pop("PYTHONHOME", None)
+ # The venv bin dir must never be where `python` resolves.
+ path_entries = [
+ p for p in env.get("PATH", "").split(os.pathsep) if p and Path(p) != venv_bin
+ ]
+ env["PATH"] = os.pathsep.join([str(python_bin.parent), *path_entries])
+ site = _venv_site_packages(venv_dir, win)
+ ours = str(repo) + (os.pathsep + str(site) if site else "")
+ existing = env.get("PYTHONPATH", "")
+ env["PYTHONPATH"] = ours + (os.pathsep + existing if existing else "")
+ return env
+
+
+def cmd_develop(args) -> int:
+ """Install everything, sync the venv, then activate: spawn a subshell
+ with every tool's env composed in and the pm STORE python resolving
+ `python` (PYTHONPATH=repo;venv-site-packages for imports — never the
+ venv interpreter). The devshell equivalent of nix develop. --print
+ emits eval-able exports for the current shell."""
+ import os
+ import subprocess
+
+ from pm.ensure import sync_venv
+
+ install_names = [
+ n for n in _lockfile().names()
+ if not get_package(n).optional
+ and get_package(n).missing_reason(current_target()) is None
+ ]
+ # The devshell boots the STORE python — make sure it is materialized.
+ if (
+ "python" not in install_names
+ and get_package("python").missing_reason(current_target()) is None
+ ):
+ install_names.append("python")
+ failed = _install_names(install_names)
+ try:
+ sync_venv(explicit=True)
+ print("✓ venv")
+ except InstallError as e:
+ print(f"✗ {e}")
+ failed += 1
+ if failed:
+ return 1
+
+ env = _develop_env(_lockfile().names())
+ if env is None:
+ print("✗ develop: no pm store interpreter — run 'hermes pm install' first")
+ return 1
+
+ from pm import paths
+
+ win = current_target().startswith("win32")
+ if args.print_env:
+ changed = {k: v for k, v in env.items() if os.environ.get(k) != v}
+ for key, value in sorted(changed.items()):
+ if win and os.environ.get("SHELL") is None:
+ print(f'$env:{key} = "{value}"')
+ else:
+ escaped = value.replace("'", "'\\''")
+ print(f"export {key}='{escaped}'")
+ return 0
+
+ shell = os.environ.get("SHELL") or os.environ.get("COMSPEC") or (
+ "cmd.exe" if win else "/bin/sh"
+ )
+ print(f"pm develop: entering {shell} (exit to leave)")
+ return subprocess.call([shell], env=env, cwd=paths.repo_root())
+
+
+def cmd_gc(args) -> int:
+ from pm.downloader import gc_protected_names
+
+ facts = _facts()
+ store = _store()
+ if not store.root.is_dir():
+ return 0
+ removed = 0
+ with store.install_lock():
+ facts.reload()
+ keep = facts.entries_in_use()
+ # Partials an in-flight (or recently interrupted) download still
+ # owns must survive the sweep.
+ protected_partials = gc_protected_names(store.root / "partials")
+ for item in sorted(store.root.iterdir()):
+ if not item.is_dir() or item.name.startswith("."):
+ continue
+ if item.name == "partials" and protected_partials:
+ for child in sorted(item.iterdir()):
+ if child.name in protected_partials:
+ continue
+ print(f"removing {item.name}/{child.name}")
+ if child.is_dir():
+ shutil.rmtree(child, ignore_errors=True)
+ else:
+ try:
+ child.unlink()
+ except OSError:
+ pass
+ continue
+ if item.name in keep:
+ continue
+ print(f"removing {item.name}")
+ shutil.rmtree(item, ignore_errors=True)
+ removed += 1
+ print(f"gc: removed {removed}, kept {len(keep)}")
+ return 0
+
+
+def _run_live(cmd: list[str], *, cwd, env, timeout: int = 3600) -> tuple[int, str]:
+ """Run cmd with its output streamed through our stdout — a long uv
+ venv build must prove liveness in a piped (CI) log, not vanish until
+ exit — while still capturing the tail for the failure message. A
+ reader thread drains output so proc.wait(timeout) keeps the wall-clock
+ kill the old subprocess.run(timeout=) had. Returns (returncode, last
+ ~2k chars of combined output)."""
+ proc = subprocess.Popen(
+ cmd, cwd=cwd, env=env, stdout=subprocess.PIPE,
+ stderr=subprocess.STDOUT, text=True, bufsize=1, errors="replace",
+ )
+ tail = ""
+ lock = threading.Lock()
+
+ def drain() -> None:
+ nonlocal tail
+ for line in proc.stdout:
+ print(line, end="", flush=True)
+ with lock:
+ tail = (tail + line)[-2000:]
+
+ thread = threading.Thread(target=drain, daemon=True)
+ thread.start()
+ try:
+ code = proc.wait(timeout=timeout)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.wait()
+ raise RuntimeError(f"{cmd[0]} timed out after {timeout}s")
+ thread.join()
+ with lock:
+ return code, tail
+
+
+def cmd_bundle(args) -> int:
+ """Stage a complete payload for THIS machine's target into --out:
+ repo snapshot + store + facts (via the normal install path, redirected)
+ + a relocatable venv built on the staged interpreter and synced from
+ uv.lock. Built natively per (os, arch); there is no cross-target
+ staging."""
+ import os
+
+ from pm import paths
+
+ out = Path(args.out).resolve()
+ store_dir = out / "tools"
+ store_dir.mkdir(parents=True, exist_ok=True)
+ # A manifest from a previous run would make this payload look sealed
+ # and refuse its own staging; it is rewritten at the end.
+ (out / "manifest.json").unlink(missing_ok=True)
+
+ repo_dir = out / "hermes-agent"
+ ref = args.ref or "HEAD"
+ if repo_dir.exists():
+ shutil.rmtree(repo_dir)
+ repo_dir.mkdir(parents=True)
+ print(f"staging repo snapshot ({ref})…", flush=True)
+ archive = subprocess.run(
+ ["git", "archive", "--format=tar", ref],
+ cwd=paths.repo_root(), capture_output=True, timeout=600,
+ )
+ if archive.returncode != 0:
+ print(f"✗ repo: git archive {ref} failed: {archive.stderr.decode()[-500:]}")
+ return 1
+ import io
+ import tarfile
+
+ with tarfile.open(fileobj=io.BytesIO(archive.stdout)) as tar:
+ tar.extractall(repo_dir, filter="data")
+ print(f"✓ repo ({ref})")
+
+ os.environ["HERMES_RUNTIME_DIR"] = str(store_dir)
+ paths._stamp.cache_clear()
+
+ failed = 0
+ names = _bundle_package_names()
+ failed += _install_names(
+ [n for n in names if get_package(n).missing_reason(current_target()) is None]
+ )
+ _drop_unloadable_runtime_files(store_dir)
+
+ uv_bin, env = pm_uv()
+ if uv_bin is None:
+ print("✗ venv: uv did not stage")
+ return 1
+
+ python_fact = _facts().get("python")
+ if python_fact is None:
+ print("✗ venv: no staged interpreter to build on")
+ return 1
+ python_bin = get_package("python").binary(
+ _store().entry(python_fact["entry"]), current_target()
+ )
+
+ # Build + sync INSIDE the staged repo: the editable project install
+ # must point at the payload's own tree, not this checkout.
+ venv_dir = out / "venv"
+ if venv_dir.exists():
+ shutil.rmtree(venv_dir)
+ env["VIRTUAL_ENV"] = str(venv_dir)
+ env.pop("UV_NO_CONFIG", None)
+ if current_target().startswith("darwin"):
+ # python-build-standalone bakes phantom toolchain paths (its build
+ # dir's llvm-ar) into sysconfig; sdist builds then fail with
+ # "No such file or directory: .../tools/llvm/bin/llvm-ar". Point
+ # sdist builds at the machine's real toolchain.
+ env.setdefault("AR", "/usr/bin/ar")
+ env.setdefault("CC", "clang")
+ for cmd in (
+ [uv_bin, "venv", "--relocatable", "--python", str(python_bin), str(venv_dir)],
+ [uv_bin, "sync", "--frozen", "--all-extras", "--active"],
+ ):
+ print(f" venv: $ {' '.join(cmd)}", flush=True)
+ code, tail = _run_live(cmd, cwd=repo_dir, env=env)
+ if code != 0:
+ print(f"✗ venv: {' '.join(cmd[1:3])} failed:\n{tail}")
+ return 1
+ print("✓ venv (relocatable, all extras, on the staged interpreter)")
+
+ bad = _arch_guard(store_dir)
+ for line in bad:
+ print(f"✗ arch: {line}")
+ failed += 1
+
+ manifest = {
+ "schema": 1,
+ "target": current_target(),
+ "ref": ref,
+ "repo": "hermes-agent",
+ "venv": "venv",
+ "store": "tools",
+ }
+ (out / "manifest.json").write_text(
+ json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8"
+ )
+ print(f"✓ manifest ({out / 'manifest.json'})")
+ return 1 if failed else 0
+
+
+def _arch_guard(store_dir: Path) -> list[str]:
+ """Every staged binary must be built for this machine's target — a
+ payload staged with a mismatched interpreter or PATH tool ships an
+ artifact that cannot run. Reads facts, probes each entry binary."""
+ from pm.lock import Facts
+ from pm.package import machine_matches_binary
+
+ facts = Facts(store_dir / "facts.json")
+ problems = []
+ target = current_target()
+ for name in _lockfile().names():
+ package = get_package(name)
+ fact = facts.get(name)
+ if fact is None or "entry" not in fact:
+ continue
+ binary = package.binary(store_dir / fact["entry"], target)
+ if binary is None or not binary.is_file():
+ continue
+ verdict = machine_matches_binary(binary, target)
+ # A package that declares this target as emulated (x64 binary run
+ # under Windows ARM64 built-in emulation) is fine with the x64 PE.
+ if verdict is False and target not in package.emulated_arch_targets:
+ problems.append(f"{name}: {binary.name} is not a {target} binary")
+ return problems
+
+
+def main(argv=None) -> int:
+ # Windows consoles default to cp1252; pm prints ✓/✗. Never let the
+ # status glyphs crash the command reporting them. line_buffering:
+ # pm output must stream live in a piped (CI) log, not sit in a block
+ # buffer and flush only at exit.
+ for stream in (sys.stdout, sys.stderr):
+ try:
+ stream.reconfigure(errors="replace", line_buffering=True)
+ except (AttributeError, OSError):
+ pass
+ parser = argparse.ArgumentParser(prog="hermes pm")
+ sub = parser.add_subparsers(dest="cmd", required=True)
+
+ p = sub.add_parser("lock", help="write versions+hashes into pm/lock.json")
+ p.add_argument("--bump", dest="name", required=True)
+ p.add_argument("version")
+ p.set_defaults(func=cmd_lock)
+
+ p = sub.add_parser("install", help="install packages (default: all required)")
+ p.add_argument("names", nargs="*")
+ p.set_defaults(func=cmd_install)
+
+ p = sub.add_parser("env", help="print composed env of installed packages")
+ p.add_argument("names", nargs="*")
+ p.set_defaults(func=cmd_env)
+
+ p = sub.add_parser("doctor", help="check installed state against the lockfile")
+ p.set_defaults(func=cmd_doctor)
+
+ p = sub.add_parser("develop", help="install + sync, then activate a devshell with the composed env")
+ p.add_argument("--print", dest="print_env", action="store_true",
+ help="print eval-able exports instead of spawning a shell")
+ p.set_defaults(func=cmd_develop)
+
+ p = sub.add_parser("gc", help="remove store entries nothing references")
+ p.set_defaults(func=cmd_gc)
+
+ p = sub.add_parser("bundle", help="stage a payload (repo+store+facts+relocatable venv) into --out")
+ p.add_argument("--out", required=True)
+ p.add_argument("--ref", help="git ref for the repo snapshot (default HEAD)")
+ p.set_defaults(func=cmd_bundle)
+
+ args = parser.parse_args(argv)
+ return args.func(args)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --cc pm/lock.json
index 68de12c6eef,00000000000..a4df1078eb5
mode 100644,000000..100644
--- a/pm/lock.json
+++ b/pm/lock.json
@@@ -1,381 -1,0 +1,381 @@@
+{
+ "packages": {
+ "agent-browser": {
+ "artifacts": {
+ "any": {
+ "sha256": "8a48cf4110d7dc2c12c1c4d6d25e0babdfa31604b537f05df0dc835fe2f854bf",
+ "url": "https://registry.npmjs.org/agent-browser/-/agent-browser-0.26.0.tgz"
+ }
+ },
+ "version": "0.26.0"
+ },
+ "chromium": {
+ "artifacts": {
+ "darwin-arm64": {
+ "sha256": "3dbf04e28a02079148e9c7417840a0c1d3903361eceeee7e7eb59ef77021bdb2",
+ "url": "https://cdn.playwright.dev/builds/cft/145.0.7632.6/mac-arm64/chrome-mac-arm64.zip"
+ },
+ "darwin-x64": {
+ "sha256": "0de8f876af53a93f8832e54490ff7de41a9b6648211590280cb50289ed45f240",
+ "url": "https://cdn.playwright.dev/builds/cft/145.0.7632.6/mac-x64/chrome-mac-x64.zip"
+ },
+ "linux-arm64": {
+ "sha256": "70b4620521b1ada360475e1059dfe9d549a6461a79b9342f85b7d47e44123077",
+ "url": "https://cdn.playwright.dev/dbazure/download/playwright/builds/chromium/1208/chromium-linux-arm64.zip"
+ },
+ "linux-x64": {
+ "sha256": "b5e3195041af345a668d110f5daf5581961fa3608626ea588c97dd0fe81c4e38",
+ "url": "https://cdn.playwright.dev/builds/cft/145.0.7632.6/linux64/chrome-linux64.zip"
+ },
+ "win32-arm64": {
+ "sha256": "08476e6fe550ccbc0d11d1ab030292fc4e32d4987400c77b2d1905a6bd13b4f6",
+ "url": "https://cdn.playwright.dev/builds/cft/145.0.7632.6/win64/chrome-win64.zip"
+ },
+ "win32-x64": {
+ "sha256": "08476e6fe550ccbc0d11d1ab030292fc4e32d4987400c77b2d1905a6bd13b4f6",
+ "url": "https://cdn.playwright.dev/builds/cft/145.0.7632.6/win64/chrome-win64.zip"
+ }
+ },
+ "version": "1208+145.0.7632.6"
+ },
+ "chromium-headless-shell": {
+ "artifacts": {
+ "darwin-arm64": {
+ "sha256": "8510b9b1575538aa6a092ed16d981738b2ebf52c5e41ea4c54a7ce16756cdcf5",
+ "url": "https://cdn.playwright.dev/builds/cft/145.0.7632.6/mac-arm64/chrome-headless-shell-mac-arm64.zip"
+ },
+ "darwin-x64": {
+ "sha256": "4316f7f98213a173e2356406203359cd4ab5b2b2db36cb219b9d99edec746819",
+ "url": "https://cdn.playwright.dev/builds/cft/145.0.7632.6/mac-x64/chrome-headless-shell-mac-x64.zip"
+ },
+ "linux-arm64": {
+ "sha256": "6bdb4349429ec33e7c0267e0eaa039c2131fa0b3b2997dec0ec96b0d40f579fd",
+ "url": "https://cdn.playwright.dev/dbazure/download/playwright/builds/chromium/1208/chromium-headless-shell-linux-arm64.zip"
+ },
+ "linux-x64": {
+ "sha256": "2536e97d8f410df0394b3e7c4252e88ce9f239f04f3af4e247a26caf45baf49e",
+ "url": "https://cdn.playwright.dev/builds/cft/145.0.7632.6/linux64/chrome-headless-shell-linux64.zip"
+ },
+ "win32-arm64": {
+ "sha256": "839500db9e1b0865961ce8b05134ba3d3d71b82be5dec236d6c87ecd93e082cd",
+ "url": "https://cdn.playwright.dev/builds/cft/145.0.7632.6/win64/chrome-headless-shell-win64.zip"
+ },
+ "win32-x64": {
+ "sha256": "839500db9e1b0865961ce8b05134ba3d3d71b82be5dec236d6c87ecd93e082cd",
+ "url": "https://cdn.playwright.dev/builds/cft/145.0.7632.6/win64/chrome-headless-shell-win64.zip"
+ }
+ },
+ "version": "1208+145.0.7632.6"
+ },
+ "cua-driver": {
+ "artifacts": {
+ "darwin-arm64": {
+ "sha256": "5e327e58f6ce81d5c117fe5edec5f267e87e1b921e8c5a8aa4f7f21cbcf5f273",
+ "url": "https://github.com/trycua/cua/releases/download/cua-driver-rs-v0.21.0/cua-driver-rs-0.21.0-darwin-universal-binary.tar.gz"
+ },
+ "darwin-x64": {
+ "sha256": "5e327e58f6ce81d5c117fe5edec5f267e87e1b921e8c5a8aa4f7f21cbcf5f273",
+ "url": "https://github.com/trycua/cua/releases/download/cua-driver-rs-v0.21.0/cua-driver-rs-0.21.0-darwin-universal-binary.tar.gz"
+ },
+ "linux-arm64": {
+ "sha256": "6b3a308c6741dd8291aad22a308bd2ec8eb52eab64687be007ac86ceaf7e3307",
+ "url": "https://github.com/trycua/cua/releases/download/cua-driver-rs-v0.21.0/cua-driver-rs-0.21.0-linux-arm64-binary.tar.gz"
+ },
+ "linux-x64": {
+ "sha256": "cf29bfaad16737e31e72f38dad2a6424f24b21a4ac2edea885e83cb9d5034135",
+ "url": "https://github.com/trycua/cua/releases/download/cua-driver-rs-v0.21.0/cua-driver-rs-0.21.0-linux-x86_64-binary.tar.gz"
+ },
+ "win32-arm64": {
+ "sha256": "79caf7e4f55cdab08533abf7ead4038132aa070040669238d806d057f648cc5f",
+ "url": "https://github.com/trycua/cua/releases/download/cua-driver-rs-v0.21.0/cua-driver-rs-0.21.0-windows-arm64-binary.zip"
+ },
+ "win32-x64": {
+ "sha256": "d63f6a78e65afc06524048f5557fed36cdf01f0a8a680236e93c9a2fb3587f44",
+ "url": "https://github.com/trycua/cua/releases/download/cua-driver-rs-v0.21.0/cua-driver-rs-0.21.0-windows-x86_64-binary.zip"
+ }
+ },
+ "version": "0.21.0"
+ },
+ "gh": {
+ "artifacts": {
+ "darwin-arm64": {
+ "sha256": "a58b8fd77b417a38f47a0b54d1370c59b0fcdb324ccc9ca002b0998f7c4c999e",
+ "url": "https://github.com/cli/cli/releases/download/v2.97.0/gh_2.97.0_macOS_arm64.zip"
+ },
+ "darwin-x64": {
+ "sha256": "63298c998cc2a924c9e254c6af6a1caad6ece281122687a91f079bc0a462700e",
+ "url": "https://github.com/cli/cli/releases/download/v2.97.0/gh_2.97.0_macOS_amd64.zip"
+ },
+ "linux-arm64": {
+ "sha256": "73ea440ecad9c9e284429997ee6f93577bc6f7bc6fba357ef62c53ad8fb641a5",
+ "url": "https://github.com/cli/cli/releases/download/v2.97.0/gh_2.97.0_linux_arm64.tar.gz"
+ },
+ "linux-x64": {
+ "sha256": "a2c9b8497e1f85b1ad0dfcb78b5a622e098801b8e461e459e88e1ee12f018112",
+ "url": "https://github.com/cli/cli/releases/download/v2.97.0/gh_2.97.0_linux_amd64.tar.gz"
+ },
+ "win32-arm64": {
+ "sha256": "3e2d4a166da4ee5020c592737b65eec0e724946d5d5b962f5fe59d99116dc4bf",
+ "url": "https://github.com/cli/cli/releases/download/v2.97.0/gh_2.97.0_windows_arm64.zip"
+ },
+ "win32-x64": {
+ "sha256": "35d7fe05c4dd1411ffda1e73dfc7c6f44b75c936ca51fa6595c657fdc0350cec",
+ "url": "https://github.com/cli/cli/releases/download/v2.97.0/gh_2.97.0_windows_amd64.zip"
+ }
+ },
+ "version": "2.97.0"
+ },
+ "ffmpeg": {
+ "artifacts": {
+ "darwin-arm64": {
+ "sha256": "8287a1b2229e05eb41859f073e18e6c52c60a778f2f5e6881070fe51b79407fe",
+ "url": "https://ffmpeg.martin-riedl.de/download/macos/arm64/1787073674_9.0.1/ffmpeg.zip"
+ },
+ "darwin-x64": {
+ "sha256": "5bdead62ff504ab9b447cc72b212c4fb481e3f7de5877d427a51bee8136dda40",
+ "url": "https://ffmpeg.martin-riedl.de/download/macos/amd64/1787081194_9.0.1/ffmpeg.zip"
+ },
+ "linux-arm64": {
+ "sha256": "92cff3dec20d996bb5b8a918b156b64301338e7c28046053c82d0935cf7c6eb2",
+ "url": "https://ffmpeg.martin-riedl.de/download/linux/arm64/1787072884_9.0.1/ffmpeg.zip"
+ },
+ "linux-x64": {
+ "sha256": "18bec7d5c2ab3b24d277466b758394e109b0479133b98d155c5540ed3013fa74",
+ "url": "https://ffmpeg.martin-riedl.de/download/linux/amd64/1787074600_9.0.1/ffmpeg.zip"
+ },
+ "win32-arm64": {
+ "sha256": "c50d45440d6376155842b653ecea1b323569b254db29cd7a42b298a924fd162c",
+ "url": "https://github.com/BtbN/FFmpeg-Builds/releases/download/autobuild-2026-08-28-17-08/ffmpeg-n9.0.1-11-ge47273f4d9-winarm64-gpl-9.0.zip"
+ },
+ "win32-x64": {
+ "sha256": "dee63142094f79f6a50cdece65384b7793181eab3b6db2ec907834981bb8ab10",
+ "url": "https://github.com/BtbN/FFmpeg-Builds/releases/download/autobuild-2026-08-28-17-08/ffmpeg-n9.0.1-11-ge47273f4d9-win64-gpl-9.0.zip"
+ }
+ },
+ "version": "9.0.1"
+ },
+ "git": {
+ "artifacts": {
+ "win32-arm64": {
+ "sha256": "4015f05a68bd2bcf3cc6c426e8d44b65d670fbb879225bb7b7c347cfc3a2758a",
+ "url": "https://github.com/git-for-windows/git/releases/download/v2.53.0.windows.3/Git-2.53.0.3-arm64.tar.bz2"
+ },
+ "win32-x64": {
+ "sha256": "1661f02e85a7901ad7920e2a358ee3772ed9066b00d8590bf2d9046ef10aa8b2",
+ "url": "https://github.com/git-for-windows/git/releases/download/v2.53.0.windows.3/Git-2.53.0.3-64-bit.tar.bz2"
+ }
+ },
+ "version": "2.53.0+3"
+ },
+ "llamacpp-cpu": {
+ "artifacts": {
+ "darwin-arm64": {
+ "sha256": "e353a453cadb25960bea9b24692b72bd0a6b7b50b3bab5860bd5df8a434e7c5b",
+ "url": "https://github.com/ggml-org/llama.cpp/releases/download/b10362/llama-b10362-bin-macos-arm64.tar.gz"
+ },
+ "darwin-x64": {
+ "sha256": "007ad98aec86111c87f5a602342d9da30f410dfb2e21c35b26c338cb915196e0",
+ "url": "https://github.com/ggml-org/llama.cpp/releases/download/b10362/llama-b10362-bin-macos-x64.tar.gz"
+ },
+ "linux-arm64": {
+ "sha256": "69bddd2aa441982bb7cf79ff65faa41a82b0629ad79741b32521ce00cba5165f",
+ "url": "https://github.com/ggml-org/llama.cpp/releases/download/b10362/llama-b10362-bin-ubuntu-arm64.tar.gz"
+ },
+ "linux-x64": {
+ "sha256": "d55a64e814e0a379082f79b9a974499fe14bcc6f4b491ffae23e4a2993d1b85f",
+ "url": "https://github.com/ggml-org/llama.cpp/releases/download/b10362/llama-b10362-bin-ubuntu-x64.tar.gz"
+ },
+ "win32-arm64": {
+ "sha256": "901a5c6c680f17e17c3dae1baf134b695144e300ac1e2c3f65607401406f5c75",
+ "url": "https://github.com/ggml-org/llama.cpp/releases/download/b10362/llama-b10362-bin-win-cpu-arm64.zip"
+ },
+ "win32-x64": {
+ "sha256": "a9d95d26cf00664f2902f73cb0fd9b167a3a1f252294bb2f8b236305f57d6363",
+ "url": "https://github.com/ggml-org/llama.cpp/releases/download/b10362/llama-b10362-bin-win-cpu-x64.zip"
+ }
+ },
+ "version": "10362"
+ },
+ "llamacpp-cuda": {
+ "artifacts": {
+ "win32-arm64": [
+ {
+ "sha256": "e96c44911a48f8813760b9076c7c7799db4374debb28d26a5464919bc0f27e8f",
+ "url": "https://github.com/ggml-org/llama.cpp/releases/download/b10362/llama-b10362-bin-win-cuda-13.4-arm64.zip"
+ },
+ {
+ "sha256": "5a40dc7c5fa3d0a80ceeba4f16f9e8d25d87bcf1399c9233588953c43436c33c",
+ "url": "https://github.com/ggml-org/llama.cpp/releases/download/b10362/cudart-llama-bin-win-cuda-13.4-arm64.zip"
+ }
+ ],
+ "win32-x64": [
+ {
+ "sha256": "65d74d6164ed5c8245762f6a7d646269e1c0cd6f8972e74771a43f6d2b3ce2ea",
+ "url": "https://github.com/ggml-org/llama.cpp/releases/download/b10362/llama-b10362-bin-win-cuda-13.3-x64.zip"
+ },
+ {
+ "sha256": "1462a050eb4c684921ba51dcc4cc488a036674c3e73e9945ee705b854808d03e",
+ "url": "https://github.com/ggml-org/llama.cpp/releases/download/b10362/cudart-llama-bin-win-cuda-13.3-x64.zip"
+ }
+ ]
+ },
+ "version": "10362"
+ },
+ "llamacpp-metal": {
+ "artifacts": {
+ "darwin-arm64": {
+ "sha256": "e353a453cadb25960bea9b24692b72bd0a6b7b50b3bab5860bd5df8a434e7c5b",
+ "url": "https://github.com/ggml-org/llama.cpp/releases/download/b10362/llama-b10362-bin-macos-arm64.tar.gz"
+ },
+ "darwin-x64": {
+ "sha256": "007ad98aec86111c87f5a602342d9da30f410dfb2e21c35b26c338cb915196e0",
+ "url": "https://github.com/ggml-org/llama.cpp/releases/download/b10362/llama-b10362-bin-macos-x64.tar.gz"
+ }
+ },
+ "version": "10362"
+ },
+ "llamacpp-vulkan": {
+ "artifacts": {
+ "linux-arm64": {
+ "sha256": "aaa5cd203ad591ffc637535239ebd5e341fa4d272f70a976825d8823d9325b0e",
+ "url": "https://github.com/ggml-org/llama.cpp/releases/download/b10362/llama-b10362-bin-ubuntu-vulkan-arm64.tar.gz"
+ },
+ "linux-x64": {
+ "sha256": "cd9dc4885a32bae4c7640454e15aeba1324fff8bb6ea003555b5b112aa16d3bc",
+ "url": "https://github.com/ggml-org/llama.cpp/releases/download/b10362/llama-b10362-bin-ubuntu-vulkan-x64.tar.gz"
+ },
+ "win32-x64": {
+ "sha256": "5da6d2c0cac199b917f0a7677c22b619750a9dd12432586d5d61457350e65a50",
+ "url": "https://github.com/ggml-org/llama.cpp/releases/download/b10362/llama-b10362-bin-win-vulkan-x64.zip"
+ }
+ },
+ "version": "10362"
+ },
+ "node": {
+ "artifacts": {
+ "darwin-arm64": {
- "sha256": "7ee659a7768e641bbfd5360940660b8e8fd0052f77488f365562bac522fc15d4",
++ "sha256": "595d2f934e081b82961d1a5fd41c6dbd0c5a952d9e8be5b4566ab754426968d2",
+ "url": "https://nodejs.org/dist/v26.7.0/node-v26.7.0-darwin-arm64.tar.xz"
+ },
+ "darwin-x64": {
- "sha256": "f279d1ed28ce57f7788bf23435d2ad7fdd7438904ad5c4d8a1081a7cde3d4b96",
++ "sha256": "bd19c6b98d923fb049f64b547163b9f7d52ae73f16fdee09ecef9ab248c4d6ff",
+ "url": "https://nodejs.org/dist/v26.7.0/node-v26.7.0-darwin-x64.tar.xz"
+ },
+ "linux-arm64": {
+ "sha256": "afc7a004018485092ac8985b817b0d5684472bd9472e0b57d2ab88737e50090d",
+ "url": "https://nodejs.org/dist/v26.7.0/node-v26.7.0-linux-arm64.tar.xz"
+ },
+ "linux-x64": {
+ "sha256": "982aa24dd8be4c889c6a8ab337ddff3b0896645b20f4239356e80552c16277ee",
+ "url": "https://nodejs.org/dist/v26.7.0/node-v26.7.0-linux-x64.tar.xz"
+ },
+ "win32-arm64": {
+ "sha256": "be8775204cfceca5a73c30f91bf0de5e85274c01b776dc13f16b91aa251ebb01",
+ "url": "https://nodejs.org/dist/v26.7.0/node-v26.7.0-win-arm64.zip"
+ },
+ "win32-x64": {
+ "sha256": "d3bd72755141ed32bbcd841228ee81897c8a98d50dfa7dae2179399a0a7c90f8",
+ "url": "https://nodejs.org/dist/v26.7.0/node-v26.7.0-win-x64.zip"
+ }
+ },
+ "version": "26.7.0"
+ },
+ "npm": {
+ "artifacts": {
+ "any": {
+ "sha256": "5dbb86c71d07a1957f2e90734092dd6a58bdcd9ebc2d8d41ca1c6e6a21d364e1",
+ "url": "https://registry.npmjs.org/npm/-/npm-12.0.2.tgz"
+ }
+ },
+ "version": "12.0.2"
+ },
+ "python": {
+ "artifacts": {
+ "darwin-arm64": {
+ "sha256": "fcba9f3f676c83e07225e38116649f0c6eb94cb4fcc166632cf92769462b6e39",
+ "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20260814/cpython-3.11.16+20260814-aarch64-apple-darwin-install_only.tar.gz"
+ },
+ "darwin-x64": {
+ "sha256": "d9117d31251ba5c9a81ac7ad7c00dab1d5228e261eb0cda94550b4da1cc73bd1",
+ "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20260814/cpython-3.11.16+20260814-x86_64-apple-darwin-install_only.tar.gz"
+ },
+ "linux-arm64": {
+ "sha256": "9142c12dd3559eaac58a18d8905b99a293979d5e5a1b4fb5cf4cebbf82ef6f33",
+ "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20260814/cpython-3.11.16+20260814-aarch64-unknown-linux-gnu-install_only.tar.gz"
+ },
+ "linux-x64": {
+ "sha256": "33994fad90145ba559ebbe8a18d69fa7e56653502f7ba14ba07199b52cde3775",
+ "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20260814/cpython-3.11.16+20260814-x86_64-unknown-linux-gnu-install_only.tar.gz"
+ },
+ "win32-arm64": {
+ "sha256": "450cbf91ff0dbfce7fa1d40ba19103187852076496b6153e528fa6dc43a88a58",
+ "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20260814/cpython-3.11.16+20260814-aarch64-pc-windows-msvc-install_only.tar.gz"
+ },
+ "win32-x64": {
+ "sha256": "ffaee1e94c8488f833473e56e1c980ca1a58d91126d21ddf0f6ba052e69cf511",
+ "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20260814/cpython-3.11.16+20260814-x86_64-pc-windows-msvc-install_only.tar.gz"
+ }
+ },
+ "version": "3.11.16+20260814"
+ },
+ "ripgrep": {
+ "artifacts": {
+ "darwin-arm64": {
+ "sha256": "3750b2e93f37e0c692657da574d7019a101c0084da05a790c83fd335bad973e4",
+ "url": "https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-aarch64-apple-darwin.tar.gz"
+ },
+ "darwin-x64": {
+ "sha256": "af7825fcc69a2afc7a7aea55fc9af90e26421d8f20fe59df32e233c0b8a231c1",
+ "url": "https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-x86_64-apple-darwin.tar.gz"
+ },
+ "linux-arm64": {
+ "sha256": "800b1e7206afe799dfb5a6901f23147cfaabe0e52210538100f61e86e1740915",
+ "url": "https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-aarch64-unknown-linux-musl.tar.gz"
+ },
+ "linux-x64": {
+ "sha256": "33e15bcf1624b25cdd2a55813a47a2f95dbe126268203e76aa6a585d1e7b149c",
+ "url": "https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-x86_64-unknown-linux-musl.tar.gz"
+ },
+ "win32-arm64": {
+ "sha256": "e4abca10c3a64ebea742667dd7009449d49403db5460dd6873e389fa2945360f",
+ "url": "https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-aarch64-pc-windows-msvc.zip"
+ },
+ "win32-x64": {
+ "sha256": "71b2fef860abe467217a538ff31de02f5258807c0129f771846f87bd029aafc5",
+ "url": "https://github.com/BurntSushi/ripgrep/releases/download/15.2.0/ripgrep-15.2.0-x86_64-pc-windows-msvc.zip"
+ }
+ },
+ "version": "15.2.0"
+ },
+ "uv": {
+ "artifacts": {
+ "darwin-arm64": {
+ "sha256": "546f7f8a6c70ff13a3a9d2bc958db3427298cebf3e0cb756f9177133b7068843",
+ "url": "https://github.com/astral-sh/uv/releases/download/0.12.3/uv-aarch64-apple-darwin.tar.gz"
+ },
+ "darwin-x64": {
+ "sha256": "4c9f52262a14da336e4a42ed24992d12d0c956acde87619e4611d321dffa602b",
+ "url": "https://github.com/astral-sh/uv/releases/download/0.12.3/uv-x86_64-apple-darwin.tar.gz"
+ },
+ "linux-arm64": {
+ "sha256": "bb66cb52e7b1823aed1183630d8d8e5c958840d584a4c55ec10a4cfc168dcca2",
+ "url": "https://github.com/astral-sh/uv/releases/download/0.12.3/uv-aarch64-unknown-linux-gnu.tar.gz"
+ },
+ "linux-x64": {
+ "sha256": "600cf9a742aca00d292673b16b5acffaa7b8c269a364ad0c2e79498dcb1fe101",
+ "url": "https://github.com/astral-sh/uv/releases/download/0.12.3/uv-x86_64-unknown-linux-gnu.tar.gz"
+ },
+ "win32-arm64": {
+ "sha256": "4343217d668727b8a8eb5cad92389a1d2eeead93c89940d1b955ba1bb15462eb",
+ "url": "https://github.com/astral-sh/uv/releases/download/0.12.3/uv-aarch64-pc-windows-msvc.zip"
+ },
+ "win32-x64": {
+ "sha256": "b23350c79e8ad0192b8124af13a0f17e8d4e4549524785e1aef389ae5a06990e",
+ "url": "https://github.com/astral-sh/uv/releases/download/0.12.3/uv-x86_64-pc-windows-msvc.zip"
+ }
+ },
+ "version": "0.12.3"
+ }
+ },
+ "schema": 1
+}
diff --cc pm/packages.py
index 8384a24e6a3,00000000000..c1a4c23a28e
mode 100644,000000..100644
--- a/pm/packages.py
+++ b/pm/packages.py
@@@ -1,778 -1,0 +1,801 @@@
+"""Package definitions for the tools hermes manages. Versions and hashes
+live in pm/lock.json (written by `pm lock`), never here."""
+
+from __future__ import annotations
+
+import os
+import platform
+import shutil
+import subprocess
+from pathlib import Path
+from typing import Optional
+
+from pm.package import (
+ InstallError,
+ Package,
+ StatePackage,
+ _entry_listing,
+ _missing_reason,
+ _probe_reason,
+)
+from pm.registry import register
+from pm.store import ALL_TARGETS, Store, flatten_single_dir, merge_tree
+
+_RUST_TRIPLE = {
+ "win32-x64": "x86_64-pc-windows-msvc",
+ "win32-arm64": "aarch64-pc-windows-msvc",
+ "linux-x64": "x86_64-unknown-linux-gnu",
+ "linux-arm64": "aarch64-unknown-linux-gnu",
+ "darwin-x64": "x86_64-apple-darwin",
+ "darwin-arm64": "aarch64-apple-darwin",
+}
+
+_NODE_PLAT = {
+ "win32-x64": "win-x64",
+ "win32-arm64": "win-arm64",
+ "linux-x64": "linux-x64",
+ "linux-arm64": "linux-arm64",
+ "darwin-x64": "darwin-x64",
+ "darwin-arm64": "darwin-arm64",
+}
+
+
+class BinaryPackage(Package):
+ """A downloaded archive exposing one binary. Covers most tools."""
+
+ binary_rel: dict[str, str] = {}
+ flatten = True
+ probe_version = True
+ # argv after the binary for the smoke probe. A package whose binary
+ # rejects the GNU double-dash form (ffmpeg's BtbN autobuild) overrides.
+ probe_args: list[str] = ["--version"]
+ # Run the probe with cwd=binary.parent: dlopen'd backends (llama.cpp's
+ # cudart) resolve their shared libraries from the working directory.
+ probe_cwd = False
+
+ def _rel(self, target: str) -> Optional[str]:
+ win = target.startswith("win32")
+ return self.binary_rel.get(target) or self.binary_rel.get(
+ "win32" if win else "posix"
+ )
+
+ def stage(self, store: Store, staged: Path, version: str, target: str) -> None:
+ if self.flatten:
+ flatten_single_dir(staged)
+
+ def binary(self, entry: Path, target: str) -> Optional[Path]:
+ rel = self._rel(target)
+ return entry / rel if rel else None
+
+ def verify(self, entry: Path, target: str) -> str:
+ """Return '' when the entry is usable on target, else why not:
+ a missing binary, a wrong-arch binary, or a --version probe that
+ fails to exec, times out, or exits nonzero."""
+ binary = self.binary(entry, target)
+ if binary is None:
+ return "no binary_rel for this target"
+ reason = self._binary_reason(binary, entry, target)
+ if reason:
+ return reason
+ if not self.probe_version:
+ return ""
+ try:
+ proc = subprocess.run(
+ [str(binary), *self.probe_args],
+ capture_output=True,
+ timeout=60,
+ cwd=str(binary.parent) if self.probe_cwd else None,
+ env=self._probe_env(),
+ )
+ except OSError as e:
+ return f"could not exec {binary} {' '.join(self.probe_args)}: {e}"
+ except subprocess.TimeoutExpired:
+ return f"{binary} {' '.join(self.probe_args)} timed out after 60s"
+ if proc.returncode != 0:
+ return _probe_reason(binary, proc)
+ return ""
+
+ def _probe_env(self) -> dict:
+ """Deps' env composed in: npm's shim is `#!/usr/bin/env node` and
+ must find the node it extends on PATH."""
+ if not self.deps:
+ return dict(os.environ)
+ from pm.ensure import env_for
+
+ return env_for(*self.deps)
+
+
+@register
+class Uv(BinaryPackage):
+ name = "uv"
+ internal = True
+ binary_rel = {"win32": "uv.exe", "posix": "uv"}
+
+ def fetch_url(self, version: str, target: str) -> str:
+ triple = _RUST_TRIPLE[target]
+ ext = "zip" if target.startswith("win32") else "tar.gz"
+ return f"https://github.com/astral-sh/uv/releases/download/{version}/uv-{triple}.{ext}"
+
+
+_MACOS_MANAGED_PYTHON_IDENTIFIER = "com.nousresearch.hermes.managed-python"
+
+
+def _macos_sign_managed_python(python: Path) -> bool:
+ """Give a downloaded Python a stable macOS code identity."""
+ if platform.system() != "Darwin":
+ return False
+
+ codesign = shutil.which("codesign")
+ if not codesign:
+ return False
+
+ requirement = (
+ "=designated => identifier "
+ f'"{_MACOS_MANAGED_PYTHON_IDENTIFIER}"'
+ )
+ try:
+ signed = subprocess.run(
+ [
+ codesign,
+ "--force",
+ "--deep",
+ "--sign",
+ "-",
+ "--timestamp=none",
+ "--identifier",
+ _MACOS_MANAGED_PYTHON_IDENTIFIER,
+ "--requirements",
+ requirement,
+ str(python),
+ ],
+ check=False,
+ capture_output=True,
+ text=True,
+ )
+ if signed.returncode != 0:
+ return False
+ verified = subprocess.run(
+ [codesign, "--verify", "--deep", "--strict", str(python)],
+ check=False,
+ capture_output=True,
+ text=True,
+ )
+ return verified.returncode == 0
+ except Exception:
+ return False
+
+
+@register
+class Python(BinaryPackage):
+ """The payload interpreter (python-build-standalone install_only).
+ Optional: dev installs use their own venv's python; bundles stage this
+ and point the relocatable venv's pyvenv.cfg at it (pm adopt)."""
+
+ name = "python"
+ optional = True
+ probe_version = False
+ binary_rel = {"win32": "python.exe", "posix": "bin/python3"}
+
+ def stage(self, store: Store, staged: Path, version: str, target: str) -> None:
+ super().stage(store, staged, version, target)
+ binary = self.binary(staged, target)
+ if binary is not None:
+ _macos_sign_managed_python(binary)
+
+ def fetch_url(self, version: str, target: str) -> str:
+ # lock version is "<python>+<release tag>", e.g. "3.11.13+20250807"
+ pyver, _, tag = version.partition("+")
+ if not tag:
+ raise InstallError(self.name, f"version {version!r} needs the +<release> tag")
+ triple = _RUST_TRIPLE[target]
+ return (
+ "https://github.com/astral-sh/python-build-standalone/releases/download/"
+ f"{tag}/cpython-{pyver}+{tag}-{triple}-install_only.tar.gz"
+ )
+
+
+def _uv_lock_digest(path: Path) -> bytes:
+ """sha256 of uv.lock, cached on (mtime_ns, size) — check() runs at
+ every startup and uv.lock is megabyte-class."""
+ import hashlib
+
+ stat = path.stat()
+ key = (stat.st_mtime_ns, stat.st_size)
+ cached = _uv_lock_digest_cache.get(path)
+ if cached and cached[0] == key:
+ return cached[1]
+ digest = hashlib.sha256(path.read_bytes()).digest()
+ _uv_lock_digest_cache[path] = (key, digest)
+ return digest
+
+
+_uv_lock_digest_cache: dict[Path, tuple] = {}
+
+
+def uv_env(base_env: Optional[dict] = None) -> dict[str, str]:
+ """Sanitized env for pm's internal uv invocations: user-level UV
+ overrides and active-venv leakage must not steer which interpreter or
- install dir uv picks (the interpreter-hijack class, #83914)."""
++ install dir uv picks (the interpreter-hijack class, #83914), and
++ ambient user/system uv config (uv.toml under XDG_CONFIG_HOME/DIRS)
++ must not reach the subprocess either. User config discovery is
++ redirected to an empty dir; HOME is left alone so caches, credentials,
++ and git keep working (the #82446 isolation contract, which lived in
++ the installers' run_locked_uv_sync() before the sync moved into pm)."""
+ env = dict(os.environ if base_env is None else base_env)
+ for key in list(env):
+ if key.startswith("UV_") or key in (
+ "VIRTUAL_ENV",
+ "PYTHONPATH",
+ "PYTHONHOME",
+ "PYTHONSTARTUP",
+ "PYTHONEXECUTABLE",
+ ):
+ env.pop(key)
++ isolated = _isolated_config_dir()
++ env["XDG_CONFIG_HOME"] = str(isolated)
++ env["XDG_CONFIG_DIRS"] = str(isolated)
+ env["UV_NO_CONFIG"] = "1"
+ return env
+
+
++_ISOLATED_CONFIG_DIR: Optional[str] = None
++
++
++def _isolated_config_dir() -> Path:
++ """A per-process empty dir ambient uv config is redirected to. One
++ shared empty dir is all that's needed (and all that ever gets
++ created); it is never populated, so it cannot steer resolution."""
++ import tempfile
++
++ global _ISOLATED_CONFIG_DIR
++ if _ISOLATED_CONFIG_DIR is None:
++ _ISOLATED_CONFIG_DIR = tempfile.mkdtemp(prefix="pm-uv-")
++ return Path(_ISOLATED_CONFIG_DIR)
++
++
+@register
+class Venv(StatePackage):
+ """The project venv: pyproject.toml + uv.lock + enabled extras.
+ Made true by `uv sync --frozen`; uv is its internal dependency."""
+
+ name = "venv"
+ deps = ("uv",)
+
+ def project_root(self) -> Path:
+ from pm.paths import repo_root
+
+ return repo_root()
+
+ def venv_dir(self) -> Path:
+ from hermes_constants import project_venv_dir
+
+ found = project_venv_dir(self.project_root())
+ return found if found else self.project_root() / "venv"
+
+ def expected_stamp(self, extras: list[str]) -> str:
+ import hashlib
+ import sys
+
+ h = hashlib.sha256()
+ h.update(_uv_lock_digest(self.project_root() / "uv.lock"))
+ h.update(",".join(sorted(extras)).encode())
+ h.update(f"{sys.version_info.major}.{sys.version_info.minor}".encode())
+ return h.hexdigest()
+
+ def apply(self, extras: list[str]) -> None:
+ from pm.ensure import uv as pm_uv
+
+ uv_bin, env = pm_uv(venv=self.venv_dir())
+ if uv_bin is None:
+ raise InstallError(self.name, "uv is not installed")
+ cmd = [uv_bin, "sync", "--frozen"]
+ for extra in sorted(extras):
+ cmd += ["--extra", extra]
+ proc = subprocess.run(
+ cmd,
+ cwd=str(self.project_root()),
+ capture_output=True,
+ text=True,
+ timeout=1800,
+ env=env,
+ )
+ if proc.returncode != 0:
+ raise InstallError(
+ self.name, f"uv sync exited {proc.returncode}: {proc.stderr[-400:]}"
+ )
+
+
+@register
+class Nodejs(BinaryPackage):
+ name = "node"
+ binary_rel = {"win32": "node.exe", "posix": "bin/node"}
+
+ def fetch_url(self, version: str, target: str) -> str:
+ plat = _NODE_PLAT[target]
+ ext = "zip" if target.startswith("win32") else "tar.xz"
+ return f"https://nodejs.org/dist/v{version}/node-v{version}-{plat}.{ext}"
+
+
+@register
+class Npm(BinaryPackage):
+ name = "npm"
+ deps = ("node",)
+ binary_rel = {"win32": "npm.cmd", "posix": "bin/npm"}
+ flatten = False
+ probe_version = False
+ url = "https://registry.npmjs.org/npm/-/npm-{version}.tgz"
+
+ def unpack(self, archive: Path, staged: Path, target: str) -> None:
+ """npm installs itself using the node it extends: a plain unpack
+ resolves the cli from dirname(process.execPath) and finds node's
+ bundled npm instead. --offline pins the bytes to the verified
+ tarball; --ignore-scripts + a sanitized env keep user npm/node
+ config out of the staging."""
+ from pm.ensure import _facts, _store
+ from pm.registry import get_package
+
+ facts = _facts()
+ store = _store()
+ node = get_package("node")
+ node_fact = facts.get("node")
+ if node_fact is None:
+ raise InstallError(self.name, "npm extends node, which is not installed")
+ node_bin = node.binary(store.entry(node_fact["entry"]), target)
+ if node_bin is None or not node_bin.is_file():
+ raise InstallError(self.name, "node's entry is missing its binary")
+ win = target.startswith("win32")
+ bundled_cli = (
+ node_bin.parent / "node_modules" / "npm" / "bin" / "npm-cli.js"
+ if win
+ else node_bin.parent.parent / "lib" / "node_modules" / "npm" / "bin" / "npm-cli.js"
+ )
+ if not bundled_cli.is_file():
+ raise InstallError(self.name, "node's entry is missing its bundled npm-cli.js")
+
+ env = {
+ key: value
+ for key, value in os.environ.items()
+ if not key.lower().startswith("npm_config_")
+ and key not in ("NODE_OPTIONS", "NODE_PATH", "NODE_ENV")
+ }
+ env["npm_config_cache"] = str(archive.parent / ".npm-cache")
+
+ staged.mkdir(parents=True, exist_ok=True)
+ proc = subprocess.run(
+ [
+ str(node_bin), str(bundled_cli), "install", "--global",
+ "--prefix", str(staged), "--offline", "--ignore-scripts",
+ "--no-audit", "--no-fund", str(archive),
+ ],
+ capture_output=True,
+ text=True,
+ timeout=900,
+ env=env,
+ )
+ if proc.returncode != 0:
+ raise InstallError(
+ self.name, f"self-install exited {proc.returncode}: {proc.stderr[-400:]}"
+ )
+
+
+@register
+class Git(BinaryPackage):
+ """Windows only: Git for Windows carries the bash.exe contract. POSIX
+ uses the system git — a deliberate gap, not an oversight. The tar.bz2
+ release asset extracts with stdlib tarfile: no self-extractor, no GUI."""
+
+ name = "git"
+ optional = True
+ binary_rel = {"win32": "cmd/git.exe"}
+ flatten = False
+ gaps = {
+ "linux-x64": "POSIX uses system git by choice",
+ "linux-arm64": "POSIX uses system git by choice",
+ "darwin-x64": "POSIX uses system git by choice",
+ "darwin-arm64": "POSIX uses system git by choice",
+ }
+
+ def fetch_url(self, version: str, target: str) -> str:
+ tag, build = version.split("+")
+ arch = "arm64" if target.endswith("arm64") else "64-bit"
+ return (
+ f"https://github.com/git-for-windows/git/releases/download/"
+ f"v{tag}.windows.{build}/Git-{tag}.{build}-{arch}.tar.bz2"
+ )
+
+ def unpack(self, archive: Path, staged: Path, target: str) -> None:
+ """stdlib tar extract, but skip members the data filter refuses —
+ the MSYS tree ships dev/fd → /proc/self/fd style links that mean
+ nothing on Windows and must not fail the install."""
+ import tarfile
+
+ staged.mkdir(parents=True, exist_ok=True)
+ with tarfile.open(archive) as tf:
+ for member in tf:
+ try:
+ tf.extract(member, staged, filter="data")
+ except (tarfile.FilterError, OSError):
+ continue
+
+ def env(self, entry: Path, target: str) -> dict:
+ return {"PATH": [str(entry / "cmd"), str(entry / "usr" / "bin")]}
+
+
+@register
+class Gh(BinaryPackage):
+ name = "gh"
+ optional = True
+ binary_rel = {"win32": "bin/gh.exe", "posix": "bin/gh"}
+
+ def fetch_url(self, version: str, target: str) -> str:
+ osname, arch = target.split("-")
+ plat = {"win32": "windows", "linux": "linux", "darwin": "macOS"}[osname]
+ arch = {"x64": "amd64", "arm64": "arm64"}[arch]
+ ext = "zip" if osname in ("win32", "darwin") else "tar.gz"
+ return (
+ f"https://github.com/cli/cli/releases/download/v{version}/"
+ f"gh_{version}_{plat}_{arch}.{ext}"
+ )
+
+
+@register
+class Ffmpeg(BinaryPackage):
+ """Static ffmpeg. GPLv3 builds; always bundled.
+ optional=False: ffmpeg is a required runtime tool. Sealed bundles ship
+ it baked into the payload (post_update skips provisioning sealed
+ installs — the artifact is atomic); dev installs get it re-ensured by
+ step_provision_runtimes when the pin bumps. Windows: BtbN/FFmpeg-Builds
+ (dated autobuild tag; ships ffprobe too). Linux + macOS:
+ ffmpeg.martin-riedl.de (uniform ZIP, published sha256; single-binary —
+ no ffprobe)."""
+
+ name = "ffmpeg"
+ optional = False
+ # martin-riedl (posix) zips are a single `ffmpeg` file at the zip root;
+ # BtbN (win32) zips carry bin/ffmpeg.exe under one top-level dir that
+ # flatten hoists.
+ binary_rel = {"win32": "bin/ffmpeg.exe", "posix": "ffmpeg"}
+ flatten = True
+ # BtbN autobuild n9.0.1-11-ge47273f4d9 rejects `--version`
+ # ("Unrecognized option '-version'", exit 2880417800); `-version` works
+ # and is accepted by every ffmpeg build.
+ probe_args = ["-version"]
+
+ def fetch_url(self, version: str, target: str) -> str:
+ osname, arch = target.split("-")
+ if osname == "win32":
+ # BtbN ships branch builds; the URL is the immutable dated tag.
+ return (
+ "https://github.com/BtbN/FFmpeg-Builds/releases/download/"
+ f"autobuild-{self._btbn_tag}/{self._btbn_asset(target)}"
+ )
+ martin = {
+ ("linux", "x64"): "linux/amd64/1787074600_9.0.1",
+ ("linux", "arm64"): "linux/arm64/1787072884_9.0.1",
+ ("darwin", "x64"): "macos/amd64/1787081194_9.0.1",
+ ("darwin", "arm64"): "macos/arm64/1787073674_9.0.1",
+ }
+ return f"https://ffmpeg.martin-riedl.de/download/{martin[(osname, arch)]}/ffmpeg.zip"
+
+ def _btbn_tag(self) -> str:
+ return "2026-08-28-17-08"
+
+ def _btbn_asset(self, target: str) -> str:
+ arch = "arm64" if target.endswith("arm64") else "64"
+ return (
+ "ffmpeg-n9.0.1-11-ge47273f4d9-"
+ f"win{arch}-gpl-9.0.zip"
+ )
+
+
+
+@register
+class Ripgrep(BinaryPackage):
+ name = "ripgrep"
+ binary_rel = {"win32": "rg.exe", "posix": "rg"}
+
+ def fetch_url(self, version: str, target: str) -> str:
+ triple = _RUST_TRIPLE[target].replace("-unknown-linux-gnu", "-unknown-linux-musl")
+ ext = "zip" if target.startswith("win32") else "tar.gz"
+ return (
+ f"https://github.com/BurntSushi/ripgrep/releases/download/{version}/"
+ f"ripgrep-{version}-{triple}.{ext}"
+ )
+
+
+@register
+class CuaDriver(BinaryPackage):
+ name = "cua-driver"
+ optional = True
+ binary_rel = {"win32": "cua-driver.exe", "posix": "cua-driver"}
+
+ def fetch_url(self, version: str, target: str) -> str:
+ arch = {
+ "darwin-x64": "darwin-universal",
+ "darwin-arm64": "darwin-universal",
+ "linux-x64": "linux-x86_64",
+ "linux-arm64": "linux-arm64",
+ "win32-x64": "windows-x86_64",
+ "win32-arm64": "windows-arm64",
+ }[target]
+ ext = "zip" if target.startswith("win32") else "tar.gz"
+ return (
+ f"https://github.com/trycua/cua/releases/download/cua-driver-rs-v{version}/"
+ f"cua-driver-rs-{version}-{arch}-binary.{ext}"
+ )
+
+ def stage(self, store: Store, staged: Path, version: str, target: str) -> None:
+ flatten_single_dir(staged)
+ sdk = staged / "sdk"
+ if sdk.is_dir():
+ shutil.rmtree(sdk, ignore_errors=True)
+
+ def _probe_env(self) -> dict:
+ """The probe IS a first run: it must not mint telemetry state."""
+ try:
+ from tools.computer_use.cua_backend import cua_driver_child_env
+
+ return cua_driver_child_env()
+ except Exception:
+ return dict(os.environ, CUA_DRIVER_RS_TELEMETRY_ENABLED="0")
+
+
+@register
+class AgentBrowser(BinaryPackage):
+ name = "agent-browser"
+ optional = True
+ deps = ("chromium", "chromium-headless-shell")
+ flatten = True
+ probe_version = False
+ url = "https://registry.npmjs.org/agent-browser/-/agent-browser-{version}.tgz"
+ # No win32-arm64 gap: agent-browser ships only win32-x64, and Windows
+ # ARM64 runs it via built-in emulation (its own postinstall falls back
+ # to x64 on arm64). chromium is likewise the x64 build on win32-arm64.
+ emulated_arch_targets = frozenset({"win32-arm64"})
+
+ def _rel(self, target: str) -> Optional[str]:
+ ext = ".exe" if target.startswith("win32") else ""
+ # Windows ARM64 runs the x64 binary under built-in emulation:
+ # agent-browser ships no native arm64 build (its own postinstall
+ # falls back to x64 on arm64), so the staged name is win32-x64.
+ if target == "win32-arm64":
+ target = "win32-x64"
+ return f"bin/agent-browser-{target}{ext}"
+
+ def binary(self, entry: Path, target: str) -> Optional[Path]:
+ # The win32-arm64 payload carries the x64 binary (emulated), so
+ # resolve it under the win32-x64 name.
+ return super().binary(entry, "win32-x64" if target == "win32-arm64" else target)
+
+ def stage(self, store: Store, staged: Path, version: str, target: str) -> None:
+ flatten_single_dir(staged)
+ bin_dir = staged / "bin"
+ if not bin_dir.is_dir():
+ raise InstallError(self.name, "staged without a bin/ directory")
+ keep = Path(self._rel(target)).name
+ if not (bin_dir / keep).is_file():
+ raise InstallError(self.name, f"{keep} missing from the staged tarball")
+ for item in bin_dir.iterdir():
+ if item.is_file() and item.name.startswith("agent-browser-") and item.name != keep:
+ item.unlink()
+
+
+class PlaywrightBrowser(Package):
+ """Playwright resolves browsers by DIRECTORY NAME under one root:
+ `<name with '-'→'_'>-<revision>`, no target suffix. The env points
+ PLAYWRIGHT_BROWSERS_PATH at the store root itself. The entry carries
+ the INSTALLATION_COMPLETE marker playwright checks.
+
+ The version is `<playwright revision>+<chrome version>` — most targets
+ download from the Chrome-for-Testing CDN by chrome version, and the
+ targets CfT doesn't build (linux-arm64) come from playwright's own
+ mirror by revision. The store entry is named by revision only, which
+ is all playwright's resolver reads."""
+
+ optional = True
+ on_path = False
+ _CDN = "https://cdn.playwright.dev"
+
+ # Chrome-for-Testing platform names; targets absent here fall back to
+ # playwright's dbazure mirror with its own platform names.
+ # win32-arm64 uses the win64 (x64) build: CfT publishes no native
+ # win-arm64 chromium, and Windows ARM64 runs x64 binaries via built-in
+ # emulation — the same choice agent-browser's own postinstall makes.
+ _CFT = {
+ "linux-x64": "linux64",
+ "darwin-x64": "mac-x64",
+ "darwin-arm64": "mac-arm64",
+ "win32-x64": "win64",
+ "win32-arm64": "win64",
+ }
+ _MIRROR = {"linux-arm64": "linux-arm64"}
+ _FILE = "" # "chrome" / "chrome-headless-shell"
+ _MIRROR_FILE = "" # "chromium" / "chromium-headless-shell"
+
+ def store_entry(self, version: str, target: str) -> str:
+ revision = version.partition("+")[0]
+ return f"{self.name.replace('-', '_')}-{revision}"
+
+ def fetch_url(self, version: str, target: str) -> str:
+ revision, _, chrome = version.partition("+")
+ plat = self._CFT.get(target)
+ if plat and chrome:
+ return f"{self._CDN}/builds/cft/{chrome}/{plat}/{self._FILE}-{plat}.zip"
+ mirror_plat = self._MIRROR[target]
+ return (
+ f"{self._CDN}/dbazure/download/playwright/builds/chromium/"
+ f"{revision}/{self._MIRROR_FILE}-{mirror_plat}.zip"
+ )
+
+ def stage(self, store: Store, staged: Path, version: str, target: str) -> None:
+ (staged / "INSTALLATION_COMPLETE").write_text("", encoding="utf-8")
+
+ def verify(self, entry: Path, target: str) -> str:
+ marker = entry / "INSTALLATION_COMPLETE"
+ if marker.is_file():
+ return ""
+ return f"INSTALLATION_COMPLETE missing under {entry}; {_entry_listing(entry)}"
+
+ def env(self, entry: Path, target: str) -> dict:
+ return {"PLAYWRIGHT_BROWSERS_PATH": str(entry.parent)}
+
+
+@register
+class Chromium(PlaywrightBrowser):
+ name = "chromium"
+ _FILE = "chrome"
+ _MIRROR_FILE = "chromium"
+
+
+@register
+class ChromiumHeadlessShell(PlaywrightBrowser):
+ name = "chromium-headless-shell"
+ _FILE = "chrome-headless-shell"
+ _MIRROR_FILE = "chromium-headless-shell"
+
+
+class LlamaCpp(BinaryPackage):
+ """One llama.cpp backend build. Backends are dlopen'd plugins, so a
+ usable engine is one archive per (target, backend) — plus, for Windows
+ CUDA, the cudart archive: end users have no CUDA toolkit, and Windows
+ resolves a DLL from the loading executable's own directory, so those
+ DLLs must land beside llama-server.exe rather than in a second entry.
+
+ Backend is a HARDWARE choice, not a target, so each backend is its own
+ optional package and the runtime asks for the one this machine can
+ use. Version is llama.cpp's rolling release tag without the `b`.
+ """
+
+ optional = True
+ on_path = False
+ binary_rel = {"win32": "llama-server.exe", "posix": "llama-server"}
+ flatten = False
+ # --version is llama-server's liveness proof AND the check that the
+ # backend's shared libraries resolve: a CUDA build with no cudart
+ # beside it fails here rather than at first chat.
+ probe_cwd = True
+
+ backend: str = ""
+ # Release-asset infix per target, or absent where upstream ships none.
+ assets: dict[str, str] = {}
+
+ @property
+ def gaps(self) -> dict[str, str]: # type: ignore[override]
+ return {
+ target: f"llama.cpp publishes no {self.backend} build for {target}"
+ for target in ALL_TARGETS
+ if target not in self.assets
+ }
+
+ def _asset_names(self, version: str, target: str) -> list[str]:
+ ext = "zip" if target.startswith("win32") else "tar.gz"
+ return [f"llama-b{version}-bin-{self.assets[target]}.{ext}"]
+
+ def fetch_urls(self, version: str, target: str) -> list[str]:
+ return [
+ f"https://github.com/ggml-org/llama.cpp/releases/download/b{version}/{asset}"
+ for asset in self._asset_names(version, target)
+ ]
+
+ def fetch_url(self, version: str, target: str) -> str:
+ return self.fetch_urls(version, target)[0]
+
+ def known_sha256(self, version: str, url: str) -> Optional[str]:
+ """GitHub's release API serves every asset's digest, so pinning a
+ 280 MB engine costs one API call instead of the download."""
+ return _github_release_digests("ggml-org/llama.cpp", f"b{version}").get(
+ url.rsplit("/", 1)[-1]
+ )
+
+ def stage(self, store: Store, staged: Path, version: str, target: str) -> None:
+ """Some archives nest the binaries under build/bin; hoist them so
+ binary_rel is one path for every target."""
+ if (staged / self.binary(staged, target).name).is_file():
+ return
+ found = sorted(staged.rglob(self.binary(staged, target).name))
+ if not found:
+ raise InstallError(self.name, "archive contains no llama-server")
+ merge_tree(found[0].parent, staged)
+
+
+def _github_release_digests(repo: str, tag: str) -> dict[str, str]:
+ import json
+ import urllib.request
+
+ cached = _release_digest_cache.get((repo, tag))
+ if cached is not None:
+ return cached
+ url = f"https://api.github.com/repos/{repo}/releases/tags/{tag}"
+ try:
+ with urllib.request.urlopen(
+ urllib.request.Request(url, headers={"User-Agent": "hermes-pm"}),
+ timeout=120,
+ ) as resp:
+ release = json.load(resp)
+ except Exception:
+ return {}
+ digests = {}
+ for asset in release.get("assets", []):
+ digest = (asset.get("digest") or "").partition("sha256:")[2]
+ if digest:
+ digests[asset["name"]] = digest
+ _release_digest_cache[(repo, tag)] = digests
+ return digests
+
+
+_release_digest_cache: dict[tuple, dict] = {}
+
+
+@register
+class LlamaCppCuda(LlamaCpp):
+ """Windows only: upstream publishes no prebuilt Linux CUDA archive at
+ current tags, so NVIDIA Linux users run the vulkan build."""
+
+ name = "llamacpp-cuda"
+ backend = "cuda"
+ # CUDA 13.3 verified against 13.1/13.2 drivers; arm64 prebuilts landed
+ # on 13.4 (the only CUDA line upstream builds for win-arm64).
+ assets = {
+ "win32-x64": "win-cuda-13.3-x64",
+ "win32-arm64": "win-cuda-13.4-arm64",
+ }
+ _CUDART = {"win32-x64": "13.3-x64", "win32-arm64": "13.4-arm64"}
+
+ def _asset_names(self, version: str, target: str) -> list[str]:
+ return super()._asset_names(version, target) + [
+ f"cudart-llama-bin-win-cuda-{self._CUDART[target]}.zip"
+ ]
+
+
+@register
+class LlamaCppVulkan(LlamaCpp):
+ name = "llamacpp-vulkan"
+ backend = "vulkan"
+ assets = {
+ "win32-x64": "win-vulkan-x64",
+ "linux-x64": "ubuntu-vulkan-x64",
+ "linux-arm64": "ubuntu-vulkan-arm64",
+ }
+
+
+@register
+class LlamaCppMetal(LlamaCpp):
+ """macOS archives are unified builds with Metal compiled in."""
+
+ name = "llamacpp-metal"
+ backend = "metal"
+ assets = {"darwin-x64": "macos-x64", "darwin-arm64": "macos-arm64"}
+
+
+@register
+class LlamaCppCpu(LlamaCpp):
+ name = "llamacpp-cpu"
+ backend = "cpu"
+ assets = {
+ "win32-x64": "win-cpu-x64",
+ "win32-arm64": "win-cpu-arm64",
+ "linux-x64": "ubuntu-x64",
+ "linux-arm64": "ubuntu-arm64",
+ "darwin-x64": "macos-x64",
+ "darwin-arm64": "macos-arm64",
+ }
diff --cc pm/store.py
index 9a467bf825f,00000000000..4efbfc1cec9
mode 100644,000000..100644
--- a/pm/store.py
+++ b/pm/store.py
@@@ -1,344 -1,0 +1,349 @@@
+"""Machine-wide byte store: download, verify, extract, publish atomically."""
+
+from __future__ import annotations
+
+import os
+import platform
+import shutil
+import stat
+import sys
+import tempfile
+import time
+from contextlib import contextmanager
+from pathlib import Path
+
+_UA = {"User-Agent": "hermes-pm"}
+
+
+ALL_TARGETS = (
+ "win32-x64",
+ "win32-arm64",
+ "linux-x64",
+ "linux-arm64",
+ "darwin-x64",
+ "darwin-arm64",
+)
+
+
+def _native_machine() -> str:
+ """The MACHINE's architecture, not the interpreter's. An x64 python on
+ Windows-on-ARM reports AMD64 — staging a payload for the wrong target.
+ IsWow64Process2 reports the real machine regardless of emulation."""
+ if sys.platform.startswith("win"):
+ try:
+ import ctypes
+ from ctypes import wintypes
+
+ k32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ k32.GetCurrentProcess.restype = wintypes.HANDLE
+ k32.IsWow64Process2.argtypes = [
+ wintypes.HANDLE,
+ ctypes.POINTER(ctypes.c_ushort),
+ ctypes.POINTER(ctypes.c_ushort),
+ ]
+ k32.IsWow64Process2.restype = wintypes.BOOL
+ process_machine = ctypes.c_ushort()
+ native_machine = ctypes.c_ushort()
+ if k32.IsWow64Process2(
+ k32.GetCurrentProcess(),
+ ctypes.byref(process_machine),
+ ctypes.byref(native_machine),
+ ):
+ if native_machine.value == 0xAA64:
+ return "arm64"
+ if native_machine.value == 0x8664:
+ return "x86_64"
+ except Exception:
+ pass
+ # Pre-IsWow64Process2 hosts: WOW64 exposes the real machine here.
+ wow = os.environ.get("PROCESSOR_ARCHITEW6432", "")
+ if wow.upper() == "ARM64":
+ return "arm64"
+ if wow.upper() == "AMD64":
+ return "x86_64"
+ return platform.machine().lower()
+
+
+def current_target() -> str:
+ machine = _native_machine()
+ if machine in ("arm64", "aarch64"):
+ arch = "arm64"
+ elif machine in ("x86_64", "amd64", "x64"):
+ arch = "x64"
+ else:
+ raise RuntimeError(f"unsupported architecture: {platform.machine()}")
+ if sys.platform.startswith("win"):
+ return f"win32-{arch}"
+ if sys.platform == "darwin":
+ return f"darwin-{arch}"
+ return f"linux-{arch}"
+
+
+def sha256_file(path: Path) -> str:
+ import hashlib
+
+ digest = hashlib.sha256()
+ with open(path, "rb") as f:
+ for block in iter(lambda: f.read(1024 * 1024), b""):
+ digest.update(block)
+ return digest.hexdigest()
+
+
+def hash_url(url: str) -> str:
+ """sha256 of a url's content, streamed. `pm lock` uses this to pin."""
+ import hashlib
+ import urllib.request
+
+ from pm.downloader import _OPENER
+
+ digest = hashlib.sha256()
+ with _OPENER.open(
+ urllib.request.Request(url, headers=_UA), timeout=600
+ ) as resp:
+ for block in iter(lambda: resp.read(1024 * 1024), b""):
+ digest.update(block)
+ return digest.hexdigest()
+
+
+def download(url: str, dest: Path, sha256: str, progress=None) -> Path:
+ """Fetch url into dest dir, hash-verified, via the resumable downloader.
+ The digest is proven before the caller ever sees the file.
+ ``progress(done, total)`` ticks per chunk — a several-hundred-MB engine
+ archive on a slow line must never look hung. Partial state lives in the
+ store's managed partials area (outside scratch, keyed by sha256(url)), so
+ an interrupted = failed fetch resumes on the next call instead of
+ re-fetching the whole archive. Non-https/non-loopback urls are refused by
+ Download itself (ValueError)."""
+ from pm.downloader import Download, Source
+
+ dest.mkdir(parents=True, exist_ok=True)
+ archive = dest / url.rsplit("/", 1)[-1]
+ p = (lambda d, t, r: progress(d, t)) if progress is not None else None
+ Download([Source(url, archive, sha256)]).run(progress=p)
+ return archive
+
+
+def extract(archive: Path, dest: Path) -> None:
+ import tarfile
+
+ shutil.rmtree(dest, ignore_errors=True)
+ dest.mkdir(parents=True, exist_ok=True)
+ name = archive.name.lower()
+ if name.endswith((".tar.gz", ".tgz", ".tar.xz", ".txz", ".tar.bz2")):
+ with tarfile.open(archive) as tf:
+ tf.extractall(dest, filter="data")
+ elif name.endswith(".zip"):
+ _extract_zip(archive, dest)
+ else:
+ raise ValueError(f"unsupported archive: {archive.name}")
+
+
+def _extract_zip(archive: Path, dest: Path) -> None:
+ import zipfile
+
+ with zipfile.ZipFile(archive) as zf:
+ symlinks: list[tuple] = []
+ for info in zf.infolist():
+ mode = info.external_attr >> 16
+ if stat.S_ISLNK(mode):
+ symlinks.append((info, zf.read(info).decode("utf-8")))
+ continue
+ written = Path(zf.extract(info, dest))
+ if mode & 0o111 and written.is_file():
+ written.chmod(mode & 0o777)
+ for info, target in symlinks:
+ _zip_symlink(info.filename, target, dest)
+
+
+def _zip_symlink(member: str, target: str, dest: Path) -> None:
+ root = dest.resolve()
+ link = (root / member).resolve()
+ if not link.is_relative_to(root):
+ return
+ if Path(target).is_absolute():
+ return
+ resolved = (link.parent / target).resolve()
+ if not resolved.is_relative_to(root):
+ return
+ link.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ link.symlink_to(target)
+ except OSError:
+ link.write_text(target, encoding="utf-8")
+
+
+def flatten_single_dir(dest: Path) -> None:
+ """Hoist a lone top-level dir's contents unless it IS the layout
+ (bin/, cmd/, lib/...). Refuses on name collisions."""
+ keep = {"bin", "cmd", "lib", "libexec", "share", "etc", "usr"}
+ entries = list(dest.iterdir())
+ if len(entries) != 1 or not entries[0].is_dir() or entries[0].name in keep:
+ return
+ inner = entries[0]
+ for item in list(inner.iterdir()):
+ target = dest / item.name
+ if target.exists():
+ return
+ item.rename(target)
+ inner.rmdir()
+
+
+def merge_tree(src: Path, dst: Path) -> None:
+ """Move src's tree into dst, keeping both layouts. A file present in
+ both is unresolvable — two archives disagreeing about one file cannot
+ be settled by extraction order, so it fails loudly instead."""
+ for item in sorted(src.rglob("*")):
+ if item.is_dir():
+ continue
+ rel = item.relative_to(src)
+ target = dst / rel
+ if target.exists():
+ raise FileExistsError(f"archives disagree about {rel}")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ item.replace(target)
+
+
+def tree_digest(root: Path) -> str:
+ """Deterministic sha256 over a directory tree: walk every file, sort
+ by posix relpath, hash `relpath\\0<content>` per entry. No mtimes, no
+ mode bits. Symlinks contribute their LINK TARGET TEXT (os.readlink),
+ not the target's bytes — the link is the data. Directory symlinks are
- not followed."""
++ not followed.
++
++ ``__pycache__`` directories are skipped: CPython writes .pyc caches
++ into them the first time the staged interpreter runs (uv venv/uv sync
++ in a bundle build; first boot of a shipped app), so they are runtime
++ state, not package bytes — the digest is over what pm published."""
+ import hashlib
+
+ files: list[tuple[str, Path]] = []
+ for dirpath, dirnames, filenames in os.walk(root):
- dirnames.sort()
++ dirnames[:] = [d for d in sorted(dirnames) if d != "__pycache__"]
+ for fname in filenames:
+ path = Path(dirpath) / fname
+ files.append((path.relative_to(root).as_posix(), path))
+ files.sort(key=lambda item: item[0])
+
+ digest = hashlib.sha256()
+ for rel, path in files:
+ digest.update(rel.encode("utf-8"))
+ digest.update(b"\0")
+ if path.is_symlink():
+ digest.update(os.readlink(path).encode("utf-8"))
+ else:
+ with open(path, "rb") as f:
+ for block in iter(lambda: f.read(1024 * 1024), b""):
+ digest.update(block)
+ return digest.hexdigest()
+
+
+class Store:
+ """One directory of immutable published entries plus a scratch area.
+ Downloads are entries too, keyed by hash, so rebuilds never re-fetch."""
+
+ def __init__(self, root: Path):
+ self.root = root
+
+ def entry(self, name: str) -> Path:
+ return self.root / name
+
+ def published(self, name: str) -> bool:
+ return self.entry(name).is_dir()
+
+ def fetch(self, url: str, sha256: str, scratch: Path, progress=None) -> Path:
+ """Verified archive for url, from the store if already fetched.
+ The cache entry is `fetch-<full sha256>/` holding the single file.
+ The cached file is RE-HASHED against the requested digest before
+ it is returned: the cache lives on a mutable disk, so trust is
+ re-proven, not assumed. On mismatch the entry is deleted and the
+ archive re-downloaded (the 100MB+ re-hash is install-time only)."""
+ entry_name = f"fetch-{sha256}"
+ entry = self.entry(entry_name)
+ if entry.is_dir():
+ files = [p for p in entry.iterdir() if p.is_file()]
+ if len(files) == 1 and sha256_file(files[0]) == sha256:
+ return files[0]
+ shutil.rmtree(entry, ignore_errors=True)
+ archive = download(url, scratch, sha256, progress=progress)
+ staged = scratch / entry_name
+ staged.mkdir(parents=True)
+ archive.rename(staged / archive.name)
+ published = self.publish(staged, entry_name)
+ return published / archive.name
+
+ @contextmanager
+ def scratch(self):
+ self.root.mkdir(parents=True, exist_ok=True)
+ path = Path(tempfile.mkdtemp(prefix=".staging-", dir=self.root))
+ try:
+ yield path
+ finally:
+ shutil.rmtree(path, ignore_errors=True)
+
+ def publish(self, staged: Path, name: str) -> Path:
+ """Atomic rename into place, retried for Windows file-lock holds
+ (Defender, indexers). A concurrent winner's entry is kept."""
+ target = self.entry(name)
+ delay = 0.5
+ for _ in range(5):
+ try:
+ os.replace(staged, target)
+ return target
+ except OSError:
+ if target.is_dir():
+ return target
+ time.sleep(delay)
+ delay *= 2
+ try:
+ os.replace(staged, target)
+ except OSError:
+ if not target.is_dir():
+ raise
+ return target
+
+ @contextmanager
+ def install_lock(self):
+ """Single-flight advisory lock for all installs on this machine.
+ Blocks until acquired: installs legitimately hold it for minutes
+ (browser downloads), so the Windows rung polls LK_NBLCK instead of
+ msvcrt's 10-second LK_LOCK ladder."""
+ self.root.mkdir(parents=True, exist_ok=True)
+ lock_path = self.root / ".install.lock"
+ handle = open(lock_path, "a+b")
+ try:
+ if sys.platform.startswith("win"):
+ import msvcrt
+
+ handle.seek(0)
+ waited = 0
+ while True:
+ try:
+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
+ break
+ except OSError:
+ if waited == 5:
+ print("waiting for another hermes install to finish...")
+ time.sleep(1)
+ waited += 1
+ else:
+ import fcntl
+
+ try:
+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError:
+ print("waiting for another hermes install to finish...")
+ fcntl.flock(handle, fcntl.LOCK_EX)
+ yield
+ finally:
+ try:
+ if sys.platform.startswith("win"):
+ import msvcrt
+
+ handle.seek(0)
+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
+ else:
+ import fcntl
+
+ fcntl.flock(handle, fcntl.LOCK_UN)
+ finally:
+ handle.close()
diff --cc pyproject.toml
index 1ce949d5511,202d44b61df..99c6ed61071
--- a/pyproject.toml
+++ b/pyproject.toml
@@@ -203,7 -200,7 +203,20 @@@ dev = ["debugpy==1.8.20", "pytest==9.1.
messaging = ["python-telegram-bot[webhooks]==22.8", "discord.py[voice]==2.7.1", "aiohttp==3.14.3", "brotlicffi==1.2.0.1", "slack-bolt==1.30.0", "slack-sdk==3.43.0", "qrcode==7.4.2"] # aiohttp 3.14.3: prior CVEs + GHSA-cq5v-8q36-5273/GHSA-mfx4-hv73-q22v/GHSA-mq44-7p77-q5h7
cron = [] # croniter is now a core dependency; this extra kept for back-compat
slack = ["slack-bolt==1.30.0", "slack-sdk==3.43.0", "aiohttp==3.14.3"]
--matrix = ["mautrix[encryption]==0.21.1", "aiosqlite==0.22.1", "asyncpg==0.31.0", "aiohttp-socks==0.11.0", "aiohttp==3.14.3"] # aiohttp 3.14.3: prior CVEs + GHSA-cq5v-8q36-5273/GHSA-mfx4-hv73-q22v/GHSA-mq44-7p77-q5h7 (mautrix/aiohttp-socks only cap aiohttp<4 / >=3.10, so pin the patched floor directly)
++# Matrix gateway deps. `mautrix[encryption]` pulls `python-olm`, whose
++# vendored libolm (archived 2023) cannot build on Windows or modern macOS:
++# no wheels for those targets AND the sdist fails to compile on current
++# clang/MSVC (olm/list.hh const-iterator error) and on CMake >= 4. It is
++# linux-only — gate the whole extra so `uv sync --all-extras` (the bundle
++# build) doesn't try to build python-olm on the win/darwin lanes. The
++# matrix adapter degrades gracefully without mautrix (import stubs).
++matrix = [
++ "mautrix[encryption]==0.21.1; sys_platform == 'linux'",
++ "aiosqlite==0.22.1; sys_platform == 'linux'",
++ "asyncpg==0.31.0; sys_platform == 'linux'",
++ "aiohttp-socks==0.11.0; sys_platform == 'linux'",
++ "aiohttp==3.14.3; sys_platform == 'linux'",
++] # aiohttp 3.14.3: prior CVEs + GHSA-cq5v-8q36-5273/GHSA-mfx4-hv73-q22v/GHSA-mq44-7p77-q5h7 (mautrix/aiohttp-socks only cap aiohttp<4 / >=3.10, so pin the patched floor directly)
# WeCom callback-mode adapter — parses untrusted XML POST bodies from
# WeCom-controlled callback endpoints, so we use defusedxml (drop-in
# replacement for stdlib xml.etree.ElementTree) to block billion-laughs
@@@ -213,7 -210,7 +226,11 @@@ wecom = ["defusedxml==0.7.1"
tts-premium = ["elevenlabs==1.59.0"]
voice = [
# Local STT pulls in wheel-only transitive deps (ctranslate2, onnxruntime).
-- "faster-whisper==1.2.1",
++ # faster-whisper's closure is prebuilt-only and missing pieces on two
++ # targets: ctranslate2 has no win_arm64 wheel/sdist (win32-arm64), and
++ # onnxruntime has no darwin-x64 wheel/sdist (darwin-x64). Gate the local
++ # STT path off both; sounddevice/numpy still ship.
++ "faster-whisper==1.2.1; (platform_machine != 'ARM64' or sys_platform != 'win32') and (platform_machine != 'x86_64' or platform_system != 'Darwin')",
"sounddevice==0.5.5",
"numpy==2.4.3",
]
@@@ -224,12 -221,9 +241,15 @@@
# [wake]+[voice] so the ear works instantly; CLI-only installs lazy-install on
# first /wake; mirrored in tools/lazy_deps.py.
wake = [
-- "openwakeword==0.6.0",
-- "onnxruntime==1.27.0",
- "sherpa-onnx==1.13.4",
++ # onnxruntime has no darwin-x64 wheel and no sdist (prebuilt only), so
++ # openwakeword (which hard-requires onnxruntime) cannot install there.
++ # sherpa-onnx / sentencepiece / pvporcupine / sounddevice / numpy ship.
++ "openwakeword==0.6.0; platform_machine != 'x86_64' or platform_system != 'Darwin'",
++ "onnxruntime==1.27.0; platform_machine != 'x86_64' or platform_system != 'Darwin'",
+ # sherpa-onnx ships win_amd64/win32 wheels only (its kaldi-decoder C++ has
+ # no win_arm64 build), so win32-arm64 would build the sdist and fail. Gate
+ # it off there like faster-whisper; the other engines still ship.
+ "sherpa-onnx==1.13.4; platform_machine != 'ARM64' or sys_platform != 'win32'",
"sentencepiece==0.2.2",
"pvporcupine==4.0.3",
"sounddevice==0.5.5",
@@@ -237,37 -231,10 +257,38 @@@
# openWakeWord's onnx embedding model scores near-zero on macOS ARM64
# (dscripka/openWakeWord#336), so the wake word runs on tflite there.
# Upstream declares tflite-runtime for Linux only; ai-edge-litert is the
-- # macOS equivalent, bridged in tools/wake_word.py.
-- "ai-edge-litert==2.1.6; platform_system == 'Darwin'",
++ # macOS ARM64 equivalent (no darwin-x64 wheel, no sdist), bridged in
++ # tools/wake_word.py.
++ "ai-edge-litert==2.1.6; platform_system == 'Darwin' and platform_machine == 'arm64'",
]
honcho = ["honcho-ai==2.2.0"]
+# Platform sub-extras / alias extras — declared so pm.extras.ANCHORS names
+# only real extras (contract: tests/pm/test_extras.py). Each is
+# lazy-installed at first use via pm.ensure_import(name) and therefore
+# deliberately NOT in [all] (see tests/test_project_metadata.py's
+# lazy_covered_extras list — keep that list in sync when adding here).
+telegram = ["python-telegram-bot[webhooks]==22.8"]
+discord = ["discord.py[voice]==2.7.1"]
+# stt-whisper + audio-io compose [voice] (faster-whisper / sounddevice / numpy).
- stt-whisper = ["faster-whisper==1.2.1"]
++stt-whisper = ["faster-whisper==1.2.1; (platform_machine != 'ARM64' or sys_platform != 'win32') and (platform_machine != 'x86_64' or platform_system != 'Darwin')"]
+audio-io = ["sounddevice==0.5.5", "numpy==2.4.3"]
+# WeChat voice decode (tools/transcription_tools.py self-heal path).
+silk = ["pilk==0.2.4"]
+# Wake-engine sub-extras — lazy per-engine installs so a user who only wants
+# sherpa-onnx doesn't pull the whole [wake] bundle. Pins match [wake].
- wake-openwakeword = ["openwakeword==0.6.0", "onnxruntime==1.27.0"]
++wake-openwakeword = ["openwakeword==0.6.0; platform_machine != 'x86_64' or platform_system != 'Darwin'", "onnxruntime==1.27.0; platform_machine != 'x86_64' or platform_system != 'Darwin'"]
+wake-sherpa = ["sherpa-onnx==1.13.4; platform_machine != 'ARM64' or sys_platform != 'win32'"]
+wake-porcupine = ["pvporcupine==4.0.3"]
+# macOS tflite bridge (tools/wake_word.py); same marker policy as [wake].
- wake-tflite = ["ai-edge-litert==2.1.6; platform_system == 'Darwin'"]
++wake-tflite = ["ai-edge-litert==2.1.6; platform_system == 'Darwin' and platform_machine == 'arm64'"]
+# Google Chat service account push (gateway/platforms/google_chat) — pubsub
+# subscriber for the Chat API's Cloud Pub/Sub delivery.
+google-chat = ["google-cloud-pubsub==2.39.2"]
+# Document extraction (read_file anydoc converter self-heal) — core already
+# bundles firecrawl-anydoc==0.2.4; the extra exists so a lean/broken install
+# can re-sync exactly the pin from core.
+doc-extract = ["firecrawl-anydoc==0.2.4"]
+trace-upload = ["huggingface-hub==1.24.0"]
# Cloud memory providers — opt-in, lazy-installed via tools/lazy_deps.py
# (memory.supermemory / memory.mem0) at first use. Exact pins MUST match the
# LAZY_DEPS pins (enforced by tests/test_project_metadata.py). Deliberately
@@@ -466,7 -433,7 +487,11 @@@ exclude-newer = "14 days
# firecrawl-anydoc: same exact-pin shape (==0.2.4, hosted-OCR wiring PR).
# 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.
--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: 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.setuptools]
# Top-level single-file modules (not packages). Without this, uv2nix's
diff --cc scripts/aa_quality_sync.py
index 00000000000,66e61c7f7d1..ca6b1e9dd44
mode 000000,100644..100644
--- a/scripts/aa_quality_sync.py
+++ b/scripts/aa_quality_sync.py
@@@ -1,0 -1,94 +1,94 @@@
+ """Propose catalog quality updates from Artificial Analysis.
+
+ Authoring-time helper — NEVER called at runtime (their terms forbid
+ client-side keys, the fleet would burn the rate limit, and a
+ recommendation must not change because a third-party endpoint
+ hiccuped). Run it when adding a model or refreshing the ordering;
+ review the printed diff and edit catalog.json yourself. The script
+ proposes, the commit decides.
+
+ The catalog's `quality` stays OUR field: AA-informed where they cover a
+ model, editorially set where they don't (day-0 releases lag their evals;
+ some entries never appear). AA's Intelligence Index grades the
+ full-precision cloud model, not our Q4 build — fine for ordering, never
+ for display.
+
+ Usage:
+ export AA_API_KEY=... # from https://artificialanalysis.ai (free tier)
+ python scripts/aa_quality_sync.py
+
+ Attribution: scores by Artificial Analysis (https://artificialanalysis.ai).
+ """
+
+ from __future__ import annotations
+
+ import json
+ import os
+ import sys
+ import urllib.request
+ from pathlib import Path
+
+ REPO_ROOT = Path(__file__).resolve().parent.parent
+ CATALOG_PATH = REPO_ROOT / "hermes_cli" / "local_runtime" / "catalog.json"
+ AA_URL = "https://artificialanalysis.ai/api/v2/data/llms/models"
+
+ # Catalog entry id -> AA slug. Hand-maintained: AA's naming rarely matches
+ # HF repo names, and a wrong match silently mis-ranks a model. An entry
+ # absent here (or mapped to None) is editorial-only and never overwritten.
+ AA_SLUG_BY_ENTRY = {
+ "qwen3.8-27b": "qwen3-8-27b",
+ "qwen3.8-flash-next": "qwen3-8-flash-next",
+ "qwen3.6-35b-a3b": "qwen3-6-35b-a3b",
+ "deepseek-v4-flash": "deepseek-v4-flash",
+ }
+
+
+ def fetch_aa_models(api_key: str) -> dict[str, dict]:
+ req = urllib.request.Request(AA_URL, headers={"x-api-key": api_key})
+ with urllib.request.urlopen(req, timeout=30) as r:
+ doc = json.load(r)
+ return {m["slug"]: m for m in doc.get("data", [])}
+
+
+ def main() -> int:
+ api_key = os.environ.get("AA_API_KEY", "").strip()
+ if not api_key:
+ print("AA_API_KEY not set — create a free key at "
+ "https://artificialanalysis.ai and export it.", file=sys.stderr)
+ return 2
+
- catalog = json.loads(CATALOG_PATH.read_text(encoding="utf-8"))
++ catalog = json.loads(CATALOG_PATH.read_text(encoding="utf-8-sig"))
+ aa = fetch_aa_models(api_key)
+
+ print(f"{'entry':24s} {'catalog q':>9s} {'AA index':>9s} note")
+ print("-" * 70)
+ for model in catalog["models"]:
+ entry_id = model["id"]
+ current = model.get("quality", 0)
+ slug = AA_SLUG_BY_ENTRY.get(entry_id)
+ if not slug:
+ print(f"{entry_id:24s} {current:>9d} {'—':>9s} editorial only (no AA mapping)")
+ continue
+ hit = aa.get(slug)
+ if hit is None:
+ print(f"{entry_id:24s} {current:>9d} {'—':>9s} not in AA data (slug {slug!r})")
+ continue
+ index = (hit.get("evaluations") or {}).get(
+ "artificial_analysis_intelligence_index")
+ if index is None:
+ print(f"{entry_id:24s} {current:>9d} {'—':>9s} AA row lacks the index")
+ continue
+ proposed = round(float(index))
+ marker = "" if proposed == current else " <-- proposes change"
+ print(f"{entry_id:24s} {current:>9d} {proposed:>9d}{marker}")
+
+ print("\nReview against the decision table before editing: a quality "
+ "change that flips cells in tests/hermes_cli/"
+ "test_local_recommendation.py is the actual decision being made.")
+ print("Attribution: scores by Artificial Analysis "
+ "(https://artificialanalysis.ai).")
+ return 0
+
+
+ if __name__ == "__main__":
+ sys.exit(main())
diff --cc scripts/install.ps1
index a5396448399,8ac4df07902..f3c684b716f
--- a/scripts/install.ps1
+++ b/scripts/install.ps1
@@@ -166,200 -535,4478 +166,214 @@@ function Ensure-Git
return $true
}
-function Write-NpmDebugLogTail {
- # On failure npm prints only a terse summary to stdout/stderr; the real
- # evidence (postinstall script stderr like Electron's install.js, network
- # traces, EBUSY retries) lives in npm's own debug log under
- # <npm-cache>\_logs\<timestamp>-debug-0.log. The bootstrap installer's
- # streaming sink only captures what WE emit, so on any npm failure this
- # helper locates that debug log and replays its tail into our output
- # stream -- making the bootstrap log a self-contained diagnosis instead
- # of "exit 1, details in a file on a VM nobody can reach".
- param(
- [string]$NpmOutput,
- [int]$TailLines = 200
- )
- $logPath = $null
- # Preferred: npm names the exact file in its failure summary.
- if ($NpmOutput -and $NpmOutput -match "A complete log of this run can be found in:\s*(?<path>[^\r\n]+)") {
- $candidate = $Matches['path'].Trim()
- if (Test-Path -LiteralPath $candidate) { $logPath = $candidate }
- }
- # Fallback (covers --silent runs, truncated output): newest debug log in
- # npm's cache _logs directory.
- if (-not $logPath) {
- try {
- $npm = Resolve-NpmCmd
- if ($npm) {
- $prevEAPLocal = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- $cacheDir = (& $npm config get cache 2>$null | Select-Object -Last 1)
- $ErrorActionPreference = $prevEAPLocal
- if ($cacheDir) {
- $logsDir = Join-Path ("$cacheDir").Trim() "_logs"
- if (Test-Path -LiteralPath $logsDir) {
- $newest = Get-ChildItem -LiteralPath $logsDir -Filter "*-debug-*.log" -ErrorAction SilentlyContinue |
- Sort-Object LastWriteTime -Descending | Select-Object -First 1
- if ($newest) { $logPath = $newest.FullName }
- }
- }
- }
- } catch { }
- }
- if (-not $logPath) {
- Write-Warn "npm debug log could not be located -- no further npm detail available"
- return
- }
- $tail = $null
- try {
- $tail = Get-Content -LiteralPath $logPath -Tail $TailLines -ErrorAction Stop
- } catch {
- Write-Warn "Could not read npm debug log ${logPath}: $($_.Exception.Message)"
- return
- }
- Write-Warn "---- npm debug log: last $TailLines lines of $logPath ----"
- foreach ($line in $tail) { Write-Host " $line" -ForegroundColor DarkGray }
- Write-Warn "---- end npm debug log ----"
-}
-
-# --- Ensure-mode helpers ---
+function Log([string]$msg) { Write-Host "[hermes] $msg" -ForegroundColor Blue }
+function Fail([string]$msg) { Write-Host "[hermes] $msg" -ForegroundColor Red; exit 1 }
-function Resolve-NpmCmd {
- $npmCmd = Get-Command npm -ErrorAction SilentlyContinue
- if (-not $npmCmd) { return $null }
- $npmExe = $npmCmd.Source
- if ($npmExe -like "*.ps1") {
- $npmCmdSibling = Join-Path (Split-Path $npmExe -Parent) "npm.cmd"
- if (Test-Path $npmCmdSibling) { return $npmCmdSibling }
- }
- return $npmExe
+function Emit-Frame([bool]$ok, [string]$name, [bool]$skipped, [string]$reason = "") {
+ $frame = [ordered]@{ ok = $ok; stage = $name; skipped = $skipped }
+ if ($reason) { $frame.reason = $reason }
+ $frame | ConvertTo-Json -Compress | Write-Output
}
-function Find-SystemBrowser {
- # Honor ONLY an explicit, user-set AGENT_BROWSER_EXECUTABLE_PATH override.
- #
- # We no longer scan well-known install locations for a system browser.
- # Auto-detection silently bound the install to an arbitrary binary instead
- # of the bundled Playwright Chromium, which made the browser tool behave
- # differently across hosts (and, on Linux, picked up a sandboxed Snap
- # Chromium that hangs every browser_navigate). Every install now uses the
- # bundled Chromium unless the user explicitly points elsewhere.
- $override = $env:AGENT_BROWSER_EXECUTABLE_PATH
- if ([string]::IsNullOrWhiteSpace($override)) { return $null }
- if (Test-Path $override) { return $override }
- return $null
+$Stages = @(
+ @{ name = "prerequisites"; title = "System prerequisites"; category = "runtime"; needs_user_input = $false },
+ @{ name = "repository"; title = "Download Hermes Agent"; category = "runtime"; needs_user_input = $false },
+ @{ name = "venv"; title = "Create Python environment"; category = "runtime"; needs_user_input = $false },
+ @{ name = "python-deps"; title = "Install Python dependencies"; category = "runtime"; needs_user_input = $false },
+ @{ name = "node-deps"; title = "Install tool dependencies"; category = "runtime"; needs_user_input = $false },
+ @{ name = "path"; title = "Install hermes command"; category = "runtime"; needs_user_input = $false },
+ @{ name = "config"; title = "Prepare config and skills"; category = "configuration"; needs_user_input = $false },
+ @{ name = "setup"; title = "Configure API keys and settings"; category = "configuration"; needs_user_input = $true },
+ @{ name = "gateway"; title = "Configure gateway service"; category = "configuration"; needs_user_input = $true }
+)
+if ($IncludeDesktop) {
+ $Stages += @{ name = "desktop"; title = "Build desktop app"; category = "runtime"; needs_user_input = $false }
}
+$Stages += @{ name = "complete"; title = "Finish install"; category = "runtime"; needs_user_input = $false }
-function Write-BrowserEnv {
- param([string]$BrowserPath)
- if (-not (Test-Path $HermesHome)) {
- New-Item -ItemType Directory -Force -Path $HermesHome | Out-Null
+function Stage-Prerequisites {
+ if (-not (Ensure-Git)) {
+ Fail "git is required. Install Git for Windows: https://git-scm.com/download/win"
}
- $envFile = Join-Path $HermesHome ".env"
- if (-not (Test-Path $envFile)) {
- Set-Content -Path $envFile -Value "AGENT_BROWSER_EXECUTABLE_PATH=$BrowserPath" -Encoding UTF8
- return
- }
- $content = Get-Content $envFile -Raw -ErrorAction SilentlyContinue
- if ($content -and $content -match "AGENT_BROWSER_EXECUTABLE_PATH=") { return }
- Add-Content -Path $envFile -Value "AGENT_BROWSER_EXECUTABLE_PATH=$BrowserPath" -Encoding UTF8
+ Log "prerequisites ok (git)"
}
-function Install-AgentBrowser {
- $npm = Resolve-NpmCmd
- if (-not $npm) {
- Write-Err "npm not found -- install Node.js first"
- throw "npm not found"
- }
-
- # agent-browser itself is intentionally NOT installed here (#43564 /
- # PR #44772 review): it resolves lazily via `npx agent-browser` instead,
- # which every consumer (tools/browser_tool.py, `hermes update`'s npx
- # cache warm) already goes through. Eagerly npm-installing a second,
- # separately version-pinned copy here -- only reachable via this
- # explicit -Ensure browser fallback in the first place -- was redundant
- # complexity and an extra credential/supply-chain surface for a path
- # npx already covers.
- Write-Info "Installing camofox browser server..."
- $prefixDir = Join-Path $HermesHome "node"
- if (-not (Test-Path $prefixDir)) {
- New-Item -ItemType Directory -Path $prefixDir -Force | Out-Null
- }
- $npmLog = [System.IO.Path]::GetTempFileName()
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- & $npm install -g --prefix $prefixDir --silent --ignore-scripts "@askjo/camofox-browser@^1.5.2" 2>&1 | Tee-Object -FilePath $npmLog | Out-Null
- $npmExit = $LASTEXITCODE
- $ErrorActionPreference = $prevEAP
- if ($npmExit -ne 0) {
- $npmDetail = Get-Content $npmLog -Raw -ErrorAction SilentlyContinue
- Remove-Item $npmLog -Force -ErrorAction SilentlyContinue
- Write-Err "npm install -g failed (exit $npmExit): $npmDetail"
- Show-NpmCertHint $npmDetail | Out-Null
- # This install runs with --silent, so $npmDetail is often near-empty;
- # npm's debug log is the only place the real error survives.
- Write-NpmDebugLogTail -NpmOutput $npmDetail
- throw "npm install failed"
- }
- Remove-Item $npmLog -Force -ErrorAction SilentlyContinue
-
- $sysBrowser = Find-SystemBrowser
- if ($sysBrowser) {
- Write-BrowserEnv -BrowserPath $sysBrowser
- Write-Info "Explicit browser override set -- Chromium download will be skipped when agent-browser installs on demand"
+function Stage-Repository {
+ if (Test-Path (Join-Path $InstallDir ".git")) {
+ Log "updating $InstallDir"
+ git -C $InstallDir fetch origin $Branch; if ($LASTEXITCODE) { Fail "git fetch failed" }
+ git -C $InstallDir checkout $Branch; if ($LASTEXITCODE) { Fail "git checkout failed" }
+ git -C $InstallDir pull --ff-only origin $Branch
+ if ($LASTEXITCODE) { Log "not fast-forwardable; keeping local state" }
+ } else {
+ Log "cloning $RepoUrl ($Branch) into $InstallDir"
+ New-Item -ItemType Directory -Force -Path (Split-Path $InstallDir) | Out-Null
+ git clone --branch $Branch $RepoUrl $InstallDir; if ($LASTEXITCODE) { Fail "git clone failed" }
}
- Write-Success "Agent-browser ready"
-}
-
-# ============================================================================
-# Dependency checks
-# ============================================================================
-
-# Resolve the PowerShell host executable used to spawn child PowerShell
-# processes (the astral uv installer below). We must NOT hardcode the bare
-# name `powershell`: it names *Windows PowerShell* and only resolves when its
-# System32 directory is on PATH. When install.ps1 is run under PowerShell 7+
-# (`pwsh`) -- or any session where `powershell` isn't on PATH -- a bare
-# `powershell` spawn dies with "The term 'powershell' is not recognized",
-# aborting uv installation (field report: Windows install stuck, uv install
-# failed with exactly that message). Prefer the absolute path of the host we
-# are already running in (PATH-independent), then fall back to whichever of
-# powershell/pwsh is resolvable, and only then to the bare name.
-function Get-PowerShellHostExe {
- try {
- $hostExe = (Get-Process -Id $PID).Path
- if ($hostExe -and (Test-Path $hostExe)) {
- $leaf = Split-Path $hostExe -Leaf
- # Only trust the current host when it is a real PowerShell CLI
- # (not e.g. powershell_ise.exe or an embedded host that can't take
- # `-ExecutionPolicy`/`-Command`).
- if ($leaf -match '^(?i:powershell|pwsh)\.exe$') { return $hostExe }
- }
- } catch { }
- foreach ($candidate in @("powershell", "pwsh")) {
- $cmd = Get-Command $candidate -CommandType Application -ErrorAction SilentlyContinue |
- Select-Object -First 1
- if ($cmd -and $cmd.Source) { return $cmd.Source }
+ if ($Commit) {
+ git -C $InstallDir checkout $Commit; if ($LASTEXITCODE) { Fail "could not pin commit $Commit" }
}
- # Last-ditch: hand back the bare name so the spawn surfaces its own error.
- return "powershell"
}
-function Install-Uv {
- # Hermes owns its own uv at $HermesHome\bin\uv.exe. Always install there --
- # no PATH probing, no conda guards, no multi-location resolution chains.
- # The runtime update path (hermes_cli/managed_uv.py) looks in the same
- # place, so install.ps1 and `hermes update` stay in sync.
- $managedUv = Join-Path $HermesHome "bin\uv.exe"
-
- if (Test-Path $managedUv) {
- $script:UvCmd = $managedUv
- $version = & $managedUv --version
- Write-Success "Managed uv found ($version)"
- return $true
- }
-
- Write-Info "Installing managed uv into $HermesHome\bin ..."
- New-Item -ItemType Directory -Path (Join-Path $HermesHome "bin") -Force | Out-Null
-
- # UV_INSTALL_DIR tells the astral installer to place the binary
- # directly into $HermesHome\bin instead of ~/.local/bin.
- $prevEAP = $ErrorActionPreference
+function Stage-Venv {
+ $uv = Get-Uv
+ Log "creating venv"
+ Push-Location $InstallDir
+ & $uv venv --allow-existing venv; $code = $LASTEXITCODE
+ Pop-Location
+ if ($code) { Fail "uv venv failed" }
+}
+
- function Stage-PythonDeps {
++# Delegate the whole python+venv+tools install to pm: stage the pinned uv,
++# let uv run pm.cli, and pm provisions the interpreter, the venv (default
++# extras = [all], so it matches what `hermes update` force-syncs), and the
++# tool store — all hash-verified against pm/lock.json + uv.lock. install.ps1
++# no longer runs `uv sync` directly; pm is the single install authority
++# (the run_locked_uv_sync contract moved into pm/packages.py::uv_env).
++function Invoke-BootstrapPm {
+ $uv = Get-Uv
- Log "syncing python dependencies (uv sync --frozen)"
++ $lock = Get-Content (Join-Path $InstallDir "pm\lock.json") -Raw | ConvertFrom-Json
++ $pyPin = $lock.packages.python
++ $pyVersion = if ($pyPin) { ($pyPin.version -split '\+')[0] -replace '^(\d+\.\d+).*', '$1' } else { '3.11' }
++ Log "delegating python + venv + tools to pm (hash-verified via uv.lock)"
+ Push-Location $InstallDir
- $env:VIRTUAL_ENV = Join-Path $InstallDir "venv"
- & $uv sync --frozen --extra all --active; $code = $LASTEXITCODE
- Remove-Item Env:VIRTUAL_ENV -ErrorAction SilentlyContinue
- Pop-Location
- if ($code) { Fail "uv sync failed" }
+ try {
- $ErrorActionPreference = "Continue"
- $env:UV_INSTALL_DIR = Join-Path $HermesHome "bin"
- # Spawn via the resolved host exe (see Get-PowerShellHostExe) rather
- # than a bare `powershell`, which isn't guaranteed to be on PATH under
- # PowerShell 7 / pwsh-only setups.
- $psHostExe = Get-PowerShellHostExe
-
- # Rungs 1 + 2: run the uv installer -- astral.sh first, then the
- # byte-identical copy published on GitHub releases. Corporate
- # proxies and AV products frequently block astral.sh while
- # github.com is reachable (issue #69216), so a second source turns
- # a hard failure into a working install. Capture the installer
- # output (Tee-Object) instead of discarding it: when every source
- # fails, the real error (download blocked, AV quarantine,
- # permissions) must reach the user instead of only the generic
- # "installed but not found" message.
- $installerOutput = @()
- $astralOut = @()
- & $psHostExe -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex" 2>&1 | Tee-Object -Variable astralOut | Out-Null
- $installerOutput += "--- uv installer source: astral.sh ---"
- $installerOutput += @($astralOut | ForEach-Object { "$_" })
- if (Test-Path $managedUv) {
- Write-Info "uv installer succeeded via astral.sh"
- } else {
- Write-Info "astral.sh uv installer did not produce $managedUv; trying GitHub releases mirror ..."
- $ghOut = @()
- & $psHostExe -ExecutionPolicy ByPass -c "irm https://github.com/astral-sh/uv/releases/latest/download/uv-installer.ps1 | iex" 2>&1 | Tee-Object -Variable ghOut | Out-Null
- $installerOutput += "--- uv installer source: GitHub releases ---"
- $installerOutput += @($ghOut | ForEach-Object { "$_" })
- if (Test-Path $managedUv) {
- Write-Info "uv installer succeeded via GitHub releases"
- }
- }
-
- # Rung 3: salvage an existing uv.exe. When the installer cannot run
- # at all (network fully blocked) but a working uv already exists --
- # on PATH, or at ~/.local/bin (the astral default location when
- # UV_INSTALL_DIR was ignored by an older installer) -- copy it into
- # the managed location so the managed-first invariant holds
- # (hermes_cli/managed_uv.py looks only at $HermesHome\bin\uv.exe).
- if (-not (Test-Path $managedUv)) {
- $existingUv = $null
- $uvOnPath = Get-Command uv -CommandType Application -ErrorAction SilentlyContinue |
- Select-Object -First 1
- if ($uvOnPath -and $uvOnPath.Source -and (Test-Path $uvOnPath.Source)) {
- $existingUv = $uvOnPath.Source
- }
- if (-not $existingUv) {
- $defaultUv = Join-Path $env:USERPROFILE ".local\bin\uv.exe"
- if (Test-Path $defaultUv) { $existingUv = $defaultUv }
- }
- if ($existingUv) {
- Write-Info "Salvaging existing uv from $existingUv"
- try {
- Copy-Item $existingUv $managedUv -Force
- # Verify the salvaged binary actually runs before
- # trusting it as the managed uv.
- $null = & $managedUv --version
- } catch {
- Write-Info "Existing uv at $existingUv could not be salvaged: $_"
- Remove-Item $managedUv -Force -ErrorAction SilentlyContinue
- }
- }
- }
-
- $ErrorActionPreference = $prevEAP
-
- if (Test-Path $managedUv) {
- $script:UvCmd = $managedUv
- $version = & $managedUv --version
- Write-Success "Managed uv installed ($version)"
- return $true
- }
-
- Write-Err "uv installed but not found at $managedUv"
- if ($installerOutput.Count -gt 0) {
- Write-Info "uv installer output (last 15 lines):"
- $installerOutput | Select-Object -Last 15 | ForEach-Object { Write-Info " $_" }
- }
- Write-Info "Install manually: https://docs.astral.sh/uv/getting-started/installation/"
- return $false
- } catch {
- if ($prevEAP) { $ErrorActionPreference = $prevEAP }
- Write-Err "Failed to install uv: $_"
- Write-Info "Install manually: https://docs.astral.sh/uv/getting-started/installation/"
- return $false
++ & $uv run --no-project --python $pyVersion python -m pm.cli install
++ if ($LASTEXITCODE) { Fail "pm install failed" }
++ } finally {
++ Pop-Location
+ }
+ }
+
-# Refresh $env:Path from the User + Machine registry hives. Stage drivers
-# invoke each stage in a fresh powershell process, but those processes
-# inherit env from the parent driver shell, NOT from the registry. When
-# an earlier stage (Stage-Git, Stage-Node, ...) installs a binary and
-# pushes its directory into User PATH, the next child process's $env:Path
-# is stale and the binary appears missing. This helper re-reads PATH
-# from the registry so every Invoke-Stage starts from a fresh, up-to-date
-# PATH view. Cheap (registry reads, no I/O elsewhere) and idempotent.
-function Sync-EnvPath {
- $env:Path = [Environment]::GetEnvironmentVariable("Path", "User") + ";" + [Environment]::GetEnvironmentVariable("Path", "Machine")
++function Stage-PythonDeps {
++ Invoke-BootstrapPm
}
-# npm lifecycle scripts on Windows spawn ``cmd.exe /d /s /c node <script>``.
-# PowerShell can resolve ``node`` via Get-Command while the child cmd process
-# still sees a PATH without node.exe's directory (nvm4w shims, App Paths
-# aliases, stale cross-process PATH). Prepend the resolved node.exe parent
-# directory so postinstall hooks (electron-winstaller, native modules, etc.)
-# can find ``node``. Regression for #48130.
-function Ensure-NodeExeOnPath {
- $nodeCmd = Get-Command node -ErrorAction SilentlyContinue
- if (-not $nodeCmd) { return $false }
-
- $nodeExeDir = Split-Path $nodeCmd.Source -Parent
- if (-not $nodeExeDir) { return $false }
-
- $pathParts = $env:Path -split ";"
- if ($pathParts -notcontains $nodeExeDir) {
- $env:Path = "$nodeExeDir;$env:Path"
- }
- return $true
+function Stage-NodeDeps {
+ Log "tool dependencies are managed by pm (hermes pm install)"
}
-# Put the Hermes-managed Node dir at the FRONT of the persisted User PATH.
-#
-# Appending is not enough: it leaves a pre-existing system Node ahead of the
-# bundled one in every new shell, so anything launched without a curated
-# environment (a standalone hermes-setup.exe run, a user typing `npm`) silently
-# resolves the wrong Node. Bundled must win.
-#
-# Move-to-front rather than add-if-missing, because installs made by an older
-# install.ps1 already have this dir in User PATH -- at the tail. An
-# add-if-missing check sees it present and leaves the broken ordering in place
-# forever, so the very users the ordering bug hurt would never be repaired.
-#
-# Unrelated entries keep their relative order, including empty segments (a
-# trailing ';' is legal and common in a real User PATH; Install-Git's splitting
-# preserves them too, so this must not quietly rewrite them). Duplicate
-# occurrences of the managed dir collapse into the single leading entry.
-# PowerShell's -ne is case-insensitive for strings, which is the right
-# comparison on Windows. Persists only when the resulting string differs, so
-# an already-correct PATH costs one registry read and no write.
-function Set-ManagedNodeFirstOnUserPath {
- param([string]$NodeDir)
-
- if (-not $NodeDir) { return }
-
+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")
- $items = if ($userPath) { @($userPath -split ";") } else { @() }
-
- $rest = @($items | Where-Object { $_ -ne $NodeDir })
- $updated = (@($NodeDir) + $rest) -join ";"
-
- if ($updated -ne $userPath) {
- [Environment]::SetEnvironmentVariable("Path", $updated, "User")
- }
-}
-
-# The npm range to install into the managed Node tree. Prefers the checkout's
-# root package.json so the installer and the manifest cannot drift; falls back
-# to the $NpmRange constant, which is the common case here because Test-Node
-# runs before the repo is cloned.
-function Get-NpmRange {
- $manifest = Join-Path $InstallDir "package.json"
- if (Test-Path $manifest) {
- try {
- $engines = (Get-Content $manifest -Raw | ConvertFrom-Json).engines
- if ($engines -and $engines.npm) { return [string]$engines.npm }
- } catch { }
+ if ($userPath -notlike "*$binDir*") {
+ [Environment]::SetEnvironmentVariable("Path", "$binDir;$userPath", "User")
+ Log "added $binDir to your user PATH (new shells pick it up)"
}
- return $NpmRange
+ Log "hermes command installed at $binDir"
}
-# Convert the numeric core of an npm version or range operand into a stable
-# three-component System.Version. npm reports semantic versions, but the
-# installer only needs the numeric core for the comparator ranges authored in
-# package.json (for example, <11.10.0 || >=11.17.0).
-function ConvertTo-NpmVersion {
- param([string]$Version)
-
- if (-not $Version) { return $null }
-
- $core = ($Version.Trim() -replace '^v', '' -replace '-.*$', '')
- $parts = @($core -split '\.')
- if ($parts.Count -lt 1 -or $parts.Count -gt 3) { return $null }
- foreach ($part in $parts) {
- if ($part -notmatch '^\d+$') { return $null }
+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
}
- while ($parts.Count -lt 3) { $parts += '0' }
-
- try {
- return [version]($parts -join '.')
- } catch {
- return $null
+ $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 }
}
+ $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"
}
-# Evaluate the comparator-only npm ranges used by the root manifest and the
-# pre-clone fallback. Alternatives are separated with || and each alternative
-# may contain one or more whitespace-separated <, <=, >, or >= comparators.
-# Unknown range syntax fails closed so an incompatible system npm cannot reach
-# npm ci and fail later with EBADENGINE.
-function Test-NpmVersionOk {
- param(
- [string]$Version,
- [string]$Range = (Get-NpmRange)
- )
-
- $actual = ConvertTo-NpmVersion $Version
- if (-not $actual -or -not $Range) { return $false }
-
- foreach ($alternative in @($Range -split '\s*\|\|\s*')) {
- $clause = $alternative.Trim()
- if (-not $clause) { continue }
-
- $comparators = [regex]::Matches(
- $clause,
- '(?:^|\s)(<=|>=|<|>)\s*(\d+(?:\.\d+){0,2})(?=\s|$)'
- )
- if ($comparators.Count -eq 0) { continue }
-
- $remainder = [regex]::Replace(
- $clause,
- '(?:^|\s)(?:<=|>=|<|>)\s*\d+(?:\.\d+){0,2}(?=\s|$)',
- ''
- ).Trim()
- if ($remainder) { continue }
-
- $matchesClause = $true
- foreach ($comparator in $comparators) {
- $target = ConvertTo-NpmVersion $comparator.Groups[2].Value
- if (-not $target) {
- $matchesClause = $false
- break
- }
-
- $matchesComparator = switch ($comparator.Groups[1].Value) {
- '<' { $actual -lt $target }
- '<=' { $actual -le $target }
- '>' { $actual -gt $target }
- '>=' { $actual -ge $target }
- default { $false }
- }
- if (-not $matchesComparator) {
- $matchesClause = $false
- break
- }
- }
-
- if ($matchesClause) { return $true }
- }
-
- return $false
+function Stage-Setup {
+ if ($NonInteractive) { return }
+ & (Join-Path $InstallDir "venv\Scripts\python.exe") (Join-Path $InstallDir "hermes") setup
}
-# Upgrade the Hermes-managed Node tree's bundled npm into $NpmRange when
-# needed. Managed Node trees survive updates, so their bundled npm can drift
-# outside a newer root package.json engine range. The repo .npmrc sets
-# `engine-strict=true`, making that mismatch fatal at the first `npm ci`.
-# Provision the right npm here instead of reacting to EBADENGINE later.
-#
-# Three details are load-bearing, mirroring _nb_ensure_bundled_npm_range in
-# scripts/lib/node-bootstrap.sh and upgrade_managed_npm in
-# hermes_cli/npm_engine.py:
-# - a temp cwd, so the checkout's own .npmrc (engine-strict,
-# min-release-age) does not gate the very upgrade meant to satisfy it;
-# - npm_config_min_release_age=0, which also neutralises a user ~/.npmrc;
-# - an explicit --prefix at the managed tree, so the upgrade rewrites the
-# tree's own npm rather than installing a second copy elsewhere.
-#
-# Best-effort: a failure leaves a working Node with an old npm, which beats no
-# Node at all, and npm_engine.py still covers the EBADENGINE that follows.
-function Update-ManagedNpm {
- param([string]$NodeDir)
-
- $npmCmd = Join-Path $NodeDir "npm.cmd"
- if (-not (Test-Path $npmCmd)) { return $false }
-
- $range = Get-NpmRange
-
- # Skip the network round-trip when the bundled npm already satisfies the
- # same range used by the system-Node acceptance gate.
- try {
- $have = (& $npmCmd --version 2>$null | Select-Object -First 1)
- if ($have -and (Test-NpmVersionOk $have $range)) { return $true }
- } catch { }
-
- # In-app updates run while the desktop app's Node processes are alive.
- # The managed npm lives inside the very tree they execute from, so an
- # in-place upgrade would hit WinError 5 (Access denied) on npm.cmd
- # (#80926). Defer; the next update with the app closed retries.
- if (Test-ManagedNodeInUse $NodeDir) {
- Write-Warn "Hermes-managed Node.js is in use by a running app; skipping the bundled npm upgrade (applies on a later update with the app closed)."
- return $false
- }
-
- Write-Info "Upgrading bundled npm to satisfy $range ..."
-
- $tmpCwd = Join-Path $env:TEMP ("hermes-npm-upgrade-" + [Guid]::NewGuid().ToString("N"))
- New-Item -ItemType Directory -Force -Path $tmpCwd | Out-Null
- $prevAge = $env:npm_config_min_release_age
- $prevCI = $env:CI
- $prevEAP = $ErrorActionPreference
- Push-Location $tmpCwd
- try {
- $env:npm_config_min_release_age = "0"
- $env:CI = "1"
- # Relax EAP=Stop so npm's stderr lines don't get wrapped as
- # ErrorRecords and short-circuit before $LASTEXITCODE is checked.
- # Same pattern as Install-Uv.
- $ErrorActionPreference = "Continue"
- & $npmCmd install --global --prefix $NodeDir "npm@$range" `
- --no-fund --no-audit --progress=false 2>&1 | Out-Null
- $exit = $LASTEXITCODE
- } catch {
- $exit = 1
- } finally {
- $ErrorActionPreference = $prevEAP
- Pop-Location
- $env:npm_config_min_release_age = $prevAge
- $env:CI = $prevCI
- Remove-Item -Recurse -Force $tmpCwd -ErrorAction SilentlyContinue
- }
-
- if ($exit -ne 0) {
- Write-Warn "Could not upgrade bundled npm to $range -- ``npm ci`` may fail with EBADENGINE."
- Write-Info "Fix manually: npm install -g --prefix `"$NodeDir`" npm@`"$range`""
- return $false
- }
-
- Write-Success "npm $(& $npmCmd --version 2>$null) installed"
- return $true
+function Stage-Gateway {
+ if ($NonInteractive) { return }
+ & (Join-Path $InstallDir "venv\Scripts\python.exe") (Join-Path $InstallDir "hermes") gateway install
}
-function Test-ManagedNodeInUse {
- param([string]$NodeDir)
- # Windows locks files that running processes execute from. During an
- # in-app update the desktop app's Node processes may hold the managed
- # tree open, and rewriting it then fails with WinError 5 (Access denied)
- # on npm.cmd (#80926). Cheap pre-check used to skip destructive steps;
- # the rename/move itself remains the authoritative guard.
- #
- # Check the executable path AND the command line: a cmd.exe wrapper
- # running npm.cmd from the tree reports its own exe (cmd.exe lives in
- # System32) while the tree path appears only in the command line.
- # Win32_Process.CommandLine is available on Windows PowerShell 5.1 and
- # 7+ (the Get-Process .CommandLine ETS property is 7.4+ only), and a
- # single CIM query beats a per-process property access loop.
- return @(
- Get-CimInstance Win32_Process -ErrorAction SilentlyContinue |
- Where-Object {
- ($_.ExecutablePath -like "$NodeDir\*") -or
- ($_.CommandLine -like "*$NodeDir*")
- }
- ).Count -gt 0
+function Stage-Desktop {
+ & (Join-Path $InstallDir "venv\Scripts\python.exe") (Join-Path $InstallDir "hermes") desktop build
+ if ($LASTEXITCODE) { Fail "desktop build failed" }
}
-# Re-discover uv without re-installing it. Cross-process stage drivers
-# (the desktop GUI's onboarding wizard, CI step-runners) invoke each stage
-# in a fresh powershell process, so $script:UvCmd set by Install-Uv in a
-# prior process is not visible here. Later stages (Test-Python,
-# Install-Venv, Install-Dependencies, Install-PlatformSdks) call this
-# at the top to populate $script:UvCmd from the managed location.
-# Throws if uv is not findable -- the caller's stage then surfaces a
-# clean error via the stage-driver's try/catch.
-function Resolve-UvCmd {
- # Already resolved (default invocation path: Install-Uv ran earlier
- # in the same process and set $script:UvCmd).
- if ($script:UvCmd) {
- if ($script:UvCmd -eq "uv") {
- # "uv" on PATH -- verify it's still resolvable (PATH could have
- # changed mid-session; cheap to recheck).
- if (Get-Command uv -ErrorAction SilentlyContinue) { return }
- } elseif (Test-Path $script:UvCmd) {
- return
+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")
}
- # Stale; fall through to re-discover.
+ $markerPath = Join-Path $InstallDir ".hermes-bootstrap-complete"
+ $tmp = "$markerPath.tmp"
+ $marker | ConvertTo-Json | Set-Content -Path $tmp -Encoding utf8
+ Move-Item -Force $tmp $markerPath
}
-
- # Check the managed location first -- this is where Install-Uv puts it.
- $managedUv = Join-Path $HermesHome "bin\uv.exe"
- if (Test-Path $managedUv) {
- $script:UvCmd = $managedUv
- return
- }
-
- # Fall back to PATH (covers edge cases where the installer ran in a
- # sibling process and HERMES_HOME wasn't propagated).
- if (Get-Command uv -ErrorAction SilentlyContinue) {
- $script:UvCmd = "uv"
- return
- }
-
- # Refresh PATH from registry in case the current process started before
- # Install-Uv updated User PATH.
- $env:Path = [Environment]::GetEnvironmentVariable("Path", "User") + ";" + [Environment]::GetEnvironmentVariable("Path", "Machine")
- if (Get-Command uv -ErrorAction SilentlyContinue) {
- $script:UvCmd = "uv"
- return
- }
-
- throw "uv is not installed. Run install.ps1 -Stage uv first."
+ Log "install complete. Run: hermes"
}
-function Resolve-AvailablePythonVersion {
- # Return the first Python minor version uv can actually find, preferring the
- # requested $PythonVersion and then $PythonFallbackVersions. Returns $null
- # when none are available.
- #
- # This is the cross-process-safe counterpart to Test-Python's in-memory
- # ``$script:PythonVersion = $fallbackVer`` mutation. Under Hermes-Setup.exe
- # each ``-Stage NAME`` runs in a *fresh* powershell.exe, so the fallback the
- # ``python`` stage settled on (e.g. 3.12 when 3.11 is absent) does NOT
- # survive into the ``venv`` stage's process -- there $PythonVersion is back
- # at its "3.11" default. Consumers re-resolve here instead of trusting that
- # default, which is exactly the propagation gap behind issue #50769.
- $candidates = @($PythonVersion) + $PythonFallbackVersions
- $seen = @{}
- foreach ($ver in $candidates) {
- if (-not $ver -or $seen.ContainsKey($ver)) { continue }
- $seen[$ver] = $true
- try {
- $found = & $UvCmd python find $ver 2>$null
- if ($found) { return $ver }
- } catch { }
+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 }
}
- return $null
}
-function Test-Python {
- Write-Info "Checking Python $PythonVersion..."
-
- # Let uv find or install Python
- try {
- $pythonPath = & $UvCmd python find $PythonVersion 2>$null
- if ($pythonPath) {
- $ver = & $pythonPath --version 2>$null
- Write-Success "Python found: $ver"
- return $true
- }
- } catch { }
-
- # Python not found -- use uv to install it (no admin needed!)
- Write-Info "Python $PythonVersion not found, installing via uv..."
- # Capture EAP outside the try block so the catch's restore call always
- # has a meaningful value (see Install-Uv for the full rationale).
- $prevEAP = $ErrorActionPreference
- try {
- # Temporarily relax ErrorActionPreference: uv writes download progress
- # ("Downloading cpython-3.11.15-windows-x86_64-none (24.5MiB)") to
- # stderr. With $ErrorActionPreference = "Stop" (set at the top of this
- # script) PowerShell wraps stderr lines from native commands as
- # ErrorRecord objects when captured via 2>&1, then throws a terminating
- # exception on the first one -- even though uv exits 0 and Python was
- # installed successfully. Verify success via `uv python find`
- # afterwards, which is the reliable signal regardless of exit-code
- # semantics or stderr noise. This fix was previously landed as
- # commit ec1714e71 and then lost in a release squash; reapplied here.
- $ErrorActionPreference = "Continue"
- $uvOutput = & $UvCmd python install $PythonVersion 2>&1
- $uvExitCode = $LASTEXITCODE
- $ErrorActionPreference = $prevEAP
-
- # Check if Python is now available (more reliable than exit code
- # since uv may return non-zero due to "already installed" etc.)
- $pythonPath = & $UvCmd python find $PythonVersion 2>$null
- if ($pythonPath) {
- $ver = & $pythonPath --version 2>$null
- Write-Success "Python installed: $ver"
- return $true
- }
-
- # uv ran but Python still not findable -- show what happened
- if ($uvExitCode -ne 0) {
- Write-Warn "uv python install output:"
- Write-Host $uvOutput -ForegroundColor DarkGray
- }
- } catch {
- # Restore EAP in case the try block threw before the assignment
- if ($prevEAP) { $ErrorActionPreference = $prevEAP }
- Write-Warn "uv python install error: $_"
- }
-
- # Fallback: check if ANY Python 3.10+ is already available on the system
- Write-Info "Trying to find any existing Python 3.10+..."
- foreach ($fallbackVer in $PythonFallbackVersions) {
- try {
- $pythonPath = & $UvCmd python find $fallbackVer 2>$null
- if ($pythonPath) {
- $ver = & $pythonPath --version 2>$null
- Write-Success "Found fallback: $ver"
- $script:PythonVersion = $fallbackVer
- return $true
- }
- } catch { }
- }
-
- # Fallback: try system python -- but skip the Microsoft Store stub.
- # On Windows, %LOCALAPPDATA%\Microsoft\WindowsApps\python.exe is a 0-byte
- # reparse-point stub that prints "Python was not found; run without
- # arguments to install from the Microsoft Store..." to stdout and exits
- # non-zero. Get-Command finds it; invoking it produces a confusing error
- # that the user sees as our installer crashing.
- $pythonCmd = Get-Command python -ErrorAction SilentlyContinue
- if ($pythonCmd) {
- $isStoreStub = $false
- try {
- $pythonSource = $pythonCmd.Source
- if ($pythonSource -and $pythonSource -like "*\WindowsApps\*") {
- $isStoreStub = $true
- } else {
- # Even outside WindowsApps, a 0-byte file is the stub
- $item = Get-Item $pythonSource -ErrorAction SilentlyContinue
- if ($item -and $item.Length -eq 0) { $isStoreStub = $true }
- }
- } catch { }
-
- if (-not $isStoreStub) {
- try {
- $prevEAP2 = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- $sysVer = & python --version 2>&1
- $ErrorActionPreference = $prevEAP2
- if ($sysVer -match "Python 3\.(1[0-9]|[1-9][0-9])") {
- Write-Success "Using system Python: $sysVer"
- return $true
- }
- } catch {
- if ($prevEAP2) { $ErrorActionPreference = $prevEAP2 }
- }
- }
- }
+if ($ProtocolVersion) { Write-Output 1; exit 0 }
- Write-Err "Failed to install Python $PythonVersion"
- Write-Info "Install Python 3.11 manually, then re-run this script:"
- Write-Info " https://www.python.org/downloads/"
- Write-Info " Or: winget install Python.Python.3.11"
- return $false
+if ($Manifest) {
+ @{ protocol_version = 1; stages = $Stages } | ConvertTo-Json -Depth 4 -Compress | Write-Output
+ exit 0
}
-$script:GitInstallFailureReason = $null
-$script:GitBashPath = $null
-$script:GitBashProbeOutput = $null
-
-function Test-GitBashCompatibility {
- <#
- .SYNOPSIS
- Verify that Git Bash can launch external MSYS programs, not just evaluate
- shell builtins. Mandatory ASLR can allow bash.exe itself to start while
- every child linked to msys-2.0.dll fails during fork/spawn.
- #>
- param([Parameter(Mandatory = $true)][string]$BashPath)
-
- $script:GitBashProbeOutput = $null
- if (-not (Test-Path -LiteralPath $BashPath)) {
- $script:GitBashProbeOutput = "bash.exe was not found at $BashPath"
- return $false
+if ($Stage) {
+ $known = @($Stages | ForEach-Object { $_.name })
+ if ($known -notcontains $Stage -and $Stage -ne "desktop") {
+ if ($Json) { Emit-Frame $false $Stage $false "unknown stage: $Stage" }
+ else { [Console]::Error.WriteLine("unknown stage: $Stage") }
+ exit 2
}
-
- $process = New-Object System.Diagnostics.Process
- try {
- $startInfo = New-Object System.Diagnostics.ProcessStartInfo
- $startInfo.FileName = $BashPath
- $startInfo.Arguments = '--noprofile --norc -c "/usr/bin/true; /usr/bin/cat --version >/dev/null"'
- $startInfo.UseShellExecute = $false
- $startInfo.CreateNoWindow = $true
- $startInfo.RedirectStandardOutput = $true
- $startInfo.RedirectStandardError = $true
- $process.StartInfo = $startInfo
-
- if (-not $process.Start()) {
- $script:GitBashProbeOutput = "bash.exe did not start"
- return $false
- }
- if (-not $process.WaitForExit(15000)) {
- try { $process.Kill() } catch { }
- $script:GitBashProbeOutput = "Git Bash compatibility probe timed out"
- return $false
- }
-
- $stdout = $process.StandardOutput.ReadToEnd()
- $stderr = $process.StandardError.ReadToEnd()
- $script:GitBashProbeOutput = ("$stdout`n$stderr").Trim()
- return ($process.ExitCode -eq 0)
- } catch {
- $script:GitBashProbeOutput = $_.Exception.Message
- return $false
- } finally {
- $process.Dispose()
+ $needsInput = ($Stage -eq "setup") -or ($Stage -eq "gateway")
+ if ($NonInteractive -and $needsInput) {
+ if ($Json) { Emit-Frame $true $Stage $true "needs user input" }
+ exit 0
}
-}
-
-function Test-MandatoryAslrEnabled {
- <# Return true only when Windows reports system-wide ForceRelocateImages=ON. #>
try {
- $cmd = Get-Command Get-ProcessMitigation -ErrorAction SilentlyContinue
- if (-not $cmd) { return $false }
- $mitigations = & $cmd -System
- $value = $mitigations.Aslr.ForceRelocateImages
- return ($null -ne $value -and $value.ToString().ToUpperInvariant() -eq "ON")
+ Invoke-StageByName $Stage
+ if ($Json) { Emit-Frame $true $Stage $false }
+ exit 0
} catch {
- return $false
- }
-}
-
-function Get-GitRootFromBashPath {
- param([Parameter(Mandatory = $true)][string]$BashPath)
-
- $binDir = Split-Path -Path $BashPath -Parent
- if ((Split-Path -Path $binDir -Leaf) -ine "bin") {
- return (Split-Path -Path $binDir -Parent)
- }
-
- $parent = Split-Path -Path $binDir -Parent
- if ((Split-Path -Path $parent -Leaf) -ieq "usr") {
- return (Split-Path -Path $parent -Parent)
+ if ($Json) { Emit-Frame $false $Stage $false "$_" }
+ exit 1
}
- return $parent
-}
-
-function New-GitBashAslrFailureReason {
- param([Parameter(Mandatory = $true)][string]$BashPath)
-
- $gitRoot = Get-GitRootFromBashPath -BashPath $BashPath
- $escapedRoot = $gitRoot -replace "'", "''"
- return @(
- "Git Bash at $BashPath cannot launch required MSYS child processes because Windows Mandatory ASLR (ForceRelocateImages) is enabled system-wide. Reinstalling Git will not change this policy."
- "Open PowerShell as Administrator and run:"
- "`$gitRoot = '$escapedRoot'"
- 'Get-Item "$gitRoot\bin\bash.exe", "$gitRoot\usr\bin\*.exe" -ErrorAction SilentlyContinue | ForEach-Object { Set-ProcessMitigation -Name $_.FullName -Disable ForceRelocateImages }'
- "Then rerun Hermes setup. If the override is blocked or later re-applied, ask your Windows administrator to allow this per-program exception."
- ) -join [Environment]::NewLine
}
-function Install-Git {
- <#
- .SYNOPSIS
- Ensure Git (and Git Bash) are installed. Git for Windows bundles bash.exe
- which Hermes uses to run shell commands.
-
- Priority order (deliberately simple -- no winget, no registry, no system
- package manager):
- 1. Existing ``git`` on PATH -- use it as-is (the common fast path).
- 2. Download **PortableGit** from the official git-for-windows GitHub
- release (self-extracting 7z.exe) and unpack it to
- ``%LOCALAPPDATA%\hermes\git`` -- never touches system Git, never
- requires admin, works even on locked-down machines and machines
- with a broken system Git install.
-
- **Why PortableGit, not MinGit:** MinGit is the minimal-automation
- distribution and ships ONLY ``git.exe`` -- no bash, no POSIX utilities.
- Hermes needs ``bash.exe`` to run shell commands. PortableGit is the
- full Git for Windows distribution without the installer UI; it ships
- ``git.exe`` + ``bash.exe`` + ``sh``, ``awk``, ``sed``, ``grep``, ``curl``,
- ``ssh``, etc. in ``usr\bin\``.
-
- We deliberately skip winget because it fails badly when the system Git
- install is in a half-installed state (partially registered, or uninstall-
- blocked). Owning the Hermes copy of Git ourselves is predictable and
- recoverable: if it ever breaks, ``Remove-Item %LOCALAPPDATA%\hermes\git``
- and re-running this installer fully recovers.
-
- After install we locate ``bash.exe`` and persist the path in
- ``HERMES_GIT_BASH_PATH`` (User scope) so Hermes can find it in a fresh
- shell without a second PATH refresh.
- #>
- $script:GitInstallFailureReason = $null
- Write-Info "Checking Git..."
-
- if (Get-Command git -ErrorAction SilentlyContinue) {
- $version = git --version
- Write-Success "Git found ($version)"
- Set-GitBashEnvVar
- if ($script:GitBashPath -and (Test-GitBashCompatibility -BashPath $script:GitBashPath)) {
- Write-Success "Git Bash can launch MSYS programs"
- return $true
- }
-
- if ($script:GitBashPath -and (Test-MandatoryAslrEnabled)) {
- $script:GitInstallFailureReason = New-GitBashAslrFailureReason -BashPath $script:GitBashPath
- Write-Err $script:GitInstallFailureReason
- return $false
- }
-
- if ($script:GitBashPath) {
- $probeDetail = if ($script:GitBashProbeOutput) { ": $script:GitBashProbeOutput" } else { "" }
- Write-Warn "System Git Bash could not launch required MSYS programs$probeDetail"
- } else {
- Write-Warn "Git is on PATH, but its Git Bash installation could not be located."
- }
- Write-Info "Trying a Hermes-managed PortableGit install instead..."
- }
-
- # Download PortableGit into $HermesHome\git. Always works as long as
- # we can reach github.com -- no admin, no winget, no reliance on the
- # user's possibly-broken system Git install.
- Write-Info "Git not found -- downloading PortableGit to $HermesHome\git\ ..."
- Write-Info "(no admin rights required; isolated from any system Git install)"
-
- try {
- $arch = Get-WindowsArch
- if ($arch -eq 'arm64') {
- $assetTag = 'arm64'
- $downloadIsZip = $false
- } elseif ($arch -eq 'x64') {
- $assetTag = '64-bit'
- $downloadIsZip = $false
- } else {
- # PortableGit does not ship 32-bit / arm builds -- fall back to MinGit
- # 32-bit with a warning that bash-based features will be unavailable.
- $assetTag = '32-bit-mingit'
- $downloadIsZip = $true
- }
-
- # Pinned git-for-windows release. We deliberately do NOT hit
- # api.github.com/repos/.../releases/latest here: that endpoint
- # is rate-limited to 60 requests/hour/IP for unauthenticated
- # callers, and users behind CGNAT / corporate NAT / dorm WiFi
- # routinely hit the limit, breaking the installer.
- # Static github.com/.../releases/download/<tag>/<asset> URLs
- # are not subject to the API rate limit.
- $gitTag = "v2.54.0.windows.1"
- $gitVer = "2.54.0"
- $gitVerTag = "$gitVer.windows.1"
-
- if ($arch -eq "32-bit-mingit") {
- Write-Warn "32-bit Windows detected -- PortableGit is 64-bit only. Installing MinGit 32-bit as a last resort; bash-dependent Hermes features (terminal tool, agent-browser) will not work on this machine."
- $assetName = "MinGit-$gitVer-32-bit.zip"
- $downloadIsZip = $true
- } elseif ($arch -eq "arm64") {
- $assetName = "PortableGit-$gitVer-arm64.7z.exe"
- $downloadIsZip = $false
- } else {
- $assetName = "PortableGit-$gitVer-64-bit.7z.exe"
- $downloadIsZip = $false
- }
-
- $downloadUrl = "https://github.com/git-for-windows/git/releases/download/$gitTag/$assetName"
- $downloadExt = if ($downloadIsZip) { "zip" } else { "7z.exe" }
- $tmpFile = "$env:TEMP\$assetName"
- $gitDir = "$HermesHome\git"
-
- Write-Info "Downloading $assetName (Git for Windows $gitVerTag)..."
- Invoke-WebRequest -Uri $downloadUrl -OutFile $tmpFile -UseBasicParsing
-
- if (Test-Path $gitDir) {
- Write-Info "Removing previous Git install at $gitDir ..."
- Remove-Item -Recurse -Force $gitDir
- }
- New-Item -ItemType Directory -Path $gitDir -Force | Out-Null
-
- if ($downloadIsZip) {
- Expand-Archive -Path $tmpFile -DestinationPath $gitDir -Force
- } else {
- # PortableGit is a self-extracting 7z archive. Invoke it with
- # `-o<target> -y` (silent) to extract to $gitDir. No 7z install
- # required; it's fully self-contained.
- Write-Info "Extracting PortableGit to $gitDir ..."
- $extractProc = Start-Process -FilePath $tmpFile `
- -ArgumentList "-o`"$gitDir`"", "-y" `
- -NoNewWindow -Wait -PassThru
- if ($extractProc.ExitCode -ne 0) {
- throw "PortableGit extraction failed (exit code $($extractProc.ExitCode))"
- }
- }
- Remove-Item -Force $tmpFile -ErrorAction SilentlyContinue
-
- # PortableGit layout: cmd\git.exe + bin\bash.exe + usr\bin\ (coreutils)
- # MinGit layout: cmd\git.exe + usr\bin\bash.exe (if present)
- $gitExe = "$gitDir\cmd\git.exe"
- if (-not (Test-Path $gitExe)) {
- throw "Git extraction did not produce git.exe at $gitExe"
- }
-
- # Add to session PATH so the rest of this install run can use git.
- $env:Path = "$gitDir\cmd;$env:Path"
-
- # Persist to User PATH so fresh shells see it. PortableGit needs
- # cmd\ (for git.exe), bin\ (for bash.exe + core tools), and
- # usr\bin\ (for perl, ssh, curl, and other POSIX coreutils).
- $newPathEntries = @(
- "$gitDir\cmd",
- "$gitDir\bin",
- "$gitDir\usr\bin"
- )
- $userPath = [Environment]::GetEnvironmentVariable("Path", "User")
- $userPathItems = if ($userPath) { $userPath -split ";" } else { @() }
- $changed = $false
- foreach ($entry in $newPathEntries) {
- if ($userPathItems -notcontains $entry) {
- $userPathItems += $entry
- $changed = $true
- }
- }
- if ($changed) {
- [Environment]::SetEnvironmentVariable("Path", ($userPathItems -join ";"), "User")
- }
-
- $version = & $gitExe --version
- Write-Success "Git $version installed to $gitDir (portable, user-scoped)"
- Set-GitBashEnvVar
- if (-not $script:GitBashPath) {
- throw "PortableGit extraction did not produce a usable bash.exe"
- }
- if (-not (Test-GitBashCompatibility -BashPath $script:GitBashPath)) {
- if (Test-MandatoryAslrEnabled) {
- $script:GitInstallFailureReason = New-GitBashAslrFailureReason -BashPath $script:GitBashPath
- } else {
- $probeDetail = if ($script:GitBashProbeOutput) { " Probe output: $script:GitBashProbeOutput" } else { "" }
- $script:GitInstallFailureReason = "Git Bash at $script:GitBashPath exists but cannot launch required MSYS programs.$probeDetail"
- }
- throw $script:GitInstallFailureReason
- }
- Write-Success "Git Bash can launch MSYS programs"
- return $true
- } catch {
- if ($script:GitInstallFailureReason) {
- Write-Err $script:GitInstallFailureReason
- return $false
- }
- Write-Err "Could not install portable Git: $_"
- Write-Info ""
- Write-Info "Fallback: install Git manually from https://git-scm.com/download/win"
- Write-Info "then re-run this installer. Hermes needs Git Bash on Windows to run"
- Write-Info "shell commands (same as Claude Code and other coding agents)."
- return $false
- }
-}
-
-function Set-GitBashEnvVar {
- <#
- .SYNOPSIS
- Locate ``bash.exe`` from an already-installed Git and persist the path in
- ``HERMES_GIT_BASH_PATH`` (User env scope) so Hermes can find it even before
- PATH propagation completes in a newly-spawned shell.
- #>
- $script:GitBashPath = $null
- $candidates = @()
-
- # Our own portable Git install is ALWAYS checked first, so a broken
- # system Git doesn't hijack us. If the user had a working system Git
- # we'd have returned early from Install-Git's fast path and never called
- # this with a system-Git-only installation anyway.
- #
- # Layouts:
- # PortableGit (our default): $HermesHome\git\bin\bash.exe
- # MinGit (32-bit fallback): $HermesHome\git\usr\bin\bash.exe
- $candidates += "$HermesHome\git\bin\bash.exe" # PortableGit layout (primary)
- $candidates += "$HermesHome\git\usr\bin\bash.exe" # MinGit / PortableGit usr\bin fallback
-
- # git.exe on PATH can tell us where the install root is
- $gitCmd = Get-Command git -ErrorAction SilentlyContinue
- if ($gitCmd) {
- $gitExe = $gitCmd.Source
- # Git for Windows (full installer): <root>\cmd\git.exe + <root>\bin\bash.exe
- # MinGit: <root>\cmd\git.exe + <root>\usr\bin\bash.exe
- $gitRoot = Split-Path (Split-Path $gitExe -Parent) -Parent
- $candidates += "$gitRoot\bin\bash.exe"
- $candidates += "$gitRoot\usr\bin\bash.exe"
- }
-
- # Standard system install locations as a final fallback. Note:
- # ProgramFiles(x86) can't be referenced via ${env:...} string interpolation
- # because of the parens -- use [Environment]::GetEnvironmentVariable().
- $candidates += "${env:ProgramFiles}\Git\bin\bash.exe"
- $pf86 = [Environment]::GetEnvironmentVariable("ProgramFiles(x86)")
- if ($pf86) { $candidates += "$pf86\Git\bin\bash.exe" }
- $candidates += "${env:LocalAppData}\Programs\Git\bin\bash.exe"
-
- foreach ($candidate in $candidates) {
- if ($candidate -and (Test-Path $candidate)) {
- [Environment]::SetEnvironmentVariable("HERMES_GIT_BASH_PATH", $candidate, "User")
- $env:HERMES_GIT_BASH_PATH = $candidate
- $script:GitBashPath = $candidate
- Write-Info "Set HERMES_GIT_BASH_PATH=$candidate"
- return
- }
- }
-
- Write-Warn "Could not locate bash.exe -- Hermes may not find Git Bash."
- Write-Info "If needed, set HERMES_GIT_BASH_PATH manually to your bash.exe path."
-}
-
-# The dependency tree supports Node 22.22+, 24.11+, and 26+. nanoid 6 excludes
-# Node 23 and 25 while its >=26 arm accepts later releases, and @babel/* 8.x
-# requires ^22.18.0 || >=24.11.0 -- so accepting 23/25 or an early Node 24
-# only defers the failure to `npm ci` under engine-strict. Keep this in sync
-# with the root package.json.
-function Test-NodeVersionOk {
- param([string]$Version)
- if ($Version -match '-') { return $false }
- try {
- $v = [version]($Version -replace '^v', '')
- } catch {
- return $false
- }
- if ($v.Major -eq 22) { return ($v.Minor -ge 22) }
- if ($v.Major -eq 24) { return ($v.Minor -ge 11) }
- return ($v.Major -ge 26)
-}
-
-# Accept a system Node only when its companion npm also satisfies the same
-# range used to provision the Hermes-managed tree. Keeping this probe separate
-# lets the initial PATH check and the post-winget check share one authority.
-function Test-SystemNodeReady {
- if (-not (Get-Command node -ErrorAction SilentlyContinue)) { return $false }
-
- $version = node --version
- if (Test-NodeVersionOk $version) {
- Ensure-NodeExeOnPath | Out-Null
- } else {
- Write-Warn "Node.js $version is unsupported (Hermes requires Node 22.22+, 24.11+, or 26+)"
- return $false
- }
-
- $npmRange = Get-NpmRange
- $npmCmd = Get-Command npm.cmd -ErrorAction SilentlyContinue
- if (-not $npmCmd) {
- $npmCmd = Get-Command npm -ErrorAction SilentlyContinue
- }
-
- $npmVersion = $null
- if ($npmCmd) {
- try {
- $npmVersion = (& $npmCmd --version 2>$null | Select-Object -First 1)
- } catch { }
- }
-
- if ($npmVersion -and (Test-NpmVersionOk $npmVersion $npmRange)) {
- Write-Success "Node.js $version with npm $npmVersion found"
- return $true
- }
-
- if ($npmVersion) {
- Write-Warn "Node.js $version uses npm $npmVersion, which does not satisfy Hermes requirement $npmRange"
- } else {
- Write-Warn "Node.js $version was found, but npm is missing or could not report its version"
- }
- return $false
-}
-
-function Test-Node {
- Write-Info "Checking Node.js (for browser tools)..."
-
- if (Test-SystemNodeReady) {
- $script:HasNode = $true
- return $true
- }
-
- Write-Info "Using a Hermes-managed Node.js installation instead..."
-
- # Prefer a Hermes-managed Node from a previous run over a too-old system one.
- $managedNode = "$HermesHome\node\node.exe"
- if ((Test-Path $managedNode) -and (Test-NodeVersionOk (& $managedNode --version))) {
- $version = & $managedNode --version
- $env:Path = "$HermesHome\node;$env:Path"
- Set-ManagedNodeFirstOnUserPath "$HermesHome\node"
- Write-Success "Node.js $version found (Hermes-managed)"
- # A tree from an older install still has that Node major's bundled
- # npm, which is below the current engines.npm floor. No-ops when the
- # npm is already in range, so reruns cost one --version probe.
- Update-ManagedNpm "$HermesHome\node" | Out-Null
- $script:HasNode = $true
- return $true
- }
-
- Write-Info "Installing Hermes-managed Node.js $NodeVersion LTS..."
-
- # Try the portable-zip path FIRST -- no UAC, no admin, no winget MSI.
- # winget install OpenJS.NodeJS.LTS triggers a system-wide MSI install
- # which prompts UAC (the dialog often appears minimized in the taskbar
- # and the install silently waits for consent, looking like a hang).
- # The portable zip path drops node.exe + npm into $HermesHome\node\
- # which is user-scoped and identical to how Install-Git handles
- # PortableGit. Same UX guarantee: works on locked-down enterprise
- # machines with no admin rights.
- Write-Info "Downloading portable Node.js $NodeVersion to $HermesHome\node\ ..."
- Write-Info "(no admin rights required; isolated from any system Node install)"
- try {
- $arch = Get-WindowsArch
- $indexUrl = "https://nodejs.org/dist/latest-v${NodeVersion}.x/"
- $indexPage = Invoke-WebRequest -Uri $indexUrl -UseBasicParsing
- $zipName = ($indexPage.Content | Select-String -Pattern "node-v${NodeVersion}\.\d+\.\d+-win-${arch}\.zip" -AllMatches).Matches[0].Value
-
- if ($zipName) {
- $downloadUrl = "${indexUrl}${zipName}"
- $tmpZip = "$env:TEMP\$zipName"
- $tmpDir = "$env:TEMP\hermes-node-extract"
-
- Invoke-WebRequest -Uri $downloadUrl -OutFile $tmpZip -UseBasicParsing
- if (Test-Path $tmpDir) { Remove-Item -Recurse -Force $tmpDir }
- Expand-Archive -Path $tmpZip -DestinationPath $tmpDir -Force
-
- $extractedDir = Get-ChildItem $tmpDir -Directory | Select-Object -First 1
- if ($extractedDir) {
- # Rename-swap instead of delete-then-move: the live tree is
- # never removed before its replacement is fully extracted.
- # Windows permits renaming a tree with running executables,
- # but if a process holds it without FILE_SHARE_DELETE the
- # rename fails with WinError 5 -- that refusal means the tree
- # is in use, so defer instead of forcing the write (#80926).
- # Best-effort sweep of staging/backup litter from interrupted
- # runs; locked files simply stay for the next attempt. Only
- # dirs older than 10 minutes are removed so a concurrent
- # heal's in-flight swap is never disturbed.
- Get-ChildItem "$HermesHome" -Directory -Filter "node.old-*" -ErrorAction SilentlyContinue |
- Where-Object { $_.LastWriteTime -lt (Get-Date).AddMinutes(-10) } |
- Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
- Get-ChildItem "$HermesHome" -Directory -Filter "node.new-*" -ErrorAction SilentlyContinue |
- Where-Object { $_.LastWriteTime -lt (Get-Date).AddMinutes(-10) } |
- Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
- $stamp = [Guid]::NewGuid().ToString("N")
- $staged = "$HermesHome\node.new-$stamp"
- $backup = "$HermesHome\node.old-$stamp"
- # Stage to a sibling directory so the final swap is a
- # same-volume rename (atomic), not a cross-volume Move-Item
- # (copy+delete, non-atomic -- a partial copy would leave a
- # broken tree). Move from $env:TEMP here, rename below.
- try {
- Move-Item $extractedDir.FullName $staged -ErrorAction Stop
- } catch {
- Write-Warn "Failed to stage the new Node.js tree; aborting the Node upgrade."
- Remove-Item -Recurse -Force $tmpDir -ErrorAction SilentlyContinue
- Remove-Item -Force $tmpZip -ErrorAction SilentlyContinue
- return $false
- }
- if (Test-Path "$HermesHome\node") {
- try {
- Rename-Item "$HermesHome\node" $backup -ErrorAction Stop
- } catch {
- Write-Warn "Hermes-managed Node.js is in use by a running app; deferring its upgrade. Close the app and re-run the update."
- Remove-Item -Recurse -Force $staged -ErrorAction SilentlyContinue
- Remove-Item -Recurse -Force $tmpDir -ErrorAction SilentlyContinue
- Remove-Item -Force $tmpZip -ErrorAction SilentlyContinue
- return $false
- }
- # A rename preserves LastWriteTime, so a backup renamed
- # from a long-lived tree would instantly look older than
- # the litter-sweep cutoff to a concurrent heal. Touch it
- # (best-effort) so the in-flight backup is never swept.
- try {
- (Get-Item $backup).LastWriteTime = Get-Date
- } catch { }
- try {
- Rename-Item $staged "$HermesHome\node" -ErrorAction Stop
- } catch {
- # Restore the live tree before bailing. The swap is a
- # same-volume rename, so a failure leaves no partial
- # target to clear.
- Rename-Item $backup "$HermesHome\node" -ErrorAction SilentlyContinue
- Remove-Item -Recurse -Force $staged -ErrorAction SilentlyContinue
- Remove-Item -Recurse -Force $tmpDir -ErrorAction SilentlyContinue
- Remove-Item -Force $tmpZip -ErrorAction SilentlyContinue
- return $false
- }
- Remove-Item -Recurse -Force $backup -ErrorAction SilentlyContinue
- } else {
- try {
- Rename-Item $staged "$HermesHome\node" -ErrorAction Stop
- } catch {
- Remove-Item -Recurse -Force $staged -ErrorAction SilentlyContinue
- Remove-Item -Recurse -Force $tmpDir -ErrorAction SilentlyContinue
- Remove-Item -Force $tmpZip -ErrorAction SilentlyContinue
- return $false
- }
- }
-
- # Session PATH so the rest of this run sees node/npm.
- $env:Path = "$HermesHome\node;$env:Path"
-
- # Persist to User PATH so fresh shells (and future stages
- # in cross-process driver mode) see it. Matches the
- # pattern Install-Git uses for PortableGit. See
- # Set-ManagedNodeFirstOnUserPath for why this is a
- # move-to-front and not an add-if-missing.
- Set-ManagedNodeFirstOnUserPath "$HermesHome\node"
-
- $version = & "$HermesHome\node\node.exe" --version
- Write-Success "Node.js $version installed to $HermesHome\node\ (portable, user-scoped)"
- # The zip's bundled npm is below the repo's engines.npm floor.
- Update-ManagedNpm "$HermesHome\node" | Out-Null
- $script:HasNode = $true
-
- Remove-Item -Force $tmpZip -ErrorAction SilentlyContinue
- Remove-Item -Recurse -Force $tmpDir -ErrorAction SilentlyContinue
- return $true
- }
- }
- } catch {
- Write-Warn "Portable Node.js download failed: $_"
- }
-
- # Fallback: try winget (used to be primary, demoted because the MSI
- # install triggers a UAC prompt that frequently appears minimized in
- # the taskbar -- looks like a hang to users on stock Windows).
- # Kept for environments where the portable download fails (proxy,
- # locked firewall, etc.) but the user is willing to consent to UAC.
- if (Get-Command winget -ErrorAction SilentlyContinue) {
- Write-Info "Falling back to winget (may prompt UAC -- check your taskbar for a flashing icon)..."
- # Capture EAP outside the try block so the catch's restore call always
- # has a meaningful value (see Install-Uv for the full rationale).
- $prevEAP = $ErrorActionPreference
- try {
- # Relax EAP=Stop so stderr lines from winget don't get wrapped
- # as ErrorRecords and short-circuit the 2>&1 pipe before we can
- # check the post-condition. See the long comment in Install-Uv
- # for the same pattern.
- $ErrorActionPreference = "Continue"
- # On ARM64, force winget to fetch the ARM64 installer. Without
- # the explicit override, winget on WoW64 sometimes still resolves
- # to x64 manifests, leaving us with an emulated Node toolchain
- # even after a "successful" install. The OpenJS manifest does
- # publish an arm64 installer, so this is safe.
- $wingetArgs = @(
- 'install','OpenJS.NodeJS','--silent',
- '--accept-package-agreements','--accept-source-agreements'
- )
- if ((Get-WindowsArch) -eq 'arm64') {
- $wingetArgs += @('--architecture','arm64')
- }
- winget @wingetArgs 2>&1 | Out-Null
- $ErrorActionPreference = $prevEAP
- # Refresh PATH
- $env:Path = [Environment]::GetEnvironmentVariable("Path", "User") + ";" + [Environment]::GetEnvironmentVariable("Path", "Machine")
- if (Test-SystemNodeReady) {
- $script:HasNode = $true
- return $true
- }
- } catch {
- if ($prevEAP) { $ErrorActionPreference = $prevEAP }
- }
- }
-
-
- Write-Info "Install manually: https://nodejs.org/en/download/"
- $script:HasNode = $false
- return $true
-}
-
-function Update-ProcessPathForPackages {
- # Make freshly-installed shims (rg.exe, ffmpeg.exe) visible to Get-Command in
- # THIS process without spawning a new shell, by folding the persisted
- # User+Machine hives plus winget's alias-shim directory into $env:Path.
- # Called after every package-manager attempt (winget/choco/scoop): previously
- # PATH was only refreshed inside the winget branch, so a successful
- # choco/scoop fallback -- or any install on a box without winget -- could be
- # misreported as "not installed".
- #
- # MERGE rather than overwrite: start from the existing process PATH so any
- # process-only entries added earlier in this installer run survive, then
- # APPEND hive/winget-Links entries not already present (case-insensitive,
- # order-preserving dedupe). A wholesale replace would silently drop those
- # process-only entries.
- $candidates = @()
- $candidates += $env:Path
- $candidates += [Environment]::GetEnvironmentVariable("Path", "User")
- $candidates += [Environment]::GetEnvironmentVariable("Path", "Machine")
- $wingetLinks = Join-Path $env:LOCALAPPDATA "Microsoft\WinGet\Links"
- if (Test-Path $wingetLinks) {
- $candidates += $wingetLinks
- }
- $seen = New-Object System.Collections.Generic.HashSet[string] ([StringComparer]::OrdinalIgnoreCase)
- $ordered = New-Object System.Collections.Generic.List[string]
- foreach ($chunk in $candidates) {
- if ([string]::IsNullOrEmpty($chunk)) { continue }
- foreach ($entry in $chunk.Split(';')) {
- $trimmed = $entry.Trim()
- if ($trimmed -and $seen.Add($trimmed)) {
- $ordered.Add($trimmed)
- }
- }
- }
- $env:Path = [string]::Join(';', $ordered)
-}
-
-function Install-SystemPackages {
- $script:HasRipgrep = $false
- $script:HasFfmpeg = $false
- $needRipgrep = $false
- $needFfmpeg = $false
-
- Write-Info "Checking ripgrep (fast file search)..."
- if (Get-Command rg -ErrorAction SilentlyContinue) {
- $version = rg --version | Select-Object -First 1
- Write-Success "$version found"
- $script:HasRipgrep = $true
- } else {
- $needRipgrep = $true
- }
-
- Write-Info "Checking ffmpeg (TTS voice messages)..."
- if (Get-Command ffmpeg -ErrorAction SilentlyContinue) {
- Write-Success "ffmpeg found"
- $script:HasFfmpeg = $true
- } else {
- $needFfmpeg = $true
- }
-
- if (-not $needRipgrep -and -not $needFfmpeg) { return }
-
- # Build description and package lists for each package manager
- $descParts = @()
- $wingetPkgs = @()
- $chocoPkgs = @()
- $scoopPkgs = @()
-
- if ($needRipgrep) {
- $descParts += "ripgrep for faster file search"
- $wingetPkgs += "BurntSushi.ripgrep.MSVC"
- $chocoPkgs += "ripgrep"
- $scoopPkgs += "ripgrep"
- }
- if ($needFfmpeg) {
- $descParts += "ffmpeg for TTS voice messages"
- $wingetPkgs += "Gyan.FFmpeg"
- $chocoPkgs += "ffmpeg"
- $scoopPkgs += "ffmpeg"
- }
-
- $description = $descParts -join " and "
- $hasWinget = Get-Command winget -ErrorAction SilentlyContinue
- $hasChoco = Get-Command choco -ErrorAction SilentlyContinue
- $hasScoop = Get-Command scoop -ErrorAction SilentlyContinue
-
- # Try winget first (most common on modern Windows)
- if ($hasWinget) {
- Write-Info "Installing $description via winget..."
- # Per-package log paths -- key the lookup by package id so we can
- # decide AFTER the post-install Get-Command check whether to keep
- # the log (still missing -> keep as breadcrumb) or delete it (now
- # present -> happy path, no clutter).
- $pkgLogs = @{}
- foreach ($pkg in $wingetPkgs) {
- $log = "$env:TEMP\hermes-winget-$($pkg -replace '[^A-Za-z0-9]','_')-$(Get-Random).log"
- $pkgLogs[$pkg] = $log
- # --source winget pins us to the github-backed source. Without this,
- # a broken msstore source (cert validation failures like 0x8a15005e
- # are common on Windows-on-ARM and some corporate networks) makes
- # winget bail with "please specify --source" *before* attempting any
- # install -- and it exits 0, so the surrounding try/catch never fires.
- # We don't ship anything from msstore, so pinning is safe.
- try {
- $output = winget install --exact --id $pkg --source winget --silent `
- --accept-package-agreements --accept-source-agreements 2>&1
- $code = $LASTEXITCODE
- $output | Out-File -FilePath $log -Encoding utf8
- "winget exit: $code" | Out-File -FilePath $log -Encoding utf8 -Append
- # 0x8A15002B (-1978335189) = APPINSTALLER_CLI_ERROR_UPDATE_NOT_APPLICABLE.
- # winget treats `install` on a package it already has registered as
- # an *upgrade*, finds no newer version, and bails with this code --
- # even when the binary is gone from disk/PATH (stale registration,
- # files removed outside winget, or a missing alias shim). We KNOW the
- # command was missing (that's why we're here), so a plain install
- # dead-ends forever. Force a reinstall to repair the registration so
- # the shim reappears.
- if ($code -eq -1978335189) {
- "-> already-installed/no-upgrade; retrying with --force" | Out-File -FilePath $log -Encoding utf8 -Append
- $output = winget install --exact --id $pkg --source winget --silent --force `
- --accept-package-agreements --accept-source-agreements 2>&1
- $output | Out-File -FilePath $log -Encoding utf8 -Append
- "winget exit (force): $LASTEXITCODE" | Out-File -FilePath $log -Encoding utf8 -Append
- }
- } catch {
- $_ | Out-File -FilePath $log -Encoding utf8 -Append
- "winget exit: <exception>" | Out-File -FilePath $log -Encoding utf8 -Append
- }
- }
- # Refresh PATH so packages winget exposed via "command line aliases" in
- # %LOCALAPPDATA%\Microsoft\WinGet\Links (added to PATH only in
- # newly-spawned shells, not this process) are visible to Get-Command below.
- Update-ProcessPathForPackages
- if ($needRipgrep -and (Get-Command rg -ErrorAction SilentlyContinue)) {
- Write-Success "ripgrep installed"
- $script:HasRipgrep = $true
- $needRipgrep = $false
- Remove-Item -Path $pkgLogs["BurntSushi.ripgrep.MSVC"] -ErrorAction SilentlyContinue
- } elseif ($pkgLogs.ContainsKey("BurntSushi.ripgrep.MSVC")) {
- Write-Warn "winget could not install ripgrep; details: $($pkgLogs['BurntSushi.ripgrep.MSVC'])"
- }
- if ($needFfmpeg -and (Get-Command ffmpeg -ErrorAction SilentlyContinue)) {
- Write-Success "ffmpeg installed"
- $script:HasFfmpeg = $true
- $needFfmpeg = $false
- Remove-Item -Path $pkgLogs["Gyan.FFmpeg"] -ErrorAction SilentlyContinue
- } elseif ($pkgLogs.ContainsKey("Gyan.FFmpeg")) {
- Write-Warn "winget could not install ffmpeg; details: $($pkgLogs['Gyan.FFmpeg'])"
- }
- if (-not $needRipgrep -and -not $needFfmpeg) { return }
- }
-
- # Fallback: choco
- if ($hasChoco -and ($needRipgrep -or $needFfmpeg)) {
- Write-Info "Trying Chocolatey..."
- foreach ($pkg in $chocoPkgs) {
- try { choco install $pkg -y 2>&1 | Out-Null } catch { }
- }
- Update-ProcessPathForPackages
- if ($needRipgrep -and (Get-Command rg -ErrorAction SilentlyContinue)) {
- Write-Success "ripgrep installed via chocolatey"
- $script:HasRipgrep = $true
- $needRipgrep = $false
- }
- if ($needFfmpeg -and (Get-Command ffmpeg -ErrorAction SilentlyContinue)) {
- Write-Success "ffmpeg installed via chocolatey"
- $script:HasFfmpeg = $true
- $needFfmpeg = $false
- }
- }
-
- # Fallback: scoop
- if ($hasScoop -and ($needRipgrep -or $needFfmpeg)) {
- Write-Info "Trying Scoop..."
- foreach ($pkg in $scoopPkgs) {
- try { scoop install $pkg 2>&1 | Out-Null } catch { }
- }
- Update-ProcessPathForPackages
- if ($needRipgrep -and (Get-Command rg -ErrorAction SilentlyContinue)) {
- Write-Success "ripgrep installed via scoop"
- $script:HasRipgrep = $true
- $needRipgrep = $false
- }
- if ($needFfmpeg -and (Get-Command ffmpeg -ErrorAction SilentlyContinue)) {
- Write-Success "ffmpeg installed via scoop"
- $script:HasFfmpeg = $true
- $needFfmpeg = $false
- }
- }
-
- # Show manual instructions for anything still missing
- if ($needRipgrep) {
- Write-Warn "ripgrep not installed (file search will use findstr fallback)"
- Write-Info " winget install BurntSushi.ripgrep.MSVC"
- }
- if ($needFfmpeg) {
- Write-Warn "ffmpeg not installed (TTS voice messages will be limited)"
- Write-Info " winget install Gyan.FFmpeg"
- }
-}
-
-# ============================================================================
-# Installation
-# ============================================================================
-
-function Install-Repository {
- Write-Info "Installing to $InstallDir..."
-
- $didUpdate = $false
-
- if (Test-Path $InstallDir) {
- # Test-Path "$InstallDir\.git" returns True when .git is a file OR a
- # directory OR a symlink OR a submodule-style gitfile -- and also when
- # it's a broken stub left over from a failed previous install (e.g.
- # a partial Remove-Item that couldn't delete a locked index.lock).
- # Validate the repo properly by asking git itself. Three checks
- # belt-and-braces: rev-parse (work tree), git status, and a resolvable
- # HEAD (an initial commit). If any fails the repo is broken and we
- # fall through to a fresh clone.
- $repoValid = $false
- if (Test-Path "$InstallDir\.git") {
- Push-Location $InstallDir
- try {
- # Reset $LASTEXITCODE before the probe so we don't pick up
- # a stale 0 from an earlier git call in this session.
- $global:LASTEXITCODE = 0
- $revParseOut = & git -c windows.appendAtomically=false rev-parse --is-inside-work-tree 2>&1
- $revParseOk = ($LASTEXITCODE -eq 0) -and ($revParseOut -match "true")
-
- $global:LASTEXITCODE = 0
- $null = & git -c windows.appendAtomically=false status --short 2>&1
- $statusOk = ($LASTEXITCODE -eq 0)
-
- # An interrupted previous clone leaves a repo with NO initial
- # commit. rev-parse/status still succeed there, but the update
- # path's `git stash` (and later `git checkout`) abort with
- # "You do not have the initial commit yet" and fail the install
- # (#40998). Require a resolvable HEAD so such partial checkouts
- # are treated as broken and re-cloned fresh below.
- $global:LASTEXITCODE = 0
- $null = & git -c windows.appendAtomically=false rev-parse --verify HEAD 2>&1
- $hasCommit = ($LASTEXITCODE -eq 0)
-
- if ($revParseOk -and $statusOk -and $hasCommit) {
- $repoValid = $true
- }
- } catch {}
- Pop-Location
- }
-
- if ($repoValid) {
- Write-Info "Existing installation found, updating..."
- Push-Location $InstallDir
- # Wrap the entire fetch+checkout block in EAP=Continue so git's
- # routine stderr output (e.g. 'From <url>' info lines emitted by
- # `git fetch`) doesn't terminate the script under the global
- # EAP=Stop. We rely on $LASTEXITCODE for actual failures.
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- $autostashRef = ""
- try {
- # This is a MANAGED checkout, not a repo the user edits. Git for
- # Windows defaults to core.autocrlf=true, which renormalizes the
- # repo's LF-only text files to CRLF in the working tree -- so
- # tracked files (.envrc, AGENTS.md, agent/*.py, workflows, ...)
- # show as locally modified even though nobody touched them. A
- # bare `git checkout` then aborts with "Your local changes would
- # be overwritten by checkout", which is exactly the failure GUI
- # users hit on update. Pin autocrlf=false so the dirt is never
- # created in the first place.
- git -c windows.appendAtomically=false config core.autocrlf false 2>$null
- Discard-LockfileChurn $InstallDir
- # Preserve any real local changes before the checkout instead of
- # discarding them with `reset --hard HEAD`. The old hard reset
- # silently destroyed agent-edited source on managed clones (the
- # #38542 data-loss class). Stash + restore mirrors install.sh:
- # nothing is lost, and a failed restore leaves the work in a
- # git stash for manual recovery. Untracked files are included so
- # agent-created dirs (e.g. tinker-atropos/) survive too.
- $statusOut = git -c windows.appendAtomically=false status --porcelain 2>$null
- if (-not [string]::IsNullOrWhiteSpace(($statusOut -join "`n"))) {
- # A previously interrupted update can leave the index with
- # unmerged entries. In that state `git stash` aborts with
- # "could not write index" and the following `git checkout`
- # aborts with "you need to resolve your current index first"
- # -- the GUI "git checkout main failed (exit 1)" install
- # failure. Clear the conflict markers with `git reset` first:
- # working-tree changes are kept (and stashed just below); only
- # the index conflict state is dropped. Mirrors the `hermes
- # update` path (#4735).
- $unmergedOut = git -c windows.appendAtomically=false ls-files --unmerged 2>$null
- if (-not [string]::IsNullOrWhiteSpace(($unmergedOut -join "`n"))) {
- Write-Info "Clearing unmerged index entries from a previous conflict..."
- git -c windows.appendAtomically=false reset -q 2>$null
- }
- $stashName = "hermes-install-autostash-" + (Get-Date -Format "yyyyMMdd-HHmmss")
- Write-Info "Local changes detected, stashing before update..."
- git -c windows.appendAtomically=false stash push --include-untracked -m "$stashName"
- if ($LASTEXITCODE -eq 0) { $autostashRef = "stash@{0}" }
- }
- git -c windows.appendAtomically=false fetch origin $Branch
- if ($LASTEXITCODE -ne 0) { throw "git fetch failed (exit $LASTEXITCODE)" }
- # Precedence: Commit > Tag > Branch. Commit and Tag check
- # out as detached HEAD intentionally -- they're meant to be
- # reproducible pins, not branches the user pulls into.
- if ($Commit) {
- # Make sure we have the commit locally (a tag-less commit
- # SHA isn't always reachable from any one branch fetch).
- git -c windows.appendAtomically=false fetch origin $Commit
- # A commit pin must never move an existing install
- # BACKWARDS. hermes-setup.exe bakes its build-time commit
- # into the binary (BUILD_PIN_COMMIT) and passes it as
- # -Commit on every install-mode run -- including the retry
- # the desktop's "Update didn't finish" screen kicks off. An
- # installer built months ago would otherwise rewind a
- # current checkout to its build commit, leaving ancient
- # code against a current venv (npm workspaces and Python
- # deps that no longer match: the #74xxx report). Skip the
- # pin when the target is already an ancestor of HEAD; a
- # fresh clone has no such ancestry and pins normally.
- $skipRollback = $false
- if (-not $ForceCommit) {
- git -c windows.appendAtomically=false merge-base --is-ancestor $Commit HEAD 2>$null
- $isAncestor = ($LASTEXITCODE -eq 0)
- $pinnedSha = (& git -c windows.appendAtomically=false rev-parse "$Commit^{commit}" 2>$null)
- $headSha = (& git -c windows.appendAtomically=false rev-parse HEAD 2>$null)
- $skipRollback = $isAncestor -and ($pinnedSha -ne $headSha)
- }
- if ($skipRollback) {
- Write-Warn "Ignoring -Commit $Commit`: the checkout is already newer."
- Write-Warn "Pinning to it would roll this install back. Pass -ForceCommit to override."
- } else {
- git -c windows.appendAtomically=false checkout --detach $Commit
- if ($LASTEXITCODE -ne 0) { throw "git checkout $Commit failed (exit $LASTEXITCODE)" }
- }
- } elseif ($Tag) {
- git -c windows.appendAtomically=false fetch origin "refs/tags/${Tag}:refs/tags/${Tag}"
- git -c windows.appendAtomically=false checkout --detach "refs/tags/$Tag"
- if ($LASTEXITCODE -ne 0) { throw "git checkout tag $Tag failed (exit $LASTEXITCODE)" }
- } else {
- git -c windows.appendAtomically=false checkout $Branch
- if ($LASTEXITCODE -ne 0) { throw "git checkout $Branch failed (exit $LASTEXITCODE)" }
- # Managed installs should follow origin/$Branch exactly. If
- # the checkout has diverged (or has local-only commits),
- # ff-only pull cannot succeed -- mirror ``hermes update`` and
- # reset to the fetched remote so bootstrap/install can recover.
- git -c windows.appendAtomically=false pull --ff-only origin $Branch
- if ($LASTEXITCODE -ne 0) {
- Write-Warn "Fast-forward not possible; resetting managed install to origin/$Branch..."
- git -c windows.appendAtomically=false reset --hard "origin/$Branch"
- if ($LASTEXITCODE -ne 0) { throw "git reset --hard origin/$Branch failed (exit $LASTEXITCODE)" }
- }
- }
-
- if ($autostashRef) {
- # Default to restoring so work is never silently dropped.
- # Only prompt when we're certain a human can answer: an
- # interactive session AND a real, non-redirected console on
- # both stdin and stdout. The desktop "Update" button and
- # bootstrap run the installer without a usable console -- in
- # those cases Read-Host would hang or return empty, so we
- # skip the prompt and just restore (the safe default).
- $restoreNow = $true
- $hasConsole = $false
- try {
- $hasConsole = (
- [Environment]::UserInteractive `
- -and (-not [Console]::IsInputRedirected) `
- -and (-not [Console]::IsOutputRedirected) `
- -and ($Host.Name -eq "ConsoleHost")
- )
- } catch { $hasConsole = $false }
- if ($hasConsole) {
- Write-Warn "Local changes were stashed before updating."
- Write-Warn "Restoring them may reapply local customizations onto the updated codebase."
- $restoreAnswer = Read-Host "Restore local changes now? [Y/n]"
- if ($restoreAnswer -match '^(n|no)$') { $restoreNow = $false }
- }
-
- if ($restoreNow) {
- Write-Info "Restoring local changes..."
- $restoreOutput = @(git -c windows.appendAtomically=false stash apply $autostashRef 2>&1)
- $restoreExit = $LASTEXITCODE
- $conflictedFiles = @(
- git -c windows.appendAtomically=false diff --name-only --diff-filter=U 2>$null
- ) | Where-Object { $_ -and $_.ToString().Trim() }
- if (($restoreExit -eq 0) -and ($conflictedFiles.Count -eq 0)) {
- git -c windows.appendAtomically=false stash drop $autostashRef 2>$null
- Write-Warn "Local changes were restored on top of the updated codebase."
- Write-Warn "Review git diff / git status if Hermes behaves unexpectedly."
- } else {
- Write-Err "Update pulled new code, but restoring local changes hit conflicts."
- foreach ($line in $restoreOutput) {
- if ($line -and $line.ToString().Trim()) {
- Write-Host $line
- }
- }
- if ($conflictedFiles.Count -gt 0) {
- Write-Host ""
- Write-Host "Conflicted files:"
- foreach ($file in $conflictedFiles) {
- Write-Host " - $file"
- }
- }
- Write-Host ""
- Write-Info "Your stashed changes are preserved -- nothing is lost."
- Write-Info " Stash ref: $autostashRef"
- git -c windows.appendAtomically=false reset --hard HEAD 2>$null | Out-Null
- Write-Info "Working tree reset to clean state."
- Write-Info "Restore your changes later with: git stash apply $autostashRef"
- }
- } else {
- Write-Info "Skipped restoring local changes."
- Write-Info "Your changes are still preserved in git stash."
- Write-Info "Restore manually with: git stash apply $autostashRef"
- }
- $autostashRef = ""
- }
- } finally {
- if ($autostashRef) {
- # We stashed but never reached the restore block (a fetch/
- # checkout/pull failure threw). Leave the stash in place and
- # tell the user how to recover it -- never silently drop it.
- Write-Warn "Update did not complete. Your local changes are preserved in git stash."
- Write-Info "Restore manually with: git stash apply $autostashRef"
- }
- $ErrorActionPreference = $prevEAP
- Pop-Location
- }
- $didUpdate = $true
- } else {
- # Directory exists but isn't a usable git repo -- e.g. an
- # interrupted clone with no initial commit (#40998), or a leftover
- # ``.git`` stub from a partial uninstall that used to lock the
- # installer into the "update" branch forever. Move it aside rather
- # than deleting it -- never destroy a directory the user might still
- # want -- and fall through to a fresh clone.
- $backupDir = "$InstallDir.broken-" + (Get-Date -Format "yyyyMMdd-HHmmss")
- Write-Warn "Existing directory at $InstallDir is not a valid git repo."
- Write-Warn "Moving it aside to $backupDir before re-cloning."
- try {
- Move-Item -LiteralPath $InstallDir -Destination $backupDir -ErrorAction Stop
- } catch {
- Write-Err "Could not move $InstallDir aside : $_"
- Write-Info "Close any programs that might be using files in $InstallDir (editors,"
- Write-Info "terminals, running hermes processes) and try again."
- throw
- }
- }
- }
-
- if (-not $didUpdate) {
- $cloneSuccess = $false
-
- # Fix Windows git "copy-fd: write returned: Invalid argument" error.
- # Git for Windows can fail on atomic file operations (hook templates,
- # config lock files) due to antivirus, OneDrive, or NTFS filter drivers.
- # The -c flag injects config before any file I/O occurs.
- Write-Info "Configuring git for Windows compatibility..."
- $env:GIT_CONFIG_COUNT = "1"
- $env:GIT_CONFIG_KEY_0 = "windows.appendAtomically"
- $env:GIT_CONFIG_VALUE_0 = "false"
- git config --global windows.appendAtomically false 2>$null
-
- # Try SSH first, then HTTPS, with -c flag for atomic write fix
- Write-Info "Trying SSH clone..."
- $env:GIT_SSH_COMMAND = "ssh -o BatchMode=yes -o ConnectTimeout=5"
- try {
- Invoke-NativeWithRelaxedErrorAction { git -c windows.appendAtomically=false clone --depth 1 --branch $Branch $RepoUrlSsh $InstallDir }
- if ($LASTEXITCODE -eq 0) { $cloneSuccess = $true }
- } catch { }
- $env:GIT_SSH_COMMAND = $null
-
- if (-not $cloneSuccess) {
- if (Test-Path $InstallDir) { Remove-Item -Recurse -Force $InstallDir -ErrorAction SilentlyContinue }
- Write-Info "SSH failed, trying HTTPS..."
- try {
- Invoke-NativeWithRelaxedErrorAction { git -c windows.appendAtomically=false clone --depth 1 --branch $Branch $RepoUrlHttps $InstallDir }
- if ($LASTEXITCODE -eq 0) { $cloneSuccess = $true }
- } catch { }
- }
-
- # Fallback: download ZIP archive (bypasses git file I/O issues entirely)
- if (-not $cloneSuccess) {
- if (Test-Path $InstallDir) { Remove-Item -Recurse -Force $InstallDir -ErrorAction SilentlyContinue }
- Write-Warn "Git clone failed -- downloading ZIP archive instead..."
- try {
- # Pick the ZIP URL for the most-specific ref the caller asked
- # for. GitHub supports archive URLs for commits, tags, and
- # branches; we honour Commit > Tag > Branch.
- if ($Commit) {
- $zipUrl = "https://github.com/NousResearch/hermes-agent/archive/$Commit.zip"
- $zipLabel = $Commit
- } elseif ($Tag) {
- $zipUrl = "https://github.com/NousResearch/hermes-agent/archive/refs/tags/$Tag.zip"
- $zipLabel = $Tag
- } else {
- $zipUrl = "https://github.com/NousResearch/hermes-agent/archive/refs/heads/$Branch.zip"
- $zipLabel = $Branch
- }
- $zipPath = "$env:TEMP\hermes-agent-$zipLabel.zip"
- $extractPath = "$env:TEMP\hermes-agent-extract"
-
- Invoke-WebRequest -Uri $zipUrl -OutFile $zipPath -UseBasicParsing
- if (Test-Path $extractPath) { Remove-Item -Recurse -Force $extractPath }
- Expand-Archive -Path $zipPath -DestinationPath $extractPath -Force
-
- # GitHub ZIPs extract to repo-branch/ subdirectory
- $extractedDir = Get-ChildItem $extractPath -Directory | Select-Object -First 1
- if ($extractedDir) {
- New-Item -ItemType Directory -Force -Path (Split-Path $InstallDir) -ErrorAction SilentlyContinue | Out-Null
- Move-Item $extractedDir.FullName $InstallDir -Force
- Write-Success "Downloaded and extracted"
-
- # Initialize git repo so updates work later. A bare
- # `git init` leaves NO HEAD -- desktop's write-build-stamp
- # then hard-fails with "could not determine git commit"
- # (#50823 / #61657). Fetch the requested ref and force-check
- # it out (-f) so untracked ZIP files cannot block checkout.
- Push-Location $InstallDir
- git -c windows.appendAtomically=false init 2>$null
- git -c windows.appendAtomically=false config windows.appendAtomically false 2>$null
- # Pin autocrlf=false BEFORE the checkout below. Git for Windows
- # defaults to core.autocrlf=true, which would renormalize the
- # repo's LF text files to CRLF in the working tree during
- # `checkout -f FETCH_HEAD` -- leaving this freshly-created
- # managed checkout dirty vs HEAD and aborting the next
- # `hermes update` (see the notes at the shared clone-path
- # config below and install.ps1:1461-1469). The later pin on
- # the shared path is idempotent and still covers git clones.
- git -c windows.appendAtomically=false config core.autocrlf false 2>$null
- git remote add origin $RepoUrlHttps 2>$null
- $fetchRef = if ($Commit) { $Commit } elseif ($Tag) { "refs/tags/$Tag" } else { $Branch }
- Write-Info "Fetching $fetchRef so the ZIP checkout has a resolvable HEAD..."
- $prevZipEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- try {
- git -c windows.appendAtomically=false fetch --depth 1 origin $fetchRef 2>&1 | Out-Null
- if ($LASTEXITCODE -eq 0) {
- if ($Commit -or $Tag) {
- git -c windows.appendAtomically=false checkout -f --detach FETCH_HEAD 2>&1 | Out-Null
- } else {
- git -c windows.appendAtomically=false checkout -f -B $Branch FETCH_HEAD 2>&1 | Out-Null
- }
- if ($LASTEXITCODE -eq 0) {
- Write-Success "ZIP checkout pinned to $fetchRef"
- } else {
- # Checkout blocked, but FETCH_HEAD still has a SHA we can stamp with.
- $fetchSha = & git -c windows.appendAtomically=false rev-parse FETCH_HEAD 2>$null
- if ($LASTEXITCODE -eq 0 -and $fetchSha) {
- if (-not $env:GITHUB_SHA) { $env:GITHUB_SHA = ("$fetchSha").Trim() }
- Write-Warn "ZIP checkout failed; seeded GITHUB_SHA from FETCH_HEAD for desktop stamp"
- } else {
- Write-Warn "ZIP extract succeeded but git checkout failed -- desktop build may need `$env:GITHUB_SHA"
- }
- }
- } else {
- Write-Warn "ZIP extract succeeded but git fetch of $fetchRef failed -- desktop build may need `$env:GITHUB_SHA"
- }
- } finally {
- $ErrorActionPreference = $prevZipEAP
- }
- Pop-Location
- Write-Success "Git repo initialized for future updates"
-
- $cloneSuccess = $true
- }
-
- # Cleanup temp files
- Remove-Item -Force $zipPath -ErrorAction SilentlyContinue
- Remove-Item -Recurse -Force $extractPath -ErrorAction SilentlyContinue
- } catch {
- Write-Err "ZIP download also failed: $_"
- }
- }
-
- if (-not $cloneSuccess) {
- throw "Failed to download repository (tried git clone SSH, HTTPS, and ZIP)"
- }
- }
-
- # Set per-repo config (harmless if it fails)
- Push-Location $InstallDir
- git -c windows.appendAtomically=false config windows.appendAtomically false 2>$null
- # Pin autocrlf=false on the managed clone so git never renormalizes the
- # repo's LF text files to CRLF in the working tree. Without this, the very
- # next `hermes update` checkout aborts on a "dirty" tree the user never
- # touched (see the update path above).
- git -c windows.appendAtomically=false config core.autocrlf false 2>$null
-
- # Post-clone pin: when a clone (or ZIP-fallback init) just landed us on
- # $Branch's tip, honour the higher-precedence $Commit / $Tag by checking
- # the exact ref out as a detached HEAD. Skipped for the in-place update
- # path (above) since that already routed via the same precedence.
- if (-not $didUpdate) {
- # Same EAP=Continue wrap as the update path -- git fetch's 'From <url>'
- # info line goes to stderr and would terminate the script under the
- # global EAP=Stop otherwise. We check $LASTEXITCODE for real errors.
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- try {
- if ($Commit) {
- Write-Info "Pinning to commit $Commit..."
- git -c windows.appendAtomically=false fetch origin $Commit
- git -c windows.appendAtomically=false checkout --detach $Commit
- if ($LASTEXITCODE -ne 0) {
- throw "git checkout $Commit failed (exit $LASTEXITCODE)"
- }
- } elseif ($Tag) {
- Write-Info "Pinning to tag $Tag..."
- git -c windows.appendAtomically=false fetch origin "refs/tags/${Tag}:refs/tags/${Tag}"
- git -c windows.appendAtomically=false checkout --detach "refs/tags/$Tag"
- if ($LASTEXITCODE -ne 0) {
- throw "git checkout tag $Tag failed (exit $LASTEXITCODE)"
- }
- }
- } finally {
- $ErrorActionPreference = $prevEAP
- }
- }
-
- Write-Success "Repository ready"
-}
-
-function Install-Venv {
- if ($NoVenv) {
- Write-Info "Skipping virtual environment (-NoVenv)"
- return
- }
-
- # Re-resolve the interpreter before creating the venv. Under Hermes-Setup.exe
- # each stage runs in its own powershell.exe, so the fallback the `python`
- # stage picked (e.g. 3.12 when 3.11 is absent) did NOT propagate into this
- # fresh process -- $PythonVersion is back at its "3.11" default. Trusting it
- # here made `uv venv venv --python 3.11` fail with exit 2 on machines without
- # 3.11 even though the `python` stage reported success (issue #50769).
- $resolved = Resolve-AvailablePythonVersion
- if ($resolved -and $resolved -ne $PythonVersion) {
- Write-Info "Python $PythonVersion not available; using detected Python $resolved"
- $script:PythonVersion = $resolved
- }
-
- Write-Info "Creating virtual environment with Python $PythonVersion..."
-
- Push-Location $InstallDir
-
- # Tasks we disabled below and must re-enable no matter how this stage
- # exits. Populated only with tasks that were ENABLED before we touched
- # them, so a task the user deliberately disabled is never re-armed.
- $gatewayTasksDisabled = @()
- $venvHadExistingVenv = $false
- $venvBackupName = $null
- $venvParked = $false
- try {
- if (Test-Path -LiteralPath "venv") {
- $venvHadExistingVenv = $true
- Write-Info "Virtual environment already exists, recreating..."
- # On Windows, native Python extensions (e.g. _bcrypt.pyd, tornado's
- # speedups.pyd) are loaded as DLLs by any running hermes process.
- # Windows denies deletion of loaded DLLs, so every process running out
- # of this venv must be stopped before retiring it. This keeps cleanup
- # from accumulating locked stale trees and avoids carrying a live
- # gateway into the replacement venv.
- if ($env:OS -eq "Windows_NT") {
- $myPid = $PID
- Write-Info "Stopping any running hermes processes before recreating venv..."
- # Disarm the respawner FIRST: the gateway autostart Scheduled Task
- # relaunches a killed gateway within seconds, and losing that race
- # re-locks the venv's .pyd files between our kill sweep and
- # venv parking/cleanup (the July 2026 _brotlicffi.pyd incident). schtasks
- # /End stops a running task instance; /Change /DISABLE stops it
- # from re-firing mid-install. (The Startup-folder .vbs fallback is
- # NOT touched: it only fires at logon, so it cannot respawn a
- # gateway mid-install.) Re-enabled in the finally below -- including
- # on failure -- but only for tasks that were enabled to begin with.
- # Best-effort: a missing task just errors quietly.
- try {
- schtasks /Query /FO CSV 2>$null | ConvertFrom-Csv | Where-Object { $_.TaskName -like '*Hermes_Gateway*' } | ForEach-Object {
- $tn = $_.TaskName
- if ($_.Status -eq 'Disabled') {
- Write-Info " gateway autostart task $tn is already disabled; leaving it that way"
- return
- }
- schtasks /End /TN $tn 2>$null | Out-Null
- schtasks /Change /TN $tn /DISABLE 2>$null | Out-Null
- $gatewayTasksDisabled += $tn
- Write-Info " disabled gateway autostart task $tn for the duration of the install"
- }
- } catch {
- Write-Warn "Could not enumerate gateway scheduled tasks: $($_.Exception.Message)"
- }
- # The launcher CLI (hermes.exe) plus its child tree.
- & taskkill /F /T /IM hermes.exe /FI "PID ne $myPid" 2>$null | Out-Null
- # taskkill /IM hermes.exe is NOT enough: the gateway/agent that a
- # scheduled task or watchdog autostarts runs as
- # `pythonw.exe -m hermes_cli.main gateway run` straight out of
- # venv\Scripts\, so its image name is python/pythonw, not hermes.exe.
- # That process holds the venv's .pyd files open and re-triggers the
- # access-denied failure. Select only roots whose executable lives
- # under this venv, then stop each root's whole process tree. Some
- # Hermes children re-exec through .hermes-runtime, so killing only
- # the selected venv process can leave its child holding the install
- # open. The path-prefix check still keeps unrelated Python processes
- # outside this venv untouched.
- #
- # The gateway autostart task registers with /RL LIMITED as the current
- # user (see hermes_cli/gateway_windows.py), so the installer always
- # runs at equal-or-higher integrity and can read its executable path.
- # Get-CimInstance is used over Get-Process because it returns a null
- # ExecutablePath for a process it cannot inspect (a different session)
- # instead of throwing, so an unreadable process is skipped rather than
- # aborting the whole sweep.
- #
- # The sweep is a bounded LOOP, not single-shot: supervised processes
- # (the Desktop app's backend, a watchdog-managed gateway) respawn in
- # the window between one kill pass and venv parking. Each pass re-
- # enumerates; three consecutive clean passes (or the attempt cap)
- # ends the loop.
- $venvPrefix = [System.IO.Path]::GetFullPath((Join-Path $InstallDir "venv")).TrimEnd('\') + '\'
- $cleanPasses = 0
- for ($sweep = 0; $sweep -lt 10 -and $cleanPasses -lt 3; $sweep++) {
- $found = 0
- try {
- Get-CimInstance Win32_Process -ErrorAction Stop |
- Where-Object { $_.ProcessId -ne $myPid -and $_.ExecutablePath -and $_.ExecutablePath.StartsWith($venvPrefix, [System.StringComparison]::OrdinalIgnoreCase) } |
- ForEach-Object {
- $found++
- $treePid = [string]$_.ProcessId
- Write-Info " stopping process tree at PID $treePid ($($_.Name)) running from venv"
- & taskkill /F /T /PID $treePid 2>$null | Out-Null
- }
- } catch {
- Write-Warn "Could not enumerate venv processes: $($_.Exception.Message)"
- break
- }
- if ($found -eq 0) { $cleanPasses++ } else { $cleanPasses = 0 }
- Start-Sleep -Milliseconds 400
- }
- }
- # Move the old venv aside before creating its replacement. A directory
- # rename is atomic on the same volume and does not require deleting
- # files mapped as DLLs. NEVER fall back to deleting the live venv
- # (#83149): Remove-Item -Recurse can delete most of site-packages and
- # then fail on one locked .pyd, leaving a gutted venv with no usable
- # interpreter and no rollback source. Abort with the previous install
- # intact so the user can close holders and retry.
- $venvBackupName = "venv.stale.{0}-{1}" -f (Get-Date -Format "yyyyMMddHHmmss"), ([Guid]::NewGuid().ToString("N"))
- try {
- Rename-Item -LiteralPath "venv" -NewName $venvBackupName -ErrorAction Stop
- $venvParked = $true
- } catch {
- $renameErr = $_.Exception.Message
- throw (
- "Could not move the existing venv aside ($renameErr). " +
- "A process still has the install directory open (often a non-Hermes " +
- "python.exe that resolved into this venv via PATH). Close those " +
- "processes and retry - the previous install was left intact."
- )
- }
- }
-
- # uv creates the venv and pins the Python version in one step. uv emits
- # normal progress such as "Using CPython ..." on stderr; under Windows
- # PowerShell 5.1 with EAP=Stop that stderr is a NativeCommandError unless
- # we temporarily relax EAP and trust $LASTEXITCODE for real failures.
- Invoke-NativeWithRelaxedErrorAction { & $UvCmd venv venv --python $PythonVersion }
- # Relaxing EAP above means a *genuine* uv-venv failure (exit != 0) no longer
- # aborts on its own. Capture $LASTEXITCODE immediately and fail fast, so the
- # `venv` stage can't falsely report success (and Invoke-Stage can't emit
- # ok=true) when the venv was never created.
- $venvExitCode = $LASTEXITCODE
- if ($venvExitCode -ne 0) {
- throw "Failed to create virtual environment (uv venv exited with $venvExitCode)"
- }
-
- # uv can return success without leaving the interpreter expected by the
- # installer (for example after an interrupted filesystem operation). Treat
- # that as a failed transaction so the previous venv can be restored.
- $venvPythonExe = Join-Path $InstallDir "venv\Scripts\python.exe"
- if (-not (Test-Path -LiteralPath $venvPythonExe -PathType Leaf)) {
- throw "uv reported success but venv interpreter is missing at $venvPythonExe"
- }
-
- # The replacement has a working interpreter, but the transaction is only
- # committed after Install-Dependencies' baseline-import gate passes -- the
- # bootstrap runs the stages as separate processes, and every dependency
- # tier (or the import validation) can still fail after this stage
- # succeeds. Record the parked backup so the dependency stage can restore
- # it on failure and commit its cleanup only after validation (#83149).
- if ($venvParked) {
- Set-Content -LiteralPath (Join-Path $InstallDir "venv.pending-backup") -Value $venvBackupName -Encoding ascii
- Write-Info "Previous venv parked at $venvBackupName until the dependency install is verified"
- }
-
- # Clean up parked venvs from previous installs whose handles have since
- # been released. Best-effort -- a still-held tree just stays for next time.
- # The backup parked THIS run is excluded: it is the rollback source until
- # Install-Dependencies commits the transaction.
- Get-ChildItem -Directory -Filter "venv.stale.*" -ErrorAction SilentlyContinue |
- Where-Object { $_.Name -ne $venvBackupName } | ForEach-Object {
- Remove-Item -Recurse -Force $_.FullName -ErrorAction SilentlyContinue
- }
-
- # Neutralize any inherited UV_PYTHON (e.g. $env:UV_PYTHON = "3.14" left in
- # the user's shell). uv honours UV_PYTHON over an existing venv for the
- # later `uv sync` / `uv pip install` tiers, so without this it would
- # silently delete this 3.11 venv and recreate it at the inherited version
- # -- building Rust transitives that have no wheel for that version from
- # source via maturin, which fails. Pinning UV_PYTHON to the interpreter we
- # just created forces every subsequent uv command onto it.
- $env:UV_PYTHON = $venvPythonExe
- } catch {
- $originalError = $_
- $rollbackError = $null
-
- if ($venvParked -and $venvBackupName -and (Test-Path -LiteralPath $venvBackupName)) {
- try {
- if (Test-Path -LiteralPath "venv") {
- $failedVenvName = "venv.failed.{0}-{1}" -f (Get-Date -Format "yyyyMMddHHmmss"), ([Guid]::NewGuid().ToString("N"))
- Rename-Item -LiteralPath "venv" -NewName $failedVenvName -ErrorAction Stop
- Write-Warn "Failed replacement parked at $failedVenvName"
- }
- Rename-Item -LiteralPath $venvBackupName -NewName "venv" -ErrorAction Stop
- Write-Warn "Restored previous virtual environment after failed recreate"
- } catch {
- $rollbackError = $_.Exception.Message
- }
-
- if ($rollbackError) {
- throw "Virtual environment recreate failed: $($originalError.Exception.Message). Rollback failed: $rollbackError. Previous venv remains at $venvBackupName."
- }
- } elseif (-not $venvHadExistingVenv -and (Test-Path -LiteralPath "venv")) {
- # Preserve a partial first install too. This branch must not touch a
- # pre-existing venv whose move-aside failed above.
- try {
- $failedVenvName = "venv.failed.{0}-{1}" -f (Get-Date -Format "yyyyMMddHHmmss"), ([Guid]::NewGuid().ToString("N"))
- Rename-Item -LiteralPath "venv" -NewName $failedVenvName -ErrorAction Stop
- Write-Warn "Partial virtual environment parked at $failedVenvName"
- } catch {
- $rollbackError = $_.Exception.Message
- }
- if ($rollbackError) {
- throw "Virtual environment creation failed: $($originalError.Exception.Message). Could not park partial venv: $rollbackError"
- }
- }
-
- throw $originalError
- } finally {
- Pop-Location
- # Re-arm the gateway autostart tasks disabled during the venv teardown
- # -- in a finally so a failed teardown/creation can never strand the
- # user's gateway autostart in the disabled state. Same function scope,
- # so the list survives even under the stage-per-process bootstrap.
- # Deliberately NOT started here -- dependencies aren't installed yet;
- # the task fires normally on next logon and `hermes update` / the
- # gateway resume path handles the immediate restart.
- if ($gatewayTasksDisabled -and $gatewayTasksDisabled.Count -gt 0) {
- foreach ($tn in $gatewayTasksDisabled) {
- schtasks /Change /TN $tn /ENABLE 2>$null | Out-Null
- }
- Write-Info "Re-enabled gateway autostart task(s): $($gatewayTasksDisabled -join ', ')"
- }
- }
-
- Write-Success "Virtual environment ready (Python $PythonVersion)"
-}
-
-function Get-PendingVenvBackup {
- # Rollback source recorded by Install-Venv (#83149). Returns the parked
- # directory name, or $null when there is nothing to roll back to. A marker
- # pointing at a directory that no longer exists is stale -- drop it.
- $markerPath = Join-Path $InstallDir "venv.pending-backup"
- if (-not (Test-Path -LiteralPath $markerPath -PathType Leaf)) { return $null }
- $name = (Get-Content -LiteralPath $markerPath -ErrorAction SilentlyContinue | Select-Object -First 1)
- if ($name) { $name = $name.Trim() }
- if (-not $name -or -not (Test-Path -LiteralPath (Join-Path $InstallDir $name))) {
- Remove-Item -LiteralPath $markerPath -Force -ErrorAction SilentlyContinue
- return $null
- }
- return $name
-}
-
-function Complete-VenvTransaction {
- # Commit: dependency install + baseline imports passed, so the previous
- # venv is no longer needed as a rollback source. Best-effort delete; a
- # tree still held open just stays parked for the next install's sweep.
- $backupName = Get-PendingVenvBackup
- if (-not $backupName) { return }
- $backupPath = Join-Path $InstallDir $backupName
- Remove-Item -LiteralPath $backupPath -Recurse -Force -ErrorAction SilentlyContinue
- if (Test-Path -LiteralPath $backupPath) {
- Write-Warn "Old venv parked at $backupName (a process still holds files in it); it will be cleaned up on the next install"
- }
- Remove-Item -LiteralPath (Join-Path $InstallDir "venv.pending-backup") -Force -ErrorAction SilentlyContinue
-}
-
-function Restore-VenvBackup {
- # Rollback: the dependency stage failed after Install-Venv replaced the
- # venv. Park the unusable replacement and restore the previous working
- # venv so Hermes (and the venv-blocker probe) stay usable (#83149).
- $backupName = Get-PendingVenvBackup
- if (-not $backupName) { return }
- try {
- if (Test-Path -LiteralPath (Join-Path $InstallDir "venv")) {
- $failedVenvName = "venv.failed.{0}-{1}" -f (Get-Date -Format "yyyyMMddHHmmss"), ([Guid]::NewGuid().ToString("N"))
- Rename-Item -LiteralPath (Join-Path $InstallDir "venv") -NewName $failedVenvName -ErrorAction Stop
- Write-Warn "Failed replacement parked at $failedVenvName"
- }
- Rename-Item -LiteralPath (Join-Path $InstallDir $backupName) -NewName "venv" -ErrorAction Stop
- Remove-Item -LiteralPath (Join-Path $InstallDir "venv.pending-backup") -Force -ErrorAction SilentlyContinue
- Write-Warn "Restored previous virtual environment after failed dependency install"
- } catch {
- Write-Warn "Could not restore previous venv (still parked at $backupName): $($_.Exception.Message)"
- }
-}
-
-function Install-Dependencies {
- Write-Info "Installing dependencies..."
-
- Push-Location $InstallDir
-
- if (-not $NoVenv) {
- # Tell uv to install into our venv (no activation needed)
- $env:VIRTUAL_ENV = "$InstallDir\venv"
- }
-
- # Re-pin UV_PYTHON to the venv interpreter. Install-Venv already does this,
- # but the bootstrap runs install stages (venv, python-deps) as separate
- # processes, so the env var set in Install-Venv does NOT survive into a
- # separate python-deps invocation. Re-deriving it here covers that path.
- # Without it, an inherited $env:UV_PYTHON = "3.14" makes the uv sync/pip
- # tiers below recreate the venv at 3.14 and fail the maturin source build
- # (no cp314 wheels yet).
- if (-not $NoVenv) {
- $venvPythonExe = Join-Path $InstallDir "venv\Scripts\python.exe"
- if (Test-Path $venvPythonExe) {
- $env:UV_PYTHON = $venvPythonExe
- }
- }
-
- # Hash-verified install (Tier 0) -- when uv.lock is present, prefer
- # `uv sync --locked`. The lockfile records SHA256 hashes for every
- # transitive dependency, so a compromised transitive (different hash
- # than what we shipped) is REJECTED by the resolver. This is the
- # *only* path that protects against the "direct dep is fine, but the
- # dep's dep got worm-poisoned overnight" failure mode. The
- # `uv pip install` tiers below re-resolve transitives fresh from PyPI
- # without any hash verification -- they exist to keep installs working
- # when the lockfile is stale, missing, or out-of-sync with the
- # current extras spec, NOT because they're equivalent in posture.
- #
- # Everything through the baseline-import gate runs inside the venv
- # transaction opened by Install-Venv (#83149): on any failure the parked
- # previous venv is restored before the error propagates, and the parked
- # tree is deleted only after the imports prove the replacement usable.
- try {
- if (Test-Path "uv.lock") {
- Write-Info "Trying tier: hash-verified (uv.lock) ..."
- # Critical flag choice: `--extra all`, NOT `--all-extras`.
- # --all-extras = every [project.optional-dependencies] key,
- # bypassing the curated [all] extra. On Windows
- # that means [matrix] -> python-olm (no wheel,
- # needs `make` to build from sdist) and the
- # install fails.
- # --extra all = just the [all] extra's contents (curated).
- #
- # UV_PROJECT_ENVIRONMENT pins the sync target to our venv\.
- # Without it, modern uv (>=0.5) ignores VIRTUAL_ENV for `sync`
- # and creates a sibling .venv\ inside the repo -- leaving venv\
- # empty and producing the broken state where `hermes.exe` exists
- # in the wrong directory and imports fail with ModuleNotFoundError.
- # (Mirrors the same flag in scripts/install.sh::install_deps.)
- $env:UV_PROJECT_ENVIRONMENT = "$InstallDir\venv"
- Invoke-NativeWithRelaxedErrorAction { & $UvCmd sync --extra all --locked }
- if ($LASTEXITCODE -eq 0) {
- Write-Success "Main package installed (hash-verified via uv.lock)"
- $script:InstalledTier = "hash-verified (uv.lock)"
- # Skip the rest of the tiered cascade -- we already have a
- # complete, hash-verified install.
- $skipPipFallback = $true
- } else {
- Write-Warn "uv.lock sync failed (lockfile may be stale), falling back to PyPI resolve..."
- $skipPipFallback = $false
- }
- } else {
- Write-Info "uv.lock not found -- falling back to PyPI resolve (no hash verification)"
- $skipPipFallback = $false
- }
-
- # Install main package. Tiered fallback so a single flaky transitive
- # doesn't silently drop everything. Each tier's stdout/stderr is
- # preserved -- no Out-Null swallowing -- so the user can see what failed.
- #
- # Tier 1: [all] -- the curated extra in pyproject.toml.
- # Tier 2: [all] minus the currently-broken extras list ($brokenExtras).
- # Edit $brokenExtras below when something on PyPI breaks; this
- # lets users keep the rest of [all] when one transitive is
- # unavailable. The list of [all]'s contents is parsed from
- # pyproject.toml at runtime -- there is NO hand-mirrored copy
- # to drift out of sync.
- # Tier 3: bare `.` -- last-resort so at least the core CLI launches.
-
- # Currently-broken extras. Edit this list when an upstream package
- # gets quarantined / yanked / breaks resolution. Empty means everything
- # in [all] should be installable; populate with the names of extras
- # whose deps are temporarily unavailable.
- $brokenExtras = @()
-
- # Parse [project.optional-dependencies].all from pyproject.toml.
- # tomllib is stdlib on Python 3.11+ which the bootstrap guarantees.
- $pythonExeForParse = if (-not $NoVenv) { "$InstallDir\venv\Scripts\python.exe" } else { (& $UvCmd python find $PythonVersion) }
- $allExtras = @()
- if (Test-Path $pythonExeForParse) {
- $parsed = & $pythonExeForParse -c @"
-import re, sys, tomllib
-try:
- with open('pyproject.toml', 'rb') as fh:
- data = tomllib.load(fh)
- specs = data['project']['optional-dependencies']['all']
- out = []
- for s in specs:
- m = re.search(r'hermes-agent\[([\w-]+)\]', s)
- if m: out.append(m.group(1))
- print(','.join(out))
-except Exception:
- sys.exit(1)
-"@ 2>$null
- if ($LASTEXITCODE -eq 0 -and $parsed) {
- $allExtras = $parsed.Trim().Split(',')
- }
- }
- if (-not $allExtras -or $allExtras.Count -eq 0) {
- Write-Warn "Could not parse [all] from pyproject.toml; Tier 2 will be a no-op."
- $safeAll = "all"
- } else {
- $safeAll = ($allExtras | Where-Object { $brokenExtras -notcontains $_ }) -join ","
- }
- $brokenLabel = if ($brokenExtras) { ($brokenExtras -join ", ") } else { "none" }
-
- $installTiers = @(
- @{ Name = "all"; Spec = ".[all]" },
- @{ Name = "all minus known-broken ($brokenLabel)"; Spec = ".[$safeAll]" },
- @{ Name = "core only (no extras)"; Spec = "." }
- )
- $installed = $skipPipFallback
- if (-not $skipPipFallback) {
- foreach ($tier in $installTiers) {
- Write-Info "Trying tier: $($tier.Name) ..."
- Invoke-NativeWithRelaxedErrorAction { & $UvCmd pip install -e $tier.Spec }
- if ($LASTEXITCODE -eq 0) {
- Write-Success "Main package installed ($($tier.Name))"
- $script:InstalledTier = $tier.Name
- $installed = $true
- break
- }
- Write-Warn "Tier '$($tier.Name)' failed (exit $LASTEXITCODE). Trying next tier..."
- }
- }
- if (-not $installed) {
- throw "Failed to install hermes-agent package even with no extras. Inspect the uv pip install output above."
- }
-
- # Baseline-import gate. Even if a tier reported success above, the
- # actual deps may have landed somewhere other than $InstallDir\venv\
- # (e.g. uv 0.5+ syncing into a sibling .venv\ when UV_PROJECT_ENVIRONMENT
- # isn't set, leaving venv\ empty and hermes.exe broken with
- # `ModuleNotFoundError: No module named 'dotenv'` on first run).
- # We probe via the venv's own python so a misdirected sync is caught
- # here, not 30 seconds later when the user runs `hermes`.
- if (-not $NoVenv) {
- $venvPython = "$InstallDir\venv\Scripts\python.exe"
- if (-not (Test-Path $venvPython)) {
- throw "Install reported success but $venvPython does not exist. The dependency sync likely landed in a sibling .venv\ directory. Re-run the installer; if it persists, close Hermes processes and preserve existing venv directories before retrying. Do not delete venv in place."
- }
- # Relax EAP=Stop while running the import probe. Python writes
- # deprecation warnings and import-system info to stderr; under
- # EAP=Stop the 2>&1 merge wraps those as ErrorRecord objects and
- # throws even when the imports succeed. $LASTEXITCODE is the
- # reliable signal (it's 0 iff the python invocation exited 0,
- # regardless of what was written to stderr).
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- & $venvPython -c "import dotenv, openai, rich, prompt_toolkit" 2>&1 | Out-Null
- $importExitCode = $LASTEXITCODE
- $ErrorActionPreference = $prevEAP
- if ($importExitCode -ne 0) {
- $sibling = "$InstallDir\.venv"
- $hint = if (Test-Path $sibling) {
- "Detected sibling .venv\ at $sibling -- uv synced there instead of venv\. Close Hermes processes, preserve the existing venv, and rerun the installer so the transactional recovery path can move directories safely."
- } else {
- "Recover with: cd '$InstallDir'; `$env:UV_PROJECT_ENVIRONMENT='$InstallDir\venv'; uv sync --extra all --locked"
- }
- throw "Baseline imports failed in $InstallDir\venv (dotenv/openai/rich/prompt_toolkit). The install completed but dependencies are not in the venv. $hint"
- }
- Write-Success "Baseline imports verified in venv"
- }
-
- # Commit the venv transaction: the dependency install completed and the
- # baseline imports passed, so the previous venv is no longer needed as a
- # rollback source (#83149).
- Complete-VenvTransaction
- } catch {
- # Dependency install or import validation failed: restore the previous
- # working venv (parked by Install-Venv) before surfacing the error, so
- # a failed update leaves Hermes and its blocker probe usable.
- Restore-VenvBackup
- Pop-Location
- throw
- }
-
- if (-not $NoVenv) {
- # uv on Windows can register hermes.exe in dist-info/RECORD but fail to
- # materialise the .exe (file lock during self-update, distlib edge case).
- # Catch it here so a fresh install/update does not finish with a broken
- # `hermes` command while hermes-agent.exe / hermes-acp.exe exist
- $scriptsDir = Join-Path $InstallDir "venv\Scripts"
- $pythonExe = Join-Path $scriptsDir "python.exe"
- if ((Test-Path $scriptsDir) -and (Test-Path $pythonExe)) {
- $scriptNames = & $pythonExe -c @"
-import tomllib
-with open('pyproject.toml', 'rb') as fh:
- scripts = tomllib.load(fh).get('project', {}).get('scripts', {}) or {}
-print(','.join(scripts))
-"@ 2>$null
- if ($LASTEXITCODE -eq 0 -and $scriptNames) {
- $expected = @($scriptNames.Trim().Split(',') | Where-Object { $_ })
- $missing = @()
- foreach ($name in $expected) {
- $exe = Join-Path $scriptsDir "$name.exe"
- if (-not (Test-Path $exe)) { $missing += "$name.exe" }
- }
- if ($missing.Count -gt 0) {
- Write-Warn "Console entry point(s) missing: $($missing -join ', ')"
- Write-Info "Reinstalling entry points..."
- $env:UV_PROJECT_ENVIRONMENT = "$InstallDir\venv"
- Invoke-NativeWithRelaxedErrorAction { & $UvCmd pip install --reinstall -e . }
- $stillMissing = @()
- foreach ($name in $expected) {
- $exe = Join-Path $scriptsDir "$name.exe"
- if (-not (Test-Path $exe)) { $stillMissing += "$name.exe" }
- }
- if ($stillMissing.Count -gt 0) {
- Write-Warn "Entry points still missing after repair: $($stillMissing -join ', ')"
- Write-Info "Workaround: `"$pythonExe`" -m hermes_cli.main <command>"
- } else {
- Write-Success "Console entry points restored"
- }
- }
- }
- }
- }
-
- # Verify the dashboard deps specifically -- they're the most common thing
- # users hit and lazy-import errors from `hermes dashboard` are confusing.
- # If tier 1 failed (the common case), [web] was still picked up by tiers
- # 2-3; only tier 4 leaves you without it.
- $pythonExe = if (-not $NoVenv) { "$InstallDir\venv\Scripts\python.exe" } else { (& $UvCmd python find $PythonVersion) }
- if (Test-Path $pythonExe) {
- $webOk = $false
- $webServerSyntaxOk = $false
- # Relax EAP=Stop while running the import probe; see the matching
- # comment on the baseline-imports check above. Python writes
- # deprecation warnings to stderr and we don't want those wrapped
- # as ErrorRecords that silently force the "not importable" path
- # even when fastapi/uvicorn are actually installed.
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- try {
- & $pythonExe -c "import fastapi, uvicorn" 2>&1 | Out-Null
- if ($LASTEXITCODE -eq 0) { $webOk = $true }
- } catch { }
- try {
- & $pythonExe -m py_compile "$InstallDir\hermes_cli\web_server.py" 2>&1 | Out-Null
- if ($LASTEXITCODE -eq 0) { $webServerSyntaxOk = $true }
- } catch { }
- $ErrorActionPreference = $prevEAP
- if (-not $webOk) {
- Write-Warn "fastapi/uvicorn not importable -- `hermes dashboard` will not work."
- Write-Info "Attempting targeted install of [web] extra as last resort..."
- & $UvCmd pip install -e ".[web]"
- if ($LASTEXITCODE -eq 0) {
- Write-Success "[web] extra installed; `hermes dashboard` should now work."
- } else {
- Write-Warn "Could not install [web] extra. Run manually: uv pip install --python `"$pythonExe`" `"fastapi>=0.104,<1`" `"uvicorn[standard]>=0.24,<1`""
- }
- }
- if (-not $webServerSyntaxOk) {
- throw "dashboard backend source failed syntax check: hermes_cli/web_server.py"
- }
- }
-
- Pop-Location
-
- Write-Success "All dependencies installed"
-}
-
-function Install-HermesCommandLaunchers {
- param(
- [Parameter(Mandatory=$true)] [string]$Root,
- [Parameter(Mandatory=$true)] [string]$Destination
- )
-
- # Expose ONLY the hermes launchers on PATH -- never the whole
- # venv\Scripts directory, which contains python.exe / pip.exe and
- # silently hijacks the `python` command in every terminal (#83797).
- # Requiring hermes.exe before creating the destination keeps the PATH
- # stage from reporting success with an unusable command (PR #92092).
- $scriptsDir = Join-Path $Root "venv\Scripts"
- $requiredSource = Join-Path $scriptsDir "hermes.exe"
- if (-not (Test-Path -LiteralPath $requiredSource -PathType Leaf)) {
- throw "Cannot set up the hermes command: required launcher not found: $requiredSource"
- }
-
- New-Item -ItemType Directory -Force -Path $Destination | Out-Null
-
- # Launcher form depends on the venv (keep in lockstep with
- # hermes_cli/_install_repair.py): a normal venv's exe trampoline
- # embeds an absolute interpreter path and survives copying; a
- # relocatable venv's trampoline (managed_uv rebuilds use
- # --relocatable) resolves relative to its own location, and a copy
- # dies with 'uv trampoline failed to canonicalize script path' --
- # those get a .cmd delegator invoking the in-venv exe instead.
- $pyvenvCfg = Join-Path $Root "venv\pyvenv.cfg"
- $venvRelocatable = $false
- if (Test-Path -LiteralPath $pyvenvCfg) {
- $venvRelocatable = [bool](Select-String -Path $pyvenvCfg -Pattern '^\s*relocatable\s*=\s*true\s*$' -Quiet)
- }
- foreach ($launcher in @("hermes", "hermes-acp")) {
- $src = Join-Path $scriptsDir "$launcher.exe"
- if (-not (Test-Path -LiteralPath $src -PathType Leaf)) { continue }
- if ($venvRelocatable) {
- Remove-Item (Join-Path $Destination "$launcher.exe") -Force -ErrorAction SilentlyContinue
- Set-Content -Path (Join-Path $Destination "$launcher.cmd") -Value "@echo off`r`n`"$src`" %*" -Encoding Ascii
- } else {
- Remove-Item (Join-Path $Destination "$launcher.cmd") -Force -ErrorAction SilentlyContinue
- Copy-Item -Force -LiteralPath $src -Destination (Join-Path $Destination "$launcher.exe")
- }
- }
-
- # Verify either staged form before the caller mutates PATH.
- $requiredExe = Join-Path $Destination "hermes.exe"
- $requiredCmd = Join-Path $Destination "hermes.cmd"
- if (-not ((Test-Path -LiteralPath $requiredExe -PathType Leaf) -or
- (Test-Path -LiteralPath $requiredCmd -PathType Leaf))) {
- throw "Cannot set up the hermes command: launcher was not installed: $requiredExe"
- }
- return $Destination
-}
-
-function Set-PathVariable {
- Write-Info "Setting up hermes command..."
-
- if ($NoVenv) {
- $hermesBin = "$InstallDir"
- } else {
- # $HermesHome\bin is the managed binary dir (shared with the managed
- # uv), OUTSIDE the git checkout: `hermes update`'s autostash
- # (git stash push --include-untracked) deletes untracked files from
- # the working tree, which silently removed the launchers an earlier
- # installer staged under hermes-agent\bin. No git operation can ever
- # touch this dir. Staging and verification live in
- # Install-HermesCommandLaunchers, which throws BEFORE any PATH
- # mutation when the launchers cannot be staged.
- $hermesBin = "$HermesHome\bin"
- Install-HermesCommandLaunchers -Root $InstallDir -Destination $hermesBin | Out-Null
- }
-
- $currentPath = [Environment]::GetEnvironmentVariable("Path", "User")
-
- # Migrate older layouts off the user PATH:
- # venv\Scripts -- shadowed the user's python (#83797)
- # hermes-agent\bin -- lived inside the git checkout, where the update
- # autostash could sweep the launchers off disk
- # The hermes-agent\bin FILES are left in place on purpose: editor/ACP
- # configs that captured absolute launcher paths keep working, and the
- # dir is git-ignored so it cannot dirty the checkout.
- if (-not $NoVenv) {
- $legacyEntries = @("$InstallDir\venv\Scripts", "$InstallDir\bin")
- $items = @(($currentPath -split ';') | Where-Object { $_ })
- $cleaned = @($items | Where-Object { $legacyEntries -notcontains $_ })
- if ($cleaned.Count -ne $items.Count) {
- $currentPath = $cleaned -join ";"
- [Environment]::SetEnvironmentVariable("Path", $currentPath, "User")
- Write-Info "Removed legacy launcher entries from user PATH (kept hermes via $hermesBin)"
- }
- }
-
- if ($currentPath -notlike "*$hermesBin*") {
- [Environment]::SetEnvironmentVariable(
- "Path",
- "$hermesBin;$currentPath",
- "User"
- )
- Write-Success "Added to user PATH: $hermesBin"
- } else {
- Write-Info "PATH already configured"
- }
-
- # Set HERMES_HOME so the Python code finds config/data in the right place.
- # Only needed on Windows where we install to %LOCALAPPDATA%\hermes instead
- # of the Unix default ~/.hermes
- $currentHermesHome = [Environment]::GetEnvironmentVariable("HERMES_HOME", "User")
- if (-not $currentHermesHome -or $currentHermesHome -ne $HermesHome) {
- [Environment]::SetEnvironmentVariable("HERMES_HOME", $HermesHome, "User")
- Write-Success "Set HERMES_HOME=$HermesHome"
- }
- $env:HERMES_HOME = $HermesHome
-
- # Update current session
- $env:Path = "$hermesBin;$env:Path"
-
- Write-Success "hermes command ready"
-}
-
-function Write-BootstrapMarker {
- # Writes $InstallDir\.hermes-bootstrap-complete which tells the Hermes
- # desktop app (apps/desktop/electron/main.ts) "install.ps1 ran
- # successfully -- DON'T trigger the legacy first-launch bootstrap
- # runner."
- #
- # Schema mirrors what main.ts's writeBootstrapMarker() / isBootstrap
- # Complete() expect. Keep this in lockstep when either side changes:
- # apps/desktop/electron/main.ts lines 1199-1222
- # BOOTSTRAP_MARKER_SCHEMA_VERSION = 1 (line 187)
- #
- # Pinned commit/branch come from -Commit + -Branch flags (passed by
- # Hermes-Setup.exe) or fall back to whatever git resolves in the
- # checkout. The desktop validates schemaVersion + pinnedCommit
- # length but doesn't enforce that HEAD matches the pin (users
- # update via `hermes update` which moves HEAD legitimately).
- if (-not (Test-Path $InstallDir)) {
- Write-Warn "Skipping bootstrap marker: $InstallDir doesn't exist"
- return
- }
-
- # Resolve the pinned commit: explicit -Commit wins, otherwise read
- # the checkout's HEAD via git. If git can't run, leave commit empty
- # and the marker will fail desktop validation (pinnedCommit.length
- # >= 7) -- better to be invalid than wrong.
- $pinnedCommit = $Commit
- if (-not $pinnedCommit) {
- # PS 5.1 doesn't support the ?. null-conditional operator, so
- # check Get-Command's result explicitly before reading .Source.
- $gitCmd = Get-Command git -ErrorAction SilentlyContinue
- $gitExe = if ($gitCmd) { $gitCmd.Source } else { $null }
- if ($gitExe) {
- Push-Location $InstallDir
- try {
- $resolved = & $gitExe rev-parse HEAD 2>$null
- if ($LASTEXITCODE -eq 0 -and $resolved) {
- $pinnedCommit = $resolved.Trim()
- }
- } catch {
- # Ignore -- pinnedCommit stays empty, marker stays invalid,
- # desktop falls through to its legacy bootstrap path.
- } finally {
- Pop-Location
- }
- }
- }
-
- $pinnedBranch = $Branch
- if (-not $pinnedBranch) {
- $pinnedBranch = "main" # install.ps1's own default for -Branch
- }
-
- $markerPath = Join-Path $InstallDir ".hermes-bootstrap-complete"
- $marker = [ordered]@{
- schemaVersion = 1
- pinnedCommit = $pinnedCommit
- pinnedBranch = $pinnedBranch
- completedAt = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
- # desktopVersion field intentionally omitted -- only the desktop
- # app knows its own version, and the marker validator doesn't
- # require it. The desktop fills it in if/when it writes its
- # own marker (e.g. after a future in-app upgrade).
- }
- $json = $marker | ConvertTo-Json -Compress:$false
-
- # Write WITHOUT a UTF-8 BOM. PowerShell 5.1's `Set-Content -Encoding UTF8`
- # always emits a BOM, and Node's plain JSON.parse rejects the BOM as an
- # unexpected character -- so a BOM'd marker would silently fail the
- # desktop's readJson(), make isBootstrapComplete() return null, and the
- # desktop would re-run the legacy bootstrap runner anyway. Defeats the
- # whole point. Use the .NET API directly for BOM-less UTF-8.
- $utf8NoBom = New-Object System.Text.UTF8Encoding $false
- [System.IO.File]::WriteAllText($markerPath, $json, $utf8NoBom)
-
- Write-Success "Bootstrap marker written: $markerPath"
-}
-
-function Copy-ConfigTemplates {
- Write-Info "Setting up configuration files..."
-
- # Create the HERMES_HOME directory structure ($HermesHome, default %LOCALAPPDATA%\hermes)
- New-Item -ItemType Directory -Force -Path "$HermesHome\cron" | Out-Null
- New-Item -ItemType Directory -Force -Path "$HermesHome\sessions" | Out-Null
- New-Item -ItemType Directory -Force -Path "$HermesHome\logs" | Out-Null
- New-Item -ItemType Directory -Force -Path "$HermesHome\pairing" | Out-Null
- New-Item -ItemType Directory -Force -Path "$HermesHome\hooks" | Out-Null
- New-Item -ItemType Directory -Force -Path "$HermesHome\image_cache" | Out-Null
- New-Item -ItemType Directory -Force -Path "$HermesHome\audio_cache" | Out-Null
- New-Item -ItemType Directory -Force -Path "$HermesHome\memories" | Out-Null
- New-Item -ItemType Directory -Force -Path "$HermesHome\skills" | Out-Null
-
-
- # Create .env
- $envPath = "$HermesHome\.env"
- if (-not (Test-Path $envPath)) {
- $examplePath = "$InstallDir\.env.example"
- if (Test-Path $examplePath) {
- Copy-Item $examplePath $envPath
- Write-Success "Created $envPath from template"
- } else {
- New-Item -ItemType File -Force -Path $envPath | Out-Null
- Write-Success "Created $envPath"
- }
- } else {
- Write-Info "$envPath already exists, keeping it"
- }
-
- # Create config.yaml
- $configPath = "$HermesHome\config.yaml"
- if (-not (Test-Path $configPath)) {
- $examplePath = "$InstallDir\cli-config.yaml.example"
- if (Test-Path $examplePath) {
- Copy-Item $examplePath $configPath
- Write-Success "Created $configPath from template"
- }
- } else {
- Write-Info "$configPath already exists, keeping it"
- }
-
- # Create SOUL.md if it doesn't exist (global persona file).
- # IMPORTANT: write without a BOM. Windows PowerShell 5.1's
- # ``Set-Content -Encoding UTF8`` writes UTF-8 WITH a byte-order-mark
- # (the default PS5 behaviour), and Hermes's prompt-injection scanner
- # flags the BOM as an invisible unicode character and refuses to
- # load the file. PS7's ``-Encoding utf8NoBOM`` fixes that but we
- # don't control which PowerShell version the user has. Go direct
- # to .NET with an explicit UTF8Encoding($false) -- BOM-free on every
- # PowerShell version.
- $soulPath = "$HermesHome\SOUL.md"
- if (-not (Test-Path $soulPath)) {
- # MUST match DEFAULT_SOUL_MD in hermes_cli/default_soul.py. The runtime
- # upgrades the old comment-only scaffold to this text on next run, so
- # drift is self-healing, but keep them in sync to avoid first-run churn.
- $soulContent = @"
-You are Hermes Agent, built by Nous Research. Be direct: match the length of your reply to the weight of the ask -- a one-line question gets a one-line answer, and finished work gets a short report of what changed, what's verified, and what's left, never a replay of the process. No filler ("Great question," "I'd be happy to"), no restating the request back, no re-summarizing what you already said, no narrating tool calls the user can see. Plain claims over adjectives; when unsure, say so plainly. Agree because it's right, not because the user said it. Depth is earned -- give it when the user asks for detail, teaches, or the stakes demand it, not by default.
-"@
- $utf8NoBom = New-Object System.Text.UTF8Encoding($false)
- [System.IO.File]::WriteAllText($soulPath, $soulContent, $utf8NoBom)
- Write-Success "Created $soulPath (edit to customize personality)"
- }
-
- Write-Success "Configuration directory ready: $HermesHome"
-
- # Seed bundled skills into $HermesHome\skills (manifest-based, one-time per skill)
- Write-Info "Syncing bundled skills to $HermesHome\skills ..."
- $pythonExe = "$InstallDir\venv\Scripts\python.exe"
- if (Test-Path $pythonExe) {
- try {
- # Force the child python.exe to emit UTF-8 on its stdout/stderr.
- # On non-UTF-8 Windows locales (CP936/GBK zh-CN) Python defaults
- # its stream encoding to the active codepage and crashes on glyphs
- # like the checkmark (U+2713) that the codepage can't encode; the
- # resulting non-UTF-8 bytes break this script's JSON result frame on
- # stdout and abort the config-templates stage. Scope to this call
- # only. (Comment kept ASCII per this file's PS 5.1 contract above.)
- $prevPythonioencoding = $env:PYTHONIOENCODING
- $prevPythonutf8 = $env:PYTHONUTF8
- $env:PYTHONIOENCODING = "utf-8"
- $env:PYTHONUTF8 = "1"
- try {
- & $pythonExe "$InstallDir\tools\skills_sync.py" 2>$null
- } finally {
- $env:PYTHONIOENCODING = $prevPythonioencoding
- $env:PYTHONUTF8 = $prevPythonutf8
- }
- Write-Success "Skills synced to $HermesHome\skills"
- } catch {
- # Fallback: simple directory copy
- $bundledSkills = "$InstallDir\skills"
- $userSkills = "$HermesHome\skills"
- if ((Test-Path $bundledSkills) -and -not (Get-ChildItem $userSkills -Exclude '.bundled_manifest' -ErrorAction SilentlyContinue)) {
- Copy-Item -Path "$bundledSkills\*" -Destination $userSkills -Recurse -Force -ErrorAction SilentlyContinue
- Write-Success "Skills copied to $HermesHome\skills"
- }
- }
- }
-}
-
-function Install-NodeDeps {
- if (-not $HasNode) {
- # Cross-process driver mode (Hermes-Setup.exe runs each -Stage NAME
- # in a fresh powershell.exe) means $script:HasNode set by Stage-Node
- # in the previous process isn't visible here. Re-probe rather than
- # trust the stale global -- Stage-Node already ran successfully or
- # the bootstrap would've aborted, so npm is reachable.
- if (-not (Get-Command npm -ErrorAction SilentlyContinue)) {
- Write-Info "Skipping Node.js dependencies (Node not installed)"
- return
- }
- }
-
- # npm lifecycle scripts need node.exe on the PATH visible to child
- # cmd.exe processes. Stage-Node may have run in a prior process, so
- # re-apply here before any npm install (regression #48130).
- Ensure-NodeExeOnPath | Out-Null
-
- # Resolve npm explicitly to npm.cmd, NOT npm.ps1. Node.js on Windows
- # ships BOTH npm.cmd (a batch shim) and npm.ps1 (a PowerShell shim).
- # Get-Command's default ordering picks whichever comes first in PATHEXT,
- # and on many systems that's .ps1 -- but .ps1 requires scripts to be
- # enabled in PowerShell's execution policy, which most Windows users
- # don't have (the Restricted / RemoteSigned default blocks unsigned
- # .ps1 files). .cmd has no such restriction and works on every box.
- #
- # Strategy: look next to the npm shim we found and prefer npm.cmd if
- # it exists in the same directory. Fall back to whatever Get-Command
- # returned if we can't find a .cmd sibling.
- $npmCmd = Get-Command npm -ErrorAction SilentlyContinue
- if (-not $npmCmd) {
- Write-Warn "npm not found on PATH -- skipping Node.js dependencies."
- Write-Info "Open a new PowerShell window and re-run 'hermes setup tools' later."
- return
- }
- $npmExe = $npmCmd.Source
- if ($npmExe -like "*.ps1") {
- $npmCmdSibling = Join-Path (Split-Path $npmExe -Parent) "npm.cmd"
- if (Test-Path $npmCmdSibling) {
- Write-Info "Using npm.cmd (PowerShell execution policy blocks npm.ps1)"
- $npmExe = $npmCmdSibling
- } else {
- Write-Warn "Only npm.ps1 available -- install may fail if script execution is disabled."
- Write-Info " If it fails, either enable PS script execution or install Node via winget."
- }
- }
-
- # Wall-clock ceiling for each npm / Playwright invocation in this stage.
- # scripts/install.sh has time-boxed the same work with
- # ``run_with_timeout "$NODE_DEPS_TIMEOUT"`` (600s default) since #39219;
- # Windows never got the guard, so a stalled registry fetch or a wedged
- # Chromium extraction (#76222, #84614) froze the installer forever -- one
- # user left it running 12+ hours overnight. Same env override as bash
- # for very slow links.
- $nodeDepsTimeoutSec = 600
- if ($env:NODE_DEPS_TIMEOUT -match '^\d+$') {
- $nodeDepsTimeoutSec = [int]$env:NODE_DEPS_TIMEOUT
- }
-
- # Helper: run a native command with a hard wall-clock timeout while
- # still streaming its output live. Returns the exit code, or 124 on
- # timeout (the same convention as coreutils ``timeout`` and bash's
- # run_with_timeout).
- #
- # Launcher notes: ``Start-Process -FilePath npm.cmd`` fails with
- # ``%1 is not a valid Win32 application`` on some PowerShell versions
- # because Start-Process bypasses cmd.exe / PATHEXT and expects a real
- # PE file -- so route through cmd.exe, which IS a real PE, honours .cmd
- # batch shims, and performs the stdout+stderr merge into the log file
- # natively. The parent then tails the log into the console each poll
- # tick, preserving the live progress that makes a 3-minute download
- # distinguishable from a hang (the whole reason _Run-NpmInstall streams
- # output in the first place). ``Wait-Job -Timeout`` was rejected: jobs
- # swallow live output, and Stop-Job leaves the npm child running.
- # taskkill /T kills the real process tree. Works on Windows PowerShell
- # 5.1 -- no pwsh-only primitives.
- function _Invoke-NativeWithTimeout(
- [string]$exePath, [string]$argLine, [string]$workDir,
- [string]$logPath, [int]$timeoutSec
- ) {
- $cmdLine = "/d /s /c "" ""$exePath"" $argLine > ""$logPath"" 2>&1 """
- $proc = Start-Process -FilePath $env:ComSpec -ArgumentList $cmdLine `
- -WorkingDirectory $workDir -NoNewWindow -PassThru
- $deadline = [DateTime]::UtcNow.AddSeconds($timeoutSec)
- $shown = 0
- function _Drain-NewLines([string]$path, [ref]$count) {
- $lines = @(Get-Content $path -ErrorAction SilentlyContinue)
- if ($lines.Count -gt $count.Value) {
- $lines[$count.Value..($lines.Count - 1)] | ForEach-Object {
- Write-Host " $_" -ForegroundColor DarkGray
- }
- $count.Value = $lines.Count
- }
- }
- while (-not $proc.HasExited) {
- if ([DateTime]::UtcNow -gt $deadline) {
- & taskkill /T /F /PID $proc.Id 2>&1 | Out-Null
- return 124
- }
- Start-Sleep -Milliseconds 750
- _Drain-NewLines $logPath ([ref]$shown)
- }
- _Drain-NewLines $logPath ([ref]$shown)
- return $proc.ExitCode
- }
-
- # Helper: run "npm install" in a given directory and surface the real
- # error when it fails. Returns $true on success.
- function _Run-NpmInstall([string]$label, [string]$installDir, [string]$logPath, [string]$npmPath) {
- Push-Location $installDir
- # Capture EAP outside the try block so the catch's restore call always
- # has a meaningful value (see Install-Uv for the full rationale).
- $prevEAP = $ErrorActionPreference
- try {
- # The helper streams npm's output to BOTH the console and the log
- # file, so the user watches real progress instead of a frozen
- # "Installing..." line (on a fresh VM the install is 1-3 minutes;
- # total silence is indistinguishable from a hang) -- and the
- # wall-clock ceiling turns a genuinely stalled install (#76222
- # class) into a diagnosable failure instead of an overnight freeze.
- #
- # Relax EAP around the invocation: with EAP=Stop (set at the top
- # of this script), PowerShell can wrap stray stderr from the
- # launcher plumbing as ErrorRecord objects and throw even though
- # npm exited 0. This is the same issue Test-Python and Install-Uv
- # work around for uv's stderr-emitting installer. Check success
- # via the returned exit code, which is reliable regardless of
- # stderr noise.
- $ErrorActionPreference = "Continue"
- $code = _Invoke-NativeWithTimeout $npmPath "install --silent" `
- $installDir $logPath $nodeDepsTimeoutSec
- $ErrorActionPreference = $prevEAP
- if ($code -eq 0) {
- Write-Success "$label dependencies installed"
- Remove-Item -Force $logPath -ErrorAction SilentlyContinue
- return $true
- }
- if ($code -eq 124) {
- Write-Warn "$label npm install timed out after $([math]::Round($nodeDepsTimeoutSec / 60)) minutes -- a stalled download, wedged extraction, or file lock is the usual cause."
- Write-Info " Re-run the installer to retry (completed stages are skipped)."
- Write-Info " Slow connection? Raise the ceiling: set NODE_DEPS_TIMEOUT to seconds (default 600)."
- } else {
- Write-Warn "$label npm install failed -- exit code $code"
- }
- if (Test-Path $logPath) {
- $errText = (Get-Content $logPath -Raw -ErrorAction SilentlyContinue)
- if ($errText) {
- $snippet = if ($errText.Length -gt 1200) { $errText.Substring(0, 1200) + "..." } else { $errText }
- Write-Info " npm output:"
- foreach ($line in $snippet -split "`n") {
- Write-Host " $line" -ForegroundColor DarkGray
- }
- Write-Info " Full log: $logPath"
- Show-NpmCertHint $errText | Out-Null
- Write-NpmDebugLogTail -NpmOutput $errText
- }
- }
- Write-Info "Run manually later: cd `"$installDir`"; npm install"
- return $false
- } catch {
- if ($prevEAP) { $ErrorActionPreference = $prevEAP }
- Write-Warn "$label npm install could not be launched: $_"
- return $false
- } finally {
- Pop-Location
- }
- }
-
- # Browser tools
- if (Test-Path "$InstallDir\package.json") {
- Write-Info "Installing Node.js dependencies (browser tools)..."
- $browserLog = "$env:TEMP\hermes-npm-browser-$(Get-Random).log"
- $browserNpmOk = _Run-NpmInstall "Browser tools" $InstallDir $browserLog $npmExe
-
- # Install Playwright Chromium (mirrors scripts/install.sh behaviour for
- # Linux). Without this, tools/browser_tool.py::check_browser_requirements
- # returns False (no Chromium under %LOCALAPPDATA%\ms-playwright), and the
- # browser_* tools are silently filtered out of the agent's tool schema.
- # System Chrome at "C:\Program Files\Google\Chrome\..." is NOT used by
- # agent-browser -- it expects a Playwright-managed Chromium.
- if ($browserNpmOk) {
- Write-Info "Installing browser engine (Playwright Chromium)..."
- # npx lives next to npm in the same bin dir. Prefer .cmd to dodge
- # the same execution-policy gotcha that affects npm.ps1 (see above).
- $npmDir = Split-Path $npmExe -Parent
- $npxExe = $null
- foreach ($cand in @("npx.cmd", "npx.exe", "npx")) {
- $try = Join-Path $npmDir $cand
- if (Test-Path $try) { $npxExe = $try; break }
- }
- if (-not $npxExe) {
- $npxCmd = Get-Command npx -ErrorAction SilentlyContinue
- if ($npxCmd) { $npxExe = $npxCmd.Source }
- }
- if (-not $npxExe) {
- Write-Warn "npx not found -- cannot install Playwright Chromium."
- Write-Info "Run manually later: cd `"$InstallDir`"; npx playwright install chromium"
- } else {
- $pwLog = "$env:TEMP\hermes-playwright-install-$(Get-Random).log"
- Push-Location $InstallDir
- # Capture EAP outside the try block so the catch's restore call
- # always has a meaningful value (see Install-Uv for the full
- # rationale).
- $prevEAP = $ErrorActionPreference
- try {
- # Playwright Chromium is ~170MB compressed and the
- # download regularly takes 3-10 minutes on a fresh
- # VM. Tee the output to console + log so the user
- # sees download progress in real time instead of
- # staring at a silent prompt that looks hung. See
- # _Run-NpmInstall above for the same pattern and
- # the rationale behind 2>&1 before the pipe.
- Write-Info "(this can take several minutes -- streaming progress below)"
- # --yes auto-accepts npx's "Need to install [email protected]"
- # confirmation prompt. Without it, npx 7+ blocks on stdin
- # waiting for a y/N answer that never comes when this is
- # invoked through a pipeline (Tee-Object disconnects stdin
- # from the user's TTY), and the install hangs indefinitely
- # after printing "Need to install the following packages:
- #
- # Relax EAP around the playwright invocation: playwright
- # emits a "Chromium downloaded to ..." success banner to
- # stderr after a successful install. The launcher merges
- # stderr into the log natively, but keep EAP relaxed so
- # stray plumbing stderr can't fire the catch block with a
- # mangled banner even though the install succeeded. Check
- # the returned exit code instead, which is the reliable
- # signal.
- #
- # The wall-clock ceiling is the #76222 / #84614 fix: the
- # Chromium download reaches 100% and the extraction wedges
- # (or the registry fetch stalls), and without a bound the
- # installer sits on this line forever. bash has carried
- # the same 600s guard via run_playwright_install since
- # #39219.
- $ErrorActionPreference = "Continue"
- $pwCode = _Invoke-NativeWithTimeout $npxExe "--yes playwright install chromium" `
- $InstallDir $pwLog $nodeDepsTimeoutSec
- $ErrorActionPreference = $prevEAP
- if ($pwCode -eq 0) {
- Write-Success "Playwright Chromium installed (browser tools ready)"
- Remove-Item -Force $pwLog -ErrorAction SilentlyContinue
- } elseif ($pwCode -eq 124) {
- Write-Warn "Playwright Chromium install timed out after $([math]::Round($nodeDepsTimeoutSec / 60)) minutes."
- Write-Warn "This usually means a stalled download or a wedged archive extraction (a locked previous browser version can also cause it)."
- Write-Warn "Browser tools will not work until Chromium is installed."
- if (Test-Path $pwLog) { Write-Info " Partial log: $pwLog" }
- Write-Info "Run manually later: cd `"$InstallDir`"; npx playwright install chromium"
- } else {
- Write-Warn "Playwright Chromium install failed -- exit code $pwCode"
- Write-Warn "Browser tools will not work until Chromium is installed."
- if (Test-Path $pwLog) {
- $pwErr = Get-Content $pwLog -Raw -ErrorAction SilentlyContinue
- if ($pwErr) {
- $snippet = if ($pwErr.Length -gt 1200) { $pwErr.Substring(0, 1200) + "..." } else { $pwErr }
- Write-Info " playwright output:"
- foreach ($line in $snippet -split "`n") {
- Write-Host " $line" -ForegroundColor DarkGray
- }
- Write-Info " Full log: $pwLog"
- }
- }
- Write-Info "Run manually later: cd `"$InstallDir`"; npx playwright install chromium"
- }
- } catch {
- if ($prevEAP) { $ErrorActionPreference = $prevEAP }
- Write-Warn "Playwright Chromium install could not be launched: $_"
- Write-Info "Run manually later: cd `"$InstallDir`"; npx playwright install chromium"
- } finally {
- Pop-Location
- }
- }
- }
- }
-
- # TUI
- $tuiDir = "$InstallDir\ui-tui"
- if (Test-Path "$tuiDir\package.json") {
- Write-Info "Installing TUI dependencies..."
- $tuiLog = "$env:TEMP\hermes-npm-tui-$(Get-Random).log"
- [void](_Run-NpmInstall "TUI" $tuiDir $tuiLog $npmExe)
- }
-
- Install-BrowserUseCli
- Install-CuaDriver
-}
-
-# The Browser Use CLI is the default browser backend when it is runnable
-# (tools/browser_use_cli.py). Provision it at install time so fresh installs
-# don't silently fall back to the built-in browser tools. Best-effort: any
-# failure is non-fatal (browser_exec can still run via uvx, and `hermes tools`
-# can install it later).
-function Install-BrowserUseCli {
- if (-not $script:UvCmd) { Resolve-UvCmd }
- if (-not $script:UvCmd) {
- Write-Info "Skipping Browser Use CLI install (uv unavailable)"
- return
- }
- $managedBin = Join-Path $HermesHome "bin"
- $managedBu = Join-Path $managedBin "browser-use.exe"
- # MANAGED-FIRST: only Hermes' managed copy short-circuits. A browser-use
- # on the user's PATH is a side install -- resolution prefers the managed
- # copy, so it must be provisioned regardless.
- if (Test-Path $managedBu) {
- Write-Success "Browser Use CLI already installed"
- return
- }
-
- Write-Info "Installing Browser Use CLI (default browser backend)..."
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = "Continue"
- try {
- # UV_TOOL_BIN_DIR keeps the binary inside Hermes' managed bin dir,
- # where the browser tool resolves it -- no reliance on the user PATH.
- $env:UV_TOOL_BIN_DIR = $managedBin
- $env:UV_NO_CONFIG = "1"
- & $script:UvCmd tool install browser-use 2>&1 | Out-Null
- if ($LASTEXITCODE -eq 0) {
- Write-Success "Browser Use CLI installed"
- } else {
- Write-Warn "Browser Use CLI install failed (exit $LASTEXITCODE) -- browser automation falls back to built-in tools."
- Write-Info "Install later with: uv tool install browser-use (or via 'hermes tools')"
- }
- } catch {
- Write-Warn "Browser Use CLI install failed: $_"
- } finally {
- $ErrorActionPreference = $prevEAP
- Remove-Item Env:\UV_TOOL_BIN_DIR -ErrorAction SilentlyContinue
- Remove-Item Env:\UV_NO_CONFIG -ErrorAction SilentlyContinue
- }
-}
-
-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
- }
-}
-
-# 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"
- }
-
- 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
- }
-}
-
-# 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 { }
- })
- }
-
- # 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 { }
- })
- }
-
- 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')
-}
-
-# 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)
-}
-
-# 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 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 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 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 = "python"; Title = "Verifying Python $PythonVersion"; Category = "prereqs"; NeedsUserInput = $false; Worker = "Stage-Python" }
- @{ 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" }
- @{ 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
- }
- }
- }
-}
-
-# ============================================================================
-# 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
- }
-}
-
-# ----------------------------------------------------------------------------
-# Entry-point dispatch
-# ----------------------------------------------------------------------------
-#
-# All branches funnel through one try/catch so errors don't kill an `irm |
-# iex` PowerShell session, and so failures in stage-driver mode produce a
-# structured JSON error frame instead of a bare exception.
-
-# Dot-sourcing loads the installer's real functions for isolated behavioral
-# tests without running an install. Normal script and `irm | iex` entry points
-# are unchanged.
-if ($MyInvocation.InvocationName -eq ".") {
- return
-}
-
-try {
- if ($Ensure -ne "") {
- if ($PSBoundParameters.ContainsKey("Stage")) {
- Write-Err "Cannot use -Ensure and -Stage simultaneously"
- exit 1
- }
- Invoke-EnsureMode -Deps $Ensure
- exit 0
- }
- if ($PostInstall) {
- Invoke-PostInstallMode
- exit 0
- }
-
- if ($ProtocolVersion) {
- Write-Output $InstallStageProtocolVersion
- exit 0
- }
-
- if ($ShowResolvedPaths) {
- $script:ResolvedPathReport | ConvertTo-Json -Depth 5 -Compress | Write-Output
- exit 0
- }
-
- if ($Manifest) {
- $payload = @{
- protocol_version = $InstallStageProtocolVersion
- stages = @($InstallStages | ForEach-Object {
- @{
- name = $_.Name
- title = $_.Title
- category = $_.Category
- needs_user_input = $_.NeedsUserInput
- }
- })
- }
- $payload | ConvertTo-Json -Depth 5 -Compress | Write-Output
- exit 0
- }
-
- # Use PSBoundParameters rather than $Stage truthiness so that an
- # explicit `-Stage ""` from a misbehaving driver doesn't fall through
- # to the full-install Main path and silently kick off a destructive
- # operation. Empty string is a contract violation; surface it as
- # unknown-stage exit 2 with a structured JSON frame.
- if ($PSBoundParameters.ContainsKey("Stage")) {
- $def = Get-InstallStage -Name $Stage
- if (-not $def) {
- $err = @{
- ok = $false
- stage = $Stage
- reason = "unknown stage: $Stage. Run install.ps1 -Manifest to list valid stages."
- }
- $err | ConvertTo-Json -Compress | Write-Output
- exit 2
- }
- Step-OutOfInstallDir
- Invoke-Stage -StageDef $def
- exit 0
- }
-
- # Default: full install (today's behavior, plus optional -NonInteractive
- # and -Json layered on by the params above).
- Main
-} catch {
- if ($Json -or $Stage) {
- # Stage-driver mode: caller wants JSON they can parse. Emit a
- # structured error frame and exit non-zero -- BUT only if
- # Invoke-Stage didn't already emit one for this same failure.
- # The inner finally emits the authoritative per-stage frame
- # (with duration_ms + skipped fields); a second emit here
- # would produce two concatenated JSON objects on stdout and
- # break drivers that parse one-line-per-invocation.
- if (-not $script:_StageEmittedErrorFrame) {
- $err = @{
- ok = $false
- stage = if ($Stage) { $Stage } else { $null }
- reason = "$_"
- }
- $err | ConvertTo-Json -Compress | Write-Output
- }
- exit 1
- }
-
- # Interactive mode: keep today's friendly recovery hint.
- Write-Host ""
- Write-Err "Installation failed: $_"
- Write-Host ""
- Write-Info "If the error is unclear, try downloading and running the script directly:"
- Write-Host " Invoke-WebRequest -Uri 'https://hermes-agent.nousresearch.com/install.ps1' -OutFile install.ps1" -ForegroundColor Yellow
- Write-Host " .\install.ps1" -ForegroundColor Yellow
- Write-Host ""
+# No -Stage: run the whole ladder.
+foreach ($s in @("prerequisites","repository","venv","python-deps","node-deps","path","config","setup","gateway","complete")) {
+ Invoke-StageByName $s
}
diff --cc scripts/install.sh
index 249f750a808,81c1c7c7f79..6368b15c17d
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@@ -1,21 -1,85 +1,27 @@@
-#!/bin/bash
-# ============================================================================
-# Hermes Agent Installer
-# ============================================================================
-# Installation script for Linux, macOS, and Android/Termux.
-# Uses uv for desktop/server installs and Python's stdlib venv + pip on Termux.
-#
-# Usage:
-# curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash
-#
-# Or with options:
-# curl -fsSL ... | bash -s -- --no-venv --skip-setup
-#
-# ============================================================================
-
-set -e
-
-# Guard against environment leakage when the installer is launched from another
-# Python-driven tool session (e.g. Hermes terminal tool). A pre-set PYTHONPATH
-# can force pip/entrypoints to import a different checkout than the one being
-# installed, which makes fresh installs appear broken or stale.
-if [ -n "${PYTHONPATH:-}" ]; then
- echo "⚠ Ignoring inherited PYTHONPATH during install to avoid module shadowing"
- unset PYTHONPATH
-fi
-if [ -n "${PYTHONHOME:-}" ]; then
- echo "⚠ Ignoring inherited PYTHONHOME during install"
- unset PYTHONHOME
-fi
+#!/usr/bin/env bash
+# Hermes Agent bootstrap: git checkout + venv + hermes command on PATH.
+# Heavy dependencies (tool binaries, browsers, node) are pm's job after
+# this: `hermes pm install`. Stage protocol kept for Hermes-Setup:
+# --manifest print the stage list as JSON
+# --stage NAME [--json] run one stage
+# --non-interactive skip stages that need input
+# --include-desktop add the desktop build stage
+set -u
+ # Prevent uv from discovering config files (uv.toml, pyproject.toml) from the
+ # wrong user's home directory when running under sudo -u <user>. See #21269.
++# pm's own venv sync re-isolates (pm/packages.py::uv_env), so this bootstrap
++# hygiene can't break the locked sync the way it used to before pm owned it.
+ export UV_NO_CONFIG=1
+
-# Colors
-RED='\033[0;31m'
-GREEN='\033[0;32m'
-YELLOW='\033[0;33m'
-BLUE='\033[0;34m'
-MAGENTA='\033[0;35m'
-CYAN='\033[0;36m'
-NC='\033[0m' # No Color
-BOLD='\033[1m'
-
-# Configuration
-REPO_URL_SSH="[email protected]:NousResearch/hermes-agent.git"
-REPO_URL_HTTPS="https://github.com/NousResearch/hermes-agent.git"
-HERMES_HOME="${HERMES_HOME:-$HOME/.hermes}"
-# INSTALL_DIR is resolved AFTER arg parsing and OS detection so we can pick an
-# FHS-style layout for root installs. Track whether the user gave us an
-# explicit directory — if so we never override it.
-if [ -n "${HERMES_INSTALL_DIR:-}" ]; then
- INSTALL_DIR="$HERMES_INSTALL_DIR"
- INSTALL_DIR_EXPLICIT=true
-else
- INSTALL_DIR=""
- INSTALL_DIR_EXPLICIT=false
-fi
-PYTHON_VERSION="3.11"
-NODE_VERSION="26"
-
-# FHS-style root install layout (set by resolve_install_layout when applicable):
-# code at /usr/local/lib/hermes-agent, command at /usr/local/bin/hermes,
-# data still at /root/.hermes (HERMES_HOME). Matches Claude Code / Codex CLI
-# and keeps Docker bind-mounted /root/ volumes lean.
-ROOT_FHS_LAYOUT=false
-DETECTED_BROWSER_EXECUTABLE=""
-
-# Options
-USE_VENV=true
-RUN_SETUP=true
-SKIP_BROWSER=false
-SKIP_COMPUTER_USE=false
-NO_SKILLS=false
+REPO_URL="${HERMES_REPO_URL:-https://github.com/NousResearch/hermes-agent.git}"
BRANCH="main"
INSTALL_COMMIT=""
-FORCE_COMMIT=false
-ENSURE_DEPS=""
-
-MANIFEST_MODE=false
-STAGE_NAME=""
-JSON_OUTPUT=false
+INSTALL_DIR="${HERMES_INSTALL_DIR:-$HOME/.hermes/hermes-agent}"
+HERMES_HOME="${HERMES_HOME:-$HOME/.hermes}"
+STAGE=""
+WANT_MANIFEST=false
+JSON=false
NON_INTERACTIVE=false
INCLUDE_DESKTOP=false
@@@ -174,197 -615,3064 +180,213 @@@ json_frame()
fi
}
-check_python() {
- if [ "$DISTRO" = "termux" ]; then
- log_info "Checking Termux Python..."
- if command -v python >/dev/null 2>&1; then
- PYTHON_PATH="$(command -v python)"
- if "$PYTHON_PATH" -c 'import sys; raise SystemExit(0 if sys.version_info >= (3, 11) else 1)' 2>/dev/null; then
- PYTHON_FOUND_VERSION="$("$PYTHON_PATH" --version 2>/dev/null)"
- log_success "Python found: $PYTHON_FOUND_VERSION"
- return 0
- fi
- fi
-
- log_info "Installing Python via pkg..."
- pkg install -y python >/dev/null
- PYTHON_PATH="$(command -v python)"
- PYTHON_FOUND_VERSION="$("$PYTHON_PATH" --version 2>/dev/null)"
- log_success "Python installed: $PYTHON_FOUND_VERSION"
- return 0
- fi
-
- log_info "Checking Python $PYTHON_VERSION..."
-
- # Let uv handle Python — it can download and manage Python versions
- # First check if a suitable Python is already available
- if PYTHON_PATH="$("$UV_CMD" python find "$PYTHON_VERSION" 2>/dev/null)"; then
- PYTHON_FOUND_VERSION="$("$PYTHON_PATH" --version 2>/dev/null)"
- log_success "Python found: $PYTHON_FOUND_VERSION"
- return 0
+emit_manifest() {
+ local desktop=""
+ if [ "$INCLUDE_DESKTOP" = true ]; then
+ desktop='{"name":"desktop","title":"Build desktop app","category":"runtime","needs_user_input":false},'
+ fi
+ printf '%s' '{"protocol_version":1,"stages":['
+ printf '%s' '{"name":"prerequisites","title":"System prerequisites","category":"runtime","needs_user_input":false},'
+ printf '%s' '{"name":"repository","title":"Download Hermes Agent","category":"runtime","needs_user_input":false},'
+ printf '%s' '{"name":"venv","title":"Create Python environment","category":"runtime","needs_user_input":false},'
+ printf '%s' '{"name":"python-deps","title":"Install Python dependencies","category":"runtime","needs_user_input":false},'
+ printf '%s' '{"name":"node-deps","title":"Install tool dependencies","category":"runtime","needs_user_input":false},'
+ printf '%s' '{"name":"path","title":"Install hermes command","category":"runtime","needs_user_input":false},'
+ printf '%s' '{"name":"config","title":"Prepare config and skills","category":"configuration","needs_user_input":false},'
+ printf '%s' '{"name":"setup","title":"Configure API keys and settings","category":"configuration","needs_user_input":true},'
+ printf '%s' '{"name":"gateway","title":"Configure gateway service","category":"configuration","needs_user_input":true},'
+ printf '%s' "$desktop"
+ printf '%s\n' '{"name":"complete","title":"Finish install","category":"runtime","needs_user_input":false}]}'
+}
+
+stage_prerequisites() {
+ command -v git >/dev/null 2>&1 || fail "git is required. Install it with your system package manager."
+ command -v curl >/dev/null 2>&1 || fail "curl is required. Install it with your system package manager."
+ log "prerequisites ok (git, curl)"
+}
+
+stage_repository() {
+ if [ -d "$INSTALL_DIR/.git" ]; then
+ log "updating $INSTALL_DIR"
+ git -C "$INSTALL_DIR" fetch origin "$BRANCH" || fail "git fetch failed"
+ git -C "$INSTALL_DIR" checkout "$BRANCH" || fail "git checkout failed"
+ git -C "$INSTALL_DIR" pull --ff-only origin "$BRANCH" || log "not fast-forwardable; keeping local state"
+ else
+ log "cloning $REPO_URL ($BRANCH) into $INSTALL_DIR"
+ mkdir -p "$(dirname "$INSTALL_DIR")"
+ git clone --branch "$BRANCH" "$REPO_URL" "$INSTALL_DIR" || fail "git clone failed"
fi
-
- # Python not found — use uv to install it (no sudo needed!)
- log_info "Python $PYTHON_VERSION not found, installing via uv..."
- if "$UV_CMD" python install "$PYTHON_VERSION"; then
- PYTHON_PATH="$("$UV_CMD" python find "$PYTHON_VERSION")"
- PYTHON_FOUND_VERSION="$("$PYTHON_PATH" --version 2>/dev/null)"
- log_success "Python installed: $PYTHON_FOUND_VERSION"
- else
- log_error "Failed to install Python $PYTHON_VERSION"
- log_info "Install Python $PYTHON_VERSION manually, then re-run this script"
- exit 1
+ if [ -n "$INSTALL_COMMIT" ]; then
+ git -C "$INSTALL_DIR" checkout "$INSTALL_COMMIT" || fail "could not pin commit $INSTALL_COMMIT"
+ fi
+}
+
+stage_venv() {
+ ensure_uv
+ log "creating venv"
+ (cd "$INSTALL_DIR" && "$UV_CMD" venv --allow-existing venv) || fail "uv venv failed"
+}
+
- stage_python_deps() {
++# Delegate the whole python+venv+tools install to pm: stage the pinned uv,
++# let uv run pm.cli, and pm provisions the interpreter, the venv (default
++# extras = [all], so it matches what `hermes update` force-syncs), and the
++# tool store — all hash-verified against pm/lock.json + uv.lock. install.sh
++# no longer runs `uv sync` directly; pm is the single install authority
++# (the run_locked_uv_sync contract moved into pm/packages.py::uv_env).
++bootstrap_pm() {
+ ensure_uv
- log "syncing python dependencies (uv sync --frozen)"
- (cd "$INSTALL_DIR" && VIRTUAL_ENV="$INSTALL_DIR/venv" "$UV_CMD" sync --frozen --extra all --active) || fail "uv sync failed"
++ local _py
++ _py="$(awk '/^ "python": \{/ { in_py = 1 }
++ in_py && /^ "version":/ { gsub(/.*: "|"$|",$/, ""); print; exit }' \
++ "$INSTALL_DIR/pm/lock.json" | cut -d+ -f1 | cut -d. -f1,2)"
++ [ -n "$_py" ] || _py="3.11"
++ log "delegating python + venv + tools to pm (hash-verified via uv.lock)"
++ (cd "$INSTALL_DIR" && "$UV_CMD" run --no-project --python "$_py" python -m pm.cli install) \
++ || fail "pm install failed"
++}
++
++stage_python_deps() {
++ bootstrap_pm
+}
+
+stage_node_deps() {
+ # Tool binaries, node, browsers: pm packages, installed on demand or
+ # via `hermes pm install`. Nothing to do at bootstrap time.
+ log "tool dependencies are managed by pm (hermes pm install)"
+}
+
+stage_path() {
+ local link_dir="$HOME/.local/bin"
+ mkdir -p "$link_dir"
+ rm -f "$link_dir/hermes"
+ # Boot wrapper: exec the pm STORE python with PYTHONPATH=repo:venv-
+ # site-packages (repo first). Never boots through venv/bin/python —
+ # the venv is only a uv sync target and pyvenv.cfg is inert dead
+ # config (pm work item 3). Store root + python entry mirror
+ # pm/paths.py / pm facts.json; resolved at BOOT so the wrapper picks
+ # up `hermes pm install` whenever it materializes the store.
+ cat > "$link_dir/hermes" <<WRAPPER
+#!/usr/bin/env bash
+# Hermes boot wrapper: store python + PYTHONPATH (never the venv python).
+set -u
+repo="\${HERMES_INSTALL_DIR:-$INSTALL_DIR}"
+unset PYTHONHOME
+runtime="\${HERMES_RUNTIME_DIR:-}"
+if [ -z "\$runtime" ] && [ -f "\$repo/install-stamp.json" ]; then
+ runtime="\$(sed -n 's/.*"runtimeDir"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "\$repo/install-stamp.json" | head -n 1)"
+fi
+[ -n "\$runtime" ] || runtime="\$HOME/.hermes/tools"
+store_py=""
+if [ -f "\$runtime/facts.json" ]; then
+ entry="\$(sed -n 's/.*"entry"[[:space:]]*:[[:space:]]*"\(python-[^"]*\)".*/\1/p' "\$runtime/facts.json" | head -n 1)"
+ if [ -n "\$entry" ] && [ -x "\$runtime/\$entry/bin/python3" ]; then
+ store_py="\$runtime/\$entry/bin/python3"
fi
-}
-
-# Best-effort automatic git provisioning, mirroring install.ps1's Install-Git
-# (which downloads PortableGit on Windows). git is required to clone the repo,
-# and a fresh "normie" machine with no developer tools won't have it. Returns 0
-# if git is available afterwards, non-zero otherwise (caller prints manual
-# instructions and aborts).
-attempt_install_git() {
- case "$OS" in
- macos)
- # Prefer Homebrew — fully headless when present.
- if command -v brew >/dev/null 2>&1; then
- log_info "Installing Git via Homebrew..."
- brew install git >/dev/null 2>&1 || true
- command -v git >/dev/null 2>&1 && return 0
- fi
- # Fall back to Apple Command Line Tools, which provide git AND the
- # compiler some Python wheels need. `xcode-select --install` pops a
- # system dialog (Apple gates CLT behind it — it cannot be fully
- # silent without MDM), so we trigger it and poll for git to appear.
- if command -v xcode-select >/dev/null 2>&1; then
- log_info "Requesting Apple Command Line Tools (provides git + compiler)..."
- log_info "If a macOS dialog appears, click \"Install\" and accept the license."
- xcode-select --install >/dev/null 2>&1 || true
- local waited=0
- local timeout=900
- while [ "$waited" -lt "$timeout" ]; do
- if command -v git >/dev/null 2>&1 && git --version >/dev/null 2>&1; then
- return 0
- fi
- sleep 5
- waited=$((waited + 5))
- if [ $((waited % 60)) -eq 0 ]; then
- log_info "Still waiting for Command Line Tools install ($((waited / 60))m)..."
- fi
- done
- fi
- return 1
- ;;
- linux)
- local sudo_cmd=""
- if [ "$(id -u 2>/dev/null || echo 1000)" -ne 0 ]; then
- command -v sudo >/dev/null 2>&1 && sudo_cmd="sudo"
- fi
- case "$DISTRO" in
- ubuntu|debian)
- log_info "Installing Git via apt..."
- $sudo_cmd env DEBIAN_FRONTEND=noninteractive apt-get update -qq >/dev/null 2>&1 || true
- $sudo_cmd env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq git >/dev/null 2>&1 || true
- ;;
- fedora)
- log_info "Installing Git via dnf..."
- $sudo_cmd dnf install -y git >/dev/null 2>&1 || true
- ;;
- arch)
- log_info "Installing Git via pacman..."
- $sudo_cmd pacman -S --noconfirm git >/dev/null 2>&1 || true
- ;;
- *)
- return 1
- ;;
- esac
- command -v git >/dev/null 2>&1 && return 0
- return 1
- ;;
+fi
+if [ -z "\$store_py" ]; then
+ for d in "\$runtime"/python-*/bin/python3; do
+ [ -x "\$d" ] && store_py="\$d"
+ done
+fi
+if [ -z "\$store_py" ]; then
+ echo "hermes: no pm store interpreter under \$runtime - run 'hermes pm install' first" >&2
+ exit 1
+fi
+site=""
+for d in "\$repo"/venv/lib/python3.*/site-packages "\$repo"/.venv/lib/python3.*/site-packages; do
+ [ -d "\$d" ] && site="\$d"
+done
+export PYTHONPATH="\$repo\${site:+:\$site}"
+exec "\$store_py" "\$repo/hermes" "\$@"
+WRAPPER
+ chmod +x "$link_dir/hermes"
+ case ":$PATH:" in
+ *":$link_dir:"*) : ;;
+ *) log "add $link_dir to your PATH to use the hermes command" ;;
esac
- return 1
+ log "hermes command installed at $link_dir/hermes"
}
-check_git() {
- log_info "Checking Git..."
-
- # On fresh macOS /usr/bin/git is a stub that exits non-zero until CLT is installed.
- if command -v git &> /dev/null && git --version &> /dev/null; then
- GIT_VERSION=$(git --version | awk '{print $3}')
- log_success "Git $GIT_VERSION found"
- return 0
- fi
-
- log_error "Git not found"
-
- if [ "$DISTRO" = "termux" ]; then
- log_info "Installing Git via pkg..."
- pkg install -y git >/dev/null
- if command -v git >/dev/null 2>&1; then
- GIT_VERSION=$(git --version | awk '{print $3}')
- log_success "Git $GIT_VERSION installed"
- return 0
- fi
+stage_config() {
+ mkdir -p "$HERMES_HOME"/cron "$HERMES_HOME"/sessions "$HERMES_HOME"/logs \
+ "$HERMES_HOME"/pairing "$HERMES_HOME"/hooks "$HERMES_HOME"/image_cache \
+ "$HERMES_HOME"/audio_cache "$HERMES_HOME"/memories "$HERMES_HOME"/skills
+ if [ ! -f "$HERMES_HOME/.env" ]; then
+ cp "$INSTALL_DIR/.env.example" "$HERMES_HOME/.env" 2>/dev/null || touch "$HERMES_HOME/.env"
fi
-
- # Try to install it automatically before giving up (parity with install.ps1).
- log_info "Attempting to install Git automatically..."
- if attempt_install_git; then
- GIT_VERSION=$(git --version | awk '{print $3}')
- log_success "Git $GIT_VERSION installed"
- return 0
+ chmod 600 "$HERMES_HOME/.env"
+ if [ ! -f "$HERMES_HOME/config.yaml" ] && [ -f "$INSTALL_DIR/cli-config.yaml.example" ]; then
+ cp "$INSTALL_DIR/cli-config.yaml.example" "$HERMES_HOME/config.yaml"
fi
-
- log_warn "Could not install Git automatically. Please install it manually:"
-
- case "$OS" in
- linux)
- case "$DISTRO" in
- ubuntu|debian)
- log_info " sudo apt update && sudo apt install git"
- ;;
- fedora)
- log_info " sudo dnf install git"
- ;;
- arch)
- log_info " sudo pacman -S git"
- ;;
- *)
- log_info " Use your package manager to install git"
- ;;
- esac
- ;;
- android)
- log_info " pkg install git"
- ;;
- macos)
- log_info " xcode-select --install"
- log_info " Or: brew install git"
- ;;
- esac
-
- exit 1
+ log "config prepared in $HERMES_HOME"
}
-# Node deps below (install_node_deps) build native addons — most notably
-# node-pty, which every install needs — via node-gyp. node-gyp needs a C/C++
-# toolchain (make + a compiler); Python and make are already covered by
-# check_python/check_node's prerequisites, but the compiler itself was never
-# checked, so a missing g++/clang++ only surfaced as a wall of node-gyp/make
-# output deep inside `npm install`, with no earlier, actionable warning.
-# Best-effort like install_system_packages: warns and lets the caller decide
-# whether to proceed rather than aborting the whole install (unlike git,
-# which is hard-required much earlier for clone_repo).
-check_cxx_compiler() {
- log_info "Checking for a C++ compiler (needed to build native Node modules like node-pty)..."
-
- if command -v g++ &> /dev/null || command -v clang++ &> /dev/null; then
- log_success "C++ compiler found"
- HAS_CXX_COMPILER=true
- return 0
- fi
-
- HAS_CXX_COMPILER=false
- log_warn "No C++ compiler found"
-
- case "$OS" in
- macos)
- # Same Command Line Tools path as attempt_install_git — CLT provides
- # git AND a compiler, so this is usually already satisfied by the
- # check_git step above. Handles the case where git was present
- # without CLT (e.g. installed via Homebrew) so CLT never triggered.
- log_info "Attempting to install Xcode Command Line Tools (provides a C++ compiler)..."
- log_info "If a macOS dialog appears, click \"Install\" and accept the license."
- xcode-select --install >/dev/null 2>&1 || true
- local waited=0
- local timeout=900
- while [ "$waited" -lt "$timeout" ]; do
- if command -v g++ &> /dev/null || command -v clang++ &> /dev/null; then
- log_success "C++ compiler installed"
- HAS_CXX_COMPILER=true
- return 0
- fi
- sleep 5
- waited=$((waited + 5))
- if [ $((waited % 60)) -eq 0 ]; then
- log_info "Still waiting for Command Line Tools install ($((waited / 60))m)..."
- fi
- done
- ;;
- linux)
- local sudo_cmd=""
- if [ "$(id -u 2>/dev/null || echo 1000)" -ne 0 ]; then
- command -v sudo >/dev/null 2>&1 && sudo_cmd="sudo"
- fi
- log_info "Attempting to install a C++ compiler automatically..."
- case "$DISTRO" in
- ubuntu|debian)
- log_info "Installing build-essential via apt..."
- $sudo_cmd env DEBIAN_FRONTEND=noninteractive apt-get update -qq >/dev/null 2>&1 || true
- $sudo_cmd env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq build-essential >/dev/null 2>&1 || true
- ;;
- fedora)
- log_info "Installing gcc-c++ via dnf..."
- $sudo_cmd dnf install -y gcc-c++ >/dev/null 2>&1 || true
- ;;
- arch)
- log_info "Installing base-devel via pacman..."
- $sudo_cmd pacman -S --noconfirm base-devel >/dev/null 2>&1 || true
- ;;
- esac
- if command -v g++ &> /dev/null || command -v clang++ &> /dev/null; then
- log_success "C++ compiler installed"
- HAS_CXX_COMPILER=true
- return 0
- fi
- ;;
- esac
-
- log_warn "Could not install a C++ compiler automatically."
- log_warn "Node steps that compile native modules (e.g. node-pty) will fail below until one is installed."
- log_info "Install it manually, then re-run this installer:"
- case "$OS" in
- linux)
- case "$DISTRO" in
- ubuntu|debian) log_info " sudo apt install build-essential" ;;
- fedora) log_info " sudo dnf install gcc-c++" ;;
- arch) log_info " sudo pacman -S base-devel" ;;
- *) log_info " Install a C++ compiler (g++/gcc-c++) via your package manager" ;;
- esac
- ;;
- android)
- log_info " pkg install clang"
- ;;
- macos)
- log_info " xcode-select --install"
- ;;
- esac
- return 1
+stage_setup() {
+ if [ "$NON_INTERACTIVE" = true ]; then return 0; fi
+ "$INSTALL_DIR/venv/bin/python" "$INSTALL_DIR/hermes" setup || true
}
-# The dependency tree supports Node 22.22+, 24.11+, and 26+. nanoid 6 excludes
-# Node 23 and 25 while its >=26 arm accepts later releases, and @babel/* 8.x
-# requires ^22.18.0 || >=24.11.0 — so accepting 23/25 or an early Node 24
-# here only defers the failure to `npm ci` under engine-strict. Keep this in
-# sync with the root package.json. Anything outside the supported lines is
-# replaced with the Hermes-managed Node $NODE_VERSION.
-node_satisfies_build() {
- local ver="${1#v}"
- case "$ver" in *-*) return 1 ;; esac
- local major="${ver%%.*}"
- local minor="${ver#*.}"; minor="${minor%%.*}"
- case "$major" in ''|*[!0-9]*) return 1 ;; esac
- case "$minor" in ''|*[!0-9]*) minor=0 ;; esac
- if [ "$major" -eq 22 ] && [ "$minor" -ge 22 ]; then return 0; fi
- if [ "$major" -eq 24 ] && [ "$minor" -ge 11 ]; then return 0; fi
- if [ "$major" -ge 26 ]; then return 0; fi
- return 1
+stage_gateway() {
+ if [ "$NON_INTERACTIVE" = true ]; then return 0; fi
+ "$INSTALL_DIR/venv/bin/python" "$INSTALL_DIR/hermes" gateway install || true
}
-# npm 11.10.0–11.16.x honor `min-release-age` but ignore
-# `min-release-age-exclude`, both of which `.npmrc` sets. That combination
-# applies the 14-day age gate to packages we deliberately exempted, so every
-# install fails ETARGET on a freshly published dependency. The root
-# package.json excludes that band via `engines.npm`, and `engine-strict=true`
-# makes it fatal — so a system npm in the band cannot install this repo, no
-# matter how new its Node is. Returns 0 when the npm is usable.
-npm_supports_npmrc() {
- local ver="${1#v}"
- local major="${ver%%.*}"
- local minor="${ver#*.}"; minor="${minor%%.*}"
- case "$major" in ''|*[!0-9]*) return 1 ;; esac
- case "$minor" in ''|*[!0-9]*) minor=0 ;; esac
- # The bad band is 11.10.0 through 11.16.x.
- if [ "$major" -eq 11 ] && [ "$minor" -ge 10 ] && [ "$minor" -le 16 ]; then
- return 1
- fi
- return 0
+stage_desktop() {
+ "$INSTALL_DIR/venv/bin/python" "$INSTALL_DIR/hermes" desktop build || fail "desktop build failed"
}
-check_node() {
- log_info "Checking Node.js (for browser tools)..."
-
- # Repair pre-existing Hermes-managed installs where `npm install -g` lands
- # off PATH. No-op when there's no managed Node, so this is safe to run on
- # every install — including re-runs that skip the Node (re)install below.
- configure_managed_node_npm_prefix
-
- # The system toolchain is only usable when BOTH halves work: a Node new
- # enough for the desktop build AND an npm that can read our .npmrc. A
- # bad-band npm (see npm_supports_npmrc) fails `npm ci` outright, and the
- # managed Node we install instead bundles one that works.
- #
- # npm must actually be reachable, not just node: a stray `node` symlink
- # without a sibling npm (leftover from a node version manager) makes
- # `command -v node` succeed while every later `npm install` silently
- # fails and the desktop build dies with an opaque "Node.js / npm
- # unavailable" (#77003). Node only counts as found when npm resolves on
- # the same PATH.
- if command -v node &> /dev/null && command -v npm &> /dev/null \
- && node_satisfies_build "$(node --version)"; then
- if npm_supports_npmrc "$(npm --version 2>/dev/null)"; then
- log_success "Node.js $(node --version) found"
- HAS_NODE=true
- return 0
- fi
- log_warn "npm $(npm --version) cannot honor this repo's .npmrc (npm 11.10-11.16 ignore"
- log_warn "min-release-age-exclude) — installing Hermes-managed Node $NODE_VERSION instead..."
- install_node
- return
- fi
-
- # Prefer a Hermes-managed Node from a previous run over a too-old system one.
- if [ -x "$HERMES_HOME/node/bin/node" ] && [ -x "$HERMES_HOME/node/bin/npm" ] \
- && node_satisfies_build "$("$HERMES_HOME/node/bin/node" --version)"; then
- export PATH="$HERMES_HOME/node/bin:$PATH"
- log_success "Node.js $("$HERMES_HOME/node/bin/node" --version) found (Hermes-managed)"
- HAS_NODE=true
- return 0
+stage_complete() {
+ local commit
+ commit="$INSTALL_COMMIT"
+ [ -n "$commit" ] || commit=$(git -C "$INSTALL_DIR" rev-parse HEAD 2>/dev/null) || commit=""
+ if [ -n "$commit" ]; then
+ printf '{\n "schemaVersion": 1,\n "pinnedCommit": "%s",\n "pinnedBranch": "%s",\n "completedAt": "%s"\n}\n' \
+ "$commit" "$BRANCH" "$(date -u +%Y-%m-%dT%H:%M:%S.000Z)" > "$INSTALL_DIR/.hermes-bootstrap-complete.tmp"
+ mv -f "$INSTALL_DIR/.hermes-bootstrap-complete.tmp" "$INSTALL_DIR/.hermes-bootstrap-complete"
fi
-
- if command -v node &> /dev/null && ! command -v npm &> /dev/null; then
- log_warn "node found but npm is not on PATH (stray node symlink?) — installing Hermes-managed Node $NODE_VERSION LTS..."
- elif command -v node &> /dev/null; then
- log_warn "Node.js $(node --version) is unsupported (Hermes requires Node 22.22+, 24.11+, or 26+) — installing Hermes-managed Node $NODE_VERSION..."
- elif [ "$DISTRO" = "termux" ]; then
- log_info "Node.js not found — installing Node.js via pkg..."
- else
- log_info "Node.js not found — installing Node.js $NODE_VERSION LTS..."
- fi
- install_node
+ log "install complete. Run: hermes"
}
-install_node() {
- if [ "$DISTRO" = "termux" ]; then
- log_info "Installing Node.js via pkg..."
- if pkg install -y nodejs >/dev/null; then
- local installed_ver
- installed_ver=$(node --version 2>/dev/null)
- log_success "Node.js $installed_ver installed via pkg"
- HAS_NODE=true
- else
- log_warn "Failed to install Node.js via pkg"
- HAS_NODE=false
- fi
- return 0
- fi
-
- local arch=$(uname -m)
- local node_arch
- case "$arch" in
- x86_64) node_arch="x64" ;;
- aarch64|arm64) node_arch="arm64" ;;
- armv7l) node_arch="armv7l" ;;
- *)
- log_warn "Unsupported architecture ($arch) for Node.js auto-install"
- log_info "Install manually: https://nodejs.org/en/download/"
- HAS_NODE=false
- return 0
- ;;
- esac
-
- local node_os
- case "$OS" in
- linux) node_os="linux" ;;
- macos) node_os="darwin" ;;
- *)
- log_warn "Unsupported OS for Node.js auto-install"
- HAS_NODE=false
- return 0
- ;;
+run_stage() {
+ case "$1" in
+ prerequisites) stage_prerequisites ;;
+ repository) stage_repository ;;
+ venv) stage_venv ;;
+ python-deps) stage_python_deps ;;
+ node-deps) stage_node_deps ;;
+ path) stage_path ;;
+ config) stage_config ;;
+ setup) stage_setup ;;
+ gateway) stage_gateway ;;
+ desktop) stage_desktop ;;
+ complete) stage_complete ;;
+ *) echo "unknown stage: $1" >&2; exit 2 ;;
esac
-
- # Resolve the latest v${NODE_VERSION}.x.x tarball name from the index page
- local index_url="https://nodejs.org/dist/latest-v${NODE_VERSION}.x/"
- local tarball_name
- tarball_name=$(curl -fsSL "$index_url" \
- | grep -oE "node-v${NODE_VERSION}\.[0-9]+\.[0-9]+-${node_os}-${node_arch}\.tar\.xz" \
- | head -1)
-
- # Fallback to .tar.gz if .tar.xz not available
- if [ -z "$tarball_name" ]; then
- tarball_name=$(curl -fsSL "$index_url" \
- | grep -oE "node-v${NODE_VERSION}\.[0-9]+\.[0-9]+-${node_os}-${node_arch}\.tar\.gz" \
- | head -1)
- fi
-
- if [ -z "$tarball_name" ]; then
- log_warn "Could not find Node.js $NODE_VERSION binary for $node_os-$node_arch"
- log_info "Install manually: https://nodejs.org/en/download/"
- HAS_NODE=false
- return 0
- fi
-
- local download_url="${index_url}${tarball_name}"
- local tmp_dir
- tmp_dir=$(mktemp -d)
-
- log_info "Downloading $tarball_name..."
- if ! curl -fsSL "$download_url" -o "$tmp_dir/$tarball_name"; then
- log_warn "Download failed"
- rm -rf "$tmp_dir"
- HAS_NODE=false
- return 0
- fi
-
- log_info "Extracting to ~/.hermes/node/..."
- if [[ "$tarball_name" == *.tar.xz ]]; then
- tar xf "$tmp_dir/$tarball_name" -C "$tmp_dir"
- else
- tar xzf "$tmp_dir/$tarball_name" -C "$tmp_dir"
- fi
-
- local extracted_dir
- extracted_dir=$(ls -d "$tmp_dir"/node-v* 2>/dev/null | head -1)
-
- if [ ! -d "$extracted_dir" ]; then
- log_warn "Extraction failed"
- rm -rf "$tmp_dir"
- HAS_NODE=false
- return 0
- fi
-
- # Place into ~/.hermes/node/ and symlink binaries into the same bin dir
- # the hermes command uses (get_command_link_dir): /usr/local/bin for root
- # FHS installs, $PREFIX/bin on Termux, ~/.local/bin otherwise.
- rm -rf "$HERMES_HOME/node"
- mkdir -p "$HERMES_HOME"
- mv "$extracted_dir" "$HERMES_HOME/node"
- rm -rf "$tmp_dir"
-
- local node_link_dir
- node_link_dir="$(get_command_link_dir)"
- mkdir -p "$node_link_dir"
- ln -sf "$HERMES_HOME/node/bin/node" "$node_link_dir/node"
- ln -sf "$HERMES_HOME/node/bin/npm" "$node_link_dir/npm"
- ln -sf "$HERMES_HOME/node/bin/npx" "$node_link_dir/npx"
-
- configure_managed_node_npm_prefix
-
- export PATH="$HERMES_HOME/node/bin:$PATH"
-
- local installed_ver
- installed_ver=$("$HERMES_HOME/node/bin/node" --version 2>/dev/null)
- log_success "Node.js $installed_ver installed to ~/.hermes/node/"
- HAS_NODE=true
}
-check_network_prerequisites() {
- log_info "Checking internet connectivity for package install and web tools..."
-
- local url
- local failed=false
- local checks=("https://pypi.org/simple/" "https://duckduckgo.com/")
-
- if ! command -v curl >/dev/null 2>&1; then
- log_warn "curl not found; skipping connectivity probes"
- return 0
- fi
-
- # Run the probes in parallel — serially, two blocked probes cost
- # 2 × --max-time (16 s) before the user sees any useful error; in
- # parallel the worst case is one --max-time (8 s).
- local pids=()
- local tmpdir
- tmpdir=$(mktemp -d)
- local i=0
- for url in "${checks[@]}"; do
- (
- if curl -fsSI --max-time 8 "$url" >/dev/null 2>&1; then
- : > "$tmpdir/ok_$i"
- fi
- ) &
- pids+=($!)
- i=$((i + 1))
- done
- wait "${pids[@]}" 2>/dev/null
-
- i=0
- for url in "${checks[@]}"; do
- if [ ! -e "$tmpdir/ok_$i" ]; then
- failed=true
- log_warn "Could not reach $url"
- fi
- i=$((i + 1))
- done
- rm -rf "$tmpdir"
-
- if [ "$failed" = false ]; then
- log_success "Internet connectivity looks good"
- return 0
- fi
-
- if [ "$DISTRO" = "termux" ]; then
- log_warn "Termux network prerequisites may be incomplete."
- log_info "Try: pkg install -y ca-certificates curl && pkg update"
- log_info "If mirrors are stale: termux-change-repo"
- log_info "Then test: curl -I https://pypi.org/simple/ && curl -I https://duckduckgo.com/"
- else
- log_warn "Network checks failed. Hermes install may complete, but web search and dependency downloads can fail."
- log_info "Verify internet/DNS and retry if pip install fails."
- fi
-}
+if [ "$WANT_MANIFEST" = true ]; then
+ emit_manifest
+ exit 0
+fi
-install_system_packages() {
- # Detect what's missing
- HAS_RIPGREP=false
- HAS_FFMPEG=false
- local need_ripgrep=false
- local need_ffmpeg=false
+check_platform
- log_info "Checking ripgrep (fast file search)..."
- if command -v rg &> /dev/null; then
- log_success "$(rg --version | head -1) found"
- HAS_RIPGREP=true
- else
- need_ripgrep=true
+if [ -n "$STAGE" ]; then
+ if [ "$NON_INTERACTIVE" = true ] && { [ "$STAGE" = setup ] || [ "$STAGE" = gateway ]; }; then
+ [ "$JSON" = true ] && json_frame true "$STAGE" true "needs user input"
+ exit 0
fi
-
- log_info "Checking ffmpeg (TTS voice messages)..."
- if command -v ffmpeg &> /dev/null; then
- local ffmpeg_ver=$(ffmpeg -version 2>/dev/null | head -1 | awk '{print $3}')
- log_success "ffmpeg $ffmpeg_ver found"
- HAS_FFMPEG=true
+ if run_stage "$STAGE"; then
+ [ "$JSON" = true ] && json_frame true "$STAGE" false
+ exit 0
else
- need_ffmpeg=true
+ rc=$?
+ [ "$JSON" = true ] && json_frame false "$STAGE" false "stage failed"
+ exit "$rc"
fi
+fi
- # Termux always needs the Android build toolchain for the tested pip path,
- # even when ripgrep/ffmpeg are already present.
- if [ "$DISTRO" = "termux" ]; then
- local termux_pkgs=(clang rust make pkg-config libffi openssl ca-certificates curl)
- if [ "$need_ripgrep" = true ]; then
- termux_pkgs+=("ripgrep")
- fi
- if [ "$need_ffmpeg" = true ]; then
- termux_pkgs+=("ffmpeg")
- fi
-
- log_info "Installing Termux packages: ${termux_pkgs[*]}"
- if pkg install -y "${termux_pkgs[@]}" >/dev/null; then
- [ "$need_ripgrep" = true ] && HAS_RIPGREP=true && log_success "ripgrep installed"
- [ "$need_ffmpeg" = true ] && HAS_FFMPEG=true && log_success "ffmpeg installed"
- log_success "Termux build dependencies installed"
- return 0
- fi
-
- log_warn "Could not auto-install all Termux packages"
- log_info "Install manually: pkg install ${termux_pkgs[*]}"
- return 0
- fi
-
- # Nothing to install — done
- if [ "$need_ripgrep" = false ] && [ "$need_ffmpeg" = false ]; then
- return 0
- fi
-
- # Build a human-readable description + package list
- local desc_parts=()
- local pkgs=()
- if [ "$need_ripgrep" = true ]; then
- desc_parts+=("ripgrep for faster file search")
- pkgs+=("ripgrep")
- fi
- if [ "$need_ffmpeg" = true ]; then
- desc_parts+=("ffmpeg for TTS voice messages")
- pkgs+=("ffmpeg")
- fi
- local description
- description=$(IFS=" and "; echo "${desc_parts[*]}")
-
- # ── macOS: brew ──
- if [ "$OS" = "macos" ]; then
- if command -v brew &> /dev/null; then
- log_info "Installing ${pkgs[*]} via Homebrew..."
- if brew install "${pkgs[@]}"; then
- [ "$need_ripgrep" = true ] && HAS_RIPGREP=true && log_success "ripgrep installed"
- [ "$need_ffmpeg" = true ] && HAS_FFMPEG=true && log_success "ffmpeg installed"
- return 0
- fi
- fi
- log_warn "Could not auto-install (brew not found or install failed)"
- log_info "Install manually: brew install ${pkgs[*]}"
- return 0
- fi
-
- # ── Linux: resolve package manager command ──
- local pkg_install=""
- case "$DISTRO" in
- ubuntu|debian) pkg_install="apt install -y" ;;
- fedora) pkg_install="dnf install -y" ;;
- arch) pkg_install="pacman -S --noconfirm" ;;
- esac
-
- if [ -n "$pkg_install" ]; then
- local install_cmd="$pkg_install ${pkgs[*]}"
-
- # Prevent needrestart/whiptail dialogs from blocking non-interactive installs
- case "$DISTRO" in
- ubuntu|debian) export DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a ;;
- esac
-
- # Already root — just install
- if [ "$(id -u)" -eq 0 ]; then
- log_info "Installing ${pkgs[*]}..."
- if $install_cmd; then
- [ "$need_ripgrep" = true ] && HAS_RIPGREP=true && log_success "ripgrep installed"
- [ "$need_ffmpeg" = true ] && HAS_FFMPEG=true && log_success "ffmpeg installed"
- return 0
- fi
- # Passwordless sudo — just install
- elif command -v sudo &> /dev/null && sudo -n true 2>/dev/null; then
- log_info "Installing ${pkgs[*]}..."
- if sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a $install_cmd; then
- [ "$need_ripgrep" = true ] && HAS_RIPGREP=true && log_success "ripgrep installed"
- [ "$need_ffmpeg" = true ] && HAS_FFMPEG=true && log_success "ffmpeg installed"
- return 0
- fi
- # sudo needs password — ask once for everything
- elif command -v sudo &> /dev/null; then
- if [ "$IS_INTERACTIVE" = true ]; then
- echo ""
- log_info "sudo is needed ONLY to install optional system packages (${pkgs[*]}) via your package manager."
- log_info "Hermes Agent itself does not require or retain root access."
- if prompt_yes_no "Install ${description}? (requires sudo)" "no"; then
- if sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a $install_cmd; then
- [ "$need_ripgrep" = true ] && HAS_RIPGREP=true && log_success "ripgrep installed"
- [ "$need_ffmpeg" = true ] && HAS_FFMPEG=true && log_success "ffmpeg installed"
- return 0
- fi
- fi
- elif (: </dev/tty) 2>/dev/null; then
- # Non-interactive (e.g. curl | bash) but a terminal is available.
- # Read the prompt from /dev/tty (same approach the setup wizard uses).
- # Probe by actually opening /dev/tty: a bare existence test passes
- # in Docker builds where the device node is in the mount namespace
- # but opening fails with ENXIO. See #16746.
- echo ""
- log_info "sudo is needed ONLY to install optional system packages (${pkgs[*]}) via your package manager."
- log_info "Hermes Agent itself does not require or retain root access."
- if prompt_yes_no "Install ${description}?" "yes"; then
- if sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a $install_cmd < /dev/tty; then
- [ "$need_ripgrep" = true ] && HAS_RIPGREP=true && log_success "ripgrep installed"
- [ "$need_ffmpeg" = true ] && HAS_FFMPEG=true && log_success "ffmpeg installed"
- return 0
- fi
- fi
- else
- log_warn "Non-interactive mode and no terminal available — cannot install system packages"
- log_info "Install manually after setup completes: sudo $install_cmd"
- fi
- fi
- fi
-
- # ── Fallback for ripgrep: cargo ──
- if [ "$need_ripgrep" = true ] && [ "$HAS_RIPGREP" = false ]; then
- if command -v cargo &> /dev/null; then
- log_info "Trying cargo install ripgrep (no sudo needed)..."
- if cargo install ripgrep; then
- log_success "ripgrep installed via cargo"
- HAS_RIPGREP=true
- fi
- fi
- fi
-
- # ── Show manual instructions for anything still missing ──
- if [ "$HAS_RIPGREP" = false ] && [ "$need_ripgrep" = true ]; then
- log_warn "ripgrep not installed (file search will use grep fallback)"
- show_manual_install_hint "ripgrep"
- fi
- if [ "$HAS_FFMPEG" = false ] && [ "$need_ffmpeg" = true ]; then
- log_warn "ffmpeg not installed (TTS voice messages will be limited)"
- show_manual_install_hint "ffmpeg"
- fi
-}
-
-show_manual_install_hint() {
- local pkg="$1"
- log_info "To install $pkg manually:"
- case "$OS" in
- linux)
- case "$DISTRO" in
- ubuntu|debian) log_info " sudo apt install $pkg" ;;
- fedora) log_info " sudo dnf install $pkg" ;;
- arch) log_info " sudo pacman -S $pkg" ;;
- *) log_info " Use your package manager or visit the project homepage" ;;
- esac
- ;;
- android)
- log_info " pkg install $pkg"
- ;;
- macos) log_info " brew install $pkg" ;;
- esac
-}
-
-# ============================================================================
-# Installation
-# ============================================================================
-
-clone_repo() {
- log_info "Installing to $INSTALL_DIR..."
-
- # An interrupted previous clone leaves a .git with no initial commit, where
- # the update path's `git stash` / `git checkout` abort with "You do not
- # have the initial commit yet" and fail the install (#40998). Move such a
- # partial checkout aside -- never delete it, in case it holds something the
- # user wants -- so the fresh-clone path below can proceed.
- if [ -d "$INSTALL_DIR/.git" ] && ! git -C "$INSTALL_DIR" rev-parse --verify HEAD >/dev/null 2>&1; then
- backup_dir="${INSTALL_DIR}.broken-$(date -u +%Y%m%d-%H%M%S)"
- log_warn "Existing checkout at $INSTALL_DIR has no commits (interrupted clone)."
- log_warn "Moving it aside to $backup_dir before re-cloning."
- mv "$INSTALL_DIR" "$backup_dir"
- fi
-
- if [ -d "$INSTALL_DIR" ]; then
- if [ -d "$INSTALL_DIR/.git" ]; then
- log_info "Existing installation found, updating..."
- cd "$INSTALL_DIR"
-
- local autostash_ref=""
- discard_update_lockfile_churn "$INSTALL_DIR"
- if [ -n "$(git status --porcelain)" ]; then
- # A previously interrupted update can leave the index with
- # unmerged entries. In that state `git stash` aborts with
- # "could not write index" and the later `git checkout` aborts
- # with "you need to resolve your current index first", failing
- # the whole install at the repository stage. Clear the conflict
- # markers with `git reset` first -- this keeps working-tree
- # changes (they're still stashed just below) and only drops the
- # index-level conflict state. Mirrors the `hermes update` path
- # (#4735).
- if [ -n "$(git ls-files --unmerged)" ]; then
- log_info "Clearing unmerged index entries from a previous conflict..."
- git reset -q
- fi
- local stash_name
- stash_name="hermes-install-autostash-$(date -u +%Y%m%d-%H%M%S)"
- log_info "Local changes detected, stashing before update..."
- git stash push --include-untracked -m "$stash_name"
- autostash_ref="stash@{0}"
- fi
-
- # Fetch only the target branch. A bare `git fetch origin` pulls
- # every ref, and this repo carries thousands of auto-generated
- # branches — on a non-single-branch checkout that turns each update
- # into a multi-minute download that can stall the installer.
- git remote set-branches origin "$BRANCH" 2>/dev/null || true
- git fetch origin "$BRANCH"
- git checkout "$BRANCH"
- # Managed installs should follow origin/$BRANCH exactly. If the
- # checkout has diverged (or has local-only commits), ff-only pull
- # cannot succeed — mirror ``hermes update`` and reset to the
- # fetched remote so bootstrap/install can recover.
- if ! git pull --ff-only origin "$BRANCH"; then
- log_warn "Fast-forward not possible; resetting managed install to origin/$BRANCH..."
- git reset --hard "origin/$BRANCH"
- fi
-
- if [ -n "$autostash_ref" ]; then
- local restore_now="yes"
- if [ -t 0 ] && [ -t 1 ]; then
- echo
- log_warn "Local changes were stashed before updating."
- log_warn "Restoring them may reapply local customizations onto the updated codebase."
- printf "Restore local changes now? [Y/n] "
- read -r restore_answer
- case "$restore_answer" in
- ""|y|Y|yes|YES|Yes) restore_now="yes" ;;
- *) restore_now="no" ;;
- esac
- fi
-
- if [ "$restore_now" = "yes" ]; then
- log_info "Restoring local changes..."
- local restore_output=""
- local restore_ok="yes"
- if restore_output="$(git stash apply "$autostash_ref" 2>&1)"; then
- restore_ok="yes"
- else
- restore_ok="no"
- fi
- local conflicted_files=""
- conflicted_files="$(git diff --name-only --diff-filter=U || true)"
- if [ "$restore_ok" = "yes" ] && [ -z "$conflicted_files" ]; then
- git stash drop "$autostash_ref" >/dev/null
- log_warn "Local changes were restored on top of the updated codebase."
- log_warn "Review git diff / git status if Hermes behaves unexpectedly."
- else
- log_error "Update pulled new code, but restoring local changes hit conflicts."
- if [ -n "$restore_output" ]; then
- printf '%s\n' "$restore_output"
- fi
- if [ -n "$conflicted_files" ]; then
- printf '\nConflicted files:\n'
- while IFS= read -r file; do
- [ -n "$file" ] && printf ' • %s\n' "$file"
- done <<EOF
-$conflicted_files
-EOF
- fi
- printf '\n'
- log_info "Your stashed changes are preserved — nothing is lost."
- log_info " Stash ref: $autostash_ref"
- git reset --hard HEAD >/dev/null 2>&1 || true
- log_info "Working tree reset to clean state."
- log_info "Restore your changes later with: git stash apply $autostash_ref"
- fi
- else
- log_info "Skipped restoring local changes."
- log_info "Your changes are still preserved in git stash."
- log_info "Restore manually with: git stash apply $autostash_ref"
- fi
- fi
- else
- log_error "Directory exists but is not a git repository: $INSTALL_DIR"
- log_info "Remove it or choose a different directory with --dir"
- exit 1
- fi
- else
- # Try SSH first (for private repo access), fall back to HTTPS
- # GIT_SSH_COMMAND disables interactive prompts and sets a short timeout
- # so SSH fails fast instead of hanging when no key is configured.
- log_info "Trying SSH clone..."
- if GIT_SSH_COMMAND="ssh -o BatchMode=yes -o ConnectTimeout=5" \
- git clone --depth 1 --branch "$BRANCH" "$REPO_URL_SSH" "$INSTALL_DIR" 2>/dev/null; then
- log_success "Cloned via SSH"
- else
- rm -rf "$INSTALL_DIR" 2>/dev/null # Clean up partial SSH clone
- log_info "SSH failed, trying HTTPS..."
- if git clone --depth 1 --branch "$BRANCH" "$REPO_URL_HTTPS" "$INSTALL_DIR"; then
- log_success "Cloned via HTTPS"
- else
- log_error "Failed to clone repository"
- exit 1
- fi
- fi
- fi
-
- cd "$INSTALL_DIR"
-
- if [ -n "$INSTALL_COMMIT" ]; then
- # Validate the commit argument: must look like a hex SHA (full 40-char
- # or abbreviated 7-39 char). Reject anything else early so the user
- # gets a clear error instead of a misleading git message (#87268).
- if ! printf '%s' "$INSTALL_COMMIT" | grep -qE '^[0-9a-fA-F]{7,40}$'; then
- log_error "--commit expects a hex SHA (7-40 chars), got: $INSTALL_COMMIT"
- return 1
- fi
- # A commit pin must never move an existing install BACKWARDS. The
- # bootstrap installer bakes its build-time commit into the binary
- # (BUILD_PIN_COMMIT) and passes it as --commit on every install-mode
- # run -- including the one the desktop's failure screen retries. An
- # installer built months ago would otherwise rewind a current checkout
- # to its build commit, stranding the user on ancient code with a
- # current venv. Only pin when the target is not already an ancestor of
- # HEAD; a fresh clone has no such ancestry and pins normally.
- if ! git cat-file -e "$INSTALL_COMMIT^{commit}" 2>/dev/null; then
- if ! git fetch origin "$INSTALL_COMMIT"; then
- log_error "Could not fetch commit $INSTALL_COMMIT from origin."
- log_error "Abbreviated SHAs are not supported — use the full 40-char hash."
- log_error "Find it with: git ls-remote origin | grep <short-sha>"
- return 1
- fi
- fi
- if git rev-parse --verify --quiet HEAD >/dev/null 2>&1 \
- && git merge-base --is-ancestor "$INSTALL_COMMIT" HEAD 2>/dev/null \
- && [ "$(git rev-parse "$INSTALL_COMMIT^{commit}" 2>/dev/null)" != "$(git rev-parse HEAD)" ]; then
- if [ "$FORCE_COMMIT" = true ]; then
- log_warn "--force-commit: rolling this install back to $INSTALL_COMMIT."
- if ! git checkout --detach "$INSTALL_COMMIT"; then
- log_error "Failed to detach at $INSTALL_COMMIT"
- return 1
- fi
- else
- log_warn "Ignoring --commit $INSTALL_COMMIT: the checkout is already newer."
- log_warn "Pinning to it would roll this install back. Pass --force-commit to override."
- fi
- else
- log_info "Pinning checkout to commit $INSTALL_COMMIT..."
- if ! git checkout --detach "$INSTALL_COMMIT"; then
- log_error "Failed to detach at $INSTALL_COMMIT"
- return 1
- fi
- fi
- fi
-
- log_success "Repository ready"
-}
-
-setup_venv() {
- if [ "$USE_VENV" = false ]; then
- log_info "Skipping virtual environment (--no-venv)"
- return 0
- fi
-
- if [ "$DISTRO" = "termux" ]; then
- log_info "Creating virtual environment with Termux Python..."
-
- if [ -d "venv" ]; then
- log_info "Virtual environment already exists, recreating..."
- rm -rf venv
- fi
-
- "$PYTHON_PATH" -m venv venv
- log_success "Virtual environment ready ($(./venv/bin/python --version 2>/dev/null))"
- return 0
- fi
-
- log_info "Creating virtual environment with Python $PYTHON_VERSION..."
-
- if [ -d "venv" ]; then
- log_info "Virtual environment already exists, recreating..."
- rm -rf venv
- fi
-
- # uv creates the venv and pins the Python version in one step
- $UV_CMD venv venv --python "$PYTHON_VERSION"
-
- # Neutralize any inherited UV_PYTHON (e.g. UV_PYTHON=3.14 left in the
- # user's shell env). uv honours UV_PYTHON over an existing venv for the
- # later `uv sync` / `uv pip install` tiers, so without this it would
- # silently delete this 3.11 venv and recreate it at the inherited
- # version — building Rust transitives that have no wheel for that
- # version from source via maturin, which fails. Pinning UV_PYTHON to the
- # interpreter we just created forces every subsequent uv command onto it.
- if [ -x "$INSTALL_DIR/venv/bin/python" ]; then
- export UV_PYTHON="$INSTALL_DIR/venv/bin/python"
- fi
-
- log_success "Virtual environment ready (Python $PYTHON_VERSION)"
-}
-
-run_locked_uv_sync() {
- # Bootstrap uv calls stay isolated from ambient config via UV_NO_CONFIG
- # (#21269). A locked project sync is different: uv.lock records resolver
- # settings from this checkout's [tool.uv], so hiding pyproject.toml makes
- # uv 0.12+ reject the valid lock. Re-enable project discovery only for
- # this subprocess while redirecting user/system config lookups to an empty
- # directory. Keep HOME unchanged so caches, credentials, and git continue
- # to work normally.
- local project_env="$1"
- local isolated_uv_config
- local sync_rc
- isolated_uv_config="$(mktemp -d)" || return 1
-
- (
- unset UV_NO_CONFIG UV_CONFIG_FILE
- export XDG_CONFIG_HOME="$isolated_uv_config"
- export XDG_CONFIG_DIRS="$isolated_uv_config"
- UV_PROJECT_ENVIRONMENT="$project_env" $UV_CMD sync --extra all --locked
- )
- sync_rc=$?
- rmdir "$isolated_uv_config" 2>/dev/null || true
- return "$sync_rc"
-}
-
-install_deps() {
- log_info "Installing dependencies..."
-
- # Re-pin UV_PYTHON to the venv interpreter. setup_venv already does this,
- # but the bootstrap runs install stages (`venv`, `python-deps`) as separate
- # processes, so an export from setup_venv does NOT survive into a separate
- # python-deps invocation. Re-deriving it here covers that path. Without it,
- # an inherited UV_PYTHON=3.14 makes the uv sync/pip tiers below recreate the
- # venv at 3.14 and fail the maturin source build (no cp314 wheels yet).
- if [ "$DISTRO" != "termux" ] && [ -x "$INSTALL_DIR/venv/bin/python" ]; then
- export UV_PYTHON="$INSTALL_DIR/venv/bin/python"
- fi
-
- if [ "$DISTRO" = "termux" ]; then
- if [ "$USE_VENV" = true ]; then
- export VIRTUAL_ENV="$INSTALL_DIR/venv"
- PIP_PYTHON="$INSTALL_DIR/venv/bin/python"
- else
- PIP_PYTHON="$PYTHON_PATH"
- fi
-
- if [ -z "${ANDROID_API_LEVEL:-}" ]; then
- ANDROID_API_LEVEL="$(getprop ro.build.version.sdk 2>/dev/null || true)"
- if [ -z "$ANDROID_API_LEVEL" ]; then
- ANDROID_API_LEVEL=24
- fi
- export ANDROID_API_LEVEL
- log_info "Using ANDROID_API_LEVEL=$ANDROID_API_LEVEL for Android wheel builds"
- fi
-
- "$PIP_PYTHON" -m pip install --upgrade pip setuptools wheel >/dev/null
-
- # On Android, psutil's setup.py rejects sys.platform == 'android' before
- # it ever invokes the C build, so the next pip install would fail at
- # "platform android is not supported". Prebuild psutil from the official
- # sdist with a one-line marker patch (Linux source path is fine on
- # Android). Stopgap until psutil#2762 ships upstream.
- if "$PIP_PYTHON" -c 'import sys; raise SystemExit(0 if sys.platform == "android" else 1)' 2>/dev/null; then
- log_info "Android Python detected: prebuilding psutil compatibility shim..."
- if ! "$PIP_PYTHON" "$INSTALL_DIR/scripts/install_psutil_android.py" --pip "$PIP_PYTHON -m pip"; then
- log_warn "psutil Android prebuild failed — package install will likely fail next."
- log_info "Workaround: manually rerun 'python scripts/install_psutil_android.py' once your toolchain is set up."
- fi
- fi
-
- # Try the broad Termux profile first (best-effort "install all" for Android),
- # then fall back to the conservative Termux baseline, then base package.
- if ! "$PIP_PYTHON" -m pip install -e '.[termux-all]' -c constraints-termux.txt; then
- log_warn "Termux broad profile (.[termux-all]) failed, trying baseline Termux profile..."
- if ! "$PIP_PYTHON" -m pip install -e '.[termux]' -c constraints-termux.txt; then
- log_warn "Termux baseline profile (.[termux]) failed, trying base install..."
- if ! "$PIP_PYTHON" -m pip install -e '.' -c constraints-termux.txt; then
- log_error "Package installation failed on Termux."
- log_info "Ensure these packages are installed: pkg install clang rust make pkg-config libffi openssl ca-certificates curl"
- log_info "Then re-run: cd $INSTALL_DIR && python -m pip install -e '.[termux-all]' -c constraints-termux.txt"
- exit 1
- fi
- fi
- fi
-
- log_success "Main package installed"
- log_info "Termux note: matrix e2ee and local faster-whisper extras are excluded from .[termux-all] due to upstream Android wheel/toolchain blockers."
- log_info "Termux note: browser/WhatsApp tooling is not installed by default; see the Termux guide for optional follow-up steps."
-
- log_success "All dependencies installed"
- return 0
- fi
-
- if [ "$USE_VENV" = true ]; then
- # Tell uv to install into our venv (no need to activate)
- export VIRTUAL_ENV="$INSTALL_DIR/venv"
- fi
-
- # On Debian/Ubuntu (including WSL), some Python packages need build tools.
- # Check and offer to install them if missing.
- if [ "$DISTRO" = "ubuntu" ] || [ "$DISTRO" = "debian" ]; then
- local need_build_tools=false
- for pkg in gcc python3-dev libffi-dev; do
- if ! dpkg -s "$pkg" &>/dev/null; then
- need_build_tools=true
- break
- fi
- done
- if [ "$need_build_tools" = true ]; then
- log_info "Some build tools may be needed for Python packages..."
- if command -v sudo &> /dev/null; then
- if sudo -n true 2>/dev/null; then
- sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update -qq && sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y -qq build-essential python3-dev libffi-dev >/dev/null 2>&1 || true
- log_success "Build tools installed"
- else
- log_info "sudo is needed ONLY to install build tools (build-essential, python3-dev, libffi-dev) via apt."
- log_info "Hermes Agent itself does not require or retain root access."
- if prompt_yes_no "Install build tools?" "yes"; then
- sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get update -qq && sudo DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt-get install -y -qq build-essential python3-dev libffi-dev >/dev/null 2>&1 || true
- log_success "Build tools installed"
- fi
- fi
- fi
- fi
- fi
-
- # Install the main package in editable mode with all extras.
- #
- # Hash-verified install (Tier 0) — when uv.lock is present, prefer
- # `uv sync --locked`. The lockfile records SHA256 hashes for every
- # transitive, so a compromised transitive (different hash than what
- # we shipped) is REJECTED by the resolver. This is the *only* path
- # that protects against the "direct dep is fine, but the dep's dep
- # got worm-poisoned overnight" failure mode. All `uv pip install`
- # tiers below re-resolve transitives fresh from PyPI without any
- # hash verification — they exist to keep installs working when the
- # lockfile is stale, missing, or out-of-sync with the current
- # extras spec, NOT because they're equivalent in posture.
- if [ -f "uv.lock" ]; then
- log_info "Trying tier: hash-verified (uv.lock) ..."
- log_info "(this resolves + downloads the curated [all] set — first run on a"
- log_info " fresh venv can take 1-5 minutes; uv prints progress below)"
- # Stream uv's progress directly to the user instead of swallowing
- # it with `2>"$(mktemp)"`. Two reasons:
- # 1. `--extra all --locked` against a fresh venv has to pull
- # every transitive — silencing stderr makes the install
- # look frozen for minutes on slow networks. Users see
- # "Trying tier: hash-verified ..." and assume it's hung.
- # 2. The previous `2>"$(mktemp)"` substituted the path at
- # command-build time but never saved it, so on failure the
- # uv error message was unreachable — the user just got the
- # generic "lockfile may be stale" warning.
- #
- # Critical flag choice: `--extra all`, NOT `--all-extras`.
- # --all-extras = every [project.optional-dependencies] key.
- # This bypasses the curated `[all]` extra
- # entirely and pulls e.g. [matrix] (which
- # needs python-olm + make on Windows) and
- # [rl] (git+https deps that fail offline).
- # --extra all = install just the `[all]` extra's contents.
- # This respects the curation in pyproject.toml.
- # uv's own progress UI handles TTY detection and downgrades
- # gracefully when stdout/stderr aren't terminals.
- #
- # Run the Tier-0 locked sync via run_locked_uv_sync: the global
- # UV_NO_CONFIG export at script start (the #21269 sudo -u hygiene
- # guard) also hides the project's own [tool.uv] policy —
- # exclude-newer, its package exemptions, and override-dependencies —
- # from uv. The resolver then runs under a different policy than the
- # one uv.lock was resolved under, and --locked turns that mismatch
- # fatal, so every fresh install fell through to the non-hash-verified
- # PyPI tiers. The helper re-enables project config discovery for this
- # one subprocess while keeping ambient user/system uv config hidden
- # (redirected to an empty XDG dir), preserving the #21269 guarantee.
- # Runtime code does the same before its locked syncs
- # (hermes_cli/managed_uv.py).
- if run_locked_uv_sync "$INSTALL_DIR/venv"; then
- log_success "Main package installed (hash-verified via uv.lock)"
- log_success "All dependencies installed"
- return 0
- fi
- log_warn "uv.lock sync failed (see uv output above), falling back to PyPI resolve..."
- else
- log_info "uv.lock not found — falling back to PyPI resolve (no hash verification)"
- fi
-
- # Multi-tier fallback. The point of the tiers is that ONE compromised
- # PyPI package (a worm-poisoned release that gets quarantined, like
- # mistralai 2.4.6 in May 2026) shouldn't be able to silently demote a
- # fresh install all the way down to "core only" — the user should keep
- # everything else they signed up for.
- #
- # Tier 1: [all] — the curated extra in pyproject.toml.
- # Tier 2: [all] minus the currently-broken extras list (_BROKEN_EXTRAS).
- # Edit _BROKEN_EXTRAS below when something on PyPI breaks; this
- # lets users keep the rest of [all] when one transitive is
- # unavailable. The list of [all]'s contents is parsed from
- # pyproject.toml at runtime — there is NO hand-mirrored copy
- # to drift out of sync. If you want to change what [all]
- # contains, edit pyproject.toml only.
- # Tier 3: bare `.` — last-resort so at least the core CLI launches.
- # Skipped tiers like "PyPI-only extras (no git deps)" used to
- # exist to dodge [rl] / [matrix] git+sdist deps; those are no
- # longer in [all] post-2026-05-12 lazy-install migration, so
- # a separate PyPI-only tier had no remaining content.
- local _BROKEN_EXTRAS=() # populate when an extra becomes unresolvable
-
- # Parse [project.optional-dependencies].all from pyproject.toml.
- # tomllib is stdlib on Python 3.11+ which uv's bootstrap guarantees.
- # Falls back to a hand list if parse fails — defensive only.
- local _ALL_EXTRAS_CSV
- _ALL_EXTRAS_CSV="$(
- "$PYTHON_PATH" - <<'PY' 2>/dev/null
-import re, sys, tomllib
-try:
- with open("pyproject.toml", "rb") as fh:
- data = tomllib.load(fh)
- specs = data["project"]["optional-dependencies"]["all"]
- extras = []
- for s in specs:
- m = re.search(r"hermes-agent\[([\w-]+)\]", s)
- if m:
- extras.append(m.group(1))
- print(",".join(extras))
-except Exception as e:
- print("", file=sys.stderr)
- sys.exit(1)
-PY
- )"
- if [ -z "$_ALL_EXTRAS_CSV" ]; then
- log_warn "Could not parse [all] from pyproject.toml; falling back to .[all] only."
- _ALL_EXTRAS_CSV=""
- fi
-
- # Build "[all] minus broken" spec by filtering the parsed list.
- local _SAFE_SPEC=".[all]"
- if [ -n "$_ALL_EXTRAS_CSV" ] && [ "${#_BROKEN_EXTRAS[@]}" -gt 0 ]; then
- local _SAFE_EXTRAS=()
- local _e _b _skip
- IFS=',' read -ra _ALL_EXTRAS_ARR <<< "$_ALL_EXTRAS_CSV"
- for _e in "${_ALL_EXTRAS_ARR[@]}"; do
- _skip=false
- for _b in "${_BROKEN_EXTRAS[@]}"; do
- if [ "$_e" = "$_b" ]; then _skip=true; break; fi
- done
- if [ "$_skip" = false ]; then _SAFE_EXTRAS+=("$_e"); fi
- done
- _SAFE_SPEC=".[$(IFS=,; echo "${_SAFE_EXTRAS[*]}")]"
- fi
-
- ALL_INSTALL_LOG=$(mktemp)
- local _installed=false
- local _tier_name=""
-
- install_tier() {
- local name="$1"; local spec="$2"
- log_info "Trying tier: $name ..."
- if $UV_CMD pip install -e "$spec" 2>"$ALL_INSTALL_LOG"; then
- log_success "Main package installed ($name)"
- _installed=true
- _tier_name="$name"
- return 0
- fi
- log_warn "Tier '$name' failed. Top of pip output:"
- head -5 "$ALL_INSTALL_LOG" | sed 's/^/ /' >&2
- return 1
- }
-
- install_tier "all" ".[all]" \
- || install_tier "all minus known-broken (${_BROKEN_EXTRAS[*]:-none})" "$_SAFE_SPEC" \
- || install_tier "core only (no extras)" "."
-
- rm -f "$ALL_INSTALL_LOG"
-
- if [ "$_installed" = false ]; then
- log_error "Package installation failed even with no extras."
- log_info "Check that build tools are installed: sudo apt install build-essential python3-dev"
- log_info "Then re-run: cd $INSTALL_DIR && uv pip install -e '.[all]'"
- exit 1
- fi
-
- if [ "$_tier_name" != "all" ]; then
- log_warn "Note: installed via fallback tier ($_tier_name)."
- log_info "Some optional features may be missing. After resolving any"
- log_info "PyPI/network issue, re-run: $UV_CMD pip install -e '.[all]'"
- fi
-
- log_success "Main package installed"
-
- log_success "All dependencies installed"
-}
-
-setup_path() {
- log_info "Setting up hermes command..."
-
- if [ "$USE_VENV" = true ]; then
- HERMES_BIN="$INSTALL_DIR/venv/bin/python"
- HERMES_ENTRYPOINT="$INSTALL_DIR/hermes"
- else
- HERMES_BIN="$(which hermes 2>/dev/null || echo "")"
- if [ -z "$HERMES_BIN" ]; then
- log_warn "hermes not found on PATH after install"
- return 0
- fi
- fi
-
- # Verify the interpreter and the checked-in entrypoint needed by the launcher.
- if [ ! -x "$HERMES_BIN" ] || { [ "$USE_VENV" = true ] && [ ! -f "$HERMES_ENTRYPOINT" ]; }; then
- log_warn "Hermes launcher prerequisites not found"
- log_info "This usually means the Python package install didn't complete successfully."
- if [ "$DISTRO" = "termux" ]; then
- log_info "Try: cd $INSTALL_DIR && python -m pip install -e '.[termux-all]' -c constraints-termux.txt"
- else
- log_info "Try: cd $INSTALL_DIR && uv pip install -e '.[all]'"
- fi
- return 0
- fi
-
- local command_link_dir
- local command_link_display_dir
- command_link_dir="$(get_command_link_dir)"
- command_link_display_dir="$(get_command_link_display_dir)"
-
- # Create a user-facing shim for the hermes command.
- # We intentionally clear PYTHONPATH/PYTHONHOME here so inherited env vars
- # can't make this launcher import modules from another checkout.
- mkdir -p "$command_link_dir"
- # Older installs created this path as a symlink to $HERMES_BIN. Without
- # the rm, `cat >` follows the symlink and overwrites the venv pip entry
- # point with this shim — making `exec "$HERMES_BIN"` self-recurse. (#21454)
- rm -f "$command_link_dir/hermes"
- if [ "$USE_VENV" = true ]; then
- # uv-generated console scripts resolve themselves through `realpath`,
- # which stock macOS does not provide. Run the checked-in entrypoint
- # with the venv interpreter instead, so the public launcher remains
- # independent of non-standard shell utilities.
- cat > "$command_link_dir/hermes" <<EOF
-#!/usr/bin/env bash
-unset PYTHONPATH
-unset PYTHONHOME
-exec "$HERMES_BIN" "$HERMES_ENTRYPOINT" "\$@"
-EOF
- else
- cat > "$command_link_dir/hermes" <<EOF
-#!/usr/bin/env bash
-unset PYTHONPATH
-unset PYTHONHOME
-exec "$HERMES_BIN" "\$@"
-EOF
- fi
- chmod +x "$command_link_dir/hermes"
- log_success "Installed hermes launcher → $command_link_display_dir/hermes"
-
- # Also expose `hermes-agent`. The `hermes-agent` console script declared in
- # pyproject.toml's [project.scripts] lives inside the venv, which is not on
- # the login-shell PATH. Without this launcher users can't invoke the agent
- # entrypoint directly from outside the venv. (#74819)
- rm -f "$command_link_dir/hermes-agent"
- if [ "$USE_VENV" = true ]; then
- cat > "$command_link_dir/hermes-agent" <<EOF
-#!/usr/bin/env bash
-unset PYTHONPATH
-unset PYTHONHOME
-exec "$HERMES_BIN" "$INSTALL_DIR/run_agent.py" "\$@"
-EOF
- else
- cat > "$command_link_dir/hermes-agent" <<EOF
-#!/usr/bin/env bash
-unset PYTHONPATH
-unset PYTHONHOME
-exec "$HERMES_BIN" run_agent.py "\$@"
-EOF
- fi
- chmod +x "$command_link_dir/hermes-agent"
- log_success "Installed hermes-agent launcher → $command_link_display_dir/hermes-agent"
-
- # Also expose `hermes-acp`. ACP hosts (Zed, JetBrains, Buzz) resolve the
- # agent by command name on the login-shell PATH, and the `hermes-acp`
- # console script lives inside the venv, which is not on that PATH. Without
- # this launcher those hosts report Hermes as not installed. (#21454 applies
- # here too: clear the path first so `cat >` cannot follow an old symlink
- # into the venv and overwrite the console script.)
- rm -f "$command_link_dir/hermes-acp"
- if [ "$USE_VENV" = true ]; then
- cat > "$command_link_dir/hermes-acp" <<EOF
-#!/usr/bin/env bash
-unset PYTHONPATH
-unset PYTHONHOME
-exec "$HERMES_BIN" "$HERMES_ENTRYPOINT" acp "\$@"
-EOF
- else
- cat > "$command_link_dir/hermes-acp" <<EOF
-#!/usr/bin/env bash
-unset PYTHONPATH
-unset PYTHONHOME
-exec "$HERMES_BIN" acp "\$@"
-EOF
- fi
- chmod +x "$command_link_dir/hermes-acp"
- log_success "Installed hermes-acp launcher → $command_link_display_dir/hermes-acp"
-
- if [ "$DISTRO" = "termux" ]; then
- export PATH="$command_link_dir:$PATH"
- log_info "$command_link_display_dir is the native Termux command path"
- log_success "hermes command ready"
- return 0
- fi
-
- # FHS layout: /usr/local/bin is normally on PATH for login shells (via
- # /etc/profile pathmunge), but on RHEL/CentOS/Rocky/Alma 8+ non-login
- # interactive root shells (su, sudo -s, tmux panes, some web terminals)
- # only source /etc/bashrc, which does NOT add /usr/local/bin — and
- # /root/.bash_profile doesn't either. So verify with `command -v` and
- # fall back to writing a PATH guard into /root/.bashrc when needed.
- if [ "$ROOT_FHS_LAYOUT" = true ]; then
- export PATH="$command_link_dir:$PATH"
- # Probe a fresh non-login interactive bash the way the user will use it.
- # `bash -i -c` sources ~/.bashrc but NOT ~/.bash_profile or /etc/profile,
- # which is the exact scenario where RHEL root loses /usr/local/bin.
- if env -i HOME="$HOME" TERM="${TERM:-dumb}" bash -i -c 'command -v hermes' \
- >/dev/null 2>&1; then
- log_info "/usr/local/bin is already on PATH for all shells"
- log_success "hermes command ready"
- return 0
- fi
-
- log_info "hermes not on PATH in non-login shells (common on RHEL-family)"
- PATH_LINE='export PATH="/usr/local/bin:$PATH"'
- PATH_COMMENT='# Hermes Agent — ensure /usr/local/bin is on PATH (RHEL non-login shells)'
- for SHELL_CONFIG in "$HOME/.bashrc" "$HOME/.bash_profile"; do
- [ -f "$SHELL_CONFIG" ] || continue
- if ! grep -v '^[[:space:]]*#' "$SHELL_CONFIG" 2>/dev/null \
- | grep -qE 'PATH=.*(/usr/local/bin|\$command_link_dir)'; then
- echo "" >> "$SHELL_CONFIG"
- echo "$PATH_COMMENT" >> "$SHELL_CONFIG"
- echo "$PATH_LINE" >> "$SHELL_CONFIG"
- log_success "Added /usr/local/bin to PATH in $SHELL_CONFIG"
- fi
- done
- log_success "hermes command ready"
- return 0
- fi
-
- # Check if ~/.local/bin is on PATH; if not, add it to shell config.
- # Detect the user's actual login shell (not the shell running this script,
- # which is always bash when piped from curl).
- if ! echo "$PATH" | tr ':' '\n' | grep -q "^$command_link_dir$"; then
- SHELL_CONFIGS=()
- IS_FISH=false
- LOGIN_SHELL="$(basename "${SHELL:-/bin/bash}")"
- case "$LOGIN_SHELL" in
- zsh)
- [ -f "$HOME/.zshrc" ] && SHELL_CONFIGS+=("$HOME/.zshrc")
- [ -f "$HOME/.zprofile" ] && SHELL_CONFIGS+=("$HOME/.zprofile")
- # If neither exists, create ~/.zshrc (common on fresh macOS installs)
- if [ ${#SHELL_CONFIGS[@]} -eq 0 ]; then
- touch "$HOME/.zshrc"
- SHELL_CONFIGS+=("$HOME/.zshrc")
- fi
- ;;
- bash)
- [ -f "$HOME/.bashrc" ] && SHELL_CONFIGS+=("$HOME/.bashrc")
- [ -f "$HOME/.bash_profile" ] && SHELL_CONFIGS+=("$HOME/.bash_profile")
- ;;
- fish)
- # fish uses ~/.config/fish/config.fish and fish_add_path — not export PATH=
- IS_FISH=true
- FISH_CONFIG="$HOME/.config/fish/config.fish"
- mkdir -p "$(dirname "$FISH_CONFIG")"
- touch "$FISH_CONFIG"
- ;;
- *)
- [ -f "$HOME/.bashrc" ] && SHELL_CONFIGS+=("$HOME/.bashrc")
- [ -f "$HOME/.zshrc" ] && SHELL_CONFIGS+=("$HOME/.zshrc")
- ;;
- esac
- # Also ensure ~/.profile has it (sourced by login shells on
- # Ubuntu/Debian/WSL even when ~/.bashrc is skipped)
- [ "$IS_FISH" = "false" ] && [ -f "$HOME/.profile" ] && SHELL_CONFIGS+=("$HOME/.profile")
-
- PATH_LINE='export PATH="$HOME/.local/bin:$PATH"'
-
- for SHELL_CONFIG in "${SHELL_CONFIGS[@]}"; do
- if ! grep -v '^[[:space:]]*#' "$SHELL_CONFIG" 2>/dev/null | grep -qE 'PATH=.*\.local/bin'; then
- echo "" >> "$SHELL_CONFIG"
- echo "# Hermes Agent — ensure ~/.local/bin is on PATH" >> "$SHELL_CONFIG"
- echo "$PATH_LINE" >> "$SHELL_CONFIG"
- log_success "Added ~/.local/bin to PATH in $SHELL_CONFIG"
- fi
- done
-
- # fish uses fish_add_path instead of export PATH=...
- if [ "$IS_FISH" = "true" ]; then
- if ! grep -q 'fish_add_path.*\.local/bin' "$FISH_CONFIG" 2>/dev/null; then
- echo "" >> "$FISH_CONFIG"
- echo "# Hermes Agent — ensure ~/.local/bin is on PATH" >> "$FISH_CONFIG"
- echo 'fish_add_path "$HOME/.local/bin"' >> "$FISH_CONFIG"
- log_success "Added ~/.local/bin to PATH in $FISH_CONFIG"
- fi
- fi
-
- if [ "$IS_FISH" = "false" ] && [ ${#SHELL_CONFIGS[@]} -eq 0 ]; then
- log_warn "Could not detect shell config file to add ~/.local/bin to PATH"
- log_info "Add manually: $PATH_LINE"
- fi
- else
- log_info "~/.local/bin already on PATH"
- fi
-
- # Export for current session so hermes works immediately
- export PATH="$command_link_dir:$PATH"
-
- log_success "hermes command ready"
-}
-
-copy_config_templates() {
- log_info "Setting up configuration files..."
-
- # Create ~/.hermes directory structure (config at top level, code in subdir)
- mkdir -p "$HERMES_HOME"/{cron,sessions,logs,pairing,hooks,image_cache,audio_cache,memories,skills}
-
- # Create .env at ~/.hermes/.env (top level, easy to find)
- if [ ! -f "$HERMES_HOME/.env" ]; then
- if [ -f "$INSTALL_DIR/.env.example" ]; then
- cp "$INSTALL_DIR/.env.example" "$HERMES_HOME/.env"
- log_success "Created ~/.hermes/.env from template"
- else
- touch "$HERMES_HOME/.env"
- log_success "Created ~/.hermes/.env"
- fi
- else
- log_info "~/.hermes/.env already exists, keeping it"
- fi
- # Restrict .env permissions — this file holds API keys and tokens.
- # 0600 ensures only the file owner can read/write, matching standard
- # practice for credential files (.netrc, .aws/credentials, .ssh/config).
- chmod 600 "$HERMES_HOME/.env"
- configure_browser_env_from_system_browser
-
- # Create config.yaml at ~/.hermes/config.yaml (top level, easy to find)
- if [ ! -f "$HERMES_HOME/config.yaml" ]; then
- if [ -f "$INSTALL_DIR/cli-config.yaml.example" ]; then
- cp "$INSTALL_DIR/cli-config.yaml.example" "$HERMES_HOME/config.yaml"
- log_success "Created ~/.hermes/config.yaml from template"
- fi
- else
- log_info "~/.hermes/config.yaml already exists, keeping it"
- fi
-
- # Create SOUL.md if it doesn't exist (global persona file).
- # This MUST match DEFAULT_SOUL_MD in hermes_cli/default_soul.py — the
- # runtime (_ensure_default_soul_md) treats the old comment-only scaffold as
- # "never customized" and upgrades it to this text on next run, so any drift
- # here is self-healing, but keep them in sync to avoid a churn on first run.
- if [ ! -f "$HERMES_HOME/SOUL.md" ]; then
- cat > "$HERMES_HOME/SOUL.md" << 'SOUL_EOF'
-You are Hermes Agent, built by Nous Research. Be direct: match the length of your reply to the weight of the ask — a one-line question gets a one-line answer, and finished work gets a short report of what changed, what's verified, and what's left, never a replay of the process. No filler ("Great question," "I'd be happy to"), no restating the request back, no re-summarizing what you already said, no narrating tool calls the user can see. Plain claims over adjectives; when unsure, say so plainly. Agree because it's right, not because the user said it. Depth is earned — give it when the user asks for detail, teaches, or the stakes demand it, not by default.
-SOUL_EOF
- log_success "Created ~/.hermes/SOUL.md (edit to customize personality)"
- fi
-
- log_success "Configuration directory ready: ~/.hermes/"
-
- # Seed bundled skills into ~/.hermes/skills/ (manifest-based, one-time per skill)
- if [ "$NO_SKILLS" = true ]; then
- # Blank-slate install: write the opt-out marker and skip seeding.
- # skills_sync.py and `hermes update` both honor this marker, so the
- # default profile stays empty across future updates too.
- printf '%s\n' \
- "This profile opted out of bundled-skill seeding (installed with --no-skills)." \
- "Delete this file to re-enable sync on the next 'hermes update'." \
- > "$HERMES_HOME/.no-bundled-skills" 2>/dev/null || true
- log_info "Skipping bundled skills (--no-skills). Wrote $HERMES_HOME/.no-bundled-skills"
- log_info " Future 'hermes update' runs will not inject bundled skills. Delete the marker to opt back in."
- else
- log_info "Syncing bundled skills to ~/.hermes/skills/ ..."
- if "$INSTALL_DIR/venv/bin/python" "$INSTALL_DIR/tools/skills_sync.py" 2>/dev/null; then
- log_success "Skills synced to ~/.hermes/skills/"
- else
- # Fallback: simple directory copy if Python sync fails
- if [ -d "$INSTALL_DIR/skills" ] && [ ! "$(ls -A "$HERMES_HOME/skills/" 2>/dev/null | grep -v '.bundled_manifest')" ]; then
- cp -r "$INSTALL_DIR/skills/"* "$HERMES_HOME/skills/" 2>/dev/null || true
- log_success "Skills copied to ~/.hermes/skills/"
- fi
- fi
- fi
-}
-
-find_system_browser() {
- # Honor ONLY an explicit, user-set AGENT_BROWSER_EXECUTABLE_PATH override.
- #
- # We deliberately do NOT scan PATH or well-known app locations any more.
- # Auto-detection silently bound the install to whatever `command -v chromium`
- # resolved to — most damagingly a Snap Chromium (/snap/bin/chromium), whose
- # sandbox blocks agent-browser's control socket under /tmp, so every
- # browser_navigate hung until the 60s timeout fired ("opening web page
- # failed"). Every install now uses the bundled Playwright Chromium unless the
- # user explicitly points elsewhere.
- local override="${AGENT_BROWSER_EXECUTABLE_PATH:-}"
-
- if [ -z "$override" ]; then
- return 1
- fi
-
- # A Snap binary is never a valid target — its confinement is the very bug we
- # are fixing — so reject it even when set explicitly.
- case "$override" in
- /snap/*) return 1 ;;
- esac
-
- if [ -x "$override" ]; then
- echo "$override"
- return 0
- fi
- if command -v "$override" >/dev/null 2>&1; then
- command -v "$override"
- return 0
- fi
-
- return 1
-}
-
-strip_snap_browser_override() {
- # Existing installs created before the system-browser fallback was dropped
- # may carry an auto-written AGENT_BROWSER_EXECUTABLE_PATH pointing at a Snap
- # Chromium (/snap/bin/chromium). That path is the root cause of the "opening
- # web page failed" hang, and the runtime reads it straight from .env — so
- # removing the fallback in the installer is not enough on its own. Strip any
- # snap-pointing override here (and its auto-written comment) so the bundled
- # Chromium download runs and the agent stops using the broken binary. A
- # deliberately-set non-snap override is left untouched.
- local env_file="$HERMES_HOME/.env"
-
- [ -f "$env_file" ] || return 0
- grep -Eq '^AGENT_BROWSER_EXECUTABLE_PATH=/snap/' "$env_file" 2>/dev/null || return 0
-
- local tmp
- tmp="$(mktemp)" || return 0
- if grep -Ev '^AGENT_BROWSER_EXECUTABLE_PATH=/snap/|^# Hermes Agent browser tools' "$env_file" > "$tmp"; then
- mv "$tmp" "$env_file"
- log_warn "Removed stale Snap browser override (AGENT_BROWSER_EXECUTABLE_PATH=/snap/...) from $env_file"
- log_info "Hermes will use the bundled Chromium instead."
- # Drop it from this process too so the rest of the run doesn't re-detect it.
- unset AGENT_BROWSER_EXECUTABLE_PATH
- else
- rm -f "$tmp"
- fi
-}
-
-run_browser_install_with_timeout() {
- run_with_timeout "$@"
-}
-
-# Run a command with a hard wall-clock timeout, returning non-zero if it is
-# killed. Prefers GNU coreutils `timeout` (Linux) or `gtimeout` (macOS via
-# Homebrew) for an external-command target; otherwise (and always for a shell
-# function target, which the `timeout` binary cannot exec) it uses a pure-shell
-# watchdog: launch the command in its own process group, poll until it finishes,
-# and SIGTERM (then SIGKILL) the whole group on timeout. The pure-shell path is
-# what protects the bug-#39219 case — a stalled Electron download on macOS,
-# where `timeout` is usually absent — turning an indefinite hang into a non-zero
-# exit so callers (install_desktop) can self-heal via the mirror fallback.
-#
-# $1 (timeout) must be a bare integer number of seconds — the pure-shell loop
-# compares it arithmetically (the `timeout` binary would also accept suffixes
-# like 15m, but we normalize so both paths share one contract). On timeout the
-# return code is 124, matching GNU `timeout`.
-run_with_timeout() {
- local timeout_seconds="$1"
- shift
-
- # Normalize to a bare integer; fall back to the desktop default if a caller
- # ever passes a suffixed/empty value (the pure-shell loop needs an int).
- case "$timeout_seconds" in
- ''|*[!0-9]*) timeout_seconds=900 ;;
- esac
-
- # The `timeout` binary can only exec an external command, not a shell
- # function. Use it only when the target is NOT a function; functions always
- # go through the pure-shell watchdog (which runs them in a subshell of the
- # current shell and sees them directly — no fragile env export needed).
- if [ "$(type -t "$1" 2>/dev/null)" != "function" ]; then
- local timeout_bin=""
- if command -v timeout >/dev/null 2>&1; then
- timeout_bin="timeout"
- elif command -v gtimeout >/dev/null 2>&1; then
- timeout_bin="gtimeout"
- fi
- if [ -n "$timeout_bin" ]; then
- # GNU `timeout` runs the command in its own process group, so a
- # terminal Ctrl+C is delivered to `timeout` but never reaches the
- # child — the download looks frozen and ignores Ctrl+C (#35166).
- # `--foreground` keeps the command in the shell's foreground group
- # so Ctrl+C reaches it; `-k 10` sends SIGKILL 10s after the deadline
- # so a wedged download can't outlive the timeout. Both flags are
- # GNU-only — probe once and fall back to plain `timeout` on BusyBox
- # (Alpine). When neither binary exists (stock macOS) we drop to the
- # pure-shell watchdog below.
- if "$timeout_bin" --foreground -k 10 1 true >/dev/null 2>&1; then
- "$timeout_bin" --foreground -k 10 "$timeout_seconds" "$@"
- else
- "$timeout_bin" "$timeout_seconds" "$@"
- fi
- return $?
- fi
- fi
-
- # Pure-shell fallback: run in a new process group so we can kill the whole
- # subtree (npm spawns node + the Electron downloader as children).
- set -m
- ( "$@" ) &
- local cmd_pid=$!
- set +m
-
- local waited=0
- local rc
- while [ "$waited" -lt "$timeout_seconds" ]; do
- if ! kill -0 "$cmd_pid" 2>/dev/null; then
- # `|| rc=$?` keeps the non-zero child status without letting `set -e`
- # abort the caller here (this would fire if run_with_timeout were
- # ever called outside an if/|| context).
- rc=0; wait "$cmd_pid" 2>/dev/null || rc=$?
- return "$rc"
- fi
- sleep 1
- waited=$((waited + 1))
- done
-
- # Final boundary recheck: the command may have finished during the last
- # poll interval — don't kill (and mislabel as 124) a process that already
- # exited cleanly in the last second of the budget.
- if ! kill -0 "$cmd_pid" 2>/dev/null; then
- rc=0; wait "$cmd_pid" 2>/dev/null || rc=$?
- return "$rc"
- fi
-
- # Timed out: kill the process group (negative PID), escalate to KILL.
- kill -TERM "-$cmd_pid" 2>/dev/null || kill -TERM "$cmd_pid" 2>/dev/null || true
- sleep 2
- kill -KILL "-$cmd_pid" 2>/dev/null || kill -KILL "$cmd_pid" 2>/dev/null || true
- wait "$cmd_pid" 2>/dev/null || true
- return 124
-}
-
-# Return success only when the host is an apt release NEWER than the newest one
-# Playwright's platform resolver recognizes — the exact condition that makes
-# `playwright install` hang uninterruptibly (#35166). We scope the override
-# retry to this case rather than retrying on *any* failure, so a genuine
-# network/disk/permission failure doesn't get a mismatched-glibc build forced
-# onto it. Newest Playwright-known apt releases as of this writing: Ubuntu
-# 24.04, Debian 13. Anything above triggers the fallback; everything Playwright
-# already handles (and every non-apt distro) does not.
-playwright_host_unrecognized() {
- # Compare dotted versions: returns 0 if $1 > $2.
- _ver_gt() {
- [ "$1" = "$2" ] && return 1
- [ "$(printf '%s\n%s\n' "$1" "$2" | sort -V | tail -n1)" = "$1" ]
- }
- case "$DISTRO" in
- ubuntu) _ver_gt "${DISTRO_VERSION:-0}" "24.04" ;;
- debian) _ver_gt "${DISTRO_VERSION:-0}" "13" ;;
- *) return 1 ;; # Non-apt or unknown — not the #35166 hang condition.
- esac
-}
-
-# Compute the PLAYWRIGHT_HOST_PLATFORM_OVERRIDE value to retry an install with
-# when Playwright's platform resolver rejects the host. ubuntu24.04 is the
-# newest Linux build Playwright has shipped across recent releases and runs on
-# newer apt releases (its binaries are dynamically linked); we point too-new /
-# unrecognized hosts at it. Only x64/arm64 Linux have Playwright builds — emit
-# nothing for anything else so the caller skips the retry. Echoes the value
-# (e.g. "ubuntu24.04-x64") or nothing.
-playwright_fallback_platform() {
- case "$(uname -m)" in
- x86_64|amd64) echo "ubuntu24.04-x64" ;;
- aarch64|arm64) echo "ubuntu24.04-arm64" ;;
- *) : ;; # No Playwright Linux build for this arch.
- esac
-}
-
-# Run a `playwright install ...` command, and if it fails or hangs (the
-# uninterruptible "Installing Playwright Chromium with system dependencies"
-# stall on apt releases Playwright doesn't recognize yet — Ubuntu 26.04,
-# Debian 14, future distros — see #35166), retry it ONCE with
-# PLAYWRIGHT_HOST_PLATFORM_OVERRIDE pinned to the newest known build.
-#
-# The override retry is scoped to the actual hang condition: it fires only when
-# the host is an apt release NEWER than Playwright recognizes
-# (playwright_host_unrecognized). On every release Playwright already supports
-# (Ubuntu <=24.04, Debian <=13) and every non-apt distro, the first attempt is
-# authoritative and a failure is reported as-is — we never force a
-# mismatched-glibc build (microsoft/playwright#35114) onto a host Playwright
-# handles correctly. This is deliberately narrower than a retry-on-any-failure:
-# a network/disk/permission error on a supported host should surface, not get
-# papered over with a platform override. Playwright's maintainers bless this
-# env var as the supported escape hatch for unrecognized platforms
-# (microsoft/playwright#33434); a hardcoded full distro/version table was
-# rejected upstream (microsoft/playwright#33432), so we only need the
-# newest-known floor here.
-#
-# An operator-provided PLAYWRIGHT_HOST_PLATFORM_OVERRIDE is always respected:
-# it is inherited by the first attempt, and the retry is skipped.
-#
-# Usage: run_playwright_install <timeout_seconds> npx playwright install [args...]
-run_playwright_install() {
- local timeout_seconds="$1"
- shift
-
- # First attempt: native platform resolution (inherits any operator override).
- if run_browser_install_with_timeout "$timeout_seconds" "$@" 2>/dev/null; then
- return 0
- fi
-
- # Operator already pinned the platform — their choice already applied to the
- # attempt above; a second identical run won't help.
- if [ -n "${PLAYWRIGHT_HOST_PLATFORM_OVERRIDE:-}" ]; then
- return 1
- fi
-
- # Only retry with an override on the apt releases too new for Playwright to
- # recognize (the #35166 hang). Any other failure is a real failure and is
- # surfaced unchanged.
- if ! playwright_host_unrecognized; then
- return 1
- fi
-
- local fallback
- fallback="$(playwright_fallback_platform)"
- if [ -z "$fallback" ]; then
- return 1 # No usable fallback build for this arch.
- fi
-
- log_warn "Playwright doesn't recognize ${DISTRO} ${DISTRO_VERSION} yet — retrying with PLAYWRIGHT_HOST_PLATFORM_OVERRIDE=$fallback"
- log_info "(apt releases newer than Playwright knows hang at this step; see #35166)"
- PLAYWRIGHT_HOST_PLATFORM_OVERRIDE="$fallback" \
- run_browser_install_with_timeout "$timeout_seconds" "$@"
-}
-
-configure_browser_env_from_system_browser() {
- local env_file="$HERMES_HOME/.env"
- local browser_path="${DETECTED_BROWSER_EXECUTABLE:-}"
-
- if [ -z "$browser_path" ]; then
- browser_path="$(find_system_browser 2>/dev/null || true)"
- fi
-
- if [ -z "$browser_path" ]; then
- return 0
- fi
-
- mkdir -p "$HERMES_HOME"
- if [ ! -f "$env_file" ]; then
- touch "$env_file"
- fi
-
- if grep -q '^AGENT_BROWSER_EXECUTABLE_PATH=' "$env_file" 2>/dev/null; then
- log_info "AGENT_BROWSER_EXECUTABLE_PATH already configured"
- return 0
- fi
-
- {
- echo ""
- echo "# Hermes Agent browser tools — explicit browser override."
- echo "AGENT_BROWSER_EXECUTABLE_PATH=$browser_path"
- } >> "$env_file"
- log_success "Configured browser tools to use $browser_path"
-}
-
-install_node_deps() {
- if [ "$HAS_NODE" = false ]; then
- log_info "Skipping Node.js dependencies (Node not installed)"
- return 0
- fi
-
- if [ "$DISTRO" = "termux" ]; then
- log_info "Skipping automatic Node/browser dependency setup on Termux"
- log_info "Browser automation is not part of the tested Termux install path yet."
- log_info "If you want to experiment manually later, run: cd $INSTALL_DIR && npm install"
- return 0
- fi
-
- if [ -f "$INSTALL_DIR/package.json" ]; then
- log_info "Installing Node.js dependencies (browser tools)..."
- cd "$INSTALL_DIR"
- # Time-boxed: a stalled registry fetch would otherwise hang here with no
- # progress (same #39219 stall class as the desktop build below).
- # A failed npm install used to still print "✓ Node.js dependencies
- # installed", hiding the degradation from the user (#77003). Now it
- # fails the install outright instead of burying the warning (#85297).
- # Capture npm output so failures are diagnosable (#87340).
- local npm_log
- npm_log="$(mktemp)"
- if ! run_with_timeout "$NODE_DEPS_TIMEOUT" npm install --silent \
- >"$npm_log" 2>&1; then
- log_error "npm install failed or timed out; Node.js dependencies were not installed"
- if [ -s "$npm_log" ]; then
- log_error "npm output:"
- cat "$npm_log" >&2
- fi
- rm -f "$npm_log"
- restore_dirty_lockfiles "$INSTALL_DIR"
- return 1
- fi
- rm -f "$npm_log"
- log_success "Node.js dependencies installed"
-
- # Install Playwright browser + system dependencies.
- # Playwright's --with-deps only supports apt-based systems natively.
- # For Arch/Manjaro we install the system libs via pacman first.
- # Other systems must install Chromium dependencies manually.
- if [ "$SKIP_BROWSER" = true ]; then
- log_info "Skipping Playwright/Chromium install (--skip-browser)"
- log_info "Browser tools will be unavailable until you run manually:"
- log_info " cd $INSTALL_DIR && npx playwright install chromium"
- log_info "On apt-based systems, an admin also needs to run:"
- log_info " sudo npx playwright install-deps chromium"
- else
- log_info "Installing browser engine (Playwright Chromium)..."
- strip_snap_browser_override
- DETECTED_BROWSER_EXECUTABLE="$(find_system_browser 2>/dev/null || true)"
- if [ -n "$DETECTED_BROWSER_EXECUTABLE" ]; then
- log_success "Using explicit browser override: $DETECTED_BROWSER_EXECUTABLE"
- log_info "Skipping bundled Chromium download (AGENT_BROWSER_EXECUTABLE_PATH is set)."
- else
- case "$DISTRO" in
- ubuntu|debian|raspbian|pop|linuxmint|elementary|zorin|kali|parrot)
- # Use --with-deps only when sudo is available non-interactively
- # (root, or a user with passwordless sudo). Non-sudo users
- # — typical for systemd service accounts and unprivileged
- # operator users — would otherwise get blocked on an
- # interactive sudo prompt that they can't satisfy. Fall back
- # to the browser-only install in that case, and print the
- # exact command the admin needs to run separately.
- if [ "$(id -u)" -eq 0 ] || (command -v sudo >/dev/null 2>&1 && sudo -n true 2>/dev/null); then
- log_info "Installing Playwright Chromium with system dependencies..."
- cd "$INSTALL_DIR" && run_playwright_install 600 npx playwright install --with-deps chromium || {
- log_warn "Playwright browser installation failed — browser tools will not work."
- log_warn "Try running manually: cd $INSTALL_DIR && npx playwright install --with-deps chromium"
- }
- else
- log_warn "No sudo available — skipping system-library install (--with-deps)."
- log_info "Ask an administrator to run, one time, as root:"
- log_info " sudo npx playwright install-deps chromium"
- log_info " (from $INSTALL_DIR, after Node.js deps are installed)"
- log_info "Installing Chromium binary into this user's Playwright cache..."
- cd "$INSTALL_DIR" && run_playwright_install 600 npx playwright install chromium || {
- log_warn "Playwright browser installation failed — browser tools will not work."
- log_warn "Try running manually: cd $INSTALL_DIR && npx playwright install chromium"
- }
- fi
- ;;
- arch|manjaro|cachyos|endeavouros|garuda)
- if command -v pacman &> /dev/null; then
- log_info "Arch-family distro detected — installing Chromium system dependencies via pacman..."
- if command -v sudo &> /dev/null && sudo -n true 2>/dev/null; then
- sudo NEEDRESTART_MODE=a pacman -S --noconfirm --needed \
- nss atk at-spi2-core cups libdrm libxkbcommon mesa pango cairo alsa-lib >/dev/null 2>&1 || true
- elif [ "$(id -u)" -eq 0 ]; then
- pacman -S --noconfirm --needed \
- nss atk at-spi2-core cups libdrm libxkbcommon mesa pango cairo alsa-lib >/dev/null 2>&1 || true
- else
- log_warn "Cannot install browser deps without sudo. Run manually:"
- log_warn " sudo pacman -S nss atk at-spi2-core cups libdrm libxkbcommon mesa pango cairo alsa-lib"
- fi
- fi
- cd "$INSTALL_DIR" && run_playwright_install 600 npx playwright install chromium || {
- log_warn "Playwright browser installation failed — browser tools will not work."
- }
- ;;
- fedora|rhel|centos|rocky|alma)
- log_warn "Playwright does not support automatic dependency installation on RPM-based systems."
- log_info "Install Chromium system dependencies manually before using browser tools:"
- log_info " sudo dnf install nss atk at-spi2-core cups-libs libdrm libxkbcommon mesa-libgbm pango cairo alsa-lib"
- cd "$INSTALL_DIR" && run_playwright_install 600 npx playwright install chromium || {
- log_warn "Playwright browser installation failed — install dependencies above and retry."
- }
- ;;
- opensuse*|sles)
- log_warn "Playwright does not support automatic dependency installation on zypper-based systems."
- log_info "Install Chromium system dependencies manually before using browser tools:"
- log_info " sudo zypper install mozilla-nss libatk-1_0-0 at-spi2-core cups-libs libdrm2 libxkbcommon0 Mesa-libgbm1 pango cairo libasound2"
- cd "$INSTALL_DIR" && run_playwright_install 600 npx playwright install chromium || {
- log_warn "Playwright browser installation failed — install dependencies above and retry."
- }
- ;;
- *)
- log_warn "Playwright does not support automatic dependency installation on $DISTRO."
- log_info "Install Chromium/browser system dependencies for your distribution, then run:"
- log_info " cd $INSTALL_DIR && npx playwright install chromium"
- log_info "Browser tools will not work until dependencies are installed."
- cd "$INSTALL_DIR" && run_playwright_install 600 npx playwright install chromium || true
- ;;
- esac
- fi
- fi
- log_success "Browser engine setup complete"
- fi
-
- # Install TUI dependencies
- if [ -f "$INSTALL_DIR/ui-tui/package.json" ]; then
- log_info "Installing TUI dependencies..."
- cd "$INSTALL_DIR/ui-tui"
- # Time-boxed: a stalled registry fetch would otherwise hang here (#39219).
- # Report success only on actual success, same as node-deps above
- # (#77003) — and fail the install outright (#85297).
- # Capture npm output so failures are diagnosable (#87340).
- local tui_npm_log
- tui_npm_log="$(mktemp)"
- if ! run_with_timeout "$NODE_DEPS_TIMEOUT" npm install --silent \
- >"$tui_npm_log" 2>&1; then
- log_error "TUI npm install failed or timed out; TUI dependencies were not installed"
- if [ -s "$tui_npm_log" ]; then
- log_error "npm output:"
- cat "$tui_npm_log" >&2
- fi
- rm -f "$tui_npm_log"
- restore_dirty_lockfiles "$INSTALL_DIR"
- return 1
- fi
- rm -f "$tui_npm_log"
- log_success "TUI dependencies installed"
- fi
-
- # Keep the checkout clean so `hermes update` doesn't autostash every run.
- restore_dirty_lockfiles "$INSTALL_DIR"
-}
-
-install_browser_use_cli() {
- # The Browser Use CLI is the default browser backend when it is runnable
- # (tools/browser_use_cli.py). Provision it here so fresh installs don't
- # silently fall back to the built-in browser tools. Best-effort: any
- # failure is non-fatal because browser_exec can still run via uvx and
- # `hermes tools` can install it later.
- if [ "$SKIP_BROWSER" = true ]; then
- log_info "Skipping Browser Use CLI install (--skip-browser)"
- return 0
- fi
- if [ "$DISTRO" = "termux" ]; then
- return 0
- fi
- if [ -z "$UV_CMD" ]; then
- log_info "Skipping Browser Use CLI install (uv unavailable)"
- return 0
- fi
- # MANAGED-FIRST: only Hermes' managed copy short-circuits. A browser-use
- # on the user's PATH is a side install — resolution prefers the managed
- # copy, so it must be provisioned regardless.
- if [ -x "$HERMES_HOME/bin/browser-use" ]; then
- log_success "Browser Use CLI already installed"
- return 0
- fi
-
- log_info "Installing Browser Use CLI (default browser backend)..."
- # UV_TOOL_BIN_DIR keeps the binary inside Hermes' managed bin dir, where
- # the browser tool resolves it — no reliance on the user's PATH.
- if run_with_timeout 600 env UV_NO_CONFIG=1 UV_TOOL_BIN_DIR="$HERMES_HOME/bin" \
- "$UV_CMD" tool install browser-use >/dev/null 2>&1; then
- log_success "Browser Use CLI installed"
- else
- log_warn "Browser Use CLI install failed — browser automation falls back to built-in tools."
- log_info "Install later with: $UV_CMD tool install browser-use (or via 'hermes tools')"
- fi
-}
-
-cua_driver_runtime_compatible() {
- local driver_path version_output manifest_output
- local major minor
- driver_path="$(command -v cua-driver 2>/dev/null)" || return 1
- version_output="$("$driver_path" --version 2>/dev/null)" || return 1
- if [[ ! "$version_output" =~ ([0-9]+)\.([0-9]+)\.([0-9]+) ]]; then
- return 1
- fi
- major="${BASH_REMATCH[1]}"
- minor="${BASH_REMATCH[2]}"
- if (( major == 0 && minor < 20 )); then
- return 1
- fi
- manifest_output="$("$driver_path" manifest 2>/dev/null)" || return 1
- local required
- for required in \
- '"mcp_invocation"' \
- '"--socket"' \
- '"--grant"' \
- '"--permission-mode"' \
- '"--capability-manifest"' \
- '"--approve-capability-manifest"' \
- '"--embedded"'; do
- case "$manifest_output" in
- *"$required"*) ;;
- *) return 1 ;;
- esac
- done
- return 0
-}
-
-install_computer_use_driver() {
- # 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 (the confusion this fixes:
- # users had to discover `hermes computer-use install` on their own).
- # Best-effort and non-fatal: the enable paths still lazy-install via
- # install_cua_driver() when this step was skipped or failed.
- if [ "$SKIP_COMPUTER_USE" = true ]; then
- log_info "Skipping Computer Use (cua-driver) install (--skip-computer-use)"
- return 0
- fi
- case "$DISTRO" in
- termux)
- return 0
- ;;
- esac
- if command -v cua-driver >/dev/null 2>&1; then
- if cua_driver_runtime_compatible; then
- log_success "Computer Use driver (cua-driver) already installed and compatible"
- return 0
- fi
- log_warn "Existing cua-driver is old or incomplete; repairing it"
- fi
- # Non-admin macOS accounts can't receive the CuaDriver.app bundle in
- # /Applications; skip cleanly instead of failing loudly (#47865 class).
- if [ "$(uname -s)" = "Darwin" ] && [ -d /Applications ] && [ ! -w /Applications ]; then
- log_info "Skipping Computer Use driver (cua-driver): /Applications is not writable"
- return 0
- fi
-
- log_info "Installing Computer Use driver (cua-driver)..."
- # Same upstream installer `hermes computer-use install` runs; time-boxed
- # so a stalled GitHub download can't hang the Hermes install. The
- # upstream installer serializes with its own lock (600s stale window),
- # so give it a ceiling above that — matching Hermes'
- # _CUA_INSTALLER_TIMEOUT (660s).
- local cua_log
- cua_log="$(mktemp)"
- if run_with_timeout 660 /bin/bash -c \
- 'curl -fsSL https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver/scripts/install.sh | /bin/bash' \
- >"$cua_log" 2>&1; then
- log_success "Computer Use driver installed (enable via 'hermes tools' → Computer Use)"
- else
- log_warn "Computer Use driver install failed — it will install on demand when you enable the tool."
- log_info "Install later with: hermes computer-use install"
- tail -n 5 "$cua_log" >&2 || true
- fi
- rm -f "$cua_log"
-}
-
-run_setup_wizard() {
- if [ "$RUN_SETUP" = false ]; then
- log_info "Skipping setup wizard (--skip-setup)"
- return 0
- fi
-
- # The setup wizard reads from /dev/tty, so it works even when the
- # install script itself is piped (curl | bash). Only skip if no
- # terminal is available at all (e.g. Docker build, CI).
- #
- # Probe by actually opening /dev/tty: a bare existence test passes
- # in Docker builds where the device node is in the mount namespace
- # but opening fails with ENXIO, so the wizard would proceed and
- # then crash on `< /dev/tty` below.
- if ! (: </dev/tty) 2>/dev/null; then
- log_info "Setup wizard skipped (no terminal available). Run 'hermes setup' after install."
- return 0
- fi
-
- echo ""
- log_info "Starting setup wizard..."
- echo ""
-
- cd "$INSTALL_DIR"
-
- # Run hermes setup using the venv Python directly (no activation needed).
- # Redirect stdin from /dev/tty so interactive prompts work when piped from curl.
- if [ "$USE_VENV" = true ]; then
- "$INSTALL_DIR/venv/bin/python" -m hermes_cli.main setup < /dev/tty
- else
- python -m hermes_cli.main setup < /dev/tty
- fi
-}
-
-maybe_start_gateway() {
- # Check if any messaging platform tokens were configured
- ENV_FILE="$HERMES_HOME/.env"
- if [ ! -f "$ENV_FILE" ]; then
- return 0
- fi
-
- HAS_MESSAGING=false
- for VAR in TELEGRAM_BOT_TOKEN DISCORD_BOT_TOKEN SLACK_BOT_TOKEN SLACK_APP_TOKEN WHATSAPP_ENABLED; do
- VAL=$(grep "^${VAR}=" "$ENV_FILE" 2>/dev/null | cut -d'=' -f2-)
- if [ -n "$VAL" ] && [ "$VAL" != "your-token-here" ]; then
- HAS_MESSAGING=true
- break
- fi
- done
-
- if [ "$HAS_MESSAGING" = false ]; then
- return 0
- fi
-
- echo ""
- log_info "Messaging platform token detected!"
- log_info "The gateway needs to be running for Hermes to send/receive messages."
-
- # If WhatsApp is enabled and no session exists yet, run foreground first for QR scan
- WHATSAPP_VAL=$(grep "^WHATSAPP_ENABLED=" "$ENV_FILE" 2>/dev/null | cut -d'=' -f2-)
- WHATSAPP_SESSION="$HERMES_HOME/whatsapp/session/creds.json"
- if [ "$WHATSAPP_VAL" = "true" ] && [ ! -f "$WHATSAPP_SESSION" ]; then
- if [ "$IS_INTERACTIVE" = true ]; then
- echo ""
- log_info "WhatsApp is enabled but not yet paired."
- log_info "Running 'hermes whatsapp' to pair via QR code..."
- echo ""
- if prompt_yes_no "Pair WhatsApp now?" "yes"; then
- HERMES_CMD="$(get_hermes_command_path)"
- $HERMES_CMD whatsapp || true
- fi
- else
- log_info "WhatsApp pairing skipped (non-interactive). Run 'hermes whatsapp' to pair."
- fi
- fi
-
- # Probe by actually opening /dev/tty: a bare existence test passes
- # in Docker builds where the device node is in the mount namespace
- # but opening fails with ENXIO. See #16746.
- if ! (: </dev/tty) 2>/dev/null; then
- log_info "Gateway setup skipped (no terminal available). Run 'hermes gateway install' later."
- return 0
- fi
-
- echo ""
- local should_install_gateway=false
- if [ "$DISTRO" = "termux" ]; then
- if prompt_yes_no "Would you like to start the gateway in the background?" "yes"; then
- should_install_gateway=true
- fi
- else
- if prompt_yes_no "Would you like to install the gateway as a background service?" "yes"; then
- should_install_gateway=true
- fi
- fi
-
- if [ "$should_install_gateway" = true ]; then
- HERMES_CMD="$(get_hermes_command_path)"
-
- if [ "$DISTRO" != "termux" ] && command -v systemctl &> /dev/null; then
- log_info "Installing systemd service..."
- if $HERMES_CMD gateway install 2>/dev/null; then
- log_success "Gateway service installed"
- if $HERMES_CMD gateway start 2>/dev/null; then
- log_success "Gateway started! Your bot is now online."
- else
- log_warn "Service installed but failed to start. Try: hermes gateway start"
- fi
- else
- log_warn "Systemd install failed. You can start manually: hermes gateway"
- fi
- else
- if [ "$DISTRO" = "termux" ]; then
- log_info "Termux detected — starting gateway in best-effort background mode..."
- else
- log_info "systemd not available — starting gateway in background..."
- fi
- nohup $HERMES_CMD gateway > "$HERMES_HOME/logs/gateway.log" 2>&1 &
- GATEWAY_PID=$!
- log_success "Gateway started (PID $GATEWAY_PID). Logs: ~/.hermes/logs/gateway.log"
- log_info "To stop: kill $GATEWAY_PID"
- log_info "To restart later: hermes gateway"
- if [ "$DISTRO" = "termux" ]; then
- log_warn "Android may stop background processes when Termux is suspended or the system reclaims resources."
- fi
- fi
- else
- log_info "Skipped. Start the gateway later with: hermes gateway"
- fi
-}
-
-write_bootstrap_marker() {
- # Writes $INSTALL_DIR/.hermes-bootstrap-complete, which tells the Hermes
- # desktop app (apps/desktop/electron/main.ts) and the macOS launcher fast
- # path (apps/bootstrap-installer) "a real install finished here -- don't
- # re-run first-run bootstrap."
- #
- # Schema mirrors install.ps1's Write-BootstrapMarker and main.ts's
- # writeBootstrapMarker(). Keep the three in lockstep:
- # schemaVersion 1 + pinnedCommit (length >= 7) are what the desktop
- # validator requires; desktopVersion is omitted because only the desktop
- # app knows its own version.
- if [ ! -d "$INSTALL_DIR" ]; then
- log_warn "Skipping bootstrap marker: $INSTALL_DIR doesn't exist"
- return 0
- fi
-
- # Explicit --commit wins; otherwise read HEAD from the checkout we just
- # installed. If neither resolves, skip the marker entirely rather than
- # write one the desktop will reject -- an absent marker is a clean
- # "bootstrap needed", a malformed one is a confusing half-state.
- local pinned_commit="$INSTALL_COMMIT"
- if [ -z "$pinned_commit" ]; then
- pinned_commit=$(git -C "$INSTALL_DIR" rev-parse HEAD 2>/dev/null) || pinned_commit=""
- fi
-
- if [ -z "$pinned_commit" ]; then
- log_warn "Skipping bootstrap marker: could not resolve HEAD in $INSTALL_DIR"
- return 0
- fi
-
- local marker_path="$INSTALL_DIR/.hermes-bootstrap-complete"
- local tmp_path="$marker_path.tmp"
-
- # Atomic publish: the macOS launcher predicate only checks existence, so a
- # torn write would arm the fast path against a half-written marker.
- printf '{\n "schemaVersion": 1,\n "pinnedCommit": "%s",\n "pinnedBranch": "%s",\n "completedAt": "%s"\n}\n' \
- "$pinned_commit" \
- "$BRANCH" \
- "$(date -u +%Y-%m-%dT%H:%M:%S.000Z)" > "$tmp_path"
- mv -f "$tmp_path" "$marker_path"
-}
-
-print_success() {
- echo ""
- echo -e "${GREEN}${BOLD}"
- echo "┌─────────────────────────────────────────────────────────┐"
- echo "│ ✓ Installation Complete! │"
- echo "└─────────────────────────────────────────────────────────┘"
- echo -e "${NC}"
- echo ""
-
- # Show file locations
- echo -e "${CYAN}${BOLD}📁 Your files:${NC}"
- echo ""
- echo -e " ${YELLOW}Config:${NC} $HERMES_HOME/config.yaml"
- echo -e " ${YELLOW}API Keys:${NC} $HERMES_HOME/.env"
- echo -e " ${YELLOW}Data:${NC} $HERMES_HOME/cron/, sessions/, logs/"
- echo -e " ${YELLOW}Code:${NC} $INSTALL_DIR"
- echo ""
-
- echo -e "${CYAN}─────────────────────────────────────────────────────────${NC}"
- echo ""
- echo -e "${CYAN}${BOLD}🚀 Commands:${NC}"
- echo ""
- echo -e " ${GREEN}hermes${NC} Start chatting"
- echo -e " ${GREEN}hermes setup${NC} Configure API keys & settings"
- echo -e " ${GREEN}hermes config${NC} View/edit configuration"
- echo -e " ${GREEN}hermes config edit${NC} Open config in editor"
- echo -e " ${GREEN}hermes gateway install${NC} Install gateway service (messaging + cron)"
- echo -e " ${GREEN}hermes update${NC} Update to latest version"
- echo ""
-
- echo -e "${CYAN}─────────────────────────────────────────────────────────${NC}"
- echo ""
- if [ "$DISTRO" = "termux" ]; then
- echo -e "${YELLOW}⚡ 'hermes' was linked into $(get_command_link_display_dir), which is already on PATH in Termux.${NC}"
- echo ""
- elif [ "$ROOT_FHS_LAYOUT" = true ]; then
- echo -e "${YELLOW}⚡ 'hermes' was linked into /usr/local/bin and is ready to use — no shell reload needed.${NC}"
- echo ""
- else
- echo -e "${YELLOW}⚡ Reload your shell to use 'hermes' command:${NC}"
- echo ""
- LOGIN_SHELL="$(basename "${SHELL:-/bin/bash}")"
- if [ "$LOGIN_SHELL" = "zsh" ]; then
- echo " source ~/.zshrc"
- elif [ "$LOGIN_SHELL" = "bash" ]; then
- echo " source ~/.bashrc"
- elif [ "$LOGIN_SHELL" = "fish" ]; then
- echo " source ~/.config/fish/config.fish"
- else
- echo " source ~/.bashrc # or ~/.zshrc"
- fi
- echo ""
- fi
-
- # Show Node.js warning if auto-install failed
- if [ "$HAS_NODE" = false ]; then
- echo -e "${YELLOW}"
- echo "Note: Node.js could not be installed automatically."
- echo "Browser tools need Node.js. Install manually:"
- if [ "$DISTRO" = "termux" ]; then
- echo " pkg install nodejs"
- else
- echo " https://nodejs.org/en/download/"
- fi
- echo -e "${NC}"
- fi
-
- # Show ripgrep note if not installed
- if [ "$HAS_RIPGREP" = false ]; then
- echo -e "${YELLOW}"
- echo "Note: ripgrep (rg) was not found. File search will use"
- echo "grep as a fallback. For faster search in large codebases,"
- if [ "$DISTRO" = "termux" ]; then
- echo "install ripgrep: pkg install ripgrep"
- else
- echo "install ripgrep: sudo apt install ripgrep (or brew install ripgrep)"
- fi
- echo -e "${NC}"
- fi
-}
-
-ensure_browser() {
- if ! command -v node >/dev/null 2>&1; then
- local node_bin="$HERMES_HOME/node/bin/node"
- if [ -x "$node_bin" ]; then
- export PATH="$HERMES_HOME/node/bin:$PATH"
- else
- log_error "Node.js not found. Run with --ensure node first."
- return 1
- fi
- fi
-
- local npm_bin
- npm_bin="$(command -v npm 2>/dev/null || echo "$HERMES_HOME/node/bin/npm")"
- if [ ! -x "$npm_bin" ]; then
- log_error "npm not found"
- return 1
- fi
-
- # agent-browser itself is intentionally NOT installed here (#43564 /
- # PR #44772 review): it resolves lazily via `npx agent-browser` instead,
- # which every consumer (tools/browser_tool.py, `hermes update`'s npx
- # cache warm) already goes through. Eagerly npm-installing a second,
- # separately version-pinned copy here -- only reachable via this
- # explicit --ensure browser fallback in the first place -- was redundant
- # complexity and an extra credential/supply-chain surface for a path
- # npx already covers.
- log_info "Installing camofox browser server..."
- local log_file
- log_file="$(mktemp)"
- # Time-boxed (#39219): a stalled npm registry fetch here would otherwise
- # hang the installer with no progress, same class as the desktop build.
- if ! run_with_timeout "$NODE_DEPS_TIMEOUT" "$npm_bin" install -g --prefix "$HERMES_HOME/node" --silent --ignore-scripts \
- "@askjo/camofox-browser@^1.5.2" \
- >"$log_file" 2>&1; then
- log_error "npm install failed or timed out:"
- cat "$log_file" >&2
- rm -f "$log_file"
- return 1
- fi
- rm -f "$log_file"
- export PATH="$HERMES_HOME/node/bin:$PATH"
-
- strip_snap_browser_override
- local sys_browser
- sys_browser="$(find_system_browser 2>/dev/null || true)"
- if [ -n "$sys_browser" ]; then
- configure_browser_env_from_system_browser "$sys_browser"
- log_info "Explicit browser override set -- Chromium download will be skipped when agent-browser installs on demand"
- fi
-
- return 0
-}
-
-ensure_mode() {
- detect_os
-
- IFS=',' read -ra DEPS <<< "$ENSURE_DEPS"
- for dep in "${DEPS[@]}"; do
- dep="$(echo "$dep" | tr -d '[:space:]')"
- case "$dep" in
- node)
- check_node
- ;;
- browser)
- check_node
- if [ "$HAS_NODE" = true ]; then
- ensure_browser
- fi
- ;;
- ripgrep)
- if ! command -v rg &>/dev/null; then
- HAS_RIPGREP=false
- HAS_FFMPEG=true
- install_system_packages
- fi
- ;;
- ffmpeg)
- if ! command -v ffmpeg &>/dev/null; then
- HAS_FFMPEG=false
- HAS_RIPGREP=true
- install_system_packages
- fi
- ;;
- *)
- log_warn "Unknown dependency: $dep"
- ;;
- esac
- done
-}
-
-
-# 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/resumed download
-# that leaves concatenated junk - makes electron-builder's `unpack-electron`
-# extract a tree MISSING the electron binary, so the `electron`->`Hermes` rename
-# dies with ENOENT and every re-run repeats the broken extraction forever. This
-# is the bash sibling of install.ps1's Clear-ElectronBuildCache and the Python
-# _purge_electron_build_cache() used by `hermes desktop`; install.sh was the only
-# build path lacking it. Echoes the removed paths (one per line); best-effort.
-clear_electron_build_cache() {
- local desktop_dir="$1"
- local removed=""
-
- # Per-user Electron download cache dirs, honoring the overrides @electron/get
- # respects, then the platform defaults (macOS: ~/Library/Caches/electron,
- # Linux: $XDG_CACHE_HOME/electron or ~/.cache/electron).
- local cache_dirs=()
- [ -n "${electron_config_cache:-}" ] && cache_dirs+=("$electron_config_cache")
- [ -n "${ELECTRON_CACHE:-}" ] && cache_dirs+=("$ELECTRON_CACHE")
- if [ "$OS" = "macos" ]; then
- cache_dirs+=("$HOME/Library/Caches/electron")
- else
- [ -n "${XDG_CACHE_HOME:-}" ] && cache_dirs+=("$XDG_CACHE_HOME/electron")
- cache_dirs+=("$HOME/.cache/electron")
- fi
-
- local dir zip
- for dir in "${cache_dirs[@]}"; do
- [ -d "$dir" ] || continue
- # Recurse: the bad copy may be the top-level zip OR a copy inside an
- # @electron/get hash subdir.
- while IFS= read -r zip; do
- [ -n "$zip" ] || continue
- if rm -f "$zip" 2>/dev/null; then
- removed="$removed$zip
-"
- fi
- done <<EOF
-$(find "$dir" -type f -name 'electron-*.zip' 2>/dev/null)
-EOF
- done
-
- # A half-written unpacked dir from an interrupted prior pack poisons the
- # rename even after the zip is fixed (mac-arm64-unpacked / linux-unpacked).
- local release_dir="$desktop_dir/release"
- if [ -d "$release_dir" ]; then
- local unpacked
- while IFS= read -r unpacked; do
- [ -n "$unpacked" ] || continue
- if rm -rf "$unpacked" 2>/dev/null; then
- removed="$removed$unpacked
-"
- fi
- done <<EOF
-$(find "$release_dir" -maxdepth 1 -type d -name '*-unpacked' 2>/dev/null)
-EOF
- fi
-
- printf '%s' "$removed"
-}
-
-# Run the desktop pack in $1 (the apps/desktop dir). `npm run pack` = tsc +
-# vite build + electron-builder --dir, producing an unpacked app for the
-# current OS. Signing auto-discovery is disabled so electron-builder falls back
-# to an ad-hoc signature instead of grabbing an unrelated Developer ID from the
-# keychain (a real signed/notarized .dmg needs Apple credentials — a separate
-# release concern). Optional $2 = an ELECTRON_MIRROR base URL for this attempt,
-# used as a fallback when the default GitHub release download is blocked.
-_desktop_pack() {
- local desktop_dir="$1"
- local mirror="${2:-}"
- if [ -n "$mirror" ]; then
- ( cd "$desktop_dir" && ELECTRON_MIRROR="$mirror" CSC_IDENTITY_AUTO_DISCOVERY=false npm run pack )
- else
- ( cd "$desktop_dir" && CSC_IDENTITY_AUTO_DISCOVERY=false npm run pack )
- fi
-}
-
-# Last-resort Electron mirror after GitHub download fails (#47266).
-DESKTOP_ELECTRON_FALLBACK_MIRROR="https://npmmirror.com/mirrors/electron/"
-
-# Per-attempt wall-clock cap for the desktop npm install / electron-builder pack
-# (#39219). A stalled (not failed) Electron download on a throttled/blocked link
-# never returns, so without this the installer hangs forever on "Build desktop
-# app". 900s is generous enough for a slow-but-progressing ~150MB fetch + build;
-# override with DESKTOP_BUILD_TIMEOUT for very slow links.
-DESKTOP_BUILD_TIMEOUT="${DESKTOP_BUILD_TIMEOUT:-900}"
-
-# Wall-clock cap for the plain registry `npm install`s (browser-tools + TUI
-# deps). Same #39219 stall class but no ~150MB Electron binary, so a shorter
-# default; override with NODE_DEPS_TIMEOUT for very slow links.
-NODE_DEPS_TIMEOUT="${NODE_DEPS_TIMEOUT:-600}"
-
-# Electron package dir — workspace-local nest first, then root hoist.
-_electron_dir() {
- local install_dir="$1"
- if [ -d "$install_dir/apps/desktop/node_modules/electron" ]; then
- printf '%s\n' "$install_dir/apps/desktop/node_modules/electron"
- else
- printf '%s\n' "$install_dir/node_modules/electron"
- fi
-}
-
-# True when dist/ holds a usable Electron binary (#38673 / run-electron-builder.mjs).
-_electron_dist_ok() {
- local install_dir="$1"
- local electron_dir
- electron_dir="$(_electron_dir "$install_dir")"
- if [ "$OS" = "macos" ]; then
- [ -e "$electron_dir/dist/Electron.app/Contents/MacOS/Electron" ]
- else
- [ -e "$electron_dir/dist/electron" ]
- fi
-}
-
-# Best-effort: run electron/install.js to populate dist/ (optional mirror).
-_restore_electron_dist() {
- local install_dir="$1"
- local mirror="${2:-}"
- local electron_dir
- electron_dir="$(_electron_dir "$install_dir")"
- _electron_dist_ok "$install_dir" && return 0
-
- [ -f "$electron_dir/install.js" ] || return 1
- command -v node >/dev/null 2>&1 || return 1
-
- rm -rf "$electron_dir/dist" 2>/dev/null || true
- rm -f "$electron_dir/path.txt" 2>/dev/null || true
-
- if [ -n "$mirror" ]; then
- ( cd "$electron_dir" && ELECTRON_MIRROR="$mirror" node install.js ) || true
- else
- ( cd "$electron_dir" && node install.js ) || true
- fi
- _electron_dist_ok "$install_dir"
-}
-
-_electron_pkg_staged_missing_dist() {
- local install_dir="$1"
- local electron_dir
- electron_dir="$(_electron_dir "$install_dir")"
- [ -f "$electron_dir/package.json" ] && [ -f "$electron_dir/install.js" ] && ! _electron_dist_ok "$install_dir"
-}
-
-_restore_electron_dist_with_fallback() {
- local install_dir="$1"
- _restore_electron_dist "$install_dir" \
- || { [ -z "${ELECTRON_MIRROR:-}" ] && _restore_electron_dist "$install_dir" "$DESKTOP_ELECTRON_FALLBACK_MIRROR"; }
-}
-
-# Build apps/desktop into a launchable native app. Mirrors install.ps1's
-# Install-Desktop: a root-level npm install so the apps/* workspace resolves
-# the desktop's own deps (Electron ~150MB), then `npm run pack`
-# (electron-builder --dir) which emits an unpacked app for the current OS. Only invoked
-# via the 'desktop' stage / --include-desktop, which the Electron app's own
-# first-launch bootstrap never requests (it must not rebuild itself).
-install_desktop_voice_deps() {
- # 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. Lazy install remains the fallback for CLI-only installs and
- # for anything this best-effort step fails to fetch.
- local _prev_venv="${VIRTUAL_ENV:-}"
- if [ "$USE_VENV" = true ]; then
- export VIRTUAL_ENV="$INSTALL_DIR/venv"
- fi
- if [ -z "${UV_CMD:-}" ]; then
- install_uv || true
- fi
- if [ -z "${UV_CMD:-}" ]; then
- log_warn "uv unavailable — voice/wake deps will lazy-install at first use instead"
- return 0
- fi
- log_info "Installing voice + wake-word dependencies (onnxruntime, faster-whisper — 1-3min)..."
- if (cd "$INSTALL_DIR" && $UV_CMD pip install -e ".[wake,voice]") ; then
- log_success "Voice + wake-word dependencies installed"
- else
- log_warn "Voice/wake dependency install failed — they will lazy-install at first use"
- fi
- if [ "$USE_VENV" = true ] && [ -z "$_prev_venv" ]; then
- unset VIRTUAL_ENV
- fi
- return 0
-}
-
-install_desktop() {
- local desktop_dir="$INSTALL_DIR/apps/desktop"
-
- # The desktop stage only runs when a build is explicitly requested
- # (--include-desktop / 'desktop' stage), so a missing toolchain is a hard
- # failure, not a silent skip — a silent skip yields a "complete" install
- # with no app and a confusing "couldn't find a built desktop" at launch.
- # Always re-resolve Node here. Stages run in separate processes, so we can't
- # trust an earlier check; more importantly check_node now enforces the
- # supported Node lines and prepends the Hermes-managed Node to PATH, so
- # the build never runs on a too-old system Node — the cause of the opaque
- # "Build desktop app … exit code 1" failure (Vite crashes on old Node).
- check_node
- if ! command -v npm >/dev/null 2>&1; then
- log_error "Cannot build desktop app: Node.js / npm unavailable"
- log_info "Install Node.js and retry: cd $desktop_dir && npm run pack"
- return 1
- fi
- if [ ! -f "$desktop_dir/package.json" ]; then
- log_warn "Skipping desktop build (apps/desktop not present in checkout)"
- return 0
- fi
-
- # 1. Root workspace install so apps/desktop's deps (Electron, Vite,
- # node-pty prebuilds) resolve. The browser-tools install runs in the
- # repo-root package workspace, which does not pull apps/* deps.
- #
- # Prefer `npm ci`: it deletes node_modules and reinstalls from the
- # lockfile, so it always produces 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 and `npm run pack`'s
- # `tsc -b` failing with no obvious cause. Fall back to `npm install`
- # only if `npm ci` is unavailable or the lockfile is out of sync.
- #
- # Both the install and the build below are wrapped in a hard wall-clock
- # timeout (#39219): the Electron binary (~150MB) is fetched from GitHub,
- # and on a throttled/blocked connection that download can *stall* — npm
- # neither errors nor exits, so the installer sits on "Build desktop app"
- # forever with only `npm warn deprecated` lines visible. A stall now
- # converts to a non-zero exit, which feeds the existing self-heal /
- # mirror-fallback escalation instead of hanging the whole install.
- #
- # The `npm ci` and its `npm install` fallback SHARE one budget: a stalled
- # link wedges both identically, so giving each a full DESKTOP_BUILD_TIMEOUT
- # would double the worst-case hang. We compute a single deadline and pass
- # the remaining seconds to the fallback (min 30s so it still gets a real
- # attempt if `npm ci` failed fast rather than stalling).
- log_info "Installing desktop workspace dependencies (includes Electron ~150MB, 1-3min)..."
- local _deps_start _deps_remaining
- _deps_start=$(date +%s)
- if run_with_timeout "$DESKTOP_BUILD_TIMEOUT" bash -c 'cd "$1" && npm ci' _ "$INSTALL_DIR"; then
- log_success "Desktop workspace dependencies installed"
- elif _deps_remaining=$(( DESKTOP_BUILD_TIMEOUT - ($(date +%s) - _deps_start) )); \
- [ "$_deps_remaining" -lt 30 ] && _deps_remaining=30; \
- run_with_timeout "$_deps_remaining" bash -c 'cd "$1" && npm install' _ "$INSTALL_DIR"; then
- log_success "Desktop workspace dependencies installed"
- elif _electron_pkg_staged_missing_dist "$INSTALL_DIR"; then
- log_warn "Desktop dependency install failed with a missing Electron dist; attempting self-heal..."
- _restore_electron_dist_with_fallback "$INSTALL_DIR" || true
- else
- log_error "Desktop workspace npm install failed"
- # Common cause: a previous 'sudo npm'/'sudo npx' left root-owned files in
- # ~/.npm, so this non-root install can't write the shared cache. npm hides
- # it behind a confusing EEXIST / "File exists" message while the real errno
- # is EACCES (-13). Point the user at the fix instead of a raw npm trace.
- log_info "If the errors above mention EACCES / 'permission denied' / EEXIST while"
- log_info "writing the npm cache, your ~/.npm likely holds root-owned files from an"
- log_info "earlier 'sudo npm' or 'sudo npx'. Reclaim ownership and retry:"
- log_info " sudo chown -R \"\$(id -un)\" ~/.npm && npm cache verify"
- log_info "Then re-run this installer, or build manually:"
- log_info " cd \"$INSTALL_DIR\" && npm ci && cd apps/desktop && npm run pack"
- return 1
- fi
-
- # 2. Build, with up to three escalating attempts so a transient/blocked
- # Electron download self-heals instead of failing the whole install:
- # a) plain `npm run pack` (downloads Electron from GitHub),
- # b) on failure, purge a corrupt cached zip + stale unpacked dir and
- # retry (matches install.ps1 / `hermes desktop`),
- # c) on still-failing, fall back to a public Electron mirror — this is
- # the GitHub-blocked/throttled case (the repeating "retrying" log).
- log_info "Building desktop app (this takes 1-3 minutes)..."
- local pack_ok=false
- if run_with_timeout "$DESKTOP_BUILD_TIMEOUT" _desktop_pack "$desktop_dir"; then
- pack_ok=true
- else
- local purged=""
- local restored=false
- if ! _electron_dist_ok "$INSTALL_DIR"; then
- purged="$(clear_electron_build_cache "$desktop_dir")"
- if _restore_electron_dist "$INSTALL_DIR"; then restored=true; fi
- fi
- if [ "$restored" = true ]; then
- log_warn "Desktop build failed; refreshed the Electron download and retrying once..."
- if run_with_timeout "$DESKTOP_BUILD_TIMEOUT" _desktop_pack "$desktop_dir"; then
- pack_ok=true
- fi
- fi
- fi
-
- # (c) GitHub blocked → mirror fallback (#47266).
- if [ "$pack_ok" = false ] && [ -z "${ELECTRON_MIRROR:-}" ]; then
- log_warn "Desktop build still failing — the Electron download from GitHub looks blocked."
- log_warn "Re-downloading Electron via a public mirror ($DESKTOP_ELECTRON_FALLBACK_MIRROR), then rebuilding..."
- log_warn " (set ELECTRON_MIRROR yourself to use a different/trusted mirror)"
- _electron_dist_ok "$INSTALL_DIR" || _restore_electron_dist "$INSTALL_DIR" "$DESKTOP_ELECTRON_FALLBACK_MIRROR" || true
- if run_with_timeout "$DESKTOP_BUILD_TIMEOUT" _desktop_pack "$desktop_dir" "$DESKTOP_ELECTRON_FALLBACK_MIRROR"; then
- pack_ok=true
- fi
- fi
-
- if [ "$pack_ok" = false ]; then
- log_error "Desktop app build failed"
- # If the log shows repeated "retrying" lines fetching the Electron zip,
- # the binary download is blocked/throttled (firewall, proxy, region) and
- # the mirror fallback above also couldn't reach a host. Try a mirror you
- # trust and rebuild (@electron/get honors ELECTRON_MIRROR):
- log_info "If the log shows Electron download retries, rebuild via a reachable mirror:"
- log_info " ELECTRON_MIRROR=<mirror-base-url> \\"
- log_info " bash -c 'cd \"$desktop_dir\" && CSC_IDENTITY_AUTO_DISCOVERY=false npm run pack'"
- log_info "Otherwise build manually: cd $desktop_dir && npm run pack"
- return 1
- fi
-
- local app=""
- if [ "$OS" = "linux" ]; then
- if [ -x "$desktop_dir/release/linux-unpacked/Hermes" ]; then
- app="$desktop_dir/release/linux-unpacked/Hermes"
- elif [ -x "$desktop_dir/release/linux-unpacked/hermes" ]; then
- app="$desktop_dir/release/linux-unpacked/hermes"
- fi
- else
- local cand
- for cand in \
- "$desktop_dir/release/mac-arm64/Hermes.app" \
- "$desktop_dir/release/mac/Hermes.app"; do
- if [ -d "$cand" ]; then
- app="$cand"
- break
- fi
- done
- fi
- if [ -z "$app" ]; then
- log_error "Desktop build completed but no app was found under $desktop_dir/release/"
- return 1
- fi
- log_success "Desktop app built: $app"
-
- # Linux: Electron's chrome-sandbox helper needs root:root 4755 or the
- # sandboxed renderer will abort on startup. Check the file is a regular
- # file (not a symlink) before chown/chmod so we don't follow an
- # attacker-controlled link to an arbitrary path.
- if [ "$OS" = "linux" ]; then
- local sandbox="$desktop_dir/release/linux-unpacked/chrome-sandbox"
- if [ -f "$sandbox" ] && [ ! -L "$sandbox" ]; then
- if [ "$(id -u)" -eq 0 ]; then
- chown root:root "$sandbox" && chmod 4755 "$sandbox" || {
- log_error "Cannot configure Electron sandbox helper: $sandbox"
- return 1
- }
- elif command -v sudo >/dev/null 2>&1; then
- sudo chown root:root "$sandbox" && sudo chmod 4755 "$sandbox" || {
- log_error "Cannot configure Electron sandbox helper (sudo failed): $sandbox"
- return 1
- }
- else
- log_error "Cannot configure Electron sandbox helper without sudo: $sandbox"
- return 1
- fi
- fi
- fi
-
- # macOS: route through the same config-aware signing fixup as
- # `hermes desktop`, so install/repair and self-update agree about the app's
- # identity. The fixup preserves the Electron entitlement plists and signs
- # with a stable Designated Requirement (configured keychain identity, else
- # identifier-pinned ad-hoc), so macOS TCC grants — Full Disk Access,
- # Desktop/Downloads/Documents, Accessibility, microphone — survive the
- # rebuild instead of resetting on every update. The shell's
- # publisher-signing decision governed the build and is passed explicitly so
- # importing Python cannot reverse it by loading HERMES_HOME/.env. If the
- # helper is unavailable or fails, branch into the historical quarantine
- # strip + deep ad-hoc repair so a broken venv never leaves the bundle
- # unsigned/unlaunchable.
- if [ "$OS" = "macos" ] && [ -z "${CSC_LINK:-}" ] && [ -z "${APPLE_SIGNING_IDENTITY:-}" ] && command -v codesign >/dev/null 2>&1; then
- local config_python="$INSTALL_DIR/venv/bin/python"
- local fixup_ok=""
- if [ -x "$config_python" ]; then
- if HERMES_HOME="$HERMES_HOME" "$config_python" - "$desktop_dir" <<'PYEOF'
-import sys
-from pathlib import Path
-from hermes_cli.main import _desktop_macos_relaunchable_fixup
-ok = _desktop_macos_relaunchable_fixup(
- Path(sys.argv[1]), publisher_signing_configured=False
-)
-sys.exit(0 if ok else 1)
-PYEOF
- then
- fixup_ok=1
- else
- log_warn "Config-aware macOS signing fixup failed; applying the historical ad-hoc fallback."
- fi
- fi
- if [ -z "$fixup_ok" ]; then
- xattr -cr "$app" 2>/dev/null || true
- codesign --force --deep --sign - "$app" >/dev/null 2>&1 || true
- fi
- fi
-
- # `npm install` + `npm run pack` rewrite lockfiles; restore them so the
- # checkout stays clean for the next `hermes update`.
- restore_dirty_lockfiles "$INSTALL_DIR"
-}
-
-# Each --stage runs in its own process, so (unlike the monolithic main() where
-# clone_repo cd's once and later steps inherit it) a stage that operates on the
-# checkout must cd into it explicitly. Without this, install_deps/setup_path run
-# from the desktop app's cwd and resolve `.` / the venv against the wrong tree.
-require_install_dir() {
- if [ -z "$INSTALL_DIR" ] || [ ! -d "$INSTALL_DIR" ]; then
- log_error "Install directory not found: ${INSTALL_DIR:-<unset>}"
- log_info "The 'repository' stage must run before this one."
- return 1
- fi
- cd "$INSTALL_DIR"
-}
-
-# Desktop bootstrap stage protocol. Mirrors the Windows install.ps1 surface
-# closely enough for the Electron bootstrap runner to show structured progress.
-run_stage_body() {
- local stage="$1"
-
- case "$stage" in
- prerequisites)
- print_banner
- detect_os
- resolve_install_layout
- install_uv
- check_python
- check_git
- check_node
- check_cxx_compiler
- check_network_prerequisites
- install_system_packages
- ;;
- repository)
- detect_os
- resolve_install_layout
- check_git
- clone_repo
- ;;
- venv)
- detect_os
- resolve_install_layout
- require_install_dir
- install_uv
- check_python
- setup_venv
- ;;
- python-deps)
- detect_os
- resolve_install_layout
- require_install_dir
- install_uv
- check_python
- install_deps
- ;;
- node-deps)
- detect_os
- resolve_install_layout
- require_install_dir
- check_node
- install_node_deps || return
- install_uv
- install_browser_use_cli
- install_computer_use_driver
- ;;
- path)
- detect_os
- resolve_install_layout
- require_install_dir
- setup_path
- ;;
- config)
- detect_os
- resolve_install_layout
- require_install_dir
- copy_config_templates
- ;;
- setup)
- detect_os
- resolve_install_layout
- require_install_dir
- run_setup_wizard
- ;;
- gateway)
- detect_os
- resolve_install_layout
- require_install_dir
- maybe_start_gateway
- ;;
- desktop)
- detect_os
- resolve_install_layout
- require_install_dir
- # Each stage runs in its own process, so the Hermes-managed Node
- # provisioned during prerequisites/node-deps (at $HERMES_HOME/node/bin)
- # isn't on PATH here. check_node re-adds it (or installs if missing)
- # so install_desktop can find npm instead of silently skipping.
- check_node
- install_desktop_voice_deps
- install_desktop
- ;;
- complete)
- detect_os
- resolve_install_layout
- print_success
- write_bootstrap_marker
- # Code-scoped stamp: write next to the install tree, not into
- # $HERMES_HOME. $HERMES_HOME is a shared data dir (it can be
- # bind-mounted into a Docker gateway too), so a stamp there gets
- # clobbered by the container's 'docker' stamp and wrongly blocks
- # 'hermes update' on this host install. See detect_install_method().
- echo "git" > "$INSTALL_DIR/.install_method"
- ;;
- *)
- log_error "Unknown stage: $stage"
- return 2
- ;;
- esac
-}
-
-run_stage_protocol() {
- local stage="$1"
- if [ -z "$stage" ]; then
- log_error "--stage requires a stage name"
- if [ "$JSON_OUTPUT" = true ]; then
- emit_stage_json "" false false "missing stage name"
- fi
- return 2
- fi
-
- if [ "$NON_INTERACTIVE" = true ] && stage_needs_user_input "$stage"; then
- log_info "Skipping $stage (non-interactive bootstrap)"
- if [ "$JSON_OUTPUT" = true ]; then
- emit_stage_json "$stage" true true
- fi
- return 0
- fi
-
- # Run the stage body in a subshell so a stage helper that calls `exit 1`
- # on failure (clone_repo, install_deps, etc. were written for the monolithic
- # flow) only exits the subshell — the parent still reaches the JSON result
- # frame below. Without this, a failed --stage would terminate the process
- # before emitting the frame and the Rust/Electron parser would see "no
- # result frame" instead of a clean {ok:false} contract response.
- set +e
- ( run_stage_body "$stage" )
- local code=$?
- set -e
-
- if [ "$JSON_OUTPUT" = true ]; then
- if [ "$code" -eq 0 ]; then
- emit_stage_json "$stage" true false
- else
- emit_stage_json "$stage" false false "exit code $code"
- fi
- fi
- return "$code"
-}
-
-# ============================================================================
-# Main
-# ============================================================================
-
-main() {
- print_banner
-
- detect_os
- resolve_install_layout
- install_uv
- check_python
- check_git
- check_node
- check_cxx_compiler
- check_network_prerequisites
- install_system_packages
-
- clone_repo
- setup_venv
- install_deps
- install_node_deps || return
- install_browser_use_cli
- install_computer_use_driver
- setup_path
- copy_config_templates
- run_setup_wizard
- maybe_start_gateway
-
- if [ "$INCLUDE_DESKTOP" = true ]; then
- install_desktop_voice_deps
- install_desktop
- fi
-
- print_success
-
- write_bootstrap_marker
-
- # Code-scoped stamp: write next to the install tree, not into $HERMES_HOME.
- # $HERMES_HOME is a shared data dir (it can be bind-mounted into a Docker
- # gateway too), so a stamp there gets clobbered by the container's 'docker'
- # stamp and wrongly blocks 'hermes update' on this host install.
- # See detect_install_method().
- echo "git" > "$INSTALL_DIR/.install_method"
-}
-
-if [ "$MANIFEST_MODE" = true ]; then
- emit_manifest
-elif [ -n "$STAGE_NAME" ]; then
- run_stage_protocol "$STAGE_NAME"
-elif [ -n "$ENSURE_DEPS" ]; then
- ensure_mode
-else
- main
-fi
+# No --stage: run the whole ladder.
+for s in prerequisites repository venv python-deps node-deps path config setup gateway complete; do
+ run_stage "$s"
+done
diff --cc tests/hermes_cli/test_boot_preset_staleness.py
index 00000000000,fd7256c8bfc..1266d422b74
mode 000000,100644..100644
--- a/tests/hermes_cli/test_boot_preset_staleness.py
+++ b/tests/hermes_cli/test_boot_preset_staleness.py
@@@ -1,0 -1,126 +1,133 @@@
+ """Every staged model must launch with a policy decision, never stock fit.
+
+ The managed server autoloads any GGUF in its models dir; a model missing
+ from the preset INI loads with llama-server defaults (f16 KV at max
+ context, no placement) — on Windows/WDDM that silently demotes VRAM and
+ decodes at a crawl. Boot must therefore refuse to adopt a running server
+ whose presets predate the staged set."""
+
+ from __future__ import annotations
+
+ import pytest
+
+
+ @pytest.fixture
+ def hermes_home(tmp_path, monkeypatch):
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ return home
+
+
+ def _stage(home, name):
+ mdir = home / "models"
+ mdir.mkdir(parents=True, exist_ok=True)
+ (mdir / f"{name}.gguf").write_bytes(b"GGUF" + b"\x00" * 32)
+
+
+ def _write_presets(home, *model_ids):
+ pdir = home / "runtimes" / "llamacpp"
+ pdir.mkdir(parents=True, exist_ok=True)
+ body = "\n".join(f"[{m}]\nctx-size = 65536\n" for m in model_ids)
+ (pdir / "presets.ini").write_text(body, encoding="utf-8")
+
+
+ def test_presets_stale_when_a_staged_model_has_no_section(hermes_home):
+ from hermes_cli.local_runtime.bootstrap import _presets_stale
+
+ _stage(hermes_home, "model-a")
+ _stage(hermes_home, "model-b")
+ _write_presets(hermes_home, "model-a")
+ assert _presets_stale() is True
+
+
+ def test_presets_current_when_every_staged_model_is_covered(hermes_home):
+ from hermes_cli.local_runtime.bootstrap import _presets_stale
+
+ _stage(hermes_home, "model-a")
+ _write_presets(hermes_home, "model-a")
+ assert _presets_stale() is False
+
+
+ def test_no_models_is_never_stale(hermes_home):
+ from hermes_cli.local_runtime.bootstrap import _presets_stale
+
+ _write_presets(hermes_home, "model-a")
+ assert _presets_stale() is False
+
+
+ def test_boot_replaces_incumbent_with_stale_presets(hermes_home, monkeypatch):
+ """ensure_local_runtime must not adopt a running server whose presets
+ miss a staged model — it stops it and boots fresh (boot itself is
+ stubbed; the contract under test is the adopt/replace decision)."""
+ import hermes_cli.local_runtime.bootstrap as boot
+
+ _stage(hermes_home, "model-a")
+ _stage(hermes_home, "model-b")
+ _write_presets(hermes_home, "model-a")
+
++ # An installed engine so boot proceeds to server_binary().
++ from pm import paths
++ from pm.lock import Facts
++
++ store = paths.store_root()
++ entry = "llamacpp-cpu-10362-win32-x64"
++ (store / entry).mkdir(parents=True, exist_ok=True)
++ Facts(store / "facts.json").record("llamacpp-cpu", "10362", entry, {}, store)
++
+ stopped = {}
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.endpoint._state_endpoint",
+ lambda: {"base_url": "http://127.0.0.1:18434/v1", "pid": 12345})
+ monkeypatch.setattr(boot, "_stop_state_server",
+ lambda state: stopped.setdefault("pid", state["pid"]))
+
- sentinel = object()
++ class _BootReached(Exception):
++ pass
+
+ def fake_boot(*a, **k):
+ raise _BootReached()
+
- class _BootReached(Exception):
- pass
-
+ # Fail fast once boot proper begins — reaching it IS the assertion.
+ monkeypatch.setattr(
- "hermes_cli.local_runtime.binaries.ensure_runtime_installed", fake_boot)
++ "hermes_cli.local_runtime.binaries.server_binary", fake_boot)
+
+ result = boot.ensure_local_runtime({"local_runtime": {"enabled": True}})
+ assert stopped.get("pid") == 12345, "stale incumbent was not stopped"
+ # Boot proceeded past adoption (our fake raised inside the try block,
+ # which ensure_local_runtime swallows into a None return).
- assert result is None or result is sentinel
++ assert result is None
+
+
+ def test_refresh_bounces_an_adopted_server(hermes_home, monkeypatch):
+ """refresh_local_runtime with no in-process supervisor but a running
+ state-file server (the post-restart shape) must stop that server and
+ boot fresh — NOT silently no-op. Regression: the no-op meant every
+ download/delete after a backend restart left the router serving a
+ stale model catalog, and picking the new model failed with
+ 'not found in this provider's model listing'."""
+ import hermes_cli.local_runtime.bootstrap as boot
+
+ stopped = {}
+ monkeypatch.setattr(boot, "_SUPERVISOR", None)
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.endpoint._state_endpoint",
+ lambda: {"base_url": "http://127.0.0.1:18434/v1", "pid": 4242})
+ monkeypatch.setattr(boot, "_stop_state_server",
+ lambda state: stopped.setdefault("pid", state["pid"]))
+ booted = {}
+ monkeypatch.setattr(boot, "ensure_local_runtime",
+ lambda cfg, force=False: booted.setdefault("force", force) or object())
+
+ assert boot.refresh_local_runtime() is True
+ assert stopped.get("pid") == 4242, "adopted server was not stopped"
+ assert booted.get("force") is True, "fresh boot did not follow the stop"
+
+
+ def test_refresh_no_server_anywhere_is_a_noop(hermes_home, monkeypatch):
+ import hermes_cli.local_runtime.bootstrap as boot
+
+ monkeypatch.setattr(boot, "_SUPERVISOR", None)
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.endpoint._state_endpoint", lambda: None)
+ assert boot.refresh_local_runtime() is False
diff --cc tests/hermes_cli/test_catalog_json.py
index 00000000000,9aa8973b109..b4f611f339f
mode 000000,100644..100644
--- a/tests/hermes_cli/test_catalog_json.py
+++ b/tests/hermes_cli/test_catalog_json.py
@@@ -1,0 -1,118 +1,118 @@@
+ """The pulled catalog: packaged JSON is the offline truth, a GitHub fetch
+ swaps entries in memory only, and min_engine gates day-0 models.
+
+ Nothing here touches disk beyond the packaged file — the design constraint
+ is that a git checkout must never see a dirty tracked catalog.json."""
+
+ from __future__ import annotations
+
+ import dataclasses
+ import io
+ import json
+ import urllib.request
+
+ import pytest
+
+ import hermes_cli.local_runtime.catalog as cat
+
+
+ @pytest.fixture(autouse=True)
+ def _reset_refresh_state(monkeypatch):
+ """Each test starts outside the TTL window with the packaged catalog."""
+ monkeypatch.setattr(cat, "_last_refresh_attempt", 0.0)
+ packaged = cat._packaged_catalog()
+ monkeypatch.setattr(cat, "CATALOG", packaged)
+ yield
+
+
+ def _doc_from(entries):
+ """A fetchable catalog document built by mutating the packaged JSON."""
+ from importlib.resources import files
+
+ doc = json.loads(files("hermes_cli.local_runtime")
+ .joinpath("catalog.json").read_text(encoding="utf-8"))
+ doc["models"] = entries(doc["models"])
+ return doc
+
+
+ def _fetch_returns(monkeypatch, doc):
+ body = json.dumps(doc).encode()
+
+ class R(io.BytesIO):
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *a):
+ return False
+
+ monkeypatch.setattr(urllib.request, "urlopen",
+ lambda *a, **k: R(body))
+
+
+ def test_packaged_json_round_trips_the_catalog():
+ """The packaged JSON must produce a complete, selection-ready catalog:
+ every entry carries estimator inputs and at least one variant, and the
+ known invariants (best-first ordering, Q4 floor) hold — the same
+ contract the literals obeyed."""
+ assert len(cat.CATALOG) >= 4
+ for e in cat.CATALOG:
+ assert e.variants and e.n_ctx_train > 0 and e.per_layer_f16 >= 0
+ sizes = [v.size_bytes for v in e.variants]
+ assert sizes == sorted(sizes, reverse=True), f"{e.id} not best-first"
+
+
+ def test_refresh_swaps_in_memory_only(monkeypatch, tmp_path):
+ """A fetched catalog replaces CATALOG in memory; the packaged file on
+ disk is untouched (checkout stays clean)."""
+ from importlib.resources import files
+
+ packaged_path = files("hermes_cli.local_runtime").joinpath("catalog.json")
+ before = packaged_path.read_text(encoding="utf-8")
+
+ def add_day0(models):
+ day0 = dict(models[0])
+ day0.update(id="day0-model", display_name="Day 0",
+ description="new", min_engine="b99999")
+ return models + [day0]
+
+ _fetch_returns(monkeypatch, _doc_from(add_day0))
+ assert cat.refresh_catalog(force=True) is True
+ assert "day0-model" in {e.id for e in cat.CATALOG}
+ assert cat.catalog_by_id()["day0-model"].min_engine == "b99999"
+ assert packaged_path.read_text(encoding="utf-8") == before
+
+
+ def test_refresh_failure_keeps_current_catalog(monkeypatch):
+ def boom(*a, **k):
+ raise OSError("offline")
+
+ monkeypatch.setattr(urllib.request, "urlopen", boom)
+ ids_before = [e.id for e in cat.CATALOG]
+ assert cat.refresh_catalog(force=True) is False
+ assert [e.id for e in cat.CATALOG] == ids_before
+
+
+ def test_refresh_rejects_wrong_schema(monkeypatch):
+ doc = _doc_from(lambda m: m)
+ doc["schema_version"] = 2
+ _fetch_returns(monkeypatch, doc)
+ ids_before = [e.id for e in cat.CATALOG]
+ assert cat.refresh_catalog(force=True) is False
+ assert [e.id for e in cat.CATALOG] == ids_before
+
+
+ def test_loader_ignores_unknown_fields():
+ doc = _doc_from(lambda m: m)
+ doc["models"][0]["future_field"] = {"anything": True}
+ entries = cat._load_catalog(doc)
+ assert entries[0].id == doc["models"][0]["id"]
+
+
-def test_min_engine_gate(monkeypatch):
++def test_min_engine_gate():
++ from hermes_cli.local_runtime.binaries import engine_version
+ from hermes_cli.web_routers.local_models import _engine_too_old
+
- monkeypatch.setattr("hermes_cli.local_runtime.binaries.installed_tags",
- lambda: ["b10362"])
++ pinned = int(engine_version().lstrip("b"))
+ assert _engine_too_old("") is False, "no requirement, no gate"
- assert _engine_too_old("b10000") is False, "installed engine suffices"
- assert _engine_too_old("b10363") is True, "newer requirement gates"
++ assert _engine_too_old(f"b{pinned}") is False, "current pin suffices"
++ assert _engine_too_old(f"b{pinned + 1}") is True, "newer requirement gates"
diff --cc tests/hermes_cli/test_local_models_routes.py
index 00000000000,6ee98aae1ea..99a66fb364c
mode 000000,100644..100644
--- a/tests/hermes_cli/test_local_models_routes.py
+++ b/tests/hermes_cli/test_local_models_routes.py
@@@ -1,0 -1,293 +1,439 @@@
+ """Contract tests for the local-models dashboard routes (Rollout 4).
+
+ Real FastAPI TestClient against the real router; the runtime pieces
+ underneath are exercised against temp HERMES_HOME (autouse fixture). Network
+ downloads are stubbed at the urllib boundary — never live."""
+
+ from __future__ import annotations
+
+ import io
+ import json
+ import time
+ from pathlib import Path
+
+ import pytest
+ from fastapi.testclient import TestClient
+
+
+ @pytest.fixture
+ def client(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ from hermes_cli import web_server
+
+ test_client = TestClient(web_server.app)
+ # Same auth pattern as the git-route tests: present the session token.
+ test_client.headers[web_server._SESSION_HEADER_NAME] = web_server._SESSION_TOKEN
+ return test_client
+
+
+ def test_local_models_routes_require_auth(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ from hermes_cli import web_server
+
+ unauth = TestClient(web_server.app)
+ assert unauth.get("/api/local-models/status").status_code == 401
+
+
+ def _write_fake_gguf(path: Path, size: int = 1024) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(b"GGUF" + b"\x00" * size)
+
+
+ # ── status ───────────────────────────────────────────────────
+
+
+ def test_status_shape_and_defaults(client):
+ r = client.get("/api/local-models/status")
+ assert r.status_code == 200
+ data = r.json()
+ # Contract: every key the pane's first paint needs, present and typed.
+ assert isinstance(data["enabled"], bool)
+ assert isinstance(data["tag"], str) and data["tag"].startswith("b")
+ assert isinstance(data["runtime_installed"], bool)
+ assert isinstance(data["server_running"], bool)
+ assert isinstance(data["models"], list)
+
+
+ def test_status_lists_staged_models_with_labels(client, tmp_path):
+ from hermes_cli.local_runtime.bootstrap import models_dir
+
+ _write_fake_gguf(models_dir() / "Some-Model.gguf", size=2048)
+ data = client.get("/api/local-models/status").json()
+ ids = [m["id"] for m in data["models"]]
+ assert "Some-Model" in ids
+ row = data["models"][ids.index("Some-Model")]
+ assert row["size_bytes"] > 0
+ assert row["size_label"].endswith("GB")
+
+
+ # ── hardware ─────────────────────────────────────────────────
+
+
+ def test_hardware_plain_facts(client):
+ data = client.get("/api/local-models/hardware").json()
+ assert isinstance(data["uma"], bool)
+ assert data["ram_total_bytes"] > 0
+ assert data["vram_total_bytes"] >= 0
+ # GPU fields are None-able (non-NVIDIA machines) but must exist.
+ assert "gpu_name" in data and "gpu_util_percent" in data and "vram_used_bytes" in data
+
+
+ # ── catalog ──────────────────────────────────────────────────
+
+
+ def test_catalog_prices_every_entry_for_this_machine(client):
+ data = client.get("/api/local-models/catalog").json()
+ assert len(data["models"]) >= 3
+ for row in data["models"]:
+ # The three user questions, answered on every row:
+ assert row["size_label"].endswith("GB") # how big
+ assert isinstance(row["fits"], bool) # will it fit
+ assert row["fit_summary"] # what shape
+ if row["fits"]:
+ assert row["start_window"] >= 1
+ assert row["start_window_label"].endswith("K")
+ else:
+ assert "memory" in row["fit_summary"].lower()
+ assert isinstance(row["downloaded"], bool)
+
+
+ def test_catalog_never_hides_unaffordable_models(client, monkeypatch):
+ """Unaffordable entries stay visible with a plain reason — hiding them
+ is how users conclude the feature is broken."""
+ from hermes_cli.local_runtime.estimator import HardwareBudget
+
+ tiny = HardwareBudget(usable_vram_bytes=1 << 30, total_device_bytes=1 << 30,
+ ram_available_bytes=1 << 30)
+ monkeypatch.setattr("hermes_cli.local_runtime.hardware.probe_budget",
+ lambda **kw: tiny)
+ data = client.get("/api/local-models/catalog").json()
+ from hermes_cli.local_runtime.catalog import CATALOG
+
+ assert len(data["models"]) == len(CATALOG)
+ refused = [m for m in data["models"] if not m["fits"]]
+ assert refused, "a 1 GiB machine must refuse the 20 GB models"
+ for row in refused:
+ assert row["fit_detail"] or row["fit_summary"]
+
+
+ # ── downloads ────────────────────────────────────────────────
+
+
++class _FakeRangeOpener:
++ """Stands in for pm.downloader._OPENER: serves `body` with honest Range
++ support (the downloader probes bytes=0-0 and then fetches 8-way ranges)."""
++
++ def __init__(self, body: bytes, content_length: int | None = None):
++ self._body = body
++ self._length = content_length if content_length is not None else len(body)
++
++ def open(self, req, timeout=None):
++ parent = self
++
++ class _Resp(io.BytesIO):
++ status = 200
++ headers = {"Content-Length": str(parent._length)}
++
++ def __enter__(self):
++ return self
++
++ def __exit__(self, *a):
++ return False
++
++ rng = req.headers.get("Range") if req.headers else None
++ if rng and rng.startswith("bytes="):
++ lo_hi = rng[len("bytes="):]
++ if lo_hi == "0-0":
++ # probe: 206 with full Content-Range so range support is detected
++ probe = _Resp(b"")
++ probe.status = 206
++ probe.headers = {
++ "Content-Range": f"bytes 0-0/{parent._length}",
++ "Content-Length": "1",
++ }
++ return probe
++ lo, hi = (int(x) for x in lo_hi.split("-"))
++ part = parent._body[lo:hi + 1]
++ resp = _Resp(part)
++ resp.headers = {
++ "Content-Range": f"bytes {lo}-{hi}/{parent._length}",
++ "Content-Length": str(len(part)),
++ }
++ return resp
++ return _Resp(parent._body)
++
++
++
++
+ def test_download_unknown_model_404s(client):
+ r = client.post("/api/local-models/download", json={"model_id": "nope"})
+ assert r.status_code == 404
+
+
+ def test_download_short_of_server_length_errors_and_cleans_up(client, monkeypatch):
+ """Catalog sizes are advisory (upstream re-uploads may make them
+ stale — a mismatch against the CATALOG must not fail a download).
+ The server's own declared length is the only completeness check:
+ fewer bytes than the server promised means a dropped connection, so
+ the job errors and nothing is staged."""
+
- class FakeResponse(io.BytesIO):
- # Body is 17 bytes; the server promises 32 — a truncated stream.
- headers = {"Content-Length": "32"}
-
- def __enter__(self):
- return self
-
- def __exit__(self, *a):
- return False
-
- monkeypatch.setattr("urllib.request.urlopen",
- lambda *a, **k: FakeResponse(b"not the real body"))
++ # Body is 17 bytes; the server promises 32 — a truncated stream.
++ monkeypatch.setattr(
++ "pm.downloader._OPENER",
++ _FakeRangeOpener(b"not the real body", content_length=32))
+
+ # Pin a generous budget: variant selection prices against the machine
+ # running the test, and a GPU-less CI runner honestly refuses every
+ # build (409) — this test is about the download path, not selection.
+ from hermes_cli.local_runtime.estimator import HardwareBudget
+
+ budget = HardwareBudget(usable_vram_bytes=64 << 30,
+ total_device_bytes=64 << 30,
+ ram_available_bytes=64 << 30)
+ monkeypatch.setattr("hermes_cli.local_runtime.hardware.probe_budget",
+ lambda **kw: budget)
+
+ from hermes_cli.local_runtime.catalog import CATALOG
+
+ entry_id = CATALOG[0].id
+ r = client.post("/api/local-models/download", json={"model_id": entry_id})
+ assert r.status_code == 200
+ job_id = r.json()["job_id"]
+ assert job_id
+
+ deadline = time.time() + 10
+ status = None
+ while time.time() < deadline:
+ status = client.get(f"/api/local-models/jobs/{job_id}").json()
+ if status["status"] in ("done", "error"):
+ break
+ time.sleep(0.05)
+ assert status is not None and status["status"] == "error"
+ assert "bytes" in status["error"].lower()
+
+ from hermes_cli.local_runtime.bootstrap import models_dir
+
+ assert not (models_dir() / f"{entry_id}.gguf").exists()
+ assert not (models_dir() / f"{entry_id}.part").exists()
+
+
+ def test_download_already_downloaded_short_circuits(client, monkeypatch):
+ from hermes_cli.local_runtime.bootstrap import models_dir
+ from hermes_cli.local_runtime.catalog import CATALOG, select_variant
+ from hermes_cli.local_runtime.estimator import HardwareBudget
+
+ # Pin the budget so the selected variant is deterministic in the test.
+ budget = HardwareBudget(usable_vram_bytes=64 << 30, total_device_bytes=64 << 30,
+ ram_available_bytes=64 << 30)
+ monkeypatch.setattr("hermes_cli.local_runtime.hardware.probe_budget",
+ lambda **kw: budget)
+ choice = select_variant(CATALOG[0], budget)
+ assert choice is not None
+ _write_fake_gguf(models_dir() / choice.variant.files[0].local_name)
+ r = client.post("/api/local-models/download", json={"model_id": CATALOG[0].id})
+ assert r.status_code == 200
+ assert r.json()["already_downloaded"] is True
+
+
+ def test_delete_model(client):
+ from hermes_cli.local_runtime.bootstrap import models_dir
+
+ _write_fake_gguf(models_dir() / "Doomed.gguf")
+ assert client.delete("/api/local-models/models/Doomed").status_code == 200
+ assert not (models_dir() / "Doomed.gguf").exists()
+ assert client.delete("/api/local-models/models/Doomed").status_code == 404
+
+
+ # ── runtime install ──────────────────────────────────────────
+
+
+ def test_runtime_install_rejects_impossible_combo(client, monkeypatch):
+ """Impossible platform/backend combos fail the POST itself with the
+ resolver's honest message — not a background job that dies silently.
+ (win-arm64-vulkan; the old cuda case became real upstream at ~b1036x.)"""
+ monkeypatch.setattr(
- "hermes_cli.local_runtime.binaries._host_os_arch", lambda: ("win", "arm64"))
++ "pm.store.current_target", lambda: "win32-arm64")
+ r = client.post("/api/local-models/runtime/install", json={"backend": "vulkan"})
+ assert r.status_code == 400
+ assert "arm64" in r.json()["detail"]
+
+
+ def test_job_poll_unknown_404s(client):
+ assert client.get("/api/local-models/jobs/deadbeef").status_code == 404
+
+
+ def test_eject_without_supervisor_is_not_a_500(client, monkeypatch):
+ """Eject on an ADOPTED server (no in-process supervisor — the shape
+ every backend restart produces, since boot adopts the running server
+ via the state file) must route through the persisted endpoint, not
+ crash. Regression: _state_endpoint was only imported inside the
+ status route, so eject raised NameError -> 500 for every adopted-
+ server session."""
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.bootstrap.get_supervisor", lambda: None)
+ # No running server either: the route must answer 409 (no server),
+ # never a NameError 500.
+ monkeypatch.setattr(
+ "hermes_cli.web_routers.local_models._state_endpoint", lambda: None)
+ r = client.post("/api/local-models/eject", json={"model_id": "anything"})
+ assert r.status_code == 409, (r.status_code, r.text)
+
+
+ def test_download_tolerates_stale_catalog_size(client, monkeypatch):
+ """Upstream re-uploads make catalog sizes stale; a download whose
+ delivered bytes are self-consistent with the SERVER's declared length
+ must succeed even when the catalog said something else. (This is the
+ tolerance the sha removal was for — being out of date must not break
+ downloads.)"""
+
+ body = b"x" * 48 # server-consistent: Content-Length == body length
+
- class FakeResponse(io.BytesIO):
- headers = {"Content-Length": str(len(body))}
-
- def __enter__(self):
- return self
-
- def __exit__(self, *a):
- return False
-
- monkeypatch.setattr("urllib.request.urlopen",
- lambda *a, **k: FakeResponse(body))
++ monkeypatch.setattr("pm.downloader._OPENER", _FakeRangeOpener(body))
+
+ from hermes_cli.local_runtime.estimator import HardwareBudget
+
+ budget = HardwareBudget(usable_vram_bytes=64 << 30,
+ total_device_bytes=64 << 30,
+ ram_available_bytes=64 << 30)
+ monkeypatch.setattr("hermes_cli.local_runtime.hardware.probe_budget",
+ lambda **kw: budget)
+ # Keep the post-download server bounce out of this unit.
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.bootstrap.refresh_local_runtime",
+ lambda: False)
+
+ from hermes_cli.local_runtime.catalog import CATALOG
+
+ # Catalog size for this entry is in the tens of GB — wildly stale
+ # versus our 48-byte body. The download must still land.
+ entry_id = CATALOG[0].id
+ r = client.post("/api/local-models/download", json={"model_id": entry_id})
+ assert r.status_code == 200
+ job_id = r.json()["job_id"]
+
+ deadline = time.time() + 10
+ status = None
+ while time.time() < deadline:
+ status = client.get(f"/api/local-models/jobs/{job_id}").json()
+ if status["status"] in ("done", "error"):
+ break
+ time.sleep(0.05)
+ assert status is not None and status["status"] == "done", status.get("error")
++
++
++# ── pause / resume ───────────────────────────────────────────
++
++
++def test_download_pause_and_resume_unknown_404(client):
++ assert client.post("/api/local-models/download/pause",
++ json={"job_id": "deadbeef"}).status_code == 404
++ assert client.post("/api/local-models/download/resume",
++ json={"job_id": "deadbeef"}).status_code == 404
++
++
++def test_download_finished_job_releases_handles(client, monkeypatch):
++ """A finished download drops its live download + resume handles, so the
++ job dict stays JSON-serializable and nothing lingers to pause/resume."""
++ body = b"x" * 48
++
++ monkeypatch.setattr("pm.downloader._OPENER", _FakeRangeOpener(body))
++ from hermes_cli.local_runtime.estimator import HardwareBudget
++
++ budget = HardwareBudget(usable_vram_bytes=64 << 30,
++ total_device_bytes=64 << 30,
++ ram_available_bytes=64 << 30)
++ monkeypatch.setattr("hermes_cli.local_runtime.hardware.probe_budget",
++ lambda **kw: budget)
++ monkeypatch.setattr(
++ "hermes_cli.local_runtime.bootstrap.refresh_local_runtime",
++ lambda: False)
++ from hermes_cli.local_runtime.catalog import CATALOG
++
++ r = client.post("/api/local-models/download", json={"model_id": CATALOG[0].id})
++ job_id = r.json()["job_id"]
++ deadline = time.time() + 10
++ status = None
++ while time.time() < deadline:
++ status = client.get(f"/api/local-models/jobs/{job_id}").json()
++ if status["status"] in ("done", "error"):
++ break
++ time.sleep(0.05)
++ assert status is not None and status["status"] == "done"
++
++ from hermes_cli.web_routers import local_models as lm
++
++ assert job_id not in lm._RUNNING
++
++
++def test_download_pause_reaches_paused_status(client, monkeypatch):
++ """A running download can be paused; the job lands in a 'paused' state
++ (partials preserved for resume) instead of erroring."""
++ import threading
++
++ gate = threading.Event()
++
++ class _BlockingOpener:
++ """Stands in for pm.downloader._OPENER: the probe answers honestly
++ (1 MiB, range-supported) and every body read blocks on the gate, so
++ the worker is mid-download when the test pauses it."""
++
++ def open(self, req, timeout=None):
++ parent = self
++
++ class _Resp:
++ status = 206
++ headers = {"Content-Range": "bytes 0-0/1048576",
++ "Content-Length": "1"}
++
++ def __enter__(self):
++ return self
++
++ def __exit__(self, *a):
++ return False
++
++ def read(self, size=-1):
++ gate.wait(timeout=15) # hold the worker until let go
++ return b""
++
++ rng = req.headers.get("Range") if req.headers else None
++ if rng and rng.startswith("bytes=") and rng != "bytes=0-0":
++ # body range: answer the probe shape with full length so the
++ # worker blocks inside read()
++ _Resp.headers = {"Content-Range": "bytes 0-1048575/1048576",
++ "Content-Length": "1048576"}
++ return _Resp()
++
++ monkeypatch.setattr("pm.downloader._OPENER", _BlockingOpener())
++ from hermes_cli.local_runtime.catalog import CATALOG
++ from hermes_cli.local_runtime.estimator import HardwareBudget
++
++ budget = HardwareBudget(usable_vram_bytes=64 << 30,
++ total_device_bytes=64 << 30,
++ ram_available_bytes=64 << 30)
++ monkeypatch.setattr("hermes_cli.local_runtime.hardware.probe_budget",
++ lambda **kw: budget)
++
++ r = client.post("/api/local-models/download", json={"model_id": CATALOG[0].id})
++ job_id = r.json()["job_id"]
++
++ # Pause as soon as the live download handle is in place (idempotent).
++ deadline = time.time() + 10
++ paused = False
++ while time.time() < deadline:
++ pr = client.post("/api/local-models/download/pause",
++ json={"job_id": job_id})
++ if pr.status_code == 200 and pr.json()["paused"] is True:
++ paused = True
++ break
++ time.sleep(0.05)
++ assert paused
++ gate.set()
++
++ deadline = time.time() + 10
++ status = None
++ while time.time() < deadline:
++ status = client.get(f"/api/local-models/jobs/{job_id}").json()
++ if status["status"] in ("paused", "done", "error"):
++ break
++ time.sleep(0.05)
++ assert status is not None and status["status"] == "paused"
diff --cc tests/hermes_cli/test_local_quickstart.py
index 00000000000,f6a8f56193a..948dfa3e85d
mode 000000,100644..100644
--- a/tests/hermes_cli/test_local_quickstart.py
+++ b/tests/hermes_cli/test_local_quickstart.py
@@@ -1,0 -1,187 +1,192 @@@
+ """Quickstart route: one POST from nothing to a working local default.
+
+ Contract, not implementation: the route must (a) preflight-fail
+ synchronously when nothing fits, (b) report which legs the job will run
+ (runtime install / model download), skipping legs already satisfied,
+ and (c) run install -> download -> activate through the same code paths
+ the individual routes use. The slow legs are stubbed at their module
+ boundaries; the sequencing and job bookkeeping are real.
+ """
+
+ from __future__ import annotations
+
+ import time
+ from pathlib import Path
+
+ import pytest
+ from fastapi.testclient import TestClient
+
+
+ @pytest.fixture
+ def client(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ from hermes_cli import web_server
+
+ test_client = TestClient(web_server.app)
+ test_client.headers[web_server._SESSION_HEADER_NAME] = web_server._SESSION_TOKEN
+ return test_client
+
+
+ def _wait_job(client, job_id: str, timeout: float = 10.0) -> dict:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ job = client.get(f"/api/local-models/jobs/{job_id}").json()
+ if job["status"] != "running":
+ return job
+ time.sleep(0.05)
+ raise AssertionError(f"job {job_id} still running after {timeout}s")
+
+
+ def test_quickstart_unknown_model_404s(client):
+ r = client.post("/api/local-models/quickstart", json={"model_id": "no-such"})
+ assert r.status_code == 404
+
+
+ def test_quickstart_refuses_when_nothing_fits(client, monkeypatch):
+ """Preflight is synchronous: a machine no catalog entry fits gets a 409
+ with guidance, not a doomed background job."""
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.catalog.select_variant", lambda *a, **k: None)
+ r = client.post("/api/local-models/quickstart", json={})
+ assert r.status_code == 409
+ assert "Local Models" in r.json()["detail"]
+
+
+ def test_quickstart_runs_all_three_legs(client, monkeypatch, tmp_path):
+ """Fresh machine: install runtime -> download recommended -> activate.
+ Each leg is asserted by its observable call, in order."""
+ calls: list[str] = []
+
+ # Leg 1: no runtime installed yet; install is the stubbed binaries call.
+ monkeypatch.setattr(
- "hermes_cli.local_runtime.binaries.installed_tags", lambda: [])
++ "hermes_cli.local_runtime.binaries.installed_backends", lambda: [])
+ monkeypatch.setattr(
- "hermes_cli.local_runtime.binaries.ensure_runtime_installed",
- lambda tag, backend, progress=None: calls.append("install"))
++ "hermes_cli.local_runtime.binaries.ensure_engine",
++ lambda backend, progress=None: calls.append("install"))
+
+ # Leg 2: nothing staged; the download writes the files the plan names.
- def _fake_download(url, dest, job, *, base_done=0, keep_totals=False):
- Path(dest).parent.mkdir(parents=True, exist_ok=True)
- Path(dest).write_bytes(b"GGUF\x00")
++ # The store download runs a whole plan as one resumable Download
++ # (_download_job(job, plan)); fake it at that seam — walk the plan's
++ # (url, dest, size) triples and land each file.
++ def _fake_download_job(job, plan):
++ for url, dest, _size in plan:
++ Path(dest).parent.mkdir(parents=True, exist_ok=True)
++ Path(dest).write_bytes(b"GGUF\x00")
++ job["done_bytes"] = job.get("total_bytes", 0)
+ calls.append("download")
+
+ monkeypatch.setattr(
- "hermes_cli.web_routers.local_models.download_file", _fake_download)
++ "hermes_cli.web_routers.local_models._download_job", _fake_download_job)
+
+ # Leg 3: activation — stub the server start and the model assignment.
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.bootstrap.ensure_local_runtime",
+ lambda config, force=False: calls.append("server") or None)
+ monkeypatch.setattr(
+ "hermes_cli.web_routers.local_models._state_endpoint",
+ lambda: {"base_url": "http://127.0.0.1:1/v1", "api_key": "k"})
+ from hermes_cli import web_deps
+
+ monkeypatch.setattr(
+ web_deps, "late",
+ lambda name: (lambda *a, **k: calls.append("assign")))
+
+ r = client.post("/api/local-models/quickstart", json={})
+ assert r.status_code == 200
+ body = r.json()
+ assert body["needs_runtime"] is True
+ assert body["needs_download"] is True
+ assert body["download_bytes"] > 0
+
+ job = _wait_job(client, body["job_id"])
+ assert job["status"] == "done", job["error"]
+ assert job["kind"] == "quickstart"
+ # Order is the contract: engine, weights, server, default.
+ assert calls[0] == "install"
+ assert "download" in calls
+ assert calls.index("install") < calls.index("download") < calls.index("assign")
+
+ # Durable effect: the runtime is enabled in config.
+ from hermes_cli.config import load_config
+
+ assert load_config()["local_runtime"]["enabled"] is True
+
+
+ def test_quickstart_skips_satisfied_legs(client, monkeypatch):
+ """Runtime present and model already staged: the response says so and
+ the job goes straight to activation."""
+ calls: list[str] = []
+
+ monkeypatch.setattr(
- "hermes_cli.local_runtime.binaries.installed_tags", lambda: ["b10362"])
++ "hermes_cli.local_runtime.binaries.installed_backends", lambda: ["cpu"])
+ monkeypatch.setattr(
- "hermes_cli.local_runtime.binaries.ensure_runtime_installed",
- lambda tag, backend, progress=None: calls.append("install"))
++ "hermes_cli.local_runtime.binaries.ensure_engine",
++ lambda backend, progress=None: calls.append("install"))
+
+ # Every catalog variant reads as staged.
+ from hermes_cli.local_runtime.catalog import CATALOG
+
+ all_ids = {v.model_id for e in CATALOG for v in e.variants}
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.bootstrap.staged_model_ids", lambda: all_ids)
+ monkeypatch.setattr(
- "hermes_cli.web_routers.local_models.download_file",
- lambda *a, **k: calls.append("download"))
++ "hermes_cli.web_routers.local_models._download_job",
++ lambda job, plan: calls.append("download"))
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.bootstrap.ensure_local_runtime",
+ lambda config, force=False: None)
+ monkeypatch.setattr(
+ "hermes_cli.web_routers.local_models._state_endpoint",
+ lambda: {"base_url": "http://127.0.0.1:1/v1", "api_key": "k"})
+ from hermes_cli import web_deps
+
+ monkeypatch.setattr(
+ web_deps, "late",
+ lambda name: (lambda *a, **k: calls.append("assign")))
+
+ r = client.post("/api/local-models/quickstart", json={})
+ assert r.status_code == 200
+ body = r.json()
+ assert body["needs_runtime"] is False
+ assert body["needs_download"] is False
+ assert body["download_bytes"] == 0
+
+ job = _wait_job(client, body["job_id"])
+ assert job["status"] == "done", job["error"]
+ assert "install" not in calls and "download" not in calls
+ assert calls == ["assign"] or calls[-1] == "assign"
+
+
+ @pytest.fixture
+ def quickstart_ready(monkeypatch):
+ """Preflight passes without hardware or network: the runtime reads as
+ installed and every entry's first variant is servable, so the POST
+ reaches the single-flight lock instead of 409ing at fit/engine
+ preflight on machines where nothing fits."""
+ from hermes_cli.local_runtime.catalog import VariantChoice
+
+ monkeypatch.setattr(
- "hermes_cli.local_runtime.binaries.installed_tags", lambda: ["b10362"])
++ "hermes_cli.local_runtime.binaries.engine_version", lambda: "b10679")
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.catalog.select_variant",
+ lambda entry, budget: VariantChoice(variant=entry.variants[0],
+ zero_spill=True,
+ reason_key="best-fits"))
+ monkeypatch.setattr(
+ "hermes_cli.web_routers.local_models._engine_too_old",
+ lambda min_engine: False)
+
+
+ def test_quickstart_is_single_flight(client, quickstart_ready, monkeypatch):
+ """A second quickstart while one runs must 409, not start a twin job
+ (the job sequences installs, downloads, a server bounce, and a config
+ write — two interleaved runs corrupt all four)."""
+ import hermes_cli.web_routers.local_models as lm
+
+ lm._QUICKSTART_LOCK.acquire()
+ try:
+ r = client.post("/api/local-models/quickstart", json={})
+ assert r.status_code == 409
+ assert "already running" in r.json()["detail"].lower()
+ finally:
+ lm._QUICKSTART_LOCK.release()
diff --cc tests/hermes_cli/test_local_runtime.py
index 00000000000,0603e9ec296..a8de559c515
mode 000000,100644..100644
--- a/tests/hermes_cli/test_local_runtime.py
+++ b/tests/hermes_cli/test_local_runtime.py
@@@ -1,0 -1,825 +1,844 @@@
+ """Contract tests for hermes_cli.local_runtime — Rollouts 1+2.
+
+ Per the design's verification plan: relationships and contracts, no
+ change-detector tests, real imports against temp HERMES_HOME (the autouse
+ fixture isolates it). The stub HTTP server speaks just enough llama-server
+ (/props, /health, /models, /v1/chat/completions, /metrics, /slots) to
+ exercise detection fingerprinting and supervisor logic without a GPU.
+ """
+
+ from __future__ import annotations
+
+ import json
+ import os
+ import threading
+ from http.server import BaseHTTPRequestHandler, HTTPServer
+ from pathlib import Path
+
+ import pytest
+
+ from hermes_cli.local_runtime.binaries import (
- AssetPlan,
+ BinaryResolutionError,
- resolve_assets,
++ resolve_backend,
+ select_backend,
+ )
+ from hermes_cli.local_runtime.detect import DetectedServer, probe_port
+
+
+ # ── stub llama-server ────────────────────────────────────────
+
+
+ class _StubHandler(BaseHTTPRequestHandler):
+ """Minimal llama-server imitation; behavior driven by class attrs."""
+
+ props: dict = {}
+ models: dict | None = None
+ require_auth = False
+ chat_answer = "Paris"
+ requests_processing = 0
+ slots: list = []
+
+ def _send(self, code: int, body: dict | str | None = None) -> None:
+ raw = (json.dumps(body) if isinstance(body, dict) else (body or "")).encode()
+ self.send_response(code)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(raw)))
+ self.end_headers()
+ self.wfile.write(raw)
+
+ def do_GET(self): # noqa: N802
+ if self.require_auth and "Authorization" not in self.headers:
+ self._send(401, {})
+ return
+ path = self.path.split("?")[0] # router telemetry uses ?model=
+ if path == "/props":
+ self._send(200, self.props)
+ elif path == "/health":
+ self._send(200, {"status": "ok"})
+ elif path == "/models":
+ if self.models is None:
+ self._send(404, {})
+ else:
+ self._send(200, self.models)
+ elif path == "/metrics":
+ self._send(200, f"llamacpp:requests_processing {self.requests_processing}\n")
+ elif path == "/slots":
+ raw = json.dumps(self.slots).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(raw)))
+ self.end_headers()
+ self.wfile.write(raw)
+ else:
+ self._send(404, {})
+
+ def do_POST(self): # noqa: N802
+ if self.path == "/v1/chat/completions":
+ self._send(200, {"choices": [{"message": {
+ "role": "assistant", "content": self.chat_answer}}]})
+ elif self.path == "/models/load":
+ self._send(200, {"success": True})
+ elif self.path == "/models/unload":
+ type(self).unloaded = getattr(type(self), "unloaded", [])
+ length = int(self.headers.get("Content-Length", 0))
+ body = json.loads(self.rfile.read(length)) if length else {}
+ type(self).unloaded.append(body.get("model"))
+ self._send(200, {"success": True})
+ else:
+ self._send(404, {})
+
+ def log_message(self, *args): # silence
+ pass
+
+
+ @pytest.fixture
+ def stub_server():
+ """Yields (port, handler_class); handler attrs are per-test mutable."""
+
+ class Handler(_StubHandler):
+ props = {}
+ models = None
+ require_auth = False
+ slots = []
+
+ server = HTTPServer(("127.0.0.1", 0), Handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ yield server.server_address[1], Handler
+ server.shutdown()
+
+
+ # ── detection (Rollout 1) ────────────────────────────────────
+
+
+ def test_probe_fingerprints_real_llama_server(stub_server):
+ port, handler = stub_server
+ handler.props = {
+ "build_info": "b10290-c8e03ce81",
+ "model_path": "C:/models/some model with spaces.gguf",
+ "default_generation_settings": {"n_ctx": 65536},
+ }
+ handler.models = {"data": [{"id": "m", "status": {"value": "unloaded"}}]}
+ hit = probe_port(port)
+ assert isinstance(hit, DetectedServer)
+ assert hit.base_url == f"http://127.0.0.1:{port}/v1"
+ assert hit.build_info.startswith("b10290")
+ assert hit.n_ctx == 65536
+ assert hit.router_mode is True
+ assert hit.auth_required is False
+
+
+ def test_probe_rejects_non_llama_openai_server(stub_server):
+ # Answers /props with no build_info (e.g. some other local service).
+ port, handler = stub_server
+ handler.props = {"something": "else"}
+ assert probe_port(port) is None
+
+
+ def test_probe_single_model_mode_is_not_router(stub_server):
+ port, handler = stub_server
+ handler.props = {"build_info": "b10290-x", "model_path": "m.gguf"}
+ handler.models = None # /models 404s in plain (non-router) mode
+ hit = probe_port(port)
+ assert hit is not None
+ assert hit.router_mode is False
+
+
+ def test_probe_auth_required_still_detected(stub_server):
+ port, handler = stub_server
+ handler.require_auth = True
+ hit = probe_port(port)
+ assert hit is not None
+ assert hit.auth_required is True
+
+
+ def test_probe_dead_port_returns_none():
+ # Bind-then-close to get a port that is definitely closed.
+ import socket
+ with socket.socket() as s:
+ s.bind(("127.0.0.1", 0))
+ dead_port = s.getsockname()[1]
+ assert probe_port(dead_port) is None
+
+
-# ── binary resolver (Rollout 2) ──────────────────────────────
++# ── engine packages (Rollout 2, on pm) ───────────────────────
+
+
[email protected]("os_name,arch,backend,ok", [
- ("win", "x64", "cuda", True),
- ("win", "x64", "vulkan", True),
- ("win", "x64", "cpu", True),
- ("win", "arm64", "cpu", True),
- ("win", "arm64", "cuda", True), # upstream ships these since ~b1036x (CUDA 13.4)
- ("win", "arm64", "vulkan", False),
- ("macos", "arm64", "metal", True),
- ("ubuntu", "x64", "vulkan", True),
- ("ubuntu", "x64", "cpu", True),
- ("ubuntu", "x64", "cuda", False), # no prebuilt linux CUDA
++def _llama(backend: str):
++ from pm.registry import get_package
++
++ return get_package(f"llamacpp-{backend}")
++
++
++def _target(os_name: str, arch: str) -> str:
++ return f"{os_name}-{arch}"
++
++
[email protected]("backend,target,ok", [
++ ("cuda", "win32-x64", True),
++ ("vulkan", "win32-x64", True),
++ ("cpu", "win32-x64", True),
++ ("cpu", "win32-arm64", True),
++ ("cuda", "win32-arm64", True), # upstream ships these since ~b1036x (CUDA 13.4)
++ ("vulkan", "win32-arm64", False), # upstream publishes no win-arm64 vulkan
++ ("metal", "darwin-arm64", True),
++ ("vulkan", "linux-x64", True),
++ ("cpu", "linux-x64", True),
++ ("cuda", "linux-x64", False), # no prebuilt linux CUDA
+ ])
-def test_resolver_platform_matrix(os_name, arch, backend, ok):
++def test_backend_platform_matrix(backend, target, ok):
++ pkg = _llama(backend)
+ if ok:
- plan = resolve_assets("b10290", backend, os_name=os_name, arch=arch)
- assert plan.assets, "resolvable combination must yield assets"
- # Invariant: every asset names the tag or is a paired runtime zip.
- for asset in plan.assets:
- assert "b10290" in asset or asset.startswith("cudart-")
++ urls = pkg.fetch_urls("10362", target)
++ assert urls, "available combination must yield archive urls"
++ # Every asset names the tag (the version without the b).
++ for url in urls:
++ assert "b10362" in url
++ assert pkg.missing_reason(target) is None
+ else:
- with pytest.raises(BinaryResolutionError):
- resolve_assets("b10290", backend, os_name=os_name, arch=arch)
++ assert pkg.missing_reason(target) is not None
+
+
+ def test_windows_cuda_pairs_cudart():
- """Windows CUDA must ship the runtime zip — users have no toolkit."""
- plan = resolve_assets("b10290", "cuda", os_name="win", arch="x64")
- assert any(a.startswith("cudart-") for a in plan.assets)
++ """Windows CUDA must ship the cudart archive — users have no toolkit,
++ and Windows resolves a DLL from the executable's own directory."""
++ urls = _llama("cuda").fetch_urls("10362", "win32-x64")
++ assert len(urls) == 2
++ assert any("cudart-llama" in u for u in urls)
++ assert any("llama-b10362-bin" in u for u in urls)
+
+
+ def test_windows_cuda_arm64_pairs_cudart_on_its_own_version():
+ """arm64 CUDA rides its own CUDA line (13.4 at b10362, verified live):
- both zips must agree on version and name the arch."""
- plan = resolve_assets("b10362", "cuda", os_name="win", arch="arm64")
- assert len(plan.assets) == 2
- assert all("arm64" in a for a in plan.assets)
- versions = {a.split("cuda-")[1].split("-")[0] for a in plan.assets}
- assert len(versions) == 1, f"paired zips disagree on CUDA version: {plan.assets}"
- assert any(a.startswith("cudart-") for a in plan.assets)
- assert any(a.startswith("llama-") for a in plan.assets)
++ both archives must agree on version and name the arch."""
++ urls = _llama("cuda").fetch_urls("10362", "win32-arm64")
++ assert len(urls) == 2
++ assert all("arm64" in u for u in urls)
++ versions = {u.split("cuda-")[1].split("-")[0] for u in urls}
++ assert len(versions) == 1, f"paired zips disagree on CUDA version: {urls}"
++ assert any("cudart-" in u for u in urls)
++ assert any("llama-" in u for u in urls)
+
+
-def test_install_dir_is_profile_scoped(tmp_path, monkeypatch):
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
- plan = AssetPlan(tag="b10290", backend="cuda")
- assert str(tmp_path) in str(plan.install_dir)
- assert "runtimes" in plan.install_dir.parts
++def test_backend_ladder_falls_back_when_unavailable(monkeypatch):
++ """An explicit backend this platform has no build for falls back down
++ the ladder instead of failing (the hardware-aware boot path)."""
++ import pm.store as store_mod
++
++ monkeypatch.setattr(store_mod, "current_target", lambda: "win32-arm64")
++ # vulkan has no win32-arm64 build; the ladder must walk to cuda (the
++ # next rung that IS built for this target), not fail.
++ assert resolve_backend("vulkan") == "cuda"
++
++
++def test_backend_ladder_raises_when_nothing_available(monkeypatch):
++ """When every rung is unavailable the declared gaps surface instead of
++ a silent wrong-backend install."""
++ import hermes_cli.local_runtime.binaries as binaries
++
++ monkeypatch.setattr(binaries, "unavailable_reason", lambda backend: f"no {backend}")
++ with pytest.raises(BinaryResolutionError):
++ resolve_backend("cuda")
+
+
+ @pytest.mark.parametrize("vendor,os_name,expected", [
+ ("NVIDIA GeForce RTX 5090", "win", "cuda"),
+ ("nvidia", "ubuntu", "cuda"),
+ ("AMD Radeon RX 7900", "win", "vulkan"),
+ ("intel", "win", "vulkan"),
+ (None, "win", "cpu"),
+ ("", "ubuntu", "cpu"),
+ ("nvidia", "macos", "metal"), # macOS is Metal regardless
+ (None, "macos", "metal"),
+ ])
+ def test_backend_selection(vendor, os_name, expected):
+ assert select_backend(vendor, os_name=os_name) == expected
+
+
-def test_sha256_mismatch_rejects(tmp_path, monkeypatch):
- """A pinned hash that doesn't match the download must hard-fail."""
- from hermes_cli.local_runtime import binaries
-
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
- # Pre-place a wrong-content "download" so no network is touched. The
- # asset name is host-dependent (win/.zip, ubuntu/.tar.gz, macos/.zip)
- # — resolve it the way the installer will, so the poisoned file is the
- # one it verifies on every CI platform.
- plan = binaries.resolve_assets("b10290", "cpu")
- asset = plan.assets[0]
- downloads = binaries.runtimes_root() / "downloads"
- downloads.mkdir(parents=True)
- (downloads / asset).write_bytes(b"not the real archive")
- with pytest.raises(BinaryResolutionError, match="sha256 mismatch"):
- binaries.ensure_runtime_installed(
- "b10290", "cpu",
- expected_sha256={asset: "0" * 64})
- # The poisoned download must not survive for a retry to trust.
- assert not (downloads / asset).exists()
-
-
+ # ── supervisor contracts (stubbed; no GPU) ───────────────────
+
+
+ def _make_supervisor(tmp_path, port):
+ """Supervisor pointed at the stub: skip spawn, drive HTTP logic only."""
+ from hermes_cli.local_runtime.supervisor import LlamaServerSupervisor
+
+ sup = LlamaServerSupervisor(
- install_dir=tmp_path, models_dir=tmp_path, port=port)
++ server_exe=tmp_path / "llama-server.exe", models_dir=tmp_path, port=port)
+ return sup
+
+
+ def test_touch_generate_is_the_readiness_proof(stub_server, tmp_path):
+ port, handler = stub_server
+ sup = _make_supervisor(tmp_path, port)
+ handler.chat_answer = "Paris"
+ assert sup.touch_generate("m") is True
+ handler.chat_answer = "I cannot answer that."
+ assert sup.touch_generate("m") is False
+
+
+ def test_touch_generate_scans_reasoning_content(stub_server, tmp_path):
+ """Reasoning models answer inside reasoning_content (receipted pitfall)."""
+ port, handler = stub_server
+ sup = _make_supervisor(tmp_path, port)
+
+ class ReasoningHandler(handler): # type: ignore[valid-type]
+ def do_POST(self): # noqa: N802
+ if self.path == "/v1/chat/completions":
+ self._send(200, {"choices": [{"message": {
+ "role": "assistant", "content": "",
+ "reasoning_content": "The capital of France is Paris."}}]})
+ else:
+ self._send(404, {})
+
+ # Swap handler class on the live stub server socket is overkill; just
+ # verify the scan logic path via the normal handler with empty content.
+ handler.chat_answer = ""
+ assert sup.touch_generate("m") is False # empty content, no reasoning field
+
+
+ def test_ensure_model_ready_unknown_model_raises(stub_server, tmp_path):
+ port, handler = stub_server
+ handler.models = {"data": [{"id": "present", "status": {"value": "unloaded"}}]}
+ sup = _make_supervisor(tmp_path, port)
+ with pytest.raises(KeyError):
+ sup.ensure_model_ready("absent")
+
+
+ def test_model_failures_surface_exit_code_not_retry(stub_server, tmp_path):
+ """Design: child failures surface, never auto-retry."""
+ port, handler = stub_server
+ handler.models = {"data": [
+ {"id": "ok", "status": {"value": "loaded"}},
+ {"id": "dead", "status": {"value": "failed", "exit_code": -1073741819}},
+ ]}
+ sup = _make_supervisor(tmp_path, port)
+ failures = sup.model_failures()
+ assert failures == {"dead": -1073741819}
+
+
+ def test_is_idle_requires_no_busy_slots_and_zero_processing(stub_server, tmp_path):
+ port, handler = stub_server
+ sup = _make_supervisor(tmp_path, port)
+ # Router telemetry is per-child (?model=); a loaded model must exist for
+ # is_idle to have anything to check.
+ handler.models = {"data": [{"id": "m", "status": {"value": "loaded"}}]}
+ handler.slots = [{"id": 0, "is_processing": False}]
+ handler.requests_processing = 0
+ assert sup.is_idle() is True
+ handler.slots = [{"id": 0, "is_processing": True}]
+ assert sup.is_idle() is False
+ handler.slots = [{"id": 0, "is_processing": False}]
+ handler.requests_processing = 2
+ assert sup.is_idle() is False
+
+
+ def test_base_url_dials_loopback_ip_never_localhost(tmp_path):
+ """C12: localhost costs ~2s/request on Windows."""
+ sup = _make_supervisor(tmp_path, 9999)
+ assert "127.0.0.1" in sup.base_url
+ assert "localhost" not in sup.base_url
+
+
+ # ── provider integration (existing alias mechanism, no new plugin) ──
+
+
+ def test_llamacpp_aliases_route_to_custom_profile():
+ """Design + maintainer direction: llamacpp fits the EXISTING provider
+ mechanism — the aliases already resolve to the keyless custom profile;
+ no parallel provider plugin exists."""
+ from providers import get_provider_profile
+
+ for alias in ("llamacpp", "llama.cpp", "llama-cpp"):
+ profile = get_provider_profile(alias)
+ assert profile is not None, alias
+ assert profile.name == "custom"
+ assert profile.env_vars == () # credential is reachability
+
+
+ def test_llamacpp_endpoint_resolution_prefers_managed(tmp_path, monkeypatch, stub_server):
+ """provider: llamacpp with a live managed server resolves to it,
+ api-key included."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ port, handler = stub_server
+ from hermes_cli.local_runtime import endpoint as ep
+ from hermes_cli.local_runtime.supervisor import state_path
+
+ state_path().parent.mkdir(parents=True, exist_ok=True)
+ state_path().write_text(json.dumps({
+ # A LIVE pid: the ownership guard treats health-200 + dead recorded
+ # pid as a foreign server on our stable port (scratch-profile
+ # collision), so claiming this test process models "our server".
+ "base_url": f"http://127.0.0.1:{port}/v1", "api_key": "sk-managed", "pid": os.getpid(),
+ }), encoding="utf-8")
+ resolved = ep.resolve_llamacpp_endpoint()
+ assert resolved == {"base_url": f"http://127.0.0.1:{port}/v1", "api_key": "sk-managed"}
+
+
+ def test_llamacpp_endpoint_stale_state_falls_through(tmp_path, monkeypatch):
+ """A crashed-without-cleanup state file (dead pid, dead endpoint) must
+ not blackhole requests: state ignored -> detection (none here) -> None."""
+ import socket
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ with socket.socket() as s:
+ s.bind(("127.0.0.1", 0))
+ dead_port = s.getsockname()[1]
+ from hermes_cli.local_runtime import endpoint as ep
+ from hermes_cli.local_runtime.detect import DEFAULT_PROBE_PORTS
+ from hermes_cli.local_runtime.supervisor import state_path
+
+ state_path().parent.mkdir(parents=True, exist_ok=True)
+ state_path().write_text(json.dumps({
+ "base_url": f"http://127.0.0.1:{dead_port}/v1", "api_key": "sk-x", "pid": 1,
+ }), encoding="utf-8")
+ monkeypatch.setattr(ep, "_pid_alive", lambda pid: False)
+ # Keep detection away from any real server on 8080 during the test.
+ monkeypatch.setattr("hermes_cli.local_runtime.detect.DEFAULT_PROBE_PORTS",
+ (dead_port,))
+ assert ep.resolve_llamacpp_endpoint() is None
+ assert DEFAULT_PROBE_PORTS # (import kept honest)
+
+
-def test_llamacpp_dead_server_raises_friendly_error(tmp_path, monkeypatch):
- """A llamacpp send with no server must say WHY in user terms, not fall
- through to the generic custom path (which lands on a cloud provider
- with a placeholder key and surfaces as a baffling '401 Invalid API
- key'). Message tracks the off switch: enabled = probably starting;
- disabled = the user turned it off."""
- import pytest
-
- monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
-
- from hermes_cli import runtime_provider as rp
-
- monkeypatch.setattr(
- "hermes_cli.local_runtime.endpoint.resolve_llamacpp_endpoint",
- lambda *a, **k: None)
-
- monkeypatch.setattr(
- "hermes_cli.config.load_config",
- lambda: {"local_runtime": {"enabled": False}})
- with pytest.raises(ValueError, match="turned off"):
- rp._resolve_named_custom_runtime(requested_provider="llamacpp")
-
- monkeypatch.setattr(
- "hermes_cli.config.load_config",
- lambda: {"local_runtime": {"enabled": True}})
- with pytest.raises(ValueError, match="isn't running"):
- rp._resolve_named_custom_runtime(requested_provider="llamacpp")
-
- # An explicit base_url is the user pointing at a specific server —
- # that path keeps its own error reporting, never this one.
- result = rp._resolve_named_custom_runtime(
- requested_provider="llamacpp",
- explicit_base_url="http://127.0.0.1:9999/v1")
- assert result is None or result.get("base_url", "").startswith("http://127.0.0.1:9999")
-
-
+ def test_llamacpp_endpoint_starting_server_resolves(tmp_path, monkeypatch):
+ """The restart race: state written at spawn, server not yet healthy,
+ supervisor child alive — resolution must return the endpoint (a
+ STARTING server is configured, not missing credentials; this exact
+ race threw the app back to onboarding on the first restart test)."""
+ import socket
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ with socket.socket() as s:
+ s.bind(("127.0.0.1", 0))
+ not_listening = s.getsockname()[1]
+ from hermes_cli.local_runtime import endpoint as ep
+ from hermes_cli.local_runtime.supervisor import state_path
+
+ state_path().parent.mkdir(parents=True, exist_ok=True)
+ state_path().write_text(json.dumps({
+ "base_url": f"http://127.0.0.1:{not_listening}/v1",
+ "api_key": "sk-starting", "pid": 4242,
+ }), encoding="utf-8")
+ monkeypatch.setattr(ep, "_pid_alive", lambda pid: True)
+ resolved = ep.resolve_llamacpp_endpoint()
+ assert resolved is not None
+ assert resolved["api_key"] == "sk-starting"
+
+
+ def test_llamacpp_endpoint_waits_for_boot_in_flight(tmp_path, monkeypatch):
+ """The SECOND restart race (no state file at all yet): a fresh backend's
+ readiness probe resolves before the lifespan boot thread has even
+ spawned the server. With the runtime enabled+installed, resolution must
+ poll briefly and pick up the state file when the boot thread writes it
+ — not report unconfigured."""
+ import threading
+ import time as _time
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ from hermes_cli.local_runtime import endpoint as ep
+ from hermes_cli.local_runtime.supervisor import state_path
+
+ # Boot is in flight: runtime enabled + binary installed.
+ monkeypatch.setattr(ep, "_boot_in_flight", lambda config: True)
+ monkeypatch.setattr(ep, "_pid_alive", lambda pid: True)
+ # Nothing detected externally.
+ monkeypatch.setattr("hermes_cli.local_runtime.detect.DEFAULT_PROBE_PORTS", ())
+
+ def _late_writer():
+ _time.sleep(0.6)
+ state_path().parent.mkdir(parents=True, exist_ok=True)
+ state_path().write_text(json.dumps({
+ "base_url": "http://127.0.0.1:59999/v1",
+ "api_key": "sk-boot", "pid": 777,
+ }), encoding="utf-8")
+
+ t = threading.Thread(target=_late_writer)
+ t.start()
+ try:
+ resolved = ep.resolve_llamacpp_endpoint(wait_for_boot_s=5.0)
+ finally:
+ t.join()
+ assert resolved is not None
+ assert resolved["api_key"] == "sk-boot"
+
+
+ def test_resolution_kicks_boot_when_no_thread_is_booting(tmp_path, monkeypatch):
+ """The dead-router-mid-flight case: runtime enabled+installed, but no
+ state file and NO lifespan boot thread running (the router died after
+ backend start — tree-killed with a stale backend, or the stable port
+ was owned by another install and the ownership guard refused it).
+ Resolution must not just wait for a boot that nobody is doing — it
+ kicks ensure_local_runtime itself and picks up the state file that
+ boot writes."""
+ import time as _time
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ from hermes_cli.local_runtime import bootstrap as bs
+ from hermes_cli.local_runtime import endpoint as ep
+ from hermes_cli.local_runtime.supervisor import state_path
+
+ monkeypatch.setattr(ep, "_boot_in_flight", lambda config: True)
+ monkeypatch.setattr(ep, "_pid_alive", lambda pid: True)
+ monkeypatch.setattr("hermes_cli.local_runtime.detect.DEFAULT_PROBE_PORTS", ())
+
+ def _fake_ensure(config, force=False):
+ _time.sleep(0.3) # a real spawn takes a moment
+ state_path().parent.mkdir(parents=True, exist_ok=True)
+ state_path().write_text(json.dumps({
+ "base_url": "http://127.0.0.1:59998/v1",
+ "api_key": "sk-kicked", "pid": 778,
+ }), encoding="utf-8")
+
+ monkeypatch.setattr(bs, "ensure_local_runtime", _fake_ensure)
+
+ resolved = ep.resolve_llamacpp_endpoint(config={}, wait_for_boot_s=5.0)
+ assert resolved is not None
+ assert resolved["api_key"] == "sk-kicked"
+
+
+ def test_boot_in_flight_real_gate(tmp_path, monkeypatch):
+ """_boot_in_flight exercised FOR REAL (the previous regression test
+ monkeypatched it — and the real one threw TypeError on every call,
- silently disabling the boot wait). Enabled + verified manifest on
- disk -> True; either missing -> False."""
++ silently disabling the boot wait). Enabled + an installed engine ->
++ True; either missing -> False."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ from hermes_cli.local_runtime import endpoint as ep
- from hermes_cli.local_runtime.binaries import runtimes_root
++
++ def _install(backend, version):
++ from pm import paths
++ from pm.lock import Facts
++
++ store = paths.store_root()
++ name = f"llamacpp-{backend}"
++ entry = f"{name}-{version}-win32-x64"
++ (store / entry).mkdir(parents=True, exist_ok=True)
++ Facts(store / "facts.json").record(name, version, entry, {}, store)
+
+ enabled = {"local_runtime": {"enabled": True}}
+ # Not installed yet -> False.
+ assert ep._boot_in_flight(enabled) is False
- # Verified install manifest -> True.
- install = runtimes_root() / "b10290" / "cuda"
- install.mkdir(parents=True)
- (install / "manifest.json").write_text(
- json.dumps({"tag": "b10290", "verified_version": "5015 (abc)"}),
- encoding="utf-8")
++ # An installed engine -> True.
++ _install("cpu", "10362")
+ assert ep._boot_in_flight(enabled) is True
+ # Disabled -> False even when installed.
+ assert ep._boot_in_flight({"local_runtime": {"enabled": False}}) is False
+
+
+ def test_idle_sweep_unloads_idle_models(tmp_path, monkeypatch, stub_server):
+ """Residency v2 contract: after the idle threshold, idle loaded models
+ unload — no exemptions; demand reloads anything the user returns to.
+ Idleness is the C5 contract (no busy slots)."""
+ port, handler = stub_server
+ handler.models = {"data": [
+ {"id": "model-a", "status": {"value": "loaded"}},
+ {"id": "model-b", "status": {"value": "loaded"}},
+ ]}
+ handler.slots = [] # everyone idle per C5
+ handler.requests_processing = 0
+ handler.unloaded = []
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ from hermes_cli.local_runtime.supervisor import LlamaServerSupervisor
+
- sup = LlamaServerSupervisor(tmp_path / "i", tmp_path / "m", port=port)
++ sup = LlamaServerSupervisor(tmp_path / "llama-server.exe", tmp_path / "m", port=port)
+
+ t0 = 1000.0
+ # First sweep: starts the idle clocks, nothing unloads yet.
+ assert sup.sweep_idle(now=t0) == []
+ # Before the threshold: still nothing.
+ assert sup.sweep_idle(now=t0 + sup.IDLE_UNLOAD_S - 1) == []
+ # Past the threshold: both idle models unload.
+ assert sorted(sup.sweep_idle(now=t0 + sup.IDLE_UNLOAD_S + 1)) == ["model-a", "model-b"]
+ assert sorted(handler.unloaded) == ["model-a", "model-b"]
+
+
+ def test_idle_sweep_busy_model_resets_clock(tmp_path, monkeypatch, stub_server):
+ """A model seen busy (C5: busy slot) restarts its idle clock — an
+ active conversation never trips the sweep."""
+ port, handler = stub_server
+ handler.models = {"data": [{"id": "side-m", "status": {"value": "loaded"}}]}
+ handler.unloaded = []
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ from hermes_cli.local_runtime.supervisor import LlamaServerSupervisor
+
- sup = LlamaServerSupervisor(tmp_path / "i", tmp_path / "m", port=port)
++ sup = LlamaServerSupervisor(tmp_path / "llama-server.exe", tmp_path / "m", port=port)
+
+ t0 = 1000.0
+ handler.slots = [] # idle: clock starts
+ assert sup.sweep_idle(now=t0) == []
+ handler.slots = [{"is_processing": True}] # busy mid-window
+ assert sup.sweep_idle(now=t0 + sup.IDLE_UNLOAD_S) == []
+ handler.slots = [] # idle again: clock restarts, not expired
+ assert sup.sweep_idle(now=t0 + sup.IDLE_UNLOAD_S + 10) == []
+ assert handler.unloaded == []
+
+
+ def test_staged_models_requires_every_split_part(tmp_path, monkeypatch):
+ """A split GGUF mid-download must NOT count as staged: the picker, the
+ catalog's 'downloaded' flag, and the router's model list all read
+ staged_models(), and a first part with missing continuations is not
+ servable. Single files and complete splits count; continuation parts
+ never count as their own model."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ import hermes_cli.local_runtime.bootstrap as bs
+
+ mdir = bs.models_dir()
+ mdir.mkdir(parents=True, exist_ok=True)
+
+ (mdir / "Single-Q4_K_M.gguf").touch()
+ # Complete split: both parts present.
+ (mdir / "Whole-Q4-00001-of-00002.gguf").touch()
+ (mdir / "Whole-Q4-00002-of-00002.gguf").touch()
+ # Mid-download split: first part only, of three.
+ (mdir / "Partial-Q4-00001-of-00003.gguf").touch()
+
+ assert bs.staged_model_ids() == ["Single-Q4_K_M", "Whole-Q4"]
+
+
+ def test_bootstrap_skips_boot_with_no_staged_models(tmp_path, monkeypatch):
+ """Residency: enabled + installed but zero staged models -> no server
+ boot (nothing to serve; the walked-away story)."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ import hermes_cli.local_runtime.bootstrap as bs
+
+ monkeypatch.setattr(bs, "_SUPERVISOR", None)
+ called = {"spawn": False}
+
+ def _boom(*a, **k):
+ called["spawn"] = True
+ raise AssertionError("must not reach install/spawn")
+
- monkeypatch.setattr("hermes_cli.local_runtime.binaries.ensure_runtime_installed", _boom)
++ monkeypatch.setattr("hermes_cli.local_runtime.binaries.ensure_engine", _boom)
+ result = bs.ensure_local_runtime({"local_runtime": {"enabled": True}})
+ assert result is None
+ assert called["spawn"] is False
+
+
+ def test_endpoint_identity_stable_across_supervisor_instances(tmp_path, monkeypatch):
+ """Round-7 contract: base_url AND api_key survive a restart as a unit.
+ Two supervisor constructions (= two backend boots) must agree on both —
+ sessions persist the resolved pair, so either piece rotating strands
+ every resumed session (connection error / HTTP 401)."""
+ import socket as _socket
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ from hermes_cli.local_runtime import supervisor as sup_mod
+ from hermes_cli.local_runtime.supervisor import LlamaServerSupervisor
+
+ # A test-owned default port: the production default may legitimately be
+ # held by a live managed server on the dev machine.
+ with _socket.socket() as s:
+ s.bind(("127.0.0.1", 0))
+ test_port = s.getsockname()[1]
+ monkeypatch.setattr(sup_mod, "_DEFAULT_PORT", test_port)
+
- first = LlamaServerSupervisor(tmp_path / "install", tmp_path / "models")
- second = LlamaServerSupervisor(tmp_path / "install", tmp_path / "models")
++ first = LlamaServerSupervisor(tmp_path / "llama-server.exe", tmp_path / "models")
++ second = LlamaServerSupervisor(tmp_path / "llama-server.exe", tmp_path / "models")
+ assert first.api_key == second.api_key
+ assert len(first.api_key) >= 16
+ assert first.port == second.port == test_port
+ # The key is persisted, not per-process state.
+ key_file = tmp_path / ".hermes" / "runtimes" / "llamacpp" / ".api_key"
+ assert key_file.exists()
+ assert key_file.read_text(encoding="utf-8").strip() == first.api_key
+
+
+ def test_llamacpp_endpoint_no_wait_when_not_enabled(tmp_path, monkeypatch):
+ """No boot in flight (runtime disabled/uninstalled): resolution returns
+ None promptly instead of burning the wait budget."""
+ import time as _time
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ from hermes_cli.local_runtime import endpoint as ep
+
+ monkeypatch.setattr(ep, "_boot_in_flight", lambda config: False)
+ monkeypatch.setattr("hermes_cli.local_runtime.detect.DEFAULT_PROBE_PORTS", ())
+ t0 = _time.monotonic()
+ assert ep.resolve_llamacpp_endpoint(wait_for_boot_s=8.0) is None
+ assert _time.monotonic() - t0 < 3.0
+
+
+ def test_switch_model_explicit_llamacpp_provider(tmp_path, monkeypatch, stub_server):
+ """The desktop dropdown path: switch_model(explicit_provider='llamacpp')
- must resolve the managed provider — not 'Unknown provider' (the
- desktop-review symptom). E2E through the real pipeline against a stub server."""
++ must resolve the managed provider — not 'Unknown provider' (Jeff's
++ round-5 symptom). E2E through the real pipeline against a stub server."""
+ port, handler = stub_server
+ handler.models = {"data": [{"id": "stub-model-a", "owned_by": "llamacpp"}]}
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ from hermes_cli.local_runtime.supervisor import state_path
+
+ state_path().parent.mkdir(parents=True, exist_ok=True)
+ state_path().write_text(json.dumps({
+ "base_url": f"http://127.0.0.1:{port}/v1",
+ # Live pid: ownership guard rejects health-200 + dead recorded pid
+ # (foreign server on our stable port).
+ "api_key": "sk-managed", "pid": os.getpid(),
+ }), encoding="utf-8")
+
+ from hermes_cli.model_switch import switch_model
+
+ result = switch_model(
+ "stub-model-a",
+ current_provider="nous",
+ current_model="Hermes-4.5",
+ current_base_url="",
+ explicit_provider="llamacpp",
+ )
+ assert result.success, result.error_message
+ assert f"127.0.0.1:{port}" in (result.base_url or "")
+ assert result.api_key == "sk-managed"
+
+
+ def test_runtime_provider_seam_llamacpp_alias(tmp_path, monkeypatch, stub_server):
+ """End to end through the REAL resolver: provider='llamacpp' with no
+ base_url lands on the managed endpoint with source='local-runtime'."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ port, handler = stub_server
+ from hermes_cli.local_runtime.supervisor import state_path
+
+ state_path().parent.mkdir(parents=True, exist_ok=True)
+ state_path().write_text(json.dumps({
+ # A LIVE pid: the ownership guard treats health-200 + dead recorded
+ # pid as a foreign server on our stable port (scratch-profile
+ # collision), so claiming this test process models "our server".
+ "base_url": f"http://127.0.0.1:{port}/v1", "api_key": "sk-managed", "pid": os.getpid(),
+ }), encoding="utf-8")
+
+ from hermes_cli.runtime_provider import _resolve_named_custom_runtime
+
+ runtime = _resolve_named_custom_runtime(requested_provider="llamacpp")
+ assert runtime is not None
+ assert runtime["source"] == "local-runtime"
+ assert runtime["base_url"] == f"http://127.0.0.1:{port}/v1"
+ assert runtime["api_key"] == "sk-managed"
+ assert runtime["provider"] == "custom"
+
+
+ def test_runtime_provider_seam_explicit_base_url_wins(tmp_path, monkeypatch):
+ """A user-specified base_url must never be overridden by the managed
+ endpoint — pointing at a specific server means that server."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ from hermes_cli.local_runtime.supervisor import state_path
+
+ state_path().parent.mkdir(parents=True, exist_ok=True)
+ state_path().write_text(json.dumps({
+ "base_url": "http://127.0.0.1:1/v1", "api_key": "sk-managed", "pid": 1,
+ }), encoding="utf-8")
+
+ from hermes_cli.runtime_provider import _resolve_named_custom_runtime
+
+ runtime = _resolve_named_custom_runtime(
+ requested_provider="llamacpp",
+ explicit_base_url="http://127.0.0.1:9999/v1")
+ assert runtime is not None
+ assert runtime["base_url"] == "http://127.0.0.1:9999/v1"
+ assert runtime["source"] != "local-runtime"
+
+
+ def test_local_runtime_config_defaults_shape():
- """Contract: the section exists, is off by default, and carries no
- context/VRAM knobs (design: constants, not knobs)."""
++ """Contract: the section exists, is off by default, carries no tag
++ (the build is pinned in pm/lock.json), and no context/VRAM knobs
++ (design: constants, not knobs)."""
+ from hermes_cli.config_defaults import DEFAULT_CONFIG
+
+ cfg = DEFAULT_CONFIG["local_runtime"]
+ assert cfg["enabled"] is False
- assert isinstance(cfg["tag"], str) and cfg["tag"].startswith("b")
++ assert "tag" not in cfg # version authority is pm/lock.json
+ forbidden = [k for k in cfg if "context" in k or "ctx" in k or "vram" in k or "kv" in k]
+ assert forbidden == [], f"policy constants leaked into config: {forbidden}"
+
+
+ # ── bootstrap contracts ──────────────────────────────────────
+
+
+ def test_bootstrap_disabled_is_noop(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ from hermes_cli.local_runtime import bootstrap
+
+ monkeypatch.setattr(bootstrap, "_SUPERVISOR", None)
+ assert bootstrap.ensure_local_runtime({"local_runtime": {"enabled": False}}) is None
+ assert bootstrap.ensure_local_runtime({}) is None
+ assert bootstrap.ensure_local_runtime(None) is None
+
+
+ def test_bootstrap_reuses_running_server(tmp_path, monkeypatch, stub_server):
+ """A live state file (another process supervising) short-circuits the
+ install/spawn path entirely."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ port, handler = stub_server
+ from hermes_cli.local_runtime import bootstrap
+ from hermes_cli.local_runtime.supervisor import state_path
+
+ monkeypatch.setattr(bootstrap, "_SUPERVISOR", None)
+ state_path().parent.mkdir(parents=True, exist_ok=True)
+ state_path().write_text(json.dumps({
+ "base_url": f"http://127.0.0.1:{port}/v1", "api_key": "k", "pid": os.getpid(),
+ }), encoding="utf-8")
+
+ called = []
+ monkeypatch.setattr(
- "hermes_cli.local_runtime.binaries.ensure_runtime_installed",
++ "hermes_cli.local_runtime.binaries.ensure_engine",
+ lambda *a, **k: called.append(1))
+ assert bootstrap.ensure_local_runtime({"local_runtime": {"enabled": True}}) is None
+ assert called == []
+
+
+ def test_bootstrap_failure_never_raises(tmp_path, monkeypatch):
+ """Session start must survive a broken runtime: failures log + return
+ None, chat falls back to configured providers."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ from hermes_cli.local_runtime import bootstrap
++ from hermes_cli.local_runtime.bootstrap import models_dir
+
+ monkeypatch.setattr(bootstrap, "_SUPERVISOR", None)
+ monkeypatch.setattr(bootstrap, "_detect_gpu_vendor", lambda: None)
++ # Stage a model and an installed engine so boot proceeds far enough to
++ # hit the supervisor constructor, which is what blows up here.
++ models_dir().mkdir(parents=True, exist_ok=True)
++ (models_dir() / "m.gguf").write_bytes(b"x")
++ from pm import paths
++ from pm.lock import Facts
++
++ store = paths.store_root()
++ entry = "llamacpp-cpu-10362-win32-x64"
++ (store / entry).mkdir(parents=True, exist_ok=True)
++ Facts(store / "facts.json").record("llamacpp-cpu", "10362", entry, {}, store)
+
+ def boom(*a, **k):
+ raise RuntimeError("no network")
+
+ monkeypatch.setattr(
- "hermes_cli.local_runtime.binaries.ensure_runtime_installed", boom)
++ "hermes_cli.local_runtime.supervisor.LlamaServerSupervisor", boom)
+ result = bootstrap.ensure_local_runtime({"local_runtime": {"enabled": True}})
+ assert result is None # no exception escaped
++
++
++def test_stop_state_server_uses_pid_exists_not_os_kill(monkeypatch):
++ """Windows pitfall: os.kill(pid, 0) TERMINATES the process there
++ instead of probing. The liveness probe must go through
++ psutil.pid_exists: True (alive) first, then False (exited) — the loop
++ terminates as soon as the pid is gone."""
++ import sys
++ import types
++
++ from hermes_cli.local_runtime import bootstrap as bs
++
++ killed = []
++ monkeypatch.setattr("os.kill", lambda pid, sig: killed.append((pid, sig)))
++
++ calls = {"n": 0}
++
++ def _fake_pid_exists(pid):
++ calls["n"] += 1
++ return calls["n"] <= 2 # alive twice, then gone
++
++ # Inject a stub psutil module rather than monkeypatching the real one:
++ # hermetic, and the real psutil's native DLL may be unavailable in
++ # sandboxed test environments.
++ fake_psutil = types.SimpleNamespace(pid_exists=_fake_pid_exists)
++ monkeypatch.setitem(sys.modules, "psutil", fake_psutil)
++ monkeypatch.setattr(bs.time, "sleep", lambda s: None)
++
++ bs._stop_state_server({"pid": 4242})
++
++ assert killed == [(4242, 15)] # SIGTERM sent once, no os.kill(pid, 0)
++ assert calls["n"] == 3 # loop terminated on the False probe
diff --cc tests/hermes_cli/test_local_runtime_updates.py
index 00000000000,f6f4d43ea22..d49f2b4c3b8
mode 000000,100644..100644
--- a/tests/hermes_cli/test_local_runtime_updates.py
+++ b/tests/hermes_cli/test_local_runtime_updates.py
@@@ -1,0 -1,123 +1,155 @@@
-"""Engine-update contracts (Rollout 4 follow-up):
++"""Engine contracts on the pm pin system (Rollout 4 follow-up):
+
-- default tag flows from DEFAULT_CONFIG unless the user pinned;
++- the pinned build lives in pm/lock.json (engine_version reads it); there
++ is NO user-settable tag in config to disagree with it;
+ - boot serves what is INSTALLED, never downloads (the ladder);
-- update_available only when the local engine is enabled AND installed
- AND the configured tag is missing on disk;
-- the update itself is a button-driven job, and prune keeps N-1.
++- update_available only when the local engine is enabled AND something is
++ installed AND an installed engine is older than the pin;
++- retention is `hermes pm gc`'s call, not one install job's.
+ """
+
+ from __future__ import annotations
+
+ import json
+
+ import pytest
+
+
+ @pytest.fixture
+ def hermes_home(tmp_path, monkeypatch):
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ return home
+
+
-def _install_fake_tag(home, tag: str, backend: str = "cuda") -> None:
- d = home / "runtimes" / "llamacpp" / tag / backend
- d.mkdir(parents=True)
- (d / "manifest.json").write_text(json.dumps({
- "tag": tag, "backend": backend, "assets": {},
- "verified_version": f"version: {tag.lstrip('b')}",
- }), encoding="utf-8")
- # server_binary() looks for the executable name per-OS; give it both.
- (d / "llama-server.exe").write_bytes(b"MZ fake")
- (d / "llama-server").write_bytes(b"\x7fELF fake")
++def _store(hermes_home):
++ """The pm store for this temp home: HERMES_HOME points at the root, so
++ the store is <home>/tools."""
++ from pm import paths
+
++ return paths.store_root()
+
-def test_installed_tags_newest_first(hermes_home):
- from hermes_cli.local_runtime.binaries import installed_tags
+
- assert installed_tags() == []
- _install_fake_tag(hermes_home, "b10290")
- _install_fake_tag(hermes_home, "b10412")
- assert installed_tags() == ["b10412", "b10290"]
++def _install_fake_backend(hermes_home, backend: str, version: str) -> None:
++ """Record an installed engine in pm's facts + store: version is the
++ lockfile tag WITHOUT the b (e.g. "10290"). The fact carries the full
++ digest-bound identity (target + artifact shas) the way a real pm
++ install records it — is_installed() refuses identity-less facts."""
++ from pm.ensure import _identity, _lockfile
++ from pm.lock import Facts
++ from pm.store import current_target
+
++ store = _store(hermes_home)
++ name = {"cuda": "llamacpp-cuda", "cpu": "llamacpp-cpu"}[backend]
++ entry = f"{name}-{version}-win32-x64"
++ (store / entry).mkdir(parents=True, exist_ok=True)
++ facts = Facts(store / "facts.json")
++ lockfile = _lockfile()
++ facts.record(
++ name,
++ version,
++ entry,
++ {},
++ store,
++ target=current_target(),
++ # The FULL pinned artifact list — installed() compares the exact
++ # identity tuple, and a truncated one is a different identity.
++ artifacts=[a["sha256"] for a in lockfile.artifacts(name, current_target())],
++ )
+
-def test_default_tag_flows_from_default_config(hermes_home):
- """Unpinned users inherit the Hermes-release default (deep-merge);
- the shipped default must be a plausible rolling tag."""
- from hermes_cli.config import load_config
++
++def _load_facts(hermes_home):
++ from pm.lock import Facts
++
++ return Facts(_store(hermes_home) / "facts.json")
++
++
++def test_installed_backends_in_ladder_order(hermes_home):
++ from hermes_cli.local_runtime.binaries import installed_backends
++
++ assert installed_backends() == []
++ _install_fake_backend(hermes_home, "cuda", "10362")
++ _install_fake_backend(hermes_home, "cpu", "10362")
++ assert installed_backends() == ["cuda", "cpu"]
++
++
++def test_installed_backends_not_version_gated(hermes_home):
++ """An engine from a previous pin still serves — boot must keep working
++ across a lockfile bump until the user clicks the update."""
++ from hermes_cli.local_runtime.binaries import (
++ engine_update_pending,
++ installed_backends,
++ )
++
++ _install_fake_backend(hermes_home, "cuda", "10290")
++ assert installed_backends() == ["cuda"]
++ assert engine_update_pending() is True # 10290 < pinned 10362
++
++
++def test_no_tag_key_in_config(hermes_home):
++ """The build is pinned in pm/lock.json, not config; a second version
++ authority would only disagree with the pin."""
+ from hermes_cli.config_defaults import DEFAULT_CONFIG
+
- default_tag = DEFAULT_CONFIG["local_runtime"]["tag"]
- assert default_tag.startswith("b") and default_tag.lstrip("b").isdigit()
- assert load_config()["local_runtime"]["tag"] == default_tag
++ assert "tag" not in DEFAULT_CONFIG["local_runtime"]
++
++
++def test_engine_version_reads_the_lockfile(hermes_home):
++ from hermes_cli.local_runtime.binaries import engine_version
++
++ assert engine_version().startswith("b")
++ assert engine_version().lstrip("b").isdigit()
+
+
+ def test_update_available_requires_enabled_and_installed(hermes_home, monkeypatch):
- """The flag's truth table: enabled+installed+configured-missing only."""
++ """The flag's truth table: enabled AND something installed AND an
++ installed engine older than the pin."""
+ from fastapi.testclient import TestClient
+
+ from hermes_cli import web_server
+
+ client = TestClient(web_server.app)
- # Same auth pattern as the other local-models route tests.
+ client.headers[web_server._SESSION_HEADER_NAME] = web_server._SESSION_TOKEN
+
+ def status():
+ r = client.get("/api/local-models/status")
+ assert r.status_code == 200, r.text
+ return r.json()
+
+ import hermes_cli.web_routers.local_models as lm
+
- # Case 1: enabled, configured newer than installed -> update available.
- monkeypatch.setattr(lm, "_runtime_section",
- lambda: {"enabled": True, "tag": "b10412"})
- _install_fake_tag(hermes_home, "b10290")
++ # Case 1: enabled + installed at an older pin -> update available.
++ monkeypatch.setattr(lm, "_runtime_section", lambda: {"enabled": True})
++ _install_fake_backend(hermes_home, "cuda", "10290")
+ s = status()
+ assert s["update_available"] is True
- assert s["configured_tag"] == "b10412"
- assert s["tag"] == "b10290" # serving what's installed
++ assert s["configured_tag"] == "b10362" # the pin
++ assert s["tag"] == "b10290" # serving what's installed
+
- # Case 2: configured tag installed -> no update.
- _install_fake_tag(hermes_home, "b10412")
++ # Case 2: installed at the current pin -> no update.
++ _install_fake_backend(hermes_home, "cuda", "10362")
+ s = status()
+ assert s["update_available"] is False
- assert s["tag"] == "b10412"
++ assert s["tag"] == "b10362"
+
- # Case 3: disabled -> never flagged, even with a mismatch.
- monkeypatch.setattr(lm, "_runtime_section",
- lambda: {"enabled": False, "tag": "b10999"})
++ # Case 3: disabled -> never flagged, even with a stale engine.
++ monkeypatch.setattr(lm, "_runtime_section", lambda: {"enabled": False})
+ assert status()["update_available"] is False
+
+
-def test_boot_never_downloads_missing_tag(hermes_home, monkeypatch):
- """The ladder: configured-but-not-installed serves the newest installed
- tag; nothing installed means no boot (and NO download either way)."""
++def test_boot_never_downloads(hermes_home, monkeypatch):
++ """Boot serves what is INSTALLED; nothing installed means no boot (and
++ NO download either way — installing is a click in the pane)."""
+ from hermes_cli.local_runtime import bootstrap
+
+ calls = []
+ monkeypatch.setattr(
- "hermes_cli.local_runtime.binaries.ensure_runtime_installed",
- lambda tag, backend, **kw: calls.append(tag) or (_ for _ in ()).throw(
- AssertionError("boot must not reach install for missing tags")))
++ "hermes_cli.local_runtime.binaries.ensure_engine",
++ lambda *a, **kw: calls.append(True) or (_ for _ in ()).throw(
++ AssertionError("boot must never install the engine")))
+
+ # Nothing installed: returns None before any install attempt.
- cfg = {"local_runtime": {"enabled": True, "tag": "b10412"}}
++ cfg = {"local_runtime": {"enabled": True}}
+ assert bootstrap.ensure_local_runtime(cfg) is None
+ assert calls == []
-
-
-def test_prune_keeps_n_minus_one(hermes_home):
- from hermes_cli.local_runtime.binaries import installed_tags, prune_old_tags
-
- for tag in ("b10100", "b10200", "b10290"):
- _install_fake_tag(hermes_home, tag)
- prune_old_tags(["b10290", "b10200"])
- assert installed_tags() == ["b10290", "b10200"]
- # downloads/ cache dir must survive pruning when present.
- downloads = hermes_home / "runtimes" / "llamacpp" / "downloads"
- downloads.mkdir(exist_ok=True)
- prune_old_tags(["b10290"])
- assert downloads.exists()
diff --cc tests/hermes_cli/test_runtime_install_progress.py
index 00000000000,da34f19b5c3..e27041864c8
mode 000000,100644..100644
--- a/tests/hermes_cli/test_runtime_install_progress.py
+++ b/tests/hermes_cli/test_runtime_install_progress.py
@@@ -1,0 -1,124 +1,46 @@@
+ """Runtime install progress: the slow legs must tick, never hang silently.
+
+ The incident: 'Installing runtime…' sat frozen for minutes on a slow
-line — ensure_runtime_installed downloaded and extracted with no
-progress stream, so both the quickstart hero and the pane's install row
-showed a dead bar. Contract: _download and _extract tick per chunk /
-per member, ensure_runtime_installed forwards a staged stream, and the
-router's hook translates it into live job fields."""
++line — the old bespoke downloader streamed no progress, so both the
++quickstart hero and the pane's install row showed a dead bar. The engine
++now installs through pm, which streams download -> unpack per artifact;
++this test pins the router hook that translates that stream into live job
++fields. (The pm-side streaming itself is covered in tests/pm/test_pm_core.py.)
++"""
+
+ from __future__ import annotations
+
-import io
-import zipfile
-from pathlib import Path
-
-import hermes_cli.local_runtime.binaries as binaries
+ from hermes_cli.web_routers.local_models import _job, _runtime_progress_hook
+
+
-def _make_zip(path: Path, names_sizes: dict[str, int]) -> None:
- with zipfile.ZipFile(path, "w") as z:
- for name, size in names_sizes.items():
- z.writestr(name, b"x" * size)
-
-
-def test_extract_ticks_per_member(tmp_path):
- archive = tmp_path / "runtime.zip"
- _make_zip(archive, {"a.bin": 1000, "b.bin": 3000, "c.bin": 500})
- ticks: list[tuple[int, int]] = []
- binaries._extract(archive, tmp_path / "out",
- progress=lambda d, t: ticks.append((d, t)))
- assert len(ticks) == 3
- total = 4500
- assert all(t == total for _, t in ticks)
- assert [d for d, _ in ticks] == sorted(d for d, _ in ticks)
- assert ticks[-1][0] == total
- assert (tmp_path / "out" / "b.bin").stat().st_size == 3000
-
-
-def test_download_ticks_with_content_length(tmp_path, monkeypatch):
- payload = b"y" * (3 << 20) # 3 MiB -> several 1 MiB chunks
-
- class _Resp(io.BytesIO):
- headers = {"Content-Length": str(len(payload))}
-
- def __enter__(self):
- return self
-
- def __exit__(self, *a):
- return False
-
- monkeypatch.setattr(binaries.urllib.request, "urlopen",
- lambda url, timeout=0: _Resp(payload))
- ticks: list[tuple[int, int]] = []
- dest = tmp_path / "asset.zip"
- binaries._download("http://x/asset.zip", dest,
- progress=lambda d, t: ticks.append((d, t)))
- assert dest.read_bytes() == payload
- assert len(ticks) >= 3
- assert ticks[-1] == (len(payload), len(payload))
-
-
-def test_ensure_runtime_installed_forwards_staged_progress(tmp_path, monkeypatch):
- """The full install path emits download -> verify -> extract stages
- (per asset) and a final verify, all through one callback."""
- monkeypatch.setattr(binaries, "runtimes_root", lambda: tmp_path)
-
- class _Plan:
- assets = ["a.zip", "b.zip"]
- backend = "cuda"
- install_dir = tmp_path / "b1" / "cuda"
-
- monkeypatch.setattr(binaries, "resolve_assets", lambda tag, backend: _Plan())
- monkeypatch.setattr(binaries, "verify_install", lambda d, t: "ok")
-
- def _fake_download(url, dest, progress=None):
- _make_zip(dest, {"f.bin": 2048})
- if progress is not None:
- progress(1024, 2048)
- progress(2048, 2048)
-
- monkeypatch.setattr(binaries, "_download", _fake_download)
-
- events: list[tuple[str, str]] = []
- binaries.ensure_runtime_installed(
- "b1", "cuda",
- progress=lambda stage, d, t, label: events.append((stage, label)))
-
- stages = [s for s, _ in events]
- assert "download" in stages and "extract" in stages and "verify" in stages
- # Two assets -> per-asset labels on the slow stages.
- assert ("download", "1/2") in events and ("download", "2/2") in events
- assert ("extract", "1/2") in events and ("extract", "2/2") in events
- # Stage order per asset: download before extract.
- assert stages.index("download") < stages.index("extract")
-
-
+ def test_progress_hook_translates_stages_to_job_fields():
+ job = _job("quickstart", "Test Model")
+ hook = _runtime_progress_hook(job)
+
+ hook("download", 5 << 20, 100 << 20, "1/2")
+ assert job["phase"] == "downloading-runtime"
+ assert "1/2" in job["detail"]
+ assert job["done_bytes"] == 5 << 20
+ assert job["total_bytes"] == 100 << 20
+
+ # Rapid second tick inside the throttle window is dropped...
+ hook("download", 6 << 20, 100 << 20, "1/2")
+ assert job["done_bytes"] == 5 << 20
+ # ...but a terminal tick (done == total) always lands.
+ hook("download", 100 << 20, 100 << 20, "1/2")
+ assert job["done_bytes"] == 100 << 20
+
- hook("extract", 10, 100, "")
- assert job["phase"] in ("downloading-runtime", "unpacking-runtime")
++ # pm's unpack stage maps to the unpacking phase. (Terminal tick: the
++ # throttle drops non-terminal updates inside its window.)
++ hook("unpack", 100, 100, "2/2")
++ assert job["phase"] == "unpacking-runtime"
++ assert "2/2" in job["detail"]
+
++ # An indeterminate download (no Content-Length -> total 0) must not
++ # read as a stuck 0% bar.
+ job2 = _job("runtime-install", "x")
+ hook2 = _runtime_progress_hook(job2)
- hook2("extract", 100, 100, "")
- assert job2["phase"] == "unpacking-runtime"
- hook2("verify", 0, 0, "")
- assert job2["phase"] == "verifying-runtime"
- assert job2["total_bytes"] is None # indeterminate bar, not a stuck 0%
++ hook2("download", 4 << 20, 0, "")
++ assert job2["phase"] == "downloading-runtime"
++ assert job2["total_bytes"] is None
++ assert job2["done_bytes"] == 4 << 20
diff --cc tests/pm/test_pm_authority.py
index 135c83a4443,00000000000..432f9a07408
mode 100644,000000..100644
--- a/tests/pm/test_pm_authority.py
+++ b/tests/pm/test_pm_authority.py
@@@ -1,419 -1,0 +1,453 @@@
+"""pm authority spine: digest-bound facts, tree_digest + doctor re-hash,
+adopt() verification gate, repair logging.
+
+Same conventions as test_pm_core: real loopback server, real archives,
+real store — no mocked stores. Assertions are relationships (identity
+matches lock, digest matches bytes), not snapshots."""
+
+from __future__ import annotations
+
+import hashlib
+import io
+import json
+import logging
+import shutil
+import tarfile
+import threading
+from functools import partial
+from http.server import HTTPServer, SimpleHTTPRequestHandler
+from pathlib import Path
+
+import pytest
+
+import pm.paths as paths
+import pm.registry as registry
+from pm.lock import Facts, Lockfile
+from pm.package import Package
+from pm.packages import BinaryPackage
+from pm.store import Store, current_target, tree_digest
+
+
+class FakeTool(BinaryPackage):
+ name = "faketool"
+ probe_version = False
+ binary_rel = {"win32": "bin/faketool", "posix": "bin/faketool"}
+
+ def fetch_url(self, version, target):
+ return f"{FakeTool.base_url}/{self.name}-{version}.tar.gz"
+
+
+def make_tar(docroot: Path, name: str, files: dict[str, str]) -> tuple[str, str]:
+ buf = io.BytesIO()
+ with tarfile.open(fileobj=buf, mode="w:gz") as tf:
+ for rel, content in files.items():
+ data = content.encode()
+ info = tarfile.TarInfo(rel)
+ info.size = len(data)
+ info.mode = 0o755
+ tf.addfile(info, io.BytesIO(data))
+ payload = buf.getvalue()
+ (docroot / name).write_bytes(payload)
+ return name, hashlib.sha256(payload).hexdigest()
+
+
+def served(tmp_path):
+ docroot = tmp_path / "www"
+ docroot.mkdir()
+ handler = partial(SimpleHTTPRequestHandler, directory=str(docroot))
+ server = HTTPServer(("127.0.0.1", 0), handler)
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ yield docroot, f"http://127.0.0.1:{server.server_port}"
+ server.shutdown()
+
+
+def pm_env(tmp_path, served, monkeypatch):
+ docroot, base_url = served
+ runtime = tmp_path / "runtime"
+ monkeypatch.setenv("HERMES_RUNTIME_DIR", str(runtime))
+ monkeypatch.delenv("HERMES_DISABLE_LAZY_INSTALLS", raising=False)
+ import importlib
+
+ ensure_mod = importlib.import_module("pm.ensure")
+ monkeypatch.setattr(ensure_mod, "lazy_installs_allowed", lambda: True)
+ paths._stamp.cache_clear()
+
+ saved = dict(registry._packages)
+ registry._packages.clear()
+ registry._packages[FakeTool.name] = FakeTool()
+ FakeTool.base_url = base_url
+
+ lock_dir = tmp_path / "repo-lock"
+ lock_dir.mkdir()
+ lockfile_path = lock_dir / "lock.json"
+ monkeypatch.setattr(paths, "lockfile_path", lambda: lockfile_path)
+
+ name, digest = make_tar(docroot, "faketool-1.0.tar.gz", {"bin/faketool": "#!x"})
+ lockfile = Lockfile(lockfile_path)
+ lockfile.set_pin(
+ "faketool", "1.0",
+ {"any": {"url": f"{base_url}/faketool-1.0.tar.gz", "sha256": digest}},
+ )
+ lockfile.save()
+
+ yield {
+ "lockfile_path": lockfile_path,
+ "runtime": runtime,
+ "docroot": docroot,
+ "base_url": base_url,
+ "digest": digest,
+ "tmp_path": tmp_path,
+ "monkeypatch": monkeypatch,
+ }
+
+ registry._packages.clear()
+ registry._packages.update(saved)
+
+
+def _pin(env, name: str, version: str, digest: str) -> None:
+ lockfile = Lockfile(env["lockfile_path"])
+ url = f"{env['base_url']}/{name}-{version}.tar.gz"
+ lockfile.set_pin(name, version, {"any": {"url": url, "sha256": digest}})
+ lockfile.save()
+
+
+# ── item 1: digest-bound facts ────────────────────────────────────────
+
+
+def test_same_version_different_sha_is_not_installed_and_repaired(pm_env):
+ """The witness: same version, different artifact sha. Version/path
+ matching cannot see this; identity matching must — check() reports
+ it and ensure() replaces the entry bytes."""
+ from pm.ensure import check, ensure, is_installed
+
+ env = pm_env
+ ensure("faketool", base_env={})
+ assert is_installed("faketool")
+
+ _, digest_b = make_tar(env["docroot"], "faketool-1.0-b.tar.gz", {"bin/faketool": "#!B"})
+ # Same VERSION, different archive (different url + sha) — the
+ # version-only check would accept this re-pin.
+ lockfile = Lockfile(env["lockfile_path"])
+ lockfile.set_pin(
+ "faketool", "1.0",
+ {"any": {"url": f"{env['base_url']}/faketool-1.0-b.tar.gz", "sha256": digest_b}},
+ )
+ lockfile.save()
+ assert not is_installed("faketool")
+ assert check() == ["faketool: not installed or outdated"]
+
+ runner = ensure("faketool", base_env={})
+ assert is_installed("faketool")
+ fact = Facts(paths.facts_path()).get("faketool")
+ entry_bin = paths.store_root() / fact["entry"] / "bin" / "faketool"
+ with open(entry_bin, "rb") as f:
+ assert f.read() == b"#!B"
+
+ # The fact now binds the new identity, not the old one.
+ fact = Facts(paths.facts_path()).get("faketool")
+ assert fact["target"] == current_target()
+ assert fact["artifacts"] == [digest_b]
+
+
+def test_poisoned_fetch_cache_is_redownloaded(pm_env):
+ """The fetch cache is keyed on the FULL sha and re-hashed before it is
+ trusted; poisoned bytes are deleted and re-downloaded."""
+ env = pm_env
+ runtime = env["runtime"]
+ store = Store(runtime / "scratch-store")
+ url = f"{env['base_url']}/faketool-1.0.tar.gz"
+ digest = env["digest"]
+
+ first = store.fetch(url, digest, runtime / "scratch-store")
+ assert sha_of(first) == digest
+
+ # Poison the cached entry: same name, wrong bytes.
+ with open(first, "wb") as f:
+ f.write(b"poisoned")
+
+ second = store.fetch(url, digest, runtime / "scratch-store")
+ assert sha_of(second) == digest
+
+
+def sha_of(path: Path) -> str:
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def test_legacy_fact_without_identity_is_not_installed(pm_env):
+ """Facts written before identity existed read back fine but are NOT
+ vouchable: installed() with identity returns False and forces one
+ reinstall."""
+ from pm.ensure import ensure, is_installed
+
+ env = pm_env
+ ensure("faketool", base_env={})
+
+ facts_path = paths.facts_path()
+ data = json.loads(facts_path.read_text(encoding="utf-8"))
+ data["packages"]["faketool"] = {
+ "entry": data["packages"]["faketool"]["entry"],
+ "version": "1.0",
+ "env": data["packages"]["faketool"]["env"],
+ }
+ facts_path.write_text(json.dumps(data), encoding="utf-8")
+
+ assert not is_installed("faketool")
+ # ensure() repairs it: reinstalls and records the full identity.
+ ensure("faketool", base_env={})
+ assert is_installed("faketool")
+ fact = Facts(paths.facts_path()).get("faketool")
+ assert fact["artifacts"] == [env["digest"]]
+
+
+def test_doctor_flags_legacy_fact(pm_env, capsys):
+ from pm.cli import cmd_doctor
+ from pm.ensure import ensure
+
+ env = pm_env
+ ensure("faketool", base_env={})
+ facts_path = paths.facts_path()
+ data = json.loads(facts_path.read_text(encoding="utf-8"))
+ for key in ("target", "artifacts", "digest"):
+ data["packages"]["faketool"].pop(key, None)
+ facts_path.write_text(json.dumps(data), encoding="utf-8")
+
+ assert cmd_doctor(None) == 1
+ assert "legacy fact: no recorded identity" in capsys.readouterr().out
+
+
+# ── item 2: realized digest + doctor re-hash ──────────────────────────
+
+
+def test_tree_digest_is_content_bound(pm_env):
+ """Same content in different creation order digests identically; one
+ changed byte digests differently; a symlink contributes its link
+ TARGET TEXT, not the target's bytes."""
+ import os
+
+ a = pm_env["tmp_path"] / "tree-a"
+ b = pm_env["tmp_path"] / "tree-b"
+ (a / "sub").mkdir(parents=True)
+ (b / "sub").mkdir(parents=True)
+ (a / "sub" / "f.txt").write_text("hello")
+ (b / "sub" / "f.txt").write_text("hello")
+ (a / "top.txt").write_text("t")
+ (b / "top.txt").write_text("t")
+ assert tree_digest(a) == tree_digest(b)
+
+ (b / "top.txt").write_text("u")
+ assert tree_digest(a) != tree_digest(b)
+
+ # Symlink: link text is the data — retargeting changes the digest
+ # even though the pointed-at bytes never change.
+ (a / "sub" / "f.txt").write_text("hello")
+ try:
+ (b / "link").symlink_to("sub/f.txt")
+ d1 = tree_digest(b)
+ (b / "link").unlink()
+ (b / "link").symlink_to("top.txt")
+ assert tree_digest(b) != d1
+ except OSError:
+ pytest.skip("symlinks unavailable on this host")
+
+
+def test_doctor_flags_tampered_entry_bytes(pm_env, capsys):
+ """Post-install tampering: doctor re-hashes the realized tree against
+ the recorded digest and flags it; restoring the bytes clears it."""
+ from pm.cli import cmd_doctor
+ from pm.ensure import ensure
+
+ env = pm_env
+ ensure("faketool", base_env={})
+ assert cmd_doctor(None) == 0
+
+ fact = Facts(paths.facts_path()).get("faketool")
+ binary = paths.store_root() / fact["entry"] / "bin" / "faketool"
+ original = binary.read_bytes()
+ binary.write_bytes(original + b"tampered")
+ assert cmd_doctor(None) == 1
+ assert "realized bytes do not match recorded digest" in capsys.readouterr().out
+
+ binary.write_bytes(original)
+ assert cmd_doctor(None) == 0
+
+
+# ── item 4: adopt() verification gate ─────────────────────────────────
+
+
+def _bundle_payload(env) -> Path:
+ """Build a shipped payload the way cmd_bundle lays it out: a repo
+ snapshot carrying pm/lock.json, and a store whose facts.json holds
+ the installed state. adopt()'s paths point here via repo_root."""
+ from pm.ensure import ensure
+
+ monkeypatch = env["monkeypatch"]
+ tmp_path = env["tmp_path"]
+ shipped_repo = tmp_path / "shipped-repo"
+ (shipped_repo / "pm").mkdir(parents=True)
+ shutil.copy(env["lockfile_path"], shipped_repo / "pm" / "lock.json")
+ monkeypatch.setattr(paths, "repo_root", lambda: shipped_repo)
+ ensure("faketool", base_env={})
+ return shipped_repo
+
+
+def test_adopt_adopts_intact_payload(pm_env):
+ from pm.ensure import adopt
+
+ _bundle_payload(pm_env)
+ marker = paths.store_root().parent / ".adopted"
+ assert not marker.is_file()
+ assert adopt() is True
+ assert marker.is_file()
+ # Idempotent: already adopted → False, marker untouched.
+ assert adopt() is False
+
+
+def test_adopt_refuses_on_missing_staged_binary(pm_env):
+ from pm.ensure import adopt
+
+ _bundle_payload(pm_env)
+ fact = Facts(paths.facts_path()).get("faketool")
+ binary = paths.store_root() / fact["entry"] / "bin" / "faketool"
+ binary.unlink()
+
+ marker = paths.store_root().parent / ".adopted"
+ assert adopt() is False
+ assert not marker.is_file()
+
+
+def test_adopt_refuses_on_tampered_staged_binary(pm_env):
+ """The adversarial witness: bytes substituted AFTER install fail even
+ though facts + lock still agree — the digest is computed over the
+ actual bytes, not read from the manifest."""
+ from pm.ensure import adopt
+
+ _bundle_payload(pm_env)
+ fact = Facts(paths.facts_path()).get("faketool")
+ binary = paths.store_root() / fact["entry"] / "bin" / "faketool"
+ binary.write_bytes(b"#!substituted")
+
+ marker = paths.store_root().parent / ".adopted"
+ assert adopt() is False
+ assert not marker.is_file()
+
+
+def test_adopt_refuses_when_fact_lacks_identity(pm_env):
+ from pm.ensure import adopt
+
+ _bundle_payload(pm_env)
+ facts_path = paths.facts_path()
+ data = json.loads(facts_path.read_text(encoding="utf-8"))
+ for key in ("target", "artifacts", "digest"):
+ data["packages"]["faketool"].pop(key, None)
+ facts_path.write_text(json.dumps(data), encoding="utf-8")
+
+ assert adopt() is False
+ assert not (paths.store_root().parent / ".adopted").is_file()
+
+
+# ── item 6: repair logging ────────────────────────────────────────────
+
+
+def test_gc_protects_in_flight_partials(pm_env):
+ """gc sweeps the store root, but partials an in-flight download still
+ owns (fresh mtimes) survive; stale partials are swept."""
+ from pm.cli import cmd_gc
+
+ env = pm_env
+ runtime = env["runtime"]
+ runtime.mkdir(parents=True, exist_ok=True)
+ partials = runtime / "partials"
+ partials.mkdir()
+ fresh = partials / "abc.part"
+ fresh.write_bytes(b"x")
+ stale = partials / "old.part"
+ stale.write_bytes(b"y")
+ import os
+ import time
+
+ old = time.time() - 7 * 3600 # beyond the 6h gc grace window
+ os.utime(stale, (old, old))
+
+ orphan = runtime / "orphan-9.9-nowhere"
+ orphan.mkdir()
+
+ cmd_gc(None)
+ assert fresh.is_file()
+ assert not stale.exists()
+ assert not orphan.exists()
+
+
+def test_repair_log_line_on_reinstall(pm_env, caplog):
+ """Established fact + missing entry + ensure() → one repair log line,
+ and the install completes."""
+ from pm.ensure import ensure, is_installed
+
+ env = pm_env
+ ensure("faketool", base_env={})
+
+ fact = Facts(paths.facts_path()).get("faketool")
+ shutil.rmtree(paths.store_root() / fact["entry"])
+
+ with caplog.at_level(logging.INFO, logger="pm.ensure"):
+ ensure("faketool", base_env={})
+ assert is_installed("faketool")
+ repairs = [r for r in caplog.records if "repair:" in r.getMessage()]
+ assert any(
+ "repair: faketool re-realized" in r.getMessage() for r in repairs
+ )
+
+
+def test_repair_log_line_on_same_version_repin(pm_env, caplog):
+ from pm.ensure import ensure
+
+ env = pm_env
+ ensure("faketool", base_env={})
+ _, digest_b = make_tar(env["docroot"], "faketool-1.0-b.tar.gz", {"bin/faketool": "#!B"})
+ lockfile = Lockfile(env["lockfile_path"])
+ lockfile.set_pin(
+ "faketool", "1.0",
+ {"any": {"url": f"{env['base_url']}/faketool-1.0-b.tar.gz", "sha256": digest_b}},
+ )
+ lockfile.save()
+
+ with caplog.at_level(logging.INFO, logger="pm.ensure"):
+ ensure("faketool", base_env={})
+ repairs = [r.getMessage() for r in caplog.records if "repair:" in r.getMessage()]
+ assert any("1.0" in msg and env["digest"][:12] in msg for msg in repairs)
++
++
++def test_tree_digest_ignores_pycache(pm_env, monkeypatch):
++ """Bytecode caches are runtime state, not package bytes: the staged
++ python entry runs (uv venv/uv sync in a bundle build, first boot of a
++ shipped app) and CPython writes __pycache__/*.pyc into it AFTER the
++ digest was recorded. The digest must stay stable across that, while
++ tampering a REAL file inside a dir that merely sits beside a
++ __pycache__ is still caught. (Live field failure: '✗ python: realized
++ bytes do not match recorded digest' on every bundled-release smoke.)"""
++ tree = pm_env["tmp_path"] / "py-entry"
++ (tree / "Lib").mkdir(parents=True)
++ (tree / "Lib" / "os.py").write_text("print('stdlib')")
++
++ before = tree_digest(tree)
++
++ # The interpreter "ran": pyc caches appeared deep in the tree.
++ cache = tree / "Lib" / "__pycache__"
++ cache.mkdir()
++ (cache / "os.cpython-311.pyc").write_bytes(b"\x00compiled-bytes\x00")
++ nested = tree / "Lib" / "json" / "__pycache__"
++ nested.mkdir(parents=True)
++ (nested / "tool.cpython-311.pyc").write_bytes(b"\x00more\x00")
++
++ assert tree_digest(tree) == before
++
++ # A cache write is not a mask: changing a real .py still trips the digest.
++ (tree / "Lib" / "os.py").write_text("print('tampered')")
++ assert tree_digest(tree) != before
++
++ # Restoring the .py (leaving the caches) restores the digest: caches
++ # contribute nothing in either direction.
++ (tree / "Lib" / "os.py").write_text("print('stdlib')")
++ assert tree_digest(tree) == before
diff --cc tests/pm/test_venv_sync_ambient_config.py
index 00000000000,00000000000..6e97c821151
new file mode 100644
--- /dev/null
+++ b/tests/pm/test_venv_sync_ambient_config.py
@@@ -1,0 -1,0 +1,135 @@@
++"""Desired behavior: ambient user uv configuration must not affect pm's
++venv sync, while the project's own [tool.uv] settings stay honored.
++
++This is the contract the installers' old run_locked_uv_sync() used to
++guarantee (#82446, #21269, #83914). Now that install.sh / install.ps1
++delegate to ``python -m pm.cli install``, the contract lives in pm's
++venv-sync env. We assert the behavior (a locked project sync succeeds
++under pm's env even when the ambient environment is poisoned), not the
++names of helper functions.
++
++The negative control is the load-bearing half: the same poisoned ambient
++env fed to uv RAW must break the sync — otherwise the test could pass for
++the wrong reason and never catch a regression.
++"""
++
++from __future__ import annotations
++
++import os
++import shutil
++import subprocess
++from pathlib import Path
++
++import pytest
++
++
++def _write_project(root: Path) -> None:
++ """A project whose [tool.uv] the lock depends on: hide it and uv
++ rejects the lock (the #82446 shape)."""
++ (root / "pyproject.toml").write_text(
++ """[project]
++name = "venv-sync-regression"
++version = "0.1.0"
++requires-python = ">=3.11"
++
++[project.optional-dependencies]
++all = []
++
++[tool.uv]
++package = false
++exclude-newer = "14 days"
++""",
++ encoding="utf-8",
++ )
++
++
++def real_uv() -> str:
++ uv = shutil.which("uv")
++ if uv is None:
++ pytest.skip("uv is unavailable")
++ return uv
++
++
++def locked_project(real_uv, tmp_path: Path) -> Path:
++ """A temp project with a lock generated in a clean ambient env."""
++ project = tmp_path / "project"
++ project.mkdir()
++ _write_project(project)
++ clean = os.environ.copy()
++ for key in ("UV_NO_CONFIG", "UV_CONFIG_FILE", "UV_DEFAULT_INDEX", "XDG_CONFIG_HOME", "XDG_CONFIG_DIRS"):
++ clean.pop(key, None)
++ clean["UV_OFFLINE"] = "1"
++ locked = subprocess.run(
++ [real_uv, "lock"], cwd=project, env=clean,
++ capture_output=True, text=True, check=False,
++ )
++ assert locked.returncode == 0, locked.stderr
++ return project
++
++
++def _poisoned_env() -> dict:
++ env = os.environ.copy()
++ env["UV_NO_CONFIG"] = "1"
++ env["UV_CONFIG_FILE"] = "/poison/uv.toml"
++ # A hostile index: resolution against it can only fail, so if it ever
++ # reaches uv the sync is observably broken.
++ env["UV_DEFAULT_INDEX"] = "https://poison.invalid/simple"
++ env["XDG_CONFIG_HOME"] = "/poison/user"
++ env["XDG_CONFIG_DIRS"] = "/poison/system"
++ return env
++
++
++def test_ambient_uv_config_does_not_affect_pm_venv_sync(real_uv, locked_project, monkeypatch):
++ """Poison the ambient env, then sync through pm's venv-sync env. The
++ sync must succeed with the project's [tool.uv] honored — identical to
++ the clean-env outcome."""
++ poisoned = _poisoned_env()
++ monkeypatch.setenv("UV_NO_CONFIG", "1")
++ monkeypatch.setenv("UV_CONFIG_FILE", "/poison/uv.toml")
++ monkeypatch.setenv("UV_DEFAULT_INDEX", "https://poison.invalid/simple")
++
++ # Negative control: uv with the RAW poisoned ambient env rejects the
++ # lock (project config hidden by UV_NO_CONFIG). Proves the poison is a
++ # real threat the test would catch.
++ raw = subprocess.run(
++ [real_uv, "lock", "--check"], cwd=locked_project,
++ env=poisoned, capture_output=True, text=True, check=False,
++ )
++ assert raw.returncode != 0, "negative control: raw poisoned env must fail"
++
++ # Behavior: pm's venv-sync env makes the ambient config a no-op.
++ from pm.packages import uv_env
++
++ env = uv_env(base_env=poisoned)
++ # The venv-sync shape restores project-config visibility (pm_uv with a
++ # venv pops UV_NO_CONFIG); XDG config discovery is isolated to an
++ # empty dir so ambient uv.toml can't steer either.
++ env.pop("UV_NO_CONFIG", None)
++ assert env.get("XDG_CONFIG_HOME") not in ("/poison/user", None)
++
++ with_pm = subprocess.run(
++ [real_uv, "lock", "--check"], cwd=locked_project,
++ env=env, capture_output=True, text=True, check=False,
++ )
++ assert with_pm.returncode == 0, with_pm.stderr
++
++
++def test_uv_env_strips_ambient_uv_overrides(monkeypatch):
++ """The env pm hands uv carries none of the ambient UV_* overrides."""
++ monkeypatch.setenv("UV_NO_CONFIG", "1")
++ monkeypatch.setenv("UV_CONFIG_FILE", "/poison/uv.toml")
++ monkeypatch.setenv("UV_DEFAULT_INDEX", "https://poison.invalid/simple")
++ monkeypatch.setenv("XDG_CONFIG_HOME", "/poison/user")
++ monkeypatch.setenv("XDG_CONFIG_DIRS", "/poison/system")
++
++ from pm.packages import uv_env
++
++ env = uv_env()
++ assert "UV_NO_CONFIG" in env # hermetic default for non-project calls
++ assert "UV_CONFIG_FILE" not in env
++ assert "UV_DEFAULT_INDEX" not in env
++ # Config discovery is redirected off the ambient dirs.
++ assert env.get("XDG_CONFIG_HOME") not in ("/poison/user", None)
++ assert env.get("XDG_CONFIG_DIRS") not in ("/poison/system", None)
diff --cc tests/test_install_sh_uv_lock_config.py
index dfa20a7429b,59d5bba96da..00000000000
deleted file mode 100644,100644
--- a/tests/test_install_sh_uv_lock_config.py
+++ /dev/null
@@@ -1,175 -1,179 +1,0 @@@
--"""Regression coverage for project-aware locked syncs in Unix installers."""
--
--from __future__ import annotations
--
--import os
--from pathlib import Path
--import shutil
--import subprocess
--
--import pytest
--
--
--REPO_ROOT = Path(__file__).resolve().parent.parent
--INSTALL_SCRIPTS = (
-- REPO_ROOT / "scripts" / "install.sh",
- REPO_ROOT / "setup-hermes.sh",
--)
- # setup-hermes.sh no longer runs uv sync itself: it delegates to
- # `python -m pm.cli install` (hash-verified via pm + uv.lock), so the
- # locked-sync helper contract below applies to scripts/install.sh only.
--_HELPER_START = "run_locked_uv_sync() {\n"
--
--
--def _locked_sync_helper(path: Path) -> str:
-- text = path.read_text(encoding="utf-8")
-- _, marker, rest = text.partition(_HELPER_START)
-- assert marker, f"{path.name} is missing run_locked_uv_sync()"
-- body, end, _ = rest.partition("\n}\n")
-- assert end, f"{path.name} has an unterminated run_locked_uv_sync()"
-- return marker + body + end
--
--
--def _bash_path(path: Path) -> str:
-- if os.name != "nt":
-- return str(path)
-- drive = path.drive.rstrip(":").lower()
-- tail = path.as_posix().split(":", 1)[1].lstrip("/")
-- return f"/mnt/{drive}/{tail}"
--
--
--def test_installers_keep_bootstrap_isolation_but_restore_project_config_for_lock() -> None:
-- install_text = INSTALL_SCRIPTS[0].read_text(encoding="utf-8")
- setup_text = INSTALL_SCRIPTS[1].read_text(encoding="utf-8")
--
-- assert "export UV_NO_CONFIG=1" in install_text
- assert "export UV_NO_CONFIG=1" in setup_text
- assert _locked_sync_helper(INSTALL_SCRIPTS[0]) == _locked_sync_helper(
- INSTALL_SCRIPTS[1]
- )
--
-- helper = _locked_sync_helper(INSTALL_SCRIPTS[0])
-- assert "unset UV_NO_CONFIG UV_CONFIG_FILE" in helper
-- assert 'export XDG_CONFIG_HOME="$isolated_uv_config"' in helper
-- assert 'export XDG_CONFIG_DIRS="$isolated_uv_config"' in helper
-- assert "$UV_CMD sync --extra all --locked" in helper
-- assert 'run_locked_uv_sync "$INSTALL_DIR/venv"' in install_text
- assert 'run_locked_uv_sync "$SCRIPT_DIR/venv"' in setup_text
--
--
--def test_locked_sync_helper_sanitizes_only_its_subprocess(tmp_path: Path) -> None:
-- bash = shutil.which("bash")
-- if bash is None:
-- pytest.skip("bash is unavailable")
--
-- record = tmp_path / "uv-args.txt"
-- fake_uv = tmp_path / "uv"
-- fake_uv.write_text(
-- """#!/bin/sh
--test -z "${UV_NO_CONFIG+x}" || exit 10
--test -z "${UV_CONFIG_FILE+x}" || exit 11
--test -d "$XDG_CONFIG_HOME" || exit 12
--test "$XDG_CONFIG_HOME" = "$XDG_CONFIG_DIRS" || exit 13
--printf '%s\n' "$@" > "$RECORD"
--""",
-- encoding="utf-8",
-- newline="\n",
-- )
--
-- harness = tmp_path / "harness.sh"
-- harness.write_text(
-- """#!/bin/bash
--set -eu
--UV_CMD="sh $1"
--RECORD="$2"
--export UV_CMD RECORD
--export UV_NO_CONFIG=1
--export UV_CONFIG_FILE=/poison/uv.toml
--export XDG_CONFIG_HOME=/poison/user
--export XDG_CONFIG_DIRS=/poison/system
--"""
-- + _locked_sync_helper(INSTALL_SCRIPTS[0])
-- + """
--run_locked_uv_sync /tmp/hermes-venv
--test "$UV_NO_CONFIG" = 1
--test "$UV_CONFIG_FILE" = /poison/uv.toml
--test "$XDG_CONFIG_HOME" = /poison/user
--test "$XDG_CONFIG_DIRS" = /poison/system
--""",
-- encoding="utf-8",
-- newline="\n",
-- )
--
-- result = subprocess.run(
-- [bash, _bash_path(harness), _bash_path(fake_uv), _bash_path(record)],
-- capture_output=True,
-- text=True,
-- check=False,
-- )
--
-- assert result.returncode == 0, result.stderr
-- assert record.read_text(encoding="utf-8").splitlines() == [
-- "sync",
-- "--extra",
-- "all",
-- "--locked",
-- ]
--
--
[email protected](os.name == "nt", reason="Unix installer behavior")
--def test_real_uv_accepts_lock_when_project_config_is_restored(tmp_path: Path) -> None:
-- uv = shutil.which("uv")
-- if uv is None:
-- pytest.skip("uv is unavailable")
--
-- project = tmp_path / "project"
-- project.mkdir()
-- (project / "pyproject.toml").write_text(
-- """[project]
--name = "installer-lock-regression"
--version = "0.1.0"
--requires-python = ">=3.11"
--
--[project.optional-dependencies]
--all = []
--
--[tool.uv]
--package = false
--exclude-newer = "14 days"
--""",
-- encoding="utf-8",
-- )
--
-- isolated_config = tmp_path / "isolated-config"
-- isolated_config.mkdir()
-- clean_env = os.environ.copy()
-- clean_env.pop("UV_NO_CONFIG", None)
-- clean_env.pop("UV_CONFIG_FILE", None)
-- clean_env["XDG_CONFIG_HOME"] = str(isolated_config)
-- clean_env["XDG_CONFIG_DIRS"] = str(isolated_config)
-- clean_env["UV_OFFLINE"] = "1"
--
-- locked = subprocess.run(
-- [uv, "lock"],
-- cwd=project,
-- env=clean_env,
-- capture_output=True,
-- text=True,
-- check=False,
-- )
-- assert locked.returncode == 0, locked.stderr
--
-- hidden_config_env = clean_env.copy()
-- hidden_config_env["UV_NO_CONFIG"] = "1"
-- rejected = subprocess.run(
-- [uv, "lock", "--check"],
-- cwd=project,
-- env=hidden_config_env,
-- capture_output=True,
-- text=True,
-- check=False,
-- )
-- assert rejected.returncode != 0
--
-- accepted = subprocess.run(
-- [uv, "lock", "--check"],
-- cwd=project,
-- env=clean_env,
-- capture_output=True,
-- text=True,
-- check=False,
-- )
-- assert accepted.returncode == 0, accepted.stderr
diff --cc tests/test_installers_delegate_to_pm.py
index 00000000000,00000000000..79c5fccfaed
new file mode 100644
--- /dev/null
+++ b/tests/test_installers_delegate_to_pm.py
@@@ -1,0 -1,0 +1,49 @@@
++"""Desired behavior: the installers delegate the python/venv/tools install
++to pm, and keep the bootstrap config hygiene, instead of hand-rolling a
++`uv sync`. The ambient-config-doesn't-affect-uv contract itself is tested
++behaviorally at the pm layer (tests/pm/test_venv_sync_ambient_config.py);
++these assertions only pin the delegation shape so a future edit can't
++silently reintroduce a second uv-sync path.
++
++The installer scripts are fetched standalone (`curl | sh`, `irm | iex`)
++before any checkout exists, so this is a static guard on the shipped
++bytes — the same approach test_bootstrap_pins_fragment.py takes.
++"""
++
++from __future__ import annotations
++
++from pathlib import Path
++
++import pytest
++
++
++REPO_ROOT = Path(__file__).resolve().parent.parent
++INSTALL_SH = REPO_ROOT / "scripts" / "install.sh"
++INSTALL_PS1 = REPO_ROOT / "scripts" / "install.ps1"
++
++
++def test_installers_delegate_to_pm_cli() -> None:
++ """The single install authority is `python -m pm.cli install`; the
++ installers must forward to it rather than run `uv sync` themselves."""
++ for path in (INSTALL_SH, INSTALL_PS1):
++ text = path.read_text(encoding="utf-8")
++ assert "python -m pm.cli install" in text, f"{path.name}: missing pm delegation"
++ # A raw project sync must not reappear as an INVOCATION in the
++ # installers — pm owns it. (Comments may mention the words; the
++ # command shape is what we ban.)
++ for banned in ('uv sync --', 'uv sync -', '"$UV_CMD" sync', '& $uv sync'):
++ assert banned not in text, f"{path.name}: hand-rolled uv sync reappeared ({banned!r})"
++
++
++def test_install_sh_keeps_bootstrap_config_hygiene() -> None:
++ """#21269: the bootstrap uv call stays isolated from ambient config."""
++ text = INSTALL_SH.read_text(encoding="utf-8")
++ assert "export UV_NO_CONFIG=1" in text
++
++
[email protected]("path", [INSTALL_SH, INSTALL_PS1])
++def test_installers_still_create_the_venv_stage(path: Path) -> None:
++ """pm's sync targets the venv dir the installer creates; the stage must
++ survive (Hermes-Setup's manifest lists it)."""
++ text = path.read_text(encoding="utf-8")
++ assert "venv" in text # both keep a venv-creating stage / delegate to pm
diff --cc tools/browser_tool.py
index cd3ddf72923,866f8bb78dd..3303500213c
--- a/tools/browser_tool.py
+++ b/tools/browser_tool.py
@@@ -1632,9 -1675,110 +1656,110 @@@ def _real_profile_cdp() -> tuple
return None, f"browser.use_real_profile is on, but {err}"
copy_dir = snap_dir
- # Launch agent-browser's packaged Chromium on the profile COPY. This is
- # the same launch path Hermes' built-in local browsing already uses,
- # just pointed at the copied user-data-dir — no bespoke Chrome launch.
+ # Launch the user's REAL browser binary directly on the profile COPY.
+ # agent-browser 0.35's own
+ # launch path force-adds --use-mock-keychain/--password-store=basic
+ # (and --headless=new), which makes macOS Chrome treat every
+ # keychain-encrypted cookie as undecryptable and drop it — the copied
+ # profile launches signed out. Launching the real binary ourselves with
+ # NO mock-keychain switches keeps the OS keychain path intact, exactly
+ # as the snapshot design intends; agent-browser attaches to it after
+ # via --auto-connect (--cdp <port>).
+ from hermes_cli.browser_connect import chromium_executable
+
+ real_binary = chromium_executable(browser)
+ if real_binary is None:
+ return None, (
+ "browser.use_real_profile is on, but the real browser binary for "
+ f"'{browser}' could not be found. Reinstall it or turn the toggle off."
+ )
+
+ port_file = os.path.join(copy_dir, "DevToolsActivePort")
+ try:
+ os.unlink(port_file) # stale port from a previous launch confuses reuse probes
+ except OSError:
+ pass
+ chrome_argv = [
+ real_binary,
+ f"--user-data-dir={copy_dir}",
+ "--remote-debugging-port=0",
+ "--no-first-run",
+ "--no-default-browser-check",
+ "--disable-background-networking",
+ "--disable-component-update",
+ "--disable-default-apps",
+ "--disable-hang-monitor",
+ "--disable-popup-blocking",
+ "--disable-prompt-on-repost",
+ "--disable-sync",
+ "--disable-features=Translate",
+ "--no-startup-window",
+ ]
+ # Drive the copy headlessly by default. Real-profile browsing is a
+ # background capability — the agent tweets / fills forms / scrapes on
+ # the user's behalf while they keep working; a visible window that
+ # steals focus every turn defeats the point. Chrome's NEW headless mode
+ # shares the profile's normal cookie store (unlike legacy --headless
+ # with its separate store), so the copied auth/login state still loads.
+ # Cookie decryption is unaffected by headless: the drop we guard against
+ # comes from --use-mock-keychain (which agent-browser's own launcher
+ # force-adds and we deliberately avoid), NOT from headless mode. This
+ # also covers display-less Linux (servers, CI), where a headed launch
+ # would exit at startup. Users who want to watch can opt in via the same
+ # browser.headed / AGENT_BROWSER_HEADED toggle the rest of the browser
+ # stack honors; on a display-less host we force headless regardless so
+ # the launch doesn't die.
+ _has_display = bool(
+ os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY")
+ )
+ _want_headed = _is_headed_mode() and (
+ _has_display or not sys.platform.startswith("linux")
+ )
+ if not _want_headed:
+ chrome_argv.append("--headless=new")
+ try:
+ chrome_proc = subprocess.Popen(
+ chrome_argv,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ stdin=subprocess.DEVNULL,
+ start_new_session=True,
+ env=_build_browser_env(),
+ )
+ except (subprocess.SubprocessError, OSError) as e:
+ return None, f"browser.use_real_profile is on, but the launch failed: {e}"
+ _real_profile_chrome_procs.append(chrome_proc)
+
+ # Wait for DevToolsActivePort to appear (Chrome picks a free port).
+ import time as _time
+
+ deadline = _time.monotonic() + 30.0
+ port = None
+ while _time.monotonic() < deadline:
+ try:
- with open(port_file, encoding="utf-8") as fh:
++ with open(port_file, encoding="utf-8-sig") as fh:
+ line = fh.readline().strip()
+ if line.isdigit():
+ port = int(line)
+ break
+ except OSError:
+ pass
+ if chrome_proc.poll() is not None:
+ _terminate_real_profile_chrome()
+ return None, (
+ "browser.use_real_profile is on, but Chrome exited during "
+ "startup (another instance may hold the profile copy)."
+ )
+ _time.sleep(0.25)
+ if port is None:
+ _terminate_real_profile_chrome()
+ return None, (
+ "browser.use_real_profile is on, but the real-profile browser "
+ "did not expose a debug port in time. Retry, or turn the toggle off."
+ )
+
+ # Tell agent-browser to ATTACH to the running Chrome instead of
+ # launching its own (its own launch injects mock-keychain flags).
try:
browser_cmd = _find_agent_browser()
except FileNotFoundError as e:
@@@ -1677,6 -1814,19 +1795,19 @@@
)
cdp = _agent_browser_get_cdp(_REAL_PROFILE_SESSION)
+ # The daemon may answer with the endpoint of a
+ # browser IT spawned (throwaway temp profile) instead of the real
+ # Chrome we launched on the copy. The DevToolsActivePort file OUR
+ # Chrome wrote is the authoritative endpoint of the logged-in browser;
+ # if the daemon disagrees, trust ours.
+ try:
- with open(port_file, encoding="utf-8") as fh:
++ with open(port_file, encoding="utf-8-sig") as fh:
+ our_port = fh.readline().strip()
+ m = re.search(r":(\d+)", cdp or "")
+ if m and m.group(1) != our_port:
+ cdp = f"http://127.0.0.1:{our_port}"
+ except (OSError, ValueError):
+ pass
if not cdp:
return None, (
"browser.use_real_profile is on, but the real-profile browser "
diff --cc tools/skills_hub.py
index c87f19186e1,3b2db4b705d..696ed10e8d3
--- a/tools/skills_hub.py
+++ b/tools/skills_hub.py
@@@ -3598,6 -3793,87 +3793,87 @@@ class OptionalSkillSource(SkillSource)
self._remote_dirs = dirs
return dirs
+ def _upstream_pointer(self, skill_dir: Path) -> Optional[Dict[str, str]]:
+ """Return the upstream pointer for a catalog-stub skill dir, if any.
+
+ A stub declares ``metadata.hermes.upstream`` in its SKILL.md
+ frontmatter:
+
+ metadata:
+ hermes:
+ upstream:
+ repo: pbakaus/impeccable
+ path: .hermes/skills/impeccable
+
+ Returns ``{"repo": ..., "path": ...}`` or None for normal
+ (fully-vendored) optional skills.
+ """
+ skill_md = skill_dir / "SKILL.md"
+ try:
- content = skill_md.read_text(encoding="utf-8")
++ content = skill_md.read_text(encoding="utf-8-sig")
+ except (OSError, UnicodeDecodeError):
+ return None
+ return self._upstream_pointer_from_content(content)
+
+ def _upstream_pointer_from_content(self, content: Union[str, bytes]) -> Optional[Dict[str, str]]:
+ """Parse ``metadata.hermes.upstream`` out of SKILL.md content."""
+ if isinstance(content, bytes):
+ try:
+ content = content.decode("utf-8")
+ except UnicodeDecodeError:
+ return None
+ fm = self._parse_frontmatter(content)
+ meta_block = fm.get("metadata")
+ if not isinstance(meta_block, dict):
+ return None
+ hermes_meta = meta_block.get("hermes")
+ if not isinstance(hermes_meta, dict):
+ return None
+ upstream = hermes_meta.get("upstream")
+ if not isinstance(upstream, dict):
+ return None
+ repo = str(upstream.get("repo", "")).strip().strip("/")
+ path = str(upstream.get("path", "")).strip().strip("/")
+ # repo must be exactly owner/name; path must be a clean relative path.
+ if not repo or repo.count("/") != 1 or not path:
+ return None
+ parts = [p for p in path.split("/") if p not in ("", ".")]
+ if not parts or any(p == ".." for p in parts):
+ return None
+ return {"repo": repo, "path": "/".join(parts)}
+
+ def _fetch_from_upstream(self, upstream: Dict[str, str], rel_id: str) -> Optional[SkillBundle]:
+ """Fetch an upstream-maintained optional skill from its external repo.
+
+ Delegates to GitHubSource.fetch() (full-directory download through the
+ git tree, symlink/unsafe-path rejection, quarantine + scan downstream)
+ but re-labels the bundle as an official catalog entry so trust,
+ identifier, and update tracking stay in the optional-skills namespace.
+ """
+ github = self._get_github()
+ bundle = github.fetch(f"{upstream['repo']}/{upstream['path']}")
+ if bundle is None:
+ logger.warning(
+ "Upstream fetch failed for optional skill %s (%s:%s)",
+ rel_id, upstream["repo"], upstream["path"],
+ )
+ return None
+ return SkillBundle(
+ name=bundle.name,
+ files=bundle.files,
+ source="official",
+ identifier=f"official/{rel_id}",
+ # Curated-catalog endorsement, but the content comes live from a
+ # third-party repo — "trusted", not "builtin", so a dangerous
+ # scan verdict still blocks install (INSTALL_POLICY).
+ trust_level="trusted",
+ metadata={
+ **bundle.metadata,
+ "upstream_repo": upstream["repo"],
+ "upstream_path": upstream["path"],
+ },
+ )
+
def _find_skill_dir(self, name: str) -> Optional[Path]:
"""Find a skill directory by name anywhere in optional-skills/."""
if not self._optional_dir.is_dir():
diff --cc uv.lock
index 1f77eae9e50,1f77eae9e50..082472205f7
--- a/uv.lock
+++ b/uv.lock
@@@ -17,6 -17,6 +17,7 @@@ huggingface-hub = fals
vercel = false
pillow = false
unpaddedbase64 = false
++google-cloud-pubsub = false
h2 = false
defusedxml = false
aiohttp = false
@@@ -386,30 -386,30 +387,18 @@@ version = "0.31.0
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/fe/cc/d18065ce2380d80b1bcce927c24a2642efd38918e33fd724bc4bca904877/asyncpg-0.31.0.tar.gz", hash = "sha256:c989386c83940bfbd787180f2b1519415e2d3d6277a70d9d0f0145ac73500735", size = 993667, upload-time = "2025-11-24T23:27:00.812Z" }
wheels = [
-- { url = "https://files.pythonhosted.org/packages/08/17/cc02bc49bc350623d050fa139e34ea512cd6e020562f2a7312a7bcae4bc9/asyncpg-0.31.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:eee690960e8ab85063ba93af2ce128c0f52fd655fdff9fdb1a28df01329f031d", size = 643159, upload-time = "2025-11-24T23:25:36.443Z" },
-- { url = "https://files.pythonhosted.org/packages/a4/62/4ded7d400a7b651adf06f49ea8f73100cca07c6df012119594d1e3447aa6/asyncpg-0.31.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:2657204552b75f8288de08ca60faf4a99a65deef3a71d1467454123205a88fab", size = 638157, upload-time = "2025-11-24T23:25:37.89Z" },
{ url = "https://files.pythonhosted.org/packages/d6/5b/4179538a9a72166a0bf60ad783b1ef16efb7960e4d7b9afe9f77a5551680/asyncpg-0.31.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a429e842a3a4b4ea240ea52d7fe3f82d5149853249306f7ff166cb9948faa46c", size = 2918051, upload-time = "2025-11-24T23:25:39.461Z" },
{ url = "https://files.pythonhosted.org/packages/e6/35/c27719ae0536c5b6e61e4701391ffe435ef59539e9360959240d6e47c8c8/asyncpg-0.31.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c0807be46c32c963ae40d329b3a686356e417f674c976c07fa49f1b30303f109", size = 2972640, upload-time = "2025-11-24T23:25:41.512Z" },
{ url = "https://files.pythonhosted.org/packages/43/f4/01ebb9207f29e645a64699b9ce0eefeff8e7a33494e1d29bb53736f7766b/asyncpg-0.31.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:e5d5098f63beeae93512ee513d4c0c53dc12e9aa2b7a1af5a81cddf93fe4e4da", size = 2851050, upload-time = "2025-11-24T23:25:43.153Z" },
{ url = "https://files.pythonhosted.org/packages/3e/f4/03ff1426acc87be0f4e8d40fa2bff5c3952bef0080062af9efc2212e3be8/asyncpg-0.31.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:37fc6c00a814e18eef51833545d1891cac9aa69140598bb076b4cd29b3e010b9", size = 2962574, upload-time = "2025-11-24T23:25:44.942Z" },
-- { url = "https://files.pythonhosted.org/packages/c7/39/cc788dfca3d4060f9d93e67be396ceec458dfc429e26139059e58c2c244d/asyncpg-0.31.0-cp311-cp311-win32.whl", hash = "sha256:5a4af56edf82a701aece93190cc4e094d2df7d33f6e915c222fb09efbb5afc24", size = 521076, upload-time = "2025-11-24T23:25:46.486Z" },
-- { url = "https://files.pythonhosted.org/packages/28/fc/735af5384c029eb7f1ca60ccb8fa95521dbdaeef788edf4cecfc604c3cab/asyncpg-0.31.0-cp311-cp311-win_amd64.whl", hash = "sha256:480c4befbdf079c14c9ca43c8c5e1fe8b6296c96f1f927158d4f1e750aacc047", size = 584980, upload-time = "2025-11-24T23:25:47.938Z" },
-- { url = "https://files.pythonhosted.org/packages/2a/a6/59d0a146e61d20e18db7396583242e32e0f120693b67a8de43f1557033e2/asyncpg-0.31.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:b44c31e1efc1c15188ef183f287c728e2046abb1d26af4d20858215d50d91fad", size = 662042, upload-time = "2025-11-24T23:25:49.578Z" },
-- { url = "https://files.pythonhosted.org/packages/36/01/ffaa189dcb63a2471720615e60185c3f6327716fdc0fc04334436fbb7c65/asyncpg-0.31.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:0c89ccf741c067614c9b5fc7f1fc6f3b61ab05ae4aaa966e6fd6b93097c7d20d", size = 638504, upload-time = "2025-11-24T23:25:51.501Z" },
{ url = "https://files.pythonhosted.org/packages/9f/62/3f699ba45d8bd24c5d65392190d19656d74ff0185f42e19d0bbd973bb371/asyncpg-0.31.0-cp312-cp312-manylinux_2_28_aarch64.whl", hash = "sha256:12b3b2e39dc5470abd5e98c8d3373e4b1d1234d9fbdedf538798b2c13c64460a", size = 3426241, upload-time = "2025-11-24T23:25:53.278Z" },
{ url = "https://files.pythonhosted.org/packages/8c/d1/a867c2150f9c6e7af6462637f613ba67f78a314b00db220cd26ff559d532/asyncpg-0.31.0-cp312-cp312-manylinux_2_28_x86_64.whl", hash = "sha256:aad7a33913fb8bcb5454313377cc330fbb19a0cd5faa7272407d8a0c4257b671", size = 3520321, upload-time = "2025-11-24T23:25:54.982Z" },
{ url = "https://files.pythonhosted.org/packages/7a/1a/cce4c3f246805ecd285a3591222a2611141f1669d002163abef999b60f98/asyncpg-0.31.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3df118d94f46d85b2e434fd62c84cb66d5834d5a890725fe625f498e72e4d5ec", size = 3316685, upload-time = "2025-11-24T23:25:57.43Z" },
{ url = "https://files.pythonhosted.org/packages/40/ae/0fc961179e78cc579e138fad6eb580448ecae64908f95b8cb8ee2f241f67/asyncpg-0.31.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:bd5b6efff3c17c3202d4b37189969acf8927438a238c6257f66be3c426beba20", size = 3471858, upload-time = "2025-11-24T23:25:59.636Z" },
-- { url = "https://files.pythonhosted.org/packages/52/b2/b20e09670be031afa4cbfabd645caece7f85ec62d69c312239de568e058e/asyncpg-0.31.0-cp312-cp312-win32.whl", hash = "sha256:027eaa61361ec735926566f995d959ade4796f6a49d3bde17e5134b9964f9ba8", size = 527852, upload-time = "2025-11-24T23:26:01.084Z" },
-- { url = "https://files.pythonhosted.org/packages/b5/f0/f2ed1de154e15b107dc692262395b3c17fc34eafe2a78fc2115931561730/asyncpg-0.31.0-cp312-cp312-win_amd64.whl", hash = "sha256:72d6bdcbc93d608a1158f17932de2321f68b1a967a13e014998db87a72ed3186", size = 597175, upload-time = "2025-11-24T23:26:02.564Z" },
-- { url = "https://files.pythonhosted.org/packages/95/11/97b5c2af72a5d0b9bc3fa30cd4b9ce22284a9a943a150fdc768763caf035/asyncpg-0.31.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:c204fab1b91e08b0f47e90a75d1b3c62174dab21f670ad6c5d0f243a228f015b", size = 661111, upload-time = "2025-11-24T23:26:04.467Z" },
-- { url = "https://files.pythonhosted.org/packages/1b/71/157d611c791a5e2d0423f09f027bd499935f0906e0c2a416ce712ba51ef3/asyncpg-0.31.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:54a64f91839ba59008eccf7aad2e93d6e3de688d796f35803235ea1c4898ae1e", size = 636928, upload-time = "2025-11-24T23:26:05.944Z" },
{ url = "https://files.pythonhosted.org/packages/2e/fc/9e3486fb2bbe69d4a867c0b76d68542650a7ff1574ca40e84c3111bb0c6e/asyncpg-0.31.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c0e0822b1038dc7253b337b0f3f676cadc4ac31b126c5d42691c39691962e403", size = 3424067, upload-time = "2025-11-24T23:26:07.957Z" },
{ url = "https://files.pythonhosted.org/packages/12/c6/8c9d076f73f07f995013c791e018a1cd5f31823c2a3187fc8581706aa00f/asyncpg-0.31.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bef056aa502ee34204c161c72ca1f3c274917596877f825968368b2c33f585f4", size = 3518156, upload-time = "2025-11-24T23:26:09.591Z" },
{ url = "https://files.pythonhosted.org/packages/ae/3b/60683a0baf50fbc546499cfb53132cb6835b92b529a05f6a81471ab60d0c/asyncpg-0.31.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:0bfbcc5b7ffcd9b75ab1558f00db2ae07db9c80637ad1b2469c43df79d7a5ae2", size = 3319636, upload-time = "2025-11-24T23:26:11.168Z" },
{ url = "https://files.pythonhosted.org/packages/50/dc/8487df0f69bd398a61e1792b3cba0e47477f214eff085ba0efa7eac9ce87/asyncpg-0.31.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:22bc525ebbdc24d1261ecbf6f504998244d4e3be1721784b5f64664d61fbe602", size = 3472079, upload-time = "2025-11-24T23:26:13.164Z" },
-- { url = "https://files.pythonhosted.org/packages/13/a1/c5bbeeb8531c05c89135cb8b28575ac2fac618bcb60119ee9696c3faf71c/asyncpg-0.31.0-cp313-cp313-win32.whl", hash = "sha256:f890de5e1e4f7e14023619399a471ce4b71f5418cd67a51853b9910fdfa73696", size = 527606, upload-time = "2025-11-24T23:26:14.78Z" },
-- { url = "https://files.pythonhosted.org/packages/91/66/b25ccb84a246b470eb943b0107c07edcae51804912b824054b3413995a10/asyncpg-0.31.0-cp313-cp313-win_amd64.whl", hash = "sha256:dc5f2fa9916f292e5c5c8b2ac2813763bcd7f58e130055b4ad8a0531314201ab", size = 596569, upload-time = "2025-11-24T23:26:16.189Z" },
]
[[package]]
@@@ -1408,6 -1408,6 +1397,12 @@@ wheels =
{ url = "https://files.pythonhosted.org/packages/03/15/e56f351cf6ef1cfea58e6ac226a7318ed1deb2218c4b3cc9bd9e4b786c5a/google_api_core-2.30.3-py3-none-any.whl", hash = "sha256:a85761ba72c444dad5d611c2220633480b2b6be2521eca69cca2dbb3ffd6bfe8", size = 173274, upload-time = "2026-04-09T22:57:16.198Z" },
]
++[package.optional-dependencies]
++grpc = [
++ { name = "grpcio" },
++ { name = "grpcio-status" },
++]
++
[[package]]
name = "google-api-python-client"
version = "2.194.0"
@@@ -1463,6 -1463,6 +1458,26 @@@ wheels =
{ url = "https://files.pythonhosted.org/packages/2a/e0/cb454a95f460903e39f101e950038ec24a072ca69d0a294a6df625cc1627/google_auth_oauthlib-1.3.1-py3-none-any.whl", hash = "sha256:1a139ef23f1318756805b0e95f655c238bffd29655329a2978218248da4ee7f8", size = 19247, upload-time = "2026-03-30T20:02:23.894Z" },
]
++[[package]]
++name = "google-cloud-pubsub"
++version = "2.39.2"
++source = { registry = "https://pypi.org/simple" }
++dependencies = [
++ { name = "google-api-core", extra = ["grpc"] },
++ { name = "google-auth" },
++ { name = "grpc-google-iam-v1" },
++ { name = "grpcio" },
++ { name = "grpcio-status" },
++ { name = "opentelemetry-api" },
++ { name = "opentelemetry-sdk" },
++ { name = "proto-plus" },
++ { name = "protobuf" },
++]
++sdist = { url = "https://files.pythonhosted.org/packages/d1/2f/a70b6ba2016acc16ca3e4d357151edda047f63752ddcf8baee29c41e5f94/google_cloud_pubsub-2.39.2.tar.gz", hash = "sha256:934a3ab7496a6da09cd97d866bef3e47092e904688a66f60750895a7484bd585", size = 403181, upload-time = "2026-08-25T19:18:59.568Z" }
++wheels = [
++ { url = "https://files.pythonhosted.org/packages/62/e1/14519798b767f1ce4adf3c239c31bb1a5af607646e293e92ed1770faaa06/google_cloud_pubsub-2.39.2-py3-none-any.whl", hash = "sha256:b1295c6641032aff1dabbddf495b10642a5b547f6783ee4c6bb3365682e71354", size = 323836, upload-time = "2026-08-24T21:55:46.512Z" },
++]
++
[[package]]
name = "googleapis-common-protos"
version = "1.73.0"
@@@ -1475,6 -1475,6 +1490,11 @@@ wheels =
{ url = "https://files.pythonhosted.org/packages/69/28/23eea8acd65972bbfe295ce3666b28ac510dfcb115fac089d3edb0feb00a/googleapis_common_protos-1.73.0-py3-none-any.whl", hash = "sha256:dfdaaa2e860f242046be561e6d6cb5c5f1541ae02cfbcb034371aadb2942b4e8", size = 297578, upload-time = "2026-03-06T21:52:33.933Z" },
]
++[package.optional-dependencies]
++grpc = [
++ { name = "grpcio" },
++]
++
[[package]]
name = "greenlet"
version = "3.5.3"
@@@ -1507,6 -1507,6 +1527,20 @@@ wheels =
{ url = "https://files.pythonhosted.org/packages/c7/7e/220a7f5824a64a60443fc03b39dfac4ea63a7fb6d481efa27eafa928e7f4/greenlet-3.5.3-cp313-cp313-win_arm64.whl", hash = "sha256:dc133a1569ee667b2a6ef56ce551084aeefd87a5acbc4736d336d1e2edc6cfc4", size = 238141, upload-time = "2026-06-26T18:22:48.507Z" },
]
++[[package]]
++name = "grpc-google-iam-v1"
++version = "0.14.5"
++source = { registry = "https://pypi.org/simple" }
++dependencies = [
++ { name = "googleapis-common-protos", extra = ["grpc"] },
++ { name = "grpcio" },
++ { name = "protobuf" },
++]
++sdist = { url = "https://files.pythonhosted.org/packages/d2/d0/fa5bdd5f3f421bb68dc6dc162e9caaf942897ca41ce7255b524723c80f0b/grpc_google_iam_v1-0.14.5.tar.gz", hash = "sha256:07fd3a9fafb586588e771831fbfc8f6597050181d0c3b45e039d18b8fdc1aab5", size = 23736, upload-time = "2026-08-06T06:24:54.489Z" }
++wheels = [
++ { url = "https://files.pythonhosted.org/packages/84/ab/be3ad0d46cffe35fd1e7cc3f9947edd6cb3c552229de3be2742f15f7ea47/grpc_google_iam_v1-0.14.5-py3-none-any.whl", hash = "sha256:0f5e680b20aa0a9441e68c769da04d94d70fca4e43751a82d8abb8aa6a7181ca", size = 32674, upload-time = "2026-08-06T06:23:49.467Z" },
++]
++
[[package]]
name = "grpcio"
version = "1.81.1"
@@@ -1548,6 -1548,6 +1582,20 @@@ wheels =
{ url = "https://files.pythonhosted.org/packages/0d/20/3da8bb0d637feccdc3e1e419bb511ce93651ce7d54164f95de22cc0b8b34/grpcio-1.81.1-cp313-cp313-win_amd64.whl", hash = "sha256:edb59506291b647a30884b1d51a599d605f40b20af4a7dc3d33786a47a31de60", size = 4928648, upload-time = "2026-06-11T12:46:17.823Z" },
]
++[[package]]
++name = "grpcio-status"
++version = "1.81.1"
++source = { registry = "https://pypi.org/simple" }
++dependencies = [
++ { name = "googleapis-common-protos" },
++ { name = "grpcio" },
++ { name = "protobuf" },
++]
++sdist = { url = "https://files.pythonhosted.org/packages/32/26/0aa9168c87882381fd810d140c279a2490ed6aee655f0515d6f56c5ca404/grpcio_status-1.81.1.tar.gz", hash = "sha256:9389a03e746017b10f0630c064289201458f3ce01f5d7ef4b0bebc1ef6cf82ad", size = 13923, upload-time = "2026-06-11T12:58:48.636Z" }
++wheels = [
++ { url = "https://files.pythonhosted.org/packages/e5/5e/5abfec5f7e89d3b7993d57cfb025ca5f968a2c18656d7fcda2b6919440b9/grpcio_status-1.81.1-py3-none-any.whl", hash = "sha256:08072fa9995f4a95c647fc6f4f85e2411573d00087bcabdf30f260114338f232", size = 14638, upload-time = "2026-06-11T12:58:31.982Z" },
++]
++
[[package]]
name = "grpclib"
version = "0.4.9"
@@@ -1648,6 -1648,6 +1696,10 @@@ all =
anthropic = [
{ name = "anthropic" },
]
++audio-io = [
++ { name = "numpy" },
++ { name = "sounddevice" },
++]
azure-identity = [
{ name = "azure-identity" },
]
@@@ -1678,6 -1678,6 +1730,12 @@@ dingtalk =
{ name = "dingtalk-stream" },
{ name = "qrcode" },
]
++discord = [
++ { name = "discord-py", extra = ["voice"] },
++]
++doc-extract = [
++ { name = "firecrawl-anydoc" },
++]
edge-tts = [
{ name = "edge-tts" },
]
@@@ -1702,6 -1702,6 +1760,9 @@@ google =
{ name = "httplib2" },
{ name = "pyasn1" },
]
++google-chat = [
++ { name = "google-cloud-pubsub" },
++]
hindsight = [
{ name = "hindsight-client" },
]
@@@ -1712,11 -1712,11 +1773,11 @@@ honcho =
{ name = "honcho-ai" },
]
matrix = [
-- { name = "aiohttp" },
-- { name = "aiohttp-socks" },
-- { name = "aiosqlite" },
-- { name = "asyncpg" },
-- { name = "mautrix", extra = ["encryption"] },
++ { name = "aiohttp", marker = "sys_platform == 'linux'" },
++ { name = "aiohttp-socks", marker = "sys_platform == 'linux'" },
++ { name = "aiosqlite", marker = "sys_platform == 'linux'" },
++ { name = "asyncpg", marker = "sys_platform == 'linux'" },
++ { name = "mautrix", extra = ["encryption"], marker = "sys_platform == 'linux'" },
]
mcp = [
{ name = "httpx2" },
@@@ -1748,6 -1748,6 +1809,9 @@@ otlp =
parallel-web = [
{ name = "parallel-web" },
]
++silk = [
++ { name = "pilk" },
++]
slack = [
{ name = "aiohttp" },
{ name = "slack-bolt" },
@@@ -1756,6 -1756,6 +1820,9 @@@
sms = [
{ name = "aiohttp" },
]
++stt-whisper = [
++ { name = "faster-whisper", marker = "(platform_machine != 'x86_64' and sys_platform == 'darwin') or (platform_machine != 'ARM64' and sys_platform == 'win32') or (sys_platform != 'darwin' and sys_platform != 'win32')" },
++]
supermemory = [
{ name = "supermemory" },
]
@@@ -1763,6 -1763,6 +1830,9 @@@ teams =
{ name = "aiohttp" },
{ name = "microsoft-teams-apps" },
]
++telegram = [
++ { name = "python-telegram-bot", extra = ["webhooks"] },
++]
termux = [
{ name = "agent-client-protocol" },
{ name = "honcho-ai" },
@@@ -1789,6 -1789,6 +1859,9 @@@ termux-all =
{ name = "starlette" },
{ name = "uvicorn", extra = ["standard"] },
]
++trace-upload = [
++ { name = "huggingface-hub" },
++]
tts-premium = [
{ name = "elevenlabs" },
]
@@@ -1799,20 -1799,20 +1872,33 @@@ vertex =
{ name = "google-auth" },
]
voice = [
-- { name = "faster-whisper" },
++ { name = "faster-whisper", marker = "(platform_machine != 'x86_64' and sys_platform == 'darwin') or (platform_machine != 'ARM64' and sys_platform == 'win32') or (sys_platform != 'darwin' and sys_platform != 'win32')" },
{ name = "numpy" },
{ name = "sounddevice" },
]
wake = [
-- { name = "ai-edge-litert", marker = "sys_platform == 'darwin'" },
++ { name = "ai-edge-litert", marker = "platform_machine == 'arm64' and sys_platform == 'darwin'" },
{ name = "numpy" },
-- { name = "onnxruntime" },
-- { name = "openwakeword" },
++ { name = "onnxruntime", marker = "platform_machine != 'x86_64' or sys_platform != 'darwin'" },
++ { name = "openwakeword", marker = "platform_machine != 'x86_64' or sys_platform != 'darwin'" },
{ name = "pvporcupine" },
{ name = "sentencepiece" },
{ name = "sherpa-onnx" },
{ name = "sounddevice" },
]
++wake-openwakeword = [
++ { name = "onnxruntime", marker = "platform_machine != 'x86_64' or sys_platform != 'darwin'" },
++ { name = "openwakeword", marker = "platform_machine != 'x86_64' or sys_platform != 'darwin'" },
++]
++wake-porcupine = [
++ { name = "pvporcupine" },
++]
++wake-sherpa = [
++ { name = "sherpa-onnx" },
++]
++wake-tflite = [
++ { name = "ai-edge-litert", marker = "platform_machine == 'arm64' and sys_platform == 'darwin'" },
++]
web = [
{ name = "fastapi" },
{ name = "python-multipart" },
@@@ -1829,18 -1829,18 +1915,19 @@@ youtube =
[package.metadata]
requires-dist = [
{ name = "agent-client-protocol", marker = "extra == 'acp'", specifier = "==0.9.0" },
-- { name = "ai-edge-litert", marker = "sys_platform == 'darwin' and extra == 'wake'", specifier = "==2.1.6" },
++ { name = "ai-edge-litert", marker = "platform_machine == 'arm64' and sys_platform == 'darwin' and extra == 'wake'", specifier = "==2.1.6" },
++ { name = "ai-edge-litert", marker = "platform_machine == 'arm64' and sys_platform == 'darwin' and extra == 'wake-tflite'", specifier = "==2.1.6" },
++ { name = "aiohttp", marker = "sys_platform == 'linux' and extra == 'matrix'", specifier = "==3.14.3" },
{ name = "aiohttp", marker = "extra == 'homeassistant'", specifier = "==3.14.3" },
-- { name = "aiohttp", marker = "extra == 'matrix'", specifier = "==3.14.3" },
{ name = "aiohttp", marker = "extra == 'messaging'", specifier = "==3.14.3" },
{ name = "aiohttp", marker = "extra == 'slack'", specifier = "==3.14.3" },
{ name = "aiohttp", marker = "extra == 'sms'", specifier = "==3.14.3" },
{ name = "aiohttp", marker = "extra == 'teams'", specifier = "==3.14.3" },
-- { name = "aiohttp-socks", marker = "extra == 'matrix'", specifier = "==0.11.0" },
-- { name = "aiosqlite", marker = "extra == 'matrix'", specifier = "==0.22.1" },
++ { name = "aiohttp-socks", marker = "sys_platform == 'linux' and extra == 'matrix'", specifier = "==0.11.0" },
++ { name = "aiosqlite", marker = "sys_platform == 'linux' and extra == 'matrix'", specifier = "==0.22.1" },
{ name = "alibabacloud-dingtalk", marker = "extra == 'dingtalk'", specifier = "==2.2.42" },
{ name = "anthropic", marker = "extra == 'anthropic'", specifier = "==0.87.0" },
-- { name = "asyncpg", marker = "extra == 'matrix'", specifier = "==0.31.0" },
++ { name = "asyncpg", marker = "sys_platform == 'linux' and extra == 'matrix'", specifier = "==0.31.0" },
{ name = "azure-identity", marker = "extra == 'azure-identity'", specifier = "==1.25.3" },
{ name = "boto3", marker = "extra == 'bedrock'", specifier = "==1.42.89" },
{ name = "brotlicffi", marker = "extra == 'messaging'", specifier = "==1.2.0.1" },
@@@ -1852,6 -1852,6 +1939,7 @@@
{ name = "debugpy", marker = "extra == 'dev'", specifier = "==1.8.20" },
{ name = "defusedxml", marker = "extra == 'wecom'", specifier = "==0.7.1" },
{ name = "dingtalk-stream", marker = "extra == 'dingtalk'", specifier = "==0.24.3" },
++ { name = "discord-py", extras = ["voice"], marker = "extra == 'discord'", specifier = "==2.7.1" },
{ name = "discord-py", extras = ["voice"], marker = "extra == 'messaging'", specifier = "==2.7.1" },
{ name = "edge-tts", marker = "extra == 'edge-tts'", specifier = "==7.2.7" },
{ name = "elevenlabs", marker = "extra == 'tts-premium'", specifier = "==1.59.0" },
@@@ -1859,15 -1859,15 +1947,18 @@@
{ name = "fal-client", marker = "extra == 'fal'", specifier = "==0.13.1" },
{ name = "fastapi", specifier = ">=0.104.0,<1" },
{ name = "fastapi", marker = "extra == 'web'", specifier = "==0.133.1" },
-- { name = "faster-whisper", marker = "extra == 'voice'", specifier = "==1.2.1" },
++ { name = "faster-whisper", marker = "(platform_machine != 'x86_64' and sys_platform == 'darwin' and extra == 'stt-whisper') or (platform_machine != 'ARM64' and sys_platform == 'win32' and extra == 'stt-whisper') or (sys_platform != 'darwin' and sys_platform != 'win32' and extra == 'stt-whisper')", specifier = "==1.2.1" },
++ { name = "faster-whisper", marker = "(platform_machine != 'x86_64' and sys_platform == 'darwin' and extra == 'voice') or (platform_machine != 'ARM64' and sys_platform == 'win32' and extra == 'voice') or (sys_platform != 'darwin' and sys_platform != 'win32' and extra == 'voice')", specifier = "==1.2.1" },
{ name = "fire", specifier = "==0.7.1" },
{ name = "firecrawl-anydoc", specifier = "==0.2.4" },
++ { name = "firecrawl-anydoc", marker = "extra == 'doc-extract'", specifier = "==0.2.4" },
{ name = "firecrawl-py", marker = "extra == 'firecrawl'", specifier = "==4.17.0" },
{ name = "google-api-python-client", marker = "extra == 'google'", specifier = "==2.194.0" },
{ name = "google-auth", marker = "extra == 'google'", specifier = "==2.55.1" },
{ name = "google-auth", marker = "extra == 'vertex'", specifier = "==2.55.1" },
{ name = "google-auth-httplib2", marker = "extra == 'google'", specifier = "==0.3.1" },
{ name = "google-auth-oauthlib", marker = "extra == 'google'", specifier = "==1.3.1" },
++ { name = "google-cloud-pubsub", marker = "extra == 'google-chat'", specifier = "==2.39.2" },
{ name = "hermes-agent", extras = ["acp"], marker = "extra == 'all'" },
{ name = "hermes-agent", extras = ["acp"], marker = "extra == 'termux'" },
{ name = "hermes-agent", extras = ["cron"], marker = "extra == 'all'" },
@@@ -1894,10 -1894,10 +1985,11 @@@
{ name = "httpx2", marker = "extra == 'computer-use'", specifier = "==2.7.0" },
{ name = "httpx2", marker = "extra == 'dev'", specifier = "==2.7.0" },
{ name = "httpx2", marker = "extra == 'mcp'", specifier = "==2.7.0" },
++ { name = "huggingface-hub", marker = "extra == 'trace-upload'", specifier = "==1.24.0" },
{ name = "jinja2", specifier = "==3.1.6" },
{ name = "lark-oapi", marker = "extra == 'feishu'", specifier = "==1.6.8" },
{ name = "markdown", specifier = "==3.10.2" },
-- { name = "mautrix", extras = ["encryption"], marker = "extra == 'matrix'", specifier = "==0.21.1" },
++ { name = "mautrix", extras = ["encryption"], marker = "sys_platform == 'linux' and extra == 'matrix'", specifier = "==0.21.1" },
{ name = "mcp", marker = "extra == 'computer-use'", specifier = "==2.0.0" },
{ name = "mcp", marker = "extra == 'dev'", specifier = "==2.0.0" },
{ name = "mcp", marker = "extra == 'mcp'", specifier = "==2.0.0" },
@@@ -1906,21 -1906,21 +1998,26 @@@
{ 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 = "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" },
-- { name = "openwakeword", marker = "extra == 'wake'", specifier = "==0.6.0" },
++ { name = "openwakeword", marker = "(platform_machine != 'x86_64' and extra == 'wake') or (sys_platform != 'darwin' and extra == 'wake')", specifier = "==0.6.0" },
++ { name = "openwakeword", marker = "(platform_machine != 'x86_64' and extra == 'wake-openwakeword') or (sys_platform != 'darwin' and extra == 'wake-openwakeword')", specifier = "==0.6.0" },
{ name = "packaging", specifier = "==26.0" },
{ name = "parallel-web", marker = "extra == 'parallel-web'", specifier = "==0.4.2" },
{ name = "pathspec", specifier = "==1.1.1" },
++ { name = "pilk", marker = "extra == 'silk'", specifier = "==0.2.4" },
{ name = "pillow", specifier = "==12.3.0" },
{ name = "prompt-toolkit", specifier = "==3.0.52" },
{ name = "psutil", specifier = "==7.2.2" },
{ name = "ptyprocess", marker = "sys_platform != 'win32'", specifier = ">=0.7.0,<1" },
{ name = "pvporcupine", marker = "extra == 'wake'", specifier = "==4.0.3" },
++ { name = "pvporcupine", marker = "extra == 'wake-porcupine'", specifier = "==4.0.3" },
{ name = "pyasn1", marker = "extra == 'google'", specifier = "==0.6.4" },
{ name = "pydantic", specifier = "==2.13.4" },
{ name = "pyjwt", extras = ["crypto"], specifier = "==2.13.0" },
@@@ -1930,6 -1930,6 +2027,7 @@@
{ name = "python-multipart", specifier = ">=0.0.9,<1" },
{ name = "python-multipart", marker = "extra == 'web'", specifier = "==0.0.32" },
{ name = "python-telegram-bot", extras = ["webhooks"], marker = "extra == 'messaging'", specifier = "==22.8" },
++ { name = "python-telegram-bot", extras = ["webhooks"], marker = "extra == 'telegram'", specifier = "==22.8" },
{ name = "python-telegram-bot", extras = ["webhooks"], marker = "extra == 'termux'", specifier = "==22.8" },
{ name = "pywin32", marker = "sys_platform == 'win32'", specifier = ">=306,<312" },
{ name = "pywinpty", marker = "sys_platform == 'win32'", specifier = ">=2.0.0,<3" },
@@@ -1944,11 -1944,11 +2042,13 @@@
{ name = "sentencepiece", marker = "extra == 'wake'", specifier = "==0.2.2" },
{ name = "setuptools", marker = "extra == 'dev'", specifier = "==83.0.0" },
{ name = "sherpa-onnx", marker = "extra == 'wake'", specifier = "==1.13.4" },
++ { name = "sherpa-onnx", marker = "extra == 'wake-sherpa'", specifier = "==1.13.4" },
{ name = "slack-bolt", marker = "extra == 'messaging'", specifier = "==1.30.0" },
{ name = "slack-bolt", marker = "extra == 'slack'", specifier = "==1.30.0" },
{ name = "slack-sdk", marker = "extra == 'messaging'", specifier = "==3.43.0" },
{ name = "slack-sdk", marker = "extra == 'slack'", specifier = "==3.43.0" },
{ name = "snowballstemmer", specifier = "==3.1.1" },
++ { name = "sounddevice", marker = "extra == 'audio-io'", specifier = "==0.5.5" },
{ name = "sounddevice", marker = "extra == 'voice'", specifier = "==0.5.5" },
{ name = "sounddevice", marker = "extra == 'wake'", specifier = "==0.5.5" },
{ name = "starlette", marker = "extra == 'computer-use'", specifier = "==1.3.1" },
@@@ -1966,7 -1966,7 +2066,7 @@@
{ name = "websockets", specifier = "==15.0.1" },
{ name = "youtube-transcript-api", marker = "extra == 'youtube'", specifier = "==1.2.4" },
]
--provides-extras = ["anthropic", "exa", "firecrawl", "parallel-web", "fal", "edge-tts", "modal", "daytona", "vercel", "hindsight", "dev", "messaging", "cron", "slack", "matrix", "wecom", "tts-premium", "voice", "wake", "honcho", "supermemory", "mem0", "vision", "pty", "mcp", "nemo-relay", "homeassistant", "sms", "teams", "computer-use", "acp", "mistral", "otlp", "bedrock", "vertex", "azure-identity", "termux", "termux-all", "dingtalk", "feishu", "google", "youtube", "web", "all"]
++provides-extras = ["anthropic", "exa", "firecrawl", "parallel-web", "fal", "edge-tts", "modal", "daytona", "vercel", "hindsight", "dev", "messaging", "cron", "slack", "matrix", "wecom", "tts-premium", "voice", "wake", "honcho", "telegram", "discord", "stt-whisper", "audio-io", "silk", "wake-openwakeword", "wake-sherpa", "wake-porcupine", "wake-tflite", "google-chat", "doc-extract", "trace-upload", "supermemory", "mem0", "vision", "pty", "mcp", "nemo-relay", "homeassistant", "sms", "teams", "computer-use", "acp", "mistral", "otlp", "bedrock", "vertex", "azure-identity", "termux", "termux-all", "dingtalk", "feishu", "google", "youtube", "web", "all"]
[[package]]
name = "hf-xet"
@@@ -3132,6 -3132,6 +3232,18 @@@ wheels =
{ url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" },
]
++[[package]]
++name = "pilk"
++version = "0.2.4"
++source = { registry = "https://pypi.org/simple" }
++dependencies = [
++ { name = "typing-extensions" },
++]
++sdist = { url = "https://files.pythonhosted.org/packages/66/bb/938dd697b6bc2d851ffec4ffe82ed20078e58bd0ef049e84f4d038d6f991/pilk-0.2.4.tar.gz", hash = "sha256:d4a1bcf93dc6ef5e95e0cfd728ed4ef4d49f9c0476d70816fecbe456cc762e7f", size = 226451, upload-time = "2023-05-26T03:32:34.133Z" }
++wheels = [
++ { url = "https://files.pythonhosted.org/packages/ff/06/80cac61bc7f791bcaae552ba90fb868f7af7503ef1c74e423cc20fca1a53/pilk-0.2.4-cp311-cp311-win_amd64.whl", hash = "sha256:a6692096607e8d77d348aeec00df633788c85b527aa83cbd803ddf508936db7f", size = 127024, upload-time = "2023-05-26T03:32:24.524Z" },
++]
++
[[package]]
name = "pillow"
version = "12.3.0"