@tangle-network/sandbox 0.60.78-develop.20261017090901.9326d18 → 0.60.78-develop.20261021201434.3bcd5ef

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +61 -0
  2. package/dist/agent/index.d.ts +4 -4
  3. package/dist/agent/index.js +5 -5
  4. package/dist/agent/preview.d.ts +1 -1
  5. package/dist/agent/preview.js +2 -2
  6. package/dist/{agent-run-outcome-CTEpjCEZ.d.ts → agent-run-outcome-brwJbH5S.d.ts} +1 -1
  7. package/dist/auth/index.d.ts +2 -2
  8. package/dist/auth/index.js +5 -5
  9. package/dist/{backend-types-D6bYbvMB.js → backend-types-CLvdSX8V.js} +41 -1
  10. package/dist/{browser-interactive-control-controller-rpTbyvAS.d.ts → browser-interactive-control-controller-CvObO_Kf.d.ts} +1 -1
  11. package/dist/{browser-interactive-control-controller-BJf0P_J4.js → browser-interactive-control-controller-DHx53yre.js} +16 -1
  12. package/dist/{chunked-upload-DtIvkKNo.js → chunked-upload-DN2twsUu.js} +2 -59
  13. package/dist/{chunked-upload-file-DnsHEjg0.js → chunked-upload-file-Dpv1YsoA.js} +2 -1
  14. package/dist/{cli-auth-bundle-cSJjPeFF.js → cli-auth-bundle-CFeHsq-5.js} +23 -11
  15. package/dist/{client-R1tw-4Px.js → client-CgtR203z.js} +3349 -3341
  16. package/dist/client-Dr8qasCR.d.ts +6076 -0
  17. package/dist/collaboration/index.d.ts +1 -1
  18. package/dist/collaboration/index.js +1 -1
  19. package/dist/{collaboration-DaJU5O0E.js → collaboration-g_HzXa6f.js} +5 -5
  20. package/dist/core.d.ts +7 -7
  21. package/dist/core.js +7 -6
  22. package/dist/direct-http2-Dar5erTH.js +99 -0
  23. package/dist/{errors-DSJBKmGZ.js → errors-BfbOP_rx.js} +171 -22
  24. package/dist/{index-DO7GVpk_.d.ts → index-C8VSFtWl.d.ts} +1 -1
  25. package/dist/{index-DZ27pdB8.d.ts → index-CVjTnRWP.d.ts} +1 -1
  26. package/dist/{sandbox-CoIGxzm_.d.ts → index-D5dVNm76.d.ts} +2117 -1519
  27. package/dist/index.d.ts +12 -4704
  28. package/dist/index.js +40 -15
  29. package/dist/intelligence/index.js +1 -1
  30. package/dist/interactive-control.d.ts +1 -1
  31. package/dist/interactive-control.js +1 -1
  32. package/dist/{interactive-controller-CJ24g8Va.js → interactive-controller-OAsASPd_.js} +662 -620
  33. package/dist/interactive-controller-nMhGqXxq.d.ts +41 -0
  34. package/dist/keep-alive-fetch-BBzJDWyt.js +247 -0
  35. package/dist/{lines-DodQslsf.d.ts → lines-C5CPSg8n.d.ts} +21 -17
  36. package/dist/lines-C5ER4aN_.js +298 -0
  37. package/dist/lines.d.ts +1 -1
  38. package/dist/lines.js +1 -295
  39. package/dist/{local-cli-auth-CBV7Vjk5.js → local-cli-auth-D-CQ0-ub.js} +1 -1
  40. package/dist/{mcp-local-DjryqUiY.js → mcp-local-BjLG7VHY.js} +1 -1
  41. package/dist/{preview-wpGGk0bu.d.ts → preview-COO7TSBk.d.ts} +3 -3
  42. package/dist/public-templates-BDrchm0J.d.ts +80 -0
  43. package/dist/public-templates.d.ts +2 -0
  44. package/dist/public-templates.js +173 -0
  45. package/dist/{raw-evidence-archive-Br5a3xZ_.js → raw-evidence-archive-CDYDqHNv.js} +161 -69
  46. package/dist/runtime.d.ts +49 -41
  47. package/dist/runtime.js +8 -8
  48. package/dist/{sandbox-C7Tk62qn.js → sandbox-BrZxAq11.js} +9048 -8939
  49. package/dist/{secp256k1-Dx2XABHz.js → secp256k1-CmLpsmWl.js} +1 -1
  50. package/dist/session-gateway/index.d.ts +23 -67
  51. package/dist/session-gateway/index.js +578 -451
  52. package/dist/tangle/index.d.ts +1 -1
  53. package/dist/tangle/index.js +1 -1
  54. package/dist/{tangle-Ba4Kz5zT.js → tangle-GiPBak5X.js} +176 -169
  55. package/dist/terminal-stream-types-ClZCArRg.d.ts +662 -0
  56. package/dist/{types-B_QF-iHm.d.ts → types-CtH0GRql.d.ts} +6161 -5812
  57. package/package.json +12 -7
  58. package/dist/client-Lhxo82x1.d.ts +0 -1261
  59. package/dist/errors-mPL-qvgF.d.ts +0 -347
  60. package/dist/index-DRto9Ijb.d.ts +0 -579
  61. package/dist/managed-process-B7WfqKmi.d.ts +0 -15
  62. package/dist/terminal-stream-jdYomM1m.d.ts +0 -389
  63. /package/dist/{cli-auth-bundle-ODe06Ts7.d.ts → cli-auth-bundle-Dyw3hCGx.d.ts} +0 -0
  64. /package/dist/{line-application-Cq6dJLBD.js → line-application-DY9ZTdgF.js} +0 -0
  65. /package/dist/{preview-operations-DqSo-IBm.js → preview-operations-Ca02vPDJ.js} +0 -0
  66. /package/dist/{utils-B7_9Hl_z.js → utils-BGvM02yJ.js} +0 -0
@@ -1,9 +1,160 @@
1
- import { r as backendTypeSchema } from "./backend-types-D6bYbvMB.js";
2
- import { S as parseResponseError, b as ValidationError, g as ServerError, h as SandboxError, r as CapabilityError, u as NetworkError } from "./errors-DSJBKmGZ.js";
3
- import { c as assertInteractiveSessionRef, d as awaitWithAbort, f as combineAbortSignals, i as createBrowserInteractiveSessionControlTransport, o as InteractiveSessionControlController, r as browserInteractiveTerminalEndpoint } from "./browser-interactive-control-controller-BJf0P_J4.js";
4
- import { s as uploadChunked } from "./chunked-upload-DtIvkKNo.js";
1
+ import { a as normalizeEffectiveBackend, r as backendTypeSchema } from "./backend-types-CLvdSX8V.js";
2
+ import { T as ValidationError, b as SandboxError, m as NetworkError, r as parseResponseError, s as CapabilityError, t as TerminalStreamError, x as ServerError } from "./errors-BfbOP_rx.js";
3
+ import { c as assertInteractiveSessionRef, d as awaitWithAbort, f as combineAbortSignals, i as createBrowserInteractiveSessionControlTransport, o as InteractiveSessionControlController, r as browserInteractiveTerminalEndpoint } from "./browser-interactive-control-controller-DHx53yre.js";
4
+ import { s as uploadChunked } from "./chunked-upload-DN2twsUu.js";
5
5
  import { z } from "zod";
6
6
  import { AgentExactRunControlRefSchema, AgentExecutionOutcomeSchema, AgentInteractiveSessionAttachSchema, AgentInteractiveSessionControlClaimSchema, AgentInteractiveSessionRefSchema, AgentRuntimeAttachmentsSchema, DurablePlanSchema, InteractionRequestSchema, PlanContinuationSchema, agentInteractiveSessionControlClaimMatchesRef, agentProfileSchema, canonicalCandidateDigest } from "@tangle-network/agent-interface";
