@namzu/anthropic 0.1.2 → 1.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.
@@ -56,8 +56,13 @@ describe('@namzu/anthropic', () => {
56
56
  expect(provider.name).toBe('Anthropic')
57
57
  })
58
58
 
59
- it('throws when constructed without an apiKey', () => {
60
- expect(() => new AnthropicProvider({} as any)).toThrow(/apiKey is required/)
59
+ it('throws when constructed without an apiKey or authToken', () => {
60
+ expect(() => new AnthropicProvider({} as any)).toThrow(/apiKey.*or.*authToken.*required/)
61
+ })
62
+
63
+ it('accepts an authToken instead of an apiKey (OAuth path)', () => {
64
+ const provider = new AnthropicProvider({ authToken: 'cc-oauth-token' })
65
+ expect(provider.id).toBe('anthropic')
61
66
  })
62
67
 
63
68
  it('creates via ProviderRegistry.create with the registered type', () => {
@@ -70,5 +75,86 @@ describe('@namzu/anthropic', () => {
70
75
  expect(provider.id).toBe('anthropic')
71
76
  expect(capabilities).toEqual(ANTHROPIC_CAPABILITIES)
72
77
  })
78
+
79
+ it('does not enforce a provider-local stream idle timeout by default', async () => {
80
+ const provider = new AnthropicProvider({
81
+ apiKey: 'test-key',
82
+ model: 'claude-sonnet-4-5-20250929',
83
+ })
84
+ ;(provider as any).client = {
85
+ messages: {
86
+ create: async () => delayedAnthropicStream(10),
87
+ },
88
+ }
89
+
90
+ const chunks = []
91
+ for await (const chunk of provider.chatStream({
92
+ model: 'claude-sonnet-4-5-20250929',
93
+ messages: [{ role: 'user', content: 'hello' }],
94
+ maxTokens: 100,
95
+ })) {
96
+ chunks.push(chunk)
97
+ }
98
+
99
+ expect(chunks.length).toBeGreaterThan(0)
100
+ })
101
+
102
+ it('supports an opt-in stream idle timeout for deployments that need it', async () => {
103
+ const provider = new AnthropicProvider({
104
+ apiKey: 'test-key',
105
+ model: 'claude-sonnet-4-5-20250929',
106
+ streamIdleTimeoutMs: 1,
107
+ })
108
+ ;(provider as any).client = {
109
+ messages: {
110
+ create: async () => delayedAnthropicStream(20),
111
+ },
112
+ }
113
+
114
+ const drain = async () => {
115
+ for await (const _chunk of provider.chatStream({
116
+ model: 'claude-sonnet-4-5-20250929',
117
+ messages: [{ role: 'user', content: 'hello' }],
118
+ maxTokens: 100,
119
+ })) {
120
+ // Drain the stream.
121
+ }
122
+ }
123
+
124
+ await expect(drain()).rejects.toThrow(/stream idle/)
125
+ })
73
126
  })
74
127
  })
128
+
129
+ async function* delayedAnthropicStream(delayMs: number) {
130
+ yield {
131
+ type: 'message_start',
132
+ message: {
133
+ id: 'msg_test',
134
+ usage: { input_tokens: 1, output_tokens: 0 },
135
+ },
136
+ }
137
+ await new Promise((resolve) => setTimeout(resolve, delayMs))
138
+ yield {
139
+ type: 'content_block_start',
140
+ index: 0,
141
+ content_block: { type: 'text' },
142
+ }
143
+ yield {
144
+ type: 'content_block_delta',
145
+ index: 0,
146
+ delta: { type: 'text_delta', text: 'ok' },
147
+ }
148
+ yield {
149
+ type: 'content_block_stop',
150
+ index: 0,
151
+ }
152
+ yield {
153
+ type: 'message_delta',
154
+ delta: { stop_reason: 'end_turn' },
155
+ usage: { output_tokens: 1 },
156
+ }
157
+ yield {
158
+ type: 'message_stop',
159
+ }
160
+ }
package/src/client.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { execFileSync } from 'node:child_process'
1
2
  import Anthropic from '@anthropic-ai/sdk'
