Files
PaperClipAI/scripts/prepare-bundled-package.mjs
T
Nicky LeachandClaude Opus 5.5 ff8ec41e6a feat(runner): upgrade ACPX to 0.22.0 and move patched behavior into Paperclip (#20770)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Runner and the shared `adapter-utils` engine run ACP
agents through the embedded ACPX library
> - Paperclip pins ACPX 0.13.1 and keeps a large patch
(`patches/acpx@0.13.1.patch`) on it
> - ACPX 0.22.0 adds host hooks (`onAcpMessage`, `assertActive`,
`processLifecycle`, prompt-response `_meta`, `spawnAgent`-friendly
launch) that make much of that patch unnecessary
> - A large patch is expensive to port and hides behavior that belongs
to Paperclip
> - This pull request upgrades to ACPX 0.22.0 and moves most patched
behavior into Runner and `adapter-utils`
> - The benefit is a patch that is 484 lines instead of 1,334, with the
moved behavior covered by Paperclip tests

## Linked Issues or Issue Description

Refs #20675, #14430, #15075, #17942, #9980

**Proposed enhancement**
Upgrade the embedded ACPX library from 0.13.1 to 0.22.0. Keep only the
patch behavior that stock 0.22 cannot express.

**Motivation**
The 0.13.1 patch held behavior that Paperclip owns, for example usage
receipts, Copilot policy, model checks and the agent environment. Each
ACPX upgrade had to port all of it. ACPX 0.22 gives hooks that let
Paperclip do this work itself.

**Current behavior**
Runner and `adapter-utils` depend on 1,334 lines of patched ACPX 0.13.1
code.

**Expected behavior**
Runner and `adapter-utils` use ACPX 0.22.0. The patch keeps only:
extension methods, Cursor subagent routing, event `_meta` and the
message boundary chunk, the protocol guard hook, `spawnAgent`, and
`requestExtension`.

## What Changed

- ACPX 0.13.1 → 0.22.0 in Runner, `adapter-utils`, the server, the
Daytona runner images and the qualified profiles (`acpxVersion`).
`@agentclientprotocol/sdk` moves to 1.9.0.
- New `patches/acpx@0.22.0.patch` (484 lines). The 0.12.0 and 0.13.1
patches are removed.
- Delivery receipts: Runner confirms a permission reply when
`onAcpMessage` sees the exact outbound reply. Question and extension
replies count as delivered when Runner hands them back to ACPX. New
`interaction-delivery.ts`.
- Copilot policy: the existing policy function runs from `onAcpMessage`.
A violation stops the agent, cancels later permission requests and fails
the next prompt through `assertActive`.
- Model selection: stock 0.22 validation, plus a sidecar gate
(`createAcpxEffectiveModelGate`) that refuses a prompt if the agent
reports another model. Grok binds its model when the session opens.
Antigravity adds its concrete model to the model list ACPX reads.
- Typed session failures: Runner and `adapter-utils` read them from the
turn result `_meta` and fail the turn. They advertise the capability
themselves.
- Pi and Cursor usage receipts: a collector (`prompt-receipts.ts`) binds
them to the turn's own `session/prompt` reply.
- Goal capability: Runner reads it from the `initialize` reply. It keeps
it under `paperclip.goalCapability` in the saved agent capabilities
`_meta` and restores it when a saved session loads.
- Agent environment: Runner and `adapter-utils` set the agent
environment in `spawnAgent`. ACP terminals keep their current
environment. `adapter-utils` blocks inheritance of `XAI_API_KEY` and
refuses to start if the server has an `ACPX_AUTH_*` variable.
- `adapter-utils` spawn hooks (`spawnCwd`, stderr, `onAgentSpawn`): a
new `stockAcpRuntimeOptions` maps them to stock `spawnAgent` and
`processLifecycle`.
- Windows: ACPX 0.22 rejects raw command strings on Windows.
`adapter-utils` now passes an argv array there.
- Grok rules: a Runner guard (`grok-session-rules.ts`) writes
`session/new` `_meta.rules`.
- Turn-dispatch journal (#20675): ACPX 0.22 ignores errors from
`onAcpMessage`. The adapter keeps a failed `dispatched` write and throws
it from the turn's `assertActive`. ACPX calls `assertActive` before the
prompt write, so the write still stops. The real-ACPX test now checks
this route. `docs/durable-recovery.md` is updated.
- Plan events: the sidecar reads 0.22 `status` events tagged `plan`.
- CI: the backup-checkpoint lane now installs through the shared
`setup-ci-dependencies` action, like PR CI, so it resolves a stale
`pnpm-lock.yaml` in place. It runs on any root `package.json` change,
and pull requests never commit the lockfile, so its own frozen install
failed on dependency changes.
- Tests that checked removed patch internals are removed or rewritten:
the response-delivery, Cursor-usage and Pi-receipt package contracts,
and the goal-persistence packaging test. New unit tests cover the moved
behavior.

## Verification

Local runs on macOS (darwin-arm64), Node 26, on the rebased head:

- `pnpm --filter @paperclipai/paperclip-runner exec vitest run
src/drivers/acpx src/cli`: 2,000 passed.
- `tsc -p packages/paperclip-runner/tsconfig.json` and
`tsconfig.test.json`: no errors, except the existing
`@paperclipai/paperclip-eval-kernel` build gap in `workflow-harness.ts`.
- Runner package contracts (`node --test
test/acpx-*-package-contract.test.mjs
test/acpx-sidecar-contract.test.mjs`), `scripts/build-inputs.test.mjs`,
`scripts/contracts/contract-fingerprints.test.mjs`,
`scripts/acpx-patch-packaging.test.mjs`: all pass. `node
scripts/generate-acpx-sidecar-contract.mjs --check` passes.
- `cargo test -p paperclip-runner-core --test acpx_park_preparation
--test acpx_park_readiness --test acpx_warm_attachment --test
native_provider_backend`: 86 passed. `cargo fmt --check` passes.
- `adapter-utils`: `tsc` clean. `vitest run src/acpx-engine
src/mcp-isolation.integration.test.ts`: 457 passed (one Gemini flag test
failed once under load and passes when run alone).
- Adapters: `claude-local` and `codex-local` `acp.quota.test.ts` (23 and
39 passed), `grok-local` (149 passed).
- Server: `scripts/prepare-runner-vendor.test.mjs`,
`native-session-executor.test.ts`, `quarantined-task-retry.test.ts`
(1,416 passed).
- `cargo test -p paperclip-runner-core --lib -- previous_acpx_release
acpx_upgrade unrestorable_saved_sessions`: 3 passed. `node --test
test/acpx-session-carry-forward-package-contract.test.mjs`: passes.
- `patch -p1 --forward` on a clean `acpx-0.22.0.tgz` gives output
identical to the port.
- Under full-suite load, some Runner live and recovery tests time out.
Each one passes when run alone. Full regression is left to CI.

Not run: live provider runs (they need provider credentials), the opt-in
Kimi live peer test, the Gemini filesystem smoke test, and Windows.

## Risks

- Previous-release story: sessions saved by the previous release (ACPX
0.13.1) carry forward. ACPX 0.22 loads the session records 0.13.1 wrote.
Runner moves a saved descriptor that names 0.13.1
(`CARRIED_ACPX_RELEASES`) to 0.22.0, and the sidecar keeps 0.13.1 as the
ACPX value in the session identity, so the saved session key and
identity record still match. The existing launch-profile rebind still
decides which sessions resume: a settled session, or the same run's
interrupted turn through lost-turn recovery. A session saved by any
other ACPX release is still refused as `provider_state_incompatible`.
`rules/acpx-profile-identity.mdc` and `docs/durable-recovery.md` now
describe this.
- Proof: `acpx-session-carry-forward-package-contract.test.mjs` resumes
a session record written by the real ACPX 0.13.1 with its Paperclip
patch. 0.22 loads the same provider session (no `session/new`), runs a
turn and keeps the earlier turn. Rust tests cover a settled 0.13.1
session that the next run attaches to, and a turn interrupted by the
upgrade. A recovery-identity test checks that the session key and
identity record match across the versions.
- `pnpm-lock.yaml` is not committed. CI resolves it for each run, and
the lockfile refresh workflow updates it after merge.
- Behavior change on the server: `adapter-utils` refuses to create an
ACPX runtime if the server environment has an `ACPX_AUTH_*` variable.
Before, ACPX ignored such variables. Stock 0.22 would use them to
authenticate agents with server credentials.
- Delivery confirmation is now Runner-owned. A permission reply is
confirmed by the exact outbound message. Question and extension replies
are confirmed when Runner hands them to ACPX, not when the pipe accepts
them.
- Users can select only models that the agent advertises. Stock 0.22
rejects other model IDs (Claude is exempt).
- ACP terminals keep the sidecar or server environment, as before. This
existing exposure is not changed by this pull request.
- The `adapter-utils` Gemini version probe now runs with the server
environment plus the run variables, not the run variables alone.
- The pack contract digest and profile `acpxVersion` change, so Daytona
needs a new runner image.
- Grok launch flags (`--model`, `--reasoning-effort`) were checked on
1.0.13 but session open needs a login, so Grok keeps the existing
`_meta` path.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool
use (shell, file editing, subagents). Extended reasoning was used.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 07:28:00 -08:00

468 lines
24 KiB
JavaScript

#!/usr/bin/env node
import { execFileSync } from "node:child_process";
import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { basename, dirname, isAbsolute, relative, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
const repoRoot = resolve(fileURLToPath(new URL("..", import.meta.url)));
const nativeTargets = ["linux-x64", "darwin-arm64", "darwin-x64"];
export function materializePublishManifest(pkg) {
const publishConfig = pkg.publishConfig ?? {};
const publishManifest = { ...pkg };
for (const key of ["main", "types", "exports", "bin"]) {
if (publishConfig[key] !== undefined) publishManifest[key] = publishConfig[key];
}
for (const section of ["dependencies", "optionalDependencies", "peerDependencies"]) {
if (!publishManifest[section]) continue;
publishManifest[section] = Object.fromEntries(
Object.entries(publishManifest[section]).map(([name, specifier]) => {
if (typeof specifier !== "string" || !specifier.startsWith("workspace:")) return [name, specifier];
const range = specifier.slice("workspace:".length);
const prefix = range === "^" || range === "~" ? range : "";
return [name, `${prefix}${pkg.version}`];
}),
);
}
delete publishManifest.publishConfig;
return publishManifest;
}
export function createBundledInstallManifest(publishManifest, bundledDependencies) {
const bundledDependencyNames = new Set(bundledDependencies);
const installManifest = structuredClone(publishManifest);
delete installManifest.devDependencies;
for (const section of ["dependencies", "optionalDependencies", "peerDependencies"]) {
if (!installManifest[section]) continue;
installManifest[section] = Object.fromEntries(
Object.entries(installManifest[section]).filter(([name]) => bundledDependencyNames.has(name)),
);
if (Object.keys(installManifest[section]).length === 0) delete installManifest[section];
}
return installManifest;
}
// npm consumers cannot inherit the workspace's pnpm overrides or patches.
// Materialize the already-qualified provider bridge closures in the tarball,
// with overrides confined to the temporary, scripts-disabled producer graph.
export function configureBundledProviderOverrides(installManifest, bundledDependencies, rootPackage, profileData) {
const result = structuredClone(installManifest);
const selected = [];
for (const [agent, serverPackage, runtimePackage] of [
["codex", "@agentclientprotocol/codex-acp", "@openai/codex"],
["claude", "@agentclientprotocol/claude-agent-acp", "@anthropic-ai/claude-agent-sdk"],
]) {
if (!bundledDependencies.includes(serverPackage)) continue;
const profile = profileData?.profiles?.[agent];
if (profileData?.schema !== "paperclip.acpx-profiles.v1" || profile?.agentServerPackage !== serverPackage
|| profile.agentRuntimePackage !== runtimePackage || !/^\d+\.\d+\.\d+$/.test(profile.agentServerVersion ?? "")
|| !/^\d+\.\d+\.\d+$/.test(profile.agentRuntimeVersion ?? "")
|| result.dependencies?.[serverPackage] !== profile.agentServerVersion) {
throw new Error(`Bundled ${agent} bridge must match its exact qualified profile`);
}
const selector = `${serverPackage}@${profile.agentServerVersion}>${runtimePackage}`;
if (rootPackage.pnpm?.overrides?.[selector] !== profile.agentRuntimeVersion) {
throw new Error(`Bundled ${agent} runtime override must match its qualified profile`);
}
const npmSelector = `${serverPackage}@${profile.agentServerVersion}`;
if (result.overrides?.[npmSelector] !== undefined) {
throw new Error(`Bundled ${agent} runtime has a conflicting producer override`);
}
const overrides = { [runtimePackage]: profile.agentRuntimeVersion,
...(agent === "claude" ? { "@agentclientprotocol/sdk": "1.4.0", zod: "4.4.3" } : {}),
};
result.overrides = { ...result.overrides, [npmSelector]: overrides };
selected.push({ agent, ...profile });
}
return { installManifest: result, profiles: selected };
}
const inside = (root, candidate) => {
const value = relative(root, candidate);
return value !== "" && value !== ".." && !value.startsWith(`..${sep}`) && !isAbsolute(value);
};
// Bundle the pinned JavaScript closure, never the producer's executable.
// npm installs the official optional package for the consumer's own platform.
export function stageBundledProviderOptionalDependencies(destinationDir, publishManifest, profiles) {
const graphRoot = resolve(destinationDir, "node_modules");
if (realpathSync(graphRoot) !== graphRoot) throw new Error("Bundled Codex graph must be a canonical owned directory");
const result = structuredClone(publishManifest), remove = new Set(), optional = {}, normalize = new Map();
if (!profiles.length || new Set(profiles.map(profile => profile.agent)).size !== profiles.length) {
throw new Error("Bundled provider graph must contain distinct qualified profiles");
}
for (const profile of profiles) {
const expected = profile.agent === "codex" ? ["@agentclientprotocol/codex-acp", "@openai/codex"]
: profile.agent === "claude" ? ["@agentclientprotocol/claude-agent-acp", "@anthropic-ai/claude-agent-sdk"] : null;
if (!expected || profile.agentServerPackage !== expected[0] || profile.agentRuntimePackage !== expected[1]) {
throw new Error("Bundled provider graph contains an unknown provider profile");
}
const label = profile.agent === "codex" ? "Codex" : "Claude";
const targets = ["linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64", "win32-x64", "win32-arm64",
...(profile.agent === "claude" ? ["linux-x64-musl", "linux-arm64-musl"] : [])];
const declarations = Object.fromEntries(targets.map(target => [`${profile.agentRuntimePackage}-${target}`,
profile.agent === "codex" ? `npm:${profile.agentRuntimePackage}@${profile.agentRuntimeVersion}-${target}` : profile.agentRuntimeVersion]));
const ownedDirectory = directory => {
const stat = lstatSync(directory);
if (!stat.isDirectory() || stat.isSymbolicLink() || !inside(graphRoot, realpathSync(directory))) {
throw new Error(`Bundled ${label} dependency escapes its producer graph`);
}
};
const manifestAt = directory => {
const path = resolve(directory, "package.json"), stat = lstatSync(path);
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 256 * 1024) {
throw new Error(`Bundled ${label} dependency manifest must be a bounded regular file`);
}
return JSON.parse(readFileSync(path, "utf8"));
};
const bridgeDirectory = resolve(graphRoot, profile.agentServerPackage);
ownedDirectory(bridgeDirectory);
const bridge = manifestAt(bridgeDirectory);
if (bridge.name !== profile.agentServerPackage || bridge.version !== profile.agentServerVersion) throw new Error(`Bundled ${label} bridge version mismatch`);
const issuer = createRequire(resolve(bridgeDirectory, "package.json"));
let runtimeManifest;
try { runtimeManifest = issuer.resolve(`${profile.agentRuntimePackage}/package.json`); }
catch (error) {
if (error.code !== "ERR_PACKAGE_PATH_NOT_EXPORTED") throw error;
runtimeManifest = resolve(dirname(issuer.resolve(profile.agentRuntimePackage)), "package.json");
}
runtimeManifest = realpathSync(runtimeManifest);
if (!inside(graphRoot, runtimeManifest)) throw new Error(`Bundled ${label} runtime escapes its producer graph`);
let runtimeCount = 0, packageCount = 0;
const pending = [{ directory: graphRoot, depth: 0 }];
while (pending.length) {
const { directory, depth } = pending.pop();
if (depth > 64) throw new Error(`Bundled ${label} graph exceeds its depth limit`);
const packages = [];
for (const entry of readdirSync(directory)) {
if (entry.startsWith(".")) continue;
const candidate = resolve(directory, entry); ownedDirectory(candidate);
if (entry.startsWith("@")) {
for (const child of readdirSync(candidate)) {
const scoped = resolve(candidate, child); ownedDirectory(scoped); packages.push(scoped);
}
} else packages.push(candidate);
}
for (const packageDirectory of packages) {
if (++packageCount > 20_000) throw new Error(`Bundled ${label} graph exceeds its package limit`);
const metadata = manifestAt(packageDirectory);
const scope = basename(dirname(packageDirectory));
const binding = scope.startsWith("@") ? `${scope}/${basename(packageDirectory)}` : basename(packageDirectory);
if (binding.startsWith(`${profile.agentRuntimePackage}-`)) {
const target = binding.slice(profile.agentRuntimePackage.length + 1), [os, cpu] = target.split("-");
if (!Object.hasOwn(declarations, binding) || !(metadata.name === binding || (profile.agent === "codex" && metadata.name === profile.agentRuntimePackage))
|| metadata.version !== (profile.agent === "codex" ? `${profile.agentRuntimeVersion}-${target}` : profile.agentRuntimeVersion) || !metadata.os?.includes(os) || !metadata.cpu?.includes(cpu)) {
throw new Error(`Bundled ${label} installed platform identity mismatch`);
}
remove.add(packageDirectory);
continue;
}
const nested = resolve(packageDirectory, "node_modules");
if (lstatExists(nested)) { ownedDirectory(nested); pending.push({ directory: nested, depth: depth + 1 }); }
if (binding !== profile.agentRuntimePackage) continue;
if (metadata.name !== profile.agentRuntimePackage || metadata.version !== profile.agentRuntimeVersion) throw new Error(`Bundled ${label} runtime version mismatch`);
runtimeCount++;
const delegated = metadata.optionalDependencies === undefined
&& Object.entries(declarations).every(([name, specifier]) => result.optionalDependencies?.[name] === specifier);
if (!delegated && (Object.keys(metadata.optionalDependencies ?? {}).length !== targets.length
|| targets.some(target => metadata.optionalDependencies?.[`${profile.agentRuntimePackage}-${target}`] !== declarations[`${profile.agentRuntimePackage}-${target}`]))) {
throw new Error(`Bundled ${label} platform declaration is not qualified`);
}
if (!delegated) {
const normalized = { ...metadata }; delete normalized.optionalDependencies;
normalize.set(resolve(packageDirectory, "package.json"), normalized);
}
const vendor = resolve(packageDirectory, "vendor");
if (profile.agent === "codex" && lstatExists(vendor)) { ownedDirectory(vendor); remove.add(vendor); }
}
}
if (!runtimeCount) throw new Error(`Bundled ${label} runtime omitted its platform declarations`);
for (const [name, specifier] of Object.entries(declarations)) {
if (result.optionalDependencies?.[name] !== undefined && result.optionalDependencies[name] !== specifier) throw new Error(`Bundled ${label} platform conflicts with published dependency: ${name}`);
optional[name] = specifier;
}
}
// A bundled wrapper's optional edges make npm treat missing platform slots
// as bundled too. Delegate those exact declarations to the unbundled server
// root so normal npm can install the correct host version beside legacy deps.
// Validate the complete graph before changing metadata or deleting payloads.
for (const [path, metadata] of normalize) writeFileSync(path, `${JSON.stringify(metadata, null, 2)}\n`);
for (const directory of remove) rmSync(directory, { recursive: true, force: true });
result.optionalDependencies = { ...result.optionalDependencies, ...optional };
for (const field of ["bundleDependencies", "bundledDependencies"]) {
if (Array.isArray(result[field])) result[field] = result[field].filter(name => !Object.hasOwn(optional, name));
}
delete result.paperclipProviderArtifacts;
return result;
}
function lstatExists(path) {
try { lstatSync(path); return true; }
catch (error) { if (error.code === "ENOENT") return false; throw error; }
}
// A Linux-produced bundle contains esbuild's JavaScript but only the producer's
// optional executable. Expose its exact platform declarations to the consumer,
// just as embedded-postgres does below, before retaining the original hooks.
export function stageBundledEsbuildOptionalDependencies(destinationDir, publishManifest) {
const graphRoot = resolve(destinationDir, "node_modules");
if (realpathSync(graphRoot) !== graphRoot) throw new Error("Bundled esbuild graph must be a canonical owned directory");
const result = structuredClone(publishManifest), pending = [{ directory: graphRoot, depth: 0 }];
const optional = {}, remove = new Set();
let packageCount = 0;
const ownedDirectory = directory => {
const stat = lstatSync(directory);
if (!stat.isDirectory() || stat.isSymbolicLink() || !inside(graphRoot, realpathSync(directory))) {
throw new Error("Bundled esbuild dependency escapes its producer graph");
}
};
const manifestAt = directory => {
const file = resolve(directory, "package.json"), stat = lstatSync(file);
if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 256 * 1024) {
throw new Error("Bundled esbuild dependency manifest must be a bounded regular file");
}
return JSON.parse(readFileSync(file, "utf8"));
};
while (pending.length) {
const { directory, depth } = pending.pop();
if (depth > 64) throw new Error("Bundled esbuild dependency graph exceeds its depth limit");
const packages = [];
for (const entry of readdirSync(directory)) {
if (entry.startsWith(".")) continue;
const candidate = resolve(directory, entry);
ownedDirectory(candidate);
if (entry.startsWith("@")) {
for (const child of readdirSync(candidate)) {
const scoped = resolve(candidate, child); ownedDirectory(scoped); packages.push(scoped);
}
} else packages.push(candidate);
}
for (const packageDirectory of packages) {
if (++packageCount > 20_000) throw new Error("Bundled esbuild dependency graph exceeds its package limit");
const metadata = manifestAt(packageDirectory);
const nested = resolve(packageDirectory, "node_modules");
if (lstatExists(nested)) { ownedDirectory(nested); pending.push({ directory: nested, depth: depth + 1 }); }
if (basename(packageDirectory) !== "esbuild") continue;
if (metadata.name !== "esbuild" || !/^\d+\.\d+\.\d+$/.test(metadata.version ?? "")) {
throw new Error("Bundled esbuild package identity mismatch");
}
const declarations = metadata.optionalDependencies ?? {};
if (nativeTargets.some(target => declarations[`@esbuild/${target}`] !== metadata.version)) {
throw new Error("Bundled esbuild omitted a supported platform declaration");
}
const issuer = createRequire(resolve(packageDirectory, "package.json"));
for (const [name, version] of Object.entries(declarations)) {
if (!/^@esbuild\/[a-z0-9]+-[a-z0-9]+$/.test(name) || version !== metadata.version) {
throw new Error("Bundled esbuild platform declaration must match its exact package version");
}
if ((optional[name] !== undefined && optional[name] !== version)
|| (result.optionalDependencies?.[name] !== undefined && result.optionalDependencies[name] !== version)) {
throw new Error(`Bundled esbuild platform version conflicts with published dependency: ${name}`);
}
optional[name] = version;
for (const lookup of issuer.resolve.paths(name) ?? []) {
const candidate = resolve(lookup, name);
if (!inside(graphRoot, candidate) || !lstatExists(candidate)) continue;
ownedDirectory(candidate);
const installed = manifestAt(candidate);
if (installed.name !== name || installed.version !== version) {
throw new Error(`Bundled esbuild installed platform identity mismatch: ${name}`);
}
remove.add(candidate);
}
}
}
}
for (const directory of remove) rmSync(directory, { recursive: true, force: true });
if (Object.keys(optional).length) result.optionalDependencies = { ...result.optionalDependencies, ...optional };
return result;
}
function patchedDependencyPackageName(specifier) {
const versionSeparator = specifier.lastIndexOf("@");
const packageNameEnd = specifier.startsWith("@") ? specifier.indexOf("/") : 0;
if (packageNameEnd < 0) return specifier;
return versionSeparator > packageNameEnd ? specifier.slice(0, versionSeparator) : specifier;
}
export function selectBundledDependencyPatches(
destinationDir,
bundledDependencies,
patchedDependencies,
) {
const patchesByPackageName = new Map();
for (const [specifier, patchPath] of Object.entries(patchedDependencies)) {
const packageName = patchedDependencyPackageName(specifier);
const packagePatches = patchesByPackageName.get(packageName) ?? new Map();
packagePatches.set(specifier, patchPath);
patchesByPackageName.set(packageName, packagePatches);
}
const selectedPatches = [];
for (const packageName of new Set(bundledDependencies)) {
const packagePatches = patchesByPackageName.get(packageName);
if (!packagePatches) continue;
const installedManifestPath = resolve(
destinationDir,
"node_modules",
packageName,
"package.json",
);
let installedManifest;
try {
installedManifest = JSON.parse(readFileSync(installedManifestPath, "utf8"));
} catch (cause) {
throw new Error(
`Cannot select a patch for bundled dependency ${packageName}: failed to read ${installedManifestPath}`,
{ cause },
);
}
if (
installedManifest.name !== packageName ||
typeof installedManifest.version !== "string" ||
installedManifest.version.length === 0
) {
throw new Error(
`Cannot select a patch for bundled dependency ${packageName}: installed package manifest must declare the expected name and a version`,
);
}
const installedSpecifier = `${packageName}@${installedManifest.version}`;
const patchPath = packagePatches.get(installedSpecifier);
if (patchPath === undefined) {
const configuredSpecifiers = [...packagePatches.keys()].sort().join(", ");
throw new Error(
`Cannot select a patch for bundled dependency ${packageName}: installed ${installedSpecifier}, but configured patches are ${configuredSpecifiers}`,
);
}
if (typeof patchPath !== "string" || patchPath.length === 0) {
throw new Error(`Patch path for ${installedSpecifier} must be a non-empty string`);
}
selectedPatches.push({ packageName, specifier: installedSpecifier, patchPath });
}
return selectedPatches;
}
export function applyBundledDependencyPatches(destinationDir, bundledDependencies, sourceRoot = repoRoot) {
const rootPackage = JSON.parse(readFileSync(resolve(sourceRoot, "package.json"), "utf8"));
const patchedDependencies = rootPackage.pnpm?.patchedDependencies ?? {};
for (const { packageName, patchPath } of selectBundledDependencyPatches(
destinationDir,
bundledDependencies,
patchedDependencies,
)) {
execFileSync(
"patch",
["-p1", "--forward", "-d", resolve(destinationDir, "node_modules", packageName)],
{
input: readFileSync(resolve(sourceRoot, patchPath)),
stdio: ["pipe", "inherit", "inherit"],
},
);
}
}
export function prepareBundledPackage(sourceDir, destinationDir, { sourceRoot = repoRoot } = {}) {
const sourcePackagePath = resolve(sourceDir, "package.json");
const sourcePackage = JSON.parse(readFileSync(sourcePackagePath, "utf8"));
const bundledDependencies = sourcePackage.bundleDependencies ?? sourcePackage.bundledDependencies ?? [];
if (bundledDependencies.length === 0) {
throw new Error(`${sourcePackage.name} does not declare bundled dependencies`);
}
rmSync(destinationDir, { recursive: true, force: true });
mkdirSync(destinationDir, { recursive: true });
for (const entry of sourcePackage.files ?? []) {
cpSync(resolve(sourceDir, entry), resolve(destinationDir, entry), { recursive: true });
}
for (const entry of ["README.md", "LICENSE", "LICENSE.md"]) {
const sourcePath = resolve(sourceDir, entry);
if (existsSync(sourcePath)) cpSync(sourcePath, resolve(destinationDir, entry));
}
const deployedPackagePath = resolve(destinationDir, "package.json");
const publishManifest = materializePublishManifest(sourcePackage);
const rootPackage = JSON.parse(readFileSync(resolve(sourceRoot, "package.json"), "utf8"));
const profileData = bundledDependencies.includes("@agentclientprotocol/codex-acp")
? JSON.parse(readFileSync(resolve(sourceRoot, "packages/paperclip-runner/acpx-profiles.json"), "utf8")) : undefined;
const { installManifest, profiles } = configureBundledProviderOverrides(
createBundledInstallManifest(publishManifest, bundledDependencies), bundledDependencies, rootPackage, profileData,
);
writeFileSync(deployedPackagePath, `${JSON.stringify(installManifest, null, 2)}\n`);
execFileSync(
"npm",
["install", "--omit=dev", "--ignore-scripts", "--no-audit", "--no-fund"],
{ cwd: destinationDir, stdio: "inherit" },
);
writeFileSync(deployedPackagePath, `${JSON.stringify(publishManifest, null, 2)}\n`);
applyBundledDependencyPatches(destinationDir, bundledDependencies, sourceRoot);
if (profiles.length) writeFileSync(deployedPackagePath, `${JSON.stringify(stageBundledProviderOptionalDependencies(destinationDir, publishManifest, profiles), null, 2)}\n`);
if (bundledDependencies.includes("acpx")) {
const acpxPackage = JSON.parse(
readFileSync(resolve(destinationDir, "node_modules/acpx/package.json"), "utf8"),
);
const expectedPatchMarker = {
"0.22.0": "requestExtension",
}[acpxPackage.version];
const acpxRuntime = readFileSync(
resolve(destinationDir, "node_modules/acpx/dist/runtime.js"),
"utf8",
);
if (!expectedPatchMarker || !acpxRuntime.includes(expectedPatchMarker)) {
throw new Error(
`staged acpx@${acpxPackage.version} runtime is missing the repository patch`,
);
}
}
if (bundledDependencies.includes("embedded-postgres")) {
const embeddedPostgresSource = readFileSync(
resolve(destinationDir, "node_modules/embedded-postgres/dist/index.js"),
"utf8",
);
if (
!embeddedPostgresSource.includes("const LC_MESSAGES_LOCALE = 'C';") ||
!embeddedPostgresSource.includes("globalThis.process.env")
) {
throw new Error("staged embedded-postgres runtime is missing the repository patch");
}
const embeddedPostgresPackage = JSON.parse(
readFileSync(resolve(destinationDir, "node_modules/embedded-postgres/package.json"), "utf8"),
);
const stagedPackage = JSON.parse(readFileSync(deployedPackagePath, "utf8"));
stagedPackage.optionalDependencies = {
...(stagedPackage.optionalDependencies ?? {}),
...(embeddedPostgresPackage.optionalDependencies ?? {}),
};
writeFileSync(deployedPackagePath, `${JSON.stringify(stagedPackage, null, 2)}\n`);
rmSync(resolve(destinationDir, "node_modules/@embedded-postgres"), { recursive: true, force: true });
}
writeFileSync(deployedPackagePath, `${JSON.stringify(stageBundledEsbuildOptionalDependencies(destinationDir,
JSON.parse(readFileSync(deployedPackagePath, "utf8"))), null, 2)}\n`);
}
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const [sourceDir, destinationDir] = process.argv.slice(2);
if (!sourceDir || !destinationDir) {
console.error("Usage: prepare-bundled-package.mjs <source-dir> <destination-dir>");
process.exit(1);
}
prepareBundledPackage(resolve(sourceDir), resolve(destinationDir));
}