Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

1. default to compiled agent installs on macos and linux (#2140)

ktdd760d310886
diff --git a/.github/workflows/build-binaries.yml b/.github/workflows/build-binaries.yml
index 6fd1ab47af..06b1148aa0 100644
--- a/.github/workflows/build-binaries.yml
+++ b/.github/workflows/build-binaries.yml
@@ -115,9 +115,13 @@ jobs:
echo "Production: $publish_production ${production_version:+v${production_version}}"
echo "Beta: $publish_beta ${beta_version:+v${beta_version}}"
+ standalone:
+ needs: release-context
+ uses: ./.github/workflows/standalone-binaries.yml
+
build:
runs-on: ubuntu-latest
- needs: release-context
+ needs: [release-context, standalone]
permissions:
contents: read
env:
@@ -148,6 +152,22 @@ jobs:
- name: Check
run: npm run check
+ - name: Download tested standalone archives
+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
+ with:
+ pattern: standalone-*
+ path: standalone-artifacts
+
+ - name: Verify and stage standalone binaries
+ run: |
+ for platform in darwin-arm64 darwin-x64 linux-arm64 linux-x64; do
+ source_dir="standalone-artifacts/standalone-$platform"
+ (cd "$source_dir" && sha256sum --check SHA256SUMS)
+ destination="packages/coding-agent/binaries/$platform"
+ mkdir -p "$destination"
+ tar -xzf "$source_dir"/*.tar.gz -C "$destination"
+ done
+
- name: Pack production release
if: env.PUBLISH_PRODUCTION == 'true'
env:
@@ -158,6 +178,7 @@ jobs:
--channel stable \
--version "$PRODUCTION_VERSION" \
--base-url "$PRIME_AGENT_DOWNLOAD_BASE_URL" \
+ --binary-dir packages/coding-agent/binaries \
--out-dir packages/coding-agent/release/production
- name: Pack beta release
@@ -170,6 +191,7 @@ jobs:
--channel beta \
--version "$BETA_VERSION" \
--base-url "$PRIME_AGENT_DOWNLOAD_BASE_URL" \
+ --binary-dir packages/coding-agent/binaries \
--out-dir packages/coding-agent/release/beta
- name: Smoke test installer with npm 12
@@ -202,7 +224,9 @@ jobs:
curl -fsS --retry 5 --retry-connrefused "$SMOKE_BASE_URL/releases/v$SMOKE_VERSION/SHA256SUMS"
export NPM_CONFIG_PREFIX="$SMOKE_ROOT/npm-prefix"
PATH="$NPM_CONFIG_PREFIX/bin:$PATH" \
+ PRIME_AGENT_ALLOW_INSECURE_HTTP_FOR_TESTS=1 \
PRIME_AGENT_BOOTSTRAP_KERNEL_ON_INSTALL=0 \
+ PRIME_AGENT_INSTALL_METHOD=node \
PRIME_AGENT_INSTALLER_PLAIN=1 \
sh /tmp/prime-agent-npm12-install.sh "$SMOKE_VERSION"
test -x "$NPM_CONFIG_PREFIX/bin/prime-agent"
@@ -301,7 +325,8 @@ jobs:
test -n "$R2_BUCKET"
test -n "$R2_ENDPOINT_URL"
- for artifact in "$PRODUCTION_DIR"/*.tgz; do
+ (cd "$PRODUCTION_DIR" && sha256sum --check SHA256SUMS)
+ for artifact in "$PRODUCTION_DIR"/*.tgz "$PRODUCTION_DIR"/*.tar.gz; do
aws s3 cp "$artifact" "s3://${R2_BUCKET}/${RELEASE_PREFIX}/$(basename "$artifact")" \
--endpoint-url "$R2_ENDPOINT_URL" \
--content-type application/gzip \
@@ -369,7 +394,8 @@ jobs:
test -n "$R2_BUCKET"
test -n "$R2_ENDPOINT_URL"
- for artifact in "$BETA_DIR"/*.tgz; do
+ (cd "$BETA_DIR" && sha256sum --check SHA256SUMS)
+ for artifact in "$BETA_DIR"/*.tgz "$BETA_DIR"/*.tar.gz; do
aws s3 cp "$artifact" "s3://${R2_BUCKET}/${RELEASE_PREFIX}/$(basename "$artifact")" \
--endpoint-url "$R2_ENDPOINT_URL" \
--content-type application/gzip \
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 17e520f3ac..7a27ed1529 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -157,16 +157,23 @@ jobs:
uv run --locked ruff format --check .
uv run --locked python -m unittest discover -s tests -v
+ standalone:
+ needs: trust
+ if: needs.trust.outputs.allowed == 'true'
+ uses: ./.github/workflows/standalone-binaries.yml
+
build-check-test:
name: build-check-test
if: always() && needs.trust.outputs.allowed == 'true'
- needs: [trust, build-check, test]
+ needs: [trust, build-check, test, standalone]
runs-on: ubuntu-latest
steps:
- name: Verify CI results
env:
BUILD_CHECK_RESULT: ${{ needs.build-check.result }}
TEST_RESULT: ${{ needs.test.result }}
+ STANDALONE_RESULT: ${{ needs.standalone.result }}
run: |
test "$BUILD_CHECK_RESULT" = success
test "$TEST_RESULT" = success
+ test "$STANDALONE_RESULT" = success
diff --git a/.github/workflows/standalone-binaries.yml b/.github/workflows/standalone-binaries.yml
new file mode 100644
index 0000000000..126749afe0
--- /dev/null
+++ b/.github/workflows/standalone-binaries.yml
@@ -0,0 +1,82 @@
+name: Standalone binaries
+
+on:
+ workflow_call:
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ name: Standalone (${{ matrix.platform }})
+ runs-on: ${{ matrix.runner }}
+ timeout-minutes: 20
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - platform: darwin-arm64
+ runner: macos-15
+ - platform: darwin-x64
+ runner: macos-15-intel
+ - platform: linux-arm64
+ runner: ubuntu-24.04-arm
+ - platform: linux-x64
+ runner: ubuntu-24.04
+ steps:
+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
+ with:
+ persist-credentials: false
+ path: source
+
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ node-version: '22'
+ package-manager-cache: false
+
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ with:
+ bun-version: '1.4.0'
+ no-cache: true
+
+ - uses: astral-sh/setup-uv@94527f2e458b27549849d47d273a16bec83a01e9 # v7
+ with:
+ version: '0.11.7'
+ enable-cache: false
+
+ - name: Install native development dependencies
+ if: runner.os == 'Linux'
+ run: |
+ sudo apt-get update
+ sudo apt-get install -y libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev
+
+ - name: Install locked npm dependencies
+ working-directory: source
+ run: npm ci
+
+ - name: Compile standalone application
+ working-directory: source/packages/coding-agent
+ run: npm run build:binary
+
+ - name: Assemble native archive
+ working-directory: source
+ run: |
+ version=$(node -p "require('./package.json').version")
+ node scripts/assemble-release-archives.mjs packages/coding-agent/binaries "$RUNNER_TEMP/standalone" "$version"
+ echo "PRIME_AGENT_TEST_ARCHIVE=$RUNNER_TEMP/standalone/prime-agent-$version-${{ matrix.platform }}.tar.gz" >> "$GITHUB_ENV"
+ echo "PRIME_AGENT_TEST_UV=$(command -v uv)" >> "$GITHUB_ENV"
+
+ - name: Remove the build paths from the test machine
+ run: mv "$GITHUB_WORKSPACE/source" "$RUNNER_TEMP/standalone-source"
+
+ - name: Test extracted application without JavaScript runtimes on PATH
+ working-directory: ${{ runner.temp }}/standalone-source/packages/coding-agent
+ run: npx tsx ../../node_modules/vitest/dist/cli.js --run test/compiled-artifact.test.ts test/native-installer.test.ts
+
+ - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
+ with:
+ name: standalone-${{ matrix.platform }}
+ path: |
+ ${{ runner.temp }}/standalone/*.tar.gz
+ ${{ runner.temp }}/standalone/SHA256SUMS
+ if-no-files-found: error
diff --git a/.gitignore b/.gitignore
index d8b22e91e6..e2a17696bf 100644
--- a/.gitignore
+++ b/.gitignore
@@ -34,6 +34,7 @@ out.jsonl
pi-*.html
out.html
packages/coding-agent/binaries/
+packages/coding-agent/release/
todo.md
plans/
.prime/agent/
diff --git a/README.md b/README.md
index 626a35c121..d059b87af0 100644
--- a/README.md
+++ b/README.md
@@ -56,10 +56,10 @@ Prime Agent combines a persistent Python control environment with durable harnes
Install the latest stable release on macOS or Linux:
```bash
-curl -fsSL https://app.primeintellect.ai/prime-agent/install.sh | sh
+curl --proto '=https' --proto-redir '=https' -fsSL https://app.primeintellect.ai/prime-agent/install.sh | sh
```
-The installer downloads a versioned release, verifies its SHA-256 checksum, installs the `prime-agent` command, and can prepare the Python runtime used by the agent.
+The installer requires HTTPS for release downloads, checks the selected archive against the release origin's SHA-256 inventory, installs the `prime-agent` command, and can prepare the Python runtime used by the agent. The checksum detects corruption or an inconsistent transfer; because the inventory and archive come from the same origin, HTTPS is the authenticity boundary.
Start Prime Agent from the repository or directory you want it to work in:
diff --git a/install.sh b/install.sh
index 9a4ae18ed7..1ec8300df2 100755
--- a/install.sh
+++ b/install.sh
@@ -57,13 +57,40 @@ prime_agent_screen_status=
prime_agent_screen_detail=
prime_agent_screen_question=
prime_agent_animation_frame=0
+prime_agent_native_stage=
+prime_agent_native_lock=
+prime_agent_allow_insecure_http=0
main() {
+ if [ "${1:-}" = --native-platform ]; then
+ prime_agent_native_platform
+ return
+ fi
+ case "${PRIME_AGENT_INSTALL_METHOD:-auto}" in
+ auto|binary|node) ;;
+ *) printf 'error: PRIME_AGENT_INSTALL_METHOD must be auto, binary or node.\n' >&2; exit 1 ;;
+ esac
+ if [ "${PRIME_AGENT_INSTALL_METHOD:-auto}" != node ]; then
+ if native_platform=$(prime_agent_native_platform); then
+ prime_agent_install_native "$native_platform" "$@"
+ return
+ fi
+ if [ "${PRIME_AGENT_INSTALL_METHOD:-auto}" = binary ]; then
+ printf 'error: no compatible compiled archive is available for this platform.\n' >&2
+ exit 1
+ fi
+ printf 'Using the Node installation for this platform.\n' >&2
+ fi
+ prime_agent_install_node "$@"
+}
+
+prime_agent_install_node() {
if [ "$prime_agent_base_url" = "$prime_agent_unconfigured_base_url" ]; then
printf 'error: installer download URL is not configured.\n' >&2
printf 'Set PRIME_AGENT_DOWNLOAD_BASE_URL or use the installer published by the release workflow.\n' >&2
exit 1
fi
+ prime_agent_validate_download_base_url
prime_agent_install_traps
prime_agent_init_screen
@@ -154,10 +181,50 @@ create_temp_dir() {
exit 1
}
+prime_agent_is_loopback_test_base_url() {
+ case "$1" in
+ http://127.0.0.1:*) ;;
+ *) return 1 ;;
+ esac
+ test_port=${1##*:}
+ case "$test_port" in ''|*[!0-9]*) return 1 ;; esac
+}
+
+prime_agent_validate_download_base_url() {
+ case "$prime_agent_base_url" in
+ https://*)
+ prime_agent_allow_insecure_http=0
+ ;;
+ http://*)
+ if [ "${PRIME_AGENT_ALLOW_INSECURE_HTTP_FOR_TESTS:-0}" = 1 ] &&
+ prime_agent_is_loopback_test_base_url "$prime_agent_base_url"; then
+ prime_agent_allow_insecure_http=1
+ return
+ fi
+ printf 'error: Prime Agent downloads require an HTTPS base URL.\n' >&2
+ printf 'Local loopback test feeds require PRIME_AGENT_ALLOW_INSECURE_HTTP_FOR_TESTS=1.\n' >&2
+ exit 1
+ ;;
+ *)
+ printf 'error: Prime Agent download base URL must use HTTPS.\n' >&2
+ exit 1
+ ;;
+ esac
+}
+
+prime_agent_curl_download() {
+ if [ "$prime_agent_allow_insecure_http" = 1 ]; then
+ curl --proto '=http,https' --proto-redir '=https' "$@"
+ else
+ curl --proto '=https' --proto-redir '=https' "$@"
+ fi
+}
+
prime_agent_install_traps() {
trap 'prime_agent_cleanup' EXIT
trap 'prime_agent_signal_cleanup 130' INT
trap 'prime_agent_signal_cleanup 143' TERM
+ trap 'prime_agent_signal_cleanup 129' HUP
}
prime_agent_cleanup() {
@@ -165,6 +232,7 @@ prime_agent_cleanup() {
if [ -n "${prime_agent_download_dir:-}" ] && [ -d "$prime_agent_download_dir" ]; then
rm -rf "$prime_agent_download_dir"
fi
+ prime_agent_native_cleanup
prime_agent_restore_terminal
return "$status"
}
@@ -958,7 +1026,7 @@ resolve_prime_agent_version() {
"Resolving latest release" \
"Resolving latest release" \
"Checking the $release_channel release channel." \
- curl -fsSL "$prime_agent_base_url/$release_channel" -o "$channel_path"; then
+ prime_agent_curl_download -fsSL "$prime_agent_base_url/$release_channel" -o "$channel_path"; then
rm -rf "$channel_dir"
printf 'error: could not resolve latest Prime Agent version from %s/%s\n' "$prime_agent_base_url" "$release_channel" >&2
exit 1
@@ -1188,7 +1256,7 @@ install_node_standalone() {
mkdir -p "$node_tmp_dir" "$node_base_dir"
printf 'Resolving Node.js binary for %s-%s\n' "$node_platform" "$node_arch"
- curl -fsSL "$node_dist_base/SHASUMS256.txt" -o "$node_tmp_dir/SHASUMS256.txt"
+ prime_agent_curl_download -fsSL "$node_dist_base/SHASUMS256.txt" -o "$node_tmp_dir/SHASUMS256.txt"
node_file=$(awk -v suffix="-$node_platform-$node_arch.tar.xz" '
index($2, "node-v") == 1 && length($2) >= length(suffix) && substr($2, length($2) - length(suffix) + 1) == suffix { print $2; exit }
' "$node_tmp_dir/SHASUMS256.txt")
@@ -1212,7 +1280,7 @@ install_node_standalone() {
esac
printf 'Downloading Node.js %s\n' "${node_file%.tar.xz}"
- curl -fsSL "$node_dist_base/$node_file" -o "$node_tmp_dir/$node_file"
+ prime_agent_curl_download -fsSL "$node_dist_base/$node_file" -o "$node_tmp_dir/$node_file"
verify_node_standalone_download "$node_tmp_dir" "$node_file"
ensure_node_standalone_extract_tools "$node_platform"
@@ -1469,13 +1537,13 @@ download_prime_agent_package() {
"Downloading checksums" \
"Downloading release checksums" \
"Prime Agent v$version" \
- curl -fsSL "$checksums_url" -o "$checksums_path"
+ prime_agent_curl_download -fsSL "$checksums_url" -o "$checksums_path"
prime_agent_run_quiet_with_animation \
"Downloading Prime Agent" \
"Downloading Prime Agent v$version" \
- "Fetching the verified package." \
- curl -fsSL "$tarball_url" -o "$tarball_path"
+ "Fetching the checksummed package." \
+ prime_agent_curl_download -fsSL "$tarball_url" -o "$tarball_path"
verify_prime_agent_package_checksum "$checksums_path" "$tarball_path"
}
@@ -1531,7 +1599,7 @@ confirm_install() {
if prime_agent_prompt_yes_no \
"Install Prime Agent v$version globally with npm?" \
- "Downloads the verified release and runs npm install -g." \
+ "Downloads the checksummed release and runs npm install -g." \
"Install? [Y/n]"; then
return 0
else
@@ -1638,4 +1706,274 @@ Finalizing npm install."
fi
}
+prime_agent_native_platform() {
+ case "$(uname -s)" in
+ Darwin)
+ native_os_version=$(sw_vers -productVersion) || return 1
+ case "${native_os_version%%.*}" in ''|*[!0-9]*) return 1 ;; esac
+ [ "${native_os_version%%.*}" -ge 13 ] || return 1
+ native_os=darwin
+ ;;
+ Linux)
+ native_libc=$(getconf GNU_LIBC_VERSION 2>/dev/null) || return 1
+ printf '%s\n' "$native_libc" | awk '$1 == "glibc" { split($2, v, "."); if (v[1] > 2 || (v[1] == 2 && v[2] >= 17)) ok=1 } END { exit !ok }' || return 1
+ native_os=linux
+ ;;
+ *) return 1 ;;
+ esac
+ case "$(uname -m)" in
+ arm64|aarch64) printf '%s-arm64' "$native_os" ;;
+ x86_64|amd64) printf '%s-x64' "$native_os" ;;
+ *) return 1 ;;
+ esac
+}
+
+prime_agent_native_cleanup() {
+ if [ -n "${prime_agent_native_activation_target:-}" ] && [ -n "${prime_agent_native_activation_previous:-}" ] &&
+ [ "$(readlink "$native_root/bin/prime-agent" 2>/dev/null || :)" = "$prime_agent_native_activation_target" ] &&
+ [ "$(readlink "$native_root/bin/previous" 2>/dev/null || :)" != "$prime_agent_native_activation_previous" ]; then
+ prime_agent_native_atomic_link "$prime_agent_native_activation_previous" "$native_root/bin/previous" ||
+ printf 'Could not finish retaining the previous release; recover it from %s/releases.\n' "$native_root" >&2
+ fi
+ prime_agent_native_activation_target=
+ prime_agent_native_activation_previous=
+ if [ -n "${prime_agent_native_stage:-}" ]; then
+ rm -rf "$prime_agent_native_stage"
+ prime_agent_native_stage=
+ fi
+ if [ -n "${prime_agent_native_lock:-}" ] && [ "$(cat "$prime_agent_native_lock/pid" 2>/dev/null || :)" = "$$" ]; then
+ rm -f "$prime_agent_native_lock/pid"
+ rmdir "$prime_agent_native_lock"
+ fi
+ prime_agent_native_lock=
+}
+
+prime_agent_native_prepare_root() {
+ native_root="${PRIME_AGENT_INSTALL_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/prime-agent}"
+ case "$native_root" in /*) ;; *) printf 'error: install directory must be absolute.\n' >&2; exit 1 ;; esac
+ mkdir -p "$native_root"
+ native_root=$(CDPATH= cd "$native_root" && pwd -P)
+ if [ -L "$native_root/.managed" ] || [ -L "$native_root/releases" ] || [ -L "$native_root/bin" ]; then
+ printf 'error: managed installation directories must not be symlinks.\n' >&2; exit 1
+ fi
+ if [ -e "$native_root/.managed" ]; then
+ [ "$(cat "$native_root/.managed")" = prime-agent-native-v1 ] || {
+ printf 'error: unrecognized installation owner in %s.\n' "$native_root" >&2; exit 1;
+ }
+ elif [ -n "$(ls -A "$native_root")" ]; then
+ printf 'error: refusing to take ownership of nonempty directory %s.\n' "$native_root" >&2
+ exit 1
+ fi
+ # Never steal a lock: even stale-lock recovery can race with another installer.
+ if ! mkdir "$native_root/.install-lock" 2>/dev/null; then
+ native_lock_pid=$(cat "$native_root/.install-lock/pid" 2>/dev/null || :)
+ printf 'error: installation is locked (pid %s). After confirming no installer is running, remove %s/.install-lock.\n' "$native_lock_pid" "$native_root" >&2
+ exit 1
+ fi
+ prime_agent_native_lock="$native_root/.install-lock"
+ printf '%s\n' "$$" >"$prime_agent_native_lock/pid"
+ printf 'prime-agent-native-v1\n' >"$native_root/.managed"
+ mkdir -p "$native_root/releases" "$native_root/bin"
+ for native_link in prime-agent previous; do
+ if [ -e "$native_root/bin/$native_link" ] || [ -L "$native_root/bin/$native_link" ]; then
+ [ -L "$native_root/bin/$native_link" ] && prime_agent_native_valid_target "$(readlink "$native_root/bin/$native_link")" || {
+ printf 'error: unrecognized managed command target.\n' >&2; exit 1;
+ }
+ fi
+ done
+ prime_agent_native_stage=$(mktemp -d "$native_root/.install.XXXXXX")
+ if [ "${PRIME_AGENT_EXPECTED_CURRENT+x}" = x ] && [ "$(readlink "$native_root/bin/prime-agent" 2>/dev/null || :)" != "$PRIME_AGENT_EXPECTED_CURRENT" ]; then
+ printf 'error: the active release changed; retry the update.\n' >&2; exit 1
+ fi
+}
+
+prime_agent_native_valid_target() {
+ case "$1" in ../releases/*/prime-agent) ;; *) return 1 ;; esac
+ native_target_name=${1#../releases/}
+ native_target_name=${native_target_name%/prime-agent}
+ case "$native_target_name" in ''|.|..|*[!0-9A-Za-z.-]*) return 1 ;; esac
+}
+
+prime_agent_native_check_public_link() {
+ native_public_bin="${PRIME_AGENT_BIN_DIR:-$HOME/.local/bin}"
+ case "$native_public_bin" in /*) ;; *) printf 'error: bin directory must be absolute.\n' >&2; exit 1 ;; esac
+ if [ "${PRIME_AGENT_INSTALL_LINK:-1}" = 0 ]; then return; fi
+ case "$prime_agent_cmd" in
+ ''|.|..|*/*) printf 'error: command name must be a basename.\n' >&2; exit 1 ;;
+ esac
+ if [ -e "$native_public_bin/$prime_agent_cmd" ] || [ -L "$native_public_bin/$prime_agent_cmd" ]; then
+ if [ ! -L "$native_public_bin/$prime_agent_cmd" ] || [ "$(readlink "$native_public_bin/$prime_agent_cmd")" != "$native_root/bin/prime-agent" ]; then
+ printf 'error: refusing to replace existing command %s/%s.\n' "$native_public_bin" "$prime_agent_cmd" >&2
+ printf 'Choose PRIME_AGENT_BIN_DIR or set PRIME_AGENT_INSTALL_LINK=0.\n' >&2
+ exit 1
+ fi
+ fi
+ mkdir -p "$native_public_bin"
+}
+
+prime_agent_native_validate_archive() {
+ LC_ALL=C tar -tzf "$native_archive" >"$prime_agent_native_stage/entries"
+ awk '
+ /^\// || /(^|\/)\.\.(\/|$)/ || /\\/ { bad=1 }
+ END { exit bad }
+ ' "$prime_agent_native_stage/entries" || { printf 'error: unsafe archive path.\n' >&2; exit 1; }
+ LC_ALL=C tar -tvzf "$native_archive" >"$prime_agent_native_stage/types"
+ awk 'substr($0, 1, 1) != "-" && substr($0, 1, 1) != "d" { bad=1 } END { exit bad }' \
+ "$prime_agent_native_stage/types" || { printf 'error: archive contains links or special files.\n' >&2; exit 1; }
+}
+
+prime_agent_native_atomic_link() {
+ native_link_stage=$(mktemp -d "$prime_agent_native_stage/link.XXXXXX")
+ ln -s "$1" "$native_link_stage/link"
+ # The destination is an executable link, never a directory link.
+ mv -f "$native_link_stage/link" "$2"
+ rmdir "$native_link_stage"
+}
+
+prime_agent_native_activate() {
+ prime_agent_native_activation_target="$1"
+ prime_agent_native_activation_previous="$2"
+ prime_agent_native_atomic_link "$1" "$native_root/bin/prime-agent"
+ if [ -n "$2" ] && [ "$1" != "$2" ]; then
+ prime_agent_native_atomic_link "$2" "$native_root/bin/previous"
+ fi
+ prime_agent_native_activation_target=
+ prime_agent_native_activation_previous=
+}
+
+prime_agent_release_is_node_only() {
+ awk -v file="$2" '
+ $2 ~ /\.tar\.gz$/ { compiled=1 }
+ $2 == file { count++; if (NF != 2 || length($1) != 64 || $1 ~ /[^0-9a-fA-F]/) invalid=1 }
+ END { exit compiled || invalid || count != 1 }
+ ' "$1"
+}
+
+prime_agent_install_native() {
+ native_platform="$1"
+ shift
+ if [ "$prime_agent_base_url" = "$prime_agent_unconfigured_base_url" ]; then
+ printf 'error: set PRIME_AGENT_DOWNLOAD_BASE_URL or use the published installer.\n' >&2; exit 1
+ fi
+ prime_agent_validate_download_base_url
+ prime_agent_install_traps
+ prime_agent_init_screen
+ native_version=$(resolve_prime_agent_version "$@")
+ printf '%s\n' "$native_version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$' || {
+ printf 'error: invalid native release version.\n' >&2; exit 1;
+ }
+ # Select the release format before touching native-owned installation paths.
+ prime_agent_download_dir=$(create_temp_dir)
+ native_file="prime-agent-$native_version-$native_platform.tar.gz"
+ native_checksums="$prime_agent_download_dir/SHA256SUMS"
+ prime_agent_run_quiet_with_animation "Downloading Prime Agent" "Downloading release checksums" "Prime Agent v$native_version" \
+ prime_agent_curl_download -fsSL --connect-timeout 10 --max-time 120 "$prime_agent_base_url/releases/v$native_version/SHA256SUMS" -o "$native_checksums"
+ awk -v file="$native_file" '$2 == file { count++; hash=$1; fields=NF } END { if (count != 1 || fields != 2 || length(hash) != 64 || hash ~ /[^0-9a-fA-F]/) exit 1; print tolower(hash) " " file }' \
+ "$native_checksums" >"$prime_agent_download_dir/selected.sha256" || {
+ if [ "${PRIME_AGENT_INSTALL_METHOD:-auto}" = auto ] &&
+ prime_agent_release_is_node_only "$native_checksums" "$prime_agent_package-$native_version.tgz"; then
+ rm -rf "$prime_agent_download_dir"
+ prime_agent_download_dir=
+ printf 'This release only provides npm packages; using the Node installation.\n' >&2
+ prime_agent_install_node "$native_version"
+ return
+ fi
+ printf 'error: expected one valid checksum for %s.\n' "$native_file" >&2; exit 1;
+ }
+ if [ "${PRIME_AGENT_INSTALLER_NONINTERACTIVE:-0}" != 1 ]; then
+ if prime_agent_prompt_yes_no "Install Prime Agent v$native_version?" "Downloads and verifies the compiled application." "Install? [Y/n]"; then
+ :
+ else
+ native_prompt_status=$?
+ [ "$native_prompt_status" = 2 ] || return 0
+ fi
+ fi
+ prime_agent_native_prepare_root
+ mv "$prime_agent_download_dir/selected.sha256" "$prime_agent_native_stage/selected.sha256"
+ rm -rf "$prime_agent_download_dir"
+ prime_agent_download_dir=
+ native_archive="$prime_agent_native_stage/$native_file"
+ prime_agent_run_quiet_with_animation "Downloading Prime Agent" "Downloading compiled Prime Agent" "$native_platform" \
+ prime_agent_curl_download -fsSL --connect-timeout 10 --max-time 300 "$prime_agent_base_url/releases/v$native_version/$native_file" -o "$native_archive"
+ if command -v sha256sum >/dev/null 2>&1; then native_checker=sha256sum; else native_checker=shasum; fi
+ prime_agent_run_quiet_with_animation "Verifying Prime Agent" "Verifying SHA-256" "Checking the downloaded archive." \
+ prime_agent_run_checksum_check "$prime_agent_native_stage" selected.sha256 "$native_checker"
+ prime_agent_native_validate_archive
+ mkdir "$prime_agent_native_stage/application"
+ tar -xzf "$native_archive" -C "$prime_agent_native_stage/application"
+ native_extracted="$prime_agent_native_stage/application"
+ for native_asset in prime-agent package.json install.sh prime-agent-runtime/pyproject.toml prime-agent-runtime/src/rlm/repl.py theme/prime.json export-html/template.html photon_rs_bg.wasm; do
+ [ -f "$native_extracted/$native_asset" ] || { printf 'error: missing archive asset: %s\n' "$native_asset" >&2; exit 1; }
+ done
+ if ! "$native_extracted/prime-agent" --version >"$prime_agent_native_stage/version" 2>"$prime_agent_native_stage/probe.log"; then
+ cat "$prime_agent_native_stage/probe.log" >&2
+ prime_agent_native_cleanup
+ if [ "${PRIME_AGENT_INSTALL_METHOD:-auto}" = auto ]; then
+ printf 'The compiled executable cannot run here; using the Node installation.\n' >&2
+ prime_agent_install_node "$native_version"
+ return
+ fi
+ printf 'error: the compiled executable cannot run on this machine.\n' >&2; exit 1
+ fi
+ [ "$(cat "$prime_agent_native_stage/version")" = "$native_version" ] || { printf 'error: archive version mismatch.\n' >&2; exit 1; }
+ "$native_extracted/prime-agent" --help >"$prime_agent_native_stage/help"
+ prime_agent_native_check_public_link
+ native_digest=$(awk '{ print $1 }' "$prime_agent_native_stage/selected.sha256")
+ native_release_name="$native_version-$native_platform-$native_digest"
+ native_destination="$native_root/releases/$native_release_name"
+ if [ -e "$native_destination" ] || [ -L "$native_destination" ]; then
+ # Reinstalls activate fresh assets without modifying a running release.
+ native_destination=$(mktemp -d "$native_destination.XXXXXX")
+ rmdir "$native_destination"
+ native_release_name=${native_destination##*/}
+ fi
+ printf '%s\n' "$native_digest" >"$native_extracted/.archive-sha256"
+ printf '%s\n' "$prime_agent_base_url" >"$native_extracted/.install-source"
+ mv "$native_extracted" "$native_destination"
+ if [ "${PRIME_AGENT_BOOTSTRAP_KERNEL_ON_INSTALL:-}" != 0 ]; then
+ confirm_kernel_runtime_setup
+ if [ "$prime_agent_bootstrap_kernel_on_install" = 1 ]; then
+ if ! prime_agent_run_quiet_with_animation "Preparing Python" "Preparing Python runtime" "Installing uv and Python dependencies." \
+ env PRIME_AGENT_INSTALL_UV=1 "$native_destination/prime-agent" --prime-agent-bootstrap; then
+ printf 'Python preparation failed; retry on first Python use.\n' >&2
+ fi
+ fi
+ fi
+ prime_agent_native_check_public_link
+ native_target="../releases/$native_release_name/prime-agent"
+ native_previous=
+ if [ -L "$native_root/bin/prime-agent" ]; then
+ native_previous=$(readlink "$native_root/bin/prime-agent")
+ fi
+ # A fresh public command must point to an already activated executable.
+ if [ -z "$native_previous" ]; then
+ prime_agent_native_activate "$native_target" ""
+ fi
+ if [ "${PRIME_AGENT_INSTALL_LINK:-1}" != 0 ] && [ ! -L "$native_public_bin/$prime_agent_cmd" ]; then
+ ln -sn "$native_root/bin/prime-agent" "$native_public_bin/$prime_agent_cmd"
+ fi
+ # Keep an existing release active if creating the public command loses a race.
+ if [ -n "$native_previous" ]; then
+ prime_agent_native_activate "$native_target" "$native_previous"
+ fi
+ if [ "${PRIME_AGENT_INSTALL_LINK:-1}" != 0 ]; then
+ prime_agent_native_configure_path || printf 'Add %s to PATH to run Prime Agent.\n' "$native_public_bin" >&2
+ fi
+ prime_agent_screen "Prime Agent installed" "" "Run it with: $prime_agent_cmd" ""
+ printf 'Installed Prime Agent %s at %s\n' "$native_version" "$native_root/bin/prime-agent"
+ prime_agent_native_cleanup
+}
+
+prime_agent_native_configure_path() {
+ case ":$prime_agent_original_path:" in *":$native_public_bin:"*) return ;; esac
+ native_path_line="export PATH=$(prime_agent_shell_quote "$native_public_bin"):\$PATH"
+ if native_profile=$(detect_shell_profile); then
+ if ! grep -Fx "$native_path_line" "$native_profile" >/dev/null 2>&1; then
+ mkdir -p "$(dirname "$native_profile")"
+ printf '\n# Prime Agent\n%s\n' "$native_path_line" >>"$native_profile"
+ fi
+ fi
+ printf 'For this shell, run: %s\n' "$native_path_line"
+}
+
main "$@"
diff --git a/packages/coding-agent/.changes/eng-6027-standalone-binaries.md b/packages/coding-agent/.changes/eng-6027-standalone-binaries.md
new file mode 100644
index 0000000000..2e0bc267e0
--- /dev/null
+++ b/packages/coding-agent/.changes/eng-6027-standalone-binaries.md
@@ -0,0 +1,11 @@
+- Added standalone macOS and Linux release archives that run without Node, npm, or Bun, including the Python runtime sources and application assets.
+- Changed new installations to prefer verified compiled releases on supported machines, with Node installation available for other systems.
+- Fixed reinstalling the same compiled release to restore its assets without modifying files used by existing processes.
+- Fixed installation to preserve a public command replaced by another installer during download.
+- Fixed terminal hangups leaving an installation lock behind.
+- Fixed installing older releases that only provide npm packages through the default installer, including when an npm command already exists.
+- Fixed interrupted compiled updates discarding the existing rollback target.
+- Fixed reinstalling or upgrading through the installer after an incompatible compiled executable falls back to Node.
+- Fixed interrupted fresh installations leaving a broken command.
+- Fixed installer downloads to require HTTPS and reject redirects to insecure protocols.
+- Changed macOS installation guidance to use the published installer until browser downloads are signed and notarized.
diff --git a/packages/coding-agent/docs/index.md b/packages/coding-agent/docs/index.md
index 96fb32160e..bc247cc954 100644
--- a/packages/coding-agent/docs/index.md
+++ b/packages/coding-agent/docs/index.md
@@ -7,7 +7,7 @@ Prime Agent is an RLM-native coding and research harness built around a persiste
Install the latest stable release on Linux or macOS:
```bash
-curl -fsSL https://app.primeintellect.ai/prime-agent/install.sh | sh
+curl --proto '=https' --proto-redir '=https' -fsSL https://app.primeintellect.ai/prime-agent/install.sh | sh
```
Then run it in a project directory:
diff --git a/packages/coding-agent/docs/quickstart.md b/packages/coding-agent/docs/quickstart.md
index 5125a504f1..3026938e01 100644
--- a/packages/coding-agent/docs/quickstart.md
+++ b/packages/coding-agent/docs/quickstart.md
@@ -7,13 +7,13 @@ This page gets you from install to a useful first Prime Agent session.
Install the latest stable release on Linux or macOS:
```bash
-curl -fsSL https://app.primeintellect.ai/prime-agent/install.sh | sh
+curl --proto '=https' --proto-redir '=https' -fsSL https://app.primeintellect.ai/prime-agent/install.sh | sh
```
To try the latest beta built from `main`:
```bash
-curl -fsSL https://app.primeintellect.ai/prime-agent/install.sh | sh -s -- beta
+curl --proto '=https' --proto-redir '=https' -fsSL https://app.primeintellect.ai/prime-agent/install.sh | sh -s -- beta
```
Both commands fetch versioned Prime Agent release artifacts and install the `prime-agent` command. The inherited npm workspace identifiers in the source tree are not the public install path.
diff --git a/packages/coding-agent/docs/standalone-binaries.md b/packages/coding-agent/docs/standalone-binaries.md
new file mode 100644
index 0000000000..515bc727ba
--- /dev/null
+++ b/packages/coding-agent/docs/standalone-binaries.md
@@ -0,0 +1,89 @@
+# Standalone binaries
+
+The macOS and Linux release archives contain `prime-agent` and its support files. Normal application execution does not require Node, npm, or Bun. Keep the archive contents together: moving only the executable breaks asset and Python runtime discovery. Linux archives target glibc; Alpine/musl and Windows are outside this distribution.
+
+On macOS, use the published installer:
+
+```sh
+curl --proto '=https' --proto-redir '=https' -fsSL https://app.primeintellect.ai/prime-agent/install.sh | sh
+```
+
+The current macOS archives are not Developer ID signed or notarized. A browser-downloaded archive may retain quarantine metadata and be blocked by Gatekeeper, so manual macOS archive installation is not supported yet. Do not bypass Gatekeeper; use the installer until signed and notarized downloads are available.
+
+On Linux, download `prime-agent-<version>-<platform>.tar.gz` and `SHA256SUMS` over HTTPS from the same release. Platforms are `linux-arm64` and `linux-x64`. Check the selected archive's SHA-256 against that inventory, extract it into its own directory, and run `./prime-agent --help`.
+
+The Python tool uses the existing managed CPython setup. Its first use requires uv and network access to install Python and Python dependencies. The archive includes the matching `prime-agent-runtime` sources and built-in Python skills. It contains no prebuilt virtual environment or `node_modules` directory. External tools and extension-specific dependencies retain their own requirements.
+
+On Intel macOS, the current `cryptography` dependency has no compatible wheel and is built from source during Python setup. This also requires Xcode Command Line Tools, Rust, and OpenSSL development libraries; see the [cryptography build requirements](https://cryptography.io/en/stable/installation/#building-cryptography-on-macos). These Python dependency requirements also apply to the existing Node distribution. Shipping Python dependency wheels is separate work.
+
+## Build
+
+Development continues to use Node, npm, `package-lock.json`, TypeScript declarations/checks, and Vitest. Install locked dependencies with `npm ci`. Install Bun **1.4.0** separately as the binary compiler, or point `BUN_BINARY` at that version's executable.
+
+From `packages/coding-agent`:
+
+```sh
+npm run build:binary
+npm run build:binary -- --platform all
+```
+
+The first command builds the native platform; the second cross-compiles all four targets. A single target can also be selected with `--platform linux-arm64`. Both commands compile the workspace TypeScript packages using the committed model catalog, then bundle the existing Bun CLI entry. They do not install dependencies or change the lockfile. Output goes to `packages/coding-agent/binaries/<platform>/`.
+
+Assemble local archives from the repository root:
+
+```sh
+node scripts/assemble-release-archives.mjs packages/coding-agent/binaries /tmp/prime-agent-archives 0.9.4
+```
+
+This creates platform tarballs, `SHA256SUMS`, and `binaries.json`. The version argument sets the archive's package metadata without changing the checkout or the compiled executable. Each archive has a flat layout:
+
+```text
+prime-agent
+install.sh
+package.json
+LICENSE, README.md, CHANGELOG.md
+prime-agent-runtime/
+skills/
+theme/
+assets/
+export-html/
+docs/
+examples/
+photon_rs_bg.wasm
+```
+
+## Validation and release integration
+
+From `packages/coding-agent`, run the artifact tests against an archive for the host platform:
+
+```sh
+PRIME_AGENT_TEST_ARCHIVE=/tmp/prime-agent-archives/prime-agent-0.9.4-darwin-arm64.tar.gz \
+PRIME_AGENT_TEST_UV="$(command -v uv)" \
+npx tsx ../../node_modules/vitest/dist/cli.js --run test/compiled-artifact.test.ts
+```
+
+The suite extracts outside the checkout, creates isolated homes and a PATH without JavaScript runtimes, and exercises provider requests against a local HTTP/2 server, extension and skill loading, Photon image resizing, HTML export, RPC, managed Python, and daemon shutdown. It never uses real provider credentials. Python bootstrap requires network access. Other tests skip this suite when `PRIME_AGENT_TEST_ARCHIVE` is unset.
+
+CI builds and tests natively on all four target platforms. Before testing, it moves the build checkout so absolute build-time paths and its original `node_modules` cannot satisfy missing runtime files. Cross-compilation alone is not native execution evidence.
+
+The release workflow consumes those tested artifacts, adds the stable or beta package version, and includes all four archives in the existing aggregate `SHA256SUMS`. Existing npm tarballs and manifest fields remain. The `binaries` array adds `{ platform, file, sha256 }` entries; each file lives under `releases/v<version>/`. Stable/beta pointers retain their existing routing. Production and beta uploads use the same archives for GitHub and R2.
+
+## Installation
+
+The published installer defaults to the compiled archive on macOS 13+ and glibc Linux, on ARM64 or x64. It requires an HTTPS release base, allows redirects only to HTTPS, checks the exact release checksum, rejects unsafe archive entries, validates required assets, and runs the executable before activating it. Machines outside those targets use the existing Node installer; an executable that cannot run also falls back to Node. A failed checksum never triggers a fallback.
+
+The archive and `SHA256SUMS` inventory are served by the same release origin. The checksum detects corruption or inconsistent content but is not an independent signature and does not protect against a compromised origin; HTTPS authentication of the configured origin is the trust boundary.
+
+Pinning a release whose checksum inventory only advertises npm packages uses the checksummed Node installer. This preserves installation of releases published before compiled archives existed without requiring newer release metadata. Missing or invalid compiled checksums, an incomplete compiled release, and failed archive downloads remain errors; `binary` mode never falls back.
+
+Set `PRIME_AGENT_INSTALL_METHOD=node` to explicitly keep the Node installation, or `binary` to require the compiled application. `PRIME_AGENT_INSTALL_DIR` overrides the managed root (default `$XDG_DATA_HOME/prime-agent` or `~/.local/share/prime-agent`); `PRIME_AGENT_BIN_DIR` overrides the public command directory (default `~/.local/bin`). Both must be absolute. Existing unrelated commands are never replaced. `PRIME_AGENT_INSTALL_LINK=0` installs without a public link.
+
+Each release keeps its executable and assets together under `releases/`. The stable `bin/prime-agent` link changes only after validation, and `bin/previous` retains the earlier release. The installer serializes changes with `.install-lock`; normal interruption cleans up the lock. After a forced kill, confirm its recorded process is no longer running before removing the stale lock. User data remains in `~/.prime/agent`.
+
+Reinstalling the same archive creates a fresh release directory with a unique suffix, so it can repair missing or changed assets without modifying files used by existing processes. Old release directories are retained; there is no automatic garbage collection yet.
+
+Activation replaces the current launcher before refreshing the previous launcher. Normal interruption finishes retaining the replaced release during cleanup. A forced kill between those operations keeps the earlier rollback target intact; it may therefore point to an older retained release rather than the release that was just replaced. A forced kill still requires confirming and clearing the stale installation lock.
+
+The installer still shows download and verification progress and can prepare Python. Compilation removes JavaScript dependency installation; Python and external tools still need preparation. Set `PRIME_AGENT_BOOTSTRAP_KERNEL_ON_INSTALL=0` to defer Python setup.
+
+Existing npm installations and the in-app updater are handled by the next layers of the rollout. Homebrew packaging remains separate work.
diff --git a/packages/coding-agent/package.json b/packages/coding-agent/package.json
index 15593eb428..d51db75cdd 100644
--- a/packages/coding-agent/package.json
+++ b/packages/coding-agent/package.json
@@ -34,9 +34,9 @@
"clean": "shx rm -rf dist",
"dev": "tsgo -p tsconfig.build.json --watch --preserveWatchOutput",
"build": "tsgo -p tsconfig.build.json && shx chmod +x dist/cli.js && npm run copy-assets && npm run bundle",
- "build:binary": "npm --prefix ../tui run build && npm --prefix ../ai run build && npm --prefix ../agent run build && npm run build && bun build --compile ./dist/bun/cli.js --outfile dist/pi && npm run copy-binary-assets",
+ "build:binary": "node scripts/build-binary.mjs",
"copy-assets": "shx mkdir -p dist/modes/interactive/theme && shx cp src/modes/interactive/theme/*.json dist/modes/interactive/theme/ && shx mkdir -p dist/modes/interactive/assets && shx cp src/modes/interactive/assets/*.png dist/modes/interactive/assets/ && shx mkdir -p dist/core/export-html/vendor && shx cp src/core/export-html/template.html src/core/export-html/template.css src/core/export-html/template.js dist/core/export-html/ && shx cp src/core/export-html/vendor/*.js dist/core/export-html/vendor/ && shx rm -rf dist/prime-agent-runtime && shx cp -r ../../prime-agent-runtime dist/prime-agent-runtime && shx rm -rf dist/skills && shx cp -r skills dist/skills",
- "copy-binary-assets": "shx cp package.json dist/ && shx cp README.md dist/ && shx cp CHANGELOG.md dist/ && shx mkdir -p dist/theme && shx cp src/modes/interactive/theme/*.json dist/theme/ && shx mkdir -p dist/assets && shx cp src/modes/interactive/assets/*.png dist/assets/ && shx mkdir -p dist/export-html/vendor && shx cp src/core/export-html/template.html dist/export-html/ && shx cp src/core/export-html/vendor/*.js dist/export-html/vendor/ && shx cp -r docs dist/ && shx cp -r examples dist/ && shx cp ../../node_modules/@silvia-odwyer/photon-node/photon_rs_bg.wasm dist/ && shx rm -rf dist/skills && shx cp -r skills dist/skills",
+ "copy-binary-assets": "node scripts/copy-binary-assets.mjs",
"test": "vitest --run",
"test:ci": "tsx src/core/kernel/bootstrap-cli.ts && vitest --run --exclude test/daemon-supervisor-process.test.ts",
"test:process": "vitest --run test/daemon-supervisor-process.test.ts",
diff --git a/packages/coding-agent/scripts/build-binary.mjs b/packages/coding-agent/scripts/build-binary.mjs
new file mode 100644
index 0000000000..0dc12d1131
--- /dev/null
+++ b/packages/coding-agent/scripts/build-binary.mjs
@@ -0,0 +1,67 @@
+#!/usr/bin/env node
+import { execFileSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, renameSync, rmSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { copyBinaryAssets, validateBinaryAssets } from "./copy-binary-assets.mjs";
+
+const root = resolve(dirname(fileURLToPath(import.meta.url)), "../../..");
+const packageDir = join(root, "packages/coding-agent");
+const platforms = ["darwin-arm64", "darwin-x64", "linux-arm64", "linux-x64"];
+const args = process.argv.slice(2);
+const platform = args.length === 0 ? `${process.platform}-${process.arch}` : args[1];
+if (args.length !== 0 && (args.length !== 2 || args[0] !== "--platform")) {
+ throw new Error("Usage: npm run build:binary -- [--platform darwin-arm64|darwin-x64|linux-arm64|linux-x64|all]");
+}
+if (platform !== "all" && !platforms.includes(platform)) throw new Error(`Unsupported binary platform: ${platform}`);
+
+const bun = process.env.BUN_BINARY || "bun";
+const bunVersion = execFileSync(bun, ["--version"], { encoding: "utf8" }).trim();
+if (bunVersion !== "1.4.0") throw new Error(`Binary compilation requires Bun 1.4.0; found ${bunVersion}`);
+
+// Emit workspace JavaScript and declarations using the committed model catalog.
+for (const name of ["tui", "ai", "agent", "coding-agent"]) {
+ execFileSync(join(root, "node_modules/.bin/tsgo"), ["-p", `packages/${name}/tsconfig.build.json`], {
+ cwd: root,
+ stdio: "inherit",
+ });
+}
+
+const buildId = execFileSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8" }).trim();
+const outputRoot = join(packageDir, "binaries");
+mkdirSync(outputRoot, { recursive: true });
+for (const target of platform === "all" ? platforms : [platform]) {
+ const staging = mkdtempSync(join(outputRoot, ".build-"));
+ try {
+ execFileSync(
+ bun,
+ [
+ "build",
+ "--compile",
+ "--minify",
+ "--keep-names",
+ "--bytecode",
+ "--format=esm",
+ "--external",
+ "koffi",
+ "--no-compile-autoload-dotenv",
+ "--no-compile-autoload-bunfig",
+ "--define",
+ `__PI_BUILD_ID__=${JSON.stringify(buildId)}`,
+ `--target=bun-${target}`,
+ "./dist/bun/cli.js",
+ "--outfile",
+ join(staging, "prime-agent"),
+ ],
+ { cwd: packageDir, stdio: "inherit" },
+ );
+ copyBinaryAssets(staging);
+ validateBinaryAssets(staging);
+ const destination = join(outputRoot, target);
+ rmSync(destination, { recursive: true, force: true });
+ renameSync(staging, destination);
+ console.log(`Created ${destination}`);
+ } finally {
+ rmSync(staging, { recursive: true, force: true });
+ }
+}
diff --git a/packages/coding-agent/scripts/copy-binary-assets.mjs b/packages/coding-agent/scripts/copy-binary-assets.mjs
new file mode 100644
index 0000000000..d5c1a320c0
--- /dev/null
+++ b/packages/coding-agent/scripts/copy-binary-assets.mjs
@@ -0,0 +1,108 @@
+import { cpSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { dirname, join, relative, resolve } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const packageDir = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+const root = resolve(packageDir, "../..");
+const excluded = new Set([
+ "node_modules",
+ ".venv",
+ "__pycache__",
+ ".pytest_cache",
+ ".ruff_cache",
+ ".mypy_cache",
+ ".git",
+ ".DS_Store",
+]);
+
+export const binaryAssets = [
+ "package.json",
+ "install.sh",
+ "README.md",
+ "CHANGELOG.md",
+ "LICENSE",
+ "prime-agent-runtime",
+ "skills",
+ "theme",
+ "assets",
+ "export-html",
+ "docs",
+ "examples",
+ "photon_rs_bg.wasm",
+];
+
+function includeBinaryAsset(source) {
+ return !source
+ .split(/[\\/]/)
+ .some((part) => excluded.has(part) || part.endsWith(".pyc") || part.endsWith(".egg-info"));
+}
+
+export function copyBinaryAssets(destination) {
+ mkdirSync(destination, { recursive: true });
+ const sources = {
+ "package.json": join(packageDir, "package.json"),
+ "install.sh": join(root, "install.sh"),
+ "README.md": join(packageDir, "README.md"),
+ "CHANGELOG.md": join(packageDir, "CHANGELOG.md"),
+ LICENSE: join(root, "LICENSE"),
+ "prime-agent-runtime": join(root, "prime-agent-runtime"),
+ skills: join(packageDir, "skills"),
+ theme: join(packageDir, "src/modes/interactive/theme"),
+ assets: join(packageDir, "src/modes/interactive/assets"),
+ "export-html": join(packageDir, "src/core/export-html"),
+ docs: join(packageDir, "docs"),
+ examples: join(packageDir, "examples"),
+ "photon_rs_bg.wasm": join(root, "node_modules/@silvia-odwyer/photon-node/photon_rs_bg.wasm"),
+ };
+ for (const [name, source] of Object.entries(sources)) {
+ const target = join(destination, name);
+ rmSync(target, { recursive: true, force: true });
+ cpSync(source, target, {
+ recursive: true,
+ filter: (path) => {
+ if (!includeBinaryAsset(relative(source, path))) return false;
+ if (lstatSync(path).isSymbolicLink()) throw new Error(`Unexpected symlink in binary assets: ${path}`);
+ if (name === "theme") return path === source || path.endsWith(".json");
+ if (name === "export-html") return !path.endsWith(".ts");
+ return true;
+ },
+ });
+ }
+}
+
+export function validateBinaryAssets(directory) {
+ for (const name of binaryAssets) lstatSync(join(directory, name));
+ for (const name of [
+ "prime-agent-runtime/pyproject.toml",
+ "prime-agent-runtime/src/rlm/repl.py",
+ "theme/prime.json",
+ "theme/dark.json",
+ "theme/light.json",
+ "export-html/template.html",
+ "export-html/template.css",
+ "export-html/template.js",
+ "export-html/vendor/marked.min.js",
+ "export-html/vendor/highlight.min.js",
+ ]) {
+ if (!lstatSync(join(directory, name)).isFile()) throw new Error(`Missing binary asset: ${name}`);
+ }
+ function visit(path) {
+ const stat = lstatSync(path);
+ if (stat.isSymbolicLink() || !includeBinaryAsset(relative(directory, path))) {
+ throw new Error(`Unexpected binary asset: ${path}`);
+ }
+ if (stat.isDirectory()) for (const name of readdirSync(path)) visit(join(path, name));
+ }
+ visit(directory);
+}
+
+export function setBinaryVersion(directory, version) {
+ const path = join(directory, "package.json");
+ const metadata = JSON.parse(readFileSync(path, "utf8"));
+ metadata.version = version;
+ writeFileSync(path, `${JSON.stringify(metadata, null, 2)}\n`);
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
+ copyBinaryAssets(resolve(process.argv[2] ?? join(packageDir, "dist")));
+}
diff --git a/packages/coding-agent/src/cli-main.ts b/packages/coding-agent/src/cli-main.ts
index c598dc7b7d..5fcdd8b4b7 100644
--- a/packages/coding-agent/src/cli-main.ts
+++ b/packages/coding-agent/src/cli-main.ts
@@ -6,6 +6,7 @@ import {
isOwnedSessionWorkerProcess,
maybeRunOwnedSessionWorkerFrontend,
} from "./cli/owned-session-worker.js";
+import { runRuntimeBootstrap } from "./cli/runtime-bootstrap.js";
import { APP_NAME } from "./config.js";
export async function runCli(): Promise<void> {
@@ -22,6 +23,17 @@ export async function runCli(): Promise<void> {
installOwnedSessionWorkerOwnerWatch();
const args = process.argv.slice(2);
+ if (args.length === 1 && args[0] === "--prime-agent-bootstrap") {
+ try {
+ await runRuntimeBootstrap();
+ } catch (error) {
+ console.error(error instanceof Error ? error.message : String(error));
+ process.exitCode = 1;
+ } finally {
+ closeOwnedSessionWorkerOwnerWatch();
+ }
+ return;
+ }
const handledByOwnedWorker = await maybeRunOwnedSessionWorkerFrontend(args);
if (!handledByOwnedWorker) {
if (!isOwnedSessionWorkerProcess()) {
diff --git a/packages/coding-agent/src/cli/runtime-bootstrap.ts b/packages/coding-agent/src/cli/runtime-bootstrap.ts
new file mode 100644
index 0000000000..0fde97dafa
--- /dev/null
+++ b/packages/coding-agent/src/cli/runtime-bootstrap.ts
@@ -0,0 +1,8 @@
+import { ensureKernelPython } from "../core/kernel/bootstrap.js";
+import { ensureTool } from "../utils/tools-manager.js";
+
+export async function runRuntimeBootstrap(): Promise<void> {
+ await Promise.all([ensureTool("fd", true), ensureTool("rg", true)]);
+ const python = await ensureKernelPython();
+ console.log(`kernel python: ${python}`);
+}
diff --git a/packages/coding-agent/src/core/kernel/bootstrap.ts b/packages/coding-agent/src/core/kernel/bootstrap.ts
index 460512f5f6..bd9921caf3 100644
--- a/packages/coding-agent/src/core/kernel/bootstrap.ts
+++ b/packages/coding-agent/src/core/kernel/bootstrap.ts
@@ -686,12 +686,10 @@ async function writeBootstrapVersion(
function runtimeCandidateDirs(): string[] {
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
- // dist/prime-agent-runtime is listed first deliberately: it is the only path stable
- // across every shipped layout (dist/, dist/bundle/, bun), where import.meta.url-relative
- // resolution breaks. `npm run build` rebuilds it from live source (copy-assets does
- // rm -rf + cp), so the staleness hash still refreshes on every build. The relative
- // paths below cover running from source (tsx) where dist/ hasn't been built.
+ // Compiled executables use a flat sidecar layout; Node packages keep sources in dist/.
+ // Resolve both from the physical package directory, outside Bun's virtual filesystem.
return [
+ path.join(getPackageDir(), "prime-agent-runtime"),
path.join(getPackageDir(), "dist", "prime-agent-runtime"),
path.resolve(moduleDir, "..", "..", "prime-agent-runtime"),
path.resolve(moduleDir, "..", "..", "..", "..", "..", "prime-agent-runtime"),
diff --git a/packages/coding-agent/test/binary-runtime-source.test.ts b/packages/coding-agent/test/binary-runtime-source.test.ts
new file mode 100644
index 0000000000..de62e068fb
--- /dev/null
+++ b/packages/coding-agent/test/binary-runtime-source.test.ts
@@ -0,0 +1,30 @@
+import { createHash } from "node:crypto";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, expect, it, vi } from "vitest";
+import { resolveRuntimeIdentity } from "../src/core/kernel/bootstrap.js";
+
+let directory: string | undefined;
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ if (directory) rmSync(directory, { recursive: true, force: true });
+});
+
+it("resolves and fingerprints the Python source beside a standalone executable", async () => {
+ directory = mkdtempSync(join(tmpdir(), "prime-binary-runtime-"));
+ vi.stubEnv("PI_PACKAGE_DIR", directory);
+ const source = join(directory, "prime-agent-runtime");
+ mkdirSync(join(source, "src/rlm"), { recursive: true });
+ const files = { "pyproject.toml": '[project]\nname = "prime-agent-runtime"\n', "src/rlm/repl.py": "VALUE = 1\n" };
+ const expected = createHash("sha256");
+ for (const [name, content] of Object.entries(files)) {
+ writeFileSync(join(source, name), content);
+ expected.update(name).update("\0").update(content).update("\0");
+ }
+ const initial = await resolveRuntimeIdentity();
+ expect(initial).toBe(`sha256:${expected.digest("hex")}`);
+ writeFileSync(join(source, "src/rlm/repl.py"), "VALUE = 2\n");
+ expect(await resolveRuntimeIdentity()).not.toBe(initial);
+});
diff --git a/packages/coding-agent/test/compiled-artifact.test.ts b/packages/coding-agent/test/compiled-artifact.test.ts
new file mode 100644
index 0000000000..dd9d5a2d8f
--- /dev/null
+++ b/packages/coding-agent/test/compiled-artifact.test.ts
@@ -0,0 +1,344 @@
+import { type ChildProcess, execFileSync, spawn } from "node:child_process";
+import { createHash } from "node:crypto";
+import {
+ copyFileSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ realpathSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from "node:fs";
+import { createServer } from "node:http2";
+import { tmpdir } from "node:os";
+import { basename, dirname, join, resolve } from "node:path";
+import { deflateSync } from "node:zlib";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { DaemonClient } from "../src/modes/daemon/daemon-client.js";
+
+const archive = process.env.PRIME_AGENT_TEST_ARCHIVE;
+const uv = process.env.PRIME_AGENT_TEST_UV;
+const children = new Set<ChildProcess>();
+let root = "";
+let extracted = "";
+let binary = "";
+let home = "";
+let cwd = "";
+let socket = "";
+let environment: NodeJS.ProcessEnv;
+
+async function run(args: string[], extraEnv: NodeJS.ProcessEnv = {}, timeout = 30000, input?: string) {
+ const child = spawn(binary, args, { cwd, env: { ...environment, ...extraEnv }, stdio: ["pipe", "pipe", "pipe"] });
+ children.add(child);
+ let stdout = "";
+ let stderr = "";
+ child.stdout.on("data", (chunk) => {
+ stdout += chunk.toString();
+ });
+ child.stderr.on("data", (chunk) => {
+ stderr += chunk.toString();
+ });
+ child.stdin.end(input);
+ return await new Promise<{ code: number | null; stdout: string; stderr: string }>((done, reject) => {
+ const timer = setTimeout(() => {
+ child.kill("SIGKILL");
+ reject(new Error(`Artifact timed out: ${args.join(" ")}\n${stderr}`));
+ }, timeout);
+ child.once("error", (error) => {
+ clearTimeout(timer);
+ reject(error);
+ });
+ child.once("close", (code) => {
+ clearTimeout(timer);
+ children.delete(child);
+ done({ code, stdout, stderr });
+ });
+ });
+}
+
+function sessionArgs(): string[] {
+ return [
+ "--offline",
+ "--daemon-socket",
+ socket,
+ "--no-context-files",
+ "--no-extensions",
+ "-e",
+ join(cwd, "extension.ts"),
+ "--provider",
+ "artifact-faux",
+ "--model",
+ "artifact",
+ ];
+}
+
+function crc32(buffer: Buffer): number {
+ let crc = 0xffffffff;
+ for (const byte of buffer) {
+ crc ^= byte;
+ for (let i = 0; i < 8; i++) crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0);
+ }
+ return (crc ^ 0xffffffff) >>> 0;
+}
+
+function pngChunk(type: string, data: Buffer): Buffer {
+ const length = Buffer.alloc(4);
+ length.writeUInt32BE(data.length);
+ const content = Buffer.concat([Buffer.from(type), data]);
+ const crc = Buffer.alloc(4);
+ crc.writeUInt32BE(crc32(content));
+ return Buffer.concat([length, content, crc]);
+}
+
+describe.skipIf(!archive)("extracted standalone archive", () => {
+ beforeAll(() => {
+ root = realpathSync(mkdtempSync(join(process.platform === "darwin" ? "/tmp" : tmpdir(), "pa-bin-")));
+ extracted = join(root, "extracted app");
+ mkdirSync(extracted);
+ execFileSync("tar", ["-xzf", resolve(archive!), "-C", extracted]);
+ binary = join(extracted, "prime-agent");
+ const bin = join(root, "bin");
+ mkdirSync(bin);
+ for (const command of [
+ "sh",
+ "bash",
+ "ps",
+ "kill",
+ "env",
+ "uname",
+ "which",
+ "cat",
+ "mkdir",
+ "rm",
+ "ls",
+ "sleep",
+ "cc",
+ "clang",
+ "ld",
+ "ar",
+ "ranlib",
+ "xcrun",
+ "install_name_tool",
+ ]) {
+ const source = ["/bin", "/usr/bin"].map((path) => join(path, command)).find(existsSync);
+ if (source) symlinkSync(source, join(bin, command));
+ }
+ if (uv) {
+ symlinkSync(resolve(uv), join(bin, "uv-real"));
+ writeFileSync(join(bin, "uv"), `#!/bin/sh\nexec "\${0%/*}/uv-real" "$@" 2>> "$HOME/uv.log"\n`, {
+ mode: 0o755,
+ });
+ }
+ });
+ beforeEach(() => {
+ home = mkdtempSync(join(root, "home-"));
+ cwd = join(home, "project with spaces");
+ mkdirSync(cwd);
+ socket = join(home, "d.sock");
+ environment = {
+ HOME: home,
+ PATH: join(root, "bin"),
+ TMPDIR: root,
+ SHELL: "/bin/sh",
+ DO_NOT_TRACK: "1",
+ PRIME_AGENT_CODING_AGENT_DIR: join(home, "agent"),
+ PRIME_AGENT_INSTALL_UV: "0",
+ UV_CACHE_DIR: join(root, "uv-cache"),
+ UV_PYTHON_INSTALL_DIR: join(root, "python"),
+ };
+ mkdirSync(environment.PRIME_AGENT_CODING_AGENT_DIR!);
+ writeFileSync(
+ join(environment.PRIME_AGENT_CODING_AGENT_DIR!, "settings.json"),
+ JSON.stringify({ retry: { enabled: false } }),
+ );
+ copyFileSync(resolve(__dirname, "fixtures/compiled-artifact-extension.ts"), join(cwd, "extension.ts"));
+ });
+ afterEach(async () => {
+ for (const child of children) child.kill("SIGTERM");
+ const client = new DaemonClient(socket);
+ try {
+ await client.connect(1000);
+ const hello = await client.waitForHello();
+ await client.request({ type: "shutdown", force: true });
+ if (hello.supervisorPid) {
+ await expect
+ .poll(
+ () => {
+ try {
+ process.kill(hello.supervisorPid!, 0);
+ return false;
+ } catch {
+ return true;
+ }
+ },
+ { timeout: 10000 },
+ )
+ .toBe(true);
+ }
+ } catch (error) {
+ if (existsSync(socket)) throw error;
+ } finally {
+ client.close();
+ }
+ for (const child of children) if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
+ children.clear();
+ });
+ afterAll(() => {
+ if (root) rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
+ });
+
+ it("has verified checksums, clean sidecars, and runtime-free help/version startup", async () => {
+ const sum = createHash("sha256").update(readFileSync(archive!)).digest("hex");
+ expect(readFileSync(join(dirname(archive!), "SHA256SUMS"), "utf8")).toContain(`${sum} ${basename(archive!)}`);
+ const listing = execFileSync("tar", ["-tzf", archive!], { encoding: "utf8" });
+ expect(listing).not.toMatch(/(^|\/)(node_modules|\.venv|__pycache__|\.pytest_cache)(\/|$)/m);
+ for (const name of [
+ "prime-agent-runtime/src/rlm/repl.py",
+ "photon_rs_bg.wasm",
+ "export-html/template.css",
+ "export-html/template.js",
+ "theme/prime.json",
+ ])
+ expect(listing).toContain(name);
+ for (const name of ["node", "npm", "bun"]) expect(existsSync(join(environment.PATH!, name))).toBe(false);
+ const metadata = JSON.parse(readFileSync(join(extracted, "package.json"), "utf8"));
+ expect(metadata.name).toBe("@earendil-works/pi-coding-agent");
+ expect(await run(["--version"])).toMatchObject({ code: 0, stdout: `${metadata.version}\n` });
+ const help = await run(["--help"]);
+ expect(help.code, help.stderr).toBe(0);
+ expect(help.stdout).toContain("Python REPL");
+ });
+
+ it("loads extensions and skills, flushes piped output, and starts an owned daemon", async () => {
+ const result = await run([...sessionArgs(), "--no-tools", "-p", "artifact test"]);
+ expect(result.code, result.stderr).toBe(0);
+ expect(result.stdout.trim()).toBe(`artifact-ok:${"x".repeat(131072)}:complete`);
+ expect(JSON.parse(readFileSync(join(cwd, "loaded-assets.json"), "utf8")).skills.length).toBeGreaterThan(0);
+ const client = new DaemonClient(socket);
+ try {
+ await client.connect();
+ const hello = await client.waitForHello();
+ expect(hello.runtime?.executablePath).toBe(binary);
+ expect((await client.request({ type: "list" })).success).toBe(true);
+ } finally {
+ client.close();
+ }
+ });
+
+ it("loads Photon WASM to resize an attachment and exports HTML with its theme", async () => {
+ const header = Buffer.alloc(13);
+ header.writeUInt32BE(3000, 0);
+ header.writeUInt32BE(1, 4);
+ header[8] = 8;
+ header[9] = 2;
+ const png = Buffer.concat([
+ Buffer.from("89504e470d0a1a0a", "hex"),
+ pngChunk("IHDR", header),
+ pngChunk("IDAT", deflateSync(Buffer.alloc(9001))),
+ pngChunk("IEND", Buffer.alloc(0)),
+ ]);
+ writeFileSync(join(cwd, "wide.png"), png);
+ const result = await run([...sessionArgs(), "--no-tools", "-p", "@wide.png", "artifact image"], {
+ PRIME_AGENT_ARTIFACT_CASE: "image",
+ });
+ expect(result.code, result.stderr).toBe(0);
+ const sessionsRoot = join(environment.PRIME_AGENT_CODING_AGENT_DIR!, "sessions");
+ const sessions = readdirSync(sessionsRoot, { recursive: true })
+ .map(String)
+ .filter((path) => path.endsWith(".jsonl"));
+ expect(sessions.length).toBeGreaterThan(0);
+ const output = join(cwd, "export.html");
+ const exported = await run(["session", "export", join(sessionsRoot, sessions[0]!), output]);
+ expect(exported.code, exported.stderr).toBe(0);
+ const html = readFileSync(output, "utf8");
+ const encoded = html.match(/<script id="session-data" type="application\/json">([A-Za-z0-9+/=]+)<\/script>/)?.[1];
+ expect(encoded, "HTML export must embed its session data").toBeDefined();
+ expect(Buffer.from(encoded!, "base64").toString("utf8").includes("artifact image")).toBe(true);
+ });
+
+ it("handles RPC state and shell requests over pipes and exits on EOF", async () => {
+ const input = [
+ { id: "state", type: "get_state" },
+ { id: "shell", type: "bash", command: "printf artifact-rpc-shell" },
+ ]
+ .map((command) => `${JSON.stringify(command)}\n`)
+ .join("");
+ const result = await run([...sessionArgs(), "--no-tools", "--mode", "rpc"], {}, 30000, input);
+ expect(result.code, result.stderr).toBe(0);
+ const frames = result.stdout
+ .trim()
+ .split("\n")
+ .map((line) => JSON.parse(line));
+ expect(frames.find((frame) => frame.id === "state")).toMatchObject({
+ success: true,
+ data: { model: { provider: "artifact-faux" } },
+ });
+ expect(frames.find((frame) => frame.id === "shell")).toMatchObject({
+ success: true,
+ data: { output: "artifact-rpc-shell", exitCode: 0 },
+ });
+ });
+
+ it("selects Bedrock from AWS environment credentials and loads its bundled request path", async () => {
+ const requests: string[] = [];
+ const server = createServer((request, response) => {
+ requests.push(request.url ?? "");
+ response.writeHead(400, { "Content-Type": "application/json", "x-amzn-errortype": "ValidationException" });
+ response.end(JSON.stringify({ message: "artifact-bedrock-request-ok" }));
+ });
+ await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("Missing local provider port");
+ try {
+ const result = await run(
+ [
+ "--offline",
+ "--daemon-socket",
+ socket,
+ "--no-tools",
+ "--no-extensions",
+ "--no-skills",
+ "-p",
+ "offline provider test",
+ ],
+ {
+ AWS_ACCESS_KEY_ID: "artifact-test",
+ AWS_SECRET_ACCESS_KEY: "artifact-test",
+ AWS_REGION: "us-east-1",
+ AWS_EC2_METADATA_DISABLED: "true",
+ AWS_ENDPOINT_URL_BEDROCK_RUNTIME: `http://127.0.0.1:${address.port}`,
+ },
+ );
+ expect(
+ requests.some((path) => path.includes("converse-stream")),
+ result.stderr + result.stdout,
+ ).toBe(true);
+ expect(result.code).not.toBe(0);
+ expect(result.stderr + result.stdout).toContain("artifact-bedrock-request-ok");
+ } finally {
+ await new Promise<void>((done) => server.close(() => done()));
+ }
+ });
+
+ it("bootstraps the shipped Python sources and executes persistent cells and shell commands", async () => {
+ expect(uv, "Set PRIME_AGENT_TEST_UV to an absolute uv executable for artifact validation").toBeTruthy();
+ const result = await run(
+ [...sessionArgs(), "--tools", "ipython", "-p", "artifact python"],
+ { PRIME_AGENT_ARTIFACT_CASE: "python" },
+ 300000,
+ );
+ const uvLog = join(home, "uv.log");
+ expect(result.code, `${result.stderr}\n${existsSync(uvLog) ? readFileSync(uvLog, "utf8") : ""}`).toBe(0);
+ expect(result.stdout).toContain("artifact-python-result 42");
+ expect(result.stdout).toContain("artifact-shell-ok");
+ const bootstrap = JSON.parse(readFileSync(join(home, ".prime/agent/kernel-venv/.bootstrap-version"), "utf8"));
+ expect(bootstrap.runtime).toMatch(/^sha256:/);
+ expect(bootstrap.pythonSkills.length).toBeGreaterThan(0);
+ expect(
+ bootstrap.pythonSkills.every((skill: { packagePath: string }) => skill.packagePath.startsWith(extracted)),
+ ).toBe(true);
+ }, 320000);
+});
diff --git a/packages/coding-agent/test/fixtures/compiled-artifact-extension.ts b/packages/coding-agent/test/fixtures/compiled-artifact-extension.ts
new file mode 100644
index 0000000000..9988d195d4
--- /dev/null
+++ b/packages/coding-agent/test/fixtures/compiled-artifact-extension.ts
@@ -0,0 +1,76 @@
+import { writeFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fauxAssistantMessage, fauxToolCall, getApiProvider, registerFauxProvider } from "@earendil-works/pi-ai";
+import { DefaultResourceLoader, type ExtensionAPI, getAgentDir, initTheme } from "@earendil-works/pi-coding-agent";
+
+export default function artifactExtension(pi: ExtensionAPI): void {
+ const faux = registerFauxProvider({
+ provider: "artifact-faux",
+ models: [{ id: "artifact", reasoning: false, input: ["text", "image"] }],
+ tokenSize: { min: 131072, max: 131072 },
+ });
+ const provider = getApiProvider(faux.api);
+ if (!provider) throw new Error("Faux provider was not bundled");
+ pi.registerProvider("artifact-faux", {
+ api: faux.api,
+ apiKey: "offline-test",
+ baseUrl: faux.getModel().baseUrl,
+ streamSimple: provider.streamSimple,
+ models: faux.models,
+ });
+ if (process.env.PRIME_AGENT_ARTIFACT_CASE === "python") {
+ faux.setResponses([
+ fauxAssistantMessage(
+ fauxToolCall("ipython", {
+ code: "import os, rlm\nartifact_value = 21\nprint('artifact-python-start')\nprint(os.getpid())\nprint(rlm.__file__)",
+ }),
+ { stopReason: "toolUse" },
+ ),
+ fauxAssistantMessage(
+ fauxToolCall("ipython", {
+ code: "print('artifact-python-result', artifact_value * 2)\nprint((await bash('printf artifact-shell-ok')).output)",
+ }),
+ { stopReason: "toolUse" },
+ ),
+ (context) => {
+ const results = context.messages.filter((message) => message.role === "toolResult");
+ if (results.length !== 2 || results.some((result) => result.isError)) {
+ throw new Error(`Python execution failed: ${JSON.stringify(results)}`);
+ }
+ return fauxAssistantMessage(JSON.stringify(results));
+ },
+ ]);
+ } else {
+ faux.setResponses([
+ (context) => {
+ if (process.env.PRIME_AGENT_ARTIFACT_CASE === "image") {
+ if (!JSON.stringify(context.messages).includes("original 3000x1, displayed at 2000x1")) {
+ throw new Error("Photon did not resize the attached image");
+ }
+ }
+ return fauxAssistantMessage(`artifact-ok:${"x".repeat(131072)}:complete`);
+ },
+ ]);
+ }
+ pi.on("session_start", async () => {
+ initTheme("prime");
+ const resources = new DefaultResourceLoader({
+ cwd: process.cwd(),
+ agentDir: getAgentDir(),
+ noExtensions: true,
+ noContextFiles: true,
+ });
+ await resources.reload();
+ const skills = resources.getSkills().skills;
+ if (
+ !skills.length ||
+ skills.some((skill) => !skill.filePath.startsWith(join(dirname(process.execPath), "skills")))
+ ) {
+ throw new Error("Bundled skills did not resolve from the extracted archive");
+ }
+ writeFileSync(
+ join(process.cwd(), "loaded-assets.json"),
+ JSON.stringify({ skills: skills.map((skill) => skill.name) }),
+ );
+ });
+}
diff --git a/packages/coding-agent/test/installer-release-format.test.ts b/packages/coding-agent/test/installer-release-format.test.ts
new file mode 100644
index 0000000000..04832ea94f
--- /dev/null
+++ b/packages/coding-agent/test/installer-release-format.test.ts
@@ -0,0 +1,151 @@
+import { spawn } from "node:child_process";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readlinkSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from "node:fs";
+import { createServer } from "node:http";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+const version = "1.2.3";
+const nodeFile = `prime-agent-${version}.tgz`;
+const nativeFile = `prime-agent-${version}-${process.platform}-${process.arch}.tar.gz`;
+const digest = "a".repeat(64);
+let root: string;
+let harness: string;
+let base: string;
+let checksums = "";
+const server = createServer((request, response) => {
+ const found = request.url === `/releases/v${version}/SHA256SUMS`;
+ response.writeHead(found ? 200 : 404);
+ response.end(found ? checksums : "missing archive");
+});
+
+async function install(
+ inventory: string,
+ method = "auto",
+ existing: "npm" | "unmanaged-root" | "both" | undefined = undefined,
+) {
+ checksums = inventory;
+ const home = mkdtempSync(join(root, "home-"));
+ const publicCommand = join(home, ".local/bin/prime-agent");
+ const nativeRoot = join(home, ".local/share/prime-agent");
+ const hasNpm = existing === "npm" || existing === "both";
+ const hasUnmanagedRoot = existing === "unmanaged-root" || existing === "both";
+ if (hasNpm) {
+ const npmEntry = join(home, ".local/lib/node_modules/prime-agent/dist/bundle/cli.js");
+ mkdirSync(dirname(npmEntry), { recursive: true });
+ writeFileSync(npmEntry, "existing npm entrypoint");
+ mkdirSync(join(home, ".local/bin"), { recursive: true });
+ symlinkSync("../lib/node_modules/prime-agent/dist/bundle/cli.js", publicCommand);
+ }
+ if (hasUnmanagedRoot) {
+ mkdirSync(nativeRoot, { recursive: true });
+ writeFileSync(join(nativeRoot, "keep"), "user-owned data");
+ }
+ const child = spawn("sh", [harness, version], {
+ env: {
+ HOME: home,
+ PATH: "/usr/bin:/bin",
+ TMPDIR: root,
+ PRIME_AGENT_INSTALL_METHOD: method,
+ PRIME_AGENT_DOWNLOAD_BASE_URL: base,
+ PRIME_AGENT_ALLOW_INSECURE_HTTP_FOR_TESTS: "1",
+ PRIME_AGENT_INSTALLER_NONINTERACTIVE: "1",
+ PRIME_AGENT_INSTALLER_PLAIN: "1",
+ PRIME_AGENT_BOOTSTRAP_KERNEL_ON_INSTALL: "0",
+ },
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let output = "";
+ child.stdout.on("data", (data) => {
+ output += data.toString();
+ });
+ child.stderr.on("data", (data) => {
+ output += data.toString();
+ });
+ const code = await new Promise<number | null>((done, reject) => {
+ child.once("error", reject);
+ child.once("close", done);
+ });
+ expect(existsSync(join(home, ".local/share/prime-agent/.install-lock"))).toBe(false);
+ expect(existsSync(publicCommand)).toBe(hasNpm);
+ if (hasNpm) {
+ expect(readlinkSync(publicCommand)).toBe("../lib/node_modules/prime-agent/dist/bundle/cli.js");
+ expect(readFileSync(publicCommand, "utf8")).toBe("existing npm entrypoint");
+ }
+ if (hasUnmanagedRoot) expect(readFileSync(join(nativeRoot, "keep"), "utf8")).toBe("user-owned data");
+ return { code, output, nativeRoot };
+}
+
+describe.skipIf(process.platform === "win32")("installer release format selection", () => {
+ beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), "installer-release-format-"));
+ harness = join(root, "install.sh");
+ const installer = readFileSync(resolve(__dirname, "../../../install.sh"), "utf8");
+ writeFileSync(
+ harness,
+ installer.replace(
+ /\nmain "\$@"\s*$/,
+ '\nprime_agent_install_node() { printf "node-route:%s\\\\n" "$1"; }\nmain "$@"\n',
+ ),
+ );
+ await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("missing server address");
+ base = `http://127.0.0.1:${address.port}`;
+ });
+ afterAll(async () => {
+ await new Promise<void>((done) => server.close(() => done()));
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ it("uses Node for a release whose checksum inventory only advertises npm packages", async () => {
+ const result = await install(`${digest} ${nodeFile}\n${digest} prime-agent-ai-${version}.tgz\n`);
+ expect(result.code, result.output).toBe(0);
+ expect(result.output).toContain(`node-route:${version}`);
+ });
+
+ it("keeps binary-only installs strict for an npm-only release", async () => {
+ const result = await install(`${digest} ${nodeFile}\n`, "binary");
+ expect(result.code).not.toBe(0);
+ expect(result.output).not.toContain("node-route:");
+ });
+
+ it.each(["npm", "unmanaged-root", "both"] as const)(
+ "selects the npm-only release before checking native ownership with %s present",
+ async (existing) => {
+ const result = await install(`${digest} ${nodeFile}\n`, "auto", existing);
+ expect(result.code, result.output).toBe(0);
+ expect(result.output).toContain(`node-route:${version}`);
+ expect(existsSync(join(result.nativeRoot, ".managed"))).toBe(false);
+ },
+ );
+
+ it("still rejects an unmanaged native root for compiled releases", async () => {
+ const result = await install(`${digest} ${nativeFile}\n`, "auto", "unmanaged-root");
+ expect(result.code).not.toBe(0);
+ expect(result.output).toContain("refusing to take ownership");
+ expect(result.output).not.toContain("node-route:");
+ });
+
+ it.each([
+ ["empty inventory", ""],
+ ["invalid npm checksum", `bad ${nodeFile}\n`],
+ ["duplicate npm checksum", `${digest} ${nodeFile}\n${digest} ${nodeFile}\n`],
+ ["missing native platform", `${digest} ${nodeFile}\n${digest} prime-agent-${version}-other.tar.gz\n`],
+ ["invalid native checksum", `${digest} ${nodeFile}\nbad ${nativeFile}\n`],
+ ["missing native archive", `${digest} ${nodeFile}\n${digest} ${nativeFile}\n`],
+ ])("does not fall back after %s", async (_label, inventory) => {
+ const result = await install(inventory);
+ expect(result.code).not.toBe(0);
+ expect(result.output).not.toContain("node-route:");
+ });
+});
diff --git a/packages/coding-agent/test/native-installer.test.ts b/packages/coding-agent/test/native-installer.test.ts
new file mode 100644
index 0000000000..92bb421047
--- /dev/null
+++ b/packages/coding-agent/test/native-installer.test.ts
@@ -0,0 +1,542 @@
+import { execFileSync, spawn } from "node:child_process";
+import { createHash } from "node:crypto";
+import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readlinkSync,
+ realpathSync,
+ rmSync,
+ symlinkSync,
+ writeFileSync,
+} from "node:fs";
+import { createServer as createHttpServer, type RequestListener } from "node:http";
+import { createServer as createHttpsServer } from "node:https";
+import { tmpdir } from "node:os";
+import { basename, dirname, join, resolve } from "node:path";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+
+const installer = resolve(__dirname, "../../../install.sh");
+const assets = [
+ "package.json",
+ "install.sh",
+ "prime-agent-runtime/pyproject.toml",
+ "prime-agent-runtime/src/rlm/repl.py",
+ "theme/prime.json",
+ "export-html/template.html",
+ "photon_rs_bg.wasm",
+];
+const platform = `${process.platform}-${process.arch}`;
+const feed = new Map<string, Buffer>();
+let beforeArchiveResponse: (() => void) | undefined;
+let redirectToHttp = false;
+let insecureRequestCount = 0;
+let httpBase: string;
+const serveFeed: RequestListener = (request, response) => {
+ if (request.url?.endsWith(".tar.gz")) beforeArchiveResponse?.();
+ const data = feed.get(request.url ?? "");
+ response.writeHead(data ? 200 : 404);
+ response.end(data ?? "not found");
+};
+let server: ReturnType<typeof createHttpsServer>;
+let insecureServer: ReturnType<typeof createHttpServer>;
+let root: string;
+let home: string;
+let base: string;
+let certificate: string;
+
+function publish(version: string, options: { broken?: boolean; missing?: boolean; link?: boolean } = {}) {
+ const source = mkdtempSync(join(root, "archive-"));
+ for (const asset of assets) {
+ if (options.missing && asset === assets[2]) continue;
+ mkdirSync(dirname(join(source, asset)), { recursive: true });
+ writeFileSync(join(source, asset), "fixture\n");
+ }
+ writeFileSync(
+ join(source, "prime-agent"),
+ options.broken ? "#!/bin/sh\nexit 1\n" : `#!/bin/sh\nprintf '%s\\n' '${version}'\n`,
+ { mode: 0o755 },
+ );
+ if (options.link) symlinkSync("/tmp", join(source, "outside"));
+ const filename = `prime-agent-${version}-${platform}.tar.gz`;
+ const archive = join(root, filename);
+ execFileSync("tar", ["-czf", archive, "-C", source, "."]);
+ const bytes = readFileSync(archive);
+ const digest = createHash("sha256").update(bytes).digest("hex");
+ feed.set(`/releases/v${version}/${filename}`, bytes);
+ feed.set(`/releases/v${version}/SHA256SUMS`, Buffer.from(`${digest} ${filename}\n`));
+ return filename;
+}
+
+function publishNodePackage(version: string) {
+ const filename = `prime-agent-${version}.tgz`;
+ const bytes = Buffer.from(`node package ${version}\n`);
+ const digest = createHash("sha256").update(bytes).digest("hex");
+ feed.set(`/releases/v${version}/${filename}`, bytes);
+ feed.set(`/releases/v${version}/SHA256SUMS`, Buffer.from(`${digest} ${filename}\n`));
+}
+
+async function install(version: string, extra: NodeJS.ProcessEnv = {}, entrypoint = installer) {
+ const child = spawn("sh", [entrypoint, version], {
+ env: {
+ ...process.env,
+ HOME: home,
+ PATH: "/usr/bin:/bin",
+ XDG_DATA_HOME: join(home, "data"),
+ SHELL: "/bin/sh",
+ PRIME_AGENT_INSTALL_METHOD: "binary",
+ PRIME_AGENT_INSTALLER_NONINTERACTIVE: "1",
+ PRIME_AGENT_INSTALLER_PLAIN: "1",
+ PRIME_AGENT_BOOTSTRAP_KERNEL_ON_INSTALL: "0",
+ PRIME_AGENT_DOWNLOAD_BASE_URL: base,
+ CURL_CA_BUNDLE: certificate,
+ ...extra,
+ },
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let output = "";
+ child.stdout.on("data", (chunk) => {
+ output += chunk.toString();
+ });
+ child.stderr.on("data", (chunk) => {
+ output += chunk.toString();
+ });
+ return await new Promise<{ code: number | null; output: string }>((done, reject) => {
+ child.once("error", reject);
+ child.once("close", (code) => done({ code, output }));
+ });
+}
+
+function command() {
+ return join(home, "data/prime-agent/bin/prime-agent");
+}
+
+describe.skipIf(process.platform === "win32")("managed compiled installer", () => {
+ beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), "native-installer-"));
+ const key = join(root, "localhost.key");
+ certificate = join(root, "localhost.crt");
+ execFileSync(
+ "openssl",
+ [
+ "req",
+ "-x509",
+ "-newkey",
+ "rsa:2048",
+ "-nodes",
+ "-keyout",
+ key,
+ "-out",
+ certificate,
+ "-days",
+ "1",
+ "-subj",
+ "/CN=127.0.0.1",
+ "-addext",
+ "subjectAltName=IP:127.0.0.1",
+ ],
+ { stdio: "ignore" },
+ );
+ insecureServer = createHttpServer((request, response) => {
+ insecureRequestCount += 1;
+ serveFeed(request, response);
+ });
+ await new Promise<void>((done) => insecureServer.listen(0, "127.0.0.1", done));
+ const insecureAddress = insecureServer.address();
+ if (!insecureAddress || typeof insecureAddress === "string") throw new Error("missing insecure server address");
+ httpBase = `http://127.0.0.1:${insecureAddress.port}`;
+ server = createHttpsServer({ cert: readFileSync(certificate), key: readFileSync(key) }, (request, response) => {
+ if (redirectToHttp) {
+ response.writeHead(302, { location: `${httpBase}${request.url ?? ""}` });
+ response.end();
+ return;
+ }
+ serveFeed(request, response);
+ });
+ await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("missing server address");
+ base = `https://127.0.0.1:${address.port}`;
+ });
+ beforeEach(() => {
+ home = mkdtempSync(join(root, "home with spaces-"));
+ feed.clear();
+ beforeArchiveResponse = undefined;
+ redirectToHttp = false;
+ insecureRequestCount = 0;
+ });
+ afterAll(async () => {
+ await new Promise<void>((done) => server.close(() => done()));
+ await new Promise<void>((done) => insecureServer.close(() => done()));
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ it.each(["binary", "node"])("rejects an HTTP download base in %s mode", async (method) => {
+ const result = await install("1.0.0", {
+ PRIME_AGENT_DOWNLOAD_BASE_URL: httpBase,
+ PRIME_AGENT_INSTALL_METHOD: method,
+ });
+ expect(result.code).not.toBe(0);
+ expect(result.output).toContain("downloads require an HTTPS base URL");
+ expect(insecureRequestCount).toBe(0);
+ });
+
+ it("does not let the test opt-in enable HTTP for a non-loopback origin", async () => {
+ const result = await install("1.0.0", {
+ PRIME_AGENT_ALLOW_INSECURE_HTTP_FOR_TESTS: "1",
+ PRIME_AGENT_DOWNLOAD_BASE_URL: "http://example.invalid",
+ });
+ expect(result.code).not.toBe(0);
+ expect(result.output).toContain("downloads require an HTTPS base URL");
+ });
+
+ it("rejects an HTTPS-to-HTTP redirect before downloading a native release", async () => {
+ publish("1.0.0");
+ redirectToHttp = true;
+ const result = await install("1.0.0");
+ expect(result.code).not.toBe(0);
+ expect(insecureRequestCount).toBe(0);
+ expect(existsSync(command())).toBe(false);
+ });
+
+ it("downloads the Node package and checksum inventory over HTTPS", async () => {
+ publishNodePackage("1.0.0");
+ const harness = join(home, "node-download.sh");
+ writeFileSync(
+ harness,
+ readFileSync(installer, "utf8").replace(
+ /\nmain "\$@"\s*$/,
+ () => `
+prime_agent_validate_download_base_url
+download_prime_agent_package "$1" "$prime_agent_base_url/releases/v$1/$prime_agent_package-$1.tgz" "$HOME/$prime_agent_package-$1.tgz"
+`,
+ ),
+ );
+ const result = await install("1.0.0", {}, harness);
+ expect(result.code, result.output).toBe(0);
+ expect(readFileSync(join(home, "prime-agent-1.0.0.tgz"), "utf8")).toBe("node package 1.0.0\n");
+ });
+
+ it("rejects an HTTPS-to-HTTP redirect for the Node package route", async () => {
+ publishNodePackage("1.0.0");
+ redirectToHttp = true;
+ const harness = join(home, "node-download.sh");
+ writeFileSync(
+ harness,
+ readFileSync(installer, "utf8").replace(
+ /\nmain "\$@"\s*$/,
+ () => `
+prime_agent_validate_download_base_url
+download_prime_agent_package "$1" "$prime_agent_base_url/releases/v$1/$prime_agent_package-$1.tgz" "$HOME/$prime_agent_package-$1.tgz"
+`,
+ ),
+ );
+ const result = await install("1.0.0", {}, harness);
+ expect(result.code).not.toBe(0);
+ expect(insecureRequestCount).toBe(0);
+ expect(existsSync(join(home, "prime-agent-1.0.0.tgz"))).toBe(false);
+ });
+
+ it("defaults to a verified executable without Node, preserves user data, and retains the previous release", async () => {
+ publish("1.0.0");
+ publish("1.0.1");
+ mkdirSync(join(home, ".prime/agent"), { recursive: true });
+ writeFileSync(join(home, ".prime/agent/auth.json"), "keep credentials");
+ const first = await install("1.0.0", { PRIME_AGENT_INSTALL_METHOD: "auto" });
+ expect(first.code, first.output).toBe(0);
+ expect(execFileSync(join(home, ".local/bin/prime-agent"), ["--version"], { encoding: "utf8" })).toBe("1.0.0\n");
+ const previous = readlinkSync(command());
+ const second = await install("1.0.1");
+ expect(second.code, second.output).toBe(0);
+ expect(readlinkSync(join(dirname(command()), "previous"))).toBe(previous);
+ expect(readFileSync(join(home, ".prime/agent/auth.json"), "utf8")).toBe("keep credentials");
+ expect(existsSync(join(home, "data/prime-agent/.install-lock"))).toBe(false);
+ });
+
+ it.each(["checksum", "missing", "broken", "link", "duplicate"])(
+ "leaves the current command working after %s validation fails",
+ async (failure) => {
+ publish("1.0.0");
+ const first = await install("1.0.0");
+ expect(first.code, first.output).toBe(0);
+ const target = readlinkSync(command());
+ const filename = publish("1.0.1", {
+ missing: failure === "missing",
+ broken: failure === "broken",
+ link: failure === "link",
+ });
+ if (failure === "checksum") feed.set(`/releases/v1.0.1/${filename}`, Buffer.from("corrupt"));
+ if (failure === "duplicate")
+ feed.set(
+ "/releases/v1.0.1/SHA256SUMS",
+ Buffer.concat([feed.get("/releases/v1.0.1/SHA256SUMS")!, feed.get("/releases/v1.0.1/SHA256SUMS")!]),
+ );
+ const result = await install("1.0.1");
+ expect(result.code, result.output).not.toBe(0);
+ expect(readlinkSync(command())).toBe(target);
+ expect(execFileSync(command(), ["--version"], { encoding: "utf8" })).toBe("1.0.0\n");
+ expect(existsSync(join(home, "data/prime-agent/.install-lock"))).toBe(false);
+ },
+ );
+
+ it.each(["1.0.0", "1.0.1"])("retries the Node fallback when reinstalling or upgrading to %s", async (version) => {
+ publish("1.0.0", { broken: true });
+ publish("1.0.1", { broken: true });
+ const harness = join(home, "fallback-installer.sh");
+ writeFileSync(
+ harness,
+ readFileSync(installer, "utf8").replace(
+ /\nmain "\$@"\s*$/,
+ () => `
+prime_agent_install_node() {
+ mkdir -p "$HOME/.local/bin" "$HOME/.local/lib/node_modules/prime-agent/dist/bundle"
+ printf '%s\\n' "$1" > "$HOME/.local/lib/node_modules/prime-agent/dist/bundle/cli.js"
+ if [ ! -L "$HOME/.local/bin/prime-agent" ]; then
+ ln -s ../lib/node_modules/prime-agent/dist/bundle/cli.js "$HOME/.local/bin/prime-agent"
+ fi
+ printf 'node-route:%s\\n' "$1"
+}
+main "$@"
+`,
+ ),
+ );
+ const first = await install("1.0.0", { PRIME_AGENT_INSTALL_METHOD: "auto" }, harness);
+ expect(first.code, first.output).toBe(0);
+ expect(first.output).toContain("node-route:1.0.0");
+ const publicCommand = join(home, ".local/bin/prime-agent");
+ const npmLink = readlinkSync(publicCommand);
+ const second = await install(version, { PRIME_AGENT_INSTALL_METHOD: "auto" }, harness);
+ expect(second.code, second.output).toBe(0);
+ expect(second.output).toContain(`node-route:${version}`);
+ expect(readlinkSync(publicCommand)).toBe(npmLink);
+ expect(readFileSync(publicCommand, "utf8")).toBe(`${version}\n`);
+ expect(existsSync(command())).toBe(false);
+ expect(existsSync(join(home, "data/prime-agent/.install-lock"))).toBe(false);
+
+ // A runnable archive still cannot take over the npm-owned public command.
+ publish("1.0.2");
+ const compiled = await install("1.0.2", { PRIME_AGENT_INSTALL_METHOD: "auto" }, harness);
+ expect(compiled.code, compiled.output).not.toBe(0);
+ expect(compiled.output).toContain("refusing to replace existing command");
+ expect(compiled.output).not.toContain("node-route:");
+ expect(readlinkSync(publicCommand)).toBe(npmLink);
+ expect(readFileSync(publicCommand, "utf8")).toBe(`${version}\n`);
+ expect(existsSync(command())).toBe(false);
+ });
+
+ it("refuses to replace an unrelated public command", async () => {
+ publish("1.0.0");
+ mkdirSync(join(home, ".local/bin"), { recursive: true });
+ writeFileSync(join(home, ".local/bin/prime-agent"), "owned by another installer");
+ const result = await install("1.0.0");
+ expect(result.code).not.toBe(0);
+ expect(result.output).toContain("refusing to replace existing command");
+ expect(existsSync(command())).toBe(false);
+ });
+
+ it.each(["../outside", "/tmp/outside", ".", ".."])("rejects a command name containing a path: %s", async (name) => {
+ publish("1.0.0");
+ const result = await install("1.0.0", { PRIME_AGENT_CMD: name });
+ expect(result.code).not.toBe(0);
+ expect(result.output).toContain("command name must be a basename");
+ expect(existsSync(command())).toBe(false);
+ expect(existsSync(join(home, ".local/outside"))).toBe(false);
+ });
+
+ it("preserves a public command replaced by another installer during download", async () => {
+ publish("1.0.0");
+ expect((await install("1.0.0")).code).toBe(0);
+ const current = readlinkSync(command());
+ const publicCommand = join(home, ".local/bin/prime-agent");
+ publish("1.0.1");
+ beforeArchiveResponse = () => {
+ rmSync(publicCommand);
+ writeFileSync(publicCommand, "owned by another installer");
+ };
+ const result = await install("1.0.1");
+ expect(result.code, result.output).not.toBe(0);
+ expect(result.output).toContain("refusing to replace existing command");
+ expect(readFileSync(publicCommand, "utf8")).toBe("owned by another installer");
+ expect(readlinkSync(command())).toBe(current);
+ });
+
+ it.each(["", "../releases/an-earlier-install/prime-agent"])(
+ "rejects a stale migration expectation (%s)",
+ async (expected) => {
+ publish("1.0.1");
+ publish("1.0.0");
+ expect((await install("1.0.1")).code).toBe(0);
+ const active = readlinkSync(command());
+ const result = await install("1.0.0", { PRIME_AGENT_EXPECTED_CURRENT: expected });
+ expect(result.code, result.output).not.toBe(0);
+ expect(readlinkSync(command())).toBe(active);
+ },
+ );
+
+ it("does not overwrite a command created at the public-link handoff", async () => {
+ publish("1.0.0");
+ expect((await install("1.0.0")).code).toBe(0);
+ const current = readlinkSync(command());
+ const publicCommand = join(home, ".local/bin/prime-agent");
+ rmSync(publicCommand);
+ const shim = join(root, "link-shim");
+ mkdirSync(shim);
+ writeFileSync(
+ join(shim, "ln"),
+ '#!/bin/sh\nif [ "$3" = "$RACE_COMMAND" ]; then printf "concurrent command" > "$RACE_COMMAND"; fi\nexec /bin/ln "$@"\n',
+ { mode: 0o755 },
+ );
+ publish("1.0.1");
+ const result = await install("1.0.1", { PATH: `${shim}:/usr/bin:/bin`, RACE_COMMAND: publicCommand });
+ expect(result.code, result.output).not.toBe(0);
+ expect(readFileSync(publicCommand, "utf8")).toBe("concurrent command");
+ expect(readlinkSync(command())).toBe(current);
+ });
+
+ it.each([
+ ["before", "mv", "FAIL"],
+ ["before", "mv", "HUP"],
+ ["before", "mv", "TERM"],
+ ["before", "mv", "KILL"],
+ ["after", "mv", "HUP"],
+ ["after", "mv", "TERM"],
+ ["after", "mv", "KILL"],
+ ["after", "ln", "HUP"],
+ ["after", "ln", "TERM"],
+ ["after", "ln", "KILL"],
+ ])("keeps fresh installation retryable when %s %s receives %s", async (point, operation, signal) => {
+ publish("1.0.0");
+ const publicCommand = join(home, ".local/bin/prime-agent");
+ const shim = mkdtempSync(join(root, "fresh-activation-"));
+ writeFileSync(
+ join(shim, operation),
+ `#!/bin/sh
+interrupt() {
+ if [ "$INTERRUPT_SIGNAL" = FAIL ]; then exit 73; fi
+ kill -"$INTERRUPT_SIGNAL" "$PPID"
+ exit 74
+}
+for destination in "$@"; do :; done
+if [ "$destination" = "$INTERRUPT_COMMAND" ] && [ "$INTERRUPT_POINT" = before ]; then interrupt; fi
+/bin/${operation} "$@" || exit $?
+if [ "$destination" = "$INTERRUPT_COMMAND" ] && [ "$INTERRUPT_POINT" = after ]; then interrupt; fi
+`,
+ { mode: 0o755 },
+ );
+ mkdirSync(join(home, ".prime/agent"), { recursive: true });
+ const userData = join(home, ".prime/agent/auth.json");
+ writeFileSync(userData, "keep credentials");
+ const result = await install("1.0.0", {
+ PATH: `${shim}:/usr/bin:/bin`,
+ INTERRUPT_COMMAND:
+ operation === "mv" ? join(realpathSync(home), "data/prime-agent/bin/prime-agent") : publicCommand,
+ INTERRUPT_POINT: point,
+ INTERRUPT_SIGNAL: signal,
+ });
+ expect(result.code, result.output).not.toBe(0);
+ if (lstatSync(publicCommand, { throwIfNoEntry: false })) {
+ expect(existsSync(publicCommand), "public command must never be a dangling symlink").toBe(true);
+ expect(execFileSync(publicCommand, ["--version"], { encoding: "utf8" })).toBe("1.0.0\n");
+ }
+ expect(readFileSync(userData, "utf8")).toBe("keep credentials");
+ const lock = join(home, "data/prime-agent/.install-lock");
+ expect(existsSync(lock)).toBe(signal === "KILL");
+ // SIGKILL cannot run cleanup; recover the lock after the installer has exited.
+ if (signal === "KILL") rmSync(lock, { recursive: true });
+ const retry = await install("1.0.0");
+ expect(retry.code, retry.output).toBe(0);
+ expect(execFileSync(publicCommand, ["--version"], { encoding: "utf8" })).toBe("1.0.0\n");
+ expect(readFileSync(userData, "utf8")).toBe("keep credentials");
+ expect(existsSync(lock)).toBe(false);
+ });
+
+ it("repairs missing assets on reinstall without replacing files used by an existing process", async () => {
+ publish("1.0.0");
+ expect((await install("1.0.0")).code).toBe(0);
+ const previous = readlinkSync(command());
+ const oldRelease = dirname(realpathSync(command()));
+ rmSync(join(oldRelease, "theme/prime.json"));
+ const result = await install("1.0.0");
+ expect(result.code, result.output).toBe(0);
+ expect(readlinkSync(command())).not.toBe(previous);
+ expect(readFileSync(join(dirname(realpathSync(command())), "theme/prime.json"), "utf8")).toBe("fixture\n");
+ expect(existsSync(join(oldRelease, "theme/prime.json"))).toBe(false);
+ expect(readlinkSync(join(dirname(command()), "previous"))).toBe(previous);
+ });
+
+ it.each(["HUP", "TERM", "KILL"])("retains a rollback target after %s interrupts activation", async (signal) => {
+ for (const version of ["1.0.0", "1.0.1", "1.0.2"]) publish(version);
+ expect((await install("1.0.0")).code).toBe(0);
+ const retained = readlinkSync(command());
+ expect((await install("1.0.1")).code).toBe(0);
+ const replaced = readlinkSync(command());
+ const shim = mkdtempSync(join(root, "interrupt-activation-"));
+ writeFileSync(
+ join(shim, "mv"),
+ '#!/bin/sh\n/bin/mv "$@" || exit $?\nfor destination in "$@"; do :; done\ncase "$destination" in "$INTERRUPT_BIN/prime-agent"|"$INTERRUPT_BIN/previous") if [ ! -f "$0.sent" ]; then touch "$0.sent"; kill -"$INTERRUPT_SIGNAL" "$PPID"; fi ;; esac\n',
+ { mode: 0o755 },
+ );
+ const result = await install("1.0.2", {
+ PATH: `${shim}:/usr/bin:/bin`,
+ INTERRUPT_BIN: realpathSync(dirname(command())),
+ INTERRUPT_SIGNAL: signal,
+ });
+ expect(result.code, result.output).not.toBe(0);
+ expect(readlinkSync(join(dirname(command()), "previous"))).toBe(signal === "KILL" ? retained : replaced);
+ expect(readlinkSync(command())).not.toBe(retained);
+ expect(execFileSync(command(), ["--version"], { encoding: "utf8" })).toBe("1.0.2\n");
+ expect(existsSync(join(home, "data/prime-agent/.install-lock"))).toBe(signal === "KILL");
+ });
+
+ it("does not steal another installation's lock", async () => {
+ publish("1.0.0");
+ const first = await install("1.0.0");
+ expect(first.code, first.output).toBe(0);
+ const lock = join(home, "data/prime-agent/.install-lock");
+ mkdirSync(lock);
+ writeFileSync(join(lock, "pid"), `${process.pid}\n`);
+ const result = await install("1.0.0");
+ expect(result.code).not.toBe(0);
+ expect(result.output).toContain("installation is locked");
+ expect(readFileSync(join(lock, "pid"), "utf8")).toBe(`${process.pid}\n`);
+ });
+
+ it("releases its installation lock after a terminal hangup", async () => {
+ const harness = join(root, "hangup.sh");
+ writeFileSync(
+ harness,
+ readFileSync(installer, "utf8").replace(
+ /\nmain "\$@"\s*$/,
+ () => '\nprime_agent_install_traps\nprime_agent_native_prepare_root\nkill -HUP "$$"\n',
+ ),
+ );
+ const result = await install("", {}, harness);
+ expect(result.code, result.output).toBe(129);
+ expect(existsSync(join(home, "data/prime-agent/.install-lock"))).toBe(false);
+ });
+
+ it("reports the supported native platform without installation or release discovery", async () => {
+ const result = await install("--native-platform", { PRIME_AGENT_DOWNLOAD_BASE_URL: "http://127.0.0.1:1" });
+ expect(result).toEqual({ code: 0, output: platform });
+ expect(existsSync(join(home, "data/prime-agent"))).toBe(false);
+ });
+
+ it.skipIf(!process.env.PRIME_AGENT_TEST_ARCHIVE)(
+ "installs the actual compiled release archive",
+ async () => {
+ const archive = process.env.PRIME_AGENT_TEST_ARCHIVE!;
+ const name = basename(archive);
+ const version = name.slice("prime-agent-".length, -`-${platform}.tar.gz`.length);
+ feed.set(`/releases/v${version}/${name}`, readFileSync(archive));
+ feed.set(`/releases/v${version}/SHA256SUMS`, readFileSync(join(dirname(archive), "SHA256SUMS")));
+ const result = await install(version);
+ expect(result.code, result.output).toBe(0);
+ expect(
+ execFileSync(command(), ["--version"], { encoding: "utf8", env: { HOME: home, PATH: "/usr/bin:/bin" } }),
+ ).toBe(`${version}\n`);
+ },
+ 60000,
+ );
+});
diff --git a/scripts/assemble-release-archives.mjs b/scripts/assemble-release-archives.mjs
new file mode 100644
index 0000000000..9e57a9f2a3
--- /dev/null
+++ b/scripts/assemble-release-archives.mjs
@@ -0,0 +1,75 @@
+#!/usr/bin/env node
+import { execFileSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import {
+ chmodSync,
+ cpSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { pathToFileURL } from "node:url";
+import {
+ binaryAssets,
+ setBinaryVersion,
+ validateBinaryAssets,
+} from "../packages/coding-agent/scripts/copy-binary-assets.mjs";
+
+const platforms = ["darwin-arm64", "darwin-x64", "linux-arm64", "linux-x64"];
+
+export function assembleBinaryArchives({ binaryDir, artifactsDir, version, requireAll = true }) {
+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) throw new Error(`Invalid binary version: ${version}`);
+ const available = readdirSync(binaryDir);
+ const targets = platforms.filter((platform) => available.includes(platform));
+ if (targets.length === 0 || (requireAll && targets.length !== platforms.length)) {
+ throw new Error("Missing compiled binaries; build all four platforms before packing a release");
+ }
+ mkdirSync(artifactsDir, { recursive: true });
+ const archives = [];
+ for (const platform of targets) {
+ const source = join(binaryDir, platform);
+ validateBinaryAssets(source);
+ const binary = join(source, "prime-agent");
+ if (!statSync(binary).isFile() || !(statSync(binary).mode & 0o111))
+ throw new Error(`Missing executable: ${binary}`);
+ const staging = mkdtempSync(join(tmpdir(), "prime-agent-archive-"));
+ try {
+ for (const name of ["prime-agent", ...binaryAssets])
+ cpSync(join(source, name), join(staging, name), { recursive: true });
+ setBinaryVersion(staging, version);
+ chmodSync(join(staging, "prime-agent"), 0o755);
+ const file = `prime-agent-${version}-${platform}.tar.gz`;
+ const output = join(artifactsDir, file);
+ execFileSync("tar", ["-czf", output, "-C", staging, "prime-agent", ...binaryAssets], {
+ env: { ...process.env, COPYFILE_DISABLE: "1" },
+ });
+ archives.push({ platform, file, sha256: createHash("sha256").update(readFileSync(output)).digest("hex") });
+ } finally {
+ rmSync(staging, { recursive: true, force: true });
+ }
+ }
+ return archives;
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
+ const [binaryDir, artifactsDir, version] = process.argv.slice(2);
+ if (!binaryDir || !artifactsDir || !version)
+ throw new Error("Usage: node scripts/assemble-release-archives.mjs <binary-dir> <out-dir> <version>");
+ const archives = assembleBinaryArchives({
+ binaryDir: resolve(binaryDir),
+ artifactsDir: resolve(artifactsDir),
+ version,
+ requireAll: false,
+ });
+ writeFileSync(join(artifactsDir, "SHA256SUMS"), archives.map(({ sha256, file }) => `${sha256} ${file}\n`).join(""));
+ writeFileSync(
+ join(artifactsDir, "binaries.json"),
+ `${JSON.stringify({ version: `v${version}`, binaries: archives }, null, 2)}\n`,
+ );
+}
diff --git a/scripts/pack-prime-agent-release.mjs b/scripts/pack-prime-agent-release.mjs
index d264025e11..28febe40b2 100644
--- a/scripts/pack-prime-agent-release.mjs
+++ b/scripts/pack-prime-agent-release.mjs
@@ -14,6 +14,7 @@ import {
} from "node:fs";
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
+import { assembleBinaryArchives } from "./assemble-release-archives.mjs";
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const defaultOutputDir = join(root, "packages", "coding-agent", "release");
@@ -35,11 +36,19 @@ function parseArgs(args) {
channel: "stable",
outDir: defaultOutputDir,
version: undefined,
+ binaryDir: undefined,
};
for (let i = 0; i < args.length; i += 1) {
const arg = args[i];
switch (arg) {
+ case "--binary-dir": {
+ const value = args[i + 1];
+ if (!value) throw new Error("--binary-dir requires a value");
+ parsed.binaryDir = resolve(root, value);
+ i += 1;
+ break;
+ }
case "--channel": {
const value = args[i + 1];
if (!value || !releaseChannels.has(value)) {
@@ -89,7 +98,7 @@ function parseArgs(args) {
}
function printHelp() {
- console.log(`Usage: node scripts/pack-prime-agent-release.mjs --base-url url [--channel stable|beta] [--version x.y.z] [--out-dir path]
+ console.log(`Usage: node scripts/pack-prime-agent-release.mjs --base-url url [--channel stable|beta] [--version x.y.z] [--out-dir path] [--binary-dir path]
Creates private npm tarballs for R2 distribution:
@@ -100,6 +109,8 @@ Creates private npm tarballs for R2 distribution:
<out-dir>/artifacts/SHA256SUMS
<out-dir>/artifacts/<channel>
<out-dir>/artifacts/latest.json (stable) or beta.json (beta)
+
+Add --binary-dir packages/coding-agent/binaries to include all four standalone platform archives.
`);
}
@@ -319,9 +330,12 @@ function main() {
}
tarballs.sort((left, right) => left.file.localeCompare(right.file));
+ const binaries = args.binaryDir
+ ? assembleBinaryArchives({ binaryDir: args.binaryDir, artifactsDir, version: releaseVersion })
+ : [];
writeFileSync(
join(artifactsDir, "SHA256SUMS"),
- tarballs.map((tarball) => `${tarball.sha256} ${tarball.file}`).join("\n") + "\n",
+ [...tarballs, ...binaries].map((artifact) => `${artifact.sha256} ${artifact.file}`).join("\n") + "\n",
);
writeFileSync(join(artifactsDir, args.channel), `v${releaseVersion}\n`);
const manifestName = args.channel === "stable" ? "latest.json" : "beta.json";
@@ -329,6 +343,7 @@ function main() {
version: `v${releaseVersion}`,
package: publicPackageName,
tarball: `releases/v${releaseVersion}/${artifactFiles.get("coding-agent")}`,
+ ...(binaries.length > 0 ? { binaries } : {}),
tarballs: tarballs.map((tarball) => ({
package: tarball.name,
file: tarball.file,
@@ -336,8 +351,8 @@ function main() {
})),
});
- for (const tarball of tarballs) {
- console.log(`Created ${join(artifactsDir, tarball.file)}`);
+ for (const artifact of [...tarballs, ...binaries]) {
+ console.log(`Created ${join(artifactsDir, artifact.file)}`);
}
}