@tangle-network/sandbox 0.59.0 → 0.60.1-develop.20261001222100.ea1ca0e935

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 (42) hide show
  1. package/README.md +6 -0
  2. package/dist/agent/index.d.ts +4 -4
  3. package/dist/agent/index.js +4 -4
  4. package/dist/agent/preview.d.ts +2 -2
  5. package/dist/agent/preview.js +54 -4
  6. package/dist/{agent-run-outcome-C45u1fzK.d.ts → agent-run-outcome-C1GJ1YCD.d.ts} +2 -1
  7. package/dist/auth/index.js +1 -1
  8. package/dist/{browser-interactive-control-controller-DRBQ-jf0.js → browser-interactive-control-controller-BJf0P_J4.js} +40 -3
  9. package/dist/{browser-interactive-control-controller-BzR8sFjo.d.ts → browser-interactive-control-controller-C2qVGzQz.d.ts} +7 -2
  10. package/dist/{cli-auth-bundle-CzmAaefZ.js → cli-auth-bundle-ChOdvrjd.js} +1 -1
  11. package/dist/{client-DYgEM_h5.d.ts → client-jPPuv6Ns.d.ts} +4 -4
  12. package/dist/{client-BbiV61Yy.js → client-p2T45dAv.js} +5 -5
  13. package/dist/collaboration/index.js +1 -1
  14. package/dist/core.d.ts +4 -4
  15. package/dist/core.js +3 -3
  16. package/dist/{index-C8Y65I3y.d.ts → index-CZjj0Wj3.d.ts} +2 -2
  17. package/dist/index.d.ts +10 -9
  18. package/dist/index.js +8 -8
  19. package/dist/interactive-control.d.ts +2 -2
  20. package/dist/interactive-control.js +2 -2
  21. package/dist/{runtime-api-CACSOP5L.js → interactive-controller-DV1HT3NR.js} +850 -8
  22. package/dist/interactive-controller-Dghv9yMk.d.ts +40 -0
  23. package/dist/{lines-VAnaqs-K.d.ts → lines-BoT0rBrj.d.ts} +1 -1
  24. package/dist/lines.d.ts +1 -1
  25. package/dist/{local-cli-auth-ChDP5zu4.js → local-cli-auth-CdIM0B6p.js} +1 -1
  26. package/dist/{mcp-local-DY1CnWBn.js → mcp-local-BSvH4yAU.js} +1 -1
  27. package/dist/{preview-3G1piYer.d.ts → preview-iD-q8YLe.d.ts} +19 -6
  28. package/dist/runtime.d.ts +6 -3
  29. package/dist/runtime.js +3 -3
  30. package/dist/{sandbox-D0-Q1vpS.d.ts → sandbox-BY7KZweP.d.ts} +9 -40
  31. package/dist/{sandbox-BJLb1q3b.js → sandbox-DeE2MDx9.js} +160 -878
  32. package/dist/tangle/index.d.ts +1 -1
  33. package/dist/tangle/index.js +1 -1
  34. package/dist/{tangle-Csb8unvj.js → tangle-DsvldZtQ.js} +1 -1
  35. package/dist/{types-Br35Gfpw.d.ts → types-Cs-0Hy_K.d.ts} +24 -4
  36. package/package.json +6 -4
  37. package/dist/abort-signal-BpYYr4JT.js +0 -31
  38. /package/dist/{collaboration-d8Xcvel7.js → collaboration-C1JAl5kE.js} +0 -0
  39. /package/dist/{line-application-9k30rhb2.js → line-application-DJYY1v8U.js} +0 -0
  40. /package/dist/{preview-operations-CbTiBE-a.js → preview-operations-BLsclF88.js} +0 -0
  41. /package/dist/{specs-CnqSWFNT-CHd9ACzP.js → specs-CnqSWFNT-i2wJxPoD.js} +0 -0
  42. /package/dist/{terminal-stream-CB2DF-qq.d.ts → terminal-stream-C9jxoB07.d.ts} +0 -0
@@ -1,10 +1,9 @@
1
1
  import { r as backendTypeSchema } from "./backend-types-C7b_Gpa0.js";
2
- import { C as normalizeRuntimeBackendConfig, S as mergeRuntimeBackendConfig, T as deriveAgentResultOutcome, _ as encodePromptForWire, a as waitForRetryAfter, b as applyRequestedModel, c as mintTraceId, d as sessionHeaders, f as uploadChunked, h as SANDBOX_PROXY_REQUEST_MAX_BYTES, i as sessionMessageRequestBody, l as resolveTraceId, m as validateAcceptedDispatchRunRef, n as isRetryableCredentialRefusal, o as TRACE_ID_HEADER, p as resolveDispatchRunIdentity, r as normalizeSessionInfo, s as isTraceId, t as SandboxRuntimeApi, u as appendSessionIdQuery, w as createAgentRunOutcomeTracker, x as assertCurrentBackendType, y as parseSSEStream } from "./runtime-api-CACSOP5L.js";
2
+ import { A as mergeRuntimeBackendConfig, C as SANDBOX_PROXY_REQUEST_MAX_BYTES, D as parseSSEStream, M as createAgentRunOutcomeTracker, N as deriveAgentResultOutcome, O as applyRequestedModel, S as validateAcceptedDispatchRunRef, T as encodePromptForWire, _ as resolveTraceId, b as uploadChunked, c as requestScopedToken, d as normalizeSessionInfo, f as sessionMessageRequestBody, g as mintTraceId, h as isTraceId, j as normalizeRuntimeBackendConfig, k as assertCurrentBackendType, l as SandboxRuntimeApi, m as TRACE_ID_HEADER, n as InteractiveSessionController, o as assertScopedTokenActive, p as waitForRetryAfter, r as TerminalStream, u as isRetryableCredentialRefusal, v as appendSessionIdQuery, x as resolveDispatchRunIdentity, y as sessionHeaders } from "./interactive-controller-DV1HT3NR.js";
3
3
  import { _ as parseErrorResponse, c as NotFoundError, f as SandboxError, g as ValidationError, h as TimeoutError, m as StateError, n as CapabilityError, p as ServerError, r as EdgeNotReadyError, s as NetworkError, t as AuthError, u as QuotaError } from "./errors-CKl_BSlD.js";
4
- import { c as createInteractiveControlHolderId, d as interactiveSessionControlReleaseResponseSchema, f as interactiveSessionControlValidationResponseSchema, i as createBrowserInteractiveSessionControlTransport, o as InteractiveSessionControlController, p as interactiveSessionStatusResponseSchema, r as browserInteractiveTerminalEndpoint, s as assertInteractiveSessionRef, u as interactiveSessionControlClaimResponseSchema } from "./browser-interactive-control-controller-DRBQ-jf0.js";
5
- import { n as combineAbortSignals, t as awaitWithAbort } from "./abort-signal-BpYYr4JT.js";
4
+ import { d as awaitWithAbort, f as combineAbortSignals, g as interactiveSessionStatusResponseSchema, h as interactiveSessionControlValidationResponseSchema, l as createInteractiveControlHolderId, m as interactiveSessionControlReleaseResponseSchema, p as interactiveSessionControlClaimResponseSchema } from "./browser-interactive-control-controller-BJf0P_J4.js";
6
5
  import { SandboxLines } from "./lines.js";
7
- import "./specs-CnqSWFNT-CHd9ACzP.js";
6
+ import "./specs-CnqSWFNT-i2wJxPoD.js";
8
7
  import { AgentExactRunControlRefSchema, AgentInteractiveSessionAttachSchema, AgentInteractiveSessionControlClaimAcknowledgementSchema, AgentInteractiveSessionControlClaimRequestSchema, AgentInteractiveSessionControlClaimSchema, AgentInteractiveSessionPromptAcknowledgementSchema, AgentInteractiveSessionPromptCommandSchema, AgentInteractiveSessionRefSchema, AgentInteractiveSessionStartSchema, AgentInteractiveSessionStopAcknowledgementSchema, AgentInteractiveSessionStopCommandSchema, AgentRunCancellationAcknowledgementSchema, AgentRunCancellationRequestSchema, InteractionAcknowledgementSchema, InteractionBindingSchema, InteractionRequestSchema, InteractionResponseCommandSchema, InteractionResponseSchema, TerminalInputSchema, TerminalOutputEventSchema, TerminalReplayWindowSchema, TerminalResizeSchema, TerminalSessionRefSchema, agentInteractiveSessionControlClaimAcknowledgementMatchesRequest, agentInteractiveSessionControlClaimIsNewer, agentInteractiveSessionControlClaimMatchesRef, agentInteractiveSessionPromptAcknowledgementMatchesCommand, agentInteractiveSessionPromptRequestDigest, agentInteractiveSessionRefMatchesStart, agentInteractiveSessionStatusMatchesRef, agentInteractiveSessionStopAcknowledgementMatchesCommand, agentRunCancellationAcknowledgementMatchesRequest, canonicalCandidateDigest, exactAgentInteractiveSessionStart, sha256DigestSchema, terminalSessionUsable } from "@tangle-network/agent-interface";
