@tangle-network/sandbox 1.0.231 → 1.0.233

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/README.md +22 -1
  2. package/dist/agent/index.d.ts +4 -4
  3. package/dist/agent/index.js +5 -5
  4. package/dist/agent/preview.d.ts +1 -1
  5. package/dist/agent/preview.js +2 -2
  6. package/dist/agent-execution-preparation-BJChICex.js +18 -0
  7. package/dist/agent-execution-preparation-receipt-BIFxqyr5.js +250 -0
  8. package/dist/{agent-run-outcome-DMaHbXAk.d.ts → agent-run-outcome-B0nURFpG.d.ts} +3 -2
  9. package/dist/{api-request-_SFFNVqY.js → api-request-dyabkosT.js} +34 -9
  10. package/dist/auth/index.d.ts +2 -2
  11. package/dist/auth/index.js +2 -2
  12. package/dist/{browser-interactive-control-controller-BiP6TJFP.js → browser-interactive-control-controller-BM2p1dBp.js} +16 -252
  13. package/dist/{browser-interactive-control-controller-qv26Bpfx.d.ts → browser-interactive-control-controller-CcUjQEfa.d.ts} +1 -1
  14. package/dist/{chunked-upload-BjkxykZD.js → chunked-upload-BlvgxPWx.js} +4 -5
  15. package/dist/{chunked-upload-file-B2KFimpz.js → chunked-upload-file-DOeLpMO0.js} +2 -2
  16. package/dist/cli-auth-bundle-BLAtE6Dc.js +2 -0
  17. package/dist/{client-OlxlnLwV.js → client-BS-PR_-j.js} +38 -47
  18. package/dist/{client-DvvRMxKx.d.ts → client-DlTDphmI.d.ts} +38 -32
  19. package/dist/collaboration/index.d.ts +1 -1
  20. package/dist/collaboration/index.js +1 -1
  21. package/dist/{collaboration-DZ8ptALs.js → collaboration-Dz20mN9a.js} +20 -27
  22. package/dist/core-CUZyz-U8.js +161 -0
  23. package/dist/core.d.ts +6 -6
  24. package/dist/core.js +6 -5
  25. package/dist/{direct-http2-DU2SK2Wo.js → direct-http2-Bgb2lHte.js} +1 -1
  26. package/dist/{errors-A-bhwwsE.js → error-catalog-CAbzw67O.js} +1 -382
  27. package/dist/errors-nXGKGVFe.js +382 -0
  28. package/dist/{file-download-UhMKbMbD.js → file-download-BjkrYzy_.js} +1 -1
  29. package/dist/{index-Cip3q_xe.d.ts → index-DE5n6mot.d.ts} +13 -23
  30. package/dist/index.d.ts +12 -12
  31. package/dist/index.js +29 -25
  32. package/dist/intelligence/index.d.ts +41 -109
  33. package/dist/intelligence/index.js +60 -73
  34. package/dist/interactive-control.d.ts +1 -1
  35. package/dist/interactive-control.js +1 -1
  36. package/dist/{interactive-controller-D4gZ4f2I.js → interactive-controller-DDPdZa2H.js} +20 -54
  37. package/dist/{interactive-controller-P0yy6sGl.d.ts → interactive-controller-sEU_J6Bc.d.ts} +3 -3
  38. package/dist/lib/prepared-evidence.js +1 -1
  39. package/dist/lib/prepared-process.js +1 -1
  40. package/dist/{lines-7VecgiGd.js → lines-CSGBHEjR.js} +1 -1
  41. package/dist/{lines-DNXdVbGO.d.ts → lines-qvpmwN_2.d.ts} +1 -1
  42. package/dist/lines.d.ts +1 -1
  43. package/dist/lines.js +1 -1
  44. package/dist/{local-cli-auth-CPS9yuTc.js → local-cli-auth-CO0byocv.js} +1 -1
  45. package/dist/{mcp-local-CIXZFqF4.js → mcp-local-Dz_Sehz0.js} +4 -4
  46. package/dist/{prepared-evidence-Byty5p51.js → prepared-evidence-ibAysmX8.js} +2 -2
  47. package/dist/{prepared-process-u1B0b94R.js → prepared-process-DQ_68Ofg.js} +2 -2
  48. package/dist/{preview-CNfYklE6.d.ts → preview-BC_wLaA2.d.ts} +3 -3
  49. package/dist/{public-templates-CPvDf8CH.d.ts → public-templates-WuvmbvzY.d.ts} +2 -2
  50. package/dist/public-templates.d.ts +1 -1
  51. package/dist/public-templates.js +1 -1
  52. package/dist/{raw-evidence-archive-BgWqaQcM.js → raw-evidence-archive-Cz4j8VMw.js} +2 -2
  53. package/dist/{retry-policy-Dh-VezcE.js → retry-policy-oW3_ljoc.js} +2 -24
  54. package/dist/runtime.d.ts +7 -7
  55. package/dist/runtime.js +9 -9
  56. package/dist/{sandbox-Dvk2PYnL.js → sandbox-OyCRplrI.js} +65 -91
  57. package/dist/{secp256k1-Cbp9tbkX.js → secp256k1-ZiYFbGjz.js} +1 -1
  58. package/dist/{core-D7czAW25.js → select-seat-B4Y-7vIq.js} +40 -171
  59. package/dist/select-seat-command.d.ts +9 -3
  60. package/dist/select-seat-command.js +69 -57
  61. package/dist/session-gateway/index.js +11 -20
  62. package/dist/sidecar-proxy-error-DTdbCbUM.js +4 -0
  63. package/dist/tangle/index.d.ts +1 -1
  64. package/dist/tangle/index.js +1 -1
  65. package/dist/{tangle-DWzUnb1Y.js → tangle-Crxw_6V-.js} +22 -17
  66. package/dist/{terminal-stream-types-DB8V0hiG.d.ts → terminal-stream-types-eE97lZ-5.d.ts} +0 -1
  67. package/dist/{types-Cmv31xBh.d.ts → types-Cs5eJzOK.d.ts} +17 -57
  68. package/package.json +5 -5
  69. package/dist/cli-auth-bundle-CMJWI99l.js +0 -2
  70. package/dist/sidecar-proxy-error-DpBLxIof.js +0 -24
  71. /package/dist/{abort-signal-BbJTt2QJ.js → abort-signal-CRxC2dlT.js} +0 -0
  72. /package/dist/{cli-auth-bundle-C6DtK7GX-BbbiAn-Z.js → cli-auth-bundle-C6DtK7GX-mBUPER0R.js} +0 -0
  73. /package/dist/{cli-auth-bundle-Wg3x2hd2.d.ts → cli-auth-bundle-CjSu4D9W.d.ts} +0 -0
  74. /package/dist/{file-transfer-BSe4ayU9.js → file-transfer-DOSTbUSR.js} +0 -0
  75. /package/dist/{index-CDtEPygc.d.ts → index-C-_HY5NY.d.ts} +0 -0
  76. /package/dist/{index-YbAo-so_.d.ts → index-o31uwAkX.d.ts} +0 -0
  77. /package/dist/{keep-alive-fetch-BIaDMUtu.js → keep-alive-fetch-sGVP8skk.js} +0 -0
  78. /package/dist/{preview-operations-B3TTvqlm.js → preview-operations-DWL78boI.js} +0 -0
  79. /package/dist/{retry-after-header-DUdCC0KJ.js → retry-after-header-BZbs5rig.js} +0 -0
  80. /package/dist/{sse-parser-DOCszo1K.js → sse-parser-BCG3iL9j.js} +0 -0
  81. /package/dist/{utils-CK-x8vXj.js → utils-BT2q9nkO.js} +0 -0
