@namzu/anthropic 0.2.0 → 1.1.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.
- package/CHANGELOG.md +132 -0
- package/dist/__tests__/anthropic.test.js +218 -2
- package/dist/__tests__/anthropic.test.js.map +1 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +336 -115
- package/dist/client.js.map +1 -1
- package/dist/types.d.ts +20 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/__tests__/anthropic.test.ts +249 -2
- package/src/client.ts +367 -107
- package/src/types.ts +20 -2
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,16 +11,67 @@ import type {
|
|
|
10
11
|
} from '@namzu/sdk'
|
|
11
12
|
import type { AnthropicConfig } from './types.js'
|
|
12
13
|
|
|
13
|
-
|
|
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
|
|
18
60
|
// --------------------------------------------------------------------------------------
|
|
19
61
|
|
|
62
|
+
/**
|
|
63
|
+
* Anthropic prompt-cache breakpoint marker. A `cache_control` on a block
|
|
64
|
+
* caches everything up to and including that block in the fixed render
|
|
65
|
+
* order tools → system → messages (max 4 breakpoints per request).
|
|
66
|
+
*/
|
|
67
|
+
interface AnthropicCacheControl {
|
|
68
|
+
type: 'ephemeral'
|
|
69
|
+
}
|
|
70
|
+
|
|
20
71
|
interface AnthropicTextBlock {
|
|
21
72
|
type: 'text'
|
|
22
73
|
text: string
|
|
74
|
+
cache_control?: AnthropicCacheControl
|
|
23
75
|
}
|
|
24
76
|
|
|
25
77
|
interface AnthropicToolUseBlock {
|
|
@@ -27,29 +79,72 @@ interface AnthropicToolUseBlock {
|
|
|
27
79
|
id: string
|
|
28
80
|
name: string
|
|
29
81
|
input: unknown
|
|
82
|
+
cache_control?: AnthropicCacheControl
|
|
30
83
|
}
|
|
31
84
|
|
|
32
85
|
interface AnthropicToolResultBlock {
|
|
33
86
|
type: 'tool_result'
|
|
34
87
|
tool_use_id: string
|
|
35
88
|
content: string
|
|
89
|
+
cache_control?: AnthropicCacheControl
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
interface AnthropicImageBlock {
|
|
93
|
+
type: 'image'
|
|
94
|
+
source: { type: 'base64'; media_type: string; data: string }
|
|
95
|
+
cache_control?: AnthropicCacheControl
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
interface AnthropicToolParam {
|
|
99
|
+
name: string
|
|
100
|
+
description: string
|
|
101
|
+
input_schema: unknown
|
|
102
|
+
cache_control?: AnthropicCacheControl
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Shape of an SDK `ImageAttachment` (read structurally to avoid coupling). */
|
|
106
|
+
interface AttachmentLike {
|
|
107
|
+
readonly data: string
|
|
108
|
+
readonly mediaType: string
|
|
36
109
|
}
|
|
37
110
|
|
|
38
|
-
type AnthropicContentBlock =
|
|
111
|
+
type AnthropicContentBlock =
|
|
112
|
+
| AnthropicTextBlock
|
|
113
|
+
| AnthropicToolUseBlock
|
|
114
|
+
| AnthropicToolResultBlock
|
|
115
|
+
| AnthropicImageBlock
|
|
39
116
|
|
|
40
117
|
interface AnthropicMessageParam {
|
|
41
118
|
role: 'user' | 'assistant'
|
|
42
119
|
content: string | AnthropicContentBlock[]
|
|
43
120
|
}
|
|
44
121
|
|
|
45
|
-
|
|
46
|
-
|
|
122
|
+
/**
|
|
123
|
+
* System messages become a block array (one block per SystemMessage) so the
|
|
124
|
+
* runtime's `cacheHint` segment boundaries survive into the request: the
|
|
125
|
+
* PromptBuilder tags the static segment `'cache'` and the per-run dynamic
|
|
126
|
+
* segment `'ephemeral'`. When caching is enabled, the LAST `'cache'`-tagged
|
|
127
|
+
* block carries the `cache_control` breakpoint — everything up to it
|
|
128
|
+
* (tools + static system) is cached; dynamic blocks after it are not.
|
|
129
|
+
*/
|
|
130
|
+
function extractSystem(
|
|
131
|
+
messages: ChatCompletionParams['messages'],
|
|
132
|
+
cachingEnabled: boolean,
|
|
133
|
+
): AnthropicTextBlock[] | undefined {
|
|
134
|
+
const blocks: AnthropicTextBlock[] = []
|
|
135
|
+
let lastCacheTagged: AnthropicTextBlock | undefined
|
|
47
136
|
for (const msg of messages) {
|
|
48
|
-
if (msg.role === 'system' && typeof msg.content === 'string') {
|
|
49
|
-
|
|
137
|
+
if (msg.role === 'system' && typeof msg.content === 'string' && msg.content.length > 0) {
|
|
138
|
+
const block: AnthropicTextBlock = { type: 'text', text: msg.content }
|
|
139
|
+
blocks.push(block)
|
|
140
|
+
if (msg.cacheHint === 'cache') lastCacheTagged = block
|
|
50
141
|
}
|
|
51
142
|
}
|
|
52
|
-
|
|
143
|
+
if (blocks.length === 0) return undefined
|
|
144
|
+
if (cachingEnabled && lastCacheTagged) {
|
|
145
|
+
lastCacheTagged.cache_control = { type: 'ephemeral' }
|
|
146
|
+
}
|
|
147
|
+
return blocks
|
|
53
148
|
}
|
|
54
149
|
|
|
55
150
|
function toAnthropicMessages(messages: ChatCompletionParams['messages']): AnthropicMessageParam[] {
|
|
@@ -103,6 +198,21 @@ function toAnthropicMessages(messages: ChatCompletionParams['messages']): Anthro
|
|
|
103
198
|
}
|
|
104
199
|
|
|
105
200
|
const content = typeof msg.content === 'string' ? msg.content : JSON.stringify(msg.content)
|
|
201
|
+
// User message with image attachments → multimodal content blocks
|
|
202
|
+
// (text first, then each image as a base64 image block).
|
|
203
|
+
const attachments = (msg as { attachments?: readonly AttachmentLike[] }).attachments
|
|
204
|
+
if (msg.role === 'user' && attachments && attachments.length > 0) {
|
|
205
|
+
const blocks: AnthropicContentBlock[] = []
|
|
206
|
+
if (content.length > 0) blocks.push({ type: 'text', text: content })
|
|
207
|
+
for (const att of attachments) {
|
|
208
|
+
blocks.push({
|
|
209
|
+
type: 'image',
|
|
210
|
+
source: { type: 'base64', media_type: att.mediaType, data: att.data },
|
|
211
|
+
})
|
|
212
|
+
}
|
|
213
|
+
out.push({ role: 'user', content: blocks })
|
|
214
|
+
continue
|
|
215
|
+
}
|
|
106
216
|
out.push({
|
|
107
217
|
role: msg.role === 'assistant' ? 'assistant' : 'user',
|
|
108
218
|
content,
|
|
@@ -113,28 +223,69 @@ function toAnthropicMessages(messages: ChatCompletionParams['messages']): Anthro
|
|
|
113
223
|
return out
|
|
114
224
|
}
|
|
115
225
|
|
|
116
|
-
function toAnthropicTools(
|
|
226
|
+
function toAnthropicTools(
|
|
227
|
+
params: ChatCompletionParams,
|
|
228
|
+
cachingEnabled: boolean,
|
|
229
|
+
): AnthropicToolParam[] | undefined {
|
|
117
230
|
if (!params.tools || params.tools.length === 0) return undefined
|
|
118
|
-
|
|
231
|
+
const tools: AnthropicToolParam[] = params.tools.map((t) => ({
|
|
119
232
|
name: t.function.name,
|
|
120
233
|
description: t.function.description ?? '',
|
|
121
234
|
input_schema: t.function.parameters ?? { type: 'object' },
|
|
122
235
|
}))
|
|
236
|
+
if (cachingEnabled) {
|
|
237
|
+
// Breakpoint on the tools-array tail: tools render at position 0 of
|
|
238
|
+
// the cache prefix, so this caches every tool schema even when the
|
|
239
|
+
// system/message breakpoints downstream get invalidated.
|
|
240
|
+
const tail = tools[tools.length - 1]
|
|
241
|
+
if (tail) tail.cache_control = { type: 'ephemeral' }
|
|
242
|
+
}
|
|
243
|
+
return tools
|
|
123
244
|
}
|
|
124
245
|
|
|
125
|
-
function toAnthropicToolChoice(tc?: ToolChoice): unknown {
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
246
|
+
function toAnthropicToolChoice(tc?: ToolChoice, parallelToolCalls?: boolean): unknown {
|
|
247
|
+
// Anthropic expresses "no parallel tool calls" as a field ON tool_choice,
|
|
248
|
+
// not a top-level param. Only auto/any/tool accept it ('none' fires no
|
|
249
|
+
// tools, so the field is meaningless there).
|
|
250
|
+
const disable = parallelToolCalls === false ? { disable_parallel_tool_use: true } : undefined
|
|
251
|
+
if (tc === undefined) {
|
|
252
|
+
return disable ? { type: 'auto', ...disable } : undefined
|
|
253
|
+
}
|
|
254
|
+
if (tc === 'auto') return { type: 'auto', ...disable }
|
|
255
|
+
if (tc === 'required') return { type: 'any', ...disable }
|
|
256
|
+
// 'none' is first-class on the Messages API ("prevents Claude from using
|
|
257
|
+
// any tools"). Mapping it this way — instead of omitting the tools param —
|
|
258
|
+
// keeps the tools+system cache prefix intact and avoids a 400 when the
|
|
259
|
+
// conversation history still carries tool_use/tool_result blocks.
|
|
260
|
+
if (tc === 'none') return { type: 'none' }
|
|
132
261
|
if (typeof tc === 'object' && tc.type === 'function') {
|
|
133
|
-
return { type: 'tool', name: tc.function.name }
|
|
262
|
+
return { type: 'tool', name: tc.function.name, ...disable }
|
|
134
263
|
}
|
|
135
264
|
return undefined
|
|
136
265
|
}
|
|
137
266
|
|
|
267
|
+
/**
|
|
268
|
+
* Final cache breakpoint: the last content block of the last non-empty
|
|
269
|
+
* message. Caches the whole conversation prefix so the next iteration
|
|
270
|
+
* (which only appends messages) reads the prior history at cache rates.
|
|
271
|
+
*/
|
|
272
|
+
function applyMessageCacheBreakpoint(messages: AnthropicMessageParam[]): void {
|
|
273
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
274
|
+
const msg = messages[i]
|
|
275
|
+
if (!msg) continue
|
|
276
|
+
if (typeof msg.content === 'string') {
|
|
277
|
+
if (msg.content.length === 0) continue
|
|
278
|
+
msg.content = [{ type: 'text', text: msg.content, cache_control: { type: 'ephemeral' } }]
|
|
279
|
+
return
|
|
280
|
+
}
|
|
281
|
+
if (msg.content.length > 0) {
|
|
282
|
+
const last = msg.content[msg.content.length - 1]
|
|
283
|
+
if (last) last.cache_control = { type: 'ephemeral' }
|
|
284
|
+
return
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
138
289
|
// --------------------------------------------------------------------------------------
|
|
139
290
|
// Usage parsing
|
|
140
291
|
// --------------------------------------------------------------------------------------
|
|
@@ -219,17 +370,31 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
219
370
|
private config: AnthropicConfig
|
|
220
371
|
|
|
221
372
|
constructor(config: AnthropicConfig) {
|
|
222
|
-
if (!config.apiKey) {
|
|
223
|
-
throw new Error('AnthropicProvider: apiKey is required')
|
|
373
|
+
if (!config.apiKey && !config.authToken) {
|
|
374
|
+
throw new Error('AnthropicProvider: either `apiKey` or `authToken` is required')
|
|
224
375
|
}
|
|
225
376
|
this.config = config
|
|
226
377
|
|
|
227
378
|
const clientOpts: Record<string, unknown> = {
|
|
228
|
-
apiKey: config.apiKey,
|
|
229
379
|
timeout: config.timeout ?? DEFAULT_TIMEOUT_MS,
|
|
230
380
|
}
|
|
381
|
+
if (config.authToken) {
|
|
382
|
+
clientOpts.authToken = config.authToken
|
|
383
|
+
// OAuth routes require both beta flags + a Claude Code user-agent;
|
|
384
|
+
// without them Anthropic rejects subscription / Claude Code OAuth
|
|
385
|
+
// tokens (intermittent 401/500). The system-prompt identity block
|
|
386
|
+
// is added per-request in buildCreateParams.
|
|
387
|
+
const headers: Record<string, string> = {
|
|
388
|
+
'anthropic-beta': OAUTH_BETAS,
|
|
389
|
+
'user-agent': `claude-cli/${detectClaudeCodeVersion()} (external, cli)`,
|
|
390
|
+
...(config.defaultHeaders ?? {}),
|
|
391
|
+
}
|
|
392
|
+
clientOpts.defaultHeaders = headers
|
|
393
|
+
} else {
|
|
394
|
+
clientOpts.apiKey = config.apiKey
|
|
395
|
+
if (config.defaultHeaders) clientOpts.defaultHeaders = config.defaultHeaders
|
|
396
|
+
}
|
|
231
397
|
if (config.baseURL) clientOpts.baseURL = config.baseURL
|
|
232
|
-
if (config.defaultHeaders) clientOpts.defaultHeaders = config.defaultHeaders
|
|
233
398
|
|
|
234
399
|
this.client = new Anthropic(clientOpts)
|
|
235
400
|
}
|
|
@@ -248,10 +413,17 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
248
413
|
params: ChatCompletionParams,
|
|
249
414
|
stream: boolean,
|
|
250
415
|
): Record<string, unknown> {
|
|
251
|
-
|
|
416
|
+
// The runtime requests caching via `params.cacheControl` on every
|
|
417
|
+
// iteration. Honoring it costs three of the four allowed breakpoints:
|
|
418
|
+
// tools tail + static-system tail + last message block (render order
|
|
419
|
+
// is tools → system → messages, so each later breakpoint covers all
|
|
420
|
+
// earlier sections too).
|
|
421
|
+
const cachingEnabled = params.cacheControl !== undefined
|
|
422
|
+
const system = extractSystem(params.messages, cachingEnabled)
|
|
252
423
|
const messages = toAnthropicMessages(params.messages)
|
|
253
|
-
|
|
254
|
-
const
|
|
424
|
+
if (cachingEnabled) applyMessageCacheBreakpoint(messages)
|
|
425
|
+
const tools = toAnthropicTools(params, cachingEnabled)
|
|
426
|
+
const toolChoice = toAnthropicToolChoice(params.toolChoice, params.parallelToolCalls)
|
|
255
427
|
|
|
256
428
|
const body: Record<string, unknown> = {
|
|
257
429
|
model: this.resolveModel(params),
|
|
@@ -260,9 +432,21 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
260
432
|
stream,
|
|
261
433
|
}
|
|
262
434
|
|
|
263
|
-
if (
|
|
435
|
+
if (this.config.authToken) {
|
|
436
|
+
// OAuth: the first system block must be the Claude Code identity
|
|
437
|
+
// line or Anthropic rejects the request. Emit the block-array form
|
|
438
|
+
// with the identity prefix first; cache breakpoints (if any) stay
|
|
439
|
+
// on the tagged blocks behind it, so the ordering survives.
|
|
440
|
+
const ccBlock: AnthropicTextBlock = { type: 'text', text: CLAUDE_CODE_SYSTEM_PREFIX }
|
|
441
|
+
body.system = system ? [ccBlock, ...system] : [ccBlock]
|
|
442
|
+
} else if (system) {
|
|
443
|
+
body.system = system
|
|
444
|
+
}
|
|
264
445
|
if (tools) body.tools = tools
|
|
265
|
-
|
|
446
|
+
// tool_choice is only legal alongside tools (the API rejects it
|
|
447
|
+
// otherwise) — this also drops a parallelToolCalls-derived choice on
|
|
448
|
+
// tool-less requests.
|
|
449
|
+
if (tools && toolChoice) body.tool_choice = toolChoice
|
|
266
450
|
if (params.temperature !== undefined) body.temperature = params.temperature
|
|
267
451
|
if (params.topP !== undefined) body.top_p = params.topP
|
|
268
452
|
if (params.topK !== undefined) body.top_k = params.topK
|
|
@@ -277,114 +461,190 @@ export class AnthropicProvider implements LLMProvider {
|
|
|
277
461
|
* Casting via `unknown` keeps us out of `any` territory while acknowledging
|
|
278
462
|
* that the translation layer bridges two type worlds.
|
|
279
463
|
*/
|
|
280
|
-
private createRaw(
|
|
464
|
+
private createRaw(
|
|
465
|
+
body: Record<string, unknown>,
|
|
466
|
+
opts?: { signal?: AbortSignal },
|
|
467
|
+
): Promise<unknown> {
|
|
281
468
|
const create = this.client.messages.create as unknown as (
|
|
282
469
|
body: Record<string, unknown>,
|
|
470
|
+
options?: { signal?: AbortSignal },
|
|
283
471
|
) => Promise<unknown>
|
|
284
|
-
|
|
472
|
+
// Pass the caller AbortSignal as the SDK's per-request RequestOptions so
|
|
473
|
+
// aborting it tears down the in-flight HTTP/2 SSE request (rejects with
|
|
474
|
+
// APIUserAbortError). A non-aborted signal is identical to omitting it.
|
|
475
|
+
return create.call(this.client.messages, body, { signal: opts?.signal })
|
|
285
476
|
}
|
|
286
477
|
|
|
287
478
|
async *chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk> {
|
|
288
479
|
const createParams = this.buildCreateParams(params, true)
|
|
480
|
+
const signal = params.signal
|
|
289
481
|
|
|
290
|
-
const stream = (await this.createRaw(createParams)) as AsyncIterable<StreamEvent>
|
|
482
|
+
const stream = (await this.createRaw(createParams, { signal })) as AsyncIterable<StreamEvent>
|
|
291
483
|
|
|
292
484
|
let messageId = ''
|
|
293
485
|
// Track active tool-use blocks by content_block index so input_json_delta
|
|
294
486
|
// fragments can reference the right tool call.
|
|
295
487
|
const activeTools = new Map<number, { id: string; name: string }>()
|
|
296
488
|
|
|
297
|
-
|
|
489
|
+
// Anthropic Messages API streams over SSE. Do not impose a
|
|
490
|
+
// provider-local 90s idle cutoff by default: long reasoning or
|
|
491
|
+
// long tool-argument generation can legitimately pause between
|
|
492
|
+
// SSE events, and cutting it here turns a healthy Messages API
|
|
493
|
+
// run into a false "tool input truncated" failure. Deployments
|
|
494
|
+
// that still need a per-event watchdog can opt in via
|
|
495
|
+
// `streamIdleTimeoutMs`; otherwise the request timeout and caller
|
|
496
|
+
// AbortSignal own lifecycle cancellation.
|
|
497
|
+
const streamIdleTimeoutMs = this.config.streamIdleTimeoutMs ?? DEFAULT_STREAM_IDLE_TIMEOUT_MS
|
|
498
|
+
const iter = (stream as AsyncIterable<StreamEvent>)[Symbol.asyncIterator]()
|
|
499
|
+
const nextWithIdleTimeout = async (): Promise<IteratorResult<StreamEvent>> => {
|
|
500
|
+
if (!Number.isFinite(streamIdleTimeoutMs) || streamIdleTimeoutMs <= 0) {
|
|
501
|
+
return iter.next()
|
|
502
|
+
}
|
|
503
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
298
504
|
try {
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
505
|
+
return await Promise.race([
|
|
506
|
+
iter.next(),
|
|
507
|
+
new Promise<IteratorResult<StreamEvent>>((_, reject) => {
|
|
508
|
+
timer = setTimeout(() => {
|
|
509
|
+
reject(
|
|
510
|
+
new Error(
|
|
511
|
+
`Anthropic stream idle for ${Math.round(streamIdleTimeoutMs / 1000)}s — aborting so the run lifecycle can emit run_failed.`,
|
|
512
|
+
),
|
|
513
|
+
)
|
|
514
|
+
}, streamIdleTimeoutMs)
|
|
515
|
+
}),
|
|
516
|
+
])
|
|
517
|
+
} finally {
|
|
518
|
+
if (timer !== undefined) clearTimeout(timer)
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
try {
|
|
523
|
+
for (;;) {
|
|
524
|
+
// Cheap between-chunk abort check: if a Stop fired, stop pulling
|
|
525
|
+
// (the runtime also races this, and the SDK request is aborted).
|
|
526
|
+
signal?.throwIfAborted()
|
|
527
|
+
const result = await nextWithIdleTimeout()
|
|
528
|
+
if (result.done) break
|
|
529
|
+
const event = result.value
|
|
530
|
+
try {
|
|
531
|
+
switch (event.type) {
|
|
532
|
+
case 'message_start': {
|
|
533
|
+
if (event.message?.id) messageId = event.message.id
|
|
534
|
+
if (event.message?.usage) {
|
|
535
|
+
yield {
|
|
536
|
+
id: messageId,
|
|
537
|
+
delta: {},
|
|
538
|
+
usage: parseUsage(event.message.usage),
|
|
539
|
+
}
|
|
307
540
|
}
|
|
541
|
+
break
|
|
308
542
|
}
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
},
|
|
543
|
+
case 'content_block_start': {
|
|
544
|
+
const idx = event.index ?? 0
|
|
545
|
+
const block = event.content_block
|
|
546
|
+
if (block?.type === 'tool_use') {
|
|
547
|
+
const toolId = block.id ?? `tool-${Date.now()}`
|
|
548
|
+
activeTools.set(idx, { id: toolId, name: block.name ?? '' })
|
|
549
|
+
yield {
|
|
550
|
+
id: messageId,
|
|
551
|
+
delta: {
|
|
552
|
+
toolCalls: [
|
|
553
|
+
{
|
|
554
|
+
index: idx,
|
|
555
|
+
id: toolId,
|
|
556
|
+
type: 'function',
|
|
557
|
+
function: { name: block.name ?? '' },
|
|
558
|
+
},
|
|
559
|
+
],
|
|
560
|
+
},
|
|
561
|
+
}
|
|
329
562
|
}
|
|
563
|
+
break
|
|
330
564
|
}
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
},
|
|
565
|
+
case 'content_block_delta': {
|
|
566
|
+
const idx = event.index ?? 0
|
|
567
|
+
const delta = event.delta
|
|
568
|
+
if (delta?.type === 'text_delta' && delta.text) {
|
|
569
|
+
yield { id: messageId, delta: { content: delta.text } }
|
|
570
|
+
} else if (delta?.type === 'input_json_delta' && delta.partial_json !== undefined) {
|
|
571
|
+
const active = activeTools.get(idx)
|
|
572
|
+
yield {
|
|
573
|
+
id: messageId,
|
|
574
|
+
delta: {
|
|
575
|
+
toolCalls: [
|
|
576
|
+
{
|
|
577
|
+
index: idx,
|
|
578
|
+
id: active?.id,
|
|
579
|
+
function: { arguments: delta.partial_json },
|
|
580
|
+
},
|
|
581
|
+
],
|
|
582
|
+
},
|
|
583
|
+
}
|
|
351
584
|
}
|
|
585
|
+
break
|
|
352
586
|
}
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
587
|
+
case 'content_block_stop': {
|
|
588
|
+
// For tool_use blocks we MUST emit a `toolCallEnd`
|
|
589
|
+
// signal so the consumer-side aggregator (sdk
|
|
590
|
+
// runtime/query/iteration) can flush the buffered
|
|
591
|
+
// `argsBuf` and JSON.parse it into the tool input.
|
|
592
|
+
// Without this signal the executor sees an empty
|
|
593
|
+
// `arguments` string and rejects the call with
|
|
594
|
+
// `Error: Invalid JSON in tool arguments for "<tool>"`
|
|
595
|
+
// — exactly the failure the live cowork test
|
|
596
|
+
// surfaced (Bash + Write both blank-input failed).
|
|
597
|
+
const idx = event.index ?? 0
|
|
598
|
+
const active = activeTools.get(idx)
|
|
599
|
+
if (active) {
|
|
600
|
+
yield {
|
|
601
|
+
id: messageId,
|
|
602
|
+
delta: {
|
|
603
|
+
toolCallEnd: { index: idx, id: active.id },
|
|
604
|
+
},
|
|
605
|
+
}
|
|
606
|
+
activeTools.delete(idx)
|
|
365
607
|
}
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
608
|
+
break
|
|
609
|
+
}
|
|
610
|
+
case 'message_delta': {
|
|
611
|
+
if (event.delta?.stop_reason) {
|
|
612
|
+
yield {
|
|
613
|
+
id: messageId,
|
|
614
|
+
delta: {},
|
|
615
|
+
finishReason: mapStopReason(event.delta.stop_reason),
|
|
616
|
+
usage: event.usage ? parseUsage(event.usage) : undefined,
|
|
617
|
+
}
|
|
618
|
+
} else if (event.usage) {
|
|
619
|
+
yield {
|
|
620
|
+
id: messageId,
|
|
621
|
+
delta: {},
|
|
622
|
+
usage: parseUsage(event.usage),
|
|
623
|
+
}
|
|
371
624
|
}
|
|
625
|
+
break
|
|
372
626
|
}
|
|
373
|
-
|
|
627
|
+
case 'message_stop':
|
|
628
|
+
return
|
|
629
|
+
default:
|
|
630
|
+
// Ignore unknown / ping / opaque events.
|
|
631
|
+
break
|
|
632
|
+
}
|
|
633
|
+
} catch (parseErr) {
|
|
634
|
+
yield {
|
|
635
|
+
id: messageId,
|
|
636
|
+
delta: {},
|
|
637
|
+
error: `Stream event error: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,
|
|
374
638
|
}
|
|
375
|
-
case 'message_stop':
|
|
376
|
-
return
|
|
377
|
-
default:
|
|
378
|
-
// Ignore unknown / ping / opaque events.
|
|
379
|
-
break
|
|
380
|
-
}
|
|
381
|
-
} catch (parseErr) {
|
|
382
|
-
yield {
|
|
383
|
-
id: messageId,
|
|
384
|
-
delta: {},
|
|
385
|
-
error: `Stream event error: ${parseErr instanceof Error ? parseErr.message : String(parseErr)}`,
|
|
386
639
|
}
|
|
387
640
|
}
|
|
641
|
+
} finally {
|
|
642
|
+
// Always release the underlying HTTP/2 connection — both on
|
|
643
|
+
// idle-timeout rejection (bubbling up) and on normal stream
|
|
644
|
+
// end (`message_stop` returned out of the loop). Leaving
|
|
645
|
+
// the SSE connection open until OS-level timeout was the
|
|
646
|
+
// gap Codex called out.
|
|
647
|
+
await iter.return?.().catch(() => undefined)
|
|
388
648
|
}
|
|
389
649
|
}
|
|
390
650
|
|
package/src/types.ts
CHANGED
|
@@ -8,17 +8,35 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
export interface AnthropicConfig {
|
|
11
|
-
|
|
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:
|
|
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 {
|