9
8
  import { z } from "zod";
10
9
  import { AgentInteractiveSessionControlClaimSchema as AgentInteractiveSessionControlClaimSchema$1, AgentInteractiveSessionPromptAcknowledgementSchema as AgentInteractiveSessionPromptAcknowledgementSchema$1, AgentInteractiveSessionRefSchema as AgentInteractiveSessionRefSchema$1, AgentInteractiveSessionStatusSchema, AgentInteractiveSessionStopAcknowledgementSchema as AgentInteractiveSessionStopAcknowledgementSchema$1 } from "@tangle-network/agent-interface/environment-interactive-control";
@@ -303,6 +302,92 @@ function normalizeSandboxShape(raw) {
303
302
  };
304
303
  }
305
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
306
391
  //#region src/managed-process.ts
307
392
  var ManagedProcessClient = class {
308
393
  constructor(request, environmentId) {
@@ -405,17 +490,25 @@ function parseSandboxRuntimeCapabilities(raw) {
405
490
  if ("responseDedupe" in interactionsRecord && typeof interactionsRecord.responseDedupe !== "boolean") invalidCapabilities("a non-boolean 'interactions.responseDedupe' flag");
406
491
  const interactiveAgentValue = record.interactiveAgent;
407
492
  let interactiveAgent;
408
- if (interactiveAgentValue !== void 0) interactiveAgent = readFlagGroup(record, "interactiveAgent", [
409
- "start",
410
- "status",
411
- "attach",
412
- "control",
413
- "reattach",
414
- "sendPrompt",
415
- "input",
416
- "resize",
417
- "stop"
418
- ]);
493
+ if (interactiveAgentValue !== void 0) {
494
+ if (interactiveAgentValue === null || typeof interactiveAgentValue !== "object" || Array.isArray(interactiveAgentValue)) invalidCapabilities("a malformed 'interactiveAgent' group");
495
+ const interactiveAgentRecord = interactiveAgentValue;
496
+ if ("claudeSubscription" in interactiveAgentRecord && typeof interactiveAgentRecord.claudeSubscription !== "boolean") invalidCapabilities("a non-boolean 'interactiveAgent.claudeSubscription' flag");
497
+ interactiveAgent = {
498
+ ...readFlagGroup(record, "interactiveAgent", [
499
+ "start",
500
+ "status",
501
+ "attach",
502
+ "control",
503
+ "reattach",
504
+ "sendPrompt",
505
+ "input",
506
+ "resize",
507
+ "stop"
508
+ ]),
509
+ ...typeof interactiveAgentRecord.claudeSubscription === "boolean" ? { claudeSubscription: interactiveAgentRecord.claudeSubscription } : {}
510
+ };
511
+ }
419
512
  return {
420
513
  schema: 1,
421
514
  ...typeof record.cliAuthReferences === "boolean" ? { cliAuthReferences: record.cliAuthReferences } : {},
@@ -1463,92 +1556,6 @@ var SandboxInteractiveOperations = class {
1463
1556
  }
1464
1557
  };
1465
1558
  //#endregion
1466
- //#region src/scoped-token.ts
1467
- /** Maximum time for the exact interactive terminal-token request. */
1468
- const SCOPED_TOKEN_REQUEST_TIMEOUT_MS = 5e3;
1469
- const scopedTokenResponseSchema = z.object({
1470
- token: z.string().min(1),
1471
- expiresAt: z.number().finite().nonnegative(),
1472
- runtimeUrl: z.string().min(1),
1473
- sidecarProxyUrl: z.string().min(1),
1474
- scope: z.enum([
1475
- "session",
1476
- "session-runtime",
1477
- "project",
1478
- "read-only"
1479
- ])
1480
- });
1481
- /** Reject a scoped credential that the SDK must not send to a consumer. */
1482
- function assertScopedTokenActive(token, expectedScope) {
1483
- if (expectedScope !== void 0 && token.scope !== expectedScope) throw new ValidationError(`Scoped token must use the ${expectedScope} scope`);
1484
- if (typeof token.token !== "string" || !token.token.trim() || !(token.expiresAt instanceof Date) || !Number.isFinite(token.expiresAt.getTime()) || token.expiresAt.getTime() <= Date.now()) throw new ValidationError("Scoped token is expired or invalid");
1485
- }
1486
- function parseScopedTokenResponse(raw, expectedScope) {
1487
- const parsed = scopedTokenResponseSchema.safeParse(raw);
1488
- if (!parsed.success) throw new ServerError("Sandbox API returned an invalid scoped token response.", 502, { origin: "sandbox-api" });
1489
- if (parsed.data.scope !== expectedScope) throw new ServerError(`Sandbox API returned a ${parsed.data.scope} token for a ${expectedScope} request.`, 502, { origin: "sandbox-api" });
1490
- const token = {
1491
- token: parsed.data.token,
1492
- expiresAt: /* @__PURE__ */ new Date(parsed.data.expiresAt * 1e3),
1493
- runtimeUrl: parsed.data.runtimeUrl,
1494
- sidecarProxyUrl: parsed.data.sidecarProxyUrl,
1495
- scope: parsed.data.scope
1496
- };
1497
- try {
1498
- assertScopedTokenActive(token, expectedScope);
1499
- } catch {
1500
- throw new ServerError("Sandbox API returned an expired or invalid scoped token.", 502, { origin: "sandbox-api" });
1501
- }
1502
- return token;
1503
- }
1504
- async function requestScopedToken(client, sandboxId, options, requestOptions) {
1505
- if ((options.scope === "session" || options.scope === "session-runtime") && !options.sessionId) throw new ValidationError(`${options.scope} scope requires a sessionId`);
1506
- if (options.scope === "session" && !options.runtimeSessionId) throw new ValidationError("session scope requires the actual runtimeSessionId");
1507
- const response = await client.fetch(`/v1/sandboxes/${encodeURIComponent(sandboxId)}/scoped-token`, {
1508
- method: "POST",
1509
- headers: { "Content-Type": "application/json" },
1510
- body: JSON.stringify({
1511
- scope: options.scope,
1512
- ...options.sessionId ? { sessionId: options.sessionId } : {},
1513
- ...options.scope === "session" ? { runtimeSessionId: options.runtimeSessionId } : {},
1514
- ...options.ttlMinutes ? { ttlMinutes: options.ttlMinutes } : {}
1515
- }),
1516
- ...options.signal === void 0 ? {} : { signal: options.signal }
1517
- }, requestOptions);
1518
- if (!response.ok) {
1519
- const body = await response.text();
1520
- throw parseErrorResponse(response.status, body, void 0, response.headers);
1521
- }
1522
- let raw;
1523
- try {
1524
- raw = await response.json();
1525
- } catch {
1526
- throw new ServerError("Sandbox API returned invalid scoped token JSON.", 502, { origin: "sandbox-api" });
1527
- }
1528
- return parseScopedTokenResponse(raw, options.scope);
1529
- }
1530
- function parseInteractiveSessionTokenRef(ref) {
1531
- const parsed = AgentInteractiveSessionRefSchema.safeParse(ref);
1532
- if (!parsed.success) throw new ValidationError("Interactive session ref is invalid.", { ref: parsed.error.issues[0]?.message ?? "invalid ref" });
1533
- return parsed.data;
1534
- }
1535
- function interactiveSessionTokenOptions(ref, options = {}) {
1536
- const exactRef = parseInteractiveSessionTokenRef(ref);
1537
- return {
1538
- sandboxId: exactRef.run.environmentId,
1539
- request: {
1540
- scope: "session-runtime",
1541
- sessionId: exactRef.run.sessionId,
1542
- ...options.ttlMinutes === void 0 ? {} : { ttlMinutes: options.ttlMinutes },
1543
- ...options.signal === void 0 ? {} : { signal: options.signal }
1544
- }
1545
- };
1546
- }
1547
- function requestInteractiveSessionToken(client, ref, options) {
1548
- const exact = interactiveSessionTokenOptions(ref, options);
1549
- return requestScopedToken(client, exact.sandboxId, exact.request, { timeoutMs: SCOPED_TOKEN_REQUEST_TIMEOUT_MS });
1550
- }
1551
- //#endregion
1552
1559
  //#region src/sandbox-interactive-terminal.ts
1553
1560
  var SandboxInteractiveTerminalOperations = class {
1554
1561
  constructor(host) {
@@ -1652,752 +1659,6 @@ var SandboxInteractiveTerminalOperations = class {
1652
1659
  });
1653
1660
  }
1654
1661
  };
1655
- const TERMINAL_WS_MAX_DIMENSION = 4096;
1656
- /** Input chunk size that leaves room for JSON escaping inside one frame. */
1657
- const TERMINAL_WS_INPUT_FRAME_CHUNK_CHARS = 128 * 1024;
1658
- /** WebSocket authentication envelope prefixes. */
1659
- const TERMINAL_WS_EDGE_BEARER_SUBPROTOCOL_PREFIX = "bearer.";
1660
- const TERMINAL_WS_SIDECAR_BEARER_SUBPROTOCOL_PREFIX = "tangle.bearer.";
1661
- /** Non-credential protocol selected during a successful terminal handshake. */
1662
- const TERMINAL_WS_ECHO_SUBPROTOCOL = "tangle.terminal.v1";
1663
- const terminalGeometry = {
1664
- cols: z.number().int().min(1).max(TERMINAL_WS_MAX_DIMENSION),
1665
- rows: z.number().int().min(1).max(TERMINAL_WS_MAX_DIMENSION)
1666
- };
1667
- const terminalInitMessageSchema = z.object({
1668
- type: z.literal("init"),
1669
- connectionId: z.string().optional(),
1670
- /** Required for an interactive-agent PTY; absent for generic terminals. */
1671
- incarnationId: z.string().uuid().optional(),
1672
- ...terminalGeometry,
1673
- command: z.string().min(1).optional(),
1674
- cwd: z.string().min(1).optional(),
1675
- env: z.record(z.string(), z.string()).optional(),
1676
- sessionId: z.string().min(1).optional(),
1677
- /** Canonical control claim for an interactive-agent PTY. */
1678
- control: AgentInteractiveSessionControlClaimSchema.optional()
1679
- }).superRefine((message, refinement) => {
1680
- if (message.incarnationId !== void 0 && message.control === void 0) refinement.addIssue({
1681
- code: "custom",
1682
- path: ["control"],
1683
- message: "Interactive session attach requires a control claim"
1684
- });
1685
- if (message.incarnationId === void 0 && message.control !== void 0) refinement.addIssue({
1686
- code: "custom",
1687
- path: ["control"],
1688
- message: "Generic terminal attach cannot carry an interactive control claim"
1689
- });
1690
- });
1691
- const terminalInputMessageSchema = z.object({
1692
- type: z.literal("input"),
1693
- data: z.string()
1694
- });
1695
- const terminalResizeMessageSchema = z.object({
1696
- type: z.literal("resize"),
1697
- ...terminalGeometry
1698
- });
1699
- const terminalRenewMessageSchema = z.object({ type: z.literal("renew") });
1700
- const terminalCloseMessageSchema = z.object({ type: z.literal("close") });
1701
- z.union([
1702
- terminalInitMessageSchema,
1703
- terminalInputMessageSchema,
1704
- terminalResizeMessageSchema,
1705
- terminalRenewMessageSchema,
1706
- terminalCloseMessageSchema
1707
- ]);
1708
- const terminalReadyMessageSchema = z.object({
1709
- type: z.literal("ready"),
1710
- connectionId: z.string(),
1711
- sessionId: z.string(),
1712
- restored: z.boolean(),
1713
- detachTimeoutMs: z.number().int().positive(),
1714
- /** Exact viewer count held by the runtime for this connection. */
1715
- attachCount: z.number().int().positive().optional(),
1716
- /** Server-issued output cursor window for exact interactive terminals. */
1717
- cursors: z.object({
1718
- earliest: z.number().int().nonnegative(),
1719
- latest: z.number().int().nonnegative()
1720
- }).optional()
1721
- });
1722
- /** One sequenced output frame for an exact interactive terminal. */
1723
- const terminalOutputMessageSchema = z.object({
1724
- type: z.literal("output"),
1725
- seq: z.number().int().positive(),
1726
- /** Base64-encoded UTF-8 bytes from the retained terminal event. */
1727
- data: z.string().min(1)
1728
- });
1729
- const terminalExitMessageSchema = z.object({
1730
- type: z.literal("exit"),
1731
- exitCode: z.number().optional(),
1732
- exitSignal: z.string().optional()
1733
- });
1734
- const terminalRenewedMessageSchema = z.object({
1735
- type: z.literal("renewed"),
1736
- sessionId: z.string()
1737
- });
1738
- const terminalErrorMessageSchema = z.object({
1739
- type: z.literal("error"),
1740
- code: z.string(),
1741
- message: z.string()
1742
- });
1743
- const terminalServerMessageSchema = z.union([
1744
- terminalReadyMessageSchema,
1745
- terminalOutputMessageSchema,
1746
- terminalExitMessageSchema,
1747
- terminalRenewedMessageSchema,
1748
- terminalErrorMessageSchema
1749
- ]);
1750
- //#endregion
1751
- //#region src/terminal-stream.ts
1752
- /**
1753
- * TerminalStream — typed client for the sandbox terminal WebSocket protocol.
1754
- *
1755
- * Drives a live PTY session (an interactive harness TUI or a plain shell)
1756
- * from the caller's own program: binary frames stream raw PTY output bytes,
1757
- * TEXT JSON frames carry the control protocol. The browser-safe wire contract
1758
- * is defined by the shared browser-safe runtime contract and shared with the
1759
- * sidecar:
1760
- *
1761
- * client → server (TEXT JSON):
1762
- * init {connectionId?, cols, rows, command?, cwd?, env?} — MUST be first
1763
- * input {data}
1764
- * resize {cols, rows}
1765
- *
1766
- * Interactive-agent init frames add the exact process authority:
1767
- * {incarnationId, control: {refDigest, generation, leaseId, holderId, expiresAt}}
1768
- * Subsequent input and resize frames carry only their operation fields; the
1769
- * server binds authority to the init for the socket lifetime.
1770
- * server → client (TEXT JSON):
1771
- * ready {connectionId, sessionId, restored, detachTimeoutMs,
1772
- * attachCount?, cursors?}
1773
- * output {seq, data} — exact interactive output as base64 UTF-8 bytes
1774
- * exit {exitCode?, exitSignal?}
1775
- * error {code, message}
1776
- * rec / rec.done — recording tee frames for the platform's session
1777
- * capture consumer; not part of the client surface
1778
- * server → client (BINARY): raw PTY output bytes
1779
- *
1780
- * Detach/reconnect: the server keeps the PTY alive for `detachTimeoutMs`
1781
- * (5 minutes today) after the socket closes; re-dialing with the SAME
1782
- * connectionId reattaches and replays the buffered output history, so a
1783
- * fresh client repaints the current screen.
1784
- *
1785
- * Browser-safe: uses the global `WebSocket` (browsers, Workers, Node >= 22)
1786
- * and never imports `ws` — the same environment contract as
1787
- * `session-gateway/client.ts`.
1788
- */
1789
- /** A protocol `error` control frame or a transport failure. */
1790
- var TerminalStreamError = class extends Error {
1791
- /** Protocol error code (e.g. `INIT_FAILED`) or `TRANSPORT` for socket faults. */
1792
- code;
1793
- constructor(message, code) {
1794
- super(message);
1795
- this.name = "TerminalStreamError";
1796
- this.code = code;
1797
- }
1798
- };
1799
- /**
1800
- * The sidecar caps WebSocket frames at 1 MiB
1801
- * (`TERMINAL_WS_MAX_PAYLOAD_BYTES` in the shared runtime contract) and drops
1802
- * the connection on
1803
- * larger frames. `write()` chunks input so every serialized `input` frame
1804
- * stays under that cap: 128 Ki characters per chunk × a worst-case JSON
1805
- * escape expansion of 6 bytes per character (`` etc.) ≈ 768 KiB,
1806
- * comfortably below the limit including the frame's JSON envelope.
1807
- */
1808
- const DEFAULT_COLS = 80;
1809
- const DEFAULT_ROWS = 24;
1810
- const DEFAULT_CONNECT_TIMEOUT_MS = 15e3;
1811
- /**
1812
- * base64url-encode a UTF-8 string without padding — the exact envelope the
1813
- * edge's `parseTerminalWsSubprotocolToken` decodes (its strict round-trip
1814
- * check tolerates padding, but the reference browser client emits unpadded).
1815
- */
1816
- function base64UrlEncodeUtf8(value) {
1817
- if (typeof btoa !== "function") throw new TerminalStreamError("global btoa is unavailable; cannot build the edge bearer subprotocol", "ENVIRONMENT");
1818
- const bytes = new TextEncoder().encode(value);
1819
- let binary = "";
1820
- for (const byte of bytes) binary += String.fromCharCode(byte);
1821
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1822
- }
1823
- function buildAuthSubprotocols(format, token) {
1824
- if (format === "sidecar-direct") return [`${TERMINAL_WS_SIDECAR_BEARER_SUBPROTOCOL_PREFIX}${token}`, TERMINAL_WS_ECHO_SUBPROTOCOL];
1825
- return [`${TERMINAL_WS_EDGE_BEARER_SUBPROTOCOL_PREFIX}${base64UrlEncodeUtf8(token)}`, TERMINAL_WS_ECHO_SUBPROTOCOL];
1826
- }
1827
- /**
1828
- * Resolve the dial credential: invoke a provider (fresh token per dial) or
1829
- * pass a string through. Fails loud on an empty result — a blank credential
1830
- * would dial and be rejected with an opaque 401 downstream.
1831
- */
1832
- async function resolveTerminalToken(token, signal) {
1833
- const value = typeof token === "function" ? await token(signal) : token;
1834
- if (typeof value === "object" && value !== null) {
1835
- try {
1836
- assertScopedTokenActive(value, "session-runtime");
1837
- } catch {
1838
- throw new TerminalStreamError("Terminal stream scoped token is expired or invalid", "INVALID_TOKEN");
1839
- }
1840
- return value.token;
1841
- }
1842
- if (typeof value !== "string" || !value.trim()) throw new TerminalStreamError(typeof token === "function" ? "Terminal stream token provider returned an empty token" : "Terminal stream token must not be empty", "INVALID_TOKEN");
1843
- return value;
1844
- }
1845
- function terminalAbortReason(signal) {
1846
- return signal.reason instanceof Error ? signal.reason : new DOMException("Terminal attach was aborted", "AbortError");
1847
- }
1848
- function awaitTerminalOperation(promise, signal) {
1849
- if (!signal) return promise;
1850
- signal.throwIfAborted();
1851
- return new Promise((resolve, reject) => {
1852
- let settled = false;
1853
- const cleanup = () => signal.removeEventListener("abort", onAbort);
1854
- const onAbort = () => {
1855
- if (settled) return;
1856
- settled = true;
1857
- cleanup();
1858
- reject(terminalAbortReason(signal));
1859
- };
1860
- signal.addEventListener("abort", onAbort, { once: true });
1861
- promise.then((value) => {
1862
- if (settled) return;
1863
- settled = true;
1864
- cleanup();
1865
- resolve(value);
1866
- }, (cause) => {
1867
- if (settled) return;
1868
- settled = true;
1869
- cleanup();
1870
- reject(cause);
1871
- });
1872
- });
1873
- }
1874
- function toWebSocketUrl(url) {
1875
- let parsed;
1876
- try {
1877
- parsed = new URL(url);
1878
- } catch {
1879
- throw new TerminalStreamError(`Terminal WebSocket URL is not absolute: ${url}`, "INVALID_URL");
1880
- }
1881
- if (parsed.protocol === "https:") parsed.protocol = "wss:";
1882
- else if (parsed.protocol === "http:") parsed.protocol = "ws:";
1883
- if (parsed.protocol !== "wss:" && parsed.protocol !== "ws:") throw new TerminalStreamError(`Terminal WebSocket URL must be ws(s) or http(s), got ${parsed.protocol}`, "INVALID_URL");
1884
- return parsed.toString();
1885
- }
1886
- function assertDimension(name, value) {
1887
- if (!Number.isInteger(value) || value < 1 || value > 4096) throw new TerminalStreamError(`${name} must be an integer in [1, ${TERMINAL_WS_MAX_DIMENSION}], got ${value}`, "INVALID_DIMENSION");
1888
- }
1889
- /** Decode the sidecar's base64 output frame without a Node-only dependency. */
1890
- function decodeBase64(value) {
1891
- if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) throw new TerminalStreamError("Terminal output frame is not valid base64", "INVALID_FRAME");
1892
- let binary;
1893
- try {
1894
- binary = atob(value);
1895
- } catch {
1896
- throw new TerminalStreamError("Terminal output frame is not valid base64", "INVALID_FRAME");
1897
- }
1898
- const bytes = new Uint8Array(binary.length);
1899
- for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
1900
- return bytes;
1901
- }
1902
- function normalizeInteractiveSessionIdentity(incarnationId, control) {
1903
- if (incarnationId === void 0 && control === void 0) return void 0;
1904
- if (typeof incarnationId !== "string" || incarnationId.length === 0 || incarnationId.trim() !== incarnationId) throw new TerminalStreamError("Interactive terminal attach requires an exact incarnationId", "INVALID_INTERACTIVE_IDENTITY");
1905
- if (control === void 0) throw new TerminalStreamError("Interactive terminal attach requires an exact control claim", "INVALID_INTERACTIVE_CONTROL");
1906
- const parsedControl = AgentInteractiveSessionControlClaimSchema.safeParse(control);
1907
- if (!parsedControl.success) throw new TerminalStreamError("Interactive terminal attach requires an exact control claim", "INVALID_INTERACTIVE_CONTROL");
1908
- const expiresAt = Date.parse(parsedControl.data.expiresAt);
1909
- if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) throw new TerminalStreamError("Interactive terminal control claim is expired", "INTERACTIVE_CONTROL_EXPIRED");
1910
- return {
1911
- incarnationId,
1912
- control: parsedControl.data
1913
- };
1914
- }
1915
- function interactiveInitFields(identity) {
1916
- if (identity === void 0) return {};
1917
- return {
1918
- incarnationId: identity.incarnationId,
1919
- control: identity.control
1920
- };
1921
- }
1922
- function buildTerminalInitMessage(options, identity) {
1923
- if (typeof options.connectionId !== "string" || !options.connectionId.trim()) throw new TerminalStreamError("Terminal stream connectionId must not be empty", "INVALID_CONNECTION_ID");
1924
- if (options.cols !== void 0) assertDimension("cols", options.cols);
1925
- if (options.rows !== void 0) assertDimension("rows", options.rows);
1926
- const parsed = terminalInitMessageSchema.safeParse({
1927
- type: "init",
1928
- connectionId: options.connectionId,
1929
- cols: options.cols ?? DEFAULT_COLS,
1930
- rows: options.rows ?? DEFAULT_ROWS,
1931
- ...options.command !== void 0 ? { command: options.command } : {},
1932
- ...options.cwd !== void 0 ? { cwd: options.cwd } : {},
1933
- ...options.env !== void 0 ? { env: options.env } : {},
1934
- ...interactiveInitFields(identity)
1935
- });
1936
- if (!parsed.success) throw new TerminalStreamError("Terminal stream init does not match the shared terminal protocol", "INVALID_INIT");
1937
- return parsed.data;
1938
- }
1939
- function assertInteractiveControlActive(identity) {
1940
- if (identity === void 0) return;
1941
- if (Date.parse(identity.control.expiresAt) <= Date.now()) throw new TerminalStreamError("Interactive terminal control claim is expired", "INTERACTIVE_CONTROL_EXPIRED");
1942
- }
1943
- /**
1944
- * Split input so each serialized `input` frame stays under the server's
1945
- * 1 MiB frame cap, without splitting a surrogate pair across frames (a torn
1946
- * pair would reach the PTY as two invalid UTF-8 writes).
1947
- */
1948
- function* chunkInput(text) {
1949
- if (text.length <= 131072) {
1950
- yield text;
1951
- return;
1952
- }
1953
- let index = 0;
1954
- while (index < text.length) {
1955
- let end = Math.min(index + TERMINAL_WS_INPUT_FRAME_CHUNK_CHARS, text.length);
1956
- if (end < text.length) {
1957
- const trailing = text.charCodeAt(end - 1);
1958
- if (trailing >= 55296 && trailing <= 56319) end -= 1;
1959
- }
1960
- yield text.slice(index, end);
1961
- index = end;
1962
- }
1963
- }
1964
- /**
1965
- * Client for one terminal WebSocket connection. Construct via
1966
- * {@link TerminalStream.connect}, which resolves once the server
1967
- * acknowledges the attach with `ready` (history replay then streams through
1968
- * `handlers.onData`).
1969
- */
1970
- var TerminalStream = class TerminalStream {
1971
- ws;
1972
- options;
1973
- interactiveIdentity;
1974
- initMessage;
1975
- handlers;
1976
- readyInfo = null;
1977
- closed = false;
1978
- closeWaiters = [];
1979
- textDecoder = new TextDecoder();
1980
- reconnectInFlight;
1981
- /**
1982
- * Dial the endpoint, send `init` as the first frame, and resolve once the
1983
- * server responds `ready`. Rejects on a protocol `error` frame, a socket
1984
- * close/failure before `ready`, or the connect timeout — always with the
1985
- * reason the server gave. A token PROVIDER is awaited here, before the
1986
- * socket opens, so every dial (first connect and each reconnect) carries a
1987
- * fresh credential.
1988
- */
1989
- static async connect(options) {
1990
- const interactiveIdentity = normalizeInteractiveSessionIdentity(options.incarnationId, options.control);
1991
- options.signal?.throwIfAborted();
1992
- const initMessage = buildTerminalInitMessage(options, interactiveIdentity);
1993
- const token = await awaitTerminalOperation(resolveTerminalToken(options.token, options.signal), options.signal);
1994
- options.signal?.throwIfAborted();
1995
- return new TerminalStream(options, token, interactiveIdentity, initMessage).establish(options.signal);
1996
- }
1997
- constructor(options, resolvedToken, interactiveIdentity, initMessage) {
1998
- const exactOptions = interactiveIdentity === void 0 ? options : {
1999
- ...options,
2000
- incarnationId: interactiveIdentity.incarnationId,
2001
- control: interactiveIdentity.control
2002
- };
2003
- const WebSocketCtor = globalThis.WebSocket;
2004
- if (typeof WebSocketCtor !== "function") throw new TerminalStreamError("global WebSocket is unavailable in this environment (Node >= 22 or a browser is required)", "ENVIRONMENT");
2005
- this.options = {
2006
- ...exactOptions,
2007
- signal: void 0
2008
- };
2009
- this.interactiveIdentity = interactiveIdentity;
2010
- this.initMessage = initMessage;
2011
- this.handlers = exactOptions.handlers ?? {};
2012
- this.ws = new WebSocketCtor(toWebSocketUrl(exactOptions.url), buildAuthSubprotocols(exactOptions.authFormat ?? "edge", resolvedToken));
2013
- this.ws.binaryType = "arraybuffer";
2014
- }
2015
- establish(signal) {
2016
- return new Promise((resolve, reject) => {
2017
- let settled = false;
2018
- const timeoutMs = this.options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
2019
- const timer = setTimeout(() => {
2020
- fail(new TerminalStreamError(`Terminal attach timed out after ${timeoutMs}ms waiting for ready`, "CONNECT_TIMEOUT"));
2021
- this.ws.close(1e3, "connect timeout");
2022
- }, timeoutMs);
2023
- const cleanup = () => {
2024
- clearTimeout(timer);
2025
- signal?.removeEventListener("abort", onAbort);
2026
- };
2027
- const succeed = () => {
2028
- if (settled) return;
2029
- settled = true;
2030
- cleanup();
2031
- resolve(this);
2032
- };
2033
- const fail = (error) => {
2034
- if (settled) return;
2035
- settled = true;
2036
- cleanup();
2037
- reject(error);
2038
- };
2039
- const onAbort = () => {
2040
- if (!signal) return;
2041
- fail(terminalAbortReason(signal));
2042
- this.ws.close(1e3, "connect aborted");
2043
- };
2044
- signal?.addEventListener("abort", onAbort, { once: true });
2045
- if (signal?.aborted) {
2046
- onAbort();
2047
- return;
2048
- }
2049
- this.ws.addEventListener("open", () => {
2050
- if (settled) return;
2051
- try {
2052
- assertInteractiveControlActive(this.interactiveIdentity);
2053
- } catch (error) {
2054
- fail(error instanceof TerminalStreamError ? error : new TerminalStreamError("Interactive terminal control claim is expired", "INTERACTIVE_CONTROL_EXPIRED"));
2055
- return;
2056
- }
2057
- this.ws.send(JSON.stringify(this.initMessage));
2058
- });
2059
- this.ws.addEventListener("message", (event) => {
2060
- this.handleMessage(event.data, {
2061
- succeed,
2062
- fail,
2063
- settled: () => settled
2064
- });
2065
- });
2066
- this.ws.addEventListener("error", () => {
2067
- fail(new TerminalStreamError("Terminal WebSocket transport failed before ready", "TRANSPORT"));
2068
- });
2069
- this.ws.addEventListener("close", (event) => {
2070
- this.closed = true;
2071
- fail(new TerminalStreamError(`Terminal WebSocket closed before ready (code ${event.code}${event.reason ? `: ${event.reason}` : ""})`, "CLOSED_BEFORE_READY"));
2072
- for (const waiter of this.closeWaiters) waiter();
2073
- this.closeWaiters = [];
2074
- this.handlers.onClose?.(event.code, event.reason);
2075
- });
2076
- });
2077
- }
2078
- handleMessage(raw, connectPhase) {
2079
- if (typeof raw !== "string") {
2080
- if (raw instanceof ArrayBuffer) this.handlers.onData?.(new Uint8Array(raw));
2081
- return;
2082
- }
2083
- const failProtocolFrame = () => {
2084
- const error = new TerminalStreamError("Terminal control frame does not match the shared terminal protocol", "INVALID_FRAME");
2085
- const beforeReady = !connectPhase.settled();
2086
- if (this.ws.readyState === WebSocket.OPEN) this.ws.close(1e3, "invalid terminal frame");
2087
- if (beforeReady) connectPhase.fail(error);
2088
- else this.handlers.onError?.(error);
2089
- };
2090
- let decoded;
2091
- try {
2092
- decoded = JSON.parse(raw);
2093
- } catch {
2094
- failProtocolFrame();
2095
- return;
2096
- }
2097
- if (decoded === null || typeof decoded !== "object" || Array.isArray(decoded) || typeof decoded.type !== "string") {
2098
- failProtocolFrame();
2099
- return;
2100
- }
2101
- const message = decoded;
2102
- if (message.type === "rec" || message.type === "rec.done") return;
2103
- if (message.type !== "ready" && message.type !== "output" && message.type !== "exit" && message.type !== "renewed" && message.type !== "error") return;
2104
- const parsed = terminalServerMessageSchema.safeParse(message);
2105
- if (!parsed.success) {
2106
- failProtocolFrame();
2107
- return;
2108
- }
2109
- switch (parsed.data.type) {
2110
- case "ready": {
2111
- const info = {
2112
- connectionId: parsed.data.connectionId,
2113
- sessionId: parsed.data.sessionId,
2114
- restored: parsed.data.restored,
2115
- detachTimeoutMs: parsed.data.detachTimeoutMs,
2116
- ...parsed.data.attachCount === void 0 ? {} : { attachCount: parsed.data.attachCount },
2117
- ...parsed.data.cursors === void 0 ? {} : { cursors: parsed.data.cursors }
2118
- };
2119
- this.readyInfo = info;
2120
- connectPhase.succeed();
2121
- this.handlers.onReady?.(info);
2122
- return;
2123
- }
2124
- case "output":
2125
- try {
2126
- const bytes = decodeBase64(parsed.data.data);
2127
- this.handlers.onOutput?.(parsed.data.seq, bytes);
2128
- if (this.handlers.onOutput === void 0) this.handlers.onData?.(bytes);
2129
- } catch (error) {
2130
- const protocolError = error instanceof TerminalStreamError ? error : new TerminalStreamError("Terminal output frame is not valid base64", "INVALID_FRAME");
2131
- if (!connectPhase.settled()) connectPhase.fail(protocolError);
2132
- else this.handlers.onError?.(protocolError);
2133
- if (this.ws.readyState === WebSocket.OPEN) this.ws.close(1e3, "invalid terminal output");
2134
- }
2135
- return;
2136
- case "exit":
2137
- this.handlers.onExit?.({
2138
- exitCode: parsed.data.exitCode,
2139
- exitSignal: parsed.data.exitSignal
2140
- });
2141
- return;
2142
- case "renewed": return;
2143
- case "error": {
2144
- const error = new TerminalStreamError(parsed.data.message, parsed.data.code);
2145
- if (!connectPhase.settled()) {
2146
- connectPhase.fail(error);
2147
- return;
2148
- }
2149
- this.handlers.onError?.(error);
2150
- return;
2151
- }
2152
- }
2153
- }
2154
- /** PTY connection id this stream is attached to. */
2155
- get connectionId() {
2156
- return this.options.connectionId;
2157
- }
2158
- /** The server's `ready` acknowledgement. Set once `connect()` resolves. */
2159
- get ready() {
2160
- if (!this.readyInfo) throw new TerminalStreamError("Terminal stream is not ready yet", "NOT_READY");
2161
- return this.readyInfo;
2162
- }
2163
- /** True while the socket is open. */
2164
- get isOpen() {
2165
- return !this.closed && this.ws.readyState === WebSocket.OPEN;
2166
- }
2167
- /**
2168
- * Send input keystrokes to the PTY. `Uint8Array` input is decoded as
2169
- * UTF-8 (the wire protocol carries input as JSON text). Input larger than
2170
- * the server's 1 MiB frame cap is split across multiple `input` frames in
2171
- * order on the same socket, so delivery order is preserved.
2172
- */
2173
- write(data) {
2174
- this.assertOpen("write");
2175
- assertInteractiveControlActive(this.interactiveIdentity);
2176
- const text = typeof data === "string" ? data : this.textDecoder.decode(data);
2177
- for (const chunk of chunkInput(text)) this.ws.send(JSON.stringify({
2178
- type: "input",
2179
- data: chunk
2180
- }));
2181
- }
2182
- /** Resize the PTY. */
2183
- resize(cols, rows) {
2184
- assertDimension("cols", cols);
2185
- assertDimension("rows", rows);
2186
- this.assertOpen("resize");
2187
- assertInteractiveControlActive(this.interactiveIdentity);
2188
- this.ws.send(JSON.stringify({
2189
- type: "resize",
2190
- cols,
2191
- rows
2192
- }));
2193
- }
2194
- /**
2195
- * Detach cleanly: close the socket and resolve once the close completes.
2196
- * The PTY survives server-side for `ready.detachTimeoutMs` (5 minutes
2197
- * today) — reattach within that window via {@link reconnect} (or a fresh
2198
- * `connect()` with the same connectionId) to replay history and continue.
2199
- */
2200
- close() {
2201
- if (this.closed) return Promise.resolve();
2202
- return new Promise((resolve) => {
2203
- this.closeWaiters.push(resolve);
2204
- this.ws.close(1e3, "client detach");
2205
- });
2206
- }
2207
- /**
2208
- * Re-dial the same endpoint with the same connectionId on a fresh socket
2209
- * — the server reattaches the PTY and replays its buffered history. When
2210
- * the stream was constructed with a token PROVIDER, it is re-invoked for
2211
- * the new dial (scoped terminal tokens expire within minutes, so the
2212
- * original credential may be dead by reconnect time); with a plain string
2213
- * token, pass a fresh `token` override yourself when it may have expired.
2214
- * `handlers` rebinds callbacks for the new stream.
2215
- */
2216
- reconnect(overrides) {
2217
- const existing = this.reconnectInFlight;
2218
- if (existing !== void 0) return awaitTerminalOperation(existing, overrides?.signal);
2219
- const operation = this.reconnectOnce(overrides);
2220
- let tracked;
2221
- tracked = operation.finally(() => {
2222
- if (this.reconnectInFlight === tracked) this.reconnectInFlight = void 0;
2223
- });
2224
- this.reconnectInFlight = tracked;
2225
- return awaitTerminalOperation(tracked, overrides?.signal);
2226
- }
2227
- async reconnectOnce(overrides) {
2228
- const binding = await this.options.reconnectAuthority?.acquire(overrides?.signal);
2229
- try {
2230
- return await TerminalStream.connect({
2231
- ...this.options,
2232
- ...binding === void 0 ? {} : {
2233
- incarnationId: binding.incarnationId,
2234
- control: binding.control
2235
- },
2236
- token: overrides?.token ?? this.options.token,
2237
- handlers: this.handlersForReconnect(overrides?.handlers),
2238
- cols: overrides?.cols ?? this.options.cols,
2239
- rows: overrides?.rows ?? this.options.rows,
2240
- signal: overrides?.signal
2241
- });
2242
- } catch (error) {
2243
- try {
2244
- await binding?.onFailure?.();
2245
- } catch {}
2246
- throw error;
2247
- }
2248
- }
2249
- handlersForReconnect(overrides) {
2250
- const lifecycleHandlers = this.options.handlers;
2251
- if (overrides === void 0 || lifecycleHandlers?.onClose === void 0) return overrides ?? lifecycleHandlers;
2252
- return {
2253
- ...overrides,
2254
- onClose: (code, reason) => {
2255
- lifecycleHandlers.onClose?.(code, reason);
2256
- overrides.onClose?.(code, reason);
2257
- }
2258
- };
2259
- }
2260
- assertOpen(action) {
2261
- if (!this.isOpen) throw new TerminalStreamError(`Cannot ${action}: terminal stream is not open`, "NOT_OPEN");
2262
- }
2263
- };
2264
- //#endregion
2265
- //#region src/interactive-controller.ts
2266
- /**
2267
- * Attach-capable controller for one exact interactive process.
2268
- *
2269
- * Control ownership lives in the dependency-light base controller. This layer
2270
- * adds only the terminal attach operation after that ownership is resolved.
2271
- */
2272
- var InteractiveSessionController = class extends InteractiveSessionControlController {
2273
- attachInFlight;
2274
- constructor(attachTransport, options) {
2275
- super(attachTransport, options);
2276
- this.attachTransport = attachTransport;
2277
- }
2278
- async attach(request, requestOptions) {
2279
- requestOptions?.signal?.throwIfAborted();
2280
- if (this.attachInFlight !== void 0) return await awaitWithAbort(this.attachInFlight, requestOptions?.signal);
2281
- const operation = (async () => {
2282
- const identity = await this.resolve(requestOptions);
2283
- return this.attachWithIdentity(identity, request, requestOptions);
2284
- })();
2285
- let tracked;
2286
- tracked = operation.finally(() => {
2287
- if (this.attachInFlight === tracked) this.attachInFlight = void 0;
2288
- });
2289
- this.attachInFlight = tracked;
2290
- return await tracked;
2291
- }
2292
- /**
2293
- * Open a stream for a claim returned by this controller's `resolve()`.
2294
- * The controller releases that claim when the stream cannot be opened.
2295
- */
2296
- async attachWithIdentity(identity, request, requestOptions) {
2297
- const exactRef = AgentInteractiveSessionRefSchema.parse(identity.ref);
2298
- assertInteractiveSessionRef(exactRef, this.options);
2299
- if (!agentInteractiveSessionControlClaimMatchesRef(exactRef, identity.control)) throw new Error("Interactive control claim is not bound to the session");
2300
- let activeIdentity = {
2301
- ref: exactRef,
2302
- control: identity.control
2303
- };
2304
- const releasePromises = /* @__PURE__ */ new WeakMap();
2305
- const releaseClaim = (target) => {
2306
- const existing = releasePromises.get(target);
2307
- if (existing !== void 0) return existing;
2308
- const release = this.safelyReleaseClaim(target);
2309
- releasePromises.set(target, release);
2310
- return release;
2311
- };
2312
- let reconnectInFlight;
2313
- const reconnectAuthority = { acquire: async (signal) => {
2314
- if (!releasePromises.has(activeIdentity)) throw new Error("Interactive terminal must be closed before reconnecting");
2315
- if (reconnectInFlight !== void 0) return await awaitWithAbort(reconnectInFlight, signal);
2316
- const operation = (async () => {
2317
- const next = await this.resolve({ signal });
2318
- const nextRef = AgentInteractiveSessionRefSchema.parse(next.ref);
2319
- assertInteractiveSessionRef(nextRef, this.options);
2320
- const nextIdentity = {
2321
- ref: nextRef,
2322
- control: next.control
2323
- };
2324
- activeIdentity = nextIdentity;
2325
- return {
2326
- incarnationId: nextRef.incarnationId,
2327
- control: next.control,
2328
- onFailure: () => releaseClaim(nextIdentity)
2329
- };
2330
- })();
2331
- let tracked;
2332
- tracked = operation.finally(() => {
2333
- if (reconnectInFlight === tracked) reconnectInFlight = void 0;
2334
- });
2335
- reconnectInFlight = tracked;
2336
- return await tracked;
2337
- } };
2338
- try {
2339
- requestOptions?.signal?.throwIfAborted();
2340
- const callerHandlers = request.handlers;
2341
- const exactRequest = {
2342
- ...request,
2343
- control: identity.control,
2344
- handlers: {
2345
- ...callerHandlers,
2346
- onClose: (code, reason) => {
2347
- releaseClaim(activeIdentity);
2348
- callerHandlers?.onClose?.(code, reason);
2349
- }
2350
- }
2351
- };
2352
- const stream = await this.attachTransport.attach(this.options.sessionId, exactRef, exactRequest, requestOptions, reconnectAuthority);
2353
- if (requestOptions?.signal?.aborted) {
2354
- await stream.close();
2355
- requestOptions.signal.throwIfAborted();
2356
- }
2357
- return stream;
2358
- } catch (error) {
2359
- await releaseClaim(activeIdentity);
2360
- throw error;
2361
- }
2362
- }
2363
- };
2364
- function browserTransport(options) {
2365
- return {
2366
- ...createBrowserInteractiveSessionControlTransport(options),
2367
- async attach(sessionId, ref, request, requestOptions, reconnectAuthority) {
2368
- requestOptions?.signal?.throwIfAborted();
2369
- if (options.terminalTokenProvider === void 0) throw new Error("Browser interactive terminal attach requires terminalTokenProvider");
2370
- const exactRef = AgentInteractiveSessionRefSchema.parse(ref);
2371
- const { handlers, ...wireRequest } = request;
2372
- const { control, ...terminalRequest } = AgentInteractiveSessionAttachSchema.parse(wireRequest);
2373
- const terminalOptions = {
2374
- url: browserInteractiveTerminalEndpoint(options.sessionApiUrl, sessionId),
2375
- token: options.terminalTokenProvider,
2376
- connectionId: sessionId,
2377
- ...terminalRequest,
2378
- incarnationId: exactRef.incarnationId,
2379
- control,
2380
- authFormat: "edge",
2381
- signal: requestOptions?.signal,
2382
- ...reconnectAuthority === void 0 ? {} : { reconnectAuthority },
2383
- ...handlers === void 0 ? {} : { handlers }
2384
- };
2385
- requestOptions?.signal?.throwIfAborted();
2386
- const stream = await TerminalStream.connect(terminalOptions);
2387
- if (requestOptions?.signal?.aborted) {
2388
- await stream.close();
2389
- requestOptions.signal.throwIfAborted();
2390
- }
2391
- return stream;
2392
- }
2393
- };
2394
- }
2395
- /** Concrete controller for browser deep links and terminal attachment. */
2396
- var BrowserInteractiveSessionController = class extends InteractiveSessionController {
2397
- constructor(options) {
2398
- super(browserTransport(options), options);
2399
- }
2400
- };
2401
1662
  //#endregion