@@ -1,163 +1,10 @@
1
1
  import { r as agentProfileSchema } from "./profile-schema-C1KpT-wS.js";
2
- import { rt as canonicalAgentProfileDigest } from "./sandbox-Dvk2PYnL.js";
3
- import { D as ValidationError, S as SandboxError, l as CapabilityError } from "./errors-A-bhwwsE.js";
4
- import { t as awaitWithAbort } from "./abort-signal-BbJTt2QJ.js";
5
- import { r as cliAuthReferenceSchema } from "./cli-auth-bundle-C6DtK7GX-BbbiAn-Z.js";
6
- import "./cli-auth-bundle-CMJWI99l.js";
2
+ import { t as canonicalAgentProfileDigest } from "./agent-execution-preparation-BJChICex.js";
3
+ import { D as ValidationError, S as SandboxError, l as CapabilityError } from "./errors-nXGKGVFe.js";
4
+ import { t as awaitWithAbort } from "./abort-signal-CRxC2dlT.js";
5
+ import { r as cliAuthReferenceSchema } from "./cli-auth-bundle-C6DtK7GX-mBUPER0R.js";
6
+ import "./cli-auth-bundle-BLAtE6Dc.js";
7
7
  import { z } from "zod";
8
- //#region src/failure-kind.ts
9
- const LOST_CODES = new Set(["BACKING_CONTAINER_MISSING", "SANDBOX_NOT_FOUND"]);
10
- const CAPACITY_CODES = new Set([
11
- "CAPACITY_EXHAUSTED",
12
- "HOST_PRESSURE",
13
- "PROVISIONING_PAUSED"
14
- ]);
15
- const BUDGET_CODES = new Set(["KEY_BUDGET_EXHAUSTED", "QUOTA_EXCEEDED"]);
16
- const CAPACITY_MESSAGE = /admits no further box|host has no available slot|host capacity reservation failed|no available hosts with capacity/i;
17
- function chain(error) {
18
- const causes = [];
19
- let current = error;
20
- for (let depth = 0; depth < 8 && current && typeof current === "object"; depth += 1) {
21
- if (causes.includes(current)) break;
22
- causes.push(current);
23
- current = current.cause;
24
- }
25
- return causes;
26
- }
27
- function sandboxFailureKind(error) {
28
- for (const cause of chain(error)) {
29
- const code = String(cause.code ?? "").toUpperCase();
30
- if (LOST_CODES.has(code)) return "lost";
31
- if (BUDGET_CODES.has(code) || code.endsWith("_QUOTA_EXCEEDED")) return "budget";
32
- if (CAPACITY_CODES.has(code)) return "capacity";
33
- if (typeof cause.message === "string" && CAPACITY_MESSAGE.test(cause.message)) return "capacity";
34
- }
35
- return null;
36
- }
37
- //#endregion
38
- //#region src/line-application.ts
39
- /** Bounded callback request bytes after canonicalization, including JSON framing. */
40
- const LINE_APPLICATION_REQUEST_MAX_BYTES = 96 * 1024;
41
- /** Fits the Lines reply splitter and the callback transport's 64 KiB read bound. */
42
- const LINE_APPLICATION_REPLY_MAX_CHARS = 12e3;
43
- function record(value) {
44
- if (value === null || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Expected a line application object");
45
- return value;
46
- }
47
- function text(value, max) {
48
- if (typeof value !== "string" || !value.trim() || value.includes("\0") || value.length > max) throw new TypeError("Invalid line application text");
49
- return value;
50
- }
51
- function id(value) {
52
- const result = text(value, 256);
53
- if (!/^[A-Za-z0-9][A-Za-z0-9_.:@-]*$/.test(result)) throw new TypeError("Invalid line application identity");
54
- return result;
55
- }
56
- function subjectId(value) {
57
- if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9:._-]{0,127}$/.test(value)) throw new TypeError("Invalid line application subject");
58
- return value;
59
- }
60
- function revision(value) {
61
- const result = text(value, 64);
62
- 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");
63
- return result;
64
- }
65
- function deadline(value) {
66
- const result = text(value, 64);
67
- 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");
68
- return result;
69
- }
70
- function binding(value) {
71
- const result = text(value, 1024);
72
- if (!/^[\x21-\x7e]+$/.test(result)) throw new TypeError("Invalid line application binding");
73
- return result;
74
- }
75
- /** Canonicalize only defined fields. Unknown provider payloads and credentials stay out. */
76
- function parseLineApplicationRequest(value) {
77
- const input = record(value);
78
- if (input.version !== 1) throw new TypeError("Unknown line application version");
79
- const sender = record(input.sender);
80
- const transport = input.transport;
81
- if (transport !== "imessage" && transport !== "sms" && transport !== "whatsapp" && transport !== "email") throw new TypeError("Unknown line transport");
82
- const receivedAt = text(input.receivedAt, 64);
83
- if (!Number.isFinite(Date.parse(receivedAt))) throw new TypeError("Invalid line message time");
84
- const hasSubject = input.subjectId !== void 0;
85
- const hasRevision = input.memberRevision !== void 0;
86
- if (hasSubject !== hasRevision) throw new TypeError("Incomplete line member authority");
87
- const hasFence = input.dispatchFence !== void 0;
88
- const hasDeadline = input.dispatchDeadline !== void 0;
89
- if (hasFence !== hasDeadline || hasSubject && !hasFence && input.acceptedExecutionId === void 0) throw new TypeError("Incomplete line dispatch authority");
90
- const result = {
91
- version: 1,
92
- binding: binding(input.binding),
93
- messageId: id(input.messageId),
94
- lineId: id(input.lineId),
95
- attachmentId: id(input.attachmentId),
96
- memberId: id(input.memberId),
97
- lineThreadId: id(input.lineThreadId),
98
- ownerUserId: id(input.ownerUserId),
99
- ...hasSubject ? { subjectId: subjectId(input.subjectId) } : {},
100
- ...hasRevision ? { memberRevision: revision(input.memberRevision) } : {},
101
- ...hasFence ? { dispatchFence: id(input.dispatchFence) } : {},
102
- ...hasDeadline ? { dispatchDeadline: deadline(input.dispatchDeadline) } : {},
103
- sender: {
104
- address: text(sender.address, 320),
105
- role: id(sender.role)
106
- },
107
- transport,
108
- receivedAt,
109
- ...input.acceptedExecutionId === void 0 ? {} : { acceptedExecutionId: id(input.acceptedExecutionId) },
110
- text: text(input.text, 64 * 1024)
111
- };
112
- if (new TextEncoder().encode(JSON.stringify(result)).byteLength > 98304) throw new TypeError("Line application request exceeds the byte limit");
113
- return result;
114
- }
115
- /** A raw agent response is not this receipt. Applications report only settled output. */
116
- function parseLineApplicationResult(value, request) {
117
- const result = record(value);
118
- if (result.version !== 1 || result.binding !== request.binding || result.messageId !== request.messageId || result.attachmentId !== request.attachmentId) throw new TypeError("Line application result identity mismatch");
119
- if (request.acceptedExecutionId !== void 0 && result.executionId !== request.acceptedExecutionId) throw new TypeError("Accepted application execution changed");
120
- const identity = {
121
- version: 1,
122
- binding: request.binding,
123
- messageId: request.messageId,
124
- attachmentId: request.attachmentId
125
- };
126
- switch (result.state) {
127
- case "pending":
128
- if (typeof result.admitted !== "boolean") throw new TypeError("Admission is not established");
129
- if (result.admitted) return {
130
- ...identity,
131
- state: "pending",
132
- admitted: true,
133
- executionId: id(result.executionId)
134
- };
135
- if (result.executionId !== void 0) throw new TypeError("Unadmitted result cannot name an execution");
136
- return {
137
- ...identity,
138
- state: "pending",
139
- admitted: false
140
- };
141
- case "completed": return {
142
- ...identity,
143
- state: "completed",
144
- executionId: id(result.executionId),
145
- text: text(result.text, LINE_APPLICATION_REPLY_MAX_CHARS)
146
- };
147
- case "failed": {
148
- const code = text(result.code, 80);
149
- if (!/^[a-z][a-z0-9_:.-]*$/.test(code)) throw new TypeError("Invalid failure code");
150
- return {
151
- ...identity,
152
- state: "failed",
153
- code,
154
- ...result.executionId === void 0 ? {} : { executionId: id(result.executionId) }
155
- };
156
- }
157
- default: throw new TypeError("Unknown line application state");
158
- }
159
- }
160
- //#endregion
161
8
  //#region ../../../packages/runtime-contracts/dist/seat-selection.js
