fix: resolve installed Codex and preserve npm host dependencies (#15555)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Installed agents need their own runtime dependencies.
> - Native Codex startup and browser login could depend on a global CLI.
> - npm bundles do not inherit workspace dependency overrides or
patches.
> - Codex native packages must come from npm for the consumer host.
> - This PR fixes executable resolution and the required npm dependency
layout.
> - Usable installed CLI versions can run without a numeric version
gate.

## Linked Issues or Issue Description

Refs: #15422. This is a prerequisite for the later Codex-default change.

**What happened?**

Packaged native Codex startup and browser login could require a global
Codex CLI. The server's vendored runner lacked its own declared Codex
bridge. A bundled wrapper could retain producer-host binaries or select
the legacy adapter's separate platform version.

**Expected behavior**

Prefer the installed Codex executable. Accept usable older or newer
versions. Use the selected host's PATH when the dependency is absent.
Keep the patched JavaScript graph. Let npm install official native
packages for the consumer platform. Grant sandbox reads only to the
selected vendor resources.

**Steps to reproduce**

1. Prepare a clean npm installation without a global Codex command.
2. Start native Codex or its browser login.
3. Inspect the selected executable, installed host package, and sandbox
resource paths.

**Paperclip version or commit**

Frozen master base: `1881894973a2b25838d8abed9bd8aeebc3af4441`.

**Deployment mode**

Source and packaged self-hosted installation.

## What Changed

- Share installed Codex command resolution across native startup, direct
evals, and browser login. Accept usable version differences. Preserve
explicit commands, recorded sessions, remote host boundaries, and the
Linux ARM64 legacy login path. Return safe errors for missing
executables and failed login terminals.
- Declare the server's Codex bridge. Retain the patched JavaScript
dependency graph in npm packages. Strip Codex native payloads. Declare
official optional host packages on the published server manifest so
native and legacy versions remain separate. Preserve consumer esbuild
platform dependencies.
- Adjust resource lookup for npm's separate platform packages. Retain
package identity, path containment, resolver ownership, and narrow
sandbox reads. Keep exact version and digest checks for explicit ACPX
artifact qualification.
- Extend existing packaging, installed-consumer, login, selection,
recovery, and integrity tests. Document the retained behavior.

The diff is now 23 files, 1,709 additions, and 53 deletions. The prior
diff had 35 files and about 3,700 changed lines. Removed work is
preserved on `codex/runner-packaging-full-snapshot` at
`6f3060beaa842ffcee21af058370d3cab5f571e9`.

Removed from this PR: release workflows and assembly, provider-pack
changes, Docker materialization, Git installer changes, extra login
HOME/working-directory isolation, and unrelated CI fixture repairs. This
PR does not change agent defaults, stored runner choices, UI, schema, or
provider qualification.

## Verification

- Final candidate: `dde37d7ed0121c10b60b8801eda80f8dc17909ad`. [All 47
ordinary CI jobs
passed](https://github.com/paperclipai/paperclip/actions/runs/37842288835)
on attempt 1, including typecheck, tests, build, E2E, runner checks, and
the installed-consumer canary. [Fresh Greptile
review](https://github.com/paperclipai/paperclip/pull/15555#issuecomment-6059581546)
is 5/5 on this head; no unresolved threads remain. Human approval is
still outstanding.
- Reused focused controls passed with Node 24: 71 initial narrowed
checks, then 56 affected Codex/selection/eval checks after the relative
PATH correction. Runner TypeScript no-emit, syntax, and diff checks
passed. The existing fixture reproduces the original relative PATH
failure and verifies working-directory selection, empty entries,
ordering, and absolute launch. One CLI entrypoint test was initially
blocked by sandbox IPC and passed with its existing local socket
allowed. Login HOME, config-directory assignments, and working directory
match master.
- [The actual clean Linux npm
consumer](https://github.com/paperclipai/paperclip/actions/runs/37842288835/job/113535523044)
passed on the final candidate's CI integration. All 17 Paperclip
tarballs omit native Codex payloads. Official npm host packages retain
their own integrity and `inBundle=false`. Native Codex selects 0.160.0;
the legacy closure retains 0.156.1. Package admission, command leases,
narrow native sandbox resources, consumer hooks, preserved lock, and
offline lifecycle controls passed. Provider calls were zero. No new
workflow is added.
- Actual official Codex 0.156.1 passed on the final committed source on
macOS ARM64: installed dependency preference, absolute and relative PATH
fallback, narrow resource lookup, and app-server initialize/initialized.
Executed module hashes match the candidate. One scripts-disabled
install, three version probes, and one handshake completed in 26
seconds; owned files and process group were removed. No login,
account/model request, or provider task ran.
- CI checked out `dfda8e708e87306d22ed735d78bdfcbe770e99b7` on base
`65b558180533039a891ee0cd1ccab9988aa79adc`. Its 13 upstream paths do not
overlap this PR's 23 paths or alter packaging/Codex inputs. The consumer
report records producer `7b8e94c08657b5ddc265946459762340f125726c`,
after the existing canary staged a generated-lock-only commit (one file,
three insertions). These identities are kept separate; raw
generated-lock bytes were not retained.
- No local Docker or Rust build, paid provider turn, merge, or
deployment. Later PRs must prove live onboarding and production cloud
packaging before changing defaults.

## Risks

- npm must install optional host dependencies. Missing dependencies
still return errors. Paperclip tarballs do not pre-bundle Codex
executables.
- The repository requires CI-owned lockfile updates. PR CI resolves the
changed manifest and stages its own producer lockfile. A raw source
Docker build with `--frozen-lockfile` must wait for the existing master
lockfile bot to merge its refresh, or use a disposable resolved
checkout. No Docker build or deployment is qualified by this PR.
- Ordinary Codex startup accepts version differences. Actual protocol or
login failures remain errors. Explicit ACPX artifact checks retain their
release pins.
- The published server delegates platform installation outside its
bundled JavaScript graph. Focused negative controls reject unsafe
package metadata and paths. The hosted consumer test passed on this
candidate’s CI integration.
- Existing agents retain their stored runner choices. There is no data
migration or automatic upgrade. Release pipeline and platform
qualification work remain separate prerequisites for later defaults.

## Model Used

OpenAI Codex, GPT-6, with reasoning, tool use, code execution, and
parallel agents. The exact serving snapshot and context window are not
exposed in this session.

## 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:
DottaandPaperclip authored and GitHub committed 2026-10-09 08:19:51 -05:00
1 parent 2b688a8fe3
commit 6f9d0a56ba
23 files changed
+1709 -53

No files matched your search

@@ -1,7 +1,10 @@
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
import { spawnSync } from 'node:child_process';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import test from 'node:test';
import { GROK_PUBLIC_INSTALL_IMAGE, GROK_PUBLIC_INSTALL_LIFECYCLE, grokConsumerDockerArgs } from '../grok-public-install-sandbox.mjs';
import { GROK_PUBLIC_INSTALL_IMAGE, GROK_PUBLIC_INSTALL_LIFECYCLE, assertInstalledCodexPlatformProvenance, assertNoBundledCodexPayloads, grokConsumerDockerArgs, installedCodexProbeSource } from '../grok-public-install-sandbox.mjs';
const paths = { assets: '/private/staging/assets', consumer: '/private/staging/consumer', cache: '/private/staging/cache', uid: 1001, gid: 1001 };
const values = (args, flag) => args.flatMap((value, index) => value === flag ? [args[index + 1]] : []);
@@ -50,3 +53,152 @@ test('verification never elevates PR-controlled provisioning or cleanup on the h
assert.doesNotMatch(source, /\bsudo\b/);
assert.ok(source.includes("const prerequisite = join(root, 'native/grok')"));
});
test('the installed Codex probe exercises the public export and rejects incomplete or mismatched packages', () => {
const root = realpathSync(mkdtempSync(join(tmpdir(), 'installed-codex-probe-')));
try {
const consumer = join(root, 'consumer'); mkdirSync(consumer);
const target = `${process.platform}-${process.arch}`;
const platformPath = `node_modules/@openai/codex-${target}`;
const platform = join(consumer, platformPath); mkdirSync(platform, { recursive: true });
const nativeVendor = join(platform, 'vendor'); mkdirSync(nativeVendor);
const manifest = { name: '@openai/codex', version: `0.160.0-${target}`, os: [process.platform], cpu: [process.arch] };
writeFileSync(join(platform, 'package.json'), JSON.stringify(manifest));
const entry = { name: manifest.name, version: manifest.version,
resolved: `https://registry.npmjs.org/@openai/codex/-/codex-${manifest.version}.tgz`, integrity: `sha512-${Buffer.alloc(64, 1).toString('base64')}` };
const lock = { lockfileVersion: 3, packages: { [platformPath]: entry } };
writeFileSync(join(consumer, 'package-lock.json'), JSON.stringify(lock));
const server = join(consumer, 'node_modules/@paperclipai/server');
const vendor = join(server, 'dist/vendor/paperclip-runner'), drivers = join(vendor, 'drivers/acpx'); mkdirSync(drivers, { recursive: true });
writeFileSync(join(server, 'package.json'), JSON.stringify({ name: '@paperclipai/server', type: 'module' }));
const integrity = join(drivers, 'installation-integrity.js');
const security = join(vendor, 'drivers/codex/codex-security-config.js'); mkdirSync(join(vendor, 'drivers/codex'));
const securitySource = `export const codexExecutableReadOnlyRoots = () => [${JSON.stringify(nativeVendor)}];
export const createIsolatedCodexAppServerArgs = (source, roots) => roots.map(root => JSON.stringify(root) + '=\"read\"');`;
writeFileSync(security, securitySource);
const moduleSource = `import assert from 'node:assert/strict'; import { writeFileSync } from 'node:fs';
export function createAcpxPackageJsonResolver(root, manifest) { assert.equal(root, ${JSON.stringify(server)}); assert.equal(manifest, root + '/package.json'); return () => 'selected-authority'; }
export async function verifyQualifiedAcpxInstallation(profile, resolver) { assert.deepEqual(profile, { agent: 'codex', model: 'gpt-5.4' }); assert.equal(resolver(), 'selected-authority');
return { openCommand: async () => ({ close: async () => { writeFileSync(${JSON.stringify(join(server, 'lease-closed'))}, 'ok'); } }) }; }`;
writeFileSync(integrity, moduleSource);
writeFileSync(join(drivers, 'qualified-profiles.js'), "export const resolveQualifiedAcpxProfile = (agent, model) => ({ agent, model });");
const wrapper = join(consumer, 'node_modules/@openai/codex/bin'); mkdirSync(wrapper, { recursive: true });
writeFileSync(join(wrapper, '../package.json'), JSON.stringify({ name: '@openai/codex', version: '0.160.0' }));
const index = join(vendor, 'index.mjs'), command = join(wrapper, 'codex.js'), probe = join(root, 'probe.mjs');
const executable = version => writeFileSync(command, `#!/bin/sh\n[ "$1" = --version ] || exit 65\nprintf '%s\\n' 'codex-cli ${version}'\n`, { mode: 0o755 });
writeFileSync(probe, installedCodexProbeSource(index, consumer, '0.160.0'));
const run = () => spawnSync(process.execPath, [probe], { encoding: 'utf8', timeout: 10_000, env: { PATH: '/usr/bin:/bin', NODE_PATH: '' } });
writeFileSync(index, `export const resolvePinnedCodexCommand = () => ${JSON.stringify(command)};`);
executable('0.160.0');
let result = run(); assert.equal(result.status, 0, result.stderr);
assert.equal(JSON.parse(result.stdout).pinnedCodexCommandVerified, true);
assert.equal(JSON.parse(result.stdout).codexPlatformPackageSource, 'official npm');
assert.equal(JSON.parse(result.stdout).codexConsumerPlatform, target);
assert.equal(JSON.parse(result.stdout).codexQualifiedInstallationVerified, true);
assert.equal(JSON.parse(result.stdout).codexCommandLeaseVerified, true);
assert.equal(JSON.parse(result.stdout).codexNativeSandboxResourcesVerified, true);
assert.equal(readFileSync(join(server, 'lease-closed'), 'utf8'), 'ok');
assert.equal(JSON.parse(result.stdout).providerCalls, 0);
const legacyPath = 'node_modules/legacy-codex-adapter/node_modules/@openai/codex-' + target;
const legacy = join(consumer, legacyPath); mkdirSync(legacy, { recursive: true });
const legacyManifest = { ...manifest, version: '0.156.1-' + target };
writeFileSync(join(legacy, 'package.json'), JSON.stringify(legacyManifest));
lock.packages[legacyPath] = { ...entry, version: legacyManifest.version,
resolved: 'https://registry.npmjs.org/@openai/codex/-/codex-' + legacyManifest.version + '.tgz' };
writeFileSync(join(consumer, 'package-lock.json'), JSON.stringify(lock));
result = run(); assert.equal(result.status, 0, result.stderr);
assert.equal(JSON.parse(result.stdout).codexPlatformPackages.length, 2);
assert.equal(JSON.parse(result.stdout).codexSelectedPlatformPath, platformPath);
assert.equal(JSON.parse(result.stdout).codexSelectedPlatformVersion, '0.160.0-' + target);
const legacyCommand = join(legacy, 'codex');
writeFileSync(legacyCommand, '#!/bin/sh\nexit 0\n', { mode: 0o755 });
writeFileSync(index, `export const resolvePinnedCodexCommand = () => ${JSON.stringify(legacyCommand)};`);
result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /Selected Codex platform version must match the qualified pin/);
writeFileSync(index, `import { writeFileSync } from 'node:fs'; export const resolvePinnedCodexCommand = () => {
writeFileSync(${JSON.stringify(join(platform, 'package.json'))}, ${JSON.stringify(JSON.stringify({ ...manifest, altered: true }))});
return ${JSON.stringify(command)}; };`);
result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /metadata must match its scanned provenance/);
writeFileSync(join(platform, 'package.json'), JSON.stringify(manifest));
writeFileSync(index, "export const resolvePinnedCodexCommand = () => { throw new Error('Bundled Codex runtime version mismatch'); };");
result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /Bundled Codex runtime version mismatch/);
writeFileSync(index, `export const resolvePinnedCodexCommand = () => ${JSON.stringify(command)};`);
writeFileSync(security, securitySource.replace(JSON.stringify(nativeVendor), '"/missing-vendor-root"'));
result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /vendor directory must be readable/);
writeFileSync(security, securitySource.replace(JSON.stringify(nativeVendor), `${JSON.stringify(nativeVendor)}, ${JSON.stringify(consumer)}`));
result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /must not grant enclosing npm/);
writeFileSync(security, securitySource.replace("'=\"read\"'", "'=\"write\"'"));
result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /retain the selected native executable resources/);
writeFileSync(security, securitySource);
const emptySlot = join(server, 'node_modules/@openai/codex-' + target);
mkdirSync(emptySlot, { recursive: true });
result = run(); assert.equal(result.status, 0, result.stderr);
assert.equal(JSON.parse(result.stdout).codexPlatformPackages.length, 2,
'An empty nested npm optional slot must not obscure the qualified hoisted host package');
writeFileSync(join(emptySlot, 'undeclared-native-payload'), 'native fixture; never executed');
result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /empty regular directory; found.*undeclared-native-payload/);
rmSync(join(emptySlot, 'undeclared-native-payload'));
writeFileSync(join(emptySlot, 'package.json'), '{ malformed');
result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /SyntaxError/);
rmSync(join(emptySlot, 'package.json'));
writeFileSync(integrity, moduleSource.replace('assert.deepEqual(profile,', "throw new Error('qualified executable digest mismatch'); assert.deepEqual(profile,"));
result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /qualified executable digest mismatch/);
writeFileSync(integrity, moduleSource.replace("writeFileSync(", "throw new Error('command lease close failed'); writeFileSync("));
result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /command lease close failed/);
writeFileSync(integrity, moduleSource);
lock.packages[platformPath].inBundle = true;
writeFileSync(join(consumer, 'package-lock.json'), JSON.stringify(lock));
result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /downloaded, not bundled/);
delete lock.packages[platformPath].inBundle;
writeFileSync(join(consumer, 'package-lock.json'), JSON.stringify(lock));
const foreign = join(consumer, 'node_modules/@openai/codex-win32-arm64'); mkdirSync(foreign);
writeFileSync(join(foreign, 'package.json'), JSON.stringify({ name: '@openai/codex', version: '0.160.0-win32-arm64' }));
result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /only the host/);
rmSync(foreign, { recursive: true });
executable('9.9.9'); result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /qualified pin/);
rmSync(command); result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /ENOENT/);
const outside = join(root, 'outside'); writeFileSync(outside, '#!/bin/sh\nexit 0\n', { mode: 0o755 });
writeFileSync(index, `export const resolvePinnedCodexCommand = () => ${JSON.stringify(outside)};`);
result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /inside the installed consumer/);
writeFileSync(index, 'export const unrelated = true;'); result = run(); assert.notEqual(result.status, 0); assert.match(result.stderr, /must export the pinned Codex resolver/);
} finally { rmSync(root, { recursive: true, force: true }); }
});
test('actual tar member checks allow Codex JavaScript but reject nested platform packages and native vendor payloads', () => {
const javascript = ['package/package.json', 'package/node_modules/@openai/codex/package.json',
'package/node_modules/@openai/codex/bin/codex.js', 'package/dist/vendor/paperclip-runner/index.js'];
assert.doesNotThrow(() => assertNoBundledCodexPayloads(javascript));
for (const payload of [
'package/node_modules/@openai/codex-linux-x64/package.json',
'package/node_modules/bridge/node_modules/@openai/codex-darwin-arm64/package.json',
'package/node_modules/@openai/codex-win32-x64/package.json',
'package/node_modules/@openai/codex/vendor/x86_64-unknown-linux-musl/codex/codex',
'package/dist/vendor/aarch64-apple-darwin/bin/codex',
'package/dist/vendor/x86_64-pc-windows-msvc/bin/codex.exe',
]) assert.throws(() => assertNoBundledCodexPayloads([...javascript, payload]), /must not bundle/);
assert.throws(() => assertNoBundledCodexPayloads(['package/../outside']), /inside the package/);
const source = readFileSync(new URL('../verify-grok-npm-install.mjs', import.meta.url), 'utf8');
assert.match(source, /assertNoBundledCodexPayloads\(run\('tar', \['-tzf', tarball\]\)/);
});
test('consumer provenance rejects bundled, foreign, inconsistent and non-official Codex payloads', () => {
const path = 'node_modules/@openai/codex-linux-x64';
const manifest = { name: '@openai/codex', version: '0.160.0-linux-x64', os: ['linux'], cpu: ['x64'] };
const entry = { version: manifest.version, resolved: `https://registry.npmjs.org/@openai/codex/-/codex-${manifest.version}.tgz`,
integrity: `sha512-${Buffer.alloc(64, 1).toString('base64')}` };
const check = (value = entry, installed = [{ path, manifest }]) => assertInstalledCodexPlatformProvenance({ packages: { [path]: value } }, installed, 'linux-x64');
assert.equal(check().codexConsumerHostOnly, true);
const legacyManifest = { ...manifest, version: '0.156.1-linux-x64' };
assert.equal(check({ ...entry, version: legacyManifest.version,
resolved: 'https://registry.npmjs.org/@openai/codex/-/codex-0.156.1-linux-x64.tgz' }, [{ path, manifest: legacyManifest }]).codexConsumerHostOnly, true);
assert.throws(() => check(entry, [{ path, manifest: { ...manifest, version: '^0.160.0-linux-x64' } }]), /exact host version/);
for (const change of [
{ inBundle: true }, { link: true }, { version: '0.156.1-linux-x64' },
{ resolved: 'https://example.com/@openai/codex/-/codex-0.160.0-linux-x64.tgz' },
{ resolved: 'https://registry.npmjs.org/@openai/codex/-/codex-0.156.1-linux-x64.tgz' },
{ resolved: 'https://user@registry.npmjs.org/@openai/codex/-/codex-0.160.0-linux-x64.tgz' },
{ integrity: undefined }, { integrity: 'sha512-AA==' },
]) assert.throws(() => check({ ...entry, ...change }));
assert.throws(() => check(entry, []), /must install its host/);
assert.throws(() => check(entry, [{ path: 'node_modules/@openai/codex-darwin-arm64', manifest }]), /only the host/);
assert.throws(() => check(entry, [{ path, manifest: { ...manifest, name: 'untrusted' } }]), /identity/);
});
+233 -5
View File
@@ -6,7 +6,9 @@ import {
mkdirSync,
mkdtempSync,
readFileSync,
realpathSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { readFile } from "node:fs/promises";
@@ -20,11 +22,60 @@ import cliEsbuildConfig from "../cli/esbuild.config.mjs";
import { bundledCliNpmDependencies } from "./cli-bundled-npm-dependencies.mjs";
import {
createBundledInstallManifest,
configureBundledProviderOverrides,
materializePublishManifest,
selectBundledDependencyPatches,
stageBundledEsbuildOptionalDependencies,
stageBundledProviderOptionalDependencies,
} from "./prepare-bundled-package.mjs";
const rootPackage = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
const profileData = JSON.parse(await readFile(new URL("../packages/paperclip-runner/acpx-profiles.json", import.meta.url), "utf8"));
const nativeTargets = ["linux-x64", "darwin-arm64", "darwin-x64"];
function esbuildFixture(t) {
const directory = realpathSync(mkdtempSync(join(tmpdir(), "paperclip-bundled-esbuild-")));
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 acpx = writePackage(join(graph, "acpx"), { name: "acpx", version: "0.13.1" });
const esbuild = writePackage(join(acpx, "node_modules/esbuild"), {
name: "esbuild", version: "0.28.2", scripts: { postinstall: "node install.js" },
optionalDependencies: Object.fromEntries([...nativeTargets, "win32-x64"].map(target => [`@esbuild/${target}`, "0.28.2"])),
});
const producerBinary = writePackage(join(graph, "@esbuild/linux-x64"), {
name: "@esbuild/linux-x64", version: "0.28.2", os: ["linux"], cpu: ["x64"],
});
writePackage(join(graph, "unrelated-linux-x64"), { name: "unrelated-linux-x64", version: "1.0.0" });
const publish = { name: "@paperclipai/adapter-utils", version: "0.3.1", bundleDependencies: ["acpx"],
dependencies: { acpx: "0.13.1" }, optionalDependencies: { unrelated: "1.0.0" } };
return { directory, graph, esbuild, producerBinary, publish, writePackage };
}
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}`]));
function codexFixture(t) {
const directory = realpathSync(mkdtempSync(join(tmpdir(), "paperclip-bundled-codex-")));
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/codex-acp"), { name: "@agentclientprotocol/codex-acp", version: "1.6.2", dependencies: { "@openai/codex": "0.160.0" } });
writeFileSync(join(bridge, "index.js"), "export {};\n");
const runtime = writePackage(join(graph, "@openai/codex"), { name: "@openai/codex", version: "0.160.0", bin: { codex: "bin/codex.js" }, optionalDependencies: codexOptional });
mkdirSync(join(runtime, "bin")); writeFileSync(join(runtime, "bin/codex.js"), "// official JavaScript fixture, never executed\n");
mkdirSync(join(runtime, "vendor")); writeFileSync(join(runtime, "vendor/codex"), "producer fallback binary fixture, never executed");
const producer = writePackage(join(graph, "@openai/codex-linux-x64"), { name: "@openai/codex", version: "0.160.0-linux-x64", os: ["linux"], cpu: ["x64"] });
mkdirSync(join(producer, "vendor")); writeFileSync(join(producer, "vendor/codex"), "producer optional binary fixture, never executed");
const nested = writePackage(join(bridge, "node_modules/@openai/codex-darwin-arm64"), { name: "@openai/codex", version: "0.160.0-darwin-arm64", os: ["darwin"], cpu: ["arm64"] });
writePackage(join(graph, "unrelated-linux-x64"), { name: "unrelated-linux-x64", version: "1.0.0" });
const profiles = [{ agent: "codex", ...profileData.profiles.codex }];
const publish = { name: "paperclip-codex-pack-fixture", version: "1.0.0", dependencies: { "@agentclientprotocol/codex-acp": "1.6.2" }, bundleDependencies: ["@agentclientprotocol/codex-acp"] };
return { directory, graph, bridge, runtime, producer, nested, profiles, publish, writePackage };
}
const adapterUtilsPackage = JSON.parse(
await readFile(new URL("../packages/adapter-utils/package.json", import.meta.url), "utf8"),
);
@@ -40,6 +91,7 @@ const dbPackage = JSON.parse(
const releaseScript = await readFile(new URL("./release.sh", import.meta.url), "utf8");
const releaseLib = await readFile(new URL("./release-lib.sh", import.meta.url), "utf8");
const buildNpmScript = await readFile(new URL("./build-npm.sh", import.meta.url), "utf8");
const acpxRuntimePatch = await readFile(
new URL("../patches/acpx@0.13.1.patch", import.meta.url),
"utf8",
@@ -124,6 +176,149 @@ test("published packages preserve the patched ACPX runtime", () => {
assert.equal(cliEsbuildConfig.external.includes("acpx"), false);
});
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);
for (const profile of profiles) {
assert.equal(published.dependencies[profile.agentServerPackage], profile.agentServerVersion);
assert.ok(published.bundleDependencies.includes(profile.agentServerPackage));
assert.equal(installManifest.overrides[`${profile.agentServerPackage}@${profile.agentServerVersion}`][profile.agentRuntimePackage], profile.agentRuntimeVersion);
}
assert.equal(published.overrides, undefined);
assert.equal(installManifest.overrides.rollup, undefined);
const bad = structuredClone(rootPackage);
bad.pnpm.overrides["@agentclientprotocol/codex-acp@1.6.2>@openai/codex"] = "0.156.1";
assert.throws(() => configureBundledProviderOverrides(installManifest, serverPackage.bundleDependencies, bad, profileData), /runtime override must match/);
const unpinned = createBundledInstallManifest(published, serverPackage.bundleDependencies);
unpinned.dependencies["@agentclientprotocol/codex-acp"] = "^1.6.2";
assert.throws(() => configureBundledProviderOverrides(unpinned, serverPackage.bundleDependencies, rootPackage, profileData), /exact qualified profile/);
const conflict = createBundledInstallManifest(published, serverPackage.bundleDependencies);
conflict.overrides = { "@agentclientprotocol/codex-acp@1.6.2": { "@openai/codex": "0.156.1" } };
assert.throws(() => configureBundledProviderOverrides(conflict, serverPackage.bundleDependencies, rootPackage, profileData), /conflicting producer override/);
});
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"));
const staged = stageBundledProviderOptionalDependencies(directory, publish, profiles);
assert.deepEqual(staged.optionalDependencies, codexOptional);
assert.deepEqual(staged.bundleDependencies, publish.bundleDependencies);
assert.equal(staged.paperclipProviderArtifacts, undefined);
assert.equal(existsSync(producer), false);
assert.equal(existsSync(nested), false, "Transitive producer platform packages must also be removed");
assert.equal(existsSync(join(runtime, "vendor")), false, "Wrapper fallback native payload must be removed");
assert.equal(existsSync(join(graph, "unrelated-linux-x64")), true);
assert.equal(readFileSync(join(bridge, "package.json"), "utf8"), before[0], "The patched bridge metadata is unchanged");
const originalRuntime = JSON.parse(before[1]); delete originalRuntime.optionalDependencies;
assert.deepEqual(JSON.parse(readFileSync(join(runtime, "package.json"), "utf8")), originalRuntime,
"Only the wrapper platform declarations move to the published authority root");
assert.equal(readFileSync(join(runtime, "bin/codex.js"), "utf8"), "// official JavaScript fixture, never executed\n");
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("@openai/codex/bin/codex.js")), "The actual npm tarball retains its pinned JS runtime");
assert.equal(paths.some(path => /@openai\/codex-(?:linux|darwin|win32)-|@openai\/codex\/vendor\//.test(path)), false,
"Actual npm pack must contain no native Codex payload on any platform");
});
test("Codex bundle validation fails before deleting producer binaries for altered pins or optional declarations", (t) => {
const { directory, runtime, producer, profiles, publish } = codexFixture(t);
const file = join(runtime, "package.json"), original = JSON.parse(readFileSync(file, "utf8"));
writeFileSync(file, JSON.stringify({ ...original, version: "0.156.1" }));
assert.throws(() => stageBundledProviderOptionalDependencies(directory, publish, profiles), /runtime version mismatch/);
writeFileSync(file, JSON.stringify({ ...original, optionalDependencies: { ...codexOptional, "@openai/codex-untrusted": "0.160.0" } }));
assert.throws(() => stageBundledProviderOptionalDependencies(directory, publish, profiles), /not qualified/);
writeFileSync(file, JSON.stringify(original));
const missing = { ...original }; delete missing.optionalDependencies;
writeFileSync(file, JSON.stringify(missing));
assert.throws(() => stageBundledProviderOptionalDependencies(directory, publish, profiles), /not qualified/,
"Missing wrapper declarations require the exact published-root delegation mapping");
writeFileSync(file, JSON.stringify(original));
assert.throws(() => stageBundledProviderOptionalDependencies(directory, { ...publish,
optionalDependencies: { "@openai/codex-darwin-arm64": "npm:@openai/codex@0.156.1-darwin-arm64" } }, profiles), /conflicts with published/);
assert.equal(existsSync(producer), true);
assert.equal(readFileSync(file, "utf8"), JSON.stringify(original), "Conflicting root declarations must not normalize metadata");
});
test("Codex stripping rejects linked native payloads and wrapper fallback directories without touching external files", (t) => {
const { directory, runtime, producer, profiles, publish, writePackage } = codexFixture(t);
const outside = writePackage(join(directory, "outside"), { name: "@openai/codex", version: "0.160.0-linux-x64", os: ["linux"], cpu: ["x64"] });
rmSync(producer, { recursive: true }); symlinkSync(outside, producer, "dir");
assert.throws(() => stageBundledProviderOptionalDependencies(directory, publish, profiles), /escapes its producer graph/);
rmSync(producer); rmSync(join(runtime, "vendor"), { recursive: true }); symlinkSync(outside, join(runtime, "vendor"), "dir");
assert.throws(() => stageBundledProviderOptionalDependencies(directory, publish, profiles), /escapes its producer graph/);
assert.equal(existsSync(join(outside, "package.json")), true);
});
test("Linux-produced esbuild bundles publish exact consumer platform dependencies and retain their hooks", (t) => {
const { directory, graph, esbuild, producerBinary, publish, writePackage } = esbuildFixture(t);
const original = readFileSync(join(esbuild, "package.json"), "utf8");
const issuer = createRequire(join(esbuild, "package.json"));
// The original producer-only topology cannot resolve a Mac binary. The
// public optional declaration lets npm obtain it before offline hooks run.
assert.throws(() => issuer.resolve("@esbuild/darwin-arm64/bin/esbuild"), /Cannot find module/);
const staged = stageBundledEsbuildOptionalDependencies(directory, publish);
for (const target of [...nativeTargets, "win32-x64"]) assert.equal(staged.optionalDependencies[`@esbuild/${target}`], "0.28.2");
assert.equal(staged.optionalDependencies.unrelated, "1.0.0");
assert.deepEqual(staged.bundleDependencies, ["acpx"]);
assert.deepEqual(staged.dependencies, publish.dependencies);
assert.equal(publish.optionalDependencies["@esbuild/darwin-arm64"], undefined);
assert.equal(existsSync(producerBinary), false);
assert.equal(existsSync(join(graph, "unrelated-linux-x64")), true);
assert.equal(readFileSync(join(esbuild, "package.json"), "utf8"), original);
assert.deepEqual(stageBundledEsbuildOptionalDependencies(directory, staged), staged);
for (const target of ["darwin-arm64", "darwin-x64"]) {
const artifact = writePackage(join(graph, `@esbuild/${target}`), {
name: `@esbuild/${target}`, version: staged.optionalDependencies[`@esbuild/${target}`], os: ["darwin"], cpu: [target.slice(7)],
});
mkdirSync(join(artifact, "bin")); writeFileSync(join(artifact, "bin/esbuild"), "consumer-selected fixture; never executed");
assert.equal(issuer.resolve(`@esbuild/${target}/bin/esbuild`), join(artifact, "bin/esbuild"));
}
});
test("bundled esbuild rejects conflicting published or nested platform versions without removing the producer", (t) => {
const { directory, graph, producerBinary, publish, writePackage } = esbuildFixture(t);
assert.throws(() => stageBundledEsbuildOptionalDependencies(directory, {
...publish, optionalDependencies: { "@esbuild/darwin-arm64": "0.27.0" },
}), /platform version conflicts/);
assert.equal(existsSync(producerBinary), true);
writePackage(join(graph, "esbuild"), { name: "esbuild", version: "0.27.0",
optionalDependencies: Object.fromEntries(nativeTargets.map(target => [`@esbuild/${target}`, "0.27.0"])) });
assert.throws(() => stageBundledEsbuildOptionalDependencies(directory, publish), /platform version conflicts|installed platform identity mismatch/);
assert.equal(existsSync(producerBinary), true);
});
test("bundled esbuild rejects missing targets, altered declarations and incorrect platform identity", (t) => {
const { directory, esbuild, producerBinary, publish } = esbuildFixture(t);
const path = join(esbuild, "package.json"), metadata = JSON.parse(readFileSync(path, "utf8"));
writeFileSync(path, JSON.stringify({ ...metadata, optionalDependencies: { "@esbuild/linux-x64": "0.28.2" } }));
assert.throws(() => stageBundledEsbuildOptionalDependencies(directory, publish), /omitted a supported platform/);
writeFileSync(path, JSON.stringify({ ...metadata, optionalDependencies: { ...metadata.optionalDependencies, "@esbuild/win32-x64": "^0.28.2" } }));
assert.throws(() => stageBundledEsbuildOptionalDependencies(directory, publish), /exact package version/);
writeFileSync(path, JSON.stringify(metadata));
writeFileSync(join(producerBinary, "package.json"), JSON.stringify({ name: "@esbuild/linux-x64", version: "0.27.0" }));
assert.throws(() => stageBundledEsbuildOptionalDependencies(directory, publish), /installed platform identity mismatch/);
assert.equal(existsSync(producerBinary), true);
});
test("bundled esbuild cannot follow a platform payload or package namespace outside its producer graph", (t) => {
const { directory, graph, producerBinary, publish, writePackage } = esbuildFixture(t);
const external = writePackage(join(directory, "outside"), { name: "@esbuild/linux-x64", version: "0.28.2" });
rmSync(producerBinary, { recursive: true }); symlinkSync(external, producerBinary, "dir");
assert.throws(() => stageBundledEsbuildOptionalDependencies(directory, publish), /escapes its producer graph/);
assert.equal(readFileSync(join(external, "package.json"), "utf8").includes("0.28.2"), true);
rmSync(join(graph, "@esbuild"), { recursive: true }); symlinkSync(external, join(graph, "@esbuild"), "dir");
assert.throws(() => stageBundledEsbuildOptionalDependencies(directory, publish), /escapes its producer graph/);
});
test("Paperclip Runner pins the qualified ACPX host callbacks", () => {
assert.equal(rootPackage.pnpm.patchedDependencies["acpx@0.13.1"], "patches/acpx@0.13.1.patch");
assert.equal(
@@ -285,11 +480,13 @@ test("bundled package patch selection rejects an unpatched installed version", (
});
test("server package staging applies every bundled runtime patch and preserves the vendored runner", (t) => {
const fixtureDir = mkdtempSync(join(tmpdir(), "paperclip-bundled-stage-"));
const fixtureDir = realpathSync(mkdtempSync(join(tmpdir(), "paperclip-bundled-stage-")));
const sourceDir = join(fixtureDir, "source");
const destinationDir = join(fixtureDir, "destination");
const binDir = join(fixtureDir, "bin");
const callLog = join(fixtureDir, "calls.log");
const fixtureSourceRoot = join(fixtureDir, "repo");
const fixtureArtifacts = join(fixtureDir, "native-artifacts");
mkdirSync(sourceDir);
mkdirSync(join(sourceDir, "dist"));
writeFileSync(join(sourceDir, "dist", "index.js"), "export {};\n");
@@ -300,6 +497,18 @@ test("server package staging applies every bundled runtime patch and preserves t
JSON.stringify({ ...serverPackage, files: ["dist"] }),
);
writeFileSync(callLog, "");
mkdirSync(fixtureArtifacts);
const nativePackage = join(fixtureArtifacts, "@openai/codex-linux-x64");
mkdirSync(join(nativePackage, "vendor"), { recursive: true });
writeFileSync(join(nativePackage, "package.json"), JSON.stringify({ name: "@openai/codex", version: "0.160.0-linux-x64", os: ["linux"], cpu: ["x64"] }));
writeFileSync(join(nativePackage, "vendor/codex"), "producer host fixture; never executed");
mkdirSync(join(fixtureSourceRoot, "packages/paperclip-runner/src/drivers/acpx"), { recursive: true });
writeFileSync(join(fixtureSourceRoot, "package.json"), JSON.stringify(rootPackage));
writeFileSync(join(fixtureSourceRoot, "packages/paperclip-runner/acpx-profiles.json"), JSON.stringify(profileData));
mkdirSync(join(fixtureSourceRoot, "patches"));
for (const patchPath of Object.values(rootPackage.pnpm.patchedDependencies)) {
writeFileSync(join(fixtureSourceRoot, patchPath), readFileSync(new URL(`../${patchPath}`, import.meta.url)));
}
t.after(() => rmSync(fixtureDir, { recursive: true, force: true }));
const writeExecutable = (name, body) => {
@@ -321,8 +530,10 @@ 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 })); }'
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");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"]}));'
printf 'unpatched runtime\\n' > node_modules/acpx/dist/runtime.js
printf '{"name":"acpx","version":"0.13.1"}\\n' > node_modules/acpx/package.json
`,
@@ -356,9 +567,11 @@ printf 'patched spawnEnvironment runtime\\n' > "$target/dist/runtime.js"
execFileSync(
process.execPath,
[
new URL("./prepare-bundled-package.mjs", import.meta.url).pathname,
"--input-type=module", "-e",
`import { prepareBundledPackage } from ${JSON.stringify(new URL("./prepare-bundled-package.mjs", import.meta.url).href)}; prepareBundledPackage(process.argv[1], process.argv[2], { sourceRoot: process.argv[3] });`,
sourceDir,
destinationDir,
fixtureSourceRoot,
],
{
env: {
@@ -366,6 +579,7 @@ printf 'patched spawnEnvironment runtime\\n' > "$target/dist/runtime.js"
PATH: `${binDir}:${process.env.PATH}`,
FAKE_CALL_LOG: callLog,
FAKE_SOURCE_PACKAGE: join(sourceDir, "package.json"),
FAKE_NATIVE_ARTIFACTS: fixtureArtifacts,
},
stdio: "pipe",
},
@@ -375,6 +589,19 @@ printf 'patched spawnEnvironment runtime\\n' > "$target/dist/runtime.js"
assert.equal(lstatSync(stagedAcpxDir).isDirectory(), true);
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)) {
assert.equal(stagedManifest.optionalDependencies[name], version);
assert.equal(existsSync(join(destinationDir, "node_modules", name)), false);
assert.equal(stagedManifest.bundleDependencies.includes(name), false);
}
assert.equal(existsSync(join(destinationDir, "node_modules/@openai/codex/vendor")), false);
assert.equal(stagedManifest.paperclipProviderArtifacts, undefined);
assert.equal(JSON.parse(readFileSync(join(destinationDir, "node_modules/@openai/codex/package.json"), "utf8")).optionalDependencies, undefined);
assert.equal(stagedManifest.optionalDependencies["@esbuild/darwin-arm64"], "0.28.2");
assert.equal(stagedManifest.optionalDependencies["@esbuild/darwin-x64"], "0.28.2");
assert.equal(existsSync(join(destinationDir, "node_modules/@esbuild/linux-x64")), false);
assert.equal(JSON.parse(readFileSync(join(destinationDir, "node_modules/esbuild/package.json"))).scripts.postinstall, "node install.js");
assert.match(
readFileSync(join(stagedAcpxDir, "dist/runtime.js"), "utf8"),
/spawnEnvironment/,
@@ -383,13 +610,14 @@ printf 'patched spawnEnvironment runtime\\n' > "$target/dist/runtime.js"
readFileSync(callLog, "utf8"),
/patch -p1 --forward -d .*node_modules\/acpx/,
);
const patchedBundledDependencies = serverPackage.bundleDependencies.filter(name => rootPackage.pnpm.patchedDependencies[`${name}@${serverPackage.dependencies[name]}`]);
assert.equal(
readFileSync(callLog, "utf8")
.split("\n")
.filter((line) => line.startsWith("patch ")).length,
serverPackage.bundleDependencies.length,
patchedBundledDependencies.length,
);
for (const name of serverPackage.bundleDependencies) {
for (const name of patchedBundledDependencies) {
const specifier = `${name}@${serverPackage.dependencies[name]}`;
const patchPath = rootPackage.pnpm.patchedDependencies[specifier];
assert.equal(
+144
View File
@@ -1,3 +1,5 @@
import assert from 'node:assert/strict';
// Keep public-package lifecycle code off the verification host. Resolve and
// cache the public npm graph without scripts, then execute it offline.
export const GROK_PUBLIC_INSTALL_IMAGE =
@@ -7,6 +9,148 @@ export const GROK_PUBLIC_INSTALL_LIFECYCLE = [
'npm', 'rebuild', '--offline', '--ignore-scripts=false', '--dangerously-allow-all-scripts',
];
// Inspect the actual npm archive, independently of the staging helper.
export function assertNoBundledCodexPayloads(entries) {
assert.ok(Array.isArray(entries) && entries.length > 0, 'Packed package must have tar members');
for (const entry of entries) {
assert.equal(typeof entry, 'string');
assert.ok(!entry.startsWith('/') && !entry.split('/').includes('..'), 'Tar member must remain inside the package');
assert.doesNotMatch(entry, /(?:^|\/)node_modules\/@openai\/codex-(?:linux|darwin|win32)-(?:x64|arm64)(?:\/|$)/,
'Paperclip tarballs must not bundle Codex platform packages');
assert.doesNotMatch(entry, /(?:^|\/)node_modules\/@openai\/codex\/vendor(?:\/|$)/,
'Paperclip tarballs must not bundle the Codex wrapper vendor payload');
if (!entry.endsWith('/')) assert.doesNotMatch(entry, /(?:^|\/)codex(?:\.exe)?$/,
'Paperclip tarballs must not bundle native Codex executables');
}
}
// Verify every host payload against its own official npm provenance, including
// independent legacy closures. The selected native runtime is pinned below.
export function assertInstalledCodexPlatformProvenance(lock, installed, target) {
assert.match(target, /^(linux|darwin|win32)-(x64|arm64)$/);
assert.ok(Array.isArray(installed) && installed.length > 0, 'Consumer must install its host Codex platform package');
const alias = `@openai/codex-${target}`;
for (const { path, manifest } of installed) {
assert.ok(path.endsWith(`/node_modules/${alias}`) || path === `node_modules/${alias}`,
'Consumer must contain only the host Codex platform payload');
const version = manifest.version;
assert.ok(typeof version === 'string' && version.endsWith('-' + target)
&& /^\d+\.\d+\.\d+$/.test(version.slice(0, -target.length - 1)), 'Installed Codex platform must declare an exact host version');
assert.ok([alias, '@openai/codex'].includes(manifest.name), 'Installed Codex platform package identity must match its alias');
const [os, cpu] = target.split('-');
assert.deepEqual(manifest.os, [os]);
assert.deepEqual(manifest.cpu, [cpu]);
const entry = lock.packages?.[path];
assert.ok(entry, 'Installed Codex platform must have a consumer lock entry');
assert.notEqual(entry.inBundle, true, 'Codex platform package must be downloaded, not bundled');
assert.notEqual(entry.link, true, 'Codex platform package must not be a local link');
assert.equal(entry.version, version, 'Consumer lock must pin the host Codex platform version');
const url = new URL(entry.resolved);
assert.equal(url.protocol, 'https:');
assert.equal(url.host, 'registry.npmjs.org', 'Codex platform must resolve from official npm');
assert.equal(url.username + url.password + url.search + url.hash, '', 'Codex npm URL must not have credentials or modifiers');
assert.equal(decodeURIComponent(url.pathname), `/@openai/codex/-/codex-${version}.tgz`, 'Codex platform must use its exact official npm tarball');
assert.match(entry.integrity ?? '', /^sha512-[A-Za-z0-9+/]+={0,2}$/, 'Codex platform must have npm integrity');
assert.equal(Buffer.from(entry.integrity.slice(7), 'base64').length, 64, 'Codex npm integrity must be a SHA-512 digest');
}
return { codexConsumerHostOnly: true, codexConsumerPlatform: target, codexPlatformPackageSource: 'official npm',
codexPlatformPackages: installed.map(({ path, manifest }) => ({ path, name: manifest.name, version: manifest.version,
resolved: lock.packages[path].resolved, integrity: lock.packages[path].integrity, inBundle: false })) };
}
// Execute this in the existing offline public consumer, never in the checkout.
// The public index and returned command must both come from the installed graph.
export function installedCodexProbeSource(indexPath, consumerRoot, expectedVersion) {
return `
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { createRequire } from 'node:module';
import { accessSync, constants, existsSync, lstatSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
import { pathToFileURL } from 'node:url';
const root = realpathSync(${JSON.stringify(consumerRoot)});
const contained = path => { const value = relative(root, realpathSync(path)); return value !== '' && value !== '..' && !value.startsWith('..' + sep) && !isAbsolute(value); };
const lock = JSON.parse(readFileSync(join(root, 'package-lock.json'), 'utf8'));
const installed = [], pending = [join(root, 'node_modules')];
let visited = 0;
while (pending.length) {
const directory = pending.pop();
assert.ok(contained(directory), 'Installed dependency directory must remain in the consumer');
for (const entry of readdirSync(directory, { withFileTypes: true })) {
if (entry.name.startsWith('.') || !(entry.isDirectory() || entry.isSymbolicLink())) continue;
const namespace = join(directory, entry.name);
const packages = entry.name.startsWith('@') ? readdirSync(namespace, { withFileTypes: true })
.filter(value => value.isDirectory() || value.isSymbolicLink()).map(value => join(namespace, value.name)) : [namespace];
for (const packageRoot of packages) {
assert.ok(++visited <= 10000 && contained(packageRoot), 'Installed dependency graph must be bounded and contained');
const path = relative(root, packageRoot).split(sep).join('/');
if (${/(?:^|\/)node_modules\/@openai\/codex-(?:linux|darwin|win32)-(?:x64|arm64)$/.toString()}.test(path)) {
let manifest;
try { manifest = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8')); }
catch (error) {
if (error.code !== 'ENOENT') throw error;
const contents = readdirSync(packageRoot), slot = lstatSync(packageRoot);
assert.ok(slot.isDirectory() && !slot.isSymbolicLink() && contents.length === 0,
'Codex optional slot without a manifest must be an empty regular directory; found ' +
JSON.stringify(contents.sort().slice(0, 16).map(name => name.slice(0, 256))));
// npm can leave an empty nested optional slot while hoisting the
// actual host payload. Its real lock and manifest still qualify below.
continue;
}
installed.push({ path, manifest });
}
const nested = join(packageRoot, 'node_modules');
if (existsSync(nested)) pending.push(nested);
}
}
}
const provenance = (${assertInstalledCodexPlatformProvenance.toString()})(lock, installed, process.platform + '-' + process.arch);
const index = ${JSON.stringify(indexPath)};
assert.ok(contained(index), 'Codex public index must be installed in the consumer');
const { resolvePinnedCodexCommand } = await import(pathToFileURL(index).href);
assert.equal(typeof resolvePinnedCodexCommand, 'function', 'Installed public index must export the pinned Codex resolver');
const command = resolvePinnedCodexCommand();
assert.ok(isAbsolute(command) && contained(command), 'Pinned Codex must resolve inside the installed consumer');
assert.ok(statSync(command).isFile(), 'Pinned Codex must be a regular executable');
accessSync(command, constants.X_OK);
const selectedPlatformManifest = realpathSync(createRequire(command).resolve('@openai/codex-' + process.platform + '-' + process.arch + '/package.json'));
const selectedPlatform = installed.find(({ path }) => realpathSync(join(root, path, 'package.json')) === selectedPlatformManifest);
assert.ok(selectedPlatform, 'Codex wrapper must resolve an official host platform package from its installed graph');
const selectedMetadata = JSON.parse(readFileSync(selectedPlatformManifest, 'utf8'));
assert.deepEqual(selectedMetadata, selectedPlatform.manifest, 'Selected Codex platform metadata must match its scanned provenance');
assert.equal(selectedMetadata.version, ${JSON.stringify(expectedVersion)} + '-' + process.platform + '-' + process.arch,
'Selected Codex platform version must match the qualified pin');
const version = execFileSync(command, ['--version'], { timeout: 30_000, maxBuffer: 128 * 1024, encoding: 'utf8',
env: { PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/tmp', NODE_PATH: '' } }).trim();
assert.equal(version, 'codex-cli ' + ${JSON.stringify(expectedVersion)}, 'Installed Codex version must match the qualified pin');
const vendor = dirname(index);
const integrityPath = join(vendor, 'drivers/acpx/installation-integrity.js');
const profilesPath = join(vendor, 'drivers/acpx/qualified-profiles.js');
const securityPath = join(vendor, 'drivers/codex/codex-security-config.js');
assert.ok(contained(integrityPath) && contained(profilesPath) && contained(securityPath), 'Codex verification modules must come from the installed consumer');
const { codexExecutableReadOnlyRoots, createIsolatedCodexAppServerArgs } = await import(pathToFileURL(securityPath).href);
const platformRoot = realpathSync(dirname(selectedPlatformManifest));
const nativeVendor = realpathSync(join(platformRoot, 'vendor'));
assert.ok(contained(nativeVendor) && nativeVendor.startsWith(platformRoot + sep), 'Codex vendor resources must remain inside their installed platform package');
const sandboxSource = { HOME: '/private-provider-home', PATH: '/usr/local/bin:/usr/bin:/bin' };
const readRoots = codexExecutableReadOnlyRoots(sandboxSource, command);
assert.ok(readRoots.includes(nativeVendor), 'Selected native Codex vendor directory must be readable inside its sandbox');
assert.ok(!readRoots.includes(platformRoot) && !readRoots.includes(root) && !readRoots.includes(sandboxSource.HOME), 'Codex sandbox must not grant enclosing npm or credential-home access');
const sandboxArgs = createIsolatedCodexAppServerArgs(sandboxSource, readRoots).join('\\n');
assert.ok(sandboxArgs.includes(JSON.stringify(nativeVendor) + '="read"'), 'Codex sandbox configuration must retain the selected native executable resources');
const { createAcpxPackageJsonResolver, verifyQualifiedAcpxInstallation } = await import(pathToFileURL(integrityPath).href);
const { resolveQualifiedAcpxProfile } = await import(pathToFileURL(profilesPath).href);
const serverRoot = resolve(vendor, '../../..');
assert.ok(contained(serverRoot), 'Codex package authority must be the installed server');
const installation = await verifyQualifiedAcpxInstallation(resolveQualifiedAcpxProfile('codex', 'gpt-5.4'),
createAcpxPackageJsonResolver(serverRoot, join(serverRoot, 'package.json')));
const lease = await installation.openCommand();
await lease.close();
console.log(JSON.stringify({ pinnedCodexCommandVerified: true, pinnedCodexVersion: ${JSON.stringify(expectedVersion)},
...provenance, codexSelectedPlatformPath: selectedPlatform.path, codexSelectedPlatformVersion: selectedMetadata.version, codexNativeSandboxResourcesVerified: true, codexQualifiedInstallationVerified: true, codexCommandLeaseVerified: true, providerCalls: 0 }));
`;
}
export function grokConsumerDockerArgs({ assets, consumer, cache, command, uid, gid, download = false, prerequisite, temporarySizeMb = 256 }) {
if (!Number.isSafeInteger(uid) || uid <= 0 || !Number.isSafeInteger(gid) || gid <= 0) {
throw new Error('Public-install verification requires an unprivileged host user');
+229 -3
View File
@@ -1,11 +1,13 @@
#!/usr/bin/env node
import { execFileSync } from "node:child_process";
import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
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 ?? {};
@@ -48,6 +50,222 @@ export function createBundledInstallManifest(publishManifest, bundledDependencie
return installManifest;
}
// npm consumers cannot inherit the workspace's pnpm overrides or patches.
// Materialize the already-qualified Codex bridge closure 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"],
]) {
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 };
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 Codex 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 (!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;
}
// 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(declarations, 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;
@@ -157,7 +375,12 @@ export function prepareBundledPackage(sourceDir, destinationDir, { sourceRoot =
const deployedPackagePath = resolve(destinationDir, "package.json");
const publishManifest = materializePublishManifest(sourcePackage);
const installManifest = createBundledInstallManifest(publishManifest, bundledDependencies);
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(
@@ -167,6 +390,7 @@ export function prepareBundledPackage(sourceDir, destinationDir, { sourceRoot =
);
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(
@@ -210,6 +434,8 @@ export function prepareBundledPackage(sourceDir, destinationDir, { sourceRoot =
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)) {
+13 -3
View File
@@ -9,7 +9,7 @@ import { tmpdir } from 'node:os';
import { basename, dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { materializePublishManifest, prepareBundledPackage } from './prepare-bundled-package.mjs';
import { GROK_PUBLIC_INSTALL_IMAGE, GROK_PUBLIC_INSTALL_LIFECYCLE, grokConsumerDockerArgs } from './grok-public-install-sandbox.mjs';
import { GROK_PUBLIC_INSTALL_IMAGE, GROK_PUBLIC_INSTALL_LIFECYCLE, assertNoBundledCodexPayloads, grokConsumerDockerArgs, installedCodexProbeSource } from './grok-public-install-sandbox.mjs';
const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..');
assert.equal(process.platform, 'linux', 'Run this verification on disposable EC2 Linux, not a developer host');
const root = mkdtempSync(join(tmpdir(), 'paperclip-grok-public-install-'));
@@ -57,7 +57,10 @@ try {
}
run('npm', ['pack', '--ignore-scripts', '--pack-destination', root], target);
const packed = readdirSync(root).filter(f => f.endsWith('.tgz') && !tarballs.includes(join(root, f)));
assert.equal(packed.length, 1); tarballs.push(join(root, packed[0]));
assert.equal(packed.length, 1);
const tarball = join(root, packed[0]);
assertNoBundledCodexPayloads(run('tar', ['-tzf', tarball]).toString().trim().split('\n'));
tarballs.push(tarball);
}
const assets = join(root, 'assets'); mkdirSync(assets, { mode: 0o755 });
const consumer = join(root, 'consumer'); mkdirSync(consumer);
@@ -94,6 +97,13 @@ try {
assert.equal(existsSync(prerequisite), false, 'npm must not provision Grok');
const server = join(consumer, 'node_modules/@paperclipai/server');
const installed = join(server, 'dist/vendor/paperclip-runner');
const codexVersion = JSON.parse(readFileSync(join(repo, 'packages/paperclip-runner/acpx-profiles.json'), 'utf8')).profiles.codex.agentRuntimeVersion;
assert.match(codexVersion, /^\d+\.\d+\.\d+$/);
writeFileSync(join(assets, 'codex-probe.mjs'), installedCodexProbeSource(
'/consumer/node_modules/@paperclipai/server/dist/vendor/paperclip-runner/index.js', '/consumer', codexVersion), { mode: 0o644 });
const codex = JSON.parse(isolated(['node', '/packages/codex-probe.mjs']).toString().trim());
assert.equal(codex.codexConsumerHostOnly, true);
assert.equal(codex.codexPlatformPackageSource, 'official npm');
assert.ok(existsSync(join(installed, 'providers/grok/launcher.cjs')));
assert.equal(existsSync(join(consumer, 'node_modules/@paperclipai/grok-acp')), false);
assert.equal(existsSync(join(installed, 'providers/grok/bin')), false);
@@ -114,7 +124,7 @@ try {
// Only the positive probe sees this file at the canonical sandbox path.
run(process.execPath, [join(repo, 'packages/paperclip-runner/scripts/provision-grok.mjs'), prerequisite]);
isolated(['node', '/packages/probe.mjs', 'present'], { prerequisite });
console.log(JSON.stringify({ schema: 'paperclip.grok.public-npm-install.v1', sourceRevision, releaseVersion, lifecycleScriptsEnabled: true, lifecycleSentinelVerified: true, lifecycleNetwork: 'none', consumerImage: GROK_PUBLIC_INSTALL_IMAGE, consumerUid, consumerLockPreserved: true, cleanNpmInstall: true, packageCount: needed.size, builtinLauncherPresent: true, separateGrokPackage: false, npmProvisionedBinary: false, missingPrerequisiteRejected: true, provisionedBinaryVerified: true, commandLeaseVerified: true, providerCalls: 0 }));
console.log(JSON.stringify({ schema: 'paperclip.grok.public-npm-install.v1', sourceRevision, releaseVersion, lifecycleScriptsEnabled: true, lifecycleSentinelVerified: true, lifecycleNetwork: 'none', consumerImage: GROK_PUBLIC_INSTALL_IMAGE, consumerUid, consumerLockPreserved: true, cleanNpmInstall: true, packageCount: needed.size, codexPackedPayloadsOmitted: true, codexPackedPackagesChecked: tarballs.length, ...codex, builtinLauncherPresent: true, separateGrokPackage: false, npmProvisionedBinary: false, missingPrerequisiteRejected: true, provisionedBinaryVerified: true, commandLeaseVerified: true, providerCalls: 0 }));
} finally {
rmSync(root, { recursive: true, force: true });
}