@microvac/plugin-daytona 0.0.0-stage → 0.1.0-rc.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +98 -2
  2. package/dist/archive-stream-window.test.d.ts +2 -0
  3. package/dist/archive-stream-window.test.d.ts.map +1 -0
  4. package/dist/archive-stream-window.test.js +93 -0
  5. package/dist/archive-stream-window.test.js.map +1 -0
  6. package/dist/archive-stream.d.ts +10 -0
  7. package/dist/archive-stream.d.ts.map +1 -0
  8. package/dist/archive-stream.js +159 -0
  9. package/dist/archive-stream.js.map +1 -0
  10. package/dist/archive-stream.test.d.ts +2 -0
  11. package/dist/archive-stream.test.d.ts.map +1 -0
  12. package/dist/archive-stream.test.js +121 -0
  13. package/dist/archive-stream.test.js.map +1 -0
  14. package/dist/duplex-close-deadline.test.d.ts +2 -0
  15. package/dist/duplex-close-deadline.test.d.ts.map +1 -0
  16. package/dist/duplex-close-deadline.test.js +106 -0
  17. package/dist/duplex-close-deadline.test.js.map +1 -0
  18. package/dist/duplex-command-stream.d.ts +98 -0
  19. package/dist/duplex-command-stream.d.ts.map +1 -0
  20. package/dist/duplex-command-stream.js +218 -0
  21. package/dist/duplex-command-stream.js.map +1 -0
  22. package/dist/duplex-command-stream.live.test.d.ts +2 -0
  23. package/dist/duplex-command-stream.live.test.d.ts.map +1 -0
  24. package/dist/duplex-command-stream.live.test.js +324 -0
  25. package/dist/duplex-command-stream.live.test.js.map +1 -0
  26. package/dist/duplex-command-stream.test.d.ts +2 -0
  27. package/dist/duplex-command-stream.test.d.ts.map +1 -0
  28. package/dist/duplex-command-stream.test.js +519 -0
  29. package/dist/duplex-command-stream.test.js.map +1 -0
  30. package/dist/file-sync-capacity.live.test.d.ts +2 -0
  31. package/dist/file-sync-capacity.live.test.d.ts.map +1 -0
  32. package/dist/file-sync-capacity.live.test.js +122 -0
  33. package/dist/file-sync-capacity.live.test.js.map +1 -0
  34. package/dist/file-sync-capacity.test.d.ts +2 -0
  35. package/dist/file-sync-capacity.test.d.ts.map +1 -0
  36. package/dist/file-sync-capacity.test.js +337 -0
  37. package/dist/file-sync-capacity.test.js.map +1 -0
  38. package/dist/file-sync-diagnostics.test.d.ts +2 -0
  39. package/dist/file-sync-diagnostics.test.d.ts.map +1 -0
  40. package/dist/file-sync-diagnostics.test.js +165 -0
  41. package/dist/file-sync-diagnostics.test.js.map +1 -0
  42. package/dist/file-sync.d.ts +80 -0
  43. package/dist/file-sync.d.ts.map +1 -0
  44. package/dist/file-sync.js +1362 -0
  45. package/dist/file-sync.js.map +1 -0
  46. package/dist/file-sync.test.d.ts +2 -0
  47. package/dist/file-sync.test.d.ts.map +1 -0
  48. package/dist/file-sync.test.js +1214 -0
  49. package/dist/file-sync.test.js.map +1 -0
  50. package/dist/idle-activity.d.ts +40 -0
  51. package/dist/idle-activity.d.ts.map +1 -0
  52. package/dist/idle-activity.js +145 -0
  53. package/dist/idle-activity.js.map +1 -0
  54. package/dist/idle-activity.test.d.ts +2 -0
  55. package/dist/idle-activity.test.d.ts.map +1 -0
  56. package/dist/idle-activity.test.js +159 -0
  57. package/dist/idle-activity.test.js.map +1 -0
  58. package/dist/index.d.ts +3 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +3 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/lease-tracing.d.ts +7 -0
  63. package/dist/lease-tracing.d.ts.map +1 -0
  64. package/dist/lease-tracing.js +31 -0
  65. package/dist/lease-tracing.js.map +1 -0
  66. package/dist/lease-tracing.test.d.ts +2 -0
  67. package/dist/lease-tracing.test.d.ts.map +1 -0
  68. package/dist/lease-tracing.test.js +298 -0
  69. package/dist/lease-tracing.test.js.map +1 -0
  70. package/dist/login-pty.d.ts +162 -0
  71. package/dist/login-pty.d.ts.map +1 -0
  72. package/dist/login-pty.js +258 -0
  73. package/dist/login-pty.js.map +1 -0
  74. package/dist/login-pty.test.d.ts +2 -0
  75. package/dist/login-pty.test.d.ts.map +1 -0
  76. package/dist/login-pty.test.js +319 -0
  77. package/dist/login-pty.test.js.map +1 -0
  78. package/dist/manifest.d.ts +5 -0
  79. package/dist/manifest.d.ts.map +1 -0
  80. package/dist/manifest.js +189 -0
  81. package/dist/manifest.js.map +1 -0
  82. package/dist/one-shot-exec-deadline.test.d.ts +2 -0
  83. package/dist/one-shot-exec-deadline.test.d.ts.map +1 -0
  84. package/dist/one-shot-exec-deadline.test.js +73 -0
  85. package/dist/one-shot-exec-deadline.test.js.map +1 -0
  86. package/dist/plugin.d.ts +103 -0
  87. package/dist/plugin.d.ts.map +1 -0
  88. package/dist/plugin.js +3572 -0
  89. package/dist/plugin.js.map +1 -0
  90. package/dist/plugin.test.d.ts +2 -0
  91. package/dist/plugin.test.d.ts.map +1 -0
  92. package/dist/plugin.test.js +7276 -0
  93. package/dist/plugin.test.js.map +1 -0
  94. package/dist/pty-chunked-input.d.ts +48 -0
  95. package/dist/pty-chunked-input.d.ts.map +1 -0
  96. package/dist/pty-chunked-input.js +74 -0
  97. package/dist/pty-chunked-input.js.map +1 -0
  98. package/dist/pty-chunked-input.test.d.ts +2 -0
  99. package/dist/pty-chunked-input.test.d.ts.map +1 -0
  100. package/dist/pty-chunked-input.test.js +115 -0
  101. package/dist/pty-chunked-input.test.js.map +1 -0
  102. package/dist/runner-ingress.sdk-integration.d.ts +2 -0
  103. package/dist/runner-ingress.sdk-integration.d.ts.map +1 -0
  104. package/dist/runner-ingress.sdk-integration.js +87 -0
  105. package/dist/runner-ingress.sdk-integration.js.map +1 -0
  106. package/dist/session-command-completion.test.d.ts +2 -0
  107. package/dist/session-command-completion.test.d.ts.map +1 -0
  108. package/dist/session-command-completion.test.js +251 -0
  109. package/dist/session-command-completion.test.js.map +1 -0
  110. package/dist/session-stream-exit.d.ts +13 -0
  111. package/dist/session-stream-exit.d.ts.map +1 -0
  112. package/dist/session-stream-exit.js +48 -0
  113. package/dist/session-stream-exit.js.map +1 -0
  114. package/dist/tar-listing.test.d.ts +2 -0
  115. package/dist/tar-listing.test.d.ts.map +1 -0
  116. package/dist/tar-listing.test.js +220 -0
  117. package/dist/tar-listing.test.js.map +1 -0
  118. package/dist/worker.d.ts +3 -0
  119. package/dist/worker.d.ts.map +1 -0
  120. package/dist/worker.js +5 -0
  121. package/dist/worker.js.map +1 -0
  122. package/package.json +42 -4