7
+ const TERMINAL_WS_MAX_DIMENSION = 4096;
8
+ /** Input chunk size that leaves room for JSON escaping inside one frame. */
9
+ const TERMINAL_WS_INPUT_FRAME_CHUNK_CHARS = 128 * 1024;
10
+ /** WebSocket authentication envelope prefixes. */
11
+ const TERMINAL_WS_EDGE_BEARER_SUBPROTOCOL_PREFIX = "bearer.";
12
+ const TERMINAL_WS_SIDECAR_BEARER_SUBPROTOCOL_PREFIX = "tangle.bearer.";
13
+ /** Non-credential protocol selected during a successful terminal handshake. */
14
+ const TERMINAL_WS_ECHO_SUBPROTOCOL = "tangle.terminal.v1";
15
+ /**
16
+ * Encode the upgrade URL's query (no leading `?`): the size of a
17
+ * default-shell attach with its flag, and the trace id. Nothing else rides the
18
+ * URL.
19
+ */
20
+ function encodeTerminalUpgradeQuery(input) {
21
+ const params = new URLSearchParams();
22
+ if (input.defaultShell !== void 0) {
23
+ params.set("cols", String(input.defaultShell.cols));
24
+ params.set("rows", String(input.defaultShell.rows));
25
+ params.set("defaultShell", "1");
26
+ }
27
+ if (input.traceId !== void 0) params.set("traceId", input.traceId);
28
+ return params.toString();
29
+ }
30
+ const terminalGeometry = {
31
+ cols: z.number().int().min(1).max(TERMINAL_WS_MAX_DIMENSION),
32
+ rows: z.number().int().min(1).max(TERMINAL_WS_MAX_DIMENSION)
33
+ };
34
+ const terminalInitMessageSchema = z.object({
35
+ type: z.literal("init"),
36
+ connectionId: z.string().optional(),
37
+ /** Required for an interactive-agent PTY; absent for generic terminals. */
38
+ incarnationId: z.string().uuid().optional(),
39
+ ...terminalGeometry,
40
+ command: z.string().min(1).optional(),
41
+ cwd: z.string().min(1).optional(),
42
+ env: z.record(z.string(), z.string()).optional(),
43
+ sessionId: z.string().min(1).optional(),
44
+ /** Canonical control claim for an interactive-agent PTY. */
45
+ control: AgentInteractiveSessionControlClaimSchema.optional(),
46
+ /**
47
+ * Caller trace id for a browser, which cannot set `x-tangle-trace-id` on
48
+ * the upgrade. The server adopts it only when it is a well-formed id.
49
+ */
50
+ traceId: z.string().max(200).optional()
51
+ }).superRefine((message, refinement) => {
52
+ if (message.incarnationId !== void 0 && message.control === void 0) refinement.addIssue({
53
+ code: "custom",
54
+ path: ["control"],
55
+ message: "Interactive session attach requires a control claim"
56
+ });
57
+ if (message.incarnationId === void 0 && message.control !== void 0) refinement.addIssue({
58
+ code: "custom",
59
+ path: ["control"],
60
+ message: "Generic terminal attach cannot carry an interactive control claim"
61
+ });
62
+ });
63
+ const terminalInputMessageSchema = z.object({
64
+ type: z.literal("input"),
65
+ data: z.string()
66
+ });
67
+ const terminalResizeMessageSchema = z.object({
68
+ type: z.literal("resize"),
69
+ ...terminalGeometry
70
+ });
71
+ const terminalRenewMessageSchema = z.object({ type: z.literal("renew") });
72
+ const terminalCloseMessageSchema = z.object({ type: z.literal("close") });
73
+ z.union([
74
+ terminalInitMessageSchema,
75
+ terminalInputMessageSchema,
76
+ terminalResizeMessageSchema,
77
+ terminalRenewMessageSchema,
78
+ terminalCloseMessageSchema
79
+ ]);
80
+ /**
81
+ * Server stamps for one attach, in epoch milliseconds on the sidecar's clock.
82
+ * They are absolute so a caller can lay them against its own marks and read
83
+ * each leg (client clock skew is the only error). `spawn*` and `initPersistAt`
84
+ * are absent when the attach adopted a PTY that already existed.
85
+ */
86
+ const terminalReadyTimingsSchema = z.object({
87
+ /** The upgrade request reached the sidecar's upgrade handler. */
88
+ upgradeAt: z.number(),
89
+ /** The bearer was verified (`ws.auth` ends). */
90
+ authAt: z.number(),
91
+ /** The init parameters were in hand: at the upgrade for `via: "upgrade"`, on the init frame otherwise. */
92
+ initAt: z.number(),
93
+ /** `loadOrCreateConnection` started. */
94
+ loadAt: z.number(),
95
+ /** The PTY process was spawned (`pty.spawn` ends). */
96
+ spawnAt: z.number().optional(),
97
+ /** The `session.init` event was persisted (`session.init.persist` ends). */
98
+ initPersistAt: z.number().optional(),
99
+ /** `loadOrCreateConnection` returned. */
100
+ loadedAt: z.number(),
101
+ /** The retained history was read (`history.read` ends). */
102
+ historyAt: z.number(),
103
+ /** Retained events and bytes the replay will carry. */
104
+ historyEvents: z.number().int().nonnegative(),
105
+ historyBytes: z.number().int().nonnegative(),
106
+ /** The `ready` frame was sent. */
107
+ readyAt: z.number(),
108
+ /** How the init parameters reached the server. */
109
+ via: z.enum(["upgrade", "frame"]),
110
+ /** Correlation id of this attach (`terminal_attach` spans share it). */
111
+ ptid: z.string().optional()
112
+ });
113
+ const terminalReadyMessageSchema = z.object({
114
+ type: z.literal("ready"),
115
+ connectionId: z.string(),
116
+ sessionId: z.string(),
117
+ restored: z.boolean(),
118
+ detachTimeoutMs: z.number().int().positive(),
119
+ /** Exact viewer count held by the runtime for this connection. */
120
+ attachCount: z.number().int().positive().optional(),
121
+ /** Server-issued output cursor window for exact interactive terminals. */
122
+ cursors: z.object({
123
+ earliest: z.number().int().nonnegative(),
124
+ latest: z.number().int().nonnegative()
125
+ }).optional(),
126
+ /** Server stamps for this attach; absent from a sidecar that predates them. */
127
+ timings: terminalReadyTimingsSchema.optional()
128
+ });
129
+ /** One sequenced output frame for an exact interactive terminal. */
130
+ const terminalOutputMessageSchema = z.object({
131
+ type: z.literal("output"),
132
+ seq: z.number().int().positive(),
133
+ /** Base64-encoded UTF-8 bytes from the retained terminal event. */
134
+ data: z.string().min(1)
135
+ });
136
+ const terminalExitMessageSchema = z.object({
137
+ type: z.literal("exit"),
138
+ exitCode: z.number().optional(),
139
+ exitSignal: z.string().optional()
140
+ });
141
+ const terminalRenewedMessageSchema = z.object({
142
+ type: z.literal("renewed"),
143
+ sessionId: z.string()
144
+ });
145
+ const terminalErrorMessageSchema = z.object({
146
+ type: z.literal("error"),
147
+ code: z.string(),
148
+ message: z.string()
149
+ });
150
+ const terminalServerMessageSchema = z.union([
151
+ terminalReadyMessageSchema,
152
+ terminalOutputMessageSchema,
153
+ terminalExitMessageSchema,
154
+ terminalRenewedMessageSchema,
155
+ terminalErrorMessageSchema
156
+ ]);
157
+ //#endregion
7
158
  //#region src/agent-run-outcome-inspection.ts
8
159
  const HUB_APPROVAL_REQUIRED = "HUB_APPROVAL_REQUIRED";
9
160
  const MAX_SERIALIZED_TOOL_VALUE_BYTES = 4 * 1024 * 1024;
@@ -569,7 +720,8 @@ const ROLE_NAMED_MODEL_FIELDS = [
569
720
  "apiKeyEnv",
570
721
  "cliAuth",
571
722
  "authMode",
572
- "authFiles"
723
+ "authFiles",
724
+ "routing"
573
725
  ];
