@tangle-network/sandbox 0.63.19 → 0.63.21

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 (65) hide show
  1. package/dist/agent/index.d.ts +4 -4
  2. package/dist/agent/index.js +5 -5
  3. package/dist/agent/preview.d.ts +1 -1
  4. package/dist/agent/preview.js +2 -2
  5. package/dist/{agent-run-outcome-DlYhZnhD.d.ts → agent-run-outcome-C-VR-L0I.d.ts} +1 -1
  6. package/dist/auth/index.d.ts +2 -2
  7. package/dist/auth/index.js +1 -1
  8. package/dist/{backend-types-D6bYbvMB.js → backend-types-zuUBEJO1.js} +35 -1
  9. package/dist/{browser-interactive-control-controller-B6sySQFu.d.ts → browser-interactive-control-controller-CvObO_Kf.d.ts} +1 -1
  10. package/dist/{browser-interactive-control-controller-BJf0P_J4.js → browser-interactive-control-controller-DHx53yre.js} +16 -1
  11. package/dist/{chunked-upload-KJyRCAiC.js → chunked-upload-DN2twsUu.js} +1 -1
  12. package/dist/{chunked-upload-file-DfiGzqaR.js → chunked-upload-file-Dpv1YsoA.js} +2 -2
  13. package/dist/{cli-auth-bundle-CMgB8Ec3.js → cli-auth-bundle-AvhkWJHX.js} +1 -1
  14. package/dist/{client-Dl22CVOz.js → client-5yqzAcFJ.js} +3271 -3271
  15. package/dist/client-CqpKC6n3.d.ts +6066 -0
  16. package/dist/collaboration/index.d.ts +1 -1
  17. package/dist/collaboration/index.js +1 -1
  18. package/dist/{collaboration-XHg5BEUI.js → collaboration-g_HzXa6f.js} +1 -1
  19. package/dist/core.d.ts +6 -7
  20. package/dist/core.js +5 -5
  21. package/dist/{direct-http2-Dq7tq6jV.js → direct-http2-CoGVOqVR.js} +1 -1
  22. package/dist/{errors-AB5BD3FM.js → errors-BfbOP_rx.js} +19 -1
  23. package/dist/{sandbox-DDdPhk2j.d.ts → index-D4OBUP5M.d.ts} +2105 -1461
  24. package/dist/index.d.ts +12 -4747
  25. package/dist/index.js +15 -11
  26. package/dist/intelligence/index.js +1 -1
  27. package/dist/interactive-control.d.ts +1 -1
  28. package/dist/interactive-control.js +1 -1
  29. package/dist/{interactive-controller-BSWoA0YE.d.ts → interactive-controller-BBwB_5QQ.d.ts} +3 -2
  30. package/dist/{interactive-controller-zE6hwv3C.js → interactive-controller-D4N4zqmu.js} +578 -610
  31. package/dist/{lines-hsXVdk60.d.ts → lines-5m11CEj-.d.ts} +21 -17
  32. package/dist/lines-C5ER4aN_.js +298 -0
  33. package/dist/lines.d.ts +1 -1
  34. package/dist/lines.js +1 -295
  35. package/dist/{local-cli-auth-C4QcPdZt.js → local-cli-auth-CSnvjLAP.js} +1 -1
  36. package/dist/{mcp-local-BYHcA72Z.js → mcp-local-BjLG7VHY.js} +1 -1
  37. package/dist/{preview-D8UAF7F9.d.ts → preview-CcJBQSjB.d.ts} +3 -3
  38. package/dist/{public-templates-BP3sTaSb.d.ts → public-templates-nv4AFFVc.d.ts} +2 -2
  39. package/dist/public-templates.d.ts +1 -1
  40. package/dist/public-templates.js +1 -1
  41. package/dist/runtime.d.ts +47 -40
  42. package/dist/runtime.js +4 -4
  43. package/dist/{sandbox-BJkpVtLN.js → sandbox-BGIam_wK.js} +9256 -9215
  44. package/dist/{secp256k1-DoWlH6ff.js → secp256k1-CmLpsmWl.js} +1 -1
  45. package/dist/session-gateway/index.d.ts +16 -17
  46. package/dist/session-gateway/index.js +20 -23
  47. package/dist/tangle/index.d.ts +1 -1
  48. package/dist/tangle/index.js +1 -1
  49. package/dist/{tangle-BBpguPfj.js → tangle--i0MX6UC.js} +144 -138
  50. package/dist/terminal-stream-types-ClZCArRg.d.ts +662 -0
  51. package/dist/{types-BxZX2EVj.d.ts → types-BjyQe_CI.d.ts} +393 -315
  52. package/package.json +5 -5
  53. package/dist/client-DraGbXEP.d.ts +0 -1249
  54. package/dist/error-classes-BWS1a9HO.d.ts +0 -321
  55. package/dist/index-xS3mRl69.d.ts +0 -578
  56. package/dist/managed-process-B-pXdMLC.d.ts +0 -15
  57. package/dist/terminal-stream-DgD7GlFi.d.ts +0 -388
  58. /package/dist/{cli-auth-bundle-BKsrsbxy.d.ts → cli-auth-bundle-Dyw3hCGx.d.ts} +0 -0
  59. /package/dist/{index-DfA_usrZ.d.ts → index-C8VSFtWl.d.ts} +0 -0
  60. /package/dist/{index-CWUW8pqr.d.ts → index-CVjTnRWP.d.ts} +0 -0
  61. /package/dist/{keep-alive-fetch-CXvfSczd.js → keep-alive-fetch-CuwGi7gz.js} +0 -0
  62. /package/dist/{line-application-UtPFP0o4.js → line-application-DY9ZTdgF.js} +0 -0
  63. /package/dist/{preview-operations-Bvo5YcIq.js → preview-operations-Ca02vPDJ.js} +0 -0
  64. /package/dist/{raw-evidence-archive-Bxk6fUjS.js → raw-evidence-archive-CDYDqHNv.js} +0 -0
  65. /package/dist/{utils-B6gap92T.js → utils-BGvM02yJ.js} +0 -0
