@leitwerk-dev/session-transfer 0.0.0-bootstrap.0 → 0.2.1

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.
package/dist/index.js ADDED
@@ -0,0 +1,674 @@
1
+ // src/archive.ts
2
+ import { createHash } from "crypto";
3
+ import { createReadStream } from "fs";
4
+ import {
5
+ chmod,
6
+ lstat as lstat2,
7
+ mkdir,
8
+ open,
9
+ readdir,
10
+ readlink,
11
+ symlink,
12
+ utimes,
13
+ writeFile
14
+ } from "fs/promises";
15
+ import path4 from "path";
16
+ import { Transform } from "stream";
17
+ import { pipeline } from "stream/promises";
18
+ import { createZstdCompress, createZstdDecompress, constants as zlibConstants } from "zlib";
19
+ import tar from "tar-stream";
20
+
21
+ // src/format.ts
22
+ import path from "path";
23
+ import * as v from "valibot";
24
+ var SESSION_TRANSFER_CONTENT_TYPE = "application/vnd.leitwerk.session-transfer+tar+zstd";
25
+ function sessionTransferAttemptStateForPhase(phase) {
26
+ switch (phase) {
27
+ case "queued":
28
+ case "waiting_for_execution_chain":
29
+ return "queued";
30
+ case "stopping_worker":
31
+ case "starting_exporter":
32
+ case "scanning":
33
+ case "ready_to_stream":
34
+ case "streaming":
35
+ return "exporting";
36
+ case "awaiting_ack":
37
+ case "consumed":
38
+ case "cancelled":
39
+ case "failed":
40
+ return phase;
41
+ default:
42
+ throw new Error(`Unknown session transfer phase: ${phase}`);
43
+ }
44
+ }
45
+ var nonBlankStringSchema = v.pipe(
46
+ v.string(),
47
+ v.check((value) => value.trim().length > 0, "Expected a non-empty string")
48
+ );
49
+ var safeIntegerSchema = v.pipe(v.number(), v.safeInteger());
50
+ var positiveSafeIntegerSchema = v.pipe(safeIntegerSchema, v.minValue(1));
51
+ var nonNegativeSafeIntegerSchema = v.pipe(safeIntegerSchema, v.minValue(0));
52
+ var normalizedRelativePathSchema = v.pipe(
53
+ nonBlankStringSchema,
54
+ v.check((value) => {
55
+ try {
56
+ return assertSafeRelativePath(value) === value;
57
+ } catch {
58
+ return false;
59
+ }
60
+ }, "Expected a normalized relative path")
61
+ );
62
+ var sessionTransferLimitsSchema = v.object({
63
+ /** @internal */
64
+ maxEntries: positiveSafeIntegerSchema,
65
+ /** @internal */
66
+ maxLogicalBytes: positiveSafeIntegerSchema,
67
+ /** @internal */
68
+ maxCompressedBytes: positiveSafeIntegerSchema
69
+ });
70
+ var DEFAULT_SESSION_TRANSFER_LIMITS = {
71
+ maxEntries: 25e4,
72
+ maxLogicalBytes: 20 * 1024 * 1024 * 1024,
73
+ maxCompressedBytes: 10 * 1024 * 1024 * 1024
74
+ };
75
+ var leitwerkTransferManifestV1Schema = v.object({
76
+ /** @internal */
77
+ version: v.literal(1, "Unsupported transfer manifest version"),
78
+ /** @internal */
79
+ instanceId: nonBlankStringSchema,
80
+ /** @internal */
81
+ createdAt: v.pipe(
82
+ nonBlankStringSchema,
83
+ v.check((value) => Number.isFinite(Date.parse(value)), "Expected an ISO datetime")
84
+ ),
85
+ /** @internal */
86
+ session: v.object({
87
+ /** @internal */
88
+ sourceCwd: nonBlankStringSchema,
89
+ /** @internal */
90
+ cwdRelativeToWorkspace: v.nullable(v.union([v.literal("."), normalizedRelativePathSchema]))
91
+ }),
92
+ /** @internal */
93
+ projects: v.array(
94
+ v.object({
95
+ /** @internal */
96
+ key: nonBlankStringSchema,
97
+ /** @internal */
98
+ relativePath: normalizedRelativePathSchema,
99
+ /** @internal */
100
+ branch: v.nullable(v.string()),
101
+ /** @internal */
102
+ head: v.nullable(v.string())
103
+ })
104
+ )
105
+ });
106
+ var sessionTransferPreflightSchema = v.object({
107
+ /** @internal */
108
+ entriesTotal: v.pipe(nonNegativeSafeIntegerSchema, v.minValue(3)),
109
+ /** @internal */
110
+ logicalBytesTotal: nonNegativeSafeIntegerSchema
111
+ });
112
+ var sessionTransferPreflightReportSchema = v.object({
113
+ /** @internal */
114
+ manifest: leitwerkTransferManifestV1Schema,
115
+ /** @internal */
116
+ preflight: sessionTransferPreflightSchema
117
+ });
118
+ var sessionTransferHelperSpecSchema = v.object({
119
+ /** @internal */
120
+ manifest: leitwerkTransferManifestV1Schema,
121
+ /** @internal */
122
+ limits: sessionTransferLimitsSchema
123
+ });
124
+ function object2(value, label) {
125
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
126
+ throw new Error(`${label} must be an object`);
127
+ }
128
+ return value;
129
+ }
130
+ function string2(value, label) {
131
+ if (typeof value !== "string" || value.trim().length === 0) {
132
+ throw new Error(`${label} must be a non-empty string`);
133
+ }
134
+ return value;
135
+ }
136
+ function parsePiSessionHeader(content) {
137
+ const firstLine = content.split(/\r?\n/, 1)[0];
138
+ if (!firstLine) throw new Error("Pi session is empty");
139
+ const value = JSON.parse(firstLine);
140
+ if (!value || typeof value !== "object" || Array.isArray(value) || value.type !== "session") {
141
+ throw new Error("Pi session header is invalid");
142
+ }
143
+ return value;
144
+ }
145
+ function isPathInside(root, candidate) {
146
+ const relative = path.relative(path.resolve(root), path.resolve(candidate));
147
+ return relative === "" || !relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative);
148
+ }
149
+ function assertSafeRelativePath(value, label = "path") {
150
+ if (value.includes("\0") || path.posix.isAbsolute(value) || path.win32.isAbsolute(value)) {
151
+ throw new Error(`${label} must be relative`);
152
+ }
153
+ const normalized = path.posix.normalize(value.replaceAll("\\", "/"));
154
+ if (normalized === ".." || normalized.startsWith("../") || normalized === ".") {
155
+ throw new Error(`${label} escapes its root`);
156
+ }
157
+ return normalized;
158
+ }
159
+ function parseTransferManifest(value) {
160
+ return v.parse(leitwerkTransferManifestV1Schema, value);
161
+ }
162
+ function parseSessionTransferHelperSpec(value) {
163
+ return v.parse(sessionTransferHelperSpecSchema, value);
164
+ }
165
+ var TRANSFER_ID_PATTERN = /^[A-Za-z0-9_.-]+$/;
166
+ function decodeTransferId(value, label) {
167
+ let decoded;
168
+ try {
169
+ decoded = decodeURIComponent(value);
170
+ } catch (error) {
171
+ throw new Error(`Transfer link has an invalid ${label}`, { cause: error });
172
+ }
173
+ if (!TRANSFER_ID_PATTERN.test(decoded)) {
174
+ throw new Error(`Transfer link has an invalid ${label}`);
175
+ }
176
+ return decoded;
177
+ }
178
+ function parseTransferLink(raw) {
179
+ let url;
180
+ try {
181
+ url = new URL(raw.trim());
182
+ } catch {
183
+ throw new Error("Transfer link is not a valid URL");
184
+ }
185
+ const loopback = url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "::1" || url.hostname === "[::1]";
186
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
187
+ throw new Error("Transfer links require HTTPS (HTTP is allowed only for loopback development)");
188
+ }
189
+ if (url.username || url.password || url.search)
190
+ throw new Error("Transfer link contains unexpected URL credentials or query parameters");
191
+ const match = /^\/api\/session-transfers\/([^/]+)\/([^/]+)$/.exec(url.pathname);
192
+ if (!match) throw new Error("Transfer link has an unexpected path");
193
+ const instanceId = decodeTransferId(match[1], "instance id");
194
+ const grantId = decodeTransferId(match[2], "grant id");
195
+ const token = new URLSearchParams(url.hash.slice(1)).get("token");
196
+ if (!token || token.length < 32)
197
+ throw new Error("Transfer link is missing its bearer token fragment");
198
+ return {
199
+ origin: url.origin,
200
+ instanceId,
201
+ grantId,
202
+ token,
203
+ grantUrl: `${url.origin}/api/session-transfers/${encodeURIComponent(instanceId)}/${encodeURIComponent(grantId)}`
204
+ };
205
+ }
206
+ function rewritePiSession(content, localCwd, expectedSourceCwd) {
207
+ const lines = content.split(/\r?\n/).filter((line) => line.trim() !== "");
208
+ if (lines.length === 0) throw new Error("Transferred Pi session is empty");
209
+ const parsed = lines.map((line, index) => {
210
+ try {
211
+ return object2(JSON.parse(line), `session line ${index + 1}`);
212
+ } catch (error) {
213
+ if (error instanceof SyntaxError)
214
+ throw new Error(`Session line ${index + 1} is not valid JSON`, { cause: error });
215
+ throw error;
216
+ }
217
+ });
218
+ const sourceHeader = parsePiSessionHeader(content);
219
+ if (sourceHeader.version !== 3) {
220
+ throw new Error("unsupported_pi_session_version");
221
+ }
222
+ string2(sourceHeader.id, "session header.id");
223
+ const sourceCwd = string2(sourceHeader.cwd, "session header.cwd");
224
+ if (!path.isAbsolute(sourceCwd)) throw new Error("Transferred session cwd must be absolute");
225
+ if (expectedSourceCwd !== void 0 && sourceCwd !== expectedSourceCwd) {
226
+ throw new Error("Transferred session cwd does not match the transfer manifest");
227
+ }
228
+ const timestamp = string2(sourceHeader.timestamp, "session header.timestamp");
229
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(timestamp) || !Number.isFinite(Date.parse(timestamp))) {
230
+ throw new Error("Transferred session timestamp must be an ISO datetime");
231
+ }
232
+ const ids = /* @__PURE__ */ new Set();
233
+ for (let index = 1; index < parsed.length; index += 1) {
234
+ const entry = parsed[index];
235
+ if (entry.type === "session") throw new Error("Transferred session contains a second header");
236
+ string2(entry.type, `session line ${index + 1}.type`);
237
+ const id = string2(entry.id, `session line ${index + 1}.id`);
238
+ if (ids.has(id)) throw new Error(`Transferred session contains duplicate entry id '${id}'`);
239
+ const parentId = entry.parentId;
240
+ if (parentId !== null && (typeof parentId !== "string" || !ids.has(parentId))) {
241
+ throw new Error(`Transferred session entry '${id}' has an invalid parent`);
242
+ }
243
+ ids.add(id);
244
+ }
245
+ const { parentSession: _parentSession, ...rest } = sourceHeader;
246
+ const header = { ...rest, cwd: path.resolve(localCwd) };
247
+ return {
248
+ content: `${[header, ...parsed.slice(1)].map((entry) => JSON.stringify(entry)).join("\n")}
249
+ `,
250
+ header,
251
+ entryCount: parsed.length - 1
252
+ };
253
+ }
254
+
255
+ // src/project-evidence.ts
256
+ import { execFile } from "child_process";
257
+ import { lstat } from "fs/promises";
258
+ import path2 from "path";
259
+ import { promisify } from "util";
260
+ var execFileAsync = promisify(execFile);
261
+ async function readProjectEvidence(workspaceRoot, projects, signal) {
262
+ return Promise.all(
263
+ projects.map(async (project) => {
264
+ const projectRoot = path2.resolve(workspaceRoot, ...project.relativePath.split("/"));
265
+ if (!isPathInside(workspaceRoot, projectRoot)) {
266
+ throw new Error(`Project '${project.key}' escapes the workspace`);
267
+ }
268
+ try {
269
+ await lstat(path2.join(projectRoot, ".git"));
270
+ } catch {
271
+ throw new Error(`Project '${project.key}' is not a Git worktree`);
272
+ }
273
+ const [head = "", branch = ""] = (await execFileAsync(
274
+ "git",
275
+ ["-C", projectRoot, "rev-parse", "HEAD", "--abbrev-ref", "HEAD"],
276
+ {
277
+ signal
278
+ }
279
+ )).stdout.trim().split("\n");
280
+ return {
281
+ ...project,
282
+ head: head || null,
283
+ branch: branch && branch !== "HEAD" ? branch : null
284
+ };
285
+ })
286
+ );
287
+ }
288
+
289
+ // src/symlink-confinement.ts
290
+ import path3 from "path";
291
+ function assertConfinedSymlinks(links) {
292
+ const resolvedLinks = /* @__PURE__ */ new Map();
293
+ const resolving = /* @__PURE__ */ new Set();
294
+ const resolve = (segments, initial = []) => {
295
+ let resolved = [...initial];
296
+ for (const segment of segments) {
297
+ if (segment === "" || segment === ".") continue;
298
+ if (segment === "..") {
299
+ if (resolved.length === 0) throw new Error("Symlink escapes the workspace");
300
+ resolved.pop();
301
+ continue;
302
+ }
303
+ const candidate = [...resolved, segment].join("/");
304
+ const target = links.get(candidate);
305
+ if (target === void 0) {
306
+ resolved.push(segment);
307
+ continue;
308
+ }
309
+ if (path3.posix.isAbsolute(target) || path3.win32.isAbsolute(target)) {
310
+ throw new Error(`Absolute symlink is not portable: ${candidate}`);
311
+ }
312
+ if (resolving.has(candidate)) throw new Error(`Symlink cycle in workspace: ${candidate}`);
313
+ let destination = resolvedLinks.get(candidate);
314
+ if (!destination) {
315
+ resolving.add(candidate);
316
+ destination = resolve(target.split("/"), resolved);
317
+ resolving.delete(candidate);
318
+ resolvedLinks.set(candidate, destination);
319
+ }
320
+ resolved = [...destination];
321
+ }
322
+ return resolved;
323
+ };
324
+ for (const name of links.keys()) resolve(name.split("/"));
325
+ }
326
+
327
+ // src/archive.ts
328
+ var MANIFEST_MAX_BYTES = 1024 * 1024;
329
+ function abortIfNeeded(signal) {
330
+ if (signal?.aborted) throw signal.reason ?? new Error("Transfer cancelled");
331
+ }
332
+ function toSafeNumber(value, label) {
333
+ if (value > BigInt(Number.MAX_SAFE_INTEGER))
334
+ throw new Error(`${label} exceeds safe integer range`);
335
+ return Number(value);
336
+ }
337
+ async function scanPortableWorkspace(input) {
338
+ const limits = input.limits ?? DEFAULT_SESSION_TRANSFER_LIMITS;
339
+ const root = path4.resolve(input.workspaceRoot);
340
+ if (!(await lstat2(root, { bigint: true })).isDirectory()) {
341
+ throw new Error("Process workspace is not a directory");
342
+ }
343
+ const entries = [];
344
+ let logicalBytesTotal = 0;
345
+ const add = (entry) => {
346
+ entries.push(entry);
347
+ if (entries.length + 3 > limits.maxEntries) throw new Error("Transfer entry limit exceeded");
348
+ if (entry.kind === "file") {
349
+ logicalBytesTotal += entry.size;
350
+ if (!Number.isSafeInteger(logicalBytesTotal) || logicalBytesTotal > limits.maxLogicalBytes) {
351
+ throw new Error("Transfer logical byte limit exceeded");
352
+ }
353
+ }
354
+ };
355
+ const walk = async (directory, relativeDirectory) => {
356
+ abortIfNeeded(input.signal);
357
+ const names = await readdir(directory);
358
+ names.sort((left, right) => Buffer.from(left).compare(Buffer.from(right)));
359
+ for (const name of names) {
360
+ abortIfNeeded(input.signal);
361
+ if (name.includes("\\")) {
362
+ throw new Error(`Workspace entry contains an unsupported path separator: ${name}`);
363
+ }
364
+ const absolute = path4.join(directory, name);
365
+ if (!isPathInside(root, absolute))
366
+ throw new Error("Workspace scan escaped its configured root");
367
+ const relativePath = path4.posix.join(relativeDirectory, name);
368
+ const stats = await lstat2(absolute, { bigint: true });
369
+ const common = {
370
+ relativePath,
371
+ mode: Number(stats.mode & 0o7777n),
372
+ mtimeMs: Number(stats.mtimeMs)
373
+ };
374
+ if (stats.isDirectory()) {
375
+ add({ ...common, kind: "directory", size: 0 });
376
+ await walk(absolute, relativePath);
377
+ } else if (stats.isFile()) {
378
+ add({ ...common, kind: "file", size: toSafeNumber(stats.size, relativePath) });
379
+ } else if (stats.isSymbolicLink()) {
380
+ const linkTarget = await readlink(absolute);
381
+ if (path4.isAbsolute(linkTarget) || path4.win32.isAbsolute(linkTarget)) {
382
+ throw new Error(`Absolute symlink is not portable: ${relativePath}`);
383
+ }
384
+ add({ ...common, kind: "symlink", size: 0, linkTarget });
385
+ } else {
386
+ throw new Error(`Unsupported workspace entry type: ${relativePath}`);
387
+ }
388
+ }
389
+ };
390
+ await walk(root, "");
391
+ assertConfinedSymlinks(
392
+ new Map(
393
+ entries.flatMap(
394
+ (entry) => entry.kind === "symlink" ? [[entry.relativePath, entry.linkTarget ?? ""]] : []
395
+ )
396
+ )
397
+ );
398
+ const sessionStats = await lstat2(path4.resolve(input.sessionFile), { bigint: true });
399
+ if (!sessionStats.isFile()) throw new Error("Primary Pi session is not a regular file");
400
+ logicalBytesTotal += toSafeNumber(sessionStats.size, "Pi session");
401
+ if (!Number.isSafeInteger(logicalBytesTotal) || logicalBytesTotal > limits.maxLogicalBytes) {
402
+ throw new Error("Transfer logical byte limit exceeded");
403
+ }
404
+ return { entries, entriesTotal: entries.length + 3, logicalBytesTotal };
405
+ }
406
+ function addBufferEntry(pack, header, content = Buffer.alloc(0)) {
407
+ return new Promise((resolve, reject) => {
408
+ pack.entry(header, content, (error) => error ? reject(error) : resolve());
409
+ });
410
+ }
411
+ async function addFileEntry(pack, header, filePath, signal) {
412
+ abortIfNeeded(signal);
413
+ const entry = pack.entry(header);
414
+ await pipeline(createReadStream(filePath), entry, { signal });
415
+ }
416
+ async function prepareTransferArchive(input) {
417
+ const preflight = await scanPortableWorkspace(input);
418
+ const manifest = {
419
+ ...input.manifest,
420
+ projects: await readProjectEvidence(input.workspaceRoot, input.manifest.projects, input.signal)
421
+ };
422
+ return {
423
+ manifest,
424
+ preflight,
425
+ stream: ({ signal }) => createTransferArchive({ ...input, manifest, preflight, signal })
426
+ };
427
+ }
428
+ function createTransferArchive(input) {
429
+ const pack = tar.pack();
430
+ const zstd = createZstdCompress({
431
+ params: {
432
+ [zlibConstants.ZSTD_c_compressionLevel]: 1,
433
+ [zlibConstants.ZSTD_c_checksumFlag]: 1
434
+ }
435
+ });
436
+ const createdAt = new Date(input.manifest.createdAt);
437
+ const finish = async () => {
438
+ abortIfNeeded(input.signal);
439
+ const manifest = `${JSON.stringify(input.manifest)}
440
+ `;
441
+ await addBufferEntry(pack, { name: "manifest.json", mode: 384, mtime: createdAt }, manifest);
442
+ await addBufferEntry(pack, {
443
+ name: "workspace/",
444
+ type: "directory",
445
+ mode: 493,
446
+ mtime: createdAt
447
+ });
448
+ for (const entry of input.preflight.entries) {
449
+ abortIfNeeded(input.signal);
450
+ const name = `workspace/${entry.relativePath}${entry.kind === "directory" ? "/" : ""}`;
451
+ const header = {
452
+ name,
453
+ type: entry.kind === "file" ? "file" : entry.kind,
454
+ mode: entry.mode,
455
+ mtime: new Date(entry.mtimeMs),
456
+ ...entry.kind === "file" ? { size: entry.size } : {},
457
+ ...entry.linkTarget ? { linkname: entry.linkTarget } : {}
458
+ };
459
+ if (entry.kind === "file") {
460
+ await addFileEntry(
461
+ pack,
462
+ header,
463
+ path4.join(input.workspaceRoot, ...entry.relativePath.split("/")),
464
+ input.signal
465
+ );
466
+ } else {
467
+ await addBufferEntry(pack, header);
468
+ }
469
+ }
470
+ const workspaceBytes = input.preflight.entries.reduce(
471
+ (sum, entry) => sum + (entry.kind === "file" ? entry.size : 0),
472
+ 0
473
+ );
474
+ await addFileEntry(
475
+ pack,
476
+ {
477
+ name: "session.jsonl",
478
+ mode: 384,
479
+ mtime: createdAt,
480
+ size: input.preflight.logicalBytesTotal - workspaceBytes
481
+ },
482
+ input.sessionFile,
483
+ input.signal
484
+ );
485
+ pack.finalize();
486
+ };
487
+ void pipeline(pack, zstd, { signal: input.signal }).catch(() => void 0);
488
+ void finish().catch((error) => pack.destroy(error));
489
+ return zstd;
490
+ }
491
+ async function assertNoSymlinkParents(root, target) {
492
+ let current = root;
493
+ for (const segment of path4.relative(root, path4.dirname(target)).split(path4.sep).filter(Boolean)) {
494
+ current = path4.join(current, segment);
495
+ try {
496
+ if ((await lstat2(current)).isSymbolicLink()) {
497
+ throw new Error(`Archive path traverses symlink '${segment}'`);
498
+ }
499
+ } catch (error) {
500
+ if (error.code !== "ENOENT") throw error;
501
+ }
502
+ }
503
+ }
504
+ async function drainEntry(stream) {
505
+ for await (const _chunk of stream) {
506
+ }
507
+ }
508
+ async function streamBuffer(stream, limit, label) {
509
+ const chunks = [];
510
+ let size = 0;
511
+ for await (const chunk of stream) {
512
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
513
+ size += buffer.length;
514
+ if (size > limit) throw new Error(`${label} is too large`);
515
+ chunks.push(buffer);
516
+ }
517
+ return Buffer.concat(chunks);
518
+ }
519
+ async function extractTransferArchive(input) {
520
+ const limits = input.limits ?? DEFAULT_SESSION_TRANSFER_LIMITS;
521
+ const outputRoot = path4.resolve(input.outputRoot);
522
+ await mkdir(outputRoot, { recursive: false, mode: 448 });
523
+ if (input.ownershipMarker) {
524
+ const markerName = assertSafeRelativePath(input.ownershipMarker.name, "ownership marker");
525
+ if (markerName.includes("/")) throw new Error("Ownership marker must be a root file");
526
+ await writeFile(path4.join(outputRoot, markerName), `${input.ownershipMarker.value}
527
+ `, {
528
+ flag: "wx",
529
+ mode: 384
530
+ });
531
+ }
532
+ const hash = createHash("sha256");
533
+ let compressedBytes = 0;
534
+ let entriesProcessed = 0;
535
+ let logicalBytesProcessed = 0;
536
+ let manifest = null;
537
+ const seen = /* @__PURE__ */ new Set();
538
+ const symlinks = /* @__PURE__ */ new Map();
539
+ const directoryMetadata = [];
540
+ const report = () => input.onProgress?.({ entriesProcessed, logicalBytesProcessed, compressedBytes });
541
+ const metered = new Transform({
542
+ transform(chunk, _encoding, callback) {
543
+ compressedBytes += chunk.length;
544
+ if (compressedBytes > limits.maxCompressedBytes) {
545
+ callback(new Error("Transfer compressed byte limit exceeded"));
546
+ return;
547
+ }
548
+ hash.update(chunk);
549
+ report();
550
+ callback(null, chunk);
551
+ }
552
+ });
553
+ const extract = tar.extract();
554
+ extract.on("entry", (header, entryStream, next) => {
555
+ void (async () => {
556
+ abortIfNeeded(input.signal);
557
+ const name = assertSafeRelativePath(header.name.replace(/\/$/, ""), "archive path");
558
+ if (seen.has(name)) throw new Error(`Duplicate archive path '${name}'`);
559
+ seen.add(name);
560
+ entriesProcessed += 1;
561
+ if (entriesProcessed > limits.maxEntries) throw new Error("Transfer entry limit exceeded");
562
+ if (entriesProcessed === 1 && name !== "manifest.json") {
563
+ throw new Error("manifest.json must be the first archive entry");
564
+ }
565
+ if (name !== "manifest.json" && name !== "session.jsonl" && name !== "workspace" && !name.startsWith("workspace/")) {
566
+ throw new Error(`Unexpected archive path '${name}'`);
567
+ }
568
+ const target = path4.resolve(outputRoot, ...name.split("/"));
569
+ if (!isPathInside(outputRoot, target))
570
+ throw new Error(`Archive path escapes output: ${name}`);
571
+ await assertNoSymlinkParents(outputRoot, target);
572
+ const mode = (header.mode ?? (header.type === "directory" ? 493 : 384)) & 4095;
573
+ const mtime = header.mtime ?? /* @__PURE__ */ new Date(0);
574
+ if (header.type === "directory") {
575
+ if (header.size !== 0) throw new Error(`Directory '${name}' has content`);
576
+ await drainEntry(entryStream);
577
+ await mkdir(target, { recursive: false, mode: mode | 448 });
578
+ directoryMetadata.push({ target, mode, mtime });
579
+ } else if (header.type === "symlink") {
580
+ if (header.size !== 0) throw new Error(`Symlink '${name}' has content`);
581
+ await drainEntry(entryStream);
582
+ if (!name.startsWith("workspace/")) {
583
+ throw new Error(`Archive symlink is outside the workspace: ${name}`);
584
+ }
585
+ const link = header.linkname ?? "";
586
+ if (path4.isAbsolute(link) || path4.win32.isAbsolute(link)) {
587
+ throw new Error(`Absolute archive symlink '${name}'`);
588
+ }
589
+ await mkdir(path4.dirname(target), { recursive: true, mode: 448 });
590
+ await symlink(link, target);
591
+ symlinks.set(name.slice("workspace/".length), link);
592
+ } else if (header.type === "file" || !header.type) {
593
+ const size = header.size ?? 0;
594
+ if (!Number.isSafeInteger(size) || size < 0) {
595
+ throw new Error(`Invalid size for archive entry '${name}'`);
596
+ }
597
+ await mkdir(path4.dirname(target), { recursive: true, mode: 448 });
598
+ if (name === "manifest.json") {
599
+ const content = await streamBuffer(
600
+ entryStream,
601
+ MANIFEST_MAX_BYTES,
602
+ "Transfer manifest"
603
+ );
604
+ await writeFile(target, content, { flag: "wx", mode: 384 });
605
+ manifest = parseTransferManifest(JSON.parse(content.toString("utf8")));
606
+ } else {
607
+ const handle = await open(target, "wx", mode);
608
+ let actualSize = 0;
609
+ try {
610
+ for await (const chunk of entryStream) {
611
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
612
+ actualSize += buffer.length;
613
+ logicalBytesProcessed += buffer.length;
614
+ if (!Number.isSafeInteger(actualSize) || logicalBytesProcessed > limits.maxLogicalBytes) {
615
+ throw new Error("Transfer logical byte limit exceeded");
616
+ }
617
+ await handle.write(buffer);
618
+ }
619
+ } finally {
620
+ await handle.close();
621
+ }
622
+ if (actualSize !== size) {
623
+ throw new Error(`Archive entry '${name}' size does not match its content`);
624
+ }
625
+ await chmod(target, mode);
626
+ await utimes(target, mtime, mtime);
627
+ }
628
+ } else {
629
+ await drainEntry(entryStream);
630
+ throw new Error(`Unsupported tar entry type '${header.type}' for '${name}'`);
631
+ }
632
+ report();
633
+ next();
634
+ })().catch((error) => next(error));
635
+ });
636
+ const abort = () => extract.destroy(input.signal?.reason);
637
+ input.signal?.addEventListener("abort", abort, { once: true });
638
+ try {
639
+ await pipeline(input.compressed, metered, createZstdDecompress(), extract);
640
+ } finally {
641
+ input.signal?.removeEventListener("abort", abort);
642
+ }
643
+ assertConfinedSymlinks(symlinks);
644
+ for (const directory of directoryMetadata.reverse()) {
645
+ await chmod(directory.target, directory.mode);
646
+ await utimes(directory.target, directory.mtime, directory.mtime);
647
+ }
648
+ if (!manifest) throw new Error("Transfer manifest is missing");
649
+ if (!seen.has("workspace") || !seen.has("session.jsonl")) {
650
+ throw new Error("Transfer archive is incomplete");
651
+ }
652
+ return {
653
+ manifest,
654
+ compressedBytes,
655
+ streamSha256: hash.digest("hex")
656
+ };
657
+ }
658
+ export {
659
+ DEFAULT_SESSION_TRANSFER_LIMITS,
660
+ SESSION_TRANSFER_CONTENT_TYPE,
661
+ createTransferArchive,
662
+ extractTransferArchive,
663
+ isPathInside,
664
+ parsePiSessionHeader,
665
+ parseSessionTransferHelperSpec,
666
+ parseTransferLink,
667
+ prepareTransferArchive,
668
+ readProjectEvidence,
669
+ rewritePiSession,
670
+ scanPortableWorkspace,
671
+ sessionTransferAttemptStateForPhase,
672
+ sessionTransferPreflightReportSchema
673
+ };
674
+ //# sourceMappingURL=index.js.map