@tangle-network/agent-provider-tangle 4.4.2 → 4.4.4

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.
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Streaming reader for the Sandbox directory archive (`fs.downloadArchive`): ustar headers as the
3
+ * Sidecar's node-tar writes them, with PAX `x` records and GNU `L`/`K` long names. Every header
4
+ * checksum is verified, and a member's body must be consumed or is skipped before the next header
5
+ * is read, so memory stays bounded by one header block plus one source chunk.
6
+ */
7
+ export interface WorkspaceArchiveMember {
8
+ /** Member name relative to the archived directory, without a trailing slash. */
9
+ name: string;
10
+ type: "file" | "directory" | "symlink" | "link";
11
+ /** Body bytes for a file; 0 for every other type. */
12
+ size: number;
13
+ mode: number;
14
+ uid: number;
15
+ gid: number;
16
+ /** Seconds since the epoch; fractional only when a PAX record carries sub-second time. */
17
+ mtime: number;
18
+ /** Symlink target or hard link target member name; empty for other types. */
19
+ linkName: string;
20
+ body: AsyncIterable<Uint8Array>;
21
+ }
22
+ /** Yield each member once; an unconsumed body is skipped when the next member is requested. */
23
+ export declare function readWorkspaceArchive(chunks: AsyncIterable<Uint8Array>): AsyncGenerator<WorkspaceArchiveMember>;
@@ -0,0 +1,222 @@
1
+ const BLOCK = 512;
2
+ // Bounds a PAX or GNU long-name record, which the reader holds in memory.
3
+ const MAX_METADATA_BYTES = 1024 * 1024;
4
+ // Bounds the zero padding read after the end-of-archive marker.
5
+ const MAX_TRAILING_BYTES = 1024 * 1024;
6
+ class ArchiveBytes {
7
+ chunks = [];
8
+ buffered = 0;
9
+ ended = false;
10
+ source;
11
+ constructor(source) { this.source = source; }
12
+ /** Buffer the next non-empty chunk; false at the end of the source. */
13
+ async fill() {
14
+ while (!this.ended) {
15
+ const next = await this.source.next();
16
+ if (next.done) {
17
+ this.ended = true;
18
+ break;
19
+ }
20
+ if (next.value.byteLength) {
21
+ this.chunks.push(next.value);
22
+ this.buffered += next.value.byteLength;
23
+ return true;
24
+ }
25
+ }
26
+ return false;
27
+ }
28
+ async exact(length) {
29
+ while (this.buffered < length)
30
+ if (!await this.fill())
31
+ throw new Error("Tangle workspace archive is truncated");
32
+ const out = new Uint8Array(length);
33
+ let offset = 0;
34
+ for await (const piece of this.span(length)) {
35
+ out.set(piece, offset);
36
+ offset += piece.byteLength;
37
+ }
38
+ return out;
39
+ }
40
+ /** The next buffered piece, at most `limit` bytes. */
41
+ async next(limit) {
42
+ if (!this.buffered && !await this.fill())
43
+ throw new Error("Tangle workspace archive is truncated");
44
+ const head = this.chunks[0];
45
+ const piece = head.byteLength <= limit ? head : head.subarray(0, limit);
46
+ if (piece === head)
47
+ this.chunks.shift();
48
+ else
49
+ this.chunks[0] = head.subarray(limit);
50
+ this.buffered -= piece.byteLength;
51
+ return piece;
52
+ }
53
+ async *span(length) {
54
+ for (let left = length; left > 0;) {
55
+ const piece = await this.next(left);
56
+ left -= piece.byteLength;
57
+ yield piece;
58
+ }
59
+ }
60
+ async *rest() {
61
+ for (;;) {
62
+ if (!this.buffered && !await this.fill())
63
+ return;
64
+ const head = this.chunks.shift();
65
+ this.buffered -= head.byteLength;
66
+ yield head;
67
+ }
68
+ }
69
+ }
70
+ function text(block, offset, length) {
71
+ const field = block.subarray(offset, offset + length);
72
+ const end = field.indexOf(0);
73
+ return Buffer.from(end === -1 ? field : field.subarray(0, end)).toString("utf8");
74
+ }
75
+ function number(block, offset, length) {
76
+ const field = block.subarray(offset, offset + length);
77
+ if (field[0] & 0x80) {
78
+ // GNU base-256: a positive big-endian value after the marker bit.
79
+ if (field[0] & 0x40)
80
+ throw new Error("Tangle workspace archive has a negative numeric field");
81
+ let value = field[0] & 0x3f;
82
+ for (const byte of field.subarray(1))
83
+ value = value * 256 + byte;
84
+ if (!Number.isSafeInteger(value))
85
+ throw new Error("Tangle workspace archive numeric field is too large");
86
+ return value;
87
+ }
88
+ const digits = text(block, offset, length).trim();
89
+ if (!digits)
90
+ return 0;
91
+ if (!/^[0-7]+$/.test(digits))
92
+ throw new Error("Tangle workspace archive has an invalid numeric field");
93
+ const value = parseInt(digits, 8);
94
+ if (!Number.isSafeInteger(value))
95
+ throw new Error("Tangle workspace archive numeric field is too large");
96
+ return value;
97
+ }
98
+ function verifyChecksum(block) {
99
+ let sum = 0;
100
+ for (let index = 0; index < BLOCK; index++)
101
+ sum += index >= 148 && index < 156 ? 0x20 : block[index];
102
+ if (sum !== number(block, 148, 8))
103
+ throw new Error("Tangle workspace archive header checksum mismatch");
104
+ }
105
+ function paxRecords(bytes) {
106
+ const records = new Map();
107
+ const source = Buffer.from(bytes);
108
+ let offset = 0;
109
+ while (offset < source.byteLength) {
110
+ const space = source.indexOf(0x20, offset);
111
+ if (space === -1)
112
+ throw new Error("Tangle workspace archive has a malformed PAX record");
113
+ const length = Number(source.subarray(offset, space).toString("ascii"));
114
+ if (!Number.isSafeInteger(length) || length <= space - offset + 1 || offset + length > source.byteLength ||
115
+ source[offset + length - 1] !== 0x0a) {
116
+ throw new Error("Tangle workspace archive has a malformed PAX record");
117
+ }
118
+ const record = source.subarray(space + 1, offset + length - 1).toString("utf8");
119
+ const equals = record.indexOf("=");
120
+ if (equals < 1)
121
+ throw new Error("Tangle workspace archive has a malformed PAX record");
122
+ records.set(record.slice(0, equals), record.slice(equals + 1));
123
+ offset += length;
124
+ }
125
+ return records;
126
+ }
127
+ function paxNumber(value, fallback, integer) {
128
+ if (value === undefined)
129
+ return fallback;
130
+ const parsed = Number(value);
131
+ if (!Number.isFinite(parsed) || parsed < 0 || (integer && !Number.isSafeInteger(parsed))) {
132
+ throw new Error("Tangle workspace archive has an invalid PAX number");
133
+ }
134
+ return parsed;
135
+ }
136
+ function padding(size) {
137
+ return (BLOCK - (size % BLOCK)) % BLOCK;
138
+ }
139
+ /** Yield each member once; an unconsumed body is skipped when the next member is requested. */
140
+ export async function* readWorkspaceArchive(chunks) {
141
+ const bytes = new ArchiveBytes(chunks[Symbol.asyncIterator]());
142
+ let pax;
143
+ let longName;
144
+ let longLink;
145
+ for (;;) {
146
+ const block = await bytes.exact(BLOCK);
147
+ if (block.every((byte) => byte === 0)) {
148
+ if (!(await bytes.exact(BLOCK)).every((byte) => byte === 0))
149
+ throw new Error("Tangle workspace archive has a malformed end marker");
150
+ let trailing = 0;
151
+ for await (const tail of bytes.rest()) {
152
+ trailing += tail.byteLength;
153
+ if (trailing > MAX_TRAILING_BYTES || !tail.every((byte) => byte === 0)) {
154
+ throw new Error("Tangle workspace archive has data after its end marker");
155
+ }
156
+ }
157
+ if (pax || longName !== undefined || longLink !== undefined)
158
+ throw new Error("Tangle workspace archive ends inside a member");
159
+ return;
160
+ }
161
+ verifyChecksum(block);
162
+ const magic = text(block, 257, 6);
163
+ if (magic !== "ustar" && magic !== "ustar ")
164
+ throw new Error("Tangle workspace archive has an unknown header format");
165
+ const flag = String.fromCharCode(block[156]);
166
+ const headerSize = number(block, 124, 12);
167
+ if (flag === "x" || flag === "L" || flag === "K") {
168
+ if (headerSize > MAX_METADATA_BYTES)
169
+ throw new Error("Tangle workspace archive metadata record is too large");
170
+ const record = await bytes.exact(headerSize);
171
+ await bytes.exact(padding(headerSize));
172
+ if (flag === "x")
173
+ pax = paxRecords(record);
174
+ else if (flag === "L")
175
+ longName = text(record, 0, record.byteLength);
176
+ else
177
+ longLink = text(record, 0, record.byteLength);
178
+ continue;
179
+ }
180
+ if (flag === "g")
181
+ throw new Error("Tangle workspace archive has an unsupported global header");
182
+ const type = flag === "0" || flag === "\0" || flag === "7" ? "file"
183
+ : flag === "5" ? "directory" : flag === "2" ? "symlink" : flag === "1" ? "link" : undefined;
184
+ if (!type)
185
+ throw new Error("Tangle workspace contains an unsupported file type");
186
+ // The POSIX prefix field holds GNU-only data in an old-GNU ("ustar ") header.
187
+ const prefix = magic === "ustar" ? text(block, 345, 155) : "";
188
+ const headerName = prefix ? `${prefix}/${text(block, 0, 100)}` : text(block, 0, 100);
189
+ let name = pax?.get("path") ?? longName ?? headerName;
190
+ if (type === "directory")
191
+ name = name.replace(/\/$/, "");
192
+ const size = paxNumber(pax?.get("size"), headerSize, true);
193
+ if (type !== "file" && size !== 0)
194
+ throw new Error("Tangle workspace archive gives a non-file member a body");
195
+ const member = {
196
+ name,
197
+ type,
198
+ size,
199
+ mode: number(block, 100, 8) & 0o7777,
200
+ uid: paxNumber(pax?.get("uid"), number(block, 108, 8), true),
201
+ gid: paxNumber(pax?.get("gid"), number(block, 116, 8), true),
202
+ mtime: paxNumber(pax?.get("mtime"), number(block, 136, 12), false),
203
+ linkName: pax?.get("linkpath") ?? longLink ?? text(block, 157, 100),
204
+ };
205
+ pax = undefined;
206
+ longName = undefined;
207
+ longLink = undefined;
208
+ // The count lives outside the generator, so a consumer that stops early still leaves the
209
+ // reader able to skip exactly the unread rest of the body.
210
+ let left = size;
211
+ const body = (async function* () {
212
+ while (left > 0) {
213
+ const piece = await bytes.next(left);
214
+ left -= piece.byteLength;
215
+ yield piece;
216
+ }
217
+ })();
218
+ yield { ...member, body };
219
+ for await (const _ of bytes.span(left)) { /* discard */ }
220
+ await bytes.exact(padding(size));
221
+ }
222
+ }
@@ -75,6 +75,12 @@ export interface TangleEnvironmentEvidence {
75
75
  reportedFiles: number;
76
76
  reportedDirectories: number;
77
77
  complete: boolean;
78
+ /** Bytes and SHA-256 of each top-level directory archive stream whose contents were read. */
79
+ archives: Array<{
80
+ path: string;
81
+ sizeBytes: number;
82
+ sha256: string;
83
+ }>;
78
84
  };
