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