@tangle-network/sandbox 0.58.4 → 0.58.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/agent/index.d.ts +4 -4
  2. package/dist/agent/index.js +5 -5
  3. package/dist/agent/preview.d.ts +1 -1
  4. package/dist/agent/preview.js +2 -2
  5. package/dist/{agent-run-outcome-xCHr2-OU.d.ts → agent-run-outcome-1MxGwnx3.d.ts} +1 -1
  6. package/dist/auth/index.d.ts +3 -2
  7. package/dist/auth/index.js +2 -2
  8. package/dist/backend-types-C7b_Gpa0.js +59 -0
  9. package/dist/{browser-interactive-control-controller-1m7jgLeg.d.ts → browser-interactive-control-controller-BzR8sFjo.d.ts} +1 -1
  10. package/dist/{browser-interactive-control-controller-CVGqjPgs.js → browser-interactive-control-controller-DRBQ-jf0.js} +1 -1
  11. package/dist/cli-auth-bundle-CzmAaefZ.js +53 -0
  12. package/dist/cli-auth-bundle-gs7xEnA1.d.ts +33 -0
  13. package/dist/{client-CGy_hRo4.js → client-CyIgS8us.js} +11 -31
  14. package/dist/{client-FSfwsq91.d.ts → client-KFbYYO9V.d.ts} +5 -13
  15. package/dist/collaboration/index.d.ts +1 -1
  16. package/dist/collaboration/index.js +1 -1
  17. package/dist/{collaboration-CSHswAOI.js → collaboration-d8Xcvel7.js} +1 -1
  18. package/dist/core.d.ts +5 -5
  19. package/dist/core.js +4 -4
  20. package/dist/{index-D4u-vv87.d.ts → index-BSCz2Q0v.d.ts} +1 -11
  21. package/dist/{index-D7RBHUmk.d.ts → index-DFXcrGG6.d.ts} +2 -2
  22. package/dist/index.d.ts +11 -11
  23. package/dist/index.js +9 -8
  24. package/dist/intelligence/index.js +1 -1
  25. package/dist/interactive-control.d.ts +1 -1
  26. package/dist/interactive-control.js +1 -1
  27. package/dist/{lines-QsZsBO42.d.ts → lines-DuPzlFrJ.d.ts} +1 -1
  28. package/dist/lines.d.ts +1 -1
  29. package/dist/lines.js +1 -1
  30. package/dist/{local-cli-auth-N1IYywxf.js → local-cli-auth-ChDP5zu4.js} +1 -1
  31. package/dist/{mcp-local-BWsftreI.js → mcp-local-DY1CnWBn.js} +1 -1
  32. package/dist/{preview-DRouZBdQ.d.ts → preview-C9PBEsQH.d.ts} +3 -3
  33. package/dist/{runtime-api-DZy6PuPe.js → runtime-api-BZhd0M3Z.js} +5 -61
  34. package/dist/runtime.d.ts +3 -3
  35. package/dist/runtime.js +3 -3
  36. package/dist/{sandbox-CUTfilZU.js → sandbox-D8HtCO-L.js} +9 -16
  37. package/dist/{sandbox-Cpfr2SpU.d.ts → sandbox-fTLRps4I.d.ts} +4 -4
  38. package/dist/session-gateway/index.d.ts +125 -67
  39. package/dist/session-gateway/index.js +22 -10
  40. package/dist/specs-CnqSWFNT-CHd9ACzP.js +536 -0
  41. package/dist/tangle/index.d.ts +1 -1
  42. package/dist/tangle/index.js +1 -1
  43. package/dist/{tangle-nU1V_G1c.js → tangle-CYGQg5Bf.js} +2 -2
  44. package/dist/{types-C90H0DjS.d.ts → types-B_rwXChV.d.ts} +6 -2
  45. package/package.json +4 -4
  46. package/dist/cli-auth-bundle-0VjPAtKt.js +0 -25
  47. /package/dist/{abort-signal-CgFhjY_v.js → abort-signal-BpYYr4JT.js} +0 -0
  48. /package/dist/{errors-AVpynVrG.d.ts → errors-C6dll8Qf.d.ts} +0 -0
  49. /package/dist/{errors-BkhlSDW-.js → errors-CKl_BSlD.js} +0 -0
  50. /package/dist/{index-C48z7K4r.d.ts → index-BKhRnV0i.d.ts} +0 -0
  51. /package/dist/{line-application-DOg7jrnA.js → line-application-9k30rhb2.js} +0 -0
  52. /package/dist/{preview-operations-BhQ4_CF7.js → preview-operations-CbTiBE-a.js} +0 -0
  53. /package/dist/{terminal-stream-Bf2stNDX.d.ts → terminal-stream-CB2DF-qq.d.ts} +0 -0
@@ -1,2 +1,2 @@
1
- import { n as browserInteractiveControlHolderId, t as BrowserInteractiveSessionControlController } from "./browser-interactive-control-controller-CVGqjPgs.js";
1
+ import { n as browserInteractiveControlHolderId, t as BrowserInteractiveSessionControlController } from "./browser-interactive-control-controller-DRBQ-jf0.js";
2
2
  export { BrowserInteractiveSessionControlController, browserInteractiveControlHolderId };
@@ -1,4 +1,4 @@
1
- import { B as CreateSandboxOptions, d as BackendConfig } from "./types-C90H0DjS.js";
1
+ import { B as CreateSandboxOptions, d as BackendConfig } from "./types-B_rwXChV.js";
2
2
 
3
3
  //#region src/line-application.d.ts
4
4
  /** Bounded callback request bytes after canonicalization, including JSON framing. */