@@ -1,9 +1,160 @@
1
- import { r as backendTypeSchema } from "./backend-types-D6bYbvMB.js";
2
- import { b as ServerError, n as parseResponseError, o as CapabilityError, p as NetworkError, w as ValidationError, y as SandboxError } from "./errors-AB5BD3FM.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-KJyRCAiC.js";
1
+ import { i as normalizeEffectiveBackend, r as backendTypeSchema } from "./backend-types-zuUBEJO1.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;
@@ -743,6 +894,101 @@ function requestedSecretProfilePublicDigest(backend) {
743
894
  }) ?? {});
744
895
  }
745
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
746
992
  //#region ../../../packages/sse-core/dist/index.js
747
993
  /**
748
994
  * A copy of `value` that shares no memory with the string it was cut from.
@@ -969,104 +1215,7 @@ async function* parseSSEStream(body, options) {
969
1215
  }
970
1216
  }
971
1217
  //#endregion
972
- //#region src/lib/wire-encoding.ts
973
- /**
974
- * Encode a prompt text part for the wire. Server decodes at the route
975
- * boundary; the LLM only ever sees the original UTF-8. Done
976
- * unconditionally because readable bodies false-positive on ingress WAF
977
- * rules that pattern-match shell-injection-shaped substrings (which
978
- * legitimate prompts routinely contain — e.g. Step-0 dev-server
979
- * bootstrap).
980
- */
981
- function encodeTextForWire(text) {
982
- if (typeof Buffer !== "undefined") return Buffer.from(text, "utf8").toString("base64");
983
- if (typeof btoa === "function") return btoa(encodeURIComponent(text).replace(/%([0-9A-F]{2})/g, (_, h) => String.fromCharCode(Number.parseInt(h, 16))));
984
- throw new Error("encodeTextForWire: no base64 encoder available (Buffer and btoa both undefined)");
985
- }
986
- /**
987
- * Convert a caller-supplied prompt (string or parts array) into the
988
- * wire-format parts array. Every text part is base64-encoded; non-text
989
- * parts pass through. A bare string is wrapped in a single text part.
990
- */
991
- function encodePromptForWire(message) {
992
- return (typeof message === "string" ? [{
993
- type: "text",
994
- text: message
995
- }] : message).map((part) => part.type === "text" ? {
996
- type: "text",
997
- text: encodeTextForWire(part.text)
998
- } : part);
999
- }
1000
- //#endregion
1001
- //#region src/dispatch-run-control.ts
1002
- const DISPATCH_RUN_PROVIDER = "tangle-sandbox";
1003
- function generateRuntimeId(prefix) {
1004
- const crypto = globalThis.crypto;
1005
- if (crypto?.randomUUID) return `${prefix}-${crypto.randomUUID()}`;
1006
- if (crypto?.getRandomValues) {
1007
- const bytes = crypto.getRandomValues(new Uint8Array(16));
1008
- return `${prefix}-${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
1009
- }
1010
- throw new ValidationError("Run identity generation requires global crypto");
1011
- }
1012
- function resolveDispatchRunIdentity(sandboxId, message, options) {
1013
- const sessionId = options?.sessionId ?? options?.runControlRef?.sessionId ?? generateRuntimeId("session");
1014
- const executionId = options?.executionId ?? options?.runControlRef?.executionId ?? generateRuntimeId("execution");
1015
- return {
1016
- sessionId,
1017
- executionId,
1018
- runControlRef: options?.runControlRef ?? {
1019
- runId: generateRuntimeId("run"),
1020
- provider: DISPATCH_RUN_PROVIDER,
1021
- environmentId: sandboxId,
1022
- sessionId,
1023
- executionId,
1024
- requestDigest: canonicalCandidateDigest({
1025
- message,
1026
- sessionId,
1027
- turnId: options?.turnId ?? null,
1028
- backend: options?.backend ?? null,
1029
- model: options?.model ?? null,
1030
- context: options?.context ?? null
1031
- })
1032
- }
1033
- };
1034
- }
1035
- function sameExactRunControlRef(left, right) {
1036
- 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;
1037
- }
1038
- function validateAcceptedDispatchRunRef(raw, expected, sandboxId, sessionId, executionId, endpoint = "/agents/run/stream") {
1039
- const parsed = AgentExactRunControlRefSchema.safeParse(raw);
1040
- if (!parsed.success) throw new ServerError("Sandbox returned an invalid exact run reference on admission", 502, {
1041
- origin: "runtime",
1042
- endpoint
1043
- });
1044
- const accepted = parsed.data;
1045
- 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, {
1046
- origin: "runtime",
1047
- endpoint
1048
- });
1049
- return accepted;
1050
- }
1051
- //#endregion
1052
- //#region src/lib/session-id.ts
1053
- const SESSION_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;
1054
- function assertValidSessionId(value) {
1055
- 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}`);
1056
- }
1057
- function sessionHeaders(sessionId) {
1058
- if (sessionId === void 0) return void 0;
1059
- assertValidSessionId(sessionId);
1060
- return { "X-Session-Id": sessionId };
1061
- }
1062
- function appendSessionIdQuery(params, sessionId) {
1063
- if (sessionId === void 0) return false;
1064
- assertValidSessionId(sessionId);
1065
- params.set("sessionId", sessionId);
1066
- return true;
1067
- }
1068
- //#endregion
1069
- //#region src/lib/trace-id.ts
1218
+ //#region src/lib/trace-id.ts
1070
1219
  /**
1071
1220
  * Request header that carries one turn's trace id. The Sandbox API adopts it
1072
1221
  * as the request's correlation id, the orchestrator logs it on every proxied
@@ -1112,7 +1261,7 @@ function traceHeaders(traceId) {
1112
1261
  return { [TRACE_ID_HEADER]: resolveTraceId(traceId) };
1113
1262
  }
1114
1263
  //#endregion
1115
- //#region src/runtime-api.ts
1264
+ //#region src/runtime-credential-retry.ts
1116
1265
  /** A 503 the runtime answers before any work starts; the request may be resent. */
