@anthropic-ai/sdk 0.101.0 → 0.103.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.
Files changed (152) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/client.d.mts +35 -2
  3. package/client.d.mts.map +1 -1
  4. package/client.d.ts +35 -2
  5. package/client.d.ts.map +1 -1
  6. package/client.js +74 -24
  7. package/client.js.map +1 -1
  8. package/client.mjs +73 -23
  9. package/client.mjs.map +1 -1
  10. package/core/middleware.d.mts +42 -5
  11. package/core/middleware.d.mts.map +1 -1
  12. package/core/middleware.d.ts +42 -5
  13. package/core/middleware.d.ts.map +1 -1
  14. package/core/middleware.js +14 -7
  15. package/core/middleware.js.map +1 -1
  16. package/core/middleware.mjs +14 -7
  17. package/core/middleware.mjs.map +1 -1
  18. package/core/streaming.d.mts +9 -0
  19. package/core/streaming.d.mts.map +1 -1
  20. package/core/streaming.d.ts +9 -0
  21. package/core/streaming.d.ts.map +1 -1
  22. package/core/streaming.js +11 -0
  23. package/core/streaming.js.map +1 -1
  24. package/core/streaming.mjs +11 -0
  25. package/core/streaming.mjs.map +1 -1
  26. package/index.d.mts +1 -0
  27. package/index.d.mts.map +1 -1
  28. package/index.d.ts +1 -0
  29. package/index.d.ts.map +1 -1
  30. package/index.js +4 -1
  31. package/index.js.map +1 -1
  32. package/index.mjs +1 -0
  33. package/index.mjs.map +1 -1
  34. package/internal/parse.d.mts.map +1 -1
  35. package/internal/parse.d.ts.map +1 -1
  36. package/internal/parse.js +0 -3
  37. package/internal/parse.js.map +1 -1
  38. package/internal/parse.mjs +0 -3
  39. package/internal/parse.mjs.map +1 -1
  40. package/internal/request-options.d.mts +46 -3
  41. package/internal/request-options.d.mts.map +1 -1
  42. package/internal/request-options.d.ts +46 -3
  43. package/internal/request-options.d.ts.map +1 -1
  44. package/internal/request-options.js +12 -1
  45. package/internal/request-options.js.map +1 -1
  46. package/internal/request-options.mjs +10 -0
  47. package/internal/request-options.mjs.map +1 -1
  48. package/internal/utils/log.d.mts +11 -1
  49. package/internal/utils/log.d.mts.map +1 -1
  50. package/internal/utils/log.d.ts +11 -1
  51. package/internal/utils/log.d.ts.map +1 -1
  52. package/internal/utils/log.js +34 -9
  53. package/internal/utils/log.js.map +1 -1
  54. package/internal/utils/log.mjs +32 -8
  55. package/internal/utils/log.mjs.map +1 -1
  56. package/lib/BetaMessageStream.d.mts.map +1 -1
  57. package/lib/BetaMessageStream.d.ts.map +1 -1
  58. package/lib/BetaMessageStream.js +5 -0
  59. package/lib/BetaMessageStream.js.map +1 -1
  60. package/lib/BetaMessageStream.mjs +5 -0
  61. package/lib/BetaMessageStream.mjs.map +1 -1
  62. package/lib/middleware.d.mts +96 -0
  63. package/lib/middleware.d.mts.map +1 -0
  64. package/lib/middleware.d.ts +96 -0
  65. package/lib/middleware.d.ts.map +1 -0
  66. package/lib/middleware.js +703 -0
  67. package/lib/middleware.js.map +1 -0
  68. package/lib/middleware.mjs +698 -0
  69. package/lib/middleware.mjs.map +1 -0
  70. package/lib/tools/BetaToolRunner.d.mts +1 -1
  71. package/lib/tools/BetaToolRunner.d.mts.map +1 -1
  72. package/lib/tools/BetaToolRunner.d.ts +1 -1
  73. package/lib/tools/BetaToolRunner.d.ts.map +1 -1
  74. package/lib/tools/BetaToolRunner.js +10 -2
  75. package/lib/tools/BetaToolRunner.js.map +1 -1
  76. package/lib/tools/BetaToolRunner.mjs +10 -2
  77. package/lib/tools/BetaToolRunner.mjs.map +1 -1
  78. package/package.json +1 -1
  79. package/resources/beta/agents/agents.d.mts +12 -22
  80. package/resources/beta/agents/agents.d.mts.map +1 -1
  81. package/resources/beta/agents/agents.d.ts +12 -22
  82. package/resources/beta/agents/agents.d.ts.map +1 -1
  83. package/resources/beta/agents/agents.js.map +1 -1
  84. package/resources/beta/agents/agents.mjs.map +1 -1
  85. package/resources/beta/beta.d.mts +3 -3
  86. package/resources/beta/beta.d.mts.map +1 -1
  87. package/resources/beta/beta.d.ts +3 -3
  88. package/resources/beta/beta.d.ts.map +1 -1
  89. package/resources/beta/beta.js.map +1 -1
  90. package/resources/beta/beta.mjs.map +1 -1
  91. package/resources/beta/index.d.mts +1 -1
  92. package/resources/beta/index.d.mts.map +1 -1
  93. package/resources/beta/index.d.ts +1 -1
  94. package/resources/beta/index.d.ts.map +1 -1
  95. package/resources/beta/index.js.map +1 -1
  96. package/resources/beta/index.mjs.map +1 -1
  97. package/resources/beta/messages/batches.d.mts +28 -0
  98. package/resources/beta/messages/batches.d.mts.map +1 -1
  99. package/resources/beta/messages/batches.d.ts +28 -0
  100. package/resources/beta/messages/batches.d.ts.map +1 -1
  101. package/resources/beta/messages/index.d.mts +1 -1
  102. package/resources/beta/messages/index.d.mts.map +1 -1
  103. package/resources/beta/messages/index.d.ts +1 -1
  104. package/resources/beta/messages/index.d.ts.map +1 -1
  105. package/resources/beta/messages/index.js.map +1 -1
  106. package/resources/beta/messages/index.mjs.map +1 -1
  107. package/resources/beta/messages/messages.d.mts +247 -8
  108. package/resources/beta/messages/messages.d.mts.map +1 -1
  109. package/resources/beta/messages/messages.d.ts +247 -8
  110. package/resources/beta/messages/messages.d.ts.map +1 -1
  111. package/resources/beta/messages/messages.js +7 -0
  112. package/resources/beta/messages/messages.js.map +1 -1
  113. package/resources/beta/messages/messages.mjs +7 -0
  114. package/resources/beta/messages/messages.mjs.map +1 -1
  115. package/resources/beta/models.d.mts +6 -0
  116. package/resources/beta/models.d.mts.map +1 -1
  117. package/resources/beta/models.d.ts +6 -0
  118. package/resources/beta/models.d.ts.map +1 -1
  119. package/resources/beta/webhooks.d.mts +22 -22
  120. package/resources/beta/webhooks.d.ts +22 -22
  121. package/resources/messages/messages.d.mts +3 -2
  122. package/resources/messages/messages.d.mts.map +1 -1
  123. package/resources/messages/messages.d.ts +3 -2
  124. package/resources/messages/messages.d.ts.map +1 -1
  125. package/resources/messages/messages.js +1 -0
  126. package/resources/messages/messages.js.map +1 -1
  127. package/resources/messages/messages.mjs +1 -0
  128. package/resources/messages/messages.mjs.map +1 -1
  129. package/src/client.ts +92 -27
  130. package/src/core/middleware.ts +53 -7
  131. package/src/core/streaming.ts +15 -0
  132. package/src/index.ts +6 -0
  133. package/src/internal/parse.ts +0 -4
  134. package/src/internal/request-options.ts +48 -3
  135. package/src/internal/utils/log.ts +39 -9
  136. package/src/lib/BetaMessageStream.ts +5 -0
  137. package/src/lib/middleware.ts +937 -0
  138. package/src/lib/tools/BetaToolRunner.ts +12 -3
  139. package/src/resources/beta/agents/agents.ts +13 -21
  140. package/src/resources/beta/beta.ts +15 -1
  141. package/src/resources/beta/index.ts +6 -0
  142. package/src/resources/beta/messages/batches.ts +30 -0
  143. package/src/resources/beta/messages/index.ts +6 -0
  144. package/src/resources/beta/messages/messages.ts +296 -7
  145. package/src/resources/beta/models.ts +7 -0
  146. package/src/resources/beta/webhooks.ts +22 -22
  147. package/src/resources/messages/messages.ts +6 -1
  148. package/src/version.ts +1 -1
  149. package/version.d.mts +1 -1
  150. package/version.d.ts +1 -1
  151. package/version.js +1 -1
  152. package/version.mjs +1 -1