package/dist/lines.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as LinesClient, C as LineRole, D as LineTransport, E as LineThread, M as SandboxLines, N as lineInstanceKey, O as LineVoice, P as profileChannelReference, S as LineRespondView, T as LineSendReceipt, _ as LineNumberInventory, a as LineAttachOptions, b as LineReplyGate, c as LineFromConnectionInput, d as LineLimits, f as LineMember, g as LineMessage, h as LineMemberSpec, i as LineAllowanceSubject, j as LinesHttpClient, k as LineVoiceOptions, l as LineInstanceAttachOptions, m as LineMemberPatch, n as LineAgentRolePolicy, o as LineAttachment, p as LineMemberInstance, r as LineAllowance, s as LineExecutionKey, t as Line, u as LineInstanceCreate, v as LineProvider, w as LineSendInput, x as LineRespondAgent, y as LineReminderPreferences } from "./lines-QsZsBO42.js";
1
+ import { A as LinesClient, C as LineRole, D as LineTransport, E as LineThread, M as SandboxLines, N as lineInstanceKey, O as LineVoice, P as profileChannelReference, S as LineRespondView, T as LineSendReceipt, _ as LineNumberInventory, a as LineAttachOptions, b as LineReplyGate, c as LineFromConnectionInput, d as LineLimits, f as LineMember, g as LineMessage, h as LineMemberSpec, i as LineAllowanceSubject, j as LinesHttpClient, k as LineVoiceOptions, l as LineInstanceAttachOptions, m as LineMemberPatch, n as LineAgentRolePolicy, o as LineAttachment, p as LineMemberInstance, r as LineAllowance, s as LineExecutionKey, t as Line, u as LineInstanceCreate, v as LineProvider, w as LineSendInput, x as LineRespondAgent, y as LineReminderPreferences } from "./lines-DuPzlFrJ.js";
2
2
  export { Line, LineAgentRolePolicy, LineAllowance, LineAllowanceSubject, LineAttachOptions, LineAttachment, LineExecutionKey, LineFromConnectionInput, LineInstanceAttachOptions, LineInstanceCreate, LineLimits, LineMember, LineMemberInstance, LineMemberPatch, LineMemberSpec, LineMessage, LineNumberInventory, LineProvider, LineReminderPreferences, LineReplyGate, LineRespondAgent, LineRespondView, LineRole, LineSendInput, LineSendReceipt, LineThread, LineTransport, LineVoice, LineVoiceOptions, LinesClient, LinesHttpClient, SandboxLines, lineInstanceKey, profileChannelReference };
package/dist/lines.js CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as parseErrorResponse, g as ValidationError } from "./errors-BkhlSDW-.js";
1
+ import { _ as parseErrorResponse, g as ValidationError } from "./errors-CKl_BSlD.js";
2
2
  //#region src/lines.ts
3
3
  /**
4
4
  * Lines: give a sandbox a phone number or messaging address.
@@ -1,4 +1,4 @@
1
- import { t as AUTH_BUNDLE_PATHS } from "./cli-auth-bundle-0VjPAtKt.js";
1
+ import { t as AUTH_BUNDLE_PATHS } from "./cli-auth-bundle-CzmAaefZ.js";
2
2
  import { existsSync, readFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
@@ -1,4 +1,4 @@
1
- import { a as listAgentPreviews, i as getAgentPreview, o as publishAgentPreview, r as ensureAgentPreview, s as removeAgentPreview, t as AgentPreviewError } from "./preview-operations-BhQ4_CF7.js";
1
+ import { a as listAgentPreviews, i as getAgentPreview, o as publishAgentPreview, r as ensureAgentPreview, s as removeAgentPreview, t as AgentPreviewError } from "./preview-operations-CbTiBE-a.js";
2
2
  import { createRequire } from "node:module";
3
3
  //#region \0rolldown/runtime.js
4
4
  var __defProp = Object.defineProperty;
@@ -1,6 +1,6 @@
1
- import { r as SandboxInstance } from "./sandbox-Cpfr2SpU.js";
2
- import { Pn as PreviewLinkInfo, mt as EnsureDevServerOptions } from "./types-C90H0DjS.js";
3
- import { i as Sandbox } from "./client-FSfwsq91.js";
1
+ import { r as SandboxInstance } from "./sandbox-fTLRps4I.js";
2
+ import { Pn as PreviewLinkInfo, mt as EnsureDevServerOptions } from "./types-B_rwXChV.js";
3
+ import { i as Sandbox } from "./client-KFbYYO9V.js";
4
4
 
5
5
  //#region src/agent/preview-operations.d.ts
6
6
  type AgentPreviewOptions = Pick<EnsureDevServerOptions, "sessionId" | "cwd"> & {
@@ -1,63 +1,7 @@
1
- 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-BkhlSDW-.js";
2
- import { n as combineAbortSignals } from "./abort-signal-CgFhjY_v.js";
3
- import { AgentExactRunControlRefSchema, AgentExecutionOutcomeSchema, AgentRuntimeAttachmentsSchema, DurablePlanSchema, InteractionRequestSchema, agentProfileSchema, canonicalCandidateDigest, harnessTypeSchema } from "@tangle-network/agent-interface";
4
- import { z } from "zod";
5
- //#region ../../../packages/runtime-contracts/dist/backend-types.js
6
- /**
7
- * Canonical harnesses this repo ships no provider adapter for.
8
- *
9
- * `gemini` reaches a workspace only as an openclaw/acp sub-agent CLI and through
10
- * `agent-profile-materialize`; there is no `packages/sdk-provider-gemini`, so naming it as a
11
- * backend must keep failing closed rather than dispatching to a runner that cannot start.
12
- */
13
- const NON_BACKEND_HARNESSES = ["gemini"];
14
- const BACKEND_TYPE = {
15
- OPENCODE: "opencode",
16
- CLAUDE_CODE: "claude-code",
17
- KIMI_CODE: "kimi-code",
18
- CODEX: "codex",
19
- AMP: "amp",
20
- FACTORY_DROIDS: "factory-droids",
21
- PI: "pi",
22
- PRIME: "prime",
23
- HERMES: "hermes",
24
- FORGE: "forge",
25
- OPENCLAW: "openclaw",
26
- NANOCLAW: "nanoclaw",
27
- ACP: "acp",
28
- CURSOR: "cursor",
29
- CLI_BASE: "cli-base"
30
- };
31
- const nonBackendHarnesses = new Set(NON_BACKEND_HARNESSES);
32
- /**
33
- * Order mirrors `CLI_AGENT_SPECS` — a backend without a spec has no install/launch definition and
34
- * cannot run, so the registry's order is the contract (`packages/cli-agent-registry`), not an
35
- * arbitrary list.
36
- */
37
- const ALL_BACKEND_TYPES = Object.values(BACKEND_TYPE);
38
- /**
39
- * Bind the enum to `harnessTypeSchema` in both directions at import time, so the canonical set
40
- * stays the authority on membership while the spec registry keeps owning order. A harness added
41
- * upstream, or a backend here that no longer exists upstream, fails loud instead of leaving request
42
- * validation and the harness taxonomy quietly disagreeing.
43
- */
44
- const canonicalBackendHarnesses = harnessTypeSchema.options.filter((harness) => !nonBackendHarnesses.has(harness));
45
- const declaredBackendTypes = new Set(ALL_BACKEND_TYPES);
46
- const canonicalBackendHarnessSet = new Set(canonicalBackendHarnesses);
47
- const undeclaredCanonicalHarnesses = canonicalBackendHarnesses.filter((harness) => !declaredBackendTypes.has(harness));
48
- if (undeclaredCanonicalHarnesses.length > 0) throw new Error(`BACKEND_TYPE is missing canonical harnesses: ${undeclaredCanonicalHarnesses.join(", ")}. Add the named constant plus its CLI_AGENT_SPECS entry, or list it in NON_BACKEND_HARNESSES with a reason.`);
49
- const unrecognizedBackendTypes = ALL_BACKEND_TYPES.filter((backend) => !canonicalBackendHarnessSet.has(backend));
50
- if (unrecognizedBackendTypes.length > 0) throw new Error(`BACKEND_TYPE declares runners the canonical harness enum does not define: ${unrecognizedBackendTypes.join(", ")}. Reconcile them into @tangle-network/agent-interface.`);
51
- const backendTypeSchema = z.enum(ALL_BACKEND_TYPES);
52
- const BACKEND_TYPE_SET = new Set(ALL_BACKEND_TYPES);
53
- function isBackendType(value) {
54
- return BACKEND_TYPE_SET.has(value);
55
- }
56
- function parseBackendType(value) {
57
- if (!isBackendType(value)) throw new Error(`Unknown backend type "${value}". Expected one of: ${ALL_BACKEND_TYPES.join(", ")}`);
58
- return value;
59
- }
60
- //#endregion
1
+ import { r as backendTypeSchema } from "./backend-types-C7b_Gpa0.js";
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 { n as combineAbortSignals } from "./abort-signal-BpYYr4JT.js";
4
+ import { AgentExactRunControlRefSchema, AgentExecutionOutcomeSchema, AgentRuntimeAttachmentsSchema, DurablePlanSchema, InteractionRequestSchema, agentProfileSchema, canonicalCandidateDigest } from "@tangle-network/agent-interface";
61
5
  //#region src/agent-run-outcome-inspection.ts
