Files
PaperClipAI/scripts/prepare-bundled-package.mjs
DottaandPaperclip db2f00947b fix(runner): include Claude ACP in the server package (#15912)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The server ships a copy of Paperclip Runner for native agent
execution.
> - The Claude ACP bridge is a runner dependency, but it was absent from
the server package.
> - The runner resolves this bridge dynamically, so the import-based
packaging check missed it.
> - A Claude session then failed before startup and showed a generic
connection error.
> - This pull request ships the qualified bridge and reports a missing
runtime with repair steps.

## Linked Issues or Issue Description

**What happened?**

A server install with the vendored runner could not load
`@agentclientprotocol/claude-agent-acp/package.json`. The runtime test
suggested checking the model or provider connection. The task reported
an interrupted runner session.

**Expected behavior**

The server package includes its qualified Claude ACP runtime. A missing
bundled runtime reports an installation error and explains how to repair
it.

**Steps to reproduce**

1. Use a server install with the vendored runner and no Claude ACP
bridge.
2. Select the Paperclip Runner ACP harness and the Claude provider.
3. Run the runtime test or open a session.
4. Observe a missing-module failure before Claude starts.

**Paperclip version or commit**

Reproduced on `e733bddc45`. This branch is based on current master.

**Deployment mode**

Self-hosted server built from source.

Related: #15224 upgrades the Claude bridge. This PR fixes its omission
from the server package and keeps the current qualified version. A
future bridge upgrade must update the server pin too.

## What Changed

- Add Claude ACP `0.73.0` to the server dependencies and bundled
dependencies.
- Pin the qualified Claude SDK and bridge dependencies in the npm bundle
producer graph. Publish its native packages as consumer optional
dependencies instead of shipping the producer executable.
- Bind source-built vendored runners to the shared pnpm dependency store
while retaining the server manifest as the provider authority. Keep
published npm and self-rooted deployment roots unchanged.
- Include dynamically resolved Claude and Codex bridges in the vendor
dependency check.
- Preserve the missing-package category through the sidecar, Rust
transport, and native session executor. Stop automatic retries for this
installation failure.
- Show **Runtime missing** in the runtime test and task thread. Explain
the reinstall or rebuild, server restart, and runtime test steps.
- Add regression tests and document the repair procedure.

## Verification

- Red/green comparison with the production sidecar: the same
missing-package setup returns a raw require-stack error on the original
code and an actionable, non-retryable missing-runtime error on this
branch.
- The rebuilt server's vendored Claude installation probe passes using
the source-server authority selected by the launcher, without starting a
provider or making a model request.
- Focused server verification: 830 tests passed. Runner installation and
sidecar error tests: 83 passed, with 6 platform-specific skips.
Packaging tests: 28 passed. Rust transport tests: 7 passed.
- Source/deployment authority tests: 3 passed. Red/green packaging tests
include a Linux-produced Claude SDK bundle, actual npm pack, and closed
executable admission on Linux x64 and macOS ARM64/x64.
- Full UI suite: 8,113 tests passed.
- `pnpm -r typecheck` and `pnpm build` passed on the rebased branch.
- Full current-head CI passed, including all general and serialized test
lanes, Runner Rust/Vitest verification, typecheck, build, and all eight
e2e shards. Greptile reviewed `d6a2741834ff922956560f2f689382827bbaf9e0`
at 5/5 with no unresolved threads.
- Local full-suite limitation: an earlier parallel attempt hit Postgres
startup failures and timeouts; the affected server tests and a database
fixture passed in isolation. The subsequent serial `pnpm test:run` was
stopped while still running after complete CI passed. Focused local
tests, full UI tests, typecheck, and build completed as listed above.
- Token gates and `git diff --check` passed.

## Risks

- Bundling the Claude bridge increases the server package size. The
producer graph retains the qualified SDK version and existing isolation
patch. Native platform declarations move to the published server
manifest, while the runtime keeps its exact version, declared-slot,
no-follow, and executable digest checks.
- The new failure category is permanent. Operators must repair the
server installation before they retry the task.
- Existing failed runs retain their recorded error. The clearer message
applies to new runtime tests and runs.
- No database schema or migration changes.

## Model Used

OpenAI GPT-6 through Codex. The system reports the model family; the
exact deployment ID and context-window size are not exposed in this
session. Used reasoning, browser inspection, tool use, and code
execution.

## 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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-12 06:51:22 -05:00

469 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.12.0": "onAgentStderr",
"0.13.1": "spawnEnvironment",
}[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));
}