@namzu/anthropic 1.1.1 → 1.2.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.
@@ -0,0 +1,274 @@
1
+ /**
2
+ * Provider error taxonomy — Anthropic driver.
3
+ *
4
+ * The driver hands the request to the vendor SDK and lets whatever the SDK
5
+ * rejects with escape verbatim (`RateLimitError`, `BadRequestError`, …).
6
+ * Those are vendor types: a caller cannot classify them without importing
7
+ * `@anthropic-ai/sdk`, so nothing downstream can distinguish a throttle
8
+ * from a context overflow from a bad request.
9
+ *
10
+ * Transport seam: `AnthropicConfig.baseURL` — the tests point the SDK at a
11
+ * loopback server that answers with a scripted status/headers/body. This
12
+ * exercises the REAL vendor client (including its own internal retries,
13
+ * which this group must not disturb).
14
+ */
15
+
16
+ import { type Server, createServer } from 'node:http'
17
+ import type { AddressInfo } from 'node:net'
18
+ import { afterEach, describe, expect, it } from 'vitest'
19
+ import { AnthropicProvider } from '../client.js'
20
+
21
+ /** Obviously fake, non-functional token — present only as a leak probe. */
22
+ const FAKE_CREDENTIAL = 'sk-ant-FAKE-DO-NOT-USE-0000'
23
+
24
+ interface ScriptedReply {
25
+ status: number
26
+ body: string
27
+ headers?: Record<string, string>
28
+ }
29
+
30
+ let server: Server | undefined
31
+
32
+ afterEach(async () => {
33
+ if (server) {
34
+ await new Promise<void>((resolve) => server?.close(() => resolve()))
35
+ server = undefined
36
+ }
37
+ })
38
+
39
+ /** Boot a loopback endpoint that answers every request with `reply`. */
40
+ async function startEndpoint(reply: ScriptedReply): Promise<string> {
41
+ server = createServer((_req, res) => {
42
+ res.writeHead(reply.status, {
43
+ 'Content-Type': 'application/json',
44
+ ...(reply.headers ?? {}),
45
+ })
46
+ res.end(reply.body)
47
+ })
48
+ await new Promise<void>((resolve) => server?.listen(0, '127.0.0.1', () => resolve()))
49
+ const { port } = server.address() as AddressInfo
50
+ return `http://127.0.0.1:${port}`
51
+ }
52
+
53
+ /** Boot a loopback endpoint that streams `frames` as an SSE 200 response. */
54
+ async function startSseEndpoint(frames: string[]): Promise<string> {
55
+ server = createServer((_req, res) => {
56
+ res.writeHead(200, {
57
+ 'Content-Type': 'text/event-stream',
58
+ 'Cache-Control': 'no-cache',
59
+ Connection: 'keep-alive',
60
+ })
61
+ res.end(`${frames.join('\n\n')}\n\n`)
62
+ })
63
+ await new Promise<void>((resolve) => server?.listen(0, '127.0.0.1', () => resolve()))
64
+ const { port } = server.address() as AddressInfo
65
+ return `http://127.0.0.1:${port}`
66
+ }
67
+
68
+ async function captureChatStreamError(reply: ScriptedReply): Promise<unknown> {
69
+ const baseURL = await startEndpoint(reply)
70
+ // maxRetries is deliberately NOT set: this group classifies errors and
71
+ // must leave the vendor SDK's own retry behaviour exactly as it is.
72
+ const provider = new AnthropicProvider({
73
+ apiKey: 'test-key',
74
+ model: 'claude-sonnet-4-5-20250929',
75
+ baseURL,
76
+ })
77
+ try {
78
+ for await (const _chunk of provider.chatStream({
79
+ model: 'claude-sonnet-4-5-20250929',
80
+ messages: [{ role: 'user', content: 'hi' }],
81
+ })) {
82
+ // drain
83
+ }
84
+ } catch (err) {
85
+ return err
86
+ }
87
+ throw new Error('expected chatStream to throw')
88
+ }
89
+
90
+ async function captureProviderError(
91
+ provider: AnthropicProvider,
92
+ signal?: AbortSignal,
93
+ ): Promise<unknown> {
94
+ try {
95
+ for await (const _chunk of provider.chatStream({
96
+ model: 'claude-sonnet-4-5-20250929',
97
+ messages: [{ role: 'user', content: 'hi' }],
98
+ signal,
99
+ })) {
100
+ // drain
101
+ }
102
+ } catch (err) {
103
+ return err
104
+ }
105
+ throw new Error('expected chatStream to throw')
106
+ }
107
+
108
+ describe('@namzu/anthropic — provider error taxonomy', () => {
109
+ it('(a) 429 with `retry-after: 2` throws a throttle-classified error carrying retryAfterMs', async () => {
110
+ const err = await captureChatStreamError({
111
+ status: 429,
112
+ headers: { 'retry-after': '2' },
113
+ body: JSON.stringify({
114
+ type: 'error',
115
+ error: { type: 'rate_limit_error', message: 'slow' },
116
+ }),
117
+ })
118
+
119
+ expect(err).toMatchObject({
120
+ name: 'ProviderRequestError',
121
+ kind: 'throttle',
122
+ status: 429,
123
+ retryAfterMs: 2000,
124
+ providerId: 'anthropic',
125
+ })
126
+ }, 60_000)
127
+
128
+ it("(c) 400 whose body says the prompt is too long classifies as 'context_overflow'", async () => {
129
+ const err = await captureChatStreamError({
130
+ status: 400,
131
+ body: JSON.stringify({
132
+ type: 'error',
133
+ error: {
134
+ type: 'invalid_request_error',
135
+ message: 'prompt is too long: 305231 tokens > 200000 maximum',
136
+ },
137
+ }),
138
+ })
139
+
140
+ expect(err).toMatchObject({
141
+ name: 'ProviderRequestError',
142
+ kind: 'context_overflow',
143
+ status: 400,
144
+ providerId: 'anthropic',
145
+ })
146
+ }, 30_000)
147
+
148
+ it("(c) 400 that is not an overflow classifies as 'bad_request'", async () => {
149
+ const err = await captureChatStreamError({
150
+ status: 400,
151
+ body: JSON.stringify({
152
+ type: 'error',
153
+ error: {
154
+ type: 'invalid_request_error',
155
+ message: 'messages: at least one message required',
156
+ },
157
+ }),
158
+ })
159
+
160
+ expect(err).toMatchObject({
161
+ name: 'ProviderRequestError',
162
+ kind: 'bad_request',
163
+ status: 400,
164
+ providerId: 'anthropic',
165
+ })
166
+ }, 30_000)
167
+
168
+ it("(auth) 401 classifies as 'auth'", async () => {
169
+ const err = await captureChatStreamError({
170
+ status: 401,
171
+ body: JSON.stringify({
172
+ type: 'error',
173
+ error: { type: 'authentication_error', message: 'invalid x-api-key' },
174
+ }),
175
+ })
176
+
177
+ expect(err).toMatchObject({
178
+ name: 'ProviderRequestError',
179
+ kind: 'auth',
180
+ status: 401,
181
+ providerId: 'anthropic',
182
+ })
183
+ }, 30_000)
184
+
185
+ it("529 (upstream overload) classifies as 'server'", async () => {
186
+ const err = await captureChatStreamError({
187
+ status: 529,
188
+ body: JSON.stringify({
189
+ type: 'error',
190
+ error: { type: 'overloaded_error', message: 'Overloaded' },
191
+ }),
192
+ })
193
+
194
+ expect(err).toMatchObject({
195
+ name: 'ProviderRequestError',
196
+ kind: 'server',
197
+ status: 529,
198
+ providerId: 'anthropic',
199
+ })
200
+ }, 60_000)
201
+
202
+ it("MID-STREAM: an `event: error` frame after a 200 classifies as 'server'", async () => {
203
+ // The vendor SDK's SSE reader throws its own `APIError` for an
204
+ // `event: error` frame (core/streaming: `if (sse.event === 'error')`),
205
+ // so the driver's event switch never sees it — the vendor error escapes
206
+ // the driver unclassified, with the frame body interpolated.
207
+ const baseURL = await startSseEndpoint([
208
+ 'event: message_start\ndata: {"type":"message_start","message":{"id":"msg_1","usage":{"input_tokens":5,"output_tokens":0}}}',
209
+ 'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"partial"}}',
210
+ 'event: error\ndata: {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}',
211
+ ])
212
+ const provider = new AnthropicProvider({
213
+ apiKey: 'test-key',
214
+ model: 'claude-sonnet-4-5-20250929',
215
+ baseURL,
216
+ })
217
+
218
+ let caught: unknown
219
+ try {
220
+ for await (const _chunk of provider.chatStream({
221
+ model: 'claude-sonnet-4-5-20250929',
222
+ messages: [{ role: 'user', content: 'hi' }],
223
+ })) {
224
+ // drain
225
+ }
226
+ } catch (err) {
227
+ caught = err
228
+ }
229
+
230
+ expect(caught).toMatchObject({
231
+ name: 'ProviderRequestError',
232
+ kind: 'server',
233
+ providerId: 'anthropic',
234
+ })
235
+ }, 30_000)
236
+
237
+ it('(d) SECURITY: a credential echoed back in a 401 body never reaches the thrown message', async () => {
238
+ const err = await captureChatStreamError({
239
+ status: 401,
240
+ body: JSON.stringify({
241
+ type: 'error',
242
+ error: {
243
+ type: 'authentication_error',
244
+ message: `invalid x-api-key ${FAKE_CREDENTIAL}`,
245
+ },
246
+ }),
247
+ })
248
+
249
+ expect((err as Error).message).not.toContain(FAKE_CREDENTIAL)
250
+ expect(JSON.stringify(err)).not.toContain(FAKE_CREDENTIAL)
251
+ expect('cause' in (err as object)).toBe(false)
252
+ }, 30_000)
253
+
254
+ it('preserves the caller abort reason when the SDK replaces the error object', async () => {
255
+ const controller = new AbortController()
256
+ const reason = new Error('user stopped')
257
+ const sdkAbort = Object.assign(new Error('request aborted'), {
258
+ name: 'APIUserAbortError',
259
+ })
260
+ controller.abort(reason)
261
+ const provider = new AnthropicProvider({
262
+ apiKey: 'test-key',
263
+ model: 'claude-sonnet-4-5-20250929',
264
+ })
265
+ ;(provider as unknown as { client: unknown }).client = {
266
+ messages: { create: async () => Promise.reject(sdkAbort) },
267
+ }
268
+
269
+ const err = await captureProviderError(provider, controller.signal)
270
+
271
+ expect(sdkAbort).not.toBe(reason)
272
+ expect(err).toBe(reason)
273
+ })
274
+ })
package/src/client.ts CHANGED
@@ -10,6 +10,12 @@ import type {
10
10
  TokenUsage,
11
11
  ToolChoice,
12
12
  } from '@namzu/sdk'