162
9
  /**
163
10
  * Wire contract of `POST /v1/model-credentials/resolve` seat selection, shared by
@@ -207,18 +54,47 @@ const resolutionSchema = z.strictObject({
207
54
  credentials: credentialsSchema
208
55
  });
209
56
  const refusalSchema = seatSelectionRefusalSchema;
57
+ const SEAT_OWNER_MAX_RESPONSE_BYTES = 64 * 1024;
58
+ const SEAT_OWNER_MAX_REQUEST_BYTES = 8 * 1024 * 1024;
210
59
  /** The authenticated Sandbox gateway to the hosted account owner. */
211
60
  function gatewaySeatTransport(client) {
212
61
  return async (request, signal) => {
62
+ const payload = JSON.stringify(request);
63
+ if (new TextEncoder().encode(payload).byteLength > 8388608) throw new ValidationError("The account owner request exceeded its public bound");
213
64
  const response = await client.fetch("/v1/model-credentials/resolve", {
214
65
  method: "POST",
215
- body: JSON.stringify(request),
66
+ redirect: "error",
67
+ body: payload,
216
68
  ...signal ? { signal } : {}
217
69
  });
218
- const body = await response.json().catch((error) => {
219
- if (error instanceof SyntaxError) throw new ValidationError("The account owner returned invalid JSON");
220
- throw error;
221
- });
70
+ const reader = response.body?.getReader();
71
+ if (!reader) throw new ValidationError("The account owner returned no reply");
72
+ const chunks = [];
73
+ let size = 0;
74
+ try {
75
+ for (;;) {
76
+ const { done, value } = await awaitWithAbort(reader.read(), signal);
77
+ if (done) break;
78
+ size += value.byteLength;
79
+ if (size > 65536) throw new ValidationError("The account owner exceeded its public response bound");
80
+ chunks.push(value);
81
+ }
82
+ } finally {
83
+ await reader.cancel();
84
+ reader.releaseLock();
85
+ }
86
+ const bytes = new Uint8Array(size);
87
+ let offset = 0;
88
+ for (const chunk of chunks) {
89
+ bytes.set(chunk, offset);
90
+ offset += chunk.byteLength;
91
+ }
92
+ let body;
93
+ try {
94
+ body = JSON.parse(new TextDecoder().decode(bytes));
95
+ } catch {
96
+ throw new ValidationError("The account owner returned invalid JSON");
97
+ }
222
98
  return {
223
99
  ok: response.ok,
224
100
  status: response.status,
@@ -366,11 +242,4 @@ function createSelectSeat(options) {
366
242
  };
367
243
  }
368
244
  //#endregion
369
- //#region src/core.ts
370
- /** Local SDK protocol support only, not a deployed-host readiness assertion.
371
- * Version 1 refuses unconfirmed isolated receipts before materializing any
372
- * profile/files and suppresses ambient CLI credential discovery. Callers must
373
- * still inspect the host receipt and their own customer/workspace binding. */
374
- const ISOLATED_CREATION_ATTESTATION_VERSION = 1;
375
- //#endregion
376
- export { LINE_APPLICATION_REPLY_MAX_CHARS as a, parseLineApplicationResult as c, gatewaySeatTransport as i, sandboxFailureKind as l, SeatSelectionError as n, LINE_APPLICATION_REQUEST_MAX_BYTES as o, createSelectSeat as r, parseLineApplicationRequest as s, ISOLATED_CREATION_ATTESTATION_VERSION as t };
245
+ export { gatewaySeatTransport as a, createSelectSeat as i, SEAT_OWNER_MAX_RESPONSE_BYTES as n, SeatSelectionError as r, SEAT_OWNER_MAX_REQUEST_BYTES as t };
@@ -1,4 +1,5 @@
1
- import { mt as SeatOwnerTransport } from "./client-DvvRMxKx.js";
1
+ import { L as SandboxError } from "./terminal-stream-types-eE97lZ-5.js";
2
+ import { ht as SeatOwnerTransport, vt as SeatSelectionRequest } from "./client-DlTDphmI.js";
2
3
 
3
4
  //#region src/select-seat-command.d.ts
4
5
  /** Public reply bound; the owner prints one metadata object. */
@@ -11,6 +12,11 @@ interface CommandSeatTransportOptions {
11
12
  env?: Record<string, string | undefined>;
12
13
  timeoutMs?: number;
13
14
  }
14
- declare function commandSeatTransport(options: CommandSeatTransportOptions): SeatOwnerTransport;
15
+ declare class SeatOwnerCommandError extends SandboxError {
16
+ readonly exitCode: number | null;
17
+ readonly terminationSignal: string | null;
18
+ constructor(message: string, exitCode?: number | null, terminationSignal?: string | null);
19
+ }
20
+ declare function commandSeatTransport<Request = SeatSelectionRequest>(options: CommandSeatTransportOptions): SeatOwnerTransport<Request>;
15
21
  //#endregion
16
- export { CommandSeatTransportOptions, SEAT_COMMAND_MAX_RESPONSE_BYTES, SEAT_COMMAND_TIMEOUT_MS, commandSeatTransport };
22
+ export { CommandSeatTransportOptions, SEAT_COMMAND_MAX_RESPONSE_BYTES, SEAT_COMMAND_TIMEOUT_MS, SeatOwnerCommandError, commandSeatTransport };
@@ -1,4 +1,5 @@
1
- import { D as ValidationError, S as SandboxError } from "./errors-A-bhwwsE.js";
1
+ import { D as ValidationError, S as SandboxError } from "./errors-nXGKGVFe.js";
2
+ import { n as SEAT_OWNER_MAX_RESPONSE_BYTES } from "./select-seat-B4Y-7vIq.js";
2
3
  import { spawn } from "node:child_process";
3
4
  //#region src/select-seat-command.ts
4
5
  /**
@@ -17,7 +18,7 @@ import { spawn } from "node:child_process";
17
18
  * @packageDocumentation
18
19
  */
19
20
  /** Public reply bound; the owner prints one metadata object. */
20
- const SEAT_COMMAND_MAX_RESPONSE_BYTES = 64 * 1024;
21
+ const SEAT_COMMAND_MAX_RESPONSE_BYTES = SEAT_OWNER_MAX_RESPONSE_BYTES;
21
22
  const SEAT_COMMAND_TIMEOUT_MS = 3e4;
22
23
  /** The owner command's exit contract: 0 selected, 75 capacity refusal, 78 permanent route refusal. */
23
24
  const EXIT_STATUS = {
@@ -25,66 +26,77 @@ const EXIT_STATUS = {
25
26
  75: 503,
26
27
  78: 400
27
28
  };
29
+ var SeatOwnerCommandError = class extends SandboxError {
30
+ constructor(message, exitCode = null, terminationSignal = null) {
31
+ super(message, {
32
+ code: "SEAT_SELECTION_UNCONFIRMED",
33
+ status: 502
34
+ });
35
+ this.exitCode = exitCode;
36
+ this.terminationSignal = terminationSignal;
37
+ }
38
+ };
28
39
  function commandSeatTransport(options) {
29
40
  const [program, ...args] = options.command;
30
41
  if (program === void 0 || options.command.some((part) => typeof part !== "string" || part.length === 0)) throw new ValidationError("Seat selection requires a configured account command");
31
42
  const timeoutMs = options.timeoutMs ?? 3e4;
32
- return (request, signal) => new Promise((resolve, reject) => {
33
- signal?.throwIfAborted();
34
- const child = spawn(program, args, {
35
- env: options.env ?? process.env,
36
- shell: false,
37
- stdio: [
38
- "pipe",
39
- "pipe",
40
- "pipe"
41
- ]
42
- });
43
- let settled = false;
44
- let size = 0;
45
- const chunks = [];
46
- const finish = (error, reply = null) => {
47
- if (settled) return;
48
- settled = true;
49
- clearTimeout(timer);
50
- signal?.removeEventListener("abort", abort);
51
- if (error) {
52
- child.kill("SIGKILL");
53
- reject(error);
54
- } else if (reply) resolve(reply);
55
- };
56
- const fail = (message) => finish(new SandboxError(message, {
57
- code: "SEAT_SELECTION_UNCONFIRMED",
58
- status: 502
59
- }));
60
- const abort = () => finish(signal?.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("aborted"));
61
- signal?.addEventListener("abort", abort, { once: true });
62
- const timer = setTimeout(() => fail("The account owner command timed out"), timeoutMs);
63
- child.stderr.resume();
64
- child.stdin.on("error", () => fail("The account owner command refused its request"));
65
- child.stdout.on("data", (chunk) => {
66
- size += chunk.length;
67
- if (size > 65536) return fail("The account owner exceeded its public response bound");
68
- chunks.push(chunk);
69
- });
70
- child.on("error", () => fail("The account owner command could not start"));
71
- child.on("close", (code) => {
72
- const status = code === null ? void 0 : EXIT_STATUS[code];
73
- if (status === void 0) return fail("The account owner could not establish eligible capacity");
74
- let body;
75
- try {
76
- body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
77
- } catch {
78
- return finish(new ValidationError("The account owner returned invalid JSON"));
79
- }
80
- finish(null, {
81
- ok: status === 200,
82
- status,
83
- body
43
+ return (request, signal) => {
44
+ const payload = JSON.stringify(request);
45
+ if (Buffer.byteLength(payload) > 8388608) return Promise.reject(new ValidationError("The account owner request exceeded its public bound"));
46
+ return new Promise((resolve, reject) => {
47
+ signal?.throwIfAborted();
48
+ const child = spawn(program, args, {
49
+ env: options.env ?? process.env,
50
+ shell: false,
51
+ stdio: [
52
+ "pipe",
53
+ "pipe",
54
+ "pipe"
55
+ ]
56
+ });
57
+ let settled = false;
58
+ let size = 0;
59
+ const chunks = [];
60
+ const finish = (error, reply = null) => {
61
+ if (settled) return;
62
+ settled = true;
63
+ clearTimeout(timer);
64
+ signal?.removeEventListener("abort", abort);
65
+ if (error) {
66
+ child.kill("SIGKILL");
67
+ reject(error);
68
+ } else if (reply) resolve(reply);
69
+ };
70
+ const fail = (message, code = null, signal = null) => finish(new SeatOwnerCommandError(message, code, signal));
71
+ const abort = () => finish(signal?.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("aborted"));
72
+ signal?.addEventListener("abort", abort, { once: true });
73
+ const timer = setTimeout(() => fail("The account owner command timed out"), timeoutMs);
74
+ child.stderr.resume();
75
+ child.stdin.on("error", () => fail("The account owner command refused its request"));
76
+ child.stdout.on("data", (chunk) => {
77
+ size += chunk.length;
78
+ if (size > SEAT_COMMAND_MAX_RESPONSE_BYTES) return fail("The account owner exceeded its public response bound");
79
+ chunks.push(chunk);
80
+ });
81
+ child.on("error", () => fail("The account owner command could not start"));
82
+ child.on("close", (code, terminationSignal) => {
83
+ const status = code === null ? void 0 : EXIT_STATUS[code];
84
+ if (status === void 0) return fail("The account owner could not establish eligible capacity", code, terminationSignal);
85
+ let body;
86
+ try {
87
+ body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
88
+ } catch {
89
+ return finish(new ValidationError("The account owner returned invalid JSON"));
90
+ }
91
+ finish(null, {
92
+ ok: status === 200,
93
+ status,
94
+ body
95
+ });
84
96
  });
97
+ child.stdin.end(payload);
85
98
  });
86
- child.stdin.end(JSON.stringify(request));
87
- });
99
+ };
88
100
  }
89
101
  //#endregion
90
- export { SEAT_COMMAND_MAX_RESPONSE_BYTES, SEAT_COMMAND_TIMEOUT_MS, commandSeatTransport };
102
+ export { SEAT_COMMAND_MAX_RESPONSE_BYTES, SEAT_COMMAND_TIMEOUT_MS, SeatOwnerCommandError, commandSeatTransport };
@@ -1,6 +1,7 @@
1
- import { n as combineAbortSignals } from "../abort-signal-BbJTt2QJ.js";
2
- import "../sidecar-proxy-error-DpBLxIof.js";
3
- import { t as parseSSEStream } from "../sse-parser-DOCszo1K.js";
1
+ import { n as combineAbortSignals } from "../abort-signal-CRxC2dlT.js";
2
+ import { i as fetchSandboxApi } from "../api-request-dyabkosT.js";
3
+ import "../sidecar-proxy-error-DTdbCbUM.js";
4
+ import { t as parseSSEStream } from "../sse-parser-BCG3iL9j.js";
4
5
  import { PART_TEXT, PART_TEXT_SUFFIX } from "@tangle-network/agent-core/sse";
5
6
  //#region ../../../packages/runtime-contracts/dist/session-gateway.js
6
7
  /**
@@ -60,22 +61,9 @@ function calculateSessionStreamConnectionQuality(metrics, isConnected) {
60
61
  //#endregion
61
62
  //#region src/session-gateway/client.ts
62
63
  /**
63
- * SessionGatewayClient: one agent session's events, read from the sandbox's
64
- * cell edge, so no control-plane process holds a socket for them.
65
- *
66
- * The client reads `GET {url}/agents/events`, where a browser's `url` is the
67
- * Sandbox API proxy (`ScopedToken.sidecarProxyUrl`) because the box host
68
- * is server-facing; a server may read the box host. While the session runs a
69
- * turn, it reads that turn's execution stream (`executionId`): every frame
70
- * comes from the sidecar's event store with its store id, and an attach
71
- * resumes after the last delivered id (`since`), so a drop loses nothing and
72
- * repeats nothing. Between turns it reads the session stream, which carries
73
- * the session's container events (ports, sidecar, Hub); a turn frame there
74
- * makes the client move to that turn's execution stream from its first
75
- * event. Each attach first asks the runtime which turn is running
76
- * (`GET /agents/sessions/{id}`).
77
- *
78
- * Browser-safe: global `fetch` and streams only.
64
+ * Browser-safe session events from the API proxy or owning host.
65
+ * Execution-store ids resume without gaps/duplicates; a session turn frame
66
+ * switches to that execution's stream, then returns to session events.
79
67
  */
80
68
  const DEFAULTS = {
81
69
  autoReconnect: true,
@@ -180,7 +168,10 @@ var SessionGatewayClient = class {
180
168
  const url = runtimeBaseUrl(config.url);
181
169
  const fetchImpl = config.fetch ?? globalThis.fetch;
182
170
  if (typeof fetchImpl !== "function") throw new Error("SessionGatewayClient requires a fetch implementation");
183
- this.#fetch = (input, init) => fetchImpl(input, init);
171
+ this.#fetch = (input, init) => fetchSandboxApi({
172
+ baseUrl: "",
173
+ fetchImpl
174
+ }, String(input), init);
184
175
  this.#config = {
185
176
  url,
186
177
  sessionId,
@@ -0,0 +1,4 @@
1
+ //#region ../../../packages/runtime-contracts/dist/sidecar-proxy-error.js
2
+ const SIDECAR_PROXY_ERROR_HEADER = "X-Tangle-Sidecar-Proxy-Error";
3
+ //#endregion
4
+ export { SIDECAR_PROXY_ERROR_HEADER as t };
@@ -1,2 +1,2 @@
1
- import { C as JsonResponseParamTypes, E as SandboxIdParamTypes, S as JOB_SANDBOX_DELETE, T as SandboxCreateResponseParamTypes, _ as TANGLE_CHAIN_ID, a as fetchQuote, b as AgentSandboxBlueprintAbi, c as parseQuoteResponse, d as OperatorSession, f as OperatorSessionError, g as BlueprintSandboxClientConfig, h as BlueprintSandboxClient, i as SignedQuote, l as validateQuote, m as SignMessage, n as QuoteDomain, o as inputsHashOf, p as OperatorSessionToken, r as QuoteError, s as jobQuoteDigest, t as JobQuoteDetails, u as OperatorChallenge, v as TANGLE_JOBS_CONTRACT, w as SandboxCreateParamTypes, x as JOB_SANDBOX_CREATE, y as ITangleJobsAbi } from "../index-Cip3q_xe.js";
1
+ import { C as JsonResponseParamTypes, E as SandboxIdParamTypes, S as JOB_SANDBOX_DELETE, T as SandboxCreateResponseParamTypes, _ as TANGLE_CHAIN_ID, a as fetchQuote, b as AgentSandboxBlueprintAbi, c as parseQuoteResponse, d as OperatorSession, f as OperatorSessionError, g as BlueprintSandboxClientConfig, h as BlueprintSandboxClient, i as SignedQuote, l as validateQuote, m as SignMessage, n as QuoteDomain, o as inputsHashOf, p as OperatorSessionToken, r as QuoteError, s as jobQuoteDigest, t as JobQuoteDetails, u as OperatorChallenge, v as TANGLE_JOBS_CONTRACT, w as SandboxCreateParamTypes, x as JOB_SANDBOX_CREATE, y as ITangleJobsAbi } from "../index-DE5n6mot.js";
2
2
  export { AgentSandboxBlueprintAbi, BlueprintSandboxClient, BlueprintSandboxClientConfig, ITangleJobsAbi, JOB_SANDBOX_CREATE, JOB_SANDBOX_DELETE, JobQuoteDetails, JsonResponseParamTypes, OperatorChallenge, OperatorSession, OperatorSessionError, OperatorSessionToken, QuoteDomain, QuoteError, SandboxCreateParamTypes, SandboxCreateResponseParamTypes, SandboxIdParamTypes, SignMessage, SignedQuote, TANGLE_CHAIN_ID, TANGLE_JOBS_CONTRACT, fetchQuote, inputsHashOf, jobQuoteDigest, parseQuoteResponse, validateQuote };
@@ -1,2 +1,2 @@
1
- import { _ as SandboxCreateParamTypes, a as parseQuoteResponse, c as OperatorSession, d as TANGLE_JOBS_CONTRACT, f as ITangleJobsAbi, g as JsonResponseParamTypes, h as JOB_SANDBOX_DELETE, i as jobQuoteDigest, l as OperatorSessionError, m as JOB_SANDBOX_CREATE, n as fetchQuote, o as validateQuote, p as AgentSandboxBlueprintAbi, r as inputsHashOf, s as BlueprintSandboxClient, t as QuoteError, u as TANGLE_CHAIN_ID, v as SandboxCreateResponseParamTypes, y as SandboxIdParamTypes } from "../tangle-DWzUnb1Y.js";
1
+ import { _ as SandboxCreateParamTypes, a as parseQuoteResponse, c as OperatorSession, d as TANGLE_JOBS_CONTRACT, f as ITangleJobsAbi, g as JsonResponseParamTypes, h as JOB_SANDBOX_DELETE, i as jobQuoteDigest, l as OperatorSessionError, m as JOB_SANDBOX_CREATE, n as fetchQuote, o as validateQuote, p as AgentSandboxBlueprintAbi, r as inputsHashOf, s as BlueprintSandboxClient, t as QuoteError, u as TANGLE_CHAIN_ID, v as SandboxCreateResponseParamTypes, y as SandboxIdParamTypes } from "../tangle-Crxw_6V-.js";
2
2
  export { AgentSandboxBlueprintAbi, BlueprintSandboxClient, ITangleJobsAbi, JOB_SANDBOX_CREATE, JOB_SANDBOX_DELETE, JsonResponseParamTypes, OperatorSession, OperatorSessionError, QuoteError, SandboxCreateParamTypes, SandboxCreateResponseParamTypes, SandboxIdParamTypes, TANGLE_CHAIN_ID, TANGLE_JOBS_CONTRACT, fetchQuote, inputsHashOf, jobQuoteDigest, parseQuoteResponse, validateQuote };
@@ -1,6 +1,7 @@
1
- import { L as readFilesystemIncarnationTuple, n as createSandboxInstanceFromResponse } from "./sandbox-Dvk2PYnL.js";
2
- import { a as readResponseJson } from "./errors-A-bhwwsE.js";
3
- import { _ as rotlBH, a as anumber, b as rotlSL, d as createXOFer, g as u32, h as toBytes$1, l as createHasher, m as swap32IfBE, n as abytes, o as aoutput, r as aexists, s as clean, t as Hash, v as rotlBL, x as split, y as rotlSH } from "./utils-CK-x8vXj.js";
1
+ import { L as readFilesystemIncarnationTuple, n as createSandboxInstanceFromResponse } from "./sandbox-OyCRplrI.js";
2
+ import { a as readResponseJson } from "./errors-nXGKGVFe.js";
3
+ import { i as fetchSandboxApi } from "./api-request-dyabkosT.js";
4
+ import { _ as rotlBH, a as anumber, b as rotlSL, d as createXOFer, g as u32, h as toBytes$1, l as createHasher, m as swap32IfBE, n as abytes, o as aoutput, r as aexists, s as clean, t as Hash, v as rotlBL, x as split, y as rotlSH } from "./utils-BT2q9nkO.js";
4
5
  //#region ../../../packages/runtime-contracts/dist/tangle-blueprint-abi.js
5
6
  /**
6
7
  * Tangle blueprint wire contract shared by the orchestrator's Tangle driver and
@@ -998,12 +999,18 @@ var OperatorSession = class OperatorSession {
998
999
  */
999
1000
  static async establish(baseUrl, signMessage, fetchImpl = fetch) {
1000
1001
  const root = baseUrl.replace(/\/+$/, "");
1001
- const challengeResponse = await fetchImpl(`${root}/api/auth/challenge`, { method: "POST" });
1002
+ const challengeResponse = await fetchSandboxApi({
1003
+ baseUrl: "",
1004
+ fetchImpl
1005
+ }, `${root}/api/auth/challenge`, { method: "POST" });
1002
1006
  if (!challengeResponse.ok) throw new OperatorSessionError(`Operator challenge failed (HTTP ${challengeResponse.status})`, challengeResponse.status);
1003
1007
  const challenge = await challengeResponse.json();
1004
1008
  if (!challenge?.nonce || !challenge?.message) throw new OperatorSessionError("Operator challenge response is missing nonce/message");
1005
1009
  const signature = await signMessage(challenge.message);
1006
- const sessionResponse = await fetchImpl(`${root}/api/auth/session`, {
1010
+ const sessionResponse = await fetchSandboxApi({
1011
+ baseUrl: "",
1012
+ fetchImpl
1013
+ }, `${root}/api/auth/session`, {
1007
1014
  method: "POST",
1008
1015
  headers: { "Content-Type": "application/json" },
1009
1016
  body: JSON.stringify({
@@ -1258,13 +1265,13 @@ var BlueprintSandboxClient = class {
1258
1265
  * - POST /v1/sandboxes/:id/resume → unsupported until blueprint exposes resume
1259
1266
  * - DELETE /v1/sandboxes/:id → on-chain JOB_SANDBOX_DELETE
1260
1267
  */
1261
- async fetch(path, options) {
1268
+ async fetch(path, options, fetchOptions) {
1262
1269
  const method = options?.method ?? "GET";
1263
1270
  const runtimeMatch = path.match(/^\/v1\/sandboxes\/([^/]+)\/runtime(\/.*)$/);
1264
1271
  if (runtimeMatch) {
1265
1272
  const id = decodeURIComponent(requirePathGroup(runtimeMatch, 1));
1266
1273
  const runtimePath = requirePathGroup(runtimeMatch, 2);
1267
- return this.fetchRuntime(id, runtimePath, options);
1274
+ return this.fetchRuntime(id, runtimePath, options, fetchOptions);
1268
1275
  }
1269
1276
  const getMatch = path.match(/^\/v1\/sandboxes\/([^/]+)$/);
1270
1277
  if (getMatch && method === "GET") {
@@ -1349,7 +1356,7 @@ var BlueprintSandboxClient = class {
1349
1356
  }
1350
1357
  throw new Error(`Operation not supported via on-chain client: ${method} ${path}`);
1351
1358
  }
1352
- async fetchRuntime(sandboxId, runtimePath, options) {
1359
+ async fetchRuntime(sandboxId, runtimePath, options, fetchOptions) {
1353
1360
  let entry = this.#sandboxes.get(sandboxId);
1354
1361
  if (this.operatorApiUrl) {
1355
1362
  const operatorResponse = await this.fetchOperatorApi(`/api/sandboxes/${encodeURIComponent(sandboxId)}`, { method: "GET" });
@@ -1366,12 +1373,10 @@ var BlueprintSandboxClient = class {
1366
1373
  headers.set("Authorization", `Bearer ${entry.runtimeToken}`);
1367
1374
  const isFormDataBody = typeof FormData !== "undefined" && options?.body instanceof FormData;
1368
1375
  if (!headers.has("Content-Type") && !isFormDataBody) headers.set("Content-Type", "application/json");
1369
- const method = options?.method ?? "GET";
1370
- return await fetch(`${entry.runtimeUrl.replace(/\/$/, "")}${runtimePath}`, {
1376
+ return fetchSandboxApi({ baseUrl: entry.runtimeUrl }, runtimePath, {
1371
1377
  ...options,
1372
- method,
1373
1378
  headers
1374
- });
1379
+ }, fetchOptions);
1375
1380
  }
1376
1381
  /**
1377
1382
  * Get available capacity from the blueprint contract.
@@ -1410,7 +1415,7 @@ var BlueprintSandboxClient = class {
1410
1415
  */
1411
1416
  async injectSecrets(sandboxId, secrets) {
1412
1417
  await this.withOperatorSession(sandboxId, async (session, url) => {
1413
- return await fetch(`${url}/api/sandboxes/${encodeURIComponent(sandboxId)}/secrets`, {
1418
+ return await fetchSandboxApi({ baseUrl: "" }, `${url}/api/sandboxes/${encodeURIComponent(sandboxId)}/secrets`, {
1414
1419
  method: "POST",
1415
1420
  headers: {
1416
1421
  Authorization: session.authorizationHeader(),
@@ -1423,7 +1428,7 @@ var BlueprintSandboxClient = class {
1423
1428
  /** Read a sandbox's provisioned secret keys and credential availability. */
1424
1429
  async getSecrets(sandboxId) {
1425
1430
  return this.withOperatorSession(sandboxId, async (session, url) => {
1426
- return await fetch(`${url}/api/sandboxes/${encodeURIComponent(sandboxId)}/secrets`, {
1431
+ return await fetchSandboxApi({ baseUrl: "" }, `${url}/api/sandboxes/${encodeURIComponent(sandboxId)}/secrets`, {
1427
1432
  method: "GET",
1428
1433
  headers: { Authorization: session.authorizationHeader() }
1429
1434
  });
@@ -1437,7 +1442,7 @@ var BlueprintSandboxClient = class {
1437
1442
  });
1438
1443
  }
1439
1444
  async readSandboxCredentials(sandboxId) {
1440
- const body = await (await this.withOperatorSession(sandboxId, async (session, url) => fetch(`${url}/api/sandboxes/${encodeURIComponent(sandboxId)}/credentials`, {
1445
+ const body = await (await this.withOperatorSession(sandboxId, async (session, url) => fetchSandboxApi({ baseUrl: "" }, `${url}/api/sandboxes/${encodeURIComponent(sandboxId)}/credentials`, {
1441
1446
  method: "GET",
1442
1447
  headers: { Authorization: session.authorizationHeader() }
1443
1448
  }), "read credentials for")).json();
@@ -1476,7 +1481,7 @@ var BlueprintSandboxClient = class {
1476
1481
  const headers = new Headers(options?.headers);
1477
1482
  if (this.#operatorApiToken && !headers.has("Authorization")) headers.set("Authorization", `Bearer ${this.#operatorApiToken}`);
1478
1483
  if (options?.body && !headers.has("Content-Type")) headers.set("Content-Type", "application/json");
1479
- return fetch(`${this.operatorApiUrl}${path}`, {
1484
+ return fetchSandboxApi({ baseUrl: this.operatorApiUrl }, path, {
1480
1485
  ...options,
1481
1486
  headers
1482
1487
  });
@@ -2712,7 +2717,7 @@ function isAddressEqual(a, b) {
2712
2717
  //#region ../../../node_modules/.pnpm/viem@2.57.11_bufferutil@4.1.0_typescript@6.0.3_utf-8-validate@5.0.10_zod@4.6.6/node_modules/viem/_esm/utils/signature/recoverPublicKey.js
2713
2718
  async function recoverPublicKey({ hash, signature }) {
2714
2719
  const hashHex = isHex(hash) ? hash : toHex(hash);
2715
- const { secp256k1 } = await import("./secp256k1-Cbp9tbkX.js");
2720
+ const { secp256k1 } = await import("./secp256k1-ZiYFbGjz.js");
2716
2721
  return `0x${(() => {
2717
2722
  if (typeof signature === "object" && "r" in signature && "s" in signature) {
2718
2723
  const { r, s, v, yParity } = signature;
@@ -3404,7 +3404,6 @@ declare const ERROR_CATALOG: {
3404
3404
  readonly TEMPLATE_PUBLICATION_WAIT_INTERRUPTED: "504 retry | The SDK stopped waiting for a template publication; the job keeps running. | Resume the wait with resumeJobId instead of publishing again.";
3405
3405
  };
3406
3406
  type ErrorCode = keyof typeof ERROR_CATALOG;
3407
- /** What armed a HOST_AGENT_RESTARTING refusal's planned restart: its `restartKind`. */
3408
3407
  declare const HOST_AGENT_RESTART_KINDS: readonly ["rollout", "maintenance", "authorized", "in_place"];
3409
3408
  type HostAgentRestartKind = (typeof HOST_AGENT_RESTART_KINDS)[number];
3410
3409
  //#endregion