62
6
  const HUB_APPROVAL_REQUIRED = "HUB_APPROVAL_REQUIRED";
63
7
  const MAX_SERIALIZED_TOOL_VALUE_BYTES = 4 * 1024 * 1024;
@@ -1699,4 +1643,4 @@ function sessionMessageRequestBody(request) {
1699
1643
  };
1700
1644
  }
1701
1645
  //#endregion
1702
- export { parseBackendType as A, normalizeRuntimeBackendConfig as C, ALL_BACKEND_TYPES as D, deriveAgentRunOutcome as E, BACKEND_TYPE as O, mergeRuntimeBackendConfig as S, deriveAgentResultOutcome as T, encodePromptForWire as _, waitForRetryAfter as a, applyRequestedModel as b, mintTraceId as c, sessionHeaders as d, uploadChunked as f, FILE_DECODED_WRITE_MAX_BYTES as g, SANDBOX_PROXY_REQUEST_MAX_BYTES as h, sessionMessageRequestBody as i, backendTypeSchema as k, resolveTraceId as l, validateAcceptedDispatchRunRef as m, isRetryableCredentialRefusal as n, TRACE_ID_HEADER as o, resolveDispatchRunIdentity as p, normalizeSessionInfo as r, isTraceId as s, SandboxRuntimeApi as t, appendSessionIdQuery as u, encodeTextForWire as v, createAgentRunOutcomeTracker as w, assertCurrentBackendType as x, parseSSEStream as y };
1646
+ export { normalizeRuntimeBackendConfig as C, deriveAgentRunOutcome as E, mergeRuntimeBackendConfig as S, deriveAgentResultOutcome as T, encodePromptForWire as _, waitForRetryAfter as a, applyRequestedModel as b, mintTraceId as c, sessionHeaders as d, uploadChunked as f, FILE_DECODED_WRITE_MAX_BYTES as g, SANDBOX_PROXY_REQUEST_MAX_BYTES as h, sessionMessageRequestBody as i, resolveTraceId as l, validateAcceptedDispatchRunRef as m, isRetryableCredentialRefusal as n, TRACE_ID_HEADER as o, resolveDispatchRunIdentity as p, normalizeSessionInfo as r, isTraceId as s, SandboxRuntimeApi as t, appendSessionIdQuery as u, encodeTextForWire as v, createAgentRunOutcomeTracker as w, assertCurrentBackendType as x, parseSSEStream as y };
package/dist/runtime.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { A as CommitTaskSessionOptions, At as FileUsageResult, Bi as SessionExecutionInfo, Ci as SandboxTerminalManager, Dt as FileTreeOptions, Er as SandboxEvent, Fi as SendSessionMessageOptions, H as CreateTaskSessionOptions, Ii as SendSessionMessageRequest, Ji as SessionMessageAdmission, Li as SentSessionMessage, Ot as FileTreeResult, Si as SandboxTerminalInfo, Sn as ListMessagesOptions, T as ChunkedUploadResult, V as CreateSessionOptions, Vi as SessionExecutionStatus, Wi as SessionInfo, bt as FileReadBatchOptions, fa as TaskSessionInfo, hi as SandboxRuntimeHealth, jt as FileWriteResult, ka as WriteFileOptions, kt as FileUsageOptions, la as TaskSessionChanges, li as SandboxPortBinding, or as RenameOptions, qi as SessionMessage, ua as TaskSessionCommitResult, w as ChunkedUploadOptions, wa as UploadProgress, wi as SandboxTerminalRequestOptions, wt as FileRenameResult, xi as SandboxTerminalCreateOptions, xt as FileReadBatchResult, zi as SessionEventStreamOptions } from "./types-C90H0DjS.js";
2
- import { _ as TimeoutError, a as FileWriteConflictError, c as NotFoundError, f as SandboxError, g as StateError, h as ServerError, l as PartialFailureError, m as SandboxFailureDetail, n as CapabilityError, p as SandboxErrorJson, s as NetworkError, t as AuthError, u as QuotaError, v as ValidationError } from "./errors-AVpynVrG.js";
3
- import { a as deriveAgentRunOutcome, i as deriveAgentResultOutcome, n as AgentRunOutcomeTracker, r as createAgentRunOutcomeTracker, t as AgentRunOutcome } from "./agent-run-outcome-xCHr2-OU.js";
1
+ import { A as CommitTaskSessionOptions, At as FileUsageResult, Bi as SessionExecutionInfo, Ci as SandboxTerminalManager, Dt as FileTreeOptions, Er as SandboxEvent, Fi as SendSessionMessageOptions, H as CreateTaskSessionOptions, Ii as SendSessionMessageRequest, Ji as SessionMessageAdmission, Li as SentSessionMessage, Ot as FileTreeResult, Si as SandboxTerminalInfo, Sn as ListMessagesOptions, T as ChunkedUploadResult, V as CreateSessionOptions, Vi as SessionExecutionStatus, Wi as SessionInfo, bt as FileReadBatchOptions, fa as TaskSessionInfo, hi as SandboxRuntimeHealth, jt as FileWriteResult, ka as WriteFileOptions, kt as FileUsageOptions, la as TaskSessionChanges, li as SandboxPortBinding, or as RenameOptions, qi as SessionMessage, ua as TaskSessionCommitResult, w as ChunkedUploadOptions, wa as UploadProgress, wi as SandboxTerminalRequestOptions, wt as FileRenameResult, xi as SandboxTerminalCreateOptions, xt as FileReadBatchResult, zi as SessionEventStreamOptions } from "./types-B_rwXChV.js";
2
+ import { _ as TimeoutError, a as FileWriteConflictError, c as NotFoundError, f as SandboxError, g as StateError, h as ServerError, l as PartialFailureError, m as SandboxFailureDetail, n as CapabilityError, p as SandboxErrorJson, s as NetworkError, t as AuthError, u as QuotaError, v as ValidationError } from "./errors-C6dll8Qf.js";
3
+ import { a as deriveAgentRunOutcome, i as deriveAgentResultOutcome, n as AgentRunOutcomeTracker, r as createAgentRunOutcomeTracker, t as AgentRunOutcome } from "./agent-run-outcome-1MxGwnx3.js";
4
4
 
