@tangle-network/sandbox 0.11.1 → 0.12.0

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.
@@ -1,5 +1,5 @@
1
- import { l as normalizeRuntimeBackendConfig, n as normalizeSessionInfo, o as combineAbortSignals, r as uploadChunked, s as encodePromptForWire, t as SandboxRuntimeApi } from "./runtime-api-kukaWPtF.js";
2
- import { c as SandboxError, d as TimeoutError, f as ValidationError, i as NetworkError, l as ServerError, n as CapabilityError, p as parseErrorResponse, s as QuotaError, t as AuthError, u as StateError } from "./errors-Cbs78OlF.js";
1
+ import { l as normalizeRuntimeBackendConfig, n as normalizeSessionInfo, o as combineAbortSignals, r as uploadChunked, s as encodePromptForWire, t as SandboxRuntimeApi, u as normalizeRuntimeModelOverride } from "./runtime-api-XhAv6YiH.js";
2
+ import { a as NotFoundError, c as SandboxError, d as TimeoutError, f as ValidationError, i as NetworkError, l as ServerError, n as CapabilityError, p as parseErrorResponse, s as QuotaError, t as AuthError, u as StateError } from "./errors-D9fFOWX9.js";
3
3
  import { addTokenUsage, readTokenCostUsd, readTokenUsage } from "@tangle-network/agent-core";
4
4
  //#region src/lib/sse-parser.ts
5
5
  /**
@@ -345,7 +345,7 @@ function normalizeSshCredentials(raw) {
345
345
  * lives at `data.part.text` (or `.content`) when
346
346
  * `part.type === "text"`.
347
347
  */