2402
1663
  //#region src/interactive-terminal-session.ts
2403
1664
  const MAX_RETAINED_TERMINAL_FRAMES = 4096;
@@ -3720,6 +2981,21 @@ function isProfileNotCachedError(err) {
3720
2981
  function serializeProfileSnapshot(profile) {
3721
2982
  return JSON.stringify(profile);
3722
2983
  }
2984
+ /** Preserve the server's refusal without inferring an HTTP status from its message. */
2985
+ function fromStreamErrorEvent(data) {
2986
+ const message = typeof data?.message === "string" ? data.message : "sandbox rejected the prompt before admission";
2987
+ const status = typeof data?.status === "number" && Number.isInteger(data.status) && data.status >= 400 && data.status <= 599 ? data.status : void 0;
2988
+ const code = typeof data?.code === "string" && data.code.length > 0 ? data.code : void 0;
2989
+ if (status === void 0 && code === void 0) return new ServerError(message);
2990
+ const origin = data?.origin;
2991
+ const error = new SandboxError(message, code ?? "SERVER_ERROR", status, {
2992
+ ...origin === "sidecar" || origin === "sandbox-api" || origin === "control-plane" || origin === "runtime" || origin === "unknown" ? { origin } : {},
2993
+ ...typeof data?.endpoint === "string" ? { endpoint: data.endpoint } : {},
2994
+ ...typeof data?.retryAfterMs === "number" && Number.isFinite(data.retryAfterMs) && data.retryAfterMs >= 0 ? { retryAfterMs: data.retryAfterMs } : {}
2995
+ });
2996
+ if (typeof data?.name === "string" && data.name.length > 0) error.name = data.name;
2997
+ return error;
2998
+ }
3723
2999
  /**
3724
3000
  * Convert a thrown error into an in-band `error` SandboxEvent so a streaming
3725
3001
  * generator can surface a failure as an event followed by a terminal `done`
@@ -4687,6 +3963,7 @@ var SandboxInstance = class SandboxInstance {
4687
3963
  response: responseText,
4688
3964
  error: outcome.error,
4689
3965
  errorCode: outcome.errorCode,
3966
+ ...outcome.statusCode === void 0 ? {} : { statusCode: outcome.statusCode },
4690
3967
  toolInvocations: outcome.toolInvocations,
4691
3968
  approval: outcome.approval,
4692
3969
  interaction: outcome.interaction,
@@ -4962,7 +4239,10 @@ var SandboxInstance = class SandboxInstance {
4962
4239
  response = await this.runtimeFetch(requestEndpoint, request);
4963
4240
  for (let attempt = 1; !explicitReplay && response.status === 503 && attempt <= MAX_CREDENTIAL_REFUSAL_RETRIES; attempt += 1) {
4964
4241
  const body = await response.clone().text();
4965
- const refusal = parseErrorResponse(response.status, body, void 0, response.headers);
4242
+ const refusal = parseErrorResponse(response.status, body, {
4243
+ method: request.method,
4244
+ path: `/v1/sandboxes/${encodeURIComponent(this.id)}/runtime${requestEndpoint}`
4245
+ }, response.headers);
4966
4246
  if (!isRetryableCredentialRefusal(refusal)) break;
4967
4247
  await waitForRetryAfter(refusal.retryAfterMs ?? 1e3, streamSignal);
4968
4248
  response = await this.runtimeFetch(requestEndpoint, request);
@@ -4978,7 +4258,10 @@ var SandboxInstance = class SandboxInstance {
4978
4258
  }
4979
4259
  if (!response.ok) {
4980
4260
  const body = await response.text();
4981
- const responseError = parseErrorResponse(response.status, body, void 0, response.headers);
4261
+ const responseError = parseErrorResponse(response.status, body, {
4262
+ method: explicitReplay ? "GET" : "POST",
4263
+ path: `/v1/sandboxes/${encodeURIComponent(this.id)}/runtime${requestEndpoint}`
4264
+ }, response.headers);
4982
4265
  if (!isProfileNotCachedError(responseError)) await reconcileRuntimeRefusal(response.status);
4983
4266
  if (!explicitReplay) throw responseError;
4984
4267
  lastReplayStatus = response.status;
@@ -5640,6 +4923,7 @@ var SandboxInstance = class SandboxInstance {
5640
4923
  get fs() {
5641
4924
  return {
5642
4925
  supportsWriteMode: true,
4926
+ supportsBoundedDownload: true,
5643
4927
  read: (path) => this.read(path),
5644
4928
  readBatch: (paths, options) => this.fsReadBatch(paths, options),
5645
4929
  tree: (path, options) => this.fsTree(path, options),
@@ -5698,29 +4982,18 @@ var SandboxInstance = class SandboxInstance {
5698
4982
  return uploadChunked({ fetch: (path, init) => this.runtimeFetch(path, init) }, remotePath, data, options);
5699
4983
  }
5700
4984
  async fsDownload(remotePath, localPath, options) {
5701
- await this.ensureRunning();
5702
- const fs = await import("node:fs/promises");
5703
- const path = await import("node:path");
5704
- await fs.mkdir(path.dirname(localPath), { recursive: true });
5705
- const response = await this.runtimeFetch(runtimeFilesystemPath("/fs/download", remotePath), { method: "GET" });
5706
- if (!response.ok) {
5707
- const body = await response.text();
5708
- throw parseErrorResponse(response.status, body, void 0, response.headers);
5709
- }
5710
- const contentLength = response.headers.get("content-length");
5711
- const totalBytes = contentLength ? Number.parseInt(contentLength, 10) : 0;
5712
- if (options?.onProgress && totalBytes > 0) options.onProgress({
5713
- bytesDownloaded: 0,
5714
- totalBytes,
5715
- percentage: 0
5716
- });
5717
- const buffer = await response.arrayBuffer();
5718
- await fs.writeFile(localPath, Buffer.from(buffer));
5719
- if (options?.onProgress) options.onProgress({
5720
- bytesDownloaded: buffer.byteLength,
5721
- totalBytes: buffer.byteLength,
5722
- percentage: 100
5723
- });
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);
5724
4997
  }
5725
4998
  async fsUploadDir(localDir, remoteDir) {
5726
4999
  await this.ensureRunning();
@@ -7438,15 +6711,23 @@ var SandboxInstance = class SandboxInstance {
7438
6711
  * Resume a stopped sandbox.
7439
6712
  */
7440
6713
  async resume(options = {}) {
6714
+ await this.resumeRuntime("resume", options);
6715
+ }
6716
+ /** Rebuild a stopped sandbox from its durable snapshot under the same ID. */
6717
+ async rebuild(options = {}) {
6718
+ await this.resumeRuntime("rebuild", options);
6719
+ }
6720
+ async resumeRuntime(operation, options) {
7441
6721
  if (options.timeoutMs !== void 0 && (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0)) throw new ValidationError("resume timeoutMs must be a positive number");
7442
6722
  const timeoutSignal = options.timeoutMs ? AbortSignal.timeout(options.timeoutMs) : void 0;
7443
6723
  const signal = timeoutSignal ? options.signal ? combineAbortSignals([options.signal, timeoutSignal]) : timeoutSignal : options.signal;
7444
6724
  const response = await withLifecycleConflictRetry(async () => {
7445
- const attempt = await this.client.fetch(`/v1/sandboxes/${this.id}/resume`, {
6725
+ const requestOptions = {
7446
6726
  method: "POST",
7447
6727
  ...options.env ? { body: JSON.stringify({ env: options.env }) } : {},
7448
6728
  ...signal ? { signal } : {}
7449
- }, usableTimeoutMs(options.timeoutMs));
6729
+ };
6730
+ const attempt = operation === "resume" ? await this.client.fetch(`/v1/sandboxes/${this.id}/resume`, requestOptions, usableTimeoutMs(options.timeoutMs)) : await this.client.fetch(`/v1/sandboxes/${this.id}/rebuild`, requestOptions, usableTimeoutMs(options.timeoutMs));
7450
6731
  if (!attempt.ok) {
7451
6732
  const body = await attempt.text();
7452
6733
  throw parseErrorResponse(attempt.status, body, void 0, attempt.headers);
@@ -8067,7 +7348,7 @@ var SandboxInstance = class SandboxInstance {
8067
7348
  try {
8068
7349
  for await (const event of stream) {
8069
7350
  const data = event.data;
8070
- if (event.type === "error") dispatchError = typeof data?.message === "string" ? data.message : "sandbox rejected the prompt before admission";
7351
+ if (event.type === "error") dispatchError = fromStreamErrorEvent(data);
8071
7352
  if (event.type === "execution.started") {
8072
7353
  const id = data?.sessionId;
8073
7354
  const executionId = data?.executionId;
@@ -8081,7 +7362,7 @@ var SandboxInstance = class SandboxInstance {
8081
7362
  } finally {
8082
7363
  ctrl.abort();
8083
7364
  }
8084
- if (!admissionObserved || !resolvedSessionId || !resolvedExecutionId) throw new ServerError(dispatchError ?? "dispatchPrompt did not receive an execution admission from the sandbox");
7365
+ if (!admissionObserved || !resolvedSessionId || !resolvedExecutionId) throw dispatchError ?? new ServerError("dispatchPrompt did not receive an execution admission from the sandbox");
8085
7366
  if (!resolvedRunControlRef) throw new ServerError("Sandbox admission did not return the exact run reference", 502, {
8086
7367
  origin: "runtime",
8087
7368
  endpoint: "/agents/run/stream"
@@ -8444,7 +7725,7 @@ var SandboxInstance = class SandboxInstance {
8444
7725
  const aggregateNativeId = nativeIds.size === 1 && record.attempts.every((attempt) => attempt.nativeSessionIds.length === 1) ? [...nativeIds][0] : null;
8445
7726
  if (record.nativeSessionId !== aggregateNativeId) throw new ServerError("Raw evidence native session ID mismatch");
8446
7727
  const verifyBytes = async (entry, label) => {
8447
- if (typeof entry.contentBase64 !== "string" || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(entry.contentBase64) || !Number.isSafeInteger(entry.sizeBytes) || entry.sizeBytes < 0 || typeof entry.sha256 !== "string" || !/^sha256:[a-f0-9]{64}$/.test(entry.sha256)) throw new ServerError(`Malformed raw evidence ${label}`);
7728
+ if (typeof entry.contentBase64 !== "string" || !Number.isSafeInteger(entry.sizeBytes) || entry.sizeBytes < 0 || typeof entry.sha256 !== "string" || !/^sha256:[a-f0-9]{64}$/.test(entry.sha256)) throw new ServerError(`Malformed raw evidence ${label}`);
8448
7729
  let binary;
8449
7730
  try {
8450
7731
  binary = atob(entry.contentBase64);
@@ -8561,6 +7842,7 @@ var SandboxInstance = class SandboxInstance {
8561
7842
  response,
8562
7843
  error: outcome.error,
8563
7844
  errorCode: outcome.errorCode,
7845
+ ...outcome.statusCode === void 0 ? {} : { statusCode: outcome.statusCode },
8564
7846
  toolInvocations: outcome.toolInvocations,
8565
7847
  approval: outcome.approval,
8566
7848
  interaction: outcome.interaction,
@@ -8868,4 +8150,4 @@ function quoteForShell(value) {
8868
8150
  return `'${value.replace(/'/g, "'\\''")}'`;
8869
8151
  }
8870
8152
  //#endregion
8871
- export { rewrapResponse as A, collectAgentFinalMessageText as C, ManagedProcessClient as D, isToolBearingEvent as E, exportTraceBundle as M, otelTraceIdForTangleTrace as N, normalizeConnection as O, toOtelJson as P, applySandboxEventText as S, getSandboxEventText as T, InteractiveSessionController as _, normalizeStartupDiagnostics as a, TERMINAL_WS_ECHO_SUBPROTOCOL as b, MAX_EGRESS_DENIALS_LIMIT as c, InteractiveSessionHandle as d, agentInteractiveSessionPromptRequestDigest as f, BrowserInteractiveSessionController as g, createInteractiveTerminalSession as h, normalizeSandboxCreateReceipt as i, buildTraceExportPayload as j, normalizeSandboxShape as k, SandboxTaskSession as l, createInteractiveTerminalCapture as m, createSandboxInstanceFromResponse as n, WorkspaceImages as o, InteractiveTerminalFrameLog as p, normalizeCaptureProof as r, GPU_LEASE_PROVIDER_NAMES as s, SandboxInstance as t, SandboxSession as u, TerminalStream as v, collectAgentResponseText as w, requestInteractiveSessionToken as x, TerminalStreamError as y };
8153
+ export { normalizeSandboxShape as C, otelTraceIdForTangleTrace as D, exportTraceBundle as E, toOtelJson as O, normalizeConnection as S, buildTraceExportPayload as T, collectAgentFinalMessageText as _, normalizeStartupDiagnostics as a, isToolBearingEvent as b, MAX_EGRESS_DENIALS_LIMIT as c, InteractiveSessionHandle as d, agentInteractiveSessionPromptRequestDigest as f, applySandboxEventText as g, createInteractiveTerminalSession as h, normalizeSandboxCreateReceipt as i, SandboxTaskSession as l, createInteractiveTerminalCapture as m, createSandboxInstanceFromResponse as n, WorkspaceImages as o, InteractiveTerminalFrameLog as p, normalizeCaptureProof as r, GPU_LEASE_PROVIDER_NAMES as s, SandboxInstance as t, SandboxSession as u, collectAgentResponseText as v, rewrapResponse as w, ManagedProcessClient as x, getSandboxEventText as y };