2
3
  import type {
3
4
  ChatCompletionParams,
@@ -10,8 +11,49 @@ import type {
10
11
  } from '@namzu/sdk'
11
12
  import type { AnthropicConfig } from './types.js'
12
13
 
13
- const DEFAULT_MAX_TOKENS = 4096
14
+ // Floor for `max_tokens` when neither the request nor the provider
15
+ // config supplied one. Anthropic's API requires the field, so we cannot
16
+ // truly omit it — but 4096 (the original SDK example default) is far
17
+ // below what Sonnet 4.6 / Opus 4.7 natively emit, and would silently
18
+ // clip 20k-word documents. 64k is the canonical "long output" budget
19
+ // these models advertise; the model still stops at its own native
20
+ // ceiling, so passing 64k just means "don't bound below the model".
21
+ const DEFAULT_MAX_TOKENS = 64_000
14
22
  const DEFAULT_TIMEOUT_MS = 120_000
23
+ const DEFAULT_STREAM_IDLE_TIMEOUT_MS = 0
24
+
25
+ // Claude Code OAuth tokens are scoped to Claude Code usage. Anthropic
26
+ // authorizes them only when three signals are all present, else 401:
27
+ // 1. the OAuth beta headers,
28
+ // 2. a `claude-cli/<version>` user-agent (version validated server-side),
29
+ // 3. a system prompt whose first block is the Claude Code identity line.
30
+ const OAUTH_BETAS = 'claude-code-20250219,oauth-2025-04-20'
31
+ const CLAUDE_CODE_SYSTEM_PREFIX = "You are Claude Code, Anthropic's official CLI for Claude."
32
+ const CLAUDE_CODE_VERSION_FALLBACK = '2.1.74'
33
+
34
+ let claudeCodeVersionCache: string | null = null
35
+ function detectClaudeCodeVersion(): string {
36
+ if (claudeCodeVersionCache !== null) return claudeCodeVersionCache
37
+ for (const bin of ['claude', 'claude-code']) {
38
+ try {
39
+ const out = execFileSync(bin, ['--version'], {
40
+ encoding: 'utf8',
41
+ timeout: 5_000,
42
+ stdio: ['ignore', 'pipe', 'ignore'],
43
+ })
44
+ .trim()
45
+ .split(/\s+/)[0]
46
+ if (out && /^\d/.test(out)) {
47
+ claudeCodeVersionCache = out
48
+ return out
49
+ }
50
+ } catch {
51
+ // try next binary
52
+ }
53
+ }
54
+ claudeCodeVersionCache = CLAUDE_CODE_VERSION_FALLBACK
55
+ return CLAUDE_CODE_VERSION_FALLBACK
56
+ }
15
57
 
16
58
  // --------------------------------------------------------------------------------------
17
59
  // Message translation: @namzu/sdk → Anthropic Messages API
@@ -35,7 +77,22 @@ interface AnthropicToolResultBlock {
35
77
  content: string
36
78
  }
37
79
 
38
- type AnthropicContentBlock = AnthropicTextBlock | AnthropicToolUseBlock | AnthropicToolResultBlock
80
+ interface AnthropicImageBlock {
81
+ type: 'image'
82
+ source: { type: 'base64'; media_type: string; data: string }
83
+ }
84
+
85
+ /** Shape of an SDK `ImageAttachment` (read structurally to avoid coupling). */
86
+ interface AttachmentLike {
87
+ readonly data: string
88
+ readonly mediaType: string
89
+ }
90
+
91
+ type AnthropicContentBlock =
92
+ | AnthropicTextBlock
93
+ | AnthropicToolUseBlock
94
+ | AnthropicToolResultBlock
95
+ | AnthropicImageBlock
39
96
 
40
97
  interface AnthropicMessageParam {
41
98
  role: 'user' | 'assistant'
@@ -103,6 +160,21 @@ function toAnthropicMessages(messages: ChatCompletionParams['messages']): Anthro
103
160
  }
104
161
 
105
162
  const content = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content)