348
- function isRecord(v) {
348
+ function isRecord$1(v) {
349
349
  return typeof v === "object" && v !== null;
350
350
  }
351
351
  /** The first candidate that is actually a string. Using `typeof` rather than a
@@ -356,11 +356,11 @@ function firstString(...candidates) {
356
356
  for (const candidate of candidates) if (typeof candidate === "string") return candidate;
357
357
  }
358
358
  function getSandboxEventText(event) {
359
- const data = isRecord(event.data) ? event.data : {};
359
+ const data = isRecord$1(event.data) ? event.data : {};
360
360
  if (event.type === "result") return firstString(data.finalText, data.response, data.output, data.content, data.text);
361
361
  if (event.type === "token") return firstString(data.value, data.delta, data.text, data.content);
362
362
  if (event.type !== "message.part.updated") return;
363
- const part = isRecord(data.part) ? data.part : void 0;
363
+ const part = isRecord$1(data.part) ? data.part : void 0;
364
364
  if (part?.type !== "text") return;
365
365
  return firstString(part.text, part.content);
366
366
  }
@@ -433,9 +433,10 @@ var InteractiveSessionHandle = class {
433
433
  }
434
434
  /**
435
435
  * Spawn the harness's interactive TUI for this session. Returns the
436
- * `streamUrl` to attach a terminal client to. Throws if the harness has no
437
- * interactive entrypoint (e.g. opencode), the binary is not installed, or a
438
- * session is already running for this id.
436
+ * `streamUrl` of the live framebuffer — open it programmatically with
437
+ * `attach()`, or hand it to a terminal frontend. Throws if the harness has
438
+ * no interactive entrypoint (e.g. cursor, which is SDK-only), the binary is
439
+ * not installed, or a session is already running for this id.
439
440
  */
440
441
  start(options) {
441
442
  return this.host._startInteractive(this.sessionId, options);
@@ -444,6 +445,32 @@ var InteractiveSessionHandle = class {
444
445
  sendPrompt(prompt) {
445
446
  return this.host._sendInteractivePrompt(this.sessionId, prompt);
446
447
  }
448
+ /**
449
+ * Attach to the live harness PTY as a {@link TerminalStream}: the same PTY
450
+ * the interactive TUI runs in (the sidecar keys it by this session id), so
451
+ * the stream sees the harness's screen and its keystrokes drive the
452
+ * harness — never a fresh shell. The host mints a short-lived scoped
453
+ * terminal token and dials the session's `streamUrl` through the secured
454
+ * sidecar proxy; resolves once the server acknowledges the attach (the
455
+ * buffered screen then replays through `handlers.onData`).
456
+ *
457
+ * Throws when no interactive session is running for this id — attach after
458
+ * `start()`, or to a session another caller started.
459
+ */
460
+ attach(options) {
461
+ if (!this.host._attachInteractive) return Promise.reject(/* @__PURE__ */ new Error("Interactive session attach is not supported by this host"));
462
+ return this.host._attachInteractive(this.sessionId, options);
463
+ }
464
+ /**
465
+ * Observe the session: running, exited (with its exit code), or `null`
466
+ * when the sidecar no longer knows the id. Poll this to detect completion —
467
+ * an interactive session has no structured result stream, so the exit
468
+ * tombstone is the completion signal.
469
+ */
470
+ status() {
471
+ if (!this.host._interactiveStatus) return Promise.reject(/* @__PURE__ */ new Error("Interactive session status is not supported by this host"));
472
+ return this.host._interactiveStatus(this.sessionId);
473
+ }
447
474
  /** Stop the interactive harness and reap its PTY. */
448
475
  stop() {
449
476
  return this.host._stopInteractive(this.sessionId);
@@ -509,9 +536,10 @@ var SandboxSession = class SandboxSession {
509
536
  return this.box._sessionEvents(this.id, opts);
510
537
  }
511
538
  /**
512
- * Await the session's terminal result. Polls status + drains events
513
- * until the session reaches a terminal state, then returns the
514
- * aggregated `PromptResult`.
539
+ * Await the session's terminal result. Reads status and drains events
540
+ * from the latest execution until the session reaches a terminal state,
541
+ * then returns the aggregated `PromptResult`. Event replay makes this safe
542
+ * to call after the execution has already finished.
515
543
  *
516
544
  * Use this to wait for a session that was started by another caller
517
545
  * (e.g. `dispatchPrompt`).
@@ -541,8 +569,10 @@ var SandboxSession = class SandboxSession {
541
569
  });
542
570
  }
543
571
  /**
544
- * Send a structured message through the session message endpoint. Model and
545
- * message identifiers are translated to the runtime's wire names by the SDK.
572
+ * Submit a structured message through the session message endpoint. The
573
+ * returned receipt confirms admission; follow progress with `events()` or
574
+ * await the terminal response with `result()`. Model and message identifiers
575
+ * are translated to the runtime's wire names by the SDK.
546
576
  */
547
577
  async sendMessage(request, options) {
548
578
  return this.box._sessionSendMessage(this.id, request, options);
@@ -652,6 +682,543 @@ var SandboxTaskSession = class extends SandboxSession {
652
682
  }
653
683
  };
654
684
  //#endregion
685
+ //#region src/terminal-stream.ts
686
+ /** A protocol `error` control frame or a transport failure. */
687
+ var TerminalStreamError = class extends Error {
688
+ /** Protocol error code (e.g. `INIT_FAILED`) or `TRANSPORT` for socket faults. */
689
+ code;
690
+ constructor(message, code) {
691
+ super(message);
692
+ this.name = "TerminalStreamError";
693
+ this.code = code;
694
+ }
695
+ };
696
+ /**
697
+ * The sidecar caps WebSocket frames at 1 MiB (`WS_MAX_PAYLOAD_BYTES` in
698
+ * `apps/sidecar/src/routes/terminal-ws.ts`) and drops the connection on
699
+ * larger frames. `write()` chunks input so every serialized `input` frame
700
+ * stays under that cap: 128 Ki characters per chunk × a worst-case JSON
701
+ * escape expansion of 6 bytes per character (`` etc.) ≈ 768 KiB,
702
+ * comfortably below the limit including the frame's JSON envelope.
703
+ */
704
+ const INPUT_FRAME_CHUNK_CHARS = 128 * 1024;
705
+ const DEFAULT_COLS = 80;
706
+ const DEFAULT_ROWS = 24;
707
+ const DEFAULT_CONNECT_TIMEOUT_MS = 15e3;
708
+ /** Geometry bounds mirrored from the sidecar's init/resize schemas. */
709
+ const MIN_DIMENSION = 1;
710
+ const MAX_DIMENSION = 4096;
711
+ const EDGE_BEARER_SUBPROTOCOL_PREFIX = "bearer.";
712
+ const SIDECAR_BEARER_SUBPROTOCOL_PREFIX = "tangle.bearer.";
713
+ /**
714
+ * Fixed non-credential marker offered on EVERY dial (both auth formats),
715
+ * giving a spec-compliant server something safe to select into the 101's
716
+ * `Sec-WebSocket-Protocol`. Two reasons it exists:
717
+ *
718
+ * 1. RFC 6455 §4.1 says a client that offered subprotocols MUST fail the
719
+ * connection when the server selects none. Node's WebSocket (undici,
720
+ * per the WHATWG spec) enforces this strictly; browsers are lenient and
721
+ * tolerate a 101 with no selected subprotocol — which is why the
722
+ * browser-only reference client got away with offering just the
723
+ * credential.
724
+ * 2. The server must never echo the token-bearing offer back (that would
725
+ * leak the live credential into a response header) — so it needs a
726
+ * non-credential protocol it CAN select.
727
+ */
728
+ const TERMINAL_WS_ECHO_SUBPROTOCOL = "tangle.terminal.v1";
729
+ /**
730
+ * base64url-encode a UTF-8 string without padding — the exact envelope the
731
+ * edge's `parseTerminalWsSubprotocolToken` decodes (its strict round-trip
732
+ * check tolerates padding, but the reference browser client emits unpadded).
733
+ */
734
+ function base64UrlEncodeUtf8(value) {
735
+ if (typeof btoa !== "function") throw new TerminalStreamError("global btoa is unavailable; cannot build the edge bearer subprotocol", "ENVIRONMENT");
736
+ const bytes = new TextEncoder().encode(value);
737
+ let binary = "";
738
+ for (const byte of bytes) binary += String.fromCharCode(byte);
739
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
740
+ }
741
+ function buildAuthSubprotocols(format, token) {
742
+ if (format === "sidecar-direct") return [`${SIDECAR_BEARER_SUBPROTOCOL_PREFIX}${token}`, TERMINAL_WS_ECHO_SUBPROTOCOL];
743
+ return [`${EDGE_BEARER_SUBPROTOCOL_PREFIX}${base64UrlEncodeUtf8(token)}`, TERMINAL_WS_ECHO_SUBPROTOCOL];
744
+ }
745
+ /**
746
+ * Resolve the dial credential: invoke a provider (fresh token per dial) or
747
+ * pass a string through. Fails loud on an empty result — a blank credential
748
+ * would dial and be rejected with an opaque 401 downstream.
749
+ */
750
+ async function resolveTerminalToken(token) {
751
+ const value = typeof token === "function" ? await token() : token;
752
+ 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");
753
+ return value;
754
+ }
755
+ function toWebSocketUrl(url) {
756
+ let parsed;
757
+ try {
758
+ parsed = new URL(url);
759
+ } catch {
760
+ throw new TerminalStreamError(`Terminal WebSocket URL is not absolute: ${url}`, "INVALID_URL");
761
+ }
762
+ if (parsed.protocol === "https:") parsed.protocol = "wss:";
763
+ else if (parsed.protocol === "http:") parsed.protocol = "ws:";
764
+ 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");
765
+ return parsed.toString();
766
+ }
767
+ function assertDimension(name, value) {
768
+ if (!Number.isInteger(value) || value < MIN_DIMENSION || value > MAX_DIMENSION) throw new TerminalStreamError(`${name} must be an integer in [${MIN_DIMENSION}, ${MAX_DIMENSION}], got ${value}`, "INVALID_DIMENSION");
769
+ }
770
+ /**
771
+ * Split input so each serialized `input` frame stays under the server's
772
+ * 1 MiB frame cap, without splitting a surrogate pair across frames (a torn
773
+ * pair would reach the PTY as two invalid UTF-8 writes).
774
+ */
775
+ function* chunkInput(text) {
776
+ if (text.length <= INPUT_FRAME_CHUNK_CHARS) {
777
+ yield text;
778
+ return;
779
+ }
780
+ let index = 0;
781
+ while (index < text.length) {
782
+ let end = Math.min(index + INPUT_FRAME_CHUNK_CHARS, text.length);
783
+ if (end < text.length) {
784
+ const trailing = text.charCodeAt(end - 1);
785
+ if (trailing >= 55296 && trailing <= 56319) end -= 1;
786
+ }
787
+ yield text.slice(index, end);
788
+ index = end;
789
+ }
790
+ }
791
+ /**
792
+ * Client for one terminal WebSocket connection. Construct via
793
+ * {@link TerminalStream.connect}, which resolves once the server
794
+ * acknowledges the attach with `ready` (history replay then streams through
795
+ * `handlers.onData`).
796
+ */
797
+ var TerminalStream = class TerminalStream {
798
+ ws;
799
+ options;
800
+ handlers;
801
+ readyInfo = null;
802
+ closed = false;
803
+ closeWaiters = [];
804
+ textDecoder = new TextDecoder();
805
+ /**
806
+ * Dial the endpoint, send `init` as the first frame, and resolve once the
807
+ * server responds `ready`. Rejects on a protocol `error` frame, a socket
808
+ * close/failure before `ready`, or the connect timeout — always with the
809
+ * reason the server gave. A token PROVIDER is awaited here, before the
810
+ * socket opens, so every dial (first connect and each reconnect) carries a
811
+ * fresh credential.
812
+ */
813
+ static async connect(options) {
814
+ return new TerminalStream(options, await resolveTerminalToken(options.token)).establish();
815
+ }
816
+ constructor(options, resolvedToken) {
817
+ if (!options.connectionId.trim()) throw new TerminalStreamError("Terminal stream connectionId must not be empty", "INVALID_CONNECTION_ID");
818
+ if (options.cols !== void 0) assertDimension("cols", options.cols);
819
+ if (options.rows !== void 0) assertDimension("rows", options.rows);
820
+ const WebSocketCtor = globalThis.WebSocket;
821
+ if (typeof WebSocketCtor !== "function") throw new TerminalStreamError("global WebSocket is unavailable in this environment (Node >= 22 or a browser is required)", "ENVIRONMENT");
822
+ this.options = options;
823
+ this.handlers = options.handlers ?? {};
824
+ this.ws = new WebSocketCtor(toWebSocketUrl(options.url), buildAuthSubprotocols(options.authFormat ?? "edge", resolvedToken));
825
+ this.ws.binaryType = "arraybuffer";
826
+ }
827
+ establish() {
828
+ return new Promise((resolve, reject) => {
829
+ let settled = false;
830
+ const timeoutMs = this.options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
831
+ const timer = setTimeout(() => {
832
+ fail(new TerminalStreamError(`Terminal attach timed out after ${timeoutMs}ms waiting for ready`, "CONNECT_TIMEOUT"));
833
+ this.ws.close(1e3, "connect timeout");
834
+ }, timeoutMs);
835
+ const succeed = () => {
836
+ if (settled) return;
837
+ settled = true;
838
+ clearTimeout(timer);
839
+ resolve(this);
840
+ };
841
+ const fail = (error) => {
842
+ if (settled) return;
843
+ settled = true;
844
+ clearTimeout(timer);
845
+ reject(error);
846
+ };
847
+ this.ws.addEventListener("open", () => {
848
+ this.ws.send(JSON.stringify({
849
+ type: "init",
850
+ connectionId: this.options.connectionId,
851
+ cols: this.options.cols ?? DEFAULT_COLS,
852
+ rows: this.options.rows ?? DEFAULT_ROWS,
853
+ ...this.options.command !== void 0 ? { command: this.options.command } : {},
854
+ ...this.options.cwd !== void 0 ? { cwd: this.options.cwd } : {},
855
+ ...this.options.env !== void 0 ? { env: this.options.env } : {}
856
+ }));
857
+ });
858
+ this.ws.addEventListener("message", (event) => {
859
+ this.handleMessage(event.data, {
860
+ succeed,
861
+ fail,
862
+ settled: () => settled
863
+ });
864
+ });
865
+ this.ws.addEventListener("error", () => {
866
+ fail(new TerminalStreamError("Terminal WebSocket transport failed before ready", "TRANSPORT"));
867
+ });
868
+ this.ws.addEventListener("close", (event) => {
869
+ this.closed = true;
870
+ fail(new TerminalStreamError(`Terminal WebSocket closed before ready (code ${event.code}${event.reason ? `: ${event.reason}` : ""})`, "CLOSED_BEFORE_READY"));
871
+ for (const waiter of this.closeWaiters) waiter();
872
+ this.closeWaiters = [];
873
+ this.handlers.onClose?.(event.code, event.reason);
874
+ });
875
+ });
876
+ }
877
+ handleMessage(data, connectPhase) {
878
+ if (typeof data !== "string") {
879
+ if (data instanceof ArrayBuffer) this.handlers.onData?.(new Uint8Array(data));
880
+ return;
881
+ }
882
+ let message;
883
+ try {
884
+ message = JSON.parse(data);
885
+ } catch {
886
+ this.handlers.onError?.(new TerminalStreamError("Terminal control frame is not valid JSON", "INVALID_FRAME"));
887
+ return;
888
+ }
889
+ switch (message.type) {
890
+ case "ready": {
891
+ const info = {
892
+ connectionId: String(message.connectionId ?? ""),
893
+ sessionId: String(message.sessionId ?? ""),
894
+ restored: message.restored === true,
895
+ detachTimeoutMs: Number(message.detachTimeoutMs ?? 0)
896
+ };
897
+ this.readyInfo = info;
898
+ connectPhase.succeed();
899
+ this.handlers.onReady?.(info);
900
+ return;
901
+ }
902
+ case "exit":
903
+ this.handlers.onExit?.({
904
+ exitCode: typeof message.exitCode === "number" ? message.exitCode : void 0,
905
+ exitSignal: typeof message.exitSignal === "string" ? message.exitSignal : void 0
906
+ });
907
+ return;
908
+ case "error": {
909
+ const error = new TerminalStreamError(typeof message.message === "string" ? message.message : "terminal error", typeof message.code === "string" ? message.code : "UNKNOWN");
910
+ if (!connectPhase.settled()) {
911
+ connectPhase.fail(error);
912
+ return;
913
+ }
914
+ this.handlers.onError?.(error);
915
+ return;
916
+ }
917
+ case "rec":
918
+ case "rec.done": return;
919
+ default: return;
920
+ }
921
+ }
922
+ /** PTY connection id this stream is attached to. */
923
+ get connectionId() {
924
+ return this.options.connectionId;
925
+ }
926
+ /** The server's `ready` acknowledgement. Set once `connect()` resolves. */
927
+ get ready() {
928
+ if (!this.readyInfo) throw new TerminalStreamError("Terminal stream is not ready yet", "NOT_READY");
929
+ return this.readyInfo;
930
+ }
931
+ /** True while the socket is open. */
932
+ get isOpen() {
933
+ return !this.closed && this.ws.readyState === WebSocket.OPEN;
934
+ }
935
+ /**
936
+ * Send input keystrokes to the PTY. `Uint8Array` input is decoded as
937
+ * UTF-8 (the wire protocol carries input as JSON text). Input larger than
938
+ * the server's 1 MiB frame cap is split across multiple `input` frames in
939
+ * order on the same socket, so delivery order is preserved.
940
+ */
941
+ write(data) {
942
+ this.assertOpen("write");
943
+ const text = typeof data === "string" ? data : this.textDecoder.decode(data);
944
+ for (const chunk of chunkInput(text)) this.ws.send(JSON.stringify({
945
+ type: "input",
946
+ data: chunk
947
+ }));
948
+ }
949
+ /** Resize the PTY. */
950
+ resize(cols, rows) {
951
+ assertDimension("cols", cols);
952
+ assertDimension("rows", rows);
953
+ this.assertOpen("resize");
954
+ this.ws.send(JSON.stringify({
955
+ type: "resize",
956
+ cols,
957
+ rows
958
+ }));
959
+ }
960
+ /**
961
+ * Detach cleanly: close the socket and resolve once the close completes.
962
+ * The PTY survives server-side for `ready.detachTimeoutMs` (5 minutes
963
+ * today) — reattach within that window via {@link reconnect} (or a fresh
964
+ * `connect()` with the same connectionId) to replay history and continue.
965
+ */
966
+ close() {
967
+ if (this.closed) return Promise.resolve();
968
+ return new Promise((resolve) => {
969
+ this.closeWaiters.push(resolve);
970
+ this.ws.close(1e3, "client detach");
971
+ });
972
+ }
973
+ /**
974
+ * Re-dial the same endpoint with the same connectionId on a fresh socket
975
+ * — the server reattaches the PTY and replays its buffered history. When
976
+ * the stream was constructed with a token PROVIDER, it is re-invoked for
977
+ * the new dial (scoped terminal tokens expire within minutes, so the
978
+ * original credential may be dead by reconnect time); with a plain string
979
+ * token, pass a fresh `token` override yourself when it may have expired.
980
+ * `handlers` rebinds callbacks for the new stream.
981
+ */
982
+ reconnect(overrides) {
983
+ return TerminalStream.connect({
984
+ ...this.options,
985
+ token: overrides?.token ?? this.options.token,
986
+ handlers: overrides?.handlers ?? this.options.handlers,
987
+ cols: overrides?.cols ?? this.options.cols,
988
+ rows: overrides?.rows ?? this.options.rows
989
+ });
990
+ }
991
+ assertOpen(action) {
992
+ if (!this.isOpen) throw new TerminalStreamError(`Cannot ${action}: terminal stream is not open`, "NOT_OPEN");
993
+ }
994
+ };
995
+ //#endregion
996
+ //#region src/workspace-images.ts
997
+ const DEFAULT_WORKSPACE_IMAGE_CLIENT_TIMEOUT_MS = 99e4;
998
+ const WORKSPACE_IMAGE_REQUEST_ATTEMPTS = 2;
999
+ const MAX_WORKSPACE_IMAGE_RESPONSE_BYTES = 64 * 1024;
1000
+ const MAX_TIMER_DELAY_MS = 2147483647;
1001
+ const IDEMPOTENCY_KEY_PATTERN = /^[A-Za-z0-9_-]{16,128}$/;
1002
+ const MAX_WORKSPACE_IMAGE_EXPOSED_PORTS = 64;
1003
+ function createIdempotencyKey() {
1004
+ const crypto = globalThis.crypto;
1005
+ if (crypto?.randomUUID) return crypto.randomUUID();
1006
+ if (crypto?.getRandomValues) {
1007
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
1008
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1009
+ }
1010
+ throw new Error("workspace image publication requires global crypto");
1011
+ }
1012
+ function throwIfAborted(signal) {
1013
+ if (!signal?.aborted) return;
1014
+ throw signal.reason instanceof Error ? signal.reason : /* @__PURE__ */ new Error("workspace image publication was aborted");
1015
+ }
1016
+ function awaitWithSignal(promise, signal) {
1017
+ if (signal.aborted) return Promise.reject(signal.reason);
1018
+ return new Promise((resolve, reject) => {
1019
+ const onAbort = () => reject(signal.reason);
1020
+ signal.addEventListener("abort", onAbort, { once: true });
1021
+ promise.then((value) => {
1022
+ signal.removeEventListener("abort", onAbort);
1023
+ resolve(value);
1024
+ }, (error) => {
1025
+ signal.removeEventListener("abort", onAbort);
1026
+ reject(error);
1027
+ });
1028
+ });
1029
+ }
1030
+ async function readBoundedResponseText(response, signal) {
1031
+ const declaredBytes = Number(response.headers.get("content-length"));
1032
+ if (Number.isFinite(declaredBytes) && declaredBytes > MAX_WORKSPACE_IMAGE_RESPONSE_BYTES) {
1033
+ response.body?.cancel();
1034
+ throw new ServerError("Sandbox API returned an oversized workspace image response", 502);
1035
+ }
1036
+ if (!response.body) return "";
1037
+ const reader = response.body.getReader();
1038
+ const chunks = [];
1039
+ let totalBytes = 0;
1040
+ let rejectOnAbort;
1041
+ const aborted = new Promise((_resolve, reject) => {
1042
+ rejectOnAbort = reject;
1043
+ });
1044
+ const onAbort = () => rejectOnAbort?.(signal.reason);
1045
+ signal.addEventListener("abort", onAbort, { once: true });
1046
+ try {
1047
+ if (signal.aborted) throw signal.reason;
1048
+ while (true) {
1049
+ const { done, value } = await Promise.race([reader.read(), aborted]);
1050
+ if (done) break;
1051
+ totalBytes += value.byteLength;
1052
+ if (totalBytes > MAX_WORKSPACE_IMAGE_RESPONSE_BYTES) throw new ServerError("Sandbox API returned an oversized workspace image response", 502);
1053
+ chunks.push(value);
1054
+ }
1055
+ } catch (error) {
1056
+ reader.cancel(error).catch(() => void 0);
1057
+ throw error;
1058
+ } finally {
1059
+ signal.removeEventListener("abort", onAbort);
1060
+ reader.releaseLock();
1061
+ }
1062
+ const body = new Uint8Array(totalBytes);
1063
+ let offset = 0;
1064
+ for (const chunk of chunks) {
1065
+ body.set(chunk, offset);
1066
+ offset += chunk.byteLength;
1067
+ }
1068
+ return new TextDecoder().decode(body);
1069
+ }
1070
+ const WORKSPACE_IMAGE_RESULT_KEYS = [
1071
+ "image",
1072
+ "taggedImage",
1073
+ "digest",
1074
+ "imageId",
1075
+ "sizeBytes",
1076
+ "contextBytes",
1077
+ "contextEntries",
1078
+ "buildDurationMs",
1079
+ "pushDurationMs",
1080
+ "exposedPorts"
1081
+ ];
1082
+ const SHA256_DIGEST_PATTERN = /^sha256:[a-f0-9]{64}$/;
1083
+ const IMAGE_TAG_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$/;
1084
+ function isRecord(value) {
1085
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1086
+ }
1087
+ function isNonNegativeSafeInteger(value) {
1088
+ return Number.isSafeInteger(value) && Number(value) >= 0;
1089
+ }
1090
+ function parseExposedPorts(value) {
1091
+ if (!Array.isArray(value) || value.length > MAX_WORKSPACE_IMAGE_EXPOSED_PORTS) return;
1092
+ const ports = [];
1093
+ const seen = /* @__PURE__ */ new Set();
1094
+ for (const entry of value) {
1095
+ if (!isRecord(entry) || Object.keys(entry).length !== 2) return void 0;
1096
+ const { port, protocol } = entry;
1097
+ if (typeof port !== "number" || !Number.isSafeInteger(port) || port < 1 || port > 65535 || protocol !== "tcp" && protocol !== "udp" && protocol !== "sctp") return;
1098
+ const identity = `${port}/${protocol}`;
1099
+ if (seen.has(identity)) return void 0;
1100
+ seen.add(identity);
1101
+ ports.push({
1102
+ port,
1103
+ protocol
1104
+ });
1105
+ }
1106
+ return ports;
1107
+ }
1108
+ function parseWorkspaceImagePublishResult(value, repository) {
1109
+ if (!isRecord(value)) return void 0;
1110
+ if (Object.keys(value).length !== WORKSPACE_IMAGE_RESULT_KEYS.length || !WORKSPACE_IMAGE_RESULT_KEYS.every((key) => Object.hasOwn(value, key))) return;
1111
+ const { image, taggedImage, digest, imageId, sizeBytes, contextBytes, contextEntries, buildDurationMs, pushDurationMs, exposedPorts } = value;
1112
+ const parsedExposedPorts = parseExposedPorts(exposedPorts);
1113
+ if (typeof image !== "string" || typeof taggedImage !== "string" || typeof digest !== "string" || typeof imageId !== "string" || !SHA256_DIGEST_PATTERN.test(digest) || !SHA256_DIGEST_PATTERN.test(imageId) || image !== `${repository}@${digest}` || !taggedImage.startsWith(`${repository}:`) || !IMAGE_TAG_PATTERN.test(taggedImage.slice(repository.length + 1)) || !isNonNegativeSafeInteger(sizeBytes) || !isNonNegativeSafeInteger(contextBytes) || !isNonNegativeSafeInteger(contextEntries) || !isNonNegativeSafeInteger(buildDurationMs) || !isNonNegativeSafeInteger(pushDurationMs) || !parsedExposedPorts) return;
1114
+ return {
1115
+ image,
1116
+ taggedImage,
1117
+ digest,
1118
+ imageId,
1119
+ sizeBytes,
1120
+ contextBytes,
1121
+ contextEntries,
1122
+ buildDurationMs,
1123
+ pushDurationMs,
1124
+ exposedPorts: parsedExposedPorts
1125
+ };
1126
+ }
1127
+ /** Builds and publishes the current sandbox workspace from trusted hosts. */
1128
+ var WorkspaceImages = class {
1129
+ constructor(client, sandboxId, ensureRunning, filesystemIncarnationId) {
1130
+ this.client = client;
1131
+ this.sandboxId = sandboxId;
1132
+ this.ensureRunning = ensureRunning;
1133
+ this.filesystemIncarnationId = filesystemIncarnationId;
1134
+ }
1135
+ async publish(input, options = {}) {
1136
+ if (options.timeoutMs !== void 0 && (!Number.isSafeInteger(options.timeoutMs) || options.timeoutMs <= 0 || options.timeoutMs > MAX_TIMER_DELAY_MS)) throw new TypeError(`workspace image timeoutMs must be a positive safe integer no greater than ${MAX_TIMER_DELAY_MS}`);
1137
+ if (options.idempotencyKey !== void 0 && !IDEMPOTENCY_KEY_PATTERN.test(options.idempotencyKey)) throw new TypeError("workspace image idempotencyKey must be 16-128 letters, numbers, underscores, or dashes");
1138
+ const path = `/v1/sandboxes/${encodeURIComponent(this.sandboxId)}/images`;
1139
+ const timeoutMs = options.timeoutMs ?? DEFAULT_WORKSPACE_IMAGE_CLIENT_TIMEOUT_MS;
1140
+ const deadline = Date.now() + timeoutMs;
1141
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
1142
+ const signal = options.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal;
1143
+ throwIfAborted(options.signal);
1144
+ try {
1145
+ await awaitWithSignal(this.ensureRunning(), signal);
1146
+ } catch (error) {
1147
+ throwIfAborted(options.signal);
1148
+ if (timeoutSignal.aborted || Date.now() >= deadline) throw new TimeoutError(timeoutMs, `Workspace image publication timed out after ${timeoutMs}ms`, {
1149
+ origin: "sandbox-api",
1150
+ endpoint: path
1151
+ });
1152
+ throw error;
1153
+ }
1154
+ throwIfAborted(options.signal);
1155
+ const filesystemIncarnationId = this.filesystemIncarnationId();
1156
+ if (!filesystemIncarnationId) throw new StateError("Sandbox filesystem incarnation is not ready", "running", "running with a ready filesystem incarnation", void 0, "FILESYSTEM_INCARNATION_NOT_READY");
1157
+ const idempotencyKey = options.idempotencyKey ?? createIdempotencyKey();
1158
+ const body = JSON.stringify({
1159
+ ...input,
1160
+ filesystemIncarnationId
1161
+ });
1162
+ for (let attempt = 1; attempt <= WORKSPACE_IMAGE_REQUEST_ATTEMPTS; attempt++) {
1163
+ const remainingMs = deadline - Date.now();
1164
+ if (remainingMs <= 0) throw new TimeoutError(timeoutMs, `Workspace image publication timed out after ${timeoutMs}ms`, {
1165
+ origin: "sandbox-api",
1166
+ endpoint: path
1167
+ });
1168
+ let response;
1169
+ let responseText;
1170
+ try {
1171
+ response = await this.client.fetch(path, {
1172
+ method: "POST",
1173
+ headers: {
1174
+ "Content-Type": "application/json",
1175
+ "Idempotency-Key": idempotencyKey
1176
+ },
1177
+ body,
1178
+ signal
1179
+ }, { timeoutMs: remainingMs });
1180
+ responseText = await readBoundedResponseText(response, signal);
1181
+ } catch (error) {
1182
+ throwIfAborted(options.signal);
1183
+ if (timeoutSignal.aborted || Date.now() >= deadline) throw new TimeoutError(timeoutMs, `Workspace image publication timed out after ${timeoutMs}ms`, {
1184
+ origin: "sandbox-api",
1185
+ endpoint: path
1186
+ });
1187
+ if (error instanceof ServerError) throw error;
1188
+ if (attempt < WORKSPACE_IMAGE_REQUEST_ATTEMPTS && Date.now() < deadline) continue;
1189
+ throw new NetworkError("Failed to read the workspace image publication response", error instanceof Error ? error : new Error(String(error)), {
1190
+ origin: "sandbox-api",
1191
+ endpoint: path
1192
+ });
1193
+ }
1194
+ if (!response.ok) {
1195
+ const error = parseErrorResponse(response.status, responseText, {
1196
+ method: "POST",
1197
+ path
1198
+ }, response.headers);
1199
+ if (error.code === "IMAGE_PUBLISH_OUTCOME_UNKNOWN" && attempt < WORKSPACE_IMAGE_REQUEST_ATTEMPTS && Date.now() < deadline) continue;
1200
+ throw error;
1201
+ }
1202
+ const parsed = parseWorkspaceImagePublishResult((() => {
1203
+ try {
1204
+ return JSON.parse(responseText);
1205
+ } catch {
1206
+ return;
1207
+ }
1208
+ })(), input.repository);
1209
+ if (!parsed) throw new ServerError("Sandbox API returned an invalid workspace image result", 502, {
1210
+ origin: "sandbox-api",
1211
+ endpoint: path
1212
+ });
1213
+ return parsed;
1214
+ }
1215
+ throw new ServerError("Sandbox API did not return a workspace image result", 502, {
1216
+ origin: "sandbox-api",
1217
+ endpoint: path
1218
+ });
1219
+ }
1220
+ };
1221
+ //#endregion
655
1222
  //#region src/sandbox.ts
656
1223
  /**
657
1224
  * Sandbox Instance
@@ -735,6 +1302,10 @@ const SNAPSHOT_RESTORE_POLL_INTERVAL_MS = 1e3;
735
1302
  const SNAPSHOT_RESTORE_TIMEOUT_MS = 600 * 1e3;
736
1303
  const SNAPSHOT_VISIBILITY_POLL_INTERVAL_MS = 1e3;
737
1304
  const SNAPSHOT_VISIBILITY_TIMEOUT_MS = 120 * 1e3;
1305
+ const EXEC_DEFAULT_TIMEOUT_MS = 3e4;
1306
+ const EXEC_MIN_TIMEOUT_MS = 100;
1307
+ const EXEC_MAX_TIMEOUT_MS = 6e5;
1308
+ const EXEC_TRANSPORT_MARGIN_MS = 15e3;
738
1309
  const SNAPSHOT_CREATE_REQUEST_TIMEOUT_MS = 600 * 1e3;
739
1310
  function toSnapshotResult(data) {
740
1311
  return {
@@ -902,6 +1473,18 @@ function questionsFromAnswerSpec(request) {
902
1473
  multiSelect: field.multi === true
903
1474
  } : { question: field.label });
904
1475
  }
1476
+ function isProfileNotCachedError(err) {
1477
+ return err instanceof SandboxError && err.code === "PROFILE_NOT_CACHED";
1478
+ }
1479
+ /**
1480
+ * Stable-enough serialization for detecting whether a profile's content has
1481
+ * changed since it was primed. Not a canonical hash — key reordering yields a
1482
+ * different string, which only forgoes the optimization (the turn sends
1483
+ * inline), never breaks correctness. Used purely for the local content check.
1484
+ */
1485
+ function serializeProfileSnapshot(profile) {
1486
+ return JSON.stringify(profile);
1487
+ }
905
1488
  /**
906
1489
  * Convert a thrown error into an in-band `error` SandboxEvent so a streaming
907
1490
  * generator can surface a failure as an event followed by a terminal `done`
@@ -951,6 +1534,29 @@ function parseTextFileReadResponse(body) {
951
1534
  return payload.data.content;
952
1535
  }
953
1536
  const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1537
+ const SANDBOX_STATUS_FRESHNESS_MS = 1e3;
1538
+ const sandboxStatusObservedAt = /* @__PURE__ */ new WeakMap();
1539
+ const directRuntimeInstances = /* @__PURE__ */ new WeakSet();
1540
+ function readFilesystemIncarnationTuple(value) {
1541
+ const rawId = value.filesystemIncarnationId;
1542
+ const rawProvenance = value.filesystemIncarnationProvenance;
1543
+ const rawReadiness = value.filesystemIncarnationReadiness;
1544
+ const id = typeof rawId === "string" && rawId.length > 0 ? rawId : void 0;
1545
+ const provenance = rawProvenance === "fresh" || rawProvenance === "restored" || rawProvenance === "unknown" ? rawProvenance : void 0;
1546
+ const readiness = rawReadiness === "transitioning" || rawReadiness === "ready" ? rawReadiness : void 0;
1547
+ return {
1548
+ hasAny: rawId !== void 0 || rawProvenance !== void 0 || rawReadiness !== void 0,
1549
+ complete: id !== void 0 && provenance !== void 0 && readiness !== void 0,
1550
+ id,
1551
+ provenance,
1552
+ readiness
1553
+ };
1554
+ }
1555
+ function createSandboxInstanceFromResponse(client, info, defaultRuntimeBackend) {
1556
+ const instance = new SandboxInstance(client, info, defaultRuntimeBackend);
1557
+ sandboxStatusObservedAt.set(instance, Date.now());
1558
+ return instance;
1559
+ }
954
1560
  /** Transient file-write failures worth retrying: rate-limit (quota), 5xx,
955
1561
  * transport (network), and request timeouts. A non-transient error (bad path,
956
1562
  * auth, validation) fails loud immediately. */
@@ -963,16 +1569,40 @@ function isTransientWriteError(err) {
963
1569
  var SandboxInstance = class SandboxInstance {
964
1570
  client;
965
1571
  info;
1572
+ /** Once observed, incarnation metadata is authoritative for this handle. */
1573
+ filesystemIncarnationContract;
1574
+ refreshInFlight;
966
1575
  defaultRuntimeBackend;
967
1576
  runtime;
1577
+ workspaceImages;
1578
+ /**
1579
+ * A profile the runtime has cached (create-time priming), letting turns
1580
+ * send `backend.profileSha256` instead of re-shipping the profile's static
1581
+ * corpus. Set only when priming succeeded; when unset every turn sends the
1582
+ * full profile (unchanged legacy behavior). `snapshot` is the serialized
1583
+ * content at prime time — a turn substitutes the reference only when the
1584
+ * outgoing profile serializes identically, so a caller that mutates the
1585
+ * profile in place (or passes an equivalent object) is compared by CONTENT,
1586
+ * never by object identity, and a changed profile is sent inline.
1587
+ */
1588
+ deferredProfileReference;
968
1589
  constructor(client, info, defaultRuntimeBackend) {
969
1590
  this.client = client;
970
- this.info = info;
1591
+ const incarnation = readFilesystemIncarnationTuple(info);
1592
+ this.filesystemIncarnationContract = incarnation.hasAny;
1593
+ this.info = incarnation.hasAny ? {
1594
+ ...info,
1595
+ filesystemIncarnationId: incarnation.complete ? incarnation.id : void 0,
1596
+ filesystemIncarnationProvenance: incarnation.complete ? incarnation.provenance : void 0,
1597
+ filesystemIncarnationReadiness: incarnation.complete ? incarnation.readiness : void 0,
1598
+ connection: incarnation.complete && incarnation.readiness === "ready" ? info.connection : void 0
1599
+ } : info;
971
1600
  this.defaultRuntimeBackend = defaultRuntimeBackend;
972
1601
  this.runtime = new SandboxRuntimeApi({
973
1602
  ensureRunning: () => this.ensureRunning(),
974
1603
  fetch: (path, init) => this.runtimeFetch(path, init)
975
1604
  });
1605
+ this.workspaceImages = new WorkspaceImages(this.client, this.info.id, () => this.ensureRunning(), () => this.info.filesystemIncarnationId);
976
1606
  }
977
1607
  /** Unique sandbox identifier */
978
1608
  get id() {
@@ -982,6 +1612,18 @@ var SandboxInstance = class SandboxInstance {
982
1612
  get name() {
983
1613
  return this.info.name;
984
1614
  }
1615
+ /** Identity of the currently published filesystem contents. */
1616
+ get filesystemIncarnationId() {
1617
+ return this.info.filesystemIncarnationId;
1618
+ }
1619
+ /** How the current filesystem contents were acquired. */
1620
+ get filesystemIncarnationProvenance() {
1621
+ return this.info.filesystemIncarnationProvenance;
1622
+ }
1623
+ /** Whether the current incarnation is safe to use as authoritative state. */
1624
+ get filesystemIncarnationReadiness() {
1625
+ return this.info.filesystemIncarnationReadiness;
1626
+ }
985
1627
  /** Current status */
986
1628
  get status() {
987
1629
  return this.info.status;
@@ -1022,6 +1664,10 @@ var SandboxInstance = class SandboxInstance {
1022
1664
  get url() {
1023
1665
  return this.info.connection?.webTerminalUrl;
1024
1666
  }
1667
+ /** Build and publish this sandbox's workspace without exposing registry credentials to it. */
1668
+ get images() {
1669
+ return this.workspaceImages;
1670
+ }
1025
1671
  /**
1026
1672
  * The 12-phase startup breakdown (storage_provision, host_select, edge_bind,
1027
1673
  * edge_ready, egress_proxy, docker_pull/create/start, sidecar_boot,
@@ -1051,6 +1697,9 @@ var SandboxInstance = class SandboxInstance {
1051
1697
  return {
1052
1698
  id: this.id,
1053
1699
  name: this.name,
1700
+ filesystemIncarnationId: this.filesystemIncarnationId,
1701
+ filesystemIncarnationProvenance: this.filesystemIncarnationProvenance,
1702
+ filesystemIncarnationReadiness: this.filesystemIncarnationReadiness,
1054
1703
  status: this.status,
1055
1704
  connection: redactConnectionSecrets(this.connection),
1056
1705
  metadata: this.metadata,
@@ -1095,6 +1744,8 @@ var SandboxInstance = class SandboxInstance {
1095
1744
  const client = this.client;
1096
1745
  if (next && typeof client._emitTokenRefresh === "function") client._emitTokenRefresh(this.id, next);
1097
1746
  }), { ...this.info }, this.defaultRuntimeBackend);
1747
+ if (this.deferredProfileReference !== void 0) directInstance.deferredProfileReference = this.deferredProfileReference;
1748
+ directRuntimeInstances.add(directInstance);
1098
1749
  return directInstance;
1099
1750
  }
1100
1751
  /**
@@ -1134,6 +1785,19 @@ var SandboxInstance = class SandboxInstance {
1134
1785
  * Refresh sandbox information from the server.
1135
1786
  */
1136
1787
  async refresh() {
1788
+ if (this.refreshInFlight) {
1789
+ await this.refreshInFlight;
1790
+ return;
1791
+ }
1792
+ const refresh = this.refreshInfo();
1793
+ this.refreshInFlight = refresh;
1794
+ try {
1795
+ await refresh;
1796
+ } finally {
1797
+ if (this.refreshInFlight === refresh) this.refreshInFlight = void 0;
1798
+ }
1799
+ }
1800
+ async refreshInfo() {
1137
1801
  const response = await this.client.fetch(`/v1/sandboxes/${this.id}`);
1138
1802
  if (!response.ok) {
1139
1803
  const body = await response.text();
@@ -1141,6 +1805,7 @@ var SandboxInstance = class SandboxInstance {
1141
1805
  }
1142
1806
  const data = await response.json();
1143
1807
  this.info = this.parseInfo(data);
1808
+ sandboxStatusObservedAt.set(this, Date.now());
1144
1809
  }
1145
1810
  /**
1146
1811
  * Fetch fresh TEE attestation evidence for this sandbox.
@@ -1270,28 +1935,31 @@ var SandboxInstance = class SandboxInstance {
1270
1935
  */
1271
1936
  async exec(command, options) {
1272
1937
  await this.ensureRunning();
1938
+ const timeoutMs = options?.timeoutMs ?? EXEC_DEFAULT_TIMEOUT_MS;
1939
+ if (!Number.isInteger(timeoutMs) || timeoutMs < EXEC_MIN_TIMEOUT_MS || timeoutMs > EXEC_MAX_TIMEOUT_MS) throw new ValidationError(`exec timeoutMs must be an integer between ${EXEC_MIN_TIMEOUT_MS} and ${EXEC_MAX_TIMEOUT_MS}`);
1273
1940
  const headers = {};
1274
1941
  if (options?.sessionId) headers["X-Session-Id"] = options.sessionId;
1275
- const response = await this.runtimeFetch("/terminals/commands", {
1942
+ const response = await this.runtimeFetch("/process/spawn", {
1276
1943
  method: "POST",
1277
1944
  headers,
1278
1945
  body: JSON.stringify({
1279
1946
  command,
1280
1947
  cwd: options?.cwd,
1281
1948
  env: options?.env,
1282
- timeout: options?.timeoutMs
1949
+ timeoutMs,
1950
+ blocking: true
1283
1951
  })
1284
- });
1952
+ }, { timeoutMs: timeoutMs + EXEC_TRANSPORT_MARGIN_MS });
1285
1953
  if (!response.ok) {
1286
1954
  const body = await response.text();
1287
1955
  throw parseErrorResponse(response.status, body, void 0, response.headers);
1288
1956
  }
1289
- const data = await response.json();
1290
- const result = data.result ?? data;
1957
+ const result = (await response.json()).data;
1958
+ if (!result || typeof result.exitCode !== "number" || typeof result.stdout !== "string" || typeof result.stderr !== "string") throw new ServerError("Sandbox process response was malformed", 502);
1291
1959
  return {
1292
- exitCode: result.exitCode ?? 0,
1293
- stdout: result.stdout ?? "",
1294
- stderr: result.stderr ?? ""
1960
+ exitCode: result.exitCode,
1961
+ stdout: result.stdout,
1962
+ stderr: result.stderr
1295
1963
  };
1296
1964
  }
1297
1965
  /**
@@ -1538,18 +2206,96 @@ var SandboxInstance = class SandboxInstance {
1538
2206
  * received. Reconnection is transparent — replayed events that were
1539
2207
  * already yielded (based on event ID tracking) are deduplicated.
1540
2208
  */
2209
+ /**
2210
+ * Record that the runtime holds `profile` under `sha256` (from create-time
2211
+ * priming), so later turns can reference it by hash. Captures a content
2212
+ * snapshot so a later mutation of the same object is detected and sent
2213
+ * inline. Internal — called by the client after a successful prime; never
2214
+ * part of the public surface.
2215
+ */
2216
+ _setDeferredProfileReference(profile, sha256) {
2217
+ this.deferredProfileReference = {
2218
+ snapshot: serializeProfileSnapshot(profile),
2219
+ sha256
2220
+ };
2221
+ }
2222
+ /**
2223
+ * Store `profile` on the runtime and record its hash so subsequent turns
2224
+ * send `backend.profileSha256` instead of the full corpus. Internal; called
2225
+ * by the client after the sandbox is running. Throws on transport/HTTP
2226
+ * failure — the caller decides whether a prime failure is fatal (it is not:
2227
+ * turns fall back to sending the full profile inline).
2228
+ */
2229
+ async _primeDeferredProfile(profile) {
2230
+ const response = await this.runtimeFetch("/agents/profiles", {
2231
+ method: "POST",
2232
+ headers: { "content-type": "application/json" },
2233
+ body: JSON.stringify({ profile })
2234
+ });
2235
+ if (!response.ok) {
2236
+ const body = await response.text();
2237
+ throw parseErrorResponse(response.status, body, {
2238
+ method: "POST",
2239
+ path: "/agents/profiles"
2240
+ });
2241
+ }
2242
+ const data = await response.json();
2243
+ if (typeof data.sha256 !== "string" || data.sha256.length === 0) throw new Error("Profile priming returned no sha256; runtime response malformed");
2244
+ this._setDeferredProfileReference(profile, data.sha256);
2245
+ return data.sha256;
2246
+ }
2247
+ /**
2248
+ * Build the run request's `backend` body. When the outgoing profile's CONTENT
2249
+ * matches the one the runtime already holds (and we are not resending after a
2250
+ * cache miss), swap the inline `profile` for its `profileSha256` so a large
2251
+ * static corpus does not ride every turn. The match is by serialized content,
2252
+ * not object identity, so a mutated-in-place profile — or an equivalent
2253
+ * object passed as a per-turn override — is compared correctly: unchanged
2254
+ * content references by hash, changed content sends inline (the legacy shape).
2255
+ */
2256
+ buildRunBackendBody(overrideBackend, forceFullProfile) {
2257
+ const normalized = normalizeRuntimeBackendConfig(overrideBackend ?? this.defaultRuntimeBackend);
2258
+ if (!normalized) return normalized;
2259
+ const deferred = this.deferredProfileReference;
2260
+ if (!forceFullProfile && deferred !== void 0 && normalized.profile !== void 0 && serializeProfileSnapshot(normalized.profile) === deferred.snapshot) {
2261
+ const { profile: _omitted, ...rest } = normalized;
2262
+ return {
2263
+ ...rest,
2264
+ profileSha256: deferred.sha256
2265
+ };
2266
+ }
2267
+ return normalized;
2268
+ }
1541
2269
  async *streamPrompt(message, options) {
1542
2270
  const isCallerAbort = () => options?.signal?.aborted === true;
1543
2271
  let receivedTerminal = false;
1544
2272
  let sessionId = options?.sessionId;
1545
2273
  let executionId = options?.executionId;
2274
+ let profileResendAttempted = false;
1546
2275
  try {
1547
- for await (const event of this.streamPromptInner(message, options)) {
1548
- if (event.type === "result" || event.type === "done") receivedTerminal = true;
1549
- if (event.type === "execution.started" && event.data.executionId) executionId = event.data.executionId;
1550
- const sid = event.data.sessionId;
1551
- if (typeof sid === "string" && sid.length > 0) sessionId = sid;
1552
- yield event;
2276
+ for (;;) {
2277
+ let yieldedThisAttempt = false;
2278
+ try {
2279
+ for await (const event of this.streamPromptInner(message, options, { forceFullProfile: profileResendAttempted })) {
2280
+ yieldedThisAttempt = true;
2281
+ if (event.type === "result" || event.type === "done") receivedTerminal = true;
2282
+ if (event.type === "execution.started" && event.data.executionId) executionId = event.data.executionId;
2283
+ const sid = event.data.sessionId;
2284
+ if (typeof sid === "string" && sid.length > 0) sessionId = sid;
2285
+ yield event;
2286
+ }
2287
+ break;
2288
+ } catch (err) {
2289
+ if (!yieldedThisAttempt && !profileResendAttempted && isProfileNotCachedError(err)) {
2290
+ this.logStreamCheckpoint("profile_reference_miss_resend", {
2291
+ sessionId,
2292
+ executionId
2293
+ });
2294
+ profileResendAttempted = true;
2295
+ continue;
2296
+ }
2297
+ throw err;
2298
+ }
1553
2299
  }
1554
2300
  } catch (err) {
1555
2301
  if (isCallerAbort()) return;
@@ -1582,7 +2328,7 @@ var SandboxInstance = class SandboxInstance {
1582
2328
  * the public `streamPrompt` wrapper converts those throws into a terminal
1583
2329
  * `error` + `done` so callers never see a thrown generator.
1584
2330
  */
1585
- async *streamPromptInner(message, options) {
2331
+ async *streamPromptInner(message, options, internal) {
1586
2332
  if (options?.lastEventId && !options.executionId) throw new ValidationError("lastEventId requires executionId so the SDK can replay the correct execution", { executionId: "Required when lastEventId is set" });
1587
2333
  await this.ensureRunning();
1588
2334
  const timeoutMs = typeof options?.timeoutMs === "number" && options.timeoutMs > 0 ? options.timeoutMs : void 0;
@@ -1649,7 +2395,8 @@ var SandboxInstance = class SandboxInstance {
1649
2395
  requireVisibleAssistantOutput: options?.requireVisibleAssistantOutput,
1650
2396
  ...timeoutMs ? { timeoutMs } : {},
1651
2397
  ...options?.detach ? { detach: true } : {},
1652
- backend: normalizeRuntimeBackendConfig(options?.backend ?? this.defaultRuntimeBackend, { model: options?.model })
2398
+ backend: this.buildRunBackendBody(options?.backend, internal?.forceFullProfile ?? false),
2399
+ ...options?.model ? { model: normalizeRuntimeModelOverride(options.model) } : {}
1653
2400
  })
1654
2401
  };
1655
2402
  response = await this.runtimeFetch(requestEndpoint, request);
@@ -2132,9 +2879,16 @@ var SandboxInstance = class SandboxInstance {
2132
2879
  async ports() {
2133
2880
  return this.runtime.ports();
2134
2881
  }
2135
- /** Interactive terminal operations for this runtime. */
2882
+ /**
2883
+ * Interactive terminal operations for this runtime: the REST manager
2884
+ * (create/input/list/get) plus `attach()`, which opens the live terminal
2885
+ * WebSocket as a {@link TerminalStream}.
2886
+ */
2136
2887
  get terminals() {
2137
- return this.runtime.terminals;
2888
+ return {
2889
+ ...this.runtime.terminals,
2890
+ attach: (connectionId, options) => this._attachTerminal(connectionId, options)
2891
+ };
2138
2892
  }
2139
2893
  /** List profiles installed in this sandbox runtime. */
2140
2894
  async listProfiles() {
@@ -2384,6 +3138,7 @@ var SandboxInstance = class SandboxInstance {
2384
3138
  read: (path) => this.read(path),
2385
3139
  readBatch: (paths, options) => this.fsReadBatch(paths, options),
2386
3140
  tree: (path, options) => this.fsTree(path, options),
3141
+ usage: (path, options) => this.fsUsage(path, options),
2387
3142
  write: (path, content, options) => this.write(path, content, options),
2388
3143
  writeMany: (files, options) => this.writeMany(files, options),
2389
3144
  search: (query, options) => this.search(query, options),
@@ -2406,6 +3161,9 @@ var SandboxInstance = class SandboxInstance {
2406
3161
  async fsTree(path, options = {}) {
2407
3162
  return this.runtime.fileTree(path, options);
2408
3163
  }
3164
+ async fsUsage(path, options = {}) {
3165
+ return this.runtime.fileUsage(path, options);
3166
+ }
2409
3167
  async fsUpload(localPath, remotePath, options) {
2410
3168
  await this.ensureRunning();
2411
3169
  const fs = await import("node:fs/promises");
@@ -3004,13 +3762,34 @@ var SandboxInstance = class SandboxInstance {
3004
3762
  */
3005
3763
  get process() {
3006
3764
  return {
3765
+ ensureDevServer: (options) => this.processEnsureDevServer(options),
3007
3766
  spawn: (command, options) => this.processSpawn(command, options),
3008
3767
  spawnExact: (executable, args, options) => this.processSpawnExact(executable, args, options),
3009
3768
  runCode: (code, options) => this.processRunCode(code, options),
3010
- list: () => this.processList(),
3769
+ list: (options) => this.processList(options),
3011
3770
  get: (pid) => this.processGet(pid)
3012
3771
  };
3013
3772
  }
3773
+ async processEnsureDevServer(options) {
3774
+ if (options?.sessionId !== void 0) assertValidSessionId(options.sessionId);
3775
+ if (options?.cwd !== void 0 && (typeof options.cwd !== "string" || options.cwd.trim().length === 0)) throw new ValidationError("Dev server cwd must be a non-empty string");
3776
+ await this.ensureRunning();
3777
+ const headers = options?.sessionId ? { "X-Session-Id": options.sessionId } : void 0;
3778
+ const response = await this.runtimeFetch("/process/ensure-dev-server", {
3779
+ method: "POST",
3780
+ headers,
3781
+ body: JSON.stringify(options?.cwd ? { cwd: options.cwd } : {})
3782
+ });
3783
+ if (!response.ok) {
3784
+ const body = await response.text();
3785
+ throw parseErrorResponse(response.status, body, void 0, response.headers);
3786
+ }
3787
+ const payload = await response.json();
3788
+ return {
3789
+ ...payload.data,
3790
+ startedAt: new Date(payload.data.startedAt)
3791
+ };
3792
+ }
3014
3793
  async processSpawn(command, options) {
3015
3794
  await this.ensureRunning();
3016
3795
  const response = await this.runtimeFetch("/process/spawn", {
@@ -3039,8 +3818,11 @@ var SandboxInstance = class SandboxInstance {
3039
3818
  args,
3040
3819
  cwd: options?.cwd,
3041
3820
  env: options?.env,
3821
+ inheritEnv: options?.inheritEnv,
3042
3822
  timeoutMs: options?.timeoutMs,
3043
3823
  stdin: options?.stdin,
3824
+ idempotencyKey: options?.idempotencyKey,
3825
+ retentionMs: options?.retentionMs,
3044
3826
  blocking: false
3045
3827
  })
3046
3828
  });
@@ -3069,15 +3851,18 @@ var SandboxInstance = class SandboxInstance {
3069
3851
  }
3070
3852
  return (await response.json()).data;
3071
3853
  }
3072
- async processList() {
3854
+ async processList(options) {
3073
3855
  await this.ensureRunning();
3074
- const response = await this.runtimeFetch("/process", { method: "GET" });
3856
+ const query = new URLSearchParams();
3857
+ if (options?.idempotencyKey !== void 0) query.set("idempotencyKey", options.idempotencyKey);
3858
+ const response = await this.runtimeFetch(query.size === 0 ? "/process" : `/process?${query.toString()}`, { method: "GET" });
3075
3859
  if (!response.ok) {
3076
3860
  const body = await response.text();
3077
3861
  throw parseErrorResponse(response.status, body, void 0, response.headers);
3078
3862
  }
3079
3863
  return ((await response.json()).data ?? []).map((p) => ({
3080
3864
  pid: p.pid,
3865
+ ...p.idempotencyKey === void 0 ? {} : { idempotencyKey: p.idempotencyKey },
3081
3866
  command: p.command,
3082
3867
  cwd: p.cwd,
3083
3868
  running: p.running,
@@ -3112,6 +3897,7 @@ var SandboxInstance = class SandboxInstance {
3112
3897
  const p = (await response.json()).data;
3113
3898
  return {
3114
3899
  pid: p.pid,
3900
+ ...p.idempotencyKey === void 0 ? {} : { idempotencyKey: p.idempotencyKey },
3115
3901
  command: p.command,
3116
3902
  cwd: p.cwd,
3117
3903
  running: p.running,
@@ -3829,7 +4615,7 @@ var SandboxInstance = class SandboxInstance {
3829
4615
  const body = await response.text();
3830
4616
  throw parseErrorResponse(response.status, body, void 0, response.headers);
3831
4617
  }
3832
- return ((await response.json()).children ?? []).map((child) => new SandboxInstance(this.client, this.parseInfo(child), this.defaultRuntimeBackend));
4618
+ return ((await response.json()).children ?? []).map((child) => createSandboxInstanceFromResponse(this.client, this.parseInfo(child), this.defaultRuntimeBackend));
3833
4619
  }
3834
4620
  /**
3835
4621
  * Speculative rollouts: branch this RUNNING sandbox into `n` copy-on-write
@@ -3962,6 +4748,7 @@ var SandboxInstance = class SandboxInstance {
3962
4748
  }
3963
4749
  const diagnostics = await this.readLifecycleDiagnostics(response);
3964
4750
  if (diagnostics) this.info.startupDiagnostics = diagnostics;
4751
+ sandboxStatusObservedAt.delete(this);
3965
4752
  }
3966
4753
  /**
3967
4754
  * Read the per-phase lifecycle breakdown off a stop/resume/delete response
@@ -4078,6 +4865,10 @@ var SandboxInstance = class SandboxInstance {
4078
4865
  /**
4079
4866
  * Wait for the sandbox to reach a specific status.
4080
4867
  *
4868
+ * A sandbox using the filesystem-incarnation contract is not considered
4869
+ * `running` until that incarnation is ready. Legacy servers that omit the
4870
+ * contract retain the status-only behavior.
4871
+ *
4081
4872
  * When `onProgress` is provided and the sandbox is still provisioning,
4082
4873
  * uses SSE events for real-time progress instead of polling. Falls back
4083
4874
  * to polling if the SSE connection fails or is unavailable.
@@ -4103,17 +4894,16 @@ var SandboxInstance = class SandboxInstance {
4103
4894
  const statuses = Array.isArray(status) ? status : [status];
4104
4895
  const timeoutMs = options?.timeoutMs ?? 12e4;
4105
4896
  const pollIntervalMs = options?.pollIntervalMs ?? 2e3;
4897
+ const startTime = Date.now();
4106
4898
  if (options?.onProgress && (this.status === "provisioning" || this.status === "pending")) try {
4107
- await this.waitForWithSSE(statuses, timeoutMs, options.onProgress, options.signal);
4108
- return;
4899
+ if (await this.waitForWithSSE(statuses, timeoutMs, options.onProgress, options.signal)) return;
4109
4900
  } catch (err) {
4110
4901
  if (err instanceof StateError || err instanceof TimeoutError) throw err;
4111
4902
  }
4112
- const startTime = Date.now();
4113
4903
  while (true) {
4114
4904
  if (options?.signal?.aborted) throw new TimeoutError(0, "Aborted");
4115
4905
  await this.refresh();
4116
- if (statuses.includes(this.status)) return;
4906
+ if (this.hasReachedWaitTarget(statuses)) return;
4117
4907
  if (this.status === "failed") throw new StateError(this.error ?? "Sandbox failed", this.status);
4118
4908
  if (Date.now() - startTime > timeoutMs) throw new TimeoutError(timeoutMs, `Timed out waiting for sandbox to reach ${statuses.join(" or ")}`);
4119
4909
  await this.sleep(pollIntervalMs);
@@ -4157,25 +4947,38 @@ var SandboxInstance = class SandboxInstance {
4157
4947
  throw new StateError(event.data.error ?? "Provisioning failed", this.status);
4158
4948
  } else if (event.type === "provision_complete" || event.type === "status_change") {
4159
4949
  await this.refresh();
4160
- if (statuses.includes(this.status)) return;
4950
+ if (this.hasReachedWaitTarget(statuses)) return true;
4161
4951
  if (this.status === "failed") throw new StateError(this.error ?? "Sandbox failed", this.status);
4162
4952
  }
4163
4953
  await this.refresh();
4164
- if (statuses.includes(this.status)) return;
4954
+ if (this.hasReachedWaitTarget(statuses)) return true;
4165
4955
  if (this.status === "failed") throw new StateError(this.error ?? "Sandbox failed", this.status);
4956
+ if (statuses.includes("running") && this.status === "running" && this.filesystemIncarnationContract) return false;
4166
4957
  throw new TimeoutError(timeoutMs, `SSE stream ended before sandbox reached ${statuses.join(" or ")}`);
4167
4958
  } finally {
4168
4959
  clearTimeout(timeout);
4169
4960
  abortController.abort();
4170
4961
  }
4171
4962
  }
4963
+ hasReachedWaitTarget(statuses) {
4964
+ if (!statuses.includes(this.status)) return false;
4965
+ return this.status !== "running" || !this.filesystemIncarnationContract || this.filesystemIncarnationReadiness === "ready";
4966
+ }
4172
4967
  async ensureRunning() {
4173
- await this.refresh();
4968
+ const statusObservedAt = sandboxStatusObservedAt.get(this) ?? 0;
4969
+ const statusAgeMs = Date.now() - statusObservedAt;
4970
+ if (directRuntimeInstances.has(this) || statusObservedAt <= 0 || statusAgeMs < 0 || statusAgeMs >= SANDBOX_STATUS_FRESHNESS_MS) await this.refresh();
4174
4971
  if (this.status !== "running") throw new StateError(`Sandbox is not running (status: ${this.status})`, this.status, "running");
4972
+ this.assertFilesystemIncarnationReady();
4175
4973
  }
4176
- async runtimeFetch(path, options) {
4974
+ assertFilesystemIncarnationReady() {
4975
+ if (this.filesystemIncarnationContract && this.filesystemIncarnationReadiness !== "ready") throw new StateError("Sandbox filesystem incarnation is not ready", this.status, "running with a ready filesystem incarnation");
4976
+ }
4977
+ async runtimeFetch(path, options, fetchOptions) {
4978
+ this.assertFilesystemIncarnationReady();
4177
4979
  const url = `/v1/sandboxes/${encodeURIComponent(this.id)}/runtime${path}`;
4178
4980
  try {
4981
+ if (fetchOptions) return await this.client.fetch(url, options, fetchOptions);
4179
4982
  return options ? await this.client.fetch(url, options) : await this.client.fetch(url);
4180
4983
  } catch (err) {
4181
4984
  throw new NetworkError(`Failed to connect to sandbox: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : void 0, {
@@ -4213,17 +5016,16 @@ var SandboxInstance = class SandboxInstance {
4213
5016
  * ```typescript
4214
5017
  * await box.registerSessionMapping({
4215
5018
  * sessionId: "sess_abc",
4216
- * userId: "user_123",
5019
+ * runtimeSessionId: "runtime_abc",
4217
5020
  * });
4218
5021
  * ```
4219
5022
  */
4220
5023
  async registerSessionMapping(opts) {
4221
5024
  const response = await this.client.fetch(`/v1/session/${encodeURIComponent(opts.sessionId)}/mapping`, {
4222
5025
  method: "PUT",
4223
- headers: { "x-user-id": opts.userId },
4224
5026
  body: JSON.stringify({
4225
5027
  sidecarSessionId: opts.runtimeSessionId,
4226
- ...opts.sidecarId ? { sidecarId: opts.sidecarId } : {},
5028
+ sidecarId: opts.sidecarId ?? this.id,
4227
5029
  ...opts.projectRef ? { projectRef: opts.projectRef } : {}
4228
5030
  })
4229
5031
  });
@@ -4252,10 +5054,7 @@ var SandboxInstance = class SandboxInstance {
4252
5054
  * sandbox stays alive.
4253
5055
  */
4254
5056
  async unregisterSessionMapping(opts) {
4255
- const response = await this.client.fetch(`/v1/session/${encodeURIComponent(opts.sessionId)}/mapping`, {
4256
- method: "DELETE",
4257
- headers: { "x-user-id": opts.userId }
4258
- });
5057
+ const response = await this.client.fetch(`/v1/session/${encodeURIComponent(opts.sessionId)}/mapping`, { method: "DELETE" });
4259
5058
  if (!response.ok) {
4260
5059
  const body = await response.text();
4261
5060
  throw parseErrorResponse(response.status, body, void 0, response.headers);
@@ -4267,11 +5066,19 @@ var SandboxInstance = class SandboxInstance {
4267
5066
  };
4268
5067
  }
4269
5068
  parseInfo(data) {
5069
+ const id = data.id ?? this.id;
5070
+ const incarnation = readFilesystemIncarnationTuple(data);
5071
+ this.filesystemIncarnationContract ||= incarnation.hasAny;
5072
+ const incarnationComplete = incarnation.complete;
5073
+ const connection = this.filesystemIncarnationContract ? incarnationComplete && incarnation.readiness === "ready" ? normalizeConnection(data.connection) : void 0 : normalizeConnection(data.connection) ?? this.info.connection;
4270
5074
  return {
4271
- id: data.id ?? this.id,
5075
+ id,
4272
5076
  name: data.name,
5077
+ filesystemIncarnationId: incarnationComplete ? incarnation.id : void 0,
5078
+ filesystemIncarnationProvenance: incarnationComplete ? incarnation.provenance : void 0,
5079
+ filesystemIncarnationReadiness: incarnationComplete ? incarnation.readiness : void 0,
4273
5080
  status: data.status ?? "pending",
4274
- connection: normalizeConnection(data.connection) ?? this.info.connection,
5081
+ connection,
4275
5082
  metadata: data.metadata,
4276
5083
  createdAt: data.createdAt ? new Date(data.createdAt) : this.info.createdAt,
4277
5084
  startedAt: data.startedAt ? new Date(data.startedAt) : void 0,
@@ -4514,7 +5321,11 @@ var SandboxInstance = class SandboxInstance {
4514
5321
  };
4515
5322
  }
4516
5323
  if (info) {
4517
- const result = await this._sessionResult(opts.sessionId);
5324
+ if (!info.latestExecutionId) return {
5325
+ state: "failed",
5326
+ error: `session ${opts.sessionId} ${info.status}: no execution result is available`
5327
+ };
5328
+ const result = await this._sessionResult(opts.sessionId, info);
4518
5329
  const settled = settleTurnDrive({ ...result });
4519
5330
  if (settled.state === "awaiting_plan_decision") return settled;
4520
5331
  if (!result.success) return {
@@ -4537,12 +5348,14 @@ var SandboxInstance = class SandboxInstance {
4537
5348
  */
4538
5349
  async mintScopedToken(opts) {
4539
5350
  if ((opts.scope === "session" || opts.scope === "session-runtime") && !opts.sessionId) throw new ValidationError(`${opts.scope} scope requires a sessionId`);
5351
+ if (opts.scope === "session" && !opts.runtimeSessionId) throw new ValidationError("session scope requires the actual runtimeSessionId");
4540
5352
  const response = await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}/scoped-token`, {
4541
5353
  method: "POST",
4542
5354
  headers: { "Content-Type": "application/json" },
4543
5355
  body: JSON.stringify({
4544
5356
  scope: opts.scope,
4545
5357
  ...opts.sessionId ? { sessionId: opts.sessionId } : {},
5358
+ ...opts.scope === "session" ? { runtimeSessionId: opts.runtimeSessionId } : {},
4546
5359
  ...opts.ttlMinutes ? { ttlMinutes: opts.ttlMinutes } : {}
4547
5360
  })
4548
5361
  });
@@ -4590,8 +5403,17 @@ var SandboxInstance = class SandboxInstance {
4590
5403
  }
4591
5404
  }
4592
5405
  /** @internal — invoked by SandboxSession.result(). */
4593
- async _sessionResult(id) {
5406
+ async _sessionResult(id, knownSession) {
4594
5407
  const startTime = Date.now();
5408
+ const session = knownSession ?? await this._sessionStatus(id);
5409
+ if (!session) throw new NotFoundError("Session", id, {
5410
+ origin: "runtime",
5411
+ endpoint: `/agents/sessions/${encodeURIComponent(id)}`
5412
+ });
5413
+ if (!session.latestExecutionId) throw new StateError(`Session ${id} has no execution result to await`, session.status, "session with an admitted execution", {
5414
+ origin: "runtime",
5415
+ endpoint: `/agents/sessions/${encodeURIComponent(id)}`
5416
+ }, "SESSION_EXECUTION_MISSING");
4595
5417
  let response;
4596
5418
  let runError;
4597
5419
  let runErrorCode;
@@ -4602,7 +5424,10 @@ var SandboxInstance = class SandboxInstance {
4602
5424
  let question;
4603
5425
  let plan;
4604
5426
  let terminalReached = false;
4605
- for await (const event of this._sessionEvents(id, void 0, true)) {
5427
+ for await (const event of this._sessionEvents(id, {
5428
+ since: "0",
5429
+ executionId: session.latestExecutionId
5430
+ }, true)) {
4606
5431
  response = applySandboxEventText(response, event);
4607
5432
  if (event.type === "result" || event.type === "done") {
4608
5433
  const data = event.data;
@@ -4692,6 +5517,102 @@ var SandboxInstance = class SandboxInstance {
4692
5517
  throw parseErrorResponse(response.status, body, void 0, response.headers);
4693
5518
  }
4694
5519
  }
5520
+ /** @internal — invoked by InteractiveSessionHandle.status(). */
5521
+ async _interactiveStatus(id) {
5522
+ await this.ensureRunning();
5523
+ const response = await this.runtimeFetch(`/agents/sessions/${encodeURIComponent(id)}/interactive`, { method: "GET" });
5524
+ if (response.status === 404) return null;
5525
+ if (!response.ok) {
5526
+ const body = await response.text();
5527
+ throw parseErrorResponse(response.status, body, void 0, response.headers);
5528
+ }
5529
+ const data = (await response.json())?.data;
5530
+ if (!data || data.state !== "running" && data.state !== "exited") throw new ServerError("Interactive status response missing data", 502, {
5531
+ endpoint: `/agents/sessions/${encodeURIComponent(id)}/interactive`,
5532
+ origin: "runtime"
5533
+ });
5534
+ return data;
5535
+ }
5536
+ /**
5537
+ * @internal Test seam: unit tests replace this to intercept terminal
5538
+ * WebSocket dials without opening a real socket. Production paths always
5539
+ * go through `TerminalStream.connect`.
5540
+ */
5541
+ _terminalStreamConnect = (options) => TerminalStream.connect(options);
5542
+ /**
5543
+ * Resolve a sandbox-relative terminal stream path against the browser-safe
5544
+ * sidecar proxy base returned by the scoped-token mint. Concatenation, not
5545
+ * URL resolution: the proxy base carries a path prefix
5546
+ * (`/v1/sidecar-proxy/{id}`) that `new URL(absolutePath, base)` would drop.
5547
+ */
5548
+ resolveTerminalStreamUrl(sidecarProxyUrl, streamPath) {
5549
+ if (!streamPath.startsWith("/")) throw new ServerError(`Terminal stream path must be sandbox-relative (got "${streamPath}")`, 502, { origin: "runtime" });
5550
+ return `${sidecarProxyUrl.replace(/\/+$/, "")}${streamPath}`;
5551
+ }
5552
+ /** @internal — invoked by InteractiveSessionHandle.attach(). */
5553
+ async _attachInteractive(id, options = {}) {
5554
+ const status = await this._interactiveStatus(id);
5555
+ if (!status) throw new NotFoundError("Interactive session", id, {
5556
+ origin: "runtime",
5557
+ endpoint: `/agents/sessions/${encodeURIComponent(id)}/interactive`
5558
+ });
5559
+ if (status.state !== "running") throw new StateError(`Interactive session ${id} has exited; there is no live PTY to attach`, status.state, "running", {
5560
+ origin: "runtime",
5561
+ endpoint: `/agents/sessions/${encodeURIComponent(id)}/interactive`
5562
+ }, "INTERACTIVE_SESSION_EXITED");
5563
+ const scoped = await this.mintScopedToken({
5564
+ scope: "session-runtime",
5565
+ sessionId: id
5566
+ });
5567
+ return this._terminalStreamConnect({
5568
+ url: this.resolveTerminalStreamUrl(scoped.sidecarProxyUrl, status.streamUrl),
5569
+ token: this.terminalTokenProvider(scoped.token, id),
5570
+ connectionId: id,
5571
+ cols: options.cols,
5572
+ rows: options.rows,
5573
+ handlers: options.handlers
5574
+ });
5575
+ }
5576
+ /**
5577
+ * Per-dial credential for a terminal attach. The first dial consumes the
5578
+ * token minted alongside the proxy URL (no second mint); every later dial
5579
+ * (a `reconnect()` after the socket dropped or the detach window) re-mints,
5580
+ * because scoped terminal tokens are clamped to a <= 15-minute TTL and the
5581
+ * original is likely dead by then.
5582
+ */
5583
+ terminalTokenProvider(initialToken, sessionId) {
5584
+ let unused = initialToken;
5585
+ return async () => {
5586
+ if (unused !== null) {
5587
+ const token = unused;
5588
+ unused = null;
5589
+ return token;
5590
+ }
5591
+ return (await this.mintScopedToken({
5592
+ scope: "session-runtime",
5593
+ sessionId
5594
+ })).token;
5595
+ };
5596
+ }
5597
+ /** @internal — invoked by `box.terminals.attach()`. */
5598
+ async _attachTerminal(connectionId, options = {}) {
5599
+ if (!connectionId.trim()) throw new ValidationError("Terminal connectionId is required");
5600
+ const scoped = await this.mintScopedToken({
5601
+ scope: "session-runtime",
5602
+ sessionId: connectionId
5603
+ });
5604
+ return this._terminalStreamConnect({
5605
+ url: this.resolveTerminalStreamUrl(scoped.sidecarProxyUrl, `/terminals/${encodeURIComponent(connectionId)}/ws`),
5606
+ token: this.terminalTokenProvider(scoped.token, connectionId),
5607
+ connectionId,
5608
+ cols: options.cols,
5609
+ rows: options.rows,
5610
+ command: options.command,
5611
+ cwd: options.cwd,
5612
+ env: options.env,
5613
+ handlers: options.handlers
5614
+ });
5615
+ }
4695
5616
  /** @internal — invoked by InteractiveSessionHandle.stop(). */
4696
5617
  async _stopInteractive(id) {
4697
5618
  await this.ensureRunning();
@@ -4901,4 +5822,4 @@ function quoteForShell(value) {
4901
5822
  return `'${value.replace(/'/g, "'\\''")}'`;
4902
5823
  }
4903
5824
  //#endregion
4904
- export { InteractiveSessionHandle as a, getSandboxEventText as c, exportTraceBundle as d, otelTraceIdForTangleTrace as f, SandboxSession as i, normalizeConnection as l, parseSSEStream as m, normalizeStartupDiagnostics as n, applySandboxEventText as o, toOtelJson as p, SandboxTaskSession as r, collectAgentResponseText as s, SandboxInstance as t, buildTraceExportPayload as u };
5825
+ export { otelTraceIdForTangleTrace as _, TERMINAL_WS_ECHO_SUBPROTOCOL as a, SandboxTaskSession as c, applySandboxEventText as d, collectAgentResponseText as f, exportTraceBundle as g, buildTraceExportPayload as h, WorkspaceImages as i, SandboxSession as l, normalizeConnection as m, createSandboxInstanceFromResponse as n, TerminalStream as o, getSandboxEventText as p, normalizeStartupDiagnostics as r, TerminalStreamError as s, SandboxInstance as t, InteractiveSessionHandle as u, toOtelJson as v, parseSSEStream as y };