@tangle-network/sandbox 0.60.1 → 0.60.3

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.
@@ -16,6 +16,20 @@ function id(value) {
16
16
  if (!/^[A-Za-z0-9][A-Za-z0-9_.:@-]*$/.test(result)) throw new TypeError("Invalid line application identity");
17
17
  return result;
18
18
  }
19
+ function subjectId(value) {
20
+ if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9:._-]{0,127}$/.test(value)) throw new TypeError("Invalid line application subject");
21
+ return value;
22
+ }
23
+ function revision(value) {
24
+ const result = text(value, 64);
25
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(result) || !Number.isFinite(Date.parse(result)) || new Date(result).toISOString() !== result) throw new TypeError("Invalid line member revision");
26
+ return result;
27
+ }
28
+ function deadline(value) {
29
+ const result = text(value, 64);
30
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(result) || !Number.isFinite(Date.parse(result)) || new Date(result).toISOString() !== result) throw new TypeError("Invalid line dispatch deadline");
31
+ return result;
32
+ }
19
33
  function binding(value) {
20
34
  const result = text(value, 1024);
21
35
  if (!/^[\x21-\x7e]+$/.test(result)) throw new TypeError("Invalid line application binding");
@@ -30,6 +44,12 @@ function parseLineApplicationRequest(value) {
30
44
  if (transport !== "imessage" && transport !== "sms" && transport !== "whatsapp" && transport !== "email") throw new TypeError("Unknown line transport");
31
45
  const receivedAt = text(input.receivedAt, 64);
32
46
  if (!Number.isFinite(Date.parse(receivedAt))) throw new TypeError("Invalid line message time");
47
+ const hasSubject = input.subjectId !== void 0;
48
+ const hasRevision = input.memberRevision !== void 0;
49
+ if (hasSubject !== hasRevision) throw new TypeError("Incomplete line member authority");
50
+ const hasFence = input.dispatchFence !== void 0;
51
+ const hasDeadline = input.dispatchDeadline !== void 0;
52
+ if (hasFence !== hasDeadline || hasSubject && !hasFence && input.acceptedExecutionId === void 0) throw new TypeError("Incomplete line dispatch authority");
33
53
  const result = {
34
54
  version: 1,
35
55
  binding: binding(input.binding),
@@ -39,6 +59,10 @@ function parseLineApplicationRequest(value) {
39
59
  memberId: id(input.memberId),
40
60
  lineThreadId: id(input.lineThreadId),
41
61
  ownerUserId: id(input.ownerUserId),
62
+ ...hasSubject ? { subjectId: subjectId(input.subjectId) } : {},
63
+ ...hasRevision ? { memberRevision: revision(input.memberRevision) } : {},
64
+ ...hasFence ? { dispatchFence: id(input.dispatchFence) } : {},
65
+ ...hasDeadline ? { dispatchDeadline: deadline(input.dispatchDeadline) } : {},
42
66
  sender: {
43
67
  address: text(sender.address, 320),
44
68
  role: id(sender.role)
@@ -1,4 +1,4 @@
1
- import { B as CreateSandboxOptions, d as BackendConfig } from "./types-BQlqLwrK.js";
1
+ import { B as CreateSandboxOptions, d as BackendConfig } from "./types-C9w6MdZB.js";
2
2
 
3
3
  //#region src/line-application.d.ts
4
4
  /** Bounded callback request bytes after canonicalization, including JSON framing. */
@@ -26,6 +26,14 @@ interface LineApplicationRequest {
26
26
  memberId: string;
27
27
  lineThreadId: string;
28
28
  ownerUserId: string;
29
+ /** Owner-authored customer identity from the current declared Hub member. */
30
+ subjectId?: string;
31
+ /** Hub member authority revision. A later consent or STOP invalidates this callback. */
32
+ memberRevision?: string;
33
+ /** Unique Hub lease attempt for one callback admission. */
34
+ dispatchFence?: string;
35
+ /** Latest UTC time at which the application may admit new work. */
36
+ dispatchDeadline?: string;
29
37
  /** Native transport framing is not an application user identity. */
30
38
  sender: {
31
39
  address: string;
@@ -103,8 +111,9 @@ interface LineMemberSpec {
103
111
  /** A role name from the attachment's `roles`. */
104
112
  role: string;
105
113
  label?: string;
106
- /** Opaque, owner-verified customer/enrollment identity, not a phone number.
107
- * With member instances it keys the private home across addresses. A new
114
+ /** Opaque, owner-authored customer identity, not a phone number.
115
+ * With member instances it keys the private home across addresses. A shared
116
+ * application line passes it to the authorized callback. A new
108
117
  * customer at a recycled address must receive a new subjectId. */
109
118
  subjectId?: string;
110
119
  /** This member's allowance subject; requires limits.allowance.perMember.
@@ -269,8 +278,8 @@ interface LineAttachOptions {
269
278
  /**
270
279
  * Default: owner and member share context and act; guest is own-context and chat-only.
271
280
  * One sandbox serves every member, and `act` tools can read every member's session in it.
272
- * A shared attachment that uses an `own`-context role is refused unless every role in use is `chat`,
273
- * or each member runs in their own sandbox (`client.lines.attach()` with `instance`).
281
+ * An `own`-context role cannot use `act` in a shared sandbox.
282
+ * Member instances or a targetless application provide separate execution.
274
283
  */
275
284
  roles?: Record<string, LineRole>;
276
285
  respond?: LineRespondAgent;
@@ -297,6 +306,21 @@ interface LineMemberInstance {
297
306
  type LineInstanceAttachOptions = LineAttachOptions & {
298
307
  instance: LineMemberInstance;
299
308
  };
309
+ /** One callback carries each declared member's customer subject to the application. */
310
+ type LineApplicationAttachOptions = Omit<LineAttachOptions, "mode" | "members" | "unknownSenders" | "roles" | "respond" | "limits"> & {
311
+ mode: "shared";
312
+ members: Array<LineMemberSpec & {
313
+ subjectId: string;
314
+ }>;
315
+ unknownSenders: "reject";
316
+ roles: Record<string, LineRole & {
317
+ context: "own";
318
+ }>;
319
+ respond: Omit<LineRespondAgent, "backend" | "profileId" | "rolePolicy"> & {
320
+ application: LineApplication;
321
+ };
322
+ limits?: Omit<Partial<LineLimits>, "allowance">;
323
+ };
300
324
  /**
301
325
  * The instance key that serves one member: `keyPrefix` plus the first 32 hex
302
326
  * characters of the SHA-256 of the member's address as Hub stores it (E.164,
@@ -371,13 +395,15 @@ interface LineMember {
371
395
  /** `invited` until the member's first message, which is their consent. */
372
396
  status: "invited" | "active" | "stopped" | "removed";
373
397
  createdAt: string;
398
+ /** Hub authority revision. Compare it with the callback's memberRevision. */
399
+ updatedAt: string;
374
400
  }
375
401
  interface LineAttachment {
376
402
  id: string;
377
403
  lineId: string;
378
404
  /** Execution key ID. Pass the observed value when reauthorizing this attachment. */
379
405
  runAsKeyId: string;
380
- /** Native execution sandbox or initial application enrollment anchor; empty for member instances. */
406
+ /** Native execution sandbox; empty for member instances and shared application lines. */
381
407
  sandboxId: string;
382
408
  /** Present when each member runs in their own sandbox. */
383
409
  instance?: {
@@ -510,12 +536,11 @@ declare class LinesClient {
510
536
  /** Read proof state with the same owner API key that started the test. */
511
537
  getSenderVerification(number: string, testId: string): Promise<LineSenderVerification>;
512
538
  /**
513
- * Attach a line so each member runs in their own sandbox. Hub checks that
514
- * your API key can run sandboxes, and each turn runs as a short-lived child
515
- * of that key. Attaching again with the same options returns the same
516
- * attachment. To attach a line to one sandbox, use `box.lines.attach()`.
539
+ * Attach a line to member sandboxes or one application callback. Hub checks
540
+ * the owner key and keeps one active attachment. The callback must resolve
541
+ * each declared customer's subject to its own authorized private target.
517
542
  */
518
- attach(options: LineInstanceAttachOptions): Promise<LineAttachment>;
543
+ attach(options: LineInstanceAttachOptions | LineApplicationAttachOptions): Promise<LineAttachment>;
519
544
  /** Bind the current API key to this same attachment after app key rotation.
520
545
  * Hub checks the observed attachment and old key, app key lineage, owner,
521
546
  * workspace and sandbox. A race leaves the existing binding unchanged.
@@ -592,4 +617,4 @@ declare class SandboxLines {
592
617
  detach(number: string): Promise<void>;
593
618
  }
594
619
  //#endregion
595
- export { LineTransport as A, LineApplication as B, LineRespondView as C, LineSenderVerification as D, LineSendReceipt as E, SandboxLines as F, parseLineApplicationRequest as G, LineApplicationResult as H, lineInstanceKey as I, parseLineApplicationResult as K, profileChannelReference as L, LineVoiceOptions as M, LinesClient as N, LineSenderVerificationStart as O, LinesHttpClient as P, LINE_APPLICATION_REPLY_MAX_CHARS as R, LineRespondAgent as S, LineSendInput as T, LineApplicationState as U, LineApplicationRequest as V, LineApplicationView as W, LineMessage as _, LineAttachOptions as a, LineReminderPreferences as b, LineExecutionKey as c, LineInstanceCreate as d, LineLimits as f, LineMemberSpec as g, LineMemberPatch as h, LineAllowanceSubject as i, LineVoice as j, LineThread as k, LineFromConnectionInput as l, LineMemberInstance as m, LineAgentRolePolicy as n, LineAttachment as o, LineMember as p, LineAllowance as r, LineAttachmentReauthorization as s, Line as t, LineInstanceAttachOptions as u, LineNumberInventory as v, LineRole as w, LineReplyGate as x, LineProvider as y, LINE_APPLICATION_REQUEST_MAX_BYTES as z };
620
+ export { LineThread as A, LINE_APPLICATION_REQUEST_MAX_BYTES as B, LineRespondAgent as C, LineSendReceipt as D, LineSendInput as E, LinesHttpClient as F, LineApplicationView as G, LineApplicationRequest as H, SandboxLines as I, parseLineApplicationRequest as K, lineInstanceKey as L, LineVoice as M, LineVoiceOptions as N, LineSenderVerification as O, LinesClient as P, profileChannelReference as R, LineReplyGate as S, LineRole as T, LineApplicationResult as U, LineApplication as V, LineApplicationState as W, LineMemberSpec as _, LineApplicationAttachOptions as a, LineProvider as b, LineAttachmentReauthorization as c, LineInstanceAttachOptions as d, LineInstanceCreate as f, LineMemberPatch as g, LineMemberInstance as h, LineAllowanceSubject as i, LineTransport as j, LineSenderVerificationStart as k, LineExecutionKey as l, LineMember as m, LineAgentRolePolicy as n, LineAttachOptions as o, LineLimits as p, parseLineApplicationResult as q, LineAllowance as r, LineAttachment as s, Line as t, LineFromConnectionInput as u, LineMessage as v, LineRespondView as w, LineReminderPreferences as x, LineNumberInventory as y, LINE_APPLICATION_REPLY_MAX_CHARS as z };
package/dist/lines.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as LineTransport, C as LineRespondView, D as LineSenderVerification, E as LineSendReceipt, F as SandboxLines, I as lineInstanceKey, L as profileChannelReference, M as LineVoiceOptions, N as LinesClient, O as LineSenderVerificationStart, P as LinesHttpClient, S as LineRespondAgent, T as LineSendInput, _ as LineMessage, a as LineAttachOptions, b as LineReminderPreferences, c as LineExecutionKey, d as LineInstanceCreate, f as LineLimits, g as LineMemberSpec, h as LineMemberPatch, i as LineAllowanceSubject, j as LineVoice, k as LineThread, l as LineFromConnectionInput, m as LineMemberInstance, n as LineAgentRolePolicy, o as LineAttachment, p as LineMember, r as LineAllowance, s as LineAttachmentReauthorization, t as Line, u as LineInstanceAttachOptions, v as LineNumberInventory, w as LineRole, x as LineReplyGate, y as LineProvider } from "./lines-CHK_7gLO.js";
2
- export { Line, LineAgentRolePolicy, LineAllowance, LineAllowanceSubject, LineAttachOptions, LineAttachment, LineAttachmentReauthorization, LineExecutionKey, LineFromConnectionInput, LineInstanceAttachOptions, LineInstanceCreate, LineLimits, LineMember, LineMemberInstance, LineMemberPatch, LineMemberSpec, LineMessage, LineNumberInventory, LineProvider, LineReminderPreferences, LineReplyGate, LineRespondAgent, LineRespondView, LineRole, LineSendInput, LineSendReceipt, LineSenderVerification, LineSenderVerificationStart, LineThread, LineTransport, LineVoice, LineVoiceOptions, LinesClient, LinesHttpClient, SandboxLines, lineInstanceKey, profileChannelReference };
1
+ import { A as LineThread, C as LineRespondAgent, D as LineSendReceipt, E as LineSendInput, F as LinesHttpClient, I as SandboxLines, L as lineInstanceKey, M as LineVoice, N as LineVoiceOptions, O as LineSenderVerification, P as LinesClient, R as profileChannelReference, S as LineReplyGate, T as LineRole, _ as LineMemberSpec, a as LineApplicationAttachOptions, b as LineProvider, c as LineAttachmentReauthorization, d as LineInstanceAttachOptions, f as LineInstanceCreate, g as LineMemberPatch, h as LineMemberInstance, i as LineAllowanceSubject, j as LineTransport, k as LineSenderVerificationStart, l as LineExecutionKey, m as LineMember, n as LineAgentRolePolicy, o as LineAttachOptions, p as LineLimits, r as LineAllowance, s as LineAttachment, t as Line, u as LineFromConnectionInput, v as LineMessage, w as LineRespondView, x as LineReminderPreferences, y as LineNumberInventory } from "./lines-CRlIO585.js";
2
+ export { Line, LineAgentRolePolicy, LineAllowance, LineAllowanceSubject, LineApplicationAttachOptions, LineAttachOptions, LineAttachment, LineAttachmentReauthorization, LineExecutionKey, LineFromConnectionInput, LineInstanceAttachOptions, LineInstanceCreate, LineLimits, LineMember, LineMemberInstance, LineMemberPatch, LineMemberSpec, LineMessage, LineNumberInventory, LineProvider, LineReminderPreferences, LineReplyGate, LineRespondAgent, LineRespondView, LineRole, LineSendInput, LineSendReceipt, LineSenderVerification, LineSenderVerificationStart, LineThread, LineTransport, LineVoice, LineVoiceOptions, LinesClient, LinesHttpClient, SandboxLines, lineInstanceKey, profileChannelReference };
package/dist/lines.js CHANGED
@@ -133,10 +133,9 @@ var LinesClient = class {
133
133
  return hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/sender-verifications/${encodeURIComponent(testId)}`));
134
134
  }
135
135
  /**
136
- * Attach a line so each member runs in their own sandbox. Hub checks that
137
- * your API key can run sandboxes, and each turn runs as a short-lived child
138
- * of that key. Attaching again with the same options returns the same
139
- * attachment. To attach a line to one sandbox, use `box.lines.attach()`.
136
+ * Attach a line to member sandboxes or one application callback. Hub checks
137
+ * the owner key and keeps one active attachment. The callback must resolve
138
+ * each declared customer's subject to its own authorized private target.
140
139
  */
141
140
  async attach(options) {
142
141
  const lineId = await this.resolve(options.number);
@@ -1,6 +1,6 @@
1
- import { r as SandboxInstance } from "./sandbox-BsEk7BTy.js";
2
- import { Pn as PreviewLinkInfo, mt as EnsureDevServerOptions } from "./types-BQlqLwrK.js";
3
- import { i as Sandbox } from "./client-DGwZ0Swl.js";
1
+ import { r as SandboxInstance } from "./sandbox-fyuaDhc3.js";
2
+ import { Fn as PreviewLinkInfo, ht as EnsureDevServerOptions } from "./types-C9w6MdZB.js";
3
+ import { i as Sandbox } from "./client-Co3TZfTd.js";
4
4
 
5
5
  //#region src/agent/preview-operations.d.ts
6
6
  type AgentPreviewOptions = Pick<EnsureDevServerOptions, "sessionId" | "cwd"> & {
package/dist/runtime.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { l as ScopedToken, t as TerminalStream } from "./terminal-stream-C9jxoB07.js";
2
2
  import { c as InteractiveSessionIdentity, l as InteractiveSessionNotRunningError, r as browserInteractiveControlHolderId } from "./browser-interactive-control-controller-C2qVGzQz.js";
3
3
  import { t as BrowserInteractiveSessionController } from "./interactive-controller-Dghv9yMk.js";
4
- import { A as CommitTaskSessionOptions, At as FileUsageResult, Bi as SessionExecutionInfo, Ci as SandboxTerminalManager, Dt as FileTreeOptions, Er as SandboxEvent, Fi as SendSessionMessageOptions, H as CreateTaskSessionOptions, Ii as SendSessionMessageRequest, Ji as SessionMessageAdmission, Li as SentSessionMessage, Ot as FileTreeResult, Si as SandboxTerminalInfo, Sn as ListMessagesOptions, T as ChunkedUploadResult, V as CreateSessionOptions, Vi as SessionExecutionStatus, Wi as SessionInfo, bt as FileReadBatchOptions, fa as TaskSessionInfo, hi as SandboxRuntimeHealth, jt as FileWriteResult, ka as WriteFileOptions, kt as FileUsageOptions, la as TaskSessionChanges, li as SandboxPortBinding, or as RenameOptions, qi as SessionMessage, ua as TaskSessionCommitResult, w as ChunkedUploadOptions, wa as UploadProgress, wi as SandboxTerminalRequestOptions, wt as FileRenameResult, xi as SandboxTerminalCreateOptions, xt as FileReadBatchResult, zi as SessionEventStreamOptions } from "./types-BQlqLwrK.js";
4
+ import { A as CommitTaskSessionOptions, Aa as WriteFileOptions, At as FileUsageOptions, Bi as SessionEventStreamOptions, Ci as SandboxTerminalInfo, Cn as ListMessagesOptions, Dr as SandboxEvent, Gi as SessionInfo, H as CreateTaskSessionOptions, Hi as SessionExecutionStatus, Ii as SendSessionMessageOptions, Ji as SessionMessage, Li as SendSessionMessageRequest, Mt as FileWriteResult, Ot as FileTreeOptions, Ri as SentSessionMessage, Si as SandboxTerminalCreateOptions, St as FileReadBatchResult, T as ChunkedUploadResult, Ta as UploadProgress, Ti as SandboxTerminalRequestOptions, Tt as FileRenameResult, V as CreateSessionOptions, Vi as SessionExecutionInfo, Yi as SessionMessageAdmission, da as TaskSessionCommitResult, gi as SandboxRuntimeHealth, jt as FileUsageResult, kt as FileTreeResult, pa as TaskSessionInfo, sr as RenameOptions, ua as TaskSessionChanges, ui as SandboxPortBinding, w as ChunkedUploadOptions, wi as SandboxTerminalManager, xt as FileReadBatchOptions } from "./types-C9w6MdZB.js";
5
5
  import { _ as TimeoutError, a as FileWriteConflictError, c as NotFoundError, f as SandboxError, g as StateError, h as ServerError, l as PartialFailureError, m as SandboxFailureDetail, n as CapabilityError, p as SandboxErrorJson, s as NetworkError, t as AuthError, u as QuotaError, v as ValidationError } from "./errors-C6dll8Qf.js";
6
- import { a as deriveAgentRunOutcome, i as deriveAgentResultOutcome, n as AgentRunOutcomeTracker, r as createAgentRunOutcomeTracker, t as AgentRunOutcome } from "./agent-run-outcome-Cs5H4B3s.js";
6
+ import { a as deriveAgentRunOutcome, i as deriveAgentResultOutcome, n as AgentRunOutcomeTracker, r as createAgentRunOutcomeTracker, t as AgentRunOutcome } from "./agent-run-outcome-BDxby7zK.js";
7
7
 
8
8
  //#region src/lib/chunked-upload.d.ts
9
9
  /** The transport a caller wires this module to — {@link SandboxInstance.runtimeFetch}
@@ -302,6 +302,92 @@ function normalizeSandboxShape(raw) {
302
302
  };
303
303
  }
304
304
  //#endregion
305
+ //#region src/lib/file-download.ts
306
+ /** Retain only complete downloads; failed streams leave the destination intact. */
307
+ async function downloadFile(request, localPath, options = {}) {
308
+ for (const [name, value] of Object.entries({
309
+ maxBytes: options.maxBytes,
310
+ expectedSize: options.expectedSize
311
+ })) if (value !== void 0 && (!Number.isSafeInteger(value) || value < 0)) throw new ValidationError(`${name} must be a non-negative safe integer`);
312
+ const expectedHash = options.expectedSha256?.replace(/^sha256:/, "");
313
+ if (expectedHash !== void 0 && !/^[a-f0-9]{64}$/i.test(expectedHash)) throw new ValidationError("expectedSha256 must be a SHA-256 digest");
314
+ const maxBytes = options.maxBytes ?? Number.MAX_SAFE_INTEGER;
315
+ if (options.expectedSize !== void 0 && options.expectedSize > maxBytes) throw new ValidationError("expectedSize exceeds download maxBytes");
316
+ options.signal?.throwIfAborted();
317
+ const response = await request(options.signal);
318
+ const reader = response.body?.getReader();
319
+ const abort = () => {
320
+ reader?.cancel(options.signal?.reason).catch(() => {});
321
+ };
322
+ options.signal?.addEventListener("abort", abort, { once: true });
323
+ let directory;
324
+ let file;
325
+ const fs = await import("node:fs/promises");
326
+ try {
327
+ options.signal?.throwIfAborted();
328
+ const length = response.headers.get("content-length");
329
+ const totalBytes = length === null ? void 0 : Number(length);
330
+ if (length !== null && (!/^\d+$/.test(length) || !Number.isSafeInteger(totalBytes))) throw new Error("Download returned an invalid content-length");
331
+ if (totalBytes !== void 0 && totalBytes > maxBytes) throw new Error("Download exceeds maxBytes");
332
+ if (options.expectedSize !== void 0 && totalBytes !== void 0 && totalBytes !== options.expectedSize) throw new Error("Download size does not match expectedSize");
333
+ const path = await import("node:path");
334
+ const { createHash } = await import("node:crypto");
335
+ await fs.mkdir(path.dirname(localPath), { recursive: true });
336
+ directory = await fs.mkdtemp(path.join(path.dirname(localPath), ".sandbox-download-"));
337
+ const temporaryPath = path.join(directory, "content");
338
+ file = await fs.open(temporaryPath, "wx", 384);
339
+ const hash = createHash("sha256");
340
+ let sizeBytes = 0;
341
+ if (totalBytes !== void 0 && totalBytes > 0) options.onProgress?.({
342
+ bytesDownloaded: 0,
343
+ totalBytes,
344
+ percentage: 0
345
+ });
346
+ for (;;) {
347
+ options.signal?.throwIfAborted();
348
+ const chunk = await reader?.read();
349
+ options.signal?.throwIfAborted();
350
+ if (!chunk || chunk.done) break;
351
+ sizeBytes += chunk.value.byteLength;
352
+ if (sizeBytes > maxBytes) throw new Error("Download exceeds maxBytes");
353
+ if (options.expectedSize !== void 0 && sizeBytes > options.expectedSize) throw new Error("Download size does not match expectedSize");
354
+ hash.update(chunk.value);
355
+ await file.writeFile(chunk.value);
356
+ if (totalBytes !== void 0 && sizeBytes < totalBytes) options.onProgress?.({
357
+ bytesDownloaded: sizeBytes,
358
+ totalBytes,
359
+ percentage: sizeBytes / totalBytes * 100
360
+ });
361
+ }
362
+ if (totalBytes !== void 0 && sizeBytes !== totalBytes || options.expectedSize !== void 0 && sizeBytes !== options.expectedSize) throw new Error("Download was truncated or its size changed");
363
+ const sha256 = hash.digest("hex");
364
+ if (expectedHash !== void 0 && sha256 !== expectedHash.toLowerCase()) throw new Error("Download SHA-256 does not match expectedSha256");
365
+ await file.close();
366
+ file = void 0;
367
+ options.signal?.throwIfAborted();
368
+ if (options.overwrite === false) await fs.link(temporaryPath, localPath);
369
+ else await fs.rename(temporaryPath, localPath);
370
+ options.onProgress?.({
371
+ bytesDownloaded: sizeBytes,
372
+ totalBytes: sizeBytes,
373
+ percentage: 100
374
+ });
375
+ return {
376
+ sizeBytes,
377
+ sha256
378
+ };
379
+ } finally {
380
+ options.signal?.removeEventListener("abort", abort);
381
+ await reader?.cancel().catch(() => {});
382
+ reader?.releaseLock();
383
+ await file?.close();
384
+ if (directory !== void 0) await fs.rm(directory, {
385
+ recursive: true,
386
+ force: true
387
+ });
388
+ }
389
+ }
390
+ //#endregion
305
391
  //#region src/managed-process.ts
306
392
  var ManagedProcessClient = class {
307
393
  constructor(request, environmentId) {
@@ -4837,6 +4923,7 @@ var SandboxInstance = class SandboxInstance {
4837
4923
  get fs() {
4838
4924
  return {
4839
4925
  supportsWriteMode: true,
4926
+ supportsBoundedDownload: true,
4840
4927
  read: (path) => this.read(path),
4841
4928
  readBatch: (paths, options) => this.fsReadBatch(paths, options),
4842
4929
  tree: (path, options) => this.fsTree(path, options),
@@ -4895,29 +4982,18 @@ var SandboxInstance = class SandboxInstance {
4895
4982
  return uploadChunked({ fetch: (path, init) => this.runtimeFetch(path, init) }, remotePath, data, options);
4896
4983
  }
4897
4984
  async fsDownload(remotePath, localPath, options) {
4898
- await this.ensureRunning();
4899
- const fs = await import("node:fs/promises");
4900
- const path = await import("node:path");
4901
- await fs.mkdir(path.dirname(localPath), { recursive: true });
4902
- const response = await this.runtimeFetch(runtimeFilesystemPath("/fs/download", remotePath), { method: "GET" });
4903
- if (!response.ok) {
4904
- const body = await response.text();
4905
- throw parseErrorResponse(response.status, body, void 0, response.headers);
4906
- }
4907
- const contentLength = response.headers.get("content-length");
4908
- const totalBytes = contentLength ? Number.parseInt(contentLength, 10) : 0;
4909
- if (options?.onProgress && totalBytes > 0) options.onProgress({
4910
- bytesDownloaded: 0,
4911
- totalBytes,
4912
- percentage: 0
4913
- });
4914
- const buffer = await response.arrayBuffer();
4915
- await fs.writeFile(localPath, Buffer.from(buffer));
4916
- if (options?.onProgress) options.onProgress({
4917
- bytesDownloaded: buffer.byteLength,
4918
- totalBytes: buffer.byteLength,
4919
- percentage: 100
4920
- });
4985
+ return downloadFile(async (signal) => {
4986
+ await this.ensureRunning();
4987
+ const response = await this.runtimeFetch(runtimeFilesystemPath("/fs/download", remotePath), {
4988
+ method: "GET",
4989
+ signal
4990
+ });
4991
+ if (!response.ok) {
4992
+ const body = await response.text();
4993
+ throw parseErrorResponse(response.status, body, void 0, response.headers);
4994
+ }
4995
+ return response;
4996
+ }, localPath, options);
4921
4997
  }
4922
4998
  async fsUploadDir(localDir, remoteDir) {
4923
4999
  await this.ensureRunning();
@@ -1,8 +1,8 @@
1
1
  import { a as TerminalStreamReconnectAuthority, c as MintScopedTokenOptions, h as TerminalReadyInfo, l as ScopedToken, r as TerminalStreamHandlers, t as TerminalStream } from "./terminal-stream-C9jxoB07.js";
2
2
  import { f as InteractiveAttachOptions, g as InteractiveSessionStatus, h as InteractiveRequestOptions, m as InteractiveControlClaimOptions, p as InteractiveControlClaimAcknowledgement } from "./browser-interactive-control-controller-C2qVGzQz.js";
3
3
  import { r as InteractiveAttachRequest } from "./interactive-controller-Dghv9yMk.js";
4
- import { F as SandboxLines } from "./lines-CHK_7gLO.js";
5
- import { A as CommitTaskSessionOptions, Aa as WriteManyFile, An as NetworkManager, Bi as SessionExecutionInfo, C as BranchOptions, Cr as SandboxDeleteOptions, D as CodeExecutionResult, Da as WaitForRolloutOptions, E as CodeExecutionOptions, Ea as WaitForOptions, Ei as SandboxTraceBundle, Er as SandboxEvent, Fi as SendSessionMessageOptions, Fn as PreviewLinkManager, Gi as SessionInterruptOptions, Gn as PromptInputPart, H as CreateTaskSessionOptions, Ii as SendSessionMessageRequest, Ji as SessionMessageAdmission, Jn as ProvisionEvent, Ki as SessionListOptions, Kn as PromptOptions, Li as SentSessionMessage, M as ConversationTurnOptions, Mi as SearchOptions, N as ConversationTurnResult, Nn as PermissionsManager, O as CodeLanguage, Oa as WorkspaceOperationLookup, Q as DispatchedSession, Qi as SnapshotDeleteAcknowledgement, Sn as ListMessagesOptions, Sr as SandboxDeleteAcknowledgement, Ti as SandboxTerminals, Tt as FileSystem, Ui as SessionForkOptions, V as CreateSessionOptions, Vn as ProcessManager, Wi as SessionInfo, Xi as SessionResultOptions, Xt as ForkIdempotency, Yn as ProvisionResult, Yt as ForkCounts, Z as DispatchPromptOptions, Zr as SandboxFleetTraceBundle, Zt as ForkLookupOptions, _n as IntelligenceReportBudget, _r as SSHCredentials, _t as ExecOptions, aa as StartupDiagnostics, an as GpuLease, at as DurablePlan, bi as SandboxTerminalAttachOptions, bn as IntelligenceReportWindow, cr as ResumeOptions, d as BackendConfig, dr as RolloutOptions, en as GitBranch, fa as TaskSessionInfo, fi as SandboxResourceUsage, ft as EgressManager, ga as TeeAttestationResponse, gi as SandboxShape, gn as IntelligenceReport, gr as SSHCommandDescriptor, hi as SandboxRuntimeHealth, hn as InstalledTool, ht as EventStreamOptions, in as GitStatus, j as CompletedTurnResult, ja as WriteManyOptions, ji as SearchMatch, jt as FileWriteResult, ka as WriteFileOptions, ki as SandboxTraceOptions, la as TaskSessionChanges, li as SandboxPortBinding, lr as Rollout, ma as TeeAttestationOptions, mi as SandboxRuntimeCapabilities, na as SnapshotOptions, ot as DurablePlanDecisionResult, p as BackendManager, pr as RolloutStartResult, qi as SessionMessage, qn as PromptResult, ra as SnapshotResult, rn as GitDiff, rt as DriverInfo, si as SandboxInfo, sr as RestoreSnapshotOptions, ta as SnapshotInfo, tn as GitCommit, tt as DriveTurnOptions, ua as TaskSessionCommitResult, un as GpuLeaseManager, va as TeePublicKeyResponse, vn as IntelligenceReportCompareTo, vt as ExecResult, xa as TurnDriveResult, xn as JsonValue, xr as SandboxCreateReceipt, yi as SandboxStatus, yr as SandboxConnection, zi as SessionEventStreamOptions } from "./types-BQlqLwrK.js";
4
+ import { I as SandboxLines } from "./lines-CRlIO585.js";
5
+ import { $i as SnapshotDeleteAcknowledgement, A as CommitTaskSessionOptions, Aa as WriteFileOptions, Ai as SandboxTraceOptions, Bi as SessionEventStreamOptions, C as BranchOptions, Cn as ListMessagesOptions, Cr as SandboxDeleteAcknowledgement, D as CodeExecutionResult, Da as WaitForOptions, Di as SandboxTraceBundle, Dr as SandboxEvent, E as CodeExecutionOptions, Ei as SandboxTerminals, Et as FileSystem, Gi as SessionInfo, H as CreateTaskSessionOptions, Hn as ProcessManager, Ii as SendSessionMessageOptions, In as PreviewLinkManager, Ji as SessionMessage, Jn as PromptResult, Ki as SessionInterruptOptions, Kn as PromptInputPart, Li as SendSessionMessageRequest, M as ConversationTurnOptions, Ma as WriteManyOptions, Mi as SearchMatch, Mt as FileWriteResult, N as ConversationTurnResult, Ni as SearchOptions, O as CodeLanguage, Oa as WaitForRolloutOptions, Pn as PermissionsManager, Q as DispatchedSession, Qr as SandboxFleetTraceBundle, Qt as ForkLookupOptions, Ri as SentSessionMessage, Sa as TurnDriveResult, Sn as JsonValue, Sr as SandboxCreateReceipt, V as CreateSessionOptions, Vi as SessionExecutionInfo, Wi as SessionForkOptions, Xn as ProvisionResult, Xt as ForkCounts, Yi as SessionMessageAdmission, Yn as ProvisionEvent, Z as DispatchPromptOptions, Zi as SessionResultOptions, Zt as ForkIdempotency, _a as TeeAttestationResponse, _i as SandboxShape, _n as IntelligenceReport, _r as SSHCommandDescriptor, an as GitStatus, bi as SandboxStatus, br as SandboxConnection, ci as SandboxInfo, cr as RestoreSnapshotOptions, d as BackendConfig, da as TaskSessionCommitResult, dn as GpuLeaseManager, fr as RolloutOptions, gi as SandboxRuntimeHealth, gn as InstalledTool, gt as EventStreamOptions, ha as TeeAttestationOptions, hi as SandboxRuntimeCapabilities, ia as SnapshotResult, in as GitDiff, it as DriverInfo, j as CompletedTurnResult, ja as WriteManyFile, jn as NetworkManager, ka as WorkspaceOperationLookup, lr as ResumeOptions, mr as RolloutStartResult, na as SnapshotInfo, nn as GitCommit, nt as DriveTurnOptions, oa as StartupDiagnostics, on as GpuLease, ot as DurablePlan, p as BackendManager, pa as TaskSessionInfo, pi as SandboxResourceUsage, pt as EgressManager, qi as SessionListOptions, qn as PromptOptions, ra as SnapshotOptions, st as DurablePlanDecisionResult, tn as GitBranch, ua as TaskSessionChanges, ui as SandboxPortBinding, ur as Rollout, vn as IntelligenceReportBudget, vr as SSHCredentials, vt as ExecOptions, wr as SandboxDeleteOptions, xi as SandboxTerminalAttachOptions, xn as IntelligenceReportWindow, ya as TeePublicKeyResponse, yn as IntelligenceReportCompareTo, yt as ExecResult } from "./types-C9w6MdZB.js";
6
6
  import { AgentInteractiveSessionAttach, AgentInteractiveSessionControlClaim, AgentInteractiveSessionControlClaimAcknowledgement, AgentInteractiveSessionControlClaimRequest, AgentInteractiveSessionPromptAcknowledgement, AgentInteractiveSessionPromptCommand, AgentInteractiveSessionRef, AgentInteractiveSessionStart, AgentInteractiveSessionStopAcknowledgement, AgentInteractiveSessionStopCommand, AgentInteractiveTerminalSession, AgentInteractiveTerminalSession as AgentInteractiveTerminalSession$1, AgentRunCancellationAcknowledgement, AgentRunCancellationRequest, InteractionAcknowledgement, InteractionData, InteractionRequest, InteractionResponseCommand, TerminalOutputEvent, TerminalReplayWindow, agentInteractiveSessionPromptRequestDigest } from "@tangle-network/agent-interface";
7
7
  import { z } from "zod";
8
8
 
@@ -1,2 +1,2 @@
1
- import { a as TANGLE_JOBS_CONTRACT, c as ITangleJobsAbi, d as SandboxCreateResponseParamTypes, f as SandboxIdParamTypes, i as TANGLE_CHAIN_ID, l as JsonResponseParamTypes, n as JOB_SANDBOX_CREATE, o as TangleSandboxClientConfig, r as JOB_SANDBOX_DELETE, s as AgentSandboxBlueprintAbi, t as TangleSandboxClient, u as SandboxCreateParamTypes } from "../index-CcMKzCk4.js";
2
- export { AgentSandboxBlueprintAbi, ITangleJobsAbi, JOB_SANDBOX_CREATE, JOB_SANDBOX_DELETE, JsonResponseParamTypes, SandboxCreateParamTypes, SandboxCreateResponseParamTypes, SandboxIdParamTypes, TANGLE_CHAIN_ID, TANGLE_JOBS_CONTRACT, TangleSandboxClient, TangleSandboxClientConfig };
1
+ import { _ as SandboxIdParamTypes, a as SignMessage, c as JOB_SANDBOX_DELETE, d as TangleSandboxClientConfig, f as AgentSandboxBlueprintAbi, g as SandboxCreateResponseParamTypes, h as SandboxCreateParamTypes, i as OperatorSessionToken, l as TANGLE_CHAIN_ID, m as JsonResponseParamTypes, n as OperatorSession, o as TangleSandboxClient, p as ITangleJobsAbi, r as OperatorSessionError, s as JOB_SANDBOX_CREATE, t as OperatorChallenge, u as TANGLE_JOBS_CONTRACT } from "../index-Numcq5sH.js";
2
+ export { AgentSandboxBlueprintAbi, ITangleJobsAbi, JOB_SANDBOX_CREATE, JOB_SANDBOX_DELETE, JsonResponseParamTypes, OperatorChallenge, OperatorSession, OperatorSessionError, OperatorSessionToken, SandboxCreateParamTypes, SandboxCreateResponseParamTypes, SandboxIdParamTypes, SignMessage, TANGLE_CHAIN_ID, TANGLE_JOBS_CONTRACT, TangleSandboxClient, TangleSandboxClientConfig };
@@ -1,2 +1,2 @@
1
- import { a as TANGLE_JOBS_CONTRACT, c as JsonResponseParamTypes, d as SandboxIdParamTypes, i as TANGLE_CHAIN_ID, l as SandboxCreateParamTypes, n as JOB_SANDBOX_CREATE, o as AgentSandboxBlueprintAbi, r as JOB_SANDBOX_DELETE, s as ITangleJobsAbi, t as TangleSandboxClient, u as SandboxCreateResponseParamTypes } from "../tangle-DKaBCad0.js";
2
- export { AgentSandboxBlueprintAbi, ITangleJobsAbi, JOB_SANDBOX_CREATE, JOB_SANDBOX_DELETE, JsonResponseParamTypes, SandboxCreateParamTypes, SandboxCreateResponseParamTypes, SandboxIdParamTypes, TANGLE_CHAIN_ID, TANGLE_JOBS_CONTRACT, TangleSandboxClient };
1
+ import { a as JOB_SANDBOX_DELETE, c as AgentSandboxBlueprintAbi, d as SandboxCreateParamTypes, f as SandboxCreateResponseParamTypes, i as JOB_SANDBOX_CREATE, l as ITangleJobsAbi, n as OperatorSession, o as TANGLE_CHAIN_ID, p as SandboxIdParamTypes, r as OperatorSessionError, s as TANGLE_JOBS_CONTRACT, t as TangleSandboxClient, u as JsonResponseParamTypes } from "../tangle-SNShua9T.js";
2
+ export { AgentSandboxBlueprintAbi, ITangleJobsAbi, JOB_SANDBOX_CREATE, JOB_SANDBOX_DELETE, JsonResponseParamTypes, OperatorSession, OperatorSessionError, SandboxCreateParamTypes, SandboxCreateResponseParamTypes, SandboxIdParamTypes, TANGLE_CHAIN_ID, TANGLE_JOBS_CONTRACT, TangleSandboxClient };