The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(release): bake explicit environment defaults into commit bundles
ethernet7d326adf9dcb
diff --git a/.github/workflows/desktop-bundled-release.yml b/.github/workflows/desktop-bundled-release.ymlindex a9381b96d8a..112cd5dd43e 100644--- a/.github/workflows/desktop-bundled-release.yml+++ b/.github/workflows/desktop-bundled-release.yml@@ -105,6 +105,11 @@ on:required: falsetype: stringdefault: ''+ bundle_env:+ description: 'Commit desktop bundles only: JSON object of non-secret runtime environment defaults. Explicit runtime values win.'+ required: false+ type: string+ default: '{}'termux_only:description: 'Build and publish only the Termux package'required: false@@ -167,6 +172,7 @@ jobs:env:TAG: ${{ inputs.tag }}BUILD_COMMIT: ${{ inputs.build_commit }}+ BUNDLE_ENV_JSON: ${{ inputs.bundle_env }}RELEASE_PHASE: ${{ inputs.release-phase }}DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}UPLOAD_RELEASE: ${{ inputs.upload_release }}@@ -190,6 +196,9 @@ jobs:python -m scripts.releases.commit_build admitexit 0fi+ if [ -n "${BUNDLE_ENV_JSON:-}" ] && [ "$BUNDLE_ENV_JSON" != '{}' ]; then+ echo '::error::bundle environment defaults require a commit build'; exit 1+ fiif [ -z "$TAG" ]; thenecho "::error::either tag or build_commit is required"; exit 1fi@@ -466,6 +475,7 @@ jobs:shell: bashtimeout-minutes: 900env:+ HERMES_BUNDLE_ENV_JSON: ${{ inputs.bundle_env }}PYTHONUTF8: '1'AZURE_SIGN_ENDPOINT: ${{ vars.AZURE_SIGN_ENDPOINT }}AZURE_SIGN_ACCOUNT: ${{ vars.AZURE_SIGN_ACCOUNT }}@@ -738,6 +748,7 @@ jobs:shell: bashtimeout-minutes: 330env:+ HERMES_BUNDLE_ENV_JSON: ${{ inputs.bundle_env }}GITHUB_SHA: ${{ needs.validate.outputs.sha }}GITHUB_REF_NAME: ${{ inputs.tag }}PYTHONUTF8: '1'diff --git a/apps/desktop/BUILDING.md b/apps/desktop/BUILDING.mdindex 826d4c730b2..a41b4b03ca7 100644--- a/apps/desktop/BUILDING.md+++ b/apps/desktop/BUILDING.md@@ -115,6 +115,25 @@ It prints the dispatch command without changing local branches, tags, or releaseAdd `--publish` to dispatch that build. This flag does not publish a releasein commit-build mode.+Use repeatable `--bundle-env NAME=VALUE` options to bake non-secret runtime+defaults into the desktop app, for example:++```sh+python scripts/release.py --build-commit REV --remote fork --publish \+ --bundle-env HERMES_GUEST_ONBOARDING=1 \+ --bundle-env HERMES_DATA_DIR_SUFFIX=magic-test+```++These defaults run before Electron initializes its paths and are inherited by+local backend processes. Explicit runtime environment values win, including+empty values. Do not pass secrets: the values are visible in the workflow inputs+and packaged JavaScript. This option affects desktop bundles, not Termux.+The suffix is appended literally; include a leading hyphen if desired.+For local commit builds, `HERMES_BUNDLE_ENV_JSON` accepts the same defaults as+a JSON object of strings. Defaults are not applied to the build runner itself.+Commit archive keys still use the SHA, so use a fresh commit for different+defaults: an existing artifact is never overwritten with different bytes.+The workflow must exist on the repository's default branch. Admission requiresa default-branch `workflow_dispatch` and repository write, maintain, or adminpermission for both the original actor and the actor who reruns it.diff --git a/apps/desktop/scripts/bundle-electron-main.mjs b/apps/desktop/scripts/bundle-electron-main.mjsindex cb8b17f25a6..e7fac8544b5 100644--- a/apps/desktop/scripts/bundle-electron-main.mjs+++ b/apps/desktop/scripts/bundle-electron-main.mjs@@ -5,6 +5,7 @@ import { join, resolve } from 'node:path'import { pathToFileURL } from 'node:url'import { parseArgs } from 'node:util'import { isMain, workspaceTool } from '../../../scripts/build/frontend-common.mjs'+import { environmentDefaultsBanner } from './bundle-env.mjs'const repoRoot = resolve(import.meta.dirname, '../../..')@@ -28,6 +29,9 @@ export async function bundleElectronMain({ source, out, stamp, dev = false }) {source = resolve(source)out = resolve(out)const { build } = await import(pathToFileURL(workspaceTool(source, 'apps/desktop', 'esbuild')).href)+ // Defaults must run before bundled modules resolve paths or onboarding flags.+ // Dev bundles leave the environment alone so source-tree resolution keeps working.+ const envBanner = dev ? '' : environmentDefaultsBanner(process.env.HERMES_BUNDLE_ENV_JSON || '{}')const define = {}if (!dev) {if (!stamp) throw new Error('A prepared install stamp is required')@@ -52,7 +56,7 @@ export async function bundleElectronMain({ source, out, stamp, dev = false }) {entryPoints: [join(source, 'apps/desktop/electron/main.ts')],format: 'esm',outfile: join(out, 'electron-main.mjs'),- banner: { js: "import { createRequire } from 'module'; const require = createRequire(import.meta.url);" },+ banner: { js: "import { createRequire } from 'module'; const require = createRequire(import.meta.url);" + envBanner },})await build({...common,diff --git a/apps/desktop/scripts/bundle-env.mjs b/apps/desktop/scripts/bundle-env.mjsnew file mode 100644index 00000000000..d191941b162--- /dev/null+++ b/apps/desktop/scripts/bundle-env.mjs@@ -0,0 +1,15 @@+// Defaults must run before bundled modules resolve paths or onboarding flags.+// An esbuild define would replace reads, not populate the child process env.+/** @param {string} raw @returns {string} */+export function environmentDefaultsBanner(raw) {+ const values = JSON.parse(raw)+ if (!values || Array.isArray(values) || typeof values !== 'object') {+ throw new Error('Bundle environment must be a JSON object')+ }+ for (const [key, value] of Object.entries(values)) {+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || typeof value !== 'string' || value.includes('\0')) {+ throw new Error('Bundle environment requires valid names and string values without NUL')+ }+ }+ return `\nfor (const [key, value] of ${JSON.stringify(Object.entries(values))}) { process.env[key] ??= value; }\n`+}diff --git a/apps/desktop/scripts/bundle-env.test.mjs b/apps/desktop/scripts/bundle-env.test.mjsnew file mode 100644index 00000000000..02166b44599--- /dev/null+++ b/apps/desktop/scripts/bundle-env.test.mjs@@ -0,0 +1,32 @@+import { build } from 'esbuild'+import { execFileSync } from 'node:child_process'+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { expect, test } from 'vitest'++import { environmentDefaultsBanner } from './bundle-env.mjs'++test('baked defaults precede imported module initialization and reach children without overriding explicit env', async () => {+ const root = mkdtempSync(join(tmpdir(), 'hermes-bundle-env-'))+ const defaults = { HERMES_GUEST_ONBOARDING: '1', HERMES_DATA_DIR_SUFFIX: 'magic-test', LITERAL: 'a=b "q"\n$(no)', EMPTY: '' }+ const env = { ...process.env }+ for (const key of Object.keys(defaults)) {+ delete env[key]+ }+ try {+ writeFileSync(join(root, 'reader.mjs'), `export const values = Object.fromEntries(${JSON.stringify(Object.keys(defaults))}.map(key => [key, process.env[key]]));`, 'utf8')+ const entry = join(root, 'entry.mjs')+ writeFileSync(entry, `import {values} from './reader.mjs'; import {execFileSync} from 'node:child_process'; console.log(JSON.stringify({values, child: execFileSync(process.execPath, ['-p', 'process.env.HERMES_DATA_DIR_SUFFIX'], {encoding:'utf8'}).trim()}));`, 'utf8')+ const outfile = join(root, 'bundle.mjs')+ await build({ entryPoints: [entry], bundle: true, platform: 'node', format: 'esm', outfile, banner: { js: environmentDefaultsBanner(JSON.stringify(defaults)) } })+ const run = extra => JSON.parse(execFileSync(process.execPath, [outfile], { env: { ...env, ...extra }, encoding: 'utf8' }))+ expect(run({})).toEqual({ values: defaults, child: defaults.HERMES_DATA_DIR_SUFFIX })+ expect(run({ HERMES_DATA_DIR_SUFFIX: '-explicit', HERMES_GUEST_ONBOARDING: '' })).toEqual({ values: { ...defaults, HERMES_DATA_DIR_SUFFIX: '-explicit', HERMES_GUEST_ONBOARDING: '' }, child: '-explicit' })+ for (const bad of ['[]', 'null', '{"BAD-NAME":"x"}', '{"NAME":1}', '{"NAME":"\\u0000"}']) {+ expect(() => environmentDefaultsBanner(bad)).toThrow()+ }+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+})diff --git a/scripts/bundles/desktop.py b/scripts/bundles/desktop.pyindex e943080d996..4981d0d9755 100644--- a/scripts/bundles/desktop.py+++ b/scripts/bundles/desktop.py@@ -55,8 +55,12 @@ def build(repo: Path, tag: str | None, variant: str, builder_args: list[str],commit_build: str | None = None) -> None:from pm.store import current_targetfrom scripts.releases.commit_build import require_commit, version_at+ from scripts.releases.bundle_env import decoderepo = repo.resolve()+ bundle_env = decode(os.environ.get("HERMES_BUNDLE_ENV_JSON", ""))+ if bundle_env and not commit_build:+ raise ValueError("Bundle environment defaults require a commit build")if commit_build:commit = require_commit(commit_build)if tag:@@ -78,6 +82,7 @@ def build(repo: Path, tag: str | None, variant: str, builder_args: list[str],npm = npm_command(node)env = {**os.environ, "CI": "true", "PYTHONUTF8": "1", "GITHUB_SHA": commit,"HERMES_DESKTOP_VARIANT": variant}+ env["HERMES_BUNDLE_ENV_JSON"] = json.dumps(bundle_env, sort_keys=True)if commit_build:env["HERMES_PAYLOAD_VERSION"] = versionenv["HERMES_BUILD_COMMIT"] = commitdiff --git a/scripts/release.py b/scripts/release.pyindex e33d769574d..1b9ab6476b9 100755--- a/scripts/release.py+++ b/scripts/release.py@@ -2896,6 +2896,9 @@ def main():parser.add_argument("--build-commit", type=str, metavar="REV",help="Preview an exact-commit build into releases/commit/<sha>/ on R2. ""Add --publish to dispatch without a tag or release.")+ parser.add_argument("--bundle-env", action="append", default=[], metavar="NAME=VALUE",+ help="Bake a non-secret environment default into a commit desktop bundle. "+ "Repeat for multiple variables. Runtime environment values win.")parser.add_argument("--prune-canaries", action="store_true",help="Delete canary releases+tags older than 14 days")parser.add_argument("--publish", action="store_true",@@ -2914,6 +2917,8 @@ def main():help="Skip changelog")args = parser.parse_args()+ if args.bundle_env and args.build_commit is None:+ parser.error("--bundle-env requires --build-commit")if args.canary and args.bump:parser.error("--canary and --bump are mutually exclusive")if args.build_commit is not None:diff --git a/scripts/releases/bundle_env.py b/scripts/releases/bundle_env.pynew file mode 100644index 00000000000..e3e820ba218--- /dev/null+++ b/scripts/releases/bundle_env.py@@ -0,0 +1,32 @@+"""Non-secret environment defaults carried by a desktop bundle."""+from __future__ import annotations++import json+import re+++def validate(values: object) -> dict[str, str]:+ if not isinstance(values, dict):+ raise ValueError("Bundle environment must be a JSON object")+ for key, value in values.items():+ if not isinstance(key, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key):+ raise ValueError("Bundle environment names must be valid environment identifiers")+ if not isinstance(value, str) or "\0" in value:+ raise ValueError(f"Bundle environment value for {key} must be a string without NUL")+ return values+++def parse_assignments(assignments: list[str]) -> dict[str, str]:+ values = {}+ for assignment in assignments:+ key, separator, value = assignment.partition("=")+ if not separator:+ raise ValueError("--bundle-env requires NAME=VALUE")+ if key in values:+ raise ValueError(f"Duplicate bundle environment name: {key}")+ values[key] = value+ return validate(values)+++def decode(raw: str) -> dict[str, str]:+ return validate(json.loads(raw or "{}"))diff --git a/scripts/releases/commit_build.py b/scripts/releases/commit_build.pyindex 36f25f25ee3..80d3ab78f04 100644--- a/scripts/releases/commit_build.py+++ b/scripts/releases/commit_build.py@@ -43,6 +43,8 @@ def version_at(repo: Path | None, commit: str) -> str:def admit(env: dict[str, str]) -> dict[str, str]:+ from scripts.releases.bundle_env import decode+commit = require_commit(env.get("BUILD_COMMIT", ""))if env.get("TAG") or env.get("RELEASE_PHASE") or env.get("UPLOAD_RELEASE", "false") != "false":raise ValueError("Commit builds cannot use tag, release-phase or upload_release")@@ -63,6 +65,7 @@ def admit(env: dict[str, str]) -> dict[str, str]:if permission not in {"write", "maintain", "admin"}:raise ValueError("Commit builds require repository write, maintain or admin permission")require_pushed(commit, "origin")+ decode(env.get("BUNDLE_ENV_JSON", ""))return {"sha": commit, "channel": "commit", "payload-version": version_at(None, commit)}@@ -75,18 +78,26 @@ def resolve_revision(rev: str, remote: str, repo: Path) -> str:return commit-def dispatch_command(commit: str, repository: str, branch: str) -> list[str]:+def dispatch_command(commit: str, repository: str, branch: str,+ bundle_env: dict[str, str] | None = None) -> list[str]:+ from scripts.releases.bundle_env import validate+require_commit(commit)- return ["gh", "workflow", "run", WORKFLOW, "--ref", branch, "--repo", repository,+ command = ["gh", "workflow", "run", WORKFLOW, "--ref", branch, "--repo", repository,"-f", f"build_commit={commit}", "-f", "tag=", "-f", "upload_release=false","-f", "termux_only=false", "-f", "termux_upgrade_from_tag="]+ if bundle_env:+ command += ["-f", "bundle_env=" + json.dumps(validate(bundle_env), sort_keys=True)]+ return commanddef cmd_build_commit(args) -> None:from scripts import releasefrom scripts.releases import r2+ from scripts.releases.bundle_env import parse_assignmentstry:+ bundle_env = parse_assignments(args.bundle_env)remote = release.resolve_push_remote(args.remote)repository = release.remote_github_repo(remote)if not repository:@@ -95,7 +106,7 @@ def cmd_build_commit(args) -> None:branch = release._default_branch(repository)if not branch:raise ValueError("could not resolve the repository default branch")- command = dispatch_command(commit, repository, branch)+ command = dispatch_command(commit, repository, branch, bundle_env)page = r2.public_url_for(r2.public_base_url(), r2.commit_page_key_for(commit))print(f"Commit: {commit}\nR2: {r2.commit_prefix_for(commit)}\nPage: {page}\nWorkflow: {repository}@{branch}")print(shlex.join(command))diff --git a/tests/scripts/test_commit_bundle_entrypoints.py b/tests/scripts/test_commit_bundle_entrypoints.pyindex d7047ab0c94..522bef83f5d 100644--- a/tests/scripts/test_commit_bundle_entrypoints.py+++ b/tests/scripts/test_commit_bundle_entrypoints.py@@ -23,6 +23,8 @@ def test_desktop_build_reaches_the_managed_payload_with_commit_ref(tmp_path, monmonkeypatch.setenv("HERMES_PAYLOAD_TAG", "v9.9.9")monkeypatch.setenv("GITHUB_SHA", "b" * 40)monkeypatch.setenv("BUILD_NUMBER", "123")+ defaults = {"HERMES_GUEST_ONBOARDING": "1", "HERMES_DATA_DIR_SUFFIX": "magic-test"}+ monkeypatch.setenv("HERMES_BUNDLE_ENV_JSON", json.dumps(defaults))monkeypatch.setattr(desktop.shutil, "which", lambda name: name)monkeypatch.setattr(desktop, "npm_command", lambda node: [node, "npm-cli.js"])monkeypatch.setattr("scripts.build.windows_deps.prepare_windows_environment", lambda **kwargs: dict(kwargs["env"]))@@ -52,6 +54,7 @@ def test_desktop_build_reaches_the_managed_payload_with_commit_ref(tmp_path, monassert env["HERMES_BUILD_COMMIT"] == shaassert env["GITHUB_SHA"] == shaassert env["HERMES_PAYLOAD_VERSION"] == "0.1.2"+ assert json.loads(env["HERMES_BUNDLE_ENV_JSON"]) == defaultsif "scripts.bundles.stage" in argv:assert argv[argv.index("--ref") + 1] == shaassert "--tui" in argv and "--web" in argvdiff --git a/tests/scripts/test_release_build_commit.py b/tests/scripts/test_release_build_commit.pyindex c756ecab67e..9ce136243c5 100644--- a/tests/scripts/test_release_build_commit.py+++ b/tests/scripts/test_release_build_commit.py@@ -29,6 +29,7 @@ def fixture_repo(tmp_path):git(repo, 'push', '-q', 'origin', 'main')git(repo, 'remote', 'set-url', 'origin', 'https://github.com/fixture-owner/fixture-repo.git')for relative in ('scripts/release.py', 'scripts/releases/commit_build.py',+ 'scripts/releases/bundle_env.py','scripts/releases/r2.py', 'scripts/release-content-types.json','hermes_cli/__init__.py', 'hermes_cli/update_channel.py','hermes_cli/runtime_paths.py', 'hermes_constants.py'):@@ -109,6 +110,20 @@ def test_commit_build_cli_dispatches_only_the_resolved_remote_commit(tmp_path):assert git(repo, 'show-ref', '--heads', '--tags') == beforeassert git(upstream, 'rev-parse', 'refs/heads/main') == tip+ values = {'HERMES_GUEST_ONBOARDING': '1', 'HERMES_DATA_DIR_SUFFIX': 'magic-test',+ 'EMPTY': '', 'LITERAL': 'a=b "quote"\n$(not-a-command)'}+ flags = [part for key, value in values.items() for part in ('--bundle-env', f'{key}={value}')]+ result, calls = invoke('--build-commit', tip, '--publish', *flags)+ assert result.returncode == 0, result.stderr+ dispatch = next(call for call in calls if call[1:3] == ['workflow', 'run'])+ assert json.loads(next(field.split('=', 1)[1] for field in dispatch if field.startswith('bundle_env='))) == values+ for invalid in (['--bundle-env', 'MISSING'], ['--bundle-env', 'BAD-NAME=x'],+ ['--bundle-env', 'DUP=x', '--bundle-env', 'DUP=y']):+ result, calls = invoke('--build-commit', tip, '--publish', *invalid)+ assert result.returncode != 0 and not calls+ result, calls = invoke('--bundle-env', 'NAME=value')+ assert result.returncode == 2 and not calls+git(repo, 'checkout', '-qb', 'feature')(repo / 'feature').write_text('pushed feature', encoding='utf-8')git(repo, 'add', 'feature')@@ -156,7 +171,8 @@ def test_workflow_admission_checks_trust_before_publishing_outputs(tmp_path):'GITHUB_REF': 'refs/heads/main','GITHUB_WORKFLOW_REF': 'fixture-owner/fixture-repo/.github/workflows/desktop-bundled-release.yml@refs/heads/main','GITHUB_ACTOR': 'maintainer', 'GITHUB_TRIGGERING_ACTOR': 'maintainer',- 'GITHUB_OUTPUT': str(output), 'UPLOAD_RELEASE': 'false'}+ 'GITHUB_OUTPUT': str(output), 'UPLOAD_RELEASE': 'false',+ 'BUNDLE_ENV_JSON': '{"HERMES_GUEST_ONBOARDING":"1"}'}result, calls = invoke('admit', extra=env)assert result.returncode == 0, result.stderrassert dict(line.split('=', 1) for line in output.read_text(encoding='utf-8').splitlines()) == {@@ -167,7 +183,8 @@ def test_workflow_admission_checks_trust_before_publishing_outputs(tmp_path):('RELEASE_PHASE', 'candidate'), ('TERMUX_UPGRADE_FROM_TAG', 'v1.0.0'),('GITHUB_EVENT_NAME', 'workflow_call'), ('GITHUB_REF', 'refs/heads/other'),('GITHUB_WORKFLOW_REF', 'fixture-owner/fixture-repo/.github/workflows/other.yml@refs/heads/main'),- ('PROBE_PERMISSION', 'read')]:+ ('PROBE_PERMISSION', 'read'), ('BUNDLE_ENV_JSON', '[]'),+ ('BUNDLE_ENV_JSON', '{"X":1}')]:result, _ = invoke('admit', extra={**env, key: value})assert result.returncode != 0assert output.read_bytes() == original