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

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.
@@ -13,6 +13,7 @@ import { Context, Effect, Layer } from "effect";
13
13
  import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";
14
14
  import { HttpApiClient } from "effect/http-api";
15
15
  import { resolveRequestPriority } from "../internal/config.js";
16
+ import { withHttpRetryMiddleware } from "./retry-middleware.js";
16
17
  import { CallerTraceState, DirectTraceparent, endpointRoutes, instrumentClient } from "./trace.js";
17
18
  /** A per-operation priority; providing it never changes concurrent requests. */
18
19
  export const CurrentRequestPriority = Context.Reference("@sealant/sdk/CurrentRequestPriority", { defaultValue: () => undefined });
@@ -21,7 +22,7 @@ const CONTROL_PLANE_ROUTES = endpointRoutes(ControlPlaneAPI);
21
22
  const buildControlPlaneClient = (config) => {
22
23
  return Effect.map(HttpApiClient.make(ControlPlaneAPI, {
23
24
  baseUrl: config.baseUrl,
24
- transformClient: (client) => HttpClient.mapRequestEffect(client, (request) => Effect.gen(function* () {
25
+ transformClient: (client) => withHttpRetryMiddleware(HttpClient.mapRequestEffect(client, (request) => Effect.gen(function* () {
25
26
  const priority = yield* CurrentRequestPriority;
26
27
  const traceparent = yield* DirectTraceparent;
27
28
  const tracestate = yield* CallerTraceState;
@@ -35,7 +36,7 @@ const buildControlPlaneClient = (config) => {
35
36
  return config.apiKey === undefined
36
37
  ? prioritized
37
38
  : HttpClientRequest.bearerToken(prioritized, config.apiKey);
38
- })),
39
+ }))),
39
40
  }), (client) => instrumentClient(client, CONTROL_PLANE_ROUTES));
40
41
  };
41
42
  export class SealantApiClient extends Context.Service()("@sealant/sdk/SealantApiClient") {
@@ -19,6 +19,8 @@
19
19
  */
20
20
  export { SealantApiClient, sealantApiClientLayer } from "./api-client.js";
21
21
  export type { ControlPlaneClient } from "./api-client.js";
22
+ export { CurrentRetryPolicy, DEFAULT_HTTP_RETRY_POLICY, NO_HTTP_RETRY_POLICY, isTransientSdkError, retryTransientEffect, withHttpRetryMiddleware, } from "./retry-middleware.js";
23
+ export type { HttpRetryPolicy, RetryTransientEffectOptions } from "./retry-middleware.js";
22
24
  export * from "./operations.js";
23
25
  export { makeSdkRuntime } from "./runtime.js";
24
26
  export type { SdkRuntime, SdkServices } from "./runtime.js";
@@ -26,4 +28,4 @@ export { captureCallerTrace } from "./trace.js";
26
28
  export type { CallerTrace } from "./trace.js";
27
29
  export { resolveInternalConfig } from "../internal/config.js";
28
30
  export type { SealantHostLocalConfig, SealantInternalConfig } from "../internal/config.js";
29
- export { ConnectedAccountBadRequestError, ConnectedAccountConflictError, ConnectedAccountInternalServerError, ConnectedAccountNotFoundError, ConnectedAccountServiceUnavailableError, InferenceBadRequestError, InferenceConflictError, InferenceInternalServerError, InferenceNotFoundError, InferenceUnavailableError, RunBadRequestError, RunInternalServerError, RunNotFoundError, UserBadRequestError, UserInternalServerError, UserNotFoundError, WorkspaceBadGatewayError, WorkspaceBadRequestError, WorkspaceConflictError, WorkspaceForbiddenError, WorkspaceInternalServerError, WorkspaceNotFoundError, WorkspaceRuntimeRequirementUnsupportedError, WorkspaceServiceUnavailableError, WorkspaceUnauthorizedError, } from "@sealant/api-contracts";
31
+ export { isRateLimitedContractError, isRetryableContractError, isTransientContractError, ConnectedAccountBadRequestError, ConnectedAccountConflictError, ConnectedAccountInternalServerError, ConnectedAccountNotFoundError, ConnectedAccountServiceUnavailableError, InferenceBadRequestError, InferenceConflictError, InferenceInternalServerError, InferenceNotFoundError, InferenceUnavailableError, RunBadRequestError, RunInternalServerError, RunNotFoundError, UserBadRequestError, UserInternalServerError, UserNotFoundError, WorkspaceBadGatewayError, WorkspaceBadRequestError, WorkspaceConflictError, WorkspaceForbiddenError, WorkspaceInternalServerError, WorkspaceNotFoundError, WorkspaceRuntimeRequirementUnsupportedError, WorkspaceServiceUnavailableError, WorkspaceUnauthorizedError, } from "@sealant/api-contracts";
@@ -19,6 +19,8 @@
19
19
  */
20
20
  // The contract-derived client service + layer.
21
21
  export { SealantApiClient, sealantApiClientLayer } from "./api-client.js";
22
+ // HTTP retry/timeout middleware policy and Effect-level transient retry combinator.
23
+ export { CurrentRetryPolicy, DEFAULT_HTTP_RETRY_POLICY, NO_HTTP_RETRY_POLICY, isTransientSdkError, retryTransientEffect, withHttpRetryMiddleware, } from "./retry-middleware.js";
22
24
  // One operation effect per contract endpoint (wire types in, wire types out).
23
25
  export * from "./operations.js";
24
26
  // The managed runtime the Promise facade runs on.
@@ -30,4 +32,4 @@ export { resolveInternalConfig } from "../internal/config.js";
30
32
  // The typed contract errors carried on the client's failure channel (workspaces + runs +
31
33
  // inference — the groups the operations above call). Re-exported so Effect consumers don't need to
32
34
  // depend on the contracts package directly to `Effect.catchTag` a failure.
33
- export { ConnectedAccountBadRequestError, ConnectedAccountConflictError, ConnectedAccountInternalServerError, ConnectedAccountNotFoundError, ConnectedAccountServiceUnavailableError, InferenceBadRequestError, InferenceConflictError, InferenceInternalServerError, InferenceNotFoundError, InferenceUnavailableError, RunBadRequestError, RunInternalServerError, RunNotFoundError, UserBadRequestError, UserInternalServerError, UserNotFoundError, WorkspaceBadGatewayError, WorkspaceBadRequestError, WorkspaceConflictError, WorkspaceForbiddenError, WorkspaceInternalServerError, WorkspaceNotFoundError, WorkspaceRuntimeRequirementUnsupportedError, WorkspaceServiceUnavailableError, WorkspaceUnauthorizedError, } from "@sealant/api-contracts";
35
+ export { isRateLimitedContractError, isRetryableContractError, isTransientContractError, ConnectedAccountBadRequestError, ConnectedAccountConflictError, ConnectedAccountInternalServerError, ConnectedAccountNotFoundError, ConnectedAccountServiceUnavailableError, InferenceBadRequestError, InferenceConflictError, InferenceInternalServerError, InferenceNotFoundError, InferenceUnavailableError, RunBadRequestError, RunInternalServerError, RunNotFoundError, UserBadRequestError, UserInternalServerError, UserNotFoundError, WorkspaceBadGatewayError, WorkspaceBadRequestError, WorkspaceConflictError, WorkspaceForbiddenError, WorkspaceInternalServerError, WorkspaceNotFoundError, WorkspaceRuntimeRequirementUnsupportedError, WorkspaceServiceUnavailableError, WorkspaceUnauthorizedError, } from "@sealant/api-contracts";
@@ -5,31 +5,27 @@
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, WorkspaceInternalServerError, } from "@sealant/api-contracts";
8
+ import { isRateLimitedContractError, isTransientContractError } 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";
12
12
  import { elapsed } from "../internal/clock.js";
13
13
  import { toSealantError } from "../internal/map-error.js";
14
+ import { CurrentRetryPolicy, NO_HTTP_RETRY_POLICY, parseRetryAfterMs } from "./retry-middleware.js";
14
15
  /** The first backoff when the answer names no `Retry-After`; it doubles up to the cap. */
15
16
  const READ_RETRY_FIRST_MS = 100;
16
17
  const READ_RETRY_MAX_BACKOFF_MS = 2_000;
17
18
  /** The most one read waits across all its retries: a whole budget window, and no more. */
18
19
  export const READ_RETRY_BUDGET_MS = 60_000;
19
- /** `Retry-After` in milliseconds: delay-seconds or an HTTP date. */
20
- const retryAfterMs = (value, now) => {
21
- if (value === undefined || value.trim().length === 0)
22
- return undefined;
23
- const seconds = Number(value);
24
- if (Number.isFinite(seconds))
25
- return Math.max(0, seconds * 1_000);
26
- const at = Date.parse(value);
27
- return Number.isNaN(at) ? undefined : Math.max(0, at - now);
28
- };
29
20
  const statusOf = (error) => {
30
- if (error instanceof BudgetExceededError)
21
+ if (isRateLimitedContractError(error))
31
22
  return 429;
32
- if (error instanceof RunInternalServerError || error instanceof WorkspaceInternalServerError) {
23
+ if (isTransientContractError(error)) {
24
+ const tag = error["_tag"];
25
+ if (tag.endsWith("BadGatewayError"))
26
+ return 502;
27
+ if (tag.endsWith("UnavailableError"))
28
+ return 503;
33
29
  return 500;
34
30
  }
35
31
  if (HttpClientError.isHttpClientError(error) && "response" in error.reason) {
@@ -44,10 +40,10 @@ const statusOf = (error) => {
44
40
  export const readRetryDelayMs = (error, attempt, now = Date.now(), options) => {
45
41
  const retryBudget = options?.retryBudgetExceeded ?? true;
46
42
  const backoff = Math.min(READ_RETRY_FIRST_MS * 2 ** attempt, READ_RETRY_MAX_BACKOFF_MS);
47
- if (error instanceof BudgetExceededError) {
43
+ if (isRateLimitedContractError(error)) {
48
44
  return retryBudget ? Math.max(error.retryAfterSeconds * 1_000, backoff) : undefined;
49
45
  }
50
- if (error instanceof RunInternalServerError || error instanceof WorkspaceInternalServerError) {
46
+ if (isTransientContractError(error)) {
51
47
  return backoff;
52
48
  }
53
49
  if (!HttpClientError.isHttpClientError(error))
@@ -62,7 +58,7 @@ export const readRetryDelayMs = (error, attempt, now = Date.now(), options) => {
62
58
  return undefined;
63
59
  if (status !== 429 && status < 500)
64
60
  return undefined;
65
- const after = retryAfterMs(reason.response.headers["retry-after"], now);
61
+ const after = parseRetryAfterMs(reason.response.headers["retry-after"], now);
66
62
  return after === undefined ? backoff : Math.max(after, backoff);
67
63
  };
68
64
  /**
@@ -71,8 +67,11 @@ export const readRetryDelayMs = (error, attempt, now = Date.now(), options) => {
71
67
  */
72
68
  export const retryRead = (read, options) => Effect.gen(function* () {
73
69
  let waited = 0;
70
+ // Own the retry schedule here (up to 60 s / deadline) without nesting middleware retries,
71
+ // while keeping the middleware's per-attempt HTTP read timeout active.
72
+ const singleAttempt = Effect.provideService(read, CurrentRetryPolicy, NO_HTTP_RETRY_POLICY);
74
73
  for (let attempt = 0;; attempt += 1) {
75
- const result = yield* Effect.result(read);
74
+ const result = yield* Effect.result(singleAttempt);
76
75
  if (Result.isSuccess(result))
77
76
  return result.success;
78
77
  const error = result.failure;
@@ -97,8 +96,9 @@ export const retryRead = (read, options) => Effect.gen(function* () {
97
96
  */
98
97
  export const retryWorkspaceRead = (read, options) => Effect.gen(function* () {
99
98
  let waited = 0;
99
+ const singleAttempt = Effect.provideService(read, CurrentRetryPolicy, NO_HTTP_RETRY_POLICY);
100
100
  for (let attempt = 0;; attempt += 1) {
101
- const result = yield* Effect.result(read);
101
+ const result = yield* Effect.result(singleAttempt);
102
102
  if (Result.isSuccess(result))
103
103
  return result.success;
104
104
  const error = result.failure;
@@ -0,0 +1,51 @@
1
+ import { Context, Effect } from "effect";
2
+ import { HttpClient } from "effect/http";
3
+ export interface HttpRetryPolicy {
4
+ /** Max retry attempts after the initial attempt (`0` disables retries). */
5
+ readonly maxRetries: number;
6
+ /** Initial backoff delay in milliseconds before doubling. */
7
+ readonly initialBackoffMs: number;
8
+ /** Cap on exponential backoff delay in milliseconds. */
9
+ readonly maxBackoffMs: number;
10
+ /** Apply Effect's `Schedule.jittered` to backoff delays (default `true`). */
11
+ readonly jitter: boolean;
12
+ /** Per-attempt timeout in milliseconds for safe reads (`GET`/`HEAD`); `undefined` disables it. */
13
+ readonly requestTimeoutMs: number | undefined;
14
+ /** Also retry HTTP 429 responses (default `false` so callers observe `BudgetExceededError`). */
15
+ readonly retryBudgetExceeded: boolean;
16
+ /** Also retry `TransportError` on `POST`/`PUT` carrying `idempotency-key` (default `true`). */
17
+ readonly retryIdempotentWrites: boolean;
18
+ }
19
+ export declare const DEFAULT_HTTP_RETRY_POLICY: HttpRetryPolicy;
20
+ /** Disables middleware retries while keeping the per-attempt read timeout active. */
21
+ export declare const NO_HTTP_RETRY_POLICY: HttpRetryPolicy;
22
+ /** Per-fiber HTTP retry policy; providing it never mutates concurrent requests. */
23
+ export declare const CurrentRetryPolicy: Context.Reference<HttpRetryPolicy>;
24
+ /** Parses an HTTP `Retry-After` header (delay-seconds or HTTP-date) into milliseconds. */
25
+ export declare const parseRetryAfterMs: (value: string | undefined, now?: number) => number | undefined;
26
+ /**
27
+ * Wraps an Effect `HttpClient` with default per-attempt timeouts for safe reads (`GET`/`HEAD`)
28
+ * and bounded transient retries governed by {@link CurrentRetryPolicy}.
29
+ */
30
+ export declare const withHttpRetryMiddleware: (client: HttpClient.HttpClient) => HttpClient.HttpClient;
31
+ /**
32
+ * True when `error` is a transient failure according to either the API contract's `isRetryable`
33
+ * getters (`isTransientContractError` / optional `isRateLimitedContractError`) or Effect's
34
+ * `HttpClientError` (`TransportError` or transient HTTP status).
35
+ */
36
+ export declare const isTransientSdkError: (error: unknown, options?: {
37
+ readonly retryBudgetExceeded?: boolean;
38
+ }) => boolean;
39
+ export interface RetryTransientEffectOptions {
40
+ readonly maxRetries?: number;
41
+ readonly initialBackoffMs?: number;
42
+ readonly maxBackoffMs?: number;
43
+ readonly jitter?: boolean;
44
+ readonly retryBudgetExceeded?: boolean;
45
+ }
46
+ /**
47
+ * Retries an Effect on contract-tagged transient errors (`isRetryable === true`), `TransportError`s,
48
+ * and transient HTTP responses using Effect's capped, jittered exponential `Schedule` (honoring
49
+ * `Retry-After` and `error.retryAfter`).
50
+ */
51
+ export declare const retryTransientEffect: (options?: RetryTransientEffectOptions) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Shared Effect HTTP retry/timeout middleware and Effect-level transient retry combinator.
3
+ *
4
+ * Every control-plane request goes through `withHttpRetryMiddleware` in `api-client.ts`:
5
+ * - Safe reads (`GET`, `HEAD`) get a bounded per-attempt timeout (default 15 s, preventing a dead
6
+ * socket from sitting for undici's 300 s default) and automatic jittered exponential-backoff
7
+ * retries on transport errors, timeouts, and transient 5xx/408 responses (honoring `Retry-After`).
8
+ * - Writes carrying an `idempotency-key` (`POST`, `PUT`) retry `TransportError` only — never HTTP
9
+ * status responses (e.g. a 503 capability refusal like `unsupported-runtime` is never retried).
10
+ * - HTTP 429 (`BudgetExceededError`) is NOT retried by default so admission refusals surface
11
+ * immediately unless a caller opts in via `CurrentRetryPolicy`.
12
+ * - Unkeyed writes (`POST`, `PATCH`, `DELETE`) are never retried.
13
+ *
14
+ * For Effect-native callers above the HTTP layer, `retryTransientEffect` composes `Effect.retry`
15
+ * with Effect v4's canonical `Schedule.min([Schedule.exponential, Schedule.spaced])` +
16
+ * `Schedule.jittered` schedule and the contract's `isRetryable` / `retryAfter` getters.
17
+ */
18
+ import { isRateLimitedContractError, isTransientContractError } from "@sealant/api-contracts";
19
+ import { Context, Data, Duration, Effect, Option, Schedule } from "effect";
20
+ import { HttpClient, HttpClientError } from "effect/http";
21
+ export const DEFAULT_HTTP_RETRY_POLICY = {
22
+ maxRetries: 3,
23
+ initialBackoffMs: 100,
24
+ maxBackoffMs: 2_000,
25
+ jitter: true,
26
+ requestTimeoutMs: 15_000,
27
+ retryBudgetExceeded: false,
28
+ retryIdempotentWrites: true,
29
+ };
30
+ /** Disables middleware retries while keeping the per-attempt read timeout active. */
31
+ export const NO_HTTP_RETRY_POLICY = {
32
+ ...DEFAULT_HTTP_RETRY_POLICY,
33
+ maxRetries: 0,
34
+ };
35
+ /** Per-fiber HTTP retry policy; providing it never mutates concurrent requests. */
36
+ export const CurrentRetryPolicy = Context.Reference("@sealant/sdk/CurrentRetryPolicy", { defaultValue: () => DEFAULT_HTTP_RETRY_POLICY });
37
+ /** Parses an HTTP `Retry-After` header (delay-seconds or HTTP-date) into milliseconds. */
38
+ export const parseRetryAfterMs = (value, now = Date.now()) => {
39
+ if (value === undefined || value.trim().length === 0)
40
+ return undefined;
41
+ const seconds = Number(value);
42
+ if (Number.isFinite(seconds))
43
+ return Math.max(0, seconds * 1_000);
44
+ const at = Date.parse(value);
45
+ return Number.isNaN(at) ? undefined : Math.max(0, at - now);
46
+ };
47
+ const isRetryableHttpStatus = (status, retryBudgetExceeded) => status === 408 ||
48
+ status === 500 ||
49
+ status === 502 ||
50
+ status === 503 ||
51
+ status === 504 ||
52
+ (retryBudgetExceeded && status === 429);
53
+ const isTransportError = (error) => HttpClientError.isHttpClientError(error) &&
54
+ error.reason instanceof HttpClientError.TransportError;
55
+ class RetryableResponseError extends Data.TaggedError("RetryableResponseError") {
56
+ }
57
+ const retryAfterFromAttemptError = (error, now) => {
58
+ if (error instanceof RetryableResponseError) {
59
+ const ms = parseRetryAfterMs(error.response.headers["retry-after"], now);
60
+ return ms === undefined ? undefined : Duration.millis(ms);
61
+ }
62
+ if (HttpClientError.isHttpClientError(error) && "response" in error.reason) {
63
+ const ms = parseRetryAfterMs(error.reason.response.headers["retry-after"], now);
64
+ return ms === undefined ? undefined : Duration.millis(ms);
65
+ }
66
+ if (isRateLimitedContractError(error)) {
67
+ return error.retryAfter;
68
+ }
69
+ return undefined;
70
+ };
71
+ const makeBackoffSchedule = (policy) => {
72
+ const capped = Schedule.min([
73
+ Schedule.exponential(Duration.millis(policy.initialBackoffMs)),
74
+ Schedule.spaced(Duration.millis(policy.maxBackoffMs)),
75
+ ]);
76
+ const base = policy.jitter ? Schedule.jittered(capped) : capped;
77
+ return base.pipe(Schedule.modifyDelay(({ duration, input, now }) => {
78
+ const retryAfter = retryAfterFromAttemptError(input, now);
79
+ return Effect.succeed(retryAfter === undefined ? duration : Duration.max(duration, retryAfter));
80
+ }));
81
+ };
82
+ /**
83
+ * Wraps an Effect `HttpClient` with default per-attempt timeouts for safe reads (`GET`/`HEAD`)
84
+ * and bounded transient retries governed by {@link CurrentRetryPolicy}.
85
+ */
86
+ export const withHttpRetryMiddleware = (client) => HttpClient.transform(client, (responseEffect, request) => Effect.gen(function* () {
87
+ const policy = yield* CurrentRetryPolicy;
88
+ const isSafeRead = request.method === "GET" || request.method === "HEAD";
89
+ const isIdempotentWrite = (request.method === "POST" || request.method === "PUT") &&
90
+ request.headers["idempotency-key"] !== undefined;
91
+ if (!isSafeRead && !(isIdempotentWrite && policy.retryIdempotentWrites)) {
92
+ return yield* responseEffect;
93
+ }
94
+ if (isSafeRead) {
95
+ const timeoutMs = policy.requestTimeoutMs;
96
+ const timedAttempt = timeoutMs === undefined
97
+ ? responseEffect
98
+ : Effect.flatMap(Effect.timeoutOption(responseEffect, Duration.millis(timeoutMs)), Option.match({
99
+ onSome: Effect.succeed,
100
+ onNone: () => Effect.fail(new HttpClientError.HttpClientError({
101
+ reason: new HttpClientError.TransportError({
102
+ request,
103
+ description: `Request timed out after ${String(timeoutMs)}ms`,
104
+ }),
105
+ })),
106
+ }));
107
+ if (policy.maxRetries <= 0) {
108
+ return yield* timedAttempt;
109
+ }
110
+ const attempt = Effect.flatMap(timedAttempt, (response) => isRetryableHttpStatus(response.status, policy.retryBudgetExceeded)
111
+ ? Effect.fail(new RetryableResponseError({ response }))
112
+ : Effect.succeed(response));
113
+ return yield* attempt.pipe(Effect.retry({
114
+ schedule: makeBackoffSchedule(policy),
115
+ times: policy.maxRetries,
116
+ while: (error) => error instanceof RetryableResponseError ||
117
+ isTransportError(error) ||
118
+ (HttpClientError.isHttpClientError(error) &&
119
+ "response" in error.reason &&
120
+ isRetryableHttpStatus(error.reason.response.status, policy.retryBudgetExceeded)),
121
+ }), Effect.catchTag("RetryableResponseError", ({ response }) => Effect.succeed(response)));
122
+ }
123
+ if (policy.maxRetries <= 0) {
124
+ return yield* responseEffect;
125
+ }
126
+ return yield* responseEffect.pipe(Effect.retry({
127
+ schedule: makeBackoffSchedule(policy),
128
+ times: policy.maxRetries,
129
+ while: isTransportError,
130
+ }));
131
+ }));
132
+ /**
133
+ * True when `error` is a transient failure according to either the API contract's `isRetryable`
134
+ * getters (`isTransientContractError` / optional `isRateLimitedContractError`) or Effect's
135
+ * `HttpClientError` (`TransportError` or transient HTTP status).
136
+ */
137
+ export const isTransientSdkError = (error, options) => {
138
+ const retryBudget = options?.retryBudgetExceeded ?? false;
139
+ if (isTransientContractError(error))
140
+ return true;
141
+ if (retryBudget && isRateLimitedContractError(error))
142
+ return true;
143
+ if (!HttpClientError.isHttpClientError(error))
144
+ return false;
145
+ if (error.reason instanceof HttpClientError.TransportError)
146
+ return true;
147
+ if ("response" in error.reason) {
148
+ return isRetryableHttpStatus(error.reason.response.status, retryBudget);
149
+ }
150
+ return false;
151
+ };
152
+ /**
153
+ * Retries an Effect on contract-tagged transient errors (`isRetryable === true`), `TransportError`s,
154
+ * and transient HTTP responses using Effect's capped, jittered exponential `Schedule` (honoring
155
+ * `Retry-After` and `error.retryAfter`).
156
+ */
157
+ export const retryTransientEffect = (options = {}) => (effect) => {
158
+ const maxRetries = options.maxRetries ?? DEFAULT_HTTP_RETRY_POLICY.maxRetries;
159
+ if (maxRetries <= 0)
160
+ return effect;
161
+ const retryBudgetExceeded = options.retryBudgetExceeded ?? false;
162
+ return effect.pipe(Effect.retry({
163
+ schedule: makeBackoffSchedule({
164
+ initialBackoffMs: options.initialBackoffMs ?? DEFAULT_HTTP_RETRY_POLICY.initialBackoffMs,
165
+ maxBackoffMs: options.maxBackoffMs ?? DEFAULT_HTTP_RETRY_POLICY.maxBackoffMs,
166
+ jitter: options.jitter ?? DEFAULT_HTTP_RETRY_POLICY.jitter,
167
+ }),
168
+ times: maxRetries,
169
+ while: (error) => isTransientSdkError(error, { retryBudgetExceeded }),
170
+ }));
171
+ };
@@ -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
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sealant/sdk-next",
3
- "version": "0.40.0-next.966",
3
+ "version": "0.40.0-next.968",
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.966"
29
+ "@sealant/api-contracts": "npm:@sealant/api-contracts-next@0.40.0-next.968"
30
30
  },
31
31
  "peerDependencies": {
32
32
  "effect": "^4.0.5"
33
33
  },
34
- "gitHead": "449c6833bd97eba69e54001cb970c10b6821063e",
34
+ "gitHead": "0059589d543d3873d583060dc926977ded51fc5d",
35
35
  "publishConfig": {
36
36
  "access": "public"
37
37
  }