@guuey/agent-client 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guuey/agent-client",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Client SDK for Guuey's agent runtime: the `useAgentInvoke` React hook + pure SSE helpers that speak the /agent/invoke streaming contract, plus the paginated thread-history read plane. Host adapters (storage / id / transport) are injected, so it runs on web (Next) and React Native alike.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -25,11 +25,17 @@
25
25
  "types": "./dist/react.d.ts",
26
26
  "import": "./dist/react.js",
27
27
  "default": "./dist/react.js"
28
+ },
29
+ "./transport": {
30
+ "react-native": "./src/transport.ts",
31
+ "types": "./dist/transport.d.ts",
32
+ "import": "./dist/transport.js",
33
+ "default": "./dist/transport.js"
28
34
  }
29
35
  },
30
36
  "dependencies": {
31
37
  "@silverprotocol/core": "0.4.1",
32
- "@guuey/mcp-apps-host": "0.4.0"
38
+ "@guuey/mcp-apps-host": "0.5.0"
33
39
  },
34
40
  "peerDependencies": {
35
41
  "react": ">=18"
@@ -27,6 +27,13 @@ export const AGENT_ERROR_CODES = {
27
27
  INVALID_REQUEST: "INVALID_REQUEST",
28
28
  /** The builder turned anonymous access off for this agent. */
29
29
  GUEST_ACCESS_DISABLED: "GUEST_ACCESS_DISABLED",
30
+ /**
31
+ * The agent's own definition declares `auth: 'required'` and the caller is
32
+ * anonymous — sign in and retry with a bearer. The snapshot-declared twin of
33
+ * {@link AGENT_ERROR_CODES.GUEST_ACCESS_DISABLED} (the app-record runtime
34
+ * override); either gate can refuse.
35
+ */
36
+ AUTH_REQUIRED: "AUTH_REQUIRED",
30
37
  /** The caller (or the app) is out of plan allowance — the upgrade prompt. */
31
38
  QUOTA_EXCEEDED: "QUOTA_EXCEEDED",
32
39
  /** The app hit its builder-set managed spend cap. */
@@ -56,3 +63,27 @@ export const AGENT_ERROR_CODES = {
56
63
 
57
64
  /** One of the pod's wire codes — see {@link AGENT_ERROR_CODES}. */
58
65
  export type AgentErrorCode = (typeof AGENT_ERROR_CODES)[keyof typeof AGENT_ERROR_CODES];
66
+
67
+ /**
68
+ * CLIENT-originated failure codes — minted by THIS SDK, never by the pod.
69
+ *
70
+ * Deliberately a SEPARATE constant from {@link AGENT_ERROR_CODES}: that
71
+ * object is a transcribed mirror of the runtime's wire vocabulary, guarded by
72
+ * the runtime-side `agent-client-codes.sync.test.ts` — adding a code the pod
73
+ * never emits there would both break the sync guard and lie about the wire.
74
+ * These codes surface through the SAME `errorCode` channel (it is a plain
75
+ * `string` for exactly this kind of growth), so consumers branch the same
76
+ * way; the split exists so each vocabulary keeps one honest owner.
77
+ */
78
+ export const CLIENT_ERROR_CODES = {
79
+ /**
80
+ * The SSE stream went byte-silent mid-turn and bounded history probes never
81
+ * found the finished reply (guuey#192's stall watchdog giving up). The turn
82
+ * is over (`status` returns to `ready`); a retry or a reload may still find
83
+ * the reply if the backend completes later.
84
+ */
85
+ STREAM_STALLED: "STREAM_STALLED",
86
+ } as const;
87
+
88
+ /** One of this SDK's client-originated codes — see {@link CLIENT_ERROR_CODES}. */
89
+ export type ClientErrorCode = (typeof CLIENT_ERROR_CODES)[keyof typeof CLIENT_ERROR_CODES];
package/src/index.ts CHANGED
@@ -8,6 +8,9 @@ export {
8
8
  type ParsedSseEvent,
9
9
  } from "./sse.js";
10
10
  export { dismissLinkPrompt } from "./link-prompt.js";
11
+ // One agent turn as a pure async generator — the wire walk `useAgentInvoke`
12
+ // wraps, for hosts that drive their own turn state machine (guuey#186 G5).
13
+ export { invokeTurn, toInvokeUrl, type InvokeTurnEvent } from "./invoke-turn.js";
11
14
  export {
12
15
  createUiActionRelay,
13
16
  type CreateUiActionRelayOptions,
@@ -16,24 +19,41 @@ export {
16
19
  createWebAdapters,
17
20
  localStorageThreadStore,
18
21
  webGenerateId,
19
- fetchStreamTransport,
20
22
  type CreateWebAdaptersOptions,
21
23
  } from "./web-adapters.js";
22
- // The `POD_SATURATED` single-retry wrapper, transport-agnostic: a host that
23
- // brings its own `fetch` (Portal's React-Native transport) wraps it to wear the
24
- // same semantics as the web transport instead of hand-rolling a second copy.
25
- // `parseRetryAfterSeconds` ships with it because filling
26
- // `AgentResponseError.retryAfterSeconds` the same way is what makes the wrapper
27
- // honour the pod's hint.
24
+ // The invoke transport + guest-identity wire pieces, in their own
25
+ // mcp-apps-host-free module. Consumers that want ONLY this graph (no
26
+ // host-role card layer riding along) import `@guuey/agent-client/transport`
27
+ // instead of the barrel see that module's docblock (guuey#186 G2).
28
+ export {
29
+ fetchStreamTransport,
30
+ sendableGuestSecret,
31
+ GUEST_HEADER,
32
+ withActivityObserver,
33
+ type FetchStreamTransportOptions,
34
+ } from "./transport.js";
35
+ // The invoke-refusal retry wrappers, transport-agnostic: a host that brings
36
+ // its own `fetch` (Portal's React-Native transport) wraps them to wear the
37
+ // same semantics as the web transport instead of hand-rolling second copies.
38
+ // `parseRetryAfterSeconds` ships with them because filling
39
+ // `AgentResponseError.retryAfterSeconds` the same way is what makes the
40
+ // wrappers honour the pod's hint.
28
41
  export {
29
42
  withSaturationRetry,
43
+ withColdStartRetry,
30
44
  parseRetryAfterSeconds,
31
45
  type SaturationRetryOptions,
46
+ type ColdStartRetryOptions,
32
47
  } from "./saturation-retry.js";
33
48
  export { AgentResponseError } from "./errors.js";
34
49
  // The pod's wire-code vocabulary, mirrored — branch on these instead of
35
50
  // re-typing the string literals (see the module docblock for the sync guard).
36
- export { AGENT_ERROR_CODES, type AgentErrorCode } from "./error-codes.js";
51
+ export {
52
+ AGENT_ERROR_CODES,
53
+ type AgentErrorCode,
54
+ CLIENT_ERROR_CODES,
55
+ type ClientErrorCode,
56
+ } from "./error-codes.js";
37
57
  export {
38
58
  fetchThreadHistory,
39
59
  threadHistoryRowsToMessages,
@@ -50,7 +70,10 @@ export { ingestMessageFrame } from "./blocks.js";
50
70
  export { sortHistoryCards, toolNameFor } from "./history.js";
51
71
  // Re-export the AgJSON types the block-preserving transcript surfaces, so
52
72
  // consumers can name `reduceResult` / block types without a direct
53
- // `@silverprotocol/core` import.
73
+ // `@silverprotocol/core` import — and the `Reducer` CLASS beside them, so a
74
+ // host folding `invokeTurn`'s agEvents outside the hook builds its transcript
75
+ // on the same terms (the types alone forced the direct dep back, guuey#186 G4).
76
+ export { Reducer } from "@silverprotocol/core";
54
77
  export type { AgEvent, AgReduceResult, AgMessage, AgBlock } from "@silverprotocol/core";
55
78
  export type {
56
79
  AgentMessage,
@@ -65,6 +88,7 @@ export type {
65
88
  AgentInvokeHistoryAdapter,
66
89
  AgentInvokeStatus,
67
90
  HistoryLoadResult,
91
+ StallRecoveryOptions,
68
92
  UseAgentInvokeOptions,
69
93
  UseAgentInvokeReturn,
70
94
  } from "./types.js";
@@ -0,0 +1,187 @@
1
+ /**
2
+ * invokeTurn — one agent turn as a pure async generator (guuey#186 G5).
3
+ *
4
+ * The per-turn loop `useAgentInvoke` runs — SSE accumulate → event switch →
5
+ * cumulative text fold → AgJSON block ingest — used to exist only fused to
6
+ * React state inside the hook, so a host with its own turn state machine
7
+ * (a game loop, a native view model, a server-side driver) had to re-walk
8
+ * the wire switch by hand. This module IS that loop, wire-in / semantics-out
9
+ * and React-free: feed it the request and a transport, iterate
10
+ * {@link InvokeTurnEvent}s. The hook is a thin wrapper that maps each event
11
+ * onto its state setters — behaviour-identical, one walk of the switch,
12
+ * owned here.
13
+ *
14
+ * Turn-scoped by design: the generator owns the CUMULATIVE assistant text
15
+ * for this turn (every `message` event carries the full folded text so far,
16
+ * not a delta). Cross-turn state stays with the caller — notably the AgJSON
17
+ * `Reducer`, which folds an entire conversation: this generator yields each
18
+ * frame's validated `agEvents` and never touches a reducer.
19
+ *
20
+ * Transport failures (e.g. `AgentResponseError` on a pre-stream refusal)
21
+ * propagate out of iteration — catch around the `for await`, exactly as the
22
+ * hook does. Unknown SSE events yield nothing, matching the hook's silent
23
+ * fall-through, so new wire events are additive for every consumer.
24
+ */
25
+ import type { AgEvent } from "@silverprotocol/core";
26
+ import {
27
+ parseConsentRequest,
28
+ parseLinkRequest,
29
+ parseSseEvents,
30
+ reduceAssistantText,
31
+ stringField,
32
+ } from "./sse.js";
33
+ import { ingestMessageFrame } from "./blocks.js";
34
+ import type {
35
+ AgentInvokeStatus,
36
+ InvokeRequest,
37
+ InvokeTransport,
38
+ ProfileConsentRequest,
39
+ ProfileLinkRequest,
40
+ } from "./types.js";
41
+
42
+ /**
43
+ * One semantic step of a turn. Field conventions:
44
+ *
45
+ * - `message.status` / `message.activeTool` are ABSENT (not null) when the
46
+ * frame implies no change — apply them only when present, so an unknown
47
+ * frame type leaves your state machine untouched (the hook's exact rule:
48
+ * only `tool.start`/`tool.done` ever move `activeTool`, and a text frame
49
+ * moving status to `responding` does NOT clear a lingering tool name).
50
+ * - `message.assistantText` is the full folded text of the turn so far —
51
+ * render it as-is on every event; there is no delta bookkeeping to do.
52
+ * - `message.agEvents` are the frame's validated AgJSON events (empty for
53
+ * bypass frames) — push them into your own cross-turn `Reducer` if you
54
+ * keep a block-preserving transcript, ignore them otherwise.
55
+ */
56
+ export type InvokeTurnEvent =
57
+ | { kind: "session"; threadId: string | null }
58
+ | {
59
+ kind: "message";
60
+ status?: Extract<AgentInvokeStatus, "thinking" | "using-tool" | "responding">;
61
+ activeTool?: string | null;
62
+ assistantText: string;
63
+ agEvents: AgEvent[];
64
+ }
65
+ | { kind: "error"; message: string; code: string | null }
66
+ | { kind: "profile-consent"; request: ProfileConsentRequest }
67
+ | { kind: "profile-link"; request: ProfileLinkRequest }
68
+ | { kind: "done"; stopReason: string | null };
69
+
70
+ /**
71
+ * Normalize an agent endpoint to its invoke URL (guuey#186 G3). Accepts BOTH
72
+ * shapes a consumer legitimately holds — a pod base (`https://host`) and the
73
+ * full invoke URL the deploy-controller records (`https://host/agent/invoke`)
74
+ * — and returns exactly one `/agent/invoke`, trailing slashes dropped. This
75
+ * is the single normalization `useAgentInvoke` applies to its `endpointUrl`;
76
+ * a host driving {@link invokeTurn} (or any raw transport) directly builds
77
+ * its request URL with the same call instead of re-implementing the rule.
78
+ */
79
+ export function toInvokeUrl(endpointUrl: string): string {
80
+ const base = endpointUrl.replace(/\/+$/, "");
81
+ return base.endsWith("/agent/invoke") ? base : `${base}/agent/invoke`;
82
+ }
83
+
84
+ /**
85
+ * Drive one `/agent/invoke` turn over `transport`, yielding semantic events.
86
+ * Pure per-turn: no React, no storage, no retry policy (the transport owns
87
+ * saturation retry), no reducer — see the module docblock for what belongs
88
+ * to the caller.
89
+ *
90
+ * The event stream is also the OBSERVATION channel (guuey#186 Gap 4): there
91
+ * is deliberately no `onToolResult` callback API, because filtering the
92
+ * generator expresses it directly — every tool result arrives as a typed
93
+ * `tool.done` AgEvent on a `message` event, carrying `toolCallId`,
94
+ * `content`, `outcome` and `structuredContent`.
95
+ *
96
+ * @example Telemetry off the fold — observe tool results without touching
97
+ * the transcript path:
98
+ * ```ts
99
+ * for await (const ev of invokeTurn(req, transport)) {
100
+ * if (ev.kind !== "message") continue;
101
+ * for (const agEvent of ev.agEvents) {
102
+ * if (agEvent.type === "tool.done") {
103
+ * telemetry.record(agEvent.toolCallId, agEvent.outcome ?? "ok");
104
+ * }
105
+ * }
106
+ * render(ev.assistantText); // the fold is untouched by the observation
107
+ * }
108
+ * ```
109
+ */
110
+ export async function* invokeTurn(
111
+ req: InvokeRequest,
112
+ transport: InvokeTransport,
113
+ ): AsyncGenerator<InvokeTurnEvent> {
114
+ let assistantText = "";
115
+ let buffer = "";
116
+ for await (const chunk of transport(req)) {
117
+ buffer += chunk;
118
+ const { events, rest } = parseSseEvents(buffer);
119
+ buffer = rest;
120
+ for (const ev of events) {
121
+ if (ev.event === "session") {
122
+ // The pod is awake and the turn is admitted (this frame arrives
123
+ // within ~1s of a warm pod; a cold scale-to-zero start is exactly
124
+ // the long wait before it).
125
+ yield { kind: "session", threadId: stringField(ev.data, "threadId") ?? null };
126
+ } else if (ev.event === "message") {
127
+ // Status derivation (guuey#91) — read the frame's `type` before the
128
+ // text fold. Silver frames announce tools + text explicitly; bypass
129
+ // frames ('text' / 'assistant' SDKMessages) only ever carry
130
+ // assistant text, so they map to 'responding'. Unknown types
131
+ // deliberately imply no status change.
132
+ const frameType = stringField(ev.data, "type");
133
+ assistantText = reduceAssistantText(assistantText, ev.data);
134
+ // Only VALID AgEvents surface (bypass frames ingest to []) — the
135
+ // caller's reducer, if any, advances on these alone.
136
+ const agEvents = ingestMessageFrame(ev.data);
137
+ if (frameType === "tool.start") {
138
+ yield {
139
+ kind: "message",
140
+ status: "using-tool",
141
+ activeTool: stringField(ev.data, "name") ?? null,
142
+ assistantText,
143
+ agEvents,
144
+ };
145
+ } else if (frameType === "tool.done") {
146
+ yield { kind: "message", status: "thinking", activeTool: null, assistantText, agEvents };
147
+ } else if (
148
+ frameType === "text.start" ||
149
+ frameType === "text.delta" ||
150
+ frameType === "text" ||
151
+ frameType === "assistant"
152
+ ) {
153
+ yield { kind: "message", status: "responding", assistantText, agEvents };
154
+ } else {
155
+ yield { kind: "message", assistantText, agEvents };
156
+ }
157
+ } else if (ev.event === "error") {
158
+ // In-band failure frame — one of the two channels that carry the
159
+ // pod's wire code (the other is the pre-stream refusal thrown by the
160
+ // transport). A frame without a `code` yields null rather than
161
+ // leaving a previous turn's code standing beside a new message.
162
+ yield {
163
+ kind: "error",
164
+ message: stringField(ev.data, "message") ?? "agent error",
165
+ code: stringField(ev.data, "code") ?? null,
166
+ };
167
+ } else if (ev.event === "profile-consent-needed") {
168
+ // Cross-app profile consent ask (T6). Only a well-formed payload
169
+ // yields; a malformed one is dropped, leaving any prior valid
170
+ // request untouched (never clobbered to null).
171
+ const parsed = parseConsentRequest(ev.data);
172
+ if (parsed) yield { kind: "profile-consent", request: parsed };
173
+ } else if (ev.event === "profile-link-needed") {
174
+ // Cross-app profile LINK invite (linkcoh T3) for an unlinked byo
175
+ // caller. Same drop-if-malformed contract as consent above.
176
+ const parsed = parseLinkRequest(ev.data);
177
+ if (parsed) yield { kind: "profile-link", request: parsed };
178
+ } else if (ev.event === "done") {
179
+ // The stream closes after this frame; yielded so a host can read the
180
+ // pod's stop reason without private wire knowledge.
181
+ yield { kind: "done", stopReason: stringField(ev.data, "stopReason") ?? null };
182
+ }
183
+ // Any other (unknown) event falls through silently — additive wire
184
+ // events never disturb a consumer.
185
+ }
186
+ }
187
+ }
package/src/react.ts CHANGED
@@ -6,7 +6,13 @@
6
6
  * history reader, and the web adapters). Consumers that only need those never
7
7
  * import React at all; consumers that render chat import the hook from here.
8
8
  */
9
- export { useAgentInvoke, applyHistoryResult, type HistoryApplication } from "./useAgentInvoke.js";
9
+ export {
10
+ useAgentInvoke,
11
+ applyHistoryResult,
12
+ type HistoryApplication,
13
+ stallProbeDecision,
14
+ STALL_RECOVERY_DEFAULTS,
15
+ } from "./useAgentInvoke.js";
10
16
  // The block-preserving transcript surfaces `AgReduceResult`; re-export it (and
11
17
  // `AgEvent`) here so `./react` consumers can type `reduceResult` without a
12
18
  // direct `@silverprotocol/core` import.
@@ -1,15 +1,24 @@
1
1
  /**
2
- * The single `POD_SATURATED` auto-retry, as a transport-agnostic wrapper.
2
+ * The invoke-refusal retry wrappers, transport-agnostic: the single
3
+ * `POD_SATURATED` auto-retry ({@link withSaturationRetry}) and the bounded
4
+ * cold-start 503 retry ({@link withColdStartRetry}).
3
5
  *
4
- * Its own module — rather than living inside `./web-adapters.ts`, where it was
5
- * born — because the behaviour is a property of the POD's refusal vocabulary,
6
- * not of `fetch`. Every host that speaks `/agent/invoke` wants it, including
7
- * the ones that cannot import the web adapter bundle: Portal's React-Native
8
- * transport wraps its own `fetch` call with {@link withSaturationRetry} the
6
+ * Their own module — rather than living inside `./web-adapters.ts`, where the
7
+ * first was born — because the behaviour is a property of the platform's
8
+ * refusal vocabulary, not of `fetch`. Every host that speaks `/agent/invoke`
9
+ * wants them, including the ones that cannot import the web adapter bundle:
10
+ * Portal's React-Native transport wraps its own `fetch` call with these the
9
11
  * same way `fetchStreamTransport` wraps its browser streaming reader, so the
10
12
  * two wear byte-identical retry semantics instead of two hand-written copies
11
13
  * that drift.
12
14
  *
15
+ * The two wrappers are DELIBERATELY distinct code paths: saturation retry is
16
+ * driven by the pod's structured refusal envelope (`code: POD_SATURATED`),
17
+ * while the cold-start retry matches only an envelope-LESS 503 — the raw
18
+ * infra answer (ingress with no ready pod) during the post-redeploy window,
19
+ * which by definition carries no wire code. They share the backoff machinery,
20
+ * never the predicate.
21
+ *
13
22
  * This module imports only `./types.js`, `./errors.js` and `./error-codes.js`
14
23
  * — all pure — so pulling it in costs a React-Native build nothing.
15
24
  */
@@ -148,3 +157,91 @@ export function withSaturationRetry(
148
157
  yield* transport(req);
149
158
  };
150
159
  }
160
+
161
+ /** Options for {@link withColdStartRetry}. */
162
+ export interface ColdStartRetryOptions {
163
+ /**
164
+ * Retries after the initial attempt (`0` disables the wrapper's behaviour
165
+ * entirely). Default 3 — a small, bounded budget: the point is parity with
166
+ * guuey's first-party embeds during the ordinary post-redeploy window, not
167
+ * riding out an outage. Raise it for an unattended harness that would
168
+ * rather wait than fail.
169
+ */
170
+ attempts?: number;
171
+ /**
172
+ * First wait in ms; each subsequent wait doubles, capped at
173
+ * {@link maxDelayMs}. Default 2000 → 2s / 4s / 8s for the default budget.
174
+ */
175
+ baseDelayMs?: number;
176
+ /** Ceiling on any single wait (hinted or computed), in ms. Default 10000. */
177
+ maxDelayMs?: number;
178
+ /** The wait itself — injectable so tests drive the retry without timers. */
179
+ sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
180
+ }
181
+
182
+ const COLD_START_DEFAULT_ATTEMPTS = 3;
183
+ const COLD_START_BASE_DELAY_MS = 2_000;
184
+ const COLD_START_MAX_DELAY_MS = 10_000;
185
+
186
+ /**
187
+ * Is this failure the cold-start refusal shape? An envelope-less 503: the
188
+ * status came from infra (no ready pod behind the route — the ~30–60s window
189
+ * after a redeploy), so there is no wire `code`. A 503 that DOES carry a code
190
+ * is the pod itself refusing (`POD_SATURATED`, `DRAINING`) and belongs to
191
+ * {@link withSaturationRetry}'s policy — including its deliberate decision NOT
192
+ * to retry `DRAINING` — never to this wrapper.
193
+ */
194
+ function isColdStartRefusal(err: unknown): err is AgentResponseError {
195
+ return err instanceof AgentResponseError && err.status === 503 && err.code === undefined;
196
+ }
197
+
198
+ /**
199
+ * Wrap an invoke transport with a bounded retry on cold-start 503s
200
+ * (guuey#186 Gap 3 — parity with first-party embeds, which already carry
201
+ * this behaviour; SDK consumers were eating the raw 503 window instead).
202
+ *
203
+ * Matches ONLY {@link isColdStartRefusal} — an envelope-less 503 — and
204
+ * retries up to `attempts` times with doubling, capped backoff (honouring a
205
+ * `Retry-After` hint when the response carried one). Exhaustion propagates
206
+ * the final refusal untouched.
207
+ *
208
+ * Nothing is retried once a chunk has been yielded: a stream that dies
209
+ * MID-turn is never silently re-POSTed — the turn may have had side effects
210
+ * and the consumer already saw partial output. Same `yielded` guard as
211
+ * {@link withSaturationRetry}, same reasoning. An abort during a wait
212
+ * surfaces the refusal that caused the wait.
213
+ *
214
+ * Like the saturation wrapper, the retry is invisible to `useAgentInvoke`
215
+ * (the turn stays in `connecting`), and the wrapped transport is re-invoked
216
+ * from scratch so per-attempt identity resolution re-runs.
217
+ */
218
+ export function withColdStartRetry(
219
+ transport: InvokeTransport,
220
+ options: ColdStartRetryOptions = {},
221
+ ): InvokeTransport {
222
+ const attempts = options.attempts ?? COLD_START_DEFAULT_ATTEMPTS;
223
+ const baseDelayMs = options.baseDelayMs ?? COLD_START_BASE_DELAY_MS;
224
+ const maxDelayMs = options.maxDelayMs ?? COLD_START_MAX_DELAY_MS;
225
+ const sleep = options.sleep ?? delay;
226
+ return async function* retrying(req: InvokeRequest): AsyncGenerator<string> {
227
+ let yielded = false;
228
+ for (let attempt = 0; ; attempt++) {
229
+ try {
230
+ for await (const chunk of transport(req)) {
231
+ yielded = true;
232
+ yield chunk;
233
+ }
234
+ return;
235
+ } catch (err) {
236
+ if (!isColdStartRefusal(err) || yielded || attempt >= attempts) throw err;
237
+ const hintedMs =
238
+ err.retryAfterSeconds !== undefined ? err.retryAfterSeconds * 1000 : undefined;
239
+ const waitMs = Math.min(hintedMs ?? baseDelayMs * 2 ** attempt, maxDelayMs);
240
+ await sleep(waitMs, req.signal);
241
+ // Aborted mid-wait: surface the refusal that caused the wait rather
242
+ // than spending a request that `fetch` would reject on the signal.
243
+ if (req.signal.aborted) throw err;
244
+ }
245
+ }
246
+ };
247
+ }