1117
1266
  function isRetryableCredentialRefusal(error) {
1118
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");
@@ -1138,8 +1287,26 @@ function waitForRetryAfter(delayMs, signal) {
1138
1287
  signal?.addEventListener("abort", onAbort, { once: true });
1139
1288
  });
1140
1289
  }
1141
- /** Internal typed client for routes served by a sandbox runtime. */
1142
- 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 {
1143
1310
  terminals;
1144
1311
  constructor(transport) {
1145
1312
  this.transport = transport;
@@ -1170,104 +1337,53 @@ var SandboxRuntimeApi = class {
1170
1337
  await this.transport.ensureRunning();
1171
1338
  return (await this.json("/ports", { method: "GET" })).data?.ports ?? [];
1172
1339
  }
1173
- /**
1174
- * Subscribe to a session's agent event stream (`/agents/events`).
1175
- *
1176
- * The consume half of the supervisor pattern: construct the client from a
1177
- * `read-only` or `session-runtime` scoped token
1178
- * (`SandboxInstance.mintScopedToken`) and a parent agent observes a child
1179
- * sandbox's stream while holding no credential that can mutate the child.
1180
- * With `executionId` set, the stream ends at that turn's terminal
1181
- * `done`/`error` event; a stream that dies before the terminal throws
1182
- * instead of reading like a finished turn. Aborting `options.signal` ends
1183
- * the generator cleanly, matching every other SDK stream. Events carry no
1184
- * `data.sandboxId` stamp here: a scoped-token client knows only its own
1185
- * runtime URL, and the subscriber already knows which sandbox it minted
1186
- * the token for.
1187
- */
1188
- async *events(sessionId, options = {}) {
1340
+ async createTerminal(options = {}, request = {}) {
1341
+ const params = new URLSearchParams();
1342
+ appendSessionIdQuery(params, request.sessionId);
1343
+ const query = params.toString();
1189
1344
  await this.transport.ensureRunning();
1190
- const search = new URLSearchParams();
1191
- search.set("sessionId", sessionId);
1192
- if (options.since) search.set("since", options.since);
1193
- if (options.executionId) search.set("executionId", options.executionId);
1194
- const response = await this.request(`/agents/events?${search.toString()}`, { signal: options.signal });
1195
- if (!response.body) throw new NetworkError("event stream has no response body");
1196
- let sawTerminal = false;
1197
- try {
1198
- for await (const event of parseSSEStream(response.body, {
1199
- signal: options.signal,
1200
- invalidEvent: "warn-and-skip"
1201
- })) {
1202
- yield {
1203
- type: event.type,
1204
- data: event.data,
1205
- ...event.id !== void 0 ? { id: event.id } : {}
1206
- };
1207
- if (options.executionId !== void 0 && (event.type === "done" || event.type === "error")) {
1208
- sawTerminal = true;
1209
- return;
1210
- }
1211
- }
1212
- } catch (err) {
1213
- if (err instanceof DOMException && err.name === "AbortError") return;
1214
- throw err;
1215
- }
1216
- 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;
1217
1349
  }
1218
- /** Read a turn's retained admission without proposing or admitting a message. */
1219
- async admission(sessionId, turnId, options = {}) {
1220
- 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();
1221
1354
  await this.transport.ensureRunning();
1222
- const endpoint = `/agents/sessions/${encodeURIComponent(sessionId)}/admissions/${encodeURIComponent(turnId)}`;
1223
- const payload = await this.json(endpoint, {
1224
- method: "GET",
1225
- signal: options.signal
1226
- });
1227
- if (payload?.receipt === null) return null;
1228
- const receipt = payload?.receipt;
1229
- if (!receipt || typeof receipt.info?.id !== "string" || !receipt.info.id || receipt.processing !== true) throw new ServerError("Runtime returned an invalid message admission receipt", 502, {
1230
- origin: "runtime",
1231
- endpoint
1232
- });
1233
- const parsedRef = receipt.runControlRef === void 0 ? void 0 : AgentExactRunControlRefSchema.safeParse(receipt.runControlRef);
1234
- if (parsedRef && !parsedRef.success) throw new ServerError("Admission returned an invalid exact run reference", 502, {
1235
- origin: "runtime",
1236
- endpoint
1237
- });
1238
- const runControlRef = parsedRef?.data;
1239
- if (runControlRef && (runControlRef.sessionId !== sessionId || runControlRef.executionId !== receipt.info.id)) throw new ServerError("Admission control reference does not match its execution", 502, {
1240
- origin: "runtime",
1241
- endpoint
1355
+ await this.request(`/terminals/${encodeURIComponent(terminalId)}/input${query ? `?${query}` : ""}`, {
1356
+ method: "POST",
1357
+ body: JSON.stringify({ data })
1242
1358
  });
1243
- const run = (await this.runs(sessionId, options)).find((candidate) => candidate.executionId === receipt.info.id);
1244
- return {
1245
- sessionId,
1246
- turnId,
1247
- executionId: receipt.info.id,
1248
- status: run?.status ?? "unavailable",
1249
- ...runControlRef ? { runControlRef } : {}
1250
- };
1251
1359
  }
1252
- /** List validated execution records from the runtime ledger, newest first. */
1253
- async runs(sessionId, options = {}) {
1360
+ async listTerminals() {
1254
1361
  await this.transport.ensureRunning();
1255
- const endpoint = `/agents/sessions/${encodeURIComponent(sessionId)}/runs`;
1256
- const payload = await this.json(endpoint, {
1257
- method: "GET",
1258
- signal: options.signal
1259
- });
1260
- if (payload.success !== true || !Array.isArray(payload.executions)) throw new ServerError("Session runs response has an invalid shape", 502, {
1261
- origin: "runtime",
1262
- endpoint
1263
- });
1264
- const executions = payload.executions.map((value) => normalizeSessionExecutionInfo(value, sessionId));
1265
- if (executions.some((execution) => execution === null)) throw new ServerError("Session runs response has an invalid execution", 502, {
1266
- origin: "runtime",
1267
- endpoint
1268
- });
1269
- return executions.filter((execution) => execution !== null);
1362
+ return (await this.json("/terminals", { method: "GET" })).data ?? [];
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;
1270
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 {
1271
1387
  async readFiles(paths, options = {}) {
1272
1388
  const params = new URLSearchParams();
1273
1389
  appendSessionIdQuery(params, options.sessionId);
@@ -1401,193 +1517,12 @@ var SandboxRuntimeApi = class {
1401
1517
  await this.transport.ensureRunning();
1402
1518
  return (await this.json(`/files/usage?${params}`, { method: "GET" })).data;
1403
1519
  }
1404
- async createSession(options) {
1405
- await this.transport.ensureRunning();
1406
- const backend = normalizeRuntimeBackendConfig(options.backend);
1407
- const info = normalizeSessionInfo(await this.json("/agents/sessions", {
1408
- method: "POST",
1409
- body: JSON.stringify({
1410
- ...options.sessionId !== void 0 ? { sessionId: options.sessionId } : {},
1411
- ...options.title !== void 0 ? { title: options.title } : {},
1412
- ...options.retention !== void 0 ? { retention: options.retention } : {},
1413
- ...options.parentId !== void 0 ? { parentID: options.parentId } : {},
1414
- ...options.workspaceRoot !== void 0 ? { workspaceRoot: options.workspaceRoot } : {},
1415
- ...options.conversationHistory !== void 0 ? { conversationHistory: options.conversationHistory } : {},
1416
- ...options.importFromSessionId !== void 0 ? { importFromSessionId: options.importFromSessionId } : {},
1417
- ...backend && Object.keys(backend).length > 0 ? { backend } : {}
1418
- })
1419
- }));
1420
- if (!info) throw new ServerError("Session creation response missing session id", 502, {
1421
- endpoint: "/agents/sessions",
1422
- origin: "runtime"
1423
- });
1424
- return info;
1425
- }
1426
- async messages(id, options = {}) {
1427
- await this.transport.ensureRunning();
1428
- const params = new URLSearchParams({ sessionId: id });
1429
- if (options.limit !== void 0) params.set("limit", String(options.limit));
1430
- if (options.offset !== void 0) params.set("offset", String(options.offset));
1431
- if (options.since !== void 0) params.set("since", String(options.since));
1432
- const query = params.toString();
1433
- return (await this.json(`/messages${query ? `?${query}` : ""}`, { method: "GET" })).map((message) => ({
1434
- id: message.info.id,
1435
- role: message.info.role,
1436
- timestamp: message.info.timestamp,
1437
- parts: message.parts,
1438
- metadata: message.info.metadata
1439
- }));
1440
- }
1441
- async createTaskSession(options) {
1442
- await this.transport.ensureRunning();
1443
- const info = await this.json("/tasks", {
1444
- method: "POST",
1445
- body: JSON.stringify({
1446
- sessionId: options.sessionId,
1447
- backend: normalizeRuntimeBackendConfig(options.backend),
1448
- title: options.title,
1449
- ...options.parentSessionId !== void 0 ? { parentSessionId: options.parentSessionId } : {},
1450
- ...options.profile !== void 0 ? { profile: options.profile } : {},
1451
- ...options.isolateFileWrites !== void 0 ? { isolateFileWrites: options.isolateFileWrites } : {}
1452
- })
1453
- });
1454
- if (!info.id) throw new ServerError("Task session creation response missing session id", 502, {
1455
- endpoint: "/tasks",
1456
- origin: "runtime"
1457
- });
1458
- return info;
1459
- }
1460
- async sendSessionMessage(id, request, options = {}) {
1461
- if (options.timeoutMs !== void 0 && options.timeoutMs <= 0) throw new ValidationError("timeoutMs must be greater than zero");
1462
- await this.transport.ensureRunning();
1463
- const headers = new Headers({
1464
- "content-type": "application/json",
1465
- "x-no-retry": "true"
1466
- });
1467
- if (options.planFollowUp) {
1468
- 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");
1469
- headers.set("x-tangle-plan-followup-credential", options.planFollowUp.credential);
1470
- headers.set("x-tangle-plan-followup-callback", options.planFollowUp.callbackUrl);
1471
- }
1472
- if (options.credentials?.apiKey) headers.set("X-Backend-Api-Key", options.credentials.apiKey);
1473
- if (options.credentials?.baseUrl) headers.set("X-Backend-Base-Url", options.credentials.baseUrl);
1474
- if (options.traceId !== void 0) headers.set(TRACE_ID_HEADER, resolveTraceId(options.traceId));
1475
- const timeoutSignal = options.timeoutMs !== void 0 ? AbortSignal.timeout(options.timeoutMs) : void 0;
1476
- const signal = options.signal && timeoutSignal ? combineAbortSignals([options.signal, timeoutSignal]) : options.signal ?? timeoutSignal;
1477
- const path = `/agents/sessions/${encodeURIComponent(id)}/messages`;
1478
- const init = {
1479
- method: "POST",
1480
- headers,
1481
- signal,
1482
- body: JSON.stringify(sessionMessageRequestBody(request))
1483
- };
1484
- let receipt;
1485
- try {
1486
- receipt = await this.json(path, init);
1487
- } catch (error) {
1488
- if (options.planFollowUp || !isRetryableCredentialRefusal(error)) throw error;
1489
- await waitForRetryAfter(error.retryAfterMs ?? 1e3, signal);
1490
- receipt = await this.json(path, init);
1491
- }
1492
- if (request.runControlRef) validateAcceptedDispatchRunRef(receipt.runControlRef, request.runControlRef, request.runControlRef.environmentId, id, receipt.info.id, path);
1493
- return receipt;
1494
- }
1495
- async deleteSession(id) {
1496
- await this.transport.ensureRunning();
1497
- await this.request(`/agents/sessions/${encodeURIComponent(id)}`, { method: "DELETE" });
1498
- }
1499
- async taskSessionChanges(id) {
1500
- await this.transport.ensureRunning();
1501
- return this.json(`/tasks/${encodeURIComponent(id)}/changes`, { method: "GET" });
1502
- }
1503
- async commitTaskSession(id, options = {}) {
1504
- await this.transport.ensureRunning();
1505
- return this.json(`/tasks/${encodeURIComponent(id)}/changes`, {
1506
- method: "POST",
1507
- body: JSON.stringify({
1508
- ...options.message !== void 0 ? { message: options.message } : {},
1509
- ...options.files !== void 0 ? { files: options.files } : {}
1510
- })
1511
- });
1512
- }
1513
- async createTerminal(options = {}, request = {}) {
1514
- const params = new URLSearchParams();
1515
- appendSessionIdQuery(params, request.sessionId);
1516
- const query = params.toString();
1517
- await this.transport.ensureRunning();
1518
- return (await this.json(`/terminals${query ? `?${query}` : ""}`, {
1519
- method: "POST",
1520
- body: JSON.stringify(options)
1521
- })).data;
1522
- }
1523
- async writeTerminal(terminalId, data, request = {}) {
1524
- const params = new URLSearchParams();
1525
- appendSessionIdQuery(params, request.sessionId);
1526
- const query = params.toString();
1527
- await this.transport.ensureRunning();
1528
- await this.request(`/terminals/${encodeURIComponent(terminalId)}/input${query ? `?${query}` : ""}`, {
1529
- method: "POST",
1530
- body: JSON.stringify({ data })
1531
- });
1532
- }
1533
- async listTerminals() {
1534
- await this.transport.ensureRunning();
1535
- return (await this.json("/terminals", { method: "GET" })).data ?? [];
1536
- }
1537
- async getTerminal(terminalId) {
1538
- await this.transport.ensureRunning();
1539
- const response = await this.transport.fetch(`/terminals/${encodeURIComponent(terminalId)}`, { method: "GET" });
1540
- if (response.status === 404) return null;
1541
- await this.assertOk(response);
1542
- return (await response.json()).data;
1543
- }
1544
- async json(path, init) {
1545
- return await (await this.request(path, init)).json();
1546
- }
1547
- async request(path, init) {
1548
- const response = await this.transport.fetch(path, init);
1549
- await this.assertOk(response);
1550
- return response;
1551
- }
1552
- async assertOk(response) {
1553
- if (response.ok) return;
1554
- throw await parseResponseError(response);
1555
- }
1556
1520
  };
1557
- const EFFECTIVE_BACKEND_SOURCES = [
1558
- "request",
1559
- "environment",
1560
- "profile"
1561
- ];
1521
+ //#endregion
1522
+ //#region src/runtime-session-normalize.ts
1562
1523
  function nonEmptyField(value) {
1563
1524
  return typeof value === "string" && value.length > 0 ? value : void 0;
1564
1525
  }
1565
- function normalizeEffectiveBackendProfile(value) {
1566
- if (!value || typeof value !== "object") return void 0;
1567
- const raw = value;
1568
- const digest = nonEmptyField(raw.digest);
1569
- if (!digest) return void 0;
1570
- const name = nonEmptyField(raw.name);
1571
- return {
1572
- ...name ? { name } : {},
1573
- digest
1574
- };
1575
- }
1576
- function normalizeEffectiveBackend(value) {
1577
- if (!value || typeof value !== "object") return void 0;
1578
- const raw = value;
1579
- const provider = nonEmptyField(raw.provider);
1580
- const model = nonEmptyField(raw.model);
1581
- const profile = normalizeEffectiveBackendProfile(raw.profile);
1582
- if (!provider && !model && !profile) return void 0;
1583
- const source = nonEmptyField(raw.source);
1584
- return {
1585
- ...provider ? { provider } : {},
1586
- ...model ? { model } : {},
1587
- ...source && EFFECTIVE_BACKEND_SOURCES.includes(source) ? { source } : {},
1588
- ...profile ? { profile } : {}
1589
- };
1590
- }
1591
1526
  function normalizeSessionFailureReason(value) {
1592
1527
  if (!value || typeof value !== "object") return void 0;
1593
1528
  const raw = value;
@@ -1708,20 +1643,220 @@ function sessionMessageRequestBody(request) {
1708
1643
  };
1709
1644
  }
1710
1645
  //#endregion
1711
- //#region src/lib/runtime-env.ts
1712
- /**
1713
- * True inside a Cloudflare Worker. Under `nodejs_compat` workerd sets
1714
- * `process.versions.node`, but it ships `node:http2` as a stub whose `connect()`
1715
- * throws "The http2.connect method is not implemented", so `process.versions`
1716
- * cannot tell a Worker from Node. The user agent can.
1717
- */
1718
- function isCloudflareWorker() {
1719
- return globalThis.navigator?.userAgent?.startsWith("Cloudflare-Workers") === true;
1720
- }
1721
- /** True where `node:http2` can open a session: Node, but not a Worker. */
1722
- function canUseNodeHttp2() {
1723
- return typeof process !== "undefined" && typeof process.versions?.node === "string" && !isCloudflareWorker();
1724
- }
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
+ };
1725
1860
  //#endregion
1726
1861
  //#region src/scoped-token.ts
1727
1862
  /** Maximum time for the exact interactive terminal-token request. */
@@ -1805,221 +1940,8 @@ function requestInteractiveSessionToken(client, ref, options) {
1805
1940
  const exact = interactiveSessionTokenOptions(ref, options);
1806
1941
  return requestScopedToken(client, exact.sandboxId, exact.request, { timeoutMs: SCOPED_TOKEN_REQUEST_TIMEOUT_MS });
1807
1942
  }
1808
- const TERMINAL_WS_MAX_DIMENSION = 4096;
1809
- /** Input chunk size that leaves room for JSON escaping inside one frame. */
1810
- const TERMINAL_WS_INPUT_FRAME_CHUNK_CHARS = 128 * 1024;
1811
- /** WebSocket authentication envelope prefixes. */
1812
- const TERMINAL_WS_EDGE_BEARER_SUBPROTOCOL_PREFIX = "bearer.";
1813
- const TERMINAL_WS_SIDECAR_BEARER_SUBPROTOCOL_PREFIX = "tangle.bearer.";
1814
- /** Non-credential protocol selected during a successful terminal handshake. */
1815
- const TERMINAL_WS_ECHO_SUBPROTOCOL = "tangle.terminal.v1";
1816
- /**
1817
- * Encode the upgrade URL's query (no leading `?`): the size of a
1818
- * default-shell attach with its flag, and the trace id. Nothing else rides the
1819
- * URL.
1820
- */
1821
- function encodeTerminalUpgradeQuery(input) {
1822
- const params = new URLSearchParams();
1823
- if (input.defaultShell !== void 0) {
1824
- params.set("cols", String(input.defaultShell.cols));
1825
- params.set("rows", String(input.defaultShell.rows));
1826
- params.set("defaultShell", "1");
1827
- }
1828
- if (input.traceId !== void 0) params.set("traceId", input.traceId);
1829
- return params.toString();
1830
- }
1831
- const terminalGeometry = {
1832
- cols: z.number().int().min(1).max(TERMINAL_WS_MAX_DIMENSION),
1833
- rows: z.number().int().min(1).max(TERMINAL_WS_MAX_DIMENSION)
1834
- };
1835
- const terminalInitMessageSchema = z.object({
1836
- type: z.literal("init"),
1837
- connectionId: z.string().optional(),
1838
- /** Required for an interactive-agent PTY; absent for generic terminals. */
1839
- incarnationId: z.string().uuid().optional(),
1840
- ...terminalGeometry,
1841
- command: z.string().min(1).optional(),
1842
- cwd: z.string().min(1).optional(),
1843
- env: z.record(z.string(), z.string()).optional(),
1844
- sessionId: z.string().min(1).optional(),
1845
- /** Canonical control claim for an interactive-agent PTY. */
1846
- control: AgentInteractiveSessionControlClaimSchema.optional(),
1847
- /**
1848
- * Caller trace id for a browser, which cannot set `x-tangle-trace-id` on
1849
- * the upgrade. The server adopts it only when it is a well-formed id.
1850
- */
1851
- traceId: z.string().max(200).optional()
1852
- }).superRefine((message, refinement) => {
1853
- if (message.incarnationId !== void 0 && message.control === void 0) refinement.addIssue({
1854
- code: "custom",
1855
- path: ["control"],
1856
- message: "Interactive session attach requires a control claim"
1857
- });
1858
- if (message.incarnationId === void 0 && message.control !== void 0) refinement.addIssue({
1859
- code: "custom",
1860
- path: ["control"],
1861
- message: "Generic terminal attach cannot carry an interactive control claim"
1862
- });
1863
- });
1864
- const terminalInputMessageSchema = z.object({
1865
- type: z.literal("input"),
1866
- data: z.string()
1867
- });
1868
- const terminalResizeMessageSchema = z.object({
1869
- type: z.literal("resize"),
1870
- ...terminalGeometry
1871
- });
1872
- const terminalRenewMessageSchema = z.object({ type: z.literal("renew") });
1873
- const terminalCloseMessageSchema = z.object({ type: z.literal("close") });
1874
- z.union([
1875
- terminalInitMessageSchema,
1876
- terminalInputMessageSchema,
1877
- terminalResizeMessageSchema,
1878
- terminalRenewMessageSchema,
1879
- terminalCloseMessageSchema
1880
- ]);
1881
- /**
1882
- * Server stamps for one attach, in epoch milliseconds on the sidecar's clock.
1883
- * They are absolute so a caller can lay them against its own marks and read
1884
- * each leg (client clock skew is the only error). `spawn*` and `initPersistAt`
1885
- * are absent when the attach adopted a PTY that already existed.
1886
- */
1887
- const terminalReadyTimingsSchema = z.object({
1888
- /** The upgrade request reached the sidecar's upgrade handler. */
1889
- upgradeAt: z.number(),
1890
- /** The bearer was verified (`ws.auth` ends). */
1891
- authAt: z.number(),
1892
- /** The init parameters were in hand: at the upgrade for `via: "upgrade"`, on the init frame otherwise. */
1893
- initAt: z.number(),
1894
- /** `loadOrCreateConnection` started. */
1895
- loadAt: z.number(),
1896
- /** The PTY process was spawned (`pty.spawn` ends). */
1897
- spawnAt: z.number().optional(),
1898
- /** The `session.init` event was persisted (`session.init.persist` ends). */
1899
- initPersistAt: z.number().optional(),
1900
- /** `loadOrCreateConnection` returned. */
1901
- loadedAt: z.number(),
1902
- /** The retained history was read (`history.read` ends). */
1903
- historyAt: z.number(),
1904
- /** Retained events and bytes the replay will carry. */
1905
- historyEvents: z.number().int().nonnegative(),
1906
- historyBytes: z.number().int().nonnegative(),
1907
- /** The `ready` frame was sent. */
1908
- readyAt: z.number(),
1909
- /** How the init parameters reached the server. */
1910
- via: z.enum(["upgrade", "frame"]),
1911
- /** Correlation id of this attach (`terminal_attach` spans share it). */
1912
- ptid: z.string().optional()
1913
- });
1914
- const terminalReadyMessageSchema = z.object({
1915
- type: z.literal("ready"),
1916
- connectionId: z.string(),
1917
- sessionId: z.string(),
1918
- restored: z.boolean(),
1919
- detachTimeoutMs: z.number().int().positive(),
1920
- /** Exact viewer count held by the runtime for this connection. */
1921
- attachCount: z.number().int().positive().optional(),
1922
- /** Server-issued output cursor window for exact interactive terminals. */
1923
- cursors: z.object({
1924
- earliest: z.number().int().nonnegative(),
1925
- latest: z.number().int().nonnegative()
1926
- }).optional(),
1927
- /** Server stamps for this attach; absent from a sidecar that predates them. */
1928
- timings: terminalReadyTimingsSchema.optional()
1929
- });
1930
- /** One sequenced output frame for an exact interactive terminal. */
1931
- const terminalOutputMessageSchema = z.object({
1932
- type: z.literal("output"),
1933
- seq: z.number().int().positive(),
1934
- /** Base64-encoded UTF-8 bytes from the retained terminal event. */
1935
- data: z.string().min(1)
1936
- });
1937
- const terminalExitMessageSchema = z.object({
1938
- type: z.literal("exit"),
1939
- exitCode: z.number().optional(),
1940
- exitSignal: z.string().optional()
1941
- });
1942
- const terminalRenewedMessageSchema = z.object({
1943
- type: z.literal("renewed"),
1944
- sessionId: z.string()
1945
- });
1946
- const terminalErrorMessageSchema = z.object({
1947
- type: z.literal("error"),
1948
- code: z.string(),
1949
- message: z.string()
1950
- });
1951
- const terminalServerMessageSchema = z.union([
1952
- terminalReadyMessageSchema,
1953
- terminalOutputMessageSchema,
1954
- terminalExitMessageSchema,
1955
- terminalRenewedMessageSchema,
1956
- terminalErrorMessageSchema
1957
- ]);
1958
1943
  //#endregion
1959
- //#region src/terminal-stream.ts
1960
- /**
1961
- * TerminalStream — typed client for the sandbox terminal WebSocket protocol.
1962
- *
1963
- * Drives a live PTY session (an interactive harness TUI or a plain shell)
1964
- * from the caller's own program: binary frames stream raw PTY output bytes,
1965
- * TEXT JSON frames carry the control protocol. The browser-safe wire contract
1966
- * is defined by the shared browser-safe runtime contract and shared with the
1967
- * sidecar:
1968
- *
1969
- * client → server (TEXT JSON):
1970
- * init {connectionId?, cols, rows, command?, cwd?, env?} — MUST be first
1971
- * input {data}
1972
- * resize {cols, rows}
1973
- *
1974
- * Interactive-agent init frames add the exact process authority:
1975
- * {incarnationId, control: {refDigest, generation, leaseId, holderId, expiresAt}}
1976
- * Subsequent input and resize frames carry only their operation fields; the
1977
- * server binds authority to the init for the socket lifetime.
1978
- * server → client (TEXT JSON):
1979
- * ready {connectionId, sessionId, restored, detachTimeoutMs,
1980
- * attachCount?, cursors?}
1981
- * output {seq, data} — exact interactive output as base64 UTF-8 bytes
1982
- * exit {exitCode?, exitSignal?}
1983
- * error {code, message}
1984
- * rec / rec.done — recording tee frames for the platform's session
1985
- * capture consumer; not part of the client surface
1986
- * server → client (BINARY): raw PTY output bytes
1987
- *
1988
- * A default-shell attach (no `command`, `cwd`, `env` or interactive identity)
1989
- * also puts `cols`, `rows` and `defaultShell=1` on the upgrade URL. A server
1990
- * that reads them starts the PTY when it accepts the upgrade and sends `ready`
1991
- * without waiting for `init`; the `init` frame is still sent, first, and that
1992
- * server ignores it. A server that does not read them waits for `init` exactly
1993
- * as before. `command` and `cwd` travel only in the `init` frame, inside the
1994
- * WebSocket: the URL and the request headers reach access logs.
1995
- *
1996
- * Detach/reconnect: the server keeps the PTY alive for `detachTimeoutMs`
1997
- * (5 minutes today) after the socket closes; re-dialing with the SAME
1998
- * connectionId reattaches and replays the buffered output history, so a
1999
- * fresh client repaints the current screen.
2000
- *
2001
- * Browser-safe: uses the global `WebSocket` (browsers, Workers, Node >= 22)
2002
- * and never imports `ws` — the same environment contract as
2003
- * `session-gateway/client.ts`.
2004
- */
2005
- /** A protocol `error` control frame or a transport failure. */
2006
- var TerminalStreamError = class extends Error {
2007
- /** Protocol error code (e.g. `INIT_FAILED`) or `TRANSPORT` for socket faults. */
2008
- code;
2009
- /**
2010
- * True when the socket never reached OPEN: the upgrade was refused (a
2011
- * WebSocket client cannot read the HTTP status, so a 401 and a network drop
2012
- * look alike) or the runtime rejected the dial's options. No PTY work had
2013
- * started on the client's side of that dial.
2014
- */
2015
- beforeOpen;
2016
- constructor(message, code, options = {}) {
2017
- super(message);
2018
- this.name = "TerminalStreamError";
2019
- this.code = code;
2020
- this.beforeOpen = options.beforeOpen === true;
2021
- }
2022
- };
1944
+ //#region src/terminal-stream-protocol.ts
2023
1945
  /**
2024
1946
  * The sidecar caps WebSocket frames at 1 MiB
2025
1947
  * (`TERMINAL_WS_MAX_PAYLOAD_BYTES` in the shared runtime contract) and drops
@@ -2031,7 +1953,6 @@ var TerminalStreamError = class extends Error {
2031
1953
  */
2032
1954
  const DEFAULT_COLS = 80;
2033
1955
  const DEFAULT_ROWS = 24;
2034
- const DEFAULT_CONNECT_TIMEOUT_MS = 15e3;
2035
1956
  /**
2036
1957
  * base64url-encode a UTF-8 string without padding — the exact envelope the
2037
1958
  * edge's `parseTerminalWsSubprotocolToken` decodes (its strict round-trip
@@ -2256,6 +2177,53 @@ function* chunkInput(text) {
2256
2177
  index = end;
2257
2178
  }
2258
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
+ */
2259
2227
  /**
2260
2228
  * Client for one terminal WebSocket connection. Construct via
2261
2229
  * {@link TerminalStream.connect}, which resolves once the server
@@ -2321,7 +2289,7 @@ var TerminalStream = class TerminalStream {
2321
2289
  return new Promise((resolve, reject) => {
2322
2290
  let settled = false;
2323
2291
  let opened = false;
2324
- const timeoutMs = this.#options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
2292
+ const timeoutMs = this.#options.connectTimeoutMs ?? 15e3;
2325
2293
  const timer = setTimeout(() => {
2326
2294
  fail(new TerminalStreamError(`Terminal attach timed out after ${timeoutMs}ms waiting for ready`, "CONNECT_TIMEOUT"));
2327
2295
  this.ws.close(1e3, "connect timeout");
@@ -2743,4 +2711,4 @@ var BrowserInteractiveSessionController = class extends InteractiveSessionContro
2743
2711
  }
2744
2712
  };
2745
2713
  //#endregion
2746
- export { assertCurrentBackendType as A, deriveAgentResultOutcome as B, sessionHeaders as C, encodeTextForWire as D, encodePromptForWire as E, requestedSecretProfilePublicDigest as F, projectAgentTerminalRecord as H, withProfileHarness as I, withoutCreateOnlyModelFields as L, mergeRuntimeBackendConfig as M, normalizeRuntimeBackendConfig as N, parseSSEStream as O, requestedPublicProfileDigest as P, withoutRuntimeSecrets as R, appendSessionIdQuery as S, validateAcceptedDispatchRunRef as T, deriveAgentRunOutcome as V, TRACE_ID_HEADER as _, terminalUpgradeHeadersSupported as a, resolveTraceId as b, requestInteractiveSessionToken as c, SandboxRuntimeApi as d, isRetryableCredentialRefusal as f, waitForRetryAfter as g, sessionMessageRequestBody as h, TerminalStreamError as i, foldModelRoutingFields as j, applyRequestedModel as k, requestScopedToken as l, normalizeSessionInfo as m, InteractiveSessionController as n, TERMINAL_WS_ECHO_SUBPROTOCOL as o, normalizeEffectiveBackend as p, TerminalStream as r, assertScopedTokenActive as s, BrowserInteractiveSessionController as t, canUseNodeHttp2 as u, isTraceId as v, resolveDispatchRunIdentity as w, traceHeaders as x, mintTraceId as y, createAgentRunOutcomeTracker as z };
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 };