13
+ import {
14
+ ProviderRequestError,
15
+ isCallerAbortError,
16
+ isProviderRequestError,
17
+ providerVendorError,
18
+ } from '@namzu/sdk'
13
19
  import type { AnthropicConfig } from './types.js'
14
20
 
15
21
  // Floor for `max_tokens` when neither the request nor the provider
@@ -100,6 +106,7 @@ interface AnthropicToolParam {
100
106
  name: string
101
107
  description: string
102
108
  input_schema: unknown
109
+ strict?: boolean
103
110
  cache_control?: AnthropicCacheControl
104
111
  }
105
112
 
@@ -227,13 +234,19 @@ function toAnthropicMessages(messages: ChatCompletionParams['messages']): Anthro
227
234
  function toAnthropicTools(
228
235
  params: ChatCompletionParams,
229
236
  cachingEnabled: boolean,
237
+ strictToolUseEnabled: boolean,
230
238
  ): AnthropicToolParam[] | undefined {
231
239
  if (!params.tools || params.tools.length === 0) return undefined
232
- const tools: AnthropicToolParam[] = params.tools.map((t) => ({
233
- name: t.function.name,
234
- description: t.function.description ?? '',
235
- input_schema: t.function.parameters ?? { type: 'object' },
236
- }))
240
+ const enforcedNames = new Set(params.enforceToolInputSchema ?? [])
241
+ const tools: AnthropicToolParam[] = params.tools.map((t) => {
242
+ const strict = strictToolUseEnabled && enforcedNames.has(t.function.name)
243
+ return {
244
+ name: t.function.name,
245
+ description: t.function.description ?? '',
246
+ input_schema: t.function.parameters ?? { type: 'object' },
247
+ ...(strict ? { strict: true } : {}),
248
+ }
249
+ })
237
250
  if (cachingEnabled) {
238
251
  // Breakpoint on the tools-array tail: tools render at position 0 of
239
252
  // the cache prefix, so this caches every tool schema even when the
@@ -244,6 +257,24 @@ function toAnthropicTools(
244
257
  return tools
245
258
  }
246
259
 
260
+ function shouldUseStrictToolInputs(
261
+ model: string,
262
+ mode: AnthropicConfig['strictToolUse'] = 'auto',
263
+ ): boolean {
264
+ if (mode === 'on') return true
265
+ if (mode === 'off') return false
266
+
267
+ const normalized = model.toLowerCase()
268
+ if (/^(?:anthropic\/)?claude-mythos-preview$/.test(normalized)) return true
269
+ const version = normalized.match(
270
+ /^(?:anthropic\/)?claude-(?:haiku|sonnet|opus|fable|mythos)-(\d+)(?:[-_.](\d+))?(?:-\d{8})?$/,
271
+ )
272
+ if (!version) return false
273
+ const major = Number(version[1])
274
+ const minor = Number(version[2] ?? 0)
275
+ return major > 4 || (major === 4 && minor >= 5)
276
+ }
277
+
247
278
  function toAnthropicToolChoice(tc?: ToolChoice, parallelToolCalls?: boolean): unknown {
248
279
  // Anthropic expresses "no parallel tool calls" as a field ON tool_choice,
249
280
  // not a top-level param. Only auto/any/tool accept it ('none' fires no
@@ -276,7 +307,13 @@ function applyMessageCacheBreakpoint(messages: AnthropicMessageParam[]): void {
276
307
  if (!msg) continue
277
308
  if (typeof msg.content === 'string') {
278
309
  if (msg.content.length === 0) continue
279
- msg.content = [{ type: 'text', text: msg.content, cache_control: { type: 'ephemeral' } }]
310
+ msg.content = [
311
+ {
312
+ type: 'text',
313
+ text: msg.content,
314
+ cache_control: { type: 'ephemeral' },
315
+ },
316
+ ]
280
317
  return
281
318
  }
282
319
  if (msg.content.length > 0) {
@@ -433,14 +470,19 @@ export class AnthropicProvider implements LLMProvider {
433
470
  // is tools → system → messages, so each later breakpoint covers all
434
471
  // earlier sections too).
435
472
  const cachingEnabled = params.cacheControl !== undefined
473
+ const model = this.resolveModel(params)
436
474
  const system = extractSystem(params.messages, cachingEnabled)
437
475
  const messages = toAnthropicMessages(params.messages)
438
476
  if (cachingEnabled) applyMessageCacheBreakpoint(messages)
439
- const tools = toAnthropicTools(params, cachingEnabled)
477
+ const tools = toAnthropicTools(
478
+ params,
479
+ cachingEnabled,
480
+ shouldUseStrictToolInputs(model, this.config.strictToolUse),
481
+ )
440
482
  const toolChoice = toAnthropicToolChoice(params.toolChoice, params.parallelToolCalls)
441
483
 
442
484
  const body: Record<string, unknown> = {
443
- model: this.resolveModel(params),
485
+ model,
444
486
  messages,
445
487
  max_tokens: params.maxTokens ?? this.config.maxTokens ?? DEFAULT_MAX_TOKENS,
446
488
  stream,
@@ -451,7 +493,10 @@ export class AnthropicProvider implements LLMProvider {
451
493
  // line or Anthropic rejects the request. Emit the block-array form
452
494
  // with the identity prefix first; cache breakpoints (if any) stay
453
495
  // on the tagged blocks behind it, so the ordering survives.
454
- const ccBlock: AnthropicTextBlock = { type: 'text', text: CLAUDE_CODE_SYSTEM_PREFIX }
496
+ const ccBlock: AnthropicTextBlock = {
497
+ type: 'text',
498
+ text: CLAUDE_CODE_SYSTEM_PREFIX,
499
+ }
455
500
  body.system = system ? [ccBlock, ...system] : [ccBlock]
456
501
  } else if (system) {
457
502
  body.system = system
@@ -493,7 +538,21 @@ export class AnthropicProvider implements LLMProvider {
493
538
  const createParams = this.buildCreateParams(params, true)
494
539
  const signal = params.signal
495
540
 
496
- const stream = (await this.createRaw(createParams, { signal })) as AsyncIterable<StreamEvent>
541
+ let stream: AsyncIterable<StreamEvent>
542
+ try {
543
+ stream = (await this.createRaw(createParams, {
544
+ signal,
545
+ })) as AsyncIterable<StreamEvent>
546
+ } catch (err) {
547
+ // The vendor SDK builds its error message FROM the response body, so a
548
+ // credential the upstream echoed back is already inside `err.message`
549
+ // before this code runs (proven with a planted fake token). Classify from
550
+ // the status and drop the vendor error entirely — no re-throw, no
551
+ // `cause`, because a `cause` is exactly what a structured logger walks.
552
+ if (isCallerAbortError(err, signal)) throw signal?.reason ?? err
553
+ if (isProviderRequestError(err)) throw err
554
+ throw providerVendorError({ providerId: 'anthropic', error: err })
555
+ }
497
556
 
498
557
  let messageId = ''
499
558
  // Track active tool-use blocks by content_block index so input_json_delta
@@ -521,9 +580,11 @@ export class AnthropicProvider implements LLMProvider {
521
580
  new Promise<IteratorResult<StreamEvent>>((_, reject) => {
522
581
  timer = setTimeout(() => {
523
582
  reject(
524
- new Error(
525
- `Anthropic stream idle for ${Math.round(streamIdleTimeoutMs / 1000)}s — aborting so the run lifecycle can emit run_failed.`,
526
- ),
583
+ new ProviderRequestError({
584
+ kind: 'network',
585
+ providerId: 'anthropic',
586
+ detail: `stream idle for ${Math.round(streamIdleTimeoutMs / 1000)}s — aborting so the run lifecycle can emit run_failed`,
587
+ }),
527
588
  )
528
589
  }, streamIdleTimeoutMs)
529
590
  }),
@@ -645,13 +706,25 @@ export class AnthropicProvider implements LLMProvider {
645
706
  break
646
707
  }
647
708
  } catch (parseErr) {
648
- yield {
649
- id: messageId,
650
- delta: {},
651
- error: `Stream event error: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,
652
- }
709
+ if (isProviderRequestError(parseErr)) throw parseErr
710
+ throw new ProviderRequestError({
711
+ kind: 'server',
712
+ providerId: 'anthropic',
713
+ detail: 'the provider stream returned malformed data',
714
+ })
653
715
  }
654
716
  }
717
+ } catch (err) {
718
+ // A mid-stream failure arrives AFTER a 200, so the create-call wrap above
719
+ // never sees it: the vendor SDK's SSE reader throws its own APIError for
720
+ // an `event: error` frame, with the frame body as the message. Same
721
+ // treatment — classify, then drop.
722
+ //
723
+ // An abort is NOT a provider failure: restore the caller's signal.reason
724
+ // even when the SDK replaced it with its own APIUserAbortError object.
725
+ if (isCallerAbortError(err, signal)) throw signal?.reason ?? err
726
+ if (isProviderRequestError(err)) throw err
727
+ throw providerVendorError({ providerId: 'anthropic', error: err })
655
728
  } finally {
656
729
  // Always release the underlying HTTP/2 connection — both on
657
730
  // idle-timeout rejection (bubbling up) and on normal stream
package/src/types.ts CHANGED
@@ -29,6 +29,12 @@ export interface AnthropicConfig {
29
29
  defaultHeaders?: Record<string, string>
30
30
  /** Default max_tokens (Anthropic requires this field). Default: 64000. */
31
31
  maxTokens?: number
32
+ /**
33
+ * Constrained tool-input policy. `auto` enables strict tool use for known
34
+ * Claude 4.5+ model identifiers, `on` opts a compatible proxy alias in,
35
+ * and `off` disables it. Default: `auto`.
36
+ */
37
+ strictToolUse?: 'auto' | 'on' | 'off'
32
38
  /**
33
39
  * Bearer-style OAuth access token (mutually exclusive with `apiKey`).
34
40
  * Use when the credential is an Anthropic OAuth or Claude Code OAuth