5
5
  //#region src/lib/chunked-upload.d.ts
6
6
  /** The transport a caller wires this module to — {@link SandboxInstance.runtimeFetch}
package/dist/runtime.js CHANGED
@@ -1,6 +1,6 @@
1
- import { E as deriveAgentRunOutcome, T as deriveAgentResultOutcome, f as uploadChunked, t as SandboxRuntimeApi, w as createAgentRunOutcomeTracker } from "./runtime-api-DZy6PuPe.js";
2
- import { a as FileWriteConflictError, c as NotFoundError, f as SandboxError, g as ValidationError, h as TimeoutError, l as PartialFailureError, m as StateError, n as CapabilityError, p as ServerError, s as NetworkError, t as AuthError, u as QuotaError } from "./errors-BkhlSDW-.js";
3
- import { n as combineAbortSignals } from "./abort-signal-CgFhjY_v.js";
1
+ import { E as deriveAgentRunOutcome, T as deriveAgentResultOutcome, f as uploadChunked, t as SandboxRuntimeApi, w as createAgentRunOutcomeTracker } from "./runtime-api-BZhd0M3Z.js";
2
+ import { a as FileWriteConflictError, c as NotFoundError, f as SandboxError, g as ValidationError, h as TimeoutError, l as PartialFailureError, m as StateError, n as CapabilityError, p as ServerError, s as NetworkError, t as AuthError, u as QuotaError } from "./errors-CKl_BSlD.js";
3
+ import { n as combineAbortSignals } from "./abort-signal-BpYYr4JT.js";
4
4
  //#region src/runtime-client.ts
5
5
  const DEFAULT_RUNTIME_TIMEOUT_MS = 3e4;
6
6
  function requireToken(token) {
@@ -1,9 +1,11 @@
1
- import { C as normalizeRuntimeBackendConfig, O as BACKEND_TYPE, S as mergeRuntimeBackendConfig, T as deriveAgentResultOutcome, _ as encodePromptForWire, a as waitForRetryAfter, b as applyRequestedModel, c as mintTraceId, d as sessionHeaders, f as uploadChunked, h as SANDBOX_PROXY_REQUEST_MAX_BYTES, i as sessionMessageRequestBody, k as backendTypeSchema, l as resolveTraceId, m as validateAcceptedDispatchRunRef, n as isRetryableCredentialRefusal, o as TRACE_ID_HEADER, p as resolveDispatchRunIdentity, r as normalizeSessionInfo, s as isTraceId, t as SandboxRuntimeApi, u as appendSessionIdQuery, w as createAgentRunOutcomeTracker, x as assertCurrentBackendType, y as parseSSEStream } from "./runtime-api-DZy6PuPe.js";
2
- 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-BkhlSDW-.js";
3
- import { c as createInteractiveControlHolderId, d as interactiveSessionControlReleaseResponseSchema, f as interactiveSessionControlValidationResponseSchema, i as createBrowserInteractiveSessionControlTransport, o as InteractiveSessionControlController, p as interactiveSessionStatusResponseSchema, r as browserInteractiveTerminalEndpoint, s as assertInteractiveSessionRef, u as interactiveSessionControlClaimResponseSchema } from "./browser-interactive-control-controller-CVGqjPgs.js";
4
- import { n as combineAbortSignals, t as awaitWithAbort } from "./abort-signal-CgFhjY_v.js";
1
+ import { r as backendTypeSchema } from "./backend-types-C7b_Gpa0.js";
2
+ import { C as normalizeRuntimeBackendConfig, S as mergeRuntimeBackendConfig, T as deriveAgentResultOutcome, _ as encodePromptForWire, a as waitForRetryAfter, b as applyRequestedModel, c as mintTraceId, d as sessionHeaders, f as uploadChunked, h as SANDBOX_PROXY_REQUEST_MAX_BYTES, i as sessionMessageRequestBody, l as resolveTraceId, m as validateAcceptedDispatchRunRef, n as isRetryableCredentialRefusal, o as TRACE_ID_HEADER, p as resolveDispatchRunIdentity, r as normalizeSessionInfo, s as isTraceId, t as SandboxRuntimeApi, u as appendSessionIdQuery, w as createAgentRunOutcomeTracker, x as assertCurrentBackendType, y as parseSSEStream } from "./runtime-api-BZhd0M3Z.js";
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 { c as createInteractiveControlHolderId, d as interactiveSessionControlReleaseResponseSchema, f as interactiveSessionControlValidationResponseSchema, i as createBrowserInteractiveSessionControlTransport, o as InteractiveSessionControlController, p as interactiveSessionStatusResponseSchema, r as browserInteractiveTerminalEndpoint, s as assertInteractiveSessionRef, u as interactiveSessionControlClaimResponseSchema } from "./browser-interactive-control-controller-DRBQ-jf0.js";
5
+ import { n as combineAbortSignals, t as awaitWithAbort } from "./abort-signal-BpYYr4JT.js";
5
6
  import { SandboxLines } from "./lines.js";
6
- 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, agentProfileSchema as agentProfileSchema$1, agentRunCancellationAcknowledgementMatchesRequest, canonicalCandidateDigest, exactAgentInteractiveSessionStart, sha256DigestSchema, terminalSessionUsable } from "@tangle-network/agent-interface";
7
+ import "./specs-CnqSWFNT-CHd9ACzP.js";
8
+ 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";
7
9
  import { z } from "zod";
8
10
  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";
9
11
  import { readTokenCostUsd, readTokenUsage } from "@tangle-network/agent-core";
@@ -353,17 +355,6 @@ var ManagedProcessClient = class {
353
355
  }
354
356
  };
355
357
  //#endregion
356
- //#region ../../../packages/cli-agent-registry/dist/specs-C1v8lTUN.mjs
357
- const { $schema: _jsonSchemaDialect, ...agentProfileJsonSchema } = z.toJSONSchema(agentProfileSchema$1, {
358
- io: "input",
359
- unrepresentable: "any"
360
- });
361
- z.globalRegistry.add(agentProfileSchema$1, {
362
- id: "AgentProfile",
363
- ...agentProfileJsonSchema
364
- });
365
- BACKEND_TYPE.OPENCODE, BACKEND_TYPE.CLAUDE_CODE, BACKEND_TYPE.KIMI_CODE, BACKEND_TYPE.CODEX, BACKEND_TYPE.AMP, BACKEND_TYPE.FACTORY_DROIDS, BACKEND_TYPE.PI, BACKEND_TYPE.PRIME, BACKEND_TYPE.HERMES, BACKEND_TYPE.FORGE, BACKEND_TYPE.OPENCLAW, BACKEND_TYPE.NANOCLAW, BACKEND_TYPE.ACP, BACKEND_TYPE.CURSOR, BACKEND_TYPE.CLI_BASE;
366
- //#endregion
367
358
  //#region src/capabilities.ts
368
359
  function invalidCapabilities(message) {
369
360
  throw new ServerError(`Capability discovery returned ${message}`, 502, {
@@ -402,6 +393,7 @@ function parseSandboxRuntimeCapabilities(raw) {
402
393
  if (typeof record.schema === "number" && Number.isInteger(record.schema) && record.schema > 1) return null;
403
394
  if (record.schema !== 1) invalidCapabilities(`schema version ${JSON.stringify(record.schema)} — this SDK understands 1`);
404
395
  if (typeof record.agentInterface !== "string" || typeof record.sidecarVersion !== "string" || typeof record.image !== "string") invalidCapabilities("a document missing its identity fields");
396
+ if (record.cliAuthReferences !== void 0 && typeof record.cliAuthReferences !== "boolean") invalidCapabilities("a non-boolean 'cliAuthReferences' flag");
405
397
  const nativeVersion = record.nativeSessionCaptureVersion;
406
398
  const nativeHarnesses = record.nativeSessionCaptureHarnesses;
407
399
  if (nativeVersion !== void 0 && (typeof nativeVersion !== "number" || !Number.isSafeInteger(nativeVersion) || nativeVersion < 1)) invalidCapabilities("a malformed 'nativeSessionCaptureVersion'");
@@ -426,6 +418,7 @@ function parseSandboxRuntimeCapabilities(raw) {
426
418
  ]);
427
419
  return {
428
420
  schema: 1,
421
+ ...typeof record.cliAuthReferences === "boolean" ? { cliAuthReferences: record.cliAuthReferences } : {},
429
422
  ...typeof nativeVersion === "number" ? { nativeSessionCaptureVersion: nativeVersion } : {},
430
423
  ...Array.isArray(nativeHarnesses) ? { nativeSessionCaptureHarnesses: nativeHarnesses.map((harness) => backendTypeSchema.parse(harness)) } : {},
431
424
  agentInterface: record.agentInterface,
@@ -1,7 +1,7 @@
1
- import { a as TerminalStreamReconnectAuthority, c as MintScopedTokenOptions, h as TerminalReadyInfo, l as ScopedToken, r as TerminalStreamHandlers, t as TerminalStream } from "./terminal-stream-Bf2stNDX.js";
2
- import { a as InteractiveSessionControlController, c as InteractiveSessionIdentity, d as InteractiveAttachOptions, f as InteractiveControlClaimAcknowledgement, h as InteractiveSessionStatus, m as InteractiveRequestOptions, n as BrowserInteractiveSessionControlControllerOptions, o as InteractiveSessionControlControllerOptions, p as InteractiveControlClaimOptions, s as InteractiveSessionControlTransport } from "./browser-interactive-control-controller-1m7jgLeg.js";
3
- import { M as SandboxLines } from "./lines-QsZsBO42.js";
4
- import { A as CommitTaskSessionOptions, Aa as WriteManyFile, An as NetworkManager, Bi as SessionExecutionInfo, C as BranchOptions, Cr as SandboxDeleteOptions, D as CodeExecutionResult, Da as WaitForRolloutOptions, E as CodeExecutionOptions, Ea as WaitForOptions, Ei as SandboxTraceBundle, Er as SandboxEvent, Fi as SendSessionMessageOptions, Fn as PreviewLinkManager, Gi as SessionInterruptOptions, Gn as PromptInputPart, H as CreateTaskSessionOptions, Ii as SendSessionMessageRequest, Ji as SessionMessageAdmission, Jn as ProvisionEvent, Ki as SessionListOptions, Kn as PromptOptions, Li as SentSessionMessage, M as ConversationTurnOptions, Mi as SearchOptions, N as ConversationTurnResult, Nn as PermissionsManager, O as CodeLanguage, Oa as WorkspaceOperationLookup, Q as DispatchedSession, Qi as SnapshotDeleteAcknowledgement, Sn as ListMessagesOptions, Sr as SandboxDeleteAcknowledgement, Ti as SandboxTerminals, Tt as FileSystem, Ui as SessionForkOptions, V as CreateSessionOptions, Vn as ProcessManager, Wi as SessionInfo, Xi as SessionResultOptions, Xt as ForkIdempotency, Yn as ProvisionResult, Yt as ForkCounts, Z as DispatchPromptOptions, Zr as SandboxFleetTraceBundle, Zt as ForkLookupOptions, _n as IntelligenceReportBudget, _r as SSHCredentials, _t as ExecOptions, aa as StartupDiagnostics, an as GpuLease, at as DurablePlan, bi as SandboxTerminalAttachOptions, bn as IntelligenceReportWindow, cr as ResumeOptions, d as BackendConfig, dr as RolloutOptions, en as GitBranch, fa as TaskSessionInfo, fi as SandboxResourceUsage, ft as EgressManager, ga as TeeAttestationResponse, gi as SandboxShape, gn as IntelligenceReport, gr as SSHCommandDescriptor, hi as SandboxRuntimeHealth, hn as InstalledTool, ht as EventStreamOptions, in as GitStatus, j as CompletedTurnResult, ja as WriteManyOptions, ji as SearchMatch, jt as FileWriteResult, ka as WriteFileOptions, ki as SandboxTraceOptions, la as TaskSessionChanges, li as SandboxPortBinding, lr as Rollout, ma as TeeAttestationOptions, mi as SandboxRuntimeCapabilities, na as SnapshotOptions, ot as DurablePlanDecisionResult, p as BackendManager, pr as RolloutStartResult, qi as SessionMessage, qn as PromptResult, ra as SnapshotResult, rn as GitDiff, rt as DriverInfo, si as SandboxInfo, sr as RestoreSnapshotOptions, ta as SnapshotInfo, tn as GitCommit, tt as DriveTurnOptions, ua as TaskSessionCommitResult, un as GpuLeaseManager, va as TeePublicKeyResponse, vn as IntelligenceReportCompareTo, vt as ExecResult, xa as TurnDriveResult, xn as JsonValue, xr as SandboxCreateReceipt, yi as SandboxStatus, yr as SandboxConnection, zi as SessionEventStreamOptions } from "./types-C90H0DjS.js";
1
+ import { a as TerminalStreamReconnectAuthority, c as MintScopedTokenOptions, h as TerminalReadyInfo, l as ScopedToken, r as TerminalStreamHandlers, t as TerminalStream } from "./terminal-stream-CB2DF-qq.js";
2
+ import { a as InteractiveSessionControlController, c as InteractiveSessionIdentity, d as InteractiveAttachOptions, f as InteractiveControlClaimAcknowledgement, h as InteractiveSessionStatus, m as InteractiveRequestOptions, n as BrowserInteractiveSessionControlControllerOptions, o as InteractiveSessionControlControllerOptions, p as InteractiveControlClaimOptions, s as InteractiveSessionControlTransport } from "./browser-interactive-control-controller-BzR8sFjo.js";
3
+ import { M as SandboxLines } from "./lines-DuPzlFrJ.js";
4
+ import { A as CommitTaskSessionOptions, Aa as WriteManyFile, An as NetworkManager, Bi as SessionExecutionInfo, C as BranchOptions, Cr as SandboxDeleteOptions, D as CodeExecutionResult, Da as WaitForRolloutOptions, E as CodeExecutionOptions, Ea as WaitForOptions, Ei as SandboxTraceBundle, Er as SandboxEvent, Fi as SendSessionMessageOptions, Fn as PreviewLinkManager, Gi as SessionInterruptOptions, Gn as PromptInputPart, H as CreateTaskSessionOptions, Ii as SendSessionMessageRequest, Ji as SessionMessageAdmission, Jn as ProvisionEvent, Ki as SessionListOptions, Kn as PromptOptions, Li as SentSessionMessage, M as ConversationTurnOptions, Mi as SearchOptions, N as ConversationTurnResult, Nn as PermissionsManager, O as CodeLanguage, Oa as WorkspaceOperationLookup, Q as DispatchedSession, Qi as SnapshotDeleteAcknowledgement, Sn as ListMessagesOptions, Sr as SandboxDeleteAcknowledgement, Ti as SandboxTerminals, Tt as FileSystem, Ui as SessionForkOptions, V as CreateSessionOptions, Vn as ProcessManager, Wi as SessionInfo, Xi as SessionResultOptions, Xt as ForkIdempotency, Yn as ProvisionResult, Yt as ForkCounts, Z as DispatchPromptOptions, Zr as SandboxFleetTraceBundle, Zt as ForkLookupOptions, _n as IntelligenceReportBudget, _r as SSHCredentials, _t as ExecOptions, aa as StartupDiagnostics, an as GpuLease, at as DurablePlan, bi as SandboxTerminalAttachOptions, bn as IntelligenceReportWindow, cr as ResumeOptions, d as BackendConfig, dr as RolloutOptions, en as GitBranch, fa as TaskSessionInfo, fi as SandboxResourceUsage, ft as EgressManager, ga as TeeAttestationResponse, gi as SandboxShape, gn as IntelligenceReport, gr as SSHCommandDescriptor, hi as SandboxRuntimeHealth, hn as InstalledTool, ht as EventStreamOptions, in as GitStatus, j as CompletedTurnResult, ja as WriteManyOptions, ji as SearchMatch, jt as FileWriteResult, ka as WriteFileOptions, ki as SandboxTraceOptions, la as TaskSessionChanges, li as SandboxPortBinding, lr as Rollout, ma as TeeAttestationOptions, mi as SandboxRuntimeCapabilities, na as SnapshotOptions, ot as DurablePlanDecisionResult, p as BackendManager, pr as RolloutStartResult, qi as SessionMessage, qn as PromptResult, ra as SnapshotResult, rn as GitDiff, rt as DriverInfo, si as SandboxInfo, sr as RestoreSnapshotOptions, ta as SnapshotInfo, tn as GitCommit, tt as DriveTurnOptions, ua as TaskSessionCommitResult, un as GpuLeaseManager, va as TeePublicKeyResponse, vn as IntelligenceReportCompareTo, vt as ExecResult, xa as TurnDriveResult, xn as JsonValue, xr as SandboxCreateReceipt, yi as SandboxStatus, yr as SandboxConnection, zi as SessionEventStreamOptions } from "./types-B_rwXChV.js";
5
5
  import { AgentInteractiveSessionAttach, AgentInteractiveSessionControlClaim, AgentInteractiveSessionControlClaimAcknowledgement, AgentInteractiveSessionControlClaimRequest, AgentInteractiveSessionPromptAcknowledgement, AgentInteractiveSessionPromptCommand, AgentInteractiveSessionRef, AgentInteractiveSessionStart, AgentInteractiveSessionStopAcknowledgement, AgentInteractiveSessionStopCommand, AgentInteractiveTerminalSession, AgentInteractiveTerminalSession as AgentInteractiveTerminalSession$1, AgentRunCancellationAcknowledgement, AgentRunCancellationRequest, InteractionAcknowledgement, InteractionData, InteractionRequest, InteractionResponseCommand, TerminalOutputEvent, TerminalReplayWindow, agentInteractiveSessionPromptRequestDigest } from "@tangle-network/agent-interface";
6
6
  import { z } from "zod";
7
7
 
@@ -1,9 +1,9 @@
1
- //#region src/session-gateway/types.d.ts
1
+ //#region ../../../packages/runtime-contracts/dist/session-gateway.d.ts
2
2
  /**
3
- * SessionGatewayClient Types
3
+ * Shared session-gateway protocol and connection metrics
4
4
  *
5
- * Type definitions for WebSocket-based session gateway communication.
6
- * Browser-safe: no Node.js APIs.
5
+ * Browser-safe wire contracts. SDK-specific extensions and connection defaults
6
+ * remain with their clients; this module imports no runtime or Node services.
7
7
  */