574
726
  function sameRoutingValue(left, right) {
575
727
  if (Object.is(left, right)) return true;
@@ -590,7 +742,8 @@ function foldModelRoutingFields(backend) {
590
742
  ...backend.apiKeyEnv !== void 0 ? { apiKeyEnv: backend.apiKeyEnv } : {},
591
743
  ...backend.cliAuth !== void 0 ? { cliAuth: backend.cliAuth } : {},
592
744
  ...backend.authMode !== void 0 ? { authMode: backend.authMode } : {},
593
- ...backend.authFiles !== void 0 ? { authFiles: backend.authFiles } : {}
745
+ ...backend.authFiles !== void 0 ? { authFiles: backend.authFiles } : {},
746
+ ...backend.routing !== void 0 ? { routing: backend.routing } : {}
594
747
  };
595
748
  if (Object.keys(flat).length === 0) return backend;
596
749
  const rest = { ...backend };
@@ -678,6 +831,7 @@ function withoutRuntimeSecrets(backend) {
678
831
  function normalizeRuntimeBackendConfig(backendInput, options = {}) {
679
832
  const backend = foldModelRoutingFields(backendInput);
680
833
  if (!backend) return void 0;
834
+ if (backend.model?.routing !== void 0 && !options.allowRouting) throw new ValidationError("backend.routing is set at sandbox creation only; turns, sessions and fleet runs use the routing the sandbox was created with");
681
835
  const continuation = backendInput?.planContinuation;
682
836
  if (continuation !== void 0 && !options.allowPlanContinuation) throw new ValidationError("backend.planContinuation is turn-only; session creation and persistence cannot carry it");
683
837
  if (continuation !== void 0 && !PlanContinuationSchema.safeParse(continuation).success) throw new ValidationError("backend.planContinuation is invalid");
@@ -708,6 +862,23 @@ function normalizeRuntimeBackendConfig(backendInput, options = {}) {
708
862
  ...backend?.metadata !== void 0 ? { metadata: backend.metadata } : {}
709
863
  };
710
864
  }
865
+ /**
866
+ * The backend a created sandbox keeps as its per-turn defaults: `routing` is
867
+ * consumed by the create (the box env carries it), so a turn never resends it.
868
+ * A turn that carried it would also change the public profile digest the
869
+ * sidecar recomputes after stripping unknown model fields.
870
+ */
871
+ function withoutCreateOnlyModelFields(backend) {
872
+ if (!backend) return backend;
873
+ if (backend.routing === void 0 && backend.model?.routing === void 0) return backend;
874
+ const { routing: _flat, ...rest } = backend;
875
+ if (!rest.model) return rest;
876
+ const { routing: _nested, ...model } = rest.model;
877
+ return {
878
+ ...rest,
879
+ model
880
+ };
881
+ }
711
882
  /** Digest the exact public backend payload the SDK sends for a profile turn. */
712
883
  function requestedPublicProfileDigest(backend) {
713
884
  return publicProfileRequestDigest(normalizeRuntimeBackendConfig(backend, {
@@ -723,6 +894,101 @@ function requestedSecretProfilePublicDigest(backend) {
723
894
  }) ?? {});
724
895
  }
725
896
  //#endregion
897
+ //#region src/lib/runtime-env.ts
898
+ /**
899
+ * True inside a Cloudflare Worker. Under `nodejs_compat` workerd sets
900
+ * `process.versions.node`, but it ships `node:http2` as a stub whose `connect()`
901
+ * throws "The http2.connect method is not implemented", so `process.versions`
902
+ * cannot tell a Worker from Node. The user agent can.
903
+ */
904
+ function isCloudflareWorker() {
905
+ return globalThis.navigator?.userAgent?.startsWith("Cloudflare-Workers") === true;
906
+ }
907
+ /** True where `node:http2` can open a session: Node, but not a Worker. */
908
+ function canUseNodeHttp2() {
909
+ return typeof process !== "undefined" && typeof process.versions?.node === "string" && !isCloudflareWorker();
910
+ }
911
+ //#endregion
912
+ //#region src/lib/wire-encoding.ts
913
+ /**
914
+ * Encode a prompt text part for the wire. Server decodes at the route
915
+ * boundary; the LLM only ever sees the original UTF-8. Done
916
+ * unconditionally because readable bodies false-positive on ingress WAF
917
+ * rules that pattern-match shell-injection-shaped substrings (which
918
+ * legitimate prompts routinely contain — e.g. Step-0 dev-server
919
+ * bootstrap).
920
+ */
921
+ function encodeTextForWire(text) {
922
+ if (typeof Buffer !== "undefined") return Buffer.from(text, "utf8").toString("base64");
923
+ if (typeof btoa === "function") return btoa(encodeURIComponent(text).replace(/%([0-9A-F]{2})/g, (_, h) => String.fromCharCode(Number.parseInt(h, 16))));
924
+ throw new Error("encodeTextForWire: no base64 encoder available (Buffer and btoa both undefined)");
925
+ }
926
+ /**
927
+ * Convert a caller-supplied prompt (string or parts array) into the
928
+ * wire-format parts array. Every text part is base64-encoded; non-text
929
+ * parts pass through. A bare string is wrapped in a single text part.
930
+ */
931
+ function encodePromptForWire(message) {
932
+ return (typeof message === "string" ? [{
933
+ type: "text",
934
+ text: message
935
+ }] : message).map((part) => part.type === "text" ? {
936
+ type: "text",
937
+ text: encodeTextForWire(part.text)
938
+ } : part);
939
+ }
940
+ //#endregion
941
+ //#region src/dispatch-run-control.ts
942
+ const DISPATCH_RUN_PROVIDER = "tangle-sandbox";
943
+ function generateRuntimeId(prefix) {
944
+ const crypto = globalThis.crypto;
945
+ if (crypto?.randomUUID) return `${prefix}-${crypto.randomUUID()}`;
946
+ if (crypto?.getRandomValues) {
947
+ const bytes = crypto.getRandomValues(new Uint8Array(16));
948
+ return `${prefix}-${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
949
+ }
950
+ throw new ValidationError("Run identity generation requires global crypto");
951
+ }
952
+ function resolveDispatchRunIdentity(sandboxId, message, options) {
953
+ const sessionId = options?.sessionId ?? options?.runControlRef?.sessionId ?? generateRuntimeId("session");
954
+ const executionId = options?.executionId ?? options?.runControlRef?.executionId ?? generateRuntimeId("execution");
955
+ return {
956
+ sessionId,
957
+ executionId,
958
+ runControlRef: options?.runControlRef ?? {
959
+ runId: generateRuntimeId("run"),
960
+ provider: DISPATCH_RUN_PROVIDER,
961
+ environmentId: sandboxId,
962
+ sessionId,
963
+ executionId,
964
+ requestDigest: canonicalCandidateDigest({
965
+ message,
966
+ sessionId,
967
+ turnId: options?.turnId ?? null,
968
+ backend: options?.backend ?? null,
969
+ model: options?.model ?? null,
970
+ context: options?.context ?? null
971
+ })
972
+ }
973
+ };
974
+ }
975
+ function sameExactRunControlRef(left, right) {
976
+ return left.runId === right.runId && left.provider === right.provider && left.environmentId === right.environmentId && left.sessionId === right.sessionId && left.executionId === right.executionId && left.requestDigest === right.requestDigest;
977
+ }
978
+ function validateAcceptedDispatchRunRef(raw, expected, sandboxId, sessionId, executionId, endpoint = "/agents/run/stream") {
979
+ const parsed = AgentExactRunControlRefSchema.safeParse(raw);
980
+ if (!parsed.success) throw new ServerError("Sandbox returned an invalid exact run reference on admission", 502, {
981
+ origin: "runtime",
982
+ endpoint
983
+ });
984
+ const accepted = parsed.data;
985
+ if (accepted.environmentId !== sandboxId || accepted.sessionId !== sessionId || accepted.executionId !== executionId || !sameExactRunControlRef(accepted, expected)) throw new ServerError("Sandbox returned an exact run reference for another execution", 502, {
986
+ origin: "runtime",
987
+ endpoint
988
+ });
989
+ return accepted;
990
+ }
991
+ //#endregion
726
992
  //#region ../../../packages/sse-core/dist/index.js
727
993
  /**
728
994
  * A copy of `value` that shares no memory with the string it was cut from.
@@ -735,6 +1001,20 @@ function detached(value) {
735
1001
  return value === "" ? value : JSON.parse(JSON.stringify(value));
736
1002
  }
737
1003
  /**
1004
+ * Thrown when a stream sends no bytes for longer than its `idleMs`. A
1005
+ * producer that heartbeats would have written in that time, so the
1006
+ * connection is dead even though it never closed: a half-open TCP connection
1007
+ * or a stalled proxy hold the socket open while nothing arrives.
1008
+ */
1009
+ var SSEStreamSilentError = class extends Error {
1010
+ name = "SSEStreamSilentError";
1011
+ idleMs;
1012
+ constructor(idleMs) {
1013
+ super(`SSE stream sent no bytes for ${idleMs} ms`);
1014
+ this.idleMs = idleMs;
1015
+ }
1016
+ };
1017
+ /**
738
1018
  * Incremental SSE frame parser. Feed decoded text via `push()`; call
739
1019
  * `flush()` when the stream ends.
740
1020
  */
@@ -829,12 +1109,20 @@ async function* streamSSEFrames(body, options) {
829
1109
  const reader = body.getReader();
830
1110
  const decoder = new TextDecoder();
831
1111
  const parser = new SSEFrameParser();
832
- const { signal } = options ?? {};
1112
+ const { signal, idleMs } = options ?? {};
1113
+ const read = () => {
1114
+ const limit = idleMs?.();
1115
+ if (limit === void 0) return reader.read();
1116
+ let timer;
1117
+ return Promise.race([reader.read(), new Promise((_, reject) => {
1118
+ timer = setTimeout(() => reject(new SSEStreamSilentError(limit)), limit);
1119
+ })]).finally(() => clearTimeout(timer));
1120
+ };
833
1121
  let completed = false;
834
1122
  try {
835
1123
  for (;;) {
836
1124
  if (signal?.aborted) throw new DOMException("SSE stream aborted", "AbortError");
837
- const { done, value } = await reader.read();
1125
+ const { done, value } = await read();
838
1126
  if (done) {
839
1127
  if (signal?.aborted) throw new DOMException("SSE stream aborted", "AbortError");
840
1128
  break;
@@ -896,8 +1184,11 @@ async function* streamSSEFrames(body, options) {
896
1184
  * @throws `DOMException` with `name === "AbortError"` on cancellation.
897
1185
  */
898
1186
  async function* parseSSEStream(body, options) {
899
- const { signal, invalidEvent = "throw" } = options ?? {};
900
- for await (const frame of streamSSEFrames(body, { signal })) {
1187
+ const { signal, invalidEvent = "throw", idleMs } = options ?? {};
1188
+ for await (const frame of streamSSEFrames(body, {
1189
+ signal,
1190
+ idleMs
1191
+ })) {
901
1192
  const effectiveEvent = frame.event || "message";
902
1193
  let data;
903
1194
  try {
@@ -924,104 +1215,7 @@ async function* parseSSEStream(body, options) {
924
1215
  }
925
1216
  }
926
1217
  //#endregion
927
- //#region src/lib/wire-encoding.ts
928
- /**
929
- * Encode a prompt text part for the wire. Server decodes at the route
930
- * boundary; the LLM only ever sees the original UTF-8. Done
931
- * unconditionally because readable bodies false-positive on ingress WAF
932
- * rules that pattern-match shell-injection-shaped substrings (which
933
- * legitimate prompts routinely contain — e.g. Step-0 dev-server
934
- * bootstrap).
935
- */
936
- function encodeTextForWire(text) {
937
- if (typeof Buffer !== "undefined") return Buffer.from(text, "utf8").toString("base64");
938
- if (typeof btoa === "function") return btoa(encodeURIComponent(text).replace(/%([0-9A-F]{2})/g, (_, h) => String.fromCharCode(Number.parseInt(h, 16))));
939
- throw new Error("encodeTextForWire: no base64 encoder available (Buffer and btoa both undefined)");
940
- }
941
- /**
942
- * Convert a caller-supplied prompt (string or parts array) into the
943
- * wire-format parts array. Every text part is base64-encoded; non-text
944
- * parts pass through. A bare string is wrapped in a single text part.
945
- */
946
- function encodePromptForWire(message) {
947
- return (typeof message === "string" ? [{
948
- type: "text",
949
- text: message
950
- }] : message).map((part) => part.type === "text" ? {
951
- type: "text",
952
- text: encodeTextForWire(part.text)
953
- } : part);
954
- }
955
- //#endregion
956
- //#region src/dispatch-run-control.ts
957
- const DISPATCH_RUN_PROVIDER = "tangle-sandbox";
958
- function generateRuntimeId(prefix) {
959
- const crypto = globalThis.crypto;
960
- if (crypto?.randomUUID) return `${prefix}-${crypto.randomUUID()}`;
961
- if (crypto?.getRandomValues) {
962
- const bytes = crypto.getRandomValues(new Uint8Array(16));
963
- return `${prefix}-${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
964
- }
965
- throw new ValidationError("Run identity generation requires global crypto");
966
- }
967
- function resolveDispatchRunIdentity(sandboxId, message, options) {
968
- const sessionId = options?.sessionId ?? options?.runControlRef?.sessionId ?? generateRuntimeId("session");
969
- const executionId = options?.executionId ?? options?.runControlRef?.executionId ?? generateRuntimeId("execution");
970
- return {
971
- sessionId,
972
- executionId,
973
- runControlRef: options?.runControlRef ?? {
974
- runId: generateRuntimeId("run"),
975
- provider: DISPATCH_RUN_PROVIDER,
976
- environmentId: sandboxId,
977
- sessionId,
978
- executionId,
979
- requestDigest: canonicalCandidateDigest({
980
- message,
981
- sessionId,
982
- turnId: options?.turnId ?? null,
983
- backend: options?.backend ?? null,
984
- model: options?.model ?? null,
985
- context: options?.context ?? null
986
- })
987
- }
988
- };
989
- }
990
- function sameExactRunControlRef(left, right) {
991
- return left.runId === right.runId && left.provider === right.provider && left.environmentId === right.environmentId && left.sessionId === right.sessionId && left.executionId === right.executionId && left.requestDigest === right.requestDigest;
992
- }
993
- function validateAcceptedDispatchRunRef(raw, expected, sandboxId, sessionId, executionId, endpoint = "/agents/run/stream") {
994
- const parsed = AgentExactRunControlRefSchema.safeParse(raw);
995
- if (!parsed.success) throw new ServerError("Sandbox returned an invalid exact run reference on admission", 502, {
996
- origin: "runtime",
997
- endpoint
998
- });
999
- const accepted = parsed.data;
1000
- if (accepted.environmentId !== sandboxId || accepted.sessionId !== sessionId || accepted.executionId !== executionId || !sameExactRunControlRef(accepted, expected)) throw new ServerError("Sandbox returned an exact run reference for another execution", 502, {
1001
- origin: "runtime",
1002
- endpoint
1003
- });
1004
- return accepted;
1005
- }
1006
- //#endregion
1007
- //#region src/lib/session-id.ts
1008
- const SESSION_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;
1009
- function assertValidSessionId(value) {
1010
- if (typeof value !== "string" || !SESSION_ID_PATTERN.test(value)) throw new ValidationError(`Invalid sessionId ${typeof value === "string" ? JSON.stringify(value) : `of type ${typeof value}`}: must match ${SESSION_ID_PATTERN.source}`);
1011
- }
1012
- function sessionHeaders(sessionId) {
1013
- if (sessionId === void 0) return void 0;
1014
- assertValidSessionId(sessionId);
1015
- return { "X-Session-Id": sessionId };
1016
- }
1017
- function appendSessionIdQuery(params, sessionId) {
1018
- if (sessionId === void 0) return false;
1019
- assertValidSessionId(sessionId);
1020
- params.set("sessionId", sessionId);
1021
- return true;
1022
- }
1023
- //#endregion
1024
- //#region src/lib/trace-id.ts
1218
+ //#region src/lib/trace-id.ts
1025
1219
  /**
1026
1220
  * Request header that carries one turn's trace id. The Sandbox API adopts it
1027
1221
  * as the request's correlation id, the orchestrator logs it on every proxied
@@ -1055,11 +1249,22 @@ function resolveTraceId(requested) {
1055
1249
  if (!isTraceId(requested)) throw new ValidationError("traceId must be 8-200 characters of letters, digits, '_' or '-'", { traceId: "Invalid trace id" });
1056
1250
  return requested;
1057
1251
  }
1252
+ /**
1253
+ * The request headers that join one runtime call (exec, read, write, search)
1254
+ * to its turn: the caller's trace id as `x-tangle-trace-id`, validated like a
1255
+ * prompt's. A call without one sends none, so the Sandbox API mints its own as
1256
+ * before. On the API path the Sandbox API adopts it and the orchestrator logs
1257
+ * it; on the direct path the sidecar logs it, so both lanes join the turn.
1258
+ */
1259
+ function traceHeaders(traceId) {
1260
+ if (traceId === void 0) return void 0;
1261
+ return { [TRACE_ID_HEADER]: resolveTraceId(traceId) };
1262
+ }
1058
1263
  //#endregion
1059
- //#region src/runtime-api.ts
1264
+ //#region src/runtime-credential-retry.ts
1060
1265
  /** A 503 the runtime answers before any work starts; the request may be resent. */
1061
1266
  function isRetryableCredentialRefusal(error) {
1062
- return error instanceof SandboxError && error.status === 503 && (error.code === "MODEL_CREDENTIAL_SUPERSEDED" || error.code === "HUB_CREDENTIAL_REFRESH_UNAVAILABLE");
1267
+ return error instanceof SandboxError && error.status === 503 && (error.code === "MODEL_CREDENTIAL_SUPERSEDED" || error.code === "MODEL_CREDENTIAL_PLATFORM_UNAVAILABLE" || error.code === "HUB_CREDENTIAL_REFRESH_UNAVAILABLE");
1063
1268
  }
1064
1269
  function waitForRetryAfter(delayMs, signal) {
1065
1270
  signal?.throwIfAborted();
@@ -1082,8 +1287,26 @@ function waitForRetryAfter(delayMs, signal) {
1082
1287
  signal?.addEventListener("abort", onAbort, { once: true });
1083
1288
  });
1084
1289
  }
1085
- /** Internal typed client for routes served by a sandbox runtime. */
1086
- var SandboxRuntimeApi = class {
1290
+ //#endregion
1291
+ //#region src/lib/session-id.ts
1292
+ const SESSION_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;
1293
+ function assertValidSessionId(value) {
1294
+ if (typeof value !== "string" || !SESSION_ID_PATTERN.test(value)) throw new ValidationError(`Invalid sessionId ${typeof value === "string" ? JSON.stringify(value) : `of type ${typeof value}`}: must match ${SESSION_ID_PATTERN.source}`);
1295
+ }
1296
+ function sessionHeaders(sessionId) {
1297
+ if (sessionId === void 0) return void 0;
1298
+ assertValidSessionId(sessionId);
1299
+ return { "X-Session-Id": sessionId };
1300
+ }
1301
+ function appendSessionIdQuery(params, sessionId) {
1302
+ if (sessionId === void 0) return false;
1303
+ assertValidSessionId(sessionId);
1304
+ params.set("sessionId", sessionId);
1305
+ return true;
1306
+ }
1307
+ //#endregion
1308
+ //#region src/runtime-transport.ts
1309
+ var RuntimeApiTransport = class {
1087
1310
  terminals;
1088
1311
  constructor(transport) {
1089
1312
  this.transport = transport;
@@ -1114,104 +1337,53 @@ var SandboxRuntimeApi = class {
1114
1337
  await this.transport.ensureRunning();
1115
1338
  return (await this.json("/ports", { method: "GET" })).data?.ports ?? [];
1116
1339
  }
1117
- /**
1118
- * Subscribe to a session's agent event stream (`/agents/events`).
1119
- *
1120
- * The consume half of the supervisor pattern: construct the client from a
1121
- * `read-only` or `session-runtime` scoped token
1122
- * (`SandboxInstance.mintScopedToken`) and a parent agent observes a child
1123
- * sandbox's stream while holding no credential that can mutate the child.
1124
- * With `executionId` set, the stream ends at that turn's terminal
1125
- * `done`/`error` event; a stream that dies before the terminal throws
1126
- * instead of reading like a finished turn. Aborting `options.signal` ends
1127
- * the generator cleanly, matching every other SDK stream. Events carry no
1128
- * `data.sandboxId` stamp here: a scoped-token client knows only its own
1129
- * runtime URL, and the subscriber already knows which sandbox it minted
1130
- * the token for.
1131
- */
1132
- async *events(sessionId, options = {}) {
1340
+ async createTerminal(options = {}, request = {}) {
1341
+ const params = new URLSearchParams();
1342
+ appendSessionIdQuery(params, request.sessionId);
1343
+ const query = params.toString();
1133
1344
  await this.transport.ensureRunning();
1134
- const search = new URLSearchParams();
1135
- search.set("sessionId", sessionId);
1136
- if (options.since) search.set("since", options.since);
1137
- if (options.executionId) search.set("executionId", options.executionId);
1138
- const response = await this.request(`/agents/events?${search.toString()}`, { signal: options.signal });
1139
- if (!response.body) throw new NetworkError("event stream has no response body");
1140
- let sawTerminal = false;
1141
- try {
1142
- for await (const event of parseSSEStream(response.body, {
1143
- signal: options.signal,
1144
- invalidEvent: "warn-and-skip"
1145
- })) {
1146
- yield {
1147
- type: event.type,
1148
- data: event.data,
1149
- ...event.id !== void 0 ? { id: event.id } : {}
1150
- };
1151
- if (options.executionId !== void 0 && (event.type === "done" || event.type === "error")) {
1152
- sawTerminal = true;
1153
- return;
1154
- }
1155
- }
1156
- } catch (err) {
1157
- if (err instanceof DOMException && err.name === "AbortError") return;
1158
- throw err;
1159
- }
1160
- if (options.executionId !== void 0 && !sawTerminal) throw new NetworkError("event stream ended before a terminal event — the connection dropped mid-turn");
1345
+ return (await this.json(`/terminals${query ? `?${query}` : ""}`, {
1346
+ method: "POST",
1347
+ body: JSON.stringify(options)
1348
+ })).data;
1161
1349
  }
1162
- /** Read a turn's retained admission without proposing or admitting a message. */
1163
- async admission(sessionId, turnId, options = {}) {
1164
- if (!sessionId.trim() || !turnId.trim()) throw new ValidationError("sessionId and turnId are required");
1350
+ async writeTerminal(terminalId, data, request = {}) {
1351
+ const params = new URLSearchParams();
1352
+ appendSessionIdQuery(params, request.sessionId);
1353
+ const query = params.toString();
1165
1354
  await this.transport.ensureRunning();
1166
- const endpoint = `/agents/sessions/${encodeURIComponent(sessionId)}/admissions/${encodeURIComponent(turnId)}`;
1167
- const payload = await this.json(endpoint, {
1168
- method: "GET",
1169
- signal: options.signal
1170
- });
1171
- if (payload?.receipt === null) return null;
1172
- const receipt = payload?.receipt;
1173
- if (!receipt || typeof receipt.info?.id !== "string" || !receipt.info.id || receipt.processing !== true) throw new ServerError("Runtime returned an invalid message admission receipt", 502, {
1174
- origin: "runtime",
1175
- endpoint
1176
- });
1177
- const parsedRef = receipt.runControlRef === void 0 ? void 0 : AgentExactRunControlRefSchema.safeParse(receipt.runControlRef);
1178
- if (parsedRef && !parsedRef.success) throw new ServerError("Admission returned an invalid exact run reference", 502, {
1179
- origin: "runtime",
1180
- endpoint
1181
- });
1182
- const runControlRef = parsedRef?.data;
1183
- if (runControlRef && (runControlRef.sessionId !== sessionId || runControlRef.executionId !== receipt.info.id)) throw new ServerError("Admission control reference does not match its execution", 502, {
1184
- origin: "runtime",
1185
- endpoint
1355
+ await this.request(`/terminals/${encodeURIComponent(terminalId)}/input${query ? `?${query}` : ""}`, {
1356
+ method: "POST",
1357
+ body: JSON.stringify({ data })
1186
1358
  });
1187
- const run = (await this.runs(sessionId, options)).find((candidate) => candidate.executionId === receipt.info.id);
1188
- return {
1189
- sessionId,
1190
- turnId,
1191
- executionId: receipt.info.id,
1192
- status: run?.status ?? "unavailable",
1193
- ...runControlRef ? { runControlRef } : {}
1194
- };
1195
1359
  }
1196
- /** List validated execution records from the runtime ledger, newest first. */
1197
- async runs(sessionId, options = {}) {
1360
+ async listTerminals() {
1198
1361
  await this.transport.ensureRunning();
1199
- const endpoint = `/agents/sessions/${encodeURIComponent(sessionId)}/runs`;
1200
- const payload = await this.json(endpoint, {
1201
- method: "GET",
1202
- signal: options.signal
1203
- });
1204
- if (payload.success !== true || !Array.isArray(payload.executions)) throw new ServerError("Session runs response has an invalid shape", 502, {
1205
- origin: "runtime",
1206
- endpoint
1207
- });
1208
- const executions = payload.executions.map((value) => normalizeSessionExecutionInfo(value, sessionId));
1209
- if (executions.some((execution) => execution === null)) throw new ServerError("Session runs response has an invalid execution", 502, {
1210
- origin: "runtime",
1211
- endpoint
1212
- });
1213
- return executions.filter((execution) => execution !== null);
1362
+ return (await this.json("/terminals", { method: "GET" })).data ?? [];
1214
1363
  }
1364
+ async getTerminal(terminalId) {
1365
+ await this.transport.ensureRunning();
1366
+ const response = await this.transport.fetch(`/terminals/${encodeURIComponent(terminalId)}`, { method: "GET" });
1367
+ if (response.status === 404) return null;
1368
+ await this.assertOk(response);
1369
+ return (await response.json()).data;
1370
+ }
1371
+ async json(path, init) {
1372
+ return await (await this.request(path, init)).json();
1373
+ }
1374
+ async request(path, init) {
1375
+ const response = await this.transport.fetch(path, init);
1376
+ await this.assertOk(response);
1377
+ return response;
1378
+ }
1379
+ async assertOk(response) {
1380
+ if (response.ok) return;
1381
+ throw await parseResponseError(response);
1382
+ }
1383
+ };
1384
+ //#endregion
1385
+ //#region src/runtime-files.ts
1386
+ var RuntimeFiles = class extends RuntimeApiTransport {
1215
1387
  async readFiles(paths, options = {}) {
1216
1388
  const params = new URLSearchParams();
1217
1389
  appendSessionIdQuery(params, options.sessionId);
@@ -1275,6 +1447,7 @@ var SandboxRuntimeApi = class {
1275
1447
  await this.transport.ensureRunning();
1276
1448
  const payload = await this.json(`/files/write${query ? `?${query}` : ""}`, {
1277
1449
  method: "POST",
1450
+ headers: traceHeaders(options.traceId),
1278
1451
  body: JSON.stringify({
1279
1452
  path,
1280
1453
  content,
@@ -1344,193 +1517,12 @@ var SandboxRuntimeApi = class {
1344
1517
  await this.transport.ensureRunning();
1345
1518
  return (await this.json(`/files/usage?${params}`, { method: "GET" })).data;
1346
1519
  }
1347
- async createSession(options) {
1348
- await this.transport.ensureRunning();
1349
- const backend = normalizeRuntimeBackendConfig(options.backend);
1350
- const info = normalizeSessionInfo(await this.json("/agents/sessions", {
1351
- method: "POST",
1352
- body: JSON.stringify({
1353
- ...options.sessionId !== void 0 ? { sessionId: options.sessionId } : {},
1354
- ...options.title !== void 0 ? { title: options.title } : {},
1355
- ...options.retention !== void 0 ? { retention: options.retention } : {},
1356
- ...options.parentId !== void 0 ? { parentID: options.parentId } : {},
1357
- ...options.workspaceRoot !== void 0 ? { workspaceRoot: options.workspaceRoot } : {},
1358
- ...options.conversationHistory !== void 0 ? { conversationHistory: options.conversationHistory } : {},
1359
- ...options.importFromSessionId !== void 0 ? { importFromSessionId: options.importFromSessionId } : {},
1360
- ...backend && Object.keys(backend).length > 0 ? { backend } : {}
1361
- })
1362
- }));
1363
- if (!info) throw new ServerError("Session creation response missing session id", 502, {
1364
- endpoint: "/agents/sessions",
1365
- origin: "runtime"
1366
- });
1367
- return info;
1368
- }
1369
- async messages(id, options = {}) {
1370
- await this.transport.ensureRunning();
1371
- const params = new URLSearchParams({ sessionId: id });
1372
- if (options.limit !== void 0) params.set("limit", String(options.limit));
1373
- if (options.offset !== void 0) params.set("offset", String(options.offset));
1374
- if (options.since !== void 0) params.set("since", String(options.since));
1375
- const query = params.toString();
1376
- return (await this.json(`/messages${query ? `?${query}` : ""}`, { method: "GET" })).map((message) => ({
1377
- id: message.info.id,
1378
- role: message.info.role,
1379
- timestamp: message.info.timestamp,
1380
- parts: message.parts,
1381
- metadata: message.info.metadata
1382
- }));
1383
- }
1384
- async createTaskSession(options) {
1385
- await this.transport.ensureRunning();
1386
- const info = await this.json("/tasks", {
1387
- method: "POST",
1388
- body: JSON.stringify({
1389
- sessionId: options.sessionId,
1390
- backend: normalizeRuntimeBackendConfig(options.backend),
1391
- title: options.title,
1392
- ...options.parentSessionId !== void 0 ? { parentSessionId: options.parentSessionId } : {},
1393
- ...options.profile !== void 0 ? { profile: options.profile } : {},
1394
- ...options.isolateFileWrites !== void 0 ? { isolateFileWrites: options.isolateFileWrites } : {}
1395
- })
1396
- });
1397
- if (!info.id) throw new ServerError("Task session creation response missing session id", 502, {
1398
- endpoint: "/tasks",
1399
- origin: "runtime"
1400
- });
1401
- return info;
1402
- }
1403
- async sendSessionMessage(id, request, options = {}) {
1404
- if (options.timeoutMs !== void 0 && options.timeoutMs <= 0) throw new ValidationError("timeoutMs must be greater than zero");
1405
- await this.transport.ensureRunning();
1406
- const headers = new Headers({
1407
- "content-type": "application/json",
1408
- "x-no-retry": "true"
1409
- });
1410
- if (options.planFollowUp) {
1411
- if (!request.backend?.planContinuation || !request.expectedPublicProfileRequestDigest || !request.expectedSecretProfileReceipt || !Number.isFinite(Date.parse(options.planFollowUp.expiresAt)) || Date.parse(options.planFollowUp.expiresAt) <= Date.now()) throw new ValidationError("Caller plan follow-up requires current admission and both fresh profile pins");
1412
- headers.set("x-tangle-plan-followup-credential", options.planFollowUp.credential);
1413
- headers.set("x-tangle-plan-followup-callback", options.planFollowUp.callbackUrl);
1414
- }
1415
- if (options.credentials?.apiKey) headers.set("X-Backend-Api-Key", options.credentials.apiKey);
1416
- if (options.credentials?.baseUrl) headers.set("X-Backend-Base-Url", options.credentials.baseUrl);
1417
- if (options.traceId !== void 0) headers.set(TRACE_ID_HEADER, resolveTraceId(options.traceId));
1418
- const timeoutSignal = options.timeoutMs !== void 0 ? AbortSignal.timeout(options.timeoutMs) : void 0;
1419
- const signal = options.signal && timeoutSignal ? combineAbortSignals([options.signal, timeoutSignal]) : options.signal ?? timeoutSignal;
1420
- const path = `/agents/sessions/${encodeURIComponent(id)}/messages`;
1421
- const init = {
1422
- method: "POST",
1423
- headers,
1424
- signal,
1425
- body: JSON.stringify(sessionMessageRequestBody(request))
1426
- };
1427
- let receipt;
1428
- try {
1429
- receipt = await this.json(path, init);
1430
- } catch (error) {
1431
- if (options.planFollowUp || !isRetryableCredentialRefusal(error)) throw error;
1432
- await waitForRetryAfter(error.retryAfterMs ?? 1e3, signal);
1433
- receipt = await this.json(path, init);
1434
- }
1435
- if (request.runControlRef) validateAcceptedDispatchRunRef(receipt.runControlRef, request.runControlRef, request.runControlRef.environmentId, id, receipt.info.id, path);
1436
- return receipt;
1437
- }
1438
- async deleteSession(id) {
1439
- await this.transport.ensureRunning();
1440
- await this.request(`/agents/sessions/${encodeURIComponent(id)}`, { method: "DELETE" });
1441
- }
1442
- async taskSessionChanges(id) {
1443
- await this.transport.ensureRunning();
1444
- return this.json(`/tasks/${encodeURIComponent(id)}/changes`, { method: "GET" });
1445
- }
1446
- async commitTaskSession(id, options = {}) {
1447
- await this.transport.ensureRunning();
1448
- return this.json(`/tasks/${encodeURIComponent(id)}/changes`, {
1449
- method: "POST",
1450
- body: JSON.stringify({
1451
- ...options.message !== void 0 ? { message: options.message } : {},
1452
- ...options.files !== void 0 ? { files: options.files } : {}
1453
- })
1454
- });
1455
- }
1456
- async createTerminal(options = {}, request = {}) {
1457
- const params = new URLSearchParams();
1458
- appendSessionIdQuery(params, request.sessionId);
1459
- const query = params.toString();
1460
- await this.transport.ensureRunning();
1461
- return (await this.json(`/terminals${query ? `?${query}` : ""}`, {
1462
- method: "POST",
1463
- body: JSON.stringify(options)
1464
- })).data;
1465
- }
1466
- async writeTerminal(terminalId, data, request = {}) {
1467
- const params = new URLSearchParams();
1468
- appendSessionIdQuery(params, request.sessionId);
1469
- const query = params.toString();
1470
- await this.transport.ensureRunning();
1471
- await this.request(`/terminals/${encodeURIComponent(terminalId)}/input${query ? `?${query}` : ""}`, {
1472
- method: "POST",
1473
- body: JSON.stringify({ data })
1474
- });
1475
- }
1476
- async listTerminals() {
1477
- await this.transport.ensureRunning();
1478
- return (await this.json("/terminals", { method: "GET" })).data ?? [];
1479
- }
1480
- async getTerminal(terminalId) {
1481
- await this.transport.ensureRunning();
1482
- const response = await this.transport.fetch(`/terminals/${encodeURIComponent(terminalId)}`, { method: "GET" });
1483
- if (response.status === 404) return null;
1484
- await this.assertOk(response);
1485
- return (await response.json()).data;
1486
- }
1487
- async json(path, init) {
1488
- return await (await this.request(path, init)).json();
1489
- }
1490
- async request(path, init) {
1491
- const response = await this.transport.fetch(path, init);
1492
- await this.assertOk(response);
1493
- return response;
1494
- }
1495
- async assertOk(response) {
1496
- if (response.ok) return;
1497
- throw await parseResponseError(response);
1498
- }
1499
1520
  };
1500
- const EFFECTIVE_BACKEND_SOURCES = [
1501
- "request",
1502
- "environment",
1503
- "profile"
1504
- ];
1521
+ //#endregion
1522
+ //#region src/runtime-session-normalize.ts
1505
1523
  function nonEmptyField(value) {
1506
1524
  return typeof value === "string" && value.length > 0 ? value : void 0;
1507
1525
  }
1508
- function normalizeEffectiveBackendProfile(value) {
1509
- if (!value || typeof value !== "object") return void 0;
1510
- const raw = value;
1511
- const digest = nonEmptyField(raw.digest);
1512
- if (!digest) return void 0;
1513
- const name = nonEmptyField(raw.name);
1514
- return {
1515
- ...name ? { name } : {},
1516
- digest
1517
- };
1518
- }
1519
- function normalizeEffectiveBackend(value) {
1520
- if (!value || typeof value !== "object") return void 0;
1521
- const raw = value;
1522
- const provider = nonEmptyField(raw.provider);
1523
- const model = nonEmptyField(raw.model);
1524
- const profile = normalizeEffectiveBackendProfile(raw.profile);
1525
- if (!provider && !model && !profile) return void 0;
1526
- const source = nonEmptyField(raw.source);
1527
- return {
1528
- ...provider ? { provider } : {},
1529
- ...model ? { model } : {},
1530
- ...source && EFFECTIVE_BACKEND_SOURCES.includes(source) ? { source } : {},
1531
- ...profile ? { profile } : {}
1532
- };
1533
- }
1534
1526
  function normalizeSessionFailureReason(value) {
1535
1527
  if (!value || typeof value !== "object") return void 0;
1536
1528
  const raw = value;
@@ -1611,6 +1603,7 @@ function sessionMessageRequestBody(request) {
1611
1603
  const parsed = Date.parse(deadline);
1612
1604
  if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(deadline) || !Number.isFinite(parsed) || new Date(parsed).toISOString() !== deadline) throw new ValidationError("admissionDeadline must be canonical UTC");
1613
1605
  }
1606
+ if (request.maxModelCalls !== void 0 && (!Number.isInteger(request.maxModelCalls) || request.maxModelCalls < 1 || request.maxModelCalls > 64)) throw new ValidationError("maxModelCalls must be an integer from 1 to 64");
1614
1607
  if (request.managedQuoteVersion !== void 0 && !/^mmq_[a-f0-9]{40}$/.test(request.managedQuoteVersion)) throw new ValidationError("managedQuoteVersion is invalid");
1615
1608
  if (request.expectedPublicProfileRequestDigest !== void 0) {
1616
1609
  if (request.system !== void 0 || request.agent !== void 0 || request.model !== void 0 || request.reasoningEffort !== void 0 || request.interactions !== void 0 || request.managedQuoteVersion !== void 0 || request.managedModelCredential !== void 0) throw new ValidationError("Public profile request pin requires all authority controls in backend");
@@ -1644,10 +1637,227 @@ function sessionMessageRequestBody(request) {
1644
1637
  } } : {},
1645
1638
  ...request.reasoningEffort !== void 0 ? { reasoningEffort: request.reasoningEffort } : {},
1646
1639
  ...request.turnId !== void 0 ? { turnId: request.turnId } : {},
1647
- ...request.interactions !== void 0 ? { interactions: request.interactions } : {}
1640
+ ...request.interactions !== void 0 ? { interactions: request.interactions } : {},
1641
+ ...request.disableTools === true ? { disableTools: true } : {},
1642
+ ...request.maxModelCalls !== void 0 ? { maxModelCalls: request.maxModelCalls } : {}
1648
1643
  };
1649
1644
  }
1650
1645
  //#endregion
1646
+ //#region src/runtime-api.ts
1647
+ /** Internal typed client for routes served by a sandbox runtime. */
1648
+ var SandboxRuntimeApi = class extends RuntimeFiles {
1649
+ /**
1650
+ * Subscribe to a session's agent event stream (`/agents/events`).
1651
+ *
1652
+ * The consume half of the supervisor pattern: construct the client from a
1653
+ * `read-only` or `session-runtime` scoped token
1654
+ * (`SandboxInstance.mintScopedToken`) and a parent agent observes a child
1655
+ * sandbox's stream while holding no credential that can mutate the child.
1656
+ * With `executionId` set, the stream ends at that turn's terminal
1657
+ * `done`/`error` event; a stream that dies before the terminal throws
1658
+ * instead of reading like a finished turn. Aborting `options.signal` ends
1659
+ * the generator cleanly, matching every other SDK stream. Events carry no
1660
+ * `data.sandboxId` stamp here: a scoped-token client knows only its own
1661
+ * runtime URL, and the subscriber already knows which sandbox it minted
1662
+ * the token for.
1663
+ */
1664
+ async *events(sessionId, options = {}) {
1665
+ await this.transport.ensureRunning();
1666
+ const search = new URLSearchParams();
1667
+ search.set("sessionId", sessionId);
1668
+ if (options.since) search.set("since", options.since);
1669
+ if (options.executionId) search.set("executionId", options.executionId);
1670
+ const response = await this.request(`/agents/events?${search.toString()}`, { signal: options.signal });
1671
+ if (!response.body) throw new NetworkError("event stream has no response body");
1672
+ let sawTerminal = false;
1673
+ try {
1674
+ for await (const event of parseSSEStream(response.body, {
1675
+ signal: options.signal,
1676
+ invalidEvent: "warn-and-skip"
1677
+ })) {
1678
+ yield {
1679
+ type: event.type,
1680
+ data: event.data,
1681
+ ...event.id !== void 0 ? { id: event.id } : {}
1682
+ };
1683
+ if (options.executionId !== void 0 && (event.type === "done" || event.type === "error")) {
1684
+ sawTerminal = true;
1685
+ return;
1686
+ }
1687
+ }
1688
+ } catch (err) {
1689
+ if (err instanceof DOMException && err.name === "AbortError") return;
1690
+ throw err;
1691
+ }
1692
+ if (options.executionId !== void 0 && !sawTerminal) throw new NetworkError("event stream ended before a terminal event — the connection dropped mid-turn");
1693
+ }
1694
+ /** Read a turn's retained admission without proposing or admitting a message. */
1695
+ async admission(sessionId, turnId, options = {}) {
1696
+ if (!sessionId.trim() || !turnId.trim()) throw new ValidationError("sessionId and turnId are required");
1697
+ await this.transport.ensureRunning();
1698
+ const endpoint = `/agents/sessions/${encodeURIComponent(sessionId)}/admissions/${encodeURIComponent(turnId)}`;
1699
+ const payload = await this.json(endpoint, {
1700
+ method: "GET",
1701
+ signal: options.signal
1702
+ });
1703
+ if (payload?.receipt === null) return null;
1704
+ const receipt = payload?.receipt;
1705
+ if (!receipt || typeof receipt.info?.id !== "string" || !receipt.info.id || receipt.processing !== true) throw new ServerError("Runtime returned an invalid message admission receipt", 502, {
1706
+ origin: "runtime",
1707
+ endpoint
1708
+ });
1709
+ const parsedRef = receipt.runControlRef === void 0 ? void 0 : AgentExactRunControlRefSchema.safeParse(receipt.runControlRef);
1710
+ if (parsedRef && !parsedRef.success) throw new ServerError("Admission returned an invalid exact run reference", 502, {
1711
+ origin: "runtime",
1712
+ endpoint
1713
+ });
1714
+ const runControlRef = parsedRef?.data;
1715
+ if (runControlRef && (runControlRef.sessionId !== sessionId || runControlRef.executionId !== receipt.info.id)) throw new ServerError("Admission control reference does not match its execution", 502, {
1716
+ origin: "runtime",
1717
+ endpoint
1718
+ });
1719
+ const run = (await this.runs(sessionId, options)).find((candidate) => candidate.executionId === receipt.info.id);
1720
+ return {
1721
+ sessionId,
1722
+ turnId,
1723
+ executionId: receipt.info.id,
1724
+ status: run?.status ?? "unavailable",
1725
+ ...runControlRef ? { runControlRef } : {}
1726
+ };
1727
+ }
1728
+ /** List validated execution records from the runtime ledger, newest first. */
1729
+ async runs(sessionId, options = {}) {
1730
+ await this.transport.ensureRunning();
1731
+ const endpoint = `/agents/sessions/${encodeURIComponent(sessionId)}/runs`;
1732
+ const payload = await this.json(endpoint, {
1733
+ method: "GET",
1734
+ signal: options.signal
1735
+ });
1736
+ if (payload.success !== true || !Array.isArray(payload.executions)) throw new ServerError("Session runs response has an invalid shape", 502, {
1737
+ origin: "runtime",
1738
+ endpoint
1739
+ });
1740
+ const executions = payload.executions.map((value) => normalizeSessionExecutionInfo(value, sessionId));
1741
+ if (executions.some((execution) => execution === null)) throw new ServerError("Session runs response has an invalid execution", 502, {
1742
+ origin: "runtime",
1743
+ endpoint
1744
+ });
1745
+ return executions.filter((execution) => execution !== null);
1746
+ }
1747
+ async createSession(options) {
1748
+ await this.transport.ensureRunning();
1749
+ const backend = normalizeRuntimeBackendConfig(options.backend);
1750
+ const info = normalizeSessionInfo(await this.json("/agents/sessions", {
1751
+ method: "POST",
1752
+ body: JSON.stringify({
1753
+ ...options.sessionId !== void 0 ? { sessionId: options.sessionId } : {},
1754
+ ...options.title !== void 0 ? { title: options.title } : {},
1755
+ ...options.retention !== void 0 ? { retention: options.retention } : {},
1756
+ ...options.parentId !== void 0 ? { parentID: options.parentId } : {},
1757
+ ...options.workspaceRoot !== void 0 ? { workspaceRoot: options.workspaceRoot } : {},
1758
+ ...options.conversationHistory !== void 0 ? { conversationHistory: options.conversationHistory } : {},
1759
+ ...options.importFromSessionId !== void 0 ? { importFromSessionId: options.importFromSessionId } : {},
1760
+ ...backend && Object.keys(backend).length > 0 ? { backend } : {}
1761
+ })
1762
+ }));
1763
+ if (!info) throw new ServerError("Session creation response missing session id", 502, {
1764
+ endpoint: "/agents/sessions",
1765
+ origin: "runtime"
1766
+ });
1767
+ return info;
1768
+ }
1769
+ async messages(id, options = {}) {
1770
+ await this.transport.ensureRunning();
1771
+ const params = new URLSearchParams({ sessionId: id });
1772
+ if (options.limit !== void 0) params.set("limit", String(options.limit));
1773
+ if (options.offset !== void 0) params.set("offset", String(options.offset));
1774
+ if (options.since !== void 0) params.set("since", String(options.since));
1775
+ const query = params.toString();
1776
+ return (await this.json(`/messages${query ? `?${query}` : ""}`, { method: "GET" })).map((message) => ({
1777
+ id: message.info.id,
1778
+ role: message.info.role,
1779
+ timestamp: message.info.timestamp,
1780
+ parts: message.parts,
1781
+ metadata: message.info.metadata
1782
+ }));
1783
+ }
1784
+ async createTaskSession(options) {
1785
+ await this.transport.ensureRunning();
1786
+ const info = await this.json("/tasks", {
1787
+ method: "POST",
1788
+ body: JSON.stringify({
1789
+ sessionId: options.sessionId,
1790
+ backend: normalizeRuntimeBackendConfig(options.backend),
1791
+ title: options.title,
1792
+ ...options.parentSessionId !== void 0 ? { parentSessionId: options.parentSessionId } : {},
1793
+ ...options.profile !== void 0 ? { profile: options.profile } : {},
1794
+ ...options.isolateFileWrites !== void 0 ? { isolateFileWrites: options.isolateFileWrites } : {}
1795
+ })
1796
+ });
1797
+ if (!info.id) throw new ServerError("Task session creation response missing session id", 502, {
1798
+ endpoint: "/tasks",
1799
+ origin: "runtime"
1800
+ });
1801
+ return info;
1802
+ }
1803
+ async sendSessionMessage(id, request, options = {}) {
1804
+ if (options.timeoutMs !== void 0 && options.timeoutMs <= 0) throw new ValidationError("timeoutMs must be greater than zero");
1805
+ await this.transport.ensureRunning();
1806
+ const headers = new Headers({
1807
+ "content-type": "application/json",
1808
+ "x-no-retry": "true"
1809
+ });
1810
+ if (options.planFollowUp) {
1811
+ if (!request.backend?.planContinuation || !request.expectedPublicProfileRequestDigest || !request.expectedSecretProfileReceipt || !Number.isFinite(Date.parse(options.planFollowUp.expiresAt)) || Date.parse(options.planFollowUp.expiresAt) <= Date.now()) throw new ValidationError("Caller plan follow-up requires current admission and both fresh profile pins");
1812
+ headers.set("x-tangle-plan-followup-credential", options.planFollowUp.credential);
1813
+ headers.set("x-tangle-plan-followup-callback", options.planFollowUp.callbackUrl);
1814
+ }
1815
+ if (options.credentials?.apiKey) headers.set("X-Backend-Api-Key", options.credentials.apiKey);
1816
+ if (options.credentials?.baseUrl) headers.set("X-Backend-Base-Url", options.credentials.baseUrl);
1817
+ if (options.traceId !== void 0) headers.set(TRACE_ID_HEADER, resolveTraceId(options.traceId));
1818
+ const timeoutSignal = options.timeoutMs !== void 0 ? AbortSignal.timeout(options.timeoutMs) : void 0;
1819
+ const signal = options.signal && timeoutSignal ? combineAbortSignals([options.signal, timeoutSignal]) : options.signal ?? timeoutSignal;
1820
+ const path = `/agents/sessions/${encodeURIComponent(id)}/messages`;
1821
+ const init = {
1822
+ method: "POST",
1823
+ headers,
1824
+ signal,
1825
+ body: JSON.stringify(sessionMessageRequestBody(request))
1826
+ };
1827
+ let receipt;
1828
+ try {
1829
+ receipt = await this.json(path, init);
1830
+ } catch (error) {
1831
+ if (options.planFollowUp || !isRetryableCredentialRefusal(error)) throw error;
1832
+ await waitForRetryAfter(error.retryAfterMs ?? 1e3, signal);
1833
+ receipt = await this.json(path, init);
1834
+ }
1835
+ if (request.runControlRef) validateAcceptedDispatchRunRef(receipt.runControlRef, request.runControlRef, request.runControlRef.environmentId, id, receipt.info.id, path);
1836
+ return receipt;
1837
+ }
1838
+ async deleteSession(id) {
1839
+ await this.transport.ensureRunning();
1840
+ await this.request(`/agents/sessions/${encodeURIComponent(id)}`, { method: "DELETE" });
1841
+ }
1842
+ async taskSessionChanges(id) {
1843
+ await this.transport.ensureRunning();
1844
+ return this.json(`/tasks/${encodeURIComponent(id)}/changes`, { method: "GET" });
1845
+ }
1846
+ async commitTaskSession(id, options = {}) {
1847
+ await this.transport.ensureRunning();
1848
+ return this.json(`/tasks/${encodeURIComponent(id)}/changes`, {
1849
+ method: "POST",
1850
+ body: JSON.stringify({
1851
+ ...options.message !== void 0 ? { message: options.message } : {},
1852
+ ...options.files !== void 0 ? { files: options.files } : {}
1853
+ })
1854
+ });
1855
+ }
1856
+ constructor(transport) {
1857
+ super(transport);
1858
+ }
1859
+ };
1860
+ //#endregion
1651
1861
  //#region src/scoped-token.ts
1652
1862
  /** Maximum time for the exact interactive terminal-token request. */
1653
1863
  const SCOPED_TOKEN_REQUEST_TIMEOUT_MS = 5e3;
@@ -1730,221 +1940,8 @@ function requestInteractiveSessionToken(client, ref, options) {
1730
1940
  const exact = interactiveSessionTokenOptions(ref, options);
1731
1941
  return requestScopedToken(client, exact.sandboxId, exact.request, { timeoutMs: SCOPED_TOKEN_REQUEST_TIMEOUT_MS });
1732
1942
  }
1733
- const TERMINAL_WS_MAX_DIMENSION = 4096;
1734
- /** Input chunk size that leaves room for JSON escaping inside one frame. */
1735
- const TERMINAL_WS_INPUT_FRAME_CHUNK_CHARS = 128 * 1024;
1736
- /** WebSocket authentication envelope prefixes. */
1737
- const TERMINAL_WS_EDGE_BEARER_SUBPROTOCOL_PREFIX = "bearer.";
1738
- const TERMINAL_WS_SIDECAR_BEARER_SUBPROTOCOL_PREFIX = "tangle.bearer.";
1739
- /** Non-credential protocol selected during a successful terminal handshake. */
1740
- const TERMINAL_WS_ECHO_SUBPROTOCOL = "tangle.terminal.v1";
1741
- /**
1742
- * Encode the upgrade URL's query (no leading `?`): the size of a
1743
- * default-shell attach with its flag, and the trace id. Nothing else rides the
1744
- * URL.
1745
- */
1746
- function encodeTerminalUpgradeQuery(input) {
1747
- const params = new URLSearchParams();
1748
- if (input.defaultShell !== void 0) {
1749
- params.set("cols", String(input.defaultShell.cols));
1750
- params.set("rows", String(input.defaultShell.rows));
1751
- params.set("defaultShell", "1");
1752
- }
1753
- if (input.traceId !== void 0) params.set("traceId", input.traceId);
1754
- return params.toString();
1755
- }
1756
- const terminalGeometry = {
1757
- cols: z.number().int().min(1).max(TERMINAL_WS_MAX_DIMENSION),
1758
- rows: z.number().int().min(1).max(TERMINAL_WS_MAX_DIMENSION)
1759
- };
1760
- const terminalInitMessageSchema = z.object({
1761
- type: z.literal("init"),
1762
- connectionId: z.string().optional(),
1763
- /** Required for an interactive-agent PTY; absent for generic terminals. */
1764
- incarnationId: z.string().uuid().optional(),
1765
- ...terminalGeometry,
1766
- command: z.string().min(1).optional(),
1767
- cwd: z.string().min(1).optional(),
1768
- env: z.record(z.string(), z.string()).optional(),
1769
- sessionId: z.string().min(1).optional(),
1770
- /** Canonical control claim for an interactive-agent PTY. */
1771
- control: AgentInteractiveSessionControlClaimSchema.optional(),
1772
- /**
1773
- * Caller trace id for a browser, which cannot set `x-tangle-trace-id` on
1774
- * the upgrade. The server adopts it only when it is a well-formed id.
1775
- */
1776
- traceId: z.string().max(200).optional()
1777
- }).superRefine((message, refinement) => {
1778
- if (message.incarnationId !== void 0 && message.control === void 0) refinement.addIssue({
1779
- code: "custom",
1780
- path: ["control"],
1781
- message: "Interactive session attach requires a control claim"
1782
- });
1783
- if (message.incarnationId === void 0 && message.control !== void 0) refinement.addIssue({
1784
- code: "custom",
1785
- path: ["control"],
1786
- message: "Generic terminal attach cannot carry an interactive control claim"
1787
- });
1788
- });
1789
- const terminalInputMessageSchema = z.object({
1790
- type: z.literal("input"),
1791
- data: z.string()
1792
- });
1793
- const terminalResizeMessageSchema = z.object({
1794
- type: z.literal("resize"),
1795
- ...terminalGeometry
1796
- });
1797
- const terminalRenewMessageSchema = z.object({ type: z.literal("renew") });
1798
- const terminalCloseMessageSchema = z.object({ type: z.literal("close") });
1799
- z.union([
1800
- terminalInitMessageSchema,
1801
- terminalInputMessageSchema,
1802
- terminalResizeMessageSchema,
1803
- terminalRenewMessageSchema,
1804
- terminalCloseMessageSchema
1805
- ]);
1806
- /**
1807
- * Server stamps for one attach, in epoch milliseconds on the sidecar's clock.
1808
- * They are absolute so a caller can lay them against its own marks and read
1809
- * each leg (client clock skew is the only error). `spawn*` and `initPersistAt`
1810
- * are absent when the attach adopted a PTY that already existed.
1811
- */
1812
- const terminalReadyTimingsSchema = z.object({
1813
- /** The upgrade request reached the sidecar's upgrade handler. */
1814
- upgradeAt: z.number(),
1815
- /** The bearer was verified (`ws.auth` ends). */
1816
- authAt: z.number(),
1817
- /** The init parameters were in hand: at the upgrade for `via: "upgrade"`, on the init frame otherwise. */
1818
- initAt: z.number(),
1819
- /** `loadOrCreateConnection` started. */
1820
- loadAt: z.number(),
1821
- /** The PTY process was spawned (`pty.spawn` ends). */
1822
- spawnAt: z.number().optional(),
1823
- /** The `session.init` event was persisted (`session.init.persist` ends). */
1824
- initPersistAt: z.number().optional(),
1825
- /** `loadOrCreateConnection` returned. */
1826
- loadedAt: z.number(),
1827
- /** The retained history was read (`history.read` ends). */
1828
- historyAt: z.number(),
1829
- /** Retained events and bytes the replay will carry. */
1830
- historyEvents: z.number().int().nonnegative(),
1831
- historyBytes: z.number().int().nonnegative(),
1832
- /** The `ready` frame was sent. */
1833
- readyAt: z.number(),
1834
- /** How the init parameters reached the server. */
1835
- via: z.enum(["upgrade", "frame"]),
1836
- /** Correlation id of this attach (`terminal_attach` spans share it). */
1837
- ptid: z.string().optional()
1838
- });
1839
- const terminalReadyMessageSchema = z.object({
1840
- type: z.literal("ready"),
1841
- connectionId: z.string(),
1842
- sessionId: z.string(),
1843
- restored: z.boolean(),
1844
- detachTimeoutMs: z.number().int().positive(),
1845
- /** Exact viewer count held by the runtime for this connection. */
1846
- attachCount: z.number().int().positive().optional(),
1847
- /** Server-issued output cursor window for exact interactive terminals. */
1848
- cursors: z.object({
1849
- earliest: z.number().int().nonnegative(),
1850
- latest: z.number().int().nonnegative()
1851
- }).optional(),
1852
- /** Server stamps for this attach; absent from a sidecar that predates them. */
1853
- timings: terminalReadyTimingsSchema.optional()
1854
- });
1855
- /** One sequenced output frame for an exact interactive terminal. */
1856
- const terminalOutputMessageSchema = z.object({
1857
- type: z.literal("output"),
1858
- seq: z.number().int().positive(),
1859
- /** Base64-encoded UTF-8 bytes from the retained terminal event. */
1860
- data: z.string().min(1)
1861
- });
1862
- const terminalExitMessageSchema = z.object({
1863
- type: z.literal("exit"),
1864
- exitCode: z.number().optional(),
1865
- exitSignal: z.string().optional()
1866
- });
1867
- const terminalRenewedMessageSchema = z.object({
1868
- type: z.literal("renewed"),
1869
- sessionId: z.string()
1870
- });
1871
- const terminalErrorMessageSchema = z.object({
1872
- type: z.literal("error"),
1873
- code: z.string(),
1874
- message: z.string()
1875
- });
1876
- const terminalServerMessageSchema = z.union([
1877
- terminalReadyMessageSchema,
1878
- terminalOutputMessageSchema,
1879
- terminalExitMessageSchema,
1880
- terminalRenewedMessageSchema,
1881
- terminalErrorMessageSchema
1882
- ]);
1883
1943
  //#endregion
1884
- //#region src/terminal-stream.ts
1885
- /**
1886
- * TerminalStream — typed client for the sandbox terminal WebSocket protocol.
1887
- *
1888
- * Drives a live PTY session (an interactive harness TUI or a plain shell)
1889
- * from the caller's own program: binary frames stream raw PTY output bytes,
1890
- * TEXT JSON frames carry the control protocol. The browser-safe wire contract
1891
- * is defined by the shared browser-safe runtime contract and shared with the
1892
- * sidecar:
1893
- *
1894
- * client → server (TEXT JSON):
1895
- * init {connectionId?, cols, rows, command?, cwd?, env?} — MUST be first
1896
- * input {data}
1897
- * resize {cols, rows}
1898
- *
1899
- * Interactive-agent init frames add the exact process authority:
1900
- * {incarnationId, control: {refDigest, generation, leaseId, holderId, expiresAt}}
1901
- * Subsequent input and resize frames carry only their operation fields; the
1902
- * server binds authority to the init for the socket lifetime.
1903
- * server → client (TEXT JSON):
1904
- * ready {connectionId, sessionId, restored, detachTimeoutMs,
1905
- * attachCount?, cursors?}
1906
- * output {seq, data} — exact interactive output as base64 UTF-8 bytes
1907
- * exit {exitCode?, exitSignal?}
1908
- * error {code, message}
1909
- * rec / rec.done — recording tee frames for the platform's session
1910
- * capture consumer; not part of the client surface
1911
- * server → client (BINARY): raw PTY output bytes
1912
- *
1913
- * A default-shell attach (no `command`, `cwd`, `env` or interactive identity)
1914
- * also puts `cols`, `rows` and `defaultShell=1` on the upgrade URL. A server
1915
- * that reads them starts the PTY when it accepts the upgrade and sends `ready`
1916
- * without waiting for `init`; the `init` frame is still sent, first, and that
1917
- * server ignores it. A server that does not read them waits for `init` exactly
1918
- * as before. `command` and `cwd` travel only in the `init` frame, inside the
1919
- * WebSocket: the URL and the request headers reach access logs.
1920
- *
1921
- * Detach/reconnect: the server keeps the PTY alive for `detachTimeoutMs`
1922
- * (5 minutes today) after the socket closes; re-dialing with the SAME
1923
- * connectionId reattaches and replays the buffered output history, so a
1924
- * fresh client repaints the current screen.
1925
- *
1926
- * Browser-safe: uses the global `WebSocket` (browsers, Workers, Node >= 22)
1927
- * and never imports `ws` — the same environment contract as
1928
- * `session-gateway/client.ts`.
1929
- */
1930
- /** A protocol `error` control frame or a transport failure. */
1931
- var TerminalStreamError = class extends Error {
1932
- /** Protocol error code (e.g. `INIT_FAILED`) or `TRANSPORT` for socket faults. */
1933
- code;
1934
- /**
1935
- * True when the socket never reached OPEN: the upgrade was refused (a
1936
- * WebSocket client cannot read the HTTP status, so a 401 and a network drop
1937
- * look alike) or the runtime rejected the dial's options. No PTY work had
1938
- * started on the client's side of that dial.
1939
- */
1940
- beforeOpen;
1941
- constructor(message, code, options = {}) {
1942
- super(message);
1943
- this.name = "TerminalStreamError";
1944
- this.code = code;
1945
- this.beforeOpen = options.beforeOpen === true;
1946
- }
1947
- };
1944
+ //#region src/terminal-stream-protocol.ts
1948
1945
  /**
1949
1946
  * The sidecar caps WebSocket frames at 1 MiB
1950
1947
  * (`TERMINAL_WS_MAX_PAYLOAD_BYTES` in the shared runtime contract) and drops
@@ -1956,7 +1953,6 @@ var TerminalStreamError = class extends Error {
1956
1953
  */
1957
1954
  const DEFAULT_COLS = 80;
1958
1955
  const DEFAULT_ROWS = 24;
1959
- const DEFAULT_CONNECT_TIMEOUT_MS = 15e3;
1960
1956
  /**
1961
1957
  * base64url-encode a UTF-8 string without padding — the exact envelope the
1962
1958
  * edge's `parseTerminalWsSubprotocolToken` decodes (its strict round-trip
@@ -2015,9 +2011,8 @@ async function resolveDialCredential(token, authFormat, signal) {
2015
2011
  * still safe: the upgrade is refused, and the caller dials with a scoped token.
2016
2012
  */
2017
2013
  function terminalUpgradeHeadersSupported() {
2018
- const runtime = globalThis;
2019
- if (typeof runtime.process?.versions?.node !== "string") return false;
2020
- if (runtime.navigator?.userAgent?.startsWith("Cloudflare-Workers")) return false;
2014
+ if (typeof globalThis.process?.versions?.node !== "string") return false;
2015
+ if (isCloudflareWorker()) return false;
2021
2016
  return typeof globalThis.WebSocket === "function";
2022
2017
  }
2023
2018
  function buildUpgradeRequest(options, credential, identity, traceId) {
@@ -2182,6 +2177,53 @@ function* chunkInput(text) {
2182
2177
  index = end;
2183
2178
  }
2184
2179
  }
2180
+ //#endregion
2181
+ //#region src/terminal-stream.ts
2182
+ /**
2183
+ * TerminalStream — typed client for the sandbox terminal WebSocket protocol.
2184
+ *
2185
+ * Drives a live PTY session (an interactive harness TUI or a plain shell)
2186
+ * from the caller's own program: binary frames stream raw PTY output bytes,
2187
+ * TEXT JSON frames carry the control protocol. The browser-safe wire contract
2188
+ * is defined by the shared browser-safe runtime contract and shared with the
2189
+ * sidecar:
2190
+ *
2191
+ * client → server (TEXT JSON):
2192
+ * init {connectionId?, cols, rows, command?, cwd?, env?} — MUST be first
2193
+ * input {data}
2194
+ * resize {cols, rows}
2195
+ *
2196
+ * Interactive-agent init frames add the exact process authority:
2197
+ * {incarnationId, control: {refDigest, generation, leaseId, holderId, expiresAt}}
2198
+ * Subsequent input and resize frames carry only their operation fields; the
2199
+ * server binds authority to the init for the socket lifetime.
2200
+ * server → client (TEXT JSON):
2201
+ * ready {connectionId, sessionId, restored, detachTimeoutMs,
2202
+ * attachCount?, cursors?}
2203
+ * output {seq, data} — exact interactive output as base64 UTF-8 bytes
2204
+ * exit {exitCode?, exitSignal?}
2205
+ * error {code, message}
2206
+ * rec / rec.done — recording tee frames for the platform's session
2207
+ * capture consumer; not part of the client surface
2208
+ * server → client (BINARY): raw PTY output bytes
2209
+ *
2210
+ * A default-shell attach (no `command`, `cwd`, `env` or interactive identity)
2211
+ * also puts `cols`, `rows` and `defaultShell=1` on the upgrade URL. A server
2212
+ * that reads them starts the PTY when it accepts the upgrade and sends `ready`
2213
+ * without waiting for `init`; the `init` frame is still sent, first, and that
2214
+ * server ignores it. A server that does not read them waits for `init` exactly
2215
+ * as before. `command` and `cwd` travel only in the `init` frame, inside the
2216
+ * WebSocket: the URL and the request headers reach access logs.
2217
+ *
2218
+ * Detach/reconnect: the server keeps the PTY alive for `detachTimeoutMs`
2219
+ * (5 minutes today) after the socket closes; re-dialing with the SAME
2220
+ * connectionId reattaches and replays the buffered output history, so a
2221
+ * fresh client repaints the current screen.
2222
+ *
2223
+ * Browser-safe: uses the global `WebSocket` (browsers, Workers, Node >= 22)
2224
+ * and never imports `ws` — the same environment contract as
2225
+ * `session-gateway/client.ts`.
2226
+ */
2185
2227
  /**
2186
2228
  * Client for one terminal WebSocket connection. Construct via
2187
2229
  * {@link TerminalStream.connect}, which resolves once the server
@@ -2190,9 +2232,9 @@ function* chunkInput(text) {
2190
2232
  */
2191
2233
  var TerminalStream = class TerminalStream {
2192
2234
  ws;
2193
- options;
2235
+ #options;
2194
2236
  interactiveIdentity;
2195
- initMessage;
2237
+ #initMessage;
2196
2238
  handlers;
2197
2239
  attachTraceId;
2198
2240
  initOnUpgrade;
@@ -2230,12 +2272,12 @@ var TerminalStream = class TerminalStream {
2230
2272
  incarnationId: interactiveIdentity.incarnationId,
2231
2273
  control: interactiveIdentity.control
2232
2274
  };
2233
- this.options = {
2275
+ this.#options = {
2234
2276
  ...exactOptions,
2235
2277
  signal: void 0
2236
2278
  };
2237
2279
  this.interactiveIdentity = interactiveIdentity;
2238
- this.initMessage = initMessage;
2280
+ this.#initMessage = initMessage;
2239
2281
  this.handlers = exactOptions.handlers ?? {};
2240
2282
  this.attachTraceId = traceId;
2241
2283
  const request = buildUpgradeRequest(exactOptions, credential, interactiveIdentity, traceId);
@@ -2247,7 +2289,7 @@ var TerminalStream = class TerminalStream {
2247
2289
  return new Promise((resolve, reject) => {
2248
2290
  let settled = false;
2249
2291
  let opened = false;
2250
- const timeoutMs = this.options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
2292
+ const timeoutMs = this.#options.connectTimeoutMs ?? 15e3;
2251
2293
  const timer = setTimeout(() => {
2252
2294
  fail(new TerminalStreamError(`Terminal attach timed out after ${timeoutMs}ms waiting for ready`, "CONNECT_TIMEOUT"));
2253
2295
  this.ws.close(1e3, "connect timeout");
@@ -2288,7 +2330,7 @@ var TerminalStream = class TerminalStream {
2288
2330
  fail(error instanceof TerminalStreamError ? error : new TerminalStreamError("Interactive terminal control claim is expired", "INTERACTIVE_CONTROL_EXPIRED"));
2289
2331
  return;
2290
2332
  }
2291
- this.ws.send(JSON.stringify(this.initMessage));
2333
+ this.ws.send(JSON.stringify(this.#initMessage));
2292
2334
  });
2293
2335
  this.ws.addEventListener("message", (event) => {
2294
2336
  this.handleMessage(event.data, {
@@ -2393,7 +2435,7 @@ var TerminalStream = class TerminalStream {
2393
2435
  }
2394
2436
  /** PTY connection id this stream is attached to. */
2395
2437
  get connectionId() {
2396
- return this.options.connectionId;
2438
+ return this.#options.connectionId;
2397
2439
  }
2398
2440
  /** The server's `ready` acknowledgement. Set once `connect()` resolves. */
2399
2441
  get ready() {
@@ -2412,7 +2454,7 @@ var TerminalStream = class TerminalStream {
2412
2454
  const opened = this.openedAt ?? this.dialStartedAt;
2413
2455
  const ready = this.readyAt ?? opened;
2414
2456
  return {
2415
- ...this.options.mintMs === void 0 ? {} : { mintMs: this.options.mintMs },
2457
+ ...this.#options.mintMs === void 0 ? {} : { mintMs: this.#options.mintMs },
2416
2458
  wsOpenMs: opened - this.dialStartedAt,
2417
2459
  initToReadyMs: ready - opened,
2418
2460
  ...this.firstByteAt === void 0 ? {} : { firstByteMs: this.firstByteAt - ready },
@@ -2494,19 +2536,19 @@ var TerminalStream = class TerminalStream {
2494
2536
  return awaitTerminalOperation(tracked, overrides?.signal);
2495
2537
  }
2496
2538
  async reconnectOnce(overrides) {
2497
- const binding = await this.options.reconnectAuthority?.acquire(overrides?.signal);
2539
+ const binding = await this.#options.reconnectAuthority?.acquire(overrides?.signal);
2498
2540
  try {
2499
2541
  return await TerminalStream.connect({
2500
- ...this.options,
2542
+ ...this.#options,
2501
2543
  ...binding === void 0 ? {} : {
2502
2544
  incarnationId: binding.incarnationId,
2503
2545
  control: binding.control
2504
2546
  },
2505
- token: overrides?.token ?? this.options.token,
2547
+ token: overrides?.token ?? this.#options.token,
2506
2548
  mintMs: void 0,
2507
2549
  handlers: this.handlersForReconnect(overrides?.handlers),
2508
- cols: overrides?.cols ?? this.options.cols,
2509
- rows: overrides?.rows ?? this.options.rows,
2550
+ cols: overrides?.cols ?? this.#options.cols,
2551
+ rows: overrides?.rows ?? this.#options.rows,
2510
2552
  signal: overrides?.signal
2511
2553
  });
2512
2554
  } catch (error) {
@@ -2517,7 +2559,7 @@ var TerminalStream = class TerminalStream {
2517
2559
  }
2518
2560
  }
2519
2561
  handlersForReconnect(overrides) {
2520
- const lifecycleHandlers = this.options.handlers;
2562
+ const lifecycleHandlers = this.#options.handlers;
2521
2563
  if (overrides === void 0 || lifecycleHandlers?.onClose === void 0) return overrides ?? lifecycleHandlers;
2522
2564
  return {
2523
2565
  ...overrides,
@@ -2669,4 +2711,4 @@ var BrowserInteractiveSessionController = class extends InteractiveSessionContro
2669
2711
  }
2670
2712
  };
2671
2713
  //#endregion
2672
- export { normalizeRuntimeBackendConfig as A, encodePromptForWire as C, assertCurrentBackendType as D, applyRequestedModel as E, createAgentRunOutcomeTracker as F, deriveAgentResultOutcome as I, deriveAgentRunOutcome as L, requestedSecretProfilePublicDigest as M, withProfileHarness as N, foldModelRoutingFields as O, withoutRuntimeSecrets as P, projectAgentTerminalRecord as R, validateAcceptedDispatchRunRef as S, parseSSEStream as T, mintTraceId as _, terminalUpgradeHeadersSupported as a, sessionHeaders as b, requestInteractiveSessionToken as c, isRetryableCredentialRefusal as d, normalizeSessionInfo as f, isTraceId as g, TRACE_ID_HEADER as h, TerminalStreamError as i, requestedPublicProfileDigest as j, mergeRuntimeBackendConfig as k, requestScopedToken as l, waitForRetryAfter as m, InteractiveSessionController as n, TERMINAL_WS_ECHO_SUBPROTOCOL as o, sessionMessageRequestBody as p, TerminalStream as r, assertScopedTokenActive as s, BrowserInteractiveSessionController as t, SandboxRuntimeApi as u, resolveTraceId as v, encodeTextForWire as w, resolveDispatchRunIdentity as x, appendSessionIdQuery as y };
2714
+ export { normalizeRuntimeBackendConfig as A, TERMINAL_WS_ECHO_SUBPROTOCOL as B, encodePromptForWire as C, assertCurrentBackendType as D, applyRequestedModel as E, withoutRuntimeSecrets as F, createAgentRunOutcomeTracker as I, deriveAgentResultOutcome as L, requestedSecretProfilePublicDigest as M, withProfileHarness as N, foldModelRoutingFields as O, withoutCreateOnlyModelFields as P, deriveAgentRunOutcome as R, validateAcceptedDispatchRunRef as S, canUseNodeHttp2 as T, mintTraceId as _, assertScopedTokenActive as a, parseSSEStream as b, SandboxRuntimeApi as c, appendSessionIdQuery as d, sessionHeaders as f, isTraceId as g, TRACE_ID_HEADER as h, terminalUpgradeHeadersSupported as i, requestedPublicProfileDigest as j, mergeRuntimeBackendConfig as k, normalizeSessionInfo as l, waitForRetryAfter as m, InteractiveSessionController as n, requestInteractiveSessionToken as o, isRetryableCredentialRefusal as p, TerminalStream as r, requestScopedToken as s, BrowserInteractiveSessionController as t, sessionMessageRequestBody as u, resolveTraceId as v, encodeTextForWire as w, resolveDispatchRunIdentity as x, traceHeaders as y, projectAgentTerminalRecord as z };