@@ -0,0 +1,937 @@
1
+ import type { APIRequest } from '../core/api';
2
+ import { AnthropicError } from '../core/error';
3
+ import type { Middleware, MiddlewareContext, MiddlewareNext } from '../core/middleware';
4
+ import { Stream, type ServerSentEvent } from '../core/streaming';
5
+ import { isAbortError } from '../internal/errors';
6
+ import { safeJSON } from '../internal/utils/values';
7
+ import type { AnthropicBeta } from '../resources/beta/beta';
8
+ import type {
9
+ BetaContentBlockParam,
10
+ BetaFallbackBlock,
11
+ BetaFallbackMessageIterationUsage,
12
+ BetaFallbackParam,
13
+ BetaMessage,
14
+ BetaMessageDeltaUsage,
15
+ BetaMessageIterationUsage,
16
+ BetaRawContentBlockDeltaEvent,
17
+ BetaRawContentBlockStartEvent,
18
+ BetaRawContentBlockStopEvent,
19
+ BetaRawMessageDeltaEvent,
20
+ BetaRawMessageStopEvent,
21
+ BetaRawMessageStreamEvent,
22
+ BetaRefusalStopDetails,
23
+ BetaUsage,
24
+ MessageCreateParams,
25
+ } from '../resources/beta/messages/messages';
26
+
27
+ export { BetaFallbackState } from '../internal/request-options';
28
+
29
+ const encoder = new TextEncoder();
30
+
31
+ /** Betas sent by default; override with {@link BetaRefusalFallbackOptions.betas}. */
32
+ const DEFAULT_BETAS: readonly AnthropicBeta[] = ['fallback-credit-2026-06-01'];
33
+
34
+ /**
35
+ * Remove `fallback` blocks replayed in history. They only parse under the
36
+ * server-side fallback beta, which belongs to the caller-owned server-side
37
+ * `fallbacks` feature — this middleware never sends it, so a request
38
+ * replaying them would 400. An assistant turn left empty is dropped whole.
39
+ */
40
+ function stripFallbackBlocks(body: MessageCreateParams): MessageCreateParams {
41
+ const messages = body.messages
42
+ .map((message) =>
43
+ Array.isArray(message.content) ?
44
+ { ...message, content: message.content.filter((block) => block.type !== 'fallback') }
45
+ : message,
46
+ )
47
+ .filter((message) => !Array.isArray(message.content) || message.content.length > 0);
48
+ return { ...body, messages };
49
+ }
50
+
51
+ /** Why {@link BetaRefusalFallbackOptions.onError} fired. */
52
+ export type BetaRefusalFallbackError =
53
+ | {
54
+ /** The refusal carries no `fallback_credit_token`, so it can't be retried. */
55
+ kind: 'no_credit_token';
56
+ message: string;
57
+ /** The refusal `message_delta` event, verbatim. */
58
+ event: BetaRawMessageDeltaEvent;
59
+ }
60
+ | {
61
+ /** The stream refused but every fallback entry has been used up. */
62
+ kind: 'chain_exhausted';
63
+ message: string;
64
+ /** The refusal `message_delta` event, verbatim. */
65
+ event: BetaRawMessageDeltaEvent;
66
+ }
67
+ | {
68
+ /** A streaming fallback request failed; the hop was skipped. */
69
+ kind: 'request_failed';
70
+ message: string;
71
+ /** The fallback model whose request failed. */
72
+ model: string;
73
+ /** The HTTP status, or `null` when the request threw instead of resolving. */
74
+ status: number | null;
75
+ /** The parsed error body, or the thrown error when `status` is `null`. */
76
+ detail: unknown;
77
+ };
78
+
79
+ export interface BetaRefusalFallbackOptions {
80
+ /**
81
+ * Betas added to the `anthropic-beta` header of every `/v1/messages`
82
+ * request this middleware handles — the original request included, since
83
+ * refusals only carry a `fallback_credit_token` when the beta is enabled.
84
+ * Defaults to `['fallback-credit-2026-06-01']`; pass `[]` to send none.
85
+ */
86
+ betas?: readonly AnthropicBeta[] | undefined;
87
+
88
+ /**
89
+ * Called when a refusal is surfaced to the client rather than retried —
90
+ * it carries no `fallback_credit_token`, no fallback entries remain, or a
91
+ * streaming fallback request failed. Discriminate on `error.kind`.
92
+ * Defaults to logging through the client logger.
93
+ */
94
+ onError?: ((error: BetaRefusalFallbackError) => void) | undefined;
95
+ }
96
+
97
+ /**
98
+ * Middleware that retries refused `/v1/messages` requests down a fallback chain.
99
+ *
100
+ * Non-streaming: when a response comes back with `stop_reason: 'refusal'`, the
101
+ * request is retried with each entry of `fallbacks` merged over the original
102
+ * params — passing along the refusal's `fallback_credit_token` — until a model
103
+ * accepts or the chain is exhausted. A message served by a fallback carries a
104
+ * `fallback` content block prepended at each model boundary — the same seam
105
+ * block shape the server-side `fallbacks` param places in `content`, though
106
+ * the rest of the envelope is the serving hop's as returned (see the
107
+ * known-divergences note below); an exhausted chain surfaces the final
108
+ * refusal verbatim.
109
+ *
110
+ * Streaming: when the stream ends in `stop_reason: 'refusal'`, a second
111
+ * request is issued to the fallback model — carrying the refused model's
112
+ * partial output as a trailing assistant prefill when the refusal grants one
113
+ * (`fallback_has_prefill_claim`), plus the refusal's `fallback_credit_token`
114
+ * — and the fallback's events are spliced onto the
115
+ * still-open stream, so the client sees one continuous message in the
116
+ * server-side `fallbacks` wire shape: a `fallback` content block at each model
117
+ * boundary, monotonic block indices, and per-hop `usage.iterations` on the
118
+ * final `message_delta`. Only `model` is honored from each entry on this path:
119
+ * the credit token is redeemable only against the refused request's body, so
120
+ * the other per-entry overrides (`max_tokens`, `thinking`, ...) would be
121
+ * rejected.
122
+ *
123
+ * The fallback-credit beta the credit tokens require is sent by default on
124
+ * every request the middleware handles; the `betas` option controls this.
125
+ *
126
+ * In both modes a fallback that itself refuses with a fresh credit token
127
+ * continues down the chain. A streaming fallback whose prefill the server
128
+ * rejects (HTTP 400) is retried once without it; a fallback whose request
129
+ * fails outright is skipped — its token was never redeemed, so it carries to
130
+ * the next entry.
131
+ *
132
+ * To keep later requests on the model that accepted, pass a
133
+ * {@link BetaFallbackState} via the `fallbackState` request option; requests
134
+ * sharing that state start directly at the pinned fallback. Reuse one state
135
+ * across whatever scope the pin should apply to — typically a conversation.
136
+ *
137
+ * @example
138
+ * ```ts
139
+ * const client = new Anthropic({
140
+ * middleware: [betaRefusalFallbackMiddleware([{ model: 'claude-opus-4-8' }])],
141
+ * });
142
+ *
143
+ * const fallbackState = new BetaFallbackState();
144
+ * const message = await client.beta.messages.create(params, { fallbackState });
145
+ * ```
146
+ */
147
+ export function betaRefusalFallbackMiddleware(
148
+ fallbacks: readonly BetaFallbackParam[],
149
+ options: BetaRefusalFallbackOptions = {},
150
+ ): Middleware {
151
+ let warnedMissingState = false;
152
+
153
+ return async (request, next, ctx) => {
154
+ // This middleware only applies to the beta messages API
155
+ // (`client.beta.messages`, which posts to `/v1/messages?beta=true`).
156
+ // An empty chain also disables this middleware.
157
+ const [path, query] = (ctx.options?.path ?? '').split('?');
158
+ if (
159
+ fallbacks.length === 0 ||
160
+ ctx.options?.method !== 'post' ||
161
+ path !== '/v1/messages' ||
162
+ new URLSearchParams(query).get('beta') !== 'true' ||
163
+ typeof ctx.options.body !== 'object' ||
164
+ ctx.options.body == null
165
+ ) {
166
+ return next(request);
167
+ }
168
+
169
+ if ((ctx.options.body as MessageCreateParams).fallbacks != null) {
170
+ throw new AnthropicError(
171
+ 'Sending the `fallbacks:` request param is not supported when using the `betaRefusalFallbackMiddleware`. ' +
172
+ 'You should either remove the middleware and send `fallbacks:` with the `server-side-fallback-2026-06-01` beta header to let the API handle refusal fallbacks, ' +
173
+ "or omit the `fallbacks:` param if you'd like `betaRefusalFallbackMiddleware` to handle fallbacks on the client side.",
174
+ );
175
+ }
176
+
177
+ const onError =
178
+ options.onError ??
179
+ ((error: BetaRefusalFallbackError) =>
180
+ ctx.logger.error(`anthropic-sdk: betaRefusalFallbackMiddleware: ${error.message}`));
181
+
182
+ // Send the configured betas on this and every hop request derived from it.
183
+ request = appendBetas(request, options.betas ?? DEFAULT_BETAS);
184
+
185
+ const body = stripFallbackBlocks(ctx.options.body as MessageCreateParams);
186
+ const state = ctx.options.fallbackState;
187
+
188
+ // start from the pinned fallback (-1 = the original params)
189
+ const startIndex = state?.index ?? -1;
190
+ if (!Number.isInteger(startIndex) || startIndex < -1 || startIndex >= fallbacks.length) {
191
+ throw new AnthropicError(
192
+ `fallbackState.index ${startIndex} is out of bounds for a chain of ${fallbacks.length} fallback(s); was the state shared with a different middleware?`,
193
+ );
194
+ }
195
+
196
+ // pin requests sharing the state to the entry being tried
197
+ const pin = (index: number) => {
198
+ if (state) {
199
+ state.index = index;
200
+ } else if (!warnedMissingState) {
201
+ warnedMissingState = true;
202
+ ctx.logger.warn(
203
+ 'anthropic-sdk: betaRefusalFallbackMiddleware fell back without a `fallbackState` request option; follow-up requests will retry models that already refused. Pass a shared `{ fallbackState: new BetaFallbackState() }` to pin them to the accepted model.',
204
+ );
205
+ }
206
+ };
207
+
208
+ // a non-string body can't be respliced or redeemed against — leave the
209
+ // request untouched (the streaming path stands down on it below too)
210
+ const initialRequest =
211
+ typeof request.body !== 'string' ?
212
+ request
213
+ : {
214
+ ...request,
215
+ body: JSON.stringify(startIndex === -1 ? body : { ...body, ...fallbacks[startIndex] }),
216
+ };
217
+
218
+ const response = await next(initialRequest);
219
+ if (!response.ok) {
220
+ return response;
221
+ }
222
+
223
+ if (ctx.options.stream === true) {
224
+ const firstHop = startIndex + 1;
225
+ // Splicing needs at least one entry left to hop to and the JSON request
226
+ // body the credit token is redeemable against (an earlier middleware
227
+ // may have rewritten it to another BodyInit); otherwise the stream
228
+ // passes through untouched.
229
+ if (firstHop >= fallbacks.length || typeof initialRequest.body !== 'string') {
230
+ return response;
231
+ }
232
+ return spliceFallbackStream({
233
+ request: initialRequest,
234
+ response,
235
+ next,
236
+ ctx,
237
+ fallbacks,
238
+ firstHop,
239
+ onError,
240
+ pin,
241
+ });
242
+ }
243
+
244
+ let index = startIndex;
245
+ let res = response;
246
+ // The model the current hop was requested as — the caller's spelling, not
247
+ // the server's `message.model` echo; the seam block's `from` carries it.
248
+ let requestedModel = (startIndex === -1 ? body : { ...body, ...fallbacks[startIndex] }).model;
249
+ const fallbackBlocks: BetaFallbackBlock[] = [];
250
+ while (index < fallbacks.length - 1) {
251
+ const message = await ctx.parse<BetaMessage | null>(res);
252
+ if (message?.type !== 'message' || message.stop_reason !== 'refusal') {
253
+ break;
254
+ }
255
+
256
+ index += 1;
257
+ pin(index);
258
+ const entry = fallbacks[index]!;
259
+ // One `fallback` seam block per model boundary, prepended to the serving
260
+ // hop's content below — the same block shape the server places in
261
+ // `content`, not a claim of full envelope parity.
262
+ fallbackBlocks.push({
263
+ type: 'fallback',
264
+ // `requestedModel` is always set for a typed body; the `??` defends
265
+ // against an untyped body that carried no `model` field.
266
+ from: { model: requestedModel ?? message.model },
267
+ to: { model: entry.model },
268
+ });
269
+ requestedModel = entry.model;
270
+ res = await next({
271
+ ...request,
272
+ body: JSON.stringify({
273
+ ...body,
274
+ ...entry,
275
+ ...(message.stop_details?.fallback_credit_token ?
276
+ { fallback_credit_token: message.stop_details.fallback_credit_token }
277
+ : undefined),
278
+ }),
279
+ });
280
+ }
281
+
282
+ if (fallbackBlocks.length === 0) {
283
+ return res;
284
+ }
285
+ const served = await ctx.parse<BetaMessage | null>(res);
286
+ // Chain exhausted on a refusal (or an error/malformed body): surface it
287
+ // verbatim. The array guard keeps a message-shaped body with non-array
288
+ // `content` from throwing at the spread below.
289
+ if (served?.type !== 'message' || served.stop_reason === 'refusal' || !Array.isArray(served.content)) {
290
+ return res;
291
+ }
292
+ // A fallback hop served (or exhausted the chain with output): prepend the
293
+ // seam blocks so the app-visible `content` opens with one `fallback` block
294
+ // per model boundary. Response init is preserved (same `_request_id`);
295
+ // `content-length` is dropped since the body grew.
296
+ const headers = new Headers(res.headers);
297
+ headers.delete('content-length');
298
+ return new Response(JSON.stringify({ ...served, content: [...fallbackBlocks, ...served.content] }), {
299
+ status: res.status,
300
+ statusText: res.statusText,
301
+ headers,
302
+ });
303
+ };
304
+ }
305
+
306
+ // --- streaming fallback (credit-token continuation) -------------------------
307
+ //
308
+ // The retry uses the appended-assistant form documented on
309
+ // `fallback_credit_token`: the refused request's body, extended by one
310
+ // trailing assistant turn carrying the refused model's partial output. The
311
+ // token authorizes that turn as a prefill continuation and applies the
312
+ // fallback credit. The refusal's `fallback_has_prefill_claim` says whether
313
+ // the partial output may be resent verbatim: when true the accumulated
314
+ // blocks are appended as-is; when false the refused hop's output is dropped
315
+ // and the token is redeemed against the same body.
316
+ //
317
+ // Known divergences from server-side `fallbacks` (applies to both paths):
318
+ //
319
+ // * Seam `to.model` and non-first `from.model` carry the chain entry's
320
+ // spelling, not the canonical id the server emits.
321
+ // * Streaming: `message.model` keeps the refused model's id — `message_start`
322
+ // has already been sent when the refusal arrives; the seam's `to.model`
323
+ // carries the serving model.
324
+ // * Streaming: `usage.iterations` survives stream accumulation only on the
325
+ // beta surface (`client.beta.messages.stream`); the non-beta accumulator
326
+ // drops it. Non-streaming: no `fallback_message` entry is synthesized in
327
+ // `usage.iterations` — the serving hop's `usage` passes through as-is.
328
+ // * Streaming: refusal text streamed before the refusal stays in the message
329
+ // and is resent as-is (the appended turn must match the partial output
330
+ // verbatim). Non-streaming: a refused hop's partial content is dropped.
331
+ // * First-seam `from.model` differs by path: non-streaming uses the caller's
332
+ // body spelling; streaming uses the server's `message.model` echo.
333
+
334
+ interface FallbackStreamArgs {
335
+ /** The request stream A was made with — the body its credit token is redeemable against. */
336
+ request: APIRequest;
337
+ /** Stream A: the OK SSE response that may end in a refusal. */
338
+ response: Response;
339
+ next: MiddlewareNext;
340
+ ctx: MiddlewareContext;
341
+ fallbacks: readonly BetaFallbackParam[];
342
+ /** Index into `fallbacks` of the first entry to try when stream A refuses. */
343
+ firstHop: number;
344
+ onError: (error: BetaRefusalFallbackError) => void;
345
+ /** Pin shared state to the entry being tried (or warn that there is none). */
346
+ pin: (index: number) => void;
347
+ }
348
+
349
+ /**
350
+ * Wrap stream A in a response whose body passes events through until a
351
+ * retryable refusal, then splices the fallback chain's events on (see
352
+ * {@link splicedEvents}). Cancelling the returned body tears down whichever
353
+ * stream is being read and aborts any in-flight fallback request or retry
354
+ * backoff: hop requests run under `controller`'s signal, which fires on
355
+ * cancel and mirrors the original request's signal — a user abort has no
356
+ * other way to reach a hop, since this synthetic body isn't fetch-backed.
357
+ */
358
+ function spliceFallbackStream(args: FallbackStreamArgs): Response {
359
+ const controller = new AbortController();
360
+ const signal = args.request.signal;
361
+ if (signal?.aborted) {
362
+ controller.abort(signal.reason);
363
+ } else {
364
+ signal?.addEventListener('abort', makeAbort(controller, signal), { once: true });
365
+ }
366
+ const iter = splicedEvents(args, controller);
367
+ const body = new ReadableStream<Uint8Array>({
368
+ async pull(ctrl) {
369
+ try {
370
+ const { value, done } = await iter.next();
371
+ if (done) return ctrl.close();
372
+ ctrl.enqueue(value);
373
+ } catch (err) {
374
+ ctrl.error(err);
375
+ }
376
+ },
377
+ async cancel() {
378
+ controller.abort();
379
+ await iter.return?.(undefined);
380
+ },
381
+ });
382
+ return new Response(body, args.response);
383
+ }
384
+
385
+ /** A response content block being accumulated from its streaming deltas. */
386
+ type AccumulatedBlock = { index: number; block: any };
387
+
388
+ async function* splicedEvents(
389
+ { request, response, next, ctx, fallbacks, firstHop, onError, pin }: FallbackStreamArgs,
390
+ controller: AbortController,
391
+ ): AsyncGenerator<Uint8Array> {
392
+ // --- stream A: pass through until a chainable refusal ---
393
+ const a = yield* consumeHop({
394
+ response,
395
+ controller,
396
+ indexBase: 0,
397
+ hasNext: true, // the caller guarantees firstHop < fallbacks.length
398
+ onError,
399
+ splice: null,
400
+ });
401
+ if (!a.refused) return; // non-refusal or not-retryable: pure pass-through.
402
+
403
+ // --- fallback chain: try each entry in order ---
404
+ // `base` is the assistant-turn content the current token's request already
405
+ // carried — the token is redeemable only with it resent verbatim. `partial`
406
+ // is the newest refused hop's output, included only when its refusal
407
+ // granted a prefill claim (any other change to the body is a 400).
408
+ let nextIndex = a.nextIndex; // monotonic block index across all spliced streams
409
+ let token = a.refused.token;
410
+ let base: BetaContentBlockParam[] = [];
411
+ let partial = a.refused.hasPrefillClaim ? toPrefillBlocks(a.blocks) : [];
412
+ let fromModel = a.model ?? '';
413
+ let lastUsage: BetaMessageDeltaUsage | null = a.refused.usage;
414
+ // The refusal whose token is currently in flight — surfaced verbatim (with a
415
+ // recommended_model added) if every fallback request fails and we degrade.
416
+ let refusalDetails = a.refused.stopDetails;
417
+
418
+ // One `message` entry per refused hop, in order — A first. Failed hops are
419
+ // skipped (no usage came back); the serving hop is appended as
420
+ // `fallback_message` when its message_delta arrives.
421
+ const iterations: BetaMessageIterationUsage[] = [
422
+ toIterationUsage('message', a.model ?? '', a.refused.usage),
423
+ ];
424
+
425
+ for (let hop = firstHop; hop < fallbacks.length; hop++) {
426
+ const model = fallbacks[hop]!.model;
427
+ const hasNext = hop + 1 < fallbacks.length;
428
+ pin(hop);
429
+
430
+ // --- boundary: a `fallback` content block at the next monotonic index ---
431
+ // Emitted before the request, so a hop that fails leaves its boundary in
432
+ // place and the next attempt emits its own (still `from: fromModel` — the
433
+ // last model that contributed output).
434
+ const fbIndex = nextIndex++;
435
+ yield emit<BetaRawContentBlockStartEvent>('content_block_start', {
436
+ type: 'content_block_start',
437
+ index: fbIndex,
438
+ content_block: { type: 'fallback', from: { model: fromModel }, to: { model } },
439
+ });
440
+ yield emit<BetaRawContentBlockStopEvent>('content_block_stop', {
441
+ type: 'content_block_stop',
442
+ index: fbIndex,
443
+ });
444
+
445
+ // --- build the request: appended-assistant continuation ---
446
+ // First attempt carries the newest partial appended (when its refusal
447
+ // granted a prefill claim); a 400 on that form means the server rejected
448
+ // the prefill, so the hop is retried once without it — the same-body
449
+ // form the token always supports.
450
+ let continuation = [...base, ...partial];
451
+ let resB: Response | null = null;
452
+ let failure: BetaRefusalFallbackError | null = null;
453
+ for (let attempt = 0; attempt < 2; attempt++) {
454
+ const reqB = buildFallbackRequest(request, { model, creditToken: token, continuation });
455
+ // controller mirrors the original signal and additionally fires when the
456
+ // spliced body is cancelled — either must abort an in-flight hop request.
457
+ reqB.signal = controller.signal;
458
+
459
+ try {
460
+ resB = await next(reqB);
461
+ } catch (err) {
462
+ // the consumer cancelled (or the original request was aborted): unwind
463
+ if (isAbortError(err)) throw err;
464
+ failure = {
465
+ kind: 'request_failed',
466
+ message: `fallback request failed: ${err}`,
467
+ model,
468
+ status: null,
469
+ detail: err,
470
+ };
471
+ break;
472
+ }
473
+ if (resB.ok) break;
474
+ // ctx.parse reads through an internal clone, so it works even though
475
+ // the client will also read this body; resB.text() would conflict.
476
+ const errBody = await ctx.parse(resB).catch(() => null);
477
+ if (attempt === 0 && resB.status === 400 && partial.length) {
478
+ ctx.logger.warn(
479
+ `anthropic-sdk: betaRefusalFallbackMiddleware: fallback request with the partial output appended was rejected (HTTP 400: ${JSON.stringify(
480
+ errBody,
481
+ )}); retrying without it`,
482
+ );
483
+ continuation = base;
484
+ resB = null;
485
+ continue;
486
+ }
487
+ failure = {
488
+ kind: 'request_failed',
489
+ message: `fallback request failed: HTTP ${resB.status}: ${JSON.stringify(errBody)}`,
490
+ model,
491
+ status: resB.status,
492
+ detail: errBody,
493
+ };
494
+ break;
495
+ }
496
+
497
+ if (failure) {
498
+ onError(failure);
499
+ // The token was never redeemed — retry it against the next entry.
500
+ if (hasNext) continue;
501
+ // Surface the held refusal verbatim — its category/explanation and the
502
+ // still-unredeemed credit token — and point recommended_model at the hop
503
+ // we last tried.
504
+ const stopDetails: BetaRefusalStopDetails = {
505
+ ...refusalDetails,
506
+ recommended_model: model,
507
+ };
508
+ yield emit<BetaRawMessageDeltaEvent>('message_delta', {
509
+ type: 'message_delta',
510
+ context_management: null,
511
+ delta: {
512
+ stop_reason: 'refusal',
513
+ stop_sequence: null,
514
+ container: null,
515
+ stop_details: stopDetails,
516
+ },
517
+ usage: (lastUsage ?? {}) as BetaMessageDeltaUsage,
518
+ });
519
+ yield emit<BetaRawMessageStopEvent>('message_stop', { type: 'message_stop' });
520
+ return;
521
+ }
522
+
523
+ // --- splice: monotonic indices, suppressed message_start, usage.iterations ---
524
+ const b = yield* consumeHop({
525
+ response: resB!,
526
+ controller,
527
+ indexBase: nextIndex,
528
+ hasNext,
529
+ onError,
530
+ splice: { iterations, model },
531
+ });
532
+ if (!b.refused) return;
533
+
534
+ // This hop refused too, with a fresh token: its emitted partial stays in
535
+ // the client's message, becomes the next partial segment, and the chain
536
+ // continues.
537
+ token = b.refused.token;
538
+ refusalDetails = b.refused.stopDetails;
539
+ base = continuation;
540
+ partial = b.refused.hasPrefillClaim ? toPrefillBlocks(b.blocks) : [];
541
+ iterations.push(toIterationUsage('message', model, b.refused.usage));
542
+ lastUsage = b.refused.usage;
543
+ fromModel = model;
544
+ nextIndex = b.nextIndex;
545
+ }
546
+ }
547
+
548
+ /** The outcome of consuming one hop's stream. */
549
+ interface HopOutcome {
550
+ /** Set when the hop refused with a credit token and an entry remained to chain to. */
551
+ refused: {
552
+ token: string;
553
+ hasPrefillClaim: boolean;
554
+ usage: BetaMessageDeltaUsage;
555
+ /** The refusal's stop_details verbatim, surfaced if the whole chain degrades. */
556
+ stopDetails: BetaRefusalStopDetails;
557
+ } | null;
558
+ /** The hop's serving model, from its message_start. */
559
+ model: string | undefined;
560
+ /** The hop's accumulated content blocks, in start order — the next partial segment. */
561
+ blocks: any[];
562
+ /** One past the highest (shifted) block index emitted — where the next boundary goes. */
563
+ nextIndex: number;
564
+ }
565
+
566
+ /**
567
+ * Consume one hop's SSE events, forwarding them to the client while
568
+ * accumulating its content blocks (returned in the outcome).
569
+ *
570
+ * Stream A (`splice: null`) is forwarded in its original wire bytes; a
571
+ * spliced hop (`splice` set) has its message_start suppressed (the client
572
+ * already saw A's), its block indices shifted by `indexBase`, and its
573
+ * terminal message_delta's usage rewritten to the `usage.iterations`
574
+ * chain shape.
575
+ *
576
+ * A refusal that can be chained — it carries a `fallback_credit_token` and a
577
+ * fallback entry remains — ends the hop early: open blocks are closed, the
578
+ * terminal message_delta + message_stop are suppressed, and the token+usage
579
+ * are returned so the caller can issue the next hop. Any other refusal is
580
+ * reported through `onError` and passes through to the client.
581
+ */
582
+ async function* consumeHop(args: {
583
+ response: Response;
584
+ controller: AbortController;
585
+ /** Shift wire block indices by this much, keeping them monotonic across hops. */
586
+ indexBase: number;
587
+ /** Whether a fallback entry exists to chain to if this hop refuses. */
588
+ hasNext: boolean;
589
+ onError: (error: BetaRefusalFallbackError) => void;
590
+ /** Splice context for fallback hops; null for stream A. */
591
+ splice: { iterations: BetaMessageIterationUsage[]; model: string } | null;
592
+ }): AsyncGenerator<Uint8Array, HopOutcome> {
593
+ const { response, controller, indexBase, hasNext, onError, splice } = args;
594
+ const tracker = new BlockTracker(indexBase);
595
+ let model: string | undefined;
596
+ let startUsage: BetaUsage | null = null;
597
+
598
+ for await (const sse of Stream.rawEvents(response, controller)) {
599
+ const p = safeJSON(sse.data) as BetaRawMessageStreamEvent | undefined;
600
+ switch (p?.type) {
601
+ case 'message_start': {
602
+ model = p.message.model;
603
+ startUsage = p.message.usage;
604
+ if (splice) continue;
605
+ break;
606
+ }
607
+ case 'content_block_start': {
608
+ tracker.start(p);
609
+ if (splice) {
610
+ yield emit(p.type, p);
611
+ continue;
612
+ }
613
+ break;
614
+ }
615
+ case 'content_block_delta': {
616
+ tracker.delta(p);
617
+ if (splice) {
618
+ yield emit(p.type, p);
619
+ continue;
620
+ }
621
+ break;
622
+ }
623
+ case 'content_block_stop': {
624
+ tracker.stop(p);
625
+ if (splice) {
626
+ yield emit(p.type, p);
627
+ continue;
628
+ }
629
+ break;
630
+ }
631
+ case 'message_delta': {
632
+ if (p.delta.stop_reason === 'refusal') {
633
+ // `fallback_credit_token` is null when the refusal isn't eligible
634
+ // for a fallback credit; without one we don't retry.
635
+ const details = p.delta.stop_details?.type === 'refusal' ? p.delta.stop_details : null;
636
+ if (details?.fallback_credit_token && hasNext) {
637
+ const usage = backfill(p.usage, startUsage);
638
+ yield* tracker.closeOpenBlocks();
639
+ // suppress this hop's message_delta + message_stop
640
+ return {
641
+ refused: {
642
+ token: details.fallback_credit_token,
643
+ hasPrefillClaim: details.fallback_has_prefill_claim === true,
644
+ usage,
645
+ stopDetails: details,
646
+ },
647
+ model,
648
+ blocks: tracker.contentBlocks(),
649
+ nextIndex: tracker.nextIndex,
650
+ };
651
+ }
652
+ if (!details?.fallback_credit_token) {
653
+ onError({
654
+ kind: 'no_credit_token',
655
+ message: 'refusal stop_details has no fallback_credit_token',
656
+ event: p,
657
+ });
658
+ } else {
659
+ onError({
660
+ kind: 'chain_exhausted',
661
+ message: 'refusal but no fallback entries remain',
662
+ event: p,
663
+ });
664
+ }
665
+ }
666
+ if (splice) {
667
+ // Terminal hop. Replace iterations, don't append: this hop's own
668
+ // message_delta self-reports a single `{type:"message",
669
+ // model:undefined}` iteration (a fresh non-fallback request counts
670
+ // itself as one message hop). Server-side `fallbacks` relabels the
671
+ // whole chain instead — refused hops as `message`, the serving hop
672
+ // as `fallback_message` — so spreading the self-report would
673
+ // prepend a spurious `message:undefined` entry.
674
+ const usage = backfill(p.usage, startUsage);
675
+ usage.iterations = [
676
+ ...splice.iterations,
677
+ toIterationUsage('fallback_message', splice.model, usage),
678
+ ];
679
+ p.usage = usage;
680
+ yield emit('message_delta', p);
681
+ continue;
682
+ }
683
+ break;
684
+ }
685
+ }
686
+
687
+ // message_stop, ping, error, unrecognised — and for stream A every
688
+ // event — pass through in their original wire bytes.
689
+ yield passthroughSSE(sse);
690
+ }
691
+ return { refused: null, model, blocks: tracker.contentBlocks(), nextIndex: tracker.nextIndex };
692
+ }
693
+
694
+ /**
695
+ * Block bookkeeping for one stream of the splice: accumulates each content
696
+ * block from its deltas (for the continuation prefill), shifts wire indices
697
+ * by `indexBase` so they stay monotonic across hops, and tracks which blocks
698
+ * are still open so a refusal that cuts mid-block can close them.
699
+ */
700
+ class BlockTracker {
701
+ /** The stream's accumulated blocks keyed by their original wire index. */
702
+ private blocks: AccumulatedBlock[] = [];
703
+ /** One past the highest shifted block index seen. */
704
+ nextIndex: number;
705
+ /** Shifted indices of blocks started but not yet stopped. */
706
+ private open: number[] = [];
707
+
708
+ constructor(private indexBase: number = 0) {
709
+ this.nextIndex = indexBase;
710
+ }
711
+
712
+ /** The accumulated content blocks, in start order. */
713
+ contentBlocks(): any[] {
714
+ return this.blocks.map((b) => b.block);
715
+ }
716
+
717
+ /** Track a content_block_start, shifting `event.index`. */
718
+ start(event: BetaRawContentBlockStartEvent): void {
719
+ this.blocks.push({ index: event.index, block: { ...event.content_block } });
720
+ event.index += this.indexBase;
721
+ this.open.push(event.index);
722
+ this.nextIndex = Math.max(this.nextIndex, event.index + 1);
723
+ }
724
+
725
+ /** Apply a content_block_delta to its accumulating block, shifting `event.index`. */
726
+ delta(event: BetaRawContentBlockDeltaEvent): void {
727
+ applyDelta(this.blocks, event.index, event.delta);
728
+ event.index += this.indexBase;
729
+ }
730
+
731
+ /** Track a content_block_stop, shifting `event.index`. */
732
+ stop(event: BetaRawContentBlockStopEvent): void {
733
+ event.index += this.indexBase;
734
+ const i = this.open.indexOf(event.index);
735
+ if (i !== -1) this.open.splice(i, 1);
736
+ this.nextIndex = Math.max(this.nextIndex, event.index + 1);
737
+ }
738
+
739
+ /** content_block_stop events for any blocks still open. */
740
+ *closeOpenBlocks(): Generator<Uint8Array> {
741
+ for (const index of this.open) {
742
+ yield emit<BetaRawContentBlockStopEvent>('content_block_stop', {
743
+ type: 'content_block_stop',
744
+ index,
745
+ });
746
+ }
747
+ this.open.length = 0;
748
+ }
749
+ }
750
+
751
+ // --- fallback request construction (appended-assistant continuation) -------
752
+
753
+ function buildFallbackRequest(
754
+ orig: APIRequest,
755
+ {
756
+ model,
757
+ creditToken,
758
+ continuation,
759
+ }: {
760
+ model: string;
761
+ creditToken: string;
762
+ continuation: BetaContentBlockParam[];
763
+ },
764
+ ): APIRequest {
765
+ // the caller guarantees a JSON string body (checked before stream A is read)
766
+ const body = JSON.parse(orig.body as string);
767
+
768
+ body.model = model;
769
+ body.fallback_credit_token = creditToken;
770
+
771
+ // Append the continuation (decided by the chain loop) as a trailing
772
+ // assistant turn; everything else must stay identical to the refused
773
+ // request. When the refusal granted no prefill claim, omit the turn
774
+ // entirely and send the same-body form.
775
+ if (continuation.length) {
776
+ body.messages = [...body.messages, { role: 'assistant', content: continuation }];
777
+ }
778
+
779
+ // Do NOT touch max_tokens (or any other render-shaping field): the token is
780
+ // only redeemable against the same request body as the refused request —
781
+ // model, fallback_credit_token, and the one appended assistant turn are the
782
+ // only permitted deltas; anything else is a 400 ("request body ... does not
783
+ // match the original refused request"). This is also why the per-entry
784
+ // BetaFallbackParam overrides are ignored on the streaming path.
785
+
786
+ return { ...orig, headers: new Headers(orig.headers), body: JSON.stringify(body) };
787
+ }
788
+
789
+ // --- block accumulation & prefill conversion -------------------------------
790
+
791
+ /** Apply a content_block_delta to the accumulating block at `index`. */
792
+ function applyDelta(
793
+ blocks: AccumulatedBlock[],
794
+ index: number,
795
+ delta: BetaRawContentBlockDeltaEvent['delta'],
796
+ ): void {
797
+ const block = blocks.find((x) => x.index === index)?.block;
798
+ if (!block) return;
799
+ switch (delta.type) {
800
+ case 'text_delta': {
801
+ block.text = (block.text ?? '') + delta.text;
802
+ break;
803
+ }
804
+ case 'input_json_delta': {
805
+ block._partial_json = (block._partial_json ?? '') + delta.partial_json;
806
+ break;
807
+ }
808
+ case 'citations_delta':
809
+ (block.citations ??= []).push(delta.citation);
810
+ break;
811
+ case 'thinking_delta': {
812
+ block.thinking = (block.thinking ?? '') + delta.thinking;
813
+ break;
814
+ }
815
+ case 'signature_delta': {
816
+ block.signature = delta.signature;
817
+ break;
818
+ }
819
+ case 'compaction_delta': {
820
+ break;
821
+ }
822
+ default:
823
+ ((_: never) => {})(delta);
824
+ }
825
+ }
826
+
827
+ /**
828
+ * Convert a hop's accumulated response blocks to the appended assistant turn,
829
+ * as-is: a `fallback_has_prefill_claim` refusal guarantees the partial output
830
+ * is resendable verbatim, so no client-side filtering is applied. The only
831
+ * rewrite is reassembling tool inputs from their accumulated
832
+ * `input_json_delta` JSON (content_block_start carries `input: {}`).
833
+ */
834
+ function toPrefillBlocks(responseBlocks: any[]): BetaContentBlockParam[] {
835
+ return responseBlocks.map((b) => {
836
+ if (typeof b?._partial_json !== 'string') return b;
837
+ const { _partial_json, ...block } = b;
838
+ return { ...block, input: safeJSON(_partial_json) ?? block.input };
839
+ });
840
+ }
841
+
842
+ // --- helpers --------------------------------------------------------------
843
+
844
+ /**
845
+ * A copy of `request` with `betas` appended to its `anthropic-beta` header,
846
+ * skipping values already present (set by the caller or another middleware).
847
+ */
848
+ function appendBetas(request: APIRequest, betas: readonly AnthropicBeta[]): APIRequest {
849
+ if (!betas.length) return request;
850
+ const headers = new Headers(request.headers);
851
+ const existing = new Set(
852
+ headers
853
+ .get('anthropic-beta')
854
+ ?.split(',')
855
+ .map((s) => s.trim()),
856
+ );
857
+ for (const beta of betas) {
858
+ if (!existing.has(beta)) {
859
+ headers.append('anthropic-beta', beta);
860
+ existing.add(beta);
861
+ }
862
+ }
863
+ return { ...request, headers };
864
+ }
865
+
866
+ function emit<T extends { type: string }>(event: T['type'], payload: T): Uint8Array {
867
+ const sse: ServerSentEvent = { event, data: JSON.stringify(payload), raw: [] };
868
+ return encoder.encode(serializeSSE(sse));
869
+ }
870
+
871
+ /**
872
+ * Forward a decoded event in its original wire bytes, preserving SSE fields
873
+ * the decoder doesn't model (`id:`, `retry:`, comment lines). Falls back to
874
+ * re-serializing for events with no raw lines.
875
+ */
876
+ function passthroughSSE(sse: ServerSentEvent): Uint8Array {
877
+ return encoder.encode(sse.raw.length ? sse.raw.join('\n') + '\n\n' : serializeSSE(sse));
878
+ }
879
+
880
+ // Field-wise union of BetaUsage and BetaMessageDeltaUsage, all nullable —
881
+ // a plain Partial<A & B> intersects `number` with `number | null` down to
882
+ // `number`, which rejects delta usage objects.
883
+ type UsageLike =
884
+ | { [K in keyof (BetaUsage & BetaMessageDeltaUsage)]?: (BetaUsage & BetaMessageDeltaUsage)[K] | null }
885
+ | null
886
+ | undefined;
887
+
888
+ function toIterationUsage(type: 'message', model: string, u: UsageLike): BetaMessageIterationUsage;
889
+ function toIterationUsage(
890
+ type: 'fallback_message',
891
+ model: string,
892
+ u: UsageLike,
893
+ ): BetaFallbackMessageIterationUsage;
894
+ function toIterationUsage(
895
+ type: 'message' | 'fallback_message',
896
+ model: string,
897
+ u: UsageLike,
898
+ ): BetaMessageIterationUsage | BetaFallbackMessageIterationUsage {
899
+ return {
900
+ type,
901
+ model,
902
+ input_tokens: u?.input_tokens ?? 0,
903
+ output_tokens: u?.output_tokens ?? 0,
904
+ cache_read_input_tokens: u?.cache_read_input_tokens ?? 0,
905
+ cache_creation_input_tokens: u?.cache_creation_input_tokens ?? 0,
906
+ cache_creation: u?.cache_creation ?? null,
907
+ };
908
+ }
909
+
910
+ /** Fill null/undefined fields on `primary` from `fallback`. */
911
+ function backfill(
912
+ primary: BetaMessageDeltaUsage | null | undefined,
913
+ fallback: BetaUsage | null | undefined,
914
+ ): BetaMessageDeltaUsage {
915
+ const out: any = { ...(fallback ?? {}), ...(primary ?? {}) };
916
+ for (const k of Object.keys(out)) {
917
+ if (out[k] == null && (fallback as any)?.[k] != null) out[k] = (fallback as any)[k];
918
+ }
919
+ return out;
920
+ }
921
+
922
+ /**
923
+ * Serialize a {@link ServerSentEvent} back to its SSE wire form
924
+ * (`event: ...\ndata: ...\n\n`). Multi-line `data` is emitted as one
925
+ * `data:` line per line, matching the spec. The inverse of the decoder
926
+ * behind {@link Stream.rawEvents}.
927
+ */
928
+ function serializeSSE(sse: ServerSentEvent): string {
929
+ let out = '';
930
+ if (sse.event !== null) out += `event: ${sse.event}\n`;
931
+ for (const line of sse.data.split('\n')) out += `data: ${line}\n`;
932
+ return out + '\n';
933
+ }
934
+
935
+ function makeAbort(controller: AbortController, signal: AbortSignal) {
936
+ return () => controller.abort(signal.reason);
937
+ }