diff --git a/packages/plugins/sandbox-providers/daytona/package.json b/packages/plugins/sandbox-providers/daytona/package.json index cbf36aedffb..e6fce5148c2 100644 --- a/packages/plugins/sandbox-providers/daytona/package.json +++ b/packages/plugins/sandbox-providers/daytona/package.json @@ -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", diff --git a/packages/plugins/sandbox-providers/daytona/src/manifest.ts b/packages/plugins/sandbox-providers/daytona/src/manifest.ts index 2494e18866e..22fd1224777 100644 --- a/packages/plugins/sandbox-providers/daytona/src/manifest.ts +++ b/packages/plugins/sandbox-providers/daytona/src/manifest.ts @@ -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", diff --git a/packages/plugins/sandbox-providers/daytona/src/plugin.test.ts b/packages/plugins/sandbox-providers/daytona/src/plugin.test.ts index ee5e0e48984..c4d617bedeb 100644 --- a/packages/plugins/sandbox-providers/daytona/src/plugin.test.ts +++ b/packages/plugins/sandbox-providers/daytona/src/plugin.test.ts @@ -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]; + 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( diff --git a/server/src/__tests__/kimi-connection-probe.test.ts b/server/src/__tests__/kimi-connection-probe.test.ts index a7a89991e94..b44b9abb44b 100644 --- a/server/src/__tests__/kimi-connection-probe.test.ts +++ b/server/src/__tests__/kimi-connection-probe.test.ts @@ -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(); diff --git a/server/src/services/kimi-connection-probe.ts b/server/src/services/kimi-connection-probe.ts index 75aaf839652..1e7b06066b7 100644 --- a/server/src/services/kimi-connection-probe.ts +++ b/server/src/services/kimi-connection-probe.ts @@ -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(); } } diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index b1bce52809b..f780da12e73 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -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; @@ -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 }), diff --git a/server/src/services/native-runtime/provider-pack-archive.test.ts b/server/src/services/native-runtime/provider-pack-archive.test.ts index 9537f9a4990..000d935e53b 100644 --- a/server/src/services/native-runtime/provider-pack-archive.test.ts +++ b/server/src/services/native-runtime/provider-pack-archive.test.ts @@ -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 { + 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(); +}); diff --git a/server/src/services/native-runtime/provider-pack-archive.ts b/server/src/services/native-runtime/provider-pack-archive.ts index 87e1938e432..17060d2cf2f 100644 --- a/server/src/services/native-runtime/provider-pack-archive.ts +++ b/server/src/services/native-runtime/provider-pack-archive.ts @@ -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; + supplementAssetsOnly?: boolean; }): Promise { 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 = (name: string, fn: () => Promise) => 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); } } diff --git a/server/src/services/native-runtime/provider-pack-compatibility.ts b/server/src/services/native-runtime/provider-pack-compatibility.ts index 0efc8f7b373..1c1d3482ae4 100644 --- a/server/src/services/native-runtime/provider-pack-compatibility.ts +++ b/server/src/services/native-runtime/provider-pack-compatibility.ts @@ -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, +): 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; + 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(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( installation: ProviderPackInstallation, expected: T, packRoot: string, provider: PackProvider, requireExactIdentity: boolean, requireCurrentOpenCodeProxy: boolean, diff --git a/server/src/services/native-runtime/provider-pack-layers.ts b/server/src/services/native-runtime/provider-pack-layers.ts index cc353873433..f4d7853e735 100644 --- a/server/src/services/native-runtime/provider-pack-layers.ts +++ b/server/src/services/native-runtime/provider-pack-layers.ts @@ -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[]): ProviderPackReuseStep[] { +export function providerPackReusePlan( + files: readonly Pick[], + sourceFiles: readonly Pick[] = files, +): ProviderPackReuseStep[] { const pathsBySha = new Map(); - 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(); 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, + 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, +) { + 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; + /** When true, add only the required `provider-assets/` subtrees into an existing verified pack. */ + supplementAssetsOnly?: boolean; }): Promise { const { archive, runner } = input; if (!runner.syncIn) throw Error("runner_remote_provider_archive_transport_unavailable"); const measure = (name: string, fn: () => Promise) => 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); } } diff --git a/server/src/services/native-runtime/provider-pack-upload.ts b/server/src/services/native-runtime/provider-pack-upload.ts index 3826036f20f..8995612c004 100644 --- a/server/src/services/native-runtime/provider-pack-upload.ts +++ b/server/src/services/native-runtime/provider-pack-upload.ts @@ -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; stageDirectory: (root: string) => Promise; + /** True when `targetPath` already holds a verified core pack for `expectedDigest` and can be supplemented in place. */ + verifyStagedCore?: () => Promise; verifyUploaded: () => Promise; }): Promise { 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); diff --git a/server/src/services/native-runtime/remote-provider-pack-verification.test.ts b/server/src/services/native-runtime/remote-provider-pack-verification.test.ts index b532ad5ef4b..f5074d229f5 100644 --- a/server/src/services/native-runtime/remote-provider-pack-verification.test.ts +++ b/server/src/services/native-runtime/remote-provider-pack-verification.test.ts @@ -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[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 }); + } + }); + }); diff --git a/server/src/services/native-runtime/remote-provider-pack-verification.ts b/server/src/services/native-runtime/remote-provider-pack-verification.ts index 10137a14a83..67d0f8e02c1 100644 --- a/server/src/services/native-runtime/remote-provider-pack-verification.ts +++ b/server/src/services/native-runtime/remote-provider-pack-verification.ts @@ -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({ 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({ "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]({ // 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,