@@ -0,0 +1,1362 @@
1
+ import path from "node:path";
2
+ import os from "node:os";
3
+ import { promises as fs, createReadStream, createWriteStream } from "node:fs";
4
+ import { randomUUID } from "node:crypto";
5
+ import { execFile, spawn } from "node:child_process";
6
+ import { promisify } from "node:util";
7
+ import zlib from "node:zlib";
8
+ import { pipeline } from "node:stream/promises";
9
+ import { recordEnvironmentSyncError, withEnvironmentSyncTransferStep } from "@paperclipai/plugin-sdk";
10
+ import { getPluginTracer } from "./plugin.js";
11
+ import { streamSandboxArchive } from "./archive-stream.js";
12
+ const execFileAsync = promisify(execFile);
13
+ // The span-attribute names. They mirror the host span-attribute contract by
14
+ // value. The plugin ships bundled, so it stays free of the host packages and
15
+ // repeats these strings; the host re-clamps a provider span by these exact keys.
16
+ const SPAN_ATTR_PREFIX = "paperclip.sandbox.startup.";
17
+ const SPAN_ATTR = {
18
+ provider: `${SPAN_ATTR_PREFIX}provider`,
19
+ packWallMs: `${SPAN_ATTR_PREFIX}pack.wall_ms`,
20
+ transferWallMs: `${SPAN_ATTR_PREFIX}transfer.wall_ms`,
21
+ transferGuardCount: `${SPAN_ATTR_PREFIX}transfer.guard.count`,
22
+ // The transfer direction: `inbound` for an upload to the sandbox, `outbound`
23
+ // for a download from the sandbox. Operation identity comes from the parent
24
+ // span, so the transfer span never carries an operation label.
25
+ transferDirection: `${SPAN_ATTR_PREFIX}transfer.direction`,
26
+ // The five transport-compression attributes. Values are a closed codec
27
+ // set (`zstd`, `gzip`) or a finite number — never a path, a command line, file content, a
28
+ // raw identifier, or error text.
29
+ transferCompressionCodec: `${SPAN_ATTR_PREFIX}transfer.compression.codec`,
30
+ transferCompressionWallMs: `${SPAN_ATTR_PREFIX}transfer.compression.wall_ms`,
31
+ transferCompressionBytesIn: `${SPAN_ATTR_PREFIX}transfer.compression.bytes_in`,
32
+ transferCompressionBytesOut: `${SPAN_ATTR_PREFIX}transfer.compression.bytes_out`,
33
+ transferDecompressWallMs: `${SPAN_ATTR_PREFIX}transfer.decompress.wall_ms`,
34
+ };
35
+ /** The value of `SpanStatusCode.ERROR` in `@opentelemetry/api`. The plugin stays
36
+ * OpenTelemetry-free, so it uses the numeric value directly. */
37
+ const SPAN_STATUS_CODE_ERROR = 2;
38
+ /**
39
+ * Run one span-wrapped step through the plugin tracer. The pack step, the
40
+ * transfer step, and each command round trip share this helper. It seeds the
41
+ * provider family, runs the step, marks a thrown step failed, and always ends
42
+ * the span. The host records the span with its true wall-clock width from the
43
+ * worker timestamps, so the span shows real time in the trace. The tracer is a
44
+ * no-op until the host injects a live tracer, so the span never changes the sync
45
+ * control flow.
46
+ *
47
+ * `wallMsAttr` is optional. The `pack` and `transfer` spans pass it to keep
48
+ * their existing `*.wall_ms` attribute. A per-round-trip span omits it, so it
49
+ * carries no `*.wall_ms` attribute and relies on the native span width.
50
+ *
51
+ * `run` receives the live span, so a caller that needs to record an attribute
52
+ * only known after the step completes (for example the compression byte
53
+ * counts) can call `span.setAttribute` directly, without a second span.
54
+ */
55
+ export async function withProviderSpan(input) {
56
+ const span = getPluginTracer().startSpan(input.name, {
57
+ attributes: { [SPAN_ATTR.provider]: "daytona", ...(input.attributes ?? {}) },
58
+ });
59
+ const startedAtMs = Date.now();
60
+ try {
61
+ return await input.run(span);
62
+ }
63
+ catch (error) {
64
+ span.setStatus({ code: SPAN_STATUS_CODE_ERROR });
65
+ throw error;
66
+ }
67
+ finally {
68
+ if (input.wallMsAttr)
69
+ span.setAttribute(input.wallMsAttr, Date.now() - startedAtMs);
70
+ span.end();
71
+ }
72
+ }
73
+ /** Convert a millisecond timeout to the whole-seconds value the Daytona SDK expects. */
74
+ function toTimeoutSeconds(timeoutMs) {
75
+ return Math.max(1, Math.ceil(timeoutMs / 1000));
76
+ }
77
+ // Reserved scratch-name stem for staged uploads/downloads and remote tarballs.
78
+ // The runtime's base64 fallback stages to `<path>.paperclip-upload`; the native
79
+ // transport reuses the same reserved prefix so a provider temp never collides
80
+ // with a real target or with the fallback's scratch name.
81
+ const SCRATCH_PREFIX = ".paperclip-upload";
82
+ function scratchName(suffix = "") {
83
+ return `${SCRATCH_PREFIX}-${randomUUID()}${suffix}`;
84
+ }
85
+ /**
86
+ * Single-quote a path for safe interpolation into a sandbox shell command. Every
87
+ * path handed to `sandbox.process.executeCommand` (tar extract / `mv -f` rename)
88
+ * MUST pass through this so a path containing shell metacharacters is transferred
89
+ * literally, never interpreted.
90
+ */
91
+ function shellQuote(value) {
92
+ return `'${value.replace(/'/g, `'"'"'`)}'`;
93
+ }
94
+ /**
95
+ * Convert a POSIX numeric mode (e.g. `0o600`) to the octal string the Daytona
96
+ * SDK's `setFilePermissions` expects (e.g. `"600"`), masked to the permission
97
+ * bits so an accidental type flag never widens the mode.
98
+ */
99
+ function toOctalModeString(mode) {
100
+ return (mode & 0o7777).toString(8).padStart(3, "0");
101
+ }
102
+ /**
103
+ * Host-side complete-mediation guard applied as defense-in-depth below the
104
+ * orchestrator's own confinement. Every sandbox-side path (the sync target for
105
+ * inbound, the sync source for outbound) MUST canonicalize inside the workspace
106
+ * remote dir; absolute escapes and `..` traversal are rejected fail-closed before
107
+ * any bytes move. Sandbox paths on the server are POSIX.
108
+ */
109
+ export function assertConfinedSandboxPath(remoteDir, candidate, label) {
110
+ const normalizedRoot = path.posix.normalize(remoteDir);
111
+ const normalized = path.posix.normalize(candidate);
112
+ if (!path.posix.isAbsolute(normalized) ||
113
+ normalized === ".." ||
114
+ normalized.includes("/../") ||
115
+ normalized.endsWith("/..")) {
116
+ throw new Error(`Daytona sync ${label} path is not a confined absolute path: ${candidate}`);
117
+ }
118
+ const prefix = normalizedRoot.endsWith("/") ? normalizedRoot : `${normalizedRoot}/`;
119
+ if (normalized !== normalizedRoot && !normalized.startsWith(prefix)) {
120
+ throw new Error(`Daytona sync ${label} path escapes the workspace remote dir: ${candidate}`);
121
+ }
122
+ }
123
+ async function withHostTempDir(fn) {
124
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-daytona-sync-"));
125
+ try {
126
+ return await fn(dir);
127
+ }
128
+ finally {
129
+ await fs.rm(dir, { recursive: true, force: true }).catch(() => undefined);
130
+ }
131
+ }
132
+ /**
133
+ * Build a host-side gzip-compressed tarball of a directory, mirroring the runtime's own
134
+ * `createTarballFromDirectory`: archive top-level entries by name (no "." self
135
+ * entry), suppress AppleDouble/xattr sidecars, honor `exclude`, and reproduce the
136
+ * `followSymlinks` → `-h` mapping so the native path is observationally identical
137
+ * to the base64 fallback's tar.
138
+ */
139
+ async function createHostTarball(input) {
140
+ const excludeArgs = ["._*", ...(input.exclude ?? [])].flatMap((entry) => ["--exclude", entry]);
141
+ const entries = (await fs.readdir(input.localDir)).sort((left, right) => left.localeCompare(right));
142
+ if (entries.length === 0) {
143
+ // An empty source is valid (blank workspace / empty asset dir). Write a valid
144
+ // gzip-compressed empty tar (1024-byte zero EOF marker) so extraction is a
145
+ // clean no-op and uses the same transport as non-empty directories.
146
+ await fs.writeFile(input.archivePath, await new Promise((resolve, reject) => {
147
+ zlib.gzip(Buffer.alloc(1024), (error, compressed) => error ? reject(error) : resolve(compressed));
148
+ }));
149
+ return;
150
+ }
151
+ await execFileAsync("tar", [
152
+ "-cz",
153
+ "--no-xattrs",
154
+ ...(input.followSymlinks ? ["-h"] : []),
155
+ "-f",
156
+ input.archivePath,
157
+ "-C",
158
+ input.localDir,
159
+ ...excludeArgs,
160
+ "--",
161
+ ...entries,
162
+ ], { env: { ...process.env, COPYFILE_DISABLE: "1" }, maxBuffer: 32 * 1024 * 1024 });
163
+ }
164
+ /**
165
+ * True when `relative` (a POSIX path) escapes its anchoring directory once
166
+ * normalized: an absolute path, `..`, or a `..`-leading traversal all break out.
167
+ */
168
+ function posixPathEscapes(relative) {
169
+ const normalized = path.posix.normalize(relative);
170
+ return normalized === ".." || normalized.startsWith("../") || path.posix.isAbsolute(normalized);
171
+ }
172
+ /**
173
+ * Parse one `tar -tvf` verbose listing line into its leading type flag and the
174
+ * trailing name-and-link-target field. The listing dialect depends on which tar
175
+ * the host ships: GNU/busybox emit
176
+ * `<perms> <owner>/<group> <size> <date> <time> <rest>`, while bsdtar
177
+ * (libarchive — the system tar on macOS) emits the ls-style
178
+ * `<perms> <links> <user> <group> <size> <Mon> <day> <time|year> <rest>`.
179
+ * The second field disambiguates: GNU always slash-joins owner/group, bsdtar
180
+ * puts a pure-digit link count there, so no line satisfies both shapes — the
181
+ * slash requirement is load-bearing, since a bsdtar line with numeric uid/gid
182
+ * would otherwise match the GNU shape shifted, hiding traversal in `<rest>`.
183
+ * Entries whose size column is not a plain byte count (e.g. a device node's
184
+ * `major,minor`) match neither shape. Returns null when nothing matches so
185
+ * callers can fail closed.
186
+ */
187
+ export function parseTarVerboseListingLine(line) {
188
+ const gnu = line.match(/^(\S+)\s+\S+\/\S+\s+\d+\s+\S+\s+\S+\s+(.*)$/);
189
+ if (gnu)
190
+ return { typeFlag: gnu[1][0], rest: gnu[2] };
191
+ const bsd = line.match(/^(\S+)\s+\d+\s+\S+\s+\S+\s+\d+\s+\S+\s+\d{1,2}\s+(?:\d{4}|\d{1,2}:\d{2}(?::\d{2})?)\s+(.*)$/);
192
+ if (bsd)
193
+ return { typeFlag: bsd[1][0], rest: bsd[2] };
194
+ return null;
195
+ }
196
+ /**
197
+ * Split a verbose-listing link field (`<name><delimiter><target>`) exactly
198
+ * once. The sandbox controls both halves, so a field with zero or multiple
199
+ * delimiter occurrences is unresolvable: a link name that itself contains the
200
+ * delimiter shifts the split point, and taking the first (or last) occurrence
201
+ * would let a crafted name or target hide an escaping link target from the
202
+ * confinement check. Returns null so callers fail closed.
203
+ */
204
+ export function splitLinkEntryOnce(field, delimiter) {
205
+ const first = field.indexOf(delimiter);
206
+ if (first === -1)
207
+ return null;
208
+ if (field.indexOf(delimiter, first + delimiter.length) !== -1)
209
+ return null;
210
+ return { name: field.slice(0, first), target: field.slice(first + delimiter.length) };
211
+ }
212
+ /**
213
+ * Reject a sandbox-authored tarball before extraction if any member would land
214
+ * outside the extraction dir. The archive is produced by the (untrusted) sandbox,
215
+ * so `tar -xf` on the host must never be handed an archive whose entries carry
216
+ * absolute paths or `../` traversal, nor a symlink/hardlink member whose target
217
+ * escapes the tree — the latter would let a follow-up member be written through
218
+ * the link to an arbitrary host path. Legitimate in-tree relative links (targets
219
+ * that resolve back inside the archive, e.g. `shortcut -> nested/data.txt`) are
220
+ * preserved. Parses the `-tvf` verbose listing so both member names and link
221
+ * targets are inspected; any unparseable line fails closed.
222
+ */
223
+ class UnsafeOutboundArchiveError extends Error {
224
+ }
225
+ function assertTarListingLineConfined(line, rejectSpecialModes = false) {
226
+ if (line.trim().length === 0)
227
+ return;
228
+ const parsed = parseTarVerboseListingLine(line);
229
+ if (!parsed) {
230
+ throw new UnsafeOutboundArchiveError(`Daytona syncOut refusing tarball with an unparseable entry listing: ${line}`);
231
+ }
232
+ // Source preservation promises ordinary 0777 permissions, not host special
233
+ // execution bits. Refuse before extraction; this must not trigger link repair.
234
+ if (rejectSpecialModes && /[sStT]/.test(line.trimStart().slice(0, 10))) {
235
+ throw new Error("Daytona syncOut source preservation does not support special mode bits");
236
+ }
237
+ const typeFlag = parsed.typeFlag;
238
+ let name = parsed.rest;
239
+ let linkTarget = null;
240
+ if (typeFlag === "l") {
241
+ const split = splitLinkEntryOnce(name, " -> ");
242
+ if (!split)
243
+ throw new UnsafeOutboundArchiveError(`Daytona syncOut refusing unparseable or ambiguous symlink entry: ${line}`);
244
+ name = split.name;
245
+ linkTarget = split.target;
246
+ }
247
+ else if (typeFlag === "h") {
248
+ const split = splitLinkEntryOnce(name, " link to ");
249
+ if (!split)
250
+ throw new UnsafeOutboundArchiveError(`Daytona syncOut refusing unparseable or ambiguous hardlink entry: ${line}`);
251
+ name = split.name;
252
+ linkTarget = split.target;
253
+ }
254
+ const cleanName = name.replace(/\/+$/, "");
255
+ if (cleanName.length > 0 && posixPathEscapes(cleanName)) {
256
+ throw new UnsafeOutboundArchiveError(`Daytona syncOut refusing tarball member that escapes the extraction dir: ${name}`);
257
+ }
258
+ if (linkTarget !== null) {
259
+ const resolved = path.posix.join(path.posix.dirname(cleanName), linkTarget);
260
+ if (path.posix.isAbsolute(linkTarget) || posixPathEscapes(resolved)) {
261
+ throw new UnsafeOutboundArchiveError(`Daytona syncOut refusing tarball link whose target escapes the extraction dir: ${name} -> ${linkTarget}`);
262
+ }
263
+ }
264
+ }
265
+ const TAR_LISTING_MAX_LINE_BYTES = 64 * 1024;
266
+ const TAR_LISTING_MAX_STDERR_BYTES = 64 * 1024;
267
+ // Full workspace exports are larger than provider checkpoints. These quotas
268
+ // admit the supported 60k-file / 39.8 MB-name export and 145k-entry regression,
269
+ // while bounding work on untrusted metadata independently of the wall deadline.
270
+ // The byte quota matches the native workspace descriptor's 64 MiB ceiling;
271
+ // it is an admission counter, never a buffer allocation.
272
+ const TAR_LISTING_MAX_TOTAL_BYTES = 64 * 1024 * 1024;
273
+ const TAR_LISTING_MAX_ENTRIES = 250_000;
274
+ const TAR_LISTING_TIMEOUT_MS = 120_000;
275
+ export async function assertTarballEntriesConfined(archivePath, timeoutMs = TAR_LISTING_TIMEOUT_MS, rejectSpecialModes = false) {
276
+ // A valid large workspace can exceed execFile's buffer. Stream within both
277
+ // aggregate admission quotas and per-entry/diagnostic memory bounds, checking
278
+ // every entry before extraction. Keep bytes until a full line to preserve
279
+ // UTF-8 characters split across pipe chunks.
280
+ // AppleDouble interpretation must also be disabled while validating, or
281
+ // libarchive hides `._*` members that the preserving extractor will write.
282
+ const rawMacEntries = rejectSpecialModes && process.platform === "darwin"
283
+ && (await execFileAsync("tar", ["--version"])).stdout.includes("bsdtar");
284
+ const child = spawn("tar", ["-tvf", archivePath, ...(rawMacEntries ? ["--options=!mac-ext"] : [])], {
285
+ env: { ...process.env, COPYFILE_DISABLE: "1" },
286
+ stdio: ["ignore", "pipe", "pipe"],
287
+ });
288
+ let spawnError;
289
+ let failure;
290
+ let stderr = Buffer.alloc(0);
291
+ let pending = Buffer.alloc(0);
292
+ let totalBytes = 0;
293
+ let entries = 0;
294
+ const validateLine = (line) => {
295
+ // Count empty lines too, so whitespace cannot evade the parsing-work quota.
296
+ if (++entries > TAR_LISTING_MAX_ENTRIES) {
297
+ throw recordEnvironmentSyncError(new Error("Daytona syncOut tar listing entry limit exceeded (250000)"), { transferFailureKind: "listing_entry_limit" });
298
+ }
299
+ try {
300
+ assertTarListingLineConfined(line.toString("utf8"), rejectSpecialModes);
301
+ }
302
+ catch (error) {
303
+ if (error instanceof UnsafeOutboundArchiveError)
304
+ recordEnvironmentSyncError(error, { transferFailureKind: "unsafe_archive" });
305
+ throw error;
306
+ }
307
+ };
308
+ const closed = new Promise((resolve) => {
309
+ child.once("error", (error) => { spawnError = error; });
310
+ child.once("close", (code, signal) => resolve({ code, signal }));
311
+ });
312
+ const stop = (error) => {
313
+ failure ??= error;
314
+ child.kill("SIGKILL");
315
+ };
316
+ const timer = setTimeout(() => {
317
+ stop(recordEnvironmentSyncError(new Error("Daytona syncOut tar listing validation timed out"), { transferFailureKind: "listing_timeout", errorCode: "ETIMEDOUT" }));
318
+ }, Math.max(1, Math.min(timeoutMs, TAR_LISTING_TIMEOUT_MS)));
319
+ child.stderr.on("data", (chunk) => {
320
+ if (stderr.length + chunk.length > TAR_LISTING_MAX_STDERR_BYTES) {
321
+ stop(recordEnvironmentSyncError(new Error("Daytona syncOut tar listing diagnostics exceed the byte limit"), { transferFailureKind: "listing_stderr_limit" }));
322
+ return;
323
+ }
324
+ stderr = Buffer.concat([stderr, chunk]);
325
+ });
326
+ try {
327
+ for await (const chunk of child.stdout) {
328
+ if (failure)
329
+ break;
330
+ const bytes = chunk;
331
+ totalBytes += bytes.length;
332
+ if (totalBytes > TAR_LISTING_MAX_TOTAL_BYTES) {
333
+ throw recordEnvironmentSyncError(new Error("Daytona syncOut tar total listing byte limit exceeded (64 MiB)"), { transferFailureKind: "listing_byte_limit" });
334
+ }
335
+ let start = 0;
336
+ while (start < bytes.length) {
337
+ const newline = bytes.indexOf(10, start);
338
+ const end = newline < 0 ? bytes.length : newline;
339
+ if (pending.length + end - start > TAR_LISTING_MAX_LINE_BYTES) {
340
+ throw recordEnvironmentSyncError(new Error("Daytona syncOut refusing tarball with an entry listing exceeding the byte limit"), { transferFailureKind: "listing_line_limit" });
341
+ }
342
+ pending = Buffer.concat([pending, bytes.subarray(start, end)]);
343
+ if (newline < 0)
344
+ break;
345
+ validateLine(pending);
346
+ pending = Buffer.alloc(0);
347
+ start = newline + 1;
348
+ }
349
+ }
350
+ if (!failure && pending.length > 0)
351
+ validateLine(pending);
352
+ const result = await closed;
353
+ if (failure)
354
+ throw failure;
355
+ if (spawnError)
356
+ throw spawnError;
357
+ if (result.code !== 0) {
358
+ throw recordEnvironmentSyncError(new Error(`Daytona syncOut tar listing failed (${result.signal ?? result.code}): ${stderr.toString("utf8").trim()}`), {
359
+ transferFailureKind: "command_failed", exitCode: result.code ?? undefined,
360
+ });
361
+ }
362
+ }
363
+ catch (error) {
364
+ stop(error instanceof Error ? error : new Error(String(error)));
365
+ await closed;
366
+ throw failure;
367
+ }
368
+ finally {
369
+ clearTimeout(timer);
370
+ }
371
+ }
372
+ async function extractHostTarball(input) {
373
+ // The archive is sandbox-authored and untrusted: validate every member (and
374
+ // link target) is confined before letting host-side tar write a single byte.
375
+ await withEnvironmentSyncTransferStep("archive_validate", () => assertTarballEntriesConfined(input.archivePath, TAR_LISTING_TIMEOUT_MS, input.preserveSourceEntries));
376
+ await withEnvironmentSyncTransferStep("archive_extract", async () => {
377
+ await fs.mkdir(input.localDir, { recursive: true });
378
+ // macOS tar otherwise consumes source files named `._*` as AppleDouble
379
+ // metadata instead of writing their bytes. These are ordinary user entries.
380
+ // Preserve mode also ignores the host umask without adopting archive owners,
381
+ // ACLs, attributes or file flags from the sandbox.
382
+ const hostTarIsBsd = input.preserveSourceEntries
383
+ && (await execFileAsync("tar", ["--version"])).stdout.includes("bsdtar");
384
+ await execFileAsync("tar", ["-xf", input.archivePath, "-C", input.localDir,
385
+ ...(input.preserveSourceEntries ? ["-p", "--no-same-owner", "--no-acls", "--no-xattrs"] : []),
386
+ ...(hostTarIsBsd ? ["--no-fflags"] : []),
387
+ ...(hostTarIsBsd && process.platform === "darwin" ? ["--no-mac-metadata", "--options=!mac-ext"] : [])], {
388
+ env: { ...process.env, COPYFILE_DISABLE: "1" },
389
+ maxBuffer: 32 * 1024 * 1024,
390
+ });
391
+ });
392
+ }
393
+ async function countHostFiles(root, exclude) {
394
+ const excludeSet = new Set(exclude ?? []);
395
+ let total = 0;
396
+ const walk = async (dir) => {
397
+ const entries = await fs.readdir(dir, { withFileTypes: true }).catch(() => []);
398
+ for (const entry of entries) {
399
+ if (excludeSet.has(entry.name))
400
+ continue;
401
+ const full = path.join(dir, entry.name);
402
+ if (entry.isDirectory()) {
403
+ await walk(full);
404
+ }
405
+ else {
406
+ total += 1;
407
+ }
408
+ }
409
+ };
410
+ await walk(root).catch(() => undefined);
411
+ return total;
412
+ }
413
+ // Fatal causes first: tar can warn about a vanished file before the error that
414
+ // stopped it. Daytona's executeCommand result already includes stderr.
415
+ const SANDBOX_ERRNO_MESSAGES = [
416
+ ["ENOSPC", "No space left on device"],
417
+ ["EIO", "Input/output error"],
418
+ ["ENAMETOOLONG", "File name too long"],
419
+ ["EACCES", "Permission denied"],
420
+ ["EPERM", "Operation not permitted"],
421
+ ["ENOTDIR", "Not a directory"],
422
+ ["EISDIR", "Is a directory"],
423
+ ["ENOENT", "No such file or directory"],
424
+ ];
425
+ /**
426
+ * Map the strerror suffix of a failed command's output to an allowlisted errno.
427
+ * Reads only a bounded tail in memory; the output text itself is never recorded.
428
+ */
429
+ function sandboxCommandErrorCode(output) {
430
+ const lines = output.slice(-16 * 1024).split(/\r?\n/).map((line) => line.trimEnd());
431
+ for (const [code, message] of SANDBOX_ERRNO_MESSAGES) {
432
+ if (lines.some((line) => line.endsWith(`: ${message}`)))
433
+ return code;
434
+ }
435
+ return undefined;
436
+ }
437
+ /**
438
+ * Run one sandbox command and return its stdout on success. Throws the same
439
+ * shaped error as {@link assertSandboxCommandOk} on a non-zero exit. Used by
440
+ * the mkdir+zstd-probe round trip, which must read the probe's answer from
441
+ * the command's own output rather than only checking the exit code.
442
+ */
443
+ async function assertSandboxCommandOkWithOutput(sandbox, command, timeoutSeconds, label) {
444
+ const result = await sandbox.process.executeCommand(command, undefined, undefined, timeoutSeconds);
445
+ if ((result.exitCode ?? 1) !== 0) {
446
+ const detail = (result.result ?? result.artifacts?.stdout ?? "").toString().trim();
447
+ throw recordEnvironmentSyncError(new Error(`Daytona ${label} command failed (exit ${result.exitCode ?? "unknown"})${detail ? `: ${detail}` : ""}`), {
448
+ transferFailureKind: "command_failed", exitCode: result.exitCode, errorCode: sandboxCommandErrorCode(detail),
449
+ });
450
+ }
451
+ return (result.result ?? result.artifacts?.stdout ?? "").toString();
452
+ }
453
+ async function assertSandboxCommandOk(sandbox, command, timeoutSeconds, label) {
454
+ await assertSandboxCommandOkWithOutput(sandbox, command, timeoutSeconds, label);
455
+ }
456
+ // -------------------------------------------------------------
457
+ // zstd transport compression (inbound file-mapping path only)
458
+ // -------------------------------------------------------------
459
+ /** A source file below this size never compresses: the round-trip and CPU
460
+ * cost of compression is not worth it for a small file. */
461
+ const ZSTD_MIN_SOURCE_BYTES = 8 * 1024 * 1024;
462
+ /** Reject a compressed candidate whose saving is below this fraction of the
463
+ * source size (a saving under 10 percent falls back to the raw path). */
464
+ const ZSTD_MIN_SAVING_RATIO = 0.1;
465
+ /** The zstd compression level for the host-side compressor. */
466
+ const ZSTD_COMPRESSION_LEVEL = 3;
467
+ /** Marker the mkdir+probe command echoes to sandbox stdout when the sandbox
468
+ * has a `zstd` binary on `PATH`. An absent or unexpected answer fails closed
469
+ * (no compression), per the design's fallback rules. */
470
+ const ZSTD_PROBE_MARKER = "PAPERCLIP_ZSTD_AVAILABLE";
471
+ /** Marker for a `gzip` binary on `PATH`. The Daytona runner image ships gzip
472
+ * but no zstd, so gzip is the fallback codec there; without it every remote
473
+ * turn uploaded the whole uncompressed workspace seed. */
474
+ const GZIP_PROBE_MARKER = "PAPERCLIP_GZIP_AVAILABLE";
475
+ /** gzip level for the fallback codec: level 1 compresses a 220 MB repository
476
+ * tar to about 70 MB in about 1.3 s; higher levels cost far more CPU for little
477
+ * extra saving. */
478
+ const GZIP_COMPRESSION_LEVEL = 1;
479
+ /**
480
+ * Feature-detect zstd support on the running Node runtime. `node:zlib` shipped
481
+ * zstd as of Node v22.15.0 / v23.8.0, ahead of this package's declared
482
+ * `engines.node` floor, but the design directs a runtime check rather than an
483
+ * assumption from the `engines` field alone: a floor can be wrong, and this
484
+ * check costs nothing to keep in place after the floor moves.
485
+ */
486
+ function isZstdCompressionSupported() {
487
+ return typeof zlib.createZstdCompress === "function";
488
+ }
489
+ async function hasCompressedHeader(sourcePath) {
490
+ const file = await fs.open(sourcePath, "r");
491
+ try {
492
+ const header = Buffer.alloc(4);
493
+ const { bytesRead } = await file.read(header, 0, header.length, 0);
494
+ return (bytesRead === 4 && header.readUInt32LE(0) === 0xfd2fb528)
495
+ || (bytesRead >= 3 && header[0] === 0x1f && header[1] === 0x8b && header[2] === 8);
496
+ }
497
+ finally {
498
+ await file.close();
499
+ }
500
+ }
501
+ /**
502
+ * Stream-compress `sourcePath` to a new file with zstd at
503
+ * {@link ZSTD_COMPRESSION_LEVEL}, never buffering the whole file in memory.
504
+ * The compressed file lives in a private directory this function creates with
505
+ * `fs.mkdtemp` (mode `0700`), and the file itself opens with `wx` and mode
506
+ * `0600` — so the workspace content this holds is never readable by another
507
+ * local principal, unlike a bare `os.tmpdir()` file at the default `0644`.
508
+ * The caller removes the returned directory (on the accept path, after the
509
+ * upload; on every reject/error path, immediately) — this function only
510
+ * removes it on its OWN failure, so a caller never has to distinguish a
511
+ * partial directory from a finished one. The cleanup scope covers every
512
+ * step after the directory create, including the post-compression size
513
+ * stat, so a throw there does not leave the directory behind.
514
+ */
515
+ async function compressFileToHostTemp(sourcePath, codec) {
516
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), `paperclip-daytona-${codec}-`));
517
+ const tempPath = path.join(dir, codec === "zstd" ? "artifact.zst" : "artifact.gz");
518
+ try {
519
+ await pipeline(createReadStream(sourcePath), codec === "zstd"
520
+ ? zlib.createZstdCompress({ params: { [zlib.constants.ZSTD_c_compressionLevel]: ZSTD_COMPRESSION_LEVEL } })
521
+ : zlib.createGzip({ level: GZIP_COMPRESSION_LEVEL }), createWriteStream(tempPath, { flags: "wx", mode: 0o600 }));
522
+ const bytesOut = (await fs.stat(tempPath)).size;
523
+ return { dir, path: tempPath, bytesOut };
524
+ }
525
+ catch (error) {
526
+ await fs.rm(dir, { recursive: true, force: true }).catch(() => undefined);
527
+ throw error;
528
+ }
529
+ }
530
+ /**
531
+ * POSIX-sh preamble defining a `_pc_resolve` canonicalizer (prefer `realpath`,
532
+ * fall back to `readlink -f`; fail closed with exit 40 if neither exists so the
533
+ * host-side lexical check is never the only line of defense) and `_pc_root` =
534
+ * the resolved workspace remote dir. Shared by every sandbox-side symlink-escape
535
+ * guard. The caller wraps the assembled script in `sh -c` so it runs under a
536
+ * POSIX shell regardless of the sandbox's default login shell.
537
+ */
538
+ function canonicalizerPreamble(quotedRoot) {
539
+ return [
540
+ 'if command -v realpath >/dev/null 2>&1; then _pc_resolve() { realpath -- "$1"; };',
541
+ 'elif command -v readlink >/dev/null 2>&1; then _pc_resolve() { readlink -f -- "$1"; };',
542
+ 'else echo "no path canonicalizer available"; exit 40; fi;',
543
+ `_pc_root=$(_pc_resolve ${quotedRoot}) || { echo "cannot resolve root"; exit 41; };`,
544
+ ];
545
+ }
546
+ /**
547
+ * Fail-closed guard: assert that every supplied sandbox path canonicalizes
548
+ * (through symlinks) inside the workspace remote dir. The sandbox is untrusted
549
+ * relative to the host, so a sandbox-planted symlink on an inbound target parent
550
+ * or an outbound source must never widen a transfer past the confinement root.
551
+ * Runs as a single batched `sh -c` precheck: any path whose realpath escapes
552
+ * fails the whole sync (exit 42) before any bytes move. `label` distinguishes
553
+ * the inbound vs outbound call site in the surfaced error.
554
+ */
555
+ async function assertSandboxPathsConfined(input) {
556
+ const { sandbox, remoteDir, paths, timeoutSeconds, label } = input;
557
+ if (paths.length === 0)
558
+ return;
559
+ const quotedPaths = paths.map(shellQuote).join(" ");
560
+ const script = [
561
+ ...canonicalizerPreamble(shellQuote(remoteDir)),
562
+ `for _pc_p in ${quotedPaths}; do`,
563
+ ' _pc_real=$(_pc_resolve "$_pc_p") || { echo "ESCAPE:$_pc_p"; exit 42; };',
564
+ ' case "$_pc_real/" in "$_pc_root"/*) : ;; *) echo "ESCAPE:$_pc_p"; exit 42 ;; esac;',
565
+ "done",
566
+ ].join("\n");
567
+ await assertSandboxCommandOk(sandbox, `sh -c ${shellQuote(script)}`, timeoutSeconds, label);
568
+ }
569
+ /**
570
+ * Validate every outbound source AND capture a protected snapshot of it in one
571
+ * atomic sandbox-side step, then hand the snapshot paths to `downloadFiles`. This
572
+ * shrinks the TOCTOU window between validation and download to near zero: the
573
+ * guard resolves each source's realpath, confirms it is inside the remote dir,
574
+ * re-checks the resolved path is still a (non-symlink) regular file, then `cp`s
575
+ * those exact bytes to a reserved snapshot — all in a single `sh -c` invocation.
576
+ *
577
+ * Two windows are closed here:
578
+ * - validation→copy: `_pc_real` is a canonical path, so a `[ -L ]`/`[ -f ]`
579
+ * re-check immediately before `cp` refuses a source the sandbox swapped for a
580
+ * symlink (or non-regular file) after `realpath` resolved, rather than letting
581
+ * `cp` follow the swap.
582
+ * - copy→download: the privileged `downloadFiles` reads the reserved snapshot,
583
+ * which is an unguessable random name that is a DIRECT child of the resolved
584
+ * workspace root — no sandbox-swappable intermediate directory sits on the
585
+ * read path, and the sandbox cannot pre-plant a symlink at the leaf name.
586
+ *
587
+ * The sandbox-side `cp` runs at sandbox-user privilege, so its residual race
588
+ * cannot read anything that user could not already read; the confinement is
589
+ * defense-in-depth for the privileged host-mediated download. Returns the
590
+ * reserved snapshot paths, index-aligned with `sources`; the caller downloads
591
+ * and then removes them. A capacity failure returns null after cleaning partial
592
+ * copies, so the caller can read through the bounded sandbox-user stream.
593
+ *
594
+ * Accepted residual risk (copy→download leaf swap): the sandbox user runs this
595
+ * `cp`, so it knows the reserved snapshot path and could overwrite that leaf with
596
+ * different bytes after `cp` returns but before the privileged `downloadFiles`
597
+ * opens it. This is informational, not a privilege-boundary crossing: the sandbox
598
+ * user can only substitute bytes it can already produce, and the host download
599
+ * would then receive bytes that same user could equally have written into the real
600
+ * source before the snapshot ran. The swap cannot redirect the read outside the
601
+ * confinement root — the leaf is a direct child of the resolved root with no
602
+ * swappable intermediate dir, and the sandbox user cannot use it to exfiltrate any
603
+ * file it lacks read access to — so no privilege escalation is possible and the
604
+ * window is accepted rather than closed.
605
+ */
606
+ async function snapshotOutboundFileSources(input) {
607
+ const { sandbox, remoteDir, sources, timeoutSeconds } = input;
608
+ // Reserved snapshot names are a DIRECT child of remoteDir (the confinement
609
+ // root), so the privileged download leg carries no swappable intermediate dir.
610
+ const snapshots = sources.map(() => path.posix.join(remoteDir, scratchName()));
611
+ if (sources.length === 0)
612
+ return snapshots;
613
+ const lines = [...canonicalizerPreamble(shellQuote(remoteDir))];
614
+ sources.forEach((source, index) => {
615
+ const quotedSource = shellQuote(source);
616
+ const quotedSnapshot = shellQuote(snapshots[index]);
617
+ lines.push(`_pc_real=$(_pc_resolve ${quotedSource}) || { echo "ESCAPE"; exit 42; };`, `case "$_pc_real/" in "$_pc_root"/*) : ;; *) echo "ESCAPE"; exit 42 ;; esac;`,
618
+ // Close the validation→copy window: refuse a canonical path the sandbox has
619
+ // repointed to a symlink or a non-regular file since `realpath` resolved,
620
+ // so `cp` never follows a post-validation swap.
621
+ `[ -L "$_pc_real" ] && { echo "REPLACED"; exit 44; };`, `[ -f "$_pc_real" ] || { echo "NOTREG"; exit 45; };`,
622
+ // Copy the confined canonical bytes into the reserved snapshot so the
623
+ // subsequent download reads this immutable copy, not the live source.
624
+ `cp -- "$_pc_real" ${quotedSnapshot} || { echo "snapshot copy failed"; exit 43; };`);
625
+ });
626
+ try {
627
+ await assertSandboxCommandOk(sandbox, `sh -c ${shellQuote(lines.join("\n"))}`, timeoutSeconds, "outbound symlink-escape guard");
628
+ }
629
+ catch (error) {
630
+ await removeSandboxScratch(sandbox, snapshots, timeoutSeconds);
631
+ // Only the copy's capacity failure selects streaming. Canonicalization,
632
+ // confinement, permissions, and transport failures must still fail closed.
633
+ if (error instanceof Error && error.message.startsWith("Daytona outbound symlink-escape guard command failed (exit 43):")
634
+ && /No space left on device|Disk quota exceeded|File\s?size limit exceeded/i.test(error.message))
635
+ return null;
636
+ throw error;
637
+ }
638
+ return snapshots;
639
+ }
640
+ /**
641
+ * Best-effort removal of reserved sandbox-side scratch files (upload/download
642
+ * snapshots or partially promoted temps) on both the happy path and error paths,
643
+ * so a failed transfer never accumulates `.paperclip-upload-*` scratch in the
644
+ * sandbox. Swallows its own failure — cleanup must never mask the original error.
645
+ */
646
+ async function removeSandboxScratch(sandbox, paths, timeoutSeconds) {
647
+ if (paths.length === 0)
648
+ return;
649
+ const script = paths.map((entry) => `rm -f ${shellQuote(entry)}`).join(" ; ");
650
+ await sandbox.process
651
+ .executeCommand(`sh -c ${shellQuote(script)}`, undefined, undefined, timeoutSeconds)
652
+ .catch(() => undefined);
653
+ }
654
+ /**
655
+ * Try to remove each `.zst` scratch name a SECOND time, after every target in
656
+ * the batch already promoted successfully.
657
+ *
658
+ * The promote script's own cleanup (`rm -f ... || true`) already tried once.
659
+ * It never fails the sync when that cleanup fails, because a completed and
660
+ * safely promoted target must never read back as a failure.
661
+ *
662
+ * This function does not touch the promote script or its fail-closed guards.
663
+ * It runs one separate, later sandbox command that retries the removal, then
664
+ * reports how many names are still present. This makes a leftover that
665
+ * survives both tries observable instead of silent.
666
+ *
667
+ * This function runs exactly once. It is not a retry loop. It swallows its
668
+ * own command failure and reports the full count as still present — the
669
+ * same "assume the worst, never throw" contract as
670
+ * {@link removeSandboxScratch}.
671
+ */
672
+ async function sweepZstdScratchAfterSuccess(sandbox, zstdScratchNames, timeoutSeconds) {
673
+ if (zstdScratchNames.length === 0)
674
+ return 0;
675
+ const removeScript = zstdScratchNames.map((name) => `rm -f ${shellQuote(name)}`).join(" ; ");
676
+ const checkScript = zstdScratchNames.map((name) => `[ -e ${shellQuote(name)} ] && echo 1 || echo 0`).join(" ; ");
677
+ const result = await sandbox.process
678
+ .executeCommand(`sh -c ${shellQuote(`${removeScript} ; ${checkScript}`)}`, undefined, undefined, timeoutSeconds)
679
+ .catch(() => null);
680
+ if (!result)
681
+ return zstdScratchNames.length;
682
+ const output = (result.result ?? result.artifacts?.stdout ?? "").toString();
683
+ return output.split("\n").filter((line) => line.trim() === "1").length;
684
+ }
685
+ async function syncInFileMappings(input) {
686
+ const { sandbox, mappings, remoteDir, timeoutSeconds } = input;
687
+ if (mappings.length === 0)
688
+ return { filesTransferred: 0, bytesTransferred: 0 };
689
+ const parentDirs = new Set();
690
+ let bytesTransferred = 0;
691
+ const plans = [];
692
+ for (const mapping of mappings) {
693
+ parentDirs.add(path.posix.dirname(mapping.targetPath));
694
+ const sourceSize = (await fs.stat(mapping.sourcePath)).size;
695
+ bytesTransferred += sourceSize;
696
+ // Stage each upload to a reserved temp that is a DIRECT child of the workspace
697
+ // root (`remoteDir`). `remoteDir` and the target dir share the workspace
698
+ // filesystem, so the closing `mv -f` is still an atomic same-fs rename and an
699
+ // interrupted upload never leaves a truncated file at targetPath.
700
+ plans.push({ mapping, sourceSize, rawScratch: path.posix.join(remoteDir, scratchName()), compressed: null });
701
+ }
702
+ // Count the serial guard round trips before the transfer, so the transfer span
703
+ // records how much of the wall time is guard cost.
704
+ let guardRoundTrips = 0;
705
+ // Ensure every target directory exists before the bulk upload writes its temp.
706
+ // The zstd availability probe rides this SAME round trip: no new sandbox round
707
+ // trip and no availability cache — a cache at any scope would hold one
708
+ // principal's observation and reuse it for another, so probing fresh on every
709
+ // call has no poisoning surface. `command -v zstd` runs only after a successful
710
+ // `mkdir -p`, and always reports success itself (`|| true`), so a sandbox with no
711
+ // `zstd` binary never fails the mkdir step — it only fails closed on compression
712
+ // eligibility below.
713
+ const mkdirCommand = [...parentDirs].map((dir) => `mkdir -p ${shellQuote(dir)}`).join(" && ");
714
+ const mkdirAndProbeCommand = [
715
+ mkdirCommand,
716
+ `&& { command -v zstd >/dev/null 2>&1 && echo ${ZSTD_PROBE_MARKER} || true; }`,
717
+ `&& { command -v gzip >/dev/null 2>&1 && echo ${GZIP_PROBE_MARKER} || true; }`,
718
+ ].join(" ");
719
+ // `ensureDirectory` span: `mkdir -p` (plus the zstd availability probe) —
720
+ // ensure a directory exists before a write.
721
+ const mkdirOutput = await withProviderSpan({
722
+ name: "ensureDirectory",
723
+ run: () => assertSandboxCommandOkWithOutput(sandbox, mkdirAndProbeCommand, timeoutSeconds, "syncIn mkdir"),
724
+ });
725
+ guardRoundTrips += 1;
726
+ // An absent or unexpected probe answer fails closed: no compression, byte-
727
+ // identical to a sandbox that has no `zstd` binary.
728
+ const sandboxHasZstd = mkdirOutput.includes(ZSTD_PROBE_MARKER);
729
+ // Prefer zstd (faster, smaller); fall back to gzip, which every Debian image
730
+ // carries. Node always has gzip, so only zstd needs the runtime feature check.
731
+ const codec = sandboxHasZstd && isZstdCompressionSupported()
732
+ ? "zstd"
733
+ : mkdirOutput.includes(GZIP_PROBE_MARKER) ? "gzip" : null;
734
+ // Host-side compression, gated on the probe AND a runtime feature check (a
735
+ // declared `engines.node` floor is an assumption, not a guarantee — always
736
+ // feature-detect). Every candidate at or above `ZSTD_MIN_SOURCE_BYTES` is
737
+ // compressed on the host with `node:zlib` at level 3, streamed so the whole
738
+ // file never buffers in memory. A candidate that throws, or whose saving
739
+ // misses `ZSTD_MIN_SAVING_RATIO`, falls back to the raw path — a fallback is
740
+ // never an error, it reproduces the present behavior exactly.
741
+ const compressCandidates = plans.filter((plan) => plan.sourceSize >= ZSTD_MIN_SOURCE_BYTES);
742
+ if (codec && compressCandidates.length > 0) {
743
+ let compressBytesIn = 0;
744
+ let compressBytesOut = 0;
745
+ await withProviderSpan({
746
+ name: "compress",
747
+ wallMsAttr: SPAN_ATTR.transferCompressionWallMs,
748
+ attributes: { [SPAN_ATTR.transferCompressionCodec]: codec },
749
+ run: async (span) => {
750
+ for (const plan of compressCandidates) {
751
+ let hostTempDir = null;
752
+ try {
753
+ if (await hasCompressedHeader(plan.mapping.sourcePath))
754
+ continue;
755
+ const compressed = await compressFileToHostTemp(plan.mapping.sourcePath, codec);
756
+ hostTempDir = compressed.dir;
757
+ compressBytesIn += plan.sourceSize;
758
+ compressBytesOut += compressed.bytesOut;
759
+ const savingRatio = 1 - compressed.bytesOut / plan.sourceSize;
760
+ if (savingRatio < ZSTD_MIN_SAVING_RATIO) {
761
+ await fs.rm(compressed.dir, { recursive: true, force: true }).catch(() => undefined);
762
+ continue;
763
+ }
764
+ plan.compressed = {
765
+ codec,
766
+ zstdScratch: path.posix.join(remoteDir, scratchName(codec === "zstd" ? ".zst" : ".gz")),
767
+ hostTempDir: compressed.dir,
768
+ hostTempPath: compressed.path,
769
+ };
770
+ }
771
+ catch {
772
+ // Host compression failed for this candidate — fall back to the raw
773
+ // path for it. Never fail the whole sync over a compression error.
774
+ if (hostTempDir)
775
+ await fs.rm(hostTempDir, { recursive: true, force: true }).catch(() => undefined);
776
+ }
777
+ }
778
+ span.setAttribute(SPAN_ATTR.transferCompressionBytesIn, compressBytesIn);
779
+ span.setAttribute(SPAN_ATTR.transferCompressionBytesOut, compressBytesOut);
780
+ },
781
+ });
782
+ }
783
+ const uploads = [];
784
+ const modeApplies = [];
785
+ for (const plan of plans) {
786
+ if (plan.compressed) {
787
+ // Upload ONLY the `.zst` file. The host never creates the raw scratch
788
+ // name — the in-sandbox decompression step below does.
789
+ uploads.push({ source: plan.compressed.hostTempPath, destination: plan.compressed.zstdScratch });
790
+ }
791
+ else {
792
+ uploads.push({ source: plan.mapping.sourcePath, destination: plan.rawScratch });
793
+ if (typeof plan.mapping.mode === "number") {
794
+ modeApplies.push({ temp: plan.rawScratch, mode: plan.mapping.mode });
795
+ }
796
+ }
797
+ }
798
+ const hasCompressedMapping = plans.some((plan) => plan.compressed !== null);
799
+ // Every reserved scratch name in this batch (raw + `.zst`), for the failure
800
+ // sweep below. A compressed mapping reserves two names; a raw mapping one.
801
+ const allScratchNames = plans.flatMap((plan) => plan.compressed ? [plan.rawScratch, plan.compressed.zstdScratch] : [plan.rawScratch]);
802
+ const compressedPlans = plans.filter((plan) => plan.compressed !== null);
803
+ const hostTempDirs = compressedPlans.map((plan) => plan.compressed.hostTempDir);
804
+ // The `.zst` scratch names for compressed mappings. The bounded post-success
805
+ // sweep below uses this list. It excludes the raw scratch names, because the
806
+ // promote script's own rename already consumes them.
807
+ const compressedZstdScratchNames = compressedPlans.map((plan) => plan.compressed.zstdScratch);
808
+ // A failed upload or a mid-batch `mv -f`/decompress failure leaves reserved
809
+ // scratch (some targets promoted, others not) — sweep every reserved name on
810
+ // any error so a retry never accumulates stale `.paperclip-upload-*` scratch.
811
+ // The private host temp directory is removed in `finally` regardless of
812
+ // outcome — no temp remains after success or failure.
813
+ try {
814
+ // One batched bulk upload (single /files/bulk-upload) for all file mappings.
815
+ // `transfer` span: the real byte upload — `sandbox.fs.uploadFiles`.
816
+ await withProviderSpan({
817
+ name: "transfer",
818
+ wallMsAttr: SPAN_ATTR.transferWallMs,
819
+ attributes: {
820
+ [SPAN_ATTR.transferGuardCount]: guardRoundTrips,
821
+ [SPAN_ATTR.transferDirection]: "inbound",
822
+ },
823
+ run: () => sandbox.fs.uploadFiles(uploads, timeoutSeconds),
824
+ });
825
+ // Apply the requested mode on the RAW mapping's temp file BEFORE the rename
826
+ // so the target never appears at a widened window. A compressed mapping's
827
+ // raw scratch does not exist yet at this point — its mode (if any) is
828
+ // applied inside the promotion script below, on the raw scratch.
829
+ for (const apply of modeApplies) {
830
+ await sandbox.fs.setFilePermissions(apply.temp, { mode: toOctalModeString(apply.mode) });
831
+ }
832
+ // Promote every mapping onto its final target with one `mv -f` per mapping,
833
+ // atomic on the shared workspace filesystem. A compressed mapping first
834
+ // decompresses its `.zst` scratch to the raw scratch name with `zstd -d -o`,
835
+ // applies the mapping's mode (if set) with `chmod`, then removes the `.zst`
836
+ // scratch after the `mv -f` promotes the raw scratch.
837
+ const renameScript = [];
838
+ for (const plan of plans) {
839
+ if (plan.compressed) {
840
+ // `zstd -d -o` copies the mode of its INPUT (the uploaded `.zst`
841
+ // scratch) onto its output with its own `chmod` call. That call runs
842
+ // AFTER creation, so it overrides any `umask` in effect — a mapping
843
+ // with no explicit `mode` must not rely on the scratch file's mode
844
+ // being owner-only already. Always `chmod` the decompressed file
845
+ // right after decompression: to the mapping's `mode` when set, or to
846
+ // owner-only (0600) otherwise. The pre-refactor decompression step
847
+ // applied the same 0600 default. The raw (uncompressed) path above
848
+ // applies no `chmod` when the mapping sets no `mode`, so the two
849
+ // inbound branches do not use the same no-mode default today.
850
+ const targetMode = typeof plan.mapping.mode === "number" ? plan.mapping.mode : 0o600;
851
+ // gzip writes through a redirect, so the output mode comes from umask;
852
+ // the `chmod` below sets it explicitly either way.
853
+ const decompress = plan.compressed.codec === "zstd"
854
+ ? `zstd -d -o ${shellQuote(plan.rawScratch)} ${shellQuote(plan.compressed.zstdScratch)}`
855
+ : `gzip -dc -- ${shellQuote(plan.compressed.zstdScratch)} > ${shellQuote(plan.rawScratch)}`;
856
+ renameScript.push(`${decompress} || { echo "decompress failed"; exit 49; };`, `chmod ${toOctalModeString(targetMode)} ${shellQuote(plan.rawScratch)} || { echo "chmod failed"; exit 50; };`);
857
+ }
858
+ renameScript.push(`mv -f ${shellQuote(plan.rawScratch)} ${shellQuote(plan.mapping.targetPath)} || { echo "rename failed"; exit 43; };`);
859
+ if (plan.compressed) {
860
+ // Clean up the `.zst` scratch after a successful promotion. `|| true`
861
+ // keeps a cleanup failure from becoming the promote script's own exit
862
+ // status — every target file is already in place by this point, so a
863
+ // stray `.zst` scratch must never read back as a sync failure.
864
+ renameScript.push(`rm -f ${shellQuote(plan.compressed.zstdScratch)} || true;`);
865
+ }
866
+ }
867
+ // `promote` span: move the staged temp onto its target. When this batch
868
+ // decompressed at least one mapping, this span also carries
869
+ // `transfer.decompress.wall_ms`. That value measures the WHOLE promote
870
+ // command — every decompression and every `mv` — not decompression alone.
871
+ // Treat it as an upper bound on the decompress wall time, not an exact
872
+ // measurement.
873
+ await withProviderSpan({
874
+ name: "promote",
875
+ wallMsAttr: hasCompressedMapping ? SPAN_ATTR.transferDecompressWallMs : undefined,
876
+ run: () => assertSandboxCommandOk(sandbox, `sh -c ${shellQuote(renameScript.join("\n"))}`, timeoutSeconds, "syncIn rename"),
877
+ });
878
+ }
879
+ catch (error) {
880
+ await removeSandboxScratch(sandbox, allScratchNames, timeoutSeconds);
881
+ throw error;
882
+ }
883
+ finally {
884
+ await Promise.all(hostTempDirs.map((dir) => fs.rm(dir, { recursive: true, force: true }).catch(() => undefined)));
885
+ }
886
+ // Every target is already promoted at this point. Give the promote
887
+ // script's own `.zst` cleanup (`|| true`) one more, separate try.
888
+ // Log a count, never a path, when a leftover survives both tries.
889
+ if (compressedZstdScratchNames.length > 0) {
890
+ const leftoverCount = await sweepZstdScratchAfterSuccess(sandbox, compressedZstdScratchNames, timeoutSeconds);
891
+ if (leftoverCount > 0) {
892
+ console.warn(`Daytona transport compression: ${leftoverCount} post-promotion scratch file(s) could not be removed after two attempts. The already-promoted target file(s) are unaffected.`);
893
+ }
894
+ }
895
+ return { filesTransferred: mappings.length, bytesTransferred };
896
+ }
897
+ async function syncInDirectoryMapping(input) {
898
+ const { sandbox, mapping, remoteDir, timeoutSeconds } = input;
899
+ return withHostTempDir(async (tmp) => {
900
+ const archivePath = path.join(tmp, "sync-in.tar.gz");
901
+ // The pack step is host-local: it builds the tarball and makes no sandbox
902
+ // round trip. The `pack` span records its wall time.
903
+ // `pack` span: build a tarball on the host — no sandbox round trip.
904
+ await withProviderSpan({
905
+ name: "pack",
906
+ wallMsAttr: SPAN_ATTR.packWallMs,
907
+ run: () => createHostTarball({
908
+ localDir: mapping.sourcePath,
909
+ archivePath,
910
+ exclude: mapping.exclude,
911
+ followSymlinks: mapping.followSymlinks,
912
+ }),
913
+ });
914
+ const bytesTransferred = (await fs.stat(archivePath)).size;
915
+ // The tar bytes ride the native bulk channel (string source ⇒ streamed);
916
+ // only the extract/cleanup control commands use exec.
917
+ const remoteTar = path.posix.join(remoteDir, scratchName(".tar.gz"));
918
+ // Count the serial guard round trips before the transfer, so the transfer
919
+ // span records how much of the wall time is guard cost.
920
+ let guardRoundTrips = 0;
921
+ // Materialize the target dir before the upload so the extract step below has
922
+ // somewhere to write.
923
+ // `ensureDirectory` span: `mkdir -p` — ensure a directory exists before a write.
924
+ await withProviderSpan({
925
+ name: "ensureDirectory",
926
+ run: () => assertSandboxCommandOk(sandbox, `mkdir -p ${shellQuote(mapping.targetPath)}`, timeoutSeconds, "syncIn mkdir"),
927
+ });
928
+ guardRoundTrips += 1;
929
+ // The uploaded scratch tar lands at the workspace root as a reserved
930
+ // `.paperclip-upload-*` entry. The extract script below removes it only on
931
+ // success. On an upload or extract failure the scratch tar can remain, and the
932
+ // runtime workspace wipe preserves every `.paperclip-upload-*` entry, so a
933
+ // stale tar would surface in the agent workspace. Sweep the scratch on any
934
+ // failure — symmetric with the file-mapping path — so a failed sync (for
935
+ // example a referenced-project extraction) leaves no residue.
936
+ try {
937
+ // `transfer` span: the real byte upload — `sandbox.fs.uploadFiles`.
938
+ await withProviderSpan({
939
+ name: "transfer",
940
+ wallMsAttr: SPAN_ATTR.transferWallMs,
941
+ attributes: {
942
+ [SPAN_ATTR.transferGuardCount]: guardRoundTrips,
943
+ [SPAN_ATTR.transferDirection]: "inbound",
944
+ },
945
+ run: () => sandbox.fs.uploadFiles([{ source: archivePath, destination: remoteTar }], timeoutSeconds),
946
+ });
947
+ // Extract the uploaded tarball onto the already-created target directory,
948
+ // then remove the scratch tarball.
949
+ const immutable = mapping.mode !== undefined && (mapping.mode & 0o222) === 0;
950
+ const extractScript = [
951
+ // A resumed sandbox can already contain these immutable 0444/0555
952
+ // assets. Repack a private extraction as the sandbox user: tar --diff
953
+ // otherwise rejects identical bytes because the host UID/GID differ.
954
+ // Compare content and modes, never skip unverified old files. A
955
+ // recovery re-materializes the same admitted bytes on the host with
956
+ // new timestamps, so a timestamp-only difference is still a match.
957
+ // Extra user files in the target stay untouched.
958
+ ...(immutable ? [
959
+ `compare_dir=${shellQuote(`${remoteTar}.compare`)};`,
960
+ `compare_tar=${shellQuote(`${remoteTar}.normalized`)};`,
961
+ `compare_list=${shellQuote(`${remoteTar}.members`)};`,
962
+ `compare_out=${shellQuote(`${remoteTar}.differences`)};`,
963
+ 'cleanup_compare() { if [ -d "$compare_dir" ]; then find "$compare_dir" -type d -exec chmod u+w {} +; rm -rf "$compare_dir"; fi; rm -f "$compare_tar" "$compare_list" "$compare_out"; };',
964
+ "trap cleanup_compare EXIT;",
965
+ 'mkdir -m 700 "$compare_dir" || exit 43;',
966
+ `tar -xf ${shellQuote(remoteTar)} --no-same-owner --delay-directory-restore -C "$compare_dir" || exit 43;`,
967
+ '(cd "$compare_dir" && find . -mindepth 1 -maxdepth 1 -print0) > "$compare_list" || exit 43;',
968
+ 'tar -cf "$compare_tar" --format=pax -C "$compare_dir" --null -T "$compare_list" || exit 43;',
969
+ `LC_ALL=C tar -df "$compare_tar" -C ${shellQuote(mapping.targetPath)} > "$compare_out" 2>&1; compare_status=$?;`,
970
+ `if [ "$compare_status" -le 1 ] && ! grep -v ': Mod time differs$' "$compare_out" >/dev/null; then rm -f ${shellQuote(remoteTar)}; exit 0; fi;`,
971
+ "cleanup_compare;",
972
+ "trap - EXIT;",
973
+ // The old copy really differs (a changed or damaged file). Its
974
+ // read-only directories would make tar fail with "Cannot open: File
975
+ // exists", so reopen them; the extract restores the archived modes.
976
+ // Record exactly which ones were reopened so a failed repair re-seals
977
+ // only those and never touches writable user directories. A reopen
978
+ // that fails part-way (an unreadable directory) re-seals the same way.
979
+ `reopened_list=${shellQuote(`${remoteTar}.reopened`)};`,
980
+ 'reseal_reopened() { if [ -s "$reopened_list" ]; then xargs -0 chmod u-w < "$reopened_list"; fi; rm -f "$reopened_list"; };',
981
+ `find ${shellQuote(mapping.targetPath)} -mindepth 1 -type d ! -perm -u+w -print0 -exec chmod u+w {} + > "$reopened_list" || { reseal_reopened; echo "reopen failed"; exit 43; };`,
982
+ ] : []),
983
+ // BSD archives may revisit a directory after its parent's files. Keep
984
+ // GNU tar from restoring a read-only skill directory's mode before all
985
+ // of its children are extracted; final permissions remain unchanged.
986
+ // A failed repair must not leave the read-only bundle writable.
987
+ `tar -xf ${shellQuote(remoteTar)} --delay-directory-restore -C ${shellQuote(mapping.targetPath)} || { ${immutable
988
+ ? "reseal_reopened; " : ""}echo "extract failed"; exit 43; };`,
989
+ `rm -f ${shellQuote(remoteTar)}${immutable ? ' "$reopened_list"' : ""};`,
990
+ ].join("\n");
991
+ // `extractTarball` span: one round trip — re-check the path, `tar -xf`, and
992
+ // remove the scratch tarball.
993
+ await withProviderSpan({
994
+ name: "extractTarball",
995
+ run: () => assertSandboxCommandOk(sandbox, `sh -c ${shellQuote(extractScript)}`, timeoutSeconds, "syncIn extract"),
996
+ });
997
+ }
998
+ catch (error) {
999
+ await removeSandboxScratch(sandbox, [remoteTar], timeoutSeconds);
1000
+ throw error;
1001
+ }
1002
+ const filesTransferred = await countHostFiles(mapping.sourcePath, mapping.exclude);
1003
+ return { filesTransferred, bytesTransferred };
1004
+ });
1005
+ }
1006
+ /**
1007
+ * Execute an operation's ordered `postUploadCommands` in-sandbox AFTER its files
1008
+ * have landed. Commands run in array order, fail-fast: the first non-zero exit
1009
+ * or timeout throws and stops the rest. Each `command` string is executed
1010
+ * VERBATIM via the exec seam; the provider never rewrites, concatenates, or
1011
+ * appends a shell fragment to it — the working directory rides
1012
+ * `executeCommand`'s structured `cwd` argument, never a `cd &&` prefix on the
1013
+ * command. An absent `cwd` defaults to the provider-resolved remote dir — never
1014
+ * a process default cwd.
1015
+ *
1016
+ * Shared by the file- and directory-mapping paths: it runs once per operation,
1017
+ * after every mapping of that operation has been placed.
1018
+ */
1019
+ async function runPostUploadCommands(input) {
1020
+ const { sandbox, commands, remoteDir, timeoutSeconds } = input;
1021
+ for (const command of commands) {
1022
+ // Absent cwd defaults to the remote dir, never a process default cwd.
1023
+ const cwd = command.cwd ?? remoteDir;
1024
+ // Run the command VERBATIM with a structured cwd (no string rewrite). The
1025
+ // first non-zero exit or timeout throws and aborts the remaining commands.
1026
+ const commandTimeoutSeconds = command.timeoutMs != null ? toTimeoutSeconds(command.timeoutMs) : timeoutSeconds;
1027
+ // `postUploadCommand` span: run one caller-supplied post-upload command.
1028
+ const result = await withProviderSpan({
1029
+ name: "postUploadCommand",
1030
+ run: () => sandbox.process.executeCommand(command.command, cwd, undefined, commandTimeoutSeconds),
1031
+ });
1032
+ if ((result.exitCode ?? 1) !== 0) {
1033
+ const detail = (result.result ?? result.artifacts?.stdout ?? "").toString().trim();
1034
+ throw new Error(`Daytona post-upload command failed (exit ${result.exitCode ?? "unknown"})${detail ? `: ${detail}` : ""}`);
1035
+ }
1036
+ }
1037
+ }
1038
+ export async function performSyncIn(input) {
1039
+ const operations = [];
1040
+ for (const operation of input.operations) {
1041
+ let filesTransferred = 0;
1042
+ let bytesTransferred = 0;
1043
+ const fileMappings = operation.files.filter((mapping) => mapping.kind === "file");
1044
+ const directoryMappings = operation.files.filter((mapping) => mapping.kind === "directory");
1045
+ const fileResult = await syncInFileMappings({
1046
+ sandbox: input.sandbox,
1047
+ mappings: fileMappings,
1048
+ remoteDir: input.remoteDir,
1049
+ timeoutSeconds: input.timeoutSeconds,
1050
+ });
1051
+ filesTransferred += fileResult.filesTransferred;
1052
+ bytesTransferred += fileResult.bytesTransferred;
1053
+ for (const mapping of directoryMappings) {
1054
+ const dirResult = await syncInDirectoryMapping({
1055
+ sandbox: input.sandbox,
1056
+ mapping,
1057
+ remoteDir: input.remoteDir,
1058
+ timeoutSeconds: input.timeoutSeconds,
1059
+ });
1060
+ filesTransferred += dirResult.filesTransferred;
1061
+ bytesTransferred += dirResult.bytesTransferred;
1062
+ }
1063
+ // Run the operation's ordered post-upload commands AFTER every file/directory
1064
+ // mapping of this operation has landed. Absent/empty → no extra exec.
1065
+ await runPostUploadCommands({
1066
+ sandbox: input.sandbox,
1067
+ commands: operation.postUploadCommands ?? [],
1068
+ remoteDir: input.remoteDir,
1069
+ timeoutSeconds: input.commandTimeoutSeconds ?? input.timeoutSeconds,
1070
+ });
1071
+ operations.push({ operationId: operation.operationId, filesTransferred, bytesTransferred });
1072
+ }
1073
+ return { operations };
1074
+ }
1075
+ // ---------------------------------------------------------------------------
1076
+ // Outbound (sandbox → host)
1077
+ // ---------------------------------------------------------------------------
1078
+ async function syncOutFileMappings(input) {
1079
+ const { sandbox, mappings, remoteDir, timeoutSeconds } = input;
1080
+ if (mappings.length === 0)
1081
+ return { filesTransferred: 0, bytesTransferred: 0 };
1082
+ // Close the validation→download TOCTOU: instead of re-opening each mutable
1083
+ // source, validate-and-snapshot it in one atomic sandbox-side step and download
1084
+ // the immutable snapshot. `snapshots` is index-aligned with `mappings`.
1085
+ const snapshots = await withEnvironmentSyncTransferStep("sandbox_guard", async () => {
1086
+ for (const mapping of mappings)
1087
+ assertConfinedSandboxPath(remoteDir, mapping.sourcePath, "source");
1088
+ return snapshotOutboundFileSources({
1089
+ sandbox, remoteDir, sources: mappings.map((mapping) => mapping.sourcePath), timeoutSeconds,
1090
+ });
1091
+ });
1092
+ const requests = [];
1093
+ const finalize = [];
1094
+ mappings.forEach((mapping, index) => {
1095
+ const dir = path.dirname(mapping.targetPath);
1096
+ // Stream each snapshot into a reserved host temp sibling, then atomic-rename
1097
+ // onto the host targetPath so an interrupted download never truncates it.
1098
+ const temp = path.join(dir, scratchName());
1099
+ if (snapshots)
1100
+ requests.push({ source: snapshots[index], destination: temp });
1101
+ finalize.push({ temp, target: mapping.targetPath, source: mapping.sourcePath, snapshot: snapshots?.[index], mode: mapping.mode });
1102
+ });
1103
+ const cleanup = async () => {
1104
+ await Promise.all(finalize.map((entry) => fs.rm(entry.temp, { force: true }).catch(() => undefined)));
1105
+ await removeSandboxScratch(sandbox, snapshots ?? [], timeoutSeconds);
1106
+ };
1107
+ // mkdir host target dirs up front (outside the download try) so a mkdir failure
1108
+ // still runs snapshot cleanup below.
1109
+ try {
1110
+ for (const entry of finalize) {
1111
+ await fs.mkdir(path.dirname(entry.target), { recursive: true });
1112
+ }
1113
+ }
1114
+ catch (error) {
1115
+ recordEnvironmentSyncError(error, { transferStep: "file_finalize" });
1116
+ await cleanup();
1117
+ throw error;
1118
+ }
1119
+ // Count the serial sandbox round trips before the transfer, so the transfer
1120
+ // span records how much of the wall time is guard cost. The validate-and-
1121
+ // snapshot step is one sandbox round trip. This is symmetric with the inbound
1122
+ // transfer span.
1123
+ const guardRoundTrips = 1;
1124
+ try {
1125
+ // One batched bulk download for all file mappings, reading the snapshots.
1126
+ // `transfer` span: the real byte download — `sandbox.fs.downloadFiles`.
1127
+ await withEnvironmentSyncTransferStep("file_download", () => withProviderSpan({
1128
+ name: "transfer",
1129
+ wallMsAttr: SPAN_ATTR.transferWallMs,
1130
+ attributes: {
1131
+ [SPAN_ATTR.transferGuardCount]: guardRoundTrips,
1132
+ [SPAN_ATTR.transferDirection]: "outbound",
1133
+ },
1134
+ run: async () => {
1135
+ if (!snapshots) {
1136
+ const deadline = Date.now() + timeoutSeconds * 1000;
1137
+ for (const entry of finalize) {
1138
+ // The user-process channel reads the file itself; privileged
1139
+ // downloadFiles never reopens a mutable live source. Recheck the
1140
+ // full guard in that process, then refuse a swapped symlink at open.
1141
+ const script = [
1142
+ ...canonicalizerPreamble(shellQuote(remoteDir)),
1143
+ `_pc_real=$(_pc_resolve ${shellQuote(entry.source)}) || exit 42;`,
1144
+ 'case "$_pc_real/" in "$_pc_root"/*) : ;; *) exit 42 ;; esac;',
1145
+ '[ ! -L "$_pc_real" ] && [ -f "$_pc_real" ] || exit 45;',
1146
+ 'dd if="$_pc_real" iflag=nofollow,nonblock status=none',
1147
+ ].join("\n");
1148
+ const remainingSeconds = (deadline - Date.now()) / 1000;
1149
+ if (remainingSeconds <= 0)
1150
+ throw new Error("Daytona file export timed out");
1151
+ await streamSandboxArchive({ process: sandbox.process, cwd: remoteDir,
1152
+ archiveScript: script, destination: entry.temp, timeoutSeconds: remainingSeconds,
1153
+ maxBytes: Math.floor(sandbox.disk * 1024 ** 3),
1154
+ });
1155
+ }
1156
+ return;
1157
+ }
1158
+ const responses = await sandbox.fs.downloadFiles(requests, timeoutSeconds);
1159
+ // Responses are keyed by the snapshot source. A missing or failed
1160
+ // response must not publish any of this batch's host temps.
1161
+ const bySource = new Map(responses.map(response => [response.source, response]));
1162
+ for (const entry of finalize) {
1163
+ const response = bySource.get(entry.snapshot);
1164
+ if (!response || response.error) {
1165
+ throw recordEnvironmentSyncError(new Error(`Daytona syncOut download failed for ${entry.source}: ${response?.error ?? "no response returned"}`), { transferStep: "file_download", transferFailureKind: response ? "download_failed" : "download_missing" });
1166
+ }
1167
+ }
1168
+ },
1169
+ }));
1170
+ }
1171
+ catch (error) {
1172
+ await cleanup();
1173
+ throw error;
1174
+ }
1175
+ let bytesTransferred = 0;
1176
+ try {
1177
+ for (const entry of finalize) {
1178
+ // chmod the temp before the rename so the target never appears at a widened
1179
+ // window; rename preserves the inode's mode.
1180
+ if (typeof entry.mode === "number") {
1181
+ await fs.chmod(entry.temp, entry.mode);
1182
+ }
1183
+ bytesTransferred += (await fs.stat(entry.temp)).size;
1184
+ await fs.rename(entry.temp, entry.target);
1185
+ }
1186
+ }
1187
+ catch (error) {
1188
+ recordEnvironmentSyncError(error, { transferStep: "file_finalize" });
1189
+ await cleanup();
1190
+ throw error;
1191
+ }
1192
+ // Success: the host temps have been renamed onto their targets; remove the
1193
+ // sandbox-side snapshots so no reserved scratch lingers.
1194
+ await removeSandboxScratch(sandbox, snapshots ?? [], timeoutSeconds);
1195
+ return { filesTransferred: mappings.length, bytesTransferred };
1196
+ }
1197
+ async function syncOutDirectoryMapping(input) {
1198
+ const { sandbox, mapping, remoteDir, timeoutSeconds } = input;
1199
+ // Count the serial sandbox round trips before the transfer, so the transfer
1200
+ // span records how much of the wall time is guard cost.
1201
+ let guardRoundTrips = 0;
1202
+ await withEnvironmentSyncTransferStep("sandbox_guard", async () => {
1203
+ assertConfinedSandboxPath(remoteDir, mapping.sourcePath, "source");
1204
+ await assertSandboxPathsConfined({
1205
+ sandbox, remoteDir, paths: [mapping.sourcePath], timeoutSeconds,
1206
+ label: "outbound symlink-escape guard",
1207
+ });
1208
+ });
1209
+ guardRoundTrips += 1;
1210
+ return withHostTempDir(async (tmp) => {
1211
+ const remoteTar = path.posix.join(remoteDir, scratchName(".tar"));
1212
+ const remoteList = path.posix.join(remoteDir, scratchName(".list"));
1213
+ const scratchPaths = [remoteTar, remoteList].flatMap(file => {
1214
+ const relative = path.posix.relative(mapping.sourcePath, file);
1215
+ return relative && !relative.startsWith("../") && !path.posix.isAbsolute(relative)
1216
+ ? [relative, `./${relative}`] : [];
1217
+ });
1218
+ const excludes = [...(mapping.preserveSourceEntries ? scratchPaths : ["._*", `${SCRATCH_PREFIX}*`]), ...(mapping.exclude ?? [])];
1219
+ // Preservation exclusions are literal paths relative to this source, not
1220
+ // basename patterns. Both archive naming forms occur in the repair path.
1221
+ const literalExcludes = [...new Set(excludes.map(entry => entry.replace(/^(?:\.\/)+/, "").replace(/\/+$/, "")))];
1222
+ const excludeFlags = (mapping.preserveSourceEntries ? "--anchored --no-wildcards " : "") +
1223
+ (mapping.preserveSourceEntries
1224
+ ? literalExcludes.flatMap(entry => [entry, `./${entry}`])
1225
+ : excludes.flatMap(entry => [entry, `${entry.replace(/\/$/, "")}/*`]))
1226
+ .map(entry => `--exclude ${shellQuote(entry)}`).join(" ");
1227
+ // Tar the source in-sandbox (naming top-level entries so no "." self-entry is
1228
+ // embedded), reproducing the `followSymlinks` → `-h` mapping, then stream the
1229
+ // single archive back over the native bulk channel.
1230
+ const tarScript = (archive) => [
1231
+ `cd ${shellQuote(mapping.sourcePath)}`,
1232
+ "set -- *",
1233
+ 'if [ "$#" -eq 1 ] && [ "$1" = "*" ] && [ ! -e "$1" ] && [ ! -L "$1" ]; then set --; fi',
1234
+ 'for entry in .[!.]* ..?*; do [ -e "$entry" ] || [ -L "$entry" ] || continue; set -- "$@" "$entry"; done',
1235
+ `if [ "$#" -eq 0 ]; then dd if=/dev/zero ${archive ? `of=${shellQuote(archive)} ` : ""}bs=1024 count=1; ` +
1236
+ `else tar -c --no-xattrs ${mapping.followSymlinks ? "-h " : ""}${excludeFlags} -f ${shellQuote(archive ?? "-")} -- "$@"; fi`,
1237
+ ].join(" && ");
1238
+ // Rebuild the archive with files, directories, and relative links whose
1239
+ // resolved targets remain inside this mapping. Nothing is deleted or
1240
+ // dereferenced. Host validation still checks the rebuilt archive, including
1241
+ // links changed by the sandbox between enumeration and tar creation.
1242
+ // find -path also interprets glob characters, even inside shell quotes.
1243
+ // Pruning a literal directory already removes its complete subtree.
1244
+ const prunePaths = (mapping.preserveSourceEntries
1245
+ ? literalExcludes.map(entry => `-path ${shellQuote(`./${entry.replace(/[\\*?[\]]/g, "\\$&")}`)}`)
1246
+ : excludes.flatMap(entry => [
1247
+ `-path ${shellQuote(`./${entry}`)}`, `-path ${shellQuote(`*/${entry}`)}`,
1248
+ ])).join(" -o ");
1249
+ const filterLinks = [
1250
+ ...canonicalizerPreamble(shellQuote(mapping.sourcePath)),
1251
+ 'for _pc_link do',
1252
+ ' _pc_target=$(readlink -- "$_pc_link") || continue;',
1253
+ ' case "$_pc_link" in *" -> "*) continue ;; esac;',
1254
+ ' case "$_pc_target" in /*|*" -> "*) continue ;; esac;',
1255
+ ' _pc_real=$(_pc_resolve "$_pc_link" 2>/dev/null) || continue;',
1256
+ ` case "$_pc_real/" in "$_pc_root"/*) printf '%s\\0' "$_pc_link" ;; esac;`,
1257
+ 'done',
1258
+ ].join("\n");
1259
+ const confinedEntriesScript = (archive) => [
1260
+ `cd ${shellQuote(mapping.sourcePath)}`,
1261
+ `find . -mindepth 1 ${prunePaths ? `\\( ${prunePaths} \\) -prune -o ` : ""}-type l -exec sh -c ${shellQuote(filterLinks)} sh {} + -o \\( -type f -o -type d \\) -print0 ${archive ? `> ${shellQuote(remoteList)} && ` : "| "}` +
1262
+ `tar -c --no-xattrs --hard-dereference --no-recursion --null ${excludeFlags} -f ${shellQuote(archive ?? "-")} -T ${shellQuote(archive ? remoteList : "-")}`,
1263
+ ].join(" && ");
1264
+ const localTar = path.join(tmp, "sync-out.tar");
1265
+ let bytesTransferred = 0;
1266
+ let streaming = false;
1267
+ try {
1268
+ for (let attempt = 0; attempt < 2; attempt += 1) {
1269
+ const script = attempt === 0 ? tarScript : confinedEntriesScript;
1270
+ if (!streaming) {
1271
+ try {
1272
+ await withEnvironmentSyncTransferStep("archive_create", () => assertSandboxCommandOk(sandbox, `sh -c ${shellQuote(script(remoteTar))}`, timeoutSeconds, "syncOut tar"));
1273
+ }
1274
+ catch (error) {
1275
+ // GNU tar can report either ENOSPC/EDQUOT or a short write when
1276
+ // archive storage is exhausted. Preserve all source files and use
1277
+ // a bounded, disk-free transfer instead of retrying that write.
1278
+ if (!(error instanceof Error) || !/No space left on device|Disk quota exceeded|File\s?size limit exceeded|Wrote only \d+ of \d+ bytes/i.test(error.message))
1279
+ throw error;
1280
+ await sandbox.fs.deleteFile(remoteTar).catch(() => undefined);
1281
+ streaming = true;
1282
+ }
1283
+ }
1284
+ guardRoundTrips += 1;
1285
+ if (streaming) {
1286
+ await withEnvironmentSyncTransferStep("archive_download", () => streamSandboxArchive({
1287
+ process: sandbox.process, cwd: remoteDir, archiveScript: script(null), destination: localTar, timeoutSeconds,
1288
+ maxBytes: Math.floor(sandbox.disk * 1024 ** 3),
1289
+ }));
1290
+ }
1291
+ else {
1292
+ // `transfer` span: the real byte download — `sandbox.fs.downloadFiles`.
1293
+ const responses = await withEnvironmentSyncTransferStep("archive_download", () => withProviderSpan({
1294
+ name: "transfer",
1295
+ wallMsAttr: SPAN_ATTR.transferWallMs,
1296
+ attributes: {
1297
+ [SPAN_ATTR.transferGuardCount]: guardRoundTrips,
1298
+ [SPAN_ATTR.transferDirection]: "outbound",
1299
+ },
1300
+ run: () => sandbox.fs.downloadFiles([{ source: remoteTar, destination: localTar }], timeoutSeconds),
1301
+ }));
1302
+ const response = responses.find((entry) => entry.source === remoteTar) ?? responses[0];
1303
+ if (!response || response.error) {
1304
+ throw recordEnvironmentSyncError(new Error(`Daytona syncOut directory download failed for ${mapping.sourcePath}: ${response?.error ?? "no response returned"}`), { transferStep: "archive_download", transferFailureKind: response ? "download_failed" : "download_missing" });
1305
+ }
1306
+ }
1307
+ bytesTransferred += await withEnvironmentSyncTransferStep("archive_download", async () => (await fs.stat(localTar)).size);
1308
+ try {
1309
+ await extractHostTarball({ archivePath: localTar, localDir: mapping.targetPath, preserveSourceEntries: mapping.preserveSourceEntries });
1310
+ break;
1311
+ }
1312
+ catch (error) {
1313
+ if (!(error instanceof UnsafeOutboundArchiveError) || attempt > 0)
1314
+ throw error;
1315
+ // Diagnostic only: no warning, task action, or additional agent turn.
1316
+ try {
1317
+ input.onArchiveRecovery?.();
1318
+ }
1319
+ catch { /* logging is best effort */ }
1320
+ }
1321
+ }
1322
+ }
1323
+ finally {
1324
+ // Best-effort remove the sandbox-side scratch tar; the host temp dir is
1325
+ // cleaned by withHostTempDir.
1326
+ await Promise.all([remoteTar, remoteList].map((file) => sandbox.fs.deleteFile(file).catch(() => undefined)));
1327
+ }
1328
+ const filesTransferred = await countHostFiles(mapping.targetPath, mapping.preserveSourceEntries ? undefined : mapping.exclude);
1329
+ return { filesTransferred, bytesTransferred };
1330
+ });
1331
+ }
1332
+ export async function performSyncOut(input) {
1333
+ const operations = [];
1334
+ for (const operation of input.operations) {
1335
+ let filesTransferred = 0;
1336
+ let bytesTransferred = 0;
1337
+ const fileMappings = operation.files.filter((mapping) => mapping.kind === "file");
1338
+ const directoryMappings = operation.files.filter((mapping) => mapping.kind === "directory");
1339
+ const fileResult = await syncOutFileMappings({
1340
+ sandbox: input.sandbox,
1341
+ mappings: fileMappings,
1342
+ remoteDir: input.remoteDir,
1343
+ timeoutSeconds: input.timeoutSeconds,
1344
+ });
1345
+ filesTransferred += fileResult.filesTransferred;
1346
+ bytesTransferred += fileResult.bytesTransferred;
1347
+ for (const mapping of directoryMappings) {
1348
+ const dirResult = await syncOutDirectoryMapping({
1349
+ sandbox: input.sandbox,
1350
+ mapping,
1351
+ onArchiveRecovery: input.onArchiveRecovery,
1352
+ remoteDir: input.remoteDir,
1353
+ timeoutSeconds: input.timeoutSeconds,
1354
+ });
1355
+ filesTransferred += dirResult.filesTransferred;
1356
+ bytesTransferred += dirResult.bytesTransferred;
1357
+ }
1358
+ operations.push({ operationId: operation.operationId, filesTransferred, bytesTransferred });
1359
+ }
1360
+ return { operations };
1361
+ }
1362
+ //# sourceMappingURL=file-sync.js.map