8
8
  /**
9
9
  * Message types sent by the client.
@@ -45,24 +45,16 @@ interface ReplayOptions {
45
45
  lastEventId?: string;
46
46
  /** Execution ID to replay events for */
47
47
  executionId?: string;
48
- /** Actual runtime session ID used to scope replayed agent events */
48
+ /** Session ID context for replay */
49
49
  sessionId?: string;
50
50
  }
51
- interface SubscriptionDenial {
52
- channel: string;
53
- reason: string;
54
- }
55
- interface SubscriptionAcknowledgement {
56
- channels: string[];
57
- denied?: SubscriptionDenial[];
58
- }
59
51
  /**
60
52
  * Base fields present on all server messages.
61
53
  */
62
54
  interface ServerMessageBase {
63
55
  id?: string;
64
56
  timestamp?: number;
65
- /** Monotonic per-session sequence number for consumers to detect gaps. */
57
+ /** Monotonic sequence number for gap detection (per session) */
66
58
  seq?: number;
67
59
  }
68
60
  type RuntimeUnavailableReason = "container_mismatch" | "incarnation_transitioning" | "project_provisioning" | "project_degraded" | "project_suspended" | "project_failed" | "project_deprovisioning" | "project_restarting" | "sidecar_starting" | "sidecar_stopped" | "sidecar_suspended";
