@tangle-network/sandbox 0.59.0 → 0.60.1-develop.20261001222100.ea1ca0e935
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/dist/agent/index.d.ts +4 -4
- package/dist/agent/index.js +4 -4
- package/dist/agent/preview.d.ts +2 -2
- package/dist/agent/preview.js +54 -4
- package/dist/{agent-run-outcome-C45u1fzK.d.ts → agent-run-outcome-C1GJ1YCD.d.ts} +2 -1
- package/dist/auth/index.js +1 -1
- package/dist/{browser-interactive-control-controller-DRBQ-jf0.js → browser-interactive-control-controller-BJf0P_J4.js} +40 -3
- package/dist/{browser-interactive-control-controller-BzR8sFjo.d.ts → browser-interactive-control-controller-C2qVGzQz.d.ts} +7 -2
- package/dist/{cli-auth-bundle-CzmAaefZ.js → cli-auth-bundle-ChOdvrjd.js} +1 -1
- package/dist/{client-DYgEM_h5.d.ts → client-jPPuv6Ns.d.ts} +4 -4
- package/dist/{client-BbiV61Yy.js → client-p2T45dAv.js} +5 -5
- package/dist/collaboration/index.js +1 -1
- package/dist/core.d.ts +4 -4
- package/dist/core.js +3 -3
- package/dist/{index-C8Y65I3y.d.ts → index-CZjj0Wj3.d.ts} +2 -2
- package/dist/index.d.ts +10 -9
- package/dist/index.js +8 -8
- package/dist/interactive-control.d.ts +2 -2
- package/dist/interactive-control.js +2 -2
- package/dist/{runtime-api-CACSOP5L.js → interactive-controller-DV1HT3NR.js} +850 -8
- package/dist/interactive-controller-Dghv9yMk.d.ts +40 -0
- package/dist/{lines-VAnaqs-K.d.ts → lines-BoT0rBrj.d.ts} +1 -1
- package/dist/lines.d.ts +1 -1
- package/dist/{local-cli-auth-ChDP5zu4.js → local-cli-auth-CdIM0B6p.js} +1 -1
- package/dist/{mcp-local-DY1CnWBn.js → mcp-local-BSvH4yAU.js} +1 -1
- package/dist/{preview-3G1piYer.d.ts → preview-iD-q8YLe.d.ts} +19 -6
- package/dist/runtime.d.ts +6 -3
- package/dist/runtime.js +3 -3
- package/dist/{sandbox-D0-Q1vpS.d.ts → sandbox-BY7KZweP.d.ts} +9 -40
- package/dist/{sandbox-BJLb1q3b.js → sandbox-DeE2MDx9.js} +160 -878
- package/dist/tangle/index.d.ts +1 -1
- package/dist/tangle/index.js +1 -1
- package/dist/{tangle-Csb8unvj.js → tangle-DsvldZtQ.js} +1 -1
- package/dist/{types-Br35Gfpw.d.ts → types-Cs-0Hy_K.d.ts} +24 -4
- package/package.json +6 -4
- package/dist/abort-signal-BpYYr4JT.js +0 -31
- /package/dist/{collaboration-d8Xcvel7.js → collaboration-C1JAl5kE.js} +0 -0
- /package/dist/{line-application-9k30rhb2.js → line-application-DJYY1v8U.js} +0 -0
- /package/dist/{preview-operations-CbTiBE-a.js → preview-operations-BLsclF88.js} +0 -0
- /package/dist/{specs-CnqSWFNT-CHd9ACzP.js → specs-CnqSWFNT-i2wJxPoD.js} +0 -0
- /package/dist/{terminal-stream-CB2DF-qq.d.ts → terminal-stream-C9jxoB07.d.ts} +0 -0
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
import { r as backendTypeSchema } from "./backend-types-C7b_Gpa0.js";
|
|
2
2
|
import { _ as parseErrorResponse, f as SandboxError, g as ValidationError, h as TimeoutError, n as CapabilityError, p as ServerError, s as NetworkError, u as QuotaError } from "./errors-CKl_BSlD.js";
|
|
3
|
-
import {
|
|
4
|
-
import { AgentExactRunControlRefSchema, AgentExecutionOutcomeSchema, AgentRuntimeAttachmentsSchema, DurablePlanSchema, InteractionRequestSchema, agentProfileSchema, canonicalCandidateDigest } from "@tangle-network/agent-interface";
|
|
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 { AgentExactRunControlRefSchema, AgentExecutionOutcomeSchema, AgentInteractiveSessionAttachSchema, AgentInteractiveSessionControlClaimSchema, AgentInteractiveSessionRefSchema, AgentRuntimeAttachmentsSchema, DurablePlanSchema, InteractionRequestSchema, agentInteractiveSessionControlClaimMatchesRef, agentProfileSchema, canonicalCandidateDigest } from "@tangle-network/agent-interface";
|
|
5
|
+
import { z } from "zod";
|
|
5
6
|
//#region src/agent-run-outcome-inspection.ts
|
|
6
7
|
const HUB_APPROVAL_REQUIRED = "HUB_APPROVAL_REQUIRED";
|
|
7
8
|
const MAX_SERIALIZED_TOOL_VALUE_BYTES = 4 * 1024 * 1024;
|
|
9
|
+
/** Read native HTTP failure metadata without inferring status from diagnostic text. */
|
|
10
|
+
function readHttpFailureStatus(value) {
|
|
11
|
+
return typeof value === "number" && Number.isInteger(value) && value >= 400 && value <= 599 ? value : void 0;
|
|
12
|
+
}
|
|
8
13
|
function parseInteraction(value) {
|
|
9
14
|
const parsed = InteractionRequestSchema.safeParse(value);
|
|
10
15
|
return parsed.success ? parsed.data : void 0;
|
|
@@ -189,6 +194,7 @@ function observeEvent(state, event) {
|
|
|
189
194
|
if (type === "error") {
|
|
190
195
|
state.runError ??= readError(data) ?? "Agent execution failed";
|
|
191
196
|
state.runErrorCode ??= readString(data.code);
|
|
197
|
+
state.runErrorStatusCode ??= readHttpFailureStatus(data.statusCode);
|
|
192
198
|
}
|
|
193
199
|
if (type === "interaction") observeInteraction(state, data);
|
|
194
200
|
if (type === "interaction.cancel") observeInteractionCancel(state, data);
|
|
@@ -248,6 +254,7 @@ function observeOutcomeFrame(state, type, data, terminal) {
|
|
|
248
254
|
}
|
|
249
255
|
state.terminalError ??= readError(data) ?? readError(outcome) ?? readError(nestedResult);
|
|
250
256
|
state.terminalErrorCode ??= readString(data.errorCode) ?? readString(data.code) ?? readString(outcome?.errorCode) ?? readString(outcome?.code) ?? readString(nestedResult?.errorCode) ?? readString(nestedResult?.code);
|
|
257
|
+
state.terminalErrorStatusCode ??= readHttpFailureStatus(data.statusCode) ?? readHttpFailureStatus(outcome?.statusCode) ?? readHttpFailureStatus(nestedResult?.statusCode);
|
|
251
258
|
const interactionCandidate = data.interaction ?? nestedResult?.interaction;
|
|
252
259
|
if (interactionCandidate !== void 0) {
|
|
253
260
|
const interaction = parseInteraction(interactionCandidate);
|
|
@@ -272,16 +279,16 @@ function observeOutcomeFrame(state, type, data, terminal) {
|
|
|
272
279
|
}
|
|
273
280
|
function settleOutcome(state) {
|
|
274
281
|
const common = outcomeDetails(state);
|
|
275
|
-
if (state.runError) return failed(state.runError, state.runErrorCode, common);
|
|
282
|
+
if (state.runError) return failed(state.runError, state.runErrorCode, common, state.runErrorStatusCode ?? state.terminalErrorStatusCode);
|
|
276
283
|
const statusGroups = classifyStatuses(state.terminalStatuses);
|
|
277
|
-
if (statusGroups.failure) return failed(state.terminalError ?? `Agent execution ended with status ${statusGroups.failure}`, state.terminalErrorCode, common);
|
|
284
|
+
if (statusGroups.failure) return failed(state.terminalError ?? `Agent execution ended with status ${statusGroups.failure}`, state.terminalErrorCode, common, state.terminalErrorStatusCode);
|
|
278
285
|
if (!state.terminalReached) return failed("Agent stream ended without a terminal event", void 0, common);
|
|
279
286
|
if (state.malformed || statusGroups.unknown || statusGroups.conflicting) return failed("Agent terminal outcome is malformed", void 0, common);
|
|
280
287
|
const wait = selectWait(state);
|
|
281
288
|
if (wait.error) return failed(wait.error, void 0, common);
|
|
282
289
|
if (statusGroups.wait && statusGroups.wait !== wait.kind) return failed("Agent terminal wait does not match its response request", void 0, common);
|
|
283
|
-
if (state.terminalSuccess === false && !wait.kind) return failed(state.terminalError ?? "Agent execution failed", state.terminalErrorCode, common);
|
|
284
|
-
if (state.terminalError && !statusGroups.wait) return failed(state.terminalError, state.terminalErrorCode, common);
|
|
290
|
+
if (state.terminalSuccess === false && !wait.kind) return failed(state.terminalError ?? "Agent execution failed", state.terminalErrorCode, common, state.terminalErrorStatusCode);
|
|
291
|
+
if (state.terminalError && !statusGroups.wait) return failed(state.terminalError, state.terminalErrorCode, common, state.terminalErrorStatusCode);
|
|
285
292
|
if (wait.kind) return waitingOutcome(wait.kind, state, common);
|
|
286
293
|
return {
|
|
287
294
|
success: true,
|
|
@@ -356,7 +363,7 @@ function outcomeDetails(state) {
|
|
|
356
363
|
if (state.plan) details.plan = state.plan;
|
|
357
364
|
return details;
|
|
358
365
|
}
|
|
359
|
-
function failed(error, errorCode, common) {
|
|
366
|
+
function failed(error, errorCode, common, statusCode) {
|
|
360
367
|
const outcome = {
|
|
361
368
|
success: false,
|
|
362
369
|
status: "failed",
|
|
@@ -364,6 +371,7 @@ function failed(error, errorCode, common) {
|
|
|
364
371
|
...common
|
|
365
372
|
};
|
|
366
373
|
if (errorCode) outcome.errorCode = errorCode;
|
|
374
|
+
if (statusCode !== void 0) outcome.statusCode = statusCode;
|
|
367
375
|
return outcome;
|
|
368
376
|
}
|
|
369
377
|
function retainPlan(state, plan) {
|
|
@@ -1556,10 +1564,12 @@ function normalizeSessionFailureReason(value) {
|
|
|
1556
1564
|
const message = nonEmptyField(raw.message);
|
|
1557
1565
|
if (!message) return void 0;
|
|
1558
1566
|
const code = nonEmptyField(raw.code);
|
|
1567
|
+
const statusCode = readHttpFailureStatus(raw.statusCode);
|
|
1559
1568
|
const executionId = nonEmptyField(raw.executionId);
|
|
1560
1569
|
return {
|
|
1561
1570
|
message,
|
|
1562
1571
|
...code ? { code } : {},
|
|
1572
|
+
...statusCode === void 0 ? {} : { statusCode },
|
|
1563
1573
|
...executionId ? { executionId } : {}
|
|
1564
1574
|
};
|
|
1565
1575
|
}
|
|
@@ -1644,4 +1654,836 @@ function sessionMessageRequestBody(request) {
|
|
|
1644
1654
|
};
|
|
1645
1655
|
}
|
|
1646
1656
|
//#endregion
|
|
1647
|
-
|
|
1657
|
+
//#region src/scoped-token.ts
|
|
1658
|
+
/** Maximum time for the exact interactive terminal-token request. */
|
|
1659
|
+
const SCOPED_TOKEN_REQUEST_TIMEOUT_MS = 5e3;
|
|
1660
|
+
const scopedTokenResponseSchema = z.object({
|
|
1661
|
+
token: z.string().min(1),
|
|
1662
|
+
expiresAt: z.number().finite().nonnegative(),
|
|
1663
|
+
runtimeUrl: z.string().min(1),
|
|
1664
|
+
sidecarProxyUrl: z.string().min(1),
|
|
1665
|
+
scope: z.enum([
|
|
1666
|
+
"session",
|
|
1667
|
+
"session-runtime",
|
|
1668
|
+
"project",
|
|
1669
|
+
"read-only"
|
|
1670
|
+
])
|
|
1671
|
+
});
|
|
1672
|
+
/** Reject a scoped credential that the SDK must not send to a consumer. */
|
|
1673
|
+
function assertScopedTokenActive(token, expectedScope) {
|
|
1674
|
+
if (expectedScope !== void 0 && token.scope !== expectedScope) throw new ValidationError(`Scoped token must use the ${expectedScope} scope`);
|
|
1675
|
+
if (typeof token.token !== "string" || !token.token.trim() || !(token.expiresAt instanceof Date) || !Number.isFinite(token.expiresAt.getTime()) || token.expiresAt.getTime() <= Date.now()) throw new ValidationError("Scoped token is expired or invalid");
|
|
1676
|
+
}
|
|
1677
|
+
function parseScopedTokenResponse(raw, expectedScope) {
|
|
1678
|
+
const parsed = scopedTokenResponseSchema.safeParse(raw);
|
|
1679
|
+
if (!parsed.success) throw new ServerError("Sandbox API returned an invalid scoped token response.", 502, { origin: "sandbox-api" });
|
|
1680
|
+
if (parsed.data.scope !== expectedScope) throw new ServerError(`Sandbox API returned a ${parsed.data.scope} token for a ${expectedScope} request.`, 502, { origin: "sandbox-api" });
|
|
1681
|
+
const token = {
|
|
1682
|
+
token: parsed.data.token,
|
|
1683
|
+
expiresAt: /* @__PURE__ */ new Date(parsed.data.expiresAt * 1e3),
|
|
1684
|
+
runtimeUrl: parsed.data.runtimeUrl,
|
|
1685
|
+
sidecarProxyUrl: parsed.data.sidecarProxyUrl,
|
|
1686
|
+
scope: parsed.data.scope
|
|
1687
|
+
};
|
|
1688
|
+
try {
|
|
1689
|
+
assertScopedTokenActive(token, expectedScope);
|
|
1690
|
+
} catch {
|
|
1691
|
+
throw new ServerError("Sandbox API returned an expired or invalid scoped token.", 502, { origin: "sandbox-api" });
|
|
1692
|
+
}
|
|
1693
|
+
return token;
|
|
1694
|
+
}
|
|
1695
|
+
async function requestScopedToken(client, sandboxId, options, requestOptions) {
|
|
1696
|
+
if ((options.scope === "session" || options.scope === "session-runtime") && !options.sessionId) throw new ValidationError(`${options.scope} scope requires a sessionId`);
|
|
1697
|
+
if (options.scope === "session" && !options.runtimeSessionId) throw new ValidationError("session scope requires the actual runtimeSessionId");
|
|
1698
|
+
const response = await client.fetch(`/v1/sandboxes/${encodeURIComponent(sandboxId)}/scoped-token`, {
|
|
1699
|
+
method: "POST",
|
|
1700
|
+
headers: { "Content-Type": "application/json" },
|
|
1701
|
+
body: JSON.stringify({
|
|
1702
|
+
scope: options.scope,
|
|
1703
|
+
...options.sessionId ? { sessionId: options.sessionId } : {},
|
|
1704
|
+
...options.scope === "session" ? { runtimeSessionId: options.runtimeSessionId } : {},
|
|
1705
|
+
...options.ttlMinutes ? { ttlMinutes: options.ttlMinutes } : {}
|
|
1706
|
+
}),
|
|
1707
|
+
...options.signal === void 0 ? {} : { signal: options.signal }
|
|
1708
|
+
}, requestOptions);
|
|
1709
|
+
if (!response.ok) {
|
|
1710
|
+
const body = await response.text();
|
|
1711
|
+
throw parseErrorResponse(response.status, body, void 0, response.headers);
|
|
1712
|
+
}
|
|
1713
|
+
let raw;
|
|
1714
|
+
try {
|
|
1715
|
+
raw = await response.json();
|
|
1716
|
+
} catch {
|
|
1717
|
+
throw new ServerError("Sandbox API returned invalid scoped token JSON.", 502, { origin: "sandbox-api" });
|
|
1718
|
+
}
|
|
1719
|
+
return parseScopedTokenResponse(raw, options.scope);
|
|
1720
|
+
}
|
|
1721
|
+
function parseInteractiveSessionTokenRef(ref) {
|
|
1722
|
+
const parsed = AgentInteractiveSessionRefSchema.safeParse(ref);
|
|
1723
|
+
if (!parsed.success) throw new ValidationError("Interactive session ref is invalid.", { ref: parsed.error.issues[0]?.message ?? "invalid ref" });
|
|
1724
|
+
return parsed.data;
|
|
1725
|
+
}
|
|
1726
|
+
function interactiveSessionTokenOptions(ref, options = {}) {
|
|
1727
|
+
const exactRef = parseInteractiveSessionTokenRef(ref);
|
|
1728
|
+
return {
|
|
1729
|
+
sandboxId: exactRef.run.environmentId,
|
|
1730
|
+
request: {
|
|
1731
|
+
scope: "session-runtime",
|
|
1732
|
+
sessionId: exactRef.run.sessionId,
|
|
1733
|
+
...options.ttlMinutes === void 0 ? {} : { ttlMinutes: options.ttlMinutes },
|
|
1734
|
+
...options.signal === void 0 ? {} : { signal: options.signal }
|
|
1735
|
+
}
|
|
1736
|
+
};
|
|
1737
|
+
}
|
|
1738
|
+
function requestInteractiveSessionToken(client, ref, options) {
|
|
1739
|
+
const exact = interactiveSessionTokenOptions(ref, options);
|
|
1740
|
+
return requestScopedToken(client, exact.sandboxId, exact.request, { timeoutMs: SCOPED_TOKEN_REQUEST_TIMEOUT_MS });
|
|
1741
|
+
}
|
|
1742
|
+
const TERMINAL_WS_MAX_DIMENSION = 4096;
|
|
1743
|
+
/** Input chunk size that leaves room for JSON escaping inside one frame. */
|
|
1744
|
+
const TERMINAL_WS_INPUT_FRAME_CHUNK_CHARS = 128 * 1024;
|
|
1745
|
+
/** WebSocket authentication envelope prefixes. */
|
|
1746
|
+
const TERMINAL_WS_EDGE_BEARER_SUBPROTOCOL_PREFIX = "bearer.";
|
|
1747
|
+
const TERMINAL_WS_SIDECAR_BEARER_SUBPROTOCOL_PREFIX = "tangle.bearer.";
|
|
1748
|
+
/** Non-credential protocol selected during a successful terminal handshake. */
|
|
1749
|
+
const TERMINAL_WS_ECHO_SUBPROTOCOL = "tangle.terminal.v1";
|
|
1750
|
+
const terminalGeometry = {
|
|
1751
|
+
cols: z.number().int().min(1).max(TERMINAL_WS_MAX_DIMENSION),
|
|
1752
|
+
rows: z.number().int().min(1).max(TERMINAL_WS_MAX_DIMENSION)
|
|
1753
|
+
};
|
|
1754
|
+
const terminalInitMessageSchema = z.object({
|
|
1755
|
+
type: z.literal("init"),
|
|
1756
|
+
connectionId: z.string().optional(),
|
|
1757
|
+
/** Required for an interactive-agent PTY; absent for generic terminals. */
|
|
1758
|
+
incarnationId: z.string().uuid().optional(),
|
|
1759
|
+
...terminalGeometry,
|
|
1760
|
+
command: z.string().min(1).optional(),
|
|
1761
|
+
cwd: z.string().min(1).optional(),
|
|
1762
|
+
env: z.record(z.string(), z.string()).optional(),
|
|
1763
|
+
sessionId: z.string().min(1).optional(),
|
|
1764
|
+
/** Canonical control claim for an interactive-agent PTY. */
|
|
1765
|
+
control: AgentInteractiveSessionControlClaimSchema.optional()
|
|
1766
|
+
}).superRefine((message, refinement) => {
|
|
1767
|
+
if (message.incarnationId !== void 0 && message.control === void 0) refinement.addIssue({
|
|
1768
|
+
code: "custom",
|
|
1769
|
+
path: ["control"],
|
|
1770
|
+
message: "Interactive session attach requires a control claim"
|
|
1771
|
+
});
|
|
1772
|
+
if (message.incarnationId === void 0 && message.control !== void 0) refinement.addIssue({
|
|
1773
|
+
code: "custom",
|
|
1774
|
+
path: ["control"],
|
|
1775
|
+
message: "Generic terminal attach cannot carry an interactive control claim"
|
|
1776
|
+
});
|
|
1777
|
+
});
|
|
1778
|
+
const terminalInputMessageSchema = z.object({
|
|
1779
|
+
type: z.literal("input"),
|
|
1780
|
+
data: z.string()
|
|
1781
|
+
});
|
|
1782
|
+
const terminalResizeMessageSchema = z.object({
|
|
1783
|
+
type: z.literal("resize"),
|
|
1784
|
+
...terminalGeometry
|
|
1785
|
+
});
|
|
1786
|
+
const terminalRenewMessageSchema = z.object({ type: z.literal("renew") });
|
|
1787
|
+
const terminalCloseMessageSchema = z.object({ type: z.literal("close") });
|
|
1788
|
+
z.union([
|
|
1789
|
+
terminalInitMessageSchema,
|
|
1790
|
+
terminalInputMessageSchema,
|
|
1791
|
+
terminalResizeMessageSchema,
|
|
1792
|
+
terminalRenewMessageSchema,
|
|
1793
|
+
terminalCloseMessageSchema
|
|
1794
|
+
]);
|
|
1795
|
+
const terminalReadyMessageSchema = z.object({
|
|
1796
|
+
type: z.literal("ready"),
|
|
1797
|
+
connectionId: z.string(),
|
|
1798
|
+
sessionId: z.string(),
|
|
1799
|
+
restored: z.boolean(),
|
|
1800
|
+
detachTimeoutMs: z.number().int().positive(),
|
|
1801
|
+
/** Exact viewer count held by the runtime for this connection. */
|
|
1802
|
+
attachCount: z.number().int().positive().optional(),
|
|
1803
|
+
/** Server-issued output cursor window for exact interactive terminals. */
|
|
1804
|
+
cursors: z.object({
|
|
1805
|
+
earliest: z.number().int().nonnegative(),
|
|
1806
|
+
latest: z.number().int().nonnegative()
|
|
1807
|
+
}).optional()
|
|
1808
|
+
});
|
|
1809
|
+
/** One sequenced output frame for an exact interactive terminal. */
|
|
1810
|
+
const terminalOutputMessageSchema = z.object({
|
|
1811
|
+
type: z.literal("output"),
|
|
1812
|
+
seq: z.number().int().positive(),
|
|
1813
|
+
/** Base64-encoded UTF-8 bytes from the retained terminal event. */
|
|
1814
|
+
data: z.string().min(1)
|
|
1815
|
+
});
|
|
1816
|
+
const terminalExitMessageSchema = z.object({
|
|
1817
|
+
type: z.literal("exit"),
|
|
1818
|
+
exitCode: z.number().optional(),
|
|
1819
|
+
exitSignal: z.string().optional()
|
|
1820
|
+
});
|
|
1821
|
+
const terminalRenewedMessageSchema = z.object({
|
|
1822
|
+
type: z.literal("renewed"),
|
|
1823
|
+
sessionId: z.string()
|
|
1824
|
+
});
|
|
1825
|
+
const terminalErrorMessageSchema = z.object({
|
|
1826
|
+
type: z.literal("error"),
|
|
1827
|
+
code: z.string(),
|
|
1828
|
+
message: z.string()
|
|
1829
|
+
});
|
|
1830
|
+
const terminalServerMessageSchema = z.union([
|
|
1831
|
+
terminalReadyMessageSchema,
|
|
1832
|
+
terminalOutputMessageSchema,
|
|
1833
|
+
terminalExitMessageSchema,
|
|
1834
|
+
terminalRenewedMessageSchema,
|
|
1835
|
+
terminalErrorMessageSchema
|
|
1836
|
+
]);
|
|
1837
|
+
//#endregion
|
|
1838
|
+
//#region src/terminal-stream.ts
|
|
1839
|
+
/**
|
|
1840
|
+
* TerminalStream — typed client for the sandbox terminal WebSocket protocol.
|
|
1841
|
+
*
|
|
1842
|
+
* Drives a live PTY session (an interactive harness TUI or a plain shell)
|
|
1843
|
+
* from the caller's own program: binary frames stream raw PTY output bytes,
|
|
1844
|
+
* TEXT JSON frames carry the control protocol. The browser-safe wire contract
|
|
1845
|
+
* is defined by the shared browser-safe runtime contract and shared with the
|
|
1846
|
+
* sidecar:
|
|
1847
|
+
*
|
|
1848
|
+
* client → server (TEXT JSON):
|
|
1849
|
+
* init {connectionId?, cols, rows, command?, cwd?, env?} — MUST be first
|
|
1850
|
+
* input {data}
|
|
1851
|
+
* resize {cols, rows}
|
|
1852
|
+
*
|
|
1853
|
+
* Interactive-agent init frames add the exact process authority:
|
|
1854
|
+
* {incarnationId, control: {refDigest, generation, leaseId, holderId, expiresAt}}
|
|
1855
|
+
* Subsequent input and resize frames carry only their operation fields; the
|
|
1856
|
+
* server binds authority to the init for the socket lifetime.
|
|
1857
|
+
* server → client (TEXT JSON):
|
|
1858
|
+
* ready {connectionId, sessionId, restored, detachTimeoutMs,
|
|
1859
|
+
* attachCount?, cursors?}
|
|
1860
|
+
* output {seq, data} — exact interactive output as base64 UTF-8 bytes
|
|
1861
|
+
* exit {exitCode?, exitSignal?}
|
|
1862
|
+
* error {code, message}
|
|
1863
|
+
* rec / rec.done — recording tee frames for the platform's session
|
|
1864
|
+
* capture consumer; not part of the client surface
|
|
1865
|
+
* server → client (BINARY): raw PTY output bytes
|
|
1866
|
+
*
|
|
1867
|
+
* Detach/reconnect: the server keeps the PTY alive for `detachTimeoutMs`
|
|
1868
|
+
* (5 minutes today) after the socket closes; re-dialing with the SAME
|
|
1869
|
+
* connectionId reattaches and replays the buffered output history, so a
|
|
1870
|
+
* fresh client repaints the current screen.
|
|
1871
|
+
*
|
|
1872
|
+
* Browser-safe: uses the global `WebSocket` (browsers, Workers, Node >= 22)
|
|
1873
|
+
* and never imports `ws` — the same environment contract as
|
|
1874
|
+
* `session-gateway/client.ts`.
|
|
1875
|
+
*/
|
|
1876
|
+
/** A protocol `error` control frame or a transport failure. */
|
|
1877
|
+
var TerminalStreamError = class extends Error {
|
|
1878
|
+
/** Protocol error code (e.g. `INIT_FAILED`) or `TRANSPORT` for socket faults. */
|
|
1879
|
+
code;
|
|
1880
|
+
constructor(message, code) {
|
|
1881
|
+
super(message);
|
|
1882
|
+
this.name = "TerminalStreamError";
|
|
1883
|
+
this.code = code;
|
|
1884
|
+
}
|
|
1885
|
+
};
|
|
1886
|
+
/**
|
|
1887
|
+
* The sidecar caps WebSocket frames at 1 MiB
|
|
1888
|
+
* (`TERMINAL_WS_MAX_PAYLOAD_BYTES` in the shared runtime contract) and drops
|
|
1889
|
+
* the connection on
|
|
1890
|
+
* larger frames. `write()` chunks input so every serialized `input` frame
|
|
1891
|
+
* stays under that cap: 128 Ki characters per chunk × a worst-case JSON
|
|
1892
|
+
* escape expansion of 6 bytes per character (`` etc.) ≈ 768 KiB,
|
|
1893
|
+
* comfortably below the limit including the frame's JSON envelope.
|
|
1894
|
+
*/
|
|
1895
|
+
const DEFAULT_COLS = 80;
|
|
1896
|
+
const DEFAULT_ROWS = 24;
|
|
1897
|
+
const DEFAULT_CONNECT_TIMEOUT_MS = 15e3;
|
|
1898
|
+
/**
|
|
1899
|
+
* base64url-encode a UTF-8 string without padding — the exact envelope the
|
|
1900
|
+
* edge's `parseTerminalWsSubprotocolToken` decodes (its strict round-trip
|
|
1901
|
+
* check tolerates padding, but the reference browser client emits unpadded).
|
|
1902
|
+
*/
|
|
1903
|
+
function base64UrlEncodeUtf8(value) {
|
|
1904
|
+
if (typeof btoa !== "function") throw new TerminalStreamError("global btoa is unavailable; cannot build the edge bearer subprotocol", "ENVIRONMENT");
|
|
1905
|
+
const bytes = new TextEncoder().encode(value);
|
|
1906
|
+
let binary = "";
|
|
1907
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
1908
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
1909
|
+
}
|
|
1910
|
+
function buildAuthSubprotocols(format, token) {
|
|
1911
|
+
if (format === "sidecar-direct") return [`${TERMINAL_WS_SIDECAR_BEARER_SUBPROTOCOL_PREFIX}${token}`, TERMINAL_WS_ECHO_SUBPROTOCOL];
|
|
1912
|
+
return [`${TERMINAL_WS_EDGE_BEARER_SUBPROTOCOL_PREFIX}${base64UrlEncodeUtf8(token)}`, TERMINAL_WS_ECHO_SUBPROTOCOL];
|
|
1913
|
+
}
|
|
1914
|
+
/**
|
|
1915
|
+
* Resolve the dial credential: invoke a provider (fresh token per dial) or
|
|
1916
|
+
* pass a string through. Fails loud on an empty result — a blank credential
|
|
1917
|
+
* would dial and be rejected with an opaque 401 downstream.
|
|
1918
|
+
*/
|
|
1919
|
+
async function resolveTerminalToken(token, signal) {
|
|
1920
|
+
const value = typeof token === "function" ? await token(signal) : token;
|
|
1921
|
+
if (typeof value === "object" && value !== null) {
|
|
1922
|
+
try {
|
|
1923
|
+
assertScopedTokenActive(value, "session-runtime");
|
|
1924
|
+
} catch {
|
|
1925
|
+
throw new TerminalStreamError("Terminal stream scoped token is expired or invalid", "INVALID_TOKEN");
|
|
1926
|
+
}
|
|
1927
|
+
return value.token;
|
|
1928
|
+
}
|
|
1929
|
+
if (typeof value !== "string" || !value.trim()) throw new TerminalStreamError(typeof token === "function" ? "Terminal stream token provider returned an empty token" : "Terminal stream token must not be empty", "INVALID_TOKEN");
|
|
1930
|
+
return value;
|
|
1931
|
+
}
|
|
1932
|
+
function terminalAbortReason(signal) {
|
|
1933
|
+
return signal.reason instanceof Error ? signal.reason : new DOMException("Terminal attach was aborted", "AbortError");
|
|
1934
|
+
}
|
|
1935
|
+
function awaitTerminalOperation(promise, signal) {
|
|
1936
|
+
if (!signal) return promise;
|
|
1937
|
+
signal.throwIfAborted();
|
|
1938
|
+
return new Promise((resolve, reject) => {
|
|
1939
|
+
let settled = false;
|
|
1940
|
+
const cleanup = () => signal.removeEventListener("abort", onAbort);
|
|
1941
|
+
const onAbort = () => {
|
|
1942
|
+
if (settled) return;
|
|
1943
|
+
settled = true;
|
|
1944
|
+
cleanup();
|
|
1945
|
+
reject(terminalAbortReason(signal));
|
|
1946
|
+
};
|
|
1947
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1948
|
+
promise.then((value) => {
|
|
1949
|
+
if (settled) return;
|
|
1950
|
+
settled = true;
|
|
1951
|
+
cleanup();
|
|
1952
|
+
resolve(value);
|
|
1953
|
+
}, (cause) => {
|
|
1954
|
+
if (settled) return;
|
|
1955
|
+
settled = true;
|
|
1956
|
+
cleanup();
|
|
1957
|
+
reject(cause);
|
|
1958
|
+
});
|
|
1959
|
+
});
|
|
1960
|
+
}
|
|
1961
|
+
function toWebSocketUrl(url) {
|
|
1962
|
+
let parsed;
|
|
1963
|
+
try {
|
|
1964
|
+
parsed = new URL(url);
|
|
1965
|
+
} catch {
|
|
1966
|
+
throw new TerminalStreamError(`Terminal WebSocket URL is not absolute: ${url}`, "INVALID_URL");
|
|
1967
|
+
}
|
|
1968
|
+
if (parsed.protocol === "https:") parsed.protocol = "wss:";
|
|
1969
|
+
else if (parsed.protocol === "http:") parsed.protocol = "ws:";
|
|
1970
|
+
if (parsed.protocol !== "wss:" && parsed.protocol !== "ws:") throw new TerminalStreamError(`Terminal WebSocket URL must be ws(s) or http(s), got ${parsed.protocol}`, "INVALID_URL");
|
|
1971
|
+
return parsed.toString();
|
|
1972
|
+
}
|
|
1973
|
+
function assertDimension(name, value) {
|
|
1974
|
+
if (!Number.isInteger(value) || value < 1 || value > 4096) throw new TerminalStreamError(`${name} must be an integer in [1, ${TERMINAL_WS_MAX_DIMENSION}], got ${value}`, "INVALID_DIMENSION");
|
|
1975
|
+
}
|
|
1976
|
+
/** Decode the sidecar's base64 output frame without a Node-only dependency. */
|
|
1977
|
+
function decodeBase64(value) {
|
|
1978
|
+
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) throw new TerminalStreamError("Terminal output frame is not valid base64", "INVALID_FRAME");
|
|
1979
|
+
let binary;
|
|
1980
|
+
try {
|
|
1981
|
+
binary = atob(value);
|
|
1982
|
+
} catch {
|
|
1983
|
+
throw new TerminalStreamError("Terminal output frame is not valid base64", "INVALID_FRAME");
|
|
1984
|
+
}
|
|
1985
|
+
const bytes = new Uint8Array(binary.length);
|
|
1986
|
+
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
|
|
1987
|
+
return bytes;
|
|
1988
|
+
}
|
|
1989
|
+
function normalizeInteractiveSessionIdentity(incarnationId, control) {
|
|
1990
|
+
if (incarnationId === void 0 && control === void 0) return void 0;
|
|
1991
|
+
if (typeof incarnationId !== "string" || incarnationId.length === 0 || incarnationId.trim() !== incarnationId) throw new TerminalStreamError("Interactive terminal attach requires an exact incarnationId", "INVALID_INTERACTIVE_IDENTITY");
|
|
1992
|
+
if (control === void 0) throw new TerminalStreamError("Interactive terminal attach requires an exact control claim", "INVALID_INTERACTIVE_CONTROL");
|
|
1993
|
+
const parsedControl = AgentInteractiveSessionControlClaimSchema.safeParse(control);
|
|
1994
|
+
if (!parsedControl.success) throw new TerminalStreamError("Interactive terminal attach requires an exact control claim", "INVALID_INTERACTIVE_CONTROL");
|
|
1995
|
+
const expiresAt = Date.parse(parsedControl.data.expiresAt);
|
|
1996
|
+
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) throw new TerminalStreamError("Interactive terminal control claim is expired", "INTERACTIVE_CONTROL_EXPIRED");
|
|
1997
|
+
return {
|
|
1998
|
+
incarnationId,
|
|
1999
|
+
control: parsedControl.data
|
|
2000
|
+
};
|
|
2001
|
+
}
|
|
2002
|
+
function interactiveInitFields(identity) {
|
|
2003
|
+
if (identity === void 0) return {};
|
|
2004
|
+
return {
|
|
2005
|
+
incarnationId: identity.incarnationId,
|
|
2006
|
+
control: identity.control
|
|
2007
|
+
};
|
|
2008
|
+
}
|
|
2009
|
+
function buildTerminalInitMessage(options, identity) {
|
|
2010
|
+
if (typeof options.connectionId !== "string" || !options.connectionId.trim()) throw new TerminalStreamError("Terminal stream connectionId must not be empty", "INVALID_CONNECTION_ID");
|
|
2011
|
+
if (options.cols !== void 0) assertDimension("cols", options.cols);
|
|
2012
|
+
if (options.rows !== void 0) assertDimension("rows", options.rows);
|
|
2013
|
+
const parsed = terminalInitMessageSchema.safeParse({
|
|
2014
|
+
type: "init",
|
|
2015
|
+
connectionId: options.connectionId,
|
|
2016
|
+
cols: options.cols ?? DEFAULT_COLS,
|
|
2017
|
+
rows: options.rows ?? DEFAULT_ROWS,
|
|
2018
|
+
...options.command !== void 0 ? { command: options.command } : {},
|
|
2019
|
+
...options.cwd !== void 0 ? { cwd: options.cwd } : {},
|
|
2020
|
+
...options.env !== void 0 ? { env: options.env } : {},
|
|
2021
|
+
...interactiveInitFields(identity)
|
|
2022
|
+
});
|
|
2023
|
+
if (!parsed.success) throw new TerminalStreamError("Terminal stream init does not match the shared terminal protocol", "INVALID_INIT");
|
|
2024
|
+
return parsed.data;
|
|
2025
|
+
}
|
|
2026
|
+
function assertInteractiveControlActive(identity) {
|
|
2027
|
+
if (identity === void 0) return;
|
|
2028
|
+
if (Date.parse(identity.control.expiresAt) <= Date.now()) throw new TerminalStreamError("Interactive terminal control claim is expired", "INTERACTIVE_CONTROL_EXPIRED");
|
|
2029
|
+
}
|
|
2030
|
+
/**
|
|
2031
|
+
* Split input so each serialized `input` frame stays under the server's
|
|
2032
|
+
* 1 MiB frame cap, without splitting a surrogate pair across frames (a torn
|
|
2033
|
+
* pair would reach the PTY as two invalid UTF-8 writes).
|
|
2034
|
+
*/
|
|
2035
|
+
function* chunkInput(text) {
|
|
2036
|
+
if (text.length <= 131072) {
|
|
2037
|
+
yield text;
|
|
2038
|
+
return;
|
|
2039
|
+
}
|
|
2040
|
+
let index = 0;
|
|
2041
|
+
while (index < text.length) {
|
|
2042
|
+
let end = Math.min(index + TERMINAL_WS_INPUT_FRAME_CHUNK_CHARS, text.length);
|
|
2043
|
+
if (end < text.length) {
|
|
2044
|
+
const trailing = text.charCodeAt(end - 1);
|
|
2045
|
+
if (trailing >= 55296 && trailing <= 56319) end -= 1;
|
|
2046
|
+
}
|
|
2047
|
+
yield text.slice(index, end);
|
|
2048
|
+
index = end;
|
|
2049
|
+
}
|
|
2050
|
+
}
|
|
2051
|
+
/**
|
|
2052
|
+
* Client for one terminal WebSocket connection. Construct via
|
|
2053
|
+
* {@link TerminalStream.connect}, which resolves once the server
|
|
2054
|
+
* acknowledges the attach with `ready` (history replay then streams through
|
|
2055
|
+
* `handlers.onData`).
|
|
2056
|
+
*/
|
|
2057
|
+
var TerminalStream = class TerminalStream {
|
|
2058
|
+
ws;
|
|
2059
|
+
options;
|
|
2060
|
+
interactiveIdentity;
|
|
2061
|
+
initMessage;
|
|
2062
|
+
handlers;
|
|
2063
|
+
readyInfo = null;
|
|
2064
|
+
closed = false;
|
|
2065
|
+
closeWaiters = [];
|
|
2066
|
+
textDecoder = new TextDecoder();
|
|
2067
|
+
reconnectInFlight;
|
|
2068
|
+
/**
|
|
2069
|
+
* Dial the endpoint, send `init` as the first frame, and resolve once the
|
|
2070
|
+
* server responds `ready`. Rejects on a protocol `error` frame, a socket
|
|
2071
|
+
* close/failure before `ready`, or the connect timeout — always with the
|
|
2072
|
+
* reason the server gave. A token PROVIDER is awaited here, before the
|
|
2073
|
+
* socket opens, so every dial (first connect and each reconnect) carries a
|
|
2074
|
+
* fresh credential.
|
|
2075
|
+
*/
|
|
2076
|
+
static async connect(options) {
|
|
2077
|
+
const interactiveIdentity = normalizeInteractiveSessionIdentity(options.incarnationId, options.control);
|
|
2078
|
+
options.signal?.throwIfAborted();
|
|
2079
|
+
const initMessage = buildTerminalInitMessage(options, interactiveIdentity);
|
|
2080
|
+
const token = await awaitTerminalOperation(resolveTerminalToken(options.token, options.signal), options.signal);
|
|
2081
|
+
options.signal?.throwIfAborted();
|
|
2082
|
+
return new TerminalStream(options, token, interactiveIdentity, initMessage).establish(options.signal);
|
|
2083
|
+
}
|
|
2084
|
+
constructor(options, resolvedToken, interactiveIdentity, initMessage) {
|
|
2085
|
+
const exactOptions = interactiveIdentity === void 0 ? options : {
|
|
2086
|
+
...options,
|
|
2087
|
+
incarnationId: interactiveIdentity.incarnationId,
|
|
2088
|
+
control: interactiveIdentity.control
|
|
2089
|
+
};
|
|
2090
|
+
const WebSocketCtor = globalThis.WebSocket;
|
|
2091
|
+
if (typeof WebSocketCtor !== "function") throw new TerminalStreamError("global WebSocket is unavailable in this environment (Node >= 22 or a browser is required)", "ENVIRONMENT");
|
|
2092
|
+
this.options = {
|
|
2093
|
+
...exactOptions,
|
|
2094
|
+
signal: void 0
|
|
2095
|
+
};
|
|
2096
|
+
this.interactiveIdentity = interactiveIdentity;
|
|
2097
|
+
this.initMessage = initMessage;
|
|
2098
|
+
this.handlers = exactOptions.handlers ?? {};
|
|
2099
|
+
this.ws = new WebSocketCtor(toWebSocketUrl(exactOptions.url), buildAuthSubprotocols(exactOptions.authFormat ?? "edge", resolvedToken));
|
|
2100
|
+
this.ws.binaryType = "arraybuffer";
|
|
2101
|
+
}
|
|
2102
|
+
establish(signal) {
|
|
2103
|
+
return new Promise((resolve, reject) => {
|
|
2104
|
+
let settled = false;
|
|
2105
|
+
const timeoutMs = this.options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
|
|
2106
|
+
const timer = setTimeout(() => {
|
|
2107
|
+
fail(new TerminalStreamError(`Terminal attach timed out after ${timeoutMs}ms waiting for ready`, "CONNECT_TIMEOUT"));
|
|
2108
|
+
this.ws.close(1e3, "connect timeout");
|
|
2109
|
+
}, timeoutMs);
|
|
2110
|
+
const cleanup = () => {
|
|
2111
|
+
clearTimeout(timer);
|
|
2112
|
+
signal?.removeEventListener("abort", onAbort);
|
|
2113
|
+
};
|
|
2114
|
+
const succeed = () => {
|
|
2115
|
+
if (settled) return;
|
|
2116
|
+
settled = true;
|
|
2117
|
+
cleanup();
|
|
2118
|
+
resolve(this);
|
|
2119
|
+
};
|
|
2120
|
+
const fail = (error) => {
|
|
2121
|
+
if (settled) return;
|
|
2122
|
+
settled = true;
|
|
2123
|
+
cleanup();
|
|
2124
|
+
reject(error);
|
|
2125
|
+
};
|
|
2126
|
+
const onAbort = () => {
|
|
2127
|
+
if (!signal) return;
|
|
2128
|
+
fail(terminalAbortReason(signal));
|
|
2129
|
+
this.ws.close(1e3, "connect aborted");
|
|
2130
|
+
};
|
|
2131
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
2132
|
+
if (signal?.aborted) {
|
|
2133
|
+
onAbort();
|
|
2134
|
+
return;
|
|
2135
|
+
}
|
|
2136
|
+
this.ws.addEventListener("open", () => {
|
|
2137
|
+
if (settled) return;
|
|
2138
|
+
try {
|
|
2139
|
+
assertInteractiveControlActive(this.interactiveIdentity);
|
|
2140
|
+
} catch (error) {
|
|
2141
|
+
fail(error instanceof TerminalStreamError ? error : new TerminalStreamError("Interactive terminal control claim is expired", "INTERACTIVE_CONTROL_EXPIRED"));
|
|
2142
|
+
return;
|
|
2143
|
+
}
|
|
2144
|
+
this.ws.send(JSON.stringify(this.initMessage));
|
|
2145
|
+
});
|
|
2146
|
+
this.ws.addEventListener("message", (event) => {
|
|
2147
|
+
this.handleMessage(event.data, {
|
|
2148
|
+
succeed,
|
|
2149
|
+
fail,
|
|
2150
|
+
settled: () => settled
|
|
2151
|
+
});
|
|
2152
|
+
});
|
|
2153
|
+
this.ws.addEventListener("error", () => {
|
|
2154
|
+
fail(new TerminalStreamError("Terminal WebSocket transport failed before ready", "TRANSPORT"));
|
|
2155
|
+
});
|
|
2156
|
+
this.ws.addEventListener("close", (event) => {
|
|
2157
|
+
this.closed = true;
|
|
2158
|
+
fail(new TerminalStreamError(`Terminal WebSocket closed before ready (code ${event.code}${event.reason ? `: ${event.reason}` : ""})`, "CLOSED_BEFORE_READY"));
|
|
2159
|
+
for (const waiter of this.closeWaiters) waiter();
|
|
2160
|
+
this.closeWaiters = [];
|
|
2161
|
+
this.handlers.onClose?.(event.code, event.reason);
|
|
2162
|
+
});
|
|
2163
|
+
});
|
|
2164
|
+
}
|
|
2165
|
+
handleMessage(raw, connectPhase) {
|
|
2166
|
+
if (typeof raw !== "string") {
|
|
2167
|
+
if (raw instanceof ArrayBuffer) this.handlers.onData?.(new Uint8Array(raw));
|
|
2168
|
+
return;
|
|
2169
|
+
}
|
|
2170
|
+
const failProtocolFrame = () => {
|
|
2171
|
+
const error = new TerminalStreamError("Terminal control frame does not match the shared terminal protocol", "INVALID_FRAME");
|
|
2172
|
+
const beforeReady = !connectPhase.settled();
|
|
2173
|
+
if (this.ws.readyState === WebSocket.OPEN) this.ws.close(1e3, "invalid terminal frame");
|
|
2174
|
+
if (beforeReady) connectPhase.fail(error);
|
|
2175
|
+
else this.handlers.onError?.(error);
|
|
2176
|
+
};
|
|
2177
|
+
let decoded;
|
|
2178
|
+
try {
|
|
2179
|
+
decoded = JSON.parse(raw);
|
|
2180
|
+
} catch {
|
|
2181
|
+
failProtocolFrame();
|
|
2182
|
+
return;
|
|
2183
|
+
}
|
|
2184
|
+
if (decoded === null || typeof decoded !== "object" || Array.isArray(decoded) || typeof decoded.type !== "string") {
|
|
2185
|
+
failProtocolFrame();
|
|
2186
|
+
return;
|
|
2187
|
+
}
|
|
2188
|
+
const message = decoded;
|
|
2189
|
+
if (message.type === "rec" || message.type === "rec.done") return;
|
|
2190
|
+
if (message.type !== "ready" && message.type !== "output" && message.type !== "exit" && message.type !== "renewed" && message.type !== "error") return;
|
|
2191
|
+
const parsed = terminalServerMessageSchema.safeParse(message);
|
|
2192
|
+
if (!parsed.success) {
|
|
2193
|
+
failProtocolFrame();
|
|
2194
|
+
return;
|
|
2195
|
+
}
|
|
2196
|
+
switch (parsed.data.type) {
|
|
2197
|
+
case "ready": {
|
|
2198
|
+
const info = {
|
|
2199
|
+
connectionId: parsed.data.connectionId,
|
|
2200
|
+
sessionId: parsed.data.sessionId,
|
|
2201
|
+
restored: parsed.data.restored,
|
|
2202
|
+
detachTimeoutMs: parsed.data.detachTimeoutMs,
|
|
2203
|
+
...parsed.data.attachCount === void 0 ? {} : { attachCount: parsed.data.attachCount },
|
|
2204
|
+
...parsed.data.cursors === void 0 ? {} : { cursors: parsed.data.cursors }
|
|
2205
|
+
};
|
|
2206
|
+
this.readyInfo = info;
|
|
2207
|
+
connectPhase.succeed();
|
|
2208
|
+
this.handlers.onReady?.(info);
|
|
2209
|
+
return;
|
|
2210
|
+
}
|
|
2211
|
+
case "output":
|
|
2212
|
+
try {
|
|
2213
|
+
const bytes = decodeBase64(parsed.data.data);
|
|
2214
|
+
this.handlers.onOutput?.(parsed.data.seq, bytes);
|
|
2215
|
+
if (this.handlers.onOutput === void 0) this.handlers.onData?.(bytes);
|
|
2216
|
+
} catch (error) {
|
|
2217
|
+
const protocolError = error instanceof TerminalStreamError ? error : new TerminalStreamError("Terminal output frame is not valid base64", "INVALID_FRAME");
|
|
2218
|
+
if (!connectPhase.settled()) connectPhase.fail(protocolError);
|
|
2219
|
+
else this.handlers.onError?.(protocolError);
|
|
2220
|
+
if (this.ws.readyState === WebSocket.OPEN) this.ws.close(1e3, "invalid terminal output");
|
|
2221
|
+
}
|
|
2222
|
+
return;
|
|
2223
|
+
case "exit":
|
|
2224
|
+
this.handlers.onExit?.({
|
|
2225
|
+
exitCode: parsed.data.exitCode,
|
|
2226
|
+
exitSignal: parsed.data.exitSignal
|
|
2227
|
+
});
|
|
2228
|
+
return;
|
|
2229
|
+
case "renewed": return;
|
|
2230
|
+
case "error": {
|
|
2231
|
+
const error = new TerminalStreamError(parsed.data.message, parsed.data.code);
|
|
2232
|
+
if (!connectPhase.settled()) {
|
|
2233
|
+
connectPhase.fail(error);
|
|
2234
|
+
return;
|
|
2235
|
+
}
|
|
2236
|
+
this.handlers.onError?.(error);
|
|
2237
|
+
return;
|
|
2238
|
+
}
|
|
2239
|
+
}
|
|
2240
|
+
}
|
|
2241
|
+
/** PTY connection id this stream is attached to. */
|
|
2242
|
+
get connectionId() {
|
|
2243
|
+
return this.options.connectionId;
|
|
2244
|
+
}
|
|
2245
|
+
/** The server's `ready` acknowledgement. Set once `connect()` resolves. */
|
|
2246
|
+
get ready() {
|
|
2247
|
+
if (!this.readyInfo) throw new TerminalStreamError("Terminal stream is not ready yet", "NOT_READY");
|
|
2248
|
+
return this.readyInfo;
|
|
2249
|
+
}
|
|
2250
|
+
/** True while the socket is open. */
|
|
2251
|
+
get isOpen() {
|
|
2252
|
+
return !this.closed && this.ws.readyState === WebSocket.OPEN;
|
|
2253
|
+
}
|
|
2254
|
+
/**
|
|
2255
|
+
* Send input keystrokes to the PTY. `Uint8Array` input is decoded as
|
|
2256
|
+
* UTF-8 (the wire protocol carries input as JSON text). Input larger than
|
|
2257
|
+
* the server's 1 MiB frame cap is split across multiple `input` frames in
|
|
2258
|
+
* order on the same socket, so delivery order is preserved.
|
|
2259
|
+
*/
|
|
2260
|
+
write(data) {
|
|
2261
|
+
this.assertOpen("write");
|
|
2262
|
+
assertInteractiveControlActive(this.interactiveIdentity);
|
|
2263
|
+
const text = typeof data === "string" ? data : this.textDecoder.decode(data);
|
|
2264
|
+
for (const chunk of chunkInput(text)) this.ws.send(JSON.stringify({
|
|
2265
|
+
type: "input",
|
|
2266
|
+
data: chunk
|
|
2267
|
+
}));
|
|
2268
|
+
}
|
|
2269
|
+
/** Resize the PTY. */
|
|
2270
|
+
resize(cols, rows) {
|
|
2271
|
+
assertDimension("cols", cols);
|
|
2272
|
+
assertDimension("rows", rows);
|
|
2273
|
+
this.assertOpen("resize");
|
|
2274
|
+
assertInteractiveControlActive(this.interactiveIdentity);
|
|
2275
|
+
this.ws.send(JSON.stringify({
|
|
2276
|
+
type: "resize",
|
|
2277
|
+
cols,
|
|
2278
|
+
rows
|
|
2279
|
+
}));
|
|
2280
|
+
}
|
|
2281
|
+
/**
|
|
2282
|
+
* Detach cleanly: close the socket and resolve once the close completes.
|
|
2283
|
+
* The PTY survives server-side for `ready.detachTimeoutMs` (5 minutes
|
|
2284
|
+
* today) — reattach within that window via {@link reconnect} (or a fresh
|
|
2285
|
+
* `connect()` with the same connectionId) to replay history and continue.
|
|
2286
|
+
*/
|
|
2287
|
+
close() {
|
|
2288
|
+
if (this.closed) return Promise.resolve();
|
|
2289
|
+
return new Promise((resolve) => {
|
|
2290
|
+
this.closeWaiters.push(resolve);
|
|
2291
|
+
this.ws.close(1e3, "client detach");
|
|
2292
|
+
});
|
|
2293
|
+
}
|
|
2294
|
+
/**
|
|
2295
|
+
* Re-dial the same endpoint with the same connectionId on a fresh socket
|
|
2296
|
+
* — the server reattaches the PTY and replays its buffered history. When
|
|
2297
|
+
* the stream was constructed with a token PROVIDER, it is re-invoked for
|
|
2298
|
+
* the new dial (scoped terminal tokens expire within minutes, so the
|
|
2299
|
+
* original credential may be dead by reconnect time); with a plain string
|
|
2300
|
+
* token, pass a fresh `token` override yourself when it may have expired.
|
|
2301
|
+
* `handlers` rebinds callbacks for the new stream.
|
|
2302
|
+
*/
|
|
2303
|
+
reconnect(overrides) {
|
|
2304
|
+
const existing = this.reconnectInFlight;
|
|
2305
|
+
if (existing !== void 0) return awaitTerminalOperation(existing, overrides?.signal);
|
|
2306
|
+
const operation = this.reconnectOnce(overrides);
|
|
2307
|
+
let tracked;
|
|
2308
|
+
tracked = operation.finally(() => {
|
|
2309
|
+
if (this.reconnectInFlight === tracked) this.reconnectInFlight = void 0;
|
|
2310
|
+
});
|
|
2311
|
+
this.reconnectInFlight = tracked;
|
|
2312
|
+
return awaitTerminalOperation(tracked, overrides?.signal);
|
|
2313
|
+
}
|
|
2314
|
+
async reconnectOnce(overrides) {
|
|
2315
|
+
const binding = await this.options.reconnectAuthority?.acquire(overrides?.signal);
|
|
2316
|
+
try {
|
|
2317
|
+
return await TerminalStream.connect({
|
|
2318
|
+
...this.options,
|
|
2319
|
+
...binding === void 0 ? {} : {
|
|
2320
|
+
incarnationId: binding.incarnationId,
|
|
2321
|
+
control: binding.control
|
|
2322
|
+
},
|
|
2323
|
+
token: overrides?.token ?? this.options.token,
|
|
2324
|
+
handlers: this.handlersForReconnect(overrides?.handlers),
|
|
2325
|
+
cols: overrides?.cols ?? this.options.cols,
|
|
2326
|
+
rows: overrides?.rows ?? this.options.rows,
|
|
2327
|
+
signal: overrides?.signal
|
|
2328
|
+
});
|
|
2329
|
+
} catch (error) {
|
|
2330
|
+
try {
|
|
2331
|
+
await binding?.onFailure?.();
|
|
2332
|
+
} catch {}
|
|
2333
|
+
throw error;
|
|
2334
|
+
}
|
|
2335
|
+
}
|
|
2336
|
+
handlersForReconnect(overrides) {
|
|
2337
|
+
const lifecycleHandlers = this.options.handlers;
|
|
2338
|
+
if (overrides === void 0 || lifecycleHandlers?.onClose === void 0) return overrides ?? lifecycleHandlers;
|
|
2339
|
+
return {
|
|
2340
|
+
...overrides,
|
|
2341
|
+
onClose: (code, reason) => {
|
|
2342
|
+
lifecycleHandlers.onClose?.(code, reason);
|
|
2343
|
+
overrides.onClose?.(code, reason);
|
|
2344
|
+
}
|
|
2345
|
+
};
|
|
2346
|
+
}
|
|
2347
|
+
assertOpen(action) {
|
|
2348
|
+
if (!this.isOpen) throw new TerminalStreamError(`Cannot ${action}: terminal stream is not open`, "NOT_OPEN");
|
|
2349
|
+
}
|
|
2350
|
+
};
|
|
2351
|
+
//#endregion
|
|
2352
|
+
//#region src/interactive-controller.ts
|
|
2353
|
+
/**
|
|
2354
|
+
* Attach-capable controller for one exact interactive process.
|
|
2355
|
+
*
|
|
2356
|
+
* Control ownership lives in the dependency-light base controller. This layer
|
|
2357
|
+
* adds only the terminal attach operation after that ownership is resolved.
|
|
2358
|
+
*/
|
|
2359
|
+
var InteractiveSessionController = class extends InteractiveSessionControlController {
|
|
2360
|
+
attachInFlight;
|
|
2361
|
+
constructor(attachTransport, options) {
|
|
2362
|
+
super(attachTransport, options);
|
|
2363
|
+
this.attachTransport = attachTransport;
|
|
2364
|
+
}
|
|
2365
|
+
async attach(request, requestOptions) {
|
|
2366
|
+
requestOptions?.signal?.throwIfAborted();
|
|
2367
|
+
if (this.attachInFlight !== void 0) return await awaitWithAbort(this.attachInFlight, requestOptions?.signal);
|
|
2368
|
+
const operation = (async () => {
|
|
2369
|
+
const identity = await this.resolve(requestOptions);
|
|
2370
|
+
return this.attachWithIdentity(identity, request, requestOptions);
|
|
2371
|
+
})();
|
|
2372
|
+
let tracked;
|
|
2373
|
+
tracked = operation.finally(() => {
|
|
2374
|
+
if (this.attachInFlight === tracked) this.attachInFlight = void 0;
|
|
2375
|
+
});
|
|
2376
|
+
this.attachInFlight = tracked;
|
|
2377
|
+
return await tracked;
|
|
2378
|
+
}
|
|
2379
|
+
/**
|
|
2380
|
+
* Open a stream for a claim returned by this controller's `resolve()`.
|
|
2381
|
+
* The controller releases that claim when the stream cannot be opened.
|
|
2382
|
+
*/
|
|
2383
|
+
async attachWithIdentity(identity, request, requestOptions) {
|
|
2384
|
+
const exactRef = AgentInteractiveSessionRefSchema.parse(identity.ref);
|
|
2385
|
+
assertInteractiveSessionRef(exactRef, this.options);
|
|
2386
|
+
if (!agentInteractiveSessionControlClaimMatchesRef(exactRef, identity.control)) throw new Error("Interactive control claim is not bound to the session");
|
|
2387
|
+
let activeIdentity = {
|
|
2388
|
+
ref: exactRef,
|
|
2389
|
+
control: identity.control
|
|
2390
|
+
};
|
|
2391
|
+
const releasePromises = /* @__PURE__ */ new WeakMap();
|
|
2392
|
+
const releaseClaim = (target) => {
|
|
2393
|
+
const existing = releasePromises.get(target);
|
|
2394
|
+
if (existing !== void 0) return existing;
|
|
2395
|
+
const release = this.safelyReleaseClaim(target);
|
|
2396
|
+
releasePromises.set(target, release);
|
|
2397
|
+
return release;
|
|
2398
|
+
};
|
|
2399
|
+
let reconnectInFlight;
|
|
2400
|
+
const reconnectAuthority = { acquire: async (signal) => {
|
|
2401
|
+
if (!releasePromises.has(activeIdentity)) throw new Error("Interactive terminal must be closed before reconnecting");
|
|
2402
|
+
if (reconnectInFlight !== void 0) return await awaitWithAbort(reconnectInFlight, signal);
|
|
2403
|
+
const operation = (async () => {
|
|
2404
|
+
const next = await this.resolve({ signal });
|
|
2405
|
+
const nextRef = AgentInteractiveSessionRefSchema.parse(next.ref);
|
|
2406
|
+
assertInteractiveSessionRef(nextRef, this.options);
|
|
2407
|
+
const nextIdentity = {
|
|
2408
|
+
ref: nextRef,
|
|
2409
|
+
control: next.control
|
|
2410
|
+
};
|
|
2411
|
+
activeIdentity = nextIdentity;
|
|
2412
|
+
return {
|
|
2413
|
+
incarnationId: nextRef.incarnationId,
|
|
2414
|
+
control: next.control,
|
|
2415
|
+
onFailure: () => releaseClaim(nextIdentity)
|
|
2416
|
+
};
|
|
2417
|
+
})();
|
|
2418
|
+
let tracked;
|
|
2419
|
+
tracked = operation.finally(() => {
|
|
2420
|
+
if (reconnectInFlight === tracked) reconnectInFlight = void 0;
|
|
2421
|
+
});
|
|
2422
|
+
reconnectInFlight = tracked;
|
|
2423
|
+
return await tracked;
|
|
2424
|
+
} };
|
|
2425
|
+
try {
|
|
2426
|
+
requestOptions?.signal?.throwIfAborted();
|
|
2427
|
+
const callerHandlers = request.handlers;
|
|
2428
|
+
const exactRequest = {
|
|
2429
|
+
...request,
|
|
2430
|
+
control: identity.control,
|
|
2431
|
+
handlers: {
|
|
2432
|
+
...callerHandlers,
|
|
2433
|
+
onClose: (code, reason) => {
|
|
2434
|
+
releaseClaim(activeIdentity);
|
|
2435
|
+
callerHandlers?.onClose?.(code, reason);
|
|
2436
|
+
}
|
|
2437
|
+
}
|
|
2438
|
+
};
|
|
2439
|
+
const stream = await this.attachTransport.attach(this.options.sessionId, exactRef, exactRequest, requestOptions, reconnectAuthority);
|
|
2440
|
+
if (requestOptions?.signal?.aborted) {
|
|
2441
|
+
await stream.close();
|
|
2442
|
+
requestOptions.signal.throwIfAborted();
|
|
2443
|
+
}
|
|
2444
|
+
return stream;
|
|
2445
|
+
} catch (error) {
|
|
2446
|
+
await releaseClaim(activeIdentity);
|
|
2447
|
+
throw error;
|
|
2448
|
+
}
|
|
2449
|
+
}
|
|
2450
|
+
};
|
|
2451
|
+
function browserTransport(options) {
|
|
2452
|
+
return {
|
|
2453
|
+
...createBrowserInteractiveSessionControlTransport(options),
|
|
2454
|
+
async attach(sessionId, ref, request, requestOptions, reconnectAuthority) {
|
|
2455
|
+
requestOptions?.signal?.throwIfAborted();
|
|
2456
|
+
if (options.terminalTokenProvider === void 0) throw new Error("Browser interactive terminal attach requires terminalTokenProvider");
|
|
2457
|
+
const exactRef = AgentInteractiveSessionRefSchema.parse(ref);
|
|
2458
|
+
const { handlers, ...wireRequest } = request;
|
|
2459
|
+
const { control, ...terminalRequest } = AgentInteractiveSessionAttachSchema.parse(wireRequest);
|
|
2460
|
+
const terminalOptions = {
|
|
2461
|
+
url: browserInteractiveTerminalEndpoint(options.sessionApiUrl, sessionId),
|
|
2462
|
+
token: options.terminalTokenProvider,
|
|
2463
|
+
connectionId: sessionId,
|
|
2464
|
+
...terminalRequest,
|
|
2465
|
+
incarnationId: exactRef.incarnationId,
|
|
2466
|
+
control,
|
|
2467
|
+
authFormat: "edge",
|
|
2468
|
+
signal: requestOptions?.signal,
|
|
2469
|
+
...reconnectAuthority === void 0 ? {} : { reconnectAuthority },
|
|
2470
|
+
...handlers === void 0 ? {} : { handlers }
|
|
2471
|
+
};
|
|
2472
|
+
requestOptions?.signal?.throwIfAborted();
|
|
2473
|
+
const stream = await TerminalStream.connect(terminalOptions);
|
|
2474
|
+
if (requestOptions?.signal?.aborted) {
|
|
2475
|
+
await stream.close();
|
|
2476
|
+
requestOptions.signal.throwIfAborted();
|
|
2477
|
+
}
|
|
2478
|
+
return stream;
|
|
2479
|
+
}
|
|
2480
|
+
};
|
|
2481
|
+
}
|
|
2482
|
+
/** Concrete controller for browser deep links and terminal attachment. */
|
|
2483
|
+
var BrowserInteractiveSessionController = class extends InteractiveSessionController {
|
|
2484
|
+
constructor(options) {
|
|
2485
|
+
super(browserTransport(options), options);
|
|
2486
|
+
}
|
|
2487
|
+
};
|
|
2488
|
+
//#endregion
|
|
2489
|
+
export { mergeRuntimeBackendConfig as A, SANDBOX_PROXY_REQUEST_MAX_BYTES as C, parseSSEStream as D, encodeTextForWire as E, createAgentRunOutcomeTracker as M, deriveAgentResultOutcome as N, applyRequestedModel as O, deriveAgentRunOutcome as P, validateAcceptedDispatchRunRef as S, encodePromptForWire as T, resolveTraceId as _, TERMINAL_WS_ECHO_SUBPROTOCOL as a, uploadChunked as b, requestScopedToken as c, normalizeSessionInfo as d, sessionMessageRequestBody as f, mintTraceId as g, isTraceId as h, TerminalStreamError as i, normalizeRuntimeBackendConfig as j, assertCurrentBackendType as k, SandboxRuntimeApi as l, TRACE_ID_HEADER as m, InteractiveSessionController as n, assertScopedTokenActive as o, waitForRetryAfter as p, TerminalStream as r, requestInteractiveSessionToken as s, BrowserInteractiveSessionController as t, isRetryableCredentialRefusal as u, appendSessionIdQuery as v, FILE_DECODED_WRITE_MAX_BYTES as w, resolveDispatchRunIdentity as x, sessionHeaders as y };
|