bundles & unified installer

This commit is contained in:
ethernet authored and GitHub committed 2026-09-24 18:57:27 -04:00
commit 27df3b8847
3390 files changed
+194858 -94343

No files matched your search

+14 -1
View File
@@ -12,6 +12,8 @@ __pycache__
*.egg-info/
dist/
build/
!scripts/build/
!scripts/build/**
# Virtual environments
venv/
@@ -27,6 +29,8 @@ node_modules
.notebooklm-playwright/
.pip-cache/
.uv-cache/
.cache/
.build/
# Built artifacts that are regenerated inside the image. Excluded so local
# rebuilds on the developer's machine don't invalidate the npm-install layer
@@ -58,6 +62,8 @@ htmlcov/
# Documentation
*.md
!skills/**/*.md
!optional-skills/**/*.md
# Runtime data (bind-mounted at /opt/data; must not leak into build context)
data/
@@ -83,8 +89,14 @@ tests/
# Documentation site (Docusaurus)
website/
# Assets only used by the GitHub README
# Keep the source artwork needed by web's icon-generation prebuild.
assets/
!assets/
assets/*
!assets/nous-girl-black.svg
!assets/nous-girl-white.svg
!assets/backgrounds/
!assets/backgrounds/**
infographic/
# Plugin-level docs (hermes-achievements ships docs/ but the runtime doesn't read them)
@@ -99,6 +111,7 @@ packaging/
# Design and planning documents
plans/
.plans/
.hermes/
# Repo-level dotfiles that are git-only or dev-tooling config
.envrc
+3
View File
@@ -1,5 +1,6 @@
# Auto-generated files — collapse diffs and exclude from language stats
web/package-lock.json linguist-generated=true
uv.lock text eol=lf
# Enforce LF for scripts that run inside Linux containers.
# Without this, Windows checkout converts to CRLF and breaks `exec` in the
@@ -22,6 +23,8 @@ docker/entrypoint.sh text eol=lf
*.js text eol=lf
*.mjs text eol=lf
*.cjs text eol=lf
*.cts text eol=lf
*.mts text eol=lf
*.jsx text eol=lf
*.json text eol=lf
*.yaml text eol=lf
+1
View File
@@ -7,3 +7,4 @@ self-hosted-runner:
- ubuntu-latest-32-core
- ubuntu-latest-32-arm-core
- windows-latest-32-core
- windows-latest-32-arm-core
@@ -0,0 +1,96 @@
name: Desktop build dependency cache
description: Transport reusable dependency candidates; preparation always performs owner admission.
inputs:
phase:
description: Explicit restore or save, with preparation between the two calls.
required: true
source:
description: Admitted source checkout containing the dependency declarations.
required: true
cache:
description: Dedicated reusable dependency root passed to preparation.
required: true
work:
description: Job-local preparation root; never part of the snapshot.
required: true
producer:
description: Producer namespace (not a cache-write authorization boundary).
required: true
key:
description: For save, the cache-key output from the restore call.
default: ''
outputs:
cache-key:
description: Immutable save key; pass this to the save phase.
value: ${{ inputs.key || steps.describe.outputs.cache-key }}
cache-paths:
description: JSON array of direct provider paths, including not-yet-created destinations.
value: ${{ steps.describe.outputs.cache-paths }}
input-prefix:
description: Preferred dependency-input restore prefix.
value: ${{ steps.describe.outputs.input-prefix }}
restore-prefix:
description: Same-producer, target and host fallback prefix.
value: ${{ steps.describe.outputs.restore-prefix }}
cache-hit:
description: Transport result only; never permission to skip preparation.
value: ${{ steps.restore.outputs.cache-hit }}
runs:
using: composite
steps:
- name: Describe dependency transport with runner Python
id: describe
if: ${{ !cancelled() }}
shell: bash
env:
CACHE_ACTION: ${{ github.action_path }}
CACHE_PHASE: ${{ inputs.phase }}
CACHE_SOURCE: ${{ inputs.source }}
CACHE_ROOT: ${{ inputs.cache }}
CACHE_WORK: ${{ inputs.work }}
CACHE_PRODUCER: ${{ inputs.producer }}
CACHE_KEY: ${{ inputs.key }}
run: |
set -euo pipefail
case "$CACHE_PHASE" in
restore) ;;
save) test -n "$CACHE_KEY" || { printf '%s\n' '::error::Save requires the restore cache-key.'; exit 1; } ;;
*) printf '%s\n' '::error::Cache phase must be restore or save.'; exit 1 ;;
esac
# Description must not create CACHE_WORK: only preparation may claim it.
# Paths go straight to Actions; no job-local manifest is transported.
if [ "$RUNNER_OS" = Windows ]; then bootstrap=python; else bootstrap=python3; fi
"$bootstrap" -S "$CACHE_ACTION/../../../scripts/ci/desktop_build_cache.py" describe \
--source "$CACHE_SOURCE" --cache "$CACHE_ROOT" --work "$CACHE_WORK" --producer "$CACHE_PRODUCER"
- name: Restore dependency candidates
id: restore
if: ${{ !cancelled() && inputs.phase == 'restore' && steps.describe.outcome == 'success' }}
continue-on-error: true
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ${{ join(fromJSON(steps.describe.outputs.cache-paths), fromJSON('"\n"')) }}
key: ${{ steps.describe.outputs.cache-key }}
restore-keys: |
${{ steps.describe.outputs.input-prefix }}
${{ steps.describe.outputs.restore-prefix }}
enableCrossOsArchive: 'false'
fail-on-cache-miss: 'false'
# Owners have stopped writing before the caller enters save. No post hook
# or pruning can race cancellation, and signed products never enter here.
# Trusted workflow/token policy, not this key or condition, admits writers.
- name: Save dependency candidates before compilation and signing
id: save
if: ${{ !cancelled() && inputs.phase == 'save' && steps.describe.outcome == 'success' }}
continue-on-error: true
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ${{ join(fromJSON(steps.describe.outputs.cache-paths), fromJSON('"\n"')) }}
key: ${{ inputs.key }}
enableCrossOsArchive: 'false'
- name: Report cache service failure without masking preparation
if: ${{ !cancelled() && (steps.restore.outcome == 'failure' || steps.save.outcome == 'failure') }}
shell: bash
run: printf '%s\n' '::warning::Desktop dependency cache unavailable; provider preparation remains authoritative.'
+4 -4
View File
@@ -40,14 +40,14 @@ outputs:
description: Check pyproject.toml dependency upper bounds.
value: ${{ steps.classify.outputs.deps }}
uv_lock:
description: Run `uv lock --check` (pyproject.toml / uv.lock changes only).
description: Run the PM project-lock check (pyproject.toml / uv.lock changes only).
value: ${{ steps.classify.outputs.uv_lock }}
npm_lock:
description: Post/update the semantic package-lock.json diff PR comment.
value: ${{ steps.classify.outputs.npm_lock }}
installer:
description: Run the PowerShell installer tests on a Windows runner.
value: ${{ steps.classify.outputs.installer }}
bootstrap:
description: Run the bootstrap installer lane (install.sh sandbox + stamp verification).
value: ${{ steps.classify.outputs.bootstrap }}
desktop_updater:
description: Run the Windows desktop-update hand-off (windows.ps1) integration tests.
value: ${{ steps.classify.outputs.desktop_updater }}
+26 -35
View File
@@ -1,11 +1,13 @@
name: E2E screen recording
description: >
One screen-recording mechanism for every install-e2e runner. mode=start
installs what the OS needs (ffmpeg everywhere; Xvfb on headless linux),
starts the recorder, and exports DISPLAY for later steps. mode=stop
finalizes the recording and fails on a zero-frame file. A missing ffmpeg
is a hard error - a graceful skip makes the missing tool invisible and
the artifact silently loses its recording.
installs what the OS needs (Xvfb on headless linux), starts the recorder,
and exports DISPLAY for later steps. mode=stop finalizes the recording and
fails on a zero-frame file. A missing ffmpeg is a hard error - a graceful
skip makes the missing tool invisible and the artifact silently loses its
recording. ffmpeg itself comes from the PM toolchain (locked, sha256-pinned,
native per-OS incl. win32-arm64) - the caller must run actions/setup-pm with
`packages: ffmpeg` first.
inputs:
mode:
@@ -19,15 +21,29 @@ runs:
using: composite
steps:
# ---- setup + start ------------------------------------------------------
- name: Install ffmpeg + Xvfb (linux)
- name: Install Xvfb (linux, headless)
if: inputs.mode == 'start' && runner.os == 'Linux'
shell: bash
run: |
set -euo pipefail
if ! command -v ffmpeg >/dev/null 2>&1 || ! command -v Xvfb >/dev/null 2>&1; then
command -v Xvfb >/dev/null 2>&1 || {
sudo apt-get update -qq
sudo apt-get install -y -qq --no-install-recommends ffmpeg xvfb
fi
sudo apt-get install -y -qq --no-install-recommends xvfb
}
- name: Verify ffmpeg from the PM toolchain
if: inputs.mode == 'start'
shell: bash
run: |
set -euo pipefail
# PM's ffmpeg rides GITHUB_PATH from actions/setup-pm (packages:
# ffmpeg). Do not trust "preinstalled" claims - verify, fail loud.
# A graceful skip makes the missing tool invisible and the artifact
# silently loses its recording.
command -v ffmpeg >/dev/null 2>&1 || {
echo "::error::ffmpeg not on PATH - run actions/setup-pm with packages: ffmpeg before this step" >&2
exit 1
}
- name: Start Xvfb (linux, headless)
if: inputs.mode == 'start' && runner.os == 'Linux'
@@ -50,14 +66,11 @@ runs:
done
[ -S "/tmp/.X11-unix/X99" ] || { echo "Xvfb :99 did not come up" >&2; exit 1; }
- name: Verify ffmpeg (macos)
- name: Prepare macOS screen-capture approvals
if: inputs.mode == 'start' && runner.os == 'macOS'
shell: bash
run: |
set -euo pipefail
# Do not trust "preinstalled" claims - verify, install on miss.
command -v ffmpeg >/dev/null 2>&1 || brew install --quiet ffmpeg
# until new runner image is published by github, we have to hack on screen record approvals
# see https://github.com/actions/runner-images/issues/14474 - as of this hermes agent commit,
# it's merged but the image isn't updated.
@@ -66,28 +79,6 @@ runs:
defaults write "$approvalsPlist" "/opt/hca/hosted-compute-agent" -date "3024-01-01 00:00:00 +0000"
killall cfprefsd 2>/dev/null || true
- name: Restore cached ffmpeg (windows)
if: inputs.mode == 'start' && runner.os == 'Windows'
id: ffmpeg-cache
uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5
with:
path: ${{ runner.temp }}\test-bins\ffmpeg
key: e2e-ffmpeg-${{ runner.os }}-v1
- name: Install ffmpeg (windows)
if: inputs.mode == 'start' && runner.os == 'Windows' && steps.ffmpeg-cache.outputs.cache-hit != 'true'
shell: pwsh
run: |
$bins = "$env:RUNNER_TEMP\test-bins\ffmpeg"
New-Item -ItemType Directory -Path $bins -Force | Out-Null
winget install -e --id Gyan.FFmpeg --silent --accept-source-agreements --accept-package-agreements --disable-interactivity --location "$env:RUNNER_TEMP\ffmpeg_dir"
Copy-Item -Path "$env:RUNNER_TEMP\ffmpeg_dir\*\*" -Destination $bins -Recurse -Force
- name: Add ffmpeg to PATH (windows)
if: inputs.mode == 'start' && runner.os == 'Windows'
shell: pwsh
run: Add-Content -Path $env:GITHUB_PATH -Value "$env:RUNNER_TEMP\test-bins\ffmpeg\bin"
- name: Start recording (posix)
if: inputs.mode == 'start' && runner.os != 'Windows'
shell: bash
+46 -32
View File
@@ -1,56 +1,70 @@
name: Hermes Plugin Validate
description: >-
Validate a Hermes Agent plugin (plugin.yaml manifest schema AND
declared-vs-actually-registered capabilities) using
`hermes plugins validate`. Drop this into your plugin repo's CI:
- uses: actions/checkout@<sha>
- uses: NousResearch/hermes-agent/.github/actions/plugin-validate@main
with:
path: .
The caller's job owns checkout; this action installs Python + hermes-agent
(git install — a supported CI-context install route) and runs the
validator against your plugin directory.
Validate a plugin's manifest and registered capabilities with Hermes at the
requested ref. The caller owns its plugin checkout; Hermes and its locked
runtime are prepared separately under RUNNER_TEMP.
inputs:
path:
description: Path to the plugin directory (containing plugin.yaml).
default: "."
hermes-ref:
description: hermes-agent git ref (branch/tag/sha) to install and validate with.
description: hermes-agent git ref (branch/tag/sha) to validate with.
default: "main"
runs:
using: composite
steps:
- name: Set up Python
uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
with:
python-version: "3.11"
- name: Install hermes-agent
- name: Prepare an isolated Hermes checkout
id: source
shell: bash
env:
_HERMES_REF: ${{ inputs.hermes-ref }}
run: |
set -euo pipefail
# CI-context install from git; the ref lets plugin authors validate
# against a pinned hermes release instead of main.
pip install "git+https://github.com/NousResearch/hermes-agent@${_HERMES_REF}"
source=$(mktemp -d "$RUNNER_TEMP/hermes-plugin-validator.XXXXXX")
git init "$source"
git -C "$source" remote add origin https://github.com/NousResearch/hermes-agent.git
git -C "$source" fetch --depth=1 -- origin "$_HERMES_REF"
git -C "$source" checkout --detach FETCH_HEAD
printf 'source=%s\n' "$source" >> "$GITHUB_OUTPUT"
if [ "$RUNNER_OS" = Windows ]; then bootstrap=python; else bootstrap=python3; fi
"$bootstrap" -S "$source/scripts/ci/setup_toolchain.py" prepare \
--toolchain python --home "$source/.build/pm"
- name: Prepare the locked Python toolchain
shell: bash
env:
_SOURCE: ${{ steps.source.outputs.source }}
run: |
set -euo pipefail
if [ "$RUNNER_OS" = Windows ]; then bootstrap=python; else bootstrap=python3; fi
"$bootstrap" -S "$_SOURCE/scripts/ci/setup_toolchain.py" install \
--toolchain python --home "$_SOURCE/.build/pm"
- name: Build the isolated validator runtime
id: runtime
shell: bash
working-directory: ${{ steps.source.outputs.source }}
env:
_SOURCE: ${{ steps.source.outputs.source }}
run: |
set -euo pipefail
"$HERMES_PYTHON" - <<'PY'
import os
from pathlib import Path
from pm import build_environment
source = Path(os.environ["_SOURCE"])
python = build_environment(source=source, out=source / ".build/validator", explicit=True)
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output:
output.write(f"python={python}\n")
PY
- name: Validate plugin
shell: bash
env:
_PLUGIN_PATH: ${{ inputs.path }}
_VALIDATOR_PYTHON: ${{ steps.runtime.outputs.python }}
run: |
set -uo pipefail
# `hermes plugins validate` checks the plugin.yaml manifest schema
# and loads the plugin in a scratch subprocess to verify that the
# capabilities it DECLARES match what it actually registers.
if hermes plugins validate "$_PLUGIN_PATH"; then
echo "✅ PASS: plugin at '$_PLUGIN_PATH' validated cleanly"
else
echo "❌ FAIL: plugin at '$_PLUGIN_PATH' failed validation (see output above)"
exit 1
fi
set -euo pipefail
"$_VALIDATOR_PYTHON" -I -m hermes_cli.main plugins validate "$_PLUGIN_PATH"
+39
View File
@@ -0,0 +1,39 @@
# Bundle dependency caches
`setup-pm` restores uv's real cache, not the installed virtual environment.
Its fallback keys retain the native target, OS version, and Python version.
A metadata or dependency change can reuse compatible wheels;
uv still resolves and installs from the frozen project lock.
Bundle jobs set `save-python-cache: false` and call `save-pm-cache` after their
build step with the `python-path`, `uv-cache-path`, and `python-cache-key` outputs.
Both the caller and this composite use `!cancelled()` so a failed build does
not suppress the save. Cancellation is excluded to avoid racing a dying uv
process. A runner crash or job timeout can still prevent the save.
Snapshots use a run ID, attempt, and producer job suffix because Actions caches
are immutable. Sibling bundle workflows in one caller run must not race to save
different contents under the same key.
Restore tries the current dependency set's rolling snapshots first, then the
compatible v2 prefix. There is no fallback to older cache formats. This lets
a retry add wheels to a snapshot saved by a partially failed build. The ordinary
automatic cache path remains available.
Suffixed namespaces precede the native/dependency identity, outside production's
restore prefix.
Before saving, `python -m pm.build_env --exact-lock --cache PATH --lock-source REPO`
deletes every entry the project's `uv.lock` cannot resolve. It keeps downloaded
wheels the lock resolves (bundles copy the full cache for offline dependency
installation) — `uv cache prune --ci` would discard them. Pruning happens after
payload staging and packaging, and it does not change the staged payload.
The same lock-exactness contract governs the bundle ship gate
(`stage_uv_cache`) and CI's rolling snapshots, so no snapshot accumulates
sediment for superseded pins.
This is not a lockfile-aware or size-bounded cache. Old, still-referenced package
versions can remain inside a snapshot and be copied forward. GitHub evicts whole
cache snapshots under its retention and repository quota policies; that does
not remove old versions inside the newest snapshot. A future size policy must
account for the offline payload too, rather than deleting uv internals or
promising that `prune` keeps only the current lock.
+35
View File
@@ -0,0 +1,35 @@
name: Save the PM Python dependency cache
description: Prune to the lock and save a rolling cache after the consumer, even when it failed.
inputs:
python:
description: Prepared Python used to invoke PM.
required: true
path:
description: Cache directory exported by setup-pm.
required: true
key:
description: Rolling snapshot key exported by setup-pm.
required: true
runs:
using: composite
steps:
# Status checks are needed inside the composite too: the caller can
# enter after a failed build. Never prune while cancellation kills uv.
- name: Prune cache entries outside the project lock
id: prune
if: ${{ !cancelled() }}
shell: bash
env:
PM_PYTHON: ${{ inputs.python }}
PM_CACHE: ${{ inputs.path }}
PM_LOCK_SOURCE: ${{ github.workspace }}
# Exact-to-lock: downloaded wheels the lock resolves survive (bundles
# copy this cache for offline installs), while superseded pins do not
# accumulate. --ci was never usable here — it discards downloaded wheels.
run: '"$PM_PYTHON" -m pm.build_env --exact-lock --cache "$PM_CACHE" --lock-source "$PM_LOCK_SOURCE"'
- name: Save reusable Python dependencies
if: ${{ !cancelled() && steps.prune.outcome == 'success' }}
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ${{ inputs.path }}
key: ${{ inputs.key }}
+89
View File
@@ -0,0 +1,89 @@
# Locked CI toolchains
Check out this repository, then use `./.github/actions/setup-pm`. The runner's
preinstalled Python bootstraps PM with the standard library only. PM downloads
and verifies the exact native artifacts from `pm/lock.json`. The action does
not resolve a version range, install another setup action, or modify the lock.
```yaml
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: ./.github/actions/setup-pm
with:
toolchain: all
extras: '[]'
test-environment: 'true'
- run: python --version && node --version && npm --version
```
`toolchain` defaults to `python` (Python and PM's private installer). `node` installs Node and npm;
`all` installs both pairs. There are no version overrides. `extras` is a JSON
array because GitHub action inputs are strings. Omit it for tools only; `[]`
installs the core Python dependencies. Set `test-environment: 'true'` to build an
independent interpreter with the `dev` and `test` dependency groups; any `extras`
then select runtime features in that interpreter. PM checks `uv.lock`, installs
the requested dependencies, and validates the environment. Only non-test installs
publish an application selection. It does not enable plugins.
Subsequent steps get `python`, `python3`, `node`, `npm` and `npx`
for the selected toolchain on PATH. The pinned npm precedes Node's bundled npm.
On Windows, PM selects the host architecture even if the bootstrap interpreter
runs under x64 emulation. A disposable command environment supplies the missing
`python3.exe` alias without changing the verified interpreter store.
For Python dependencies, the action exports `HERMES_PYTHON` and `VIRTUAL_ENV`.
Use `scripts/run_tests.sh`; do not activate `.venv`. The environment belongs to
PM under the runner's temporary home, not the checkout. No installer executable
or `UV_*` policy variables are exposed. Tool-only jobs can prepare small isolated
CI environments with `python -m scripts.ci.python_packages package==version`.
This exports the selected Python and tool entrypoints for subsequent steps;
append `-- -m module ...` to run a Python command directly and preserve its exit
status. Neither route modifies the cached tool store. Native builds still need their system libraries
and compiler, such as OpenSSL for Windows ARM64 cryptography.
## Caches
The official, SHA-pinned `actions/cache` transports three independent caches:
| Cache | Contents | Identity |
| --- | --- | --- |
| Tools | PM store and installed facts | Native target, toolchain and PM lock hash |
| Python | PM's actual uv download/build cache | Native target, OS version, Python version, prune policy and dependency-file hash |
| Node | `npm config get cache` | Runner OS, native architecture and npm dependency-lock hash |
All restores use the exact primary key, without fallback prefixes, matching
setup-uv and setup-node's npm behavior. Successful jobs save at teardown;
exact hits are not saved again. Only dependency-carrying callers
(`extras` set or `test-environment: 'true'`) auto-save the uv cache: a tool-only job never runs a
dependency operation, so letting it save would freeze an empty cache under
the production key, where an immutable exact hit blocks real saves forever.
PM re-verifies restored tools before use.
Dependency caches never contain `node_modules` or virtual environments.
Keep an installed-tree cache in the caller if that job needs one.
`cache`, `cache-python` and `cache-node` independently disable the store, uv,
and npm caches. Each defaults to `true`; language-specific caches run only for
that toolchain. `python-cache-dependency-glob` defaults to `pyproject.toml` and
`uv.lock`. `node-cache-dependency-path` defaults to `package-lock.json`; use
`website/package-lock.json` for site jobs. Both accept multiline glob strings.
An npm cache without a matching lockfile fails, rather than caching an
unversioned dependency set.
`prune-python-cache: true` registers PM's lock-exact cache-pruning operation at teardown,
after the caller's installs and before the cache save. It is skipped on an
exact hit. The default is `false`, as in setup-uv v9; migrated v8 callers opt in
to retain their former policy. The small nested JavaScript action exists only
because GitHub composite actions cannot declare their own post step. It uses
Node's standard library and has no bundled dependencies. Pruning deletes cache
entries the project's `uv.lock` cannot resolve (the same exactness contract the
bundle ship gate enforces) and keeps downloaded wheels the lock still needs —
`uv cache prune --ci` would discard them, leaving a snapshot that warms almost
nothing.
Outputs include `python-version`, `uv-version`, `node-version`, `npm-version`,
`python-path`, `venv`, `target`, and the three `*-cache-hit` flags.
Use the version outputs in installed-tree cache keys instead of repeating pins.
The tools cache key hashes `pm/**`, this action, and `scripts/ci/setup_toolchain.py`,
so a provisioning change re-runs the cold path on every lane that uses the action
(`tests-os.yml` covers macOS and both Windows architectures). `cache-suffix` is an
optional namespace for isolated cache experiments; it changes lookup, not storage.
+235
View File
@@ -0,0 +1,235 @@
name: Set up the locked PM toolchain
description: Install Python/uv and Node/npm from pm/lock.json; cache tools and dependency downloads.
inputs:
toolchain:
description: python (Python and uv), node (Node and npm), or all.
default: python
packages:
description: Comma-separated extra PM tools to install beyond the toolchain roots (e.g. ffmpeg). Rides the tools cache like npm/uv.
default: ''
archive-inputs:
description: Use protected R2 credentials to preserve and retrieve the selected toolchain before installation.
default: 'false'
extras:
description: 'JSON runtime extras: omit for tools; [] installs core. Used as test coverage extras with test-environment.'
default: ''
test-environment:
description: 'Build an isolated interpreter with the dev and test groups; never publish these to the runtime environment.'
default: 'false'
cache:
description: Cache the verified PM tool store.
default: 'true'
save-tools-cache:
description: Save the verified PM tools on success. Set false for restore-only jobs.
default: 'true'
cache-python:
description: Cache uv downloads and built wheels; never cache the dependency environment.
default: 'true'
save-python-cache:
description: Save automatically on success. Set false to save a rolling snapshot with save-pm-cache after the consumer, including on failure.
default: 'true'
cache-node:
description: Cache npm downloads; never cache node_modules.
default: 'true'
save-node-cache:
description: Save automatically on success. Set false to save a consumer-scoped rolling snapshot with actions/cache/save after npm preparation.
default: 'true'
python-cache-dependency-glob:
description: Dependency files that invalidate the uv cache.
default: |
pyproject.toml
uv.lock
node-cache-dependency-path:
description: npm lockfiles that invalidate the npm download cache; supports multiline globs.
default: package-lock.json
prune-python-cache:
description: Use uv cache prune --ci before automatic saves. Explicit bundle saves preserve downloaded wheels.
default: 'false'
cache-suffix:
description: Optional namespace for isolated cache smoke tests.
default: ''
outputs:
python-version:
description: Locked CPython version, without the PBS build suffix.
value: ${{ steps.prepare.outputs.python-version }}
uv-version:
description: Locked uv version.
value: ${{ steps.prepare.outputs.uv-version }}
node-version:
description: Locked Node version.
value: ${{ steps.prepare.outputs.node-version }}
npm-version:
description: Locked npm version.
value: ${{ steps.prepare.outputs.npm-version }}
python-path:
description: Interpreter for subsequent steps, including requested extras.
value: ${{ steps.dependencies.outputs.python-path || steps.install.outputs.python-path }}
venv:
description: Dependency environment; isolated test environment for dev, otherwise PM-selected runtime.
value: ${{ steps.dependencies.outputs.venv }}
target:
description: Native PM target, independent of the bootstrap interpreter architecture.
value: ${{ steps.prepare.outputs.target }}
tools-cache-hit:
description: Exact PM store cache hit.
value: ${{ steps.tools-cache.outputs.cache-hit || steps.tools-cache-restore.outputs.cache-hit }}
python-cache-hit:
description: Exact uv dependency cache hit.
value: ${{ steps.python-cache.outputs.cache-hit || steps.python-cache-restore.outputs.cache-hit }}
python-cache-key:
description: Rolling snapshot key for save-pm-cache when save-python-cache is false.
value: ${{ steps.python-cache-restore.outputs.cache-primary-key }}
uv-cache-path:
description: Shared uv cache directory for save-pm-cache.
value: ${{ steps.install.outputs.uv-cache-path }}
node-cache-hit:
description: Exact npm dependency cache hit.
value: ${{ steps.node-cache.outputs.cache-hit || steps.node-cache-restore.outputs.cache-hit }}
node-cache-key:
description: Rolling snapshot key when save-node-cache is false.
value: ${{ steps.node-cache-restore.outputs.cache-primary-key }}
npm-cache-path:
description: npm download cache directory for an explicit consumer save.
value: ${{ steps.install.outputs.npm-cache-path }}
runs:
using: composite
steps:
- name: Read PM pins with the runner bootstrap Python
id: prepare
shell: bash
env:
_PM_ACTION: ${{ github.action_path }}
_PM_TOOLCHAIN: ${{ inputs.toolchain }}
_PM_EXTRAS: ${{ inputs.extras }}
_PM_PACKAGES: ${{ inputs.packages }}
run: |
set -euo pipefail
# Windows provides python, not necessarily python3. The host resolver
# in PM still selects ARM64 when this bootstrap Python runs under x64.
if [ "$RUNNER_OS" = Windows ]; then bootstrap=python; else bootstrap=python3; fi
"$bootstrap" -S "$_PM_ACTION/../../../scripts/ci/setup_toolchain.py" prepare \
--toolchain "$_PM_TOOLCHAIN" --extras "$_PM_EXTRAS" --packages "$_PM_PACKAGES" --home "$RUNNER_TEMP/setup-pm"
# The key covers the PM code and this action, not only the lock: a
# provisioning change must re-run the cold path on every lane rather
# than restore a store the previous code wrote.
- name: Cache verified PM tools
id: tools-cache
if: inputs.cache == 'true' && inputs.save-tools-cache == 'true'
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ${{ steps.prepare.outputs.store }}
key: setup-pm-tools-v1-${{ steps.prepare.outputs.target }}-${{ inputs.toolchain }}${{ steps.prepare.outputs.extra-packages }}-${{ hashFiles('pm/**', '.github/actions/setup-pm/**', 'scripts/ci/setup_toolchain.py') }}-${{ inputs.cache-suffix }}
- name: Restore verified PM tools without saving
id: tools-cache-restore
if: inputs.cache == 'true' && inputs.save-tools-cache == 'false'
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ${{ steps.prepare.outputs.store }}
key: setup-pm-tools-v1-${{ steps.prepare.outputs.target }}-${{ inputs.toolchain }}${{ steps.prepare.outputs.extra-packages }}-${{ hashFiles('pm/**', '.github/actions/setup-pm/**', 'scripts/ci/setup_toolchain.py') }}-${{ inputs.cache-suffix }}
- name: Preserve and retrieve the pinned toolchain
if: inputs.archive-inputs == 'true'
shell: bash
env:
_PM_ACTION: ${{ github.action_path }}
_PM_BOOTSTRAP: ${{ steps.prepare.outputs.bootstrap-python }}
_PM_TOOLCHAIN: ${{ inputs.toolchain }}
_PM_PACKAGES: ${{ inputs.packages }}
run: |
"$_PM_BOOTSTRAP" -S "$_PM_ACTION/../../../scripts/ci/setup_toolchain.py" archive-inputs \
--toolchain "$_PM_TOOLCHAIN" --packages "$_PM_PACKAGES" --home "$HERMES_HOME"
- name: Install and verify tools through PM
id: install
shell: bash
env:
_PM_ACTION: ${{ github.action_path }}
_PM_BOOTSTRAP: ${{ steps.prepare.outputs.bootstrap-python }}
_PM_TOOLCHAIN: ${{ inputs.toolchain }}
_PM_PACKAGES: ${{ inputs.packages }}
run: |
"$_PM_BOOTSTRAP" -S "$_PM_ACTION/../../../scripts/ci/setup_toolchain.py" install \
--toolchain "$_PM_TOOLCHAIN" --packages "$_PM_PACKAGES" --home "$HERMES_HOME"
- name: Cache uv dependency downloads and builds
id: python-cache
if: inputs.toolchain != 'node' && inputs.cache-python == 'true' && inputs.save-python-cache == 'true' && (inputs.extras != '' || inputs.test-environment == 'true')
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ${{ steps.install.outputs.uv-cache-path }}
# pruned/unpruned share one namespace: the pre-save prune is now exact
# to the lock (keeps lock-required wheels, drops superseded pins), so
# both variants carry the same content contract.
key: setup-pm-uv-v3-${{ inputs.cache-suffix || 'production' }}-${{ steps.prepare.outputs.target }}-${{ steps.prepare.outputs.os-version }}-${{ steps.prepare.outputs.python-version }}-${{ hashFiles(inputs.python-cache-dependency-glob) || 'no-dependency-glob' }}
# Isolated writes also need a distinct prefix: production's broad
# fallback must not restore a smoke run's partial dependency set.
restore-keys: ${{ inputs.cache-suffix == '' && format('setup-pm-uv-v3-production-{0}-{1}-{2}-', steps.prepare.outputs.target, steps.prepare.outputs.os-version, steps.prepare.outputs.python-version) || '' }}
- name: Restore uv dependencies for an explicit save
id: python-cache-restore
if: inputs.toolchain != 'node' && inputs.cache-python == 'true' && inputs.save-python-cache == 'false'
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ${{ steps.install.outputs.uv-cache-path }}
# Caches are immutable. Each producer needs its own snapshot, even
# when a caller run contains both PM Bundle and Desktop Release.
key: setup-pm-uv-v3-${{ inputs.cache-suffix || 'production' }}-${{ steps.prepare.outputs.target }}-${{ steps.prepare.outputs.os-version }}-${{ steps.prepare.outputs.python-version }}-${{ hashFiles(inputs.python-cache-dependency-glob) || 'no-dependency-glob' }}-${{ github.run_id }}-${{ github.run_attempt }}-${{ github.job }}
restore-keys: |
setup-pm-uv-v3-${{ inputs.cache-suffix || 'production' }}-${{ steps.prepare.outputs.target }}-${{ steps.prepare.outputs.os-version }}-${{ steps.prepare.outputs.python-version }}-${{ hashFiles(inputs.python-cache-dependency-glob) || 'no-dependency-glob' }}-
${{ inputs.cache-suffix == '' && format('setup-pm-uv-v3-production-{0}-{1}-{2}-', steps.prepare.outputs.target, steps.prepare.outputs.os-version, steps.prepare.outputs.python-version) || '' }}
# Post steps run in reverse registration order: prune before cache save.
- name: Register uv cache pruning
if: inputs.toolchain != 'node' && inputs.cache-python == 'true' && inputs.save-python-cache == 'true' && inputs.prune-python-cache == 'true' && steps.python-cache.outputs.cache-hit != 'true'
uses: ./.github/actions/setup-pm/prune
with:
python: ${{ steps.install.outputs.python-path }}
cache: ${{ steps.install.outputs.uv-cache-path }}
lock-source: ${{ github.workspace }}
- name: Require an npm dependency lock for caching
if: inputs.toolchain != 'python' && inputs.cache-node == 'true' && hashFiles(inputs.node-cache-dependency-path) == ''
shell: bash
run: |
printf '%s\n' '::error::No npm lock matched node-cache-dependency-path.'
exit 1
- name: Cache npm dependency downloads
id: node-cache
if: inputs.toolchain != 'python' && inputs.cache-node == 'true' && inputs.save-node-cache == 'true'
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ${{ steps.install.outputs.npm-cache-path }}
key: node-cache-${{ runner.os }}-${{ steps.prepare.outputs.arch }}-npm-${{ hashFiles(inputs.node-cache-dependency-path) }}${{ inputs.cache-suffix != '' && format('-{0}', inputs.cache-suffix) || '' }}
# A lockfile bump misses the exact key, but the previous download set
# is still mostly valid — npm verifies every tarball it reinstalls.
restore-keys: |
node-cache-${{ runner.os }}-${{ steps.prepare.outputs.arch }}-npm-
- name: Restore npm dependencies for an explicit save
id: node-cache-restore
if: inputs.toolchain != 'python' && inputs.cache-node == 'true' && inputs.save-node-cache == 'false'
uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ${{ steps.install.outputs.npm-cache-path }}
# Scope producers so tool-only jobs cannot replace a full desktop cache.
key: setup-pm-npm-v1-${{ inputs.cache-suffix || 'production' }}-${{ steps.prepare.outputs.target }}-${{ steps.prepare.outputs.npm-version }}-${{ hashFiles(inputs.node-cache-dependency-path) }}-${{ github.job }}-${{ github.run_id }}-${{ github.run_attempt }}
restore-keys: setup-pm-npm-v1-${{ inputs.cache-suffix || 'production' }}-${{ steps.prepare.outputs.target }}-${{ steps.prepare.outputs.npm-version }}-${{ hashFiles(inputs.node-cache-dependency-path) }}-${{ github.job }}-
- name: Install the requested Python dependencies through PM
id: dependencies
if: inputs.extras != '' || inputs.test-environment == 'true'
shell: bash
env:
_PM_ACTION: ${{ github.action_path }}
_PM_TOOLCHAIN: ${{ inputs.toolchain }}
_PM_EXTRAS: ${{ inputs.extras }}
_PM_TEST_ENVIRONMENT: ${{ inputs.test-environment }}
run: |
args=()
if [ "$_PM_TEST_ENVIRONMENT" = true ]; then args+=(--test-environment); fi
"$HERMES_PYTHON" -S "$_PM_ACTION/../../../scripts/ci/setup_toolchain.py" dependencies \
--toolchain "$_PM_TOOLCHAIN" --extras "$_PM_EXTRAS" --home "$HERMES_HOME" "${args[@]}"
+17
View File
@@ -0,0 +1,17 @@
name: Prune the PM uv cache at job teardown
description: Register lock-exact pruning before the enclosing cache action saves.
inputs:
python:
description: Prepared Python used to invoke the PM cache operation.
required: true
cache:
description: Cache directory restored by the enclosing setup action.
required: true
lock-source:
description: Repository checkout whose uv.lock selects the kept entries.
required: true
runs:
using: node24
main: index.mjs
post: index.mjs
post-if: success()
+31
View File
@@ -0,0 +1,31 @@
import { spawnSync } from 'node:child_process'
import { appendFileSync } from 'node:fs'
import { pathToFileURL } from 'node:url'
// Composite actions cannot register a post step. Called after actions/cache,
// this action's post runs first, pruning the cache just before it is saved.
export function run(env, execute = spawnSync) {
if (!env.STATE_python) {
// The runner keeps hyphens when it maps an input to INPUT_<NAME>.
for (const [key, value] of Object.entries({ python: env.INPUT_PYTHON, cache: env.INPUT_CACHE, lockSource: env['INPUT_LOCK-SOURCE'] })) {
if (!value || /[\r\n\0]/.test(value)) throw new Error(`invalid ${key}`)
appendFileSync(env.GITHUB_STATE, `${key}=${value}\n`, 'utf8')
}
return
}
// Exact-to-lock pruning keeps every wheel the project's uv.lock resolves —
// including downloaded ones. `--ci` pruning discarded downloaded wheels so
// the saved snapshot warmed almost nothing; bundling later ships this same
// cache only after its own exact-lock gate, so exactness is the shared
// contract, and sediment for superseded pins never accumulates.
const result = execute(env.STATE_python, ['-m', 'pm.build_env', '--exact-lock', '--cache', env.STATE_cache, '--lock-source', env.STATE_lockSource], {
env,
stdio: 'inherit',
})
if (result.error) throw result.error
if (result.status !== 0) throw new Error(`PM cache prune failed: ${result.status}`)
}
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
run(process.env)
}
@@ -0,0 +1,21 @@
name: Set up native Windows ARM64 build dependencies
description: Prepare MSVC, SDK, Clang, Rust and static OpenSSL through the shared PowerShell installer.
runs:
using: composite
steps:
- name: Cache ARM64 OpenSSL development files
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
# Cache libraries and headers only, not a vcpkg checkout or machine state.
path: C:\vcpkg\installed\arm64-windows-static-md
key: windows-build-deps-v2-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/windows-build-deps.ps1', 'scripts/build/windows-deps.ps1') }}
- name: Initialize the native build environment
shell: powershell
env:
_WINDOWS_BUILD_ACTION: ${{ github.action_path }}
run: |
& "$env:_WINDOWS_BUILD_ACTION/../../../scripts/build/windows-deps.ps1" `
-StateRoot "$env:RUNNER_TEMP/windows-build-deps" `
-OpenSSLRoot 'C:\vcpkg' `
-GithubEnv $env:GITHUB_ENV -GithubPath $env:GITHUB_PATH
+49
View File
@@ -0,0 +1,49 @@
name: Archive pinned PM inputs
on:
push:
branches: [main]
paths:
- 'pm/lock.json'
- 'pm/artifact-mirror.json'
- 'scripts/termux/runtime_libs.json'
- 'scripts/ci/archive_inputs.py'
- '.github/workflows/archive-inputs.yml'
workflow_call:
inputs:
sha:
description: 'The admitted commit whose pins are archived.'
required: true
type: string
workflow_dispatch:
permissions:
contents: read
jobs:
archive-inputs:
name: Preserve every pinned HTTP input
if: github.event_name != 'pull_request' && github.event_name != 'pull_request_target'
runs-on: ubuntu-24.04
environment: release-signing
timeout-minutes: 60
env:
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 }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ inputs.sha || github.sha }}
persist-credentials: false
# Runner Python is intentional: the toolchain's upstream may be gone.
# A job-level `if` cannot read `secrets`; the job env can. Forks and a
# repo whose release-signing environment is not provisioned yet must
# skip the archive, not turn main red.
- name: Verify and archive every pinned input
if: env.CLOUDFLARE_R2_ACCOUNT_ID != ''
run: python3 -m scripts.ci.archive_inputs
- name: Report the unprovisioned archive
if: env.CLOUDFLARE_R2_ACCOUNT_ID == ''
run: echo "::notice::CLOUDFLARE_R2_* secrets are not configured; pinned inputs were not archived."
+156
View File
@@ -0,0 +1,156 @@
name: Bootstrap installer
# Exercises the bootstrap-installer path on PRs that can affect it: the
# POSIX shell installer (scripts/install.sh), its generated pin fragments,
# and the version stamp the `complete` stage ships. The PowerShell installer's
# native tests run in the tests-os Windows lanes; this lane runs the
# protocol/stamp cross-checks plus a whole current installer against a tiny
# application graph. The latter runs real PM/uv and generated launchers, not
# every production extra. Tool download/hash tests remain separate.
on:
workflow_call:
permissions:
contents: read
concurrency:
group: bootstrap-installer-${{ github.ref_type == 'tag' && github.run_id || github.ref }}
cancel-in-progress: ${{ github.ref_type != 'tag' }}
jobs:
posix:
name: install.sh protocol + small fresh-install E2E
runs-on: ubuntu-24.04
timeout-minutes: 15
# NOTE: `runner.temp` is only available in step-level env, not job-level
# env — a job-env `${{ runner.temp }}` makes GitHub reject the workflow
# graph at dispatch (0 jobs). Each step that needs these exports them.
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
# The mirror step pushes HEAD to a fresh bare repo — a shallow
# checkout can't (git: "shallow update not allowed").
fetch-depth: 0
- name: Stage manifest is well-formed protocol v1 (piped, as `curl | bash` runs it)
shell: bash
run: |
cat scripts/install.sh | bash -s -- --manifest | python3 -c '
import json, sys
m = json.load(sys.stdin)
assert m["protocol_version"] == 1, m
names = [s["name"] for s in m["stages"]]
expected = ["prerequisites", "repository", "venv", "python-deps",
"config", "products", "setup", "gateway", "complete"]
assert names == expected, names
assert m["stages"][-1]["name"] == "complete"
print("stage manifest ok:", " -> ".join(names))
'
- name: Generated bootstrap pins match pm/lock.json
shell: bash
run: python3 scripts/gen-bootstrap-pins.py --check
- name: Publish the PR checkout as the install source
id: source
shell: bash
run: |
# The installer clones --branch <branch>; a PR checkout is a
# detached HEAD, so mirror it onto a named branch first.
mirror="$RUNNER_TEMP/source-mirror.git"
git init --bare "$mirror"
sha="$(git rev-parse HEAD)"
git push "$mirror" "HEAD:refs/heads/ci-under-test"
echo "mirror=$mirror" >> "$GITHUB_OUTPUT"
echo "sha=$sha" >> "$GITHUB_OUTPUT"
- name: Check repository/config/completion protocol (not a working install)
shell: bash
env:
# install.sh reads HERMES_INSTALL_DIR, not INSTALL_DIR (its default
# is $HOME/.hermes/hermes-agent); the marker/verification steps
# below use the same env var so they agree on the install root.
HERMES_INSTALL_DIR: ${{ runner.temp }}/bootstrap-install
HERMES_HOME: ${{ runner.temp }}/hermes-home
HERMES_RUNTIME_DIR: ${{ runner.temp }}/hermes-tools
HERMES_REPO_URL: ${{ steps.source.outputs.mirror }}
run: |
set -euo pipefail
sha="${{ steps.source.outputs.sha }}"
run_stage() {
echo "::group::stage $1"
bash scripts/install.sh --branch ci-under-test --commit "$sha" \
--non-interactive --stage "$1" --json
echo "::endgroup::"
}
run_stage prerequisites
run_stage repository
run_stage config
run_stage complete
test -f "$HERMES_INSTALL_DIR/.hermes-bootstrap-complete"
- name: Verify the shipped version stamp
shell: bash
env:
HERMES_INSTALL_DIR: ${{ runner.temp }}/bootstrap-install
run: |
python3 scripts/verify-bootstrap-version-stamp.py \
--stamp "$HERMES_INSTALL_DIR/.hermes-bootstrap-complete" \
--repo "$HERMES_INSTALL_DIR" \
--expect-commit "${{ steps.source.outputs.sha }}" \
--expect-branch ci-under-test \
--no-source-stamp # the protocol check above skips the products stage
- name: The pinned commit is on the branch the installer cloned
shell: bash
env:
HERMES_INSTALL_DIR: ${{ runner.temp }}/bootstrap-install
run: |
# The stamp must describe the bytes actually checked out: the
# installed repo's HEAD is exactly the commit the installer pinned.
head="$(git -C "$HERMES_INSTALL_DIR" rev-parse HEAD)"
test "$head" = "${{ steps.source.outputs.sha }}" \
|| { echo "::error::installed HEAD $head != pinned ${{ steps.source.outputs.sha }}"; exit 1; }
- name: Prepare tools for the real small-graph installer test
uses: ./.github/actions/setup-pm
- name: Prepare isolated acceptance-test dependencies
shell: bash
run: python -m scripts.ci.python_packages pytest==9.1.1 pytest-asyncio==1.3.0 ruamel.yaml==0.18.17 packaging==26.0
- name: Current installer to PM worker to published command
shell: bash
env:
HERMES_TEST_FILE_RETRIES: '0'
run: bash scripts/run_tests.sh tests/scripts/test_fresh_source_install.py -q -j 1
windows:
name: install.ps1 protocol surface
runs-on: windows-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
# Windows PowerShell 5.1 is what ships with Windows and what `irm | iex`
# lands in for most users — the protocol surface must parse there.
- name: Protocol version + stage manifest (Windows PowerShell 5.1)
shell: powershell
run: |
$pv = powershell -NoProfile -ExecutionPolicy Bypass -File scripts/install.ps1 -ProtocolVersion
if ("$pv" -ne "1") { Write-Error "protocol version '$pv' != 1"; exit 1 }
$json = powershell -NoProfile -ExecutionPolicy Bypass -File scripts/install.ps1 -Manifest | ConvertFrom-Json
if ($json.protocol_version -ne 1) { Write-Error "manifest protocol_version != 1"; exit 1 }
$names = @($json.stages | ForEach-Object { $_.name })
if ($names -notcontains "complete") { Write-Error "manifest missing complete stage"; exit 1 }
Write-Host "stage manifest ok: $($names -join ' -> ')"
- name: Protocol version + stage manifest (pwsh 7)
shell: pwsh
run: |
$pv = pwsh -NoProfile -File scripts/install.ps1 -ProtocolVersion
if ("$pv" -ne "1") { Write-Error "protocol version '$pv' != 1"; exit 1 }
$json = pwsh -NoProfile -File scripts/install.ps1 -Manifest | ConvertFrom-Json
if ($json.protocol_version -ne 1) { Write-Error "manifest protocol_version != 1"; exit 1 }
Write-Host "stage manifest ok (pwsh 7)"
+81
View File
@@ -0,0 +1,81 @@
name: Canary Release
# Automatic canaries are daily: the schedule caps new tags at one per 24h.
# With no new commits, release.py resumes an existing unpublished canary until
# its protected head is live; only a published canary makes a quiet day a no-op.
# workflow_dispatch fires one on demand at any time.
#
# Source identity is the exact stable version plus build metadata:
# v<stable>+canary.<YYYYMMDDTHHMMSSZ>. It compares equal to the stable; only
# the protected R2 canary head moves subscribers. A dispatch queued behind a
# running canary has conclusion=cancelled if a newer one supersedes it; only
# conclusion=failure is a canary failure signal.
on:
schedule:
- cron: "41 6 * * *" # daily, 06:41 UTC
workflow_dispatch:
permissions:
contents: write # tag push + release create/delete for prune
actions: write # release.py dispatches the desktop build
concurrency:
group: canary-release
cancel-in-progress: false
jobs:
tag:
name: Tag, draft, and start the canary build
runs-on: ubuntu-24.04
# A dispatch from a feature branch would tag unmerged code as the canary.
if: github.ref_name == github.event.repository.default_branch
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
# The changelog walks commits since the previous canary tag
fetch-depth: 0
# the tag math reads the full tag list
fetch-tags: true
- name: Tag and draft
env:
GH_TOKEN: ${{ github.token }}
run: |
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
python3 scripts/release.py --canary --publish --remote origin
prune:
name: Prune canaries older than 14 days
runs-on: ubuntu-24.04
needs: tag
environment: release-signing
# Prune even when this run had nothing new to tag. The desktop build
# runs in its own workflow run, so this does not wait on it — the
# window is 14 days, far wider than any build.
if: always() && needs.tag.result != 'cancelled' && needs.tag.result != 'skipped'
# Job-level so the R2 prune step can gate on `env` (a step `if` cannot
# read `secrets`): an unprovisioned release-signing environment skips
# the R2 prune instead of failing the canary run.
env:
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 }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
fetch-depth: 0
fetch-tags: true
- name: Prune
env:
GH_TOKEN: ${{ github.token }}
run: python3 scripts/release.py --prune-canaries --publish --remote origin
- uses: ./.github/actions/setup-pm
if: env.CLOUDFLARE_R2_ACCOUNT_ID != ''
with:
cache-python: false
- name: Prune R2 canary objects
if: env.CLOUDFLARE_R2_ACCOUNT_ID != ''
run: python -m scripts.ci.python_packages ruamel.yaml==0.18.17 -- -m scripts.releases.r2 prune-canaries --keep-days 14
+102 -46
View File
@@ -15,6 +15,20 @@ name: CI
# main-only automation uses protected environments in its own workflows.
on:
workflow_dispatch:
inputs:
release:
description: 'Stable-release candidate run: force every applicability lane and make the aggregate gate strict (skipped required lanes fail).'
required: false
type: boolean
default: false
workflow_call:
inputs:
release:
description: 'Stable-release candidate run: force every applicability lane and make the aggregate gate strict (skipped required lanes fail).'
required: false
type: boolean
default: false
pull_request:
push:
branches: [main]
@@ -23,34 +37,46 @@ permissions:
contents: read
pull-requests: write # needed by lint (PR comment) + supply-chain review_status
# cancel-in-progress only ever applies to PR events. A push, a dispatch, and
# above all a stable-release workflow_call run are never cancelled by a later
# commit or a rerun of the same branch — the caller's own concurrency uses
# github.run_id, so even a parent rerun cannot kill this child mid-flight.
# Release (workflow_call with inputs.release) never cancels and never gets
# cancelled: its group is github.run_id. PRs collapse per-PR; pushes use the
# ref as before.
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
group: ci-${{ inputs.release == true && github.run_id || (github.event_name == 'pull_request' && github.event.pull_request.number || github.ref) }}
cancel-in-progress: ${{ inputs.release != true && github.event_name == 'pull_request' }}
jobs:
# ─────────────────────────────────────────────────────────────────────
# detect: run the classifier once. Every downstream job reads its outputs
# to decide whether to run. On push/dispatch the classifier fails open
# (all lanes true) so post-merge validation is never weakened.
#
# A release run (inputs.release) additionally forces every lane true via
# the `release-forced-*` outputs: a stable candidate must run the FULL
# pipeline, not the lanes its diff would touch — the diff of a release
# tag is not a meaningful applicability signal.
# ─────────────────────────────────────────────────────────────────────
detect:
name: Detect affected areas
runs-on: ubuntu-latest
timeout-minutes: 1
outputs:
python: ${{ steps.classify.outputs.python }}
python_prod: ${{ steps.classify.outputs.python_prod }}
frontend: ${{ steps.classify.outputs.frontend }}
site: ${{ steps.classify.outputs.site }}
scan: ${{ steps.classify.outputs.scan }}
deps: ${{ steps.classify.outputs.deps }}
uv_lock: ${{ steps.classify.outputs.uv_lock }}
npm_lock: ${{ steps.classify.outputs.npm_lock }}
installer: ${{ steps.classify.outputs.installer }}
desktop_updater: ${{ steps.classify.outputs.desktop_updater }}
rust: ${{ steps.classify.outputs.rust }}
docker_meta: ${{ steps.classify.outputs.docker_meta }}
mcp_catalog: ${{ steps.classify.outputs.mcp_catalog }}
python: ${{ steps.gate-lanes.outputs.python }}
python_prod: ${{ steps.gate-lanes.outputs.python_prod }}
frontend: ${{ steps.gate-lanes.outputs.frontend }}
site: ${{ steps.gate-lanes.outputs.site }}
scan: ${{ steps.gate-lanes.outputs.scan }}
deps: ${{ steps.gate-lanes.outputs.deps }}
uv_lock: ${{ steps.gate-lanes.outputs.uv_lock }}
npm_lock: ${{ steps.gate-lanes.outputs.npm_lock }}
bootstrap: ${{ steps.gate-lanes.outputs.bootstrap }}
desktop_updater: ${{ steps.gate-lanes.outputs.desktop_updater }}
rust: ${{ steps.gate-lanes.outputs.rust }}
docker_meta: ${{ steps.gate-lanes.outputs.docker_meta }}
mcp_catalog: ${{ steps.gate-lanes.outputs.mcp_catalog }}
ci_review: ${{ steps.classify.outputs.ci_review }}
ci_review_files: ${{ steps.classify.outputs.ci_review_files }}
event_name: ${{ github.event_name }}
@@ -60,9 +86,26 @@ jobs:
id: classify
uses: ./.github/actions/detect-changes
with:
sparse-checkout: scripts/ci/classify_changes.py
sparse-checkout-cone-mode: false
github-token: ${{ github.token }}
- name: Force all lanes on release
# Overwrite the classifier outputs with 'true' when inputs.release.
# ci_review stays raw: it only ever feeds the PR review-label gate.
id: gate-lanes
env:
RELEASE: ${{ inputs.release }}
CLASSIFIED: ${{ toJSON(steps.classify.outputs) }}
run: |
python3 - <<'PY'
import json, os
values = json.loads(os.environ['CLASSIFIED'])
with open(os.environ['GITHUB_OUTPUT'], 'a', encoding='utf-8') as output:
for lane, value in values.items():
if os.environ['RELEASE'] == 'true' and value in ('true', 'false'):
value = 'true'
if '\n' in value or '\r' in value:
continue
output.write(f'{lane}={value}\n')
PY
# ─────────────────────────────────────────────────────────────────────
# Lane-gated sub-workflows. Each runs in parallel after detect finishes.
@@ -86,7 +129,7 @@ jobs:
with:
# The Windows lane spawns the real desktop-update hand-off script
# (tests/test_desktop_update_windows_*.py) only when that surface
# changed; unit-level windows_only tests always run.
# changed; unit-level platforms("windows") tests always run.
desktop_updater: ${{ needs.detect.outputs.desktop_updater == 'true' }}
lint:
@@ -103,13 +146,6 @@ jobs:
if: needs.detect.outputs.frontend == 'true'
uses: ./.github/workflows/js-tests.yml
installer-tests:
name: Installer tests
needs: detect
# Windows-only, and only for PRs that touch install.ps1 or its tests.
if: needs.detect.outputs.installer == 'true'
uses: ./.github/workflows/installer-tests.yml
rust-tests:
name: Rust tests
needs: detect
@@ -118,6 +154,15 @@ jobs:
if: needs.detect.outputs.rust == 'true'
uses: ./.github/workflows/rust-tests.yml
bootstrap-installer:
name: Bootstrap installer
needs: detect
# The bootstrap-installer path: install.sh, the pin fragments it embeds,
# and the version stamp it ships. The PowerShell installer's native tests
# are platforms("windows") pytest files and run in tests-os.
if: needs.detect.outputs.bootstrap == 'true'
uses: ./.github/workflows/bootstrap-installer.yml
e2e-desktop:
name: Desktop E2E
needs: detect
@@ -183,11 +228,21 @@ jobs:
needs: detect
uses: ./.github/workflows/profile-artifact-check.yml
icons-freshness-check:
name: Icon assets freshness
needs: detect
uses: ./.github/workflows/icons-freshness-check.yml
case-collision-check:
name: Check no case-colliding filenames
needs: detect
uses: ./.github/workflows/case-collision-check.yml
lazy-deps-guard:
name: No production imports of the tools.lazy_deps stub
needs: detect
uses: ./.github/workflows/lazy-deps-guard.yml
lockfile-diff:
name: package-lock.json diff
needs: detect
@@ -223,8 +278,14 @@ jobs:
# ─────────────────────────────────────────────────────────────────────
# Gate: runs after everything. ``if: always()`` ensures it reports a
# status even when some deps were skipped. Only actual ``failure``
# results cause it to fail; ``skipped`` is treated as success.
# status even when some deps were skipped.
#
# Non-release (PR/push): failure fails, skipped counts as success.
# Release (inputs.release): strict — every required job must be
# `success`. A skipped required lane fails the gate; only the PR-only
# jobs (history-check, lockfile-diff, supply-chain, review-labels) and
# the deferred Desktop E2E (e2e-desktop) may skip. The OSV scan's
# findings are advisory, but its execution is required.
#
# Branch protection should require ONLY this check.
#
@@ -239,18 +300,21 @@ jobs:
- tests-os
- lint
- js-tests
- installer-tests
- rust-tests
- bootstrap-installer
- e2e-desktop
- e2e-desktop-core
- docs-site
- history-check
- contributor-check
- uv-lockfile
- infographic-check
- case-collision-check
- lazy-deps-guard
- lockfile-diff
- docker-lint
- profile-artifact-check
- icons-freshness-check
- supply-chain
- review-labels
# OSV runs weekly against main (osv-scanner.yml schedule), not per PR:
@@ -267,29 +331,21 @@ jobs:
outputs:
needs-json: ${{ steps.evaluate.outputs.needs-json }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.sha }}
- name: Evaluate job results
id: evaluate
# Shared with the stable orchestrator (scripts/ci/required_results.py
# is imported there). NEEDS is the toJSON(needs) context; RELEASE
# switches the gate into strict mode for release runs.
env:
NEEDS: ${{ toJSON(needs) }}
RELEASE: ${{ inputs.release }}
run: |
echo "$NEEDS" | python3 -c "
import json, sys
needs = json.load(sys.stdin)
# Emit compact {job_name: result} for the comment assembler.
compact = {name: info['result'] for name, info in needs.items()}
print(f'needs-json={json.dumps(compact)}')
with open('$GITHUB_OUTPUT', 'a') as f:
f.write(f'needs-json={json.dumps(compact)}\n')
failed = [name for name, info in needs.items() if info['result'] == 'failure']
for name, info in sorted(needs.items()):
result = info['result']
icon = '✅' if result in ('success', 'skipped') else '❌'
print(f'{icon} {name}: {result}')
if failed:
print(f'::error::{len(failed)} job(s) failed: {\", \".join(failed)}')
sys.exit(1)
print('All checks passed (or were skipped)')
"
args=()
if [ "$RELEASE" = true ]; then args+=(--release); fi
printf '%s' "$NEEDS" | python3 scripts/ci/required_results.py "${args[@]}"
# ─────────────────────────────────────────────────────────────────────
# CI timing report: collect per-job/step durations from the GitHub API,
+4 -4
View File
@@ -39,7 +39,7 @@ jobs:
# An email is mapped if it has a file in contributors/emails/
# (one file per email — conflict-free) or an entry in the frozen
# legacy AUTHOR_MAP in scripts/release.py.
# legacy AUTHOR_MAP in scripts/releases/authors_legacy.py.
MISSING=""
while IFS= read -r email; do
# Skip teknium and bot emails
@@ -56,7 +56,7 @@ jobs:
continue # mapped via the contributors directory
fi
if ! grep -qF "\"${email}\"" scripts/release.py 2>/dev/null; then
if ! grep -qF "\"${email}\"" scripts/releases/authors_legacy.py 2>/dev/null; then
AUTHOR=$(git log --author="$email" --format='%an' -1)
MISSING="${MISSING}\n ${email} (${AUTHOR})"
fi
@@ -67,7 +67,7 @@ jobs:
echo "⚠️ New contributor email(s) without a mapping:"
echo -e "$MISSING"
echo ""
echo "Add a mapping file (do NOT edit AUTHOR_MAP in release.py):"
echo "Add a mapping file (do NOT edit AUTHOR_MAP in scripts/releases/authors_legacy.py):"
echo " python3 scripts/audit_pr_attribution.py --fix # auto-resolve + create files"
echo "or manually:"
echo -e "$MISSING" | while read -r line; do
@@ -81,7 +81,7 @@ jobs:
# Emit review_status for unmapped emails
DETAIL=$(echo -e "$MISSING" | sed '/^$/d; s/^ //')
HOW_TO_FIX=$'Run from the PR branch:\n```\npython3 scripts/audit_pr_attribution.py --fix\ngit add contributors && git commit -m "chore: map contributor emails" && git push\n```\nOr map one email manually (do NOT edit AUTHOR_MAP in release.py):\n```\npython3 scripts/add_contributor.py <email> <github-username>\n```\nTo find the GitHub username for an email:\n```\ngh api \'search/users?q=EMAIL+in:email\' --jq \'.items[0].login\'\n```\n'
HOW_TO_FIX=$'Run from the PR branch:\n```\npython3 scripts/audit_pr_attribution.py --fix\ngit add contributors && git commit -m "chore: map contributor emails" && git push\n```\nOr map one email manually (do NOT edit AUTHOR_MAP in scripts/releases/authors_legacy.py):\n```\npython3 scripts/add_contributor.py <email> <github-username>\n```\nTo find the GitHub username for an email:\n```\ngh api \'search/users?q=EMAIL+in:email\' --jq \'.items[0].login\'\n```\n'
REVIEW_STATUS=$(jq -nc \
--arg detail "$DETAIL" \
--arg how_to_fix "$HOW_TO_FIX" \
+12 -14
View File
@@ -68,24 +68,18 @@ jobs:
client-id: ${{ vars.APP_CLIENT_ID }}
private-key: ${{ secrets.APP_PRIVATE_KEY }}
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- name: Set up the locked site toolchain
id: pm
uses: ./.github/actions/setup-pm
with:
node-version: 26
cache: npm
cache-dependency-path: website/package-lock.json
toolchain: all
extras: '[]'
node-cache-dependency-path: website/package-lock.json
- name: grab npm 12
run: |
npm i -g npm@12
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
with:
python-version: '3.11'
- name: Install PyYAML for skill extraction
- name: Install ruamel.yaml for skill extraction
uses: ./.github/actions/retry
with:
command: pip install pyyaml==6.0.2 httpx==0.28.1
command: python -m scripts.ci.python_packages ruamel.yaml==0.18.17 httpx==0.28.1
- name: Prepare skills index (unified multi-source catalog)
env:
@@ -190,6 +184,10 @@ jobs:
- name: Build Docusaurus
run: npm run build
working-directory: website
env:
# prebuild renders icons on a Hermes runtime interpreter; the ci-tools
# step above re-exports HERMES_PYTHON to a tools-only environment.
HERMES_PYTHON: ${{ steps.pm.outputs.python-path }}
- name: Stage deployment
run: |
+239
View File
@@ -0,0 +1,239 @@
name: Desktop bundle smoke
on:
workflow_call:
inputs:
platform:
required: true
type: string
arch:
required: true
type: string
format:
required: true
type: string
sha:
required: true
type: string
tag:
default: ''
type: string
archive-tag:
description: Archive ref the handoffs are staged under (attempt ref for stable phases).
default: ''
type: string
commit-build:
default: false
type: boolean
channel-build:
default: ''
type: string
channel-request-sha256:
default: ''
type: string
controller-sha:
default: ''
type: string
disposable-run:
default: ''
type: string
public-root:
default: ''
type: string
public-base:
required: true
type: string
permissions:
contents: read
jobs:
validate:
name: Require a supported native smoke target
runs-on: ubuntu-24.04
timeout-minutes: 5
env:
TARGET: ${{ inputs.platform }}/${{ inputs.arch }}/${{ inputs.format }}
steps:
- name: Reject empty or unsupported native smoke jobs
shell: bash
run: |
case "$TARGET" in
darwin/arm64/dmg|darwin/x64/dmg|darwin/arm64/zip|darwin/x64/zip|win32/arm64/msix|win32/x64/msix|win32/arm64/msixbundle|win32/x64/msixbundle) ;;
*) echo '::error::unsupported native smoke target'; exit 1 ;;
esac
macos:
name: macOS install and chat
needs: validate
if: inputs.platform == 'darwin'
runs-on: ${{ inputs.arch == 'x64' && 'macos-15-intel' || 'macos-15' }}
timeout-minutes: 30
# Also constrains the recording action's nested cache to read-only.
cache-mode: read
env: &smoke-env
RELEASE_COMMIT: ${{ inputs.sha }}
RELEASE_TAG: ${{ inputs.tag }}
ARCHIVE_TAG: ${{ inputs.archive-tag }}
COMMIT_BUILD: ${{ inputs.commit-build }}
CHANNEL_BUILD: ${{ inputs.channel-build }}
CHANNEL_REQUEST_SHA256: ${{ inputs.channel-request-sha256 }}
PUBLIC_BASE: ${{ inputs.public-base }}
CLOUDFLARE_R2_PUBLIC_URL: ${{ inputs.public-root }}
R2_DISPOSABLE_RUN: ${{ inputs.disposable-run }}
PLATFORM: ${{ inputs.platform }}
ARCH: ${{ inputs.arch }}
FORMAT: ${{ inputs.format }}
steps: &smoke-steps
- name: Isolate smoke paths
shell: bash
run: printf 'SMOKE_ROOT=%s/bundle-smoke\n' "$RUNNER_TEMP" >> "$GITHUB_ENV"
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ inputs.channel-build != '' && inputs.controller-sha || inputs.sha }}
persist-credentials: false
- name: Set up driver tools only
id: tools
uses: ./.github/actions/setup-pm
with:
toolchain: all
packages: ffmpeg
cache: false
cache-python: false
cache-node: false
- name: Install locked chat driver dependencies
id: dependencies
shell: bash
run: npm ci --workspace tests-js --include-workspace-root --omit=dev --ignore-scripts --no-audit --no-fund
- name: Fetch one exact downloadable artifact
id: artifact
shell: bash
run: |
set -euo pipefail
mkdir -p "$SMOKE_ROOT/out"
product=HermesBundled
if [ -n "${CHANNEL_BUILD:-}" ]; then
test "$COMMIT_BUILD" = false
test -z "$RELEASE_TAG"
python -m scripts.releases.channel_publish request --build-id "$CHANNEL_BUILD" \
--request-sha256 "$CHANNEL_REQUEST_SHA256" --public-base "$PUBLIC_BASE" \
--out "$SMOKE_ROOT/request.json"
product=$(python -c 'import json,sys; print(json.load(open(sys.argv[1]))["identity"]["artifactNamePascal"])' "$SMOKE_ROOT/request.json")
fi
case "$PLATFORM/$ARCH/$FORMAT" in
darwin/arm64/dmg|darwin/x64/dmg|darwin/arm64/zip|darwin/x64/zip)
name="darwin-$ARCH"; pattern="$product-*-mac-$ARCH.$FORMAT" ;;
win32/arm64/msix|win32/x64/msix)
name="win32-$ARCH"; pattern="$product-*-win-$ARCH.msix" ;;
win32/arm64/msixbundle|win32/x64/msixbundle)
name=windows-universal; pattern="$product-*-win.msixbundle" ;;
*) echo '::error::unsupported native smoke target'; exit 1 ;;
esac
args=(--tag "${ARCHIVE_TAG:-$RELEASE_TAG}" --commit "$RELEASE_COMMIT")
if [ "$COMMIT_BUILD" = true ]; then
test -z "$RELEASE_TAG"
args=(--commit-build "$RELEASE_COMMIT")
fi
if [ -n "${CHANNEL_BUILD:-}" ]; then args=(--channel-request "$SMOKE_ROOT/request.json"); fi
python -m scripts.releases.handoff fetch --public-base "$PUBLIC_BASE" "${args[@]}" \
--name "$name" --root "$SMOKE_ROOT/download" --include "$pattern" 2>&1 | tee "$SMOKE_ROOT/out/fetch.log"
python - "$name" "$pattern" <<'PY'
import fnmatch, json, os, sys
from pathlib import Path
from scripts.releases.r2 import file_sha256
root = Path(os.environ['SMOKE_ROOT'])
receipt = root / 'download' / f'handoff-{sys.argv[1]}.json'
data = json.loads(receipt.read_text(encoding='utf-8'))
selected = [row for row in data['files'] if fnmatch.fnmatchcase(row['path'], sys.argv[2])]
if len(selected) != 1:
raise ValueError(f'Expected exactly one non-Store artifact, found {len(selected)}')
row = selected[0]
artifact = root / 'download' / row['path']
if artifact.stat().st_size != row['size'] or file_sha256(artifact) != row['sha256']:
raise ValueError('Downloaded artifact no longer matches its receipt')
(root / 'out' / 'download.json').write_text(json.dumps({
'commit': data['commit'], 'tag': data.get('tag'), 'receipt': receipt.name,
'receiptSha256': file_sha256(receipt), 'artifact': row, 'request': data.get('request'),
}, indent=2) + '\n', encoding='utf-8')
with open(os.environ['GITHUB_OUTPUT'], 'a', encoding='utf-8') as output:
output.write(f'path={artifact.resolve().as_posix()}\n')
PY
- name: Start screen recording
id: recording
uses: ./.github/actions/e2e-screen-record
with:
mode: start
output: ${{ env.SMOKE_ROOT }}/out/recording.mkv
- name: Install and chat on macOS
id: macos-chat
if: runner.os == 'macOS'
shell: bash
env:
ARTIFACT: ${{ steps.artifact.outputs.path }}
run: |
args=()
if [ -n "$RELEASE_TAG" ]; then args+=(--tag "$RELEASE_TAG"); fi
if [ -n "${CHANNEL_BUILD:-}" ]; then args+=(--channel-request "$SMOKE_ROOT/request.json"); fi
bash tests/install/macos-bundle-smoke.sh --artifact "$ARTIFACT" --arch "$ARCH" \
--commit "$RELEASE_COMMIT" "${args[@]}" --work "$SMOKE_ROOT/work" --out "$SMOKE_ROOT/out"
- name: Install and chat on Windows
id: windows-chat
if: runner.os == 'Windows'
shell: powershell
env:
ARTIFACT: ${{ steps.artifact.outputs.path }}
run: |
$tagArgs = @()
if ($env:RELEASE_TAG) { $tagArgs = @('-Tag', $env:RELEASE_TAG) }
if ($env:CHANNEL_BUILD) { $tagArgs = @('-ChannelRequest', "$env:SMOKE_ROOT/request.json") }
powershell -NoProfile -ExecutionPolicy Bypass -File tests/install/windows-bundle-smoke.ps1 -Artifact $env:ARTIFACT -Arch $env:ARCH -Commit $env:RELEASE_COMMIT @tagArgs -Work "$env:SMOKE_ROOT/work" -Out "$env:SMOKE_ROOT/out"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
- name: Stop screen recording
if: always()
# Evidence only. A failed stop must not fail a chat that already passed.
continue-on-error: true
uses: ./.github/actions/e2e-screen-record
with:
mode: stop
output: ${{ env.SMOKE_ROOT }}/out/recording.mkv
- name: Record smoke step outcomes
if: always()
shell: bash
env:
STEP_RESULTS: ${{ toJSON(steps) }}
run: |
mkdir -p "$SMOKE_ROOT/out"
printf '%s\n' "$STEP_RESULTS" > "$SMOKE_ROOT/out/steps.json"
- name: Upload smoke diagnostics
if: always()
# Evidence only. A 403 from the artifact store must not fail the smoke.
continue-on-error: true
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: desktop-smoke-${{ inputs.platform }}-${{ inputs.arch }}-${{ inputs.format }}-${{ github.run_id }}-${{ github.run_attempt }}
# Only evidence, never the isolated profile or installed application.
path: ${{ env.SMOKE_ROOT }}/out
if-no-files-found: warn
retention-days: 14
windows:
name: Windows install and chat
needs: validate
if: inputs.platform == 'win32'
runs-on: ${{ inputs.arch == 'arm64' && 'windows-latest-32-arm-core' || 'windows-latest-32-core' }}
# windows-11-arm runners are much slower (npm ci alone runs 12+ minutes and
# the MSIX leg exceeds 30 total); x64 legs complete in ~14.
timeout-minutes: 45
cache-mode: read
env: *smoke-env
steps: *smoke-steps
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -17,8 +17,8 @@ permissions:
contents: read
concurrency:
group: docker-lint-${{ github.ref }}
cancel-in-progress: true
group: docker-lint-${{ github.ref_type == 'tag' && github.run_id || github.ref }}
cancel-in-progress: ${{ github.ref_type != 'tag' }}
jobs:
hadolint:
+489 -88
View File
@@ -2,18 +2,47 @@ name: Docker Build, Test, and Publish
on:
# This workflow owns its own triggers. ci.yml does not call it.
# A reusable-workflow call eeps the caller run in progress for that full time.
# GitHub refuses ``gh run rerun`` on a run that is still in progress.
# A reusable-workflow call keeps the caller run in progress for that full time.
# GitHub refuses ``gh run rerun`` on a run that is still in progress.
# Thus one slow advisory job blocked every rerun of the fast required jobs. A separate
# run reruns and cancels independently.
#
# Trusted main pushes resolve the environment-scoped Docker Hub secrets in
# this same workflow, never across a workflow boundary.
#
# The ``release: published`` trigger was REMOVED on purpose: a GitHub release
# event must never rebuild or rewrite the stable Docker channel. This staged
# path publishes only immutable version tags; the ordered stable publication
# controller moves stable/latest from the receipt-bound registry digest.
pull_request:
push:
branches: [main]
release:
types: [published]
workflow_call:
inputs:
release-phase:
description: "Stable-release phase: 'test' or 'publish'. Empty keeps the standalone triggers."
required: false
type: string
default: ''
tag:
description: "Exact stable tag (vX.Y.Z) under release. The caller is dispatched on this tag, so github.sha is the release candidate."
required: false
type: string
default: ''
version:
description: "Release version written directly to the image install stamp."
required: false
type: string
default: ''
skip-tests:
description: "Release test phase only: build and archive the image without its integration tests (the claim skipped tests)."
required: false
type: boolean
default: false
outputs:
manifest-digest:
description: "Immutable digest of the published versioned multi-arch manifest."
value: ${{ jobs.release-publish-manifest.outputs.digest }}
permissions:
contents: read
@@ -21,21 +50,50 @@ permissions:
# Concurrency: push/release runs are NEVER cancelled so every merge gets
# its own image. PR runs reuse a PR-scoped group with
# cancel-in-progress: true so rapid pushes to the same PR collapse to
# the latest commit.
# the latest commit. Release runs include the run_id: several reusable calls
# (test/publish) of this workflow live inside ONE parent run, and a
# shared group would cancel the parent mid-release.
concurrency:
group: docker-${{ github.event.pull_request.number || github.ref }}
group: docker-${{ github.event.pull_request.number || github.ref }}-${{ inputs.release-phase || 'standalone' }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
IMAGE_NAME: nousresearch/hermes-agent
jobs:
# Resolve the release phase. Release modes run only via workflow_call from
# the parent stable-release workflow on the tagged candidate commit.
mode:
name: Resolve release phase
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
phase: ${{ steps.resolve.outputs.phase }}
release: ${{ steps.resolve.outputs.release }}
steps:
- id: resolve
env:
PHASE: ${{ inputs.release-phase }}
run: |
set -euo pipefail
case "$PHASE" in
'') echo "phase=standalone" >> "$GITHUB_OUTPUT"; echo "release=false" >> "$GITHUB_OUTPUT" ;;
test) echo "phase=test" >> "$GITHUB_OUTPUT"; echo "release=true" >> "$GITHUB_OUTPUT" ;;
publish)
echo "phase=$PHASE" >> "$GITHUB_OUTPUT"; echo "release=true" >> "$GITHUB_OUTPUT" ;;
*) echo "::error::Invalid release-phase input: $PHASE"; exit 1 ;;
esac
# Classify the PR's changed files. ci.yml used to gate the docker call on
# its own ``detect`` outputs; now that this workflow triggers itself, it
# runs the same composite action. On push and release the classifier fails
# open (every lane true), so post-merge validation is never weakened.
# Release phases skip classification entirely: the parent already ran full
# CI and the tag dispatch has no meaningful PR diff to classify.
detect:
name: Detect affected areas
needs: [mode]
if: needs.mode.outputs.release != 'true'
runs-on: ubuntu-latest
timeout-minutes: 10
outputs:
@@ -65,19 +123,28 @@ jobs:
echo "build=false" >> "$GITHUB_OUTPUT"
fi
# Build and test the image for each architecture. This job runs PR code,
# so it must remain secret-free. Publishing happens in the separate,
# protected publish job after these tests pass.
# Build and test the image for each architecture. This job runs PR code, so
# in standalone mode it must remain secret-free. Publishing happens in the
# separate, protected publish paths after these tests pass.
#
# Runs ONLY in standalone mode and in the release 'test' phase: it builds
# the SAME Dockerfile and runs the SAME real docker-integration tests, then
# (test phase) saves the tested per-arch image archive + sha256 as run
# artifacts. No registry push, no signing secrets. The publish phase never
# rebuilds — it downloads these exact artifacts.
build:
needs: [detect]
if: github.repository == 'NousResearch/hermes-agent' && needs.detect.outputs.build == 'true'
name: Build and test image (${{ matrix.variant }}/${{ matrix.arch }})
needs: [mode, detect]
if: >-
!cancelled() && needs.mode.result == 'success' &&
((needs.mode.outputs.release != 'true' && github.repository == 'NousResearch/hermes-agent' && needs.detect.outputs.build == 'true') || needs.mode.outputs.phase == 'test')
strategy:
fail-fast: false
matrix:
# Two images per arch. `slim` is what :latest has always been; `desktop`
# adds the Bot Screen packages and a headed Chromium (+1.4 GB) for the
# tier that offers a screen. Both are built on a PR so a change that only
# breaks the gated layers cannot reach publish.
# adds the Bot Screen packages and distro Chromium fallback for the
# tier that offers a screen. PM's pinned full Chromium is in both.
# Both are built on a PR so gated-layer failures cannot reach publish.
arch: [amd64, arm64]
variant: [slim, desktop]
include:
@@ -95,7 +162,31 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
# Release calls are dispatched on the stable tag: pin to the exact
# candidate commit, never a mutable branch ref.
ref: ${{ needs.mode.outputs.release == 'true' && github.sha || '' }}
# Dev identity is the distance from the highest reachable final
# release, so the stamp needs both its ancestry and release tags.
fetch-depth: 0
- name: Write install stamp
env:
RELEASE_VERSION: ${{ needs.mode.outputs.release == 'true' && inputs.version || '' }}
run: |
display="$RELEASE_VERSION"
if [ -z "$display" ]; then
display="$(python3 -m scripts.releases.distance)"
fi
identity=(--commit "$GITHUB_SHA")
if [ -n "$display" ]; then
base="${display%%+*}"
development="${display#*+}"
if [ "$development" = "$display" ]; then distance=0; else distance="${development%%.*}"; fi
identity+=(--base-version "$base" --display-version "$display" --distance "$distance")
fi
python3 scripts/write_install_stamp.py --output install-stamp.json \
--distribution docker --update-mechanism external --source ci "${identity[@]}"
- name: Reject profile exports in the build context
run: python3 scripts/ci/check_profile_archive_boundary.py
@@ -116,7 +207,7 @@ jobs:
# Build once, load into the local daemon for testing. Cached
# per-arch; the push step below reuses every layer from this build.
- name: Build image (${{ matrix.arch }})
- name: Build image (${{ matrix.variant }}/${{ matrix.arch }})
uses: docker/build-push-action@bcafcacb16a39f128d818304e6c9c0c18556b85f # v7.1.0
with:
context: .
@@ -125,51 +216,35 @@ jobs:
platforms: ${{ matrix.platform }}
tags: ${{ env.IMAGE_NAME }}:test
build-args: |
HERMES_GIT_SHA=${{ github.sha }}
HERMES_BOT_DESKTOP=${{ matrix.variant == 'desktop' && '1' || '0' }}
# Slim owns the scope; desktop is slim plus two RUN steps, so it reads
# and writes nothing — a 5.5 GB mode=max scope would blow the 10 GB cap.
# Slim owns the scope; desktop adds the gated apt layer, so it reads
# and writes nothing — a mode=max scope could exceed the cache cap.
cache-from: type=gha,scope=docker-${{ matrix.arch }}
cache-to: ${{ (github.event_name != 'pull_request' && matrix.variant == 'slim') && format('type=gha,mode=max,scope=docker-{0}', matrix.arch) || '' }}
# Run the docker-integration test suite against the freshly-built
# image already loaded into the local daemon (`:test`).
#
# Piggybacking here avoids a second image build: the build step
# already loaded the image into the daemon under
# `${IMAGE_NAME}:test`, so we just point ``HERMES_TEST_IMAGE`` at
# that. The fixture's ``HERMES_TEST_IMAGE`` branch (see
# tests/docker/conftest.py:62-63) short-circuits the rebuild.
#
# Why this job and not a standalone one: the image is 5GB+; passing
# it between jobs via ``docker save``/``upload-artifact`` is slower
# than the build itself. Reusing the existing daemon state is the
# cheapest path to coverage on every PR that touches docker code.
# ---------------------------------------------------------------------
- name: Install uv (for docker tests)
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0
with:
# Pinned: unpinned setup-uv fetches a 'latest' manifest from
# raw.githubusercontent.com every job; transient fetch failures
# fail the job (2026-07-28 incident). Keep in sync with tests.yml.
version: "0.9.28"
# Run the docker-integration test suite against the freshly-built image
# already loaded into the local daemon (`:test`). The fixture's
# HERMES_TEST_IMAGE branch short-circuits the rebuild. Release tests
# archive these exact bytes rather than rebuilding at publish time.
# Park the stamp while PM provisions the runner, then restore it so
# tests/docker can compare the image's provenance with the checkout.
- name: Park the image install stamp while provisioning the runner toolchain
run: mv install-stamp.json "$RUNNER_TEMP/install-stamp.json"
- name: Set up Python 3.11 (for docker tests)
uses: ./.github/actions/retry
- name: Set up locked Python and test dependencies
if: inputs.skip-tests != true
uses: ./.github/actions/setup-pm
with:
command: uv python install 3.11
extras: '[]'
test-environment: 'true'
prune-python-cache: true
- name: Install Python dependencies (for docker tests)
# ``dev`` extra pulls in pytest, pytest-asyncio —
# everything tests/docker/ needs. We deliberately avoid ``all``
# here because the docker tests only drive the container via
# subprocess and don't import hermes_agent's optional deps.
uses: ./.github/actions/retry
with:
command: uv sync --locked --python 3.11 --extra dev
- name: Restore the image install stamp for the docker tests
run: mv "$RUNNER_TEMP/install-stamp.json" install-stamp.json
- name: Run docker integration tests
if: inputs.skip-tests != true
env:
# Skip rebuild; use the image already loaded by the build step.
HERMES_TEST_IMAGE: ${{ env.IMAGE_NAME }}:test
@@ -180,18 +255,77 @@ jobs:
NOUS_API_KEY: ""
run: |
# Each of these tests drives a container, so the docker daemon sets
# the limit and not the processor. This caps the workers. The
# default from run_tests.sh is cpu_count*2, which starts 64
# containers together on the 32-core amd64 runner.
HERMES_TEST_WORKERS=$(nproc) scripts/run_tests.sh tests/docker/ --file-timeout 600
# the limit and not the processor. This pins the runner's worker
# count to the core count.
HERMES_TEST_WORKERS=$(nproc) scripts/run_tests.sh tests/docker/
- name: Verify release image identity
if: needs.mode.outputs.phase == 'test'
env:
RELEASE_VERSION: ${{ inputs.version }}
run: |
actual="$(docker run --rm --entrypoint python "${IMAGE_NAME}:test" -c \
'import json; print(json.load(open("/opt/hermes/install-stamp.json"))["baseVersion"])')"
test "$actual" = "$RELEASE_VERSION"
# ---------------------------------------------------------------------
# Release 'test' phase only: hand the EXACT tested bytes to the publish
# phase via actions artifacts. No registry push, no credentials here.
# ---------------------------------------------------------------------
- name: Save tested image archive (release test)
if: needs.mode.outputs.phase == 'test'
env:
ARCH: ${{ matrix.arch }}
RELEASE_TAG: ${{ inputs.tag }}
VARIANT: ${{ matrix.variant }}
run: |
set -euo pipefail
mkdir -p /tmp/image-artifacts
docker image inspect "${IMAGE_NAME}:test" > /tmp/image-artifacts/image-inspect.json
python3 - <<'PY'
import json, os
from pathlib import Path
image = json.loads(Path('/tmp/image-artifacts/image-inspect.json').read_text())[0]
if image['Architecture'] != os.environ['ARCH']:
raise SystemExit('Docker image architecture mismatch')
Path('/tmp/image-artifacts/identity.json').write_text(json.dumps({
'tag': os.environ['RELEASE_TAG'], 'commit': os.environ['GITHUB_SHA'],
'arch': os.environ['ARCH'], 'variant': os.environ['VARIANT'], 'imageId': image['Id']}), encoding='utf-8')
PY
docker save --output "/tmp/image-artifacts/image-${ARCH}.tar" "${IMAGE_NAME}:test"
(
cd /tmp/image-artifacts
sha256sum "image-${ARCH}.tar" > "image-${ARCH}.tar.sha256"
)
- name: Upload tested image archive (release test)
if: needs.mode.outputs.phase == 'test'
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: docker-test-image-${{ matrix.variant }}-${{ matrix.arch }}-${{ inputs.tag }}
path: |
/tmp/image-artifacts/image-${{ matrix.arch }}.tar
/tmp/image-artifacts/image-${{ matrix.arch }}.tar.sha256
/tmp/image-artifacts/identity.json
if-no-files-found: error
retention-days: 7
compression-level: 0
# ---------------------------------------------------------------------------
# Rebuild and push each architecture only after the unprivileged build/test
# matrix passes. This job is the sole Docker Hub credential boundary.
# Standalone publish: rebuild and push each architecture only after the
# unprivileged build/test matrix passes, on trusted main pushes.
# This job is the sole Docker Hub credential boundary for merges.
#
# NOTE: main pushes tag :main ONLY. :latest is a user-facing stable alias
# now; the ordered publication controller moves it only after the global
# release gate, so a main push can never advance the stable channel.
# ---------------------------------------------------------------------------
publish:
if: github.repository == 'NousResearch/hermes-agent' && (github.event_name == 'push' && github.ref == 'refs/heads/main' || github.event_name == 'release')
needs: [build]
if: >-
needs.mode.outputs.release != 'true' &&
github.repository == 'NousResearch/hermes-agent' &&
github.event_name == 'push' && github.ref == 'refs/heads/main'
needs: [mode, build]
environment: container-publish
strategy:
fail-fast: false
@@ -211,7 +345,21 @@ jobs:
steps:
- name: Checkout trusted source
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
fetch-depth: 0
- name: Write install stamp
run: |
display="$(python3 -m scripts.releases.distance)"
identity=(--commit "$GITHUB_SHA")
if [ -n "$display" ]; then
base="${display%%+*}"
development="${display#*+}"
if [ "$development" = "$display" ]; then distance=0; else distance="${development%%.*}"; fi
identity+=(--base-version "$base" --display-version "$display" --distance "$distance")
fi
python3 scripts/write_install_stamp.py --output install-stamp.json \
--distribution docker --update-mechanism external --source ci "${identity[@]}"
- name: Reject profile exports in the build context
run: python3 scripts/ci/check_profile_archive_boundary.py
@@ -234,18 +382,17 @@ jobs:
# Push by digest only (no tag). The merge job assembles the tagged
# manifest list after both architecture publishers complete.
- name: Push ${{ matrix.arch }} by digest
- name: Push ${{ matrix.variant }}/${{ matrix.arch }} by digest
id: push
uses: docker/build-push-action@bcafcacb16a39f128d818304e6c9c0c18556b85f # v7.1.0
with:
context: .
file: Dockerfile
platforms: ${{ matrix.platform }}
build-args: |
HERMES_BOT_DESKTOP=${{ matrix.variant == 'desktop' && '1' || '0' }}
labels: |
org.opencontainers.image.revision=${{ github.sha }}
build-args: |
HERMES_GIT_SHA=${{ github.sha }}
HERMES_BOT_DESKTOP=${{ matrix.variant == 'desktop' && '1' || '0' }}
outputs: type=image,name=${{ env.IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
cache-from: type=gha,scope=docker-${{ matrix.arch }}
cache-to: ${{ matrix.variant == 'slim' && format('type=gha,mode=max,scope=docker-{0}', matrix.arch) || '' }}
@@ -269,23 +416,22 @@ jobs:
# This is a registry-side operation — no building, no layer re-push —
# so it runs in ~30 seconds.
#
# On main pushes: tags both :main and :latest.
# On releases: tags :<release_tag_name>.
# Main pushes tag :main only. :latest is reserved for the ordered stable
# publication controller.
# ---------------------------------------------------------------------------
merge:
# `needs` is the whole 4-leg matrix and a failed need skips the job, so a
# transient desktop push would take slim's :latest with it. Guard below.
if: ${{ !cancelled() && github.repository == 'NousResearch/hermes-agent' && (github.event_name == 'push' && github.ref == 'refs/heads/main' || github.event_name == 'release') }}
# `needs` is the whole 4-leg matrix: only publish both :main variants
# after every arch and variant publisher succeeds.
if: ${{ !cancelled() && needs.mode.outputs.release != 'true' && github.repository == 'NousResearch/hermes-agent' && github.event_name == 'push' && github.ref == 'refs/heads/main' }}
runs-on: ubuntu-latest
needs: [publish]
needs: [mode, publish]
timeout-minutes: 10
environment: container-publish
strategy:
fail-fast: false
matrix:
# One manifest list per variant. `slim` keeps the unsuffixed tags it has
# always had, so nothing that pulls :latest today changes; `desktop`
# publishes the same digests under a -desktop suffix.
# always had; `desktop` publishes its own digests under -desktop.
include:
- variant: slim
suffix: ""
@@ -320,7 +466,6 @@ jobs:
working-directory: /tmp/digests
env:
IMAGE_NAME: ${{ env.IMAGE_NAME }}
RELEASE_TAG: ${{ github.event.release.tag_name }}
SUFFIX: ${{ matrix.suffix }}
run: |
set -euo pipefail
@@ -330,17 +475,8 @@ jobs:
for digest_file in *; do
args+=("${IMAGE_NAME}@sha256:${digest_file}")
done
# One per arch in the publish matrix; a short set means a leg failed, and
# stitching it would publish a single-arch :latest. Keep in step with it.
if [ "${#args[@]}" -ne 2 ]; then
echo "::error::variant ${{ matrix.variant }}: want 2 digests, found ${#args[@]} (a publish leg failed)"
exit 1
fi
if [ "${{ github.event_name }}" = "release" ]; then
tags=(-t "${IMAGE_NAME}:${RELEASE_TAG}${SUFFIX}")
else
tags=(-t "${IMAGE_NAME}:main${SUFFIX}" -t "${IMAGE_NAME}:latest${SUFFIX}")
fi
if [ "${#args[@]}" -ne 2 ]; then echo "::error::Expected two ${SUFFIX} digests"; exit 1; fi
tags=(-t "${IMAGE_NAME}:main${SUFFIX}")
# Retry: Docker Hub API + just-pushed digest eventual consistency
# can transiently fail the create; the operation is idempotent.
for i in 1 2 3; do
@@ -358,11 +494,276 @@ jobs:
- name: Inspect image
env:
IMAGE_NAME: ${{ env.IMAGE_NAME }}
RELEASE_TAG: ${{ github.event.release.tag_name }}
SUFFIX: ${{ matrix.suffix }}
run: docker buildx imagetools inspect "${IMAGE_NAME}:main${SUFFIX}"
# ===========================================================================
# Staged stable-release path (workflow_call from stable-release.yml).
# The caller is dispatched on the exact stable TAG, so github.sha in every
# reusable call is the release candidate commit.
# ===========================================================================
# Release 'publish' phase: load the EXACT tested image archives uploaded by
# the 'test' phase of this SAME workflow run, verify their hashes, push
# per-arch and NEVER rebuild. No owner gate: on a fork the Docker Hub
# login/push fails loudly (missing credentials) instead of faking green.
release-publish:
name: Publish tested Docker image (${{ matrix.variant }}/${{ matrix.arch }})
if: needs.mode.outputs.phase == 'publish'
needs: [mode]
environment: container-publish
strategy:
fail-fast: false
matrix:
arch: [amd64, arm64]
variant: [slim, desktop]
runs-on: ubuntu-latest-32-core
timeout-minutes: 45
env:
ARCH: ${{ matrix.arch }}
RELEASE_TAG: ${{ inputs.tag }}
VARIANT: ${{ matrix.variant }}
SUFFIX: ${{ matrix.variant == 'desktop' && '-desktop' || '' }}
steps:
- name: Checkout release code (helper scripts only, no build)
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.sha }}
- name: Download tested image archive from the test phase (same run)
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: docker-test-image-${{ matrix.variant }}-${{ matrix.arch }}-${{ inputs.tag }}
path: /tmp/image-artifacts
- name: Verify tested archive hash (published bytes == tested bytes)
run: |
if [ "${{ github.event_name }}" = "release" ]; then
docker buildx imagetools inspect "${IMAGE_NAME}:${RELEASE_TAG}${SUFFIX}"
else
docker buildx imagetools inspect "${IMAGE_NAME}:main${SUFFIX}"
fi
set -euo pipefail
cd /tmp/image-artifacts
echo " expected: $(cat "image-${ARCH}.tar.sha256")"
sha256sum --check "image-${ARCH}.tar.sha256"
- name: Set up Docker Buildx
id: buildx
continue-on-error: true
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- name: Set up Docker Buildx (retry)
if: steps.buildx.outcome == 'failure'
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- name: Load tested image
run: |
set -euo pipefail
docker load --input /tmp/image-artifacts/image-${ARCH}.tar
docker image inspect "${IMAGE_NAME}:test" > /tmp/image-artifacts/loaded.json
python3 - <<'PY'
import json, os
from pathlib import Path
identity = json.loads(Path('/tmp/image-artifacts/identity.json').read_text())
loaded = json.loads(Path('/tmp/image-artifacts/loaded.json').read_text())[0]
expected = (os.environ['RELEASE_TAG'], os.environ['GITHUB_SHA'], os.environ['ARCH'], os.environ['VARIANT'])
if (identity['tag'], identity['commit'], identity['arch'], identity['variant']) != expected:
raise SystemExit('Tested Docker archive identity mismatch')
if (loaded['Id'], loaded['Architecture']) != (identity['imageId'], identity['arch']):
raise SystemExit('Loaded Docker image differs from tested image')
PY
- name: Log in to Docker Hub
uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Push tested image with per-arch release tag
run: |
set -euo pipefail
docker tag "${IMAGE_NAME}:test" "${IMAGE_NAME}:${RELEASE_TAG}-${ARCH}${SUFFIX}"
docker push "${IMAGE_NAME}:${RELEASE_TAG}-${ARCH}${SUFFIX}"
- name: Record pushed per-arch digest
run: |
set -euo pipefail
mkdir -p /tmp/digests
digest="$(docker buildx imagetools inspect "${IMAGE_NAME}:${RELEASE_TAG}-${ARCH}${SUFFIX}" \
--format '{{json .Manifest.Digest}}' | tr -d '"')"
case "$digest" in
sha256:*) ;;
*) echo "::error::Unexpected digest format: $digest"; exit 1 ;;
esac
printf '%s' "$digest" > "/tmp/digests/${ARCH}.digest"
cat "/tmp/digests/${ARCH}.digest"
- name: Upload per-arch digest artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: docker-publish-digest-${{ matrix.variant }}-${{ matrix.arch }}-${{ inputs.tag }}
path: /tmp/digests/${{ matrix.arch }}.digest
if-no-files-found: error
retention-days: 7
# Assemble the immutable versioned multi-arch manifest and expose its digest
# to the parent release receipt. Registry-side only; nothing is rebuilt.
release-publish-manifest:
name: Assemble versioned manifest and digest receipt
if: needs.mode.outputs.phase == 'publish'
needs: [mode, release-publish]
runs-on: ubuntu-latest
outputs:
digest: ${{ steps.list.outputs.digest }}
timeout-minutes: 15
environment: container-publish
env:
RELEASE_TAG: ${{ inputs.tag }}
steps:
- name: Checkout release code (helper scripts only)
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.sha }}
- name: Download per-arch digests
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
path: /tmp/digests
pattern: docker-publish-digest-*-${{ inputs.tag }}
- name: Set up Docker Buildx
id: buildx
continue-on-error: true
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- name: Set up Docker Buildx (retry)
if: steps.buildx.outcome == 'failure'
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- name: Log in to Docker Hub
uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Create both immutable versioned manifest lists
env:
IMAGE_NAME: ${{ env.IMAGE_NAME }}
run: |
set -euo pipefail
cd /tmp/digests
for variant in slim desktop; do
suffix=""
[ "$variant" = desktop ] && suffix=-desktop
digest_files=()
args=()
for arch in amd64 arm64; do
file="docker-publish-digest-${variant}-${arch}-${RELEASE_TAG}/${arch}.digest"
test -s "$file"
digest_files+=("$file")
args+=("${IMAGE_NAME}@$(cat "$file")")
done
verify_manifest() {
python3 - "$1" "${digest_files[@]}" <<'PY'
import json, pathlib, sys
manifest = json.loads(pathlib.Path(sys.argv[1]).read_text())
expected = {pathlib.Path(path).read_text().strip() for path in sys.argv[2:]}
actual = {row.get("digest") for row in manifest.get("manifests", [])}
if actual != expected or len(manifest.get("manifests", [])) != 2:
raise SystemExit(f"versioned Docker manifest differs: expected {sorted(expected)}, got {sorted(actual)}")
PY
}
ref="${IMAGE_NAME}:${RELEASE_TAG}${suffix}"
if docker buildx imagetools inspect "$ref" --raw > existing.json 2>/dev/null; then
verify_manifest existing.json
else
for i in 1 2 3; do
if docker buildx imagetools create -t "$ref" "${args[@]}"; then break; fi
if [ "$i" = 3 ]; then echo "::error::imagetools create failed after 3 attempts"; exit 1; fi
sleep 20
done
fi
docker buildx imagetools inspect "$ref" --raw > verified.json
verify_manifest verified.json
done
- name: Record slim manifest-list digest for the release receipt
id: list
env:
IMAGE_NAME: ${{ env.IMAGE_NAME }}
run: |
set -euo pipefail
digest="$(docker buildx imagetools inspect "${IMAGE_NAME}:${RELEASE_TAG}" \
--format '{{json .Manifest.Digest}}' | tr -d '"')"
case "$digest" in
sha256:*) ;;
*) echo "::error::Unexpected manifest-list digest: $digest"; exit 1 ;;
esac
echo "digest=$digest" >> "$GITHUB_OUTPUT"
- name: Emit release manifest artifact
id: manifest
run: |
set -euo pipefail
mkdir -p /tmp/manifest
python3 -m scripts.releases.docker manifest \
--tag "$RELEASE_TAG" \
--commit "$GITHUB_SHA" \
--digest-amd64 "$(sed 's/^sha256://' /tmp/digests/docker-publish-digest-slim-amd64-${RELEASE_TAG}/amd64.digest)" \
--digest-arm64 "$(sed 's/^sha256://' /tmp/digests/docker-publish-digest-slim-arm64-${RELEASE_TAG}/arm64.digest)" \
> /tmp/manifest/manifest.json
python3 - "$RELEASE_TAG" "${{ steps.list.outputs.digest }}" <<'EOF'
import json, sys
manifest = json.load(open("/tmp/manifest/manifest.json"))
manifest["list-digest"] = sys.argv[2]
manifest["image"] = "nousresearch/hermes-agent"
manifest["tags"] = [sys.argv[1]]
json.dump(manifest, open("/tmp/manifest/manifest.json", "w"), indent=2)
EOF
cat /tmp/manifest/manifest.json
- name: Verify manifest identity
run: |
set -euo pipefail
python3 -m scripts.releases.docker verify \
--tag "$RELEASE_TAG" --commit "$GITHUB_SHA" /tmp/manifest/manifest.json
- name: Upload release manifest artifact
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
with:
name: docker-publish-manifest-${{ inputs.tag }}
path: /tmp/manifest/manifest.json
if-no-files-found: error
retention-days: 7
# Strict phase gate: in every release phase, the jobs that phase requires
# must actually have run and succeeded. `if: always()` keeps this job in
# the graph even when earlier jobs were skipped, so a skipped/failed
# publisher turns this red instead of letting the phase go green.
release-phase-gate:
name: Docker phase requirements met
if: always() && inputs.release-phase != ''
needs: [mode, build, release-publish, release-publish-manifest]
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Validate phase job results
env:
PHASE: ${{ needs.mode.outputs.phase }}
BUILD: ${{ needs.build.result }}
RELEASE_PUBLISH: ${{ needs.release-publish.result }}
RELEASE_MANIFEST: ${{ needs.release-publish-manifest.result }}
MODE: ${{ needs.mode.result }}
run: |
set -euo pipefail
test "$MODE" = success
case "$PHASE" in
test)
failures=()
[ "$BUILD" = success ] || failures+=("build=$BUILD")
[ "${#failures[@]}" -eq 0 ] || { printf '::error::%s\n' "${failures[@]}"; exit 1; }
;;
publish)
failures=()
[ "$RELEASE_PUBLISH" = success ] || failures+=("release-publish=$RELEASE_PUBLISH")
[ "$RELEASE_MANIFEST" = success ] || failures+=("release-publish-manifest=$RELEASE_MANIFEST")
[ "${#failures[@]}" -eq 0 ] || { printf '::error::%s\n' "${failures[@]}"; exit 1; }
;;
*) echo "::error::Unknown phase $PHASE"; exit 1 ;;
esac
+5 -13
View File
@@ -13,15 +13,11 @@ jobs:
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- name: Set up the locked site toolchain
uses: ./.github/actions/setup-pm
with:
node-version: 26
cache: npm
cache-dependency-path: website/package-lock.json
- name: grab npm 12
run: |
npm i -g npm@12
toolchain: all
node-cache-dependency-path: website/package-lock.json
- name: Install website dependencies
uses: ./.github/actions/retry
@@ -29,14 +25,10 @@ jobs:
command: npm ci
working-directory: website
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
with:
python-version: "3.11"
- name: Install ascii-guard
uses: ./.github/actions/retry
with:
command: python -m pip install ascii-guard==2.3.0 pyyaml==6.0.3
command: python -m scripts.ci.python_packages ascii-guard==2.3.0 ruamel.yaml==0.18.17
- name: Extract skill metadata for dashboard
run: python3 website/scripts/extract-skills.py
+8 -25
View File
@@ -37,13 +37,13 @@ jobs:
libgtk-3-0 libnotify4 libnss3 libxss1 libxtst6 \
xdg-utils libatspi2.0-0 libdrm2 libgbm1 libasound2t64
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- name: Prepare locked Desktop build and test toolchain
id: pm
uses: ./.github/actions/setup-pm
with:
node-version: 26
cache: npm
- name: grab npm 12
run: npm i -g npm@12
toolchain: all
extras: '[]'
test-environment: 'true'
# Full npm ci (not --ignore-scripts): electron's postinstall downloads
# the binary we launch.
@@ -51,27 +51,9 @@ jobs:
with:
command: npm ci
- name: Install uv
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0
with:
version: '0.9.28'
enable-cache: true
cache-dependency-glob: |
pyproject.toml
uv.lock
- name: Set up Python 3.11
uses: ./.github/actions/retry
with:
command: uv python install 3.11
- name: Install Python dependencies
uses: ./.github/actions/retry
with:
command: uv sync --locked --python 3.11 --extra all --extra dev
- name: Build the desktop app
working-directory: apps/desktop
# The generator uses the runtime's Pillow + resvg-py, not a build-only venv.
run: npm run build
# Package the Linux app the way users get it (electron-builder --dir; no
@@ -89,6 +71,7 @@ jobs:
npx playwright test -c e2e/core/playwright.config.ts
env:
CI: 'true'
HERMES_E2E_PYTHON: ${{ steps.pm.outputs.python-path }}
# The pack step above ran: a missing release/linux-unpacked is a failure, not a skip.
HERMES_E2E_REQUIRE_PACKAGED: '1'
OPENROUTER_API_KEY: ''
+6 -32
View File
@@ -39,15 +39,13 @@ jobs:
libgtk-3-0 libnotify4 libnss3 libxss1 libxtst6 \
xdg-utils libatspi2.0-0 libdrm2 libgbm1 libasound2t64
# ── Node ───────────────────────────────────────────────────────────
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- name: Set up the locked desktop toolchain
uses: ./.github/actions/setup-pm
with:
node-version: 26
cache: npm
- name: grab npm 12
run: |
npm i -g npm@12
toolchain: all
extras: '["all"]'
test-environment: 'true'
prune-python-cache: true
# Full npm ci (not --ignore-scripts): electron's postinstall
# downloads the binary we launch, and node-pty's native build is
@@ -56,30 +54,6 @@ jobs:
with:
command: npm ci
# ── Python (for the hermes serve backend) ──────────────────────────
- name: Install uv
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0
with:
# Pin the uv version: unpinned, setup-uv resolves "latest" by
# fetching a manifest from raw.githubusercontent.com on EVERY job —
# a transient fetch failure fails the whole job (2026-07-28 slice-5
# incident). Pinned, the binary downloads directly; no manifest hop.
version: '0.9.28'
enable-cache: true
cache-dependency-glob: |
pyproject.toml
uv.lock
- name: Set up Python 3.11
uses: ./.github/actions/retry
with:
command: uv python install 3.11
- name: Install Python dependencies
uses: ./.github/actions/retry
with:
command: uv sync --locked --python 3.11 --extra all --extra dev
# ── Build desktop app ─────────────────────────────────────────────
# The Playwright step below runs `npm run build` before testing so
# dist/ is always fresh — no separate build step needed here.
@@ -0,0 +1,42 @@
name: Icon Assets Freshness
# Guard for the icon pipeline. The sources of truth are the nous-girl SVGs
# (assets/nous-girl-*.svg) and the per-platform backgrounds
# (assets/backgrounds/*.svg). Generated outputs are NOT committed — every
# consuming pipeline regenerates them via scripts/generate-icons.mjs — so
# this lane regenerates everything from a fresh checkout and runs --check,
# which asserts structural invariants (sizes, transparent squircle corners,
# container frame sets). A source change can never land broken. See
# scripts/generate_icons.py.
#
# Byte-determinism note: resvg renders the same SVG to identical bytes on any
# host for pure-shape artwork. If the master ever contains <text>, font
# rendering can differ across OSes — pin fonts via resvg's font_files/font_dirs
# and commit a known font before relying on this check for that master.
on:
workflow_call:
permissions:
contents: read
jobs:
check:
name: Regenerate icons + structural check
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
# The generator runs on a Hermes runtime interpreter; [] exports one as HERMES_PYTHON.
- uses: ./.github/actions/setup-pm
with:
toolchain: all
extras: '[]'
cache-python: true
prune-python-cache: true
- name: Regenerate every target, then verify structure
run: |
node scripts/generate-icons.mjs
node scripts/generate-icons.mjs --check
+124 -1
View File
@@ -33,6 +33,11 @@ on:
required: false
type: string
default: refs/heads/main
update-ref:
description: 'What to update TO: HEAD (the commit under test), or NEXT -- a synthetic child of install-ref that the driver mints, so a leg that installs HEAD still has an update to take (HEAD''s own updater).'
required: false
type: string
default: HEAD
tag-has-desktop:
description: "Whether install-ref ships the desktop app (apps/desktop). The caller annotates this from the tag's own tree; desktop-method legs from pre-desktop releases natively skip."
required: false
@@ -47,6 +52,20 @@ on:
required: false
type: string
default: https://hermes-assets.nousresearch.com/Hermes-Setup.dmg
bundle-manifest-url:
description: 'URL of the JSON schema-1 bundle manifest for the packaged-app arm. Empty (default) means the bundled arm does not run — native packaged coverage only runs when the caller pins a real signed OLD/NEW pair.'
required: false
type: string
default: ''
bundle-manifest-sha256:
description: Pinned transition manifest digest for stable acceptance
type: string
default: ''
bundle-arch:
description: 'Architecture of the bundled pair: arm64 (macos-15) or x64 (macos-15-intel).'
required: false
type: string
default: arm64
timeout-minutes:
description: 'Job timeout. App-update legs do a full Electron build.'
required: false
@@ -70,6 +89,7 @@ jobs:
install-method: ${{ inputs.install-method }}
update-method: ${{ inputs.update-method }}
install-ref: ${{ inputs.install-ref }}
update-ref: ${{ inputs.update-ref }}
tag-has-desktop: ${{ inputs.tag-has-desktop }}
leg-id: ${{ inputs.leg-id }}
runner: macos-latest
@@ -91,8 +111,22 @@ jobs:
# installer/updater talk to.
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.sha }}
fetch-depth: 0
- name: Set up driver tools only
uses: ./.github/actions/setup-pm
with:
toolchain: all
packages: ffmpeg
cache: false
cache-python: false
cache-node: false
- name: Install locked chat driver dependencies
shell: bash
run: npm ci --workspace tests-js --include-workspace-root --omit=dev --ignore-scripts --no-audit --no-fund
- name: Start screen recording
uses: ./.github/actions/e2e-screen-record
with:
@@ -105,6 +139,7 @@ jobs:
tests/install/macos-desktop-e2e.sh --phase stage \
--update-method '${{ inputs.update-method }}' \
--install-ref '${{ inputs.install-ref }}' \
--update-ref '${{ inputs.update-ref }}' \
--dmg-url '${{ inputs.dmg-url }}'
env:
HERMES_E2E_LOG_DIR: ${{ runner.temp }}/e2e-logs
@@ -119,7 +154,7 @@ jobs:
env:
HERMES_E2E_LOG_DIR: ${{ runner.temp }}/e2e-logs
- name: Update ${{ inputs.install-ref }} -> HEAD (${{ inputs.update-method }})
- name: Update ${{ inputs.install-ref }} -> ${{ inputs.update-ref }} (${{ inputs.update-method }})
run: |
set -euo pipefail
tests/install/macos-desktop-e2e.sh --phase update \
@@ -160,3 +195,91 @@ jobs:
path: ${{ runner.temp }}/e2e-logs
retention-days: 14
if-no-files-found: ignore
# ---- arm 3: the real signed bundle pair, in-app update ------------------
# Runs ONLY when the caller passes a bundle-manifest-url: the parent's
# matrix job owns resolving + pinning the OLD/NEW signed release pair.
# The driver itself re-guards on Darwin + GITHUB_ACTIONS and refuses to
# run anywhere native coverage would be fake.
bundled-e2e:
name: packaged bundle (open-app-update)
if: inputs.install-method == 'packaged-app' && inputs.update-method == 'open-app-update'
runs-on: ${{ inputs.bundle-arch == 'x64' && 'macos-15-intel' || 'macos-15' }}
timeout-minutes: ${{ inputs.timeout-minutes }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.sha }}
- name: Set up driver tools only
uses: ./.github/actions/setup-pm
with:
toolchain: all
packages: ffmpeg
cache: false
cache-python: false
cache-node: false
- name: Install locked chat driver dependencies
shell: bash
run: npm ci --workspace tests-js --include-workspace-root --omit=dev --ignore-scripts --no-audit --no-fund
- name: Start screen recording
uses: ./.github/actions/e2e-screen-record
with:
mode: start
output: ${{ runner.temp }}/e2e-logs/recording.mkv
- name: Install OLD signed bundle (${{ inputs.install-ref }})
run: |
set -euo pipefail
bash tests/install/macos-bundled-e2e.sh --phase install \
--manifest-url "$BUNDLE_MANIFEST" --arch "$BUNDLE_ARCH"
env:
BUNDLE_MANIFEST: ${{ inputs.bundle-manifest-url }}
BUNDLE_MANIFEST_SHA256: ${{ inputs.bundle-manifest-sha256 }}
BUNDLE_ARCH: ${{ inputs.bundle-arch }}
HERMES_E2E_LOG_DIR: ${{ runner.temp }}/e2e-logs
- name: Update to NEW via About -> Update now (${{ inputs.bundle-arch }})
run: |
set -euo pipefail
bash tests/install/macos-bundled-e2e.sh --phase update \
--manifest-url "$BUNDLE_MANIFEST" --arch "$BUNDLE_ARCH"
env:
BUNDLE_MANIFEST: ${{ inputs.bundle-manifest-url }}
BUNDLE_MANIFEST_SHA256: ${{ inputs.bundle-manifest-sha256 }}
BUNDLE_ARCH: ${{ inputs.bundle-arch }}
HERMES_E2E_LOG_DIR: ${{ runner.temp }}/e2e-logs
- name: Stop screen recording
if: always()
uses: ./.github/actions/e2e-screen-record
with:
mode: stop
output: ${{ runner.temp }}/e2e-logs/recording.mkv
- name: Remux recording for browser playback
if: always()
run: |
set -euo pipefail
if [ -f "${{ runner.temp }}/e2e-logs/recording.mkv" ]; then
ffmpeg -y -hide_banner -loglevel error -i "${{ runner.temp }}/e2e-logs/recording.mkv" \
-c copy "${{ runner.temp }}/e2e-logs/recording.mp4"
fi
- name: Build artifact name
id: artifact
if: always()
run: |
echo "name=install-e2e-logs-${{ inputs.leg-id }}-bundle-${{ inputs.bundle-arch }}" >> "$GITHUB_OUTPUT"
- name: Upload logs
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: ${{ steps.artifact.outputs.name }}
path: ${{ runner.temp }}/e2e-logs
retention-days: 14
if-no-files-found: ignore
+22 -1
View File
@@ -50,6 +50,11 @@ on:
required: false
type: string
default: refs/heads/main
update-ref:
description: 'What to update TO: HEAD (the commit under test), or NEXT -- a synthetic child of install-ref that the driver mints, so a leg that installs HEAD still has an update to take (HEAD''s own updater).'
required: false
type: string
default: HEAD
leg-id:
description: 'Artifact-safe matrix leg id (from generate-e2e-matrix.mjs legId). Names this leg''s logs + player artifacts so the report job can link a row to its zip.'
required: true
@@ -94,8 +99,23 @@ jobs:
# in that clone. A shallow clone cannot serve either need.
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.sha }}
fetch-depth: 0
# The checkout owns the chat driver, not OLD's installed Node/runtime.
- name: Set up driver tools only
uses: ./.github/actions/setup-pm
with:
toolchain: all
packages: ffmpeg
cache: false
cache-python: false
cache-node: false
- name: Install locked chat driver dependencies
shell: bash
run: npm ci --workspace tests-js --include-workspace-root --omit=dev --ignore-scripts --no-audit --no-fund
# One recording mechanism on every OS (Xvfb gives headless linux a
# display; the same display serves any app the driver launches).
- name: Start screen recording
@@ -110,7 +130,8 @@ jobs:
tests/install/installer-script-e2e.sh \
--install-method '${{ inputs.install-method }}' \
--update-method '${{ inputs.update-method }}' \
--install-ref '${{ inputs.install-ref }}'
--install-ref '${{ inputs.install-ref }}' \
--update-ref '${{ inputs.update-ref }}'
env:
# Outside the workspace on purpose: logs written into the repo
# would trip the driver's own dirty-tree guard.
+120 -6
View File
@@ -58,13 +58,18 @@ on:
required: false
type: string
default: auto
update-ref:
description: "What to update TO: HEAD (the commit under test), or NEXT -- a synthetic child of install-ref that the driver mints, so a leg that installs HEAD still has an update to take (HEAD's own updater)."
required: false
type: string
default: HEAD
tag-has-desktop:
description: "Whether install-ref ships the desktop app (apps/desktop). The caller annotates this from the tag's own tree; desktop-method legs from pre-desktop releases natively skip."
required: false
type: boolean
default: true
leg-id:
description: 'Artifact-safe matrix leg id (from generate-e2e-matrix.mjs legId). Names this leg''s logs + player artifacts so the report job can link a row to its zip.'
description: "Artifact-safe matrix leg id (from generate-e2e-matrix.mjs legId). Names this leg's logs + player artifacts so the report job can link a row to its zip."
required: true
type: string
setup-exe-url:
@@ -77,11 +82,77 @@ on:
required: false
type: number
default: 60
bundle-manifest-url:
type: string
default: ''
bundle-manifest-sha256:
description: Pinned transition manifest digest for stable acceptance
type: string
default: ''
bundle-arch:
type: string
default: x64
permissions:
contents: read
jobs:
bundled-e2e:
name: packaged bundle (open-app-update)
if: inputs.install-method == 'packaged-app' && inputs.update-method == 'open-app-update'
runs-on: ${{ inputs.bundle-arch == 'arm64' && 'windows-latest-32-arm-core' || 'windows-latest-32-core' }}
timeout-minutes: ${{ inputs.timeout-minutes }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.sha }}
- name: Set up driver tools only
uses: ./.github/actions/setup-pm
with:
toolchain: all
packages: ffmpeg
cache: false
cache-python: false
cache-node: false
- name: Install locked chat driver dependencies
shell: bash
run: npm ci --workspace tests-js --include-workspace-root --omit=dev --ignore-scripts --no-audit --no-fund
- name: Verify native helpers
shell: pwsh
run: |
node --test tests/install/e2e-assets/windows-bundled-helpers.test.mjs
if ($LASTEXITCODE) { exit $LASTEXITCODE }
- name: Start recording
uses: ./.github/actions/e2e-screen-record
with:
mode: start
output: ${{ runner.temp }}/hermes-bundled-update-recording.mkv
- name: Install, update and observe native relaunch
shell: pwsh
env:
BUNDLE_MANIFEST: ${{ inputs.bundle-manifest-url }}
BUNDLE_MANIFEST_SHA256: ${{ inputs.bundle-manifest-sha256 }}
BUNDLE_ARCH: ${{ inputs.bundle-arch }}
run: |
powershell -NoProfile -ExecutionPolicy Bypass -File tests/install/windows-bundled-e2e.ps1 -ManifestUrl $env:BUNDLE_MANIFEST -Arch $env:BUNDLE_ARCH
if ($LASTEXITCODE) { exit $LASTEXITCODE }
- name: Stop recording
if: always()
uses: ./.github/actions/e2e-screen-record
with:
mode: stop
output: ${{ runner.temp }}/hermes-bundled-update-recording.mkv
- name: Upload native acceptance evidence
if: always()
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: install-e2e-logs-${{ inputs.leg-id }}-bundle-${{ inputs.bundle-arch }}
path: |
${{ runner.temp }}/hermes-bundled-update/proof/
${{ runner.temp }}/hermes-bundled-update/home/logs/
${{ runner.temp }}/hermes-bundled-update-recording.mkv
if-no-files-found: error
retention-days: 14
e2e:
# Short static name on purpose: name expressions render UNEXPANDED on
# skipped jobs.
@@ -99,7 +170,7 @@ jobs:
|| (contains(fromJSON('["installer-script+desktop", "hermes-desktop-app-update", "desktop-installer@latest"]'), inputs.update-method) && inputs.tag-has-desktop)
|| (inputs.update-method == 'open-app-update' && inputs.tag-has-desktop
&& contains(fromJSON('["desktop-installer@latest", "installer-script+desktop"]'), inputs.install-method)))
runs-on: windows-latest
runs-on: windows-latest-32-core
timeout-minutes: ${{ inputs.timeout-minutes }}
env:
@@ -116,10 +187,44 @@ jobs:
# in that clone. A shallow checkout cannot serve either need.
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.sha }}
fetch-depth: 0
# One recording mechanism on every OS: the composite action installs
# ffmpeg (cached - winget's download is the slow part), starts the
# Old installers refresh PATH after winget installs ripgrep, dropping the
# process-only uv path. Supply the tool before running those shipped scripts.
- name: Set up driver tools only
uses: ./.github/actions/setup-pm
with:
toolchain: all
packages: ffmpeg,ripgrep
cache: false
cache-python: false
cache-node: false
- name: Install locked chat driver dependencies
shell: bash
run: npm ci --workspace tests-js --include-workspace-root --omit=dev --ignore-scripts --no-audit --no-fund
# A released tag prints its one-shot chat through prompt_toolkit, whose Windows
# output object needs a console screen buffer -- piping the CLI's stdout into the
# evidence log takes that away and the turn dies with NoConsoleScreenBufferError.
# The driver therefore runs that turn under e2e-assets/pty-run.py, which uses
# pywinpty: the same ConPTY spawner the product uses on Windows, pinned to the
# version pyproject.toml requires. Install it with uv (the toolchain python ships
# without pip) out of HERMES_RUNTIME_DIR, which is the tools directory itself and
# is not on PATH for workflow steps; the import check proves it landed.
- name: Install the pseudoconsole runner's dependency
shell: pwsh
run: |
$uvDir = Get-ChildItem $env:HERMES_RUNTIME_DIR -Filter 'uv-*' -Directory | Select-Object -First 1
if (-not $uvDir) { throw "uv not found under $env:HERMES_RUNTIME_DIR" }
& (Join-Path $uvDir.FullName 'uv.exe') pip install --system --python $env:HERMES_PYTHON --quiet "pywinpty==3.0.5"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
python -c "import winpty; print('pty-run dependency ready')"
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
# One recording mechanism on every OS: the composite action verifies
# ffmpeg from the PM toolchain (packages: ffmpeg above), starts the
# capture, and record-stop fails on a zero-frame file so a silently
# missing recording cannot go green.
- name: Start screen recording
@@ -130,17 +235,26 @@ jobs:
- name: Stage serve repo (main -> ${{ inputs.install-ref }})
shell: powershell
run: powershell -NoProfile -ExecutionPolicy Bypass -File tests\install\windows-e2e.ps1 -Phase stage -InstallMethod "${{ inputs.install-method }}" -Route "${{ inputs.update-method }}" -InstallRef "${{ inputs.install-ref }}" -SetupExeUrl ${{ inputs.setup-exe-url }}
run: powershell -NoProfile -ExecutionPolicy Bypass -File tests\install\windows-e2e.ps1 -Phase stage -InstallMethod "${{ inputs.install-method }}" -Route "${{ inputs.update-method }}" -InstallRef "${{ inputs.install-ref }}" -UpdateRef "${{ inputs.update-ref }}" -SetupExeUrl ${{ inputs.setup-exe-url }}
- name: Install ${{ inputs.install-ref }} (${{ inputs.install-method }})
shell: powershell
run: powershell -NoProfile -ExecutionPolicy Bypass -File tests\install\windows-e2e.ps1 -Phase install -InstallMethod "${{ inputs.install-method }}" -Route "${{ inputs.update-method }}" -InstallRef "${{ inputs.install-ref }}" -SetupExeUrl ${{ inputs.setup-exe-url }}
- name: Update ${{ inputs.install-ref }} -> HEAD (${{ inputs.update-method }})
- name: Update ${{ inputs.install-ref }} -> ${{ inputs.update-ref }} (${{ inputs.update-method }})
id: update
shell: powershell
run: powershell -NoProfile -ExecutionPolicy Bypass -File tests\install\windows-e2e.ps1 -Phase update -InstallMethod "${{ inputs.install-method }}" -Route "${{ inputs.update-method }}" -InstallRef "${{ inputs.install-ref }}" -SetupExeUrl ${{ inputs.setup-exe-url }}
# After everything, including the new runtime's launch and its smoke
# checks: the bootstrap marker can complete on a later run than the
# install, so stamp truthfulness is asserted here — not in the install
# phase. Known-failure legs legitimately never reach the new HEAD.
- name: Verify install stamps describe the updated checkout
if: steps.update.outputs.known_failure == ''
shell: powershell
run: powershell -NoProfile -ExecutionPolicy Bypass -File tests\install\windows-e2e.ps1 -Phase verify-stamp -InstallMethod "${{ inputs.install-method }}" -Route "${{ inputs.update-method }}" -InstallRef "${{ inputs.install-ref }}" -SetupExeUrl ${{ inputs.setup-exe-url }}
- name: Stage known-failure receipt
if: steps.update.outputs.known_failure != ''
shell: pwsh
+194 -30
View File
@@ -35,9 +35,8 @@ name: Install & Update E2E
# Triggers:
# * every 12 hours, so upstream drift (a new uv, a Node bump, a PyPI change)
# surfaces on a schedule rather than in someone's review cycle;
# * when a release tag is created -- the moment the set of versions users can
# update FROM changes, and the moment a broken updater would strand them;
# * manually, where you can pick the route and how many releases to sample.
# * manually, where you can pick the route (a preset or specific legs) and how many
# releases to sample.
#
# Deliberately NOT on pull_request: a leg takes ~11 minutes of real toolchain
# installation, and the matrix multiplies that. Updating is release-shaped work,
@@ -47,11 +46,18 @@ on:
workflow_dispatch:
inputs:
route:
description: 'Which combinations to run. all = every OS; both/update/installer = the linux legs; windows-desktop = the windows legs; macos-desktop = the macos legs.'
description: 'Which legs to run: all = every OS; both/update/installer = the linux legs; windows-desktop / macos-desktop = that OS; bundled / windows-bundled / macos-bundled = the signed-bundle legs. Anything else selects legs by name (a leg or job name, or a fragment of one).'
required: false
type: choice
type: string
default: all
options: [all, both, update, installer, windows-desktop, macos-desktop]
windows-bundle-manifest:
description: 'HTTPS manifest pinning signed Windows OLD/NEW msixbundles; NEW must match this ref.'
type: string
default: ''
macos-bundle-manifest:
description: 'HTTPS manifest pinning signed macOS OLD/NEW app ZIPs; NEW must match this ref.'
type: string
default: ''
tag-count:
description: 'How many release tags to sample (newest, oldest, and a spread between).'
required: false
@@ -62,26 +68,66 @@ on:
required: false
type: string
default: ''
workflow_call:
# Reusable entry for the stable-release orchestrator. Same input names as
# workflow_dispatch; on a release run the caller dispatches on the exact
# candidate tag, so github.sha is the candidate commit throughout.
#
# route: which combinations to run (same choices as dispatch). The
# bundled routes require the matching bundle manifests, exactly like a
# manual dispatch — a source (non-bundle) release run passes route=all
# with empty manifests and gets the source install/update matrix only.
inputs:
release:
description: 'Stable-release candidate run (informational; jobs behave as route=all with empty manifests).'
required: false
type: boolean
default: false
route:
description: 'Which legs to run: all = every OS; both/update/installer = the linux legs; windows-desktop / macos-desktop = that OS; bundled / windows-bundled / macos-bundled = the signed-bundle legs. Anything else selects legs by name (a leg or job name, or a fragment of one).'
required: false
type: string
default: all
windows-bundle-manifest:
description: 'HTTPS manifest pinning signed Windows OLD/NEW msixbundles; NEW must match this ref.'
required: false
type: string
default: ''
macos-bundle-manifest:
description: 'HTTPS manifest pinning signed macOS OLD/NEW app ZIPs; NEW must match this ref.'
required: false
type: string
default: ''
tag-count:
description: 'How many release tags to sample (newest, oldest, and a spread between).'
required: false
type: string
default: '3'
install-ref:
description: 'Optional exact release tag for a focused reproduction; overrides tag-count.'
required: false
type: string
default: ''
exclude-ref:
description: 'Exact release tag to EXCLUDE from the sampled OLD baselines (e.g. the candidate itself — testing an update from it would be a no-change test).'
required: false
type: string
default: ''
schedule:
# Every 12 hours, off the hour to avoid the top-of-hour runner crunch.
- cron: '20 7,19 * * *'
push:
tags:
# Release tags only: the repo also carries backup/* and one-off tags.
- 'v[0-9]+.[0-9]+.[0-9]+'
- 'v[0-9]+.[0-9]+.[0-9]+.[0-9]+'
permissions:
contents: read
# A workflow_call run (stable release) is never cancelled: its group uses
# github.run_id so a parent rerun cannot kill this child mid-flight. The
# scheduled/manual runs keep ref-scoped collapse.
concurrency:
group: install-e2e-${{ github.ref }}
cancel-in-progress: true
group: install-e2e-${{ inputs.release == true && github.run_id || github.ref }}
cancel-in-progress: ${{ inputs.release != true }}
jobs:
# Which released versions do we test updating FROM? Resolved once,
# annotated with what each tag's own tree supports, and shared by every
# OS's matrix so all combos cover the same set.
pick-releases:
name: Pick release tags
runs-on: ubuntu-latest
@@ -97,24 +143,36 @@ jobs:
with:
filter: blob:none
fetch-tags: true
sparse-checkout: scripts/sandbox/pick-release-tags.sh
sparse-checkout: |
scripts/sandbox/pick-release-tags.sh
scripts/releases/pick_tags.py
sparse-checkout-cone-mode: false
- id: pick
env:
# Dispatch inputs never touch shell syntax directly: TAG_COUNT
# arrives via the environment and is validated decimal-only (bash
# arithmetic reads a leading zero as octal). GitHub's 256-job cap
# applies to each per-OS matrix separately; at 10 tags the largest
# is windows at 180 (first over the cap at 15 tags = 270).
# Inputs never touch shell syntax directly: TAG_COUNT arrives via
# the environment and is validated decimal-only (bash arithmetic
# reads a leading zero as octal). GitHub's 256-job cap applies to
# each per-OS matrix separately; at 10 tags the largest is windows
# at 180 (first over the cap at 15 tags = 270).
#
# EXCLUDE_REF removes one tag from the sampled OLD baselines: on a
# stable release the candidate tag itself is the newest release
# tag, and sampling it as an OLD version would produce a no-change
# update leg — the candidate must never update from itself.
TAG_COUNT: ${{ inputs.tag-count || 2 }}
INSTALL_REF: ${{ inputs.install-ref }}
EXCLUDE_REF: ${{ inputs.exclude-ref }}
RELEASE_MODE: ${{ inputs.release }}
run: |
set -euo pipefail
[[ "$TAG_COUNT" =~ ^(10|[1-9])$ ]] || { echo "tag-count must be 1-10, got: $TAG_COUNT" >&2; exit 1; }
if [ -n "$INSTALL_REF" ]; then
[[ "$INSTALL_REF" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(\.[0-9]+)?$ ]] || { echo 'install-ref must be an exact release tag' >&2; exit 1; }
[ "$INSTALL_REF" != "$EXCLUDE_REF" ] || { echo "Candidate cannot be its own baseline" >&2; exit 1; }
git rev-parse --verify "refs/tags/$INSTALL_REF^{commit}" >/dev/null
tags="$(jq -cn --arg ref "$INSTALL_REF" '[$ref]')"
elif [ "$RELEASE_MODE" = true ]; then
tags="$(python3 -m scripts.releases.pick_tags --count "$TAG_COUNT" --exclude-ref "$EXCLUDE_REF")"
else
tags="$(scripts/sandbox/pick-release-tags.sh --count "$TAG_COUNT")"
fi
@@ -142,19 +200,27 @@ jobs:
linux: ${{ steps.gen.outputs.linux }}
windows: ${{ steps.gen.outputs.windows }}
macos: ${{ steps.gen.outputs.macos }}
linux-legs: ${{ steps.gen.outputs.linux-legs }}
windows-legs: ${{ steps.gen.outputs.windows-legs }}
macos-legs: ${{ steps.gen.outputs.macos-legs }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
sparse-checkout: scripts/sandbox/generate-e2e-matrix.mjs
sparse-checkout-cone-mode: false
- id: gen
env:
# Free text on dispatch, so it reaches the script as data, never as script.
# Scheduled runs have no inputs: the default route.
ROUTE: ${{ inputs.route || 'all' }}
run: |
set -euo pipefail
matrices="$(node scripts/sandbox/generate-e2e-matrix.mjs \
--tags '${{ needs.pick-releases.outputs.tags }}')"
--tags '${{ needs.pick-releases.outputs.tags }}' --route "$ROUTE")"
echo "$matrices"
for key in linux windows macos; do
echo "$key=$(echo "$matrices" | node -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>console.log(JSON.stringify(JSON.parse(d)[process.argv[1]])))' "$key")" >> "$GITHUB_OUTPUT"
echo "$key-legs=$(echo "$matrices" | node -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>console.log(JSON.parse(d)[process.argv[1]].include.length))' "$key")" >> "$GITHUB_OUTPUT"
done
# The plan, human-readable: a combination x starting-tag chart on
# the run's summary page.
@@ -162,12 +228,63 @@ jobs:
--tags '${{ needs.pick-releases.outputs.tags }}' \
--format markdown >> "$GITHUB_STEP_SUMMARY"
bundle-inputs:
name: Validate pinned bundle transitions
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
windows: ${{ steps.inputs.outputs.windows }}
macos: ${{ steps.inputs.outputs.macos }}
windows-arch: ${{ steps.inputs.outputs.windows-arch }}
macos-arch: ${{ steps.inputs.outputs.macos-arch }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- id: inputs
env:
BUNDLE_WINDOWS_MANIFEST: ${{ inputs.windows-bundle-manifest }}
BUNDLE_MACOS_MANIFEST: ${{ inputs.macos-bundle-manifest }}
BUNDLE_ROUTE: ${{ inputs.route }}
run: |
npm ci --ignore-scripts --no-audit --no-fund
node tests/install/e2e-assets/bundle-plan.mjs
windows-bundled:
name: ${{ matrix.name }}
if: inputs.windows-bundle-manifest != '' && contains(fromJSON('["all", "bundled", "windows-bundled"]'), inputs.route)
needs: bundle-inputs
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.bundle-inputs.outputs.windows) }}
uses: ./.github/workflows/install-e2e-windows-run.yml
with:
install-method: packaged-app
update-method: open-app-update
install-ref: ${{ matrix.install_ref }}
leg-id: ${{ matrix.leg_id }}
bundle-manifest-url: ${{ inputs.windows-bundle-manifest }}
bundle-arch: ${{ needs.bundle-inputs.outputs.windows-arch }}
macos-bundled:
name: ${{ matrix.name }}
if: inputs.macos-bundle-manifest != '' && contains(fromJSON('["all", "bundled", "macos-bundled"]'), inputs.route)
needs: bundle-inputs
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.bundle-inputs.outputs.macos) }}
uses: ./.github/workflows/install-e2e-macos-run.yml
with:
install-method: packaged-app
update-method: open-app-update
install-ref: ${{ matrix.install_ref }}
leg-id: ${{ matrix.leg_id }}
bundle-manifest-url: ${{ inputs.macos-bundle-manifest }}
bundle-arch: ${{ needs.bundle-inputs.outputs.macos-arch }}
linux:
name: ${{ matrix.name }}
# The update/installer route choices map to the linux update methods;
# either way the whole linux matrix runs (legs are cheap and the
# distinction wasn't worth a filter layer in the generator).
if: github.event_name != 'workflow_dispatch' || contains(fromJSON('["all", "both", "update", "installer"]'), inputs.route)
# The generator applies the route; an OS it selected no legs for is skipped
# (GitHub rejects an empty matrix).
if: needs.generate-matrix.outputs.linux-legs != '0'
needs: generate-matrix
strategy:
# One leg breaking is worth knowing about even if another already
@@ -179,12 +296,13 @@ jobs:
install-method: ${{ matrix.install_method }}
update-method: ${{ matrix.update_method }}
install-ref: ${{ matrix.install_ref }}
update-ref: ${{ matrix.update_ref }}
tag-has-desktop: ${{ matrix.tag_has_desktop }}
leg-id: ${{ matrix.leg_id }}
windows:
name: ${{ matrix.name }}
if: github.event_name != 'workflow_dispatch' || contains(fromJSON('["all", "windows-desktop"]'), inputs.route)
if: needs.generate-matrix.outputs.windows-legs != '0'
needs: generate-matrix
strategy:
fail-fast: false
@@ -194,12 +312,13 @@ jobs:
install-method: ${{ matrix.install_method }}
update-method: ${{ matrix.update_method }}
install-ref: ${{ matrix.install_ref }}
update-ref: ${{ matrix.update_ref }}
tag-has-desktop: ${{ matrix.tag_has_desktop }}
leg-id: ${{ matrix.leg_id }}
macos:
name: ${{ matrix.name }}
if: github.event_name != 'workflow_dispatch' || contains(fromJSON('["all", "macos-desktop"]'), inputs.route)
if: needs.generate-matrix.outputs.macos-legs != '0'
needs: generate-matrix
strategy:
fail-fast: false
@@ -211,6 +330,7 @@ jobs:
install-method: ${{ matrix.install_method }}
update-method: ${{ matrix.update_method }}
install-ref: ${{ matrix.install_ref }}
update-ref: ${{ matrix.update_ref }}
tag-has-desktop: ${{ matrix.tag_has_desktop }}
leg-id: ${{ matrix.leg_id }}
@@ -238,6 +358,50 @@ jobs:
retention-days: 14
if-no-files-found: error
# Strict source-matrix gate (release runs). needs collapses each matrix to
# one aggregate, so the three source parents are the required check here.
# Every source leg must succeed — a skip is a failure EXCEPT when it is the
# native, declared capability skip (a starting tag predating the desktop
# app reports tag-has-desktop=false and its GUI leg legitimately cannot
# run); those are honest skips, counted and listed. A no-legs-at-all
# generation (empty matrix) also fails: a release run must actually test
# the source install/update paths.
source-gate:
name: Source matrix gate
if: always() && inputs.release == true
needs: [generate-matrix, linux, windows, macos]
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Evaluate source legs
env:
LINUX: ${{ needs.linux.result }}
WINDOWS: ${{ needs.windows.result }}
MACOS: ${{ needs.macos.result }}
LINUX_MATRIX: ${{ needs.generate-matrix.outputs.linux }}
WINDOWS_MATRIX: ${{ needs.generate-matrix.outputs.windows }}
MACOS_MATRIX: ${{ needs.generate-matrix.outputs.macos }}
run: |
set -euo pipefail
fail=0
for os_name in LINUX WINDOWS MACOS; do
result="${!os_name}"
matrix_var="${os_name}_MATRIX"
matrix="${!matrix_var}"
legs=$(printf '%s' "$matrix" | jq 'if type == "object" then ([.include // []] | add // []) else . end | length')
echo "$os_name: result=$result legs=$legs"
if [ "$result" != "success" ] || [ "$legs" -eq 0 ]; then
echo "$os_name requires executed source coverage"
echo "::error::$os_name source matrix result=$result (legs=$legs)"
fail=1
fi
done
if [ "$fail" -ne 0 ]; then
echo "::error::source install/update matrix did not fully succeed; a release cannot proceed on a partial or skipped matrix"
exit 1
fi
echo "Source install/update matrix: all OS aggregates succeeded"
# The outcome, human-readable: the plan chart again, with each cell
# replaced by how that leg actually concluded. Per-leg conclusions are
# NOT reachable through `needs` (a matrix job's result collapses to one
@@ -247,7 +411,7 @@ jobs:
report:
name: Result chart
if: always()
needs: [leg-player, pick-releases, linux, windows, macos]
needs: [leg-player, pick-releases, linux, windows, macos, bundle-inputs, windows-bundled, macos-bundled]
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
-54
View File
@@ -1,54 +0,0 @@
name: Installer tests
# scripts/install.ps1's PowerShell tests. They exercise the installer as a real
# subprocess, and every path contract they assert (8.3 short-name aliases,
# Git Bash layouts, provider-cmdlet behavior) is Windows-specific — so they need
# a Windows runner. Before this workflow existed the files were in the tree but
# nothing ever ran them.
on:
workflow_call:
permissions:
contents: read
concurrency:
group: installer-tests-${{ github.ref }}
cancel-in-progress: true
jobs:
powershell:
name: PowerShell installer tests
runs-on: windows-latest
timeout-minutes: 15
steps:
- name: Checkout code
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
# Windows PowerShell 5.1 as well as pwsh 7: install.ps1 is delivered via
# `irm | iex` into whatever shell the user already has, and 5.1 is what
# ships with Windows. A construct that only parses under 7 is a broken
# installer for most of the people hitting it.
- name: 8.3 short-path normalization (pwsh 7)
shell: pwsh
run: pwsh -NoProfile -ExecutionPolicy Bypass -File scripts/tests/test-install-ps1-longpath.ps1
- name: 8.3 short-path normalization (Windows PowerShell 5.1)
shell: powershell
run: powershell -NoProfile -ExecutionPolicy Bypass -File scripts/tests/test-install-ps1-longpath.ps1
- name: System Node and npm compatibility (pwsh 7)
shell: pwsh
run: pwsh -NoProfile -ExecutionPolicy Bypass -File scripts/tests/test-install-ps1-node-compatibility.ps1
- name: System Node and npm compatibility (Windows PowerShell 5.1)
shell: powershell
run: powershell -NoProfile -ExecutionPolicy Bypass -File scripts/tests/test-install-ps1-node-compatibility.ps1
- name: Managed uv acceptance rejects relocated shims (pwsh 7)
shell: pwsh
run: pwsh -NoProfile -ExecutionPolicy Bypass -File scripts/tests/test-install-ps1-uv-shim-validation.ps1
- name: Managed uv acceptance rejects relocated shims (Windows PowerShell 5.1)
shell: powershell
run: powershell -NoProfile -ExecutionPolicy Bypass -File scripts/tests/test-install-ps1-uv-shim-validation.ps1
+4 -7
View File
@@ -65,14 +65,11 @@ jobs:
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- name: Set up locked Node and npm
id: node
uses: ./.github/actions/setup-pm
with:
node-version: 26
cache: npm
- name: grab npm 12
run: |
npm i -g npm@12
toolchain: node
# --ignore-scripts: eslint only needs TS sources + eslint packages.
- uses: ./.github/actions/retry
+12 -19
View File
@@ -18,18 +18,17 @@ jobs:
timeout-minutes: 30
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- name: Set up the locked JS build toolchain
id: node
uses: ./.github/actions/setup-pm
with:
node-version: 26
cache: npm
# Desktop checks also run Python payload and icon build helpers, and
# the electron contracts drive real hermes_cli/pm code through
# HERMES_PYTHON, which needs the application dependencies.
toolchain: all
extras: '[]'
test-environment: 'true'
# The desktop SSH watchdog tests run their probe through a real zsh
# login shell (#111949). The ubuntu image ships no zsh and the tests
# skip without it, so install it here or those legs never run on CI.
#
# The desktop portal-session live test drives real Electron windows
# (electron/portal-session-live.test.ts) and skips without a display,
# so give the runner a virtual one the same way the Playwright lane does.
- name: Install zsh and a virtual display for Electron
if: runner.os == 'Linux'
run: |
@@ -37,14 +36,8 @@ jobs:
libgtk-3-0 libnotify4 libnss3 libxss1 libxtst6 \
xdg-utils libatspi2.0-0 libdrm2 libgbm1 libasound2t64
- name: grab npm 12
run: |
# No-op once the bundled npm is already 12.x — saves ~5-15s/job and
# keeps the installed major aligned with the npm12 cache-key tag.
npm --version | grep -q '^12\.' || npm i -g npm@12
# The ``cache: npm`` option of ``setup-node`` caches only the ~/.npm
# tarball cache. The job then extracts the full workspace node_modules
# setup-pm caches npm downloads, not the installed workspace tree.
# The job then extracts the full workspace node_modules
# again and runs the postinstalls again, which includes the Electron
# binary fetch. This caches the installed tree itself, keyed on the
# lockfile, and skips ``npm ci`` on an exact hit. There are no
@@ -69,7 +62,7 @@ jobs:
ui-tui/packages/*/node_modules
tests-js/node_modules
web/node_modules
key: node-modules-scripts-${{ runner.os }}-node26-npm12-${{ hashFiles('package-lock.json') }}
key: node-modules-scripts-${{ runner.os }}-${{ runner.arch }}-node${{ steps.node.outputs.node-version }}-npm${{ steps.node.outputs.npm-version }}-${{ hashFiles('package-lock.json') }}
- uses: ./.github/actions/retry
if: steps.node-modules-cache.outputs.cache-hit != 'true'
+37
View File
@@ -0,0 +1,37 @@
name: Lazy-deps import guard
# Rejects any tracked production code that imports tools/lazy_deps.py.
# The pm migration reduced it to an old-updater stub that only raises or
# stops for relaunch (pm.extras — available / ensure_import /
# ensure_and_bind — is the only lazy-install surface), so a production
# import never gets its dependencies.
#
# Runs unconditionally (no change-classifier gate): the stub
# must stay unimported on every change, in any kind of PR — the same
# "passive rule that cannot enforce a policy" reasoning as the
# case-collision check. Not folded into lint.yml because the lint lane is
# language-gated by the orchestrator's detect outputs.
#
# The checker builds the tracked inventory (git ls-files), does AST import
# analysis (comments/prose ignored by construction), and FAILS on
# inventory errors — it can never pass by scanning nothing. Exit 1 lists
# the exact offender sites; their migration is owned by the lazy-deps
# owner, not this gate. Contract tests (fixture repos prove red/green):
# tests/pm/test_no_lazy_deps.py.
on:
workflow_call:
permissions:
contents: read
jobs:
lazy-deps-guard:
name: No production imports of the tools.lazy_deps stub
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Check tools.lazy_deps imports in tracked production code
run: python3 scripts/ci/check_lazy_deps_imports.py
+17 -28
View File
@@ -23,8 +23,8 @@ permissions:
contents: read
concurrency:
group: lint-${{ github.ref }}
cancel-in-progress: true
group: lint-${{ github.ref_type == 'tag' && github.run_id || github.ref }}
cancel-in-progress: ${{ github.ref_type != 'tag' }}
jobs:
lint-diff:
@@ -38,18 +38,15 @@ jobs:
with:
fetch-depth: 0 # need full history for merge-base + worktree
- name: Install uv
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0
- uses: ./.github/actions/setup-pm
with:
# Pinned: unpinned setup-uv fetches a 'latest' manifest from
# raw.githubusercontent.com every job; transient fetch failures
# fail the job (2026-07-28 incident). Keep in sync with tests.yml.
version: "0.9.28"
cache-python: true
prune-python-cache: true
- name: Install ruff + ty
uses: ./.github/actions/retry
with:
command: uv tool install ruff && uv tool install ty
command: python -m scripts.ci.python_packages ruff==0.15.10 ty==0.0.82
- name: Determine base ref
id: base
@@ -132,18 +129,15 @@ jobs:
- name: Checkout code
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Install uv
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0
- uses: ./.github/actions/setup-pm
with:
# Pinned: unpinned setup-uv fetches a 'latest' manifest from
# raw.githubusercontent.com every job; transient fetch failures
# fail the job (2026-07-28 incident). Keep in sync with tests.yml.
version: "0.9.28"
cache-python: true
prune-python-cache: true
- name: Install ruff
uses: ./.github/actions/retry
with:
command: uv tool install ruff
command: python -m scripts.ci.python_packages ruff==0.15.10
- name: ruff check .
# No --exit-zero, no || true. Exit code propagates to the job,
@@ -163,22 +157,17 @@ jobs:
- name: Checkout code
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Install uv
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0
- uses: ./.github/actions/setup-pm
with:
# Pinned: unpinned setup-uv fetches a 'latest' manifest from
# raw.githubusercontent.com every job; transient fetch failures
# fail the job (2026-07-28 incident). Keep in sync with tests.yml.
version: "0.9.28"
- name: Set up Python 3.11
uses: ./.github/actions/retry
with:
command: uv python install 3.11
cache-python: true
prune-python-cache: true
- name: Run footgun checker
run: python scripts/check-windows-footguns.py --all
- name: Require portable Bash shebangs
run: python scripts/check_bash_shebangs.py
# The Sep 2026 decomposition kept old import paths alive for external plugins
# (PLUGIN-COMPAT blocks, see COMPAT_MANIFEST.md). They are removed on schedule by
# reverting one commit, so in-tree code must never depend on them.
@@ -199,7 +188,7 @@ jobs:
run: python scripts/check_config_yaml_writers.py
# The OS lanes import only files carrying the matching marker, so a test that fakes
# macOS (is_macos -> True, sys.platform -> "darwin") without `macos_only` is green on
# macOS (is_macos -> True, sys.platform -> "darwin") without `platforms("macos")` is green on
# Linux over a faked branch and never runs on macOS (#111866, AGENTS.md § Don't fake the host OS).
- name: Forbid unmarked macOS fakes in tests
run: python scripts/ci/check_os_marker_fakes.py
+3 -3
View File
@@ -77,17 +77,17 @@ jobs:
pyproject.toml
uv.lock
- name: Set up Python 3.11
- name: Set up Python 3.14
if: steps.gate.outputs.configured != '0'
uses: ./.github/actions/retry
with:
command: uv python install 3.11
command: uv python install 3.14
- name: Install dependencies
if: steps.gate.outputs.configured != '0'
uses: ./.github/actions/retry
with:
command: uv sync --locked --python 3.11 --extra all --extra dev --extra anthropic
command: uv sync --locked --python 3.14 --extra all --group dev --extra anthropic
- name: Run live canaries
if: steps.gate.outputs.configured != '0'
+57 -7
View File
@@ -14,16 +14,30 @@ on:
pull_request:
push:
branches: [main]
workflow_call:
inputs:
release:
description: 'Stable-release candidate run: force the flake-check lane regardless of the classifier.'
required: false
type: boolean
default: false
version:
description: 'Release version stamped into an isolated flake source tree.'
required: false
type: string
default: ''
permissions:
contents: read
# PR runs collapse to the newest commit. A push to main is never cancelled:
# each one saves the store cache that later PRs restore from, so cancelling a
# merge would leave the next PR to build from nothing.
# A workflow_call run (stable release) is never cancelled: its group uses
# github.run_id so a parent rerun cannot kill this child mid-flight, and
# cancel-in-progress is false there — each run saves the store cache that
# later PRs restore from.
concurrency:
group: nix-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
group: nix-${{ inputs.release == true && github.run_id || github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ inputs.release != true && github.event_name == 'pull_request' }}
jobs:
# A `paths:` filter cannot gate this workflow correctly. The flake packages
@@ -39,6 +53,10 @@ jobs:
nix: ${{ steps.classify.outputs.nix }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
# github.sha is the exact candidate commit on a stable tag-dispatched
# caller and the head SHA on every other event.
ref: ${{ github.sha }}
- name: Detect affected areas
id: classify
@@ -49,7 +67,9 @@ jobs:
flake-check:
name: nix flake check
needs: [detect]
if: needs.detect.outputs.nix == 'true'
# Release runs force the lane: a stable candidate must build the flake
# no matter what its diff touches.
if: needs.detect.outputs.nix == 'true' || inputs.release == true
# The build compiles the package and its whole dependency closure, so this
# takes minutes and not seconds when the cache misses. `nix flake check`
# builds 21 checks, and --max-jobs defaults to the core count. It uses the
@@ -59,6 +79,10 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
# github.sha is the exact candidate commit on a stable tag-dispatched
# caller and the head SHA on every other event.
ref: ${{ github.sha }}
- name: Install Nix
uses: cachix/install-nix-action@630ae543ea3a38a9a4166f03376c02c50f408342 # v31.11.0
@@ -113,7 +137,33 @@ jobs:
purge-created: 0
purge-primary-key: never
- name: Prepare isolated release source
if: inputs.release == true
env:
RELEASE_VERSION: ${{ inputs.version }}
run: |
mkdir -p "$RUNNER_TEMP/release-source"
git archive "$GITHUB_SHA" | tar -x -C "$RUNNER_TEMP/release-source"
python3 scripts/releases/stamping.py --tree "$RUNNER_TEMP/release-source" \
--version "$RELEASE_VERSION"
- name: nix flake check
# --print-build-logs: a check that fails then prints the assertion
# that failed, and not only the derivation that failed to build.
run: nix flake check --print-build-logs
run: nix flake check "${{ inputs.release == true && format('path:{0}/release-source', runner.temp) || '.' }}" --print-build-logs
- name: Verify release package runtime identity
if: inputs.release == true
env:
RELEASE_VERSION: ${{ inputs.version }}
run: |
package="$(nix build "path:$RUNNER_TEMP/release-source#hermes-agent" --no-link --print-out-paths)"
actual="$("$package/bin/hermes" --version)"
ACTUAL_VERSION="$actual" python3 - <<'PY'
import os
expected = os.environ["RELEASE_VERSION"]
actual = os.environ["ACTUAL_VERSION"].split()[-1].removeprefix("v")
if actual != expected:
raise SystemExit(f"Nix package version mismatch: expected {expected}, got {actual}")
PY
-1
View File
@@ -49,4 +49,3 @@ jobs:
--lockfile=scripts/whatsapp-bridge/package-lock.json
results-file-name: osv-results.sarif
fail-on-vuln: false
+7 -10
View File
@@ -29,10 +29,10 @@ jobs:
with:
python-version: "3.11"
- name: Install PyYAML
- name: Install ruamel.yaml
uses: ./.github/actions/retry
with:
command: pip install pyyaml==6.0.2
command: pip install ruamel.yaml==0.18.17
- name: Validate catalog files (structural)
run: |
@@ -49,10 +49,6 @@ jobs:
with:
fetch-depth: 0 # need the merge-base to diff changed catalog files
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
with:
python-version: "3.11"
- name: Find changed catalog entries
id: changed
run: |
@@ -71,11 +67,12 @@ jobs:
echo '__EOF__'
} >> "$GITHUB_OUTPUT"
- name: Install hermes-agent from the PR's own checkout
- name: Prepare Hermes from the PR's own checkout
if: steps.changed.outputs.files != ''
uses: ./.github/actions/retry
uses: ./.github/actions/setup-pm
with:
command: pip install -e .
toolchain: python
extras: '[]'
- name: Clone each entry at its pinned sha and validate
if: steps.changed.outputs.files != ''
@@ -93,7 +90,7 @@ jobs:
import shlex
import sys
import yaml
import hermes_yaml as yaml
with open(sys.argv[1], encoding="utf-8") as fh:
data = yaml.safe_load(fh) or {}
+149
View File
@@ -0,0 +1,149 @@
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 commit, github.sha)'
required: false
type: string
workflow_call:
inputs:
release:
description: 'Stable-release candidate run (ignored by the jobs; uniform callable surface).'
required: false
type: boolean
default: false
ref:
description: 'Git ref to bundle (default: the triggering commit, github.sha)'
required: false
type: string
default: ''
pull_request:
paths:
- 'pm/**'
- 'scripts/bundles/**'
- 'scripts/ci/desktop_build_cache.py'
- '.github/actions/desktop-build-cache/**'
- 'scripts/windows-build-deps.ps1'
- 'scripts/build/windows-deps.ps1'
- '.github/actions/setup-windows-build-deps/**'
- 'uv.lock'
- 'pyproject.toml'
- '.github/workflows/pm-bundle.yml'
permissions:
contents: read
# A workflow_call run (stable release) is never cancelled: its group uses
# github.run_id so a parent rerun cannot kill this child mid-flight.
concurrency:
group: pm-bundle-${{ inputs.release == true && github.run_id || github.ref }}
cancel-in-progress: ${{ inputs.release != true }}
jobs:
bundle:
name: bundle ${{ matrix.target.label }}
runs-on: ${{ matrix.target.runner }}
# Leave time for setup, cache saves and smoke tests around the wheel build.
timeout-minutes: 180
strategy:
fail-fast: false
matrix:
target:
# TODO(ethie): restore the linux legs once the ubuntu-latest-32-*
# larger runners are re-imaged to Ubuntu 24.04. They currently boot
# ubuntu-22.04 (glibc 2.35), and the prebuilt llama-server staged by
# the native payload requires GLIBC_2.38, so verification fails.
# - label: linux-x64
# runner: ubuntu-latest-32-core
# - label: linux-arm64
# runner: ubuntu-latest-32-arm-core
- label: darwin-arm64
runner: macos-15
- label: darwin-x64
runner: macos-15-intel
- label: win32-x64
runner: windows-latest-32-core
- label: win32-arm64
runner: windows-latest-32-arm-core
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
# Default to the exact candidate commit (github.sha); inputs.ref
# remains an escape hatch for a focused manual reproduction.
ref: ${{ inputs.ref || github.sha }}
fetch-tags: true
# The bootstrap scripts need Python >= 3.11 (tomllib). Larger runners
# (ubuntu-latest-32-*) are provisioned with ubuntu-22.04 images whose
# system python3 is 3.10, so pin the bootstrap interpreter instead of
# trusting the image.
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
with:
python-version: "3.13"
- name: Restore native dependency candidates
id: native-cache
uses: ./.github/actions/desktop-build-cache
with:
phase: restore
source: ${{ github.workspace }}
work: ${{ runner.temp }}/payload-job
cache: ${{ runner.temp }}/payload-inputs
producer: payload-test
- name: Prepare native payload dependencies
id: prepare
shell: bash
env:
PAYLOAD_WORK: ${{ runner.temp }}/payload-job
PAYLOAD_CACHE: ${{ runner.temp }}/payload-inputs
PYTHONUTF8: '1'
run: |
if [ "$RUNNER_OS" = Windows ]; then bootstrap=python; else bootstrap=python3; fi
"$bootstrap" -S -B scripts/bundles/native_build.py --prepare-only \
--source "$GITHUB_WORKSPACE" --work "$PAYLOAD_WORK" --cache "$PAYLOAD_CACHE" \
--out "$GITHUB_WORKSPACE/build/agent-payload" --ref HEAD
# PRs can restore candidates but never gain a cache-writing lane here.
- name: Save native dependency candidates before assembly
if: ${{ !cancelled() && steps.prepare.outcome == 'success' && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' && (inputs.ref == '' || inputs.ref == github.sha) }}
uses: ./.github/actions/desktop-build-cache
with:
phase: save
source: ${{ github.workspace }}
work: ${{ runner.temp }}/payload-job
cache: ${{ runner.temp }}/payload-inputs
producer: payload-test
key: ${{ steps.native-cache.outputs.cache-key }}
- name: Assemble the prepared payload without dependency acquisition
shell: bash
run: |
if [ "$RUNNER_OS" = Windows ]; then bootstrap=python; else bootstrap=python3; fi
"$bootstrap" -S -B scripts/bundles/native_build.py \
--prepared "$GITHUB_WORKSPACE/build/agent-payload.prepared.json"
# The generated command must survive relocation without checkout env/cwd.
- name: Smoke test the relocated payload (network disabled)
if: startsWith(matrix.target.label, 'linux-')
shell: bash
run: sudo --preserve-env=PATH unshare --net bash scripts/smoke-payload.sh build/agent-payload
- name: Smoke test the relocated payload (native launchers)
if: ${{ !startsWith(matrix.target.label, 'linux-') }}
shell: bash
run: bash scripts/smoke-payload.sh build/agent-payload
+16 -2
View File
@@ -21,8 +21,8 @@ permissions:
contents: read
concurrency:
group: rust-tests-${{ github.ref }}
cancel-in-progress: true
group: rust-tests-${{ github.ref_type == 'tag' && github.run_id || github.ref }}
cancel-in-progress: ${{ github.ref_type != 'tag' }}
jobs:
bootstrap-installer:
@@ -38,6 +38,20 @@ jobs:
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
# tauri::generate_context! embeds the app icons, which are generated,
# not committed. The generator runs on a Hermes runtime interpreter; []
# exports one as HERMES_PYTHON.
- uses: ./.github/actions/setup-pm
with:
toolchain: all
extras: '[]'
cache-python: true
prune-python-cache: true
- name: Generate icons
working-directory: .
run: node scripts/generate-icons.mjs
# Tauri links against the system webkit2gtk on Linux, so the crate does
# not compile without these even for `cargo test --lib`.
- name: Install Tauri system dependencies
+3 -3
View File
@@ -37,14 +37,14 @@ jobs:
client-id: ${{ vars.APP_CLIENT_ID }}
private-key: ${{ secrets.APP_PRIVATE_KEY }}
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6.2.0
- uses: ./.github/actions/setup-pm
with:
python-version: "3.11"
cache-python: true
- name: Install dependencies
uses: ./.github/actions/retry
with:
command: pip install httpx==0.28.1 pyyaml==6.0.2
command: python -m scripts.ci.python_packages httpx==0.28.1 ruamel.yaml==0.18.17
- name: Build skills index
env:
@@ -0,0 +1,68 @@
name: Stable Release Publication
on:
workflow_dispatch:
inputs:
version:
description: 'Green stable version to publish (for example 0.21.5)'
required: false
type: string
default: ''
# The success path publishes from Stable Release's own final job; only a
# failed run needs this pass, which reruns its failed jobs immediately.
workflow_run:
workflows: ['Stable Release']
types: [completed]
# Shared with Stable Release so publication never races a build. The requested
# rerun waits as pending behind this job instead of deadlocking it: the
# sequencer only confirms the new attempt is queued, never that it finished.
concurrency:
group: stable-release
cancel-in-progress: false
permissions:
contents: write
actions: write
jobs:
reconcile:
if: >-
github.event_name != 'workflow_run' ||
(github.event.workflow_run.conclusion != 'success' &&
github.event.workflow_run.event == 'workflow_dispatch' &&
github.event.workflow_run.head_repository.full_name == github.repository)
runs-on: ubuntu-24.04
timeout-minutes: 30
environment: release-signing
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.event.repository.default_branch }}
fetch-depth: 0
persist-credentials: false
- uses: ./.github/actions/setup-pm
with:
toolchain: node
cache-python: false
- name: Set up Docker Buildx for ordered alias promotion
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- name: Log in to Docker Hub for ordered alias promotion
uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Reconcile stable drafts and protected heads
run: python -m scripts.releases.sequencer
env:
GH_TOKEN: ${{ github.token }}
REQUESTED_VERSION: ${{ inputs.version || '' }}
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 }}
MS_STORE_TENANT_ID: ${{ secrets.MS_STORE_TENANT_ID }}
MS_STORE_CLIENT_ID: ${{ secrets.MS_STORE_CLIENT_ID }}
MS_STORE_CLIENT_SECRET: ${{ secrets.MS_STORE_CLIENT_SECRET }}
MS_STORE_PRODUCT_ID: ${{ vars.MS_STORE_PRODUCT_ID }}
+616
View File
@@ -0,0 +1,616 @@
name: Stable Release
run-name: Stable release ${{ inputs.tag }}
# Dispatch on the tag so reusable workflows and github.sha identify the same tree.
on:
workflow_dispatch:
inputs:
tag:
description: Exact annotated claim tag, matching the selected workflow ref
required: true
type: string
baseline-manifest:
description: Optional HTTPS manifest of the previous published stable packages
default: ''
type: string
permissions:
contents: read
concurrency:
group: stable-release
cancel-in-progress: false
jobs:
admit:
name: Admit the claim
# A read token cannot see a draft release, so gh release view answers
# "release not found" for a draft that exists. Write is the permission
# that can read it.
permissions:
contents: write
runs-on: ubuntu-24.04
outputs:
claim-tag: ${{ steps.admit.outputs.claim-tag }}
claim-object: ${{ steps.admit.outputs.claim-object }}
tag: ${{ steps.admit.outputs.tag }}
commit: ${{ steps.admit.outputs.commit }}
version: ${{ steps.admit.outputs.version }}
release-id: ${{ steps.admit.outputs.release-id }}
release-epoch: ${{ steps.admit.outputs.release-epoch }}
skip-bundles: ${{ steps.admit.outputs.skip-bundles }}
skip-tests: ${{ steps.admit.outputs.skip-tests }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.sha }}
fetch-depth: 0
- uses: ./.github/actions/setup-pm
with:
cache-python: false
- id: admit
run: python -m scripts.releases.stable admit
env:
GH_TOKEN: ${{ github.token }}
RELEASE_CLAIM_TAG: ${{ inputs.tag }}
ci:
name: Full CI pipeline
needs: admit
if: needs.admit.outputs.skip-tests != 'true'
permissions:
contents: read
pull-requests: write
actions: read
security-events: write
uses: ./.github/workflows/ci.yaml
with:
release: true
docker:
name: Docker build and tests
needs: [admit, ci]
# The image publish-docker pushes is built here, so a claim that skipped
# tests still runs this job with its tests off.
if: >-
!cancelled() && needs.admit.result == 'success'
&& (needs.ci.result == 'success' || needs.admit.outputs.skip-tests == 'true')
uses: ./.github/workflows/docker.yml
with:
release-phase: test
skip-tests: ${{ needs.admit.outputs.skip-tests == 'true' }}
tag: ${{ needs.admit.outputs.tag }}
version: ${{ needs.admit.outputs.version }}
nix:
needs: [admit, ci, docker]
uses: ./.github/workflows/nix.yml
with:
release: true
version: ${{ needs.admit.outputs.version }}
pm-bundle:
needs: [admit, ci, docker]
# Needing ci already removes it under skip-tests.
if: needs.admit.outputs.skip-bundles != 'true'
uses: ./.github/workflows/pm-bundle.yml
with:
release: true
ref: ${{ github.sha }}
termux-checks:
needs: [ci, docker]
permissions:
contents: read
actions: read
uses: ./.github/workflows/termux-verify.yml
with:
release: true
windows-live:
needs: [ci, docker]
uses: ./.github/workflows/windows-venv-e2e.yml
with:
release: true
install-e2e:
name: Install and update E2E
needs: [ci, docker]
permissions:
contents: read
actions: read
uses: ./.github/workflows/install-e2e.yml
with:
release: true
route: all
tag-count: '3'
exclude-ref: ${{ inputs.tag }}
candidates-darwin-arm64:
name: Build signed release candidates (darwin-arm64)
needs: [admit, ci, docker]
if: >-
!cancelled() && needs.admit.result == 'success' && needs.admit.outputs.skip-bundles != 'true'
&& needs.docker.result == 'success'
&& (needs.ci.result == 'success' || needs.admit.outputs.skip-tests == 'true')
permissions:
contents: write
actions: read
packages: write
id-token: write
uses: ./.github/workflows/desktop-bundled-release.yml
with:
tag: ${{ needs.admit.outputs.tag }}
claim-tag: ${{ needs.admit.outputs.claim-tag }}
claim-object: ${{ needs.admit.outputs.claim-object }}
release-phase: candidate
jobs: darwin-arm64
skip-tests: ${{ needs.admit.outputs.skip-tests == 'true' }}
candidates-darwin-x64:
name: Build signed release candidates (darwin-x64)
needs: [admit, ci, docker]
if: >-
!cancelled() && needs.admit.result == 'success' && needs.admit.outputs.skip-bundles != 'true'
&& needs.docker.result == 'success'
&& (needs.ci.result == 'success' || needs.admit.outputs.skip-tests == 'true')
permissions:
contents: write
actions: read
packages: write
id-token: write
uses: ./.github/workflows/desktop-bundled-release.yml
with:
tag: ${{ needs.admit.outputs.tag }}
claim-tag: ${{ needs.admit.outputs.claim-tag }}
claim-object: ${{ needs.admit.outputs.claim-object }}
release-phase: candidate
jobs: darwin-x64
skip-tests: ${{ needs.admit.outputs.skip-tests == 'true' }}
candidates-win32-arm64:
name: Build signed release candidates (win32-arm64)
needs: [admit, ci, docker]
if: >-
!cancelled() && needs.admit.result == 'success' && needs.admit.outputs.skip-bundles != 'true'
&& needs.docker.result == 'success'
&& (needs.ci.result == 'success' || needs.admit.outputs.skip-tests == 'true')
permissions:
contents: write
actions: read
packages: write
id-token: write
uses: ./.github/workflows/desktop-bundled-release.yml
with:
tag: ${{ needs.admit.outputs.tag }}
claim-tag: ${{ needs.admit.outputs.claim-tag }}
claim-object: ${{ needs.admit.outputs.claim-object }}
release-phase: candidate
jobs: win32-arm64
skip-tests: ${{ needs.admit.outputs.skip-tests == 'true' }}
candidates-win32-x64:
name: Build signed release candidates (win32-x64)
needs: [admit, ci, docker]
if: >-
!cancelled() && needs.admit.result == 'success' && needs.admit.outputs.skip-bundles != 'true'
&& needs.docker.result == 'success'
&& (needs.ci.result == 'success' || needs.admit.outputs.skip-tests == 'true')
permissions:
contents: write
actions: read
packages: write
id-token: write
uses: ./.github/workflows/desktop-bundled-release.yml
with:
tag: ${{ needs.admit.outputs.tag }}
claim-tag: ${{ needs.admit.outputs.claim-tag }}
claim-object: ${{ needs.admit.outputs.claim-object }}
release-phase: candidate
jobs: win32-x64
skip-tests: ${{ needs.admit.outputs.skip-tests == 'true' }}
candidates-win32-bundle:
name: Build signed release candidates (win32-bundle)
needs: [admit, ci, docker, candidates-win32-arm64, candidates-win32-x64]
if: >-
!cancelled() && needs.admit.result == 'success' && needs.admit.outputs.skip-bundles != 'true'
&& needs.docker.result == 'success'
&& (needs.ci.result == 'success' || needs.admit.outputs.skip-tests == 'true')
&& needs.candidates-win32-arm64.result == 'success'
&& needs.candidates-win32-x64.result == 'success'
permissions:
contents: write
actions: read
packages: write
id-token: write
uses: ./.github/workflows/desktop-bundled-release.yml
with:
tag: ${{ needs.admit.outputs.tag }}
claim-tag: ${{ needs.admit.outputs.claim-tag }}
claim-object: ${{ needs.admit.outputs.claim-object }}
release-phase: candidate
jobs: win32-bundle
skip-tests: ${{ needs.admit.outputs.skip-tests == 'true' }}
candidates-termux:
name: Build signed release candidates (termux)
needs: [admit, ci, docker]
if: >-
!cancelled() && needs.admit.result == 'success' && needs.admit.outputs.skip-bundles != 'true'
&& needs.docker.result == 'success'
&& (needs.ci.result == 'success' || needs.admit.outputs.skip-tests == 'true')
permissions:
contents: write
actions: read
packages: write
id-token: write
uses: ./.github/workflows/desktop-bundled-release.yml
with:
tag: ${{ needs.admit.outputs.tag }}
claim-tag: ${{ needs.admit.outputs.claim-tag }}
claim-object: ${{ needs.admit.outputs.claim-object }}
release-phase: candidate
jobs: termux
skip-tests: ${{ needs.admit.outputs.skip-tests == 'true' }}
transitions-darwin-arm64:
name: Pin actual OLD and NEW signed packages (darwin-arm64)
needs: [admit, candidates-darwin-arm64]
if: needs.admit.outputs.skip-tests != 'true'
runs-on: ubuntu-24.04
environment: release-signing
outputs:
windows: ${{ steps.plan.outputs.windows }}
macos: ${{ steps.plan.outputs.macos }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.sha }}
fetch-depth: 0
- uses: ./.github/actions/setup-pm
with:
cache-python: false
- id: plan
run: python -m scripts.releases.stable transitions
env:
GH_TOKEN: ${{ github.token }}
RECEIPT: darwin-arm64
RECEIPT_URL: ${{ needs.candidates-darwin-arm64.outputs.darwin-arm64-receipt-url }}
RECEIPT_SHA256: ${{ needs.candidates-darwin-arm64.outputs.darwin-arm64-receipt-sha256 }}
RELEASE_TAG: ${{ needs.admit.outputs.tag }}
RELEASE_CLAIM_TAG: ${{ needs.admit.outputs.claim-tag }}
RELEASE_CLAIM_OBJECT: ${{ needs.admit.outputs.claim-object }}
BASELINE_MANIFEST_URL: ${{ inputs.baseline-manifest }}
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 }}
transitions-darwin-x64:
name: Pin actual OLD and NEW signed packages (darwin-x64)
needs: [admit, candidates-darwin-x64]
if: needs.admit.outputs.skip-tests != 'true'
runs-on: ubuntu-24.04
environment: release-signing
outputs:
windows: ${{ steps.plan.outputs.windows }}
macos: ${{ steps.plan.outputs.macos }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.sha }}
fetch-depth: 0
- uses: ./.github/actions/setup-pm
with:
cache-python: false
- id: plan
run: python -m scripts.releases.stable transitions
env:
GH_TOKEN: ${{ github.token }}
RECEIPT: darwin-x64
RECEIPT_URL: ${{ needs.candidates-darwin-x64.outputs.darwin-x64-receipt-url }}
RECEIPT_SHA256: ${{ needs.candidates-darwin-x64.outputs.darwin-x64-receipt-sha256 }}
RELEASE_TAG: ${{ needs.admit.outputs.tag }}
RELEASE_CLAIM_TAG: ${{ needs.admit.outputs.claim-tag }}
RELEASE_CLAIM_OBJECT: ${{ needs.admit.outputs.claim-object }}
BASELINE_MANIFEST_URL: ${{ inputs.baseline-manifest }}
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 }}
transitions-win32:
name: Pin actual OLD and NEW signed packages (win32)
needs: [admit, candidates-win32-bundle]
if: needs.admit.outputs.skip-tests != 'true'
runs-on: ubuntu-24.04
environment: release-signing
outputs:
windows: ${{ steps.plan.outputs.windows }}
macos: ${{ steps.plan.outputs.macos }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.sha }}
fetch-depth: 0
- uses: ./.github/actions/setup-pm
with:
cache-python: false
- id: plan
run: python -m scripts.releases.stable transitions
env:
GH_TOKEN: ${{ github.token }}
RECEIPT: win32-bundle
RECEIPT_URL: ${{ needs.candidates-win32-bundle.outputs.win32-bundle-receipt-url }}
RECEIPT_SHA256: ${{ needs.candidates-win32-bundle.outputs.win32-bundle-receipt-sha256 }}
RELEASE_TAG: ${{ needs.admit.outputs.tag }}
RELEASE_CLAIM_TAG: ${{ needs.admit.outputs.claim-tag }}
RELEASE_CLAIM_OBJECT: ${{ needs.admit.outputs.claim-object }}
BASELINE_MANIFEST_URL: ${{ inputs.baseline-manifest }}
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 }}
candidate-manifest:
name: Stage verified stable candidate artifacts
# Runs after every candidate call, so after every smoke (decision 23).
# The recorded smoke results are the calls' own workflow results: a
# call's stable-phase-result fails when its smokes fail, so a failed
# smoke fails this job's RELEASE_NEEDS check and stages no manifest.
if: always() && needs.admit.outputs.skip-bundles != 'true'
needs: [admit, candidates-darwin-arm64, candidates-darwin-x64, candidates-win32-arm64,
candidates-win32-x64, candidates-win32-bundle, candidates-termux]
runs-on: ubuntu-24.04
environment: release-signing
timeout-minutes: 90
outputs:
manifest-url: ${{ steps.manifest.outputs.manifest-url }}
manifest-sha256: ${{ steps.manifest.outputs.manifest-sha256 }}
env:
RELEASE_TAG: ${{ needs.admit.outputs.tag }}
RELEASE_CLAIM_TAG: ${{ needs.admit.outputs.claim-tag }}
RELEASE_CLAIM_OBJECT: ${{ needs.admit.outputs.claim-object }}
RELEASE_NEEDS: ${{ toJSON(needs) }}
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:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.sha }}
fetch-depth: 0
fetch-tags: true
- uses: ./.github/actions/setup-pm
with:
cache-python: false
- id: manifest
run: python -m scripts.releases.stable candidate-manifest
windows-packaged:
name: Windows signed-package acceptance
needs: transitions-win32
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.transitions-win32.outputs.windows) }}
uses: ./.github/workflows/install-e2e-windows-run.yml
with:
install-method: packaged-app
update-method: open-app-update
install-ref: ${{ matrix.old }}
leg-id: stable-${{ matrix.id }}
bundle-manifest-url: ${{ matrix.manifest }}
bundle-manifest-sha256: ${{ matrix.manifest_sha256 }}
bundle-arch: ${{ matrix.arch }}
macos-packaged-arm64:
name: macOS arm64 signed-package acceptance
needs: transitions-darwin-arm64
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.transitions-darwin-arm64.outputs.macos) }}
uses: ./.github/workflows/install-e2e-macos-run.yml
with:
install-method: packaged-app
update-method: open-app-update
install-ref: ${{ matrix.old }}
leg-id: stable-${{ matrix.id }}
bundle-manifest-url: ${{ matrix.manifest }}
bundle-manifest-sha256: ${{ matrix.manifest_sha256 }}
bundle-arch: ${{ matrix.arch }}
macos-packaged-x64:
name: macOS x64 signed-package acceptance
needs: transitions-darwin-x64
strategy:
fail-fast: false
matrix: ${{ fromJSON(needs.transitions-darwin-x64.outputs.macos) }}
uses: ./.github/workflows/install-e2e-macos-run.yml
with:
install-method: packaged-app
update-method: open-app-update
install-ref: ${{ matrix.old }}
leg-id: stable-${{ matrix.id }}
bundle-manifest-url: ${{ matrix.manifest }}
bundle-manifest-sha256: ${{ matrix.manifest_sha256 }}
bundle-arch: ${{ matrix.arch }}
bootstrap-version:
name: Bootstrap installer release identity
needs: admit
if: needs.admit.outputs.skip-tests != 'true'
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ needs.admit.outputs.commit }}
- name: Stamp and verify the Cargo and Tauri release identity
env:
RELEASE_COMMIT: ${{ needs.admit.outputs.commit }}
RELEASE_VERSION: ${{ needs.admit.outputs.version }}
run: |
set -euo pipefail
tree="$RUNNER_TEMP/bootstrap-release"
mkdir -p "$tree"
git archive "$RELEASE_COMMIT" | tar -x -C "$tree"
python3 -m scripts.releases.stamping --tree "$tree" \
--version "$RELEASE_VERSION"
actual="$(cargo metadata --no-deps --format-version 1 \
--manifest-path "$tree/apps/bootstrap-installer/src-tauri/Cargo.toml" \
| jq -r '.packages[] | select(.name == "hermes-bootstrap") | .version')"
test "$actual" = "$RELEASE_VERSION" || {
echo "::error::Bootstrap Cargo version $actual != $RELEASE_VERSION"
exit 1
}
actual_tauri="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["version"])' \
"$tree/apps/bootstrap-installer/src-tauri/tauri.conf.json")"
test "$actual_tauri" = "$RELEASE_VERSION" || {
echo "::error::Bootstrap Tauri version $actual_tauri != $RELEASE_VERSION"
exit 1
}
acceptance:
name: All release acceptance checks pass
if: always()
needs: [admit, ci, docker, nix, pm-bundle, termux-checks, windows-live, install-e2e,
candidates-darwin-arm64, candidates-darwin-x64, candidates-win32-arm64,
candidates-win32-x64, candidates-win32-bundle, candidates-termux,
candidate-manifest, transitions-darwin-arm64, transitions-darwin-x64,
transitions-win32, windows-packaged, macos-packaged-arm64, macos-packaged-x64,
bootstrap-version]
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.sha }}
- uses: ./.github/actions/setup-pm
with:
cache-python: false
- run: python -m scripts.releases.stable gate admit ci docker nix pm-bundle termux-checks windows-live install-e2e candidates-darwin-arm64 candidates-darwin-x64 candidates-win32-arm64 candidates-win32-x64 candidates-win32-bundle candidates-termux candidate-manifest transitions-darwin-arm64 transitions-darwin-x64 transitions-win32 windows-packaged macos-packaged-arm64 macos-packaged-x64 bootstrap-version
env:
RELEASE_NEEDS: ${{ toJSON(needs) }}
SKIP_BUNDLES: ${{ needs.admit.outputs.skip-bundles }}
SKIP_TESTS: ${{ needs.admit.outputs.skip-tests }}
publish-docker:
name: Publish tested Docker image
# B5: this job pushes only the immutable attempt-ref image tags; the
# stable/latest aliases move in the ordered publication pass.
needs: [admit, docker]
uses: ./.github/workflows/docker.yml
with:
release-phase: publish
tag: ${{ needs.admit.outputs.tag }}
version: ${{ needs.admit.outputs.version }}
publish-bundles:
name: Publish tested bundle artifacts
needs: [admit, acceptance, candidate-manifest]
if: needs.admit.outputs.skip-bundles != 'true'
permissions:
contents: write
actions: read
packages: write
id-token: write
uses: ./.github/workflows/desktop-bundled-release.yml
with:
tag: ${{ needs.admit.outputs.tag }}
claim-tag: ${{ needs.admit.outputs.claim-tag }}
claim-object: ${{ needs.admit.outputs.claim-object }}
release-phase: publish
manifest-sha256: ${{ needs.candidate-manifest.outputs.manifest-sha256 }}
publication:
name: All artifact publication succeeded
if: always()
needs: [admit, acceptance, publish-docker, publish-bundles]
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.sha }}
- uses: ./.github/actions/setup-pm
with:
cache-python: false
- run: python -m scripts.releases.stable gate acceptance publish-docker publish-bundles
env:
RELEASE_NEEDS: ${{ toJSON(needs) }}
SKIP_BUNDLES: ${{ needs.admit.outputs.skip-bundles }}
SKIP_TESTS: ${{ needs.admit.outputs.skip-tests }}
complete:
name: Stable release is green
if: always()
needs: [admit, ci, docker, acceptance, candidate-manifest, publication, publish-docker,
windows-packaged, macos-packaged-arm64, macos-packaged-x64]
runs-on: ubuntu-24.04
environment: release-signing
permissions:
contents: write
actions: read
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
ref: ${{ github.sha }}
fetch-depth: 0
- uses: ./.github/actions/setup-pm
with:
cache-python: false
- name: Set up the native identity reader
uses: ./.github/actions/setup-pm
with:
toolchain: node
cache-python: false
- run: python -m scripts.releases.stable gate admit ci docker acceptance candidate-manifest publication publish-docker
env:
RELEASE_NEEDS: ${{ toJSON(needs) }}
SKIP_BUNDLES: ${{ needs.admit.outputs.skip-bundles }}
SKIP_TESTS: ${{ needs.admit.outputs.skip-tests }}
- name: Validate the accepted candidate archive
if: needs.admit.outputs.skip-bundles != 'true'
run: python -m scripts.releases.stable complete
env:
RELEASE_TAG: ${{ needs.admit.outputs.tag }}
RELEASE_CLAIM_TAG: ${{ needs.admit.outputs.claim-tag }}
RELEASE_CLAIM_OBJECT: ${{ needs.admit.outputs.claim-object }}
CANDIDATE_MANIFEST_URL: ${{ needs.candidate-manifest.outputs.manifest-url }}
CANDIDATE_MANIFEST_SHA256: ${{ needs.candidate-manifest.outputs.manifest-sha256 }}
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 }}
- name: Render the admitted candidate smoke results
if: needs.admit.outputs.skip-bundles != 'true'
env:
GH_TOKEN: ${{ github.token }}
RELEASE_TAG: ${{ needs.admit.outputs.tag }}
RELEASE_COMMIT: ${{ needs.admit.outputs.commit }}
CANDIDATE_MANIFEST_SHA256: ${{ needs.candidate-manifest.outputs.manifest-sha256 }}
run: |
python scripts/render-builds-table.py --tag "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" \
--archive "$RELEASE_CLAIM_TAG" \
--candidate-manifest-sha256 "$CANDIDATE_MANIFEST_SHA256" --candidate-commit "$RELEASE_COMMIT"
- name: Set up Docker Buildx for ordered alias promotion
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3
- name: Log in to Docker Hub for ordered alias promotion
uses: docker/login-action@4907a6ddec9925e35a0a9e82d7399ccc52663121 # v4.1.0
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Reconcile ordered stable publication
run: python -m scripts.releases.sequencer
env:
GH_TOKEN: ${{ github.token }}
REQUESTED_VERSION: ''
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 }}
+159
View File
@@ -0,0 +1,159 @@
name: Termux verification
on:
push:
branches: [main]
paths:
- 'scripts/termux/**'
- 'pm/**'
- 'tests/scripts/test_termux*'
- '.github/workflows/termux-verify.yml'
pull_request:
paths:
- 'scripts/termux/**'
- 'pm/**'
- 'tests/scripts/test_termux*'
- '.github/workflows/termux-verify.yml'
workflow_dispatch:
workflow_call:
inputs:
release:
description: 'Stable-release candidate run (ignored by the jobs; uniform callable surface).'
required: false
type: boolean
default: false
permissions:
contents: read
actions: read
# A workflow_call run (stable release) is never cancelled: its group uses
# github.run_id so a parent rerun cannot kill this child mid-flight.
concurrency:
group: termux-verify-${{ inputs.release == true && github.run_id || github.ref }}
cancel-in-progress: ${{ inputs.release != true }}
jobs:
contracts:
name: Termux packaging contracts on Linux
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
# github.sha is the exact candidate commit on a stable tag-dispatched
# caller and the head SHA on every other event.
ref: ${{ github.sha }}
persist-credentials: false
- name: Install the native linker test prerequisite
run: |
sudo apt-get update
sudo apt-get install -y patchelf
- uses: ./.github/actions/setup-pm
with:
extras: '[]'
test-environment: 'true'
cache-python: false
- name: Run the native linker and wheel contracts
run: |
bash scripts/run_tests.sh -j 2 \
tests/scripts/test_termux_python_linkage.py tests/scripts/test_termux_retag_wheel.py \
tests/scripts/test_termux_build_wheels.py \
tests/scripts/test_termux_wheelhouse_cache.py tests/scripts/test_termux_runtime_libs.py \
tests/scripts/test_archive_inputs.py \
tests/scripts/test_termux_launchers.py tests/pm/test_pm_bionic.py \
tests/pm/test_stage_only.py tests/pm/test_deb_safety.py tests/scripts/test_stage_apt_repo.py \
tests/scripts/test_run_tests_shell.py
tui:
name: Prebuilt TUI checks
runs-on: ubuntu-24.04
timeout-minutes: 15
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
# github.sha is the exact candidate commit on a stable tag-dispatched
# caller and the head SHA on every other event.
ref: ${{ github.sha }}
persist-credentials: false
- uses: ./.github/actions/setup-pm
with:
toolchain: all
# tests-js generates real icons; the wrapper needs core Pillow/resvg.
extras: '[]'
cache-node: false
- name: Install the locked JS workspace
run: npm ci --workspace ui-tui --workspace tests-js --include-workspace-root --include=dev --no-fund --no-audit
- name: Check and bundle the TUI
run: |
npm run check --workspace tests-js
npm run check --workspace ui-tui
npm run build --workspace ui-tui
# A job-level `if` cannot read `secrets`, so the gate is a job that exports
# whether the release-signing environment is provisioned. Without R2 the
# bionic verification below cannot fetch its pinned inputs; skipping it
# keeps a fork or an unprovisioned main green instead of red.
r2-provisioned:
name: Detect R2 credentials
if: github.event_name != 'pull_request' && github.event_name != 'pull_request_target'
runs-on: ubuntu-24.04
environment: release-signing
timeout-minutes: 5
outputs:
configured: ${{ steps.check.outputs.configured }}
steps:
- id: check
env:
CLOUDFLARE_R2_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_R2_ACCOUNT_ID }}
run: |
echo "configured=${CLOUDFLARE_R2_ACCOUNT_ID:+true}" >> "$GITHUB_OUTPUT"
[ -n "$CLOUDFLARE_R2_ACCOUNT_ID" ] || echo "::notice::CLOUDFLARE_R2_* secrets are not configured; the bionic runtime verification is skipped."
native-runtime:
name: Verify bionic runtime tools
needs: r2-provisioned
# A stable-release candidate run still fails loudly on missing R2: the
# release must not pass on a skipped verification.
if: needs.r2-provisioned.outputs.configured == 'true' || inputs.release == true
runs-on: ubuntu-24.04-arm
environment: release-signing
timeout-minutes: 45
env:
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 }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
# github.sha is the exact candidate commit on a stable tag-dispatched
# caller and the head SHA on every other event.
ref: ${{ github.sha }}
persist-credentials: false
- uses: ./.github/actions/setup-pm
with:
archive-inputs: true
cache-python: false
- name: Preserve and retrieve pinned inputs
run: python -m scripts.ci.archive_inputs --target linux-arm64-bionic --payload termux-build/payload --store "$HERMES_RUNTIME_DIR"
- name: Stage the pinned bionic runtimes
run: |
bash scripts/termux/build_cpython.sh termux-build/payload
bash scripts/termux/build_uv.sh termux-build/payload
bash scripts/termux/termux_pkg_build.sh ffmpeg ffmpeg termux-build/payload
python3 scripts/termux/stage_runtime_libs.py termux-build/payload
- name: Verify ffmpeg on the bare bionic runtime
run: |
digest=$(python3 -c 'from pm.lock import termux_docker_digest; print(termux_docker_digest())')
docker run --rm --platform linux/arm64 --user 1000:1000 --network none \
-v "$PWD/termux-build/payload:/payload:ro" \
"termux/termux-docker@$digest" bash -c '
set -euo pipefail
export PREFIX=/data/data/com.termux/files/usr
export LD_LIBRARY_PATH="/payload/ffmpeg$PREFIX/lib:/payload/runtime-libs/lib:$PREFIX/lib"
"/payload/ffmpeg$PREFIX/bin/ffmpeg" -hide_banner \
-f lavfi -i anullsrc=r=16000:cl=mono -t 0.1 -f wav "$PREFIX/tmp/ffmpeg-proof.wav"
test -s "$PREFIX/tmp/ffmpeg-proof.wav"
printf "FFMPEG_BARE_RUNTIME_OK\n"
'
+84 -145
View File
@@ -11,19 +11,20 @@ name: OS-specific tests
# reproducing any of the OS behaviour that branch exists for. This workflow
# is where those markers actually execute:
#
# macos → ``-m macos_only`` on macos-latest
# windows → ``-m windows_only`` on windows-latest
# macos → ``-m platforms`` on macos-latest
# windows → ``-m platforms`` on windows-latest-32-core and windows-latest-32-arm-core
#
# (tests/conftest.py's ``pytest_collection_modifyitems`` hook skips
# foreign-OS ``platforms(...)`` markers on each host, so one shared ``-m
# platforms`` expression selects "this host's own marked tests" on either
# lane — the helper narrows WHICH FILES get imported first.)
#
# Deliberately NOT sliced. The marked set is small (tens of tests, not
# thousands), so one plain ``pytest`` process per OS is both faster and far
# less machinery than the per-file parallel runner the Linux lane uses.
# If either lane grows past its timeout, that is the signal to reach for
# scripts/run_tests.sh here too.
#
# Each lane FAILS when it selects zero tests (pytest exit code 5). Without
# that guard, a renamed marker or a bad selector would report a green job
# that ran nothing — the exact silent-coverage-loss failure this workflow
# exists to prevent.
# Each lane FAILS when it selects zero tests (pytest exit code 5) — a
# renamed marker or bad selector can never report a green job that ran
# nothing.
on:
workflow_call:
@@ -45,73 +46,66 @@ permissions:
contents: read
concurrency:
group: tests-os-${{ github.ref }}
cancel-in-progress: true
group: tests-os-${{ github.ref_type == 'tag' && github.run_id || github.ref }}
cancel-in-progress: ${{ github.ref_type != 'tag' }}
jobs:
os-tests:
name: ${{ matrix.name }}
runs-on: ${{ matrix.runner }}
timeout-minutes: 30
timeout-minutes: ${{ matrix.timeout || 30 }}
strategy:
fail-fast: false
matrix:
include:
- name: macOS-only tests
runner: macos-latest
marker: macos_only
marker: macos
- name: Windows-only tests
runner: windows-latest-32-core
marker: windows_only
marker: windows
- name: Windows-only tests (arm64)
runner: windows-latest-32-arm-core
marker: windows
timeout: 60
steps:
- name: Checkout code
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Install uv
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0
with:
# Pinned for the same reason as the Linux lane: unpinned, setup-uv
# resolves "latest" by fetching a manifest on every job and a
# transient fetch failure fails the whole job.
version: "0.9.28"
enable-cache: true
cache-dependency-glob: |
pyproject.toml
uv.lock
# No arm64 wheels for some of the extras below: PM builds them from sdist.
- name: Set up native ARM64 build dependencies
if: runner.os == 'Windows' && runner.arch == 'ARM64'
uses: ./.github/actions/setup-windows-build-deps
- name: Set up Python 3.11
uses: ./.github/actions/retry
- name: Set up locked Python and test dependencies
uses: ./.github/actions/setup-pm
with:
command: uv python install 3.11
- name: Install dependencies
# Same extras as the Linux test lane so an OS-marked test can import
# anything its Linux siblings can. ``[all]`` is deliberately
# Windows/macOS-installable (see the policy comment on the extra in
# pyproject.toml — matrix/python-olm was removed from it precisely
# because it could not build here).
uses: ./.github/actions/retry
with:
command: uv sync --locked --python 3.11 --extra all --extra dev --extra anthropic --extra mistral --extra fal --extra modal --extra daytona --extra parallel-web
- name: Minimize uv cache
run: uv cache prune --ci
# Installer stage tests inherit setup-pm's HERMES_RUNTIME_DIR. Prepare
# the verified Git pin once, before per-file parallelism; otherwise
# each isolated PowerShell stage races to download/extract the archive.
packages: ${{ matrix.marker == 'windows' && 'git,ripgrep' || 'ripgrep' }}
extras: '["all", "telegram", "anthropic", "mistral", "fal", "modal", "daytona", "hindsight", "parallel-web"]'
test-environment: 'true'
prune-python-cache: true
- name: Run ${{ matrix.marker }} tests
# Two-step selection:
# scripts/run_tests.sh — the canonical runner, same as every other
# lane: per-file subprocess isolation (run_tests_parallel.py). It
# natively tolerates per-file empty collections (a platform-gated
# file collects nothing after -m filtering, exit 5, treated as a
# pass for that file) and fails the run itself when NOTHING was
# collected across all files (exit 2) — the zero-tests guard the
# bare-pytest variant implemented by hand with an exit-5 branch.
#
# 1. scripts/ci/list_os_marked_tests.py narrows WHICH FILES are
# imported. ``-m`` filters after collection, and collection
# imports every module under tests/ — on this host that would
# drag ~900 unrelated test modules through import, where a
# single unrelated ImportError would fail a job whose own
# subject is fine. The helper exits non-zero if the marker
# matches no file at all.
# 2. ``-m`` decides WHICH TESTS run, and stays authoritative.
# Passing it on the command line REPLACES pyproject's
# ``-m 'not integration'`` addopts (same option, last wins) —
# hence repeating ``not integration``, or the integration
# suite would return through the side door.
# Selection still narrows WHICH FILES run:
# scripts/ci/list_os_marked_tests.py emits the file list (it exits
# non-zero when the marker matches no file at all); the list rides
# to the runner via ``--files`` so an unrelated ImportError fails
# only ITS file, red and visible, without poisoning the lane's
# other files. ``-m`` stays authoritative for which TESTS run —
# passed after ``--`` so the runner routes it to every per-file
# pytest invocation (the flag REPLACES pyproject's addopts, hence
# repeating ``not integration``).
#
# ``--timeout-method`` needs no override: tests/conftest.py's
# pytest_configure already downgrades the signal-based timer on
@@ -124,7 +118,7 @@ jobs:
# Process substitution would hide the helper's exit status, so write
# to a file and check it explicitly.
if ! uv run --no-sync python scripts/ci/list_os_marked_tests.py \
if ! python scripts/ci/list_os_marked_tests.py \
"${{ matrix.marker }}" > "$LIST"; then
echo "::error::could not enumerate ${{ matrix.marker }} test files"
exit 1
@@ -134,19 +128,9 @@ jobs:
exit 1
fi
# Deliberately NOT `mapfile`: that is a bash 4 builtin and the macOS
# runner's /bin/bash is 3.2. Word-splitting is safe here because the
# helper emits repo-relative test paths, which contain no spaces.
# shellcheck disable=SC2046
set -- $(cat "$LIST")
echo "selected $# file(s) for ${{ matrix.marker }}:"
echo "selected file(s) for ${{ matrix.marker }}:"
cat "$LIST"
# ``shell: bash`` runs this script with ``-e`` injected, which
# ``set -uo pipefail`` above does not clear. A bare pytest call
# would therefore abort the script on any non-zero exit and the
# exit-5 branch below would be unreachable dead code — the job
# would still fail red, but the diagnostic would never print.
# Desktop-update hand-off integration tests spawn the real
# windows.ps1; deselect them unless the PR touched that surface
# (see the workflow_call input). ``--ignore-glob`` keeps the file
@@ -160,34 +144,37 @@ jobs:
EXTRA_ARGS+=(--ignore-glob='*test_desktop_update_windows_*.py')
fi
status=0
uv run --no-sync python -m pytest \
"$@" \
# ``tr -d '\r'``: on Windows the helper's redirected stdout gains
# CRLF line endings; a stray \r would corrupt the path. The list
# uses the native path-list separator consumed by --files.
#
# Any non-zero exit propagates red: real test failures, or the
# runner's own zero-run guard (every file filtered to empty by
# ``-m`` — "must never pass without running its OS's tests").
SEPARATOR="$(python -c 'import os, sys; sys.stdout.write(os.pathsep)')"
FILES="$(tr -d '\r' < "$LIST" | paste -sd "$SEPARATOR" -)"
scripts/run_tests.sh --files "$FILES" -- \
${EXTRA_ARGS[@]+"${EXTRA_ARGS[@]}"} \
-m "${{ matrix.marker }} and not integration" \
-v --tb=short || status=$?
if [ "$status" -eq 5 ]; then
echo "::error::No tests matched -m ${{ matrix.marker }}. Either the" \
"marker was renamed/dropped or selection is broken — this job" \
"must never pass without running its OS's tests."
exit 1
fi
exit "$status"
-m "platforms and not integration" \
-v --tb=short
env:
# These files spawn nested PowerShell trees. CPU-count parallelism
# starves cold child startup before the fixture's idle deadline.
HERMES_TEST_WORKERS: ${{ matrix.marker == 'windows' && (runner.arch == 'ARM64' && '2' || '8') || '' }}
# Belt-and-suspenders with tests/conftest.py's env blanking: no
# test may reach a real provider API.
OPENROUTER_API_KEY: ""
OPENAI_API_KEY: ""
NOUS_API_KEY: ""
OPENROUTER_API_KEY: ''
OPENAI_API_KEY: ''
NOUS_API_KEY: ''
e2e-windows:
# Real Hermes processes on a real Windows host (tests/e2e/core/windows): hermes.exe,
# `hermes serve`, `hermes gateway run/stop`, the tui_gateway stdio process, cron script
# jobs, the terminal tool's Git Bash / PowerShell / cmd children and a ConPTY console,
# all against the loopback fake provider (tests/fakes/fake_llm_provider.py). Separate
# from os-tests above: those are unit-level windows_only tests, these spawn process
# from os-tests above: those are unit-level Windows tests, these spawn process
# trees per test. Every file there is also marked `integration`, so os-tests'
# `-m "windows_only and not integration"` never runs them a second time.
# `-m "platforms and not integration"` never runs them a second time.
#
# One pytest process per FILE, in parallel (same model as the Linux `e2e` job): the
# files spawn their own trees and must not share interpreter state. No retries: a
@@ -203,74 +190,26 @@ jobs:
- name: Checkout code
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Install uv
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0
- name: Set up locked Python and test dependencies
uses: ./.github/actions/setup-pm
with:
version: "0.9.28"
enable-cache: true
cache-dependency-glob: |
pyproject.toml
uv.lock
- name: Set up Python 3.11
uses: ./.github/actions/retry
with:
command: uv python install 3.11
- name: Install dependencies
# Same extras as os-tests: serve needs the web stack, the gateway the messaging
# imports, and the ConPTY case pywinpty (a core dependency on win32).
uses: ./.github/actions/retry
with:
command: uv sync --locked --python 3.11 --extra all --extra dev --extra anthropic --extra mistral --extra fal --extra modal --extra daytona --extra parallel-web
- name: Minimize uv cache
run: uv cache prune --ci
packages: git,ripgrep
extras: '["all", "telegram", "anthropic", "mistral", "fal", "modal", "daytona", "hindsight", "parallel-web"]'
test-environment: 'true'
prune-python-cache: true
- name: Run Windows E2E suite
shell: bash
run: |
set -uo pipefail
logs="${RUNNER_TEMP}/e2e-windows"
mkdir -p "$logs"
files=$(find tests/e2e/core/windows -name 'test_*.py' | sort)
if [ -z "$files" ]; then
echo "::error::no test files under tests/e2e/core/windows"
exit 1
fi
pids=()
names=()
start=$SECONDS
for f in $files; do
# `-m windows_only` replaces pyproject's `not integration` addopts selector.
timeout 900 .venv/Scripts/python.exe -m pytest "$f" -m windows_only \
-p no:cacheprovider -v --tb=short -rA > "$logs/$(basename "$f" .py).log" 2>&1 &
pids+=($!)
names+=("$f")
done
fail=0
for i in "${!pids[@]}"; do
rc=0
wait "${pids[$i]}" || rc=$?
f="${names[$i]}"
echo "::group::$f (rc=$rc)"
cat "$logs/$(basename "$f" .py).log"
echo "::endgroup::"
if [ "$rc" -eq 5 ]; then
echo "::error::$f selected zero tests (marker renamed or selection broken)"
fail=1
elif [ "$rc" -ne 0 ]; then
echo "::error::$f failed (rc=$rc)"
grep -E '^(FAILED|ERROR) ' "$logs/$(basename "$f" .py).log" || true
fail=1
fi
done
echo "Windows E2E wall: $((SECONDS - start)) s"
exit "$fail"
scripts/run_tests.sh tests/e2e/core/windows/ -- \
-m "platforms and integration" -v --tb=short -rA
env:
OPENROUTER_API_KEY: ""
OPENAI_API_KEY: ""
NOUS_API_KEY: ""
HERMES_TEST_WORKERS: '6'
HERMES_TEST_FILE_TIMEOUT: '900'
HERMES_TEST_FILE_RETRIES: '0'
OPENROUTER_API_KEY: ''
OPENAI_API_KEY: ''
NOUS_API_KEY: ''
- name: No leftover Python / Hermes processes
# Backstop for the per-test ownership checks: a file killed by its 900 s timeout,
+42 -116
View File
@@ -8,8 +8,8 @@ permissions:
# Cancel in-progress runs for the same ref
concurrency:
group: tests-${{ github.ref }}
cancel-in-progress: true
group: tests-${{ github.ref_type == 'tag' && github.run_id || github.ref }}
cancel-in-progress: ${{ github.ref_type != 'tag' }}
jobs:
test:
@@ -41,67 +41,21 @@ jobs:
rm -rf "$RG_TARBALL" "ripgrep-${RG_VERSION}-x86_64-unknown-linux-musl"
rg --version
- name: Install uv
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0
- name: Set up locked Python and test dependencies
uses: ./.github/actions/setup-pm
with:
# Pin the uv version: unpinned, setup-uv resolves "latest" by
# fetching a manifest from raw.githubusercontent.com on EVERY job —
# a transient fetch failure fails the whole job (2026-07-28 slice-5
# incident). Pinned, the binary downloads directly; no manifest hop.
#
# The uv pin also fixes which CPython `uv python install 3.11`
# resolves, and with it the linked SQLite. uv 0.9.28 resolved
# 3.11.14 / SQLite 3.50.4, which has the WAL-reset bug, so Hermes
# ran every state.db in DELETE mode here and the WAL path went
# untested. 0.12.13 resolves 3.11.16 / SQLite 3.53.1. The
# "Check SQLite runs WAL" step fails the job if a bump regresses it.
version: "0.12.13"
# Persist uv's download/wheel cache (~/.cache/uv) across runs.
# Keyed on the dependency manifests, so the cache is reused until
# pyproject.toml or uv.lock changes. `uv sync` still runs every
# time, but resolves from the warm cache instead of re-downloading
# and re-building wheels.
enable-cache: true
cache-dependency-glob: |
pyproject.toml
uv.lock
- name: Set up Python 3.11
uses: ./.github/actions/retry
with:
command: uv python install 3.11
- name: Install dependencies
# `uv sync --locked` installs the exact pinned set from uv.lock (and
# fails if the lock is out of sync with pyproject.toml), giving a
# reproducible env. It also creates .venv itself, so no separate
# `uv venv` step is needed.
#
# The trailing extras beyond all/dev are the lazy-install features
# (tools/lazy_deps.py) that tests exercise for real: provider.anthropic,
# stt/tts.mistral, image.fal, terminal.modal, terminal.daytona,
# search.parallel, provider.bedrock. The hermetic test env forbids
# mid-run pip installs (HERMES_DISABLE_LAZY_INSTALLS=1 in
# tests/conftest.py), so the SDKs those tests need must be in the
# venv up front — resolved from uv.lock like everything else, which
# also honors the exact supply-chain pins these extras carry.
uses: ./.github/actions/retry
with:
command: uv sync --locked --python 3.11 --extra all --extra dev --extra anthropic --extra mistral --extra fal --extra modal --extra daytona --extra parallel-web --extra bedrock
- name: Minimize uv cache
# Optimized for CI: prunes pre-built wheels that are cheap to
# re-download, keeping the persisted cache small and fast to restore.
run: uv cache prune --ci
extras: '["all", "anthropic", "bedrock", "mistral", "fal", "modal", "daytona", "hindsight", "parallel-web"]'
test-environment: 'true'
prune-python-cache: true
- name: Check SQLite runs WAL
# Hermes picks DELETE journal mode on a SQLite with the WAL-reset
# bug. If this interpreter links one, every WAL test silently runs
# DELETE (or skips), so fail loudly instead. Tests that need DELETE
# bug. If the PM-pinned interpreter links one, every WAL test silently
# runs DELETE (or skips), so fail loudly instead. Tests that need DELETE
# select it explicitly (journal_mode config, a pinned vulnerable
# version), so they run on any interpreter.
run: |
.venv/bin/python -c "import sqlite3, sys, hermes_state_wal as w; v = w.is_sqlite_wal_reset_vulnerable(); print(f'Python {sys.version.split()[0]}, SQLite {sqlite3.sqlite_version}, WAL-reset vulnerable: {v}'); sys.exit(1 if v else 0)"
"$HERMES_PYTHON" -c "import sqlite3, sys, hermes_state_wal as w; v = w.is_sqlite_wal_reset_vulnerable(); print(f'Python {sys.version.split()[0]}, SQLite {sqlite3.sqlite_version}, WAL-reset vulnerable: {v}'); sys.exit(1 if v else 0)"
- name: Restore per-file duration cache
# scripts/run_tests_parallel.py raises a file's timeout to
@@ -128,7 +82,6 @@ jobs:
# No --files: the runner discovers the suite itself. The discovered
# set is identical to the list the removed matrix job used to pass in.
run: |
source .venv/bin/activate
scripts/run_tests.sh
env:
# This is the maximum number of test FILES that run together.
@@ -152,6 +105,10 @@ jobs:
# size. The remaining time is the slowest files plus the setup.
# Workers above the core count only add contention.
HERMES_TEST_WORKERS: 96
# A healthy 44-test compression file takes ~197s alone and can exceed
# the 300s default under 96-worker load before its duration is cached.
# Match the runner's 3x known-slow headroom on the first PR run too.
HERMES_TEST_FILE_TIMEOUT: 600
# Ensure tests don't accidentally call real APIs
OPENROUTER_API_KEY: ""
OPENAI_API_KEY: ""
@@ -175,12 +132,20 @@ jobs:
- name: Checkout code
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Set up Node
# The boot-contract suite feeds serve's stdout through Desktop's own
# backend-ready.ts (native TS stripping needs Node >= 22.18).
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
- name: Set up locked Python, Node and test dependencies
# toolchain: all puts PM's locked Node in the runner's PM store, not
# only on PATH. The E2E sandboxes copy node from that store
# (tests/e2e/core/_pm_dependencies.py) and forbid lazy installs, and
# the dashboard's /api/pty resolves the TUI's node through PM only.
# A setup-node binary on PATH is invisible to PM, so every /api/pty
# chat refused to start. The locked Node also satisfies the
# boot-contract suite (backend-ready.ts needs Node >= 22.18).
uses: ./.github/actions/setup-pm
with:
node-version: 26
toolchain: all
extras: '["all", "anthropic", "bedrock", "mistral", "fal", "modal", "daytona", "hindsight", "parallel-web"]'
test-environment: 'true'
prune-python-cache: true
- name: Install Node deps and build the Ink TUI
# tests/e2e/core/terminal drives the real `hermes --tui` over a PTY;
@@ -203,58 +168,11 @@ jobs:
rm -rf "$RG_TARBALL" "ripgrep-${RG_VERSION}-x86_64-unknown-linux-musl"
rg --version
- name: Install uv
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0
with:
# Pin the uv version: unpinned, setup-uv resolves "latest" by
# fetching a manifest from raw.githubusercontent.com on EVERY job —
# a transient fetch failure fails the whole job (2026-07-28 slice-5
# incident). Pinned, the binary downloads directly; no manifest hop.
# Newer than the unit job's pin on purpose: 0.9.28 only knows CPython
# 3.11.14, whose bundled SQLite has the WAL-reset bug, so Hermes runs
# state.db in DELETE mode and the WAL torture chamber would skip.
version: "0.12.13"
# Persist uv's download/wheel cache (~/.cache/uv) across runs.
# Keyed on the dependency manifests, so the cache is reused until
# pyproject.toml or uv.lock changes. `uv sync` still runs every
# time, but resolves from the warm cache instead of re-downloading
# and re-building wheels.
enable-cache: true
# Own cache entry: the unit job's older uv would otherwise share and
# overwrite this key with a cache this uv version did not write.
cache-suffix: e2e
cache-dependency-glob: |
pyproject.toml
uv.lock
- name: Set up Python 3.11
run: uv python install 3.11.15
- name: Install dependencies
# `uv sync --locked` installs the exact pinned set from uv.lock (and
# fails if the lock is out of sync with pyproject.toml), giving a
# reproducible env. It also creates .venv itself, so no separate
# `uv venv` step is needed.
#
# Same extras as the test job's sync above: the hermetic test env
# forbids mid-run pip installs (HERMES_DISABLE_LAZY_INSTALLS=1 in
# tests/conftest.py), so lazy-install SDKs exercised by tests must be
# in the venv up front.
uses: ./.github/actions/retry
with:
command: uv sync --locked --python 3.11.15 --extra all --extra dev --extra anthropic --extra mistral --extra fal --extra modal --extra daytona --extra parallel-web --extra bedrock
- name: Minimize uv cache
# Optimized for CI: prunes pre-built wheels that are cheap to
# re-download, keeping the persisted cache small and fast to restore.
run: uv cache prune --ci
- name: Require a WAL-capable SQLite
# The state.db suites skip on a WAL-reset-vulnerable SQLite; fail
# instead of reporting green over zero coverage.
run: |
source .venv/bin/activate
python -c "import sqlite3, hermes_state_wal as w; print('sqlite', sqlite3.sqlite_version); assert not w.is_sqlite_wal_reset_vulnerable()"
"$HERMES_PYTHON" -c "import sqlite3, hermes_state_wal as w; print('sqlite', sqlite3.sqlite_version); assert not w.is_sqlite_wal_reset_vulnerable()"
- name: Run e2e tests
# One subprocess per file, in parallel: the core suites spawn real
@@ -262,10 +180,15 @@ jobs:
# and must not share interpreter state.
# tests/e2e/core/upgrade runs in its own job (e2e-upgrade) below.
run: |
source .venv/bin/activate
mapfile -t files < <(find tests/e2e -name 'test_*.py' -not -path 'tests/e2e/core/upgrade/*' | sort)
scripts/run_tests.sh --include-integration "${files[@]}"
scripts/run_tests.sh --include-integration tests/e2e
env:
# An e2e file is a process tree, not one CPU-bound pytest worker. With
# 32 files at once the hosted run starved live children before their
# ready frames (empty stderr, still alive) and hit 60–120s deadlines
# across unrelated SQLite, tenancy, provider and terminal suites.
# Bound the trees, not the child readiness/turn timeouts. At 4 the
# PTY turn and serve-SIGTERM deadlines still starved intermittently.
HERMES_TEST_WORKERS: "3"
# Multi-process episodes (torture chamber, compaction kill -9,
# gateway liveness, delivery exactly-once through a real gateway,
# the cron virtual-clock soak) legitimately run past the 300 s default.
@@ -335,8 +258,8 @@ jobs:
pyproject.toml
uv.lock
- name: Set up Python 3.11
run: uv python install 3.11.15
- name: Set up Python 3.14
run: uv python install 3.14
- name: Install dependencies
# `uv sync --locked` installs the exact pinned set from uv.lock (and
@@ -350,7 +273,7 @@ jobs:
# in the venv up front.
uses: ./.github/actions/retry
with:
command: uv sync --locked --python 3.11.15 --extra all --extra dev --extra anthropic --extra mistral --extra fal --extra modal --extra daytona --extra parallel-web
command: uv sync --locked --python 3.14 --extra all --group dev --extra anthropic --extra mistral --extra fal --extra modal --extra daytona --extra parallel-web
- name: Install bubblewrap
# Every spawned updater runs in bwrap (own PID namespace, no user
@@ -377,6 +300,9 @@ jobs:
source .venv/bin/activate
scripts/run_tests.sh --include-integration tests/e2e/core/upgrade
env:
# Each file drives real installs/updaters (process trees plus uv and
# git I/O); cpu_count of them at once starves their deadlines.
HERMES_TEST_WORKERS: "4"
HERMES_TEST_FILE_TIMEOUT: "3000"
OPENROUTER_API_KEY: ""
OPENAI_API_KEY: ""
+21 -24
View File
@@ -19,23 +19,23 @@ name: uv.lock check
# Failure mode this creates: if `main` has advanced since you branched
# (e.g. someone merged a PR that added a dep to pyproject.toml + its
# corresponding uv.lock entries), your branch's uv.lock is missing those
# new entries. `uv lock --check` resolves against the merged pyproject
# new entries. `python -m pm.build_env --source . --check-lock` resolves against the merged pyproject
# and sees a lockfile that doesn't cover all the current deps → fails
# with "The lockfile at uv.lock needs to be updated."
#
# This can be confusing: `uv lock --check` passes locally (your branch
# This can be confusing: `python -m pm.build_env --source . --check-lock` passes locally (your branch
# is internally consistent) but fails in CI (merged state isn't).
#
# Fix is to sync your branch with main and regenerate the lockfile:
#
# git fetch origin main
# git rebase origin/main # or merge, whatever the repo prefers
# uv lock # regenerates uv.lock against new pyproject.toml
# hermes pm lock # regenerates uv.lock against new pyproject.toml
# git add uv.lock
# git commit -m "chore: refresh uv.lock after rebase onto main"
# git push --force-with-lease # if you rebased
#
# If you also changed pyproject.toml in your PR, `uv lock` handles that
# If you also changed pyproject.toml in your PR, `hermes pm lock` handles that
# at the same time — one regeneration covers both your changes and the
# drift from main.
#
@@ -54,12 +54,12 @@ permissions:
contents: read
concurrency:
group: uv-lockfile-check-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
group: uv-lockfile-check-${{ github.ref_type == 'tag' && github.run_id || github.ref }}
cancel-in-progress: ${{ github.ref_type != 'tag' }}
jobs:
check:
name: uv lock --check
name: python -m pm.build_env --source . --check-lock
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
@@ -68,15 +68,12 @@ jobs:
- name: Checkout code
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Install uv
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0
- uses: ./.github/actions/setup-pm
with:
# Pinned: unpinned setup-uv fetches a 'latest' manifest from
# raw.githubusercontent.com every job; transient fetch failures
# fail the job (2026-07-28 incident). Keep in sync with tests.yml.
version: "0.9.28"
cache-python: true
prune-python-cache: true
# `uv lock --check` re-resolves the project from pyproject.toml and
# `python -m pm.build_env --source . --check-lock` re-resolves the project from pyproject.toml and
# compares the result to uv.lock, exiting non-zero if they disagree.
# No network writes, no file modifications.
#
@@ -86,7 +83,7 @@ jobs:
- name: Verify uv.lock is up-to-date
id: verify
run: |
# uv lock --check re-resolves against PyPI (network). Retry so a
# python -m pm.build_env --source . --check-lock re-resolves against PyPI (network). Retry so a
# registry blip doesn't read as "lockfile stale". A genuinely stale
# lockfile fails all attempts (deterministic), costing only seconds.
#
@@ -98,12 +95,12 @@ jobs:
# registry, versus "lockfile needs to be updated" when the lock is
# genuinely stale. Only the second is the contributor's to fix, so
# an unreachable registry says so instead of sending them to
# `uv lock` with nothing to regenerate.
# `hermes pm lock` with nothing to regenerate.
ok=false
net_fail=false
delays=(5 15 45)
for i in 1 2 3; do
if uv lock --check >lock-check.log 2>&1; then
if python -m pm.build_env --source . --check-lock >lock-check.log 2>&1; then
ok=true
net_fail=false
cat lock-check.log
@@ -119,12 +116,12 @@ jobs:
break
fi
[ "$i" = 3 ] && break
echo "::warning::uv lock --check could not reach the registry (attempt $i); retrying in ${delays[$((i-1))]}s"
echo "::warning::python -m pm.build_env --source . --check-lock could not reach the registry (attempt $i); retrying in ${delays[$((i-1))]}s"
sleep "${delays[$((i-1))]}"
done
if [ "$ok" != true ] && [ "$net_fail" = true ]; then
echo "::error title=uv.lock check could not reach PyPI::Registry unreachable after 3 attempts — infrastructure failure, not a stale lockfile. Re-run the job."
review_status='[{"source":"uv.lock check","results":[{"kind":"action_required","title":"uv.lock check could not reach PyPI","summary":"`uv lock --check` could not reach the package registry after 3 attempts. This is an infrastructure failure, not a stale lockfile.","how_to_fix":"Re-run the failed job. No change to `uv.lock` is needed."}]}]'
review_status='[{"source":"uv.lock check","results":[{"kind":"action_required","title":"uv.lock check could not reach PyPI","summary":"`python -m pm.build_env --source . --check-lock` could not reach the package registry after 3 attempts. This is an infrastructure failure, not a stale lockfile.","how_to_fix":"Re-run the failed job. No change to `uv.lock` is needed."}]}]'
echo "review_status=${review_status}" >> "$GITHUB_OUTPUT"
echo "review_status=${review_status}" > review-status.json
exit 1
@@ -135,7 +132,7 @@ jobs:
**If this is a PR:** this check runs against the merged state
(your branch + current `main`), not just your branch. If
`uv lock --check` passes locally, your branch is likely behind
`python -m pm.build_env --source . --check-lock` passes locally, your branch is likely behind
`main` — recent changes to `pyproject.toml` on `main` aren't
reflected in your branch's `uv.lock` yet.
@@ -144,13 +141,13 @@ jobs:
```bash
git fetch origin main
git rebase origin/main # or `git merge origin/main`
uv lock # regenerate against new pyproject.toml
hermes pm lock # regenerate against new pyproject.toml
git add uv.lock
git commit -m "chore: refresh uv.lock after syncing with main"
git push --force-with-lease # drop --force-with-lease if you merged
```
**If you only changed pyproject.toml:** run `uv lock` locally
**If you only changed pyproject.toml:** run `hermes pm lock` locally
and commit the result.
This check is blocking because the Docker image build uses
@@ -158,8 +155,8 @@ jobs:
— catching it here avoids a ~15 min failed docker run
on `main` post-merge.
EOF
echo "::error title=uv.lock out of sync::Run \`uv lock\` locally and commit the result. If on a PR, sync with main first."
review_status='[{"source":"uv.lock check","results":[{"kind":"action_required","title":"uv.lock out of sync","summary":"uv.lock is out of sync with pyproject.toml.","how_to_fix":"Run `uv lock` locally and commit the result. If on a PR, sync with main first:\n```\ngit fetch origin main\ngit rebase origin/main\nuv lock\ngit add uv.lock\ngit commit -m \"chore: refresh uv.lock\"\n```\n"}]}]'
echo "::error title=uv.lock out of sync::Run \`hermes pm lock\` locally and commit the result. If on a PR, sync with main first."
review_status='[{"source":"uv.lock check","results":[{"kind":"action_required","title":"uv.lock out of sync","summary":"uv.lock is out of sync with pyproject.toml.","how_to_fix":"Run `hermes pm lock` locally and commit the result. If on a PR, sync with main first:\n```\ngit fetch origin main\ngit rebase origin/main\nhermes pm lock\ngit add uv.lock\ngit commit -m \"chore: refresh uv.lock\"\n```\n"}]}]'
echo "review_status=${review_status}" >> "$GITHUB_OUTPUT"
echo "review_status=${review_status}" > review-status.json
exit 1
+47
View File
@@ -0,0 +1,47 @@
name: Windows bundle SDK
# The desktop signing adapter downloads and executes the pinned Windows SDK
# tools. The vitest halves under js-tests run on Linux and skip every
# runIf(win32) leg, so this is the only lane that runs the real downloader.
on:
pull_request:
paths:
- 'apps/desktop/scripts/windows-bundle-tools.mjs'
- 'apps/desktop/scripts/windows-bundle-tools.test.mjs'
- 'scripts/msix-shared.mjs'
- 'apps/desktop/scripts/msix-shared.test.mjs'
- 'apps/desktop/scripts/sign-msix.mjs'
- 'apps/desktop/scripts/sign-msix.test.mjs'
- 'apps/desktop/scripts/batch-sign-binaries.mjs'
- 'apps/desktop/scripts/batch-sign-binaries.test.mjs'
- '.github/workflows/windows-bundle-sdk.yml'
workflow_dispatch:
permissions:
contents: read
concurrency:
group: windows-bundle-sdk-${{ github.ref }}
cancel-in-progress: true
jobs:
windows-bundle-tools:
name: Cold Windows SDK (${{ matrix.runner }})
runs-on: ${{ matrix.runner }}
# Cold ARM64 npm extraction alone can exceed 15 minutes on the hosted runner.
timeout-minutes: 45
strategy:
fail-fast: false
matrix:
runner: [windows-latest-32-arm-core, windows-latest-32-arm-core]
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- uses: ./.github/actions/setup-pm
with:
toolchain: all
cache: false
cache-python: false
cache-node: false
- name: Install the locked bundle tooling without native postinstalls
run: npm ci --workspace apps/desktop --workspace tests-js --include-workspace-root --include=dev --ignore-scripts --no-audit --no-fund
- name: Provision from an empty cache and execute the SDK
working-directory: apps/desktop
run: node ../../node_modules/vitest/vitest.mjs run --project electron scripts/windows-bundle-tools.test.mjs scripts/msix-shared.test.mjs scripts/sign-msix.test.mjs scripts/batch-sign-binaries.test.mjs
+31 -29
View File
@@ -15,66 +15,68 @@ name: Windows venv-holder live E2E
on:
push:
branches:
- "wine2e/**"
- 'wine2e/**'
workflow_call:
inputs:
release:
description: 'Stable-release candidate run. Unused by the jobs; the caller passes it for a uniform callable surface.'
required: false
type: boolean
default: false
permissions:
contents: read
# A workflow_call run (stable release) shares the caller's commit; its group
# includes github.run_id so a rerun of the parent gets a fresh group instead
# of cancelling this child mid-flight. wine2e push runs keep ref-scoped
# collapse as before.
concurrency:
group: windows-venv-e2e-${{ github.ref }}
cancel-in-progress: true
group: windows-venv-e2e-${{ inputs.release == true && github.run_id || github.ref }}
cancel-in-progress: ${{ inputs.release != true }}
jobs:
venv-holder-e2e:
name: venv-holder live E2E (windows-latest)
runs-on: windows-latest
runs-on: windows-latest-32-core
timeout-minutes: 25
steps:
- name: Checkout code
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
- name: Install uv
uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0
with:
version: "0.9.28"
enable-cache: true
cache-dependency-glob: |
pyproject.toml
uv.lock
# The stable caller dispatches on the candidate tag; github.sha is
# the exact candidate commit there and the head SHA everywhere else.
ref: ${{ github.sha }}
- name: Set up Python 3.11
uses: ./.github/actions/retry
- name: Set up locked Python and test dependencies
uses: ./.github/actions/setup-pm
with:
command: uv python install 3.11
- name: Install dependencies
uses: ./.github/actions/retry
with:
command: uv sync --locked --python 3.11 --extra dev --extra messaging
extras: '["messaging"]'
test-environment: 'true'
prune-python-cache: true
- name: Run venv-holder live E2E
# Canonical runner (scripts/run_tests.sh) — never bare pytest: it
# enforces credential hygiene, TZ, temp HERMES_HOME and subprocess
# isolation. The live files are host-marked windows-only, so the
# runner collects them on this runner instead of skipping them.
shell: bash
run: |
set -uo pipefail
uv run --no-sync python -m pytest \
bash scripts/run_tests.sh \
tests/hermes_cli/test_venv_holder_windows_live.py \
tests/hermes_cli/test_taskkill_identity_windows_live.py \
tests/hermes_cli/test_git_trampoline_windows_live.py \
tests/hermes_cli/test_managed_uv_windows_cutover.py \
-o addopts= -v -p no:cacheprovider
tests/hermes_cli/test_runtime_repair.py::TestWindowsRuntimeSelfLock
- name: Run Telegram CLOSE-WAIT reconnect live E2E (#87057)
shell: bash
run: |
set -uo pipefail
uv run --no-sync python -m pytest \
tests/gateway/test_telegram_closewait_windows_live.py \
-o addopts= -v -p no:cacheprovider
bash scripts/run_tests.sh tests/gateway/test_telegram_closewait_windows_live.py
- name: Run background-executor spawn parity live E2E (#70716)
shell: bash
run: |
set -uo pipefail
uv run --no-sync python -m pytest \
tests/tools/test_process_registry_windows_live.py \
-o addopts= -v -p no:cacheprovider
bash scripts/run_tests.sh tests/tools/test_process_registry_windows_live.py
+43
View File
@@ -7,6 +7,8 @@
/_pycache/
*.pyc*
__pycache__/
# Generated by the release into the build tree; a checkout never carries one.
hermes_cli/_version.py
act/
.act-sandbox-agent.*
.venv/
@@ -95,6 +97,9 @@ apps/desktop/dist/
apps/desktop/src/**/*.js
apps/desktop/src/**/*.js.map
apps/desktop/src/**/*.d.ts
apps/desktop/electron/**/*.js
apps/desktop/electron/**/*.js.map
apps/desktop/electron/**/*.d.ts
# EXCEPT bundled plain-ESM plugin entries (adopted SDK-consumer plugins,
# e.g. hermes-bots): plugin.js IS the source, not tsc output. No .tsx
# sibling exists, so the stale-shadow hazard above cannot apply.
@@ -267,6 +272,7 @@ docs/superpowers/*
# Runtime metadata only — never a code change. Ignore so `git status` stays clean
# and `hermes update`'s untracked autostash does not treat it as a local edit (#66189 / #54855).
/.install_method
install-stamp.json
# Tool Search live-test harness output — non-deterministic model transcripts,
# regenerated by evals/tool_search/tool_search_livetest*.py. Never an artifact of the repo.
@@ -304,3 +310,40 @@ native/fts5_cjk/*.so
# Disposable profile created by scripts/probe_active_session_exclusivity.py
.probe-home/
# Bundle/build scratch roots (scripts/bundles/, scripts/build/frontend-common.mjs)
.build/
.cache/
# PM lockfile advisory lock; kept in place so waiting writers share its inode
/pm/.lock.json.lock
# Generated icon assets (scripts/generate_icons.py). Regenerated on demand by
# every consuming pipeline; sources of truth: assets/nous-girl-*.svg + assets/backgrounds/.
assets/icon-master.svg
assets/icon-master-dark.svg
apps/desktop/assets/icon.png
apps/desktop/assets/icon.ico
apps/desktop/assets/icon.icns
apps/desktop/assets/icon-dark.png
apps/desktop/assets/icon-dark.ico
apps/desktop/assets/icon-dark.icns
apps/desktop/assets/appx/*.png
apps/desktop/public/apple-touch-icon.png
apps/desktop/public/nous-girl.png
apps/desktop/public/nous-girl-dark.png
apps/desktop/.dist-build*
apps/bootstrap-installer/src-tauri/icons/*.png
apps/bootstrap-installer/src-tauri/icons/icon.ico
apps/bootstrap-installer/src-tauri/icons/icon.icns
apps/bootstrap-installer/public/nous-girl.png
website/static/img/logo.png
website/static/img/logo-dark.png
website/static/img/nous-logo.png
website/static/img/nous-logo-dark.png
website/static/img/favicon-16x16.png
website/static/img/favicon-32x32.png
website/static/img/apple-touch-icon.png
website/static/img/favicon.ico
website/static/img/favicon.svg
web/public/favicon.ico
+1 -1
View File
@@ -1 +1 @@
3.11
3.14
+84 -21
View File
@@ -177,8 +177,13 @@ session-scoped. Assert the GUI session gets the tool **with the env var absent**
## Development Environment
```bash
source .venv/bin/activate # or: source venv/bin/activate
source ./activate # provisions/syncs PM tools + dependencies, then activates
```
Select an isolated development `HERMES_HOME` and `HERMES_RUNTIME_DIR` first;
see `website/docs/reference/package-management.md#developer-workflow`.
PowerShell: `. .\activate.ps1`. `deactivate` restores the prior environment.
For tests, use the independent test environment in `CONTRIBUTING.md` (or Nix);
PM activation's `PYTHONPATH` does not survive the test runner's environment scrub.
`scripts/run_tests.sh` probes `.venv`, then `venv`, then `$HOME/.hermes/hermes-agent/venv`
(worktrees sharing the main checkout's venv).
@@ -320,13 +325,22 @@ Table-driven beats condition ladders for ids/routes/views. `src/app` owns routes
All dependencies carry upper bounds (litellm compromise #2796/#2810; Mini Shai-Hulud worm,
May 2026). PyPI: `>=floor,<next_major` (`"httpx>=0.28.1,<1"`); pre-1.0: `<0.(minor+2)`
(`>=0.29,<0.32`). Git URLs: 40-char commit SHA. GitHub Actions: SHA + `# vN` comment. CI-only
pip: `==exact`. A bare `>=X.Y.Z` is rejected by CI and reviewers. Run `uv lock` after
changing `pyproject.toml`. Reference: #2810 (bounds), #9801 (SHA pinning + audit CI).
Python requirements: `==exact`. A bare `>=X.Y.Z` is rejected by CI and reviewers.
After changing `pyproject.toml`, run `hermes pm lock`, re-source `./activate`, and commit
`pyproject.toml` with `uv.lock`. Reference: #2810 (bounds), #9801 (SHA pinning + audit CI).
PM owns Hermes Python dependency changes. Use `pm.sync_venv(['extra'], explicit=True)`
for declared runtime extras, `hermes pm install` for setup/sync, and `hermes pm repair`
for damaged dependencies. Do not mutate Hermes environments with raw pip or uv.
Use `pm.build_environment` for fresh build outputs and `pm.ensure_environment` for
isolated tool environments. Callers receive an interpreter or tool path, not uv.
Nix's declarative uv2nix builds and unrelated user projects remain independently owned.
The `[tool.uv] exclude-newer = "14 days"` quarantine covers **Hermes's own dependencies only**
(`uv lock`/`sync`, `hermes update`, `tools.lazy_deps.ensure` extras — `install policy "core"`).
Plugin `python_dependencies` install under the plugin's own policy (`install_specs(policy="plugin")`
→ `uv --no-config`, still inside the core constraints file); Teknium's ruling: "plugins dont have to
(every registry package in core's `uv.lock`). Plugin `python_dependencies` follow the plugin's own
policy: when PM generates the plugin workspace (`pm/workspace.py::_core_release_quarantine`) the
global cutoff moves onto each core-locked package, so plugin-only packages are not filtered and a
plugin still cannot drag a core package past the window. Teknium's ruling: "plugins dont have to
abide by our 14 day rule … Only hermes' dependencies themselves have to." We recommend (not require)
plugin authors adopt their own quarantine — the developer guide and `plugin-catalog/README.md` carry
that guidance.
@@ -350,6 +364,17 @@ isolation via `scripts/run_tests_parallel.py` (no xdist; workers scale with CPU
module-level dicts/ContextVars cannot leak between files. Direct `pytest` on a big machine
with API keys set has caused repeated "works locally, fails in CI" incidents (and the reverse).
Prepare a test interpreter with the checkout's bootstrapped Python:
```bash
python -m pm.build_env --source . --out .venv --group dev --group test
```
This is a fresh build, not an in-place sync. If the disposable output exists,
stop its processes and intentionally remove it before regeneration. The runner
clears `PYTHONPATH`, so PM shell activation alone does not supply pytest. For a
fresh output outside the checkout, set `HERMES_PYTHON` to its interpreter.
```bash
scripts/run_tests.sh # full suite
scripts/run_tests.sh tests/gateway/ # one directory
@@ -388,8 +413,8 @@ scripts/run_tests.sh -v --tb=long # pytest flags pass thro
### Don't fake the host OS
Behaviour that genuinely differs per host is tested ON that host with `@pytest.mark.linux_only`
/ `macos_only` / `windows_only`, never by patching `sys.platform`. Host-independent things stay
Behaviour that genuinely differs per host is tested ON that host with `@pytest.mark.platforms("linux")`
/ `platforms("macos")` / `platforms("windows")`, never by patching `sys.platform`. Host-independent things stay
unmarked: pure functions that take the platform as data (`hidden_windows_child_options(opts,
is_windows=True)`) and declaration/packaging invariants ("pyproject declares `tzdata` with a
`sys_platform == 'win32'` marker"). Setting a module-level `IS_WINDOWS` flag and calling
@@ -397,20 +422,58 @@ is_windows=True)`) and declaration/packaging invariants ("pyproject declares `tz
is on another OS to pass, it belongs on that OS.** A test that walks several platforms in
sequence is split — host-native arm on Linux, other arms as their own marked tests.
**Use the marker, never a bare `skipif`.** `scripts/ci/list_os_marked_tests.py` finds files for
the macOS/Windows lanes by grepping the marker *name*, then filters with `-m <marker>`. A
`skipif(sys.platform != "win32")` test skips on Linux AND is never imported on Windows — it runs
nowhere, silently. A file-local alias (`windows_only = pytest.mark.skipif(...)`) is listed but
`-m windows_only` deselects everything: green over zero coverage. Don't `pytest.skip()` non-host
rows of a platform `@parametrize` — split into one marked test per OS.
One marker per test, with any number of spec strings (any-of semantics) plus
optional arch filters. To gate on several OSes, pass several specs to ONE
marker — never stack several `platforms()` decorators on one test (the
conftest rejects that at collection):
**Live Windows process-topology E2E (`wine2e` lane):** `windows-venv-e2e.yml` runs
`tests/hermes_cli/test_venv_holder_windows_live.py` on a real `windows-latest` runner (real
processes, no mocked psutil) ONLY on pushes to `wine2e/**` branches. Workflow: write probes
pinning CORRECT behavior, push to `wine2e/` to reproduce live on unfixed code, fix, iterate to
green, then open the PR with the live receipt. Extend it when touching that subsystem; assert
against the gateway ANCESTOR found by argv, not the direct parent (the venv shim makes every
spawn a launcher/worker chain).
```python
@pytest.mark.platforms("linux", "macos") # ONE marker, two specs: runs on either
def test_posix_signal_path(): ...
```
Other single-marker forms (each is a complete marker on its own):
`platforms("windows")` (native Windows only), `platforms("not macos")`
(anywhere except macOS), `platforms("windows", arch="arm64")` (native Windows
on arm64), `platforms("posix")` (Linux or macOS).
Specs: `linux`, `macos`, `windows`, `posix`, `any`, and `not <spec>`.
The historic `linux_only` / `macos_only` / `windows_only` markers have been
fully replaced — `platforms` is the only host-gating marker in the tree.
**Live Windows process-topology E2E: the `wine2e` lane.** For claims about
real Windows process behavior that mocks cannot reproduce (venv-holder
scans, process-tree parentage, launcher/worker chains, detach semantics),
there is an on-demand workflow `windows-venv-e2e.yml` that runs
`tests/hermes_cli/test_venv_holder_windows_live.py` on a real
`windows-latest` runner — spawning actual processes and driving the real
detection code, no mocked psutil. It fires ONLY on pushes to `wine2e/**`
branches (inert on PRs and main; costs nothing on normal work). The proven
workflow: write probes that pin CORRECT behavior, push to a `wine2e/`
branch to reproduce the bugs live on unfixed code, build the fix, iterate
until the lane is green, then open the PR — the live receipt on the exact
head is the Windows proof reviewers ask for. Extend the live suite when
touching that subsystem; assert against the gateway ANCESTOR found by
argv, not the direct parent (the venv shim makes every spawn a
launcher/worker chain).
**Use the marker, never a bare `skipif`.** `scripts/ci/list_os_marked_tests.py`
decides which files an OS lane imports by resolving the quoted specs inside
`platforms(...)` (`"posix"` reaches the macOS lane, `"not linux"` reaches
both others), and the lane then selects with `-m platforms` while the
conftest's per-test host skips do the actual gating. A test gated with
`@pytest.mark.skipif(sys.platform != "win32")` therefore runs on no host at
all, silently — it is never imported by the lane that would run it, and the
full-suite lanes skip it. `skipif(sys.platform == "win32")` becomes
`platforms("posix")`; a non-host condition (`os.geteuid() == 0`) stays a
separate `skipif` beside the marker. A misspelt spec is a collection error,
not a skip. Don't stack a module-level `pytestmark =
platforms(...)` on a file whose tests carry their own host marker — the
conftest hard-rejects tests carrying two `platforms()` markers (a test
skipped on every host, reported green everywhere).
Equally, don't `pytest.skip()` the non-host rows of a `@parametrize` over
platforms — split it into one marked test per OS, or only the host's row ever
executes.
### Don't write change-detector tests
-1
View File
@@ -2953,7 +2953,6 @@ to the public equivalent or the new module. Test monkeypatch seams are likewise
| `shutil` | import | `shutil` |
| `signal` | import | `signal` |
| `timezone` | import | `datetime` |
| `warm_agent_browser_npx_cache` | moved-lazy | `tools.browser_tool_install` |
| `windows_hide_flags` | moved-lazy | `hermes_cli._subprocess_compat` |
### `tools.clarify_gateway`
+31 -46
View File
@@ -51,7 +51,7 @@ Si tu habilidad es especializada, contribuida por la comunidad o de nicho, es me
## Proveedores de Memoria: Publicar como Plugin Independiente
**Ya no aceptamos nuevos proveedores de memoria en este repositorio.** El conjunto de proveedores integrados en `plugins/memory/` (honcho, mem0, supermemory, byterover, holographic, openviking, retaindb) está cerrado. Si quieres añadir un nuevo backend de memoria, publícalo como un **repositorio de plugin independiente** que los usuarios instalen en `~/.hermes/plugins/` (o a través de un entry point de pip).
**Ya no aceptamos nuevos proveedores de memoria en este repositorio.** El conjunto de proveedores integrados en `plugins/memory/` (honcho, mem0, supermemory, byterover, hindsight, holographic, openviking, retaindb) está cerrado. Si quieres añadir un nuevo backend de memoria, publícalo como un **repositorio de plugin independiente** que los usuarios instalen en `~/.hermes/plugins/` (o a través de un entry point de pip).
Los plugins de memoria independientes:
@@ -69,65 +69,50 @@ Esto no es una barra de calidad — es una decisión de acoplamiento y mantenimi
## Configuración del Desarrollo
### Prerequisitos
### Preparar el entorno
| Requisito | Notas |
|-----------|-------|
| **Git** | Con la extensión `git-lfs` instalada |
| **Python 3.11–3.13** | uv lo instalará si falta |
| **uv** | Gestor de paquetes Python rápido ([instalar](https://docs.astral.sh/uv/)) |
| **Node.js 20+** | Opcional — necesario para herramientas de navegador y puente WhatsApp (coincide con los engines de `package.json` raíz) |
Se requieren Git y git-lfs. PM proporciona Python 3.14 (`>=3.14,<3.15`) y las herramientas fijadas.
Sigue el [flujo de desarrollo de PM](website/docs/reference/package-management.md#developer-workflow).
Selecciona un `HERMES_HOME` de desarrollo antes de preparar el checkout.
### Clonar e instalar
En Bash, desde la raíz del repositorio:
```bash
git clone https://github.com/NousResearch/hermes-agent.git
cd hermes-agent
# Crear venv con Python 3.11
uv venv venv --python 3.11
export VIRTUAL_ENV="$(pwd)/venv"
# Instalar con todos los extras (mensajería, cron, menús CLI, herramientas de desarrollo)
uv pip install -e ".[all,dev]"
# Opcional: herramientas de navegador
npm install
source ./activate
hermes --version
```
### Configurar para desarrollo
En PowerShell:
```powershell
. .\activate.ps1
hermes --version
```
### Entorno independiente de pruebas
Usa el Python preparado por PM para crear un entorno nuevo:
```bash
mkdir -p ~/.hermes/{cron,sessions,logs,memories,skills}
cp cli-config.yaml.example ~/.hermes/config.yaml
touch ~/.hermes/.env
# Añadir al menos una clave de proveedor LLM:
echo "OPENROUTER_API_KEY=***" >> ~/.hermes/.env
python -m pm.build_env --source . --out .venv --group dev --group test
scripts/run_tests.sh tests/agent/ -v
```
### Ejecutar
La ruta de salida no debe existir. Para regenerarla, detén sus procesos y elimina
explícitamente solo ese entorno desechable. PM no elimina destinos existentes.
No modifiques los entornos de Hermes con comandos directos de pip o uv.
En Windows, ejecuta el script de pruebas mediante Bash.
Si cambias `pyproject.toml`, regenera el lock, vuelve a cargar la activación y
confirma `pyproject.toml` junto con `uv.lock`:
```bash
# Enlace simbólico para acceso global
mkdir -p ~/.local/bin
ln -sf "$(pwd)/venv/bin/hermes" ~/.local/bin/hermes
# Verificar
hermes doctor
hermes chat -q "Hola"
hermes pm lock
source ./activate
```
### Ejecutar tests
```bash
# Preferido — coincide con CI (entorno hermético, 4 workers xdist); ver AGENTS.md
scripts/run_tests.sh
# Alternativa (activa el venv primero). El wrapper sigue recomendándose
# para paridad con GitHub Actions antes de abrir un PR:
pytest tests/ -v
```
Para JavaScript, ejecuta `npm ci` en el workspace correspondiente. Consulta
[CONTRIBUTING.md](CONTRIBUTING.md) para los requisitos completos.
---
+97 -86
View File
@@ -109,107 +109,114 @@ A well-built third-party-product plugin can clear automated review and still be
| Requirement | Notes |
|-------------|-------|
| **Git** | With the `git-lfs` extension installed |
| **Python 3.11–3.13** | uv will install it if missing |
| **uv** | Fast Python package manager ([install](https://docs.astral.sh/uv/)) |
| **Node.js 20+** | Optional — needed for browser tools and WhatsApp bridge (matches root `package.json` engines) |
| **Python 3.14** | The project requires `>=3.14,<3.15`; PM provides the pinned interpreter |
| **Node.js** | Use the PM pin, or a version accepted by root `package.json`: `^22.22.0`, `^24.11.0`, or `>=26.0.0` |
### Install with the standard installer
### PM developer environment
For most contributors, the best development bootstrap is the same path users
take: run the standard installer, then work inside the repository it cloned.
The installer creates the Hermes venv, wires the `hermes` command, stamps the
install method for `hermes update`, and clones the full git project into
`$HERMES_HOME/hermes-agent` (usually `~/.hermes/hermes-agent`). That keeps your
development environment on the same layout the CLI, updater, lazy dependency
installer, gateway, and docs assume.
Use the [PM developer workflow](website/docs/reference/package-management.md#developer-workflow) for preparation, activation, everyday commands,
dependency changes, and test environments. Select your development
home before setup so experimental code does not migrate production data.
Activate from the repository root in each new shell. Activation runs setup's
runtime-only path, so it provisions a fresh checkout and syncs stale dependencies.
Bash:
```bash
curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash
cd "${HERMES_HOME:-$HOME/.hermes}/hermes-agent"
# Add dev/test extras on top of the standard install.
uv pip install -e ".[all,dev]"
# Optional: docs site + workspace dependencies.
npm install
source ./activate
hermes --version
```
After that, create branches and run tests from that checkout:
PowerShell:
```powershell
. .\activate.ps1
hermes --version
```
Run `hermes` for this checkout. Activation defines it as a function for this
worktree, so it hides a global `hermes` command or MSIX alias and refuses
outside the worktree. PM activation
syncs tools and Python dependencies before adding them to the shell. It does not
install JS workspaces or rewrite launchers and shell configuration. `deactivate`
restores the prior shell environment and removes the function.
### Manual development and test environment
Use the [PM developer workflow](website/docs/reference/package-management.md#developer-workflow) to prepare Python 3.14 (`>=3.14,<3.15`) first.
Run these commands from that checkout with its prepared Python. Keep the same
development `HERMES_HOME`. PM must be able to start before it can build another
environment. On Windows, initialize the native C++ build environment for your
architecture before building source dependencies.
Build an independent interpreter for tests and editor tools:
```bash
git checkout -b fix/description
scripts/run_tests.sh
python -m pm.build_env --source . --out .venv --group dev --group test
```
### Manual clone fallback
PM builds from the committed lock and checks dependency consistency before
returning the new interpreter. The `test` group includes native launcher test
dependencies and does not enter the application runtime. If tests require
another declared feature, add its `--extra`.
Use this only if you intentionally do not want Hermes' managed install layout
(for example, a throwaway clone inside a container or CI job). If you install
this way, make sure you run the `hermes` entrypoint from this venv; running the
system `python3 -m hermes_cli.main` can pick up unrelated system Python
packages.
The output must not exist, even as an empty directory or symlink. To regenerate
it after a dependency change, stop its processes and intentionally remove only
that disposable environment first. PM does not delete an existing destination.
Do not run raw pip or uv commands to change a PM-built environment.
Create the venv **outside** the cloned source tree. A venv that lives inside
the directory the agent operates from can be wiped by a relative-path command
the agent runs against its own checkout (`rm -rf venv`, `uv venv venv`, etc.),
which silently destroys the running runtime mid-session. Keeping it outside the
tree means no relative path from the workspace resolves to it.
To keep the test environment outside the checkout, replace `.venv` with a fresh absolute
path. Set `HERMES_PYTHON` to that environment's interpreter:
- POSIX: `export HERMES_PYTHON="/absolute/path/to/hermes-dev/bin/python"`
- PowerShell: `$env:HERMES_PYTHON = 'C:\absolute\path\to\hermes-dev\Scripts\python.exe'`
The canonical runner discovers repository `.venv` automatically. It clears
`PYTHONPATH`, so pytest must be installed in the interpreter's own environment.
This test environment does not replace PM's application selection or tool
store. Do not point a bundled app at it or install into an MSIX payload.
For an isolated development instance, select a disposable `HERMES_HOME` before
starting the source command. Use `hermes setup` to configure it rather
than copying production credentials into the checkout.
### JavaScript workspaces and website
From the repository root, run `npm ci` for the desktop, TUI, dashboard, and
shared JS workspaces. The website is separate:
```bash
git clone https://github.com/NousResearch/hermes-agent.git
cd hermes-agent
# Create venv with Python 3.11, OUTSIDE the source tree
uv venv ~/.hermes/venvs/hermes-dev --python 3.11
export VIRTUAL_ENV="$HOME/.hermes/venvs/hermes-dev"
export PATH="$VIRTUAL_ENV/bin:$PATH"
# Install with all extras (messaging, cron, CLI menus, dev tools)
uv pip install -e ".[all,dev]"
# Optional: workspace / docs dependencies
npm install
npm ci --prefix website
npm run build:fast --prefix website
```
### Configure for development
Use a Node/npm version accepted by the corresponding `package.json` engines.
Native desktop dependencies can also require the platform build toolchain.
```bash
mkdir -p ~/.hermes/{cron,sessions,logs,memories,skills}
cp cli-config.yaml.example ~/.hermes/config.yaml
touch ~/.hermes/.env
# Add at minimum an LLM provider key:
echo "OPENROUTER_API_KEY=***" >> ~/.hermes/.env
```
### Run
```bash
# The standard installer already put `hermes` on PATH.
hermes doctor
hermes chat -q "Hello"
```
If you used the manual clone fallback, run `./hermes` from the checkout or
symlink this clone's venv explicitly:
```bash
mkdir -p ~/.local/bin
ln -sf "$(pwd)/venv/bin/hermes" ~/.local/bin/hermes
```
Logos and icons are generated from `assets/nous-girl-*.svg` and
`assets/backgrounds/`. `node scripts/generate-icons.mjs` renders them with the
Hermes runtime Python (`HERMES_PYTHON`, else `python` on PATH): Pillow and
resvg-py are core dependencies. Do not commit generated PNG/ICO/ICNS outputs.
### Run tests
```bash
# Preferred — matches CI (hermetic `env -i`, per-file subprocess isolation
# via run_tests_parallel.py, worker count auto-scaled); see AGENTS.md
scripts/run_tests.sh
Use the canonical runner on every host:
# Alternative (activate the venv first). The wrapper is still recommended
# for parity with GitHub Actions before you open a PR:
pytest tests/ -v
```bash
scripts/run_tests.sh
scripts/run_tests.sh tests/agent/ -v
```
On Windows, run the script through Bash. When no local `.venv` or `venv`
contains pytest, the runner accepts the explicit `HERMES_PYTHON` above. It
clears credentials, isolates `HERMES_HOME`, and runs each test file in a separate
subprocess through `scripts/run_tests_parallel.py`. It does not use xdist.
Run the relevant JS workspace checks for JS changes. Native install/update
E2E runs on disposable CI hosts, never against the developer's live app.
See [Package management](website/docs/reference/package-management.md) for PM commands and runtime ownership.
---
## Project Structure
@@ -718,7 +725,7 @@ that touches the OS, assume *any* platform can hit your code path.
```
If you specifically need the hermes wrapper (it has a stdlib fallback
for scaffold-phase imports before pip install finishes), use
for scaffold-phase imports before PM finishes dependency preparation), use
`gateway.status._pid_exists(pid)`. It calls `psutil.pid_exists` first
and falls back to a hand-rolled `OpenProcess + WaitForSingleObject`
dance on Windows only when psutil is somehow missing.
@@ -847,15 +854,19 @@ that touches the OS, assume *any* platform can hit your code path.
### Testing cross-platform
Tests that excercise behavior on specific platforms must run on their target platforms.
Tests of host-specific behavior must run on that host. Apply one `platforms`
marker to each test, rather than changing `sys.platform`:
```python
@pytest.mark.linux_only
@pytest.mark.macos_only
@pytest.mark.windows_only
@pytest.mark.platforms("windows", arch="arm64")
def test_native_windows_arm64_behavior():
...
```
Avoid monkeypatching `sys.platform` unless absolutely needed, but if you do, also patch `platform.system()` / `platform.release()` / `platform.mac_ver()`.
Symlinks, 0o600 permissions, SIGALRM, os.setsid/fork are all unix-only.
For several supported hosts, use one marker with multiple arguments, such as
`@pytest.mark.platforms("linux", "macos")`. Do not stack host markers.
Tests of pure functions that accept a platform as data need no host marker.
See [AGENTS.md](AGENTS.md#dont-fake-the-host-os) for the complete contract.
---
@@ -942,7 +953,7 @@ refactor/description # Code restructuring
### Before submitting
1. **Run tests**: `scripts/run_tests.sh` (recommended; same as CI) or `pytest tests/ -v` with the project venv activated
1. **Run tests**: use `scripts/run_tests.sh` for the same environment and per-file isolation as CI.
2. **Test manually**: Run `hermes` and exercise the code path you changed
3. **Check cross-platform impact**: If you touch file I/O, process management, or terminal handling, consider macOS, Linux, and WSL2
4. **Keep PRs focused**: One logical change per PR. Don't mix a bug fix with a refactor with a new feature.
+195 -173
View File
@@ -2,7 +2,9 @@
# corruption bug. Build a pinned shared library for the runtime image instead
# of relying on a distro backport that trixie does not currently provide.
# See #70480 and https://sqlite.org/wal.html#walresetbug.
FROM debian:13.4 AS sqlite_build
# Pinned by the multi-arch index digest: uv and node already come from pm's
# sha-verified lock, and a tag alone would let the base drift under them.
FROM debian:13.4@sha256:e2d08da6f42ef4b09b165d55528a12727aeed8240dc9edf888e3ec07e10ef9da AS sqlite_build
ARG SQLITE_AUTOCONF_VERSION=3530400
ARG SQLITE_SHA256=0e9483900e92cd5de8fd48d16bf9200145a61f7fd5be542a5ac81d8a9516eb9c
RUN apt-get -o Acquire::Retries=3 update && \
@@ -40,16 +42,8 @@ RUN apt-get -o Acquire::Retries=3 update && \
make -j"$(nproc)" && \
make install
FROM ghcr.io/astral-sh/uv:0.11.6-python3.13-trixie@sha256:b3c543b6c4f23a5f2df22866bd7857e5d304b67a564f4feab6ac22044dde719b AS uv_source
# Node 26 source stage. Debian trixie's bundled nodejs is pinned to 20.x
# which reached EOL in April 2026 — we copy node + npm from the upstream
# node:26 image instead (Hermes pins its toolchain to Node 26 everywhere).
# Bookworm-based slim image used so the produced binary links
# against glibc 2.36, which runs cleanly on our Debian 13 (trixie, glibc
# 2.41) runtime. Bumping to a new Node major is a one-line ARG change; see
# #4977.
FROM node:26-bookworm-slim@sha256:9e6f9357d371591e32ab6f2d8a26d63bdd0d17c29eee3f4f3e7e454d9634bf73 AS node_source
FROM debian:13.4
# Same digest as sqlite_build: the built libsqlite must match this libc.
FROM debian:13.4@sha256:e2d08da6f42ef4b09b165d55528a12727aeed8240dc9edf888e3ec07e10ef9da AS runtime_base
# Disable Python stdout buffering to ensure logs are printed immediately.
# Do not write .pyc files at runtime: /opt/hermes is immutable in the
@@ -57,9 +51,14 @@ FROM debian:13.4
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
# Store Playwright browsers outside the volume mount so the build-time
# install survives the /opt/data volume overlay at runtime.
ENV PLAYWRIGHT_BROWSERS_PATH=/opt/hermes/.playwright
# The pm-pinned full Chromium lives in the managed tool store at
# /opt/hermes/tools — outside the /opt/data volume mount, so the
# build-time install survives the volume overlay at runtime. pm's
# chromium package fact exports the same value (PLAYWRIGHT_BROWSERS_PATH
# at the store root); the image ENV names the same directory so
# Playwright and the browser tool resolve the pinned build even before pm
# composes tool env.
ENV PLAYWRIGHT_BROWSERS_PATH=/opt/hermes/tools
# Install system dependencies in one layer, clear APT cache.
# tini was previously PID 1 to reap orphaned zombie processes (MCP stdio
@@ -68,14 +67,22 @@ ENV PLAYWRIGHT_BROWSERS_PATH=/opt/hermes/.playwright
# replaces tini with s6-overlay's /init (PID 1 = s6-svscan), which reaps
# zombies non-blockingly on SIGCHLD and additionally supervises the main
# hermes process, the dashboard, and per-profile gateways.
# The second package list is the shared libraries the pinned Chromium links
# against. `npx playwright install --with-deps` used to apt-install them as
# a side effect; pm stages the pinned browser instead (below), so the libs
# must be declared here. The list is the `ldd ... | grep "not found"` set of
# the pinned chrome binary in this base image, mapped to trixie package
# names (see .hermes/plans/termux-removal-commit-spec.md).
RUN apt-get -o Acquire::Retries=3 update && \
apt-get -o Acquire::Retries=3 install -y --no-install-recommends \
ca-certificates curl iputils-ping python3 python-is-python3 ripgrep ffmpeg gcc g++ make cmake python3-dev python3-venv libffi-dev libolm-dev libatomic1 procps git openssh-client docker-cli xz-utils && \
ca-certificates curl iputils-ping python3 python-is-python3 gcc g++ make cmake python3-dev python3-venv libffi-dev libolm-dev libatomic1 procps git openssh-client docker-cli xz-utils \
libasound2t64 libatk-bridge2.0-0t64 libatk1.0-0t64 libatspi2.0-0t64 libcairo2 libcups2t64 libdbus-1-3 libgbm1 libglib2.0-0t64 libnspr4 libnss3 libpango-1.0-0 libx11-6 libxcb1 libxcomposite1 libxdamage1 libxext6 libxfixes3 libxkbcommon0 libxrandr2 && \
rm -rf /var/lib/apt/lists/*
# Bot Screen (opt-in): PACKAGES["apt"] from tools/bot_desktop/runtime.py plus apt
# `chromium` for the dock's Browser icon. ~930 MB apt on debian:13.4 (~1.4 GB of
# image once the gated headed Chromium below is counted); nothing starts
# `chromium` for the restricted-userns sandbox fallback. PM already stages
# pinned full Chromium for both variants; no separate Playwright install.
# Nothing starts
# at boot. docker.yml builds both variants and publishes these packages under
# the `-desktop` tags: hosted sandboxes pull a prebuilt image and never run a
# build, and cannot apt at run time either (unprivileged, no sudo). Only this
@@ -167,71 +174,151 @@ COPY --chmod=0755 docker/tini-shim.sh /usr/bin/tini
# Non-root user for runtime; UID can be overridden via HERMES_UID at runtime
RUN useradd -u 10000 -m -d /opt/data hermes
COPY --chmod=0755 --from=uv_source /usr/local/bin/uv /usr/local/bin/uvx /usr/local/bin/
# Node 26: copy the node binary plus the bundled npm JS install from the
# upstream image. npm and npx are recreated as symlinks because they're
# symlinks in the source image (and need to live on PATH).
#
# No corepack: Node unbundled it upstream, so node:26 ships only npm in
# /usr/local/lib/node_modules. Nothing here needs it — no package.json
# declares a `packageManager`, and no build step shells out to yarn or pnpm.
#
# See node_source stage at the top of the file for the version-bump
# rationale (#4977).
COPY --chmod=0755 --from=node_source /usr/local/bin/node /usr/local/bin/
COPY --from=node_source /usr/local/lib/node_modules/npm /usr/local/lib/node_modules/npm
RUN ln -sf /usr/local/lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm && \
ln -sf /usr/local/lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx
WORKDIR /opt/hermes
# ---------- Layer-cached dependency install ----------
# Copy only package manifests first so npm install + Playwright are cached
# unless the lockfiles themselves change.
# ---------- Pinned toolchain from pm/lock.json (single authority) ----------
# The image used to assemble uv from a second authority — an astral image
# tag (ghcr.io/astral-sh/uv:0.11.6-python3.13-trixie) that had already
# drifted to 0.11.6 while pm/lock.json pinned uv 0.12.3. That is exactly
# the two-authorities failure the pm design exists to end. The image is now
# a pin consumer: the stdlib-only pm provisioner reads pm/lock.json and
# stages the pinned uv + full Chromium (sha256-verified at
# download — the same code path pm.sh/pm.ps1 and the desktop payload use)
# into the image's own runtime dir, a self-contained store baked under
# /opt/hermes, outside the /opt/data volume so it survives the overlay.
# PM alone resolves the pinned uv for dependency preparation; build consumers
# receive Python environments, never an installer executable.
#
# ui-tui/packages/hermes-ink/ is copied IN FULL (not just its manifests)
# because it is referenced as a `file:` workspace dependency from
# ui-tui/package.json. Copying the tree up front lets npm resolve the
# workspace to real content instead of stopping at a bare package.json.
# Full Chromium supports both headed and headless sessions. It is staged
# here rather than by `npx playwright install`,
# which fetched whatever revision the npm-resolved playwright wanted,
# unverified, and recorded no fact. The resolved browser binary path is
# baked to /etc/hermes/agent-browser-executable-path for stage2-hook.sh:
# the layout differs per arch (chrome-linux64/chrome on amd64,
# chromium-linux-arm64/chromium on arm64), so it is resolved at build time
# and never hunted at boot.
ENV HERMES_RUNTIME_DIR=/opt/hermes/tools
COPY pm/ pm/
# pm's lazy imports resolve get_default_hermes_root()/project_venv_dir()
# from hermes_constants (stdlib-only) at install time — a sealed-stage
# `python3 -m pm.cli install` fails with "No module named
# 'hermes_constants'" without it on the path. Copy the module next to pm.
COPY hermes_constants.py hermes_constants.py
# PM imports the shared stdlib locking owner before deps exist.
COPY hermes_cli/__init__.py hermes_cli/runtime_state.py hermes_cli/
COPY scripts/bundles/payload.py scripts/bundles/payload.py
RUN set -eu; \
python3 -c 'from pm import ensure; [ensure(name, explicit=True) for name in ("uv", "chromium", "npm", "ffmpeg", "ripgrep")]'; \
python3 -c 'from pathlib import Path; from pm import installed_package; [Path("/usr/local/bin", command).symlink_to(installed_package(package).binary) for command, package in (("python3", "python"), ("node", "node"), ("npm", "npm"), ("ffmpeg", "ffmpeg"), ("rg", "ripgrep"))]; Path("/usr/local/bin/ffprobe").symlink_to(installed_package("ffmpeg").binary.with_name("ffprobe"))'; \
ffmpeg -version >/dev/null; ffprobe -version >/dev/null; rg --version >/dev/null; \
python3 -c 'import shutil; from pathlib import Path; from pm import env_for; Path("/usr/local/bin/npx").symlink_to(shutil.which("npx", path=env_for("npm", base_env={})["PATH"]))'; \
node --version; npm --version; \
browser_bin="$(python3 -c 'from pm import installed_package; print(installed_package("chromium").binary)')"; \
test -n "$browser_bin"; \
"$browser_bin" --version; \
mkdir -p /etc/hermes; \
printf '%s' "$browser_bin" > /etc/hermes/agent-browser-executable-path
# PM is resident too: never borrow application libraries or create its worker
# environment under /root (unreachable to the runtime UID).
RUN python3 -c 'from pathlib import Path; from pm import stage_manager_runtime; from scripts.bundles.payload import seal_pm_runtime; root = Path("/opt/hermes"); python = Path("/usr/local/bin/python3").resolve(); stage_manager_runtime(python=python, destination=root / "pm-runtime", project=root / "pm"); seal_pm_runtime(root, python)'
# JS build helpers use the prepared interpreter without an installer parent.
ENV HERMES_PYTHON=/usr/local/bin/python3
# The standalone interpreter records its builder's clang toolchain;
# native extensions must use the compiler installed in this image.
ENV CC=gcc CXX=g++
FROM runtime_base AS python_deps
# ---------- Layer-cached Python dependency install ----------
# Copy only pyproject.toml + uv.lock so the Python dep resolve + wheel
# download + native-extension compile layer is cached unless those inputs
# change. Before this split the Python install sat after `COPY . .`, so
# every source-only commit re-did ~4-5 min of dep work on cold builds.
#
# README.md is referenced by pyproject.toml's `readme =` field, but it's
# excluded from the build context by .dockerignore's `*.md`. uv's build
# frontend stats the readme path during dep resolution, so we `touch` an
# empty placeholder — the real README is restored by `COPY . .` below.
#
# `pm.build_env --no-install-project --extra all --extra messaging --extra otlp`
# installs the deps reachable through the composite `[all]` extra
# (handpicked set intended for the production image; dependency groups are not selected),
# plus gateway messaging adapters that should work in the published image
# without a first-boot lazy install. We do NOT use `--all-extras`:
# that would pull in `[rl]` (atroposlib + tinker + torch + wandb from
# git) and `[yc-bench]` (another git dep), neither of which belongs in
# the published container.
#
# Provider packages (anthropic, bedrock, azure-identity) are included
# so Docker users can use these providers without requiring runtime
# lazy-install access to PyPI (often blocked in containerized envs).
#
# The [otlp] extra contains the SDK/exporter imported by Hermes when Gateway
# Health export is enabled. Collector and observability-backend dependencies
# remain external and are not part of the Hermes production image.
#
# The hindsight memory provider's client (hindsight-client) is baked in
# for the same reason: it lazy-installs into /opt/hermes/.venv at first
# use, which lives inside the (immutable) image layer rather than the
# mounted /opt/data volume, so it is lost on every container recreate /
# image update and recall/retain then fails with
# `ModuleNotFoundError: No module named 'hindsight_client'` (#38128).
#
# The Matrix gateway's deps ([matrix] extra) are baked in because
# python-olm (transitive via mautrix[encryption]) builds from source on
# Python/image combinations without usable wheels. The Docker image is
# Linux-only, so keeping the native libolm/build-toolchain packages here
# avoids the cross-platform failures that kept [matrix] out of [all]
# while still making Matrix work in the published container. Fixes #30399.
#
# Google Chat's [google-chat] extra (google-cloud-pubsub + Chat API clients)
# is baked so hosted/immutable images can enable the adapter without writing
# the sealed venv.
#
# Source binding is created after the source copy below.
COPY pyproject.toml uv.lock ./
RUN touch ./README.md
RUN python3 -m pm.build_env --source /opt/hermes --python /usr/local/bin/python3 \
--out /opt/hermes/.venv --no-install-project --sealed \
--extra all --extra messaging --extra otlp --extra anthropic --extra bedrock \
--extra azure-identity --extra hindsight --extra matrix --extra google-chat
# Icons render on the runtime environment: Pillow and resvg-py are core
# dependencies. A stage of its own so the frontend stage keeps building its
# Node dependencies in parallel with the Python ones.
FROM python_deps AS icons
COPY scripts/generate_icons.py scripts/
COPY assets/ assets/
RUN /opt/hermes/.venv/bin/python -I scripts/generate_icons.py --source /opt/hermes --out /tmp/hermes-icons
# Frontend dependencies never enter the runtime layers.
FROM runtime_base AS frontend_build
COPY package.json package-lock.json ./
COPY web/package.json web/
COPY ui-tui/package.json ui-tui/
COPY ui-tui/packages/hermes-ink/ ui-tui/packages/hermes-ink/
# apps/shared/ is copied IN FULL because web/package.json references it as a
# `file:` workspace dependency (same pattern as hermes-ink above).
COPY apps/shared/ apps/shared/
# `npm_config_install_links=false` forces npm to install `file:` deps as
# symlinks instead of copies. This is the default since npm 10+, which is
# what the image ships now (via the node:22 source stage). We set it
# explicitly anyway as defense-in-depth: the previous Debian-bundled npm
# 9.x defaulted to install-as-copy, which produced a hidden
# node_modules/.package-lock.json that permanently disagreed with the root
# lock on the @hermes/ink entry, tripped the TUI launcher's
# `_tui_need_npm_install()` check on every startup, and triggered a
# runtime `npm install` that then failed with EACCES. Keeping the env
# guards against a future regression if the source npm version changes.
COPY scripts/build/node-deps.mjs scripts/build/node-deps.mjs
ENV npm_config_install_links=false
RUN node scripts/build/node-deps.mjs --source /opt/hermes --workspace ui-tui --workspace web
# chrome-headless-shell: what the browser tool has always driven headlessly.
# Smaller, no window code paths. --with-deps pulls the shared system libraries.
RUN npm install --prefer-offline --no-audit --fetch-retries=5 && \
for i in 1 2 3; do \
npx playwright install --with-deps chromium --only-shell && break || \
{ [ "$i" = 3 ] && exit 1; echo "playwright headless-shell install failed (attempt $i); retrying in 10s"; sleep 10; }; \
done && \
npm cache clean --force
COPY pyproject.toml uv.lock ./
COPY web/ web/
COPY ui-tui/ ui-tui/
COPY scripts/build/*.mjs scripts/build/
COPY scripts/generate-icons.mjs scripts/generate_icons.py scripts/
COPY assets/ assets/
COPY --from=icons /tmp/hermes-icons /tmp/hermes-icons
RUN node scripts/build/tui.mjs --source /opt/hermes --out /opt/products/tui && \
node scripts/build/web.mjs --source /opt/hermes --icons /tmp/hermes-icons --out /opt/products/web
# chrome-headless-shell cannot open a window, so the dock's Browser icon needs the
# full build. Same Chromium family as the shell, so agent and human share one
# --user-data-dir. Gated: a build with no desktop has nothing to show it on.
RUN if [ "$HERMES_BOT_DESKTOP" = "1" ]; then \
for i in 1 2 3; do \
npx playwright install chromium && break || \
{ [ "$i" = 3 ] && exit 1; echo "playwright chromium install failed (attempt $i); retrying in 10s"; sleep 10; }; \
done; \
fi
FROM python_deps AS runtime
# Standalone TypeScript linting is a runtime feature; Vite/esbuild are not.
COPY --from=frontend_build /opt/hermes/node_modules/typescript /opt/hermes/node_modules/typescript
RUN mkdir -p /opt/hermes/node_modules/.bin && \
ln -s ../typescript/bin/tsc /opt/hermes/node_modules/.bin/tsc
# ---------- Photon iMessage sidecar deps (baked, NS-606) ----------
# The photon plugin's Node sidecar needs its own node_modules
@@ -249,65 +336,9 @@ RUN cd plugins/platforms/photon/sidecar && \
npm ci --no-audit --fetch-retries=5 && \
npm cache clean --force
# ---------- Layer-cached Python dependency install ----------
# Copy only pyproject.toml + uv.lock so the Python dep resolve + wheel
# download + native-extension compile layer is cached unless those inputs
# change. Before this split the Python install sat after `COPY . .`, so
# every source-only commit re-did ~4-5 min of dep work on cold builds.
#
# README.md is referenced by pyproject.toml's `readme =` field, but it's
# excluded from the build context by .dockerignore's `*.md`. uv's build
# frontend stats the readme path during dep resolution, so we `touch` an
# empty placeholder — the real README is restored by `COPY . .` below.
#
# `uv sync --frozen --no-install-project --extra all --extra messaging --extra otlp`
# installs the deps reachable through the composite `[all]` extra
# (handpicked set intended for the production image — excludes `[dev]`),
# plus gateway messaging adapters that should work in the published image
# without a first-boot lazy install. We do NOT use `--all-extras`:
# that would pull in `[rl]` (atroposlib + tinker + torch + wandb from
# git), `[yc-bench]` (another git dep), and `[termux-all]` (Android
# redundancy), none of which belong in the published container.
#
# Provider packages (anthropic, bedrock, azure-identity) are included
# so Docker users can use these providers without requiring runtime
# lazy-install access to PyPI (often blocked in containerized envs).
#
# The [otlp] extra contains the SDK/exporter imported by Hermes when Gateway
# Health export is enabled. Collector and observability-backend dependencies
# remain external and are not part of the Hermes production image.
#
# Catalog memory plugins (e.g. hindsight, since it left the tree) are not
# baked in: their pip dependencies install at plugin-install time through
# tools/lazy_deps.py into HERMES_LAZY_INSTALL_TARGET (the durable /opt/data
# volume, see below), so they survive container recreates (#38128).
#
# The Matrix gateway's deps ([matrix] extra) are baked in because
# python-olm (transitive via mautrix[encryption]) builds from source on
# Python/image combinations without usable wheels. The Docker image is
# Linux-only, so keeping the native libolm/build-toolchain packages here
# avoids the cross-platform failures that kept [matrix] out of [all]
# while still making Matrix work in the published container. Fixes #30399.
#
# Google Chat's [google-chat] extra (google-cloud-pubsub + Chat API clients)
# is baked so hosted/immutable images can enable the adapter without writing
# the sealed venv. Runtime --install-deps still routes through lazy_deps into
# HERMES_LAZY_INSTALL_TARGET when the extra is not present.
#
# The editable link is created after the source copy below.
COPY pyproject.toml uv.lock ./
RUN touch ./README.md
RUN uv sync --frozen --no-install-project --extra all --extra messaging --extra otlp --extra anthropic --extra bedrock --extra azure-identity --extra matrix --extra google-chat
# ---------- Frontend build (cached independently from Python source) ----------
# Copy only the frontend source trees first so that Python-only changes don't
# invalidate the (relatively slow) web + ui-tui build layer.
COPY web/ web/
COPY ui-tui/ ui-tui/
COPY apps/shared/ apps/shared/
RUN cd web && npm run build && \
cd ../ui-tui && npm run build
# Shared product outputs are independent of application dependency assembly.
COPY --from=frontend_build /opt/products/tui /opt/hermes/ui-tui
COPY --from=frontend_build /opt/products/web /opt/hermes/hermes_cli/web_dist
# ---------- Bot Screen X socket directory ----------
# Xvnc would create this itself (/tmp is 1777); pre-creating it keeps ownership
# deterministic when HERMES_UID is remapped between boots.
@@ -327,14 +358,11 @@ RUN mkdir -p /tmp/hermes-runtime && chmod 0700 /tmp/hermes-runtime
# write so the build steps below don't need chmod u+w dances.
COPY --link --chmod=a+rX,go-w . .
# ---------- Permissions ----------
# Link hermes-agent itself (editable). Deps are already installed in the
# cached layer above; `--no-deps` makes this a fast egg-link creation with no
# resolution or downloads.
RUN uv pip install --no-cache-dir --no-deps -e "."
# The shared assembler binds the prepared environment and frontend products.
RUN /opt/hermes/.venv/bin/python -m docker.build_agent
# Wire the exec shim and install-method stamp. Files under /opt/hermes are
# already root-owned (COPY, uv sync, npm install all run as root) and
# already root-owned (COPY, dep assembly, npm install all run as root) and
# read-only for the hermes user (go-w from the --chmod above).
USER root
@@ -353,35 +381,34 @@ RUN mkdir -p /opt/hermes/bin && \
# `s6-setuidgid hermes` in its run script. If HERMES_UID is unset, services
# run as the default hermes user (UID 10000).
# ---------- Bake image provenance + build-time git revision ----------
# ---------- Image provenance + install stamp ----------
# CI (.github/workflows/docker.yml) runs scripts/write_install_stamp.py
# before `docker build`, so the bulk `COPY . .` above already placed a
# full-provenance /opt/hermes/install-stamp.json next to the code.
# .dockerignore excludes .git, so the stamp is the only commit channel the
# image carries: hermes_cli/version_info.py reads it at runtime (stamp
# first, live git second, unknown third), and both `hermes dump` and
# banner.get_git_banner_state() consume it through version_info.
#
# A local `docker build` without CI gets the minimal all-zero fallback
# stamp below; version_info skips the placeholder commit, so dump honestly
# reports "(unknown)". updateMechanism is `external`: the image is rebuilt
# and re-pulled, it never updates itself.
#
# The versioned, non-secret provenance marker is the authoritative runtime
# signal that this filesystem came from an immutable image. It deliberately
# lives outside both /opt/hermes (which operators sometimes bind-mount as a
# checkout) and /opt/data (the mutable HERMES_HOME volume).
# .dockerignore excludes .git, so `git rev-parse HEAD` from inside the
# container always returns nothing — meaning `hermes dump` reports
# "(unknown)" and the startup banner drops its `· upstream <sha>` suffix.
# That makes support triage from container bug reports impossible:
# we can't tell which commit the user is actually running.
#
# Fix: write the commit SHA passed via the HERMES_GIT_SHA build-arg to
# /opt/hermes/.hermes_build_sha at build time, and have
# hermes_cli/build_info.py read it at runtime. Both `hermes dump` and
# banner.get_git_banner_state() try the baked SHA first, then fall back
# to live `git rev-parse` for source installs (unchanged behaviour).
#
# The arg is optional — local `docker build` without --build-arg omits the
# SHA file (and records a null provenance revision), so build-info falls back
# to live-git lookup. CI
# (.github/workflows/docker.yml) passes ${{ github.sha }} so
# every published image has it.
ARG HERMES_GIT_SHA=
# checkout) and /opt/data (the mutable HERMES_HOME volume). Its `revision`
# is read from the install stamp; the fallback stamp's all-zero commit maps
# to null.
RUN set -eu; \
if [ -n "${HERMES_GIT_SHA}" ]; then \
printf '%s\n' "${HERMES_GIT_SHA}" > /opt/hermes/.hermes_build_sha; \
if [ ! -f /opt/hermes/install-stamp.json ]; then \
printf '{"schemaVersion":2,"commit":"0000000000000000000000000000000000000000","distribution":"docker","source":"fallback","updateMechanism":"external"}\n' \
> /opt/hermes/install-stamp.json; \
fi; \
python3 -c 'import json; from pathlib import Path; path = Path("/opt/hermes/install-stamp.json"); stamp = json.loads(path.read_text()); stamp["pmRuntime"] = "/opt/hermes/pm-runtime"; path.write_text(json.dumps(stamp) + "\n")'; \
mkdir -p /etc/hermes; \
HERMES_GIT_SHA="${HERMES_GIT_SHA}" python3 -c 'import json, os, pathlib, tomllib; project = tomllib.loads(pathlib.Path("/opt/hermes/pyproject.toml").read_text(encoding="utf-8"))["project"]; marker = pathlib.Path("/etc/hermes/image-provenance.json"); marker.write_text(json.dumps({"schema": 1, "deployment_kind": "image", "manager": "docker", "image": "nousresearch/hermes-agent", "version": project["version"], "revision": os.environ.get("HERMES_GIT_SHA") or None}, sort_keys=True, separators=(",", ":")) + "\n", encoding="utf-8"); marker.chmod(0o444)'
python3 -c 'import json, pathlib, tomllib; project = tomllib.loads(pathlib.Path("/opt/hermes/pyproject.toml").read_text(encoding="utf-8"))["project"]; stamp = json.loads(pathlib.Path("/opt/hermes/install-stamp.json").read_text(encoding="utf-8")); commit = stamp.get("commit"); revision = commit if commit and set(commit) != {"0"} else None; marker = pathlib.Path("/etc/hermes/image-provenance.json"); marker.write_text(json.dumps({"schema": 1, "deployment_kind": "image", "manager": "docker", "image": "nousresearch/hermes-agent", "version": project["version"], "revision": revision}, sort_keys=True, separators=(",", ":")) + "\n", encoding="utf-8"); marker.chmod(0o444)'
# ---------- s6-overlay service wiring ----------
# Static services declared at build time: main-hermes + dashboard.
@@ -427,20 +454,10 @@ ENV HERMES_WEB_DIST=/opt/hermes/hermes_cli/web_dist
ENV HERMES_TUI_DIR=/opt/hermes/ui-tui
ENV HERMES_HOME=/opt/data
ENV HERMES_WRITE_SAFE_ROOT=/opt/data
ENV HERMES_DISABLE_LAZY_INSTALLS=1
# The published image seals /opt/hermes (root-owned, read-only) so a runtime
# lazy install can't mutate the agent's own venv and brick it. But opt-in
# backends (Firecrawl web search, Exa, Feishu, …) keep their SDKs in
# tools/lazy_deps.py — deliberately NOT baked into [all] (see pyproject.toml
# policy 2026-05-12: one quarantined release must not break every install).
# Redirect those lazy installs to a writable dir on the durable data volume.
# lazy_deps appends this dir to the END of sys.path, so a package installed
# here can only ADD modules — it can never shadow or downgrade a core module,
# so the sealed-venv guarantee holds even with installs re-enabled. The dir
# is seeded + chowned to the hermes user by docker/stage2-hook.sh and lives
# on the /opt/data volume, so it persists across container recreates / image
# updates (an ABI stamp invalidates it if a rebuild bumps the interpreter).
ENV HERMES_LAZY_INSTALL_TARGET=/opt/data/lazy-packages
# Opt-in backend SDKs install on first use into PM dependency generations under
# /opt/data/installs (the sealed /opt/hermes/.venv is never written); stage2
# re-resolves them against each new image. security.allow_lazy_installs: false
# turns this off.
# Xfce, dbus and the display-allocation lock need one; containers have no logind
# to create /run/user/<uid>. The default fallback ($HOME/.cache) is the /opt/data
@@ -474,7 +491,12 @@ COPY --chmod=0755 docker/entrypoint-dispatch.sh /opt/hermes/docker/entrypoint-di
# binary by absolute path, so this PATH ordering is transparent to
# every other consumer.
ENV PATH="/opt/hermes/bin:/opt/hermes/.venv/bin:/opt/data/.local/bin:${PATH}"
RUN mkdir -p /opt/data
# PM's atomic writer creates private facts for source installs. In the
# image these are shared, non-secret package metadata, read by UID 10000.
# uv's environment locks are build-only and may be world-writable. Remove
# them after all builds; never relax permissions on mutable PM/home state.
RUN mkdir -p /opt/data && chmod 0644 /opt/hermes/tools/facts.json && \
rm -f /opt/hermes/.venv/.lock /opt/hermes/pm-runtime/.lock
VOLUME [ "/opt/data" ]
# The image ENTRYPOINT is a tiny dispatcher rather than `/init` directly.
+8 -23
View File
@@ -34,7 +34,7 @@ Usa cualquier modelo que quieras — [Nous Portal](https://portal.nousresearch.c
## Instalación rápida
### Linux, macOS, WSL2, Termux
### Linux, macOS, WSL2
```bash
curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash
@@ -50,11 +50,12 @@ Ejecuta esto en PowerShell:
iex (irm https://hermes-agent.nousresearch.com/install.ps1)
```
El instalador se encarga de todo: uv, Python 3.11, Node.js, ripgrep, ffmpeg, **y un Git Bash portátil** (MinGit, descomprimido en `%LOCALAPPDATA%\hermes\git` — no requiere administrador, completamente aislado de cualquier instalación de Git del sistema). Hermes usa este Git Bash incluido para ejecutar comandos de shell.
El instalador de código fuente usa PM para Python 3.14, Node.js, npm,
ripgrep, FFmpeg y las dependencias de Python. Si falta Git, descarga el archivo
verificado de Git for Windows en el almacén de Hermes, sin reemplazar el Git
del sistema. MSIX/App Installer es una distribución separada.
Si ya tienes Git instalado, el instalador lo detecta y lo usa en su lugar. De lo contrario, una descarga de ~45MB de MinGit es todo lo que necesitas — no tocará ni interferirá con ningún Git del sistema.
> **Android / Termux:** La ruta manual probada está documentada en la [guía de Termux](https://hermes-agent.nousresearch.com/docs/getting-started/termux). En Termux, Hermes instala el extra `.[termux]` curado porque el extra completo `.[all]` actualmente incluye dependencias de voz incompatibles con Android.
> **Android / Termux:** Hay un paquete APT en pruebas para dispositivos aarch64. Incluye Python, Node.js y la TUI. Sigue la [guía de Termux](https://hermes-agent.nousresearch.com/docs/getting-started/termux), no el script de instalación para escritorio y servidor.
>
> **Windows:** Windows nativo es totalmente compatible — el comando de PowerShell de arriba instala todo. Si prefieres usar WSL2, el comando de Linux también funciona allí. La instalación nativa de Windows se encuentra en `%LOCALAPPDATA%\hermes`; WSL2 instala en `~/.hermes` como en Linux.
@@ -182,24 +183,8 @@ Consulta `hermes claw migrate --help` para todas las opciones, o usa la habilida
¡Las contribuciones son bienvenidas! Consulta la [Guía de Contribución](CONTRIBUTING.es.md) para la configuración del desarrollo, el estilo de código y el proceso de PR.
Inicio rápido para colaboradores — clona y comienza con `setup-hermes.sh`:
```bash
git clone https://github.com/NousResearch/hermes-agent.git
cd hermes-agent
./setup-hermes.sh # instala uv, crea venv, instala .[all], enlaza ~/.local/bin/hermes
./hermes # detecta automáticamente el venv, no necesitas hacer `source` primero
```
Ruta manual (equivalente a lo anterior):
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
uv venv .venv --python 3.11
source .venv/bin/activate
uv pip install -e ".[all,dev]"
scripts/run_tests.sh
```
La configuración de PM, el entorno de pruebas con Python 3.14 y los comandos
de verificación están en [Development Setup](CONTRIBUTING.md#development-setup).
---
+10 -31
View File
@@ -34,7 +34,7 @@ Use any model you want — [Nous Portal](https://portal.nousresearch.com), OpenR
## Quick Install
### Linux, macOS, WSL2, Termux
### Linux, macOS, WSL2
```bash
curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash
@@ -50,11 +50,13 @@ Run this in PowerShell:
iex (irm https://hermes-agent.nousresearch.com/install.ps1)
```
The installer handles everything: uv, Python 3.11, Node.js, ripgrep, ffmpeg, **and a portable Git Bash** (MinGit, unpacked to `%LOCALAPPDATA%\hermes\git` — no admin required, completely isolated from any system Git install). Hermes uses this bundled Git Bash to run shell commands.
The source installer delegates Python 3.14, Node.js, npm, ripgrep, FFmpeg,
and Python dependencies to PM. If Git is absent, it stages the verified Git
for Windows archive in Hermes' tool store. It does not replace your system Git.
See [installation methods](https://hermes-agent.nousresearch.com/docs/getting-started/installation)
for the separate MSIX/App Installer package and its update ownership.
If you already have Git installed, the installer detects it and uses that instead. Otherwise a ~45MB MinGit download is all you need — it won't touch or interfere with any system Git.
> **Android / Termux:** The tested manual path is documented in the [Termux guide](https://hermes-agent.nousresearch.com/docs/getting-started/termux). On Termux, Hermes installs a curated `.[termux]` extra because the full `.[all]` extra currently pulls Android-incompatible voice dependencies.
> **Android / Termux:** A signed APT repository is available for aarch64 devices, with a `stable` channel (tagged releases) and a prerelease `canary` channel. The package includes Python, Node.js, and the TUI. Use the [Termux guide](https://hermes-agent.nousresearch.com/docs/getting-started/termux), not the desktop/server installer script.
>
> **Windows:** Native Windows is fully supported — the PowerShell one-liner above installs everything. If you'd rather use WSL2, the Linux command works there too. Native Windows install lives under `%LOCALAPPDATA%\hermes`; WSL2 installs under `~/.hermes` as on Linux.
@@ -218,32 +220,9 @@ See `hermes claw migrate --help` for all options, or use the `openclaw-migration
We welcome contributions! See the [Contributing Guide](https://hermes-agent.nousresearch.com/docs/developer-guide/contributing) for development setup, code style, and PR process.
Quick start for contributors — use the standard installer, then work from the
full git checkout it creates at `$HERMES_HOME/hermes-agent` (usually
`~/.hermes/hermes-agent`). This matches the layout used by `hermes update`, the
managed venv, lazy dependencies, gateway, and docs tooling.
```bash
curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash
cd "${HERMES_HOME:-$HOME/.hermes}/hermes-agent"
uv pip install -e ".[all,dev]"
scripts/run_tests.sh
```
Manual clone fallback (for throwaway clones/CI where you intentionally do not
want the managed install layout):
Create the venv outside the cloned source tree — a venv inside the directory
the agent operates from can be wiped by a relative-path command the agent runs
against its own checkout, destroying the running runtime mid-session.
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
uv venv ~/.hermes/venvs/hermes-dev --python 3.11
source ~/.hermes/venvs/hermes-dev/bin/activate
uv pip install -e ".[all,dev]"
scripts/run_tests.sh
```
Start with the [PM developer workflow](website/docs/reference/package-management.md#developer-workflow)
for activation, daily use, dependency changes, and leaving the environment.
[Development Setup](CONTRIBUTING.md#development-setup) covers the separate test environment and verification commands.
---
+9 -32
View File
@@ -33,7 +33,7 @@
## فوری انسٹالیشن (Quick Install)
### لینکس (Linux)، میک او ایس (macOS)، ڈبلیو ایس ایل ٹو (WSL2)، ٹرمکس (Termux)
### لینکس (Linux)، میک او ایس (macOS)، ڈبلیو ایس ایل ٹو (WSL2)
<div dir="ltr">
@@ -57,13 +57,14 @@ iex (irm https://hermes-agent.nousresearch.com/install.ps1)
</div>
انسٹالر سب کچھ خود سنبھالتا ہے: uv، Python 3.11، Node.js، ripgrep، ffmpeg، **اور ایک پورٹ ایبل (portable) گٹ بیش (Git Bash)** (یعنی MinGit، جو `%LOCALAPPDATA%\hermes\git` میں ان پیک ہوتا ہے — اس کے لیے ایڈمن کی اجازت درکار نہیں، اور یہ سسٹم کے کسی بھی گٹ انسٹال سے بالکل الگ ہے)۔ ہرمیس اس بنڈل شدہ گٹ بیش کو شیل کمانڈز چلانے کے لیے استعمال کرتا ہے۔
سورس انسٹالر Python 3.14، Node.js، npm، ripgrep، FFmpeg اور Python کی
ڈیپینڈینسیز کے لیے PM استعمال کرتا ہے۔ اگر Git موجود نہ ہو تو Git for Windows
کا تصدیق شدہ آرکائیو ہرمیس کے ٹول اسٹور میں نصب کرتا ہے۔ سسٹم کا Git تبدیل نہیں
ہوتا۔ MSIX/App Installer ایک الگ پیکیج ہے۔
اگر آپ کے پاس پہلے سے گٹ (Git) انسٹال ہے، تو انسٹالر اسے شناخت کر لیتا ہے اور اسے ہی استعمال کرتا ہے۔ بصورت دیگر آپ کو صرف ~45MB کے MinGit ڈاؤنلوڈ کی ضرورت ہوگی — یہ آپ کے سسٹم کے گٹ پر کوئی اثر نہیں ڈالے گا۔
> **اینڈرائیڈ (Android) / ٹرمکس (Termux):** ٹیسٹ کیا گیا مینوئل طریقہ [Termux گائیڈ](https://hermes-agent.nousresearch.com/docs/getting-started/termux) میں موجود ہے۔ ٹرمکس پر ہرمیس ایک مخصوص `.[termux]` ایکسٹرا انسٹال کرتا ہے کیونکہ مکمل `.[all]` ایکسٹرا میں ایسی وائس ڈیپینڈینسیز شامل ہیں جو اینڈرائیڈ کے ساتھ مطابقت نہیں رکھتیں۔
> **اینڈرائیڈ / ٹرمکس (Android / Termux):** aarch64 آلات کے لیے آزمائشی APT پیکیج دستیاب ہے۔ اس میں Python، Node.js اور TUI شامل ہیں۔ ڈیسک ٹاپ اور سرور کے انسٹالیشن اسکرپٹ کے بجائے [Termux گائیڈ](https://hermes-agent.nousresearch.com/docs/getting-started/termux) استعمال کریں۔
>
> **ونڈوز (Windows):** مقامی ونڈوز کی مکمل سپورٹ موجود ہے — اوپر دی گئی پاور شیل کی کمانڈ سب کچھ انسٹال کر دیتی ہے۔ اگر آپ WSL2 استعمال کرنا چاہتے ہیں، تو لینکس کی کمانڈ وہاں کام کرتی ہے۔ مقامی ونڈوز میں انسٹالیشن `%LOCALAPPDATA%\hermes` میں ہوتی ہے؛ جبکہ WSL2 میں لینکس کی طرح `~/.hermes` میں ہوتی ہے۔ ہرمیس کا وہ واحد فیچر جسے فی الحال خاص طور پر WSL2 کی ضرورت ہے وہ براؤزر پر مبنی ڈیش بورڈ چیٹ پین ہے (یہ POSIX PTY استعمال کرتا ہے — کلاسک CLI اور گیٹ وے دونوں مقامی طور پر چلتے ہیں)۔
> **ونڈوز (Windows):** مقامی سورس انسٹال کے لیے اوپر دیا گیا PowerShell کمانڈ استعمال کریں۔ WSL2 میں لینکس کمانڈ استعمال ہوتا ہے۔ مقامی ڈیٹا `%LOCALAPPDATA%\hermes` میں اور WSL2 کا ڈیٹا `~/.hermes` میں ہوتا ہے۔ ڈیش بورڈ چیٹ مقامی Windows پر pywinpty/ConPTY استعمال کرتا ہے؛ پلیٹ فارم کی حدود [Windows گائیڈ](https://hermes-agent.nousresearch.com/docs/user-guide/windows-native) میں درج ہیں۔
انسٹالیشن کے بعد:
@@ -213,32 +214,8 @@ hermes claw migrate --overwrite # موجودہ متصادم فائلوں کو
ہم آپ کے تعاون کا خیرمقدم کرتے ہیں! ڈیویلپمنٹ سیٹ اپ، کوڈ کے انداز اور PR کے طریقہ کار کے لیے براہ کرم ہماری [Contributing گائیڈ](https://hermes-agent.nousresearch.com/docs/developer-guide/contributing) دیکھیں۔
معاونین (contributors) کے لیے فوری آغاز — کلون (clone) کریں اور `setup-hermes.sh` چلائیں:
<div dir="ltr">
```bash
git clone https://github.com/NousResearch/hermes-agent.git
cd hermes-agent
./setup-hermes.sh # uv کو انسٹال کرتا ہے، venv بناتا ہے، .[all] کو انسٹال کرتا ہے، اور ~/.local/bin/hermes کا سیم لنک (symlink) بناتا ہے
./hermes # خود بخود venv کی شناخت کرتا ہے، پہلے `source` کرنے کی ضرورت نہیں
```
</div>
مینوئل طریقہ (اوپر والے طریقے کے مساوی):
<div dir="ltr">
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
uv venv .venv --python 3.11
source .venv/bin/activate
uv pip install -e ".[all,dev]"
scripts/run_tests.sh
```
</div>
PM اور Python 3.14 کے ٹیسٹ ماحول اور تصدیقی کمانڈز کے لیے
[Development Setup](CONTRIBUTING.md#development-setup) دیکھیں۔
---
+4 -22
View File
@@ -35,9 +35,9 @@
curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash
```
支持 Linux、macOS、WSL2 和 Android (Termux)。安装程序会自动处理平台特定的配置。
支持 Linux、macOS 和 WSL2。安装程序会自动处理平台特定的配置。
> **Android / Termux:** 已测试的手动安装路径请参考 [Termux 指南](https://hermes-agent.nousresearch.com/docs/getting-started/termux)。在 Termux 上,Hermes 会安装精选的 `.[termux]` 扩展,因为完整的 `.[all]` 扩展会拉取 Android 不兼容的语音依赖。
> **Android / Termux:** aarch64 设备可使用预发布的 APT 软件包,其中包含 Python、Node.js 和 TUI。请按照 [Termux 指南](https://hermes-agent.nousresearch.com/docs/getting-started/termux)安装,不要使用桌面和服务器的安装脚本。
>
> **Windows:** 在 PowerShell 中运行:
> ```powershell
@@ -168,26 +168,8 @@ hermes claw migrate --overwrite # 覆盖已有冲突
欢迎贡献!请参阅 [贡献指南](https://hermes-agent.nousresearch.com/docs/developer-guide/contributing) 了解开发设置、代码风格和 PR 流程。
贡献者快速开始——使用标准安装器,然后在它创建的完整 git checkout 中开发:
`$HERMES_HOME/hermes-agent`(通常是 `~/.hermes/hermes-agent`)。这会匹配
`hermes update`、托管 venv、lazy dependencies、gateway 和 docs tooling 使用的布局。
```bash
curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash
cd "${HERMES_HOME:-$HOME/.hermes}/hermes-agent"
uv pip install -e ".[all,dev]"
scripts/run_tests.sh
```
手动克隆备用路径(用于一次性 clone / CI,或你明确不想使用 managed install layout 时):
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
uv venv venv --python 3.11
source venv/bin/activate
uv pip install -e ".[all,dev]"
python -m pytest tests/ -q
```
PM 引导、Python 3.14 测试环境和规范验证命令见
[开发环境配置](CONTRIBUTING.md#development-setup)。
---
+3 -6
View File
@@ -13,11 +13,6 @@ from acp_adapter.session import SessionState, _expand_acp_enabled_toolsets
logger = logging.getLogger("acp_adapter.server")
try:
from hermes_cli import __version__ as HERMES_VERSION
except Exception:
HERMES_VERSION = "0.0.0"
def _estimate_tokens(history: list, agent: Any, system_prompt: str | None = None, tools: Any = None) -> int:
"""Rough request-token estimate over history + system prompt + tool schemas."""
@@ -310,4 +305,6 @@ class SlashCommandsMixin:
return f"Queued for the next turn. ({_queue_prompt(state, queued_text)} queued)"
def _cmd_version(self, args: str, state: SessionState) -> str:
return f"Hermes Agent v{HERMES_VERSION}"
from hermes_cli.version_info import get_version_info
return f"Hermes Agent v{get_version_info().derived_version}"
+8 -1
View File
@@ -76,6 +76,9 @@ def _path_from_file_uri(uri: str) -> Path | None:
if not raw:
return None
# urlparse treats a bare Windows drive as a URI scheme.
if len(raw) >= 3 and raw[0].isalpha() and raw[1] == ":" and raw[2] in "/\\":
raw = "file:///" + raw.replace("\\", "/")
parsed = urlparse(raw)
if parsed.scheme and parsed.scheme != "file":
return None
@@ -91,7 +94,11 @@ def _path_from_file_uri(uri: str) -> Path | None:
drive, rest = path_text[0], path_text[2:]
else:
return Path(path_text)
return Path("/mnt") / drive.lower() / rest.lstrip("/\\").replace("\\", "/")
import os
rest = rest.lstrip("/\\").replace("\\", "/")
if os.name == "nt":
return Path(f"{drive}:/{rest}")
return Path("/mnt") / drive.lower() / rest
def _decode_text_bytes(data: bytes, mime_type: str | None) -> str | None:
+1 -1
View File
@@ -63,7 +63,7 @@ def reset_edit_approval_requester(token: Token) -> None:
def _read_text_if_exists(path: str) -> str | None:
p = Path(path).expanduser()
if p.is_file():
return p.read_text(encoding="utf-8", errors="replace")
return p.read_text(encoding="utf-8-sig", errors="replace")
if p.exists():
raise OSError(f"Cannot edit non-file path: {path}")
return None
+23 -28
View File
@@ -12,10 +12,10 @@ Usage::
# on Windows. No-op on POSIX. See hermes_bootstrap.py for full rationale.
try:
import hermes_bootstrap # noqa: F401
except ModuleNotFoundError:
# Partial ``hermes update`` (git-reset landed, ``uv pip install -e .`` did not):
# UTF-8 stdio setup is skipped on Windows; POSIX is unaffected.
pass
except ModuleNotFoundError as exc:
# Partial ``hermes update`` (git-reset landed, ``uv pip install -e .`` did not).
if exc.name != "hermes_bootstrap":
raise # the bootstrap exists but cannot load: skipping it would skip PM activation
else:
# Stop a ``utils/``/``proxy/``/``ui/`` package in the launch cwd from shadowing Hermes modules.
hermes_bootstrap.harden_import_path()
@@ -98,18 +98,16 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
parser.add_argument("--setup", action="store_true",
help="Run interactive Hermes provider/model setup for ACP terminal auth")
parser.add_argument("--setup-browser", action="store_true",
help="Install agent-browser + Playwright Chromium into ~/.hermes/node/ "
"for browser tool support. Idempotent.")
help="Prepare PM's pinned browser tools and Chromium.")
parser.add_argument("--yes", "-y", action="store_true", dest="assume_yes",
help="Accept all prompts (currently used by --setup-browser to skip the "
"~400 MB Chromium download confirmation).")
help="Accept setup prompts.")
return parser.parse_args(argv)
def _print_version() -> None:
from hermes_cli import __version__ as hermes_version
from hermes_cli.version_info import get_version_info
print(hermes_version)
print(get_version_info().derived_version)
def _run_check() -> None:
@@ -134,34 +132,24 @@ def _run_setup() -> None:
if not sys.stdin.isatty():
return
try:
reply = input("\nInstall browser tools? Downloads agent-browser (npm) and "
"optionally Playwright Chromium (~400 MB). [y/N] ").strip().lower()
reply = input("\nInstall browser tools? Downloads the pinned browser and "
"Chromium through PM. [y/N] ").strip().lower()
except (EOFError, KeyboardInterrupt):
return
if reply in {"y", "yes"}:
_run_setup_browser(assume_yes=False)
_SETUP_BROWSER_STEPS = (
("node", "Node.js installation failed — cannot proceed with browser tools."),
("browser", "Browser tools installation failed."),
)
def _run_setup_browser(assume_yes: bool = False) -> int:
"""Bootstrap agent-browser + Chromium via dep_ensure -> install.{sh,ps1}
--ensure (shared with the runtime lazy installer). Returns 0 on success, 1 on failure."""
from hermes_cli.dep_ensure import ensure_dependency
"""The setup command is an explicit request for PM's browser closure."""
import pm
try:
for dep, failure_msg in _SETUP_BROWSER_STEPS:
if not ensure_dependency(dep, interactive=not assume_yes):
print(failure_msg, file=sys.stderr)
return 1
return 0
except OSError as exc:
print(f"Browser bootstrap failed: {exc}", file=sys.stderr)
pm.ensure("agent-browser", explicit=True)
except (pm.InstallError, OSError) as exc:
print(f"Browser setup failed: {exc}", file=sys.stderr)
return 1
return 0
def _warm_memory_provider_import(logger: logging.Logger) -> None:
@@ -194,6 +182,13 @@ def main(argv: list[str] | None = None) -> None:
if project_root not in sys.path:
sys.path.insert(0, project_root)
# One TLS authority: trust the OS store before any outbound call (bare
# requests/urllib included) resolves a CA bundle — see agent/ssl_verify.py.
# This console script bypasses hermes_cli.main, which does the same.
from agent.ssl_verify import install_truststore
install_truststore()
import acp
from .server import HermesACPAgent
+4 -2
View File
@@ -25,7 +25,7 @@ from acp.schema import (
)
from acp_adapter.auth import TERMINAL_SETUP_AUTH_METHOD_ID, build_auth_methods, detect_provider
from acp_adapter.commands import HERMES_VERSION, SlashCommandsMixin, _estimate_tokens
from acp_adapter.commands import SlashCommandsMixin, _estimate_tokens
from acp_adapter.content import PromptBlock, _content_blocks_to_openai_user_content, _extract_text
from acp_adapter.events import (
AssistantMessageIdAllocator, _build_plan_update_from_todo_result, _send_update, flush_open_tool_calls,
@@ -524,6 +524,8 @@ class HermesACPAgent(SlashCommandsMixin, acp.Agent):
self, protocol_version: int | None = None, client_capabilities: ClientCapabilities | None = None,
client_info: Implementation | None = None, **kwargs: Any,
) -> InitializeResponse:
from hermes_cli.version_info import get_version_info
auth_methods = build_auth_methods()
logger.info(
"Initialize from %s (protocol v%s)", client_info.name if client_info else "unknown",
@@ -532,7 +534,7 @@ class HermesACPAgent(SlashCommandsMixin, acp.Agent):
return InitializeResponse(
protocol_version=acp.PROTOCOL_VERSION,
agent_info=Implementation(name="hermes-agent", version=HERMES_VERSION),
agent_info=Implementation(name="hermes-agent", version=get_version_info().base_version),
agent_capabilities=AgentCapabilities(
load_session=True,
prompt_capabilities=PromptCapabilities(image=True),
Executable
+225
View File
@@ -0,0 +1,225 @@
#!/usr/bin/env bash
# ============================================================================
# venv-style activation for the Hermes dev environment (pm-managed tools).
#
# source ./activate (bash / zsh, repo root)
# .\activate.ps1 (PowerShell)
#
# Emits the composed pm env (PATH + tool vars) into the CURRENT shell, with
# save/restore: `deactivate` undoes exactly what activation changed.
#
# `hermes` becomes a shell function for this checkout. It runs only while the
# shell is inside this worktree and refuses outside it, so a sibling worktree
# keeps its own command. A prompt prefix names the worktree.
#
# Sync through setup before selecting the environment. PM owns freshness;
# activation does not maintain a second dependency stamp. It trusts the
# recorded tool digest instead of re-hashing every entry. `hermes pm
# install` and `hermes update` keep that check.
# ============================================================================
_HERMES_REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Options: `--test-extras a,b` selects the test environment's runtime extras
# (default: [all]); `--` ends options.
# A bare `source ./activate` inherits the caller's positional parameters.
# Ignore unrelated words so scripts with their own arguments can source it.
_hermes_test_env="--test-environment"
_hermes_expect_extras=""
for _hermes_arg in "$@"; do
if [ -n "$_hermes_expect_extras" ]; then
_hermes_test_env="--test-environment=$_hermes_arg"
_hermes_expect_extras=""
continue
fi
case "$_hermes_arg" in
--) break ;;
--test-extras) _hermes_expect_extras=1 ;;
--test-extras=*) _hermes_test_env="--test-environment=${_hermes_arg#--test-extras=}" ;;
*) : ;;
esac
done
if [ -n "$_hermes_expect_extras" ]; then
printf '%s\n' 'activate: --test-extras needs a comma-separated list' >&2
unset _hermes_arg _hermes_test_env _hermes_expect_extras
return 2 2>/dev/null || exit 2
fi
# Setup runs in a child: failures must not exit or partially activate the
# caller's shell, and activation must not republish launchers or shell config.
if ! (
unset PYTHONHOME PYTHONPATH VIRTUAL_ENV
bash "$_HERMES_REPO/setup-hermes.sh" --runtime-only "$_hermes_test_env"
) >&2; then
printf '%s\n' 'activate: setup failed; shell environment unchanged' >&2
unset _hermes_arg _hermes_test_env _hermes_expect_extras
return 1 2>/dev/null || exit 1
fi
unset _hermes_arg _hermes_test_env _hermes_expect_extras
# Guard against double-sourcing: venv activate precedent (re-activating is a
# no-op re-save; we keep it idempotent by deactivating first). Key on the
# function, not the sentinel: child shells inherit __HERMES_ACTIVATED from an
# activated parent but never the function, and there is nothing to undo there.
if [ "$(type -t deactivate 2>/dev/null)" = "function" ]; then
deactivate
fi
# Bootstrap Python only emits the environment; it does not install anything.
_hermes_repo="$_HERMES_REPO"
_hermes_py=""
for _hermes_candidate in "$_hermes_repo/.venv/bin/python" "$_hermes_repo/.venv/Scripts/python.exe" \
"$_hermes_repo/venv/bin/python" "$_hermes_repo/venv/Scripts/python.exe"; do
[ -x "$_hermes_candidate" ] && { _hermes_py="$_hermes_candidate"; break; }
done
if [ -z "$_hermes_py" ]; then
for _hermes_store in "${HERMES_RUNTIME_DIR:-}" "$_hermes_repo/../tools" "${HERMES_HOME:-$HOME/.hermes}/tools"; do
[ -n "$_hermes_store" ] || continue
for _hermes_candidate in "$_hermes_store"/python-*/bin/python3 "$_hermes_store"/python-*/python.exe "$_hermes_store"/python-*/bin/python "$_hermes_store"/python-*/bin/python.exe; do
[ -x "$_hermes_candidate" ] && { _hermes_py="$_hermes_candidate"; break; }
done
[ -n "$_hermes_py" ] && break
done
fi
if [ -z "$_hermes_py" ]; then
echo "activate: no bootstrap Python found; run setup-hermes.sh" >&2
return 1 2>/dev/null || exit 1
fi
# --- emit export lines from `pm env` ---
_hermes_json="$(PYTHONHOME= PYTHONPATH="$_hermes_repo" "$_hermes_py" -m pm.environments)"
if [ -z "$_hermes_json" ] || [ "${_hermes_json#*{}" = "$_hermes_json" ]; then
echo "activate: could not read pm env (run ./setup-hermes.sh first)" >&2
unset _hermes_repo _hermes_os _hermes_arch _hermes_target _hermes_store _hermes_py _hermes_json
return 1 2>/dev/null || exit 1
fi
_hermes_keys="$(printf '%s' "$_hermes_json" | "$_hermes_py" -c 'import json,sys; print(" ".join(json.load(sys.stdin)))' \
| tr ' ' '\n' | grep -E '^[A-Za-z_][A-Za-z0-9_]*$' | tr '\n' ' ')"
[ -n "$_hermes_keys" ] || _hermes_keys="PATH"
# --- snapshot what we are about to change (deactivate restores this) ---
# __HERMES_ACTIVATED is part of the composed env below (it carries the
# installed-state path this environment was built from), so it is snapshotted
# and exported with every other key — no separate assignment here.
__HERMES_SAVED_PATH="$PATH"
for _hermes_k in $_hermes_keys; do
eval "__HERMES_SAVED_$_hermes_k=\"\${$_hermes_k+set}\""
eval "__HERMES_PRIOR_$_hermes_k=\${$_hermes_k-__HERMES_UNSET__}"
done
# Resolved before the export below replaces PATH.
_hermes_cygpath="$(command -v cygpath 2>/dev/null || :)"
eval "$(printf '%s' "$_hermes_json" | "$_hermes_py" -c '
import json, sys, shlex, re
for k, v in json.load(sys.stdin).items():
# Windows carries names like ProgramFiles(ARM) that are not valid
# bash identifiers — skip them (they pass through untouched).
if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", k):
continue
print("export %s=%s" % (k, shlex.quote(str(v))))')"
# The MSYS/Cygwin runtime hands a native Windows Python these variables in
# Windows form (`C:\a;C:\b`) and converts them back only for its own children.
# Exported verbatim, bash splits PATH on ':' and finds no commands.
if [ -n "$_hermes_cygpath" ]; then
PATH="$("$_hermes_cygpath" -u -p "$PATH")"
for _hermes_k in HOME TMPDIR TMP TEMP; do
if [ -n "${!_hermes_k-}" ]; then
printf -v "$_hermes_k" '%s' "$("$_hermes_cygpath" -u "${!_hermes_k}")"
fi
done
fi
# This checkout, not whichever `hermes` PATH finds. A function beats PATH, an
# alias, and a hashed command, including the MSIX execution alias.
__HERMES_WORKTREE="$_hermes_repo"
# The branch names the worktree. A checkout cannot share a branch with another.
__HERMES_WORKTREE_NAME="$(git -C "$_hermes_repo" rev-parse --abbrev-ref HEAD 2>/dev/null || :)"
if [ -z "$__HERMES_WORKTREE_NAME" ] || [ "$__HERMES_WORKTREE_NAME" = HEAD ]; then
__HERMES_WORKTREE_NAME="$(basename "$_hermes_repo")"
fi
__HERMES_SAVED_PS1="${PS1-__HERMES_UNSET__}"
__HERMES_SAVED_PROMPT_COMMAND="${PROMPT_COMMAND-__HERMES_UNSET__}"
_hermes_worktree_here() {
_hermes_top="$(git rev-parse --show-toplevel 2>/dev/null)" || return 1
[ "$(cd "$_hermes_top" && pwd -P)" = "$(cd "$__HERMES_WORKTREE" && pwd -P)" ]
}
hermes() {
_hermes_worktree_here || {
printf '%s\n' "hermes: $(pwd) is outside $__HERMES_WORKTREE; refusing (the installed command is hidden while this checkout is active)" >&2
return 1
}
(
cd "$__HERMES_WORKTREE" || exit 1
if [ -n "${PYTHON-}" ]; then
exec "$PYTHON" hermes "$@"
elif [ -x .venv/Scripts/python.exe ]; then
exec .venv/Scripts/python.exe hermes "$@"
elif [ -x .venv/bin/python ]; then
exec .venv/bin/python hermes "$@"
elif [ -x venv/Scripts/python.exe ]; then
exec venv/Scripts/python.exe hermes "$@"
elif [ -x venv/bin/python ]; then
exec venv/bin/python hermes "$@"
else
exec python hermes "$@"
fi
)
}
_hermes_prompt() {
if [ "$__HERMES_SAVED_PS1" = "__HERMES_UNSET__" ]; then
_hermes_base_ps1=""
else
_hermes_base_ps1="$__HERMES_SAVED_PS1"
fi
if _hermes_worktree_here; then
PS1="($__HERMES_WORKTREE_NAME) $_hermes_base_ps1"
else
PS1="$_hermes_base_ps1"
fi
}
if [ -n "${PROMPT_COMMAND-}" ]; then
PROMPT_COMMAND="_hermes_prompt; ${PROMPT_COMMAND}"
else
PROMPT_COMMAND=_hermes_prompt
fi
_hermes_prompt
deactivate() {
export PATH="$__HERMES_SAVED_PATH"
for _hermes_k in $__HERMES_KEY_LIST; do
eval "_hermes_was=\"\$__HERMES_SAVED_$_hermes_k\""
eval "_hermes_old=\"\$__HERMES_PRIOR_$_hermes_k\""
if [ "$_hermes_was" != "set" ]; then
unset "$_hermes_k"
else
export "$_hermes_k=$_hermes_old"
fi
unset "__HERMES_SAVED_$_hermes_k" "__HERMES_PRIOR_$_hermes_k"
done
if [ "$__HERMES_SAVED_PS1" = "__HERMES_UNSET__" ]; then
unset PS1
else
PS1="$__HERMES_SAVED_PS1"
fi
if [ "$__HERMES_SAVED_PROMPT_COMMAND" = "__HERMES_UNSET__" ]; then
unset PROMPT_COMMAND
else
PROMPT_COMMAND="$__HERMES_SAVED_PROMPT_COMMAND"
fi
unset __HERMES_SAVED_PATH __HERMES_KEY_LIST __HERMES_ACTIVATED \
__HERMES_WORKTREE __HERMES_WORKTREE_NAME \
__HERMES_SAVED_PS1 __HERMES_SAVED_PROMPT_COMMAND
unset -f deactivate hermes _hermes_worktree_here _hermes_prompt
unset _hermes_k _hermes_was _hermes_old _hermes_top
}
# remember the key list for deactivate (kept out of the loop vars above)
__HERMES_KEY_LIST="$_hermes_keys"
unset _hermes_repo _hermes_os _hermes_arch _hermes_target _hermes_store \
_hermes_py _hermes_json _hermes_keys _hermes_k _hermes_entry _hermes_venvpy \
_hermes_winarch _hermes_top _hermes_cygpath
Executable
+156
View File
@@ -0,0 +1,156 @@
# Source this file to sync and apply the PM environment; deactivate restores it.
# Trusts the recorded tool digest. `hermes pm install` re-checks the bytes.
# -TestExtras a,b selects runtime extras in the test environment (default: [all]).
param([string]$TestExtras = '')
$ErrorActionPreference = 'Stop'
$OutputEncoding = [System.Console]::OutputEncoding = [System.Console]::InputEncoding = [System.Text.Encoding]::UTF8
$PSDefaultParameterValues['*:Encoding'] = 'utf8'
$repo = $PSScriptRoot
$bootstrapSaved = @{}
foreach ($key in @('PYTHONPATH', 'PYTHONHOME', 'VIRTUAL_ENV')) {
$bootstrapSaved[$key] = [Environment]::GetEnvironmentVariable($key)
Remove-Item "env:$key" -ErrorAction SilentlyContinue
}
try {
# Run separately so setup's exit/failure cannot terminate the sourced shell.
$shell = (Get-Process -Id $PID).Path
$testArgs = @()
if ($TestExtras) { $testArgs = @('-TestExtras', $TestExtras) }
& $shell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$repo\setup-hermes.ps1" -RuntimeOnly @testArgs | Out-Host
if ($LASTEXITCODE -ne 0) { throw 'activate: setup failed; shell environment unchanged' }
} finally {
foreach ($key in $bootstrapSaved.Keys) {
if ($null -eq $bootstrapSaved[$key]) { Remove-Item "env:$key" -ErrorAction SilentlyContinue }
else { Set-Item "env:$key" $bootstrapSaved[$key] }
}
}
if (Test-Path function:deactivate) { deactivate }
$py = $null
foreach ($candidate in @("$repo\.venv\Scripts\python.exe", "$repo\venv\Scripts\python.exe")) {
if (Test-Path -LiteralPath $candidate) { $py = $candidate; break }
}
if (-not $py) {
$roots = @($env:HERMES_RUNTIME_DIR, "$repo\..\tools")
$homeRoot = if ($env:HERMES_HOME) { $env:HERMES_HOME } else { "$env:LOCALAPPDATA\hermes" }
$roots += (Join-Path $homeRoot 'tools')
foreach ($root in $roots) {
if (-not $root) { continue }
foreach ($entry in @(Get-ChildItem -LiteralPath $root -Directory -Filter 'python-*' -ErrorAction SilentlyContinue)) {
$candidate = Join-Path $entry.FullName 'python.exe'
if (Test-Path -LiteralPath $candidate) { $py = $candidate; break }
}
if ($py) { break }
}
}
if (-not $py) { throw 'activate: no bootstrap Python found; run setup-hermes.ps1' }
$priorPath = $env:PYTHONPATH
$priorHome = $env:PYTHONHOME
try {
$env:PYTHONPATH = $repo
Remove-Item env:PYTHONHOME -ErrorAction SilentlyContinue
$json = (& $py -m pm.environments) -join "`n"
if ($LASTEXITCODE -ne 0) { throw 'activate: could not read the installed environment' }
$composed = $json | ConvertFrom-Json
} finally {
if ($null -eq $priorPath) { Remove-Item env:PYTHONPATH -ErrorAction SilentlyContinue } else { $env:PYTHONPATH = $priorPath }
if ($null -eq $priorHome) { Remove-Item env:PYTHONHOME -ErrorAction SilentlyContinue } else { $env:PYTHONHOME = $priorHome }
}
# __HERMES_ACTIVATED (the sentinel repo scripts and the shebang prologue read)
# is part of the composed env, so it is saved and restored with the rest.
$global:_hermesKeys = @($composed.PSObject.Properties.Name)
$global:_hermesSaved = @{}
foreach ($key in $global:_hermesKeys) {
$global:_hermesSaved[$key] = [pscustomobject]@{
WasSet = (Test-Path "env:$key")
Value = [Environment]::GetEnvironmentVariable($key)
}
}
foreach ($property in $composed.PSObject.Properties) {
Set-Item -Path "env:$($property.Name)" -Value ([string]$property.Value)
}
# This checkout, not whichever `hermes` PATH finds. A function beats PATH,
# an alias, and the MSIX execution alias. It runs only while the shell is
# inside this worktree.
$global:_hermesWorktree = $repo
# The branch names the worktree. A checkout cannot share a branch with another.
# git's "not a repository" is not an activation failure: the directory name is
# the label, and the command still refuses outside this tree.
$branch = $null
try { $branch = & git -C $repo rev-parse --abbrev-ref HEAD 2>$null } catch { $branch = $null }
if ($branch -and $branch -ne 'HEAD') {
$global:_hermesWorktreeName = $branch
} else {
$global:_hermesWorktreeName = Split-Path -Leaf $repo
}
if (Test-Path function:prompt) {
$global:_hermesSavedPrompt = (Get-Item function:prompt).ScriptBlock
} else {
$global:_hermesSavedPrompt = $null
}
function global:_hermesWorktreeHere {
# Prompt calls this after every command. Keep the user's exit code.
$saved = $global:LASTEXITCODE
$top = $null
try { $top = & git rev-parse --show-toplevel 2>$null } catch { $top = $null }
$global:LASTEXITCODE = $saved
if (-not $top) { return $false }
$here = [System.IO.Path]::GetFullPath($top).TrimEnd('\')
$root = [System.IO.Path]::GetFullPath($global:_hermesWorktree).TrimEnd('\')
return $here.Equals($root, [System.StringComparison]::OrdinalIgnoreCase)
}
function global:hermes {
if (-not (_hermesWorktreeHere)) {
$here = (Get-Location).Path
Write-Error "hermes: $here is outside $($global:_hermesWorktree); refusing (the installed command is hidden while this checkout is active)" -ErrorAction Continue
$global:LASTEXITCODE = 1
return
}
Push-Location -LiteralPath $global:_hermesWorktree
try {
$py = $env:PYTHON
if (-not $py) {
foreach ($candidate in @(
'.venv\Scripts\python.exe', 'venv\Scripts\python.exe',
'.venv\bin\python', 'venv\bin\python'
)) {
if (Test-Path -LiteralPath $candidate) { $py = $candidate; break }
}
}
if (-not $py) { $py = 'python' }
& $py hermes @args
} finally {
Pop-Location
}
}
function global:prompt {
$prefix = ''
if (_hermesWorktreeHere) { $prefix = "($($global:_hermesWorktreeName)) " }
if ($global:_hermesSavedPrompt) {
return $prefix + (& $global:_hermesSavedPrompt)
}
return "$prefix$($(Get-Location).Path)> "
}
function global:deactivate {
foreach ($key in $global:_hermesKeys) {
$saved = $global:_hermesSaved[$key]
if ($saved.WasSet) { Set-Item -Path "env:$key" -Value $saved.Value }
else { Remove-Item -Path "env:$key" -ErrorAction SilentlyContinue }
}
if ($global:_hermesSavedPrompt) {
Set-Item -Path function:prompt -Value $global:_hermesSavedPrompt
} else {
Remove-Item function:prompt -ErrorAction SilentlyContinue
}
$global:_hermesKeys = $null
$global:_hermesSaved = $null
$global:_hermesWorktree = $null
$global:_hermesWorktreeName = $null
$global:_hermesSavedPrompt = $null
Remove-Item function:deactivate, function:hermes, function:_hermesWorktreeHere -ErrorAction SilentlyContinue
}
-2
View File
@@ -973,8 +973,6 @@ def _init_openai_client(agent, api_key, base_url, fallback_model, _provider_time
agent.api_key = client_kwargs.get("api_key", "")
agent.base_url = client_kwargs.get("base_url", agent.base_url)
try:
from agent.ssl_guard import verify_ca_bundle
verify_ca_bundle()
agent.client = agent._create_openai_client(client_kwargs, reason="agent_init", shared=True)
if not agent.quiet_mode:
print(f"🤖 AI Agent initialized with model: {agent.model}")
+14 -7
View File
@@ -4,6 +4,7 @@ OpenAI-style internals. Auth: API keys (``sk-ant-api*``) -> x-api-key; OAuth set
payload conversion and credentials live in ``agent/anthropic_{endpoints,message_convert,
credentials}.py``; import them from there."""
from pm import install_hint
import logging
import math
import os
@@ -27,7 +28,7 @@ from agent.anthropic_message_convert import (
)
from agent.errors import EmptyStreamError
from hermes_cli import __version__ as _HERMES_VERSION
from hermes_cli.version_info import get_version_info
# ``import anthropic`` is deliberately NOT at module top: the SDK costs ~220 ms of imports and
@@ -39,9 +40,14 @@ def _get_anthropic_sdk():
"""Return the ``anthropic`` SDK module, importing lazily. None if not installed."""
global _anthropic_sdk
if _anthropic_sdk is ...:
with suppress(Exception): # ImportError or FeatureUnavailable — fall through to the import below
from tools.lazy_deps import ensure as _lazy_ensure
_lazy_ensure("provider.anthropic", prompt=False)
try:
from pm import ensure_import
ensure_import("anthropic")
except ImportError:
pass
except Exception:
# InstallError — fall through to ImportError handling below
pass
try:
import anthropic as _sdk
_anthropic_sdk = _sdk
@@ -54,7 +60,8 @@ def _require_sdk(purpose: str, verb: str = "Install it with"):
"""``_get_anthropic_sdk()`` or ImportError naming the feature that needs it."""
sdk = _get_anthropic_sdk()
if sdk is None:
raise ImportError(f"The 'anthropic' package is required for {purpose}. {verb}: pip install 'anthropic>=0.39.0'")
raise ImportError(f"The 'anthropic' package is required for {purpose}. {verb}: "
f"{install_hint('anthropic')}")
return sdk
@@ -334,7 +341,7 @@ def _attribution_headers() -> Dict[str, str]:
"""Same client-attribution set sent to OpenRouter / Vercel AI Gateway / Fireworks."""
return {
"HTTP-Referer": "https://hermes-agent.nousresearch.com", "X-Title": "Hermes Agent",
"User-Agent": f"HermesAgent/{_HERMES_VERSION}",
"User-Agent": f"HermesAgent/{get_version_info().base_version}",
}
@@ -487,7 +494,7 @@ def build_anthropic_bedrock_client(region: str):
from agent.bedrock_adapter import bedrock_guardrail_headers, scoped_aws_session_kwargs
sdk = _require_sdk("the Bedrock provider")
if not hasattr(sdk, "AnthropicBedrock"):
raise ImportError("anthropic.AnthropicBedrock not available. Upgrade with: pip install 'anthropic>=0.39.0'")
raise ImportError("anthropic.AnthropicBedrock not available. Run: hermes pm repair")
# Routed multiplex profile: its own AWS_* from the secret scope (the SDK would otherwise read the
# launch profile's process env); unscoped passes nothing and keeps the default chain.
scoped = scoped_aws_session_kwargs()
+5 -3
View File
@@ -104,7 +104,7 @@ def _load_json_if_exists(path: Path, what: str) -> Optional[Any]:
if not path.exists():
return None
try:
return json.loads(path.read_text(encoding="utf-8"))
return json.loads(path.read_text(encoding="utf-8-sig"))
except (json.JSONDecodeError, OSError) as e:
logger.debug("Failed to read %s: %s", what, e)
return None
@@ -156,7 +156,9 @@ 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"))
raw = json.loads(
_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
@@ -539,7 +541,7 @@ def _write_claude_code_credentials(
>=2.1.81 gates on ``"user:inference"`` being present."""
cred_path = claude_code_credentials_path()
try:
existing = json.loads(cred_path.read_text(encoding="utf-8")) if cred_path.exists() else {}
existing = json.loads(cred_path.read_text(encoding="utf-8-sig")) if cred_path.exists() else {}
except (OSError, ValueError) as e:
logger.error("Failed to write refreshed credentials to %s: %s", cred_path, e)
raise CredentialPersistError(cred_path, e) from e
+6 -5
View File
@@ -143,7 +143,7 @@ _LOGGED_UNSUPPORTED_OAUTH_KEYS: set = set()
def _resolve_aux_verify(base_url: Optional[str]) -> Any:
"""httpx ``verify`` for an aux base_url, mirroring the main client (per-provider ``ssl_ca_cert`` /
``ssl_verify``, ``HERMES_CA_BUNDLE`` / ``SSL_CERT_FILE``); any failure → httpx default (``True``)."""
``ssl_verify``; otherwise the OS trust store); any failure → httpx default (``True``)."""
try:
from agent.ssl_verify import resolve_httpx_verify
from hermes_cli.config import get_custom_provider_tls_settings, load_config_readonly
@@ -932,16 +932,16 @@ def build_nvidia_nim_headers(base_url: str | None) -> dict:
# Vercel AI Gateway attribution (HTTP-Referer → referrerUrl, X-Title → appName).
from hermes_cli import __version__ as _HERMES_VERSION
from hermes_cli.version_info import get_version_info
_AI_GATEWAY_HEADERS = {
"HTTP-Referer": "https://hermes-agent.nousresearch.com",
"X-Title": "Hermes Agent",
"User-Agent": f"HermesAgent/{_HERMES_VERSION}",
"User-Agent": f"HermesAgent/{get_version_info().base_version}",
}
# Nous Portal attribution extra_body. Tags come from agent.portal_tags so the client= marker
# tracks hermes_cli.__version__ — never inline a literal here.
# tracks the canonical base version — never inline a literal here.
from agent.portal_tags import nous_portal_tags as _nous_portal_tags
@@ -6817,7 +6817,8 @@ def _managed_local_netloc() -> str:
return cached
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:
+12 -7
View File
@@ -11,6 +11,7 @@ Reference: https://learn.microsoft.com/azure/ai-foundry/foundry-models/how-to/co
from __future__ import annotations
from pm import install_hint
import contextvars
import functools
import logging
@@ -25,10 +26,14 @@ logger = logging.getLogger(__name__)
# scope is an ARM control-plane scope rejected for inference by newer resources; override via ``model.entra.scope``.
SCOPE_AI_AZURE_DEFAULT = "https://ai.azure.com/.default"
_AZURE_IDENTITY_FEATURE = "provider.azure_identity"
# ---------------------------------------------------------------------------
# Lazy SDK import — only loaded when the Entra path is actually used.
# ---------------------------------------------------------------------------
_AZURE_IDENTITY_FEATURE = "azure-identity"
_INSTALL_MSG = "The 'azure-identity' package is required for Azure AI Foundry Entra ID authentication. "
_LAZY_INSTALL_HINT = (
"pip install azure-identity manually, or enable lazy installs (security.allow_lazy_installs: true in config.yaml)."
f"Run: {install_hint('azure-identity')}"
)
_AUTH_HEADERS = ("Authorization", "authorization", "Api-Key", "api-key", "X-Api-Key", "x-api-key")
@@ -49,12 +54,12 @@ def _require_azure_identity():
return _ai
except ImportError:
try:
from tools.lazy_deps import ensure, FeatureUnavailable
from pm import InstallError, ensure_import
except ImportError as exc:
raise ImportError(_INSTALL_MSG + "Install it with: pip install azure-identity") from exc
raise ImportError(_INSTALL_MSG + "Run: hermes pm repair") from exc
try:
ensure(_AZURE_IDENTITY_FEATURE, prompt=False)
except FeatureUnavailable as exc:
ensure_import(_AZURE_IDENTITY_FEATURE)
except InstallError as exc:
raise ImportError(_INSTALL_MSG + str(exc)) from exc
import azure.identity as _ai # noqa: WPS440 — retry after lazy install
return _ai
@@ -164,7 +169,7 @@ def _install_failure(allow_install: bool) -> Optional[Dict[str, Any]]:
if has_azure_identity_installed():
return None
if not allow_install:
return {"error": "azure-identity not installed", "hint": "pip install azure-identity (or rely on lazy install at first use)"}
return {"error": "azure-identity not installed", "hint": _LAZY_INSTALL_HINT}
try:
_require_azure_identity()
except ImportError as exc:
+11 -16
View File
@@ -5,6 +5,7 @@ control-plane model discovery. OpenAI-format messages/tools are converted to Con
and responses normalized back to OpenAI-shaped objects.
"""
from pm import install_hint
import base64
import importlib
import json
@@ -24,19 +25,6 @@ from agent.errors import EmptyStreamError
logger = logging.getLogger(__name__)
# boto3 is not in the [all] extras; lazy_deps installs it on demand.
try:
# --------------------------------------------------------------------------- Ensure boto3/botocore are
# installed before any code in this module runs. Upstream removed boto3 from [all] extras (PRs #24220,
# #24515); lazy_deps handles on-demand installation so the Bedrock provider still works in the EKS
# deployment without baking boto3 into the base image.
# ---------------------------------------------------------------------------
from tools.lazy_deps import ensure
ensure("provider.bedrock", prompt=False)
except Exception as exc: # downstream imports surface the real error
logger.warning("boto3 lazy install did not complete: %s", exc)
_bedrock_runtime_client_cache: Dict[str, Any] = {}
_bedrock_control_client_cache: Dict[str, Any] = {}
# Routed multiplex profiles: one client per (profile home, region). boto3 freezes the credential
@@ -100,12 +88,19 @@ _MIN_BOTO3_VERSION = (1, 34, 59)
def _require_boto3():
"""Import boto3; converse_stream() needs >= 1.34.59 (a system boto3 can shadow the venv pin)."""
try:
# boto3 left [all] (PRs #24220, #24515); PM installs the [bedrock] extra on first use. This
# runs at the first client build, never at import: an import-time sync would rebuild the
# dependency environment of whatever process happens to import this module.
try:
from pm import ensure_import
ensure_import("bedrock")
except Exception as exc: # the import below reports the real failure
logger.warning("boto3 lazy install did not complete: %s", exc)
import boto3
except ImportError:
raise ImportError(
"The 'boto3' package is required for the AWS Bedrock provider. "
"Install it with: pip install boto3\n"
"Or install Hermes with Bedrock support: pip install -e '.[bedrock]'"
f"Run: {install_hint('bedrock')}"
)
try:
version = tuple(int(x) for x in boto3.__version__.split(".")[:3])
@@ -114,7 +109,7 @@ def _require_boto3():
if version < _MIN_BOTO3_VERSION:
raise RuntimeError(
f"boto3 {boto3.__version__} does not support converse_stream "
f"(minimum 1.34.59 required). Upgrade with: pip install --upgrade boto3"
f"(minimum 1.34.59 required). Run: hermes pm repair"
)
return boto3
+1 -1
View File
@@ -796,7 +796,7 @@ def _managed_local_load_notice(agent, api_kwargs: dict) -> "Optional[str]":
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
+2 -2
View File
@@ -23,8 +23,8 @@ _NO_SOCKETS_SUFFIX = " — no sockets found; in-flight request may keep running
def _routermint_headers() -> dict:
"""User-Agent RouterMint needs to avoid Cloudflare 1010 blocks."""
from hermes_cli import __version__ as _HERMES_VERSION
return {"User-Agent": f"HermesAgent/{_HERMES_VERSION}"}
from hermes_cli.version_info import get_version_info
return {"User-Agent": f"HermesAgent/{get_version_info().base_version}"}
def _qwen_portal_headers() -> dict:
+5 -2
View File
@@ -40,8 +40,11 @@ def codex_cloudflare_headers(access_token: str, *, base_url: str = CODEX_AUX_BAS
OAuth JWT (see :func:`codex_account_headers`).
"""
if is_official_codex_base_url(base_url):
from hermes_cli import __version__
headers = {"User-Agent": f"HermesAgent/{__version__}", "originator": "hermes-agent"}
from hermes_cli.version_info import get_version_info
headers = {
"User-Agent": f"HermesAgent/{get_version_info().base_version}",
"originator": "hermes-agent",
}
else:
headers = {"User-Agent": "codex_cli_rs/0.0.0 (Hermes Agent)", "originator": "codex_cli_rs"}
headers.update(codex_account_headers(access_token))
+2 -1
View File
@@ -448,7 +448,7 @@ def _read_small(path: Path) -> str:
try:
if not path.is_file() or path.stat().st_size > _MAX_FACT_FILE_BYTES:
return ""
return path.read_text(encoding="utf-8", errors="replace")
return path.read_text(encoding="utf-8-sig", errors="replace")
except OSError:
return ""
@@ -588,6 +588,7 @@ _PROFILES: dict[str, ContextProfile] = {
CODING_PROFILE.name: CODING_PROFILE,
}
def get_profile(name: str) -> ContextProfile:
"""Return a registered profile, falling back to ``general``."""
return _PROFILES.get(name, GENERAL_PROFILE)
+1 -1
View File
@@ -347,7 +347,7 @@ def _expand_path_reference(ref: ContextReference, cwd: Path, *, allowed_root: Pa
size = path.stat().st_size
if max_inline_tokens is not None and size > max_inline_tokens * CHARS_PER_TOKEN:
return None, _oversized_text_reference_block(ref, path, size // CHARS_PER_TOKEN)
text = path.read_text(encoding="utf-8")
text = path.read_text(encoding="utf-8-sig")
lang = _FENCE_LANGUAGES.get(path.suffix.lower(), "")
text_tokens = estimate_tokens_rough(text)
# Check BEFORE building the fenced block: an oversized file is not going to be
+7 -2
View File
@@ -91,7 +91,12 @@ def _acp_supported(command: str, args: list[str]) -> bool | None:
return cached
try:
probe = subprocess.run(
[command, "--help"], capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5,
[command, "--help"],
# Explicit codec because text=True alone decodes with the
# locale default and crashes on non-ASCII help text under
# GBK/CP932 locales.
capture_output=True, text=True, encoding="utf-8",
errors="replace", timeout=5,
stdin=subprocess.DEVNULL,
)
except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
@@ -246,7 +251,7 @@ def _fs_read_text_file(params: dict[str, Any], cwd: str) -> Any:
if block_error := get_read_block_error(str(path)):
raise PermissionError(block_error)
try:
content = path.read_text(encoding="utf-8")
content = path.read_text(encoding="utf-8-sig")
except FileNotFoundError:
content = ""
line, limit = params.get("line"), params.get("limit")
+2 -1
View File
@@ -778,7 +778,8 @@ def _guarded_global_root(global_path: Optional[Path]) -> Optional[Path]:
if real_home_env:
real_root = Path(real_home_env) / ".hermes" / "auth.json"
try:
if global_path.resolve(strict=False) == real_root.resolve(strict=False):
# Comparing the guard path must not probe the real auth store.
if os.path.normcase(os.path.abspath(global_path)) == os.path.normcase(os.path.abspath(real_root)):
return None
except Exception:
return None
+1 -1
View File
@@ -343,7 +343,7 @@ def dev_fixture_credits_state() -> Optional[CreditsState]:
return None
if os.path.sep in name or "/" in name: # looks like a path → read the name from the file
try:
with open(name, "r", encoding="utf-8") as fh:
with open(name, "r", encoding="utf-8-sig") as fh:
name = fh.read().strip()
except OSError:
return None
+2 -2
View File
@@ -47,7 +47,7 @@ def load_state() -> Dict[str, Any]:
}
path = _state_file()
try:
data = json.loads(path.read_text(encoding="utf-8")) if path.exists() else {}
data = json.loads(path.read_text(encoding="utf-8-sig")) if path.exists() else {}
except (OSError, json.JSONDecodeError) as e:
logger.debug("Failed to read curator state: %s", e)
return base
@@ -529,7 +529,7 @@ def _parse_structured_summary(llm_final: str) -> Dict[str, List[Dict[str, str]]]
data = None
if match:
try:
import yaml # type: ignore
import hermes_yaml as yaml
data = yaml.safe_load(match.group(1))
except Exception:
pass
+2 -2
View File
@@ -223,7 +223,7 @@ def _prune_old(keep: int, protect: Optional[Set[str]] = None) -> List[str]:
# --- List + rollback ---
def _read_manifest(snap_dir: Path) -> Dict[str, Any]:
try:
return json.loads((snap_dir / "manifest.json").read_text(encoding="utf-8"))
return json.loads((snap_dir / "manifest.json").read_text(encoding="utf-8-sig"))
except (OSError, json.JSONDecodeError):
return {}
@@ -270,7 +270,7 @@ def _restore_cron_skill_links(snapshot_dir: Path) -> Dict[str, Any]:
if not backup_file.exists():
return {**report, "error": f"snapshot has no {CRON_JOBS_FILENAME}"}
try:
backup_jobs = _jobs_list(json.loads(backup_file.read_text(encoding="utf-8")))
backup_jobs = _jobs_list(json.loads(backup_file.read_text(encoding="utf-8-sig")))
except (OSError, json.JSONDecodeError) as e:
return {**report, "error": f"failed to load backed-up jobs: {e}"}
if backup_jobs is None:
+17 -2
View File
@@ -34,8 +34,23 @@ __all__ = [
"run_bounded_async", "run_bounded_sync", "kill_process_tree",
]
# One year: semantically "unbounded" yet far below any platform time_t limit (#83220).
MAX_SAFE_TIMEOUT_S = 31_536_000.0
# Upper bound for any timeout handed to platform wait primitives.
#
# CPython converts ``threading.Lock.acquire(timeout=...)`` /
# ``Thread.join(timeout=...)`` deadlines to an absolute timestamp; very large
# relative timeouts overflow ``time_t`` on macOS and raise
# ``OverflowError: timestamp out of range for platform time_t`` (#83220).
# On Windows the binding constraint is narrower: the underlying
# ``WaitForSingleObject`` takes a DWORD *milliseconds* argument, so any
# wait above ~49.7 days (0xFFFFFFFF ms) raises OverflowError rather than
# waiting (verified live: 4294967.0s ok, 4294967.3s overflows). One year
# is the semantic "unbounded" on platforms that can express it; Windows
# takes the DWORD-ms cap, which is still semantically "unbounded" for
# every wait in this codebase.
_WINDOWS_MAX_WAIT_S = (0xFFFFFFFF - 1000) / 1000.0 # DWORD ms, minus a 1s rounding guard
MAX_SAFE_TIMEOUT_S = (
_WINDOWS_MAX_WAIT_S if sys.platform == "win32" else 31_536_000.0
) # 365 days off-Windows
# Grace after a deadline fires before concluding the loop thread is blocked and dumping stacks.
_LOOP_BLOCKED_DUMP_GRACE_S = 5.0
+2 -2
View File
@@ -608,8 +608,8 @@ def _resolved_path(path: str) -> Path:
def _snapshot_text(path: Path) -> str | None:
"""Return UTF-8 file content, or None for missing/unreadable files."""
try:
return path.read_text(encoding="utf-8")
except (UnicodeDecodeError, OSError): # FileNotFoundError/IsADirectoryError are OSErrors
return path.read_text(encoding="utf-8-sig")
except (FileNotFoundError, IsADirectoryError, UnicodeDecodeError, OSError):
return None
-4
View File
@@ -1,7 +1,3 @@
class SSLConfigurationError(Exception):
"""Raised when SSL/TLS certificate bundle configuration fails."""
class EmptyStreamError(RuntimeError):
"""Raised when a provider closes a stream without yielding a response."""
+1 -1
View File
@@ -103,7 +103,7 @@ def get_state() -> Optional[dict]:
continue
found = True
with suppress(OSError, ValueError, AttributeError):
raw = json.loads(path.read_text(encoding="utf-8"))
raw = json.loads(path.read_text(encoding="utf-8-sig"))
if isinstance(raw, dict):
state = {"reason": raw.get("reason") or None, "engaged_at": raw.get("engaged_at") or None}
break
+2 -6
View File
@@ -25,13 +25,9 @@ from agent.gemini_schema import prepare_gemini_tool_parameters, sanitize_gemini_
logger = logging.getLogger(__name__)
try:
import hermes_cli as _hermes_cli
from hermes_cli.version_info import get_version_info
_HERMES_VERSION = str(_hermes_cli.__version__)
except Exception:
_HERMES_VERSION = "0.0.0"
_API_CLIENT = f"hermes-agent/{_HERMES_VERSION}" # client context per Gemini's partner-integration guidance
_API_CLIENT = f"hermes-agent/{get_version_info().base_version}" # client context per Gemini's partner-integration guidance
DEFAULT_GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta"
# A Vertex AI express-mode base, when the user configures one explicitly: aiplatform serves the
+2 -2
View File
@@ -100,8 +100,8 @@ def _load_catalog(lang: str) -> dict[str, str]:
logger.debug("i18n catalog missing for %s at %s", lang, path)
return _cache_catalog(lang, flat)
try:
import yaml
with path.open("r", encoding="utf-8") as f:
import hermes_yaml as yaml
with path.open("r", encoding="utf-8-sig") as f:
_flatten_into(yaml.safe_load(f) or {}, "", flat)
except Exception as exc:
logger.warning("Failed to load i18n catalog %s: %s", path, exc)
+16 -8
View File
@@ -31,11 +31,16 @@ _VALID_MODES = frozenset({"auto", "native", "text"})
# the gateway routes them via send_document and a PDF must never become a vision part.
_IMAGE_EXTS = (".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".tif", ".heic")
_IMAGE_EXT_PATTERN = "|".join(e.lstrip(".") for e in _IMAGE_EXTS)
# Local path: same shape as gateway extract_local_files() — anchored to ``~/`` or
# ``/``, lookbehind skips matches inside URLs. URL: strict ``http(s)://`` so
# ``file://`` and other schemes are not grabbed; optional query string.
# Absolute / home-relative local image path. Matches the same shape gateway's
# extract_local_files() uses: anchors to ``~/``, ``/``, or a Windows drive
# (``C:\``), ignores matches inside URLs (the ``(?<![/:\w.])`` lookbehind), and
# case-insensitive on the extension.
_LOCAL_IMAGE_PATH_RE = re.compile(
r"(?<![/:\w.])(?:~/|/)(?:[\w.\-]+/)*[\w.\-]+\.(?:" + _IMAGE_EXT_PATTERN + r")\b", re.IGNORECASE,
r"(?<![/:\w.])(?:~/|/|[A-Za-z]:[\\/])(?:[\w.\-]+[\\/])*[\w.\-]+\.(?:"
+ _IMAGE_EXT_PATTERN
+ r")\b",
re.IGNORECASE,
)
_IMAGE_URL_RE = re.compile(
r"https?://[^\s<>\"']+?\.(?:" + _IMAGE_EXT_PATTERN + r")(?:\?[^\s<>\"']*)?", re.IGNORECASE,
@@ -50,10 +55,13 @@ def _matches_outside_code(pattern: re.Pattern, text: str) -> Iterable[str]:
def _existing_file(candidate: str) -> Optional[str]:
"""Expanded path when it is a regular file; None otherwise (incl. OSError on pathological input)."""
"""Normalized path when it is a regular file; None otherwise (incl. OSError on pathological input).
The return value is the OS-canonical spelling of the real file (same norm class as
``str(Path(...))``), so callers can compare it against actual paths — ``~`` expansion
alone would leave the textual ``/`` separators of the source text in place on Windows."""
expanded = os.path.expanduser(candidate)
try:
return expanded if os.path.isfile(expanded) else None
return os.path.normpath(expanded) if os.path.isfile(expanded) else None
except OSError:
return None
@@ -432,8 +440,8 @@ def _transcode_to_png(raw: bytes) -> Optional[bytes]:
except ImportError:
logger.info(
"image_routing: Pillow not installed; cannot transcode "
"non-standard image format to PNG. Install with `pip install Pillow` "
"(and `pillow-heif` / `pillow-avif-plugin` for those formats)."
"non-standard image format to PNG. Run `hermes pm repair` to restore Pillow, "
"or convert the image to PNG before sending it."
)
return None
with suppress(Exception):
+2 -2
View File
@@ -58,7 +58,7 @@ def _load_usage() -> dict[str, dict[str, Any]]:
return load_usage()
except Exception:
try:
return json.loads((get_hermes_home() / "skills" / ".usage.json").read_text(encoding="utf-8"))
return json.loads((get_hermes_home() / "skills" / ".usage.json").read_text(encoding="utf-8-sig"))
except Exception:
return {}
@@ -87,7 +87,7 @@ def build_skill_nodes(skill_roots: list[tuple[str, Path]]) -> dict[str, SkillNod
if _SKIP_PARTS.intersection(skill_md.parts):
continue
try:
text = skill_md.read_text(encoding="utf-8")[:4000]
text = skill_md.read_text(encoding="utf-8-sig")[:4000]
except OSError:
continue
try:
+1 -1
View File
@@ -156,7 +156,7 @@ def _skill_detail(node_id: str) -> dict[str, Any]:
skill_md = Path(found["path"]) / "SKILL.md"
if not skill_md.exists():
return {"ok": False, "message": f"SKILL.md missing for '{node_id}'"}
return {"ok": True, "kind": "skill", "id": node_id, "label": node_id, "content": skill_md.read_text(encoding="utf-8")}
return {"ok": True, "kind": "skill", "id": node_id, "label": node_id, "content": skill_md.read_text(encoding="utf-8-sig")}
# ── Delete ──────────────────────────────────────────────────────────────────
+1 -1
View File
@@ -585,7 +585,7 @@ class LSPClient:
raise LSPProtocolError("client not running")
abs_path = os.path.abspath(path)
try:
text = Path(abs_path).read_text(encoding="utf-8", errors="replace")
text = Path(abs_path).read_text(encoding="utf-8-sig", errors="replace")
except OSError as e:
raise LSPProtocolError(f"cannot read {abs_path}: {e}") from e
uri = file_uri(abs_path)
+17 -17
View File
@@ -19,7 +19,7 @@ from pathlib import Path
from typing import Any, Callable, Dict, Optional
from hermes_cli._subprocess_compat import windows_hide_flags
from hermes_constants import find_node_executable
from hermes_constants import find_node_executable, with_hermes_node_path
logger = logging.getLogger("agent.lsp.install")
@@ -127,6 +127,16 @@ def _existing_binary(name: str, *, is_windows: Optional[bool] = None) -> Optiona
for staged in (c for base in bases for c in _native_binary_candidates(base, is_windows=win)):
if staged.exists() and os.access(staged, os.X_OK):
return str(staged)
if any(r.get("strategy") == "pip" and r.get("bin") == name for r in INSTALL_RECIPES.values()):
import pm
try:
binary = pm.python_tool(f"lsp-{name}", name)
except RuntimeError as exc:
logger.warning("[install] cannot read Python server %s: %s", name, exc)
else:
if binary is not None:
return str(binary)
suffixes = (*_WINDOWS_WRAPPER_SUFFIXES, "") if win else ("",)
return next((p for s in suffixes if (p := shutil.which(f"{name}{s}"))), None)
@@ -244,7 +254,7 @@ def _install_npm(pkg: str, bin_name: str, extra_pkgs: Optional[list] = None) ->
install_targets = [pkg] + list(extra_pkgs or [])
cmd = [pm_bin, *_NODE_PM_ARGV[pm](str(staging)), *install_targets]
logger.info("[install] %s %s", pm, " ".join(cmd[1:]))
if not _run_installer(pm, pkg, cmd, timeout=300):
if not _run_installer(pm, pkg, cmd, timeout=300, env=with_hermes_node_path()):
return None
found = _first_existing(staging / "node_modules" / ".bin" / bin_name)
if found is not None:
@@ -273,24 +283,14 @@ def _install_go(pkg: str, bin_name: str) -> Optional[str]:
def _install_pip(pkg: str, bin_name: str) -> Optional[str]:
"""``pip install --target <staging>/python-packages`` then link the console script into ``lsp/bin/``."""
pip_target = hermes_lsp_bin_dir().parent / "python-packages"
pip_target.mkdir(parents=True, exist_ok=True)
"""Provision a Python server in its own PM-managed environment."""
try:
logger.info("[install] pip install --target %s %s", pip_target, pkg)
from hermes_cli.tools_config import _pip_install
import pm
proc = _pip_install(["--target", str(pip_target), "--quiet", pkg], timeout=300)
if proc.returncode != 0:
logger.warning("[install] pip install failed for %s: %s", pkg, (proc.stderr or "").strip()[:500])
return None
except (subprocess.TimeoutExpired, OSError) as e:
logger.warning("[install] pip install errored for %s: %s", pkg, e)
return str(pm.ensure_python_tool(f"lsp-{bin_name}", [pkg], bin_name, timeout=300))
except Exception as exc:
logger.warning("[install] Python server install failed for %s: %s", pkg, exc)
return None
# POSIX wheels write console scripts to bin/, native Windows to Scripts/.
script_dirs = [pip_target / "bin"] + ([pip_target / "Scripts"] if _is_windows() else [])
found = _first_existing(*(d / bin_name for d in script_dirs))
return _link_into_bin(found) if found is not None else None
# strategy → installer(recipe, bin_name). ``manual`` is handled before dispatch.
+14 -3
View File
@@ -141,8 +141,12 @@ def _find_binary(ctx: ServerContext, server_id: str, which: Sequence[str], insta
def _make_spec(root: str, ctx: ServerContext, server_id: str, command: List[str],
base_init: Optional[Dict[str, Any]] = None, seed: bool = False) -> SpawnSpec:
from pm import env_for
init = ctx.init_overrides.get(server_id, {}) if base_init is None else {**base_init, **ctx.init_overrides.get(server_id, {})}
return SpawnSpec(command, root, root, env=ctx.env_overrides.get(server_id, {}),
env = env_for("node")
env.update(ctx.env_overrides.get(server_id, {}))
return SpawnSpec(command, root, root, env=env,
initialization_options=init, seed_diagnostics_on_first_push=seed)
@@ -175,9 +179,16 @@ def _spawn_pyright(root: str, ctx: ServerContext) -> Optional[SpawnSpec]:
def _detect_python(root: str) -> Optional[str]:
# Pyright needs the project's dependencies, not Hermes's runtime packages.
venvs = [v for v in (os.environ.get("VIRTUAL_ENV"), os.path.join(root, ".venv"), os.path.join(root, "venv")) if v]
paths = (os.path.join(v, sub) for v in venvs for sub in ("bin/python", "bin/python3", "Scripts/python.exe"))
return next((p for p in paths if os.path.exists(p)), None)
project_python = next((p for p in paths if os.path.exists(p)), None)
if project_python is not None:
return project_python
from pm import installed_package
installed = installed_package("python")
return str(installed.binary) if installed is not None and installed.binary is not None else None
_warned_once: set = set()
@@ -233,7 +244,7 @@ def _vue_server_major(trees: Sequence[str]) -> int:
import json
for tree in trees:
try:
with open(os.path.join(tree, "@vue", "language-server", "package.json"), encoding="utf-8") as fh:
with open(os.path.join(tree, "@vue", "language-server", "package.json"), encoding="utf-8-sig") as fh:
return int(str(json.load(fh).get("version", "")).split(".")[0])
except (OSError, ValueError):
continue
+20 -9
View File
@@ -515,6 +515,7 @@ def _trim_messages_for_reference(
_REFERENCE_POLL_INTERVAL_S = 5.0
_REFERENCE_INTERRUPT_SETTLE_S = 0.05
# Sentinel for a reference aborted by user interrupt; the facade must never cache it.
_INTERRUPTED_REFERENCE_NOTE = "[skipped: interrupted by user]"
@@ -585,6 +586,19 @@ def _run_references_parallel(
# Shared per-fan-out context-length cache (dict get/set is GIL-atomic).
ctx_len_cache: dict[tuple[str, str], int | None] = {}
cache_disabled, cache_ttl = _agent_cache_opts(agent)
def collect(done: set[Any]) -> None:
nonlocal completed
for future in done:
idx = futures[future]
results[idx] = future.result()
completed += 1
if progress_callback is not None:
try:
progress_callback(completed, total, _slot_label(reference_models[idx]))
except Exception as exc: # pragma: no cover - display must never break
logger.debug("MoA progress_callback failed: %s", exc)
try:
for idx, slot in enumerate(reference_models):
if slot.get("provider") == "moa":
@@ -600,16 +614,13 @@ def _run_references_parallel(
pending = set(futures)
while pending:
done, pending = _futures_wait(pending, timeout=_REFERENCE_POLL_INTERVAL_S)
for future in done:
idx = futures[future]
results[idx] = future.result()
completed += 1
if progress_callback is not None:
try:
progress_callback(completed, total, _slot_label(reference_models[idx]))
except Exception as exc: # pragma: no cover - display must never break
logger.debug("MoA progress_callback failed: %s", exc)
collect(done)
if pending and agent is not None and getattr(agent, "_interrupt_requested", False):
# A worker can raise the interrupt immediately before publishing
# its own result. Give concurrently-finishing work one scheduler
# turn so completed output is not replaced by an interrupt note.
done, pending = _futures_wait(pending, timeout=_REFERENCE_INTERRUPT_SETTLE_S)
collect(done)
interrupted = True
_settle_interrupted(futures, results, reference_models, late_accounting_sink)
break
+33 -84
View File
@@ -9,17 +9,15 @@ import hashlib
import ipaddress
import json
import logging
import os
import re
import time
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple, TYPE_CHECKING
from typing import Any, Callable, Dict, List, Optional, Tuple
from urllib.parse import urlparse
import yaml
import hermes_yaml as yaml
if TYPE_CHECKING: # pragma: no cover — runtime import is lazy (see below)
import requests
from agent import model_metadata_http
from utils import atomic_json_write, atomic_yaml_write, base_url_host_matches, base_url_hostname
@@ -28,45 +26,6 @@ from agent.message_metadata import PERSISTENCE_ONLY_MESSAGE_FIELDS
logger = logging.getLogger(__name__)
# ``requests`` costs ~27 ms of the `import cli` waterfall, so it is resolved lazily:
# ``_ensure_requests()`` at runtime, PEP 562 ``__getattr__`` for ``patch("agent.model_metadata.requests.get")``.
def _ensure_requests():
if "requests" not in globals():
import requests as _requests
globals()["requests"] = _requests
return globals()["requests"]
def __getattr__(name: str):
if name == "requests":
return _ensure_requests()
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
def _resolve_requests_verify(base_url: str = "") -> bool | str:
"""SSL ``verify`` for ``requests`` probes; mirrors ``agent.ssl_verify.resolve_httpx_verify``.
Priority: per-provider ``ssl_verify: false`` -> per-provider ``ssl_ca_cert`` (else probes log
spurious CERTIFICATE_VERIFY_FAILED while the httpx chat path succeeds) -> CA env vars -> certifi."""
if base_url:
try:
from hermes_cli.config import get_custom_provider_tls_settings
tls = get_custom_provider_tls_settings(base_url)
if tls.get("ssl_verify") is False:
return False
ca = tls.get("ssl_ca_cert")
if isinstance(ca, str) and ca and os.path.isfile(ca):
return ca
except Exception:
pass # fall through to env vars — never break a probe on config lookup
for env_var in ("HERMES_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "SSL_CERT_FILE"):
val = os.getenv(env_var)
if val and os.path.isfile(val):
return val
return True
# Snapshot for callers inspecting this constant; prefix routing queries the registry live.
try:
from providers import list_providers as _list_providers
@@ -174,14 +133,10 @@ def _note_if_connect_timeout(exc: BaseException, base_url: str) -> None:
def _is_connect_timeout(exc: BaseException) -> bool:
"""True for connect-phase timeouts raised by httpx or requests. Read timeouts are
excluded: the server accepted the connection, the opposite of a blackhole."""
try:
import httpx
from requests.exceptions import ConnectTimeout
return isinstance(exc, (httpx.ConnectTimeout, ConnectTimeout))
except Exception:
return False
"""Read timeouts prove the server accepted a connection, not a blackhole."""
import httpx
return isinstance(exc, httpx.ConnectTimeout)
# Disk L2 for local-endpoint probes so back-to-back CLI cold starts skip the waterfall.
@@ -197,7 +152,7 @@ def _cache_file(name: str) -> Path:
def _load_json_dict(path: Path) -> Dict[str, Any]:
"""JSON object at ``path``, or {} when missing/invalid."""
try:
with path.open("r", encoding="utf-8") as f:
with path.open("r", encoding="utf-8-sig") as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
except Exception:
@@ -259,7 +214,7 @@ def _model_metadata_disk_cache_age_seconds() -> Optional[float]:
def _load_model_metadata_disk_cache() -> Dict[str, Dict[str, Any]]:
"""Processed OpenRouter metadata cache from disk ({} on any failure)."""
try:
with _get_model_metadata_cache_path().open("r", encoding="utf-8") as f:
with _get_model_metadata_cache_path().open("r", encoding="utf-8-sig") as f:
data = json.load(f)
return {str(key): value for key, value in data.items() if isinstance(value, dict)} if isinstance(data, dict) else {}
except Exception as e:
@@ -792,7 +747,7 @@ def detect_local_server_type(base_url: str, api_key: str = "") -> Optional[str]:
)
result: Optional[str] = None
try:
with httpx.Client(timeout=2.0, headers=_auth_headers(api_key)) as client:
with httpx.Client(timeout=2.0, headers=_auth_headers(api_key), verify=model_metadata_http.resolve_verify(base_url)) as client:
for name, urls, check in waterfall:
try:
for url in urls:
@@ -948,10 +903,9 @@ def fetch_model_metadata(force_refresh: bool = False) -> Dict[str, Dict[str, Any
_model_metadata_cache_time = time.time() - disk_age
return _model_metadata_cache
try:
_ensure_requests()
# (connect, read) tuple: a flat timeout lets urllib3 block per retry stage through proxies that 403 CONNECT.
# See #46620.
response = requests.get(OPENROUTER_MODELS_URL, timeout=(5, 10), verify=_resolve_requests_verify())
response = model_metadata_http.get(OPENROUTER_MODELS_URL, timeout=(5, 10), verify=model_metadata_http.resolve_verify())
response.raise_for_status()
cache = {}
for model in response.json().get("data", []):
@@ -1001,7 +955,7 @@ def _lmstudio_loaded_context(model: Dict[str, Any]) -> Optional[int]:
def _lmstudio_native_models(normalized: str, headers: Dict[str, str]) -> Dict[str, Dict[str, Any]]:
"""LM Studio ``/api/v1/models`` → cache; context comes from the first loaded instance."""
response = requests.get(_lmstudio_server_root(normalized).rstrip("/") + "/api/v1/models", headers=headers, timeout=(5, 10), verify=_resolve_requests_verify(normalized))
response = model_metadata_http.get(_lmstudio_server_root(normalized).rstrip("/") + "/api/v1/models", headers=headers, timeout=(5, 10), verify=model_metadata_http.resolve_verify(normalized))
response.raise_for_status()
cache: Dict[str, Dict[str, Any]] = {}
for model in response.json().get("models", []):
@@ -1022,28 +976,28 @@ def _apply_llamacpp_props(cache: Dict[str, Dict[str, Any]], request_candidate: s
via ``/props?model=``; unloaded children are skipped — probing could autoload them."""
base = request_candidate.rstrip("/").replace("/v1", "")
def _props(params=None):
resp = requests.get(base + "/v1/props", params=params, headers=headers, timeout=5, verify=verify)
if not resp.ok:
resp = requests.get(base + "/props", params=params, headers=headers, timeout=5, verify=verify)
resp = model_metadata_http.get(base + "/v1/props", params=params, headers=headers, timeout=5, verify=verify)
if resp.is_error:
resp = model_metadata_http.get(base + "/props", params=params, headers=headers, timeout=5, verify=verify)
return resp
def _n_ctx(props: Dict[str, Any]) -> Any:
return (props.get("default_generation_settings") or {}).get("n_ctx")
props_resp = _props()
if props_resp.ok:
if not props_resp.is_error:
props = props_resp.json()
n_ctx, model_alias = _n_ctx(props), props.get("model_alias", "")
if n_ctx and model_alias and model_alias in cache:
cache[model_alias]["context_length"] = n_ctx
return
native = requests.get(base + "/models", headers=headers, timeout=5, verify=verify)
if not native.ok:
native = model_metadata_http.get(base + "/models", headers=headers, timeout=5, verify=verify)
if native.is_error:
return
for child in (native.json() or {}).get("data", [])[:16]:
child_id = child.get("id") if isinstance(child, dict) else None
if not child_id or child_id not in cache or (child.get("status") or {}).get("value") not in ("loaded", "ready"):
continue
pr = _props({"model": child_id})
child_ctx = _n_ctx(pr.json()) if pr.ok else None
child_ctx = _n_ctx(pr.json()) if not pr.is_error else None
if child_ctx:
cache[child_id]["context_length"] = child_ctx
@@ -1074,7 +1028,6 @@ def fetch_endpoint_model_metadata(base_url: str, api_key: str = "", force_refres
normalized = _normalize_base_url(base_url)
if not normalized or base_url_host_matches(normalized, "openrouter.ai"):
return {}
_ensure_requests()
local = is_local_endpoint(normalized)
memo_key = _endpoint_memo_key(normalized, api_key)
if not force_refresh:
@@ -1090,7 +1043,7 @@ def fetch_endpoint_model_metadata(base_url: str, api_key: str = "", force_refres
alternate = normalized[:-3].rstrip("/") if normalized.endswith("/v1") else normalized + "/v1"
candidates = [normalized] + ([alternate] if alternate != normalized else [])
headers = _auth_headers(api_key)
verify = _resolve_requests_verify(normalized)
verify = model_metadata_http.resolve_verify(normalized)
last_error: Optional[Exception] = None
if local:
try:
@@ -1106,14 +1059,14 @@ def fetch_endpoint_model_metadata(base_url: str, api_key: str = "", force_refres
# Cache keys stay unrewritten; only the outbound target is IPv4-resolved.
request_candidate = _localhost_to_ipv4(candidate)
url = request_candidate.rstrip("/") + "/models"
response = None
try:
response = requests.get(url, headers=headers, timeout=(5, 10), verify=verify, stream=True)
if response.status_code in (401, 403):
logger.debug("Model metadata probe received HTTP %s from %s; stopping candidate probing", response.status_code, url)
break
response.raise_for_status()
payload = response.json()
with model_metadata_http.stream(url, headers=headers, timeout=(5, 10), verify=verify) as response:
if response.status_code in (401, 403):
logger.debug("Model metadata probe received HTTP %s from %s; stopping candidate probing", response.status_code, url)
break
response.raise_for_status()
response.read()
payload = response.json()
cache = _parse_models_payload(payload)
if any(m.get("owned_by") == "llamacpp" for m in payload.get("data", []) if isinstance(m, dict)):
with contextlib.suppress(Exception):
@@ -1124,9 +1077,6 @@ def fetch_endpoint_model_metadata(base_url: str, api_key: str = "", force_refres
except Exception as exc:
last_error = exc
_note_if_connect_timeout(exc, normalized)
finally:
if response is not None:
response.close()
if last_error:
logger.debug("Failed to fetch model metadata from %s/models: %s", normalized, last_error)
return _remember_endpoint_models(memo_key, {})
@@ -1156,7 +1106,7 @@ def _load_context_cache_document() -> dict:
if not path.exists():
return {}
try:
with open(path, encoding="utf-8") as f:
with open(path, encoding="utf-8-sig") as f:
data = yaml.safe_load(f)
if not isinstance(data, dict):
return {}
@@ -1164,6 +1114,7 @@ def _load_context_cache_document() -> dict:
if not isinstance(data.get(section), dict):
data[section] = {}
return data
return data.get("context_lengths") or {}
except Exception as e:
logger.debug("Failed to load context length cache: %s", e)
return {}
@@ -1478,7 +1429,7 @@ def _ollama_show(server_url: str, api_key: str, bare_model: str, timeout: float
"""Ollama ``/api/show`` JSON for ``bare_model``, or None on any failure (``note_blackhole``: connect timeouts condemn the host)."""
import httpx
try:
with httpx.Client(timeout=timeout, headers=_auth_headers(api_key)) as client:
with httpx.Client(timeout=timeout, headers=_auth_headers(api_key), verify=model_metadata_http.resolve_verify(server_url)) as client:
resp = client.post(f"{server_url}/api/show", json={"name": bare_model})
return resp.json() if resp.status_code == 200 else None
except Exception as exc:
@@ -1698,7 +1649,7 @@ def _query_local_context_length_uncached(model: str, base_url: str, api_key: str
}.get(server_type)
probes = ([typed] if typed else []) + [_model_detail_ctx, lambda client: _openai_models_list_context(client, server_url, model)]
try:
with httpx.Client(timeout=3.0, headers=_auth_headers(api_key)) as client:
with httpx.Client(timeout=3.0, headers=_auth_headers(api_key), verify=model_metadata_http.resolve_verify(base_url)) as client:
return next((ctx for ctx in (probe(client) for probe in probes) if ctx is not None), None)
except Exception as exc:
_note_if_connect_timeout(exc, server_url)
@@ -1721,8 +1672,7 @@ def _query_anthropic_context_length(model: str, base_url: str, api_key: Any) ->
try:
base = base_url.rstrip("/").removesuffix("/v1")
headers = {"x-api-key": api_key, "anthropic-version": "2023-06-01"}
_ensure_requests()
resp = requests.get(f"{base}/v1/models?limit=1000", headers=headers, timeout=(5, 10), verify=_resolve_requests_verify(base_url))
resp = model_metadata_http.get(f"{base}/v1/models?limit=1000", headers=headers, timeout=(5, 10), verify=model_metadata_http.resolve_verify(base_url))
if resp.status_code != 200:
return None
for m in resp.json().get("data", []):
@@ -1881,9 +1831,8 @@ def _fetch_codex_oauth_context_lengths_with_source(access_token: str) -> Tuple[D
from agent.codex_headers import codex_account_headers
headers = {"Authorization": f"Bearer {access_token}", **codex_account_headers(access_token)}
try:
_ensure_requests()
entries, status = fetch_codex_catalog_entries(
lambda url: requests.get(url, headers=headers, timeout=(5, 10), verify=_resolve_requests_verify())
lambda url: model_metadata_http.get(url, headers=headers, timeout=(5, 10), verify=model_metadata_http.resolve_verify())
)
if status != 200:
logger.debug("Codex /models probe returned HTTP %s; falling back to hardcoded defaults", status)
Loaded 100 of 3390 files, more files were not shown because too many files have changed in this diff. Show more