mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
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
This commit is contained in:
1 parent
87fadcb108
commit
8e8c1b9f4d
13 files changed
+733
-53
No files matched your search
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@paperclipai/plugin-daytona",
|
||||
"version": "0.1.10",
|
||||
"version": "0.1.11",
|
||||
"description": "Daytona sandbox provider plugin for Paperclip environments",
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/paperclipai/paperclip",
|
||||
|
||||
@@ -15,7 +15,8 @@ export const DEFAULT_DAYTONA_OPERATION_TIMEOUT_MS = 300_000;
|
||||
// 0.1.6 adds private authenticated WebSocket ingress for paperclip_runner.
|
||||
// 0.1.7 exposes host-owned warm/cold runner lifecycle controls.
|
||||
// 0.1.8 declares the default provider acquisition budget to the host.
|
||||
const PLUGIN_VERSION = "0.1.10";
|
||||
// 0.1.11 raises the default sandbox disk allocation from 10 GiB to 20 GiB.
|
||||
const PLUGIN_VERSION = "0.1.11";
|
||||
|
||||
const manifest: PaperclipPluginManifestV1 = {
|
||||
id: PLUGIN_ID,
|
||||
@@ -134,7 +135,7 @@ const manifest: PaperclipPluginManifestV1 = {
|
||||
type: "integer",
|
||||
description: "Optional disk allocation in GiB.",
|
||||
minimum: 1,
|
||||
default: 10,
|
||||
default: 20,
|
||||
},
|
||||
gpu: {
|
||||
type: "integer",
|
||||
|
||||
@@ -757,9 +757,9 @@ describe("Daytona sandbox provider plugin", () => {
|
||||
|
||||
it("bumps the plugin version so the server reconciles the stored manifest", () => {
|
||||
// The bundled-plugin boot reconcile refreshes the stored manifest for an
|
||||
// existing install only when the version changes. The acquisition budget needs
|
||||
// the bump to reach an existing install.
|
||||
expect(manifest.version).toBe("0.1.10");
|
||||
// existing install only when the version changes. The acquisition budget and
|
||||
// default disk size need the bump to reach an existing install.
|
||||
expect(manifest.version).toBe("0.1.11");
|
||||
});
|
||||
|
||||
it.each([false, true])("closes duplex routes on lease release even when bridge drain hangs: %s", async (hangDrain) => {
|
||||
@@ -7884,10 +7884,51 @@ describe("daytona manifest form defaults", () => {
|
||||
it("pre-fills sizing and image fields for the environment form", () => {
|
||||
expect(properties.cpu?.default).toBe(4);
|
||||
expect(properties.memory?.default).toBe(4);
|
||||
expect(properties.disk?.default).toBe(10);
|
||||
expect(properties.disk?.default).toBe(20);
|
||||
expect(properties.image?.default).toBe("daytonaio/sandbox:0.8.0");
|
||||
});
|
||||
|
||||
it("validates and passes the default 20 GiB disk size through image-backed sandbox creation", async () => {
|
||||
process.env.DAYTONA_API_KEY = "host-key";
|
||||
const sandbox = createMockSandbox();
|
||||
mockCreate.mockResolvedValue(sandbox);
|
||||
const defaultConfig = {
|
||||
image: properties.image?.default,
|
||||
cpu: properties.cpu?.default,
|
||||
memory: properties.memory?.default,
|
||||
disk: properties.disk?.default,
|
||||
timeoutMs: 300000,
|
||||
reuseLease: false,
|
||||
};
|
||||
|
||||
const validation = await plugin.definition.onEnvironmentValidateConfig?.({
|
||||
driverKey: "daytona",
|
||||
config: defaultConfig,
|
||||
});
|
||||
expect(validation).toMatchObject({
|
||||
ok: true,
|
||||
normalizedConfig: { image: "daytonaio/sandbox:0.8.0", cpu: 4, memory: 4, disk: 20 },
|
||||
});
|
||||
|
||||
const lease = await plugin.definition.onEnvironmentAcquireLease?.({
|
||||
driverKey: "daytona",
|
||||
companyId: "company-1",
|
||||
environmentId: "env-1",
|
||||
runId: "run-default-disk",
|
||||
agentId: "agent-1",
|
||||
executionWorkspaceId: "workspace-1",
|
||||
adapterType: "paperclip_runner",
|
||||
config: defaultConfig,
|
||||
});
|
||||
expect(mockCreate).toHaveBeenCalledTimes(1);
|
||||
const [createParams] = mockCreate.mock.calls[0] as [Record<string, unknown>];
|
||||
expect(createParams).toMatchObject({
|
||||
image: "daytonaio/sandbox:0.8.0",
|
||||
resources: { cpu: 4, memory: 4, disk: 20, gpu: undefined },
|
||||
});
|
||||
expect(lease?.metadata).toMatchObject({ disk: 20 });
|
||||
});
|
||||
|
||||
it("keeps each default within its own schema constraints", () => {
|
||||
expect(properties.memory?.enum).toContain(properties.memory?.default);
|
||||
expect(properties.cpu?.default as number).toBeGreaterThanOrEqual(
|
||||
|
||||
@@ -181,7 +181,13 @@ describe("remote Kimi installation fallback and failure admission", () => {
|
||||
const target = { ...remote, runner } as AdapterExecutionTarget;
|
||||
await expect(probeKimiExecutionTarget(apiKey, target, model)).resolves.toEqual(verified());
|
||||
expect(mocks.select).toHaveBeenCalledWith(selected.configuredRoot);
|
||||
expect(mocks.prepare).toHaveBeenCalledWith({ target, runner, configuredProviderPackRoot: selected.configuredRoot, manifest: selected.manifest });
|
||||
expect(mocks.prepare).toHaveBeenCalledWith({
|
||||
target,
|
||||
runner,
|
||||
configuredProviderPackRoot: selected.configuredRoot,
|
||||
manifest: selected.manifest,
|
||||
provider: { kind: "acpx", agent: "kimi" },
|
||||
});
|
||||
expect(mocks.command).toHaveBeenCalledOnce();
|
||||
expect(mocks.prepare.mock.invocationCallOrder[0]).toBeLessThan(mocks.command.mock.invocationCallOrder[0]!);
|
||||
expect(mocks.local).not.toHaveBeenCalled();
|
||||
|
||||
@@ -50,7 +50,8 @@ export async function probeKimiExecutionTarget(apiKey: string, target: AdapterEx
|
||||
const runner = target.transport === "ssh" ? createSshCommandManagedRuntimeRunner({ spec: target.spec, defaultCwd: target.remoteCwd }) : target.runner;
|
||||
if (!runner) throw INSTALLATION_INVALID();
|
||||
const prepared = await prepareRemoteProviderPackOnTarget({ target, runner,
|
||||
configuredProviderPackRoot: selected.configuredRoot, manifest: selected.manifest });
|
||||
configuredProviderPackRoot: selected.configuredRoot, manifest: selected.manifest,
|
||||
provider: { kind: "acpx", agent: "kimi" } });
|
||||
locations = [`'${prepared.root.replaceAll("'", "'\\''")}'`];
|
||||
} catch { throw INSTALLATION_INVALID(); }
|
||||
}
|
||||
|
||||
@@ -58,7 +58,8 @@ import { notifyCancelledWorkspacePreservation } from "../cancelled-workspace-pre
|
||||
import { notifyInstructionCollection } from "../instruction-collection-notifications.js";
|
||||
import { providerPackWorkspaceId, recordAdmittedRemoteProviderPack, resolveRemoteProviderPackAuthority } from "./remote-provider-pack-authority.js";
|
||||
import { nativeProviderPackAdmissionFailureCode, prepareNativeProviderPackAdmission, rememberAdmittedNativeProviderPack, rememberRecoveredNativeProviderPack, recordNativeProviderPackAdmission, type NativeProviderPackAdmissionSource } from "./native-provider-pack-admission.js";
|
||||
import { type AdmittedProviderPackReceipt, type ProviderPackInstallation, providerPackIncompatible, verifyRemoteProviderPack as verifyRemoteProviderPackIdentity } from "./remote-provider-pack-verification.js";
|
||||
import { type AdmittedProviderPackReceipt, type PackProvider, type ProviderPackInstallation, providerPackIncompatible, verifyRemoteProviderPack as verifyRemoteProviderPackIdentity } from "./remote-provider-pack-verification.js";
|
||||
import { toPackProvider } from "./provider-pack-compatibility.js";
|
||||
import { writeEnvironmentCleanup } from "../environment-cleanup-notifications.js";
|
||||
import { NATIVE_SESSION_EXECUTION_LEASE_TTL_MS, lockNativeExecutionLeaseForReacquire, nativeExecutionLeaseHeldCondition, releaseUnstartedNativeExecutionClaim, startNativeSessionExecutionLeaseRenewal, type NativeExecutionLeaseRenewal } from "./native-execution-lease.js";
|
||||
export { renewNativeSessionExecutionLease } from "./native-execution-lease.js";
|
||||
@@ -14983,6 +14984,7 @@ export async function prepareRemoteProviderPackOnTarget(input: {
|
||||
runner: CommandManagedRuntimeRunner;
|
||||
configuredProviderPackRoot: string | null;
|
||||
manifest: RemoteProviderPackManifest;
|
||||
provider?: PackProvider;
|
||||
signal?: AbortSignal;
|
||||
trace?: NativeRunTrace;
|
||||
onLog?: (stream: "stdout" | "stderr", chunk: string) => void | Promise<void>;
|
||||
@@ -14998,7 +15000,8 @@ export async function prepareRemoteProviderPackOnTarget(input: {
|
||||
const seal = remoteProviderPackSeal(remoteTarget);
|
||||
const verifyRemoteProviderPack = (packRoot: string, acceptProvenance = false) =>
|
||||
verifyRemoteProviderPackIdentity({ runner: remoteCommandRunner, cwd: remoteTarget.remoteCwd, packRoot,
|
||||
manifest: expectedProviderPackManifest, acceptProvenance: acceptProvenance && input.acceptProvenanceDifferences === true,
|
||||
manifest: expectedProviderPackManifest, ...(input.provider ? { provider: input.provider } : {}),
|
||||
acceptProvenance: acceptProvenance && input.acceptProvenanceDifferences === true,
|
||||
...(seal ? { seal } : {}) });
|
||||
const discoverPreinstalledProviderPack = async () => {
|
||||
if (!remoteTarget || !remoteCommandRunner) return [];
|
||||
@@ -15078,6 +15081,7 @@ export async function prepareRemoteProviderPackOnTarget(input: {
|
||||
sourceDigest: readRemoteProviderPackIdentity(configuredProviderPackRoot, false).digest,
|
||||
expectedDigest: expectedProviderPackManifest.digest,
|
||||
manifest: expectedProviderPackManifest,
|
||||
...(input.provider ? { provider: input.provider } : {}),
|
||||
signal: input.signal,
|
||||
runner: remoteCommandRunner,
|
||||
cwd: remoteTarget.remoteCwd,
|
||||
@@ -15092,6 +15096,30 @@ export async function prepareRemoteProviderPackOnTarget(input: {
|
||||
targetPath: stagedRemoteProviderPackRoot,
|
||||
mode: 0o700,
|
||||
}),
|
||||
verifyStagedCore: async () => {
|
||||
const escapedTarget = stagedRemoteProviderPackRoot.replaceAll("'", "'\\''");
|
||||
const writable = await remoteCommandRunner.execute({
|
||||
command: "sh",
|
||||
args: ["-c", `test ! -L '${escapedTarget}' && test -d '${escapedTarget}'`],
|
||||
cwd: remoteTarget.remoteCwd,
|
||||
bypassSession: true,
|
||||
timeoutMs: 10_000,
|
||||
});
|
||||
if (writable.exitCode !== 0 || writable.timedOut) return false;
|
||||
try {
|
||||
await verifyRemoteProviderPackIdentity({
|
||||
runner: remoteCommandRunner,
|
||||
cwd: remoteTarget.remoteCwd,
|
||||
packRoot: stagedRemoteProviderPackRoot,
|
||||
manifest: expectedProviderPackManifest,
|
||||
provider: { kind: "opencode" },
|
||||
...(seal ? { seal } : {}),
|
||||
});
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
verifyUploaded: async () => { await verifyRemoteProviderPack(stagedRemoteProviderPackRoot); },
|
||||
});
|
||||
activeRemoteProviderPackRoot = stagedRemoteProviderPackRoot;
|
||||
@@ -17495,13 +17523,15 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
})
|
||||
: Promise.resolve();
|
||||
|
||||
const packProvider = toPackProvider(input.execution.provider);
|
||||
const verifyRemoteProviderPack = async (packRoot: string) => {
|
||||
if (providerPackVerified && packRoot === activeRemoteProviderPackRoot) return;
|
||||
if (!remoteTarget || !remoteCommandRunner || !expectedProviderPackManifest)
|
||||
return;
|
||||
const seal = remoteProviderPackSeal(remoteTarget);
|
||||
await verifyRemoteProviderPackIdentity({ runner: remoteCommandRunner,
|
||||
cwd: remoteTarget.remoteCwd, packRoot, manifest: expectedProviderPackManifest, ...(seal ? { seal } : {}) });
|
||||
cwd: remoteTarget.remoteCwd, packRoot, manifest: expectedProviderPackManifest,
|
||||
...(packProvider ? { provider: packProvider } : {}), ...(seal ? { seal } : {}) });
|
||||
providerPackVerified = true;
|
||||
};
|
||||
|
||||
@@ -17678,7 +17708,8 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
const sourceSignals = [startupSignal, contextSignal].filter((signal): signal is AbortSignal => !!signal);
|
||||
const prepared = await prepareRemoteProviderPackOnTarget({
|
||||
target: remoteTarget, runner: remoteCommandRunner, configuredProviderPackRoot,
|
||||
manifest: expectedProviderPackManifest, trace: input.trace, onLog: input.onLog,
|
||||
manifest: expectedProviderPackManifest, ...(packProvider ? { provider: packProvider } : {}),
|
||||
trace: input.trace, onLog: input.onLog,
|
||||
signal: sourceSignals.length ? AbortSignal.any(sourceSignals) : undefined,
|
||||
acceptProvenanceDifferences: providerPackProvenanceReuseAllowed({ retainProviderPack, explicitProviderPackSelection,
|
||||
authoritySelectable: providerPackAuthority !== null }),
|
||||
|
||||
@@ -9,6 +9,8 @@ import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/com
|
||||
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";
|
||||
|
||||
@@ -57,7 +59,16 @@ async function runner(root: string, corrupt = false, toolPath?: string) {
|
||||
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) {
|
||||
return { exitCode: 1, signal: null, pid: null, startedAt: null, timedOut: false, stdout: "", stderr: String(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 };
|
||||
@@ -524,3 +535,261 @@ it.skipIf(!tar || !hasZstd).each([
|
||||
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();
|
||||
});
|
||||
@@ -2,6 +2,12 @@ import { randomUUID } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
|
||||
import type { NativeRunTrace } from "./native-run-trace.js";
|
||||
import {
|
||||
providerAssetExcludeArgs,
|
||||
requiredProviderAssetNames,
|
||||
type PackProvider,
|
||||
type ProviderPackIdentity,
|
||||
} from "./provider-pack-compatibility.js";
|
||||
import { invalidArchive, readProviderPackLayers, stageProviderPackLayers, verifyArchive } from "./provider-pack-layers.js";
|
||||
import { providerPackExtractionProbe } from "./provider-pack-extraction.js";
|
||||
|
||||
@@ -38,11 +44,22 @@ export async function stageProviderPackArchive(input: {
|
||||
targetPath: string;
|
||||
trace?: NativeRunTrace;
|
||||
reuseRoots?: readonly string[];
|
||||
provider?: PackProvider;
|
||||
manifest?: Pick<ProviderPackIdentity, "payload">;
|
||||
supplementAssetsOnly?: boolean;
|
||||
}): Promise<boolean> {
|
||||
if ("kind" in input.archive) return stageProviderPackLayers({ ...input, archive: input.archive, reuseRoots: input.reuseRoots ?? [] });
|
||||
const archive = input.archive;
|
||||
if (!input.runner.syncIn) throw new Error("runner_remote_provider_archive_transport_unavailable");
|
||||
const supplement = input.supplementAssetsOnly === true;
|
||||
const required = requiredProviderAssetNames(input.provider, input.manifest);
|
||||
if (supplement && (!required || required.length === 0)) return false;
|
||||
const archivePath = `${input.targetPath}.upload-${randomUUID()}.tar.zst`;
|
||||
const stageDir = supplement ? `${input.targetPath}.assets-${randomUUID()}` : input.targetPath;
|
||||
const excludeFlags = providerAssetExcludeArgs({
|
||||
provider: input.provider,
|
||||
manifest: input.manifest,
|
||||
}).map(quote).join(" ");
|
||||
const measure = <T>(name: string, fn: () => Promise<T>) => input.trace ? input.trace.measure(name, fn) : fn();
|
||||
const capability = await measure("provider_pack.archive.probe", () => input.runner.execute({
|
||||
command: "sh", args: ["-c", providerPackExtractionProbe],
|
||||
@@ -54,15 +71,28 @@ export async function stageProviderPackArchive(input: {
|
||||
operationId: `runner-provider-archive-${randomUUID()}`,
|
||||
files: [{ kind: "file", sourcePath: archive.sourcePath, targetPath: archivePath, mode: 0o600 }],
|
||||
}]));
|
||||
const installCommands = supplement
|
||||
? [
|
||||
`test ! -L ${quote(input.targetPath)}; test -d ${quote(input.targetPath)};`,
|
||||
`mkdir -p ${quote(`${input.targetPath}/provider-assets`)};`,
|
||||
`test ! -L ${quote(`${input.targetPath}/provider-assets`)};`,
|
||||
...required!.map(name => [
|
||||
`test -d ${quote(`${stageDir}/provider-assets/${name}`)};`,
|
||||
`test ! -L ${quote(`${stageDir}/provider-assets/${name}`)};`,
|
||||
`rm -rf -- ${quote(`${input.targetPath}/provider-assets/${name}`)};`,
|
||||
`mv -- ${quote(`${stageDir}/provider-assets/${name}`)} ${quote(`${input.targetPath}/provider-assets/${name}`)};`,
|
||||
].join(" ")),
|
||||
]
|
||||
: [`chmod 700 ${quote(input.targetPath)};`];
|
||||
const result = await measure("provider_pack.archive.extract", () => input.runner.execute({
|
||||
command: "sh",
|
||||
args: ["-c", [
|
||||
"set -eu; umask 077;",
|
||||
`test ! -L ${quote(archivePath)}; test -f ${quote(archivePath)};`,
|
||||
`test "$(sha256sum -- ${quote(archivePath)} | cut -d ' ' -f 1)" = ${quote(archive.sha256)};`,
|
||||
`test ! -L ${quote(input.targetPath)}; mkdir -p ${quote(input.targetPath)};`,
|
||||
`tar --zstd -xf ${quote(archivePath)} --no-same-owner --same-permissions --delay-directory-restore -C ${quote(input.targetPath)};`,
|
||||
`chmod 700 ${quote(input.targetPath)};`,
|
||||
`test ! -L ${quote(stageDir)}; mkdir -p ${quote(stageDir)};`,
|
||||
`tar --zstd${excludeFlags ? ` ${excludeFlags}` : ""} -xf ${quote(archivePath)} --no-same-owner --same-permissions --delay-directory-restore -C ${quote(stageDir)};`,
|
||||
...installCommands,
|
||||
].join(" ")],
|
||||
bypassSession: true,
|
||||
timeoutMs: 120_000,
|
||||
@@ -70,7 +100,8 @@ export async function stageProviderPackArchive(input: {
|
||||
if (result.exitCode !== 0 || result.timedOut) throw new Error("runner_remote_provider_archive_extract_failed");
|
||||
return true;
|
||||
} finally {
|
||||
await input.runner.execute({ command: "sh", args: ["-c", `rm -f -- ${quote(archivePath)}`],
|
||||
const cleanup = supplement ? `rm -rf -- ${quote(archivePath)} ${quote(stageDir)}` : `rm -f -- ${quote(archivePath)}`;
|
||||
await input.runner.execute({ command: "sh", args: ["-c", cleanup],
|
||||
bypassSession: true, timeoutMs: 10_000 }).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,83 @@ export type AdmittedProviderPackReceipt = {
|
||||
sourceRevision: string;
|
||||
};
|
||||
|
||||
const KNOWN_NATIVE_ASSET_PROVIDERS = ["cursor", "copilot", "pi", "kimi", "antigravity"] as const;
|
||||
const BUILTIN_NON_ASSET_ACPX_PROVIDERS = ["claude", "codex", "grok"] as const;
|
||||
const SAFE_PROVIDER_ASSET_NAME = /^[a-z0-9-]+$/;
|
||||
|
||||
/** Narrows a native execution provider to a PackProvider when applicable. */
|
||||
export function toPackProvider(
|
||||
provider: { kind: string; agent?: string } | undefined,
|
||||
): PackProvider | undefined {
|
||||
if (!provider) return undefined;
|
||||
if (provider.kind === "opencode") return { kind: "opencode" };
|
||||
if (provider.kind === "acpx" && typeof provider.agent === "string" && provider.agent.length > 0) {
|
||||
return { kind: "acpx", agent: provider.agent };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the provider-asset subdirectory names needed for `provider`, or `null`
|
||||
* when no safe filter applies (stage/verify every declared asset tree).
|
||||
*/
|
||||
export function requiredProviderAssetNames(
|
||||
provider?: PackProvider,
|
||||
manifest?: Pick<ProviderPackIdentity, "payload">,
|
||||
): string[] | null {
|
||||
if (!provider) return null;
|
||||
if (provider.kind === "opencode") return [];
|
||||
const agent = provider.agent;
|
||||
if (!SAFE_PROVIDER_ASSET_NAME.test(agent)) return null;
|
||||
if (manifest) {
|
||||
const declared = Object.hasOwn(manifest.payload.providers ?? {}, agent)
|
||||
|| Object.hasOwn(manifest.payload.candidateProviders ?? {}, agent);
|
||||
return declared ? [agent] : [];
|
||||
}
|
||||
if ((KNOWN_NATIVE_ASSET_PROVIDERS as readonly string[]).includes(agent)) return [agent];
|
||||
if ((BUILTIN_NON_ASSET_ACPX_PROVIDERS as readonly string[]).includes(agent)) return [];
|
||||
return null;
|
||||
}
|
||||
|
||||
/** True when a pack-relative path belongs to the staged subset for `required`. */
|
||||
export function isProviderAssetPathIncluded(
|
||||
relativePath: string,
|
||||
required: readonly string[] | null,
|
||||
options?: { assetsOnly?: boolean },
|
||||
): boolean {
|
||||
const isAssetTree = relativePath === "provider-assets" || relativePath.startsWith("provider-assets/");
|
||||
if (options?.assetsOnly && !isAssetTree) return false;
|
||||
if (required === null) return true;
|
||||
if (relativePath === "provider-assets") return required.length > 0;
|
||||
if (!relativePath.startsWith("provider-assets/")) return true;
|
||||
if (required.length === 0) return false;
|
||||
const segment = relativePath.slice("provider-assets/".length).split("/")[0] ?? "";
|
||||
return required.includes(segment);
|
||||
}
|
||||
|
||||
/** GNU tar `--exclude` arguments that omit unused `provider-assets/*` trees. */
|
||||
export function providerAssetExcludeArgs(input: {
|
||||
provider?: PackProvider;
|
||||
manifest?: Pick<ProviderPackIdentity, "payload">;
|
||||
filePaths?: readonly string[];
|
||||
}): string[] {
|
||||
const required = requiredProviderAssetNames(input.provider, input.manifest);
|
||||
if (required === null) return [];
|
||||
if (required.length === 0) return ["--exclude=./provider-assets", "--exclude=provider-assets"];
|
||||
const known = new Set<string>(KNOWN_NATIVE_ASSET_PROVIDERS);
|
||||
for (const key of Object.keys(input.manifest?.payload.providers ?? {})) known.add(key);
|
||||
for (const key of Object.keys(input.manifest?.payload.candidateProviders ?? {})) known.add(key);
|
||||
for (const relativePath of input.filePaths ?? []) {
|
||||
if (!relativePath.startsWith("provider-assets/")) continue;
|
||||
const segment = relativePath.slice("provider-assets/".length).split("/")[0] ?? "";
|
||||
if (segment) known.add(segment);
|
||||
}
|
||||
return [...known]
|
||||
.filter(name => SAFE_PROVIDER_ASSET_NAME.test(name) && !required.includes(name))
|
||||
.sort()
|
||||
.flatMap(name => [`--exclude=./provider-assets/${name}`, `--exclude=provider-assets/${name}`]);
|
||||
}
|
||||
|
||||
export function compatibleProviderPackInstallation<T extends ProviderPackIdentity>(
|
||||
installation: ProviderPackInstallation, expected: T, packRoot: string,
|
||||
provider: PackProvider, requireExactIdentity: boolean, requireCurrentOpenCodeProxy: boolean,
|
||||
|
||||
@@ -6,6 +6,13 @@ import { join, posix } from "node:path";
|
||||
import { pipeline } from "node:stream/promises";
|
||||
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
|
||||
import type { NativeRunTrace } from "./native-run-trace.js";
|
||||
import {
|
||||
isProviderAssetPathIncluded,
|
||||
providerAssetExcludeArgs,
|
||||
requiredProviderAssetNames,
|
||||
type PackProvider,
|
||||
type ProviderPackIdentity,
|
||||
} from "./provider-pack-compatibility.js";
|
||||
import { providerPackExtractionProbe } from "./provider-pack-extraction.js";
|
||||
|
||||
type Archive = { sha256: string; bytes: number };
|
||||
@@ -138,22 +145,58 @@ export type ProviderPackReuseStep = {
|
||||
|
||||
/** Store repeated bytes once: the first private copy of each digest and mode is
|
||||
* shared by hardlinks, and a path the image lacks may come from a same-bytes twin. */
|
||||
export function providerPackReusePlan(files: readonly Pick<FileLayer, "path" | "sha256" | "mode">[]): ProviderPackReuseStep[] {
|
||||
export function providerPackReusePlan(
|
||||
files: readonly Pick<FileLayer, "path" | "sha256" | "mode">[],
|
||||
sourceFiles: readonly Pick<FileLayer, "path" | "sha256">[] = files,
|
||||
): ProviderPackReuseStep[] {
|
||||
const pathsBySha = new Map<string, string[]>();
|
||||
for (const file of files) pathsBySha.set(file.sha256, [...(pathsBySha.get(file.sha256) ?? []), file.path]);
|
||||
for (const file of sourceFiles) pathsBySha.set(file.sha256, [...(pathsBySha.get(file.sha256) ?? []), file.path]);
|
||||
const groups = new Map<string, number>();
|
||||
return files.map(file => {
|
||||
const key = `${file.sha256}:${file.mode}`;
|
||||
if (!groups.has(key)) groups.set(key, groups.size);
|
||||
return { sources: [file.path, ...pathsBySha.get(file.sha256)!.filter(path => path !== file.path)], group: groups.get(key)! };
|
||||
const twins = (pathsBySha.get(file.sha256) ?? []).filter(path => path !== file.path);
|
||||
return { sources: [file.path, ...twins], group: groups.get(key)! };
|
||||
});
|
||||
}
|
||||
|
||||
export function providerPackLayersArgument(archive: ProviderPackLayers, targetPath: string, reuseRoots: readonly string[]) {
|
||||
const plan = providerPackReusePlan(archive.files);
|
||||
const files = archive.files.map((file, index) => ({ ...file, ...plan[index] }));
|
||||
type SelectedFileLayer = { file: FileLayer; index: number };
|
||||
|
||||
function selectProviderPackFiles(
|
||||
files: readonly FileLayer[],
|
||||
required: readonly string[] | null,
|
||||
options?: { assetsOnly?: boolean },
|
||||
): SelectedFileLayer[] {
|
||||
return files
|
||||
.map((file, index) => ({ file, index }))
|
||||
.filter(({ file }) => isProviderAssetPathIncluded(file.path, required, options));
|
||||
}
|
||||
|
||||
function buildProviderPackLayersSpec(
|
||||
archive: ProviderPackLayers,
|
||||
targetPath: string,
|
||||
reuseRoots: readonly string[],
|
||||
provider?: PackProvider,
|
||||
manifest?: Pick<ProviderPackIdentity, "payload">,
|
||||
options?: { assetsOnly?: boolean },
|
||||
): { spec: string | null; selectedEntries: SelectedFileLayer[]; required: string[] | null } {
|
||||
const required = requiredProviderAssetNames(provider, manifest);
|
||||
const selectedEntries = selectProviderPackFiles(archive.files, required, options);
|
||||
const selectedFiles = selectedEntries.map(entry => entry.file);
|
||||
const plan = providerPackReusePlan(selectedFiles, archive.files);
|
||||
const files = selectedFiles.map((file, index) => ({ ...file, ...plan[index] }));
|
||||
const spec = Buffer.from(JSON.stringify({ target: targetPath, roots: reuseRoots, files })).toString("base64");
|
||||
return Buffer.byteLength(spec) > 120_000 ? null : spec;
|
||||
return { spec: Buffer.byteLength(spec) > 120_000 ? null : spec, selectedEntries, required };
|
||||
}
|
||||
|
||||
export function providerPackLayersArgument(
|
||||
archive: ProviderPackLayers,
|
||||
targetPath: string,
|
||||
reuseRoots: readonly string[],
|
||||
provider?: PackProvider,
|
||||
manifest?: Pick<ProviderPackIdentity, "payload">,
|
||||
) {
|
||||
return buildProviderPackLayersSpec(archive, targetPath, reuseRoots, provider, manifest).spec;
|
||||
}
|
||||
|
||||
export async function stageProviderPackLayers(input: {
|
||||
@@ -162,11 +205,25 @@ export async function stageProviderPackLayers(input: {
|
||||
targetPath: string;
|
||||
reuseRoots: readonly string[];
|
||||
trace?: NativeRunTrace;
|
||||
provider?: PackProvider;
|
||||
manifest?: Pick<ProviderPackIdentity, "payload">;
|
||||
/** When true, add only the required `provider-assets/<name>` subtrees into an existing verified pack. */
|
||||
supplementAssetsOnly?: boolean;
|
||||
}): Promise<boolean> {
|
||||
const { archive, runner } = input;
|
||||
if (!runner.syncIn) throw Error("runner_remote_provider_archive_transport_unavailable");
|
||||
const measure = <T>(name: string, fn: () => Promise<T>) => input.trace ? input.trace.measure(name, fn) : fn();
|
||||
const spec = providerPackLayersArgument(archive, input.targetPath, input.reuseRoots);
|
||||
const supplement = input.supplementAssetsOnly === true;
|
||||
const stageDir = supplement ? `${input.targetPath}.assets-${randomUUID()}` : input.targetPath;
|
||||
const { spec, selectedEntries, required } = buildProviderPackLayersSpec(
|
||||
archive,
|
||||
stageDir,
|
||||
input.reuseRoots,
|
||||
input.provider,
|
||||
input.manifest,
|
||||
supplement ? { assetsOnly: true } : undefined,
|
||||
);
|
||||
if (supplement && (!required || required.length === 0)) return false;
|
||||
// Respect the per-argument Linux limit; unusual packs retain directory staging.
|
||||
if (spec === null) return false;
|
||||
const capability = await measure("provider_pack.archive.probe", () => runner.execute({
|
||||
@@ -174,25 +231,33 @@ export async function stageProviderPackLayers(input: {
|
||||
bypassSession: true, timeoutMs: 10_000,
|
||||
}));
|
||||
if (capability.exitCode !== 0 || capability.timedOut) return false;
|
||||
const reused = await measure("provider_pack.archive.reuse", () => runner.execute({
|
||||
command: "node", args: ["-e", reuseScript, spec], bypassSession: true, timeoutMs: 60_000,
|
||||
}));
|
||||
if (reused.exitCode !== 0 || reused.timedOut) throw Error("runner_remote_provider_archive_reuse_failed");
|
||||
let missing: number[];
|
||||
try { missing = JSON.parse(reused.stdout); } catch { throw Error("runner_remote_provider_archive_reuse_failed"); }
|
||||
if (!Array.isArray(missing) || new Set(missing).size !== missing.length
|
||||
|| missing.some(index => !Number.isSafeInteger(index) || index < 0 || index >= archive.files.length)) {
|
||||
throw Error("runner_remote_provider_archive_reuse_failed");
|
||||
}
|
||||
const layers = [
|
||||
...missing.map(index => ({ name: `${index}.tar.zst`, ...archive.files[index]!.archive })),
|
||||
{ name: "overlay.tar.zst", ...archive.overlay },
|
||||
];
|
||||
const scratch = `${input.targetPath}.upload-${randomUUID()}`;
|
||||
const temporary = await mkdtemp(join(tmpdir(), "paperclip-provider-layers-"));
|
||||
const bundlePath = join(temporary, "selected.tar.zst");
|
||||
const scratch = `${input.targetPath}.upload-${randomUUID()}`;
|
||||
const remoteArchive = `${scratch}/selected.tar.zst`;
|
||||
try {
|
||||
const reused = await measure("provider_pack.archive.reuse", () => runner.execute({
|
||||
command: "node", args: ["-e", reuseScript, spec], bypassSession: true, timeoutMs: 60_000,
|
||||
}));
|
||||
if (reused.exitCode !== 0 || reused.timedOut) throw Error("runner_remote_provider_archive_reuse_failed");
|
||||
let missing: number[];
|
||||
try { missing = JSON.parse(reused.stdout); } catch { throw Error("runner_remote_provider_archive_reuse_failed"); }
|
||||
if (!Array.isArray(missing) || new Set(missing).size !== missing.length
|
||||
|| missing.some(index => !Number.isSafeInteger(index) || index < 0 || index >= selectedEntries.length)) {
|
||||
throw Error("runner_remote_provider_archive_reuse_failed");
|
||||
}
|
||||
const layers = [
|
||||
...missing.map(selectedIndex => {
|
||||
const entry = selectedEntries[selectedIndex]!;
|
||||
return { name: `${entry.index}.tar.zst`, ...entry.file.archive };
|
||||
}),
|
||||
{ name: "overlay.tar.zst", ...archive.overlay },
|
||||
];
|
||||
const excludeFlags = providerAssetExcludeArgs({
|
||||
provider: input.provider,
|
||||
manifest: input.manifest,
|
||||
filePaths: archive.files.map(file => file.path),
|
||||
}).map(quote).join(" ");
|
||||
// Concatenate independent zstd frames without recompression. One upload
|
||||
// avoids a provider round trip for every small missing layer.
|
||||
const hash = createHash("sha256");
|
||||
@@ -215,19 +280,33 @@ export async function stageProviderPackLayers(input: {
|
||||
operationId: `runner-provider-layers-${randomUUID()}`,
|
||||
files: [{ kind: "file", sourcePath: bundlePath, targetPath: remoteArchive, mode: 0o600 }],
|
||||
}]));
|
||||
const installCommands = supplement
|
||||
? [
|
||||
`test ! -L ${quote(input.targetPath)}; test -d ${quote(input.targetPath)};`,
|
||||
`mkdir -p ${quote(`${input.targetPath}/provider-assets`)};`,
|
||||
`test ! -L ${quote(`${input.targetPath}/provider-assets`)};`,
|
||||
...required!.map(name => [
|
||||
`test -d ${quote(`${stageDir}/provider-assets/${name}`)};`,
|
||||
`test ! -L ${quote(`${stageDir}/provider-assets/${name}`)};`,
|
||||
`rm -rf -- ${quote(`${input.targetPath}/provider-assets/${name}`)};`,
|
||||
`mv -- ${quote(`${stageDir}/provider-assets/${name}`)} ${quote(`${input.targetPath}/provider-assets/${name}`)};`,
|
||||
].join(" ")),
|
||||
]
|
||||
: [`chmod 700 ${quote(input.targetPath)};`];
|
||||
const result = await measure("provider_pack.archive.extract", () => runner.execute({
|
||||
command: "sh", args: ["-c", ["set -eu; umask 077;",
|
||||
`test ! -L ${quote(input.targetPath)}; test -d ${quote(input.targetPath)};`,
|
||||
`test ! -L ${quote(stageDir)}; test -d ${quote(stageDir)};`,
|
||||
`test ! -L ${quote(remoteArchive)}; test "$(sha256sum -- ${quote(remoteArchive)} | cut -d ' ' -f 1)" = ${quote(sha256)};`,
|
||||
`tar --zstd --ignore-zeros -xf ${quote(remoteArchive)} --no-same-owner --same-permissions --delay-directory-restore -C ${quote(input.targetPath)};`,
|
||||
`chmod 700 ${quote(input.targetPath)};`,
|
||||
`tar --zstd --ignore-zeros${excludeFlags ? ` ${excludeFlags}` : ""} -xf ${quote(remoteArchive)} --no-same-owner --same-permissions --delay-directory-restore -C ${quote(stageDir)};`,
|
||||
...installCommands,
|
||||
].join(" ")], bypassSession: true, timeoutMs: 120_000,
|
||||
}));
|
||||
if (result.exitCode !== 0 || result.timedOut) throw Error("runner_remote_provider_archive_extract_failed");
|
||||
return true;
|
||||
} finally {
|
||||
await rm(temporary, { recursive: true, force: true });
|
||||
await runner.execute({ command: "sh", args: ["-c", `rm -rf -- ${quote(scratch)}`],
|
||||
const cleanupPaths = supplement ? `${quote(scratch)} ${quote(stageDir)}` : quote(scratch);
|
||||
await runner.execute({ command: "sh", args: ["-c", `rm -rf -- ${cleanupPaths}`],
|
||||
bypassSession: true, timeoutMs: 10_000 }).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
|
||||
import type { NativeRunTrace } from "./native-run-trace.js";
|
||||
import { readProviderPackArchive, stageProviderPackArchive } from "./provider-pack-archive.js";
|
||||
import type { ProviderPackIdentity } from "./remote-provider-pack-verification.js";
|
||||
import { requiredProviderAssetNames } from "./provider-pack-compatibility.js";
|
||||
import type { PackProvider, ProviderPackIdentity } from "./remote-provider-pack-verification.js";
|
||||
import { resolveProviderPackUploadSource } from "./retained-provider-pack-source.js";
|
||||
import { providerPackExtractionProbe } from "./provider-pack-extraction.js";
|
||||
import { providerPackLayersArgument } from "./provider-pack-layers.js";
|
||||
@@ -16,6 +17,7 @@ export async function uploadVerifiedProviderPack(input: {
|
||||
/** Identity selected for this execution; a retained session can pin an older release. */
|
||||
expectedDigest: string;
|
||||
manifest?: ProviderPackIdentity;
|
||||
provider?: PackProvider;
|
||||
signal?: AbortSignal;
|
||||
runner: CommandManagedRuntimeRunner;
|
||||
cwd: string;
|
||||
@@ -24,6 +26,8 @@ export async function uploadVerifiedProviderPack(input: {
|
||||
trace?: NativeRunTrace;
|
||||
verifyDirectory: (root: string) => void | Promise<void>;
|
||||
stageDirectory: (root: string) => Promise<void>;
|
||||
/** True when `targetPath` already holds a verified core pack for `expectedDigest` and can be supplemented in place. */
|
||||
verifyStagedCore?: () => Promise<boolean>;
|
||||
verifyUploaded: () => Promise<void>;
|
||||
}): Promise<void> {
|
||||
if (input.sourceDigest !== input.expectedDigest && !input.manifest) {
|
||||
@@ -44,7 +48,7 @@ export async function uploadVerifiedProviderPack(input: {
|
||||
readProviderPackArchive(source.root, input.expectedDigest, input.signal));
|
||||
if (source.archiveOnly) {
|
||||
if (!archive) throw Error("runner_remote_provider_source_invalid");
|
||||
if ("kind" in archive && providerPackLayersArgument(archive, input.targetPath, input.reuseRoots) === null) {
|
||||
if ("kind" in archive && providerPackLayersArgument(archive, input.targetPath, input.reuseRoots, input.provider, input.manifest) === null) {
|
||||
throw Error("runner_remote_provider_archive_transport_unavailable");
|
||||
}
|
||||
const capability = await measure("provider_pack.archive.probe", () => input.runner.execute({
|
||||
@@ -53,6 +57,26 @@ export async function uploadVerifiedProviderPack(input: {
|
||||
}));
|
||||
if (capability.exitCode !== 0 || capability.timedOut) throw Error("runner_remote_provider_archive_transport_unavailable");
|
||||
}
|
||||
const requiredAssets = requiredProviderAssetNames(input.provider, input.manifest);
|
||||
if (archive && requiredAssets && requiredAssets.length > 0 && input.verifyStagedCore) {
|
||||
input.signal?.throwIfAborted();
|
||||
if (await input.verifyStagedCore()) {
|
||||
const supplemented = await measure("provider_pack.upload", () => stageProviderPackArchive({
|
||||
archive,
|
||||
runner: input.runner,
|
||||
targetPath: input.targetPath,
|
||||
reuseRoots: input.reuseRoots,
|
||||
trace: input.trace,
|
||||
provider: input.provider,
|
||||
manifest: input.manifest,
|
||||
supplementAssetsOnly: true,
|
||||
}));
|
||||
if (supplemented) {
|
||||
await measure("provider_pack.verify_uploaded", input.verifyUploaded);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!archive) await verifyDirectory();
|
||||
input.signal?.throwIfAborted();
|
||||
const cleared = await measure("provider_pack.clear_stale", () => input.runner.execute({
|
||||
@@ -66,9 +90,11 @@ export async function uploadVerifiedProviderPack(input: {
|
||||
if (archive && await stageProviderPackArchive({
|
||||
archive, runner: input.runner, targetPath: input.targetPath,
|
||||
reuseRoots: input.reuseRoots, trace: input.trace,
|
||||
provider: input.provider, manifest: input.manifest,
|
||||
})) return;
|
||||
if (source.archiveOnly) throw Error("runner_remote_provider_archive_transport_unavailable");
|
||||
if (archive) await verifyDirectory();
|
||||
// Directory fallback streams via syncIn without buffering the full pack in memory.
|
||||
await input.stageDirectory(source.root);
|
||||
});
|
||||
await measure("provider_pack.verify_uploaded", input.verifyUploaded);
|
||||
|
||||
@@ -365,4 +365,111 @@ describe("installed provider pack compatibility", () => {
|
||||
expect(execute).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("verifies only the selected provider's asset tree and isolates seals per provider", async () => {
|
||||
clearSealedProviderPacksForTest();
|
||||
const root = await mkdtemp(join(tmpdir(), "pack-provider-scoped-verify-"));
|
||||
try {
|
||||
const write = async (relative: string, content: string, mode?: number) => {
|
||||
const full = join(root, relative);
|
||||
await mkdir(dirname(full), { recursive: true });
|
||||
await writeFile(full, content, mode ? { mode } : undefined);
|
||||
};
|
||||
const shaFile = (content: string) => sha(content);
|
||||
const treeSha = (fileName: string, content: string) =>
|
||||
`sha256:${createHash("sha256").update(`file\0${fileName}\0${shaFile(content)}\n`).digest("hex")}`;
|
||||
await mkdir(join(root, "node_modules/node/bin"), { recursive: true });
|
||||
await symlink(process.execPath, join(root, "node_modules/node/bin/node"));
|
||||
const nodeBytes = readFileSync(process.execPath);
|
||||
const nodeSha = `sha256:${createHash("sha256").update(nodeBytes).digest("hex")}`;
|
||||
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 distDigest = `sha256:${createHash("sha256").update([
|
||||
"directory\0cli\n",
|
||||
`file\0cli/acpx-runtime-sidecar.cjs\0${shaFile("sidecar")}\n`,
|
||||
`file\0cli/opencode-app-server-proxy.cjs\0${shaFile("proxy")}\n`,
|
||||
"directory\0providers\n",
|
||||
"directory\0providers/grok\n",
|
||||
`file\0providers/grok/launcher.cjs\0${shaFile("grok")}\n`,
|
||||
].join("")).digest("hex")}`;
|
||||
const cursorPath = `provider-assets/cursor/${process.platform}-${process.arch}`;
|
||||
const kimiPath = `provider-assets/kimi/${process.platform}-${process.arch}`;
|
||||
const payload = {
|
||||
compatibility: { opencode: 1, acpx: 1 },
|
||||
contractDigest: sha("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", "cursor-v1") },
|
||||
kimi: { path: kimiPath, sha256: treeSha("agent", "kimi-v1") },
|
||||
},
|
||||
artifacts: {
|
||||
nodeCommand: { path: "node_modules/node/bin/node", sha256: nodeSha },
|
||||
productionLock: { path: "pnpm-lock.yaml", sha256: shaFile("lock") },
|
||||
opencodeCommand: { path: "node_modules/.bin/opencode", sha256: shaFile(opencodeScript) },
|
||||
opencodeExecutable: { path: "node_modules/opencode-ai/bin/opencode.exe", sha256: shaFile("bin") },
|
||||
opencodeProxy: { path: "dist/cli/opencode-app-server-proxy.cjs", sha256: shaFile("proxy") },
|
||||
acpxSidecar: { path: "dist/cli/acpx-runtime-sidecar.cjs", sha256: shaFile("sidecar") },
|
||||
grokLauncher: { path: "dist/providers/grok/launcher.cjs", sha256: shaFile("grok") },
|
||||
},
|
||||
};
|
||||
const expected = {
|
||||
schema: "paperclip-runner/remote-provider-pack/v1",
|
||||
payload,
|
||||
digest: sha(canonicalProviderPackJson(payload)),
|
||||
};
|
||||
await write("provider-pack.json", JSON.stringify(expected));
|
||||
const execute = vi.fn(async (request: Parameters<CommandManagedRuntimeRunner["execute"]>[0]) => {
|
||||
try {
|
||||
const result = await promisify(execFile)(request.command, request.args ?? [], { cwd: root, timeout: 10_000 });
|
||||
return { ...result, exitCode: 0, signal: null, timedOut: false, pid: null, startedAt: new Date().toISOString() };
|
||||
} catch (error) {
|
||||
const failed = error as Error & { code: number; stdout: string; stderr: string };
|
||||
if (typeof failed.code !== "number") throw error;
|
||||
return { stdout: failed.stdout, stderr: failed.stderr, exitCode: failed.code, signal: null, timedOut: false, pid: null, startedAt: new Date().toISOString() };
|
||||
}
|
||||
});
|
||||
const seal = { targetKey: "sandbox:env-1:scoped-provider" };
|
||||
// Claude and OpenCode succeed even when provider-assets/ is absent.
|
||||
await expect(verifyRemoteProviderPack({ runner: { execute }, cwd: root, packRoot: root, manifest: expected,
|
||||
provider: { kind: "acpx", agent: "claude" }, seal })).resolves.toEqual(expected);
|
||||
await expect(verifyRemoteProviderPack({ runner: { execute }, cwd: root, packRoot: root, manifest: expected,
|
||||
provider: { kind: "opencode" }, seal })).resolves.toEqual(expected);
|
||||
// Cursor must still reject when provider-assets/cursor is missing (and must NOT reuse Claude's seal).
|
||||
await expect(verifyRemoteProviderPack({ runner: { execute }, cwd: root, packRoot: root, manifest: expected,
|
||||
provider: { kind: "acpx", agent: "cursor" }, seal })).rejects.toMatchObject({ failureCheck: "candidate_digest" });
|
||||
// Materializing only Cursor passes Cursor verification while Kimi still rejects.
|
||||
await write(`${cursorPath}/agent`, "cursor-v1");
|
||||
await expect(verifyRemoteProviderPack({ runner: { execute }, cwd: root, packRoot: root, manifest: expected,
|
||||
provider: { kind: "acpx", agent: "cursor" }, seal })).resolves.toEqual(expected);
|
||||
await expect(verifyRemoteProviderPack({ runner: { execute }, cwd: root, packRoot: root, manifest: expected,
|
||||
provider: { kind: "acpx", agent: "kimi" }, seal })).rejects.toMatchObject({ failureCheck: "candidate_digest" });
|
||||
// Omitting provider still checks every declared provider asset tree.
|
||||
await expect(verifyRemoteProviderPack({ runner: { execute }, cwd: root, packRoot: root, manifest: expected, seal }))
|
||||
.rejects.toMatchObject({ failureCheck: "candidate_digest" });
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import { posix } from "node:path";
|
||||
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
|
||||
import { runRemoteProviderVerification } from "./remote-provider-pack.js";
|
||||
|
||||
import { canonicalProviderPackJson, providerPackIncompatible, compatibleProviderPackInstallation,
|
||||
import { canonicalProviderPackJson, providerPackIncompatible, compatibleProviderPackInstallation, requiredProviderAssetNames,
|
||||
type ProviderPackIdentity, type ProviderPackInstallation, type PackProvider, type AdmittedProviderPackReceipt } from "./provider-pack-compatibility.js";
|
||||
export { canonicalProviderPackJson, providerPackIncompatible, type ProviderPackIdentity,
|
||||
type ProviderPackInstallation, type PackProvider, type AdmittedProviderPackReceipt } from "./provider-pack-compatibility.js";
|
||||
@@ -42,9 +42,15 @@ const MAX_SEALED_PACKS = 512;
|
||||
/** Test seam: forget every sealed pack record. */
|
||||
export function clearSealedProviderPacksForTest(): void { sealedPacks.clear(); }
|
||||
|
||||
function sealKeyFor(seal: { targetKey: string } | undefined, packRoot: string, manifest: ProviderPackIdentity, acceptProvenance: boolean): string | null {
|
||||
function sealKeyFor(
|
||||
seal: { targetKey: string } | undefined,
|
||||
packRoot: string,
|
||||
manifest: ProviderPackIdentity,
|
||||
acceptProvenance: boolean,
|
||||
requiredAssets: readonly string[] | null,
|
||||
): string | null {
|
||||
if (!seal?.targetKey) return null;
|
||||
return createHash("sha256").update(canonicalProviderPackJson([seal.targetKey, packRoot, manifest, acceptProvenance])).digest("hex");
|
||||
return createHash("sha256").update(canonicalProviderPackJson([seal.targetKey, packRoot, manifest, acceptProvenance, requiredAssets])).digest("hex");
|
||||
}
|
||||
|
||||
const reportedIdentity = (stdout: string) => /paperclip-pack-identity=([a-f0-9]{64})/.exec(stdout)?.[1] ?? null;
|
||||
@@ -75,7 +81,8 @@ export async function verifyRemoteProviderPack<T extends ProviderPackIdentity>({
|
||||
packRoot,
|
||||
manifest.payload.artifacts.nodeCommand.path,
|
||||
);
|
||||
const sealKey = sealKeyFor(seal, packRoot, manifest, acceptProvenance);
|
||||
const requiredAssets = requiredProviderAssetNames(provider, manifest);
|
||||
const sealKey = sealKeyFor(seal, packRoot, manifest, acceptProvenance, requiredAssets);
|
||||
const sealed = sealKey ? sealedPacks.get(sealKey) : undefined;
|
||||
if (sealKey && sealed) {
|
||||
// Any failure or difference falls through to the full verification.
|
||||
@@ -114,7 +121,8 @@ export async function verifyRemoteProviderPack<T extends ProviderPackIdentity>({
|
||||
"const tree=(treeRoot)=>{try{return walk(treeRoot)}catch{return 'unreadable'}}",
|
||||
"for(const name of ['nodeCommand','productionLock','opencodeCommand','opencodeExecutable','opencodeProxy','acpxSidecar','grokLauncher']){const artifact=manifest.payload.artifacts[name];if(hash(artifact.path)!==artifact.sha256)fail('artifact_digest:'+name,name+' digest mismatch')}",
|
||||
"if(tree(path.join(root,'dist'))!==manifest.payload.distDigest)fail('dist_digest','dist tree digest mismatch')",
|
||||
"for(const candidate of Object.values({...manifest.payload.providers,...manifest.payload.candidateProviders})){if(tree(path.join(root,candidate.path))!==candidate.sha256)fail('candidate_digest','candidate asset tree digest mismatch')}",
|
||||
"const requiredCandidates=process.argv[4]?JSON.parse(process.argv[4]):null",
|
||||
"for(const [name,candidate] of Object.entries({...manifest.payload.providers,...manifest.payload.candidateProviders})){if(requiredCandidates!==null&&!requiredCandidates.includes(name))continue;if(tree(path.join(root,candidate.path))!==candidate.sha256)fail('candidate_digest','candidate asset tree digest mismatch')}",
|
||||
"const version=process.versions.node.split('.').map(Number)",
|
||||
"const minimum=manifest.payload.pins.nodeMinimum.split('.').map(Number)",
|
||||
"if(version[0]<minimum[0]||(version[0]===minimum[0]&&(version[1]<minimum[1]||(version[1]===minimum[1]&&version[2]<minimum[2]))))fail('node_version','Node version incompatible')",
|
||||
@@ -126,9 +134,12 @@ export async function verifyRemoteProviderPack<T extends ProviderPackIdentity>({
|
||||
// Seal only when no entry changed while it was being hashed.
|
||||
...(sealKey ? ["let identityAfter=null;try{identityAfter=packIdentity(root)}catch{}if(identityBefore&&identityBefore===identityAfter)process.stdout.write('\\npaperclip-pack-identity='+identityAfter+'\\n')"] : []),
|
||||
].join(";");
|
||||
const verifyArgs = requiredAssets !== null
|
||||
? ["-e", verifyScript, packRoot, expected, acceptProvenance ? "provenance" : "", JSON.stringify(requiredAssets)]
|
||||
: ["-e", verifyScript, packRoot, expected, ...(acceptProvenance ? ["provenance"] : [])];
|
||||
const verified = await withProviderPackCheck("pack", () => runRemoteProviderVerification(() => runner.execute({
|
||||
command: providerNodeCommand,
|
||||
args: ["-e", verifyScript, packRoot, expected, ...(acceptProvenance ? ["provenance"] : [])],
|
||||
args: verifyArgs,
|
||||
cwd: cwd,
|
||||
bypassSession: true,
|
||||
timeoutMs: 30_000,
|
||||
|
||||
Reference in new issue
Block a user