@namzu/anthropic 3.3.2 → 4.0.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.
@@ -1 +1 @@
1
- {"version":3,"file":"thinking-capability.js","sourceRoot":"","sources":["../src/thinking-capability.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAA;AA4ClD,MAAM,SAAS,GAAiB,EAAE,CAAA;AAClC,+DAA+D;AAC/D,MAAM,WAAW,GAAiB,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,CAAA;AAC3E,iEAAiE;AACjE,MAAM,oBAAoB,GAAiB,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,CAAC,CAAA;AAC3E,sCAAsC;AACtC,MAAM,WAAW,GAAiB,CAAC,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAA;AA0B3D,MAAM,WAAW,GAAuB;IACvC,QAAQ,EAAE,KAAK;IACf,MAAM,EAAE,IAAI;IACZ,UAAU,EAAE,IAAI;IAChB,MAAM,EAAE,SAAS;IACjB,kBAAkB,EAAE,SAAS;CAC7B,CAAA;AAED;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAmB;IAC/C,OAAO,EAAE,QAAQ;IACjB,QAAQ,EAAE,CAAC,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC;IACxD,aAAa,EAAE,YAAY;CAC3B,CAAA;AAED,MAAM,UAAU,yBAAyB,CAAC,KAAa;IACtD,MAAM,UAAU,GAAG,KAAK,CAAC,WAAW,EAAE,CAAA;IAEtC,yEAAyE;IACzE,0EAA0E;IAC1E,+BAA+B;IAC/B,IAAI,yCAAyC,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,CAAC;QAChE,OAAO;YACN,QAAQ,EAAE,IAAI;YACd,MAAM,EAAE,IAA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AAY,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,QAAQ,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACxF,GAAG,OAAO;SACV,CAAA;IACF,CAAC;IACD,OAAO,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,OAAO,EAAE,CAAC,CAAC,CAAC,SAAS,CAAA;AAC1E,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,UAAU,aAAa,CAC5B,MAAmC,EACnC,YAAkC,EAClC,UAA8B,EAC9B,KAAc;IAEd,IAAI,MAAM,KAAK,SAAS;QAAE,OAAO,SAAS,CAAA;IAC1C,MAAM,OAAO,GACZ,YAAY,EAAE,IAAI,KAAK,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,kBAAkB,CAAC,CAAC,CAAC,UAAU,CAAC,MAAM,CAAA;IACtF,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC;QAAE,OAAO,MAAM,CAAA;IAC3C,MAAM,MAAM,GAAG,KAAK,CAAC,CAAC,CAAC,cAAc,KAAK,GAAG,CAAC,CAAC,CAAC,qCAAqC,CAAA;IACrF,MAAM,OAAO,GAAG,OAAO,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAA;IAChE,MAAM,IAAI,KAAK,CACd,8BAA8B,MAAM,qBAAqB,MAAM,uBAAuB,OAAO,kDAAkD,CAC/I,CAAA;AACF,CAAC"}
package/package.json CHANGED
@@ -1,8 +1,11 @@
1
1
  {
2
2
  "name": "@namzu/anthropic",
3
- "version": "3.3.2",
3
+ "version": "4.0.0",
4
4
  "description": "Anthropic LLM provider for @namzu/sdk via the official @anthropic-ai/sdk. Messages API with streaming, tool-use, and extended thinking support.",
5
5
  "license": "FSL-1.1-MIT",
6
+ "engines": {
7
+ "node": ">=20.0.0"
8
+ },
6
9
  "type": "module",
7
10
  "homepage": "https://github.com/cogitave/namzu#readme",
8
11
  "repository": {
@@ -54,7 +57,7 @@
54
57
  "@types/node": "^22.19.17",
55
58
  "typescript": "^5.5.0",
56
59
  "vitest": "^3.2.6",
57
- "@namzu/sdk": "^30.0.1"
60
+ "@namzu/sdk": "^31.0.0"
58
61
  },
59
62
  "scripts": {
60
63
  "build": "tsc --build",
package/src/client.ts CHANGED
@@ -7,6 +7,7 @@ import type {
7
7
  LLMProvider,
8
8
  ModelInfo,
9
9
  ProviderCapabilities,
10
+ ProviderRoute,
10
11
  ReasoningBlock,
11
12
  ReasoningEffort,
12
13
  StreamChunk,
@@ -157,7 +158,7 @@ type AttachmentLike =
157
158
  }
158
159
 
159
160
  /**
160
- * A reasoning block, replayed exactly as it arrived.
161
+ * A reasoning block in this provider's native history shape.
161
162
  *
162
163
  * The signature is cryptographic and verified upstream: a block echoed
163
164
  * back with its text edited, its signature dropped, or its order changed
@@ -172,6 +173,17 @@ interface AnthropicThinkingBlock {
172
173
  cache_control?: AnthropicCacheControl
173
174
  }
174
175
 
176
+ type AnthropicReplayBlock =
177
+ | { type: 'thinking'; thinking: string; signature: string }
178
+ | { type: 'redacted_thinking'; data: string }
179
+
180
+ interface AnthropicReplayState {
181
+ readonly kind: 'namzu-anthropic-reasoning'
182
+ readonly version: 1
183
+ readonly route: ProviderRoute
184
+ readonly blocks: readonly AnthropicReplayBlock[]
185
+ }
186
+
175
187
  interface AnthropicDocumentBlock {
176
188
  type: 'document'
177
189
  source: { type: 'base64'; media_type: string; data: string }
@@ -223,28 +235,132 @@ function extractSystem(
223
235
  }
224
236
 
225
237
  /**
226
- * The reasoning blocks an assistant message carries, in wire form.
227
- *
228
- * Verbatim by contract, and first in the message: the API requires
229
- * thinking blocks to lead, and the signature is verified, so re-rendering
230
- * or reordering them invalidates the turn they belong to.
238
+ * Resolve the exact target member for this adapter call.
231
239
  */
232
- function replayReasoning(msg: { reasoning?: readonly ReasoningBlock[] }): AnthropicThinkingBlock[] {
233
- if (!msg.reasoning || msg.reasoning.length === 0) return []
234
- return msg.reasoning.map((block) =>
235
- block.type === 'redacted_thinking'
236
- ? {
237
- type: 'redacted_thinking' as const,
238
- ...(block.encrypted ? { data: block.encrypted } : {}),
239
- }
240
- : {
241
- type: 'thinking' as const,
242
- thinking: block.text ?? '',
243
- ...(block.signature ? { signature: block.signature } : {}),
244
- },
240
+ function resolveAnthropicRoute(model: string, candidate: ProviderRoute | undefined): ProviderRoute {
241
+ if (candidate === undefined) return { providerId: 'anthropic', model, chainIndex: 0 }
242
+ if (
243
+ candidate.providerId !== 'anthropic' ||
244
+ candidate.model !== model ||
245
+ !Number.isSafeInteger(candidate.chainIndex) ||
246
+ candidate.chainIndex < 0
247
+ ) {
248
+ throw new Error(
249
+ 'AnthropicProvider: providerRoute must name this provider, the requested model, and a non-negative integer chainIndex.',
250
+ )
251
+ }
252
+ return candidate
253
+ }
254
+
255
+ function sameRoute(left: ProviderRoute, right: ProviderRoute): boolean {
256
+ return (
257
+ left.providerId === right.providerId &&
258
+ left.model === right.model &&
259
+ left.chainIndex === right.chainIndex
260
+ )
261
+ }
262
+
263
+ function isAnthropicReplayState(value: unknown): value is AnthropicReplayState {
264
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
265
+ const state = value as Record<string, unknown>
266
+ const route = state.route
267
+ if (
268
+ state.kind !== 'namzu-anthropic-reasoning' ||
269
+ state.version !== 1 ||
270
+ typeof route !== 'object' ||
271
+ route === null ||
272
+ Array.isArray(route) ||
273
+ typeof (route as Record<string, unknown>).providerId !== 'string' ||
274
+ typeof (route as Record<string, unknown>).model !== 'string' ||
275
+ !Number.isSafeInteger((route as Record<string, unknown>).chainIndex) ||
276
+ ((route as Record<string, unknown>).chainIndex as number) < 0 ||
277
+ !Array.isArray(state.blocks)
278
+ ) {
279
+ return false
280
+ }
281
+ return state.blocks.every((value) => {
282
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false
283
+ const block = value as Record<string, unknown>
284
+ return block.type === 'thinking'
285
+ ? typeof block.thinking === 'string' && typeof block.signature === 'string'
286
+ : block.type === 'redacted_thinking' && typeof block.data === 'string'
287
+ })
288
+ }
289
+
290
+ function durableAnthropicReasoning(
291
+ reasoning: readonly ReasoningBlock[] | undefined,
292
+ ): readonly AnthropicReplayBlock[] | undefined {
293
+ if (!reasoning || reasoning.length === 0) return undefined
294
+ const blocks: AnthropicReplayBlock[] = []
295
+ for (const block of reasoning) {
296
+ if (block.type === 'thinking') {
297
+ if (
298
+ typeof block.text !== 'string' ||
299
+ typeof block.signature !== 'string' ||
300
+ block.signature.length === 0 ||
301
+ block.encrypted !== undefined
302
+ ) {
303
+ return undefined
304
+ }
305
+ blocks.push({
306
+ type: 'thinking',
307
+ thinking: block.text,
308
+ signature: block.signature,
309
+ })
310
+ continue
311
+ }
312
+ if (
313
+ typeof block.encrypted !== 'string' ||
314
+ block.encrypted.length === 0 ||
315
+ block.text !== undefined ||
316
+ block.signature !== undefined
317
+ ) {
318
+ return undefined
319
+ }
320
+ blocks.push({ type: 'redacted_thinking', data: block.encrypted })
321
+ }
322
+ return blocks
323
+ }
324
+
325
+ function replayBlocksEqual(
326
+ left: readonly AnthropicReplayBlock[],
327
+ right: readonly AnthropicReplayBlock[],
328
+ ): boolean {
329
+ return (
330
+ left.length === right.length &&
331
+ left.every((block, index) => {
332
+ const other = right[index]
333
+ if (!other || block.type !== other.type) return false
334
+ return block.type === 'thinking' && other.type === 'thinking'
335
+ ? block.thinking === other.thinking && block.signature === other.signature
336
+ : block.type === 'redacted_thinking' &&
337
+ other.type === 'redacted_thinking' &&
338
+ block.data === other.data
339
+ })
245
340
  )
246
341
  }
247
342
 
343
+ /**
344
+ * The reasoning blocks an assistant message may restore in native wire form.
345
+ *
346
+ * Durable reasoning alone is not authority to emit signed provider metadata.
347
+ * The adapter-private envelope must be well-formed, agree with that durable
348
+ * content, and belong to the exact target route. Otherwise the assistant text
349
+ * and tool calls remain usable while native thinking is omitted.
350
+ */
351
+ function replayReasoning(
352
+ msg: Extract<ChatCompletionParams['messages'][number], { role: 'assistant' }>,
353
+ targetRoute: ProviderRoute,
354
+ ): AnthropicThinkingBlock[] {
355
+ const source = msg.source
356
+ if (!source || source.type !== 'model' || !sameRoute(source, targetRoute)) return []
357
+ const state = source.replayState
358
+ if (!isAnthropicReplayState(state) || !sameRoute(state.route, source)) return []
359
+ const durable = durableAnthropicReasoning(msg.reasoning)
360
+ if (!durable || !replayBlocksEqual(durable, state.blocks)) return []
361
+ return state.blocks.map((block) => ({ ...block }))
362
+ }
363
+
248
364
  /**
249
365
  * A tool result, in the richest form this wire accepts.
250
366
  *
@@ -269,7 +385,11 @@ function toolResultContent(
269
385
  if (block.type === 'image') {
270
386
  blocks.push({
271
387
  type: 'image',
272
- source: { type: 'base64', media_type: block.mediaType, data: block.data },
388
+ source: {
389
+ type: 'base64',
390
+ media_type: block.mediaType,
391
+ data: block.data,
392
+ },
273
393
  })
274
394
  continue
275
395
  }
@@ -280,7 +400,10 @@ function toolResultContent(
280
400
  return blocks.length > 0 ? blocks : ''
281
401
  }
282
402
 
283
- function toAnthropicMessages(messages: ChatCompletionParams['messages']): AnthropicMessageParam[] {
403
+ function toAnthropicMessages(
404
+ messages: ChatCompletionParams['messages'],
405
+ targetRoute: ProviderRoute,
406
+ ): AnthropicMessageParam[] {
284
407
  const out: AnthropicMessageParam[] = []
285
408
  let pendingToolResults: AnthropicToolResultBlock[] = []
286
409
 
@@ -295,7 +418,10 @@ function toAnthropicMessages(messages: ChatCompletionParams['messages']): Anthro
295
418
  if (msg.role === 'system') continue
296
419
 
297
420
  if (msg.role === 'tool') {
298
- const toolMsg = msg as { toolCallId?: string; content?: ToolResultContent }
421
+ const toolMsg = msg as {
422
+ toolCallId?: string
423
+ content?: ToolResultContent
424
+ }
299
425
  pendingToolResults.push({
300
426
  type: 'tool_result',
301
427
  tool_use_id: toolMsg.toolCallId ?? 'unknown',
@@ -307,7 +433,7 @@ function toAnthropicMessages(messages: ChatCompletionParams['messages']): Anthro
307
433
  flushToolResults()
308
434
 
309
435
  if (msg.role === 'assistant' && 'toolCalls' in msg && msg.toolCalls) {
310
- const blocks: AnthropicContentBlock[] = [...replayReasoning(msg)]
436
+ const blocks: AnthropicContentBlock[] = [...replayReasoning(msg, targetRoute)]
311
437
  if (msg.content && typeof msg.content === 'string') {
312
438
  blocks.push({ type: 'text', text: msg.content })
313
439
  }
@@ -331,7 +457,7 @@ function toAnthropicMessages(messages: ChatCompletionParams['messages']): Anthro
331
457
 
332
458
  // An assistant turn that reasoned replays those blocks even when it
333
459
  // called no tool: dropping them invalidates the turn upstream.
334
- const replayed = msg.role === 'assistant' ? replayReasoning(msg) : []
460
+ const replayed = msg.role === 'assistant' ? replayReasoning(msg, targetRoute) : []
335
461
  const content = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content)
336
462
  if (replayed.length > 0) {
337
463
  const trailing: AnthropicContentBlock[] =
@@ -354,7 +480,11 @@ function toAnthropicMessages(messages: ChatCompletionParams['messages']): Anthro
354
480
  if (att.type === 'document') {
355
481
  blocks.push({
356
482
  type: 'document',
357
- source: { type: 'base64', media_type: att.mediaType, data: att.data },
483
+ source: {
484
+ type: 'base64',
485
+ media_type: att.mediaType,
486
+ data: att.data,
487
+ },
358
488
  ...(att.name ? { title: att.name } : {}),
359
489
  // Opt-in: citations cost tokens, so they are requested
360
490
  // only when the caller asked to be able to check the
@@ -416,7 +546,9 @@ function toAnthropicTools(
416
546
  // here rather than in the renderer keeps the dialect where the
417
547
  // knowledge is: only this file knows which wire it is talking to.
418
548
  input_schema: toSchemaDialect(
419
- (t.function.parameters as Record<string, unknown> | undefined) ?? { type: 'object' },
549
+ (t.function.parameters as Record<string, unknown> | undefined) ?? {
550
+ type: 'object',
551
+ },
420
552
  '2020-12',
421
553
  ),
422
554
  ...(strict ? { strict: true } : {}),
@@ -607,13 +739,25 @@ function toCitation(raw: RawAnthropicCitation, index: number): Citation | undefi
607
739
  | { kind: 'block'; start: number; end: number }
608
740
  | undefined => {
609
741
  if (raw.start_page_number !== undefined && raw.end_page_number !== undefined) {
610
- return { kind: 'page', start: raw.start_page_number, end: raw.end_page_number }
742
+ return {
743
+ kind: 'page',
744
+ start: raw.start_page_number,
745
+ end: raw.end_page_number,
746
+ }
611
747
  }
612
748
  if (raw.start_char_index !== undefined && raw.end_char_index !== undefined) {
613
- return { kind: 'char', start: raw.start_char_index, end: raw.end_char_index }
749
+ return {
750
+ kind: 'char',
751
+ start: raw.start_char_index,
752
+ end: raw.end_char_index,
753
+ }
614
754
  }
615
755
  if (raw.start_block_index !== undefined && raw.end_block_index !== undefined) {
616
- return { kind: 'block', start: raw.start_block_index, end: raw.end_block_index }
756
+ return {
757
+ kind: 'block',
758
+ start: raw.start_block_index,
759
+ end: raw.end_block_index,
760
+ }
617
761
  }
618
762
  return undefined
619
763
  })()
@@ -631,7 +775,14 @@ interface StreamEvent {
631
775
  type: string
632
776
  message?: { id?: string; usage?: RawAnthropicUsage }
633
777
  index?: number
634
- content_block?: { type?: string; id?: string; name?: string; data?: string }
778
+ content_block?: {
779
+ type?: string
780
+ id?: string
781
+ name?: string
782
+ data?: string
783
+ thinking?: string
784
+ signature?: string
785
+ }
635
786
  delta?: {
636
787
  type?: string
637
788
  text?: string
@@ -727,8 +878,9 @@ export class AnthropicProvider implements LLMProvider {
727
878
  // earlier sections too).
728
879
  const cachingEnabled = params.cacheControl !== undefined
729
880
  const model = this.resolveModel(params)
881
+ const providerRoute = resolveAnthropicRoute(model, params.providerRoute)
730
882
  const system = extractSystem(params.messages, cachingEnabled)
731
- const messages = toAnthropicMessages(params.messages)
883
+ const messages = toAnthropicMessages(params.messages, providerRoute)
732
884
  if (cachingEnabled) applyMessageCacheBreakpoint(messages)
733
885
  const tools = toAnthropicTools(
734
886
  params,
@@ -773,20 +925,24 @@ export class AnthropicProvider implements LLMProvider {
773
925
  // newer models, so a caller who wanted to show reasoning and never
774
926
  // serialized the field received thinking blocks with empty text and
775
927
  // nothing to explain why.
776
- const capability = resolveThinkingCapability(params.model)
928
+ const capability = resolveThinkingCapability(model)
777
929
  const thinkingBody = resolveThinkingBody(params.thinking, capability)
778
930
  if (thinkingBody) body.thinking = thinkingBody
779
931
 
780
932
  // A sibling of `thinking`, not a field inside it — and gated on the
781
933
  // model, since only some accept it at all.
782
- const effort = resolveEffort(params.effort, thinkingBody, capability)
934
+ const effort = resolveEffort(params.effort, thinkingBody, capability, model)
783
935
  // Merged rather than assigned. `output_config` is a shared envelope on
784
936
  // this wire — a structured-output format and a task budget live in it
785
937
  // too, and `responseFormat` already exists on the params unhandled
786
938
  // here. Assigning would mean whoever wires the next one silently
787
939
  // deletes effort, or has effort silently delete theirs, depending only
788
940
  // on which line ran last.
789
- if (effort) body.output_config = { ...(body.output_config as object | undefined), effort }
941
+ if (effort)
942
+ body.output_config = {
943
+ ...(body.output_config as object | undefined),
944
+ effort,
945
+ }
790
946
  if (params.temperature !== undefined) body.temperature = params.temperature
791
947
  if (params.topP !== undefined) body.top_p = params.topP
792
948
  if (params.topK !== undefined) body.top_k = params.topK
@@ -816,6 +972,7 @@ export class AnthropicProvider implements LLMProvider {
816
972
  }
817
973
 
818
974
  async *chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk> {
975
+ const providerRoute = resolveAnthropicRoute(this.resolveModel(params), params.providerRoute)
819
976
  const createParams = this.buildCreateParams(params, true)
820
977
  const signal = params.signal
821
978
 
@@ -840,6 +997,30 @@ export class AnthropicProvider implements LLMProvider {
840
997
  // fragments can reference the right tool call.
841
998
  const activeTools = new Map<number, { id: string; name: string }>()
842
999
  const activeReasoning = new Set<number>()
1000
+ const nativeReasoning = new Map<number, AnthropicReplayBlock>()
1001
+ let replayStateEmitted = false
1002
+ const completedReplayState = (): AnthropicReplayState | undefined => {
1003
+ if (replayStateEmitted || activeReasoning.size > 0 || nativeReasoning.size === 0) {
1004
+ return undefined
1005
+ }
1006
+ const blocks = [...nativeReasoning.entries()]
1007
+ .sort(([left], [right]) => left - right)
1008
+ .map(([, block]) => ({ ...block }))
1009
+ if (
1010
+ blocks.some((block) =>
1011
+ block.type === 'thinking' ? block.signature.length === 0 : block.data.length === 0,
1012
+ )
1013
+ ) {
1014
+ return undefined
1015
+ }
1016
+ replayStateEmitted = true
1017
+ return {
1018
+ kind: 'namzu-anthropic-reasoning',
1019
+ version: 1,
1020
+ route: providerRoute,
1021
+ blocks,
1022
+ }
1023
+ }
843
1024
 
844
1025
  // Anthropic Messages API streams over SSE. Do not impose a
845
1026
  // provider-local 90s idle cutoff by default: long reasoning or
@@ -902,6 +1083,18 @@ export class AnthropicProvider implements LLMProvider {
902
1083
  const block = event.content_block
903
1084
  if (block?.type === 'thinking' || block?.type === 'redacted_thinking') {
904
1085
  activeReasoning.add(idx)
1086
+ if (block.type === 'thinking') {
1087
+ nativeReasoning.set(idx, {
1088
+ type: 'thinking',
1089
+ thinking: block.thinking ?? '',
1090
+ signature: block.signature ?? '',
1091
+ })
1092
+ } else {
1093
+ nativeReasoning.set(idx, {
1094
+ type: 'redacted_thinking',
1095
+ data: block.data ?? '',
1096
+ })
1097
+ }
905
1098
  yield {
906
1099
  id: messageId,
907
1100
  delta: {
@@ -939,16 +1132,22 @@ export class AnthropicProvider implements LLMProvider {
939
1132
  if (delta?.type === 'text_delta' && delta.text) {
940
1133
  yield { id: messageId, delta: { content: delta.text } }
941
1134
  } else if (delta?.type === 'thinking_delta' && delta.thinking !== undefined) {
1135
+ const native = nativeReasoning.get(idx)
1136
+ if (native?.type === 'thinking') native.thinking += delta.thinking
942
1137
  yield {
943
1138
  id: messageId,
944
1139
  delta: { reasoning: { index: idx, text: delta.thinking } },
945
1140
  }
946
1141
  } else if (delta?.type === 'signature_delta' && delta.signature !== undefined) {
1142
+ const native = nativeReasoning.get(idx)
1143
+ if (native?.type === 'thinking') native.signature += delta.signature
947
1144
  // Arrives once, at the end of the block, and has to
948
1145
  // reach the next request unmodified.
949
1146
  yield {
950
1147
  id: messageId,
951
- delta: { reasoning: { index: idx, signature: delta.signature } },
1148
+ delta: {
1149
+ reasoning: { index: idx, signature: delta.signature },
1150
+ },
952
1151
  }
953
1152
  } else if (delta?.type === 'citations_delta' && delta.citation) {
954
1153
  // Not text: a citation lands on the assistant
@@ -988,7 +1187,10 @@ export class AnthropicProvider implements LLMProvider {
988
1187
  // Closes the block, exactly as toolCallEnd closes a
989
1188
  // tool call: without it the aggregator cannot know
990
1189
  // the signature has finished arriving.
991
- yield { id: messageId, delta: { reasoning: { index: idx, done: true } } }
1190
+ yield {
1191
+ id: messageId,
1192
+ delta: { reasoning: { index: idx, done: true } },
1193
+ }
992
1194
  break
993
1195
  }
994
1196
  const active = activeTools.get(idx)
@@ -1005,8 +1207,10 @@ export class AnthropicProvider implements LLMProvider {
1005
1207
  }
1006
1208
  case 'message_delta': {
1007
1209
  if (event.delta?.stop_reason) {
1210
+ const replayState = completedReplayState()
1008
1211
  yield {
1009
1212
  id: messageId,
1213
+ ...(replayState !== undefined ? { replayState } : {}),
1010
1214
  delta: {},
1011
1215
  finishReason: mapStopReason(event.delta.stop_reason),
1012
1216
  usage: event.usage ? parseUsage(event.usage) : undefined,
@@ -1020,8 +1224,13 @@ export class AnthropicProvider implements LLMProvider {
1020
1224
  }
1021
1225
  break
1022
1226
  }
1023
- case 'message_stop':
1227
+ case 'message_stop': {
1228
+ const replayState = completedReplayState()
1229
+ if (replayState !== undefined) {
1230
+ yield { id: messageId, delta: {}, replayState }
1231
+ }
1024
1232
  return
1233
+ }
1025
1234
  default:
1026
1235
  // Ignore unknown / ping / opaque events.
1027
1236
  break
@@ -1056,12 +1265,15 @@ export class AnthropicProvider implements LLMProvider {
1056
1265
  }
1057
1266
  }
1058
1267
 
1059
- async listModels(): Promise<ModelInfo[]> {
1268
+ async listModels(signal?: AbortSignal): Promise<ModelInfo[]> {
1269
+ signal?.throwIfAborted()
1060
1270
  try {
1061
1271
  // Models API shipped in SDK ~0.32+. Feature-detect via unknown cast so we
1062
1272
  // don't depend on the SDK's surface-level shape in a version-brittle way.
1063
1273
  const clientLike = this.client as unknown as {
1064
- models?: { list?: (opts: { limit: number }) => Promise<unknown> }
1274
+ models?: {
1275
+ list?: (opts: { limit: number }, request?: { signal?: AbortSignal }) => Promise<unknown>
1276
+ }
1065
1277
  }
1066
1278
  const models = clientLike.models
1067
1279
  if (typeof models?.list !== 'function') {
@@ -1072,9 +1284,10 @@ export class AnthropicProvider implements LLMProvider {
1072
1284
  // TypeError on EVERY call — which the catch below swallowed, so this
1073
1285
  // listing never once reached the network and the hardcoded models
1074
1286
  // were not a fallback but the only answer this method could give.
1075
- const page = (await models.list({ limit: 100 })) as {
1287
+ const page = (await models.list({ limit: 100 }, signal ? { signal } : undefined)) as {
1076
1288
  data?: Array<{ id?: string; display_name?: string; type?: string }>
1077
1289
  }
1290
+ signal?.throwIfAborted()
1078
1291
  const data = page?.data ?? []
1079
1292
  if (data.length === 0) return this.knownModels()
1080
1293
  return data.map((m) => ({
@@ -1086,6 +1299,7 @@ export class AnthropicProvider implements LLMProvider {
1086
1299
  supportsStreaming: true,
1087
1300
  }))
1088
1301
  } catch {
1302
+ if (signal?.aborted) throw signal.reason
1089
1303
  return this.knownModels()
1090
1304
  }
1091
1305
  }
@@ -1101,9 +1315,12 @@ export class AnthropicProvider implements LLMProvider {
1101
1315
  * An SDK too old to expose `models.list` throws rather than passing, so the
1102
1316
  * caller reports unverifiable — nothing was asked, so nothing is known.
1103
1317
  */
1104
- async probeCredential(): Promise<void> {
1318
+ async probeCredential(signal?: AbortSignal): Promise<void> {
1319
+ signal?.throwIfAborted()
1105
1320
  const clientLike = this.client as unknown as {
1106
- models?: { list?: (opts: { limit: number }) => Promise<unknown> }
1321
+ models?: {
1322
+ list?: (opts: { limit: number }, request?: { signal?: AbortSignal }) => Promise<unknown>
1323
+ }
1107
1324
  }
1108
1325
  const models = clientLike.models
1109
1326
  if (typeof models?.list !== 'function') {
@@ -1112,7 +1329,8 @@ export class AnthropicProvider implements LLMProvider {
1112
1329
  // Called ON the namespace. Pulling the method into a bare variable and
1113
1330
  // invoking it loses `this`, and the SDK reads `this._client` — which is
1114
1331
  // how the sibling `listModels` came to never execute at all.
1115
- await models.list({ limit: 1 })
1332
+ await models.list({ limit: 1 }, signal ? { signal } : undefined)
1333
+ signal?.throwIfAborted()
1116
1334
  }
1117
1335
 
1118
1336
  private knownModels(): ModelInfo[] {
@@ -1146,6 +1364,10 @@ export class AnthropicProvider implements LLMProvider {
1146
1364
  const body = resolveThinkingBody(thinking, capability)
1147
1365
  return body?.type === 'disabled' ? capability.effortWhenDisabled : capability.effort
1148
1366
  }
1367
+
1368
+ reasoningEffortLevelsFor(model: string, thinking?: ThinkingConfig): readonly ReasoningEffort[] {
1369
+ return this.effortLevelsFor(model, thinking)
1370
+ }
1149
1371
  }
1150
1372
 
1151
1373
  /**
@@ -194,7 +194,11 @@ export function resolveThinkingCapability(model: string): ThinkingCapability {
194
194
  /** The `thinking` body value, or `undefined` to send no thinking field. */
195
195
  export type ResolvedThinkingBody =
196
196
  | { type: 'adaptive'; display?: 'summarized' | 'omitted' }
197
- | { type: 'enabled'; budget_tokens?: number; display?: 'summarized' | 'omitted' }
197
+ | {
198
+ type: 'enabled'
199
+ budget_tokens?: number
200
+ display?: 'summarized' | 'omitted'
201
+ }
198
202
  | { type: 'disabled' }
199
203
  | undefined
200
204
 
@@ -253,10 +257,9 @@ export function resolveThinkingBody(
253
257
  * arrived with 4.7, and `max` does not exist below 4.6 — so `capability.effort`
254
258
  * is a set rather than a flag. It was a flag, which meant `xhigh` on a 4.6 and
255
259
  * `max` on a 4.5 were forwarded to a vendor that rejects an unknown level
256
- * rather than clamping it. Dropping the field is right where the level does
257
- * not exist: `effort` shapes an answer the model will still produce, so a
258
- * request without it is the same request at the model's own default, whereas
259
- * refusing would fail a call that has a correct answer.
260
+ * rather than clamping it. Refusing before transport is the only truthful
261
+ * outcome: silently dropping a caller's effort changes the request to the
262
+ * model default while reporting that the requested control was honoured.
260
263
  *
261
264
  * The COMBINATION has to be legal, and the legal set is per model rather than
262
265
  * universal. Opus 5 accepts `thinking: {type: "disabled"}` at `high` or below
@@ -274,9 +277,15 @@ export function resolveEffort(
274
277
  effort: ReasoningEffort | undefined,
275
278
  thinkingBody: ResolvedThinkingBody,
276
279
  capability: ThinkingCapability,
280
+ model?: string,
277
281
  ): ReasoningEffort | undefined {
278
282
  if (effort === undefined) return undefined
279
283
  const allowed =
280
284
  thinkingBody?.type === 'disabled' ? capability.effortWhenDisabled : capability.effort
281
- return allowed.includes(effort) ? effort : undefined
285
+ if (allowed.includes(effort)) return effort
286
+ const target = model ? ` by model "${model}"` : ' by this model/thinking combination'
287
+ const offered = allowed.length > 0 ? allowed.join(', ') : 'none'
288
+ throw new Error(
289
+ `AnthropicProvider: effort "${effort}" is not supported${target}. Supported levels: ${offered}. Choose one of those levels or omit \`effort\`.`,
290
+ )
282
291
  }