Files
PaperClipAI/server/src/services/native-runtime/provider-pack-archive.test.ts
T
Dotta 8e8c1b9f4d fix(sandbox): scope staged provider-pack assets per provider and default Daytona disk to 20 GiB (#22981)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Native agents run inside remote Daytona sandboxes that require a
verified Runner provider pack
> - When a sandbox stages the provider pack into its workspace,
Paperclip copies, transfers, and verifies every
`provider-assets/<provider>` closure (~1.6 GB across pi, cursor,
copilot, kimi, and antigravity) even when the run only uses Claude,
Codex, OpenCode, or one provider
> - New image-backed Daytona sandbox environments also default to a 10
GiB disk, which leaves too little headroom for repository installs and
tests
> - This pull request stages and verifies only the
`provider-assets/<provider>` tree needed by the active run and raises
the Daytona plugin default disk size from 10 GiB to 20 GiB
> - The benefit is significantly more free workspace disk space, smaller
pack transfers, and safer default disk sizing without changing the
provider-pack archive format or breaking multi-provider workspace reuse

## Linked Issues or Issue Description

- Fixes: #19367
- Refs #19484
- Related: #19500 (ENOSPC fail-fast and full-sandbox recovery already
merged in #22068, #22239, #22383, #22466, and #22837), #22241
(deduplicated repeated bytes in staged packs)

## What Changed

- `server/src/services/native-runtime/provider-pack-compatibility.ts`:
add `requiredProviderAssetNames`, `isProviderAssetPathIncluded`, and
`providerAssetExcludeArgs` helpers that resolve the required
`provider-assets/<provider>` subset for a `PackProvider` (returning
unfiltered behavior when `provider` is omitted).
- `server/src/services/native-runtime/provider-pack-layers.ts`: filter
large layer entries by required provider assets before running the
remote reuse script and transferring missing layers, preserve
cross-provider image-twin reuse so core files can still reuse identical
bytes from excluded provider paths in the base image, and pass
`--exclude` flags to GNU `tar` for `overlay.tar.zst`.
- `server/src/services/native-runtime/provider-pack-archive.ts` and
`provider-pack-upload.ts`: forward `provider` and `manifest` into v1 and
v2 archive staging and exclude unused `provider-assets/*` during
extraction.
-
`server/src/services/native-runtime/remote-provider-pack-verification.ts`:
scope candidate asset tree digest checks to the active provider when
`provider` is passed and include `requiredAssets` in the verification
seal key so a pack verified for one provider cannot satisfy a seal check
for a different provider.
- `server/src/services/native-runtime/native-session-executor.ts` and
`server/src/services/kimi-connection-probe.ts`: pass the active
`PackProvider` to `prepareRemoteProviderPackOnTarget` and
`verifyRemoteProviderPackIdentity`.
- `packages/plugins/sandbox-providers/daytona/src/manifest.ts` and
`package.json`: raise the default `disk` allocation from `10` to `20`
GiB and bump the plugin version from `0.1.10` to `0.1.11` so
bundled-plugin boot reconciliation refreshes persisted manifests.
- Added unit and end-to-end tests in
`packages/plugins/sandbox-providers/daytona/src/plugin.test.ts`,
`server/src/services/native-runtime/provider-pack-archive.test.ts`,
`server/src/services/native-runtime/remote-provider-pack-verification.test.ts`,
and updated `server/src/__tests__/kimi-connection-probe.test.ts`.

## Verification

- **RED (before production edits):**
- `cd packages/plugins/sandbox-providers/daytona && npx vitest run
--config vitest.config.ts -t "bumps the plugin version|pre-fills
sizing|validates and passes the default 20 GiB"` — 3 failed (`0.1.10 !==
0.1.11`, `10 !== 20`).
- `cd server && npx vitest run
src/services/native-runtime/provider-pack-archive.test.ts -t "omits all
provider-assets|stages only the selected provider"` — 2 failed (unused
`provider-assets` staged on disk).
- `cd server && npx vitest run
src/services/native-runtime/remote-provider-pack-verification.test.ts -t
"verifies only the selected provider"` — 1 failed (`candidate_digest`
rejected Claude when `provider-assets/` was absent).
- **GREEN (after fix):**
  - `cd server && npx tsc --noEmit -p tsconfig.json` — passed.
- `cd server && npx vitest run
src/services/native-runtime/provider-pack-archive.test.ts` — **56/56
passed**, including an end-to-end upload+verify test proving unfiltered
staging writes >= 6 MiB of provider assets, Claude staging omits all 6
MiB (< 256 KiB total) and verifies cleanly, and switching the same
workspace to Cursor rejects the Claude seal (`candidate_digest`) and
re-stages only Cursor (2 MiB, excluding Kimi and Pi).
- `cd server && npx vitest run
src/services/native-runtime/remote-provider-pack-verification.test.ts
src/services/native-runtime/remote-provider-pack.test.ts
src/services/native-runtime/retained-provider-pack-source.test.ts
src/__tests__/kimi-connection-probe.test.ts` — all passed
(`remote-provider-pack-verification.test.ts` 34/34,
`remote-provider-pack.test.ts` 60/60, `kimi-connection-probe.test.ts`
39/39, `retained-provider-pack-source.test.ts` all passed).
- `cd packages/plugins/sandbox-providers/daytona && pnpm typecheck &&
npx vitest run --config vitest.config.ts` — typecheck passed; all 15
offline test files passed (641 passed, 8 live tests skipped;
`archive-stream-window.test.ts` timed out once during parallel CPU
contention and passed in 6.17s when re-run).
- `node scripts/check-test-budget.mjs --files
server/src/services/native-runtime/provider-pack-archive.test.ts
server/src/services/native-runtime/remote-provider-pack-verification.test.ts
server/src/__tests__/kimi-connection-probe.test.ts` — passed (110
nightly suites validated, 3 test files checked).
- `pnpm verify --base 2d06567795
--explain` exited 2 because
`packages/plugins/sandbox-providers/daytona/package.json` is a global CI
input; focused suites and package typechecks ran locally and sharded PR
CI supplies broad coverage.
- **Not run locally:** Live Daytona sandbox provisioning (requires
`DAYTONA_API_KEY`). Managed Cloud snapshot disk sizing is updated
separately in the Cloud repository.

## Risks

- Low risk. Archive schema v1 and v2 remain unchanged, so existing
Docker images and retained OCI release packs work without rebuilding.
- If a reusable workspace previously staged a pack for one provider (for
example Claude) and a later run on the same workspace uses a provider
with native assets (for example Cursor), the provider-scoped
verification seal misses, `verifyStaged` fails with `candidate_digest`,
and `prepareRemoteProviderPackOnTarget` cleanly re-stages with the
needed provider assets.
- Raising the Daytona plugin default `disk` to 20 GiB only affects new
image-backed environments created with the form default; existing saved
environments and snapshot-backed environments keep their existing
configuration.

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

## Model Used

- Google Gemini (Antigravity agent) with shell, file editing, and local
test execution tools.

## 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
2026-11-25 15:33:44 -06:00

796 lines
48 KiB
TypeScript

import { execFile, spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import { afterEach, expect, it, vi } from "vitest";
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
import { readProviderPackArchive, stageProviderPackArchive } from "./provider-pack-archive.js";
import { uploadVerifiedProviderPack } from "./provider-pack-upload.js";
import { providerPackReusePlan } from "./provider-pack-layers.js";
import { requiredProviderAssetNames, toPackProvider } from "./provider-pack-compatibility.js";
import { canonicalProviderPackJson, verifyRemoteProviderPack } from "./remote-provider-pack-verification.js";
// @ts-expect-error Build-time script has no TypeScript declaration.
import { createProviderPackArchive, createProviderPackLayers } from "../../../../scripts/create-provider-pack-archive.mjs";
const exec = promisify(execFile);
const hasZstd = spawnSync("zstd", ["--version"]).status === 0;
const roots: string[] = [];
const digest = `sha256:${"a".repeat(64)}`;
afterEach(async () => { await Promise.all(roots.splice(0).map(root => fs.rm(root, { recursive: true, force: true }))); });
async function fixture() {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "provider-archive-"));
roots.push(root);
const pack = path.join(root, "pack");
await fs.mkdir(path.join(pack, "bin"), { recursive: true });
await fs.writeFile(path.join(pack, "provider-pack.json"), JSON.stringify({ schema: "paperclip-runner/remote-provider-pack/v1", digest }));
await fs.writeFile(path.join(pack, "bin", "tool"), "#!/bin/sh\necho fixture\n", { mode: 0o755 });
await fs.symlink("bin/tool", path.join(pack, "tool"));
await createProviderPackArchive(pack);
const archive = (await readProviderPackArchive(pack, digest))!;
if ("kind" in archive) throw Error("Expected historical single archive");
return { root, pack, archive };
}
const tar = await Promise.all(["gtar", "tar"].map(async name => {
try { const { stdout } = await exec(name, ["--version"]); return stdout.includes("GNU tar") ? name : null; }
catch { return null; }
})).then(names => names.find(Boolean));
async function runner(root: string, corrupt = false, toolPath?: string) {
const bin = path.join(root, "commands");
await fs.mkdir(bin);
const resolved = (await exec("sh", ["-c", 'command -v "$1"', "sh", tar!])).stdout.trim();
await fs.symlink(resolved, path.join(bin, "tar"));
const syncIn = vi.fn<NonNullable<CommandManagedRuntimeRunner["syncIn"]>>(async operations => {
for (const operation of operations) for (const file of operation.files) {
expect(file.kind).toBe("file");
await fs.mkdir(path.dirname(file.targetPath), { recursive: true });
await fs.copyFile(file.sourcePath, file.targetPath);
if (corrupt) await fs.appendFile(file.targetPath, "corrupted in transit");
}
return { operations: await Promise.all(operations.map(async operation => ({ operationId: operation.operationId, filesTransferred: operation.files.length,
bytesTransferred: (await Promise.all(operation.files.map(async file => (await fs.stat(file.sourcePath)).size))).reduce((sum, size) => sum + size, 0) }))) };
});
const execute = vi.fn<CommandManagedRuntimeRunner["execute"]>(async input => {
try {
const result = await exec(input.command, input.args ?? [], { env: { ...process.env, PATH: toolPath ?? `${bin}:${process.env.PATH}` } });
return { exitCode: 0, signal: null, pid: null, startedAt: null, timedOut: false, stdout: result.stdout, stderr: result.stderr };
} catch (error) {
const failed = error as { code?: unknown; stdout?: unknown; stderr?: unknown };
return {
exitCode: typeof failed.code === "number" ? failed.code : 1,
signal: null,
pid: null,
startedAt: null,
timedOut: false,
stdout: typeof failed.stdout === "string" ? failed.stdout : "",
stderr: typeof failed.stderr === "string" && failed.stderr.length > 0 ? failed.stderr : String(error),
};
}
});
return { syncIn, execute };
}
it("keeps historical/source packs without an archive on the existing path", async () => {
expect(await readProviderPackArchive("/does-not-exist/provider-pack", digest)).toBeNull();
});
it.each(["v1", "v2"])("cancels a real %s archive hash after its first read chunk", async version => {
const { pack } = version === "v2" ? await layeredFixture() : await fixture();
const archivePath = version === "v2" ? `${pack}.archives/overlay.tar.zst` : `${pack}.tar.zst`;
await fs.utimes(archivePath, new Date(), new Date(Date.now() + 60_000));
const controller = new AbortController();
const handle = await fs.open(archivePath, "r");
const prototype = Object.getPrototypeOf(handle) as typeof handle;
await handle.close();
const originalStream = prototype.createReadStream;
const streaming = vi.spyOn(prototype, "createReadStream").mockImplementation(function(this: typeof handle, options) {
const stream = originalStream.call(this, options);
stream.once("data", () => controller.abort(new Error("owned archive read stopped")));
return stream;
});
try {
await expect(readProviderPackArchive(pack, digest, controller.signal)).rejects.toThrow(/abort|owned archive read stopped/i);
expect(controller.signal.aborted).toBe(true);
} finally { streaming.mockRestore(); }
});
it("hashes an unchanged verified archive once per server process and again after it changes", async () => {
const { pack } = await fixture();
const archivePath = `${pack}.tar.zst`;
const handle = await fs.open(archivePath, "r");
const prototype = Object.getPrototypeOf(handle) as typeof handle;
await handle.close();
const streaming = vi.spyOn(prototype, "createReadStream");
try {
await expect(readProviderPackArchive(pack, digest)).resolves.toMatchObject({ sourcePath: archivePath });
expect(streaming).not.toHaveBeenCalled();
const original = await fs.readFile(archivePath);
const corrupted = Buffer.from(original);
corrupted[corrupted.length - 1] ^= 0xff;
await fs.writeFile(archivePath, corrupted);
await expect(readProviderPackArchive(pack, digest)).rejects.toThrow("sha256_mismatch");
expect(streaming).toHaveBeenCalledOnce();
} finally { streaming.mockRestore(); }
});
async function layeredFixture() {
const { root, pack } = await fixture();
await fs.writeFile(path.join(pack, "bin", "large"), Buffer.alloc(1024 * 1024, 42), { mode: 0o755 });
const receipt = await createProviderPackLayers(pack);
const archive = (await readProviderPackArchive(pack, digest))!;
if (!("kind" in archive)) throw Error("Expected layered archive");
return { root, pack, receipt, archive };
}
const toolPath = "node_modules/.pnpm/tool@1.0.0/node_modules/tool/bin/tool";
const twinPath = "node_modules/.pnpm/tool-baseline@1.0.0/node_modules/tool-baseline/bin/tool";
const otherTwinPath = "provider-assets/kimi/linux-x64/runtime/node/bin/tool";
/** A pack that repeats one large binary under three paths, like the OpenCode
* binary in a release pack, with an older image that has it under one path. */
async function repeatedBytesFixture(modes: Record<string, number> = {}) {
const { root, pack } = await fixture();
for (const relative of [toolPath, twinPath, otherTwinPath]) {
await fs.mkdir(path.dirname(path.join(pack, relative)), { recursive: true });
await fs.writeFile(path.join(pack, relative), Buffer.alloc(2 * 1024 * 1024, 9));
await fs.chmod(path.join(pack, relative), modes[relative] ?? 0o755);
}
await createProviderPackLayers(pack);
const archive = (await readProviderPackArchive(pack, digest))!;
if (!("kind" in archive)) throw Error("Expected layered archive");
const image = path.join(root, "image");
await fs.cp(pack, image, { recursive: true, verbatimSymlinks: true });
for (const relative of [twinPath, otherTwinPath]) await fs.rm(path.join(image, relative));
return { root, pack, image, archive };
}
it.skipIf(!tar || !hasZstd)("stores repeated bytes once, from an image file under another path, without transferring them", async () => {
const { root, pack, image, archive } = await repeatedBytesFixture();
const remote = await runner(root);
const targetPath = path.join(root, "fresh");
const before = (await fs.readdir(image, { recursive: true })).sort();
expect(await stageProviderPackArchive({ archive, runner: remote, targetPath, reuseRoots: [image] })).toBe(true);
const staged = await Promise.all([toolPath, twinPath, otherTwinPath].map(relative => fs.lstat(path.join(targetPath, relative))));
// Physical files inside the pack, sharing one private inode that is not the image's.
for (const stat of staged) expect(stat.isFile()).toBe(true);
expect(new Set(staged.map(stat => stat.ino)).size).toBe(1);
expect(staged[0]!.ino).not.toBe((await fs.stat(path.join(image, toolPath))).ino);
expect(staged[0]!.nlink).toBe(3);
for (const relative of [toolPath, twinPath, otherTwinPath]) {
expect(await fs.readFile(path.join(targetPath, relative))).toEqual(await fs.readFile(path.join(pack, relative)));
expect((await fs.stat(path.join(targetPath, relative))).mode & 0o777).toBe(0o755);
}
// Only the small-file overlay crosses the network, and the image is unchanged.
expect((await remote.syncIn.mock.results[0]!.value).operations[0]!.bytesTransferred).toBe(archive.overlay.bytes);
expect((await fs.readdir(image, { recursive: true })).sort()).toEqual(before);
}, 60_000);
it("plans one private copy per digest and mode, with same-bytes twins as copy sources", () => {
const a = "a".repeat(64), b = "b".repeat(64);
expect(providerPackReusePlan([
{ path: "one", sha256: a, mode: 0o755 },
{ path: "two", sha256: a, mode: 0o644 },
{ path: "three", sha256: a, mode: 0o755 },
{ path: "four", sha256: a, mode: 0o644 },
{ path: "other", sha256: b, mode: 0o755 },
])).toEqual([
{ sources: ["one", "two", "three", "four"], group: 0 },
{ sources: ["two", "one", "three", "four"], group: 1 },
{ sources: ["three", "one", "two", "four"], group: 0 },
{ sources: ["four", "one", "two", "three"], group: 1 },
{ sources: ["other"], group: 2 },
]);
});
it.skipIf(!tar || !hasZstd)("keeps one private copy per mode when the same bytes repeat with different modes", async () => {
const { root, pack, image, archive } = await repeatedBytesFixture({ [twinPath]: 0o644 });
const remote = await runner(root);
const targetPath = path.join(root, "fresh");
expect(await stageProviderPackArchive({ archive, runner: remote, targetPath, reuseRoots: [image] })).toBe(true);
const [tool, twin, other] = await Promise.all([toolPath, twinPath, otherTwinPath].map(relative => fs.lstat(path.join(targetPath, relative))));
expect(other!.ino).toBe(tool!.ino);
expect(twin!.ino).not.toBe(tool!.ino);
expect(twin!.mode & 0o777).toBe(0o644);
expect(tool!.mode & 0o777).toBe(0o755);
expect(await fs.readFile(path.join(targetPath, twinPath))).toEqual(await fs.readFile(path.join(pack, twinPath)));
expect((await remote.syncIn.mock.results[0]!.value).operations[0]!.bytesTransferred).toBe(archive.overlay.bytes);
});
it.skipIf(!tar || !hasZstd)("transfers repeated bytes when no image has them, and does not reuse a changed twin", async () => {
const { root, pack, image, archive } = await repeatedBytesFixture();
await fs.writeFile(path.join(image, toolPath), Buffer.alloc(2 * 1024 * 1024, 10));
const remote = await runner(root);
const targetPath = path.join(root, "fresh");
expect(await stageProviderPackArchive({ archive, runner: remote, targetPath, reuseRoots: [image] })).toBe(true);
for (const relative of [toolPath, twinPath, otherTwinPath]) {
expect(await fs.readFile(path.join(targetPath, relative))).toEqual(await fs.readFile(path.join(pack, relative)));
}
const layers = archive.files.reduce((sum, file) => sum + file.archive.bytes, 0);
expect((await remote.syncIn.mock.results[0]!.value).operations[0]!.bytesTransferred).toBe(archive.overlay.bytes + layers);
}, 60_000);
it("writes the same archive for the same file every time, with nothing after the frame", async () => {
// Ending the compressor while its last chunk was still queued made Node
// finish the zstd stream twice, and about half the archives got an empty
// frame at their end. An image layer of these archives then never repeated.
const emptyFrame = Buffer.from("28b52ffd2000010000", "hex");
const seen = new Set<string>();
for (let trial = 0; trial < 12; trial += 1) {
const { pack } = await fixture();
const large = path.join(pack, "bin", "large");
await fs.writeFile(large, Buffer.alloc(1024 * 1024, 42), { mode: 0o755 });
await fs.utimes(large, 0, 0);
const receipt = await createProviderPackLayers(pack);
seen.add(receipt.files[0].archive.sha256);
for (const name of ["0.tar.zst", "overlay.tar.zst"]) {
const bytes = await fs.readFile(path.join(`${pack}.archives`, name));
expect(bytes.subarray(-emptyFrame.length).equals(emptyFrame), name).toBe(false);
}
}
expect([...seen]).toHaveLength(1);
});
it("names the archives of dependency files without regard to the Runner's own large files", async () => {
// Archive N holds file N of the receipt. `dist` sorts before `node_modules`,
// so in path order one more large file in the Runner's build output renamed
// the archive of every dependency file.
const large = Buffer.alloc(1024 * 1024, 42);
const receiptOf = async (own: string[]) => {
const { pack } = await fixture();
for (const file of ["node_modules/dependency/tool", "bin/large", ...own]) {
await fs.mkdir(path.dirname(path.join(pack, file)), { recursive: true });
await fs.writeFile(path.join(pack, file), large, { mode: 0o755 });
await fs.utimes(path.join(pack, file), 0, 0);
}
const receipt = await createProviderPackLayers(pack);
const archive = (await readProviderPackArchive(pack, digest))!;
if (!("kind" in archive)) throw Error("Expected layered archive");
// What a reader pairs: file N of the receipt with N.tar.zst.
const paired = await Promise.all(archive.files.map(async (file: { path: string; archive: { sha256: string } }, index: number) =>
[file.path, `${index}.tar.zst`, createHash("sha256").update(await fs.readFile(path.join(`${pack}.archives`, `${index}.tar.zst`))).digest("hex") === file.archive.sha256]));
return { paths: receipt.files.map((file: { path: string }) => file.path), paired };
};
const before = await receiptOf(["dist/cli/one.js"]);
const after = await receiptOf(["dist/cli/one.js", "dist/a-new-large-file.js", "dist/cli/two.js"]);
expect(before.paths).toEqual(["bin/large", "node_modules/dependency/tool", "dist/cli/one.js"]);
expect(after.paths).toEqual(["bin/large", "node_modules/dependency/tool", "dist/a-new-large-file.js", "dist/cli/one.js", "dist/cli/two.js"]);
// The dependency files keep their archive names, and every pairing a reader makes still holds.
expect(after.paired.slice(0, 2)).toEqual(before.paired.slice(0, 2));
expect(after.paired.every(([, , matches]) => matches)).toBe(true);
});
it.skipIf(!tar || !hasZstd)("reuses only byte-matched image files, keeps modes, and never shares writable hardlinks", async () => {
const { root, pack, archive } = await layeredFixture();
const remote = await runner(root);
const targetPath = path.join(root, "fresh");
expect(await stageProviderPackArchive({ archive, runner: remote, targetPath, reuseRoots: [pack] })).toBe(true);
expect(remote.syncIn.mock.calls[0]![0][0]!.files).toHaveLength(1);
expect((await remote.syncIn.mock.results[0]!.value).operations[0]!.bytesTransferred).toBe(archive.overlay.bytes);
const original = path.join(pack, "bin/large"), copied = path.join(targetPath, "bin/large");
expect(await fs.readFile(copied)).toEqual(await fs.readFile(original));
expect((await fs.stat(copied)).mode & 0o777).toBe(0o755);
expect((await fs.stat(copied)).ino).not.toBe((await fs.stat(original)).ino);
await fs.writeFile(copied, "changed");
expect((await fs.stat(original)).size).toBe(1024 * 1024);
expect(await fs.readlink(path.join(targetPath, "tool"))).toBe("bin/tool");
});
it.skipIf(!tar || !hasZstd)("stages a complete layered pack into a fresh nested runtime directory", async () => {
const { root, pack, archive } = await layeredFixture();
const remote = await runner(root);
const workspace = path.join(root, "workspace");
await fs.mkdir(workspace);
const targetPath = path.join(workspace, ".paperclip-runtime", "paperclip-runner", "provider-pack");
await expect(fs.lstat(path.dirname(targetPath))).rejects.toMatchObject({ code: "ENOENT" });
expect(await stageProviderPackArchive({ archive, runner: remote, targetPath, reuseRoots: [pack] })).toBe(true);
expect(await fs.readFile(path.join(targetPath, "bin/large"))).toEqual(await fs.readFile(path.join(pack, "bin/large")));
expect(await fs.readFile(path.join(targetPath, "provider-pack.json"))).toEqual(await fs.readFile(path.join(pack, "provider-pack.json")));
expect(await fs.readlink(path.join(targetPath, "tool"))).toBe("bin/tool");
for (const directory of [targetPath, path.dirname(targetPath), path.dirname(path.dirname(targetPath))]) {
expect((await fs.stat(directory)).mode & 0o777).toBe(0o700);
}
expect((await fs.stat(path.join(targetPath, "bin/large"))).ino).not.toBe((await fs.stat(path.join(pack, "bin/large"))).ino);
});
it.skipIf(!tar || !hasZstd).each(["missing", "wrong-digest", "symlink", "ancestor-symlink"])("transfers a large layer when the image file is %s", async reason => {
const { root, pack, archive } = await layeredFixture();
const remote = await runner(root);
const old = path.join(root, "old");
await fs.cp(pack, old, { recursive: true });
const large = path.join(old, "bin/large");
if (reason === "missing") await fs.unlink(large);
if (reason === "wrong-digest") await fs.writeFile(large, Buffer.alloc(1024 * 1024, 43));
if (reason === "symlink") { await fs.unlink(large); await fs.symlink(path.join(pack, "bin/large"), large); }
if (reason === "ancestor-symlink") { await fs.rm(path.join(old, "bin"), { recursive: true }); await fs.symlink(path.join(pack, "bin"), path.join(old, "bin")); }
const targetPath = path.join(root, "fresh");
expect(await stageProviderPackArchive({ archive, runner: remote, targetPath, reuseRoots: [old] })).toBe(true);
expect((await remote.syncIn.mock.results[0]!.value).operations[0]!.bytesTransferred).toBe(archive.overlay.bytes + archive.files[0]!.archive.bytes);
expect(await fs.readFile(path.join(targetPath, "bin/large"))).toEqual(await fs.readFile(path.join(pack, "bin/large")));
});
it.each(["traversal", "duplicate", "ancestor", "mode", "digest", "layer-symlink"])("rejects invalid layer metadata or bytes: %s", async reason => {
const { pack, receipt } = await layeredFixture();
if (reason === "traversal") receipt.files[0].path = "../outside";
if (reason === "duplicate") receipt.files.push(receipt.files[0]);
if (reason === "ancestor") receipt.files.push({ ...receipt.files[0], path: "bin" });
if (reason === "mode") receipt.files[0].mode = 0o4755;
if (reason === "digest") receipt.overlay.sha256 = "0".repeat(64);
if (reason === "layer-symlink") {
const overlay = `${pack}.archives/overlay.tar.zst`;
await fs.rename(overlay, `${overlay}.original`); await fs.symlink(`${overlay}.original`, overlay);
}
await fs.writeFile(`${pack}.archive.json`, JSON.stringify(receipt));
await expect(readProviderPackArchive(pack, digest)).rejects.toThrow();
});
it.skipIf(!tar || !hasZstd)("rejects a corrupt missing layer before transfer and a corrupt upload before extraction", async () => {
const { root, pack, archive } = await layeredFixture();
const remote = await runner(root, true);
const targetPath = path.join(root, "fresh");
await expect(stageProviderPackArchive({ archive, runner: remote, targetPath })).rejects.toThrow("runner_remote_provider_archive_extract_failed");
expect(await fs.readdir(targetPath)).toEqual([]);
expect((await fs.readdir(root)).some(name => name.includes(".upload-"))).toBe(false);
await fs.appendFile(`${pack}.archives/0.tar.zst`, "corrupt");
remote.syncIn.mockClear();
await expect(stageProviderPackArchive({ archive, runner: remote, targetPath: `${targetPath}-2` })).rejects.toThrow("runner_remote_provider_archive_invalid: size_mismatch");
await fs.unlink(`${pack}.archives/0.tar.zst`);
await expect(stageProviderPackArchive({ archive, runner: remote, targetPath: `${targetPath}-3` })).rejects.toThrow("runner_remote_provider_archive_invalid: archive_unreadable");
expect(remote.syncIn).not.toHaveBeenCalled();
});
it.skipIf(!tar || !hasZstd).each(["directory", "file", "symlink"])("rejects an existing layered target %s or invalid reuse receipts", async kind => {
const { root, archive } = await layeredFixture();
const remote = await runner(root);
const targetPath = path.join(root, "target"), other = path.join(root, "other");
await fs.mkdir(other);
if (kind === "directory") await fs.mkdir(targetPath);
else if (kind === "file") await fs.writeFile(targetPath, "untouched");
else await fs.symlink(other, targetPath);
await expect(stageProviderPackArchive({ archive, runner: remote, targetPath })).rejects.toThrow("runner_remote_provider_archive_reuse_failed");
expect(await fs.readdir(other)).toEqual([]);
if (kind === "directory") expect(await fs.readdir(targetPath)).toEqual([]);
if (kind === "file") expect(await fs.readFile(targetPath, "utf8")).toBe("untouched");
remote.execute.mockResolvedValue({ exitCode: 0, timedOut: false, stdout: "[999999]", stderr: "", signal: null, pid: null, startedAt: null });
await expect(stageProviderPackArchive({ archive, runner: remote, targetPath: `${targetPath}-2` })).rejects.toThrow("runner_remote_provider_archive_reuse_failed");
expect(remote.syncIn).not.toHaveBeenCalled();
});
it.each(["identity", "bytes", "sha256", "json", "symlink"])("rejects invalid archive %s", async failure => {
const { pack } = await fixture();
const receiptPath = `${pack}.archive.json`;
const receipt = JSON.parse(await fs.readFile(receiptPath, "utf8"));
if (failure === "identity") receipt.providerPackDigest = `sha256:${"b".repeat(64)}`;
if (failure === "bytes") receipt.bytes++;
if (failure === "sha256") receipt.sha256 = "c".repeat(64);
await fs.writeFile(receiptPath, failure === "json" ? "{" : JSON.stringify(receipt));
if (failure === "symlink") {
await fs.rename(`${pack}.tar.zst`, `${pack}.original`);
await fs.symlink(`${pack}.original`, `${pack}.tar.zst`);
}
await expect(readProviderPackArchive(pack, digest)).rejects.toThrow();
});
it.skipIf(!tar || !hasZstd)("uploads build-time bytes to fresh targets, preserving files, modes and symlinks", async () => {
const { root, archive } = await fixture();
const remote = await runner(root);
for (const name of ["first ' ; #", "follow-up"]) {
const targetPath = path.join(root, name);
await stageProviderPackArchive({ archive, runner: remote, targetPath });
expect(await fs.readFile(path.join(targetPath, "bin/tool"), "utf8")).toBe("#!/bin/sh\necho fixture\n");
expect((await fs.stat(path.join(targetPath, "bin/tool"))).mode & 0o777).toBe(0o755);
expect((await fs.stat(targetPath)).mode & 0o777).toBe(0o700);
expect(await fs.readlink(path.join(targetPath, "tool"))).toBe("bin/tool");
}
expect((await fs.readdir(root)).some(name => name.includes(".upload-"))).toBe(false);
expect(remote.syncIn).toHaveBeenCalledTimes(2);
});
it.skipIf(!tar || !hasZstd)("rejects corrupt transferred bytes before extracting and cleans scratch", async () => {
const { root, archive } = await fixture();
const targetPath = path.join(root, "target");
await expect(stageProviderPackArchive({ archive, runner: await runner(root, true), targetPath }))
.rejects.toThrow("runner_remote_provider_archive_extract_failed");
expect(await fs.readdir(root)).not.toContain("target");
expect((await fs.readdir(root)).some(name => name.includes(".upload-"))).toBe(false);
});
it.skipIf(!tar || !hasZstd)("does not follow a remote target symlink", async () => {
const { root, archive } = await fixture();
const targetPath = path.join(root, "target");
const other = path.join(root, "other");
await fs.mkdir(other); await fs.symlink(other, targetPath);
await expect(stageProviderPackArchive({ archive, runner: await runner(root), targetPath }))
.rejects.toThrow("runner_remote_provider_archive_extract_failed");
expect(await fs.readdir(other)).toEqual([]);
});
it.skipIf(!tar || !hasZstd)("rejects malformed tar even with a matching transport digest", async () => {
const { root, archive } = await fixture();
await fs.writeFile(archive.sourcePath, "invalid tar");
archive.sha256 = createHash("sha256").update("invalid tar").digest("hex");
await expect(stageProviderPackArchive({ archive, runner: await runner(root), targetPath: path.join(root, "target") }))
.rejects.toThrow("runner_remote_provider_archive_extract_failed");
expect((await fs.readdir(root)).some(name => name.includes(".upload-"))).toBe(false);
});
it("keeps the directory fallback when the remote has no zstd", async () => {
const { archive } = await fixture();
const remote = { syncIn: vi.fn(), execute: vi.fn().mockResolvedValue({ exitCode: 127, timedOut: false }) };
expect(await stageProviderPackArchive({ archive, runner: remote, targetPath: "/unused" })).toBe(false);
expect(remote.syncIn).not.toHaveBeenCalled();
});
it.skipIf(!tar || !hasZstd).each(["v1", "v2"])("installs verified %s archive bytes without reading the unused expanded pack", async version => {
const { root, pack } = version === "v1" ? await fixture() : await layeredFixture();
const remote = await runner(root);
const targetPath = path.join(root, "uploaded");
const expected = await fs.readFile(path.join(pack, "bin/tool"));
// Only the archive is uploaded. The expanded tree is a different source,
// and deliberately no longer matches the bytes sealed in that archive.
await fs.writeFile(path.join(pack, "bin/tool"), "unused expanded bytes");
const verifyDirectory = vi.fn(() => { throw Error("expanded_directory_was_read"); });
const stageDirectory = vi.fn(async () => { throw Error("directory_was_uploaded"); });
const verifyUploaded = vi.fn(async () => {
expect(await fs.readFile(path.join(targetPath, "bin/tool"))).toEqual(expected);
expect(JSON.parse(await fs.readFile(path.join(targetPath, "provider-pack.json"), "utf8")).digest).toBe(digest);
});
await uploadVerifiedProviderPack({ root: pack, sourceDigest: digest, expectedDigest: digest, runner: remote, cwd: root,
targetPath, reuseRoots: [], verifyDirectory, stageDirectory, verifyUploaded });
expect(verifyDirectory).not.toHaveBeenCalled();
expect(stageDirectory).not.toHaveBeenCalled();
expect(verifyUploaded).toHaveBeenCalledOnce();
});
it.each(["absent", "unsupported"])("verifies directory bytes before fallback when the archive is %s", async mode => {
const { root, pack } = await fixture();
if (mode === "absent") await fs.unlink(`${pack}.archive.json`);
const remote = { syncIn: vi.fn(), execute: vi.fn().mockResolvedValue({ exitCode: 0, timedOut: false, stdout: "", stderr: "" }) };
// The capability probe fails; clearing the old pack succeeds.
remote.execute.mockResolvedValueOnce({ exitCode: 0, timedOut: false });
remote.execute.mockResolvedValue({ exitCode: 127, timedOut: false });
const stageDirectory = vi.fn(), verifyUploaded = vi.fn();
await expect(uploadVerifiedProviderPack({ root: pack, sourceDigest: digest, expectedDigest: digest, runner: remote, cwd: root,
targetPath: path.join(root, "uploaded"), reuseRoots: [], verifyDirectory: () => { throw Error("directory_digest_mismatch"); },
stageDirectory, verifyUploaded })).rejects.toThrow("directory_digest_mismatch");
expect(remote.syncIn).not.toHaveBeenCalled();
expect(stageDirectory).not.toHaveBeenCalled();
expect(verifyUploaded).not.toHaveBeenCalled();
});
// A retained continuation can select a pack from an earlier release. The
// controller's build-time archives then carry a different identity. That is an
// artifact incompatibility, not archive corruption, and it must not clear the
// remote pack or upload the controller's different pack.
it.each(["v1", "v2", "directory"])("refuses a selected pack this controller does not ship (%s source)", async source => {
const { root, pack } = source === "v2" ? await layeredFixture() : await fixture();
if (source === "directory") await fs.unlink(`${pack}.archive.json`);
const retained = `sha256:${"b".repeat(64)}`;
const remote = { syncIn: vi.fn(), execute: vi.fn().mockResolvedValue({ exitCode: 0, timedOut: false, stdout: "", stderr: "" }) };
const verifyDirectory = vi.fn(), stageDirectory = vi.fn(), verifyUploaded = vi.fn();
const upload = uploadVerifiedProviderPack({ root: pack, sourceDigest: digest, expectedDigest: retained, runner: remote, cwd: root,
targetPath: path.join(root, "uploaded"), reuseRoots: [], verifyDirectory, stageDirectory, verifyUploaded });
await expect(upload).rejects.toThrow(
`runner_remote_provider_artifact_incompatible: selected provider pack ${"b".repeat(12)} is not the controller's pack ${"a".repeat(12)}`);
expect(remote.execute).not.toHaveBeenCalled();
expect(remote.syncIn).not.toHaveBeenCalled();
for (const step of [verifyDirectory, stageDirectory, verifyUploaded]) expect(step).not.toHaveBeenCalled();
});
it.skipIf(!tar || !hasZstd).each(["v1", "v2"])("names the failed %s archive check in the run-visible error", async version => {
const { pack } = version === "v1" ? await fixture() : await layeredFixture();
const archive = version === "v1" ? `${pack}.tar.zst` : `${pack}.archives/overlay.tar.zst`;
const bytes = await fs.readFile(archive);
await fs.appendFile(archive, "x");
await expect(readProviderPackArchive(pack, digest)).rejects.toThrow("runner_remote_provider_archive_invalid: size_mismatch");
bytes[bytes.length - 1] ^= 1;
await fs.writeFile(archive, bytes);
await expect(readProviderPackArchive(pack, digest)).rejects.toThrow("runner_remote_provider_archive_invalid: sha256_mismatch");
const receipt = JSON.parse(await fs.readFile(`${pack}.archive.json`, "utf8"));
await fs.writeFile(`${pack}.archive.json`, JSON.stringify({ ...receipt, providerPackDigest: `sha256:${"c".repeat(64)}` }));
await expect(readProviderPackArchive(pack, digest)).rejects.toThrow("runner_remote_provider_archive_invalid: receipt_identity_mismatch");
await fs.writeFile(`${pack}.archive.json`, "{");
await expect(readProviderPackArchive(pack, digest)).rejects.toThrow("runner_remote_provider_archive_invalid: receipt_unreadable");
});
it.skipIf(!tar || !hasZstd)("rejects an installed pack that fails final verification", async () => {
const { root, pack } = await fixture();
const remote = await runner(root), targetPath = path.join(root, "uploaded");
const verifyUploaded = vi.fn(async () => { throw Error("installed_digest_mismatch"); });
await expect(uploadVerifiedProviderPack({ root: pack, sourceDigest: digest, expectedDigest: digest, runner: remote, cwd: root,
targetPath, reuseRoots: [], verifyDirectory: () => {}, stageDirectory: async () => {}, verifyUploaded }))
.rejects.toThrow("installed_digest_mismatch");
expect(remote.syncIn).toHaveBeenCalledOnce();
expect(verifyUploaded).toHaveBeenCalledOnce();
});
it.skipIf(!tar || !hasZstd).each([
["v1", "bsd-tar"], ["v2", "bsd-tar"],
["v1", "older-gnu-tar"], ["v2", "older-gnu-tar"],
["v1", "missing-sha256sum"], ["v2", "missing-sha256sum"],
])("keeps %s on directory staging with %s before creating a target or uploading", async (version, unsupported) => {
const { root, archive } = version === "v1" ? await fixture() : await layeredFixture();
const tools = path.join(root, "tools");
await fs.mkdir(tools);
await fs.symlink(process.execPath, path.join(tools, "node"));
for (const name of ["sh", "zstd", "cut", ...(unsupported === "missing-sha256sum" ? [] : ["sha256sum"])]) {
const resolved = (await exec("sh", ["-c", 'command -v "$1"', "sh", name])).stdout.trim();
await fs.symlink(resolved, path.join(tools, name));
}
if (unsupported === "bsd-tar") {
await fs.writeFile(path.join(tools, "tar"), "#!/bin/sh\nprintf 'bsdtar 3.8.2\\n'\n", { mode: 0o755 });
} else if (unsupported === "older-gnu-tar") {
await fs.writeFile(path.join(tools, "tar"), '#!/bin/sh\nif [ "$1" = "--version" ]; then printf "tar (GNU tar) 1.30\\n"; else exit 64; fi\n', { mode: 0o755 });
} else {
const resolved = (await exec("sh", ["-c", 'command -v "$1"', "sh", tar!])).stdout.trim();
await fs.symlink(resolved, path.join(tools, "tar"));
}
const remote = await runner(root, false, tools);
const targetPath = path.join(root, "fresh");
expect(await stageProviderPackArchive({ archive, runner: remote, targetPath })).toBe(false);
expect(remote.execute).toHaveBeenCalledOnce();
expect(remote.syncIn).not.toHaveBeenCalled();
await expect(fs.lstat(targetPath)).rejects.toMatchObject({ code: "ENOENT" });
});
async function multiProviderFixture() {
const { root, pack } = await fixture();
const large = (fill: number) => Buffer.alloc(1024 * 1024, fill);
const coreLarge = "node_modules/node/bin/node";
const cursorLarge = "provider-assets/cursor/linux-x64/cursor-bin";
const kimiLarge = "provider-assets/kimi/linux-x64/runtime/node/bin/node";
const piLarge = "provider-assets/pi/linux-x64/pi-bin";
const smallFiles = [
["provider-assets/cursor/linux-x64/manifest.txt", "cursor-small"],
["provider-assets/kimi/linux-x64/manifest.txt", "kimi-small"],
["provider-assets/pi/linux-x64/manifest.txt", "pi-small"],
] as const;
for (const [relative, content] of [
[coreLarge, large(1)],
[cursorLarge, large(2)],
[kimiLarge, large(1)], // Same bytes as coreLarge to verify cross-provider image-twin reuse.
[piLarge, large(3)],
] as const) {
await fs.mkdir(path.dirname(path.join(pack, relative)), { recursive: true });
await fs.writeFile(path.join(pack, relative), content, { mode: 0o755 });
}
for (const [relative, content] of smallFiles) {
await fs.mkdir(path.dirname(path.join(pack, relative)), { recursive: true });
await fs.writeFile(path.join(pack, relative), content, { mode: 0o644 });
}
await createProviderPackLayers(pack);
const archive = (await readProviderPackArchive(pack, digest))!;
if (!("kind" in archive)) throw Error("Expected layered archive");
return { root, pack, archive, coreLarge, cursorLarge, kimiLarge, piLarge };
}
it.skipIf(!tar || !hasZstd)("omits all provider-assets when staging a layered pack for Claude or OpenCode", async () => {
const { root, archive, coreLarge } = await multiProviderFixture();
const fullLayers = archive.files.reduce((sum, file) => sum + file.archive.bytes, 0);
const remote = await runner(root);
for (const provider of [{ kind: "acpx" as const, agent: "claude" }, { kind: "opencode" as const }] as const) {
remote.syncIn.mockClear();
const targetPath = path.join(root, `staged-${provider.kind}-${"agent" in provider ? provider.agent : "oc"}`);
expect(await stageProviderPackArchive({ archive, runner: remote, targetPath, provider })).toBe(true);
expect(await fs.readFile(path.join(targetPath, "bin/tool"), "utf8")).toBe("#!/bin/sh\necho fixture\n");
expect((await fs.stat(path.join(targetPath, coreLarge))).size).toBe(1024 * 1024);
await expect(fs.lstat(path.join(targetPath, "provider-assets"))).rejects.toMatchObject({ code: "ENOENT" });
const transferred = (await remote.syncIn.mock.results[0]!.value).operations[0]!.bytesTransferred;
expect(transferred).toBeLessThan(archive.overlay.bytes + fullLayers);
expect(transferred).toBe(archive.overlay.bytes + archive.files.find(f => f.path === coreLarge)!.archive.bytes);
}
}, 60_000);
it.skipIf(!tar || !hasZstd)("omits unused provider-assets when extracting a v1 single archive", async () => {
const { root, pack } = await multiProviderFixture();
await createProviderPackArchive(pack);
const v1 = (await readProviderPackArchive(pack, digest))!;
expect("kind" in v1).toBe(false);
const remote = await runner(root);
const claudeTarget = path.join(root, "v1-claude");
expect(await stageProviderPackArchive({ archive: v1, runner: remote, targetPath: claudeTarget, provider: { kind: "acpx", agent: "claude" } })).toBe(true);
await expect(fs.lstat(path.join(claudeTarget, "provider-assets"))).rejects.toMatchObject({ code: "ENOENT" });
const cursorTarget = path.join(root, "v1-cursor");
expect(await stageProviderPackArchive({ archive: v1, runner: remote, targetPath: cursorTarget, provider: { kind: "acpx", agent: "cursor" } })).toBe(true);
expect(await fs.readFile(path.join(cursorTarget, "provider-assets/cursor/linux-x64/manifest.txt"), "utf8")).toBe("cursor-small");
await expect(fs.lstat(path.join(cursorTarget, "provider-assets/kimi"))).rejects.toMatchObject({ code: "ENOENT" });
await expect(fs.lstat(path.join(cursorTarget, "provider-assets/pi"))).rejects.toMatchObject({ code: "ENOENT" });
}, 60_000);
it.skipIf(!tar || !hasZstd)("stages only the selected provider's assets and still reuses image twins across excluded providers", async () => {
const { root, pack, archive, coreLarge, cursorLarge, kimiLarge } = await multiProviderFixture();
// Image has kimiLarge (same bytes as coreLarge) but lacks coreLarge itself.
const image = path.join(root, "image");
await fs.cp(pack, image, { recursive: true, verbatimSymlinks: true });
await fs.rm(path.join(image, coreLarge));
await fs.rm(path.join(image, cursorLarge));
const remote = await runner(root);
const targetPath = path.join(root, "staged-cursor");
expect(await stageProviderPackArchive({
archive,
runner: remote,
targetPath,
reuseRoots: [image],
provider: { kind: "acpx", agent: "cursor" },
})).toBe(true);
// Core file reused from image's kimi twin without writing kimi into the workspace.
expect((await fs.stat(path.join(targetPath, coreLarge))).size).toBe(1024 * 1024);
expect((await fs.stat(path.join(targetPath, cursorLarge))).size).toBe(1024 * 1024);
expect(await fs.readFile(path.join(targetPath, "provider-assets/cursor/linux-x64/manifest.txt"), "utf8")).toBe("cursor-small");
await expect(fs.lstat(path.join(targetPath, "provider-assets/kimi"))).rejects.toMatchObject({ code: "ENOENT" });
await expect(fs.lstat(path.join(targetPath, "provider-assets/pi"))).rejects.toMatchObject({ code: "ENOENT" });
expect(await fs.lstat(path.join(image, kimiLarge))).toBeTruthy();
const transferred = (await remote.syncIn.mock.results[0]!.value).operations[0]!.bytesTransferred;
expect(transferred).toBe(archive.overlay.bytes + archive.files.find(f => f.path === cursorLarge)!.archive.bytes);
}, 60_000);
async function directoryBytes(dir: string): Promise<number> {
let total = 0;
for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) total += await directoryBytes(full);
else if (entry.isFile()) total += (await fs.lstat(full)).size;
}
return total;
}
it.skipIf(!tar || !hasZstd)("e2e: uploads and verifies a provider-scoped pack, cuts workspace disk footprint, and re-stages when switching providers", async () => {
const root = await fs.mkdtemp(path.join(os.tmpdir(), "provider-e2e-"));
roots.push(root);
const pack = path.join(root, "pack");
const write = async (relative: string, content: string | Buffer, mode = 0o644) => {
const full = path.join(pack, relative);
await fs.mkdir(path.dirname(full), { recursive: true });
await fs.writeFile(full, content, { mode });
};
const shaBytes = (content: string | Buffer) => `sha256:${createHash("sha256").update(content).digest("hex")}`;
const treeSha = (fileName: string, content: Buffer) =>
`sha256:${createHash("sha256").update(`file\0${fileName}\0${shaBytes(content)}\n`).digest("hex")}`;
await fs.mkdir(path.join(pack, "node_modules/node/bin"), { recursive: true });
await fs.symlink(process.execPath, path.join(pack, "node_modules/node/bin/node"));
const nodeSha = shaBytes(await fs.readFile(process.execPath));
const opencodeScript = "#!/bin/sh\necho 1.18.34\n";
await write("node_modules/.bin/opencode", opencodeScript, 0o755);
await write("pnpm-lock.yaml", "lock");
await write("node_modules/opencode-ai/bin/opencode.exe", "bin");
await write("dist/cli/opencode-app-server-proxy.cjs", "proxy");
await write("dist/cli/acpx-runtime-sidecar.cjs", "sidecar");
await write("dist/providers/grok/launcher.cjs", "grok");
for (const [pkg, version] of [
["acpx", "1.0.0"],
["@agentclientprotocol/claude-agent-acp", "1.0.0"],
["@agentclientprotocol/codex-acp", "1.0.0"],
["opencode-ai", "1.18.34"],
] as const) {
await write(`node_modules/${pkg}/package.json`, JSON.stringify({ version }));
}
const cursorPayload = Buffer.alloc(2 * 1024 * 1024, 11);
const kimiPayload = Buffer.alloc(2 * 1024 * 1024, 22);
const piPayload = Buffer.alloc(2 * 1024 * 1024, 33);
const cursorPath = `provider-assets/cursor/${process.platform}-${process.arch}`;
const kimiPath = `provider-assets/kimi/${process.platform}-${process.arch}`;
const piPath = `provider-assets/pi/${process.platform}-${process.arch}`;
await write(`${cursorPath}/agent`, cursorPayload, 0o755);
await write(`${kimiPath}/agent`, kimiPayload, 0o755);
await write(`${piPath}/agent`, piPayload, 0o755);
const distDigest = `sha256:${createHash("sha256").update([
"directory\0cli\n",
`file\0cli/acpx-runtime-sidecar.cjs\0${shaBytes("sidecar")}\n`,
`file\0cli/opencode-app-server-proxy.cjs\0${shaBytes("proxy")}\n`,
"directory\0providers\n",
"directory\0providers/grok\n",
`file\0providers/grok/launcher.cjs\0${shaBytes("grok")}\n`,
].join("")).digest("hex")}`;
const payload = {
compatibility: { opencode: 1, acpx: 1 },
contractDigest: shaBytes("contracts"),
pins: { opencode: "1.18.34", nodeMinimum: "20.0.0", acpx: "1.0.0", claudeAcp: "1.0.0", codexAcp: "1.0.0" },
target: { platform: process.platform, architecture: process.arch },
runnerSourceRevision: "a".repeat(40),
distDigest,
providers: {
cursor: { path: cursorPath, sha256: treeSha("agent", cursorPayload) },
kimi: { path: kimiPath, sha256: treeSha("agent", kimiPayload) },
pi: { path: piPath, sha256: treeSha("agent", piPayload) },
},
artifacts: {
nodeCommand: { path: "node_modules/node/bin/node", sha256: nodeSha },
productionLock: { path: "pnpm-lock.yaml", sha256: shaBytes("lock") },
opencodeCommand: { path: "node_modules/.bin/opencode", sha256: shaBytes(opencodeScript) },
opencodeExecutable: { path: "node_modules/opencode-ai/bin/opencode.exe", sha256: shaBytes("bin") },
opencodeProxy: { path: "dist/cli/opencode-app-server-proxy.cjs", sha256: shaBytes("proxy") },
acpxSidecar: { path: "dist/cli/acpx-runtime-sidecar.cjs", sha256: shaBytes("sidecar") },
grokLauncher: { path: "dist/providers/grok/launcher.cjs", sha256: shaBytes("grok") },
},
};
const manifest = {
schema: "paperclip-runner/remote-provider-pack/v1",
payload,
digest: shaBytes(canonicalProviderPackJson(payload)),
};
await write("provider-pack.json", JSON.stringify(manifest));
await createProviderPackLayers(pack);
const remote = await runner(root);
const targetPath = path.join(root, "workspace-pack");
const seal = { targetKey: "sandbox:env-e2e:lease-1" };
// 1. Unfiltered upload baseline (all 3 provider asset closures = 6 MiB).
const fullTarget = path.join(root, "workspace-full");
await uploadVerifiedProviderPack({
root: pack, sourceDigest: manifest.digest, expectedDigest: manifest.digest, manifest,
runner: remote, cwd: root, targetPath: fullTarget, reuseRoots: [],
verifyDirectory: () => {}, stageDirectory: async () => { throw Error("unexpected_dir_fallback"); },
verifyUploaded: async () => { await verifyRemoteProviderPack({ runner: remote, cwd: root, packRoot: fullTarget, manifest, seal }); },
});
const fullBytes = await directoryBytes(fullTarget);
expect(fullBytes).toBeGreaterThanOrEqual(6 * 1024 * 1024);
// 2. Claude upload omits all 6 MiB of unused provider-assets/* and verifies cleanly.
const claude = { kind: "acpx" as const, agent: "claude" };
await uploadVerifiedProviderPack({
root: pack, sourceDigest: manifest.digest, expectedDigest: manifest.digest, manifest, provider: claude,
runner: remote, cwd: root, targetPath, reuseRoots: [],
verifyDirectory: () => {}, stageDirectory: async () => { throw Error("unexpected_dir_fallback"); },
verifyUploaded: async () => { await verifyRemoteProviderPack({ runner: remote, cwd: root, packRoot: targetPath, manifest, provider: claude, seal }); },
});
const claudeBytes = await directoryBytes(targetPath);
expect(claudeBytes).toBeLessThan(256 * 1024);
expect(fullBytes - claudeBytes).toBeGreaterThanOrEqual(6 * 1024 * 1024);
// 3. Switching to Cursor on the same workspace supplements ONLY Cursor in place without removing core files.
const verifyStagedCore = async () => {
const stat = await fs.lstat(targetPath).catch(() => null);
if (!stat || stat.isSymbolicLink() || !stat.isDirectory()) return false;
try {
await verifyRemoteProviderPack({ runner: remote, cwd: root, packRoot: targetPath, manifest, provider: { kind: "opencode" }, seal });
return true;
} catch { return false; }
};
const sidecarBefore = (await fs.lstat(path.join(targetPath, "dist/cli/acpx-runtime-sidecar.cjs"))).ino;
const cursor = { kind: "acpx" as const, agent: "cursor" };
await expect(verifyRemoteProviderPack({ runner: remote, cwd: root, packRoot: targetPath, manifest, provider: cursor, seal }))
.rejects.toMatchObject({ failureCheck: "candidate_digest" });
await uploadVerifiedProviderPack({
root: pack, sourceDigest: manifest.digest, expectedDigest: manifest.digest, manifest, provider: cursor,
runner: remote, cwd: root, targetPath, reuseRoots: [],
verifyDirectory: () => {}, stageDirectory: async () => { throw Error("unexpected_dir_fallback"); },
verifyStagedCore,
verifyUploaded: async () => { await verifyRemoteProviderPack({ runner: remote, cwd: root, packRoot: targetPath, manifest, provider: cursor, seal }); },
});
const cursorBytes = await directoryBytes(targetPath);
expect(cursorBytes).toBeGreaterThanOrEqual(2 * 1024 * 1024);
expect(cursorBytes).toBeLessThan(3 * 1024 * 1024);
expect((await fs.lstat(path.join(targetPath, "dist/cli/acpx-runtime-sidecar.cjs"))).ino).toBe(sidecarBefore);
await expect(fs.lstat(path.join(targetPath, "provider-assets/kimi"))).rejects.toMatchObject({ code: "ENOENT" });
await expect(fs.lstat(path.join(targetPath, "provider-assets/pi"))).rejects.toMatchObject({ code: "ENOENT" });
// 4. Adding Kimi on the same workspace preserves Cursor's files and inodes so both providers remain usable concurrently.
const cursorAgentIno = (await fs.lstat(path.join(targetPath, `${cursorPath}/agent`))).ino;
const kimi = { kind: "acpx" as const, agent: "kimi" };
await uploadVerifiedProviderPack({
root: pack, sourceDigest: manifest.digest, expectedDigest: manifest.digest, manifest, provider: kimi,
runner: remote, cwd: root, targetPath, reuseRoots: [],
verifyDirectory: () => {}, stageDirectory: async () => { throw Error("unexpected_dir_fallback"); },
verifyStagedCore,
verifyUploaded: async () => { await verifyRemoteProviderPack({ runner: remote, cwd: root, packRoot: targetPath, manifest, provider: kimi, seal }); },
});
expect((await fs.lstat(path.join(targetPath, "dist/cli/acpx-runtime-sidecar.cjs"))).ino).toBe(sidecarBefore);
expect((await fs.lstat(path.join(targetPath, `${cursorPath}/agent`))).ino).toBe(cursorAgentIno);
await expect(verifyRemoteProviderPack({ runner: remote, cwd: root, packRoot: targetPath, manifest, provider: cursor, seal })).resolves.toEqual(manifest);
await expect(verifyRemoteProviderPack({ runner: remote, cwd: root, packRoot: targetPath, manifest, provider: kimi, seal })).resolves.toEqual(manifest);
await expect(fs.lstat(path.join(targetPath, "provider-assets/pi"))).rejects.toMatchObject({ code: "ENOENT" });
}, 60_000);
it("narrows native execution providers safely and fails open when manifest is absent for an unknown agent", () => {
expect(toPackProvider({ kind: "opencode" })).toEqual({ kind: "opencode" });
expect(toPackProvider({ kind: "acpx", agent: "cursor" })).toEqual({ kind: "acpx", agent: "cursor" });
expect(toPackProvider({ kind: "codex" })).toBeUndefined();
expect(toPackProvider({ kind: "claude_managed" })).toBeUndefined();
expect(requiredProviderAssetNames({ kind: "acpx", agent: "claude" })).toEqual([]);
expect(requiredProviderAssetNames({ kind: "acpx", agent: "cursor" })).toEqual(["cursor"]);
expect(requiredProviderAssetNames({ kind: "acpx", agent: "future-provider" })).toBeNull();
});