mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-01 23:43:16 +01:00
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>
This commit is contained in:
1 parent
1b4c803816
commit
db2f00947b
21 files changed
+471
-103
No files matched your search
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import {
|
||||
existsSync,
|
||||
cpSync,
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
@@ -56,6 +57,33 @@ function esbuildFixture(t) {
|
||||
}
|
||||
const codexTargets = ["linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64", "win32-x64", "win32-arm64"];
|
||||
const codexOptional = Object.fromEntries(codexTargets.map(target => [`@openai/codex-${target}`, `npm:@openai/codex@0.160.0-${target}`]));
|
||||
const claudeTargets = [...codexTargets, "linux-x64-musl", "linux-arm64-musl"];
|
||||
const claudeOptional = Object.fromEntries(claudeTargets.map(target => [`@anthropic-ai/claude-agent-sdk-${target}`, "0.3.286"]));
|
||||
function claudeFixture(t) {
|
||||
const directory = realpathSync(mkdtempSync(join(tmpdir(), "paperclip-bundled-claude-")));
|
||||
t.after(() => rmSync(directory, { recursive: true, force: true }));
|
||||
const graph = join(directory, "node_modules");
|
||||
const writePackage = (location, metadata) => {
|
||||
mkdirSync(location, { recursive: true });
|
||||
writeFileSync(join(location, "package.json"), JSON.stringify(metadata));
|
||||
return location;
|
||||
};
|
||||
const bridge = writePackage(join(graph, "@agentclientprotocol/claude-agent-acp"), {
|
||||
name: "@agentclientprotocol/claude-agent-acp", version: "0.73.0", dependencies: { "@anthropic-ai/claude-agent-sdk": "0.3.286" },
|
||||
});
|
||||
writeFileSync(join(bridge, "index.js"), "export {};\n");
|
||||
const runtime = writePackage(join(graph, "@anthropic-ai/claude-agent-sdk"), {
|
||||
name: "@anthropic-ai/claude-agent-sdk", version: "0.3.286", exports: { ".": "./sdk.mjs" }, optionalDependencies: claudeOptional,
|
||||
});
|
||||
writeFileSync(join(runtime, "sdk.mjs"), "// official JavaScript fixture, never executed\n");
|
||||
const producer = writePackage(join(graph, "@anthropic-ai/claude-agent-sdk-linux-x64"), {
|
||||
name: "@anthropic-ai/claude-agent-sdk-linux-x64", version: "0.3.286", os: ["linux"], cpu: ["x64"],
|
||||
});
|
||||
writeFileSync(join(producer, "claude"), "producer native fixture, never executed");
|
||||
const profiles = [{ agent: "claude", ...profileData.profiles.claude }];
|
||||
const publish = { name: "paperclip-claude-pack-fixture", version: "1.0.0", dependencies: { "@agentclientprotocol/claude-agent-acp": "0.73.0" }, bundleDependencies: ["@agentclientprotocol/claude-agent-acp"] };
|
||||
return { directory, graph, bridge, runtime, producer, profiles, publish, writePackage };
|
||||
}
|
||||
function codexFixture(t) {
|
||||
const directory = realpathSync(mkdtempSync(join(tmpdir(), "paperclip-bundled-codex-")));
|
||||
t.after(() => rmSync(directory, { recursive: true, force: true }));
|
||||
@@ -176,13 +204,26 @@ test("published packages preserve the patched ACPX runtime", () => {
|
||||
assert.equal(cliEsbuildConfig.external.includes("acpx"), false);
|
||||
});
|
||||
|
||||
test("published Claude bridge pins its qualified SDK and provider dependency closure", () => {
|
||||
const published = materializePublishManifest(serverPackage);
|
||||
const { installManifest } = configureBundledProviderOverrides(
|
||||
createBundledInstallManifest(published, serverPackage.bundleDependencies),
|
||||
serverPackage.bundleDependencies, rootPackage, profileData,
|
||||
);
|
||||
assert.deepEqual(installManifest.overrides["@agentclientprotocol/claude-agent-acp@0.73.0"], {
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.286",
|
||||
"@agentclientprotocol/sdk": "1.4.0",
|
||||
zod: "4.4.3",
|
||||
});
|
||||
});
|
||||
|
||||
test("published Codex bridge uses its qualified producer closure without consumer overrides", () => {
|
||||
const published = materializePublishManifest(serverPackage);
|
||||
const { installManifest, profiles } = configureBundledProviderOverrides(
|
||||
createBundledInstallManifest(published, serverPackage.bundleDependencies),
|
||||
serverPackage.bundleDependencies, rootPackage, profileData,
|
||||
);
|
||||
assert.equal(profiles.length, 1);
|
||||
assert.deepEqual(profiles.map(profile => profile.agent), ["codex", "claude"]);
|
||||
for (const profile of profiles) {
|
||||
assert.equal(published.dependencies[profile.agentServerPackage], profile.agentServerVersion);
|
||||
assert.ok(published.bundleDependencies.includes(profile.agentServerPackage));
|
||||
@@ -201,6 +242,58 @@ test("published Codex bridge uses its qualified producer closure without consume
|
||||
assert.throws(() => configureBundledProviderOverrides(conflict, serverPackage.bundleDependencies, rootPackage, profileData), /conflicting producer override/);
|
||||
});
|
||||
|
||||
test("Linux-produced Claude bundles retain the SDK and install native packages for the consumer platform", (t) => {
|
||||
const { directory, bridge, runtime, producer, profiles, publish } = claudeFixture(t);
|
||||
const bridgeBefore = readFileSync(join(bridge, "package.json"), "utf8");
|
||||
const staged = stageBundledProviderOptionalDependencies(directory, publish, profiles);
|
||||
assert.deepEqual(staged.optionalDependencies, claudeOptional);
|
||||
assert.equal(existsSync(producer), false);
|
||||
assert.equal(JSON.parse(readFileSync(join(runtime, "package.json"), "utf8")).optionalDependencies, undefined);
|
||||
assert.equal(readFileSync(join(bridge, "package.json"), "utf8"), bridgeBefore);
|
||||
assert.deepEqual(stageBundledProviderOptionalDependencies(directory, staged, profiles), staged);
|
||||
writeFileSync(join(directory, "package.json"), JSON.stringify(staged));
|
||||
const packs = JSON.parse(execFileSync("npm", ["pack", "--ignore-scripts", "--offline", "--json"], {
|
||||
cwd: directory, encoding: "utf8", timeout: 30_000,
|
||||
env: { ...process.env, HOME: directory, npm_config_cache: join(directory, "cache"), npm_config_update_notifier: "false" },
|
||||
}));
|
||||
const paths = packs[0].files.map(file => file.path);
|
||||
assert.ok(paths.some(path => path.endsWith("@anthropic-ai/claude-agent-sdk/sdk.mjs")));
|
||||
assert.equal(paths.some(path => /@anthropic-ai\/claude-agent-sdk-(?:linux|darwin|win32)-/.test(path)), false);
|
||||
});
|
||||
|
||||
test("Claude bundle validation rejects unqualified declarations before removing native payloads", (t) => {
|
||||
const { directory, runtime, producer, profiles, publish } = claudeFixture(t);
|
||||
const file = join(runtime, "package.json"), original = JSON.parse(readFileSync(file, "utf8"));
|
||||
for (const metadata of [
|
||||
{ ...original, version: "0.3.285" },
|
||||
{ ...original, optionalDependencies: { ...claudeOptional, "@anthropic-ai/claude-agent-sdk-darwin-arm64": "latest" } },
|
||||
{ ...original, optionalDependencies: {} },
|
||||
]) {
|
||||
writeFileSync(file, JSON.stringify(metadata));
|
||||
assert.throws(() => stageBundledProviderOptionalDependencies(directory, publish, profiles), /version mismatch|not qualified/);
|
||||
assert.equal(existsSync(producer), true);
|
||||
}
|
||||
});
|
||||
|
||||
test("mixed provider bundles validate both runtimes before removing either producer executable", (t) => {
|
||||
const codex = codexFixture(t), claude = claudeFixture(t);
|
||||
for (const name of ["@agentclientprotocol/claude-agent-acp", "@anthropic-ai/claude-agent-sdk", "@anthropic-ai/claude-agent-sdk-linux-x64"]) {
|
||||
cpSync(join(claude.graph, name), join(codex.graph, name), { recursive: true });
|
||||
}
|
||||
const profiles = [...codex.profiles, ...claude.profiles];
|
||||
const publish = { ...codex.publish, dependencies: { ...codex.publish.dependencies, ...claude.publish.dependencies },
|
||||
bundleDependencies: [...codex.publish.bundleDependencies, ...claude.publish.bundleDependencies] };
|
||||
const file = join(codex.graph, "@anthropic-ai/claude-agent-sdk/package.json");
|
||||
const metadata = JSON.parse(readFileSync(file, "utf8"));
|
||||
writeFileSync(file, JSON.stringify({ ...metadata, version: "0.3.285" }));
|
||||
assert.throws(() => stageBundledProviderOptionalDependencies(codex.directory, publish, profiles), /Claude runtime version mismatch/);
|
||||
assert.equal(existsSync(codex.producer), true);
|
||||
assert.deepEqual(JSON.parse(readFileSync(join(codex.runtime, "package.json"), "utf8")).optionalDependencies, codexOptional);
|
||||
writeFileSync(file, JSON.stringify(metadata));
|
||||
const staged = stageBundledProviderOptionalDependencies(codex.directory, publish, profiles);
|
||||
assert.deepEqual(staged.optionalDependencies, { ...codexOptional, ...claudeOptional });
|
||||
});
|
||||
|
||||
test("Codex bundles retain pinned JavaScript and delegate official consumer platform aliases without native payloads", (t) => {
|
||||
const { directory, graph, bridge, runtime, producer, nested, profiles, publish } = codexFixture(t);
|
||||
const before = [bridge, runtime].map(path => readFileSync(join(path, "package.json"), "utf8"));
|
||||
@@ -530,7 +623,7 @@ mkdir -p "$destination/node_modules/.pnpm"
|
||||
set -euo pipefail
|
||||
printf 'npm %s\\n' "$*" >> "$FAKE_CALL_LOG"
|
||||
[ "$*" = "install --omit=dev --ignore-scripts --no-audit --no-fund" ]
|
||||
node -e 'const fs = require("node:fs"); const pkg = require("./package.json"); if ("devDependencies" in pkg) process.exit(1); for (const [name, version] of Object.entries(pkg.dependencies)) { const dir = "node_modules/" + name; fs.mkdirSync(dir + "/dist", { recursive: true }); fs.writeFileSync(dir + "/package.json", JSON.stringify({ name, version })); } for (const [bridge, runtimes] of Object.entries(pkg.overrides ?? {})) { for (const [name, version] of Object.entries(runtimes)) { const dir = "node_modules/" + name; fs.mkdirSync(dir, { recursive: true }); const native = name === "@openai/codex"; const optionalDependencies = native ? Object.fromEntries(["linux-x64","linux-arm64","darwin-x64","darwin-arm64","win32-x64","win32-arm64"].map(target => [name+"-"+target,"npm:"+name+"@"+version+"-"+target])) : undefined; fs.writeFileSync(dir + "/package.json", JSON.stringify({ name, version, optionalDependencies })); } }'
|
||||
node -e 'const fs = require("node:fs"); const pkg = require("./package.json"); if ("devDependencies" in pkg) process.exit(1); for (const [name, version] of Object.entries(pkg.dependencies)) { const dir = "node_modules/" + name; fs.mkdirSync(dir + "/dist", { recursive: true }); fs.writeFileSync(dir + "/package.json", JSON.stringify({ name, version })); } for (const [bridge, runtimes] of Object.entries(pkg.overrides ?? {})) { for (const [name, version] of Object.entries(runtimes)) { const dir = "node_modules/" + name; fs.mkdirSync(dir, { recursive: true }); const native = name === "@openai/codex"; const targets = ["linux-x64","linux-arm64","darwin-x64","darwin-arm64","win32-x64","win32-arm64"]; const optionalDependencies = native ? Object.fromEntries(targets.map(target => [name+"-"+target,"npm:"+name+"@"+version+"-"+target])) : name === "@anthropic-ai/claude-agent-sdk" ? Object.fromEntries([...targets,"linux-x64-musl","linux-arm64-musl"].map(target => [name+"-"+target,version])) : undefined; fs.writeFileSync(dir + "/package.json", JSON.stringify({ name, version, optionalDependencies })); } }'
|
||||
node -e 'const fs=require("node:fs");fs.cpSync(process.env.FAKE_NATIVE_ARTIFACTS+"/@openai/codex-linux-x64","node_modules/@openai/codex-linux-x64",{recursive:true});fs.mkdirSync("node_modules/@openai/codex/vendor",{recursive:true});fs.writeFileSync("node_modules/@openai/codex/vendor/codex","producer fallback fixture");'
|
||||
mkdir -p node_modules/acpx/dist
|
||||
node -e 'const fs=require("node:fs");fs.mkdirSync("node_modules/esbuild",{recursive:true});fs.writeFileSync("node_modules/esbuild/package.json",JSON.stringify({name:"esbuild",version:"0.28.2",scripts:{postinstall:"node install.js"},optionalDependencies:Object.fromEntries(["linux-x64","darwin-arm64","darwin-x64"].map(target=>["@esbuild/"+target,"0.28.2"]))}));fs.mkdirSync("node_modules/@esbuild/linux-x64",{recursive:true});fs.writeFileSync("node_modules/@esbuild/linux-x64/package.json",JSON.stringify({name:"@esbuild/linux-x64",version:"0.28.2",os:["linux"],cpu:["x64"]}));'
|
||||
@@ -590,7 +683,7 @@ printf 'patched spawnEnvironment runtime\\n' > "$target/dist/runtime.js"
|
||||
assert.equal(lstatSync(stagedAcpxDir).isSymbolicLink(), false);
|
||||
assert.equal(existsSync(join(destinationDir, "node_modules/.pnpm")), false);
|
||||
const stagedManifest = JSON.parse(readFileSync(join(destinationDir, "package.json"), "utf8"));
|
||||
for (const [name, version] of Object.entries(codexOptional)) {
|
||||
for (const [name, version] of Object.entries({ ...codexOptional, ...claudeOptional })) {
|
||||
assert.equal(stagedManifest.optionalDependencies[name], version);
|
||||
assert.equal(existsSync(join(destinationDir, "node_modules", name)), false);
|
||||
assert.equal(stagedManifest.bundleDependencies.includes(name), false);
|
||||
|
||||
@@ -51,13 +51,14 @@ export function createBundledInstallManifest(publishManifest, bundledDependencie
|
||||
}
|
||||
|
||||
// npm consumers cannot inherit the workspace's pnpm overrides or patches.
|
||||
// Materialize the already-qualified Codex bridge closure in the tarball,
|
||||
// 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];
|
||||
@@ -75,7 +76,9 @@ export function configureBundledProviderOverrides(installManifest, bundledDepend
|
||||
if (result.overrides?.[npmSelector] !== undefined) {
|
||||
throw new Error(`Bundled ${agent} runtime has a conflicting producer override`);
|
||||
}
|
||||
const overrides = { [runtimePackage]: profile.agentRuntimeVersion };
|
||||
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 });
|
||||
}
|
||||
@@ -87,88 +90,105 @@ const inside = (root, candidate) => {
|
||||
return value !== "" && value !== ".." && !value.startsWith(`..${sep}`) && !isAbsolute(value);
|
||||
};
|
||||
|
||||
// Bundle the pinned JavaScript closure, never the producer's Codex executable.
|
||||
// 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();
|
||||
const profile = profiles.find(value => value.agent === "codex");
|
||||
if (profiles.length !== 1 || !profile) throw new Error("Bundled provider graph must contain its qualified Codex profile");
|
||||
const targets = ["linux-x64", "linux-arm64", "darwin-x64", "darwin-arm64", "win32-x64", "win32-arm64"];
|
||||
const declarations = Object.fromEntries(targets.map(target => [`${profile.agentRuntimePackage}-${target}`,
|
||||
`npm:${profile.agentRuntimePackage}@${profile.agentRuntimeVersion}-${target}`]));
|
||||
const ownedDirectory = directory => {
|
||||
const stat = lstatSync(directory);
|
||||
if (!stat.isDirectory() || stat.isSymbolicLink() || !inside(graphRoot, realpathSync(directory))) {
|
||||
throw new Error("Bundled Codex 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 Codex 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 Codex bridge version mismatch");
|
||||
const issuer = createRequire(resolve(bridgeDirectory, "package.json"));
|
||||
const runtimeManifest = realpathSync(issuer.resolve(`${profile.agentRuntimePackage}/package.json`));
|
||||
if (!inside(graphRoot, runtimeManifest)) throw new Error("Bundled Codex 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 Codex 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 Codex graph exceeds its package limit");
|
||||
const metadata = manifestAt(packageDirectory);
|
||||
const binding = basename(dirname(packageDirectory)) === "@openai" ? `@openai/${basename(packageDirectory)}` : null;
|
||||
if (binding?.startsWith("@openai/codex-")) {
|
||||
const target = binding.slice("@openai/codex-".length), [os, cpu] = target.split("-");
|
||||
if (!Object.hasOwn(declarations, binding) || ![binding, profile.agentRuntimePackage].includes(metadata.name)
|
||||
|| metadata.version !== `${profile.agentRuntimeVersion}-${target}` || !metadata.os?.includes(os) || !metadata.cpu?.includes(cpu)) {
|
||||
throw new Error("Bundled Codex 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 Codex 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 Codex 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 (lstatExists(vendor)) { ownedDirectory(vendor); remove.add(vendor); }
|
||||
}
|
||||
if (!profiles.length || new Set(profiles.map(profile => profile.agent)).size !== profiles.length) {
|
||||
throw new Error("Bundled provider graph must contain distinct qualified profiles");
|
||||
}
|
||||
if (!runtimeCount) throw new Error("Bundled Codex 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 Codex platform conflicts with published dependency: ${name}`);
|
||||
optional[name] = specifier;
|
||||
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
|
||||
@@ -178,7 +198,7 @@ export function stageBundledProviderOptionalDependencies(destinationDir, publish
|
||||
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(declarations, name));
|
||||
if (Array.isArray(result[field])) result[field] = result[field].filter(name => !Object.hasOwn(optional, name));
|
||||
}
|
||||
delete result.paperclipProviderArtifacts;
|
||||
return result;
|
||||
|
||||
Reference in new issue
Block a user