The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
feat(daytona): add transparent zstd-3 compression to the file-mapping upload path (#12271)
Nicky Leach24d639abad19
diff --git a/packages/plugins/sandbox-providers/daytona/src/file-sync.test.ts b/packages/plugins/sandbox-providers/daytona/src/file-sync.test.tsindex 6b171e5863..d732c6dc5d 100644--- a/packages/plugins/sandbox-providers/daytona/src/file-sync.test.ts+++ b/packages/plugins/sandbox-providers/daytona/src/file-sync.test.ts@@ -1,6 +1,10 @@import { promises as fs } from "node:fs";import os from "node:os";import path from "node:path";+import crypto from "node:crypto";+import { spawnSync } from "node:child_process";+import zlib from "node:zlib";+import { Transform } from "node:stream";import { afterEach, describe, expect, it } from "vitest";// The plugin module imports `@daytonaio/sdk` as a value, but the sync tests never@@ -14,7 +18,8 @@ vi.mock("@daytonaio/sdk", () => ({}));import { performSyncIn } from "./file-sync.js";-import type { PluginSyncOperation } from "@paperclipai/plugin-sdk";+import { __setDaytonaPluginContextForTest } from "./plugin.js";+import type { PluginContext, PluginSyncOperation } from "@paperclipai/plugin-sdk";// One recorded in-sandbox command, so a test can assert the exact cleanup command.interface RecordedCommand {@@ -153,3 +158,862 @@ describe("daytona file-sync inbound scratch cleanup", () => {expect(standaloneRemoves).toHaveLength(0);});});++// ---------------------------------------------------------------+// zstd-3 transport compression on the inbound file-mapping path+// ---------------------------------------------------------------++const ZSTD_MIN_SOURCE_BYTES_FOR_TEST = 8 * 1024 * 1024;++// A real `zstd` binary is required to run the tests that execute a real+// promotion script (the sandbox stand-in below shells out to THIS host). The+// package never depends on a `zstd` binary on the production host — only the+// sandbox side does, per the design — but the test double needs one to prove+// the decompression contract for real rather than only recording commands.+// Skip cleanly, like the existing `describeLinux`/`describeLive` gates in this+// package, when the test host has none.+const hasZstdBinary = spawnSync("zstd", ["--version"]).status === 0;+const describeWithZstd = hasZstdBinary ? describe : describe.skip;++function sha256OfFile(filePath: string): Promise<string> {+ return fs.readFile(filePath).then((buf) => crypto.createHash("sha256").update(buf).digest("hex"));+}++async function writeCompressibleFile(filePath: string, sizeBytes: number): Promise<void> {+ // Low-entropy repeated content compresses well past the 10% saving bar.+ const chunk = Buffer.from("paperclip-zstd-transport-compression-fixture-".repeat(64));+ const parts: Buffer[] = [];+ for (let written = 0; written < sizeBytes; written += chunk.length) parts.push(chunk);+ await fs.writeFile(filePath, Buffer.concat(parts).subarray(0, sizeBytes));+}++async function writeIncompressibleFile(filePath: string, sizeBytes: number): Promise<void> {+ await fs.writeFile(filePath, crypto.randomBytes(sizeBytes));+}++/**+ * Extract the raw scratch pathname from a promote-script command's own text.+ * The promote script embeds the path inside `shellQuote`, and the WHOLE+ * script is itself `shellQuote`d again for the outer `sh -c` wrapper — so the+ * literal `'...'` delimiters around the path get escaped and are not a+ * reliable anchor. The path text itself has no shell metacharacters (it is+ * `remoteDir` + a UUID-based scratch name), so it survives both quoting+ * passes unchanged and is matched directly instead. The script always emits+ * the raw scratch's `exec 9> ...` line before the `.zst` scratch's+ * `zstd -d -c -- ...` line, so the FIRST match is always the raw name.+ */+function extractRawScratchPath(command: string, remoteDir: string): string {+ const escapedRoot = remoteDir.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ const match = command.match(new RegExp(`${escapedRoot}/\\.paperclip-upload-[0-9a-f-]+`));+ if (!match) throw new Error("test setup: could not find the raw scratch path in the promote script");+ return match[0];+}++/**+ * A lightweight recording sandbox double for the fallback-condition tests: it+ * never runs a real shell, only records commands and reports a canned exit+ * code, and simulates the zstd availability probe via `probeReportsZstd`.+ * Host-side compression (`node:zlib`) still runs for real in the code under+ * test — only the SANDBOX side is faked here — so these tests genuinely+ * exercise the host compression/ratio decision.+ */+function createRecordingSandbox(input: {+ probeReportsZstd: boolean;+ uploadedSources: string[];+ uploadedDestinations: string[];+ commands: RecordedCommand[];+}) {+ return {+ process: {+ executeCommand: async (command: string) => {+ input.commands.push({ command });+ if (command.includes("mkdir -p")) {+ return { exitCode: 0, result: input.probeReportsZstd ? "PAPERCLIP_ZSTD_AVAILABLE\n" : "" };+ }+ return { exitCode: 0, result: "" };+ },+ },+ fs: {+ uploadFiles: async (uploads: Array<{ source: string; destination: string }>) => {+ for (const upload of uploads) {+ input.uploadedSources.push(upload.source);+ input.uploadedDestinations.push(upload.destination);+ }+ },+ setFilePermissions: async () => undefined,+ },+ };+}++/**+ * A real POSIX-shell-backed sandbox double: `executeCommand` runs the exact+ * command string on THIS host via `/bin/sh -c`, and `uploadFiles`/+ * `setFilePermissions` apply real bytes/modes onto a real directory standing+ * in for the sandbox root. This proves the decompression/promotion script+ * for real, instead of only recording which commands the code would send.+ *+ * `beforeCommand` runs (and may `await` a filesystem mutation) immediately+ * before each real command executes. The race-regression test uses it to+ * plant a pre-created scratch name at exactly the moment a sandbox peer could+ * have observed the pathname (the R2 residual the design discloses), and the+ * parent-swap test uses it to swap a target's parent dir between the+ * confinement guard and the promotion round trip.+ */+function createRealExecSandbox(input?: {+ beforeCommand?: (command: string, index: number) => void | Promise<void>;+ uploadOverride?: (uploads: Array<{ source: string; destination: string }>) => Promise<boolean>;+}) {+ const commands: RecordedCommand[] = [];+ let index = 0;+ return {+ commands,+ sandbox: {+ process: {+ executeCommand: async (command: string) => {+ await input?.beforeCommand?.(command, index);+ index += 1;+ commands.push({ command });+ const result = spawnSync("/bin/sh", ["-c", command], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });+ return { exitCode: result.status ?? 1, result: (result.stdout ?? "") + (result.stderr ?? "") };+ },+ },+ fs: {+ uploadFiles: async (uploads: Array<{ source: string; destination: string }>) => {+ if (input?.uploadOverride && (await input.uploadOverride(uploads))) return;+ for (const upload of uploads) await fs.copyFile(upload.source, upload.destination);+ },+ setFilePermissions: async (target: string, options: { mode: string }) => {+ await fs.chmod(target, parseInt(options.mode, 8));+ },+ },+ },+ };+}++describe("daytona file-sync inbound zstd transport compression", () => {+ const cleanupDirs: string[] = [];++ afterEach(async () => {+ while (cleanupDirs.length > 0) {+ const dir = cleanupDirs.pop();+ if (!dir) continue;+ await fs.rm(dir, { recursive: true, force: true }).catch(() => undefined);+ }+ });++ const mkTempDir = async (prefix: string): Promise<string> => {+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), prefix));+ cleanupDirs.push(dir);+ return dir;+ };++ describeWithZstd("compressed path (real promotion script, real zstd)", () => {+ it("compresses on the host and decompresses in-sandbox to a byte-identical file", async () => {+ const remoteDir = await mkTempDir("paperclip-daytona-zstd-remote-");+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const sourcePath = path.join(hostDir, "workspace-upload.tar");+ await writeCompressibleFile(sourcePath, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 1024);+ const targetPath = path.posix.join(remoteDir, "workspace-upload.tar");++ const { sandbox, commands } = createRealExecSandbox();+ const operations: PluginSyncOperation[] = [{+ operationId: "sync-op-1",+ files: [{ sourcePath, targetPath, kind: "file" }],+ }];++ const result = await performSyncIn({ sandbox: sandbox as never, operations, remoteDir, timeoutSeconds: 30 });++ expect(result.operations[0].filesTransferred).toBe(1);+ expect(result.operations[0].bytesTransferred).toBe(ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 1024);+ // The promote script actually ran a real `zstd -d -c` — proves decompression+ // happened, not just that the code called `uploadFiles`.+ expect(commands.some((entry) => entry.command.includes("zstd -d -c"))).toBe(true);+ expect(await sha256OfFile(targetPath)).toBe(await sha256OfFile(sourcePath));++ // Cleanup on success: no reserved scratch (raw or `.zst`) remains.+ const remaining = await fs.readdir(remoteDir);+ expect(remaining.filter((name) => name.includes(".paperclip-upload"))).toHaveLength(0);+ });++ it("removes the private compressed host temp directory after a successful sync", async () => {+ const remoteDir = await mkTempDir("paperclip-daytona-zstd-remote-");+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const sourcePath = path.join(hostDir, "workspace-upload.tar");+ await writeCompressibleFile(sourcePath, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 1024);+ const targetPath = path.posix.join(remoteDir, "target.bin");++ let capturedHostTempDir = "";+ const { sandbox } = createRealExecSandbox({+ uploadOverride: async (uploads) => {+ const zstdUpload = uploads.find((upload) => upload.destination.endsWith(".zst"));+ if (zstdUpload) capturedHostTempDir = path.dirname(zstdUpload.source);+ for (const upload of uploads) await fs.copyFile(upload.source, upload.destination);+ return true;+ },+ });+ const operations: PluginSyncOperation[] = [{+ operationId: "sync-op-1",+ files: [{ sourcePath, targetPath, kind: "file" }],+ }];++ await performSyncIn({ sandbox: sandbox as never, operations, remoteDir, timeoutSeconds: 30 });++ expect(capturedHostTempDir).toContain("paperclip-daytona-zstd-");+ // The private host temp directory (not just the file inside it) is gone+ // after a successful sync.+ await expect(fs.stat(capturedHostTempDir)).rejects.toThrow();+ });++ it("reports the sync as successful when the post-promotion `.zst` cleanup fails, and warns with a leftover count but no path", async () => {+ const remoteDir = await mkTempDir("paperclip-daytona-zstd-remote-");+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const sourcePath = path.join(hostDir, "workspace-upload.tar");+ await writeCompressibleFile(sourcePath, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 1024);+ const targetPath = path.posix.join(remoteDir, "target.bin");++ // Put a stand-in `rm` first on PATH. It always exits 1. So BOTH the+ // promote script's OWN `.zst` cleanup and the later bounded sweep's+ // separate `rm -f` fail, the same way a persistent cleanup error would.+ // The other commands (`mv`, `zstd`, `chmod`) still resolve to the real+ // binaries later on PATH.+ const fakeBinDir = await mkTempDir("paperclip-daytona-zstd-fakebin-");+ const fakeRmPath = path.join(fakeBinDir, "rm");+ await fs.writeFile(fakeRmPath, "#!/bin/sh\nexit 1\n");+ await fs.chmod(fakeRmPath, 0o755);+ const originalPath = process.env.PATH;+ process.env.PATH = `${fakeBinDir}${path.delimiter}${originalPath}`;+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);++ try {+ const { sandbox } = createRealExecSandbox();+ const operations: PluginSyncOperation[] = [{+ operationId: "sync-op-1",+ files: [{ sourcePath, targetPath, kind: "file" }],+ }];++ // Every target file is already installed by the time the `.zst`+ // cleanup runs, so a failing cleanup must never turn into a sync+ // failure.+ await performSyncIn({ sandbox: sandbox as never, operations, remoteDir, timeoutSeconds: 30 });++ expect(await sha256OfFile(targetPath)).toBe(await sha256OfFile(sourcePath));+ // The forced `rm` failure left the `.zst` scratch behind — proof the+ // fake `rm` actually ran and failed, not that cleanup was skipped.+ const remaining = await fs.readdir(remoteDir);+ const zstdName = remaining.find((name) => name.endsWith(".zst"));+ expect(zstdName).toBeDefined();++ // A leftover that survives both the inline cleanup and the bounded+ // sweep is observable: exactly one warning, carrying a count, never+ // the scratch pathname itself.+ expect(warnSpy).toHaveBeenCalledTimes(1);+ const warning = warnSpy.mock.calls[0]?.[0] as string;+ expect(warning).toContain("1 post-promotion scratch file");+ expect(warning).not.toContain(zstdName as string);+ } finally {+ process.env.PATH = originalPath;+ warnSpy.mockRestore();+ }+ });++ it("recovers a transient post-promotion `.zst` cleanup failure with the bounded sweep, without warning", async () => {+ const remoteDir = await mkTempDir("paperclip-daytona-zstd-remote-");+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const sourcePath = path.join(hostDir, "workspace-upload.tar");+ await writeCompressibleFile(sourcePath, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 1024);+ const targetPath = path.posix.join(remoteDir, "target.bin");++ // A stand-in `rm` that fails only its first call — the promote script's+ // own inline `.zst` cleanup. It defers to the real `rm` for every later+ // call. This simulates a transient cleanup failure: the bounded sweep's+ // own, separate `rm -f` is the second call, and it succeeds.+ const fakeBinDir = await mkTempDir("paperclip-daytona-zstd-fakebin-");+ const counterFile = path.join(fakeBinDir, "rm-call-count");+ const fakeRmPath = path.join(fakeBinDir, "rm");+ await fs.writeFile(+ fakeRmPath,+ [+ "#!/bin/sh",+ "n=0",+ `[ -f "${counterFile}" ] && n=$(cat "${counterFile}")`,+ "n=$((n + 1))",+ `printf '%s' "$n" > "${counterFile}"`,+ '[ "$n" -eq 1 ] && exit 1',+ 'exec /bin/rm "$@"',+ "",+ ].join("\n"),+ );+ await fs.chmod(fakeRmPath, 0o755);+ const originalPath = process.env.PATH;+ process.env.PATH = `${fakeBinDir}${path.delimiter}${originalPath}`;+ const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);++ try {+ const { sandbox } = createRealExecSandbox();+ const operations: PluginSyncOperation[] = [{+ operationId: "sync-op-1",+ files: [{ sourcePath, targetPath, kind: "file" }],+ }];++ await performSyncIn({ sandbox: sandbox as never, operations, remoteDir, timeoutSeconds: 30 });++ expect(await sha256OfFile(targetPath)).toBe(await sha256OfFile(sourcePath));+ expect(await fs.readFile(counterFile, "utf8")).toBe("2"); // proves the sweep actually ran a second `rm`+ // The sweep's separate, later `rm -f` succeeded where the inline+ // cleanup failed — no `.zst` scratch remains, so there is nothing to+ // warn about.+ const remaining = await fs.readdir(remoteDir);+ expect(remaining.some((name) => name.endsWith(".zst"))).toBe(false);+ expect(warnSpy).not.toHaveBeenCalled();+ } finally {+ process.env.PATH = originalPath;+ warnSpy.mockRestore();+ }+ });++ it("never promotes a partial file when decompression fails, and sweeps all reserved scratch", async () => {+ const remoteDir = await mkTempDir("paperclip-daytona-zstd-remote-");+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const sourcePath = path.join(hostDir, "workspace-upload.tar");+ await writeCompressibleFile(sourcePath, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 1024);+ const targetPath = path.posix.join(remoteDir, "target.bin");++ const { sandbox } = createRealExecSandbox({+ // Simulate the `.zst` upload landing corrupted: the in-sandbox+ // `zstd -d -c` step will fail for real on this invalid input.+ uploadOverride: async (uploads) => {+ for (const upload of uploads) {+ if (upload.destination.endsWith(".zst")) {+ await fs.writeFile(upload.destination, Buffer.from("not a valid zstd frame at all"));+ } else {+ await fs.copyFile(upload.source, upload.destination);+ }+ }+ return true;+ },+ });+ const operations: PluginSyncOperation[] = [{+ operationId: "sync-op-1",+ files: [{ sourcePath, targetPath, kind: "file" }],+ }];++ await expect(+ performSyncIn({ sandbox: sandbox as never, operations, remoteDir, timeoutSeconds: 30 }),+ ).rejects.toThrow(/syncIn rename/);++ await expect(fs.stat(targetPath)).rejects.toThrow(); // never promoted+ const remaining = await fs.readdir(remoteDir);+ expect(remaining.filter((name) => name.includes(".paperclip-upload"))).toHaveLength(0); // scratch swept+ });++ it("refuses a pre-created regular file at the raw scratch name (race regression, C1)", async () => {+ const remoteDir = await mkTempDir("paperclip-daytona-zstd-remote-");+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const sourcePath = path.join(hostDir, "workspace-upload.tar");+ await writeCompressibleFile(sourcePath, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 1024);+ const targetPath = path.posix.join(remoteDir, "target.bin");++ let injected = false;+ const { sandbox } = createRealExecSandbox({+ beforeCommand: async (command) => {+ if (injected || !command.includes("zstd -d -c")) return;+ const rawScratchPath = extractRawScratchPath(command, remoteDir);+ injected = true;+ // A peer that reads this command's own text (the R2 residual) claims+ // the reserved name first, as a plain pre-existing file.+ await fs.writeFile(rawScratchPath, "attacker-controlled pre-existing content");+ },+ });+ const operations: PluginSyncOperation[] = [{+ operationId: "sync-op-1",+ files: [{ sourcePath, targetPath, kind: "file" }],+ }];++ await expect(+ performSyncIn({ sandbox: sandbox as never, operations, remoteDir, timeoutSeconds: 30 }),+ ).rejects.toThrow();++ expect(injected).toBe(true);+ await expect(fs.stat(targetPath)).rejects.toThrow(); // never promoted+ });++ it("refuses a pre-created symlink at the raw scratch name and never writes through it (race regression, C1)", async () => {+ const remoteDir = await mkTempDir("paperclip-daytona-zstd-remote-");+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const sourcePath = path.join(hostDir, "workspace-upload.tar");+ await writeCompressibleFile(sourcePath, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 1024);+ const targetPath = path.posix.join(remoteDir, "target.bin");+ const sentinelPath = path.join(hostDir, "outside-the-workspace-root.txt");+ const sentinelContent = "PRE-EXISTING CONTENT, MUST SURVIVE UNCHANGED\n";+ await fs.writeFile(sentinelPath, sentinelContent);++ let injected = false;+ const { sandbox } = createRealExecSandbox({+ beforeCommand: async (command) => {+ if (injected || !command.includes("zstd -d -c")) return;+ const rawScratchPath = extractRawScratchPath(command, remoteDir);+ injected = true;+ // A peer that reads this command's own text (the R2 residual) claims+ // the reserved name first, as a symlink pointing OUTSIDE the workspace+ // root — the attack shape a create-with-mode-not-check-then-create+ // primitive must refuse.+ await fs.symlink(sentinelPath, rawScratchPath);+ },+ });+ const operations: PluginSyncOperation[] = [{+ operationId: "sync-op-1",+ files: [{ sourcePath, targetPath, kind: "file" }],+ }];++ await expect(+ performSyncIn({ sandbox: sandbox as never, operations, remoteDir, timeoutSeconds: 30 }),+ ).rejects.toThrow();++ expect(injected).toBe(true);+ await expect(fs.stat(targetPath)).rejects.toThrow(); // never promoted+ // The symlink's target was never opened/written through: content unchanged,+ // and no write landed outside the workspace root.+ expect(await fs.readFile(sentinelPath, "utf8")).toBe(sentinelContent);+ });++ it("still fails at the fd re-verification when a target's parent dir is swapped after the confinement guard", async () => {+ const remoteDir = await mkTempDir("paperclip-daytona-zstd-remote-");+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const outsideDir = await mkTempDir("paperclip-daytona-zstd-outside-");+ const realParentDir = path.posix.join(remoteDir, "nested");+ const targetPath = path.posix.join(realParentDir, "target.bin");+ const sourcePath = path.join(hostDir, "small.bin");+ await fs.writeFile(sourcePath, "small file, well below the compression threshold\n");++ let swapped = false;+ const { sandbox } = createRealExecSandbox({+ beforeCommand: async (_command, index) => {+ // index 0 = mkdir+probe, index 1 = checkSymlinkEscape, index 2 = promote.+ if (index !== 2 || swapped) return;+ swapped = true;+ await fs.rm(realParentDir, { recursive: true, force: true });+ await fs.symlink(outsideDir, realParentDir);+ },+ });+ const operations: PluginSyncOperation[] = [{+ operationId: "sync-op-1",+ files: [{ sourcePath, targetPath, kind: "file" }],+ }];++ await expect(+ performSyncIn({ sandbox: sandbox as never, operations, remoteDir, timeoutSeconds: 30 }),+ ).rejects.toThrow(/ESCAPE|syncIn rename/);++ expect(swapped).toBe(true);+ expect(await fs.readdir(outsideDir)).toHaveLength(0); // nothing landed outside the root+ });++ it("applies mapping.mode via the retained descriptor, defaulting to 0600 when unset", async () => {+ const remoteDir = await mkTempDir("paperclip-daytona-zstd-remote-");+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const sourceNoMode = path.join(hostDir, "no-mode.tar");+ const sourceWithMode = path.join(hostDir, "with-mode.tar");+ await writeCompressibleFile(sourceNoMode, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 1024);+ await writeCompressibleFile(sourceWithMode, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 2048);+ const targetNoMode = path.posix.join(remoteDir, "no-mode.bin");+ const targetWithMode = path.posix.join(remoteDir, "with-mode.bin");++ const { sandbox } = createRealExecSandbox();+ const operations: PluginSyncOperation[] = [{+ operationId: "sync-op-1",+ files: [+ { sourcePath: sourceNoMode, targetPath: targetNoMode, kind: "file" },+ { sourcePath: sourceWithMode, targetPath: targetWithMode, kind: "file", mode: 0o640 },+ ],+ }];++ await performSyncIn({ sandbox: sandbox as never, operations, remoteDir, timeoutSeconds: 30 });++ expect((await fs.stat(targetNoMode)).mode & 0o777).toBe(0o600);+ expect((await fs.stat(targetWithMode)).mode & 0o777).toBe(0o640);+ });++ it("runs two concurrent compressed sync operations without cross-talk", async () => {+ const remoteDirA = await mkTempDir("paperclip-daytona-zstd-remote-a-");+ const remoteDirB = await mkTempDir("paperclip-daytona-zstd-remote-b-");+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const sourceA = path.join(hostDir, "a.tar");+ const sourceB = path.join(hostDir, "b.tar");+ await writeCompressibleFile(sourceA, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 2048);+ await writeCompressibleFile(sourceB, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 4096);+ await fs.appendFile(sourceA, "AAAA-marker-a");+ await fs.appendFile(sourceB, "BBBB-marker-b");+ const targetA = path.posix.join(remoteDirA, "target.bin");+ const targetB = path.posix.join(remoteDirB, "target.bin");+ const { sandbox: sandboxA } = createRealExecSandbox();+ const { sandbox: sandboxB } = createRealExecSandbox();++ await Promise.all([+ performSyncIn({+ sandbox: sandboxA as never,+ operations: [{ operationId: "a", files: [{ sourcePath: sourceA, targetPath: targetA, kind: "file" }] }],+ remoteDir: remoteDirA,+ timeoutSeconds: 30,+ }),+ performSyncIn({+ sandbox: sandboxB as never,+ operations: [{ operationId: "b", files: [{ sourcePath: sourceB, targetPath: targetB, kind: "file" }] }],+ remoteDir: remoteDirB,+ timeoutSeconds: 30,+ }),+ ]);++ expect(await sha256OfFile(targetA)).toBe(await sha256OfFile(sourceA));+ expect(await sha256OfFile(targetB)).toBe(await sha256OfFile(sourceB));+ });++ it("emits exactly the five compression/decompress span attributes, with closed-set/numeric values", async () => {+ const spans: Array<{ attributes: Record<string, unknown> }> = [];+ const tracer = {+ startSpan(_name: string, options?: { attributes?: Record<string, unknown> }) {+ const span = { attributes: { ...(options?.attributes ?? {}) } as Record<string, unknown> };+ spans.push(span);+ return {+ setAttribute(key: string, value: unknown) {+ span.attributes[key] = value;+ },+ setStatus() {},+ end() {},+ };+ },+ };+ const restore = __setDaytonaPluginContextForTest({ tracer } as unknown as PluginContext);+ let targetPath = "";+ let remoteDir = "";+ try {+ remoteDir = await mkTempDir("paperclip-daytona-zstd-remote-");+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const sourcePath = path.join(hostDir, "workspace-upload.tar");+ await writeCompressibleFile(sourcePath, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 1024);+ targetPath = path.posix.join(remoteDir, "target.bin");+ const { sandbox } = createRealExecSandbox();+ await performSyncIn({+ sandbox: sandbox as never,+ operations: [{ operationId: "op-1", files: [{ sourcePath, targetPath, kind: "file" }] }],+ remoteDir,+ timeoutSeconds: 30,+ });+ } finally {+ restore();+ }++ const allAttrs: Record<string, unknown> = {};+ for (const span of spans) Object.assign(allAttrs, span.attributes);+ const compressionKeys = Object.keys(allAttrs).filter(+ (key) => key.includes(".transfer.compression.") || key.includes(".transfer.decompress."),+ );+ expect(new Set(compressionKeys)).toEqual(new Set([+ "paperclip.sandbox.startup.transfer.compression.codec",+ "paperclip.sandbox.startup.transfer.compression.wall_ms",+ "paperclip.sandbox.startup.transfer.compression.bytes_in",+ "paperclip.sandbox.startup.transfer.compression.bytes_out",+ "paperclip.sandbox.startup.transfer.decompress.wall_ms",+ ]));+ expect(allAttrs["paperclip.sandbox.startup.transfer.compression.codec"]).toBe("zstd");+ for (const key of [+ "paperclip.sandbox.startup.transfer.compression.wall_ms",+ "paperclip.sandbox.startup.transfer.compression.bytes_in",+ "paperclip.sandbox.startup.transfer.compression.bytes_out",+ "paperclip.sandbox.startup.transfer.decompress.wall_ms",+ ]) {+ expect(Number.isFinite(allAttrs[key] as number)).toBe(true);+ }+ });+ });++ describe("raw-path fallback conditions (no real sandbox exec needed)", () => {+ it("falls back to the raw path when the sandbox reports no zstd binary", async () => {+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const sourcePath = path.join(hostDir, "big.tar");+ await writeCompressibleFile(sourcePath, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 1024);+ const uploadedSources: string[] = [];+ const uploadedDestinations: string[] = [];+ const sandbox = createRecordingSandbox({+ probeReportsZstd: false,+ uploadedSources,+ uploadedDestinations,+ commands: [],+ });+ const operations: PluginSyncOperation[] = [{+ operationId: "op-1",+ files: [{ sourcePath, targetPath: "/workspace/target.bin", kind: "file" }],+ }];++ await performSyncIn({ sandbox: sandbox as never, operations, remoteDir: "/workspace", timeoutSeconds: 30 });++ expect(uploadedSources).toEqual([sourcePath]); // raw source uploaded directly+ expect(uploadedDestinations.some((dest) => dest.endsWith(".zst"))).toBe(false);+ });++ it("falls back to the raw path when the source is below ZSTD_MIN_SOURCE_BYTES", async () => {+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const sourcePath = path.join(hostDir, "small.tar");+ await fs.writeFile(sourcePath, "well below the 8 MiB compression floor\n");+ const uploadedSources: string[] = [];+ const uploadedDestinations: string[] = [];+ const sandbox = createRecordingSandbox({+ probeReportsZstd: true,+ uploadedSources,+ uploadedDestinations,+ commands: [],+ });+ const operations: PluginSyncOperation[] = [{+ operationId: "op-1",+ files: [{ sourcePath, targetPath: "/workspace/target.bin", kind: "file" }],+ }];++ await performSyncIn({ sandbox: sandbox as never, operations, remoteDir: "/workspace", timeoutSeconds: 30 });++ expect(uploadedSources).toEqual([sourcePath]);+ expect(uploadedDestinations.some((dest) => dest.endsWith(".zst"))).toBe(false);+ });++ it("falls back to the raw path when the saving ratio is below ZSTD_MIN_SAVING_RATIO", async () => {+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const sourcePath = path.join(hostDir, "incompressible.tar");+ await writeIncompressibleFile(sourcePath, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 1024);+ const uploadedSources: string[] = [];+ const uploadedDestinations: string[] = [];+ const sandbox = createRecordingSandbox({+ probeReportsZstd: true,+ uploadedSources,+ uploadedDestinations,+ commands: [],+ });+ const operations: PluginSyncOperation[] = [{+ operationId: "op-1",+ files: [{ sourcePath, targetPath: "/workspace/target.bin", kind: "file" }],+ }];++ await performSyncIn({ sandbox: sandbox as never, operations, remoteDir: "/workspace", timeoutSeconds: 30 });++ expect(uploadedSources).toEqual([sourcePath]); // host discarded the compressed candidate+ expect(uploadedDestinations.some((dest) => dest.endsWith(".zst"))).toBe(false);+ });++ it("falls back to the raw path when zlib.createZstdCompress is not a function (feature-detect)", async () => {+ // `createZstdCompress` is a non-writable (but configurable) property on+ // `node:zlib` — simulate an older Node runtime without zstd support by+ // redefining it, not assigning it.+ const original = zlib.createZstdCompress;+ Object.defineProperty(zlib, "createZstdCompress", { value: undefined, configurable: true, writable: true });+ try {+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const sourcePath = path.join(hostDir, "big.tar");+ await writeCompressibleFile(sourcePath, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 1024);+ const uploadedSources: string[] = [];+ const uploadedDestinations: string[] = [];+ const sandbox = createRecordingSandbox({+ probeReportsZstd: true,+ uploadedSources,+ uploadedDestinations,+ commands: [],+ });+ const operations: PluginSyncOperation[] = [{+ operationId: "op-1",+ files: [{ sourcePath, targetPath: "/workspace/target.bin", kind: "file" }],+ }];++ await performSyncIn({ sandbox: sandbox as never, operations, remoteDir: "/workspace", timeoutSeconds: 30 });++ expect(uploadedSources).toEqual([sourcePath]);+ expect(uploadedDestinations.some((dest) => dest.endsWith(".zst"))).toBe(false);+ } finally {+ Object.defineProperty(zlib, "createZstdCompress", { value: original, configurable: true, writable: true });+ }+ });++ it("falls back to the raw path when host compression throws, and leaves no host temp file", async () => {+ const original = zlib.createZstdCompress;+ const throwingCompressor = () =>+ new Transform({+ transform(_chunk, _encoding, callback) {+ callback(new Error("simulated host compression failure"));+ },+ }) as ReturnType<typeof zlib.createZstdCompress>;+ Object.defineProperty(zlib, "createZstdCompress", {+ value: throwingCompressor,+ configurable: true,+ writable: true,+ });+ try {+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const sourcePath = path.join(hostDir, "big.tar");+ await writeCompressibleFile(sourcePath, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 1024);+ const uploadedSources: string[] = [];+ const uploadedDestinations: string[] = [];+ const sandbox = createRecordingSandbox({+ probeReportsZstd: true,+ uploadedSources,+ uploadedDestinations,+ commands: [],+ });+ const operations: PluginSyncOperation[] = [{+ operationId: "op-1",+ files: [{ sourcePath, targetPath: "/workspace/target.bin", kind: "file" }],+ }];+ const before = (await fs.readdir(os.tmpdir())).filter((name) => name.startsWith("paperclip-daytona-zstd-"));++ await performSyncIn({ sandbox: sandbox as never, operations, remoteDir: "/workspace", timeoutSeconds: 30 });++ expect(uploadedSources).toEqual([sourcePath]);+ expect(uploadedDestinations.some((dest) => dest.endsWith(".zst"))).toBe(false);+ const after = (await fs.readdir(os.tmpdir())).filter((name) => name.startsWith("paperclip-daytona-zstd-"));+ expect(after).toEqual(before); // no leftover host temp file+ } finally {+ Object.defineProperty(zlib, "createZstdCompress", { value: original, configurable: true, writable: true });+ }+ });++ it("removes the private host temp directory when the post-compression size stat throws", async () => {+ const realStat = fs.stat.bind(fs);+ const statSpy = vi.spyOn(fs, "stat").mockImplementation(async (targetPath, ...rest) => {+ if (typeof targetPath === "string" && path.basename(targetPath) === "artifact.zst") {+ throw new Error("simulated post-compression stat failure");+ }+ return (realStat as typeof fs.stat)(targetPath, ...(rest as []));+ });+ try {+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const sourcePath = path.join(hostDir, "big.tar");+ await writeCompressibleFile(sourcePath, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 1024);+ const uploadedSources: string[] = [];+ const uploadedDestinations: string[] = [];+ const sandbox = createRecordingSandbox({+ probeReportsZstd: true,+ uploadedSources,+ uploadedDestinations,+ commands: [],+ });+ const operations: PluginSyncOperation[] = [{+ operationId: "op-1",+ files: [{ sourcePath, targetPath: "/workspace/target.bin", kind: "file" }],+ }];+ const before = (await fs.readdir(os.tmpdir())).filter((name) => name.startsWith("paperclip-daytona-zstd-"));++ await performSyncIn({ sandbox: sandbox as never, operations, remoteDir: "/workspace", timeoutSeconds: 30 });++ // The post-compression stat failed, so the candidate falls back to the raw path.+ expect(uploadedSources).toEqual([sourcePath]);+ expect(uploadedDestinations.some((dest) => dest.endsWith(".zst"))).toBe(false);+ const after = (await fs.readdir(os.tmpdir())).filter((name) => name.startsWith("paperclip-daytona-zstd-"));+ expect(after).toEqual(before); // the stat failure did not leak the private host temp directory+ } finally {+ statSpy.mockRestore();+ }+ });++ it("removes the host compressed temp file and sweeps sandbox scratch when the upload itself is rejected (cancellation)", async () => {+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const sourcePath = path.join(hostDir, "big.tar");+ await writeCompressibleFile(sourcePath, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 1024);+ const commands: RecordedCommand[] = [];+ const sandbox = {+ process: {+ executeCommand: async (command: string) => {+ commands.push({ command });+ return { exitCode: 0, result: command.includes("mkdir -p") ? "PAPERCLIP_ZSTD_AVAILABLE\n" : "" };+ },+ },+ fs: {+ uploadFiles: async () => {+ throw new Error("simulated cancellation");+ },+ setFilePermissions: async () => undefined,+ },+ };+ const before = (await fs.readdir(os.tmpdir())).filter((name) => name.startsWith("paperclip-daytona-zstd-"));+ const operations: PluginSyncOperation[] = [{+ operationId: "op-1",+ files: [{ sourcePath, targetPath: "/workspace/target.bin", kind: "file" }],+ }];++ await expect(+ performSyncIn({ sandbox: sandbox as never, operations, remoteDir: "/workspace", timeoutSeconds: 30 }),+ ).rejects.toThrow(/simulated cancellation/);++ const after = (await fs.readdir(os.tmpdir())).filter((name) => name.startsWith("paperclip-daytona-zstd-"));+ expect(after).toEqual(before); // no leftover host temp file+ const rmCommands = commands.filter((entry) => entry.command.includes("rm -f"));+ expect(rmCommands.length).toBeGreaterThan(0); // both reserved scratch names swept+ });++ it("stages the compressed artifact in a private 0700 directory with a 0600 file, and removes the directory when the upload fails", async () => {+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const sourcePath = path.join(hostDir, "big.tar");+ await writeCompressibleFile(sourcePath, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 1024);+ let capturedDir = "";+ let capturedDirMode = -1;+ let capturedFileMode = -1;+ const sandbox = {+ process: {+ executeCommand: async (command: string) => ({+ exitCode: 0,+ result: command.includes("mkdir -p") ? "PAPERCLIP_ZSTD_AVAILABLE\n" : "",+ }),+ },+ fs: {+ uploadFiles: async (uploads: Array<{ source: string; destination: string }>) => {+ const zstdUpload = uploads.find((upload) => upload.destination.endsWith(".zst"));+ if (!zstdUpload) throw new Error("test setup: expected a compressed upload");+ // Read the modes BEFORE throwing: the directory and its file still+ // exist at this point, on the way to the (simulated) failed upload.+ capturedDir = path.dirname(zstdUpload.source);+ capturedDirMode = (await fs.stat(capturedDir)).mode & 0o777;+ capturedFileMode = (await fs.stat(zstdUpload.source)).mode & 0o777;+ throw new Error("simulated upload failure");+ },+ setFilePermissions: async () => undefined,+ },+ };+ const operations: PluginSyncOperation[] = [{+ operationId: "op-1",+ files: [{ sourcePath, targetPath: "/workspace/target.bin", kind: "file" }],+ }];++ await expect(+ performSyncIn({ sandbox: sandbox as never, operations, remoteDir: "/workspace", timeoutSeconds: 30 }),+ ).rejects.toThrow(/simulated upload failure/);++ expect(capturedDirMode).toBe(0o700);+ expect(capturedFileMode).toBe(0o600);+ // The private directory (not only the file) is removed after the upload fails.+ await expect(fs.stat(capturedDir)).rejects.toThrow();+ });++ it("passes the caller's timeoutSeconds unchanged through every round trip on the compressed path", async () => {+ const hostDir = await mkTempDir("paperclip-daytona-zstd-host-");+ const sourcePath = path.join(hostDir, "big.tar");+ await writeCompressibleFile(sourcePath, ZSTD_MIN_SOURCE_BYTES_FOR_TEST + 1024);+ const seenTimeouts: Array<number | undefined> = [];+ const sandbox = {+ process: {+ executeCommand: async (command: string, _cwd?: string, _env?: unknown, timeoutSeconds?: number) => {+ seenTimeouts.push(timeoutSeconds);+ return { exitCode: 0, result: command.includes("mkdir -p") ? "PAPERCLIP_ZSTD_AVAILABLE\n" : "" };+ },+ },+ fs: {+ uploadFiles: async (_uploads: unknown, timeoutSeconds?: number) => {+ seenTimeouts.push(timeoutSeconds);+ },+ setFilePermissions: async () => undefined,+ },+ };+ const operations: PluginSyncOperation[] = [{+ operationId: "op-1",+ files: [{ sourcePath, targetPath: "/workspace/target.bin", kind: "file" }],+ }];++ await performSyncIn({ sandbox: sandbox as never, operations, remoteDir: "/workspace", timeoutSeconds: 123 });++ expect(seenTimeouts.length).toBeGreaterThanOrEqual(4); // mkdir+probe, checkSymlinkEscape, transfer, promote+ expect(seenTimeouts.every((timeout) => timeout === 123)).toBe(true);+ });+ });+});diff --git a/packages/plugins/sandbox-providers/daytona/src/file-sync.ts b/packages/plugins/sandbox-providers/daytona/src/file-sync.tsindex 9a613dbd77..cb8c3bb53d 100644--- a/packages/plugins/sandbox-providers/daytona/src/file-sync.ts+++ b/packages/plugins/sandbox-providers/daytona/src/file-sync.ts@@ -1,13 +1,16 @@import path from "node:path";import os from "node:os";-import { promises as fs } from "node:fs";+import { promises as fs, createReadStream, createWriteStream } from "node:fs";import { randomUUID } from "node:crypto";import { execFile } from "node:child_process";import { promisify } from "node:util";+import zlib from "node:zlib";+import { pipeline } from "node:stream/promises";import type { FileDownloadRequest, FileDownloadResponse, FileUpload, Sandbox } from "@daytonaio/sdk";import type {PluginEnvironmentSyncResult,PluginPostUploadCommand,+ PluginSpan,PluginSyncFileMapping,PluginSyncOperation,} from "@paperclipai/plugin-sdk";@@ -28,6 +31,14 @@ const SPAN_ATTR = {// for a download from the sandbox. Operation identity comes from the parent// span, so the transfer span never carries an operation label.transferDirection: `${SPAN_ATTR_PREFIX}transfer.direction`,+ // The five zstd-transport-compression attributes. Values are a closed codec+ // set or a finite number — never a path, a command line, file content, a+ // raw identifier, or error text.+ transferCompressionCodec: `${SPAN_ATTR_PREFIX}transfer.compression.codec`,+ transferCompressionWallMs: `${SPAN_ATTR_PREFIX}transfer.compression.wall_ms`,+ transferCompressionBytesIn: `${SPAN_ATTR_PREFIX}transfer.compression.bytes_in`,+ transferCompressionBytesOut: `${SPAN_ATTR_PREFIX}transfer.compression.bytes_out`,+ transferDecompressWallMs: `${SPAN_ATTR_PREFIX}transfer.decompress.wall_ms`,} as const;/** The value of `SpanStatusCode.ERROR` in `@opentelemetry/api`. The plugin stays@@ -46,19 +57,23 @@ const SPAN_STATUS_CODE_ERROR = 2;* `wallMsAttr` is optional. The `pack` and `transfer` spans pass it to keep* their existing `*.wall_ms` attribute. A per-round-trip span omits it, so it* carries no `*.wall_ms` attribute and relies on the native span width.+ *+ * `run` receives the live span, so a caller that needs to record an attribute+ * only known after the step completes (for example the compression byte+ * counts) can call `span.setAttribute` directly, without a second span.*/export async function withProviderSpan<T>(input: {name: string;wallMsAttr?: string;attributes?: Record<string, string | number | boolean>;- run: () => Promise<T>;+ run: (span: PluginSpan) => Promise<T>;}): Promise<T> {const span = getPluginTracer().startSpan(input.name, {attributes: { [SPAN_ATTR.provider]: "daytona", ...(input.attributes ?? {}) },});const startedAtMs = Date.now();try {- return await input.run();+ return await input.run(span);} catch (error) {span.setStatus({ code: SPAN_STATUS_CODE_ERROR });throw error;@@ -302,17 +317,95 @@ async function countHostFiles(root: string, exclude?: string[]): Promise<number>return total;}-async function assertSandboxCommandOk(+/**+ * Run one sandbox command and return its stdout on success. Throws the same+ * shaped error as {@link assertSandboxCommandOk} on a non-zero exit. Used by+ * the mkdir+zstd-probe round trip, which must read the probe's answer from+ * the command's own output rather than only checking the exit code.+ */+async function assertSandboxCommandOkWithOutput(sandbox: Sandbox,command: string,timeoutSeconds: number,label: string,-): Promise<void> {+): Promise<string> {const result = await sandbox.process.executeCommand(command, undefined, undefined, timeoutSeconds);if ((result.exitCode ?? 1) !== 0) {const detail = (result.result ?? result.artifacts?.stdout ?? "").toString().trim();throw new Error(`Daytona ${label} command failed (exit ${result.exitCode ?? "unknown"})${detail ? `: ${detail}` : ""}`);}+ return (result.result ?? result.artifacts?.stdout ?? "").toString();+}++async function assertSandboxCommandOk(+ sandbox: Sandbox,+ command: string,+ timeoutSeconds: number,+ label: string,+): Promise<void> {+ await assertSandboxCommandOkWithOutput(sandbox, command, timeoutSeconds, label);+}++// -------------------------------------------------------------+// zstd transport compression (inbound file-mapping path only)+// -------------------------------------------------------------++/** A source file below this size never compresses: the round-trip and CPU+ * cost of compression is not worth it for a small file. */+const ZSTD_MIN_SOURCE_BYTES = 8 * 1024 * 1024;++/** Reject a compressed candidate whose saving is below this fraction of the+ * source size (a saving under 10 percent falls back to the raw path). */+const ZSTD_MIN_SAVING_RATIO = 0.1;++/** The zstd compression level for the host-side compressor. */+const ZSTD_COMPRESSION_LEVEL = 3;++/** Marker the mkdir+probe command echoes to sandbox stdout when the sandbox+ * has a `zstd` binary on `PATH`. An absent or unexpected answer fails closed+ * (no compression), per the design's fallback rules. */+const ZSTD_PROBE_MARKER = "PAPERCLIP_ZSTD_AVAILABLE";++/**+ * Feature-detect zstd support on the running Node runtime. `node:zlib` shipped+ * zstd as of Node v22.15.0 / v23.8.0, ahead of this package's declared+ * `engines.node` floor, but the design directs a runtime check rather than an+ * assumption from the `engines` field alone: a floor can be wrong, and this+ * check costs nothing to keep in place after the floor moves.+ */+function isZstdCompressionSupported(): boolean {+ return typeof zlib.createZstdCompress === "function";+}++/**+ * Stream-compress `sourcePath` to a new file with zstd at+ * {@link ZSTD_COMPRESSION_LEVEL}, never buffering the whole file in memory.+ * The compressed file lives in a private directory this function creates with+ * `fs.mkdtemp` (mode `0700`), and the file itself opens with `wx` and mode+ * `0600` — so the workspace content this holds is never readable by another+ * local principal, unlike a bare `os.tmpdir()` file at the default `0644`.+ * The caller removes the returned directory (on the accept path, after the+ * upload; on every reject/error path, immediately) — this function only+ * removes it on its OWN failure, so a caller never has to distinguish a+ * partial directory from a finished one. The cleanup scope covers every+ * step after the directory create, including the post-compression size+ * stat, so a throw there does not leave the directory behind.+ */+async function compressFileToHostTemp(sourcePath: string): Promise<{ dir: string; path: string; bytesOut: number }> {+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-daytona-zstd-"));+ const tempPath = path.join(dir, "artifact.zst");+ try {+ await pipeline(+ createReadStream(sourcePath),+ zlib.createZstdCompress({ params: { [zlib.constants.ZSTD_c_compressionLevel]: ZSTD_COMPRESSION_LEVEL } }),+ createWriteStream(tempPath, { flags: "wx", mode: 0o600 }),+ );+ const bytesOut = (await fs.stat(tempPath)).size;+ return { dir, path: tempPath, bytesOut };+ } catch (error) {+ await fs.rm(dir, { recursive: true, force: true }).catch(() => undefined);+ throw error;+ }}/**@@ -452,10 +545,71 @@ async function removeSandboxScratch(.catch(() => undefined);}+/**+ * Try to remove each `.zst` scratch name a SECOND time, after every target in+ * the batch already promoted successfully.+ *+ * The promote script's own cleanup (`rm -f ... || true`) already tried once.+ * It never fails the sync when that cleanup fails, because a completed and+ * safely promoted target must never read back as a failure.+ *+ * This function does not touch the promote script or its fail-closed guards.+ * It runs one separate, later sandbox command that retries the removal, then+ * reports how many names are still present. This makes a leftover that+ * survives both tries observable instead of silent.+ *+ * This function runs exactly once. It is not a retry loop. It swallows its+ * own command failure and reports the full count as still present — the+ * same "assume the worst, never throw" contract as+ * {@link removeSandboxScratch}.+ */+async function sweepZstdScratchAfterSuccess(+ sandbox: Sandbox,+ zstdScratchNames: string[],+ timeoutSeconds: number,+): Promise<number> {+ if (zstdScratchNames.length === 0) return 0;+ const removeScript = zstdScratchNames.map((name) => `rm -f ${shellQuote(name)}`).join(" ; ");+ const checkScript = zstdScratchNames.map((name) => `[ -e ${shellQuote(name)} ] && echo 1 || echo 0`).join(" ; ");+ const result = await sandbox.process+ .executeCommand(`sh -c ${shellQuote(`${removeScript} ; ${checkScript}`)}`, undefined, undefined, timeoutSeconds)+ .catch(() => null);+ if (!result) return zstdScratchNames.length;+ const output = (result.result ?? result.artifacts?.stdout ?? "").toString();+ return output.split("\n").filter((line) => line.trim() === "1").length;+}+// ---------------------------------------------------------------------------// Inbound (host → sandbox)// ---------------------------------------------------------------------------+/**+ * One file mapping's transfer plan. `compressed` is null until the host+ * compression step (below) accepts this mapping onto the compressed path;+ * it stays null — and the mapping stays on the byte-identical raw path — for+ * every fallback case (no probe, no host zstd support, too small, compression+ * threw, or the saving ratio missed the bar).+ */+interface FileMappingPlan {+ mapping: PluginSyncFileMapping;+ sourceSize: number;+ dir: string;+ /** Reserved scratch name for the FINAL bytes at `targetPath`, a direct child+ * of `remoteDir`. For a raw mapping the host uploads directly to this name.+ * For a compressed mapping the host never creates this name — the in-sandbox+ * decompression step does (Security Condition C1). */+ rawScratch: string;+ compressed: null | {+ /** Reserved `.zst` scratch name, a direct child of `remoteDir`. */+ zstdScratch: string;+ /** Private `0700` host temp directory holding the compressed file, removed+ * (recursively) after upload. */+ hostTempDir: string;+ /** Host temp file (`0600`, inside `hostTempDir`) holding the compressed bytes. */+ hostTempPath: string;+ };+}+async function syncInFileMappings(input: {sandbox: Sandbox;mappings: PluginSyncFileMapping[];@@ -465,34 +619,25 @@ async function syncInFileMappings(input: {const { sandbox, mappings, remoteDir, timeoutSeconds } = input;if (mappings.length === 0) return { filesTransferred: 0, bytesTransferred: 0 };- const uploads: FileUpload[] = [];- const renames: { temp: string; target: string }[] = [];- const modeApplies: { temp: string; mode: number }[] = [];const parentDirs = new Set<string>();let bytesTransferred = 0;-+ const plans: FileMappingPlan[] = [];for (const mapping of mappings) {assertConfinedSandboxPath(remoteDir, mapping.targetPath, "target");const dir = path.posix.dirname(mapping.targetPath);parentDirs.add(dir);+ const sourceSize = (await fs.stat(mapping.sourcePath)).size;+ bytesTransferred += sourceSize;// Stage each upload to a reserved temp that is a DIRECT child of the workspace// root (`remoteDir`), never a sibling of the target. The target's parent dir is// sandbox-writable and can be swapped for a symlink to `/etc` (or any host path)- // after validation but before `uploadFiles` opens the destination — rooting the+ // after validation but before the write opens the destination — rooting the// privileged write directly under `remoteDir` removes that swappable intermediate// component, so the upload cannot be redirected outside the root by a parent// swap. `remoteDir` and the target dir share the workspace filesystem, so the// closing `mv -f` is still an atomic same-fs rename and an interrupted upload// never leaves a truncated file at targetPath.- const temp = path.posix.join(remoteDir, scratchName());- // A string `source` streams from the local path via the SDK's read stream- // (batched, flat per-file memory) rather than buffering the whole file.- uploads.push({ source: mapping.sourcePath, destination: temp });- renames.push({ temp, target: mapping.targetPath });- if (typeof mapping.mode === "number") {- modeApplies.push({ temp, mode: mapping.mode });- }- bytesTransferred += (await fs.stat(mapping.sourcePath)).size;+ plans.push({ mapping, sourceSize, dir, rawScratch: path.posix.join(remoteDir, scratchName()), compressed: null });}// Count the serial guard round trips before the transfer, so the transfer span@@ -500,13 +645,28 @@ async function syncInFileMappings(input: {let guardRoundTrips = 0;// Ensure every target directory exists before the bulk upload writes its temp.+ // The zstd availability probe rides this SAME round trip: no new sandbox round+ // trip and no availability cache — a cache at any scope would hold one+ // principal's observation and reuse it for another, so probing fresh on every+ // call has no poisoning surface. `command -v zstd` runs only after a successful+ // `mkdir -p`, and always reports success itself (`|| true`), so a sandbox with no+ // `zstd` binary never fails the mkdir step — it only fails closed on compression+ // eligibility below.const mkdirCommand = [...parentDirs].map((dir) => `mkdir -p ${shellQuote(dir)}`).join(" && ");- // `ensureDirectory` span: `mkdir -p` — ensure a directory exists before a write.- await withProviderSpan({+ const mkdirAndProbeCommand = [+ mkdirCommand,+ `&& { command -v zstd >/dev/null 2>&1 && echo ${ZSTD_PROBE_MARKER} || true; }`,+ ].join(" ");+ // `ensureDirectory` span: `mkdir -p` (plus the zstd availability probe) —+ // ensure a directory exists before a write.+ const mkdirOutput = await withProviderSpan({name: "ensureDirectory",- run: () => assertSandboxCommandOk(sandbox, mkdirCommand, timeoutSeconds, "syncIn mkdir"),+ run: () => assertSandboxCommandOkWithOutput(sandbox, mkdirAndProbeCommand, timeoutSeconds, "syncIn mkdir"),});guardRoundTrips += 1;+ // An absent or unexpected probe answer fails closed: no compression, byte-+ // identical to a sandbox that has no `zstd` binary.+ const sandboxHasZstd = mkdirOutput.includes(ZSTD_PROBE_MARKER);// Defense-in-depth beyond the lexical `assertConfinedSandboxPath`: a sandbox// can replace a target parent with a symlink to `/etc` so the string check@@ -527,9 +687,87 @@ async function syncInFileMappings(input: {});guardRoundTrips += 1;- // A failed upload or a mid-batch `mv -f` failure leaves reserved temps (some- // targets promoted, others not) — sweep every staged temp on any error so a- // retry never accumulates stale `.paperclip-upload-*` scratch.+ // Host-side compression, gated on the probe AND a runtime feature check (a+ // declared `engines.node` floor is an assumption, not a guarantee — always+ // feature-detect). Every candidate at or above `ZSTD_MIN_SOURCE_BYTES` is+ // compressed on the host with `node:zlib` at level 3, streamed so the whole+ // file never buffers in memory. A candidate that throws, or whose saving+ // misses `ZSTD_MIN_SAVING_RATIO`, falls back to the raw path — a fallback is+ // never an error, it reproduces the present behavior exactly.+ const compressCandidates = plans.filter((plan) => plan.sourceSize >= ZSTD_MIN_SOURCE_BYTES);+ if (sandboxHasZstd && isZstdCompressionSupported() && compressCandidates.length > 0) {+ let compressBytesIn = 0;+ let compressBytesOut = 0;+ await withProviderSpan({+ name: "compress",+ wallMsAttr: SPAN_ATTR.transferCompressionWallMs,+ attributes: { [SPAN_ATTR.transferCompressionCodec]: "zstd" },+ run: async (span: PluginSpan) => {+ for (const plan of compressCandidates) {+ let hostTempDir: string | null = null;+ try {+ const compressed = await compressFileToHostTemp(plan.mapping.sourcePath);+ hostTempDir = compressed.dir;+ compressBytesIn += plan.sourceSize;+ compressBytesOut += compressed.bytesOut;+ const savingRatio = 1 - compressed.bytesOut / plan.sourceSize;+ if (savingRatio < ZSTD_MIN_SAVING_RATIO) {+ await fs.rm(compressed.dir, { recursive: true, force: true }).catch(() => undefined);+ continue;+ }+ plan.compressed = {+ zstdScratch: path.posix.join(remoteDir, scratchName(".zst")),+ hostTempDir: compressed.dir,+ hostTempPath: compressed.path,+ };+ } catch {+ // Host compression failed for this candidate — fall back to the raw+ // path for it. Never fail the whole sync over a compression error.+ if (hostTempDir) await fs.rm(hostTempDir, { recursive: true, force: true }).catch(() => undefined);+ }+ }+ span.setAttribute(SPAN_ATTR.transferCompressionBytesIn, compressBytesIn);+ span.setAttribute(SPAN_ATTR.transferCompressionBytesOut, compressBytesOut);+ },+ });+ }++ const uploads: FileUpload[] = [];+ const modeApplies: { temp: string; mode: number }[] = [];+ for (const plan of plans) {+ if (plan.compressed) {+ // Upload ONLY the `.zst` file. The host never creates the raw scratch+ // name — the in-sandbox decompression step below does (C1).+ uploads.push({ source: plan.compressed.hostTempPath, destination: plan.compressed.zstdScratch });+ } else {+ uploads.push({ source: plan.mapping.sourcePath, destination: plan.rawScratch });+ if (typeof plan.mapping.mode === "number") {+ modeApplies.push({ temp: plan.rawScratch, mode: plan.mapping.mode });+ }+ }+ }+ const hasCompressedMapping = plans.some((plan) => plan.compressed !== null);+ // Every reserved scratch name in this batch (raw + `.zst`), for the failure+ // sweep below. A compressed mapping reserves two names; a raw mapping one.+ const allScratchNames = plans.flatMap((plan) =>+ plan.compressed ? [plan.rawScratch, plan.compressed.zstdScratch] : [plan.rawScratch],+ );+ const compressedPlans = plans.filter(+ (plan): plan is FileMappingPlan & { compressed: NonNullable<FileMappingPlan["compressed"]> } =>+ plan.compressed !== null,+ );+ const hostTempDirs = compressedPlans.map((plan) => plan.compressed.hostTempDir);+ // The `.zst` scratch names for compressed mappings. The bounded post-success+ // sweep below uses this list. It excludes the raw scratch names, because the+ // promote script's own rename already consumes them.+ const compressedZstdScratchNames = compressedPlans.map((plan) => plan.compressed.zstdScratch);++ // A failed upload or a mid-batch `mv -f`/decompress failure leaves reserved+ // scratch (some targets promoted, others not) — sweep every reserved name on+ // any error so a retry never accumulates stale `.paperclip-upload-*` scratch.+ // The private host temp directory is removed in `finally` regardless of+ // outcome (C2's "no temp remains after success or failure" applies host-side+ // too).try {// One batched bulk upload (single /files/bulk-upload) for all file mappings.// `transfer` span: the real byte upload — `sandbox.fs.uploadFiles`.@@ -543,14 +781,15 @@ async function syncInFileMappings(input: {run: () => sandbox.fs.uploadFiles(uploads, timeoutSeconds),});- // Apply the requested mode on the temp file BEFORE the rename so the target- // never appears at a widened window — a secret lands `0600` at targetPath from- // the instant it exists there.+ // Apply the requested mode on the RAW mapping's temp file BEFORE the rename+ // so the target never appears at a widened window. A compressed mapping's+ // raw scratch does not exist yet at this point — its mode (if any) is+ // applied inside the promotion script below, on the safe raw scratch (C3).for (const apply of modeApplies) {await sandbox.fs.setFilePermissions(apply.temp, { mode: toOctalModeString(apply.mode) });}- // Promote every staged temp onto its final target. The `mv -f` traverses the+ // Promote every mapping onto its final target. The `mv -f` traverses the// target's PARENT dir, which is sandbox-writable and could be swapped for a// symlink after the earlier parent guard ran but before the rename opens it —// redirecting the promotion outside the root. Bind the confinement re-check and@@ -568,24 +807,79 @@ async function syncInFileMappings(input: {// - open→rename: `mv` targets `/proc/self/fd/8/<base>`, which resolves through// the already-open inode rather than the path string, so the rename lands in// the verified directory even if the path is repointed mid-command.+ //+ // A compressed mapping runs a decompression block, in the SAME `sh -c`+ // script, immediately before its own fd-pinned promote block (C1–C3):+ // - `umask 077` + `set -C` (POSIX noclobber) scoped to a subshell, then+ // `exec 9> rawScratch` — an atomic exclusive create: `set -C` opens+ // with `O_CREAT|O_EXCL`, which fails on any EXISTING name, including a+ // symlink (dangling or not), because `O_EXCL` fails on the name's own+ // lstat and never opens through it. The tests in this package verify+ // this for the shells and the platform under test; it is not a claim+ // of a portable `O_NOFOLLOW` guarantee across every POSIX shell. This+ // is the retained descriptor C1 requires — never a separate+ // existence/symlink test.+ // - `zstd -d -c` writes into that retained descriptor (`>&9`), so the+ // decompressed bytes land in the pinned inode even if the pathname is+ // fought over mid-command.+ // - the mapping's `mode`, if set, is applied through `/proc/self/fd/9`+ // (the still-open descriptor) — never by reopening the pathname —+ // before the descriptor closes (C3). `umask 077` also means a mapping+ // with NO explicit mode still never appears wider than `0600` in the+ // window between create and the (absent) chmod.+ // - a subshell failure at any step exits non-zero without reaching the+ // `mv` (C2); the decompressed name is a reserved DIRECT child of+ // `remoteDir`, matching the guarantee the raw path already has for its+ // scratch name.+ // Only after the decompression block succeeds does the existing fd-pinned+ // promote block run — unchanged — for every mapping, compressed or raw.const renameScript = [...canonicalizerPreamble(shellQuote(remoteDir))];- for (const rename of renames) {- const parentDir = path.posix.dirname(rename.target);- const base = path.posix.basename(rename.target);+ for (const plan of plans) {+ const parentDir = plan.dir;+ const base = path.posix.basename(plan.mapping.targetPath);+ if (plan.compressed) {+ const modeCommand =+ typeof plan.mapping.mode === "number"+ ? `chmod ${toOctalModeString(plan.mapping.mode)} /proc/self/fd/9 || { echo "chmod failed"; exit 50; };`+ : "";+ renameScript.push(+ "(",+ "umask 077;",+ "set -C;",+ `exec 9> ${shellQuote(plan.rawScratch)} || { echo "raw scratch create failed"; exit 48; };`,+ `zstd -d -c -- ${shellQuote(plan.compressed.zstdScratch)} >&9 || { echo "decompress failed"; exit 49; };`,+ modeCommand,+ "exec 9>&-;",+ ") || exit $?;",+ );+ }renameScript.push(`_pc_tgt_dir=$(_pc_resolve ${shellQuote(parentDir)}) || { echo "ESCAPE"; exit 42; };`,`case "$_pc_tgt_dir/" in "$_pc_root"/*) : ;; *) echo "ESCAPE"; exit 42 ;; esac;`,`exec 8<"$_pc_tgt_dir" || { echo "open failed"; exit 47; };`,`_pc_fd_dir=$(_pc_resolve /proc/self/fd/8) || { echo "ESCAPE"; exit 42; };`,`case "$_pc_fd_dir/" in "$_pc_root"/*) : ;; *) echo "ESCAPE"; exit 42 ;; esac;`,- `mv -f ${shellQuote(rename.temp)} /proc/self/fd/8/${shellQuote(base)} || { echo "rename failed"; exit 43; };`,+ `mv -f ${shellQuote(plan.rawScratch)} /proc/self/fd/8/${shellQuote(base)} || { echo "rename failed"; exit 43; };`,`exec 8>&-;`,);+ if (plan.compressed) {+ // Clean up the `.zst` scratch after a successful promotion (C2/step 7).+ // `|| true` keeps a cleanup failure from becoming the promote script's+ // own exit status — every target file is already in place by this+ // point, so a stray `.zst` scratch must never read back as a sync+ // failure.+ renameScript.push(`rm -f ${shellQuote(plan.compressed.zstdScratch)} || true;`);+ }}// `promote` span: atomically move the staged temp onto its target via a- // pinned dir handle.+ // pinned dir handle. When this batch decompressed at least one mapping,+ // this span also carries `transfer.decompress.wall_ms`. That value+ // measures the WHOLE promote command — the canonicalizer preamble, every+ // decompression, and every `mv` — not decompression alone. Treat it as an+ // upper bound on the decompress wall time, not an exact measurement.await withProviderSpan({name: "promote",+ wallMsAttr: hasCompressedMapping ? SPAN_ATTR.transferDecompressWallMs : undefined,run: () =>assertSandboxCommandOk(sandbox,@@ -595,8 +889,24 @@ async function syncInFileMappings(input: {),});} catch (error) {- await removeSandboxScratch(sandbox, renames.map((rename) => rename.temp), timeoutSeconds);+ await removeSandboxScratch(sandbox, allScratchNames, timeoutSeconds);throw error;+ } finally {+ await Promise.all(+ hostTempDirs.map((dir) => fs.rm(dir, { recursive: true, force: true }).catch(() => undefined)),+ );+ }++ // Every target is already promoted at this point. Give the promote+ // script's own `.zst` cleanup (`|| true`) one more, separate try.+ // Log a count, never a path, when a leftover survives both tries.+ if (compressedZstdScratchNames.length > 0) {+ const leftoverCount = await sweepZstdScratchAfterSuccess(sandbox, compressedZstdScratchNames, timeoutSeconds);+ if (leftoverCount > 0) {+ console.warn(+ `Daytona zstd transport compression: ${leftoverCount} post-promotion scratch file(s) could not be removed after two attempts. The already-promoted target file(s) are unaffected.`,+ );+ }}return { filesTransferred: mappings.length, bytesTransferred };