@aeye/anthropic 0.0.0-stage → 0.11.1

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,808 @@
1
+ /**
2
+ * Mapping between @aeye chat shapes and the Anthropic Messages API.
3
+ *
4
+ * Output content blocks map one at a time into core `Chunk`s, so a complete
5
+ * response is its blocks' chunks folded together (`getResponseFromChunks`),
6
+ * and a stream reuses the same mapping as its blocks complete.
7
+ */
8
+ import { clampReasoningEffort } from '@aeye/ai';
9
+ import { describeTool, forcesTool, replaysTo, sentOutput, sentTools, toBase64, toText, } from '@aeye/core';
10
+ import { ProviderError } from './types.js';
11
+ /**
12
+ * The provider name, which marks the reasoning this provider produces so
13
+ * other providers don't replay it.
14
+ */
15
+ export const ANTHROPIC_PROVIDER = 'anthropic';
16
+ /**
17
+ * The `ReasoningDetail.format` of thinking blocks from the Messages API,
18
+ * which round-trip back to it in later turns.
19
+ */
20
+ export const ANTHROPIC_REASONING_FORMAT = 'anthropic-messages-v1';
21
+ /**
22
+ * The most `cache_control` breakpoints one request takes.
23
+ */
24
+ export const MAX_CACHE_BREAKPOINTS = 4;
25
+ /**
26
+ * An uploaded file (Files API) referenced by its id.
27
+ */
28
+ const FILE_ID = /^file_[A-Za-z0-9_-]{8,}$/;
29
+ /**
30
+ * Image types the Messages API accepts.
31
+ */
32
+ const IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
33
+ /**
34
+ * Document types sent as plain text documents.
35
+ */
36
+ const TEXT_TYPES = /^(text\/|application\/(json|xml|x-yaml|yaml|csv|javascript|x-ndjson|ld\+json))/;
37
+ /**
38
+ * File extensions and short format names to MIME types.
39
+ */
40
+ const EXTENSIONS = {
41
+ jpg: 'image/jpeg', jpeg: 'image/jpeg', png: 'image/png', gif: 'image/gif', webp: 'image/webp',
42
+ pdf: 'application/pdf', txt: 'text/plain', text: 'text/plain', md: 'text/markdown', markdown: 'text/markdown',
43
+ csv: 'text/csv', html: 'text/html', htm: 'text/html', xml: 'application/xml', json: 'application/json',
44
+ yaml: 'application/yaml', yml: 'application/yaml', js: 'text/javascript', ts: 'text/plain', py: 'text/plain',
45
+ };
46
+ // ============================================================================
47
+ // Request content
48
+ // ============================================================================
49
+ /**
50
+ * The MIME type a format name or MIME type stands for.
51
+ */
52
+ function mimeOf(format) {
53
+ if (!format)
54
+ return undefined;
55
+ const lower = format.toLowerCase();
56
+ return lower.includes('/') ? (lower === 'image/jpg' ? 'image/jpeg' : lower) : EXTENSIONS[lower.replace(/^\./, '')];
57
+ }
58
+ /**
59
+ * The extension of a file name or URL path, if any.
60
+ */
61
+ function extension(path) {
62
+ return path ? /\.([a-z0-9]+)(?:[?#].*)?$/i.exec(path)?.[1]?.toLowerCase() : undefined;
63
+ }
64
+ /**
65
+ * The type the leading bytes of a file give away.
66
+ */
67
+ function sniff(bytes) {
68
+ if (bytes.length >= 4 && bytes[0] === 0x89 && bytes.toString('latin1', 1, 4) === 'PNG')
69
+ return 'image/png';
70
+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff)
71
+ return 'image/jpeg';
72
+ if (bytes.toString('latin1', 0, 4) === 'GIF8')
73
+ return 'image/gif';
74
+ if (bytes.toString('latin1', 0, 4) === 'RIFF' && bytes.toString('latin1', 8, 12) === 'WEBP')
75
+ return 'image/webp';
76
+ if (bytes.toString('latin1', 0, 5) === '%PDF-')
77
+ return 'application/pdf';
78
+ return undefined;
79
+ }
80
+ /**
81
+ * A part's media, its type taken from (in order) the part's format, the
82
+ * data URL, the name or URL's extension, and the bytes themselves.
83
+ */
84
+ async function toMedia(part) {
85
+ const content = part.content;
86
+ const uri = content instanceof URL ? content.href : typeof content === 'string' ? content : undefined;
87
+ if (uri && FILE_ID.test(uri)) {
88
+ return { kind: 'file', id: uri };
89
+ }
90
+ if (uri && /^https?:\/\//i.test(uri)) {
91
+ return { kind: 'url', url: uri, mime: mimeOf(part.format) ?? mimeOf(extension(part.name)) ?? mimeOf(extension(uri)) };
92
+ }
93
+ const [, wireMime, data = ''] = /^data:([^;,]*)(?:;[^,]*)?,(.*)$/s.exec(await toBase64(content, mimeOf(part.format))) ?? [];
94
+ const named = mimeOf(part.format) ?? (wireMime && wireMime !== 'application/octet-stream' ? wireMime : undefined) ?? mimeOf(extension(part.name)) ?? mimeOf(extension(uri));
95
+ return { kind: 'data', data, mime: named ?? sniff(Buffer.from(data.slice(0, 32), 'base64')) };
96
+ }
97
+ /**
98
+ * A note standing in for content the API can't take.
99
+ */
100
+ function note(part, who, why) {
101
+ return { type: 'text', text: `${part.type[0].toUpperCase()}${part.type.slice(1)} content sent by ${who} ${why}.` };
102
+ }
103
+ /**
104
+ * One message part as a content block, or a note in its place.
105
+ */
106
+ async function toPartBlock(part, who) {
107
+ if (part.type === 'text') {
108
+ const text = await toText(part.content).catch(() => `Text content sent by ${who} could not be read.`);
109
+ return text ? { type: 'text', text } : undefined;
110
+ }
111
+ if (part.type === 'audio' || part.type === 'video') {
112
+ return note(part, who, 'was left out: Claude does not take ' + part.type);
113
+ }
114
+ const media = await toMedia(part).catch(() => undefined);
115
+ if (!media) {
116
+ return note(part, who, 'could not be read');
117
+ }
118
+ if (part.type === 'image') {
119
+ if (media.kind === 'file')
120
+ return { type: 'image', source: { type: 'file', file_id: media.id } };
121
+ if (media.kind === 'url')
122
+ return { type: 'image', source: { type: 'url', url: media.url } };
123
+ const mime = media.mime;
124
+ return mime && IMAGE_TYPES.includes(mime)
125
+ ? { type: 'image', source: { type: 'base64', media_type: mime, data: media.data } }
126
+ : note(part, who, `was left out: ${media.mime ?? 'its type'} is not an image type Claude takes (JPEG, PNG, GIF, WebP)`);
127
+ }
128
+ // A file: a PDF, or text, or an uploaded file
129
+ const title = part.name ? { title: part.name } : {};
130
+ if (media.kind === 'file') {
131
+ return { type: 'document', source: { type: 'file', file_id: media.id }, ...title };
132
+ }
133
+ if (media.kind === 'url') {
134
+ if (!media.mime || media.mime === 'application/pdf') {
135
+ return { type: 'document', source: { type: 'url', url: media.url }, ...title };
136
+ }
137
+ if (TEXT_TYPES.test(media.mime)) {
138
+ const text = await toText(media.url).catch(() => undefined);
139
+ return text === undefined ? note(part, who, 'could not be read') : { type: 'document', source: { type: 'text', media_type: 'text/plain', data: text }, ...title };
140
+ }
141
+ return note(part, who, `was left out: ${media.mime} documents aren't supported (PDF and plain text are)`);
142
+ }
143
+ if (media.mime === 'application/pdf') {
144
+ return { type: 'document', source: { type: 'base64', media_type: 'application/pdf', data: media.data }, ...title };
145
+ }
146
+ if (!media.mime || TEXT_TYPES.test(media.mime)) {
147
+ return { type: 'document', source: { type: 'text', media_type: 'text/plain', data: Buffer.from(media.data, 'base64').toString('utf8') }, ...title };
148
+ }
149
+ if (media.mime.startsWith('image/')) {
150
+ return toPartBlock({ ...part, type: 'image' }, who);
151
+ }
152
+ return note(part, who, `was left out: ${media.mime} documents aren't supported (PDF and plain text are)`);
153
+ }
154
+ /**
155
+ * Message content as content blocks, each part marked as a cache
156
+ * breakpoint carrying `cache_control`.
157
+ */
158
+ export async function toContentBlocks(content, who, cache) {
159
+ if (typeof content === 'string') {
160
+ return content ? [{ type: 'text', text: content }] : [];
161
+ }
162
+ const blocks = await Promise.all(content.map(async (part) => {
163
+ const block = await toPartBlock(part, who);
164
+ return block && part.cacheBreakpoint ? { ...block, cache_control: cache } : block;
165
+ }));
166
+ return blocks.filter((block) => !!block);
167
+ }
168
+ /**
169
+ * Reasoning from an earlier Messages API response as thinking blocks, which
170
+ * Claude needs back unmodified, signature and all, while it uses tools.
171
+ * Unsigned text can't be verified, so it isn't replayed.
172
+ */
173
+ export function toThinkingBlocks(reasoning) {
174
+ if (!replaysTo(reasoning, ANTHROPIC_PROVIDER)) {
175
+ return [];
176
+ }
177
+ return (reasoning.details ?? []).flatMap((detail) => detail.format !== ANTHROPIC_REASONING_FORMAT ? []
178
+ : detail.data ? [{ type: 'redacted_thinking', data: detail.data }]
179
+ : detail.signature ? [{ type: 'thinking', thinking: detail.text ?? '', signature: detail.signature }]
180
+ : []);
181
+ }
182
+ /**
183
+ * Tool call arguments as a tool input, kept as raw text when they aren't
184
+ * an object.
185
+ */
186
+ function toToolInput(args) {
187
+ try {
188
+ const value = JSON.parse(args || '{}');
189
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : { value };
190
+ }
191
+ catch {
192
+ return { _raw: args };
193
+ }
194
+ }
195
+ /**
196
+ * Convert a request's messages:
197
+ *
198
+ * - system messages before the conversation become the system prompt; ones
199
+ * inside it go as mid-conversation system messages where the model takes
200
+ * them and the API allows them there (after a user turn, before an
201
+ * assistant turn or last), and join the system prompt otherwise;
202
+ * - tool results become `tool_result` blocks in a user turn, a failure
203
+ * flagged `is_error`;
204
+ * - assistant turns replay their thinking (once per turn), then their text,
205
+ * then their tool calls;
206
+ * - consecutive turns of one role are merged, as the API expects.
207
+ *
208
+ * @param messages - The request's messages.
209
+ * @param traits - What the model takes.
210
+ * @param cache - The cache control a breakpoint carries.
211
+ */
212
+ export async function toMessages(messages, traits, cache) {
213
+ const system = [];
214
+ const out = [];
215
+ const replayed = new Set();
216
+ const push = (role, content) => {
217
+ if (!content.length)
218
+ return;
219
+ const last = out[out.length - 1];
220
+ if (last && last.role === role) {
221
+ last.content = [...last.content, ...content];
222
+ }
223
+ else {
224
+ out.push({ role, content });
225
+ }
226
+ };
227
+ const textOnly = (blocks) => blocks.filter((b) => b.type === 'text');
228
+ for (let i = 0; i < messages.length; i++) {
229
+ const msg = messages[i];
230
+ switch (msg.role) {
231
+ case 'system': {
232
+ const blocks = textOnly(await toContentBlocks(msg.content, msg.name || 'system', cache));
233
+ const next = messages.slice(i + 1).find(m => m.role !== 'system');
234
+ const placeable = traits.midConversationSystem && out.length > 0 && out[out.length - 1].role === 'user' && (!next || next.role === 'assistant');
235
+ if (placeable && blocks.length) {
236
+ out.push({ role: 'system', content: blocks });
237
+ }
238
+ else {
239
+ system.push(...blocks);
240
+ }
241
+ break;
242
+ }
243
+ case 'user':
244
+ push('user', await toContentBlocks(msg.content, msg.name || 'user', cache));
245
+ break;
246
+ case 'tool': {
247
+ const content = await toContentBlocks(msg.content, msg.name || 'tool', cache);
248
+ const cached = content.some(block => block.cache_control);
249
+ const stripped = content.map(({ cache_control, ...block }) => block);
250
+ push('user', [{
251
+ type: 'tool_result',
252
+ tool_use_id: msg.toolCallId ?? '',
253
+ ...(stripped.length ? { content: stripped } : {}),
254
+ ...(msg.failure ? { is_error: true } : {}),
255
+ ...(cached ? { cache_control: cache } : {}),
256
+ }]);
257
+ break;
258
+ }
259
+ case 'assistant': {
260
+ const reasoning = msg.reasoning && !replayed.has(msg.reasoning) ? msg.reasoning : undefined;
261
+ if (reasoning)
262
+ replayed.add(reasoning);
263
+ const text = textOnly(await toContentBlocks(msg.content, msg.name || 'assistant', cache)).filter(b => b.text);
264
+ const calls = (msg.toolCalls ?? []).map((tc) => ({ type: 'tool_use', id: tc.id, name: tc.name, input: toToolInput(tc.arguments) }));
265
+ push('assistant', [...toThinkingBlocks(reasoning), ...text, ...calls]);
266
+ break;
267
+ }
268
+ }
269
+ }
270
+ if (!out.some(m => m.role === 'user')) {
271
+ out.unshift({ role: 'user', content: [{ type: 'text', text: 'Continue.' }] });
272
+ }
273
+ return { system, messages: out };
274
+ }
275
+ /**
276
+ * Keeps the last `max` cache breakpoints (later ones cover more of the
277
+ * prompt), removing earlier ones: the API takes at most four.
278
+ *
279
+ * @param blocks - Every block that can carry `cache_control`, in prompt order.
280
+ */
281
+ export function limitCacheBreakpoints(blocks, max = MAX_CACHE_BREAKPOINTS) {
282
+ const marked = blocks.filter(block => block.cache_control);
283
+ for (const block of marked.slice(0, Math.max(0, marked.length - max))) {
284
+ delete block.cache_control;
285
+ }
286
+ }
287
+ /**
288
+ * The blocks of a request that can carry `cache_control`, in prompt order:
289
+ * tools, then the system prompt, then messages.
290
+ */
291
+ export function cacheableBlocks(tools, system, messages) {
292
+ return [
293
+ ...(tools ?? []),
294
+ ...system,
295
+ ...messages.flatMap(m => typeof m.content === 'string' ? [] : m.content),
296
+ ];
297
+ }
298
+ // ============================================================================
299
+ // Tools
300
+ // ============================================================================
301
+ /**
302
+ * The beta header MCP servers need.
303
+ */
304
+ export const MCP_BETA = 'mcp-client-2025-11-20';
305
+ /**
306
+ * A hosted tool as an Anthropic server tool.
307
+ *
308
+ * @param dynamic - The model takes the dynamic-filtering web tools.
309
+ */
310
+ function toServerTool(tool, dynamic, provider) {
311
+ switch (tool.type) {
312
+ case 'web_search': {
313
+ const domains = { allowed_domains: tool.allowedDomains, blocked_domains: tool.blockedDomains };
314
+ return dynamic
315
+ ? { type: 'web_search_20260318', name: 'web_search', ...domains }
316
+ : { type: 'web_search_20250305', name: 'web_search', ...domains };
317
+ }
318
+ case 'web_fetch':
319
+ return dynamic
320
+ ? { type: 'web_fetch_20260318', name: 'web_fetch' }
321
+ : { type: 'web_fetch_20250910', name: 'web_fetch' };
322
+ case 'code_interpreter':
323
+ return { type: 'code_execution_20260521', name: 'code_execution' };
324
+ case 'mcp':
325
+ return undefined;
326
+ default:
327
+ throw new ProviderError(provider, `Claude has no hosted ${tool.type} tool`);
328
+ }
329
+ }
330
+ /**
331
+ * Convert a request's tools and tool choice:
332
+ *
333
+ * - each tool goes as planned (`sentTools`), strict when the plan rendered
334
+ * it strict; a free-text tool goes as its one-field function with any
335
+ * grammar in its description; a deferred tool loads through tool search;
336
+ * - hosted tools become server tools (web search and fetch, code
337
+ * execution), and MCP servers go in `mcp_servers` with a toolset each;
338
+ * - `required` is `any`, a named tool is `tool`, and `toolsOneAtATime`
339
+ * disables parallel calls. A model that rejects forced tool use is sent
340
+ * only the tools it must pick from, with `auto`.
341
+ *
342
+ * @param request - The request, planned, with only its allowed tools.
343
+ * @param traits - What the model takes.
344
+ */
345
+ export function toTools(request, traits, provider) {
346
+ const betas = [];
347
+ const choice = request.toolChoice;
348
+ const forcedWanted = forcesTool(choice);
349
+ const named = typeof choice === 'object' && 'tool' in choice ? choice.tool : undefined;
350
+ const narrow = forcedWanted && !traits.forcedToolChoice && named;
351
+ const definitions = sentTools(request).filter(tool => !narrow || tool.name === named);
352
+ const deferred = definitions.some(tool => tool.definition?.defer);
353
+ const functions = definitions.map((tool) => ({
354
+ name: tool.name,
355
+ description: tool.definition ? describeTool(tool.definition) : tool.description,
356
+ input_schema: tool.parameters,
357
+ ...(tool.strict ? { strict: true } : {}),
358
+ ...(deferred && tool.definition?.defer ? { defer_loading: true } : {}),
359
+ }));
360
+ if (deferred) {
361
+ functions.push({ type: 'tool_search_tool_bm25_20251119', name: 'tool_search_tool_bm25' });
362
+ }
363
+ const hosted = request.hostedTools ?? [];
364
+ const server = hosted.flatMap(tool => {
365
+ const converted = toServerTool(tool, traits.dynamicWebTools, provider);
366
+ return converted ? [converted] : [];
367
+ });
368
+ const mcp = hosted.filter((tool) => tool.type === 'mcp');
369
+ const mcpServers = mcp.map(server => ({
370
+ type: 'url',
371
+ url: server.url,
372
+ name: server.label,
373
+ ...(server.headers?.Authorization ? { authorization_token: server.headers.Authorization.replace(/^Bearer\s+/i, '') } : {}),
374
+ }));
375
+ const toolsets = mcp.map(server => ({
376
+ type: 'mcp_toolset',
377
+ mcp_server_name: server.label,
378
+ ...(server.allowedTools?.length ? {
379
+ default_config: { enabled: false },
380
+ configs: Object.fromEntries(server.allowedTools.map(name => [name, { enabled: true }])),
381
+ } : {}),
382
+ }));
383
+ if (mcp.length) {
384
+ betas.push(MCP_BETA);
385
+ }
386
+ const tools = [...functions, ...server, ...toolsets];
387
+ if (!tools.length) {
388
+ return { betas, forced: false };
389
+ }
390
+ const parallel = request.toolsOneAtATime ? { disable_parallel_tool_use: true } : {};
391
+ const forced = forcedWanted && traits.forcedToolChoice && functions.length > 0;
392
+ const toolChoice = choice === 'none' ? { type: 'none' }
393
+ : forced && named ? { type: 'tool', name: named, ...parallel }
394
+ : forced ? { type: 'any', ...parallel }
395
+ : request.toolsOneAtATime ? { type: 'auto', ...parallel }
396
+ : undefined;
397
+ return { tools, toolChoice, mcpServers: mcpServers.length ? mcpServers : undefined, betas, forced };
398
+ }
399
+ // ============================================================================
400
+ // Thinking and output
401
+ // ============================================================================
402
+ /**
403
+ * Thinking budgets by effort, for models that take a budget.
404
+ */
405
+ const THINKING_BUDGETS = {
406
+ none: 0,
407
+ minimal: 1024,
408
+ low: 2048,
409
+ medium: 8192,
410
+ high: 16384,
411
+ xhigh: 32768,
412
+ max: 65536,
413
+ };
414
+ /**
415
+ * Map `Request.reason` for the model:
416
+ *
417
+ * - `always` models (Opus 5.5, Fable, Mythos) can't stop thinking: effort is
418
+ * the control, and `none` is the lowest effort;
419
+ * - `default` models think unless told not to: `none` sends `disabled` (or
420
+ * `between_tools` on Claude Sonnet 5.5) at an effort that allows it;
421
+ * - `adaptive` models (Opus 4.6–4.8, Sonnet 4.6) think when asked;
422
+ * - `budget` models (4.5 and earlier) take a `budget_tokens` from
423
+ * `maxTokens` or the effort, under `max_tokens`, and can't think on a
424
+ * turn that forces a tool.
425
+ *
426
+ * The thinking shows as a summary unless `exclude` asks to leave it out.
427
+ * Effort is clamped to what the model accepts.
428
+ *
429
+ * @param traits - What the model takes.
430
+ * @param reason - The reasoning asked for.
431
+ * @param efforts - The efforts the model accepts, when known.
432
+ * @param maxTokens - `max_tokens` before reasoning.
433
+ * @param forced - Whether the turn forces a tool call.
434
+ * @param maxOutput - The model's output limit, which a raised `max_tokens` stays under.
435
+ */
436
+ export function toThinking(traits, reason, efforts, maxTokens, forced, maxOutput) {
437
+ if (!reason) {
438
+ return { maxTokens };
439
+ }
440
+ const display = reason.exclude ? 'omitted' : 'summarized';
441
+ const off = reason.effort === 'none';
442
+ const effortOf = (effort, accepted = efforts) => {
443
+ if (!effort || (!accepted?.length && (effort === 'none' || effort === 'minimal'))) {
444
+ return effort === 'minimal' ? 'low' : undefined;
445
+ }
446
+ const clamped = clampReasoningEffort(effort, accepted?.filter(e => e !== 'none' && e !== 'minimal'));
447
+ return clamped === 'none' || clamped === 'minimal' ? 'low' : clamped;
448
+ };
449
+ switch (traits.thinking) {
450
+ case 'always':
451
+ return { maxTokens, thinking: { type: 'adaptive', display }, effort: effortOf(off ? 'low' : reason.effort) };
452
+ case 'default':
453
+ if (off) {
454
+ return traits.thinkingOff
455
+ ? { maxTokens, thinking: { type: traits.thinkingOff }, effort: undefined }
456
+ : { maxTokens, thinking: { type: 'adaptive', display }, effort: effortOf('low') };
457
+ }
458
+ return { maxTokens, thinking: { type: 'adaptive', display }, effort: effortOf(reason.effort) };
459
+ case 'adaptive':
460
+ return off
461
+ ? { maxTokens, thinking: { type: 'disabled' } }
462
+ : { maxTokens, thinking: { type: 'adaptive', display }, effort: effortOf(reason.effort) };
463
+ case 'budget': {
464
+ const effort = efforts?.length ? effortOf(reason.effort) : undefined;
465
+ if (off || forced) {
466
+ return { maxTokens, effort: off ? undefined : effort };
467
+ }
468
+ const budget = Math.max(1024, reason.maxTokens ?? THINKING_BUDGETS[reason.effort ?? 'medium']);
469
+ const room = budget + Math.max(1024, Math.min(maxTokens, 8192));
470
+ const raised = Math.min(Math.max(maxTokens, room), maxOutput ?? Number.MAX_SAFE_INTEGER);
471
+ const fitted = Math.min(budget, raised - 1);
472
+ return fitted >= 1024
473
+ ? { maxTokens: raised, thinking: { type: 'enabled', budget_tokens: fitted, display }, effort }
474
+ : { maxTokens, effort };
475
+ }
476
+ }
477
+ }
478
+ /**
479
+ * The structured output a planned request sends, as `output_config.format`.
480
+ * Only a schema the plan rendered strict goes: the API compiles every
481
+ * output schema, so a looser one goes in the prompt instead.
482
+ */
483
+ export function toOutputFormat(request) {
484
+ const output = sentOutput(request);
485
+ return output?.strict ? { type: 'json_schema', schema: output.schema } : undefined;
486
+ }
487
+ /**
488
+ * The instruction that asks for JSON when the request wants JSON without a
489
+ * schema: the API has no JSON mode, and compiles every schema it is sent.
490
+ */
491
+ export const JSON_INSTRUCTION = 'Respond with only a single valid JSON value: no markdown fences and no text before or after it.';
492
+ /**
493
+ * A request's service tier as the API's: `auto` uses priority capacity when
494
+ * the account has it, `default` keeps to standard capacity. `fast` is a
495
+ * speed (fast mode), not a tier, and `flex` has no equivalent.
496
+ */
497
+ export function toWireServiceTier(tier) {
498
+ return tier === 'auto' || tier === 'scale' ? 'auto' : tier === 'default' ? 'standard_only' : undefined;
499
+ }
500
+ // ============================================================================
501
+ // Response
502
+ // ============================================================================
503
+ /**
504
+ * Map a stop reason. A refusal is its own reason; running out of context
505
+ * ends the response like running out of tokens.
506
+ */
507
+ export function toFinishReason(stopReason) {
508
+ switch (stopReason) {
509
+ case 'max_tokens':
510
+ case 'model_context_window_exceeded':
511
+ return 'length';
512
+ case 'tool_use':
513
+ return 'tool_calls';
514
+ case 'refusal':
515
+ return 'refusal';
516
+ default:
517
+ return 'stop';
518
+ }
519
+ }
520
+ /**
521
+ * The tier a response ran on: priority capacity, standard, or fast mode.
522
+ */
523
+ export function toServiceTier(usage) {
524
+ if (usage?.speed === 'fast')
525
+ return 'fast';
526
+ return usage?.service_tier === 'priority' ? 'scale' : usage?.service_tier === 'standard' ? 'default' : undefined;
527
+ }
528
+ /**
529
+ * Usage from the API's token counts. Input excludes cache reads and writes
530
+ * (the API reports them apart); thinking tokens come out of the output as
531
+ * reasoning; web searches and fetches count as hosted tool calls.
532
+ */
533
+ export function toUsage(usage) {
534
+ if (!usage)
535
+ return undefined;
536
+ const thinking = usage.output_tokens_details?.thinking_tokens ?? 0;
537
+ const nonZero = (n) => n ? n : undefined;
538
+ const result = {
539
+ text: {
540
+ input: usage.input_tokens ?? 0,
541
+ output: Math.max(0, (usage.output_tokens ?? 0) - thinking),
542
+ cached: nonZero(usage.cache_read_input_tokens),
543
+ cacheWrite: nonZero(usage.cache_creation_input_tokens),
544
+ },
545
+ };
546
+ if (thinking) {
547
+ result.reasoning = { output: thinking };
548
+ }
549
+ const searches = usage.server_tool_use?.web_search_requests ?? 0;
550
+ const fetches = usage.server_tool_use?.web_fetch_requests ?? 0;
551
+ if (searches || fetches) {
552
+ result.tools = { ...(searches ? { web_search: searches } : {}), ...(fetches ? { web_fetch: fetches } : {}) };
553
+ }
554
+ return result;
555
+ }
556
+ /**
557
+ * The dollar cost of a response from the model's prices (overrides
558
+ * included, as the registry applies them), so the cases the generic formula
559
+ * (`ModelInfo.pricing` times `Usage`) can't price come out right: 1-hour
560
+ * cache writes, a long prompt on a model that charges more for one (Claude
561
+ * Haiku 5.5), fast mode, and the batch discount. Undefined when the model's
562
+ * prices aren't known.
563
+ *
564
+ * @param usage - The API's token counts.
565
+ * @param info - The model, with its prices.
566
+ * @param batch - Whether the request ran in a batch (half price).
567
+ */
568
+ export function claudeCost(usage, info, batch = false) {
569
+ const text = info?.pricing.text;
570
+ if (!usage || !info || !text?.input || !text.output)
571
+ return undefined;
572
+ const extra = info.providerOptions?.anthropic?.pricing ?? {};
573
+ const hour = usage.cache_creation?.ephemeral_1h_input_tokens ?? 0;
574
+ const write = usage.cache_creation_input_tokens ?? 0;
575
+ const read = usage.cache_read_input_tokens ?? 0;
576
+ const input = usage.input_tokens ?? 0;
577
+ const output = usage.output_tokens ?? 0;
578
+ const long = extra.longContext && input + read + write > extra.longContext.threshold ? extra.longContext : undefined;
579
+ const fast = usage.speed === 'fast' && extra.fast ? extra.fast : undefined;
580
+ const base = long ?? { input: text.input, output: text.output, cached: text.cached ?? text.input * 0.1, cacheWrite: text.cacheWrite ?? text.input * 1.25, cacheWrite1h: extra.cacheWrite1h ?? text.input * 2 };
581
+ // Fast mode scales every input price with the input rate
582
+ const scale = fast ? fast.input / base.input : 1;
583
+ const tokens = (input * base.input * scale +
584
+ read * base.cached * scale +
585
+ (write - hour) * base.cacheWrite * scale +
586
+ hour * base.cacheWrite1h * scale +
587
+ output * (fast?.output ?? base.output)) / 1_000_000;
588
+ const tools = info.pricing.tools ?? {};
589
+ const calls = (usage.server_tool_use?.web_search_requests ?? 0) * (tools.web_search ?? 0) + (usage.server_tool_use?.web_fetch_requests ?? 0) * (tools.web_fetch ?? 0);
590
+ return tokens * (batch ? 0.5 : 1) + calls;
591
+ }
592
+ /**
593
+ * Reasoning from a thinking or redacted thinking block at a content index.
594
+ * Text and its signature share a detail, and redacted thinking keeps its
595
+ * data, so the blocks can be replayed.
596
+ */
597
+ export function toReasoning(part, index) {
598
+ return {
599
+ content: part.thinking || undefined,
600
+ provider: ANTHROPIC_PROVIDER,
601
+ details: [{
602
+ type: part.data !== undefined ? 'reasoning.encrypted' : 'reasoning.text',
603
+ format: ANTHROPIC_REASONING_FORMAT,
604
+ index,
605
+ text: part.data !== undefined ? undefined : part.thinking ?? '',
606
+ signature: part.signature,
607
+ data: part.data,
608
+ }],
609
+ };
610
+ }
611
+ /**
612
+ * Web sources a text block cites, spanning the block's text in the response
613
+ * content. Citations of documents have no URL, so they aren't reported.
614
+ *
615
+ * @param start - Where the block's text starts in the response content.
616
+ */
617
+ export function toCitations(citations, start, end) {
618
+ const web = (citations ?? []).flatMap((c) => c.type === 'web_search_result_location' ? [{ url: c.url, title: c.title ?? undefined, start, end }]
619
+ : c.type === 'search_result_location' && /^https?:\/\//.test(c.source) ? [{ url: c.source, title: c.title ?? undefined, start, end }]
620
+ : []);
621
+ return web.length ? web : undefined;
622
+ }
623
+ /**
624
+ * What one output content block contributes to the response. Tools the API
625
+ * runs itself (server tool use and its results) aren't the caller's to run.
626
+ *
627
+ * @param offset - Where the block's text starts in the response content.
628
+ */
629
+ export function contentBlockChunk(block, index, offset) {
630
+ switch (block.type) {
631
+ case 'text':
632
+ return { content: block.text, citations: toCitations(block.citations, offset, offset + block.text.length) };
633
+ case 'tool_use':
634
+ return { toolCall: { id: block.id, name: block.name, arguments: JSON.stringify(block.input ?? {}) } };
635
+ case 'thinking':
636
+ return { reasoning: toReasoning({ thinking: block.thinking, signature: block.signature }, index) };
637
+ case 'redacted_thinking':
638
+ return { reasoning: toReasoning({ data: block.data }, index) };
639
+ default:
640
+ return {};
641
+ }
642
+ }
643
+ /**
644
+ * What a complete message contributes: its blocks, then why it stopped,
645
+ * usage and the tier it ran on.
646
+ *
647
+ * @param offset - How much response content came before this message (a
648
+ * continued turn).
649
+ */
650
+ export function messageChunks(message, offset = 0, index = 0) {
651
+ const chunks = [];
652
+ let at = offset;
653
+ message.content.forEach((block, i) => {
654
+ const chunk = contentBlockChunk(block, index + i, at);
655
+ at += chunk.content?.length ?? 0;
656
+ chunks.push(chunk);
657
+ });
658
+ chunks.push(endChunk(message));
659
+ return chunks;
660
+ }
661
+ /**
662
+ * The end of a message: finish reason, refusal, usage and tier.
663
+ */
664
+ export function endChunk(message) {
665
+ const refusal = message.stop_reason === 'refusal'
666
+ ? message.stop_details?.explanation ?? (message.stop_details?.category ? `Declined (${message.stop_details.category})` : 'Declined')
667
+ : undefined;
668
+ return {
669
+ finishReason: toFinishReason(message.stop_reason),
670
+ refusal,
671
+ usage: toUsage(message.usage),
672
+ serviceTier: toServiceTier(message.usage),
673
+ };
674
+ }
675
+ /**
676
+ * Turns stream events into chunks, building the message as it goes so a
677
+ * paused turn can be continued.
678
+ */
679
+ export class StreamAccumulator {
680
+ offset;
681
+ indexBase;
682
+ /** The message as streamed so far */
683
+ message;
684
+ blocks = new Map();
685
+ usage = {};
686
+ /**
687
+ * @param offset - Response content from earlier messages of the turn.
688
+ * @param indexBase - Content indexes taken by earlier messages of the turn.
689
+ */
690
+ constructor(offset = 0, indexBase = 0) {
691
+ this.offset = offset;
692
+ this.indexBase = indexBase;
693
+ }
694
+ /** Response content so far, earlier messages included */
695
+ get length() {
696
+ return this.offset;
697
+ }
698
+ /** The usage the API reported, for pricing */
699
+ get counts() {
700
+ return this.usage;
701
+ }
702
+ /**
703
+ * What one stream event contributes.
704
+ */
705
+ event(event) {
706
+ switch (event.type) {
707
+ case 'message_start':
708
+ this.message = { ...event.message, content: [] };
709
+ this.usage = { ...event.message.usage };
710
+ return event.message.model ? { model: event.message.model } : undefined;
711
+ case 'content_block_start': {
712
+ const block = structuredClone(event.content_block);
713
+ const streaming = { block, json: '', start: this.offset };
714
+ this.blocks.set(event.index, streaming);
715
+ this.message?.content.push(block);
716
+ if (block.type === 'text' && block.text) {
717
+ this.offset += block.text.length;
718
+ return { content: block.text };
719
+ }
720
+ if (block.type === 'tool_use') {
721
+ return { toolCallNamed: { id: block.id, name: block.name, arguments: '' } };
722
+ }
723
+ if (block.type === 'redacted_thinking') {
724
+ return { reasoning: toReasoning({ data: block.data }, this.indexBase + event.index) };
725
+ }
726
+ return undefined;
727
+ }
728
+ case 'content_block_delta': {
729
+ const streaming = this.blocks.get(event.index);
730
+ const block = streaming?.block;
731
+ const delta = event.delta;
732
+ switch (delta.type) {
733
+ case 'text_delta':
734
+ if (block?.type === 'text')
735
+ block.text += delta.text;
736
+ this.offset += delta.text.length;
737
+ return { content: delta.text };
738
+ case 'input_json_delta':
739
+ if (!streaming)
740
+ return undefined;
741
+ streaming.json += delta.partial_json;
742
+ return block?.type === 'tool_use'
743
+ ? { toolCallArguments: { id: block.id, name: block.name, arguments: streaming.json } }
744
+ : undefined;
745
+ case 'thinking_delta':
746
+ if (block?.type === 'thinking')
747
+ block.thinking += delta.thinking;
748
+ return { reasoning: { content: delta.thinking || undefined, provider: ANTHROPIC_PROVIDER, details: [{ type: 'reasoning.text', format: ANTHROPIC_REASONING_FORMAT, index: this.indexBase + event.index, text: delta.thinking }] } };
749
+ case 'signature_delta':
750
+ if (block?.type === 'thinking')
751
+ block.signature = delta.signature;
752
+ return { reasoning: { provider: ANTHROPIC_PROVIDER, details: [{ type: 'reasoning.text', format: ANTHROPIC_REASONING_FORMAT, index: this.indexBase + event.index, signature: delta.signature }] } };
753
+ case 'citations_delta':
754
+ if (block?.type === 'text')
755
+ block.citations = [...block.citations ?? [], delta.citation];
756
+ return undefined;
757
+ }
758
+ return undefined;
759
+ }
760
+ case 'content_block_stop': {
761
+ const streaming = this.blocks.get(event.index);
762
+ this.blocks.delete(event.index);
763
+ if (!streaming)
764
+ return undefined;
765
+ const { block, json, start } = streaming;
766
+ if ((block.type === 'tool_use' || block.type === 'server_tool_use') && json) {
767
+ try {
768
+ block.input = JSON.parse(json);
769
+ }
770
+ catch {
771
+ block.input = { _raw: json };
772
+ }
773
+ }
774
+ if (block.type === 'tool_use') {
775
+ return { toolCall: { id: block.id, name: block.name, arguments: json || JSON.stringify(block.input ?? {}) } };
776
+ }
777
+ if (block.type === 'text') {
778
+ const citations = toCitations(block.citations, start, this.offset);
779
+ return citations && { citations };
780
+ }
781
+ return undefined;
782
+ }
783
+ case 'message_delta': {
784
+ const usage = event.usage;
785
+ this.usage = {
786
+ ...this.usage,
787
+ output_tokens: usage.output_tokens,
788
+ ...(usage.input_tokens != null ? { input_tokens: usage.input_tokens } : {}),
789
+ ...(usage.cache_creation_input_tokens != null ? { cache_creation_input_tokens: usage.cache_creation_input_tokens } : {}),
790
+ ...(usage.cache_read_input_tokens != null ? { cache_read_input_tokens: usage.cache_read_input_tokens } : {}),
791
+ ...(usage.output_tokens_details ? { output_tokens_details: usage.output_tokens_details } : {}),
792
+ ...(usage.server_tool_use ? { server_tool_use: usage.server_tool_use } : {}),
793
+ };
794
+ if (this.message) {
795
+ this.message.stop_reason = event.delta.stop_reason;
796
+ this.message.stop_sequence = event.delta.stop_sequence;
797
+ this.message.stop_details = event.delta.stop_details ?? null;
798
+ this.message.usage = { ...this.message.usage, ...this.usage };
799
+ }
800
+ return undefined;
801
+ }
802
+ case 'message_stop':
803
+ return this.message ? endChunk({ ...this.message, usage: { ...this.message.usage, ...this.usage } }) : undefined;
804
+ }
805
+ return undefined;
806
+ }
807
+ }
808
+ //# sourceMappingURL=convert.js.map