@@ -74,15 +66,16 @@ interface RuntimeUnavailableData {
74
66
  /**
75
67
  * Message types sent by the server.
76
68
  */
77
- type ServerMessage = (ServerMessageBase & {
69
+ type ServerMessage$1 = (ServerMessageBase & {
78
70
  type: "connection.established";
79
71
  data: {
80
72
  sessionId: string;
81
- hydratedCount?: number;
82
73
  };
83
74
  }) | (ServerMessageBase & {
84
75
  type: "subscribed";
85
- data: SubscriptionAcknowledgement;
76
+ data: {
77
+ channels: string[];
78
+ };
86
79
  }) | (ServerMessageBase & {
87
80
  type: "unsubscribed";
88
81
  data: {
@@ -203,20 +196,6 @@ type ServerMessage = (ServerMessageBase & {
203
196
  totalDropped: number; /** Hint that client should request a replay */
204
197
  suggestReplay: boolean;
205
198
  };
206
- }) | (ServerMessageBase & {
207
- type: "terminal.input.error";
208
- data: {
209
- terminalId: string;
210
- code: string;
211
- message: string;
212
- };
213
- }) | (ServerMessageBase & {
214
- type: `project.${string}`;
215
- channel?: string;
216
- data: unknown;
217
- }) | (ServerMessageBase & {
218
- type: "heartbeat";
219
- data?: unknown;
220
199
  });
221
200
  interface PortEventData {
222
201
  type: "opened" | "closed";
@@ -224,31 +203,16 @@ interface PortEventData {
224
203
  protocol: string;
225
204
  processName?: string;
226
205
  }
227
- /**
228
- * Inbound WebSocket frame. `handleMessage` validates its message type before
229
- * dispatching it to the typed session protocol.
230
- */
231
- interface RawWireMessage {
232
- type?: string;
233
- channel?: string;
234
- data?: unknown;
235
- id?: string;
236
- message?: string;
237
- code?: string;
238
- timestamp?: number;
239
- seq?: number;
240
- [key: string]: unknown;
241
- }
242
- /** Every inbound frame after its message type has been validated. */
243
- interface NormalizedServerMessage extends RawWireMessage {
244
- type: string;
245
- }
246
206
  /**
247
207
  * Connection state for the WebSocket client.
248
208
  */
249
209
  type ConnectionState = "disconnected" | "connecting" | "connected" | "reconnecting";
250
210
  /**
251
211
  * Connection quality levels based on latency, missed pongs, and reconnection frequency.
212
+ *
213
+ * Current policy: disconnected first; repeated misses/reconnects are poor;
214
+ * one missed pong, >1000 ms latency, or a recent reconnect are degraded.
215
+ * A fresh <100 ms connection is excellent; remaining connected cases are good.
252
216
  */
253
217
  type ConnectionQuality = "excellent" | "good" | "degraded" | "poor" | "disconnected";
254
218
  /**
@@ -294,16 +258,22 @@ interface TokenRefreshResult {
294
258
  /**
295
259
  * Event handlers for session gateway events.
296
260
  */
297
- interface SessionGatewayEventHandlers {
298
- /** Called after internal processing for every non-duplicate normalized frame. */
299
- onMessage?: (message: NormalizedServerMessage) => void;
261
+ interface SessionGatewayEventHandlers$1 {
300
262
  onConnect?: (sessionId: string) => void;
301
263
  onDisconnect?: (code: number, reason: string) => void;
302
264
  onReconnect?: () => void;
303
265
  onRuntimeConnected?: (sandboxId: string, baseUrl: string) => void;
304
266
  onRuntimeDisconnected?: (sandboxId: string, error?: string) => void;
305
267
  onRuntimeUnavailable?: (data: RuntimeUnavailableData) => void;
268
+ /**
269
+ * Called when no running container is found for the session.
270
+ * This typically happens when a user returns after their container has expired.
271
+ * The client should trigger reprovisioning or prompt the user.
272
+ */
306
273
  onRuntimeNotFound?: (sessionId: string, containerId: string | undefined, reason: string) => void;
274
+ /**
275
+ * Called when a runtime is fully ready with rich metadata.
276
+ */
307
277
  onRuntimeReady?: (data: {
308
278
  sandboxId: string;
309
279
  sessionId: string;
@@ -351,12 +321,29 @@ interface SessionGatewayEventHandlers {
351
321
  sandboxId?: string;
352
322
  error?: string;
353
323
  }) => void;
324
+ /**
325
+ * Called when the token is about to expire.
326
+ * The client should call refreshToken() or disconnect.
327
+ * @param secondsRemaining - Seconds until token expires
328
+ */
354
329
  onTokenExpiring?: (secondsRemaining: number) => void;
330
+ /**
331
+ * Called when the token has expired.
332
+ * The client will be disconnected shortly after this event.
333
+ */
355
334
  onTokenExpired?: () => void;
335
+ /**
336
+ * Called when events have been dropped due to WebSocket backpressure.
337
+ * The client should consider requesting a replay to catch up on missed events.
338
+ * @param droppedCount - Number of events dropped since last notification
339
+ * @param since - Timestamp when the notification window started
340
+ * @param totalDropped - Total events dropped in this session
341
+ */
356
342
  onBackpressureWarning?: (droppedCount: number, since: number, totalDropped: number) => void;
357
343
  }
358
344
  /**
359
345
  * Storage interface for replay state persistence.
346
+ * Allows custom storage implementations (localStorage, sessionStorage, memory, etc.)
360
347
  */
361
348
  interface ReplayStateStorage {
362
349
  getItem(key: string): string | null;
@@ -365,23 +352,34 @@ interface ReplayStateStorage {
365
352
  }
366
353
  /**
367
354
  * Transport mode for event delivery.
355
+ *
356
+ * - "websocket": WebSocket mode - all events via WebSocket (default)
368
357
  */
369
358
  type TransportMode = "websocket";
370
359
  /**
371
360
  * Configuration for SessionGatewayClient.
372
361
  */
373
- interface SessionGatewayClientConfig {
362
+ interface SessionGatewayClientConfig$1 {
374
363
  /** WebSocket URL for the session gateway */
375
364
  url: string;
376
- /** JWT read token for authentication (required) */
365
+ /**
366
+ * JWT read token for authentication (required).
367
+ * Obtain from product backend's session creation endpoint.
368
+ */
377
369
  token: string;
378
- /** Callback to refresh the token when it's about to expire */
370
+ /**
371
+ * Callback to refresh the token when it's about to expire.
372
+ * Called when server sends token.expiring event.
373
+ * Return new token and expiry, or throw to disconnect.
374
+ */
379
375
  onTokenRefresh?: () => Promise<TokenRefreshResult>;
380
- /** Browser session ID embedded in the session-scoped read token */
376
+ /** Session ID to connect to */
381
377
  sessionId: string;
382
- /** Transport mode (default: "websocket") */
378
+ /**
379
+ * Transport mode for event delivery (default: "websocket").
380
+ */
383
381
  transport?: TransportMode;
384
- /** Additional channels to subscribe to; server-authorized channels are used by default. */
382
+ /** Channels to subscribe to (default: ["*"]) */
385
383
  channels?: string[];
386
384
  /** Auto-reconnect on disconnect (default: true) */
387
385
  autoReconnect?: boolean;
@@ -403,16 +401,14 @@ interface SessionGatewayClientConfig {
403
401
  maxDeduplicationSize?: number;
404
402
  /** Enable replay state persistence (default: false) */
405
403
  enableReplayPersistence?: boolean;
406
- /** Storage for replay state persistence */
404
+ /** Storage for replay state persistence (default: localStorage if available) */
407
405
  replayStorage?: ReplayStateStorage;
408
406
  /** Storage key prefix for replay state (default: "session_gateway_") */
409
407
  replayStorageKeyPrefix?: string;
410
408
  /** Number of latency samples to track for averaging (default: 10) */
411
409
  latencyHistorySize?: number;
412
- /** Maximum wait for `connection.established` (default: 10000 ms) */
413
- connectionEstablishmentTimeoutMs?: number;
414
410
  /** Event handlers */
415
- handlers?: SessionGatewayEventHandlers;
411
+ handlers?: SessionGatewayEventHandlers$1;
416
412
  }
417
413
  /**
418
414
  * Statistics for the session gateway connection.
@@ -430,15 +426,77 @@ interface SessionGatewayStats {
430
426
  metrics: ConnectionMetrics;
431
427
  replay: ReplayState;
432
428
  }
433
- /**
434
- * Default connection metrics.
435
- */
436
- declare const INITIAL_METRICS: ConnectionMetrics;
437
429
  /**
438
430
  * Calculate connection quality from metrics.
439
431
  */
440
432
  declare function calculateConnectionQuality(metrics: ConnectionMetrics, isConnected: boolean): ConnectionQuality;
441
433
  //#endregion
434
+ //#region src/session-gateway/types.d.ts
435
+ interface SubscriptionDenial {
436
+ channel: string;
437
+ reason: string;
438
+ }
439
+ interface SubscriptionAcknowledgement {
440
+ channels: string[];
441
+ denied?: SubscriptionDenial[];
442
+ }
443
+ type ServerMessage = Exclude<ServerMessage$1, {
444
+ type: "connection.established" | "subscribed";
445
+ }> | (ServerMessageBase & {
446
+ type: "connection.established";
447
+ data: {
448
+ sessionId: string;
449
+ hydratedCount?: number;
450
+ };
451
+ }) | (ServerMessageBase & {
452
+ type: "subscribed";
453
+ data: SubscriptionAcknowledgement;
454
+ }) | (ServerMessageBase & {
455
+ type: "terminal.input.error";
456
+ data: {
457
+ terminalId: string;
458
+ code: string;
459
+ message: string;
460
+ };
461
+ }) | (ServerMessageBase & {
462
+ type: `project.${string}`;
463
+ channel?: string;
464
+ data: unknown;
465
+ }) | (ServerMessageBase & {
466
+ type: "heartbeat";
467
+ data?: unknown;
468
+ });
469
+ /** Untrusted inbound frame; the client validates its type before dispatch. */
470
+ interface RawWireMessage {
471
+ type?: string;
472
+ channel?: string;
473
+ data?: unknown;
474
+ id?: string;
475
+ message?: string;
476
+ code?: string;
477
+ timestamp?: number;
478
+ seq?: number;
479
+ [key: string]: unknown;
480
+ }
481
+ /** Every inbound frame after its message type has been validated. */
482
+ interface NormalizedServerMessage extends RawWireMessage {
483
+ type: string;
484
+ }
485
+ interface SessionGatewayEventHandlers extends SessionGatewayEventHandlers$1 {
486
+ /** Called after internal processing for every non-duplicate normalized frame. */
487
+ onMessage?: (message: NormalizedServerMessage) => void;
488
+ }
489
+ interface SessionGatewayClientConfig extends Omit<SessionGatewayClientConfig$1, "handlers"> {
490
+ /** Browser session ID embedded in the session-scoped read token. */
491
+ sessionId: string;
492
+ /** Additional subscriptions; server-authorized channels are used by default. */
493
+ channels?: string[];
494
+ /** Maximum wait for `connection.established` (default: 10000 ms). */
495
+ connectionEstablishmentTimeoutMs?: number;
496
+ handlers?: SessionGatewayEventHandlers;
497
+ }
498
+ declare const INITIAL_METRICS: ConnectionMetrics;
499
+ //#endregion
442
500
  //#region src/session-gateway/client.d.ts
443
501
  declare class SessionGatewayClient {
444
502
  private ws;
@@ -209,19 +209,27 @@ var TokenRefresher = class {
209
209
  }
210
210
  };
211
211
  //#endregion
212
- //#region src/session-gateway/types.ts
212
+ //#region ../../../packages/runtime-contracts/dist/session-gateway.js
213
+ /**
214
+ * Shared session-gateway protocol and connection metrics
215
+ *
216
+ * Browser-safe wire contracts. SDK-specific extensions and connection defaults
217
+ * remain with their clients; this module imports no runtime or Node services.
218
+ */
213
219
  /**
214
220
  * Default connection metrics.
215
221
  */
216
- const INITIAL_METRICS = {
217
- lastPingLatencyMs: null,
218
- avgPingLatencyMs: null,
219
- missedPongCount: 0,
220
- reconnectCount: 0,
221
- lastPongAt: null,
222
- lastReconnectAt: null,
223
- quality: "disconnected"
224
- };
222
+ function createConnectionMetrics() {
223
+ return {
224
+ lastPingLatencyMs: null,
225
+ avgPingLatencyMs: null,
226
+ missedPongCount: 0,
227
+ reconnectCount: 0,
228
+ lastPongAt: null,
229
+ lastReconnectAt: null,
230
+ quality: "disconnected"
231
+ };
232
+ }
225
233
  /**
226
234
  * Calculate connection quality from metrics.
227
235
  */
@@ -236,6 +244,10 @@ function calculateConnectionQuality(metrics, isConnected) {
236
244
  return "good";
237
245
  }
238
246
  //#endregion
247
+ //#region src/session-gateway/types.ts
248
+ /** Browser-safe shared contracts plus the public Sandbox gateway extensions. */
249
+ const INITIAL_METRICS = createConnectionMetrics();
250
+ //#endregion
239
251
  //#region src/session-gateway/client.ts
240
252
  const CONNECTION_ESTABLISHMENT_TIMEOUT_CODE = 4008;
241
253
  const CONNECTION_ERROR_CODE = 4009;