@sealant/sdk-next 0.40.0-next.965 → 0.40.0-next.967

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.
@@ -6,7 +6,9 @@ export declare const READ_RETRY_BUDGET_MS = 60000;
6
6
  * How long to wait before reading again after `error` on retry number `attempt` (from 0), or
7
7
  * `undefined` when the failure is not one a second read can fix.
8
8
  */
9
- export declare const readRetryDelayMs: (error: unknown, attempt: number, now?: number) => number | undefined;
9
+ export declare const readRetryDelayMs: (error: unknown, attempt: number, now?: number, options?: {
10
+ readonly retryBudgetExceeded?: boolean;
11
+ }) => number | undefined;
10
12
  /**
11
13
  * Runs `read`, reading again on a failure {@link readRetryDelayMs} admits, until the total wait
12
14
  * would pass {@link READ_RETRY_BUDGET_MS} or `deadline`. The failure it ends with names the run.
@@ -16,3 +18,13 @@ export declare const retryRead: <A, E, R>(read: Effect.Effect<A, E, R>, options:
16
18
  readonly what: string;
17
19
  readonly deadline: number;
18
20
  }) => Effect.Effect<A, SealantApiError, R>;
21
+ /**
22
+ * Retries an idempotent workspace status read on transient transport errors and 5xx responses,
23
+ * within {@link READ_RETRY_BUDGET_MS} and `deadline`. Non-retryable failures — including 429
24
+ * budget refusals, which callers translate into `workspace_readiness_refused` /
25
+ * `workspace_stop_observation_refused` — fail immediately unchanged.
26
+ */
27
+ export declare const retryWorkspaceRead: <A, E, R>(read: Effect.Effect<A, E, R>, options: {
28
+ readonly workspaceId: string;
29
+ readonly deadline: number;
30
+ }) => Effect.Effect<A, E | SealantApiError, R>;
@@ -5,7 +5,7 @@
5
5
  * backoff, within a bounded total wait. Anything else (a 404, a 400, a body that does not decode)
6
6
  * fails at once. Either way the failure names the run, so a caller can still read its result.
7
7
  */
8
- import { BudgetExceededError, RunInternalServerError } from "@sealant/api-contracts";
8
+ import { BudgetExceededError, RunInternalServerError, WorkspaceInternalServerError, } from "@sealant/api-contracts";
9
9
  import { Duration, Effect, Result } from "effect";
10
10
  import { HttpClientError } from "effect/http";
11
11
  import { SealantApiError } from "../errors.js";
