@sealant/sdk-next 0.40.0-next.968 → 0.40.0-next.970

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/errors.d.ts CHANGED
@@ -137,6 +137,19 @@ export declare class ForwardDialError extends SealantApiError {
137
137
  readonly refusal?: RequestBudgetRefusal;
138
138
  constructor(failure: ForwardDialFailure);
139
139
  }
140
+ /**
141
+ * A wait the caller bounded with a timeout ran out before what it waited for happened. `code` says
142
+ * which wait (`run_stream_timeout`); the work itself goes on server-side.
143
+ */
144
+ export declare class SealantTimeoutError extends SealantError {
145
+ readonly name = "SealantTimeoutError";
146
+ /** The timeout the caller set, in milliseconds. */
147
+ readonly timeoutMs: number;
148
+ constructor(message: string, options: {
149
+ readonly code: string;
150
+ readonly timeoutMs: number;
151
+ });
152
+ }
140
153
  /** The requested operation is part of the public surface but not yet implemented in this slice. */
141
154
  export declare class SealantNotImplementedError extends SealantError {
142
155
  readonly name = "SealantNotImplementedError";
package/dist/errors.js CHANGED
@@ -153,6 +153,19 @@ export class ForwardDialError extends SealantApiError {
153
153
  }
154
154
  }
155
155
  }
156
+ /**
157
+ * A wait the caller bounded with a timeout ran out before what it waited for happened. `code` says
158
+ * which wait (`run_stream_timeout`); the work itself goes on server-side.
159
+ */
160
+ export class SealantTimeoutError extends SealantError {
161
+ name = "SealantTimeoutError";
162
+ /** The timeout the caller set, in milliseconds. */
163
+ timeoutMs;
164
+ constructor(message, options) {
165
+ super(message, { code: options.code });
166
+ this.timeoutMs = options.timeoutMs;
167
+ }
168
+ }
156
169
  /** The requested operation is part of the public surface but not yet implemented in this slice. */
