@tangle-network/sandbox 0.11.1 → 0.12.0-develop.20260724231304.911a687

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,103 @@ 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 already holds `profile` under `sha256`, so
2211
+ * subsequent turns whose profile serializes byte-identically send
2212
+ * `backend.profileSha256` instead of the inline corpus. Use this to hydrate
2213
+ * a freshly-fetched instance (`get()`/`list()`) from caller-persisted state
2214
+ * — the reference otherwise lives only on the instance that primed it.
2215
+ * Captures a content snapshot, so mutating the object afterwards is
2216
+ * detected and that turn falls back to sending the profile inline.
2217
+ */
2218
+ attachProfileReference(profile, sha256) {
2219
+ this.deferredProfileReference = {
2220
+ snapshot: serializeProfileSnapshot(profile),
2221
+ sha256
2222
+ };
2223
+ }
2224
+ /**
2225
+ * Upload `profile` to the runtime once (`POST /agents/profiles`) and record
2226
+ * the returned hash via {@link attachProfileReference}, so subsequent turns
2227
+ * reference it by `profileSha256` instead of re-sending the corpus.
2228
+ * `create()` calls this automatically for its inline profile when
2229
+ * `autoDeferProfile` is on; call it directly when the profile only exists
2230
+ * per-turn, or when the instance was fetched rather than created. Persist
2231
+ * the returned sha256 alongside a content hash of the profile to
2232
+ * re-attach on later instances without re-priming. Throws on transport/HTTP
2233
+ * failure — the caller decides whether that is fatal (it is not: turns fall
2234
+ * back to sending the full profile inline).
2235
+ */
2236
+ async primeProfile(profile) {
2237
+ const response = await this.runtimeFetch("/agents/profiles", {
2238
+ method: "POST",
2239
+ headers: { "content-type": "application/json" },
2240
+ body: JSON.stringify({ profile })
2241
+ });
2242
+ if (!response.ok) {
2243
+ const body = await response.text();
2244
+ throw parseErrorResponse(response.status, body, {
2245
+ method: "POST",
2246
+ path: "/agents/profiles"
2247
+ });
2248
+ }
2249
+ const data = await response.json();
2250
+ if (typeof data.sha256 !== "string" || data.sha256.length === 0) throw new Error("Profile priming returned no sha256; runtime response malformed");
2251
+ this.attachProfileReference(profile, data.sha256);
2252
+ return data.sha256;
2253
+ }
2254
+ /**
2255
+ * Build the run request's `backend` body. When the outgoing profile's CONTENT
2256
+ * matches the one the runtime already holds (and we are not resending after a
2257
+ * cache miss), swap the inline `profile` for its `profileSha256` so a large
2258
+ * static corpus does not ride every turn. The match is by serialized content,
2259
+ * not object identity, so a mutated-in-place profile — or an equivalent
2260
+ * object passed as a per-turn override — is compared correctly: unchanged
2261
+ * content references by hash, changed content sends inline (the legacy shape).
2262
+ */
2263
+ buildRunBackendBody(overrideBackend, forceFullProfile) {
2264
+ const normalized = normalizeRuntimeBackendConfig(overrideBackend ?? this.defaultRuntimeBackend);
2265
+ if (!normalized) return normalized;
2266
+ const deferred = this.deferredProfileReference;
2267
+ if (!forceFullProfile && deferred !== void 0 && normalized.profile !== void 0 && serializeProfileSnapshot(normalized.profile) === deferred.snapshot) {
2268
+ const { profile: _omitted, ...rest } = normalized;
2269
+ return {
2270
+ ...rest,
2271
+ profileSha256: deferred.sha256
2272
+ };
2273
+ }
2274
+ return normalized;
2275
+ }
1541
2276
  async *streamPrompt(message, options) {
1542
2277
  const isCallerAbort = () => options?.signal?.aborted === true;
1543
2278
  let receivedTerminal = false;
1544
2279
  let sessionId = options?.sessionId;
1545
2280
  let executionId = options?.executionId;
2281
+ let profileResendAttempted = false;
1546
2282
  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;
2283
+ for (;;) {
2284
+ let yieldedThisAttempt = false;
2285
+ try {
2286
+ for await (const event of this.streamPromptInner(message, options, { forceFullProfile: profileResendAttempted })) {
2287
+ yieldedThisAttempt = true;
2288
+ if (event.type === "result" || event.type === "done") receivedTerminal = true;
2289
+ if (event.type === "execution.started" && event.data.executionId) executionId = event.data.executionId;
2290
+ const sid = event.data.sessionId;
2291
+ if (typeof sid === "string" && sid.length > 0) sessionId = sid;
2292
+ yield event;
2293
+ }
2294
+ break;
2295
+ } catch (err) {
2296
+ if (!yieldedThisAttempt && !profileResendAttempted && isProfileNotCachedError(err)) {
2297
+ this.logStreamCheckpoint("profile_reference_miss_resend", {
2298
+ sessionId,
2299
+ executionId
2300
+ });
2301
+ profileResendAttempted = true;
2302
+ continue;
2303
+ }
2304
+ throw err;
2305
+ }
1553
2306
  }
1554
2307
  } catch (err) {
1555
2308
  if (isCallerAbort()) return;
@@ -1582,7 +2335,7 @@ var SandboxInstance = class SandboxInstance {
1582
2335
  * the public `streamPrompt` wrapper converts those throws into a terminal
1583
2336
  * `error` + `done` so callers never see a thrown generator.
1584
2337
  */
1585
- async *streamPromptInner(message, options) {
2338
+ async *streamPromptInner(message, options, internal) {
1586
2339
  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
2340
  await this.ensureRunning();
1588
2341
  const timeoutMs = typeof options?.timeoutMs === "number" && options.timeoutMs > 0 ? options.timeoutMs : void 0;
@@ -1649,7 +2402,8 @@ var SandboxInstance = class SandboxInstance {
1649
2402
  requireVisibleAssistantOutput: options?.requireVisibleAssistantOutput,
1650
2403
  ...timeoutMs ? { timeoutMs } : {},
1651
2404
  ...options?.detach ? { detach: true } : {},
1652
- backend: normalizeRuntimeBackendConfig(options?.backend ?? this.defaultRuntimeBackend, { model: options?.model })
2405
+ backend: this.buildRunBackendBody(options?.backend, internal?.forceFullProfile ?? false),
2406
+ ...options?.model ? { model: normalizeRuntimeModelOverride(options.model) } : {}
1653
2407
  })
1654
2408
  };
1655
2409
  response = await this.runtimeFetch(requestEndpoint, request);
@@ -2132,9 +2886,16 @@ var SandboxInstance = class SandboxInstance {
2132
2886
  async ports() {
2133
2887
  return this.runtime.ports();
2134
2888
  }
2135
- /** Interactive terminal operations for this runtime. */
2889
+ /**
2890
+ * Interactive terminal operations for this runtime: the REST manager
2891
+ * (create/input/list/get) plus `attach()`, which opens the live terminal
2892
+ * WebSocket as a {@link TerminalStream}.
2893
+ */
2136
2894
  get terminals() {
2137
- return this.runtime.terminals;
2895
+ return {
2896
+ ...this.runtime.terminals,
2897
+ attach: (connectionId, options) => this._attachTerminal(connectionId, options)
2898
+ };
2138
2899
  }
2139
2900
  /** List profiles installed in this sandbox runtime. */
2140
2901
  async listProfiles() {
@@ -2384,6 +3145,7 @@ var SandboxInstance = class SandboxInstance {
2384
3145
  read: (path) => this.read(path),
2385
3146
  readBatch: (paths, options) => this.fsReadBatch(paths, options),
2386
3147
  tree: (path, options) => this.fsTree(path, options),
3148
+ usage: (path, options) => this.fsUsage(path, options),
2387
3149
  write: (path, content, options) => this.write(path, content, options),
2388
3150
  writeMany: (files, options) => this.writeMany(files, options),
2389
3151
  search: (query, options) => this.search(query, options),
@@ -2406,6 +3168,9 @@ var SandboxInstance = class SandboxInstance {
2406
3168
  async fsTree(path, options = {}) {
2407
3169
  return this.runtime.fileTree(path, options);
2408
3170
  }
3171
+ async fsUsage(path, options = {}) {
3172
+ return this.runtime.fileUsage(path, options);
3173
+ }
2409
3174
  async fsUpload(localPath, remotePath, options) {
2410
3175
  await this.ensureRunning();
2411
3176
  const fs = await import("node:fs/promises");
@@ -3004,13 +3769,34 @@ var SandboxInstance = class SandboxInstance {
3004
3769
  */
3005
3770
  get process() {
3006
3771
  return {
3772
+ ensureDevServer: (options) => this.processEnsureDevServer(options),
3007
3773
  spawn: (command, options) => this.processSpawn(command, options),
3008
3774
  spawnExact: (executable, args, options) => this.processSpawnExact(executable, args, options),
3009
3775
  runCode: (code, options) => this.processRunCode(code, options),
3010
- list: () => this.processList(),
3776
+ list: (options) => this.processList(options),
3011
3777
  get: (pid) => this.processGet(pid)
3012
3778
  };
3013
3779
  }
3780
+ async processEnsureDevServer(options) {
3781
+ if (options?.sessionId !== void 0) assertValidSessionId(options.sessionId);
3782
+ 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");
3783
+ await this.ensureRunning();
3784
+ const headers = options?.sessionId ? { "X-Session-Id": options.sessionId } : void 0;
3785
+ const response = await this.runtimeFetch("/process/ensure-dev-server", {
3786
+ method: "POST",
3787
+ headers,
3788
+ body: JSON.stringify(options?.cwd ? { cwd: options.cwd } : {})
3789
+ });
3790
+ if (!response.ok) {
3791
+ const body = await response.text();
3792
+ throw parseErrorResponse(response.status, body, void 0, response.headers);
3793
+ }
3794
+ const payload = await response.json();
3795
+ return {
3796
+ ...payload.data,
3797
+ startedAt: new Date(payload.data.startedAt)
3798
+ };
3799
+ }
3014
3800
  async processSpawn(command, options) {
3015
3801
  await this.ensureRunning();
3016
3802
  const response = await this.runtimeFetch("/process/spawn", {
@@ -3039,8 +3825,11 @@ var SandboxInstance = class SandboxInstance {
3039
3825
  args,
3040
3826
  cwd: options?.cwd,
3041
3827
  env: options?.env,
3828
+ inheritEnv: options?.inheritEnv,
3042
3829
  timeoutMs: options?.timeoutMs,
3043
3830
  stdin: options?.stdin,
3831
+ idempotencyKey: options?.idempotencyKey,
3832
+ retentionMs: options?.retentionMs,
3044
3833
  blocking: false
3045
3834
  })
3046
3835
  });
@@ -3069,15 +3858,18 @@ var SandboxInstance = class SandboxInstance {
3069
3858
  }
3070
3859
  return (await response.json()).data;
3071
3860
  }
3072
- async processList() {
3861
+ async processList(options) {
3073
3862
  await this.ensureRunning();
3074
- const response = await this.runtimeFetch("/process", { method: "GET" });
3863
+ const query = new URLSearchParams();
3864
+ if (options?.idempotencyKey !== void 0) query.set("idempotencyKey", options.idempotencyKey);
3865
+ const response = await this.runtimeFetch(query.size === 0 ? "/process" : `/process?${query.toString()}`, { method: "GET" });
3075
3866
  if (!response.ok) {
3076
3867
  const body = await response.text();
3077
3868
  throw parseErrorResponse(response.status, body, void 0, response.headers);
3078
3869
  }
3079
3870
  return ((await response.json()).data ?? []).map((p) => ({
3080
3871
  pid: p.pid,
3872
+ ...p.idempotencyKey === void 0 ? {} : { idempotencyKey: p.idempotencyKey },
3081
3873
  command: p.command,
3082
3874
  cwd: p.cwd,
3083
3875
  running: p.running,
@@ -3112,6 +3904,7 @@ var SandboxInstance = class SandboxInstance {
3112
3904
  const p = (await response.json()).data;
3113
3905
  return {
3114
3906
  pid: p.pid,
3907
+ ...p.idempotencyKey === void 0 ? {} : { idempotencyKey: p.idempotencyKey },
3115
3908
  command: p.command,
3116
3909
  cwd: p.cwd,
3117
3910
  running: p.running,
@@ -3829,7 +4622,7 @@ var SandboxInstance = class SandboxInstance {
3829
4622
  const body = await response.text();
3830
4623
  throw parseErrorResponse(response.status, body, void 0, response.headers);
3831
4624
  }
3832
- return ((await response.json()).children ?? []).map((child) => new SandboxInstance(this.client, this.parseInfo(child), this.defaultRuntimeBackend));
4625
+ return ((await response.json()).children ?? []).map((child) => createSandboxInstanceFromResponse(this.client, this.parseInfo(child), this.defaultRuntimeBackend));
3833
4626
  }
3834
4627
  /**
3835
4628
  * Speculative rollouts: branch this RUNNING sandbox into `n` copy-on-write
@@ -3962,6 +4755,7 @@ var SandboxInstance = class SandboxInstance {
3962
4755
  }
3963
4756
  const diagnostics = await this.readLifecycleDiagnostics(response);
3964
4757
  if (diagnostics) this.info.startupDiagnostics = diagnostics;
4758
+ sandboxStatusObservedAt.delete(this);
3965
4759
  }
3966
4760
  /**
3967
4761
  * Read the per-phase lifecycle breakdown off a stop/resume/delete response
@@ -4078,6 +4872,10 @@ var SandboxInstance = class SandboxInstance {
4078
4872
  /**
4079
4873
  * Wait for the sandbox to reach a specific status.
4080
4874
  *
4875
+ * A sandbox using the filesystem-incarnation contract is not considered
4876
+ * `running` until that incarnation is ready. Legacy servers that omit the
4877
+ * contract retain the status-only behavior.
4878
+ *
4081
4879
  * When `onProgress` is provided and the sandbox is still provisioning,
4082
4880
  * uses SSE events for real-time progress instead of polling. Falls back
4083
4881
  * to polling if the SSE connection fails or is unavailable.
@@ -4103,17 +4901,16 @@ var SandboxInstance = class SandboxInstance {
4103
4901
  const statuses = Array.isArray(status) ? status : [status];
4104
4902
  const timeoutMs = options?.timeoutMs ?? 12e4;
4105
4903
  const pollIntervalMs = options?.pollIntervalMs ?? 2e3;
4904
+ const startTime = Date.now();
4106
4905
  if (options?.onProgress && (this.status === "provisioning" || this.status === "pending")) try {
4107
- await this.waitForWithSSE(statuses, timeoutMs, options.onProgress, options.signal);
4108
- return;
4906
+ if (await this.waitForWithSSE(statuses, timeoutMs, options.onProgress, options.signal)) return;
4109
4907
  } catch (err) {
4110
4908
  if (err instanceof StateError || err instanceof TimeoutError) throw err;
4111
4909
  }
4112
- const startTime = Date.now();
4113
4910
  while (true) {
4114
4911
  if (options?.signal?.aborted) throw new TimeoutError(0, "Aborted");
4115
4912
  await this.refresh();
4116
- if (statuses.includes(this.status)) return;
4913
+ if (this.hasReachedWaitTarget(statuses)) return;
4117
4914
  if (this.status === "failed") throw new StateError(this.error ?? "Sandbox failed", this.status);
4118
4915
  if (Date.now() - startTime > timeoutMs) throw new TimeoutError(timeoutMs, `Timed out waiting for sandbox to reach ${statuses.join(" or ")}`);
4119
4916
  await this.sleep(pollIntervalMs);
@@ -4157,25 +4954,38 @@ var SandboxInstance = class SandboxInstance {
4157
4954
  throw new StateError(event.data.error ?? "Provisioning failed", this.status);
4158
4955
  } else if (event.type === "provision_complete" || event.type === "status_change") {
4159
4956
  await this.refresh();
4160
- if (statuses.includes(this.status)) return;
4957
+ if (this.hasReachedWaitTarget(statuses)) return true;
4161
4958
  if (this.status === "failed") throw new StateError(this.error ?? "Sandbox failed", this.status);
4162
4959
  }
4163
4960
  await this.refresh();
4164
- if (statuses.includes(this.status)) return;
4961
+ if (this.hasReachedWaitTarget(statuses)) return true;
4165
4962
  if (this.status === "failed") throw new StateError(this.error ?? "Sandbox failed", this.status);
4963
+ if (statuses.includes("running") && this.status === "running" && this.filesystemIncarnationContract) return false;
4166
4964
  throw new TimeoutError(timeoutMs, `SSE stream ended before sandbox reached ${statuses.join(" or ")}`);
4167
4965
  } finally {
4168
4966
  clearTimeout(timeout);
4169
4967
  abortController.abort();
4170
4968
  }
4171
4969
  }
4970
+ hasReachedWaitTarget(statuses) {
4971
+ if (!statuses.includes(this.status)) return false;
4972
+ return this.status !== "running" || !this.filesystemIncarnationContract || this.filesystemIncarnationReadiness === "ready";
4973
+ }
4172
4974
  async ensureRunning() {
4173
- await this.refresh();
4975
+ const statusObservedAt = sandboxStatusObservedAt.get(this) ?? 0;
4976
+ const statusAgeMs = Date.now() - statusObservedAt;
4977
+ if (directRuntimeInstances.has(this) || statusObservedAt <= 0 || statusAgeMs < 0 || statusAgeMs >= SANDBOX_STATUS_FRESHNESS_MS) await this.refresh();
4174
4978
  if (this.status !== "running") throw new StateError(`Sandbox is not running (status: ${this.status})`, this.status, "running");
4979
+ this.assertFilesystemIncarnationReady();
4980
+ }
4981
+ assertFilesystemIncarnationReady() {
4982
+ if (this.filesystemIncarnationContract && this.filesystemIncarnationReadiness !== "ready") throw new StateError("Sandbox filesystem incarnation is not ready", this.status, "running with a ready filesystem incarnation");
4175
4983
  }
4176
- async runtimeFetch(path, options) {
4984
+ async runtimeFetch(path, options, fetchOptions) {
4985
+ this.assertFilesystemIncarnationReady();
4177
4986
  const url = `/v1/sandboxes/${encodeURIComponent(this.id)}/runtime${path}`;
4178
4987
  try {
4988
+ if (fetchOptions) return await this.client.fetch(url, options, fetchOptions);
4179
4989
  return options ? await this.client.fetch(url, options) : await this.client.fetch(url);
4180
4990
  } catch (err) {
4181
4991
  throw new NetworkError(`Failed to connect to sandbox: ${err instanceof Error ? err.message : String(err)}`, err instanceof Error ? err : void 0, {
@@ -4213,17 +5023,16 @@ var SandboxInstance = class SandboxInstance {
4213
5023
  * ```typescript
4214
5024
  * await box.registerSessionMapping({
4215
5025
  * sessionId: "sess_abc",
4216
- * userId: "user_123",
5026
+ * runtimeSessionId: "runtime_abc",
4217
5027
  * });
4218
5028
  * ```
4219
5029
  */
4220
5030
  async registerSessionMapping(opts) {
4221
5031
  const response = await this.client.fetch(`/v1/session/${encodeURIComponent(opts.sessionId)}/mapping`, {
4222
5032
  method: "PUT",
4223
- headers: { "x-user-id": opts.userId },
4224
5033
  body: JSON.stringify({
4225
5034
  sidecarSessionId: opts.runtimeSessionId,
4226
- ...opts.sidecarId ? { sidecarId: opts.sidecarId } : {},
5035
+ sidecarId: opts.sidecarId ?? this.id,
4227
5036
  ...opts.projectRef ? { projectRef: opts.projectRef } : {}
4228
5037
  })
4229
5038
  });
@@ -4252,10 +5061,7 @@ var SandboxInstance = class SandboxInstance {
4252
5061
  * sandbox stays alive.
4253
5062
  */
4254
5063
  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
- });
5064
+ const response = await this.client.fetch(`/v1/session/${encodeURIComponent(opts.sessionId)}/mapping`, { method: "DELETE" });
4259
5065
  if (!response.ok) {
4260
5066
  const body = await response.text();
4261
5067
  throw parseErrorResponse(response.status, body, void 0, response.headers);
@@ -4267,11 +5073,19 @@ var SandboxInstance = class SandboxInstance {
4267
5073
  };
4268
5074
  }
4269
5075
  parseInfo(data) {
5076
+ const id = data.id ?? this.id;
5077
+ const incarnation = readFilesystemIncarnationTuple(data);
5078
+ this.filesystemIncarnationContract ||= incarnation.hasAny;
5079
+ const incarnationComplete = incarnation.complete;
5080
+ const connection = this.filesystemIncarnationContract ? incarnationComplete && incarnation.readiness === "ready" ? normalizeConnection(data.connection) : void 0 : normalizeConnection(data.connection) ?? this.info.connection;
4270
5081
  return {
4271
- id: data.id ?? this.id,
5082
+ id,
4272
5083
  name: data.name,
5084
+ filesystemIncarnationId: incarnationComplete ? incarnation.id : void 0,
5085
+ filesystemIncarnationProvenance: incarnationComplete ? incarnation.provenance : void 0,
5086
+ filesystemIncarnationReadiness: incarnationComplete ? incarnation.readiness : void 0,
4273
5087
  status: data.status ?? "pending",
4274
- connection: normalizeConnection(data.connection) ?? this.info.connection,
5088
+ connection,
4275
5089
  metadata: data.metadata,
4276
5090
  createdAt: data.createdAt ? new Date(data.createdAt) : this.info.createdAt,
4277
5091
  startedAt: data.startedAt ? new Date(data.startedAt) : void 0,
@@ -4514,7 +5328,11 @@ var SandboxInstance = class SandboxInstance {
4514
5328
  };
4515
5329
  }
4516
5330
  if (info) {
4517
- const result = await this._sessionResult(opts.sessionId);
5331
+ if (!info.latestExecutionId) return {
5332
+ state: "failed",
5333
+ error: `session ${opts.sessionId} ${info.status}: no execution result is available`
5334
+ };
5335
+ const result = await this._sessionResult(opts.sessionId, info);
4518
5336
  const settled = settleTurnDrive({ ...result });
4519
5337
  if (settled.state === "awaiting_plan_decision") return settled;
4520
5338
  if (!result.success) return {
@@ -4537,12 +5355,14 @@ var SandboxInstance = class SandboxInstance {
4537
5355
  */
4538
5356
  async mintScopedToken(opts) {
4539
5357
  if ((opts.scope === "session" || opts.scope === "session-runtime") && !opts.sessionId) throw new ValidationError(`${opts.scope} scope requires a sessionId`);
5358
+ if (opts.scope === "session" && !opts.runtimeSessionId) throw new ValidationError("session scope requires the actual runtimeSessionId");
4540
5359
  const response = await this.client.fetch(`/v1/sandboxes/${encodeURIComponent(this.id)}/scoped-token`, {
4541
5360
  method: "POST",
4542
5361
  headers: { "Content-Type": "application/json" },
4543
5362
  body: JSON.stringify({
4544
5363
  scope: opts.scope,
4545
5364
  ...opts.sessionId ? { sessionId: opts.sessionId } : {},
5365
+ ...opts.scope === "session" ? { runtimeSessionId: opts.runtimeSessionId } : {},
4546
5366
  ...opts.ttlMinutes ? { ttlMinutes: opts.ttlMinutes } : {}
4547
5367
  })
4548
5368
  });
@@ -4590,8 +5410,17 @@ var SandboxInstance = class SandboxInstance {
4590
5410
  }
4591
5411
  }
4592
5412
  /** @internal — invoked by SandboxSession.result(). */
4593
- async _sessionResult(id) {
5413
+ async _sessionResult(id, knownSession) {
4594
5414
  const startTime = Date.now();
5415
+ const session = knownSession ?? await this._sessionStatus(id);
5416
+ if (!session) throw new NotFoundError("Session", id, {
5417
+ origin: "runtime",
5418
+ endpoint: `/agents/sessions/${encodeURIComponent(id)}`
5419
+ });
5420
+ if (!session.latestExecutionId) throw new StateError(`Session ${id} has no execution result to await`, session.status, "session with an admitted execution", {
5421
+ origin: "runtime",
5422
+ endpoint: `/agents/sessions/${encodeURIComponent(id)}`
5423
+ }, "SESSION_EXECUTION_MISSING");
4595
5424
  let response;
4596
5425
  let runError;
4597
5426
  let runErrorCode;
@@ -4602,7 +5431,10 @@ var SandboxInstance = class SandboxInstance {
4602
5431
  let question;
4603
5432
  let plan;
4604
5433
  let terminalReached = false;
4605
- for await (const event of this._sessionEvents(id, void 0, true)) {
5434
+ for await (const event of this._sessionEvents(id, {
5435
+ since: "0",
5436
+ executionId: session.latestExecutionId
5437
+ }, true)) {
4606
5438
  response = applySandboxEventText(response, event);
4607
5439
  if (event.type === "result" || event.type === "done") {
4608
5440
  const data = event.data;
@@ -4692,6 +5524,102 @@ var SandboxInstance = class SandboxInstance {
4692
5524
  throw parseErrorResponse(response.status, body, void 0, response.headers);
4693
5525
  }
4694
5526
  }
5527
+ /** @internal — invoked by InteractiveSessionHandle.status(). */
5528
+ async _interactiveStatus(id) {
5529
+ await this.ensureRunning();
5530
+ const response = await this.runtimeFetch(`/agents/sessions/${encodeURIComponent(id)}/interactive`, { method: "GET" });
5531
+ if (response.status === 404) return null;
5532
+ if (!response.ok) {
5533
+ const body = await response.text();
5534
+ throw parseErrorResponse(response.status, body, void 0, response.headers);
5535
+ }
5536
+ const data = (await response.json())?.data;
5537
+ if (!data || data.state !== "running" && data.state !== "exited") throw new ServerError("Interactive status response missing data", 502, {
5538
+ endpoint: `/agents/sessions/${encodeURIComponent(id)}/interactive`,
5539
+ origin: "runtime"
5540
+ });
5541
+ return data;
5542
+ }
5543
+ /**
5544
+ * @internal Test seam: unit tests replace this to intercept terminal
5545
+ * WebSocket dials without opening a real socket. Production paths always
5546
+ * go through `TerminalStream.connect`.
5547
+ */
5548
+ _terminalStreamConnect = (options) => TerminalStream.connect(options);
5549
+ /**
5550
+ * Resolve a sandbox-relative terminal stream path against the browser-safe
5551
+ * sidecar proxy base returned by the scoped-token mint. Concatenation, not
5552
+ * URL resolution: the proxy base carries a path prefix
5553
+ * (`/v1/sidecar-proxy/{id}`) that `new URL(absolutePath, base)` would drop.
5554
+ */
5555
+ resolveTerminalStreamUrl(sidecarProxyUrl, streamPath) {
5556
+ if (!streamPath.startsWith("/")) throw new ServerError(`Terminal stream path must be sandbox-relative (got "${streamPath}")`, 502, { origin: "runtime" });
5557
+ return `${sidecarProxyUrl.replace(/\/+$/, "")}${streamPath}`;
5558
+ }
5559
+ /** @internal — invoked by InteractiveSessionHandle.attach(). */
5560
+ async _attachInteractive(id, options = {}) {
5561
+ const status = await this._interactiveStatus(id);
5562
+ if (!status) throw new NotFoundError("Interactive session", id, {
5563
+ origin: "runtime",
5564
+ endpoint: `/agents/sessions/${encodeURIComponent(id)}/interactive`
5565
+ });
5566
+ if (status.state !== "running") throw new StateError(`Interactive session ${id} has exited; there is no live PTY to attach`, status.state, "running", {
5567
+ origin: "runtime",
5568
+ endpoint: `/agents/sessions/${encodeURIComponent(id)}/interactive`
5569
+ }, "INTERACTIVE_SESSION_EXITED");
5570
+ const scoped = await this.mintScopedToken({
5571
+ scope: "session-runtime",
5572
+ sessionId: id
5573
+ });
5574
+ return this._terminalStreamConnect({
5575
+ url: this.resolveTerminalStreamUrl(scoped.sidecarProxyUrl, status.streamUrl),
5576
+ token: this.terminalTokenProvider(scoped.token, id),
5577
+ connectionId: id,
5578
+ cols: options.cols,
5579
+ rows: options.rows,
5580
+ handlers: options.handlers
5581
+ });
5582
+ }
5583
+ /**
5584
+ * Per-dial credential for a terminal attach. The first dial consumes the
5585
+ * token minted alongside the proxy URL (no second mint); every later dial
5586
+ * (a `reconnect()` after the socket dropped or the detach window) re-mints,
5587
+ * because scoped terminal tokens are clamped to a <= 15-minute TTL and the
5588
+ * original is likely dead by then.
5589
+ */
5590
+ terminalTokenProvider(initialToken, sessionId) {
5591
+ let unused = initialToken;
5592
+ return async () => {
5593
+ if (unused !== null) {
5594
+ const token = unused;
5595
+ unused = null;
5596
+ return token;
5597
+ }
5598
+ return (await this.mintScopedToken({
5599
+ scope: "session-runtime",
5600
+ sessionId
5601
+ })).token;
5602
+ };
5603
+ }
5604
+ /** @internal — invoked by `box.terminals.attach()`. */
5605
+ async _attachTerminal(connectionId, options = {}) {
5606
+ if (!connectionId.trim()) throw new ValidationError("Terminal connectionId is required");
5607
+ const scoped = await this.mintScopedToken({
5608
+ scope: "session-runtime",
5609
+ sessionId: connectionId
5610
+ });
5611
+ return this._terminalStreamConnect({
5612
+ url: this.resolveTerminalStreamUrl(scoped.sidecarProxyUrl, `/terminals/${encodeURIComponent(connectionId)}/ws`),
5613
+ token: this.terminalTokenProvider(scoped.token, connectionId),
5614
+ connectionId,
5615
+ cols: options.cols,
5616
+ rows: options.rows,
5617
+ command: options.command,
5618
+ cwd: options.cwd,
5619
+ env: options.env,
5620
+ handlers: options.handlers
5621
+ });
5622
+ }
4695
5623
  /** @internal — invoked by InteractiveSessionHandle.stop(). */
4696
5624
  async _stopInteractive(id) {
4697
5625
  await this.ensureRunning();
@@ -4829,10 +5757,12 @@ function settleTurnDrive(result) {
4829
5757
  state: "failed",
4830
5758
  error: typeof result.error === "string" && result.error.length > 0 ? result.error : `turn ${status}`
4831
5759
  };
5760
+ const usage = readTokenUsage(result);
4832
5761
  return {
4833
5762
  state: "completed",
4834
5763
  text: text ?? "",
4835
- result
5764
+ result,
5765
+ ...usage ? { usage } : {}
4836
5766
  };
4837
5767
  }
4838
5768
  var DirectRuntimeHttpClient = class {
@@ -4901,4 +5831,4 @@ function quoteForShell(value) {
4901
5831
  return `'${value.replace(/'/g, "'\\''")}'`;
4902
5832
  }
4903
5833
  //#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 };
5834
+ 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 };