@tangle-network/sandbox 0.58.8 → 0.60.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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-1MxGwnx3.d.ts → agent-run-outcome-CBaBwtEo.d.ts} +1 -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-DA3Pwd3t.js → client-8U6wuUY9.js} +6 -27
- package/dist/{client-xDfwI4yj.d.ts → client-DixtsEVX.d.ts} +4 -12
- package/dist/collaboration/index.js +1 -1
- package/dist/core.d.ts +5 -5
- package/dist/core.js +3 -3
- package/dist/{index-DFXcrGG6.d.ts → index-Cma6Iz3v.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-BZhd0M3Z.js → interactive-controller-CZpuKFMa.js} +837 -3
- package/dist/interactive-controller-Dghv9yMk.d.ts +40 -0
- package/dist/{lines-DuPzlFrJ.d.ts → lines-CqurEIaM.d.ts} +41 -2
- package/dist/lines.d.ts +2 -2
- package/dist/lines.js +21 -0
- 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-l8HsyZzA.d.ts → preview-BQOsoAEx.d.ts} +19 -6
- package/dist/runtime.d.ts +6 -3
- package/dist/runtime.js +3 -3
- package/dist/{sandbox-fTLRps4I.d.ts → sandbox-CJt1v5Cj.d.ts} +9 -40
- package/dist/{sandbox-D8HtCO-L.js → sandbox-DSP2E-3S.js} +88 -865
- package/dist/tangle/index.d.ts +1 -1
- package/dist/tangle/index.js +1 -1
- package/dist/{tangle-CYGQg5Bf.js → tangle-DgmZElaI.js} +1 -1
- package/dist/{types-B_rwXChV.d.ts → types-C8OQ8bzc.d.ts} +7 -2
- package/package.json +2 -2
- 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,9 @@
|
|
|
1
1
|
import { r as backendTypeSchema } from "./backend-types-C7b_Gpa0.js";
|
|
2
|
-
import { C as
|
|
2
|
+
import { A as mergeRuntimeBackendConfig, C as SANDBOX_PROXY_REQUEST_MAX_BYTES, D as parseSSEStream, M as createAgentRunOutcomeTracker, N as deriveAgentResultOutcome, O as applyRequestedModel, S as validateAcceptedDispatchRunRef, T as encodePromptForWire, _ as resolveTraceId, b as uploadChunked, c as requestScopedToken, d as normalizeSessionInfo, f as sessionMessageRequestBody, g as mintTraceId, h as isTraceId, j as normalizeRuntimeBackendConfig, k as assertCurrentBackendType, l as SandboxRuntimeApi, m as TRACE_ID_HEADER, n as InteractiveSessionController, o as assertScopedTokenActive, p as waitForRetryAfter, r as TerminalStream, u as isRetryableCredentialRefusal, v as appendSessionIdQuery, x as resolveDispatchRunIdentity, y as sessionHeaders } from "./interactive-controller-CZpuKFMa.js";
|
|
3
3
|
import { _ as parseErrorResponse, c as NotFoundError, f as SandboxError, g as ValidationError, h as TimeoutError, m as StateError, n as CapabilityError, p as ServerError, r as EdgeNotReadyError, s as NetworkError, t as AuthError, u as QuotaError } from "./errors-CKl_BSlD.js";
|
|
4
|
-
import {
|
|
5
|
-
import { n as combineAbortSignals, t as awaitWithAbort } from "./abort-signal-BpYYr4JT.js";
|
|
4
|
+
import { d as awaitWithAbort, f as combineAbortSignals, g as interactiveSessionStatusResponseSchema, h as interactiveSessionControlValidationResponseSchema, l as createInteractiveControlHolderId, m as interactiveSessionControlReleaseResponseSchema, p as interactiveSessionControlClaimResponseSchema } from "./browser-interactive-control-controller-BJf0P_J4.js";
|
|
6
5
|
import { SandboxLines } from "./lines.js";
|
|
7
|
-
import "./specs-CnqSWFNT-
|
|
6
|
+
import "./specs-CnqSWFNT-i2wJxPoD.js";
|
|
8
7
|
import { AgentExactRunControlRefSchema, AgentInteractiveSessionAttachSchema, AgentInteractiveSessionControlClaimAcknowledgementSchema, AgentInteractiveSessionControlClaimRequestSchema, AgentInteractiveSessionControlClaimSchema, AgentInteractiveSessionPromptAcknowledgementSchema, AgentInteractiveSessionPromptCommandSchema, AgentInteractiveSessionRefSchema, AgentInteractiveSessionStartSchema, AgentInteractiveSessionStopAcknowledgementSchema, AgentInteractiveSessionStopCommandSchema, AgentRunCancellationAcknowledgementSchema, AgentRunCancellationRequestSchema, InteractionAcknowledgementSchema, InteractionBindingSchema, InteractionRequestSchema, InteractionResponseCommandSchema, InteractionResponseSchema, TerminalInputSchema, TerminalOutputEventSchema, TerminalReplayWindowSchema, TerminalResizeSchema, TerminalSessionRefSchema, agentInteractiveSessionControlClaimAcknowledgementMatchesRequest, agentInteractiveSessionControlClaimIsNewer, agentInteractiveSessionControlClaimMatchesRef, agentInteractiveSessionPromptAcknowledgementMatchesCommand, agentInteractiveSessionPromptRequestDigest, agentInteractiveSessionRefMatchesStart, agentInteractiveSessionStatusMatchesRef, agentInteractiveSessionStopAcknowledgementMatchesCommand, agentRunCancellationAcknowledgementMatchesRequest, canonicalCandidateDigest, exactAgentInteractiveSessionStart, sha256DigestSchema, terminalSessionUsable } from "@tangle-network/agent-interface";
|
|
9
8
|
import { z } from "zod";
|
|
10
9
|
import { AgentInteractiveSessionControlClaimSchema as AgentInteractiveSessionControlClaimSchema$1, AgentInteractiveSessionPromptAcknowledgementSchema as AgentInteractiveSessionPromptAcknowledgementSchema$1, AgentInteractiveSessionRefSchema as AgentInteractiveSessionRefSchema$1, AgentInteractiveSessionStatusSchema, AgentInteractiveSessionStopAcknowledgementSchema as AgentInteractiveSessionStopAcknowledgementSchema$1 } from "@tangle-network/agent-interface/environment-interactive-control";
|
|
@@ -405,17 +404,25 @@ function parseSandboxRuntimeCapabilities(raw) {
|
|
|
405
404
|
if ("responseDedupe" in interactionsRecord && typeof interactionsRecord.responseDedupe !== "boolean") invalidCapabilities("a non-boolean 'interactions.responseDedupe' flag");
|
|
406
405
|
const interactiveAgentValue = record.interactiveAgent;
|
|
407
406
|
let interactiveAgent;
|
|
408
|
-
if (interactiveAgentValue !== void 0)
|
|
409
|
-
"
|
|
410
|
-
|
|
411
|
-
"
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
407
|
+
if (interactiveAgentValue !== void 0) {
|
|
408
|
+
if (interactiveAgentValue === null || typeof interactiveAgentValue !== "object" || Array.isArray(interactiveAgentValue)) invalidCapabilities("a malformed 'interactiveAgent' group");
|
|
409
|
+
const interactiveAgentRecord = interactiveAgentValue;
|
|
410
|
+
if ("claudeSubscription" in interactiveAgentRecord && typeof interactiveAgentRecord.claudeSubscription !== "boolean") invalidCapabilities("a non-boolean 'interactiveAgent.claudeSubscription' flag");
|
|
411
|
+
interactiveAgent = {
|
|
412
|
+
...readFlagGroup(record, "interactiveAgent", [
|
|
413
|
+
"start",
|
|
414
|
+
"status",
|
|
415
|
+
"attach",
|
|
416
|
+
"control",
|
|
417
|
+
"reattach",
|
|
418
|
+
"sendPrompt",
|
|
419
|
+
"input",
|
|
420
|
+
"resize",
|
|
421
|
+
"stop"
|
|
422
|
+
]),
|
|
423
|
+
...typeof interactiveAgentRecord.claudeSubscription === "boolean" ? { claudeSubscription: interactiveAgentRecord.claudeSubscription } : {}
|
|
424
|
+
};
|
|
425
|
+
}
|
|
419
426
|
return {
|
|
420
427
|
schema: 1,
|
|
421
428
|
...typeof record.cliAuthReferences === "boolean" ? { cliAuthReferences: record.cliAuthReferences } : {},
|
|
@@ -1463,92 +1470,6 @@ var SandboxInteractiveOperations = class {
|
|
|
1463
1470
|
}
|
|
1464
1471
|
};
|
|
1465
1472
|
//#endregion
|
|
1466
|
-
//#region src/scoped-token.ts
|
|
1467
|
-
/** Maximum time for the exact interactive terminal-token request. */
|
|
1468
|
-
const SCOPED_TOKEN_REQUEST_TIMEOUT_MS = 5e3;
|
|
1469
|
-
const scopedTokenResponseSchema = z.object({
|
|
1470
|
-
token: z.string().min(1),
|
|
1471
|
-
expiresAt: z.number().finite().nonnegative(),
|
|
1472
|
-
runtimeUrl: z.string().min(1),
|
|
1473
|
-
sidecarProxyUrl: z.string().min(1),
|
|
1474
|
-
scope: z.enum([
|
|
1475
|
-
"session",
|
|
1476
|
-
"session-runtime",
|
|
1477
|
-
"project",
|
|
1478
|
-
"read-only"
|
|
1479
|
-
])
|
|
1480
|
-
});
|
|
1481
|
-
/** Reject a scoped credential that the SDK must not send to a consumer. */
|
|
1482
|
-
function assertScopedTokenActive(token, expectedScope) {
|
|
1483
|
-
if (expectedScope !== void 0 && token.scope !== expectedScope) throw new ValidationError(`Scoped token must use the ${expectedScope} scope`);
|
|
1484
|
-
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");
|
|
1485
|
-
}
|
|
1486
|
-
function parseScopedTokenResponse(raw, expectedScope) {
|
|
1487
|
-
const parsed = scopedTokenResponseSchema.safeParse(raw);
|
|
1488
|
-
if (!parsed.success) throw new ServerError("Sandbox API returned an invalid scoped token response.", 502, { origin: "sandbox-api" });
|
|
1489
|
-
if (parsed.data.scope !== expectedScope) throw new ServerError(`Sandbox API returned a ${parsed.data.scope} token for a ${expectedScope} request.`, 502, { origin: "sandbox-api" });
|
|
1490
|
-
const token = {
|
|
1491
|
-
token: parsed.data.token,
|
|
1492
|
-
expiresAt: /* @__PURE__ */ new Date(parsed.data.expiresAt * 1e3),
|
|
1493
|
-
runtimeUrl: parsed.data.runtimeUrl,
|
|
1494
|
-
sidecarProxyUrl: parsed.data.sidecarProxyUrl,
|
|
1495
|
-
scope: parsed.data.scope
|
|
1496
|
-
};
|
|
1497
|
-
try {
|
|
1498
|
-
assertScopedTokenActive(token, expectedScope);
|
|
1499
|
-
} catch {
|
|
1500
|
-
throw new ServerError("Sandbox API returned an expired or invalid scoped token.", 502, { origin: "sandbox-api" });
|
|
1501
|
-
}
|
|
1502
|
-
return token;
|
|
1503
|
-
}
|
|
1504
|
-
async function requestScopedToken(client, sandboxId, options, requestOptions) {
|
|
1505
|
-
if ((options.scope === "session" || options.scope === "session-runtime") && !options.sessionId) throw new ValidationError(`${options.scope} scope requires a sessionId`);
|
|
1506
|
-
if (options.scope === "session" && !options.runtimeSessionId) throw new ValidationError("session scope requires the actual runtimeSessionId");
|
|
1507
|
-
const response = await client.fetch(`/v1/sandboxes/${encodeURIComponent(sandboxId)}/scoped-token`, {
|
|
1508
|
-
method: "POST",
|
|
1509
|
-
headers: { "Content-Type": "application/json" },
|
|
1510
|
-
body: JSON.stringify({
|
|
1511
|
-
scope: options.scope,
|
|
1512
|
-
...options.sessionId ? { sessionId: options.sessionId } : {},
|
|
1513
|
-
...options.scope === "session" ? { runtimeSessionId: options.runtimeSessionId } : {},
|
|
1514
|
-
...options.ttlMinutes ? { ttlMinutes: options.ttlMinutes } : {}
|
|
1515
|
-
}),
|
|
1516
|
-
...options.signal === void 0 ? {} : { signal: options.signal }
|
|
1517
|
-
}, requestOptions);
|
|
1518
|
-
if (!response.ok) {
|
|
1519
|
-
const body = await response.text();
|
|
1520
|
-
throw parseErrorResponse(response.status, body, void 0, response.headers);
|
|
1521
|
-
}
|
|
1522
|
-
let raw;
|
|
1523
|
-
try {
|
|
1524
|
-
raw = await response.json();
|
|
1525
|
-
} catch {
|
|
1526
|
-
throw new ServerError("Sandbox API returned invalid scoped token JSON.", 502, { origin: "sandbox-api" });
|
|
1527
|
-
}
|
|
1528
|
-
return parseScopedTokenResponse(raw, options.scope);
|
|
1529
|
-
}
|
|
1530
|
-
function parseInteractiveSessionTokenRef(ref) {
|
|
1531
|
-
const parsed = AgentInteractiveSessionRefSchema.safeParse(ref);
|
|
1532
|
-
if (!parsed.success) throw new ValidationError("Interactive session ref is invalid.", { ref: parsed.error.issues[0]?.message ?? "invalid ref" });
|
|
1533
|
-
return parsed.data;
|
|
1534
|
-
}
|
|
1535
|
-
function interactiveSessionTokenOptions(ref, options = {}) {
|
|
1536
|
-
const exactRef = parseInteractiveSessionTokenRef(ref);
|
|
1537
|
-
return {
|
|
1538
|
-
sandboxId: exactRef.run.environmentId,
|
|
1539
|
-
request: {
|
|
1540
|
-
scope: "session-runtime",
|
|
1541
|
-
sessionId: exactRef.run.sessionId,
|
|
1542
|
-
...options.ttlMinutes === void 0 ? {} : { ttlMinutes: options.ttlMinutes },
|
|
1543
|
-
...options.signal === void 0 ? {} : { signal: options.signal }
|
|
1544
|
-
}
|
|
1545
|
-
};
|
|
1546
|
-
}
|
|
1547
|
-
function requestInteractiveSessionToken(client, ref, options) {
|
|
1548
|
-
const exact = interactiveSessionTokenOptions(ref, options);
|
|
1549
|
-
return requestScopedToken(client, exact.sandboxId, exact.request, { timeoutMs: SCOPED_TOKEN_REQUEST_TIMEOUT_MS });
|
|
1550
|
-
}
|
|
1551
|
-
//#endregion
|
|
1552
1473
|
//#region src/sandbox-interactive-terminal.ts
|
|
1553
1474
|
var SandboxInteractiveTerminalOperations = class {
|
|
1554
1475
|
constructor(host) {
|
|
@@ -1652,752 +1573,6 @@ var SandboxInteractiveTerminalOperations = class {
|
|
|
1652
1573
|
});
|
|
1653
1574
|
}
|
|
1654
1575
|
};
|
|
1655
|
-
const TERMINAL_WS_MAX_DIMENSION = 4096;
|
|
1656
|
-
/** Input chunk size that leaves room for JSON escaping inside one frame. */
|
|
1657
|
-
const TERMINAL_WS_INPUT_FRAME_CHUNK_CHARS = 128 * 1024;
|
|
1658
|
-
/** WebSocket authentication envelope prefixes. */
|
|
1659
|
-
const TERMINAL_WS_EDGE_BEARER_SUBPROTOCOL_PREFIX = "bearer.";
|
|
1660
|
-
const TERMINAL_WS_SIDECAR_BEARER_SUBPROTOCOL_PREFIX = "tangle.bearer.";
|
|
1661
|
-
/** Non-credential protocol selected during a successful terminal handshake. */
|
|
1662
|
-
const TERMINAL_WS_ECHO_SUBPROTOCOL = "tangle.terminal.v1";
|
|
1663
|
-
const terminalGeometry = {
|
|
1664
|
-
cols: z.number().int().min(1).max(TERMINAL_WS_MAX_DIMENSION),
|
|
1665
|
-
rows: z.number().int().min(1).max(TERMINAL_WS_MAX_DIMENSION)
|
|
1666
|
-
};
|
|
1667
|
-
const terminalInitMessageSchema = z.object({
|
|
1668
|
-
type: z.literal("init"),
|
|
1669
|
-
connectionId: z.string().optional(),
|
|
1670
|
-
/** Required for an interactive-agent PTY; absent for generic terminals. */
|
|
1671
|
-
incarnationId: z.string().uuid().optional(),
|
|
1672
|
-
...terminalGeometry,
|
|
1673
|
-
command: z.string().min(1).optional(),
|
|
1674
|
-
cwd: z.string().min(1).optional(),
|
|
1675
|
-
env: z.record(z.string(), z.string()).optional(),
|
|
1676
|
-
sessionId: z.string().min(1).optional(),
|
|
1677
|
-
/** Canonical control claim for an interactive-agent PTY. */
|
|
1678
|
-
control: AgentInteractiveSessionControlClaimSchema.optional()
|
|
1679
|
-
}).superRefine((message, refinement) => {
|
|
1680
|
-
if (message.incarnationId !== void 0 && message.control === void 0) refinement.addIssue({
|
|
1681
|
-
code: "custom",
|
|
1682
|
-
path: ["control"],
|
|
1683
|
-
message: "Interactive session attach requires a control claim"
|
|
1684
|
-
});
|
|
1685
|
-
if (message.incarnationId === void 0 && message.control !== void 0) refinement.addIssue({
|
|
1686
|
-
code: "custom",
|
|
1687
|
-
path: ["control"],
|
|
1688
|
-
message: "Generic terminal attach cannot carry an interactive control claim"
|
|
1689
|
-
});
|
|
1690
|
-
});
|
|
1691
|
-
const terminalInputMessageSchema = z.object({
|
|
1692
|
-
type: z.literal("input"),
|
|
1693
|
-
data: z.string()
|
|
1694
|
-
});
|
|
1695
|
-
const terminalResizeMessageSchema = z.object({
|
|
1696
|
-
type: z.literal("resize"),
|
|
1697
|
-
...terminalGeometry
|
|
1698
|
-
});
|
|
1699
|
-
const terminalRenewMessageSchema = z.object({ type: z.literal("renew") });
|
|
1700
|
-
const terminalCloseMessageSchema = z.object({ type: z.literal("close") });
|
|
1701
|
-
z.union([
|
|
1702
|
-
terminalInitMessageSchema,
|
|
1703
|
-
terminalInputMessageSchema,
|
|
1704
|
-
terminalResizeMessageSchema,
|
|
1705
|
-
terminalRenewMessageSchema,
|
|
1706
|
-
terminalCloseMessageSchema
|
|
1707
|
-
]);
|
|
1708
|
-
const terminalReadyMessageSchema = z.object({
|
|
1709
|
-
type: z.literal("ready"),
|
|
1710
|
-
connectionId: z.string(),
|
|
1711
|
-
sessionId: z.string(),
|
|
1712
|
-
restored: z.boolean(),
|
|
1713
|
-
detachTimeoutMs: z.number().int().positive(),
|
|
1714
|
-
/** Exact viewer count held by the runtime for this connection. */
|
|
1715
|
-
attachCount: z.number().int().positive().optional(),
|
|
1716
|
-
/** Server-issued output cursor window for exact interactive terminals. */
|
|
1717
|
-
cursors: z.object({
|
|
1718
|
-
earliest: z.number().int().nonnegative(),
|
|
1719
|
-
latest: z.number().int().nonnegative()
|
|
1720
|
-
}).optional()
|
|
1721
|
-
});
|
|
1722
|
-
/** One sequenced output frame for an exact interactive terminal. */
|
|
1723
|
-
const terminalOutputMessageSchema = z.object({
|
|
1724
|
-
type: z.literal("output"),
|
|
1725
|
-
seq: z.number().int().positive(),
|
|
1726
|
-
/** Base64-encoded UTF-8 bytes from the retained terminal event. */
|
|
1727
|
-
data: z.string().min(1)
|
|
1728
|
-
});
|
|
1729
|
-
const terminalExitMessageSchema = z.object({
|
|
1730
|
-
type: z.literal("exit"),
|
|
1731
|
-
exitCode: z.number().optional(),
|
|
1732
|
-
exitSignal: z.string().optional()
|
|
1733
|
-
});
|
|
1734
|
-
const terminalRenewedMessageSchema = z.object({
|
|
1735
|
-
type: z.literal("renewed"),
|
|
1736
|
-
sessionId: z.string()
|
|
1737
|
-
});
|
|
1738
|
-
const terminalErrorMessageSchema = z.object({
|
|
1739
|
-
type: z.literal("error"),
|
|
1740
|
-
code: z.string(),
|
|
1741
|
-
message: z.string()
|
|
1742
|
-
});
|
|
1743
|
-
const terminalServerMessageSchema = z.union([
|
|
1744
|
-
terminalReadyMessageSchema,
|
|
1745
|
-
terminalOutputMessageSchema,
|
|
1746
|
-
terminalExitMessageSchema,
|
|
1747
|
-
terminalRenewedMessageSchema,
|
|
1748
|
-
terminalErrorMessageSchema
|
|
1749
|
-
]);
|
|
1750
|
-
//#endregion
|
|
1751
|
-
//#region src/terminal-stream.ts
|
|
1752
|
-
/**
|
|
1753
|
-
* TerminalStream — typed client for the sandbox terminal WebSocket protocol.
|
|
1754
|
-
*
|
|
1755
|
-
* Drives a live PTY session (an interactive harness TUI or a plain shell)
|
|
1756
|
-
* from the caller's own program: binary frames stream raw PTY output bytes,
|
|
1757
|
-
* TEXT JSON frames carry the control protocol. The browser-safe wire contract
|
|
1758
|
-
* is defined by the shared browser-safe runtime contract and shared with the
|
|
1759
|
-
* sidecar:
|
|
1760
|
-
*
|
|
1761
|
-
* client → server (TEXT JSON):
|
|
1762
|
-
* init {connectionId?, cols, rows, command?, cwd?, env?} — MUST be first
|
|
1763
|
-
* input {data}
|
|
1764
|
-
* resize {cols, rows}
|
|
1765
|
-
*
|
|
1766
|
-
* Interactive-agent init frames add the exact process authority:
|
|
1767
|
-
* {incarnationId, control: {refDigest, generation, leaseId, holderId, expiresAt}}
|
|
1768
|
-
* Subsequent input and resize frames carry only their operation fields; the
|
|
1769
|
-
* server binds authority to the init for the socket lifetime.
|
|
1770
|
-
* server → client (TEXT JSON):
|
|
1771
|
-
* ready {connectionId, sessionId, restored, detachTimeoutMs,
|
|
1772
|
-
* attachCount?, cursors?}
|
|
1773
|
-
* output {seq, data} — exact interactive output as base64 UTF-8 bytes
|
|
1774
|
-
* exit {exitCode?, exitSignal?}
|
|
1775
|
-
* error {code, message}
|
|
1776
|
-
* rec / rec.done — recording tee frames for the platform's session
|
|
1777
|
-
* capture consumer; not part of the client surface
|
|
1778
|
-
* server → client (BINARY): raw PTY output bytes
|
|
1779
|
-
*
|
|
1780
|
-
* Detach/reconnect: the server keeps the PTY alive for `detachTimeoutMs`
|
|
1781
|
-
* (5 minutes today) after the socket closes; re-dialing with the SAME
|
|
1782
|
-
* connectionId reattaches and replays the buffered output history, so a
|
|
1783
|
-
* fresh client repaints the current screen.
|
|
1784
|
-
*
|
|
1785
|
-
* Browser-safe: uses the global `WebSocket` (browsers, Workers, Node >= 22)
|
|
1786
|
-
* and never imports `ws` — the same environment contract as
|
|
1787
|
-
* `session-gateway/client.ts`.
|
|
1788
|
-
*/
|
|
1789
|
-
/** A protocol `error` control frame or a transport failure. */
|
|
1790
|
-
var TerminalStreamError = class extends Error {
|
|
1791
|
-
/** Protocol error code (e.g. `INIT_FAILED`) or `TRANSPORT` for socket faults. */
|
|
1792
|
-
code;
|
|
1793
|
-
constructor(message, code) {
|
|
1794
|
-
super(message);
|
|
1795
|
-
this.name = "TerminalStreamError";
|
|
1796
|
-
this.code = code;
|
|
1797
|
-
}
|
|
1798
|
-
};
|
|
1799
|
-
/**
|
|
1800
|
-
* The sidecar caps WebSocket frames at 1 MiB
|
|
1801
|
-
* (`TERMINAL_WS_MAX_PAYLOAD_BYTES` in the shared runtime contract) and drops
|
|
1802
|
-
* the connection on
|
|
1803
|
-
* larger frames. `write()` chunks input so every serialized `input` frame
|
|
1804
|
-
* stays under that cap: 128 Ki characters per chunk × a worst-case JSON
|
|
1805
|
-
* escape expansion of 6 bytes per character (`` etc.) ≈ 768 KiB,
|
|
1806
|
-
* comfortably below the limit including the frame's JSON envelope.
|
|
1807
|
-
*/
|
|
1808
|
-
const DEFAULT_COLS = 80;
|
|
1809
|
-
const DEFAULT_ROWS = 24;
|
|
1810
|
-
const DEFAULT_CONNECT_TIMEOUT_MS = 15e3;
|
|
1811
|
-
/**
|
|
1812
|
-
* base64url-encode a UTF-8 string without padding — the exact envelope the
|
|
1813
|
-
* edge's `parseTerminalWsSubprotocolToken` decodes (its strict round-trip
|
|
1814
|
-
* check tolerates padding, but the reference browser client emits unpadded).
|
|
1815
|
-
*/
|
|
1816
|
-
function base64UrlEncodeUtf8(value) {
|
|
1817
|
-
if (typeof btoa !== "function") throw new TerminalStreamError("global btoa is unavailable; cannot build the edge bearer subprotocol", "ENVIRONMENT");
|
|
1818
|
-
const bytes = new TextEncoder().encode(value);
|
|
1819
|
-
let binary = "";
|
|
1820
|
-
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
1821
|
-
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
1822
|
-
}
|
|
1823
|
-
function buildAuthSubprotocols(format, token) {
|
|
1824
|
-
if (format === "sidecar-direct") return [`${TERMINAL_WS_SIDECAR_BEARER_SUBPROTOCOL_PREFIX}${token}`, TERMINAL_WS_ECHO_SUBPROTOCOL];
|
|
1825
|
-
return [`${TERMINAL_WS_EDGE_BEARER_SUBPROTOCOL_PREFIX}${base64UrlEncodeUtf8(token)}`, TERMINAL_WS_ECHO_SUBPROTOCOL];
|
|
1826
|
-
}
|
|
1827
|
-
/**
|
|
1828
|
-
* Resolve the dial credential: invoke a provider (fresh token per dial) or
|
|
1829
|
-
* pass a string through. Fails loud on an empty result — a blank credential
|
|
1830
|
-
* would dial and be rejected with an opaque 401 downstream.
|
|
1831
|
-
*/
|
|
1832
|
-
async function resolveTerminalToken(token, signal) {
|
|
1833
|
-
const value = typeof token === "function" ? await token(signal) : token;
|
|
1834
|
-
if (typeof value === "object" && value !== null) {
|
|
1835
|
-
try {
|
|
1836
|
-
assertScopedTokenActive(value, "session-runtime");
|
|
1837
|
-
} catch {
|
|
1838
|
-
throw new TerminalStreamError("Terminal stream scoped token is expired or invalid", "INVALID_TOKEN");
|
|
1839
|
-
}
|
|
1840
|
-
return value.token;
|
|
1841
|
-
}
|
|
1842
|
-
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");
|
|
1843
|
-
return value;
|
|
1844
|
-
}
|
|
1845
|
-
function terminalAbortReason(signal) {
|
|
1846
|
-
return signal.reason instanceof Error ? signal.reason : new DOMException("Terminal attach was aborted", "AbortError");
|
|
1847
|
-
}
|
|
1848
|
-
function awaitTerminalOperation(promise, signal) {
|
|
1849
|
-
if (!signal) return promise;
|
|
1850
|
-
signal.throwIfAborted();
|
|
1851
|
-
return new Promise((resolve, reject) => {
|
|
1852
|
-
let settled = false;
|
|
1853
|
-
const cleanup = () => signal.removeEventListener("abort", onAbort);
|
|
1854
|
-
const onAbort = () => {
|
|
1855
|
-
if (settled) return;
|
|
1856
|
-
settled = true;
|
|
1857
|
-
cleanup();
|
|
1858
|
-
reject(terminalAbortReason(signal));
|
|
1859
|
-
};
|
|
1860
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
1861
|
-
promise.then((value) => {
|
|
1862
|
-
if (settled) return;
|
|
1863
|
-
settled = true;
|
|
1864
|
-
cleanup();
|
|
1865
|
-
resolve(value);
|
|
1866
|
-
}, (cause) => {
|
|
1867
|
-
if (settled) return;
|
|
1868
|
-
settled = true;
|
|
1869
|
-
cleanup();
|
|
1870
|
-
reject(cause);
|
|
1871
|
-
});
|
|
1872
|
-
});
|
|
1873
|
-
}
|
|
1874
|
-
function toWebSocketUrl(url) {
|
|
1875
|
-
let parsed;
|
|
1876
|
-
try {
|
|
1877
|
-
parsed = new URL(url);
|
|
1878
|
-
} catch {
|
|
1879
|
-
throw new TerminalStreamError(`Terminal WebSocket URL is not absolute: ${url}`, "INVALID_URL");
|
|
1880
|
-
}
|
|
1881
|
-
if (parsed.protocol === "https:") parsed.protocol = "wss:";
|
|
1882
|
-
else if (parsed.protocol === "http:") parsed.protocol = "ws:";
|
|
1883
|
-
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");
|
|
1884
|
-
return parsed.toString();
|
|
1885
|
-
}
|
|
1886
|
-
function assertDimension(name, value) {
|
|
1887
|
-
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");
|
|
1888
|
-
}
|
|
1889
|
-
/** Decode the sidecar's base64 output frame without a Node-only dependency. */
|
|
1890
|
-
function decodeBase64(value) {
|
|
1891
|
-
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");
|
|
1892
|
-
let binary;
|
|
1893
|
-
try {
|
|
1894
|
-
binary = atob(value);
|
|
1895
|
-
} catch {
|
|
1896
|
-
throw new TerminalStreamError("Terminal output frame is not valid base64", "INVALID_FRAME");
|
|
1897
|
-
}
|
|
1898
|
-
const bytes = new Uint8Array(binary.length);
|
|
1899
|
-
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
|
|
1900
|
-
return bytes;
|
|
1901
|
-
}
|
|
1902
|
-
function normalizeInteractiveSessionIdentity(incarnationId, control) {
|
|
1903
|
-
if (incarnationId === void 0 && control === void 0) return void 0;
|
|
1904
|
-
if (typeof incarnationId !== "string" || incarnationId.length === 0 || incarnationId.trim() !== incarnationId) throw new TerminalStreamError("Interactive terminal attach requires an exact incarnationId", "INVALID_INTERACTIVE_IDENTITY");
|
|
1905
|
-
if (control === void 0) throw new TerminalStreamError("Interactive terminal attach requires an exact control claim", "INVALID_INTERACTIVE_CONTROL");
|
|
1906
|
-
const parsedControl = AgentInteractiveSessionControlClaimSchema.safeParse(control);
|
|
1907
|
-
if (!parsedControl.success) throw new TerminalStreamError("Interactive terminal attach requires an exact control claim", "INVALID_INTERACTIVE_CONTROL");
|
|
1908
|
-
const expiresAt = Date.parse(parsedControl.data.expiresAt);
|
|
1909
|
-
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) throw new TerminalStreamError("Interactive terminal control claim is expired", "INTERACTIVE_CONTROL_EXPIRED");
|
|
1910
|
-
return {
|
|
1911
|
-
incarnationId,
|
|
1912
|
-
control: parsedControl.data
|
|
1913
|
-
};
|
|
1914
|
-
}
|
|
1915
|
-
function interactiveInitFields(identity) {
|
|
1916
|
-
if (identity === void 0) return {};
|
|
1917
|
-
return {
|
|
1918
|
-
incarnationId: identity.incarnationId,
|
|
1919
|
-
control: identity.control
|
|
1920
|
-
};
|
|
1921
|
-
}
|
|
1922
|
-
function buildTerminalInitMessage(options, identity) {
|
|
1923
|
-
if (typeof options.connectionId !== "string" || !options.connectionId.trim()) throw new TerminalStreamError("Terminal stream connectionId must not be empty", "INVALID_CONNECTION_ID");
|
|
1924
|
-
if (options.cols !== void 0) assertDimension("cols", options.cols);
|
|
1925
|
-
if (options.rows !== void 0) assertDimension("rows", options.rows);
|
|
1926
|
-
const parsed = terminalInitMessageSchema.safeParse({
|
|
1927
|
-
type: "init",
|
|
1928
|
-
connectionId: options.connectionId,
|
|
1929
|
-
cols: options.cols ?? DEFAULT_COLS,
|
|
1930
|
-
rows: options.rows ?? DEFAULT_ROWS,
|
|
1931
|
-
...options.command !== void 0 ? { command: options.command } : {},
|
|
1932
|
-
...options.cwd !== void 0 ? { cwd: options.cwd } : {},
|
|
1933
|
-
...options.env !== void 0 ? { env: options.env } : {},
|
|
1934
|
-
...interactiveInitFields(identity)
|
|
1935
|
-
});
|
|
1936
|
-
if (!parsed.success) throw new TerminalStreamError("Terminal stream init does not match the shared terminal protocol", "INVALID_INIT");
|
|
1937
|
-
return parsed.data;
|
|
1938
|
-
}
|
|
1939
|
-
function assertInteractiveControlActive(identity) {
|
|
1940
|
-
if (identity === void 0) return;
|
|
1941
|
-
if (Date.parse(identity.control.expiresAt) <= Date.now()) throw new TerminalStreamError("Interactive terminal control claim is expired", "INTERACTIVE_CONTROL_EXPIRED");
|
|
1942
|
-
}
|
|
1943
|
-
/**
|
|
1944
|
-
* Split input so each serialized `input` frame stays under the server's
|
|
1945
|
-
* 1 MiB frame cap, without splitting a surrogate pair across frames (a torn
|
|
1946
|
-
* pair would reach the PTY as two invalid UTF-8 writes).
|
|
1947
|
-
*/
|
|
1948
|
-
function* chunkInput(text) {
|
|
1949
|
-
if (text.length <= 131072) {
|
|
1950
|
-
yield text;
|
|
1951
|
-
return;
|
|
1952
|
-
}
|
|
1953
|
-
let index = 0;
|
|
1954
|
-
while (index < text.length) {
|
|
1955
|
-
let end = Math.min(index + TERMINAL_WS_INPUT_FRAME_CHUNK_CHARS, text.length);
|
|
1956
|
-
if (end < text.length) {
|
|
1957
|
-
const trailing = text.charCodeAt(end - 1);
|
|
1958
|
-
if (trailing >= 55296 && trailing <= 56319) end -= 1;
|
|
1959
|
-
}
|
|
1960
|
-
yield text.slice(index, end);
|
|
1961
|
-
index = end;
|
|
1962
|
-
}
|
|
1963
|
-
}
|
|
1964
|
-
/**
|
|
1965
|
-
* Client for one terminal WebSocket connection. Construct via
|
|
1966
|
-
* {@link TerminalStream.connect}, which resolves once the server
|
|
1967
|
-
* acknowledges the attach with `ready` (history replay then streams through
|
|
1968
|
-
* `handlers.onData`).
|
|
1969
|
-
*/
|
|
1970
|
-
var TerminalStream = class TerminalStream {
|
|
1971
|
-
ws;
|
|
1972
|
-
options;
|
|
1973
|
-
interactiveIdentity;
|
|
1974
|
-
initMessage;
|
|
1975
|
-
handlers;
|
|
1976
|
-
readyInfo = null;
|
|
1977
|
-
closed = false;
|
|
1978
|
-
closeWaiters = [];
|
|
1979
|
-
textDecoder = new TextDecoder();
|
|
1980
|
-
reconnectInFlight;
|
|
1981
|
-
/**
|
|
1982
|
-
* Dial the endpoint, send `init` as the first frame, and resolve once the
|
|
1983
|
-
* server responds `ready`. Rejects on a protocol `error` frame, a socket
|
|
1984
|
-
* close/failure before `ready`, or the connect timeout — always with the
|
|
1985
|
-
* reason the server gave. A token PROVIDER is awaited here, before the
|
|
1986
|
-
* socket opens, so every dial (first connect and each reconnect) carries a
|
|
1987
|
-
* fresh credential.
|
|
1988
|
-
*/
|
|
1989
|
-
static async connect(options) {
|
|
1990
|
-
const interactiveIdentity = normalizeInteractiveSessionIdentity(options.incarnationId, options.control);
|
|
1991
|
-
options.signal?.throwIfAborted();
|
|
1992
|
-
const initMessage = buildTerminalInitMessage(options, interactiveIdentity);
|
|
1993
|
-
const token = await awaitTerminalOperation(resolveTerminalToken(options.token, options.signal), options.signal);
|
|
1994
|
-
options.signal?.throwIfAborted();
|
|
1995
|
-
return new TerminalStream(options, token, interactiveIdentity, initMessage).establish(options.signal);
|
|
1996
|
-
}
|
|
1997
|
-
constructor(options, resolvedToken, interactiveIdentity, initMessage) {
|
|
1998
|
-
const exactOptions = interactiveIdentity === void 0 ? options : {
|
|
1999
|
-
...options,
|
|
2000
|
-
incarnationId: interactiveIdentity.incarnationId,
|
|
2001
|
-
control: interactiveIdentity.control
|
|
2002
|
-
};
|
|
2003
|
-
const WebSocketCtor = globalThis.WebSocket;
|
|
2004
|
-
if (typeof WebSocketCtor !== "function") throw new TerminalStreamError("global WebSocket is unavailable in this environment (Node >= 22 or a browser is required)", "ENVIRONMENT");
|
|
2005
|
-
this.options = {
|
|
2006
|
-
...exactOptions,
|
|
2007
|
-
signal: void 0
|
|
2008
|
-
};
|
|
2009
|
-
this.interactiveIdentity = interactiveIdentity;
|
|
2010
|
-
this.initMessage = initMessage;
|
|
2011
|
-
this.handlers = exactOptions.handlers ?? {};
|
|
2012
|
-
this.ws = new WebSocketCtor(toWebSocketUrl(exactOptions.url), buildAuthSubprotocols(exactOptions.authFormat ?? "edge", resolvedToken));
|
|
2013
|
-
this.ws.binaryType = "arraybuffer";
|
|
2014
|
-
}
|
|
2015
|
-
establish(signal) {
|
|
2016
|
-
return new Promise((resolve, reject) => {
|
|
2017
|
-
let settled = false;
|
|
2018
|
-
const timeoutMs = this.options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
|
|
2019
|
-
const timer = setTimeout(() => {
|
|
2020
|
-
fail(new TerminalStreamError(`Terminal attach timed out after ${timeoutMs}ms waiting for ready`, "CONNECT_TIMEOUT"));
|
|
2021
|
-
this.ws.close(1e3, "connect timeout");
|
|
2022
|
-
}, timeoutMs);
|
|
2023
|
-
const cleanup = () => {
|
|
2024
|
-
clearTimeout(timer);
|
|
2025
|
-
signal?.removeEventListener("abort", onAbort);
|
|
2026
|
-
};
|
|
2027
|
-
const succeed = () => {
|
|
2028
|
-
if (settled) return;
|
|
2029
|
-
settled = true;
|
|
2030
|
-
cleanup();
|
|
2031
|
-
resolve(this);
|
|
2032
|
-
};
|
|
2033
|
-
const fail = (error) => {
|
|
2034
|
-
if (settled) return;
|
|
2035
|
-
settled = true;
|
|
2036
|
-
cleanup();
|
|
2037
|
-
reject(error);
|
|
2038
|
-
};
|
|
2039
|
-
const onAbort = () => {
|
|
2040
|
-
if (!signal) return;
|
|
2041
|
-
fail(terminalAbortReason(signal));
|
|
2042
|
-
this.ws.close(1e3, "connect aborted");
|
|
2043
|
-
};
|
|
2044
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
2045
|
-
if (signal?.aborted) {
|
|
2046
|
-
onAbort();
|
|
2047
|
-
return;
|
|
2048
|
-
}
|
|
2049
|
-
this.ws.addEventListener("open", () => {
|
|
2050
|
-
if (settled) return;
|
|
2051
|
-
try {
|
|
2052
|
-
assertInteractiveControlActive(this.interactiveIdentity);
|
|
2053
|
-
} catch (error) {
|
|
2054
|
-
fail(error instanceof TerminalStreamError ? error : new TerminalStreamError("Interactive terminal control claim is expired", "INTERACTIVE_CONTROL_EXPIRED"));
|
|
2055
|
-
return;
|
|
2056
|
-
}
|
|
2057
|
-
this.ws.send(JSON.stringify(this.initMessage));
|
|
2058
|
-
});
|
|
2059
|
-
this.ws.addEventListener("message", (event) => {
|
|
2060
|
-
this.handleMessage(event.data, {
|
|
2061
|
-
succeed,
|
|
2062
|
-
fail,
|
|
2063
|
-
settled: () => settled
|
|
2064
|
-
});
|
|
2065
|
-
});
|
|
2066
|
-
this.ws.addEventListener("error", () => {
|
|
2067
|
-
fail(new TerminalStreamError("Terminal WebSocket transport failed before ready", "TRANSPORT"));
|
|
2068
|
-
});
|
|
2069
|
-
this.ws.addEventListener("close", (event) => {
|
|
2070
|
-
this.closed = true;
|
|
2071
|
-
fail(new TerminalStreamError(`Terminal WebSocket closed before ready (code ${event.code}${event.reason ? `: ${event.reason}` : ""})`, "CLOSED_BEFORE_READY"));
|
|
2072
|
-
for (const waiter of this.closeWaiters) waiter();
|
|
2073
|
-
this.closeWaiters = [];
|
|
2074
|
-
this.handlers.onClose?.(event.code, event.reason);
|
|
2075
|
-
});
|
|
2076
|
-
});
|
|
2077
|
-
}
|
|
2078
|
-
handleMessage(raw, connectPhase) {
|
|
2079
|
-
if (typeof raw !== "string") {
|
|
2080
|
-
if (raw instanceof ArrayBuffer) this.handlers.onData?.(new Uint8Array(raw));
|
|
2081
|
-
return;
|
|
2082
|
-
}
|
|
2083
|
-
const failProtocolFrame = () => {
|
|
2084
|
-
const error = new TerminalStreamError("Terminal control frame does not match the shared terminal protocol", "INVALID_FRAME");
|
|
2085
|
-
const beforeReady = !connectPhase.settled();
|
|
2086
|
-
if (this.ws.readyState === WebSocket.OPEN) this.ws.close(1e3, "invalid terminal frame");
|
|
2087
|
-
if (beforeReady) connectPhase.fail(error);
|
|
2088
|
-
else this.handlers.onError?.(error);
|
|
2089
|
-
};
|
|
2090
|
-
let decoded;
|
|
2091
|
-
try {
|
|
2092
|
-
decoded = JSON.parse(raw);
|
|
2093
|
-
} catch {
|
|
2094
|
-
failProtocolFrame();
|
|
2095
|
-
return;
|
|
2096
|
-
}
|
|
2097
|
-
if (decoded === null || typeof decoded !== "object" || Array.isArray(decoded) || typeof decoded.type !== "string") {
|
|
2098
|
-
failProtocolFrame();
|
|
2099
|
-
return;
|
|
2100
|
-
}
|
|
2101
|
-
const message = decoded;
|
|
2102
|
-
if (message.type === "rec" || message.type === "rec.done") return;
|
|
2103
|
-
if (message.type !== "ready" && message.type !== "output" && message.type !== "exit" && message.type !== "renewed" && message.type !== "error") return;
|
|
2104
|
-
const parsed = terminalServerMessageSchema.safeParse(message);
|
|
2105
|
-
if (!parsed.success) {
|
|
2106
|
-
failProtocolFrame();
|
|
2107
|
-
return;
|
|
2108
|
-
}
|
|
2109
|
-
switch (parsed.data.type) {
|
|
2110
|
-
case "ready": {
|
|
2111
|
-
const info = {
|
|
2112
|
-
connectionId: parsed.data.connectionId,
|
|
2113
|
-
sessionId: parsed.data.sessionId,
|
|
2114
|
-
restored: parsed.data.restored,
|
|
2115
|
-
detachTimeoutMs: parsed.data.detachTimeoutMs,
|
|
2116
|
-
...parsed.data.attachCount === void 0 ? {} : { attachCount: parsed.data.attachCount },
|
|
2117
|
-
...parsed.data.cursors === void 0 ? {} : { cursors: parsed.data.cursors }
|
|
2118
|
-
};
|
|
2119
|
-
this.readyInfo = info;
|
|
2120
|
-
connectPhase.succeed();
|
|
2121
|
-
this.handlers.onReady?.(info);
|
|
2122
|
-
return;
|
|
2123
|
-
}
|
|
2124
|
-
case "output":
|
|
2125
|
-
try {
|
|
2126
|
-
const bytes = decodeBase64(parsed.data.data);
|
|
2127
|
-
this.handlers.onOutput?.(parsed.data.seq, bytes);
|
|
2128
|
-
if (this.handlers.onOutput === void 0) this.handlers.onData?.(bytes);
|
|
2129
|
-
} catch (error) {
|
|
2130
|
-
const protocolError = error instanceof TerminalStreamError ? error : new TerminalStreamError("Terminal output frame is not valid base64", "INVALID_FRAME");
|
|
2131
|
-
if (!connectPhase.settled()) connectPhase.fail(protocolError);
|
|
2132
|
-
else this.handlers.onError?.(protocolError);
|
|
2133
|
-
if (this.ws.readyState === WebSocket.OPEN) this.ws.close(1e3, "invalid terminal output");
|
|
2134
|
-
}
|
|
2135
|
-
return;
|
|
2136
|
-
case "exit":
|
|
2137
|
-
this.handlers.onExit?.({
|
|
2138
|
-
exitCode: parsed.data.exitCode,
|
|
2139
|
-
exitSignal: parsed.data.exitSignal
|
|
2140
|
-
});
|
|
2141
|
-
return;
|
|
2142
|
-
case "renewed": return;
|
|
2143
|
-
case "error": {
|
|
2144
|
-
const error = new TerminalStreamError(parsed.data.message, parsed.data.code);
|
|
2145
|
-
if (!connectPhase.settled()) {
|
|
2146
|
-
connectPhase.fail(error);
|
|
2147
|
-
return;
|
|
2148
|
-
}
|
|
2149
|
-
this.handlers.onError?.(error);
|
|
2150
|
-
return;
|
|
2151
|
-
}
|
|
2152
|
-
}
|
|
2153
|
-
}
|
|
2154
|
-
/** PTY connection id this stream is attached to. */
|
|
2155
|
-
get connectionId() {
|
|
2156
|
-
return this.options.connectionId;
|
|
2157
|
-
}
|
|
2158
|
-
/** The server's `ready` acknowledgement. Set once `connect()` resolves. */
|
|
2159
|
-
get ready() {
|
|
2160
|
-
if (!this.readyInfo) throw new TerminalStreamError("Terminal stream is not ready yet", "NOT_READY");
|
|
2161
|
-
return this.readyInfo;
|
|
2162
|
-
}
|
|
2163
|
-
/** True while the socket is open. */
|
|
2164
|
-
get isOpen() {
|
|
2165
|
-
return !this.closed && this.ws.readyState === WebSocket.OPEN;
|
|
2166
|
-
}
|
|
2167
|
-
/**
|
|
2168
|
-
* Send input keystrokes to the PTY. `Uint8Array` input is decoded as
|
|
2169
|
-
* UTF-8 (the wire protocol carries input as JSON text). Input larger than
|
|
2170
|
-
* the server's 1 MiB frame cap is split across multiple `input` frames in
|
|
2171
|
-
* order on the same socket, so delivery order is preserved.
|
|
2172
|
-
*/
|
|
2173
|
-
write(data) {
|
|
2174
|
-
this.assertOpen("write");
|
|
2175
|
-
assertInteractiveControlActive(this.interactiveIdentity);
|
|
2176
|
-
const text = typeof data === "string" ? data : this.textDecoder.decode(data);
|
|
2177
|
-
for (const chunk of chunkInput(text)) this.ws.send(JSON.stringify({
|
|
2178
|
-
type: "input",
|
|
2179
|
-
data: chunk
|
|
2180
|
-
}));
|
|
2181
|
-
}
|
|
2182
|
-
/** Resize the PTY. */
|
|
2183
|
-
resize(cols, rows) {
|
|
2184
|
-
assertDimension("cols", cols);
|
|
2185
|
-
assertDimension("rows", rows);
|
|
2186
|
-
this.assertOpen("resize");
|
|
2187
|
-
assertInteractiveControlActive(this.interactiveIdentity);
|
|
2188
|
-
this.ws.send(JSON.stringify({
|
|
2189
|
-
type: "resize",
|
|
2190
|
-
cols,
|
|
2191
|
-
rows
|
|
2192
|
-
}));
|
|
2193
|
-
}
|
|
2194
|
-
/**
|
|
2195
|
-
* Detach cleanly: close the socket and resolve once the close completes.
|
|
2196
|
-
* The PTY survives server-side for `ready.detachTimeoutMs` (5 minutes
|
|
2197
|
-
* today) — reattach within that window via {@link reconnect} (or a fresh
|
|
2198
|
-
* `connect()` with the same connectionId) to replay history and continue.
|
|
2199
|
-
*/
|
|
2200
|
-
close() {
|
|
2201
|
-
if (this.closed) return Promise.resolve();
|
|
2202
|
-
return new Promise((resolve) => {
|
|
2203
|
-
this.closeWaiters.push(resolve);
|
|
2204
|
-
this.ws.close(1e3, "client detach");
|
|
2205
|
-
});
|
|
2206
|
-
}
|
|
2207
|
-
/**
|
|
2208
|
-
* Re-dial the same endpoint with the same connectionId on a fresh socket
|
|
2209
|
-
* — the server reattaches the PTY and replays its buffered history. When
|
|
2210
|
-
* the stream was constructed with a token PROVIDER, it is re-invoked for
|
|
2211
|
-
* the new dial (scoped terminal tokens expire within minutes, so the
|
|
2212
|
-
* original credential may be dead by reconnect time); with a plain string
|
|
2213
|
-
* token, pass a fresh `token` override yourself when it may have expired.
|
|
2214
|
-
* `handlers` rebinds callbacks for the new stream.
|
|
2215
|
-
*/
|
|
2216
|
-
reconnect(overrides) {
|
|
2217
|
-
const existing = this.reconnectInFlight;
|
|
2218
|
-
if (existing !== void 0) return awaitTerminalOperation(existing, overrides?.signal);
|
|
2219
|
-
const operation = this.reconnectOnce(overrides);
|
|
2220
|
-
let tracked;
|
|
2221
|
-
tracked = operation.finally(() => {
|
|
2222
|
-
if (this.reconnectInFlight === tracked) this.reconnectInFlight = void 0;
|
|
2223
|
-
});
|
|
2224
|
-
this.reconnectInFlight = tracked;
|
|
2225
|
-
return awaitTerminalOperation(tracked, overrides?.signal);
|
|
2226
|
-
}
|
|
2227
|
-
async reconnectOnce(overrides) {
|
|
2228
|
-
const binding = await this.options.reconnectAuthority?.acquire(overrides?.signal);
|
|
2229
|
-
try {
|
|
2230
|
-
return await TerminalStream.connect({
|
|
2231
|
-
...this.options,
|
|
2232
|
-
...binding === void 0 ? {} : {
|
|
2233
|
-
incarnationId: binding.incarnationId,
|
|
2234
|
-
control: binding.control
|
|
2235
|
-
},
|
|
2236
|
-
token: overrides?.token ?? this.options.token,
|
|
2237
|
-
handlers: this.handlersForReconnect(overrides?.handlers),
|
|
2238
|
-
cols: overrides?.cols ?? this.options.cols,
|
|
2239
|
-
rows: overrides?.rows ?? this.options.rows,
|
|
2240
|
-
signal: overrides?.signal
|
|
2241
|
-
});
|
|
2242
|
-
} catch (error) {
|
|
2243
|
-
try {
|
|
2244
|
-
await binding?.onFailure?.();
|
|
2245
|
-
} catch {}
|
|
2246
|
-
throw error;
|
|
2247
|
-
}
|
|
2248
|
-
}
|
|
2249
|
-
handlersForReconnect(overrides) {
|
|
2250
|
-
const lifecycleHandlers = this.options.handlers;
|
|
2251
|
-
if (overrides === void 0 || lifecycleHandlers?.onClose === void 0) return overrides ?? lifecycleHandlers;
|
|
2252
|
-
return {
|
|
2253
|
-
...overrides,
|
|
2254
|
-
onClose: (code, reason) => {
|
|
2255
|
-
lifecycleHandlers.onClose?.(code, reason);
|
|
2256
|
-
overrides.onClose?.(code, reason);
|
|
2257
|
-
}
|
|
2258
|
-
};
|
|
2259
|
-
}
|
|
2260
|
-
assertOpen(action) {
|
|
2261
|
-
if (!this.isOpen) throw new TerminalStreamError(`Cannot ${action}: terminal stream is not open`, "NOT_OPEN");
|
|
2262
|
-
}
|
|
2263
|
-
};
|
|
2264
|
-
//#endregion
|
|
2265
|
-
//#region src/interactive-controller.ts
|
|
2266
|
-
/**
|
|
2267
|
-
* Attach-capable controller for one exact interactive process.
|
|
2268
|
-
*
|
|
2269
|
-
* Control ownership lives in the dependency-light base controller. This layer
|
|
2270
|
-
* adds only the terminal attach operation after that ownership is resolved.
|
|
2271
|
-
*/
|
|
2272
|
-
var InteractiveSessionController = class extends InteractiveSessionControlController {
|
|
2273
|
-
attachInFlight;
|
|
2274
|
-
constructor(attachTransport, options) {
|
|
2275
|
-
super(attachTransport, options);
|
|
2276
|
-
this.attachTransport = attachTransport;
|
|
2277
|
-
}
|
|
2278
|
-
async attach(request, requestOptions) {
|
|
2279
|
-
requestOptions?.signal?.throwIfAborted();
|
|
2280
|
-
if (this.attachInFlight !== void 0) return await awaitWithAbort(this.attachInFlight, requestOptions?.signal);
|
|
2281
|
-
const operation = (async () => {
|
|
2282
|
-
const identity = await this.resolve(requestOptions);
|
|
2283
|
-
return this.attachWithIdentity(identity, request, requestOptions);
|
|
2284
|
-
})();
|
|
2285
|
-
let tracked;
|
|
2286
|
-
tracked = operation.finally(() => {
|
|
2287
|
-
if (this.attachInFlight === tracked) this.attachInFlight = void 0;
|
|
2288
|
-
});
|
|
2289
|
-
this.attachInFlight = tracked;
|
|
2290
|
-
return await tracked;
|
|
2291
|
-
}
|
|
2292
|
-
/**
|
|
2293
|
-
* Open a stream for a claim returned by this controller's `resolve()`.
|
|
2294
|
-
* The controller releases that claim when the stream cannot be opened.
|
|
2295
|
-
*/
|
|
2296
|
-
async attachWithIdentity(identity, request, requestOptions) {
|
|
2297
|
-
const exactRef = AgentInteractiveSessionRefSchema.parse(identity.ref);
|
|
2298
|
-
assertInteractiveSessionRef(exactRef, this.options);
|
|
2299
|
-
if (!agentInteractiveSessionControlClaimMatchesRef(exactRef, identity.control)) throw new Error("Interactive control claim is not bound to the session");
|
|
2300
|
-
let activeIdentity = {
|
|
2301
|
-
ref: exactRef,
|
|
2302
|
-
control: identity.control
|
|
2303
|
-
};
|
|
2304
|
-
const releasePromises = /* @__PURE__ */ new WeakMap();
|
|
2305
|
-
const releaseClaim = (target) => {
|
|
2306
|
-
const existing = releasePromises.get(target);
|
|
2307
|
-
if (existing !== void 0) return existing;
|
|
2308
|
-
const release = this.safelyReleaseClaim(target);
|
|
2309
|
-
releasePromises.set(target, release);
|
|
2310
|
-
return release;
|
|
2311
|
-
};
|
|
2312
|
-
let reconnectInFlight;
|
|
2313
|
-
const reconnectAuthority = { acquire: async (signal) => {
|
|
2314
|
-
if (!releasePromises.has(activeIdentity)) throw new Error("Interactive terminal must be closed before reconnecting");
|
|
2315
|
-
if (reconnectInFlight !== void 0) return await awaitWithAbort(reconnectInFlight, signal);
|
|
2316
|
-
const operation = (async () => {
|
|
2317
|
-
const next = await this.resolve({ signal });
|
|
2318
|
-
const nextRef = AgentInteractiveSessionRefSchema.parse(next.ref);
|
|
2319
|
-
assertInteractiveSessionRef(nextRef, this.options);
|
|
2320
|
-
const nextIdentity = {
|
|
2321
|
-
ref: nextRef,
|
|
2322
|
-
control: next.control
|
|
2323
|
-
};
|
|
2324
|
-
activeIdentity = nextIdentity;
|
|
2325
|
-
return {
|
|
2326
|
-
incarnationId: nextRef.incarnationId,
|
|
2327
|
-
control: next.control,
|
|
2328
|
-
onFailure: () => releaseClaim(nextIdentity)
|
|
2329
|
-
};
|
|
2330
|
-
})();
|
|
2331
|
-
let tracked;
|
|
2332
|
-
tracked = operation.finally(() => {
|
|
2333
|
-
if (reconnectInFlight === tracked) reconnectInFlight = void 0;
|
|
2334
|
-
});
|
|
2335
|
-
reconnectInFlight = tracked;
|
|
2336
|
-
return await tracked;
|
|
2337
|
-
} };
|
|
2338
|
-
try {
|
|
2339
|
-
requestOptions?.signal?.throwIfAborted();
|
|
2340
|
-
const callerHandlers = request.handlers;
|
|
2341
|
-
const exactRequest = {
|
|
2342
|
-
...request,
|
|
2343
|
-
control: identity.control,
|
|
2344
|
-
handlers: {
|
|
2345
|
-
...callerHandlers,
|
|
2346
|
-
onClose: (code, reason) => {
|
|
2347
|
-
releaseClaim(activeIdentity);
|
|
2348
|
-
callerHandlers?.onClose?.(code, reason);
|
|
2349
|
-
}
|
|
2350
|
-
}
|
|
2351
|
-
};
|
|
2352
|
-
const stream = await this.attachTransport.attach(this.options.sessionId, exactRef, exactRequest, requestOptions, reconnectAuthority);
|
|
2353
|
-
if (requestOptions?.signal?.aborted) {
|
|
2354
|
-
await stream.close();
|
|
2355
|
-
requestOptions.signal.throwIfAborted();
|
|
2356
|
-
}
|
|
2357
|
-
return stream;
|
|
2358
|
-
} catch (error) {
|
|
2359
|
-
await releaseClaim(activeIdentity);
|
|
2360
|
-
throw error;
|
|
2361
|
-
}
|
|
2362
|
-
}
|
|
2363
|
-
};
|
|
2364
|
-
function browserTransport(options) {
|
|
2365
|
-
return {
|
|
2366
|
-
...createBrowserInteractiveSessionControlTransport(options),
|
|
2367
|
-
async attach(sessionId, ref, request, requestOptions, reconnectAuthority) {
|
|
2368
|
-
requestOptions?.signal?.throwIfAborted();
|
|
2369
|
-
if (options.terminalTokenProvider === void 0) throw new Error("Browser interactive terminal attach requires terminalTokenProvider");
|
|
2370
|
-
const exactRef = AgentInteractiveSessionRefSchema.parse(ref);
|
|
2371
|
-
const { handlers, ...wireRequest } = request;
|
|
2372
|
-
const { control, ...terminalRequest } = AgentInteractiveSessionAttachSchema.parse(wireRequest);
|
|
2373
|
-
const terminalOptions = {
|
|
2374
|
-
url: browserInteractiveTerminalEndpoint(options.sessionApiUrl, sessionId),
|
|
2375
|
-
token: options.terminalTokenProvider,
|
|
2376
|
-
connectionId: sessionId,
|
|
2377
|
-
...terminalRequest,
|
|
2378
|
-
incarnationId: exactRef.incarnationId,
|
|
2379
|
-
control,
|
|
2380
|
-
authFormat: "edge",
|
|
2381
|
-
signal: requestOptions?.signal,
|
|
2382
|
-
...reconnectAuthority === void 0 ? {} : { reconnectAuthority },
|
|
2383
|
-
...handlers === void 0 ? {} : { handlers }
|
|
2384
|
-
};
|
|
2385
|
-
requestOptions?.signal?.throwIfAborted();
|
|
2386
|
-
const stream = await TerminalStream.connect(terminalOptions);
|
|
2387
|
-
if (requestOptions?.signal?.aborted) {
|
|
2388
|
-
await stream.close();
|
|
2389
|
-
requestOptions.signal.throwIfAborted();
|
|
2390
|
-
}
|
|
2391
|
-
return stream;
|
|
2392
|
-
}
|
|
2393
|
-
};
|
|
2394
|
-
}
|
|
2395
|
-
/** Concrete controller for browser deep links and terminal attachment. */
|
|
2396
|
-
var BrowserInteractiveSessionController = class extends InteractiveSessionController {
|
|
2397
|
-
constructor(options) {
|
|
2398
|
-
super(browserTransport(options), options);
|
|
2399
|
-
}
|
|
2400
|
-
};
|
|
2401
1576
|
//#endregion
|
|
2402
1577
|
//#region src/interactive-terminal-session.ts
|
|
2403
1578
|
const MAX_RETAINED_TERMINAL_FRAMES = 4096;
|
|
@@ -3720,6 +2895,21 @@ function isProfileNotCachedError(err) {
|
|
|
3720
2895
|
function serializeProfileSnapshot(profile) {
|
|
3721
2896
|
return JSON.stringify(profile);
|
|
3722
2897
|
}
|
|
2898
|
+
/** Preserve the server's refusal without inferring an HTTP status from its message. */
|
|
2899
|
+
function fromStreamErrorEvent(data) {
|
|
2900
|
+
const message = typeof data?.message === "string" ? data.message : "sandbox rejected the prompt before admission";
|
|
2901
|
+
const status = typeof data?.status === "number" && Number.isInteger(data.status) && data.status >= 400 && data.status <= 599 ? data.status : void 0;
|
|
2902
|
+
const code = typeof data?.code === "string" && data.code.length > 0 ? data.code : void 0;
|
|
2903
|
+
if (status === void 0 && code === void 0) return new ServerError(message);
|
|
2904
|
+
const origin = data?.origin;
|
|
2905
|
+
const error = new SandboxError(message, code ?? "SERVER_ERROR", status, {
|
|
2906
|
+
...origin === "sidecar" || origin === "sandbox-api" || origin === "control-plane" || origin === "runtime" || origin === "unknown" ? { origin } : {},
|
|
2907
|
+
...typeof data?.endpoint === "string" ? { endpoint: data.endpoint } : {},
|
|
2908
|
+
...typeof data?.retryAfterMs === "number" && Number.isFinite(data.retryAfterMs) && data.retryAfterMs >= 0 ? { retryAfterMs: data.retryAfterMs } : {}
|
|
2909
|
+
});
|
|
2910
|
+
if (typeof data?.name === "string" && data.name.length > 0) error.name = data.name;
|
|
2911
|
+
return error;
|
|
2912
|
+
}
|
|
3723
2913
|
/**
|
|
3724
2914
|
* Convert a thrown error into an in-band `error` SandboxEvent so a streaming
|
|
3725
2915
|
* generator can surface a failure as an event followed by a terminal `done`
|
|
@@ -4962,7 +4152,10 @@ var SandboxInstance = class SandboxInstance {
|
|
|
4962
4152
|
response = await this.runtimeFetch(requestEndpoint, request);
|
|
4963
4153
|
for (let attempt = 1; !explicitReplay && response.status === 503 && attempt <= MAX_CREDENTIAL_REFUSAL_RETRIES; attempt += 1) {
|
|
4964
4154
|
const body = await response.clone().text();
|
|
4965
|
-
const refusal = parseErrorResponse(response.status, body,
|
|
4155
|
+
const refusal = parseErrorResponse(response.status, body, {
|
|
4156
|
+
method: request.method,
|
|
4157
|
+
path: `/v1/sandboxes/${encodeURIComponent(this.id)}/runtime${requestEndpoint}`
|
|
4158
|
+
}, response.headers);
|
|
4966
4159
|
if (!isRetryableCredentialRefusal(refusal)) break;
|
|
4967
4160
|
await waitForRetryAfter(refusal.retryAfterMs ?? 1e3, streamSignal);
|
|
4968
4161
|
response = await this.runtimeFetch(requestEndpoint, request);
|
|
@@ -4978,7 +4171,10 @@ var SandboxInstance = class SandboxInstance {
|
|
|
4978
4171
|
}
|
|
4979
4172
|
if (!response.ok) {
|
|
4980
4173
|
const body = await response.text();
|
|
4981
|
-
const responseError = parseErrorResponse(response.status, body,
|
|
4174
|
+
const responseError = parseErrorResponse(response.status, body, {
|
|
4175
|
+
method: explicitReplay ? "GET" : "POST",
|
|
4176
|
+
path: `/v1/sandboxes/${encodeURIComponent(this.id)}/runtime${requestEndpoint}`
|
|
4177
|
+
}, response.headers);
|
|
4982
4178
|
if (!isProfileNotCachedError(responseError)) await reconcileRuntimeRefusal(response.status);
|
|
4983
4179
|
if (!explicitReplay) throw responseError;
|
|
4984
4180
|
lastReplayStatus = response.status;
|
|
@@ -7438,15 +6634,23 @@ var SandboxInstance = class SandboxInstance {
|
|
|
7438
6634
|
* Resume a stopped sandbox.
|
|
7439
6635
|
*/
|
|
7440
6636
|
async resume(options = {}) {
|
|
6637
|
+
await this.resumeRuntime("resume", options);
|
|
6638
|
+
}
|
|
6639
|
+
/** Rebuild a stopped sandbox from its durable snapshot under the same ID. */
|
|
6640
|
+
async rebuild(options = {}) {
|
|
6641
|
+
await this.resumeRuntime("rebuild", options);
|
|
6642
|
+
}
|
|
6643
|
+
async resumeRuntime(operation, options) {
|
|
7441
6644
|
if (options.timeoutMs !== void 0 && (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0)) throw new ValidationError("resume timeoutMs must be a positive number");
|
|
7442
6645
|
const timeoutSignal = options.timeoutMs ? AbortSignal.timeout(options.timeoutMs) : void 0;
|
|
7443
6646
|
const signal = timeoutSignal ? options.signal ? combineAbortSignals([options.signal, timeoutSignal]) : timeoutSignal : options.signal;
|
|
7444
6647
|
const response = await withLifecycleConflictRetry(async () => {
|
|
7445
|
-
const
|
|
6648
|
+
const requestOptions = {
|
|
7446
6649
|
method: "POST",
|
|
7447
6650
|
...options.env ? { body: JSON.stringify({ env: options.env }) } : {},
|
|
7448
6651
|
...signal ? { signal } : {}
|
|
7449
|
-
}
|
|
6652
|
+
};
|
|
6653
|
+
const attempt = operation === "resume" ? await this.client.fetch(`/v1/sandboxes/${this.id}/resume`, requestOptions, usableTimeoutMs(options.timeoutMs)) : await this.client.fetch(`/v1/sandboxes/${this.id}/rebuild`, requestOptions, usableTimeoutMs(options.timeoutMs));
|
|
7450
6654
|
if (!attempt.ok) {
|
|
7451
6655
|
const body = await attempt.text();
|
|
7452
6656
|
throw parseErrorResponse(attempt.status, body, void 0, attempt.headers);
|
|
@@ -8067,7 +7271,7 @@ var SandboxInstance = class SandboxInstance {
|
|
|
8067
7271
|
try {
|
|
8068
7272
|
for await (const event of stream) {
|
|
8069
7273
|
const data = event.data;
|
|
8070
|
-
if (event.type === "error") dispatchError =
|
|
7274
|
+
if (event.type === "error") dispatchError = fromStreamErrorEvent(data);
|
|
8071
7275
|
if (event.type === "execution.started") {
|
|
8072
7276
|
const id = data?.sessionId;
|
|
8073
7277
|
const executionId = data?.executionId;
|
|
@@ -8081,7 +7285,7 @@ var SandboxInstance = class SandboxInstance {
|
|
|
8081
7285
|
} finally {
|
|
8082
7286
|
ctrl.abort();
|
|
8083
7287
|
}
|
|
8084
|
-
if (!admissionObserved || !resolvedSessionId || !resolvedExecutionId) throw new ServerError(
|
|
7288
|
+
if (!admissionObserved || !resolvedSessionId || !resolvedExecutionId) throw dispatchError ?? new ServerError("dispatchPrompt did not receive an execution admission from the sandbox");
|
|
8085
7289
|
if (!resolvedRunControlRef) throw new ServerError("Sandbox admission did not return the exact run reference", 502, {
|
|
8086
7290
|
origin: "runtime",
|
|
8087
7291
|
endpoint: "/agents/run/stream"
|
|
@@ -8291,6 +7495,7 @@ var SandboxInstance = class SandboxInstance {
|
|
|
8291
7495
|
}] : [...message],
|
|
8292
7496
|
turnId: opts.turnId,
|
|
8293
7497
|
...opts.managedQuoteVersion !== void 0 ? { managedQuoteVersion: opts.managedQuoteVersion } : {},
|
|
7498
|
+
...opts.managedModelCredential === true ? { managedModelCredential: true } : {},
|
|
8294
7499
|
...backend !== void 0 ? { backend } : {},
|
|
8295
7500
|
...opts.runControlRef !== void 0 ? { runControlRef: opts.runControlRef } : {}
|
|
8296
7501
|
};
|
|
@@ -8419,12 +7624,14 @@ var SandboxInstance = class SandboxInstance {
|
|
|
8419
7624
|
await this.ensureRunning();
|
|
8420
7625
|
await this.refresh();
|
|
8421
7626
|
const response = await this.runtimeFetch(`/agents/sessions/${encodeURIComponent(id)}/raw-evidence`);
|
|
8422
|
-
if (!response.ok
|
|
7627
|
+
if (!response.ok) throw parseErrorResponse(response.status, await response.text(), void 0, response.headers);
|
|
8423
7628
|
const raw = await response.json();
|
|
8424
7629
|
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new ServerError("Malformed raw evidence response");
|
|
8425
7630
|
const record = raw;
|
|
7631
|
+
const validBackendType = (value) => typeof value === "string" && value !== "unknown" && /^[a-z][a-z0-9_-]{0,127}$/.test(value);
|
|
7632
|
+
const validNativeSessionId = (value) => typeof value === "string" && value.trim().length > 0;
|
|
8426
7633
|
if (record.status === "unavailable") {
|
|
8427
|
-
if (record.sessionId !== id || typeof record.backendType !== "string" || typeof record.reason !== "string" || record.reason.length === 0) throw new ServerError("Malformed raw evidence unavailable response");
|
|
7634
|
+
if (record.sessionId !== id || typeof record.backendType !== "string" || (record.reason === "session_not_found" ? record.backendType !== "unknown" : record.reason === "unregistered_backend" ? record.backendType.trim().length === 0 : !validBackendType(record.backendType)) || typeof record.reason !== "string" || record.reason.length === 0) throw new ServerError("Malformed raw evidence unavailable response");
|
|
8428
7635
|
return record;
|
|
8429
7636
|
}
|
|
8430
7637
|
const completeness = record.completeness;
|
|
@@ -8432,23 +7639,39 @@ var SandboxInstance = class SandboxInstance {
|
|
|
8432
7639
|
const partial = record.status === "partial";
|
|
8433
7640
|
const missingReasons = record.missingReasons;
|
|
8434
7641
|
const inventory = record.inventory;
|
|
8435
|
-
if (!captured && !partial || record.sessionId !== id ||
|
|
8436
|
-
|
|
8437
|
-
for (const
|
|
8438
|
-
if (typeof
|
|
8439
|
-
|
|
7642
|
+
if (!captured && !partial || record.sessionId !== id || !validBackendType(record.backendType) || record.nativeSessionId !== null && !validNativeSessionId(record.nativeSessionId) || record.proofStatus !== "verified" && record.proofStatus !== "unverified" || record.proofStatus === "verified" && (typeof record.containerId !== "string" || !/^[a-f0-9]{64}$/.test(record.containerId) || typeof record.sidecarBundleChecksum !== "string" || !/^sha256:[a-f0-9]{64}$/.test(record.sidecarBundleChecksum)) || typeof record.sidecarImageDigest !== "string" || !/^sha256:[a-f0-9]{64}$/.test(record.sidecarImageDigest) || typeof record.sidecarBundleRevision !== "string" || !/^[a-f0-9]{40}$/.test(record.sidecarBundleRevision) || !Array.isArray(record.nativeRoots) || !Array.isArray(record.files) || !Array.isArray(record.excluded) || !Array.isArray(record.skipped) || !Array.isArray(record.processIo) || !Array.isArray(record.processTerminals) || !Array.isArray(record.events) || !Array.isArray(record.attempts) || !Array.isArray(record.evidenceSources) || !Array.isArray(record.processSources) || !inventory || typeof inventory !== "object" || Array.isArray(inventory) || !Number.isSafeInteger(inventory.skippedEntries) || inventory.skippedEntries !== record.skipped.length || !completeness || typeof completeness.nativeStore !== "boolean" || typeof completeness.processIo !== "boolean" || typeof completeness.events !== "boolean" || !Array.isArray(missingReasons) || missingReasons.some((reason) => typeof reason !== "string" || reason.length === 0) || captured && (completeness.nativeStore !== true || completeness.processIo !== true || completeness.events !== true || record.coverageComplete !== true || missingReasons.length !== 0) || partial && (record.coverageComplete !== false || missingReasons.length === 0)) throw new ServerError("Malformed raw evidence response");
|
|
7643
|
+
const nativeIds = /* @__PURE__ */ new Set();
|
|
7644
|
+
for (const attempt of record.attempts) {
|
|
7645
|
+
if (!attempt || typeof attempt !== "object" || !Array.isArray(attempt.nativeSessionIds) || attempt.nativeSessionIds.some((nativeId) => !validNativeSessionId(nativeId))) throw new ServerError("Malformed raw evidence native session ID");
|
|
7646
|
+
for (const nativeId of attempt.nativeSessionIds) nativeIds.add(nativeId);
|
|
7647
|
+
}
|
|
7648
|
+
const aggregateNativeId = nativeIds.size === 1 && record.attempts.every((attempt) => attempt.nativeSessionIds.length === 1) ? [...nativeIds][0] : null;
|
|
7649
|
+
if (record.nativeSessionId !== aggregateNativeId) throw new ServerError("Raw evidence native session ID mismatch");
|
|
7650
|
+
const verifyBytes = async (entry, label) => {
|
|
7651
|
+
if (typeof entry.contentBase64 !== "string" || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(entry.contentBase64) || !Number.isSafeInteger(entry.sizeBytes) || entry.sizeBytes < 0 || typeof entry.sha256 !== "string" || !/^sha256:[a-f0-9]{64}$/.test(entry.sha256)) throw new ServerError(`Malformed raw evidence ${label}`);
|
|
8440
7652
|
let binary;
|
|
8441
7653
|
try {
|
|
8442
|
-
binary = atob(
|
|
7654
|
+
binary = atob(entry.contentBase64);
|
|
8443
7655
|
} catch {
|
|
8444
|
-
throw new ServerError(
|
|
7656
|
+
throw new ServerError(`Malformed raw evidence ${label} base64`);
|
|
8445
7657
|
}
|
|
7658
|
+
if (btoa(binary) !== entry.contentBase64) throw new ServerError(`Malformed raw evidence ${label} base64`);
|
|
8446
7659
|
const bytes = new Uint8Array(binary.length);
|
|
8447
7660
|
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
|
|
8448
|
-
if (bytes.length !==
|
|
7661
|
+
if (bytes.length !== entry.sizeBytes) throw new ServerError(`Raw evidence ${label} size mismatch`);
|
|
8449
7662
|
const subtle = globalThis.crypto?.subtle;
|
|
8450
7663
|
const digestBytes = subtle ? new Uint8Array(await subtle.digest("SHA-256", bytes)) : Uint8Array.from((await import("node:crypto")).createHash("sha256").update(bytes).digest());
|
|
8451
|
-
if ("sha256:" + Array.from(digestBytes).map((byte) => byte.toString(16).padStart(2, "0")).join("") !==
|
|
7664
|
+
if ("sha256:" + Array.from(digestBytes).map((byte) => byte.toString(16).padStart(2, "0")).join("") !== entry.sha256) throw new ServerError(`Raw evidence ${label} SHA-256 mismatch`);
|
|
7665
|
+
};
|
|
7666
|
+
for (const file of record.files) {
|
|
7667
|
+
if (!file || typeof file !== "object" || Array.isArray(file) || file.rootScope !== "session-home" && file.rootScope !== "workspace-session" || typeof file.path !== "string" || file.path.length === 0 || file.path.startsWith("/") || file.path.split("/").includes("..") || file.kind !== "file" && file.kind !== "directory" && file.kind !== "symlink") throw new ServerError("Malformed raw evidence native file entry");
|
|
7668
|
+
if (file.kind === "file") await verifyBytes(file, "native file");
|
|
7669
|
+
else if (file.kind === "symlink" && typeof file.linkTarget !== "string" || file.contentBase64 !== void 0 || file.sha256 !== void 0) throw new ServerError("Malformed raw evidence native file entry");
|
|
7670
|
+
}
|
|
7671
|
+
for (const skipped of record.skipped) if (!skipped || typeof skipped !== "object" || skipped.rootScope !== "session-home" && skipped.rootScope !== "workspace-session" || typeof skipped.path !== "string" || skipped.path.length === 0 || skipped.path.startsWith("/") || skipped.path.split("/").includes("..") || typeof skipped.reason !== "string" || skipped.reason.length === 0) throw new ServerError("Malformed raw evidence skipped entry");
|
|
7672
|
+
for (const source of record.processSources) {
|
|
7673
|
+
if (!source || typeof source !== "object" || Array.isArray(source) || typeof source.sourceId !== "string" || source.sourceId.length === 0) throw new ServerError("Malformed raw evidence process source ID");
|
|
7674
|
+
await verifyBytes(source, "process source");
|
|
8452
7675
|
}
|
|
8453
7676
|
const expected = this.info.captureProof;
|
|
8454
7677
|
if (expected && (record.proofStatus !== "verified" || record.containerId !== expected.containerId || record.sidecarImageDigest !== expected.imageId || record.sidecarBundleRevision !== expected.bundleRevision || record.sidecarBundleChecksum !== expected.bundleChecksum)) throw new ServerError("Raw evidence does not match current container capture proof");
|
|
@@ -8849,4 +8072,4 @@ function quoteForShell(value) {
|
|
|
8849
8072
|
return `'${value.replace(/'/g, "'\\''")}'`;
|
|
8850
8073
|
}
|
|
8851
8074
|
//#endregion
|
|
8852
|
-
export {
|
|
8075
|
+
export { normalizeSandboxShape as C, otelTraceIdForTangleTrace as D, exportTraceBundle as E, toOtelJson as O, normalizeConnection as S, buildTraceExportPayload as T, collectAgentFinalMessageText as _, normalizeStartupDiagnostics as a, isToolBearingEvent as b, MAX_EGRESS_DENIALS_LIMIT as c, InteractiveSessionHandle as d, agentInteractiveSessionPromptRequestDigest as f, applySandboxEventText as g, createInteractiveTerminalSession as h, normalizeSandboxCreateReceipt as i, SandboxTaskSession as l, createInteractiveTerminalCapture as m, createSandboxInstanceFromResponse as n, WorkspaceImages as o, InteractiveTerminalFrameLog as p, normalizeCaptureProof as r, GPU_LEASE_PROVIDER_NAMES as s, SandboxInstance as t, SandboxSession as u, collectAgentResponseText as v, rewrapResponse as w, ManagedProcessClient as x, getSandboxEventText as y };
|