163
+ // User message with image attachments → multimodal content blocks
164
+ // (text first, then each image as a base64 image block).
165
+ const attachments = (msg as { attachments?: readonly AttachmentLike[] }).attachments
166
+ if (msg.role === 'user' && attachments && attachments.length > 0) {
167
+ const blocks: AnthropicContentBlock[] = []
168
+ if (content.length > 0) blocks.push({ type: 'text', text: content })
169
+ for (const att of attachments) {
170
+ blocks.push({
171
+ type: 'image',
172
+ source: { type: 'base64', media_type: att.mediaType, data: att.data },
173
+ })
174
+ }
175
+ out.push({ role: 'user', content: blocks })
176
+ continue
177
+ }
106
178
  out.push({
107
179
  role: msg.role === 'assistant' ? 'assistant' : 'user',
108
180
  content,
@@ -189,48 +261,6 @@ function mapStopReason(reason?: string | null): NamzuFinishReason {
189
261
  }
190
262
  }
191
263
 
192
- // --------------------------------------------------------------------------------------
193
- // Response content extraction
194
- // --------------------------------------------------------------------------------------
195
-
196
- interface RawAnthropicResponseBlock {
197
- type: string
198
- text?: string
199
- id?: string
200
- name?: string
201
- input?: unknown
202
- }
203
-
204
- function extractResponseContent(content?: RawAnthropicResponseBlock[]): {
205
- text: string | null
206
- toolCalls: ChatCompletionResponse['message']['toolCalls']
207
- } {
208
- if (!content || content.length === 0) return { text: null, toolCalls: undefined }
209
-
210
- let text: string | null = null
211
- const toolCalls: NonNullable<ChatCompletionResponse['message']['toolCalls']> = []
212
-
213
- for (const block of content) {
214
- if (block.type === 'text' && typeof block.text === 'string') {
215
- text = (text ?? '') + block.text
216
- } else if (block.type === 'tool_use') {
217
- toolCalls.push({
218
- id: block.id ?? `tool-${Date.now()}`,
219
- type: 'function',
220
- function: {
221
- name: block.name ?? '',
222
- arguments: JSON.stringify(block.input ?? {}),
223
- },
224
- })
225
- }
226
- }
227
-
228
- return {
229
- text,
230
- toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
231
- }
232
- }
233
-
234
264
  // --------------------------------------------------------------------------------------
235
265
  // Stream event types
236
266
  // --------------------------------------------------------------------------------------
@@ -261,17 +291,31 @@ export class AnthropicProvider implements LLMProvider {
261
291
  private config: AnthropicConfig
262
292
 
263
293
  constructor(config: AnthropicConfig) {
264
- if (!config.apiKey) {
265
- throw new Error('AnthropicProvider: apiKey is required')
294
+ if (!config.apiKey && !config.authToken) {
295
+ throw new Error('AnthropicProvider: either `apiKey` or `authToken` is required')
266
296
  }
267
297
  this.config = config
268
298
 
269
299
  const clientOpts: Record<string, unknown> = {
270
- apiKey: config.apiKey,
271
300
  timeout: config.timeout ?? DEFAULT_TIMEOUT_MS,
272
301
  }
302
+ if (config.authToken) {
303
+ clientOpts.authToken = config.authToken
304
+ // OAuth routes require both beta flags + a Claude Code user-agent;
305
+ // without them Anthropic rejects subscription / Claude Code OAuth
306
+ // tokens (intermittent 401/500). The system-prompt identity block
307
+ // is added per-request in buildCreateParams.
308
+ const headers: Record<string, string> = {
309
+ 'anthropic-beta': OAUTH_BETAS,
310
+ 'user-agent': `claude-cli/${detectClaudeCodeVersion()} (external, cli)`,
311
+ ...(config.defaultHeaders ?? {}),
312
+ }
313
+ clientOpts.defaultHeaders = headers
314
+ } else {
315
+ clientOpts.apiKey = config.apiKey
316
+ if (config.defaultHeaders) clientOpts.defaultHeaders = config.defaultHeaders
317
+ }
273
318
  if (config.baseURL) clientOpts.baseURL = config.baseURL
274
- if (config.defaultHeaders) clientOpts.defaultHeaders = config.defaultHeaders
275
319
 
276
320
  this.client = new Anthropic(clientOpts)
277
321
  }
@@ -302,7 +346,15 @@ export class AnthropicProvider implements LLMProvider {
302
346
  stream,
303
347
  }
304
348
 
305
- if (system) body.system = system
349
+ if (this.config.authToken) {
350
+ // OAuth: the first system block must be the Claude Code identity
351
+ // line or Anthropic rejects the request. Emit the block-array form
352
+ // with the identity prefix first.
353
+ const ccBlock = { type: 'text' as const, text: CLAUDE_CODE_SYSTEM_PREFIX }
354
+ body.system = system ? [ccBlock, { type: 'text' as const, text: system }] : [ccBlock]
355
+ } else if (system) {
356
+ body.system = system
357
+ }
306
358
  if (tools) body.tools = tools
307
359
  if (toolChoice) body.tool_choice = toolChoice
308
360
  if (params.temperature !== undefined) body.temperature = params.temperature
@@ -326,32 +378,6 @@ export class AnthropicProvider implements LLMProvider {
326
378
  return create.call(this.client.messages, body)
327
379
  }
328
380
 
329
- async chat(params: ChatCompletionParams): Promise<ChatCompletionResponse> {
330
- const createParams = this.buildCreateParams(params, false)
331
-
332
- const response = (await this.createRaw(createParams)) as {
333
- id?: string
334
- model?: string
335
- content: RawAnthropicResponseBlock[]
336
- stop_reason?: string | null
337
- usage?: RawAnthropicUsage
338
- }
339
-
340
- const { text, toolCalls } = extractResponseContent(response.content)
341
-
342
- return {
343
- id: response.id ?? `anthropic-${Date.now()}`,
344
- model: response.model ?? this.resolveModel(params),
345
- message: {
346
- role: 'assistant',
347
- content: text,
348
- toolCalls,
349
- },
350
- finishReason: mapStopReason(response.stop_reason),
351
- usage: parseUsage(response.usage),
352
- }
353
- }
354
-
355
381
  async *chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk> {
356
382
  const createParams = this.buildCreateParams(params, true)
357
383
 
@@ -362,97 +388,162 @@ export class AnthropicProvider implements LLMProvider {
362
388
  // fragments can reference the right tool call.
363
389
  const activeTools = new Map<number, { id: string; name: string }>()
364
390
 
365
- for await (const event of stream) {
391
+ // Anthropic Messages API streams over SSE. Do not impose a
392
+ // provider-local 90s idle cutoff by default: long reasoning or
393
+ // long tool-argument generation can legitimately pause between
394
+ // SSE events, and cutting it here turns a healthy Messages API
395
+ // run into a false "tool input truncated" failure. Deployments
396
+ // that still need a per-event watchdog can opt in via
397
+ // `streamIdleTimeoutMs`; otherwise the request timeout and caller
398
+ // AbortSignal own lifecycle cancellation.
399
+ const streamIdleTimeoutMs = this.config.streamIdleTimeoutMs ?? DEFAULT_STREAM_IDLE_TIMEOUT_MS
400
+ const iter = (stream as AsyncIterable<StreamEvent>)[Symbol.asyncIterator]()
401
+ const nextWithIdleTimeout = async (): Promise<IteratorResult<StreamEvent>> => {
402
+ if (!Number.isFinite(streamIdleTimeoutMs) || streamIdleTimeoutMs <= 0) {
403
+ return iter.next()
404
+ }
405
+ let timer: ReturnType<typeof setTimeout> | undefined
366
406
  try {
367
- switch (event.type) {
368
- case 'message_start': {
369
- if (event.message?.id) messageId = event.message.id
370
- if (event.message?.usage) {
371
- yield {
372
- id: messageId,
373
- delta: {},
374
- usage: parseUsage(event.message.usage),
407
+ return await Promise.race([
408
+ iter.next(),
409
+ new Promise<IteratorResult<StreamEvent>>((_, reject) => {
410
+ timer = setTimeout(() => {
411
+ reject(
412
+ new Error(
413
+ `Anthropic stream idle for ${Math.round(streamIdleTimeoutMs / 1000)}s — aborting so the run lifecycle can emit run_failed.`,
414
+ ),
415
+ )
416
+ }, streamIdleTimeoutMs)
417
+ }),
418
+ ])
419
+ } finally {
420
+ if (timer !== undefined) clearTimeout(timer)
421
+ }
422
+ }
423
+
424
+ try {
425
+ for (;;) {
426
+ const result = await nextWithIdleTimeout()
427
+ if (result.done) break
428
+ const event = result.value
429
+ try {
430
+ switch (event.type) {
431
+ case 'message_start': {
432
+ if (event.message?.id) messageId = event.message.id
433
+ if (event.message?.usage) {
434
+ yield {
435
+ id: messageId,
436
+ delta: {},
437
+ usage: parseUsage(event.message.usage),
438
+ }
375
439
  }
440
+ break
376
441
  }
377
- break
378
- }
379
- case 'content_block_start': {
380
- const idx = event.index ?? 0
381
- const block = event.content_block
382
- if (block?.type === 'tool_use') {
383
- const toolId = block.id ?? `tool-${Date.now()}`
384
- activeTools.set(idx, { id: toolId, name: block.name ?? '' })
385
- yield {
386
- id: messageId,
387
- delta: {
388
- toolCalls: [
389
- {
390
- index: idx,
391
- id: toolId,
392
- type: 'function',
393
- function: { name: block.name ?? '' },
394
- },
395
- ],
396
- },
442
+ case 'content_block_start': {
443
+ const idx = event.index ?? 0
444
+ const block = event.content_block
445
+ if (block?.type === 'tool_use') {
446
+ const toolId = block.id ?? `tool-${Date.now()}`
447
+ activeTools.set(idx, { id: toolId, name: block.name ?? '' })
448
+ yield {
449
+ id: messageId,
450
+ delta: {
451
+ toolCalls: [
452
+ {
453
+ index: idx,
454
+ id: toolId,
455
+ type: 'function',
456
+ function: { name: block.name ?? '' },
457
+ },
458
+ ],
459
+ },
460
+ }
397
461
  }
462
+ break
398
463
  }
399
- break
400
- }
401
- case 'content_block_delta': {
402
- const idx = event.index ?? 0
403
- const delta = event.delta
404
- if (delta?.type === 'text_delta' && delta.text) {
405
- yield { id: messageId, delta: { content: delta.text } }
406
- } else if (delta?.type === 'input_json_delta' && delta.partial_json !== undefined) {
407
- const active = activeTools.get(idx)
408
- yield {
409
- id: messageId,
410
- delta: {
411
- toolCalls: [
412
- {
413
- index: idx,
414
- id: active?.id,
415
- function: { arguments: delta.partial_json },
416
- },
417
- ],
418
- },
464
+ case 'content_block_delta': {
465
+ const idx = event.index ?? 0
466
+ const delta = event.delta
467
+ if (delta?.type === 'text_delta' && delta.text) {
468
+ yield { id: messageId, delta: { content: delta.text } }
469
+ } else if (delta?.type === 'input_json_delta' && delta.partial_json !== undefined) {
470
+ const active = activeTools.get(idx)
471
+ yield {
472
+ id: messageId,
473
+ delta: {
474
+ toolCalls: [
475
+ {
476
+ index: idx,
477
+ id: active?.id,
478
+ function: { arguments: delta.partial_json },
479
+ },
480
+ ],
481
+ },
482
+ }
419
483
  }
484
+ break
420
485
  }
421
- break
422
- }
423
- case 'content_block_stop':
424
- // Aggregation is consumer-side — nothing to emit.
425
- break
426
- case 'message_delta': {
427
- if (event.delta?.stop_reason) {
428
- yield {
429
- id: messageId,
430
- delta: {},
431
- finishReason: mapStopReason(event.delta.stop_reason),
432
- usage: event.usage ? parseUsage(event.usage) : undefined,
486
+ case 'content_block_stop': {
487
+ // For tool_use blocks we MUST emit a `toolCallEnd`
488
+ // signal so the consumer-side aggregator (sdk
489
+ // runtime/query/iteration) can flush the buffered
490
+ // `argsBuf` and JSON.parse it into the tool input.
491
+ // Without this signal the executor sees an empty
492
+ // `arguments` string and rejects the call with
493
+ // `Error: Invalid JSON in tool arguments for "<tool>"`
494
+ // — exactly the failure the live cowork test
495
+ // surfaced (Bash + Write both blank-input failed).
496
+ const idx = event.index ?? 0
497
+ const active = activeTools.get(idx)
498
+ if (active) {
499
+ yield {
500
+ id: messageId,
501
+ delta: {
502
+ toolCallEnd: { index: idx, id: active.id },
503
+ },
504
+ }
505
+ activeTools.delete(idx)
433
506
  }
434
- } else if (event.usage) {
435
- yield {
436
- id: messageId,
437
- delta: {},
438
- usage: parseUsage(event.usage),
507
+ break
508
+ }
509
+ case 'message_delta': {
510
+ if (event.delta?.stop_reason) {
511
+ yield {
512
+ id: messageId,
513
+ delta: {},
514
+ finishReason: mapStopReason(event.delta.stop_reason),
515
+ usage: event.usage ? parseUsage(event.usage) : undefined,
516
+ }
517
+ } else if (event.usage) {
518
+ yield {
519
+ id: messageId,
520
+ delta: {},
521
+ usage: parseUsage(event.usage),
522
+ }
439
523
  }
524
+ break
440
525
  }
441
- break
526
+ case 'message_stop':
527
+ return
528
+ default:
529
+ // Ignore unknown / ping / opaque events.
530
+ break
531
+ }
532
+ } catch (parseErr) {
533
+ yield {
534
+ id: messageId,
535
+ delta: {},
536
+ error: `Stream event error: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,
442
537
  }
443
- case 'message_stop':
444
- return
445
- default:
446
- // Ignore unknown / ping / opaque events.
447
- break
448
- }
449
- } catch (parseErr) {
450
- yield {
451
- id: messageId,
452
- delta: {},
453
- error: `Stream event error: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,
454
538
  }
455
539
  }
540
+ } finally {
541
+ // Always release the underlying HTTP/2 connection — both on
542
+ // idle-timeout rejection (bubbling up) and on normal stream
543
+ // end (`message_stop` returned out of the loop). Leaving
544
+ // the SSE connection open until OS-level timeout was the
545
+ // gap Codex called out.
546
+ await iter.return?.().catch(() => undefined)
456
547
  }
457
548
  }
458
549
 
package/src/types.ts CHANGED
@@ -8,17 +8,35 @@
8
8
  */
9
9
 
10
10
  export interface AnthropicConfig {
11
- apiKey: string
11
+ /**
12
+ * Console API key (`sk-ant-api-*`). Mutually exclusive with `authToken`.
13
+ * Exactly one of `apiKey` / `authToken` must be set.
14
+ */
15
+ apiKey?: string
12
16
  /** Default model. Can be overridden per-call. */
13
17
  model?: string
14
18
  /** Override base URL (e.g. for AWS Bedrock Anthropic or Google Vertex endpoints — though use @namzu/bedrock for those). */
15
19
  baseURL?: string
16
20
  /** Request timeout in ms. */
17
21
  timeout?: number
22
+ /**
23
+ * Optional per-event stream idle watchdog in ms. Disabled by default.
24
+ * Use only for deployments that need to fail a stalled SSE connection
25
+ * independently from the request timeout.
26
+ */
27
+ streamIdleTimeoutMs?: number
18
28
  /** Custom headers appended to every request. */
19
29
  defaultHeaders?: Record<string, string>
20
- /** Default max_tokens (Anthropic requires this field). Default: 4096. */
30
+ /** Default max_tokens (Anthropic requires this field). Default: 64000. */
21
31
  maxTokens?: number
32
+ /**
33
+ * Bearer-style OAuth access token (mutually exclusive with `apiKey`).
34
+ * Use when the credential is an Anthropic OAuth or Claude Code OAuth
35
+ * token rather than an `sk-ant-api-*` console key. The underlying SDK
36
+ * routes the value as `Authorization: Bearer <token>` instead of
37
+ * `x-api-key`.
38
+ */
39
+ authToken?: string
22
40
  }
23
41
 
24
42
  export interface AnthropicProviderConfig extends AnthropicConfig {