157
170
  export class SealantNotImplementedError extends SealantError {
158
171
  name = "SealantNotImplementedError";
@@ -2,6 +2,7 @@ import { FORWARD_REFUSAL_STATUS, FORWARD_V2_SUBPROTOCOL, forwardOpenFrameSchema,
2
2
  import { Option, Predicate, Schema } from "effect";
3
3
  import { ForwardDialError } from "../errors.js";
4
4
  import { resolveRequestPriority } from "../internal/config.js";
5
+ import { openControlPlaneWebSocket } from "../internal/websocket.js";
5
6
  import { boundedForward } from "./bounded-forward.js";
6
7
  const forwardUrl = (endpoint, path, query) => {
7
8
  const url = new URL(path, endpoint.baseUrl);
@@ -10,12 +11,9 @@ const forwardUrl = (endpoint, path, query) => {
10
11
  if (value !== undefined)
11
12
  url.searchParams.set(name, value);
12
13
  }
13
- // The owner assertion always rides the URL (a service principal needs it alongside its
14
- // key, and WebSocket cannot carry headers — same contract as the session attach).
14
+ // The owner assertion rides the URL; the key rides the upgrade's Authorization header
15
+ // (`openControlPlaneWebSocket`), never the URL.
15
16
  url.searchParams.set("ownerUserId", endpoint.ownerUserId);
16
- if (endpoint.apiKey !== undefined) {
17
- url.searchParams.set("token", endpoint.apiKey);
18
- }
19
17
  return url;
20
18
  };
21
19
  const bridgeForward = (ws) => {
@@ -90,7 +88,7 @@ export const openForward = (endpoint, workspaceId, port, options) => {
90
88
  protocol: options?.protocol === "udp" ? "udp" : undefined,
91
89
  });
92
90
  return new Promise((resolve, reject) => {
93
- const ws = new WebSocket(url);
91
+ const ws = openControlPlaneWebSocket(url, endpoint.apiKey);
94
92
  ws.binaryType = "arraybuffer";
95
93
  const forward = bridgeForward(ws);
96
94
  ws.addEventListener("open", () => resolve(forward), { once: true });
@@ -160,7 +158,7 @@ export const openForwardV2 = (endpoint, workspaceId, port, options) => {
160
158
  return new Promise((resolve, reject) => {
161
159
  if (signal?.aborted === true)
162
160
  return reject(signal.reason);
163
- const ws = new WebSocket(url, FORWARD_V2_SUBPROTOCOL);
161
+ const ws = openControlPlaneWebSocket(url, endpoint.apiKey, FORWARD_V2_SUBPROTOCOL);
164
162
  ws.binaryType = "arraybuffer";
165
163
  const probing = new AbortController();
166
164
  let phase = "handshake";
@@ -7,15 +7,14 @@
7
7
  */
8
8
  import { decodeRecordEventPayload, } from "@sealant/api-contracts";
9
9
  import { getRunLossOp, getRunOp, getRunScrollbackOp, getRunTimelineOp, } from "../effect/operations.js";
10
- import { SealantNotImplementedError } from "../errors.js";
10
+ import { SealantNotImplementedError, SealantTimeoutError } from "../errors.js";
11
11
  import { elapsed } from "../internal/clock.js";
12
+ import { pause } from "../internal/pause.js";
12
13
  import { bindPolling } from "./context.js";
13
14
  // Live `stream()` is poll-backed for now: it tails the timeline endpoint until the run is terminal.
14
15
  // The transport swaps to SSE over Postgres LISTEN/NOTIFY in Stage 5 behind this same signature.
15
16
  const TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "cancelled"]);
16
17
  const STREAM_POLL_INTERVAL_MS = 500;
17
- const STREAM_TIMEOUT_MS = 30 * 60 * 1_000;
18
- const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
19
18
  /**
20
19
  * Maps a wire entry to the public DISCRIMINATED entry: the contract's payload schemas fold
21
20
  * `(kind, ref)` into typed `data`, degrading to the `unknown` case (raw kind + payload preserved)
@@ -188,11 +187,17 @@ export const makeRunRecord = (ctx, runId) => {
188
187
  // Captured when stream() is called: the generator's body first runs on the first next().
189
188
  // The first read and the final drain join the caller's trace; the polls between are their own.
190
189
  const polling = bindPolling(ctx);
190
+ const signal = options?.signal;
191
+ const timeoutMs = options?.timeoutMs;
191
192
  async function* iterate() {
192
193
  let from = options?.from;
193
- const deadline = elapsed() + STREAM_TIMEOUT_MS;
194
+ // No deadline unless the caller set one: the stream follows the run for as long as it
195
+ // lives, and ends only at its terminal status or when `signal` aborts.
196
+ const startedAt = elapsed();
194
197
  let call = polling.run;
195
198
  for (;;) {
199
+ if (signal?.aborted === true)
200
+ return;
196
201
  const wire = await call(getRunTimelineOp(runId, {
197
202
  ownerUserId: ctx.config.hostLocal.ownerUserId,
198
203
  ...(from === undefined ? {} : { fromSequence: from.toString() }),
@@ -216,10 +221,10 @@ export const makeRunRecord = (ctx, runId) => {
216
221
  }
217
222
  return;
218
223
  }
219
- if (elapsed() > deadline) {
220
- return;
224
+ if (timeoutMs !== undefined && elapsed() - startedAt > timeoutMs) {
225
+ throw new SealantTimeoutError(`Run ${runId} was still ${run.status} when its record stream's ${timeoutMs} ms timeout passed.`, { code: "run_stream_timeout", timeoutMs });
221
226
  }
222
- await delay(STREAM_POLL_INTERVAL_MS);
227
+ await pause(STREAM_POLL_INTERVAL_MS, signal);
223
228
  }
224
229
  }
225
230
  return iterate();
@@ -4,28 +4,27 @@ import { traceHeaders } from "../effect/trace.js";
4
4
  import { SealantBudgetExceededError } from "../errors.js";
5
5
  import { resolveRequestPriority } from "../internal/config.js";
6
6
  import { toSealantError } from "../internal/map-error.js";
7
+ import { pause } from "../internal/pause.js";
8
+ import { openControlPlaneWebSocket } from "../internal/websocket.js";
7
9
  import { bindPolling } from "./context.js";
8
10
  /**
9
11
  * Open the held-WebSocket terminal attachment (the data plane). One socket:
10
12
  * binary frames are PTY bytes in both directions, text frames are control
11
13
  * JSON (`{"t":"resize",...}` up, `{"t":"end"}` down). Auth rides the connect —
12
- * `?ownerUserId=` always, plus `?token=` for apiKey clients (WebSocket cannot
13
- * set headers; a service principal needs the owner assertion *and* its key) —
14
- * and never repeats per event.
14
+ * `?ownerUserId=` in the URL, the API key as the upgrade's `Authorization`
15
+ * header (a service principal needs the owner assertion *and* its key) — and
16
+ * never repeats per event.
15
17
  */
16
18
  const openAttachment = (ctx, sessionId, options) => {
17
19
  const config = ctx.config;
18
20
  const url = new URL(`/v1/sessions/${sessionId}/attach`, config.baseUrl);
19
21
  url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
20
22
  url.searchParams.set("from", (options?.from ?? 0n).toString());
21
- // The owner assertion always rides the URL; a service principal needs it *alongside* its key,
22
- // and WebSocket cannot carry headers, so the key rides the URL too.
23
+ // The owner assertion rides the URL; a service principal needs it *alongside* its key, which
24
+ // rides the upgrade's Authorization header and never the URL.
23
25
  url.searchParams.set("ownerUserId", config.hostLocal.ownerUserId);
24
- if (config.apiKey !== undefined) {
25
- url.searchParams.set("token", config.apiKey);
26
- }
27
26
  return new Promise((resolve, reject) => {
28
- const ws = new WebSocket(url);
27
+ const ws = openControlPlaneWebSocket(url, config.apiKey);
29
28
  ws.binaryType = "arraybuffer";
30
29
  // Push-queue bridging WS message events to the pull-based async iterable.
31
30
  const pending = [];
@@ -129,22 +128,28 @@ const parseSseFrame = (block) => {
129
128
  }
130
129
  return { event, id, data: dataLines.join("\n") };
131
130
  };
132
- /** Stream the session's output over SSE. Throws on transport failure (caller falls back). */
131
+ /** One connection to the session's SSE output: its chunks, then how it ended. */
133
132
  async function* streamOverSse(ctx, sessionId, from, signal, priority, trace) {
134
133
  const config = ctx.config;
135
134
  const fetchImpl = config.fetch ?? fetch;
136
135
  const url = new URL(`/v1/sessions/${sessionId}/output/stream`, config.baseUrl);
137
136
  url.searchParams.set("from", from.toString());
138
137
  url.searchParams.set("ownerUserId", config.hostLocal.ownerUserId);
139
- const response = await fetchImpl(url, {
140
- headers: {
141
- accept: "text/event-stream",
142
- "x-sealant-request-priority": priority,
143
- ...traceHeaders(trace),
144
- ...(config.apiKey === undefined ? {} : { authorization: `Bearer ${config.apiKey}` }),
145
- },
146
- ...(signal === undefined ? {} : { signal }),
147
- });
138
+ let response;
139
+ try {
140
+ response = await fetchImpl(url, {
141
+ headers: {
142
+ accept: "text/event-stream",
143
+ "x-sealant-request-priority": priority,
144
+ ...traceHeaders(trace),
145
+ ...(config.apiKey === undefined ? {} : { authorization: `Bearer ${config.apiKey}` }),
146
+ },
147
+ ...(signal === undefined ? {} : { signal }),
148
+ });
149
+ }
150
+ catch {
151
+ return "unavailable";
152
+ }
148
153
  if (response.status === 429) {
149
154
  const body = await response.json().catch(() => undefined);
150
155
  const error = toSealantError(body);
@@ -152,18 +157,26 @@ async function* streamOverSse(ctx, sessionId, from, signal, priority, trace) {
152
157
  throw error;
153
158
  }
154
159
  if (!response.ok || response.body === null) {
155
- throw new Error(`session output stream failed: HTTP ${response.status}`);
160
+ await response.body?.cancel().catch(() => undefined);
161
+ return "unavailable";
156
162
  }
157
163
  const reader = response.body.getReader();
158
164
  const decoder = new TextDecoder();
159
165
  let buffered = "";
160
166
  try {
161
167
  for (;;) {
162
- const { done, value } = await reader.read();
163
- if (done) {
164
- return;
168
+ let read;
169
+ try {
170
+ read = await reader.read();
171
+ }
172
+ catch {
173
+ // The connection dropped mid-stream (or the caller aborted): not the session's end.
174
+ return "cut";
165
175
  }
166
- buffered += decoder.decode(value, { stream: true });
176
+ if (read.done) {
177
+ return "cut";
178
+ }
179
+ buffered += decoder.decode(read.value, { stream: true });
167
180
  for (;;) {
168
181
  const boundary = buffered.indexOf("\n\n");
169
182
  if (boundary === -1) {
@@ -176,7 +189,7 @@ async function* streamOverSse(ctx, sessionId, from, signal, priority, trace) {
176
189
  continue;
177
190
  }
178
191
  if (frame.event === "end") {
179
- return;
192
+ return "ended";
180
193
  }
181
194
  if (frame.event === "output" && frame.id !== undefined) {
182
195
  yield { sequence: BigInt(frame.id), data: decodeBase64(frame.data) };
@@ -188,6 +201,17 @@ async function* streamOverSse(ctx, sessionId, from, signal, priority, trace) {
188
201
  await reader.cancel().catch(() => undefined);
189
202
  }
190
203
  }
204
+ /**
205
+ * Reconnects after an SSE connection is cut, from the last chunk seen. The delay doubles with each
206
+ * connection in a row that brought no output, up to `SSE_RECONNECT_MAX_DELAY_MS`; after
207
+ * `SSE_RECONNECT_ATTEMPTS` of them (about half a minute, enough to ride out a control-plane
208
+ * deploy) the output falls back to polling, which ends only when the session has exited or failed
209
+ * and otherwise reports the error.
210
+ */
211
+ const SSE_RECONNECT_ATTEMPTS = 10;
212
+ const SSE_RECONNECT_BASE_DELAY_MS = 250;
213
+ const SSE_RECONNECT_MAX_DELAY_MS = 5_000;
214
+ const reconnectDelay = (failures) => Math.min(SSE_RECONNECT_BASE_DELAY_MS * 2 ** failures, SSE_RECONNECT_MAX_DELAY_MS);
191
215
  /** Poll-backed fallback: page the range endpoint until the session settles. */
192
216
  async function* streamByPolling(ctx, sessionId, from, signal, polling) {
193
217
  let cursor = from;
@@ -232,28 +256,52 @@ export const makeInteractiveSession = (ctx, wire) => {
232
256
  output: (options) => {
233
257
  const from = options?.from ?? 0n;
234
258
  const signal = options?.signal;
259
+ // A function, so the check reads the signal now: an abort lands while the loop awaits.
260
+ const aborted = () => signal?.aborted === true;
235
261
  // Captured when output() is called: the generator's body first runs on the first next().
236
262
  const polling = bindPolling(ctx);
237
263
  const trace = polling.trace;
238
264
  async function* iterate() {
239
265
  let cursor = from;
240
266
  const priority = resolveRequestPriority(ctx.config.requestPriority);
241
- try {
242
- for await (const chunk of streamOverSse(ctx, sessionId, cursor, signal, priority, trace)) {
243
- yield chunk;
244
- cursor = chunk.sequence + 1n;
267
+ let connected = false;
268
+ let failures = 0;
269
+ for (;;) {
270
+ // Only the first connection continues the caller's trace; a reconnect is its own.
271
+ const frames = streamOverSse(ctx, sessionId, cursor, signal, priority, connected ? undefined : trace);
272
+ let outcome;
273
+ let delivered = false;
274
+ try {
275
+ for (;;) {
276
+ const next = await frames.next();
277
+ if (next.done === true) {
278
+ outcome = next.value;
279
+ break;
280
+ }
281
+ delivered = true;
282
+ cursor = next.value.sequence + 1n;
283
+ yield next.value;
284
+ }
245
285
  }
246
- return;
247
- }
248
- catch (error) {
249
- if (error instanceof SealantBudgetExceededError)
250
- throw error;
251
- if (signal?.aborted === true) {
252
- return;
286
+ finally {
287
+ await frames.return("cut");
253
288
  }
254
- // SSE transport unavailable (proxy, fetch impl, older server) — fall back to polling
255
- // from the cursor; the sequence keying makes the switch seamless.
256
- void error;
289
+ // Only an `end` frame says the session settled. A body that stops without one was cut,
290
+ // and the session may still be running: reconnect from the cursor, which the sequence
291
+ // keying makes seamless.
292
+ if (outcome === "ended" || aborted())
293
+ return;
294
+ // An endpoint that never opened is a transport that cannot stream SSE (an older
295
+ // server, a proxy, a fetch impl): poll instead.
296
+ if (outcome === "unavailable" && !connected)
297
+ break;
298
+ connected = true;
299
+ failures = delivered ? 0 : failures + 1;
300
+ if (failures >= SSE_RECONNECT_ATTEMPTS)
301
+ break;
302
+ await pause(reconnectDelay(failures), signal);
303
+ if (aborted())
304
+ return;
257
305
  }
258
306
  yield* streamByPolling(ctx, sessionId, cursor, signal, polling);
259
307
  }
package/dist/index.d.ts CHANGED
@@ -16,7 +16,7 @@
16
16
  */
17
17
  export { Sealant } from "./client.js";
18
18
  export { antigravity, claudeCode, codex, customHarness, opencode, pi } from "./harness.js";
19
- export { ForwardDialError, type ForwardDialFailure, type ForwardDialReason, ForwardResetError, SealantApiError, SealantBoatError, SealantBudgetExceededError, SealantError, SealantNotImplementedError, SealantRuntimeError, } from "./errors.js";
19
+ export { ForwardDialError, type ForwardDialFailure, type ForwardDialReason, ForwardResetError, SealantApiError, SealantBoatError, SealantBudgetExceededError, SealantError, SealantNotImplementedError, SealantRuntimeError, SealantTimeoutError, } from "./errors.js";
20
20
  export type * from "./types.js";
21
21
  export { BOAT_FAILURE_KINDS, BOAT_RETRYABLE_FAILURE_KINDS, BOAT_DEFAULT_ACCOUNT_ID, type BoatFailure, type BoatFailureKind, type BoatKeyNotObserved, type BoatKeyProof, type BoatKeyProofStep, type BoatKeyProofStepName, type BoatKeyReport, type BoatKeyBilling, type BoatKeyWalletChoice, type BoatWallet, BOAT_KEY_PROOF_STEPS, } from "@sealant/api-contracts";
22
22
  export type { EnsuredScope, ScopeBudget, ScopeBudgetDimension, ScopeBudgetLimits, ScopeBudgets, ScopeClient, ScopeInfo, ScopeMember, ScopeMemberDecision, ScopeMemberPage, ScopeMembers, ScopesNamespace, } from "./scopes.js";
package/dist/index.js CHANGED
@@ -16,7 +16,7 @@
16
16
  */
17
17
  export { Sealant } from "./client.js";
18
18
  export { antigravity, claudeCode, codex, customHarness, opencode, pi } from "./harness.js";
19
- export { ForwardDialError, ForwardResetError, SealantApiError, SealantBoatError, SealantBudgetExceededError, SealantError, SealantNotImplementedError, SealantRuntimeError, } from "./errors.js";
19
+ export { ForwardDialError, ForwardResetError, SealantApiError, SealantBoatError, SealantBudgetExceededError, SealantError, SealantNotImplementedError, SealantRuntimeError, SealantTimeoutError, } from "./errors.js";
20
20
  // Why Boat refused a call for a Boat workspace (`SealantBoatError.boat`): a closed set of kinds.
21
21
  export { BOAT_FAILURE_KINDS, BOAT_RETRYABLE_FAILURE_KINDS, BOAT_DEFAULT_ACCOUNT_ID, BOAT_KEY_PROOF_STEPS, } from "@sealant/api-contracts";
22
22
  // The workspace environment policy (`CreateOptions.env` validation) is public API: downstream
@@ -0,0 +1,2 @@
1
+ /** Waits `ms`, or less when `signal` aborts first; never rejects. */
2
+ export declare const pause: (ms: number, signal: AbortSignal | undefined) => Promise<void>;
@@ -0,0 +1,3 @@
1
+ import { setTimeout as sleep } from "node:timers/promises";
2
+ /** Waits `ms`, or less when `signal` aborts first; never rejects. */
3
+ export const pause = (ms, signal) => sleep(ms, undefined, signal === undefined ? undefined : { signal }).catch(() => undefined);
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Opens a WebSocket to the control plane, sending the API key as an `Authorization: Bearer`
3
+ * header on the upgrade request.
4
+ *
5
+ * The key never goes in the URL: a query string ends up in proxy and load-balancer access logs,
6
+ * traces and error reports. The control plane's WebSocket routes read the header first and still
7
+ * take `?token=` from older SDKs.
8
+ */
9
+ export declare const openControlPlaneWebSocket: (url: URL, apiKey: string | undefined, protocol?: string) => WebSocket;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Opens a WebSocket to the control plane, sending the API key as an `Authorization: Bearer`
3
+ * header on the upgrade request.
4
+ *
5
+ * The key never goes in the URL: a query string ends up in proxy and load-balancer access logs,
6
+ * traces and error reports. The control plane's WebSocket routes read the header first and still
7
+ * take `?token=` from older SDKs.
8
+ */
9
+ export const openControlPlaneWebSocket = (url, apiKey, protocol) => {
10
+ // Read at each call, not at import: the global is looked up when a socket is opened.
11
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the SDK runs on Node, whose global WebSocket is undici's and takes this init object; the DOM lib in scope does not declare it.
12
+ const NodeWebSocket = WebSocket;
13
+ return new NodeWebSocket(url, {
14
+ ...(protocol === undefined ? {} : { protocols: protocol }),
15
+ ...(apiKey === undefined ? {} : { headers: { authorization: `Bearer ${apiKey}` } }),
16
+ });
17
+ };
package/dist/types.d.ts CHANGED
@@ -2309,9 +2309,16 @@ export interface RunRecord {
2309
2309
  commands(): Promise<readonly RunCommand[]>;
2310
2310
  /** A human-readable transcript: the commands and their outcomes, nicely laid out (no event noise). */
2311
2311
  transcript(): Promise<string>;
2312
- /** Subscribe to the live event stream while the run is in progress (poll-backed; SSE later). */
2312
+ /**
2313
+ * Subscribe to the live event stream while the run is in progress (poll-backed; SSE later). It
2314
+ * ends after the run reaches a terminal status and its last entries are read, or quietly when
2315
+ * `signal` aborts. With `timeoutMs` it throws `SealantTimeoutError` (`run_stream_timeout`) once
2316
+ * that long has passed with the run still going; without it there is no time limit.
2317
+ */
2313
2318
  stream(options?: {
2314
2319
  readonly from?: bigint;
2320
+ readonly signal?: AbortSignal;
2321
+ readonly timeoutMs?: number;
2315
2322
  }): AsyncIterable<TimelineEntry>;
2316
2323
  /** Iterate the full timeline as structured data. */
2317
2324
  timeline(options?: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sealant/sdk-next",
3
- "version": "0.40.0-next.968",
3
+ "version": "0.40.0-next.970",
4
4
  "description": "The fluent public SDK for Sealant — create a workspace, run a harness, replay the record.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -26,12 +26,12 @@
26
26
  "node": ">=20"
27
27
  },
28
28
  "dependencies": {
29
- "@sealant/api-contracts": "npm:@sealant/api-contracts-next@0.40.0-next.968"
29
+ "@sealant/api-contracts": "npm:@sealant/api-contracts-next@0.40.0-next.970"
30
30
  },
31
31
  "peerDependencies": {
32
32
  "effect": "^4.0.5"
33
33
  },
34
- "gitHead": "0059589d543d3873d583060dc926977ded51fc5d",
34
+ "gitHead": "5df64afeb5d0c3cb200cea278ec248dc863e3d42",
35
35
  "publishConfig": {
36
36
  "access": "public"
37
37
  }