@@ -29,8 +29,9 @@ const retryAfterMs = (value, now) => {
29
29
  const statusOf = (error) => {
30
30
  if (error instanceof BudgetExceededError)
31
31
  return 429;
32
- if (error instanceof RunInternalServerError)
32
+ if (error instanceof RunInternalServerError || error instanceof WorkspaceInternalServerError) {
33
33
  return 500;
34
+ }
34
35
  if (HttpClientError.isHttpClientError(error) && "response" in error.reason) {
35
36
  return error.reason.response.status;
36
37
  }
@@ -40,13 +41,15 @@ const statusOf = (error) => {
40
41
  * How long to wait before reading again after `error` on retry number `attempt` (from 0), or
41
42
  * `undefined` when the failure is not one a second read can fix.
42
43
  */
43
- export const readRetryDelayMs = (error, attempt, now = Date.now()) => {
44
+ export const readRetryDelayMs = (error, attempt, now = Date.now(), options) => {
45
+ const retryBudget = options?.retryBudgetExceeded ?? true;
44
46
  const backoff = Math.min(READ_RETRY_FIRST_MS * 2 ** attempt, READ_RETRY_MAX_BACKOFF_MS);
45
47
  if (error instanceof BudgetExceededError) {
46
- return Math.max(error.retryAfterSeconds * 1_000, backoff);
48
+ return retryBudget ? Math.max(error.retryAfterSeconds * 1_000, backoff) : undefined;
47
49
  }
48
- if (error instanceof RunInternalServerError)
50
+ if (error instanceof RunInternalServerError || error instanceof WorkspaceInternalServerError) {
49
51
  return backoff;
52
+ }
50
53
  if (!HttpClientError.isHttpClientError(error))
51
54
  return undefined;
52
55
  const { reason } = error;
@@ -55,6 +58,8 @@ export const readRetryDelayMs = (error, attempt, now = Date.now()) => {
55
58
  if (!("response" in reason))
56
59
  return undefined;
57
60
  const status = reason.response.status;
61
+ if (status === 429 && !retryBudget)
62
+ return undefined;
58
63
  if (status !== 429 && status < 500)
59
64
  return undefined;
60
65
  const after = retryAfterMs(reason.response.headers["retry-after"], now);
@@ -84,3 +89,31 @@ export const retryRead = (read, options) => Effect.gen(function* () {
84
89
  waited += delay;
85
90
  }
86
91
  });
92
+ /**
93
+ * Retries an idempotent workspace status read on transient transport errors and 5xx responses,
94
+ * within {@link READ_RETRY_BUDGET_MS} and `deadline`. Non-retryable failures — including 429
95
+ * budget refusals, which callers translate into `workspace_readiness_refused` /
96
+ * `workspace_stop_observation_refused` — fail immediately unchanged.
97
+ */
98
+ export const retryWorkspaceRead = (read, options) => Effect.gen(function* () {
99
+ let waited = 0;
100
+ for (let attempt = 0;; attempt += 1) {
101
+ const result = yield* Effect.result(read);
102
+ if (Result.isSuccess(result))
103
+ return result.success;
104
+ const error = result.failure;
105
+ const delay = readRetryDelayMs(error, attempt, Date.now(), { retryBudgetExceeded: false });
106
+ if (delay === undefined) {
107
+ return yield* Effect.fail(error);
108
+ }
109
+ const room = Math.min(READ_RETRY_BUDGET_MS - waited, options.deadline - elapsed());
110
+ if (delay > room) {
111
+ const mapped = toSealantError(error);
112
+ const status = statusOf(error);
113
+ const tries = attempt === 0 ? "" : ` (read ${String(attempt + 1)} times)`;
114
+ return yield* Effect.fail(new SealantApiError(`Reading workspace ${options.workspaceId} failed${tries}: ${mapped.message}`, { code: mapped.code, ...(status === undefined ? {} : { status }), cause: error }));
115
+ }
116
+ yield* Effect.sleep(Duration.millis(delay));
117
+ waited += delay;
118
+ }
119
+ });
@@ -14,5 +14,23 @@ export declare const captureTrace: (ctx: SdkContext) => CallerTrace | undefined;
14
14
  * `await`s (a polling loop), so each continues the trace the call started in.
15
15
  */
16
16
  export declare const bindRun: (ctx: SdkContext) => (<A, E>(effect: Effect.Effect<A, E, SdkServices>) => Promise<A>);
17
+ /**
18
+ * The calls of a loop that polls until something ends (a run, a session's output), which may last
19
+ * as long as an agent does. Only the calls the loop makes in the caller's name join the caller's
20
+ * trace (a first read, a final drain, what is read once it ended); the polls between join none.
21
+ */
22
+ export interface Polling {
23
+ /** The caller's trace, for a request the loop makes outside the runtime (its SSE stream). */
24
+ readonly trace: CallerTrace | undefined;
25
+ /** A call in the caller's trace: a read the caller is waiting on, not a poll. */
26
+ readonly run: <A, E>(effect: Effect.Effect<A, E, SdkServices>) => Promise<A>;
27
+ /**
28
+ * A poll, in no trace: its request starts a short trace of its own on the server, rather than
29
+ * growing the caller's trace by a few spans every half second for as long as the loop runs.
30
+ */
31
+ readonly poll: <A, E>(effect: Effect.Effect<A, E, SdkServices>) => Promise<A>;
32
+ }
33
+ /** {@link Polling} bound to the caller's trace captured now. */
34
+ export declare const bindPolling: (ctx: SdkContext) => Polling;
17
35
  /** An AsyncIterable whose iteration rejects — for surface that is typed now but not yet implemented. */
18
36
  export declare const notImplementedAsyncIterable: <A>(operation: string, error: Error) => AsyncIterable<A>;
@@ -9,6 +9,17 @@ export const bindRun = (ctx) => {
9
9
  const trace = captureTrace(ctx);
10
10
  return (effect) => ctx.runtime.run(effect, trace);
11
11
  };
12
+ /** A trace that continues nothing: the call makes no spans and its request carries no trace header. */
13
+ const NO_TRACE = { parent: undefined, tracer: undefined, tracestate: undefined };
14
+ /** {@link Polling} bound to the caller's trace captured now. */
15
+ export const bindPolling = (ctx) => {
16
+ const trace = captureTrace(ctx);
17
+ return {
18
+ trace,
19
+ run: (effect) => ctx.runtime.run(effect, trace),
20
+ poll: (effect) => ctx.runtime.run(effect, NO_TRACE),
21
+ };
22
+ };
12
23
  /** An AsyncIterable whose iteration rejects — for surface that is typed now but not yet implemented. */
13
24
  export const notImplementedAsyncIterable = (operation, error) => ({
14
25
  [Symbol.asyncIterator]() {
@@ -9,7 +9,7 @@ import { decodeRecordEventPayload, } from "@sealant/api-contracts";
9
9
  import { getRunLossOp, getRunOp, getRunScrollbackOp, getRunTimelineOp, } from "../effect/operations.js";
10
10
  import { SealantNotImplementedError } from "../errors.js";
11
11
  import { elapsed } from "../internal/clock.js";
12
- import { bindRun } from "./context.js";
12
+ import { bindPolling } from "./context.js";
13
13
  // Live `stream()` is poll-backed for now: it tails the timeline endpoint until the run is terminal.
14
14
  // The transport swaps to SSE over Postgres LISTEN/NOTIFY in Stage 5 behind this same signature.
15
15
  const TERMINAL_RUN_STATUSES = new Set(["completed", "failed", "cancelled"]);
@@ -186,12 +186,14 @@ export const makeRunRecord = (ctx, runId) => {
186
186
  transcript: async () => renderTranscript(reconstructCommands(await fetchTimeline())),
187
187
  stream: (options) => {
188
188
  // Captured when stream() is called: the generator's body first runs on the first next().
189
- const traced = bindRun(ctx);
189
+ // The first read and the final drain join the caller's trace; the polls between are their own.
190
+ const polling = bindPolling(ctx);
190
191
  async function* iterate() {
191
192
  let from = options?.from;
192
193
  const deadline = elapsed() + STREAM_TIMEOUT_MS;
194
+ let call = polling.run;
193
195
  for (;;) {
194
- const wire = await traced(getRunTimelineOp(runId, {
196
+ const wire = await call(getRunTimelineOp(runId, {
195
197
  ownerUserId: ctx.config.hostLocal.ownerUserId,
196
198
  ...(from === undefined ? {} : { fromSequence: from.toString() }),
197
199
  }));
@@ -202,9 +204,10 @@ export const makeRunRecord = (ctx, runId) => {
202
204
  }
203
205
  // Stop once the run is terminal — with one final drain to catch entries written between the
204
206
  // last timeline fetch and the status check.
205
- const run = await traced(getRunOp(runId, ctx.config.hostLocal.ownerUserId));
207
+ const run = await call(getRunOp(runId, ctx.config.hostLocal.ownerUserId));
208
+ call = polling.poll;
206
209
  if (TERMINAL_RUN_STATUSES.has(run.status)) {
207
- const tail = await traced(getRunTimelineOp(runId, {
210
+ const tail = await polling.run(getRunTimelineOp(runId, {
208
211
  ownerUserId: ctx.config.hostLocal.ownerUserId,
209
212
  ...(from === undefined ? {} : { fromSequence: from.toString() }),
210
213
  }));
@@ -1,7 +1,7 @@
1
1
  import { getRunChangesOp, getRunOp } from "../effect/operations.js";
2
2
  import { SealantError, SealantNotImplementedError } from "../errors.js";
3
3
  import { elapsed } from "../internal/clock.js";
4
- import { bindRun } from "./context.js";
4
+ import { bindPolling } from "./context.js";
5
5
  import { makeRunRecord } from "./record.js";
6
6
  /** Maps the wire changes shape to the facade data (shared with the run-harness execution path). */
7
7
  export const toRunChangesData = (wire) => ({
@@ -47,8 +47,9 @@ export const makeRun = (ctx, init) => {
47
47
  artifacts: emptyArtifacts,
48
48
  record: makeRunRecord(ctx, runId),
49
49
  wait: async () => {
50
- // Each poll continues the trace wait() was called in.
51
- const run = bindRun(ctx);
50
+ // The polls are their own short traces; what wait() reads once the run is terminal joins
51
+ // the trace it was called in.
52
+ const { run, poll } = bindPolling(ctx);
52
53
  let current = init.wire;
53
54
  const deadline = elapsed() + WAIT_TIMEOUT_MS;
54
55
  while (!TERMINAL_STATUSES.has(current.status)) {
@@ -58,7 +59,7 @@ export const makeRun = (ctx, init) => {
58
59
  });
59
60
  }
60
61
  await delay(WAIT_POLL_INTERVAL_MS);
61
- current = await run(getRunOp(runId, ctx.config.hostLocal.ownerUserId));
62
+ current = await poll(getRunOp(runId, ctx.config.hostLocal.ownerUserId));
62
63
  }
63
64
  // Settle the changes: a handle from `harness.start()` or `runs.get()` has none captured yet,
64
65
  // so read the server-side capture now that the run is terminal.
@@ -4,7 +4,7 @@ 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 { captureTrace } from "./context.js";
7
+ import { bindPolling } from "./context.js";
8
8
  /**
9
9
  * Open the held-WebSocket terminal attachment (the data plane). One socket:
10
10
  * binary frames are PTY bytes in both directions, text frames are control
@@ -189,16 +189,20 @@ async function* streamOverSse(ctx, sessionId, from, signal, priority, trace) {
189
189
  }
190
190
  }
191
191
  /** Poll-backed fallback: page the range endpoint until the session settles. */
192
- async function* streamByPolling(ctx, sessionId, from, signal, trace) {
192
+ async function* streamByPolling(ctx, sessionId, from, signal, polling) {
193
193
  let cursor = from;
194
+ // The first page continues the caller's trace; every later one is a poll of its own, so a
195
+ // session's output read this way never holds one trace open for the agent's whole life.
196
+ let call = polling.run;
194
197
  for (;;) {
195
198
  if (signal?.aborted === true) {
196
199
  return;
197
200
  }
198
- const page = await ctx.runtime.run(getSessionOutputOp(sessionId, {
201
+ const page = await call(getSessionOutputOp(sessionId, {
199
202
  ownerUserId: ctx.config.hostLocal.ownerUserId,
200
203
  from: cursor.toString(),
201
- }), trace);
204
+ }));
205
+ call = polling.poll;
202
206
  for (const chunk of page.chunks) {
203
207
  yield { sequence: BigInt(chunk.sequence), data: decodeBase64(chunk.dataBase64) };
204
208
  }
@@ -229,7 +233,8 @@ export const makeInteractiveSession = (ctx, wire) => {
229
233
  const from = options?.from ?? 0n;
230
234
  const signal = options?.signal;
231
235
  // Captured when output() is called: the generator's body first runs on the first next().
232
- const trace = captureTrace(ctx);
236
+ const polling = bindPolling(ctx);
237
+ const trace = polling.trace;
233
238
  async function* iterate() {
234
239
  let cursor = from;
235
240
  const priority = resolveRequestPriority(ctx.config.requestPriority);
@@ -250,7 +255,7 @@ export const makeInteractiveSession = (ctx, wire) => {
250
255
  // from the cursor; the sequence keying makes the switch seamless.
251
256
  void error;
252
257
  }
253
- yield* streamByPolling(ctx, sessionId, cursor, signal, trace);
258
+ yield* streamByPolling(ctx, sessionId, cursor, signal, polling);
254
259
  }
255
260
  return iterate();
256
261
  },
@@ -2,6 +2,7 @@ import { sessionArgvIssue, WORKSPACE_GATEWAY_UNAVAILABLE_CODE } from "@sealant/a
2
2
  import { applyDotfiles } from "../effect/apply-dotfiles.js";
3
3
  import { execWorkspace } from "../effect/exec-workspace.js";
4
4
  import { applyWorkspaceNetworkPolicyOp, bindWorkspaceOp, getWorkspaceNetworkPolicyOp, revokeWorkspaceAccessOp, flushWorkspaceCaptureOp, getWorkspaceCaptureStatusOp, createSessionAsUserOp, createSessionOp, expireWorkspaceOp, clearWorkspaceSshUserOp, getSessionOp, getWorkspaceOp, listSessionsOp, replanWorkspaceCaptureOp, recoverWorkspaceOp, restartWorkspaceOp, listWorkspaceCredentialsOp, putWorkspaceCredentialsOp, pruneWorkspaceCredentialsOp, releaseWorkspaceCredentialsOp, stopWorkspaceOp, } from "../effect/operations.js";
5
+ import { READ_RETRY_BUDGET_MS, retryWorkspaceRead } from "../effect/read-retry.js";
5
6
  import { withCallerTrace } from "../effect/trace.js";
6
7
  import { SealantApiError, SealantBoatError, SealantBudgetExceededError, SealantError, SealantNotImplementedError, } from "../errors.js";
7
8
  import { specHarnessId } from "../internal/blueprint.js";
@@ -520,8 +521,21 @@ export const makeWorkspace = (ctx, init) => {
520
521
  ? " A stop was requested; the workspace has not been observed stopped."
521
522
  : " Requesting a stop failed; stop it yourself."}`, { code });
522
523
  };
524
+ const readDeadline = () => {
525
+ const now = elapsed();
526
+ if (building) {
527
+ const buildRoom = imageBuildTimeoutMs === undefined
528
+ ? READ_RETRY_BUDGET_MS
529
+ : Math.max(0, imageBuildTimeoutMs - (buildMs + (now - lastPollAt)));
530
+ return now + buildRoom;
531
+ }
532
+ return now + Math.max(0, readyTimeoutMs - (now - startedAt - buildMs));
533
+ };
523
534
  for (;;) {
524
- const details = await ctx.runtime.run(getWorkspaceOp(init.id, ctx.config.hostLocal.ownerUserId), trace);
535
+ const details = await ctx.runtime.run(retryWorkspaceRead(getWorkspaceOp(init.id, ctx.config.hostLocal.ownerUserId), {
536
+ workspaceId: init.id,
537
+ deadline: readDeadline(),
538
+ }), trace);
525
539
  const now = elapsed();
526
540
  // The time since the last look was spent building when the last look saw a build.
527
541
  if (building)
@@ -746,7 +760,10 @@ export const makeWorkspace = (ctx, init) => {
746
760
  const deadline = elapsed() + STOP_TIMEOUT_MS;
747
761
  for (;;) {
748
762
  const details = await ctx.runtime
749
- .run(getWorkspaceOp(init.id, ctx.config.hostLocal.ownerUserId), trace)
763
+ .run(retryWorkspaceRead(getWorkspaceOp(init.id, ctx.config.hostLocal.ownerUserId), {
764
+ workspaceId: init.id,
765
+ deadline,
766
+ }), trace)
750
767
  .catch((error) => {
751
768
  if (error instanceof SealantBudgetExceededError) {
752
769
  throw new SealantError(`A stop for workspace ${init.id} was accepted, but a follow-up request reached its budget. Read the workspace again to observe its status.`, { code: "workspace_stop_observation_refused", cause: error });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sealant/sdk-next",
3
- "version": "0.40.0-next.965",
3
+ "version": "0.40.0-next.967",
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.965"
29
+ "@sealant/api-contracts": "npm:@sealant/api-contracts-next@0.40.0-next.967"
30
30
  },
31
31
  "peerDependencies": {
32
32
  "effect": "^4.0.5"
33
33
  },
34
- "gitHead": "962ab884d38508869aa5a6c86fce2761849dc2a1",
34
+ "gitHead": "e14bfdd3f73f866926b07ba8a57d0066c0d4afad",
35
35
  "publishConfig": {
36
36
  "access": "public"
37
37
  }