79
85
  attempts: TangleEvidenceAttemptLike[];
80
86
  sessions: Array<{
@@ -5,6 +5,7 @@ import { prepareNativeDirectoryEvidence, nativePayloadChunks } from "./tangle-ev
5
5
  import { AgentExactRunControlRefSchema } from "@tangle-network/agent-interface";
6
6
  import { requireNativeCaptureProof } from "./tangle-native-capture-proof.js";
7
7
  import { retainedCaptureAttribution } from "./tangle-retained-attribution.js";
8
+ import { readWorkspaceArchive } from "./tangle-evidence-tar.js";
8
9
  const handles = new WeakMap();
9
10
  const blockedNames = new Set([".ssh", ".config", ".claude", ".codex", ".opencode", ".env", ".env.local", ".npmrc", ".sidecar"]);
10
11
  const MAX_ENTRIES = 100_000;
@@ -60,6 +61,10 @@ async function* bufferedExecutionEvents(session, executionId, signal) {
60
61
  // Match the Sidecar request limit without accumulating 100 large JSON payloads.
61
62
  const WORKSPACE_BATCH_FILES = 100;
62
63
  const WORKSPACE_BATCH_BYTES = 8 * 1024 * 1024;
64
+ // Top-level directory archives read at once.
65
+ const WORKSPACE_ARCHIVE_STREAMS = 4;
66
+ // Tar header, PAX record and padding bytes an archive may add per member beyond its content.
67
+ const WORKSPACE_ARCHIVE_ENTRY_OVERHEAD = 2048;
63
68
  export function bindTangleEvidenceEnvironment(environment, box) {
64
69
  handles.set(environment, { box, sessions: new Map() });
65
70
  }
@@ -174,9 +179,10 @@ async function captureSandboxEvidence(box, options, writer) {
174
179
  // Only the environment scope reads through it, after the check above.
175
180
  const fs = boxFs;
176
181
  options.signal?.throwIfAborted();
177
- const usage = workspaceScope === "none"
178
- ? { complete: true, skippedEntries: 0, sizeBytes: 0, fileCount: 0, directoryCount: 0 }
179
- : await fs.usage(workspaceRoot);
182
+ // The root listing is requested with the usage scan; neither depends on the other.
183
+ const [usage, rootEntries] = workspaceScope === "none"
184
+ ? [{ complete: true, skippedEntries: 0, sizeBytes: 0, fileCount: 0, directoryCount: 0 }, []]
185
+ : await Promise.all([fs.usage(workspaceRoot), fs.list(workspaceRoot, { all: true, long: true })]);
180
186
  if (!usage.complete || usage.skippedEntries !== 0)
181
187
  throw new Error("Tangle workspace usage scan is incomplete");
182
188
  if (usage.sizeBytes > options.maxBytes)
@@ -184,11 +190,13 @@ async function captureSandboxEvidence(box, options, writer) {
184
190
  const metadata = [];
185
191
  const seenPaths = new Set();
186
192
  const excludedPaths = [];
187
- const stack = workspaceScope === "none" ? [] : [workspaceRoot];
193
+ const archiveReceipts = [];
188
194
  let scannedFiles = 0;
189
195
  let scannedDirectories = 0;
190
196
  let scannedEntries = 0;
191
197
  let scannedSize = 0;
198
+ let ignoredBytes = 0;
199
+ let archiveMembers = 0;
192
200
  let capturedBytes = 0;
193
201
  let pending = [];
194
202
  let pendingBytes = 0;
@@ -210,75 +218,246 @@ async function captureSandboxEvidence(box, options, writer) {
210
218
  pending = [];
211
219
  pendingBytes = 0;
212
220
  };
213
- while (stack.length) {
214
- options.signal?.throwIfAborted();
215
- const directory = stack.pop();
216
- const entries = await fs.list(directory, { all: true, long: true });
217
- if (!Array.isArray(entries))
221
+ const readLater = async (entry) => {
222
+ if (pending.length && (pending.length >= WORKSPACE_BATCH_FILES || pendingBytes + entry.size > WORKSPACE_BATCH_BYTES)) {
223
+ await flushWorkspaceFiles();
224
+ }
225
+ if (entry.size > options.maxBytes - capturedBytes - pendingBytes)
226
+ throw new Error("Tangle evidence exceeds byte limit");
227
+ pending.push(entry);
228
+ pendingBytes += entry.size;
229
+ };
230
+ // Classify one entry, from the root listing or an archive member, exactly as the former
231
+ // directory-by-directory walk did: "walk" captures a directory's contents, "blocked" only
232
+ // accounts for them, "retain" captures a file, "omit" keeps metadata only.
233
+ const admit = (path, item) => {
234
+ if (++scannedEntries > MAX_ENTRIES)
235
+ throw new Error("Tangle workspace entry limit exceeded");
236
+ if (seenPaths.has(path))
237
+ throw new Error("Tangle workspace inventory repeats a path");
238
+ seenPaths.add(path);
239
+ metadata.push(item);
240
+ const parts = path.split("/");
241
+ if (parts.includes(".sidecar")) {
242
+ excludedPaths.push({ ...item, reason: "runtime-owned" });
243
+ return "omit";
244
+ }
245
+ if (item.type === "directory") {
246
+ scannedDirectories++;
247
+ if (parts.some((part) => blockedNames.has(part))) {
248
+ excludedPaths.push({ ...item, reason: "credential-path" });
249
+ return "blocked";
250
+ }
251
+ return "walk";
252
+ }
253
+ scannedFiles++;
254
+ scannedSize += item.sizeBytes;
255
+ if (scannedSize > usage.sizeBytes)
256
+ throw new Error("Tangle workspace inventory does not match the complete usage scan");
257
+ if (item.type === "symlink") {
258
+ excludedPaths.push({ ...item, reason: "symlink" });
259
+ return "omit";
260
+ }
261
+ if (parts.some((part) => blockedNames.has(part) || /^\.env\./.test(part))) {
262
+ excludedPaths.push({ ...item, reason: "credential-path" });
263
+ return "omit";
264
+ }
265
+ return "retain";
266
+ };
267
+ // The root is listed once. Each top-level directory then arrives as one archive stream: listing
268
+ // every directory cost about 0.5 s per request, 62-73 s of a 121 s capture of a 2,500-file
269
+ // workspace on 2026-10-19, and the serial batch reads most of the rest. Credential and
270
+ // runtime-owned top-level directories are never archived, so their bytes stay in the box. A
271
+ // credential path nested in an archived directory crosses the wire inside its archive and is
272
+ // dropped in memory; the Sidecar archive route has no exclusion filter yet.
273
+ const archives = [];
274
+ // Credential subtree scans run alongside the archive downloads; each only adds to the totals.
275
+ const blockedScans = [];
276
+ if (workspaceScope === "environment") {
277
+ if (!Array.isArray(rootEntries))
218
278
  throw new Error("Tangle workspace list is malformed");
219
- for (const entry of entries) {
220
- if (++scannedEntries > MAX_ENTRIES)
221
- throw new Error("Tangle workspace entry limit exceeded");
279
+ for (const entry of rootEntries) {
222
280
  const sourcePath = canonicalEntryPath(entry.path);
223
281
  if (workspaceRoot !== "." && !sourcePath.startsWith(workspaceRoot + "/")) {
224
282
  throw new Error("Tangle workspace list returned a path outside its worker directory");
225
283
  }
226
284
  const path = workspaceRoot === "." ? sourcePath : canonicalEntryPath(sourcePath.slice(workspaceRoot.length + 1));
227
- if (seenPaths.has(path))
228
- throw new Error("Tangle workspace inventory repeats a path");
229
- seenPaths.add(path);
230
285
  const expectedParent = sourcePath.includes("/") ? sourcePath.slice(0, sourcePath.lastIndexOf("/")) : ".";
231
- if (expectedParent !== directory || entry.name !== path.split("/").at(-1))
286
+ if (expectedParent !== workspaceRoot || entry.name !== path)
232
287
  throw new Error("Tangle workspace list returned a path outside its parent");
233
288
  if (!Number.isSafeInteger(entry.size) || entry.size < 0)
234
289
  throw new Error("Tangle workspace entry has invalid size");
235
290
  const item = entryMetadata(path, entry);
236
- metadata.push(item);
237
- if (path.split("/").includes(".sidecar")) {
238
- excludedPaths.push({ ...item, reason: "runtime-owned" });
239
- continue;
240
- }
241
- if (entry.isDir && !entry.isSymlink) {
242
- scannedDirectories++;
243
- if (path.split("/").some((part) => blockedNames.has(part))) {
244
- excludedPaths.push({ ...item, reason: "credential-path" });
245
- // Nothing below a credential directory is read, so none of it is listed either: one
246
- // complete usage scan accounts for its subtree against the workspace totals. Listing it
247
- // cost one request per directory; .opencode/node_modules alone was 271 of a capture's
248
- // 302 list calls and about 100 s of each two-minute workspace capture on 2026-10-06.
249
- options.signal?.throwIfAborted();
250
- const subtree = await fs.usage(sourcePath);
291
+ const decision = admit(path, item);
292
+ if (decision === "walk")
293
+ archives.push({ sourcePath, path });
294
+ else if (decision === "retain")
295
+ await readLater({ sourcePath, path, size: entry.size, mode: entry.permissions & 0o777 });
296
+ else if (decision === "blocked") {
297
+ // Nothing below a credential directory is read: one complete usage scan accounts for its
298
+ // subtree against the workspace totals.
299
+ const scan = fs.usage(sourcePath).then((subtree) => {
251
300
  if (!subtree.complete || subtree.skippedEntries !== 0)
252
301
  throw new Error("Tangle workspace usage scan is incomplete");
253
302
  scannedDirectories += subtree.directoryCount;
254
303
  scannedFiles += subtree.fileCount;
255
304
  scannedSize += subtree.sizeBytes;
256
- continue;
305
+ });
306
+ // Awaited after the archives; a failure must not surface as unhandled before then.
307
+ scan.catch(() => { });
308
+ blockedScans.push(scan);
309
+ }
310
+ }
311
+ }
312
+ if (archives.length) {
313
+ if (!fs.openArchive)
314
+ throw new Error("Tangle evidence requires workspace directory archive streaming");
315
+ const { Readable } = await import("node:stream");
316
+ const { createGunzip } = await import("node:zlib");
317
+ // Archives are read from the network straight through gunzip and the tar reader; no archive
318
+ // byte is written to disk, so a credential file nested in a project directory is never at rest
319
+ // outside the box, even if this process dies mid-capture.
320
+ const streams = new AbortController();
321
+ const cancel = () => streams.abort(options.signal?.reason);
322
+ options.signal?.addEventListener("abort", cancel, { once: true });
323
+ if (options.signal?.aborted)
324
+ cancel();
325
+ const archiveLimit = options.maxBytes + MAX_ENTRIES * WORKSPACE_ARCHIVE_ENTRY_OVERHEAD;
326
+ // Hard links are read through the batch path once every archive is done.
327
+ const linkReads = [];
328
+ const readArchive = async (index) => {
329
+ const archive = archives[index];
330
+ // Each archive is read from the moment its request opens: a response body left unread
331
+ // waits on the Sidecar, and one that ends early arrives as a truncated stream.
332
+ const body = await fs.openArchive(archive.sourcePath, { signal: streams.signal });
333
+ const digest = createHash("sha256");
334
+ let archiveBytes = 0;
335
+ const counted = async function* () {
336
+ for await (const chunk of body) {
337
+ archiveBytes += chunk.byteLength;
338
+ if (archiveBytes > archiveLimit)
339
+ throw new Error("Tangle evidence workspace archive exceeds its byte limit");
340
+ digest.update(chunk);
341
+ yield chunk;
342
+ }
343
+ };
344
+ const source = Readable.from(counted());
345
+ const gunzip = createGunzip();
346
+ source.on("error", (error) => gunzip.destroy(error));
347
+ source.pipe(gunzip);
348
+ // Hard link members carry no body; they take the size of the member they name.
349
+ const fileSizes = new Map();
350
+ try {
351
+ for await (const member of readWorkspaceArchive(gunzip)) {
352
+ streams.signal.throwIfAborted();
353
+ // Every member counts, including those below credential and runtime-owned paths that
354
+ // are never admitted, so a stream of empty headers cannot run unbounded.
355
+ if (++archiveMembers > MAX_ENTRIES)
356
+ throw new Error("Tangle workspace entry limit exceeded");
357
+ const name = canonicalEntryPath(member.name);
358
+ const sourcePath = `${archive.sourcePath}/${name}`;
359
+ const path = `${archive.path}/${name}`;
360
+ const size = member.type === "file" ? member.size
361
+ : member.type === "symlink" ? Buffer.byteLength(member.linkName)
362
+ : member.type === "link" ? fileSizes.get(member.linkName) : 0;
363
+ if (size === undefined)
364
+ throw new Error("Tangle workspace archive links to an unknown member");
365
+ if (member.type === "file")
366
+ fileSizes.set(name, size);
367
+ // The former walk never listed below a runtime-owned or credential directory; the
368
+ // usage scan counted credential subtrees, so their members are counted, not admitted.
369
+ const ancestors = path.split("/").slice(0, -1);
370
+ const stop = ancestors.find((part) => blockedNames.has(part));
371
+ if (stop === ".sidecar") {
372
+ // Never admitted or counted, but its declared bytes still bound the decompression.
373
+ ignoredBytes += size;
374
+ if (ignoredBytes > options.maxBytes)
375
+ throw new Error("Tangle evidence exceeds byte limit");
376
+ continue;
377
+ }
378
+ if (stop !== undefined) {
379
+ if (member.type === "directory") {
380
+ scannedDirectories++;
381
+ }
382
+ else {
383
+ scannedFiles++;
384
+ scannedSize += size;
385
+ }
386
+ if (scannedSize > usage.sizeBytes || scannedFiles > usage.fileCount || scannedDirectories > usage.directoryCount) {
387
+ throw new Error("Tangle workspace inventory does not match the complete usage scan");
388
+ }
389
+ continue;
390
+ }
391
+ const item = {
392
+ path,
393
+ type: member.type === "link" ? "file" : member.type,
394
+ sizeBytes: size,
395
+ mode: member.mode & 0o777,
396
+ owner: String(member.uid),
397
+ group: String(member.gid),
398
+ modifiedAt: new Date(member.mtime * 1000).toISOString(),
399
+ // The archive records no access time.
400
+ accessedAt: null,
401
+ symlinkTarget: null,
402
+ };
403
+ if (admit(path, item) !== "retain")
404
+ continue;
405
+ if (member.type === "link") {
406
+ linkReads.push({ sourcePath, path, size, mode: item.mode });
407
+ continue;
408
+ }
409
+ if (size > options.maxBytes - capturedBytes)
410
+ throw new Error("Tangle evidence exceeds byte limit");
411
+ if (await writer.writeChunks(path, item.mode, member.body) !== size) {
412
+ throw new Error(`Tangle evidence workspace file changed or was truncated: ${path}`);
413
+ }
414
+ capturedBytes += size;
257
415
  }
258
- stack.push(sourcePath);
259
- continue;
260
416
  }
261
- if (!entry.isFile && !entry.isSymlink)
262
- throw new Error("Tangle workspace contains an unsupported file type");
263
- scannedFiles++;
264
- scannedSize += entry.size;
265
- if (entry.isSymlink) {
266
- excludedPaths.push({ ...item, reason: "symlink" });
267
- continue;
417
+ finally {
418
+ gunzip.destroy();
419
+ source.destroy();
268
420
  }
269
- if (path.split("/").some((part) => blockedNames.has(part) || /^\.env\./.test(part))) {
270
- excludedPaths.push({ ...item, reason: "credential-path" });
271
- continue;
421
+ // The reader drains gunzip to its end, so the digest covers every streamed byte.
422
+ archiveReceipts[index] = { path: archive.path, sizeBytes: archiveBytes, sha256: digest.digest("hex") };
423
+ };
424
+ let next = 0;
425
+ // The first failure in time is the one reported; the others are its abort echoes.
426
+ let firstError;
427
+ const stopOnFailure = async (work) => {
428
+ try {
429
+ await work();
272
430
  }
273
- if (pending.length && (pending.length >= WORKSPACE_BATCH_FILES || pendingBytes + entry.size > WORKSPACE_BATCH_BYTES)) {
274
- await flushWorkspaceFiles();
431
+ catch (error) {
432
+ firstError ??= { error };
433
+ streams.abort(error);
434
+ }
435
+ };
436
+ const worker = async () => {
437
+ while (next < archives.length) {
438
+ streams.signal.throwIfAborted();
439
+ await readArchive(next++);
275
440
  }
276
- if (entry.size > options.maxBytes - capturedBytes - pendingBytes)
277
- throw new Error("Tangle evidence exceeds byte limit");
278
- pending.push({ sourcePath, path, size: entry.size, mode: entry.permissions & 0o777 });
279
- pendingBytes += entry.size;
441
+ };
442
+ try {
443
+ // Top-level files are read while the archives stream.
444
+ await Promise.all([
445
+ stopOnFailure(flushWorkspaceFiles),
446
+ ...Array.from({ length: Math.min(WORKSPACE_ARCHIVE_STREAMS, archives.length) }, () => stopOnFailure(worker)),
447
+ ]);
448
+ // Assigned inside the workers; read it through a wider type than the narrowed let.
449
+ const failure = firstError;
450
+ if (failure)
451
+ throw failure.error;
452
+ }
453
+ finally {
454
+ streams.abort();
455
+ options.signal?.removeEventListener("abort", cancel);
280
456
  }
457
+ for (const entry of linkReads)
458
+ await readLater(entry);
281
459
  }
460
+ await Promise.all(blockedScans);
282
461
  if (scannedFiles !== usage.fileCount || scannedDirectories !== usage.directoryCount || scannedSize !== usage.sizeBytes) {
283
462
  throw new Error("Tangle workspace inventory does not match the complete usage scan");
284
463
  }
@@ -805,7 +984,7 @@ async function captureSandboxEvidence(box, options, writer) {
805
984
  capturedAt: new Date().toISOString(),
806
985
  entries: metadata.sort((a, b) => a.path.localeCompare(b.path)),
807
986
  excludedPaths,
808
- workspace: { scannedFiles, scannedDirectories, reportedFiles: usage.fileCount, reportedDirectories: usage.directoryCount, complete: workspaceScope === "environment" },
987
+ workspace: { scannedFiles, scannedDirectories, reportedFiles: usage.fileCount, reportedDirectories: usage.directoryCount, complete: workspaceScope === "environment", archives: archiveReceipts },
809
988
  attempts,
810
989
  sessions,
811
990
  missing,
@@ -0,0 +1,5 @@
1
+ import type { AgentEnvironmentProvider } from "@tangle-network/agent-interface/environment-provider";
2
+ type ProfileValidator = NonNullable<AgentEnvironmentProvider["validateProfile"]>;
3
+ /** The provider's validateProfile: the Sandbox mount check, then any caller-supplied validator. */
4
+ export declare function tangleProfileValidator(supplied?: ProfileValidator): ProfileValidator;
5
+ export {};
@@ -0,0 +1,38 @@
1
+ import { splitInlineProfileFileMounts, validateDeferredProfileFileMounts } from "@tangle-network/sandbox";
2
+ /**
3
+ * The Sandbox SDK's own create-time check of a profile's inline file mounts, run before any box
4
+ * exists. create() refuses the same input, but only once a caller has already committed to the
5
+ * spawn; a coordinator that checks first can return the refusal to whoever asked for the worker.
6
+ */
7
+ function profileFileMountIssues(profile) {
8
+ if (typeof profile === "string")
9
+ return [];
10
+ const { deferredFiles } = splitInlineProfileFileMounts(profile);
11
+ if (!deferredFiles.length)
12
+ return [];
13
+ try {
14
+ validateDeferredProfileFileMounts(deferredFiles);
15
+ return [];
16
+ }
17
+ catch (error) {
18
+ const detail = error;
19
+ return [{
20
+ level: "error",
21
+ code: typeof detail.code === "string" ? detail.code : "PROFILE_FILE_MOUNT_INVALID",
22
+ message: typeof detail.message === "string" ? detail.message : String(error),
23
+ ...(typeof detail.path === "string" ? { path: detail.path } : {}),
24
+ }];
25
+ }
26
+ }
27
+ /** The provider's validateProfile: the Sandbox mount check, then any caller-supplied validator. */
28
+ export function tangleProfileValidator(supplied) {
29
+ return async (profile) => {
30
+ const issues = profileFileMountIssues(profile);
31
+ const result = supplied ? await supplied(profile) : undefined;
32
+ return {
33
+ ok: !issues.some((issue) => issue.level === "error") && (result?.ok ?? true),
34
+ issues: [...issues, ...(result?.issues ?? [])],
35
+ ...(result?.normalizedProfile ? { normalizedProfile: result.normalizedProfile } : {}),
36
+ };
37
+ };
38
+ }
@@ -3,6 +3,7 @@ import { canonicalCandidateDigest, deepFreeze, harnessTypeSchema } from "@tangle
3
3
  import { createTangleExactProcessProvider, } from "./exact-process.js";
4
4
  import { capabilitiesForClient, defaultTangleSandboxCapabilities, narrowTangleCapabilitiesToBackend, } from "./tangle-capabilities.js";
5
5
  import { sandboxInstanceAsEnvironment } from "./tangle-environment.js";
6
+ import { tangleProfileValidator } from "./tangle-profile-validation.js";
6
7
  import { confidentialVerifierOption, createTangleWorkspaceBranching, } from "./tangle-workspace-branching.js";
7
8
  import { assertCreateInputShape, assertMappedCreateOptions, assertMappedSecretNames, assertNoInlineSecretValues, captureModelCredentials, createRoutingFromProviderOptions, NATIVE_RESUME_CHECKPOINT_METADATA_KEY, sandboxOptionsFromCreateInput, sandboxRestoreFromCheckpoint } from "./tangle-create-options.js";
8
9
  import { assertProxySecretAliases, captureProxySecrets, mergeProxySecrets, proxySecretsFromInput, proxySecretCapabilityFromDocument, PROXY_SECRETS_METADATA_KEY, rebindProxySecrets, requireProxySecretCapability } from "./tangle-proxy-secrets.js";
@@ -322,7 +323,7 @@ export function createTangleProvider(options) {
322
323
  ...(exactProcess ? { exactProcess } : {}),
323
324
  ...(workspaceBranching === undefined ? {} : { workspaceBranching }),
324
325
  capabilities: resolveCapabilities,
325
- ...(options.validateProfile ? { validateProfile: options.validateProfile } : {}),
326
+ validateProfile: tangleProfileValidator(options.validateProfile),
326
327
  async create(input) {
327
328
  const { signal, ...material } = input;
328
329
  signal?.throwIfAborted();
@@ -478,6 +478,10 @@ export interface SandboxInstanceLike {
478
478
  sizeBytes: number;
479
479
  sha256: string;
480
480
  }>;
481
+ /** A directory's tar.gz bytes as one stream; the caller reads it to the end or cancels it. */
482
+ openArchive?(remoteDir: string, options?: {
483
+ signal?: AbortSignal;
484
+ }): Promise<ReadableStream<Uint8Array>>;
481
485
  stat(path: string): Promise<{
482
486
  size: number;
483
487
  isFile: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-provider-tangle",
3
- "version": "4.4.2",
3
+ "version": "4.4.4",
4
4
  "description": "AgentEnvironmentProvider adapter for Tangle sandboxes",
5
5
  "type": "module",
6
6
  "license": "MIT",