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