@fabric-harness/sdk 6.4.0 → 6.6.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.
Files changed (153) hide show
  1. package/connector-spec/voice-telephony.md +120 -104
  2. package/dist/agent-route.d.ts +20 -2
  3. package/dist/agent-route.d.ts.map +1 -1
  4. package/dist/agent-route.js +31 -1
  5. package/dist/agent-route.js.map +1 -1
  6. package/dist/agent-router.d.ts +42 -0
  7. package/dist/agent-router.d.ts.map +1 -1
  8. package/dist/agent-router.js +49 -1
  9. package/dist/agent-router.js.map +1 -1
  10. package/dist/agent.d.ts.map +1 -1
  11. package/dist/agent.js +7 -2
  12. package/dist/agent.js.map +1 -1
  13. package/dist/attachment-store.d.ts +69 -0
  14. package/dist/attachment-store.d.ts.map +1 -1
  15. package/dist/attachment-store.js +183 -14
  16. package/dist/attachment-store.js.map +1 -1
  17. package/dist/attachments.d.ts +136 -0
  18. package/dist/attachments.d.ts.map +1 -0
  19. package/dist/attachments.js +332 -0
  20. package/dist/attachments.js.map +1 -0
  21. package/dist/channel.d.ts.map +1 -1
  22. package/dist/channel.js +26 -3
  23. package/dist/channel.js.map +1 -1
  24. package/dist/conversation-history.d.ts +186 -0
  25. package/dist/conversation-history.d.ts.map +1 -0
  26. package/dist/conversation-history.js +481 -0
  27. package/dist/conversation-history.js.map +1 -0
  28. package/dist/conversation-ui.d.ts +43 -2
  29. package/dist/conversation-ui.d.ts.map +1 -1
  30. package/dist/conversation-ui.js +44 -14
  31. package/dist/conversation-ui.js.map +1 -1
  32. package/dist/cost-budget.d.ts +50 -0
  33. package/dist/cost-budget.d.ts.map +1 -1
  34. package/dist/cost-budget.js +74 -4
  35. package/dist/cost-budget.js.map +1 -1
  36. package/dist/cost-enforcement.d.ts +32 -0
  37. package/dist/cost-enforcement.d.ts.map +1 -0
  38. package/dist/cost-enforcement.js +116 -0
  39. package/dist/cost-enforcement.js.map +1 -0
  40. package/dist/delivered-message.d.ts +20 -6
  41. package/dist/delivered-message.d.ts.map +1 -1
  42. package/dist/delivered-message.js +37 -8
  43. package/dist/delivered-message.js.map +1 -1
  44. package/dist/events.d.ts +13 -1
  45. package/dist/events.d.ts.map +1 -1
  46. package/dist/events.js.map +1 -1
  47. package/dist/experimental.d.ts +2 -2
  48. package/dist/experimental.d.ts.map +1 -1
  49. package/dist/experimental.js +1 -1
  50. package/dist/experimental.js.map +1 -1
  51. package/dist/governed-voice.d.ts +6 -0
  52. package/dist/governed-voice.d.ts.map +1 -1
  53. package/dist/governed-voice.js +142 -35
  54. package/dist/governed-voice.js.map +1 -1
  55. package/dist/history.d.ts +3 -2
  56. package/dist/history.d.ts.map +1 -1
  57. package/dist/history.js +57 -23
  58. package/dist/history.js.map +1 -1
  59. package/dist/index.d.ts +21 -14
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +11 -7
  62. package/dist/index.js.map +1 -1
  63. package/dist/loop.d.ts +25 -2
  64. package/dist/loop.d.ts.map +1 -1
  65. package/dist/loop.js +409 -60
  66. package/dist/loop.js.map +1 -1
  67. package/dist/model-pricing.d.ts +77 -4
  68. package/dist/model-pricing.d.ts.map +1 -1
  69. package/dist/model-pricing.js +259 -18
  70. package/dist/model-pricing.js.map +1 -1
  71. package/dist/model.d.ts +115 -3
  72. package/dist/model.d.ts.map +1 -1
  73. package/dist/model.js +487 -75
  74. package/dist/model.js.map +1 -1
  75. package/dist/pi-document-attachments.d.ts +43 -0
  76. package/dist/pi-document-attachments.d.ts.map +1 -0
  77. package/dist/pi-document-attachments.js +155 -0
  78. package/dist/pi-document-attachments.js.map +1 -0
  79. package/dist/pi-loop-runtime.d.ts +103 -1
  80. package/dist/pi-loop-runtime.d.ts.map +1 -1
  81. package/dist/pi-loop-runtime.js +907 -114
  82. package/dist/pi-loop-runtime.js.map +1 -1
  83. package/dist/prompt-attachments.d.ts +98 -0
  84. package/dist/prompt-attachments.d.ts.map +1 -0
  85. package/dist/prompt-attachments.js +279 -0
  86. package/dist/prompt-attachments.js.map +1 -0
  87. package/dist/session.d.ts +55 -0
  88. package/dist/session.d.ts.map +1 -1
  89. package/dist/session.js +443 -41
  90. package/dist/session.js.map +1 -1
  91. package/dist/stream-chunks.d.ts +15 -1
  92. package/dist/stream-chunks.d.ts.map +1 -1
  93. package/dist/stream-chunks.js +39 -18
  94. package/dist/stream-chunks.js.map +1 -1
  95. package/dist/strict.d.ts +23 -16
  96. package/dist/strict.d.ts.map +1 -1
  97. package/dist/strict.js +12 -8
  98. package/dist/strict.js.map +1 -1
  99. package/dist/submission-context.d.ts +7 -0
  100. package/dist/submission-context.d.ts.map +1 -1
  101. package/dist/submission-context.js.map +1 -1
  102. package/dist/submission-runner.d.ts +5 -0
  103. package/dist/submission-runner.d.ts.map +1 -1
  104. package/dist/submission-runner.js +11 -2
  105. package/dist/submission-runner.js.map +1 -1
  106. package/dist/tools.d.ts +9 -0
  107. package/dist/tools.d.ts.map +1 -1
  108. package/dist/tools.js +1 -0
  109. package/dist/tools.js.map +1 -1
  110. package/dist/types.d.ts +26 -0
  111. package/dist/types.d.ts.map +1 -1
  112. package/dist/types.js.map +1 -1
  113. package/dist/usage-completeness.d.ts +39 -0
  114. package/dist/usage-completeness.d.ts.map +1 -0
  115. package/dist/usage-completeness.js +135 -0
  116. package/dist/usage-completeness.js.map +1 -0
  117. package/dist/voice-openai-realtime.d.ts +24 -2
  118. package/dist/voice-openai-realtime.d.ts.map +1 -1
  119. package/dist/voice-openai-realtime.js +266 -49
  120. package/dist/voice-openai-realtime.js.map +1 -1
  121. package/dist/voice-pipeline.d.ts +81 -3
  122. package/dist/voice-pipeline.d.ts.map +1 -1
  123. package/dist/voice-pipeline.js +429 -60
  124. package/dist/voice-pipeline.js.map +1 -1
  125. package/dist/voice-stt-cartesia.d.ts +8 -0
  126. package/dist/voice-stt-cartesia.d.ts.map +1 -1
  127. package/dist/voice-stt-cartesia.js +77 -17
  128. package/dist/voice-stt-cartesia.js.map +1 -1
  129. package/dist/voice-stt-deepgram.d.ts +10 -2
  130. package/dist/voice-stt-deepgram.d.ts.map +1 -1
  131. package/dist/voice-stt-deepgram.js +78 -18
  132. package/dist/voice-stt-deepgram.js.map +1 -1
  133. package/dist/voice-stt.d.ts +13 -3
  134. package/dist/voice-stt.d.ts.map +1 -1
  135. package/dist/voice-tts-cartesia.d.ts +8 -0
  136. package/dist/voice-tts-cartesia.d.ts.map +1 -1
  137. package/dist/voice-tts-cartesia.js +48 -105
  138. package/dist/voice-tts-cartesia.js.map +1 -1
  139. package/dist/voice-tts-elevenlabs.d.ts +10 -1
  140. package/dist/voice-tts-elevenlabs.d.ts.map +1 -1
  141. package/dist/voice-tts-elevenlabs.js +50 -113
  142. package/dist/voice-tts-elevenlabs.js.map +1 -1
  143. package/dist/voice-ws-client.js +16 -3
  144. package/dist/voice-ws-client.js.map +1 -1
  145. package/dist/voice-ws-shared.d.ts +205 -6
  146. package/dist/voice-ws-shared.d.ts.map +1 -1
  147. package/dist/voice-ws-shared.js +510 -15
  148. package/dist/voice-ws-shared.js.map +1 -1
  149. package/dist/voice.d.ts +98 -4
  150. package/dist/voice.d.ts.map +1 -1
  151. package/dist/voice.js +71 -1
  152. package/dist/voice.js.map +1 -1
  153. package/package.json +3 -3
package/dist/model.js CHANGED
@@ -1,5 +1,44 @@
1
1
  import { createHash, createHmac } from "node:crypto";
2
2
  import { applyEstimatedCost } from "./model-pricing.js";
3
+ import { hasPriceableUsage } from "./cost-budget.js";
4
+ import { attachmentOmittedPlaceholder, isNativeImageMimeType, isDocumentMimeType, collectAttachmentPayloads, redactAttachmentPayloads, redactErrorAttachmentPayloads, warnAttachmentOmittedOnce, } from "./attachments.js";
5
+ /**
6
+ * Split a message's attachments into the ones an API accepts natively and a
7
+ * text rendering with placeholders for the rest (unsupported kind, unsupported
8
+ * image type, or bytes that are unavailable). Emits one console warning per
9
+ * `(api, kind)` the first time a placeholder replaces a supported-by-others kind.
10
+ */
11
+ export function partitionModelAttachments(message, support) {
12
+ const native = [];
13
+ const placeholders = [];
14
+ for (const attachment of message.attachments ?? []) {
15
+ const name = attachment.filename !== undefined ? { filename: attachment.filename } : {};
16
+ if (attachment.data === undefined || attachment.data.length === 0) {
17
+ placeholders.push(attachmentOmittedPlaceholder({ kind: attachment.type, api: support.api, reason: "unavailable", ...name }));
18
+ continue;
19
+ }
20
+ const supported = attachment.type === "document"
21
+ ? support.documents && isDocumentMimeType(attachment.mimeType)
22
+ : support.images && isNativeImageMimeType(attachment.mimeType);
23
+ if (supported) {
24
+ native.push({ ...attachment, data: attachment.data });
25
+ continue;
26
+ }
27
+ const kindSupported = attachment.type === "document" ? support.documents : support.images;
28
+ if (!kindSupported)
29
+ warnAttachmentOmittedOnce(support.api, attachment.type);
30
+ placeholders.push(attachmentOmittedPlaceholder({
31
+ kind: attachment.type,
32
+ api: support.api,
33
+ ...(kindSupported ? { reason: "unsupported-type", mimeType: attachment.mimeType } : {}),
34
+ ...name,
35
+ }));
36
+ }
37
+ const text = placeholders.length
38
+ ? [message.content, ...placeholders].filter((part) => part.length > 0).join("\n\n")
39
+ : message.content;
40
+ return { text, native };
41
+ }
3
42
  export function toolsToModelSchemas(tools) {
4
43
  return [...tools].map((tool) => ({
5
44
  name: tool.name,
@@ -7,8 +46,10 @@ export function toolsToModelSchemas(tools) {
7
46
  ...(tool.inputSchema !== undefined ? { inputSchema: tool.inputSchema } : {}),
8
47
  }));
9
48
  }
10
- const MAX_TRANSIENT_MODEL_RETRIES = 3;
11
- const TRANSIENT_MODEL_RETRY_BASE_DELAY_MS = 2_000;
49
+ /** @internal Default transient model retries shared by generate and stream paths. */
50
+ export const MAX_TRANSIENT_MODEL_RETRIES = 3;
51
+ /** @internal Default base backoff shared by generate and stream paths. */
52
+ export const TRANSIENT_MODEL_RETRY_BASE_DELAY_MS = 2_000;
12
53
  export async function generateWithRuntime(provider, request, options = {}) {
13
54
  const maxAttempts = (options.retries ?? MAX_TRANSIENT_MODEL_RETRIES) + 1;
14
55
  const baseDelayMs = options.retryDelayMs ?? TRANSIENT_MODEL_RETRY_BASE_DELAY_MS;
@@ -38,28 +79,22 @@ export async function generateWithRuntime(provider, request, options = {}) {
38
79
  status: "start",
39
80
  ...(request.model !== undefined ? { model: request.model } : {}),
40
81
  });
82
+ let response;
41
83
  try {
42
- const response = await provider.generate({ ...request, signal: controller.signal });
84
+ response = await provider.generate({ ...request, signal: controller.signal });
43
85
  if (timeout)
44
86
  clearTimeout(timeout);
45
87
  options.signal?.removeEventListener("abort", abortListener);
46
- await options.onAttempt?.({
47
- provider: provider.name,
48
- attempt,
49
- maxAttempts,
50
- status: "success",
51
- durationMs: Date.now() - startedAt,
52
- ...(request.model !== undefined ? { model: request.model } : {}),
53
- ...(response.usage !== undefined ? { usage: response.usage } : {}),
54
- });
55
- return response;
56
88
  }
57
89
  catch (error) {
58
90
  if (timeout)
59
91
  clearTimeout(timeout);
60
92
  options.signal?.removeEventListener("abort", abortListener);
61
93
  lastError = error;
62
- const message = error instanceof Error ? error.message : String(error);
94
+ // Providers can echo submitted attachment bytes in error text; strip
95
+ // them before the message reaches attempt journals and telemetry.
96
+ // Exact-match redaction covers payloads too short for the generic rules.
97
+ const message = redactAttachmentPayloads(error instanceof Error ? error.message : String(error), collectAttachmentPayloads(request.messages));
63
98
  const canRetry = attempt < maxAttempts && !options.signal?.aborted && isRetryableModelError(error);
64
99
  await options.onAttempt?.({
65
100
  provider: provider.name,
@@ -80,12 +115,31 @@ export async function generateWithRuntime(provider, request, options = {}) {
80
115
  : calculateRetryDelay(baseDelayMs, attempt);
81
116
  await sleepWithAbort(waitMs, retryAbortController.signal);
82
117
  }
118
+ if (response === undefined)
119
+ continue;
120
+ // Record success outside the provider try: a failure here is local
121
+ // (journal/telemetry), must not be classified as a provider error, and
122
+ // must never trigger another paid model call.
123
+ await options.onAttempt?.({
124
+ provider: provider.name,
125
+ attempt,
126
+ maxAttempts,
127
+ status: "success",
128
+ durationMs: Date.now() - startedAt,
129
+ ...(request.model !== undefined ? { model: request.model } : {}),
130
+ ...(response.usage !== undefined ? { usage: response.usage } : {}),
131
+ });
132
+ return response;
83
133
  }
84
134
  }
85
135
  finally {
86
136
  options.signal?.removeEventListener("abort", onCallerAbort);
87
137
  }
88
- throw lastError instanceof Error ? lastError : new Error(String(lastError));
138
+ // The rejected error reaches callers, loggers and CLIs directly, so it gets
139
+ // the same exact-payload redaction as the attempt events: message, stack,
140
+ // a ProviderHttpError body and any cause chain. Redaction is in place, so
141
+ // the class, status, retryAfterMs and retry classification are unchanged.
142
+ throw redactErrorAttachmentPayloads(lastError, collectAttachmentPayloads(request.messages));
89
143
  }
90
144
  /**
91
145
  * Strip a routing prefix (`<provider-name>/`) from a model reference. `AgentInit.model` keeps
@@ -229,6 +283,7 @@ const REASONING_MODEL_PATTERNS = [
229
283
  /gpt-oss/i, // OpenAI open-weights reasoning
230
284
  /^claude-3-7/i, // Claude 3.7 extended thinking
231
285
  /^claude-(opus|sonnet|haiku)-4/i, // Claude 4.x families
286
+ /^claude-(opus|sonnet|fable|mythos)-5/i, // Claude 5.x families
232
287
  /^gemini-2\.5/i, // Gemini 2.5 thinking
233
288
  ];
234
289
  /** Whether a model id (with or without provider prefix) is a known reasoning model. */
@@ -253,6 +308,72 @@ function openAIReasoningEffort(level) {
253
308
  return "high";
254
309
  }
255
310
  }
311
+ /**
312
+ * Claude models that take adaptive thinking plus `output_config.effort`
313
+ * instead of a fixed `budget_tokens` budget: Opus/Sonnet 4.6 and later and
314
+ * every Claude 5 family. Opus 4.7+, Opus 5.x, Sonnet 5.x, Fable and Mythos
315
+ * reject `budget_tokens` with a 400, so they must never receive it.
316
+ */
317
+ const ANTHROPIC_ADAPTIVE_THINKING_PATTERNS = [
318
+ // Minor version 6-99; an eight-digit date suffix (claude-sonnet-4-20250514)
319
+ // is not a minor version.
320
+ /^claude-(opus|sonnet)-4-([6-9]|[1-9]\d)(?:\D|$)/i,
321
+ /^claude-(opus|sonnet|fable|mythos)-5/i,
322
+ ];
323
+ /** Models that accept the `xhigh` effort level (introduced with Opus 4.7). */
324
+ const ANTHROPIC_XHIGH_EFFORT_PATTERNS = [
325
+ /^claude-opus-4-([7-9]|[1-9]\d)(?:\D|$)/i,
326
+ /^claude-(opus|sonnet|fable|mythos)-5/i,
327
+ ];
328
+ function anthropicModelId(model) {
329
+ return model.includes("/") ? model.slice(model.lastIndexOf("/") + 1) : model;
330
+ }
331
+ /** Whether an Anthropic model takes adaptive thinking rather than a token budget. */
332
+ function anthropicUsesAdaptiveThinking(model) {
333
+ const id = anthropicModelId(model);
334
+ return ANTHROPIC_ADAPTIVE_THINKING_PATTERNS.some((re) => re.test(id));
335
+ }
336
+ function anthropicEffort(model, level) {
337
+ switch (level) {
338
+ case "minimal":
339
+ case "low":
340
+ return "low";
341
+ case "medium":
342
+ return "medium";
343
+ case "high":
344
+ return "high";
345
+ case "xhigh":
346
+ return ANTHROPIC_XHIGH_EFFORT_PATTERNS.some((re) => re.test(anthropicModelId(model)))
347
+ ? "xhigh"
348
+ : "high";
349
+ }
350
+ }
351
+ /**
352
+ * Request fields for a caller-selected thinking level on the native
353
+ * Anthropic provider. Current models get adaptive thinking with an effort
354
+ * level; older extended-thinking models keep a token budget, and
355
+ * `max_tokens` is raised to leave room for it.
356
+ */
357
+ function anthropicThinkingRequest(model, level, maxTokens) {
358
+ if (!shouldApplyReasoning(model, level))
359
+ return { body: {}, maxTokens };
360
+ // Thinking shares max_tokens with the answer in both modes, so keep the same
361
+ // allowance the budget path has always reserved for the requested level.
362
+ const budget = anthropicThinkingBudget(level);
363
+ if (anthropicUsesAdaptiveThinking(model)) {
364
+ return {
365
+ body: {
366
+ thinking: { type: "adaptive" },
367
+ output_config: { effort: anthropicEffort(model, level) },
368
+ },
369
+ maxTokens: Math.max(maxTokens, budget + 1024),
370
+ };
371
+ }
372
+ return {
373
+ body: { thinking: { type: "enabled", budget_tokens: budget } },
374
+ maxTokens: Math.max(maxTokens, budget + 1024),
375
+ };
376
+ }
256
377
  /** Anthropic extended-thinking token budget (>= 1024; `max_tokens` must exceed it). */
257
378
  function anthropicThinkingBudget(level) {
258
379
  switch (level) {
@@ -293,9 +414,15 @@ export class OpenAICompatibleModelProvider {
293
414
  rateLimiter;
294
415
  rateLimitKey;
295
416
  fetchImpl;
417
+ messageOptions;
296
418
  constructor(options) {
297
419
  this.name = options.name ?? "openai-compatible";
298
420
  this.baseUrl = options.baseUrl.replace(/\/$/, "");
421
+ this.messageOptions = {
422
+ api: "openai-completions",
423
+ images: options.imageInput ?? true,
424
+ documents: options.documentInput ?? isOpenAIPlatformBaseUrl(this.baseUrl),
425
+ };
299
426
  this.apiKey = options.apiKey;
300
427
  this.tokenProvider = options.tokenProvider;
301
428
  if (options.defaultModel !== undefined)
@@ -331,7 +458,7 @@ export class OpenAICompatibleModelProvider {
331
458
  },
332
459
  body: JSON.stringify({
333
460
  model,
334
- messages: request.messages.map(toOpenAIMessage),
461
+ messages: request.messages.map((message) => toOpenAIMessage(message, this.messageOptions)),
335
462
  ...(request.tools !== undefined ? { tools: request.tools.map(toOpenAITool) } : {}),
336
463
  ...(shouldApplyReasoning(model, request.thinkingLevel)
337
464
  ? { reasoning_effort: openAIReasoningEffort(request.thinkingLevel) }
@@ -352,7 +479,7 @@ export class OpenAICompatibleModelProvider {
352
479
  throw new Error(`${this.name}: failed to parse response as JSON: ${message}`);
353
480
  }
354
481
  const result = openAIChatCompletionToModelResponse(json);
355
- applyEstimatedCost(`${this.name}/${model}`, result.usage);
482
+ priceAdapterUsage(`${this.name}/${model}`, result.usage);
356
483
  return result;
357
484
  }
358
485
  async *stream(request) {
@@ -376,7 +503,7 @@ export class OpenAICompatibleModelProvider {
376
503
  model,
377
504
  stream: true,
378
505
  stream_options: { include_usage: true },
379
- messages: request.messages.map(toOpenAIMessage),
506
+ messages: request.messages.map((message) => toOpenAIMessage(message, this.messageOptions)),
380
507
  ...(request.tools !== undefined ? { tools: request.tools.map(toOpenAITool) } : {}),
381
508
  ...(shouldApplyReasoning(model, request.thinkingLevel)
382
509
  ? { reasoning_effort: openAIReasoningEffort(request.thinkingLevel) }
@@ -392,6 +519,7 @@ export class OpenAICompatibleModelProvider {
392
519
  const thinking = [];
393
520
  const toolCallBuffers = new Map();
394
521
  let usage;
522
+ let stopReason;
395
523
  for await (const event of decodeOpenAISSE(response.body)) {
396
524
  if (event === "[DONE]")
397
525
  break;
@@ -399,6 +527,8 @@ export class OpenAICompatibleModelProvider {
399
527
  if (!json)
400
528
  continue;
401
529
  const choice = json.choices?.[0];
530
+ if (typeof choice?.finish_reason === "string")
531
+ stopReason = normalizeOpenAIFinishReason(choice.finish_reason);
402
532
  const delta = choice?.delta;
403
533
  const contentDelta = openAIMessageText(delta?.content) ?? "";
404
534
  const reasoningDelta = typeof delta?.reasoning_content === "string"
@@ -456,14 +586,15 @@ export class OpenAICompatibleModelProvider {
456
586
  toolCalls: [...toolCallBuffers.values()].map((buf, index) => ({
457
587
  id: buf.id ?? `openai-stream-${index + 1}`,
458
588
  name: buf.name ?? "",
459
- input: buf.args ? JSON.parse(buf.args) : {},
589
+ input: parseToolArguments(buf.args, stopReason),
460
590
  })),
461
591
  }
462
592
  : {}),
463
593
  ...(usage ? { usage } : {}),
594
+ ...(stopReason ? { stopReason } : {}),
464
595
  };
465
596
  if (done.usage)
466
- applyEstimatedCost(`${this.name}/${model}`, done.usage);
597
+ priceAdapterUsage(`${this.name}/${model}`, done.usage);
467
598
  yield { done };
468
599
  }
469
600
  }
@@ -488,14 +619,14 @@ export class AzureOpenAIModelProvider {
488
619
  ...(request.signal !== undefined ? { signal: request.signal } : {}),
489
620
  headers: { "content-type": "application/json", "api-key": this.apiKey, ...this.headers },
490
621
  body: JSON.stringify({
491
- messages: request.messages.map(toOpenAIMessage),
622
+ messages: request.messages.map((message) => toOpenAIMessage(message, { api: "azure-openai-completions", images: true, documents: false })),
492
623
  ...(request.tools !== undefined ? { tools: request.tools.map(toOpenAITool) } : {}),
493
624
  }),
494
625
  });
495
626
  if (!response.ok)
496
627
  throw formatProviderHttpError(this.name, this.deployment, response.status, response.statusText, await response.text(), response.headers);
497
628
  const result = openAIChatCompletionToModelResponse((await response.json()));
498
- applyEstimatedCost(`azure-openai/${this.deployment}`, result.usage);
629
+ priceAdapterUsage(`azure-openai/${this.deployment}`, result.usage);
499
630
  return result;
500
631
  }
501
632
  }
@@ -526,7 +657,7 @@ export class GeminiModelProvider {
526
657
  if (!response.ok)
527
658
  throw formatProviderHttpError(this.name, model, response.status, response.statusText, await response.text(), response.headers);
528
659
  const result = geminiResponseToModelResponse((await response.json()));
529
- applyEstimatedCost(`gemini/${model}`, result.usage);
660
+ priceAdapterUsage(`gemini/${model}`, result.usage);
530
661
  return result;
531
662
  }
532
663
  }
@@ -564,7 +695,7 @@ export class VertexAIModelProvider {
564
695
  if (!response.ok)
565
696
  throw formatProviderHttpError(this.name, model, response.status, response.statusText, await response.text(), response.headers);
566
697
  const result = geminiResponseToModelResponse((await response.json()));
567
- applyEstimatedCost(`gemini/${model}`, result.usage);
698
+ priceAdapterUsage(`gemini/${model}`, result.usage);
568
699
  return result;
569
700
  }
570
701
  }
@@ -615,7 +746,7 @@ export class BedrockModelProvider {
615
746
  if (!response.ok)
616
747
  throw formatProviderHttpError(this.name, model, response.status, response.statusText, await response.text(), response.headers);
617
748
  const result = bedrockResponseToModelResponse((await response.json()));
618
- applyEstimatedCost(`bedrock/${model}`, result.usage);
749
+ priceAdapterUsage(`bedrock/${model}`, result.usage);
619
750
  return result;
620
751
  }
621
752
  }
@@ -650,7 +781,7 @@ export class CohereModelProvider {
650
781
  if (!response.ok)
651
782
  throw formatProviderHttpError(this.name, model, response.status, response.statusText, await response.text(), response.headers);
652
783
  const result = cohereResponseToModelResponse((await response.json()));
653
- applyEstimatedCost(`cohere/${model}`, result.usage);
784
+ priceAdapterUsage(`cohere/${model}`, result.usage);
654
785
  return result;
655
786
  }
656
787
  }
@@ -703,12 +834,8 @@ export class AnthropicModelProvider {
703
834
  if (this.rateLimiter)
704
835
  await this.rateLimiter.acquire(this.rateLimitKey, request.signal ? { signal: request.signal } : undefined);
705
836
  const { system, messages } = toAnthropicMessages(request.messages);
706
- const thinkingBudget = shouldApplyReasoning(model, request.thinkingLevel)
707
- ? anthropicThinkingBudget(request.thinkingLevel)
708
- : undefined;
709
- const maxTokens = thinkingBudget !== undefined
710
- ? Math.max(this.maxTokens, thinkingBudget + 1024)
711
- : this.maxTokens;
837
+ const thinkingRequest = anthropicThinkingRequest(model, request.thinkingLevel, this.maxTokens);
838
+ const maxTokens = thinkingRequest.maxTokens;
712
839
  const response = await fetch(`${this.baseUrl}/messages`, {
713
840
  method: "POST",
714
841
  ...(request.signal !== undefined ? { signal: request.signal } : {}),
@@ -721,9 +848,7 @@ export class AnthropicModelProvider {
721
848
  body: JSON.stringify({
722
849
  model,
723
850
  max_tokens: maxTokens,
724
- ...(thinkingBudget !== undefined
725
- ? { thinking: { type: "enabled", budget_tokens: thinkingBudget } }
726
- : {}),
851
+ ...thinkingRequest.body,
727
852
  ...(system ? { system } : {}),
728
853
  messages,
729
854
  ...(request.tools !== undefined ? { tools: request.tools.map(toAnthropicTool) } : {}),
@@ -732,7 +857,7 @@ export class AnthropicModelProvider {
732
857
  if (!response.ok)
733
858
  throw formatProviderHttpError(this.name, model, response.status, response.statusText, await response.text(), response.headers);
734
859
  const result = anthropicResponseToModelResponse((await response.json()));
735
- applyEstimatedCost(`anthropic/${model}`, result.usage);
860
+ priceAdapterUsage(`anthropic/${model}`, result.usage);
736
861
  return result;
737
862
  }
738
863
  async *stream(request) {
@@ -742,12 +867,8 @@ export class AnthropicModelProvider {
742
867
  if (this.rateLimiter)
743
868
  await this.rateLimiter.acquire(this.rateLimitKey, request.signal ? { signal: request.signal } : undefined);
744
869
  const { system, messages } = toAnthropicMessages(request.messages);
745
- const thinkingBudget = shouldApplyReasoning(model, request.thinkingLevel)
746
- ? anthropicThinkingBudget(request.thinkingLevel)
747
- : undefined;
748
- const maxTokens = thinkingBudget !== undefined
749
- ? Math.max(this.maxTokens, thinkingBudget + 1024)
750
- : this.maxTokens;
870
+ const thinkingRequest = anthropicThinkingRequest(model, request.thinkingLevel, this.maxTokens);
871
+ const maxTokens = thinkingRequest.maxTokens;
751
872
  const response = await fetch(`${this.baseUrl}/messages`, {
752
873
  method: "POST",
753
874
  ...(request.signal !== undefined ? { signal: request.signal } : {}),
@@ -762,9 +883,7 @@ export class AnthropicModelProvider {
762
883
  model,
763
884
  stream: true,
764
885
  max_tokens: maxTokens,
765
- ...(thinkingBudget !== undefined
766
- ? { thinking: { type: "enabled", budget_tokens: thinkingBudget } }
767
- : {}),
886
+ ...thinkingRequest.body,
768
887
  ...(system ? { system } : {}),
769
888
  messages,
770
889
  ...(request.tools !== undefined ? { tools: request.tools.map(toAnthropicTool) } : {}),
@@ -776,11 +895,19 @@ export class AnthropicModelProvider {
776
895
  const thinking = [];
777
896
  const toolCallBuffers = new Map();
778
897
  let usage;
898
+ let stopReason;
899
+ let sawMessageStop = false;
779
900
  for await (const event of decodeAnthropicSSE(response.body)) {
780
901
  const type = event.event ?? "";
781
902
  const data = event.data;
903
+ if (type === "message_stop") {
904
+ sawMessageStop = true;
905
+ continue;
906
+ }
782
907
  if (!data)
783
908
  continue;
909
+ if (type === "error")
910
+ throw anthropicStreamError(this.name, model, data);
784
911
  if (type === "content_block_start") {
785
912
  const idx = typeof data.index === "number" ? data.index : 0;
786
913
  const block = data.content_block;
@@ -822,6 +949,9 @@ export class AnthropicModelProvider {
822
949
  }
823
950
  }
824
951
  else if (type === "message_delta") {
952
+ const messageDelta = data.delta;
953
+ if (typeof messageDelta?.stop_reason === "string")
954
+ stopReason = normalizeAnthropicStopReason(messageDelta.stop_reason);
825
955
  const u = data.usage;
826
956
  if (u) {
827
957
  usage = usage ?? {};
@@ -833,9 +963,6 @@ export class AnthropicModelProvider {
833
963
  usage.cachedInputTokens = u.cache_read_input_tokens;
834
964
  if (typeof u.cache_creation_input_tokens === "number")
835
965
  usage.cacheWriteTokens = u.cache_creation_input_tokens;
836
- if (usage.inputTokens !== undefined || usage.outputTokens !== undefined) {
837
- usage.totalTokens = (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0);
838
- }
839
966
  }
840
967
  }
841
968
  else if (type === "message_start") {
@@ -852,6 +979,11 @@ export class AnthropicModelProvider {
852
979
  }
853
980
  }
854
981
  }
982
+ // A stream that closes before message_stop was cut off: the text and tool
983
+ // arguments seen so far are partial, so never report them as a response.
984
+ if (!sawMessageStop) {
985
+ throw new ProviderHttpError(`${this.name} model ${model}: stream ended before message_stop (connection lost)`, this.name, 502, "Bad Gateway", "");
986
+ }
855
987
  const done = {
856
988
  ...(text.length ? { message: { role: "assistant", content: text.join("") } } : {}),
857
989
  ...(thinking.length ? { thinking: thinking.join("") } : {}),
@@ -860,14 +992,15 @@ export class AnthropicModelProvider {
860
992
  toolCalls: [...toolCallBuffers.values()].map((buf, index) => ({
861
993
  id: buf.id ?? `anthropic-stream-${index + 1}`,
862
994
  name: buf.name ?? "",
863
- input: buf.args ? JSON.parse(buf.args) : {},
995
+ input: parseToolArguments(buf.args, stopReason),
864
996
  })),
865
997
  }
866
998
  : {}),
867
- ...(usage ? { usage } : {}),
999
+ ...(usage ? { usage: foldSeparateCacheReads(usage) } : {}),
1000
+ ...(stopReason ? { stopReason } : {}),
868
1001
  };
869
1002
  if (done.usage)
870
- applyEstimatedCost(`anthropic/${model}`, done.usage);
1003
+ priceAdapterUsage(`anthropic/${model}`, done.usage);
871
1004
  yield { done };
872
1005
  }
873
1006
  }
@@ -893,12 +1026,14 @@ function estimateUsage(messages) {
893
1026
  const chars = messages.reduce((sum, message) => sum + message.content.length, 0);
894
1027
  return { totalTokens: Math.ceil(chars / 4) };
895
1028
  }
896
- function calculateRetryDelay(baseMs, attempt) {
1029
+ /** @internal */
1030
+ export function calculateRetryDelay(baseMs, attempt) {
897
1031
  const baseDelay = baseMs * 2 ** (attempt - 1);
898
1032
  const jittered = baseDelay * (0.75 + Math.random() * 0.5);
899
1033
  return Math.round(jittered);
900
1034
  }
901
- function isRetryableModelError(error) {
1035
+ /** @internal Shared transient-model-error classifier for generate and stream retries. */
1036
+ export function isRetryableModelError(error) {
902
1037
  if (error instanceof ProviderHttpError)
903
1038
  return error.status === 429 || error.status >= 500;
904
1039
  if (error instanceof Error && error.name === "AbortError")
@@ -909,7 +1044,8 @@ function isRetryableModelError(error) {
909
1044
  function delay(ms) {
910
1045
  return new Promise((resolve) => setTimeout(resolve, ms));
911
1046
  }
912
- function sleepWithAbort(ms, signal) {
1047
+ /** @internal */
1048
+ export function sleepWithAbort(ms, signal) {
913
1049
  if (signal.aborted)
914
1050
  return Promise.reject(createAbortError(signal.reason));
915
1051
  return new Promise((resolve, reject) => {
@@ -935,7 +1071,7 @@ function createAbortError(reason) {
935
1071
  err.name = "AbortError";
936
1072
  return err;
937
1073
  }
938
- export function toOpenAIMessage(message) {
1074
+ export function toOpenAIMessage(message, options) {
939
1075
  if (message.role === "tool") {
940
1076
  return {
941
1077
  role: "tool",
@@ -950,8 +1086,44 @@ export function toOpenAIMessage(message) {
950
1086
  tool_calls: message.toolCalls.map(toOpenAIToolCallForMessage),
951
1087
  };
952
1088
  }
1089
+ if (message.role === "user" && message.attachments?.length) {
1090
+ const opts = typeof options === "object" && options !== null ? options : {};
1091
+ const { text, native } = partitionModelAttachments(message, {
1092
+ api: opts.api ?? "openai-completions",
1093
+ images: opts.images ?? true,
1094
+ documents: opts.documents ?? false,
1095
+ });
1096
+ if (native.length === 0)
1097
+ return { role: "user", content: text };
1098
+ return {
1099
+ role: "user",
1100
+ content: [
1101
+ ...(text ? [{ type: "text", text }] : []),
1102
+ ...native.map((attachment) => attachment.type === "document"
1103
+ ? {
1104
+ type: "file",
1105
+ file: {
1106
+ filename: attachment.filename ?? "document.pdf",
1107
+ file_data: `data:${attachment.mimeType};base64,${attachment.data}`,
1108
+ },
1109
+ }
1110
+ : {
1111
+ type: "image_url",
1112
+ image_url: { url: `data:${attachment.mimeType};base64,${attachment.data}` },
1113
+ }),
1114
+ ],
1115
+ };
1116
+ }
953
1117
  return { role: message.role, content: message.content };
954
1118
  }
1119
+ function isOpenAIPlatformBaseUrl(baseUrl) {
1120
+ try {
1121
+ return new URL(baseUrl).hostname === "api.openai.com";
1122
+ }
1123
+ catch {
1124
+ return false;
1125
+ }
1126
+ }
955
1127
  function toOpenAIToolCallForMessage(call) {
956
1128
  return {
957
1129
  id: call.id,
@@ -989,16 +1161,116 @@ function normalizeOpenAIParameters(schema) {
989
1161
  required: Array.isArray(objectSchema.required) ? objectSchema.required : [],
990
1162
  };
991
1163
  }
992
- function fromOpenAIToolCall(call) {
1164
+ function fromOpenAIToolCall(call, stopReason) {
993
1165
  return {
994
1166
  id: call.id,
995
1167
  name: call.function.name,
996
- input: call.function.arguments ? JSON.parse(call.function.arguments) : {},
1168
+ input: parseToolArguments(call.function.arguments ?? "", stopReason),
997
1169
  };
998
1170
  }
1171
+ /**
1172
+ * Parse streamed or returned tool-call argument JSON. Arguments from a
1173
+ * `length`-truncated response may be incomplete JSON; they are never executed,
1174
+ * so an unparseable truncated payload degrades to `{}` instead of failing the
1175
+ * whole response. Complete responses keep strict parsing.
1176
+ */
1177
+ function parseToolArguments(args, stopReason) {
1178
+ if (!args)
1179
+ return {};
1180
+ if (stopReason !== "length")
1181
+ return JSON.parse(args);
1182
+ try {
1183
+ return JSON.parse(args);
1184
+ }
1185
+ catch {
1186
+ return {};
1187
+ }
1188
+ }
1189
+ /** Normalize an OpenAI-compatible `finish_reason`. */
1190
+ function normalizeOpenAIFinishReason(reason) {
1191
+ switch (reason) {
1192
+ case "stop":
1193
+ return "stop";
1194
+ case "length":
1195
+ return "length";
1196
+ case "tool_calls":
1197
+ case "function_call":
1198
+ return "tool_calls";
1199
+ case "content_filter":
1200
+ return "content_filter";
1201
+ default:
1202
+ return "other";
1203
+ }
1204
+ }
1205
+ function normalizeAnthropicStopReason(reason) {
1206
+ switch (reason) {
1207
+ case "end_turn":
1208
+ case "stop_sequence":
1209
+ return "stop";
1210
+ case "max_tokens":
1211
+ case "model_context_window_exceeded":
1212
+ return "length";
1213
+ case "tool_use":
1214
+ return "tool_calls";
1215
+ case "refusal":
1216
+ return "content_filter";
1217
+ default:
1218
+ return "other";
1219
+ }
1220
+ }
1221
+ function normalizeGeminiFinishReason(reason) {
1222
+ switch (reason) {
1223
+ case "STOP":
1224
+ return "stop";
1225
+ case "MAX_TOKENS":
1226
+ return "length";
1227
+ case "SAFETY":
1228
+ case "RECITATION":
1229
+ case "BLOCKLIST":
1230
+ case "PROHIBITED_CONTENT":
1231
+ case "SPII":
1232
+ case "IMAGE_SAFETY":
1233
+ return "content_filter";
1234
+ default:
1235
+ return "other";
1236
+ }
1237
+ }
1238
+ function normalizeBedrockStopReason(reason) {
1239
+ switch (reason) {
1240
+ case "end_turn":
1241
+ case "stop_sequence":
1242
+ return "stop";
1243
+ case "max_tokens":
1244
+ case "model_context_window_exceeded":
1245
+ return "length";
1246
+ case "tool_use":
1247
+ return "tool_calls";
1248
+ case "guardrail_intervened":
1249
+ case "content_filtered":
1250
+ return "content_filter";
1251
+ default:
1252
+ return "other";
1253
+ }
1254
+ }
1255
+ function normalizeCohereFinishReason(reason) {
1256
+ switch (reason) {
1257
+ case "COMPLETE":
1258
+ case "STOP_SEQUENCE":
1259
+ return "stop";
1260
+ case "MAX_TOKENS":
1261
+ return "length";
1262
+ case "TOOL_CALL":
1263
+ return "tool_calls";
1264
+ default:
1265
+ return "other";
1266
+ }
1267
+ }
999
1268
  export function openAIChatCompletionToModelResponse(json) {
1000
1269
  const choice = json.choices?.[0];
1001
1270
  const message = choice?.message;
1271
+ const stopReason = typeof choice?.finish_reason === "string"
1272
+ ? normalizeOpenAIFinishReason(choice.finish_reason)
1273
+ : undefined;
1002
1274
  const content = openAIMessageText(message?.content);
1003
1275
  const reasoning = typeof message?.reasoning_content === "string"
1004
1276
  ? message.reasoning_content
@@ -1006,7 +1278,10 @@ export function openAIChatCompletionToModelResponse(json) {
1006
1278
  const result = {
1007
1279
  ...(content ? { message: { role: "assistant", content } } : {}),
1008
1280
  ...(reasoning ? { thinking: reasoning } : {}),
1009
- ...(message?.tool_calls ? { toolCalls: message.tool_calls.map(fromOpenAIToolCall) } : {}),
1281
+ ...(message?.tool_calls
1282
+ ? { toolCalls: message.tool_calls.map((call) => fromOpenAIToolCall(call, stopReason)) }
1283
+ : {}),
1284
+ ...(stopReason ? { stopReason } : {}),
1010
1285
  };
1011
1286
  if (json.usage) {
1012
1287
  const usage = {};
@@ -1068,6 +1343,7 @@ function toAnthropicMessages(messages) {
1068
1343
  type: "tool_result",
1069
1344
  tool_use_id: message.toolCallId ?? message.name ?? "tool",
1070
1345
  content: message.content,
1346
+ ...(message.isError ? { is_error: true } : {}),
1071
1347
  },
1072
1348
  ],
1073
1349
  };
@@ -1085,6 +1361,31 @@ function toAnthropicMessages(messages) {
1085
1361
  ],
1086
1362
  };
1087
1363
  }
1364
+ if (message.role === "user" && message.attachments?.length) {
1365
+ const { text, native } = partitionModelAttachments(message, {
1366
+ api: "anthropic-messages",
1367
+ images: true,
1368
+ documents: true,
1369
+ });
1370
+ if (native.length === 0)
1371
+ return { role: "user", content: text };
1372
+ return {
1373
+ role: "user",
1374
+ content: [
1375
+ ...native.map((attachment) => attachment.type === "document"
1376
+ ? {
1377
+ type: "document",
1378
+ source: { type: "base64", media_type: attachment.mimeType, data: attachment.data },
1379
+ ...(attachment.filename ? { title: attachment.filename } : {}),
1380
+ }
1381
+ : {
1382
+ type: "image",
1383
+ source: { type: "base64", media_type: attachment.mimeType, data: attachment.data },
1384
+ }),
1385
+ ...(text ? [{ type: "text", text }] : []),
1386
+ ],
1387
+ };
1388
+ }
1088
1389
  return {
1089
1390
  role: message.role === "assistant" ? "assistant" : "user",
1090
1391
  content: message.content,
@@ -1119,6 +1420,22 @@ function toGeminiRequest(request, model) {
1119
1420
  functionCall: { name: call.name, args: call.input ?? {} },
1120
1421
  })),
1121
1422
  };
1423
+ if (message.role === "user" && message.attachments?.length) {
1424
+ const { text, native } = partitionModelAttachments(message, {
1425
+ api: "google-generative-ai",
1426
+ images: true,
1427
+ documents: true,
1428
+ });
1429
+ return {
1430
+ role: "user",
1431
+ parts: [
1432
+ ...(text || native.length === 0 ? [{ text }] : []),
1433
+ ...native.map((attachment) => ({
1434
+ inlineData: { mimeType: attachment.mimeType, data: attachment.data },
1435
+ })),
1436
+ ],
1437
+ };
1438
+ }
1122
1439
  return {
1123
1440
  role: message.role === "assistant" ? "model" : "user",
1124
1441
  parts: [{ text: message.content }],
@@ -1165,14 +1482,28 @@ function geminiResponseToModelResponse(json) {
1165
1482
  : {}),
1166
1483
  ...(toolCalls.length > 0 ? { toolCalls } : {}),
1167
1484
  };
1485
+ const finishReason = json.candidates?.[0]?.finishReason;
1486
+ if (typeof finishReason === "string")
1487
+ result.stopReason = normalizeGeminiFinishReason(finishReason);
1168
1488
  if (json.usageMetadata) {
1169
1489
  const usage = {};
1170
- if (json.usageMetadata.promptTokenCount !== undefined)
1171
- usage.inputTokens = json.usageMetadata.promptTokenCount;
1172
- if (json.usageMetadata.candidatesTokenCount !== undefined)
1173
- usage.outputTokens = json.usageMetadata.candidatesTokenCount;
1174
- if (json.usageMetadata.totalTokenCount !== undefined)
1175
- usage.totalTokens = json.usageMetadata.totalTokenCount;
1490
+ const meta = json.usageMetadata;
1491
+ // Gemini bills thinking tokens as output and tool-use prompt tokens as
1492
+ // input; its total includes both, so leaving them out would underprice
1493
+ // the call and leave the total unexplained.
1494
+ if (meta.promptTokenCount !== undefined || meta.toolUsePromptTokenCount !== undefined)
1495
+ usage.inputTokens = (meta.promptTokenCount ?? 0) + (meta.toolUsePromptTokenCount ?? 0);
1496
+ // Output is reported only when the candidates count is: a thoughts count
1497
+ // alone is a fragment of the output, and recording it as the whole
1498
+ // output would price the missing candidate tokens at $0.
1499
+ if (meta.candidatesTokenCount !== undefined)
1500
+ usage.outputTokens = meta.candidatesTokenCount + (meta.thoughtsTokenCount ?? 0);
1501
+ // Cached content is a subset of the prompt count, which is the
1502
+ // `ModelUsage` convention already.
1503
+ if (meta.cachedContentTokenCount !== undefined)
1504
+ usage.cachedInputTokens = meta.cachedContentTokenCount;
1505
+ if (meta.totalTokenCount !== undefined)
1506
+ usage.totalTokens = meta.totalTokenCount;
1176
1507
  result.usage = usage;
1177
1508
  }
1178
1509
  return result;
@@ -1205,7 +1536,7 @@ function toBedrockRequest(request) {
1205
1536
  };
1206
1537
  return {
1207
1538
  role: message.role === "assistant" ? "assistant" : "user",
1208
- content: [{ text: message.content }],
1539
+ content: [{ text: textWithAttachmentPlaceholders(message, "bedrock-converse") }],
1209
1540
  };
1210
1541
  });
1211
1542
  return {
@@ -1242,15 +1573,24 @@ function bedrockResponseToModelResponse(json) {
1242
1573
  ...(texts.length ? { message: { role: "assistant", content: texts.join("\n") } } : {}),
1243
1574
  ...(toolCalls.length ? { toolCalls } : {}),
1244
1575
  };
1576
+ if (typeof json.stopReason === "string")
1577
+ result.stopReason = normalizeBedrockStopReason(json.stopReason);
1245
1578
  if (json.usage) {
1246
1579
  const usage = {};
1247
1580
  if (json.usage.inputTokens !== undefined)
1248
1581
  usage.inputTokens = json.usage.inputTokens;
1249
1582
  if (json.usage.outputTokens !== undefined)
1250
1583
  usage.outputTokens = json.usage.outputTokens;
1584
+ // Bedrock's total includes prompt-cache reads and writes, reported
1585
+ // outside inputTokens (as Anthropic does); reads are folded into
1586
+ // `inputTokens` below, writes stay separate.
1587
+ if (json.usage.cacheReadInputTokens !== undefined)
1588
+ usage.cachedInputTokens = json.usage.cacheReadInputTokens;
1589
+ if (json.usage.cacheWriteInputTokens !== undefined)
1590
+ usage.cacheWriteTokens = json.usage.cacheWriteInputTokens;
1251
1591
  if (json.usage.totalTokens !== undefined)
1252
1592
  usage.totalTokens = json.usage.totalTokens;
1253
- result.usage = usage;
1593
+ result.usage = foldSeparateCacheReads(usage);
1254
1594
  }
1255
1595
  return result;
1256
1596
  }
@@ -1262,7 +1602,13 @@ function toCohereMessage(message) {
1262
1602
  : message.role === "tool"
1263
1603
  ? "tool"
1264
1604
  : "user";
1265
- return { role, content: message.content };
1605
+ return { role, content: textWithAttachmentPlaceholders(message, "cohere-chat") };
1606
+ }
1607
+ /** Text-only adapters: attachments become placeholders appended to the text. */
1608
+ function textWithAttachmentPlaceholders(message, api) {
1609
+ if (!message.attachments?.length)
1610
+ return message.content;
1611
+ return partitionModelAttachments(message, { api, images: false, documents: false }).text;
1266
1612
  }
1267
1613
  function cohereResponseToModelResponse(json) {
1268
1614
  const content = json.message?.content
@@ -1270,6 +1616,8 @@ function cohereResponseToModelResponse(json) {
1270
1616
  .filter((text) => typeof text === "string")
1271
1617
  .join("\n") ?? "";
1272
1618
  const result = content ? { message: { role: "assistant", content } } : {};
1619
+ if (typeof json.finish_reason === "string")
1620
+ result.stopReason = normalizeCohereFinishReason(json.finish_reason);
1273
1621
  const billed = json.usage?.billed_units;
1274
1622
  if (billed) {
1275
1623
  const usage = {};
@@ -1277,8 +1625,10 @@ function cohereResponseToModelResponse(json) {
1277
1625
  usage.inputTokens = billed.input_tokens;
1278
1626
  if (billed.output_tokens !== undefined)
1279
1627
  usage.outputTokens = billed.output_tokens;
1280
- if (usage.inputTokens !== undefined || usage.outputTokens !== undefined)
1281
- usage.totalTokens = (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0);
1628
+ // No provider total: synthesize one only from complete counts, so a
1629
+ // missing output count is not mistaken for proof of zero output.
1630
+ if (usage.inputTokens !== undefined && usage.outputTokens !== undefined)
1631
+ usage.totalTokens = usage.inputTokens + usage.outputTokens;
1282
1632
  result.usage = usage;
1283
1633
  }
1284
1634
  return result;
@@ -1303,6 +1653,8 @@ function anthropicResponseToModelResponse(json) {
1303
1653
  ...(thinkingChunks.length > 0 ? { thinking: thinkingChunks.join("\n") } : {}),
1304
1654
  ...(toolCalls.length > 0 ? { toolCalls } : {}),
1305
1655
  };
1656
+ if (typeof json.stop_reason === "string")
1657
+ result.stopReason = normalizeAnthropicStopReason(json.stop_reason);
1306
1658
  if (json.usage) {
1307
1659
  const usage = {};
1308
1660
  if (json.usage.input_tokens !== undefined)
@@ -1313,9 +1665,7 @@ function anthropicResponseToModelResponse(json) {
1313
1665
  usage.cachedInputTokens = json.usage.cache_read_input_tokens;
1314
1666
  if (json.usage.cache_creation_input_tokens !== undefined)
1315
1667
  usage.cacheWriteTokens = json.usage.cache_creation_input_tokens;
1316
- if (usage.inputTokens !== undefined || usage.outputTokens !== undefined)
1317
- usage.totalTokens = (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0);
1318
- result.usage = usage;
1668
+ result.usage = foldSeparateCacheReads(usage);
1319
1669
  }
1320
1670
  return result;
1321
1671
  }
@@ -1412,10 +1762,68 @@ async function* decodeOpenAISSE(stream) {
1412
1762
  reader.releaseLock();
1413
1763
  }
1414
1764
  }
1765
+ /**
1766
+ * Normalize usage from a provider that reports prompt-cache reads outside its
1767
+ * input count (Anthropic, Bedrock) to the {@link ModelUsage} convention:
1768
+ * `inputTokens` includes `cachedInputTokens`, and `cacheWriteTokens` stays
1769
+ * separate. An absent input count stays absent. When the provider sent no
1770
+ * total, one is synthesized only from complete counts (input with cache reads,
1771
+ * cache writes and output), so a missing output count stays visibly missing.
1772
+ */
1773
+ function foldSeparateCacheReads(usage) {
1774
+ if (usage.inputTokens !== undefined && usage.cachedInputTokens !== undefined)
1775
+ usage.inputTokens += usage.cachedInputTokens;
1776
+ if (usage.totalTokens === undefined &&
1777
+ usage.inputTokens !== undefined &&
1778
+ usage.outputTokens !== undefined)
1779
+ usage.totalTokens = usage.inputTokens + (usage.cacheWriteTokens ?? 0) + usage.outputTokens;
1780
+ return usage;
1781
+ }
1782
+ /**
1783
+ * Price an adapter's usage from the static table, but only when the usage is
1784
+ * complete and consistent ({@link hasPriceableUsage}). A cost synthesized from
1785
+ * partial counts (a total the input and output counts do not explain, or a
1786
+ * dropped input count) would be recorded as a known, too-low cost; leaving it
1787
+ * unpriced lets the cost budget's unknown-cost policy classify the call.
1788
+ * Provider-reported `costUsd` is kept as-is.
1789
+ */
1790
+ function priceAdapterUsage(modelRef, usage) {
1791
+ if (!usage || usage.costUsd !== undefined)
1792
+ return;
1793
+ if (!hasPriceableUsage(usage))
1794
+ return;
1795
+ applyEstimatedCost(modelRef, usage);
1796
+ }
1415
1797
  /**
1416
1798
  * Decode an Anthropic-style SSE stream — Anthropic emits `event: <type>`
1417
1799
  * followed by `data: {...}` for each event. Yields `{ event, data }` pairs.
1418
1800
  */
1801
+ /**
1802
+ * Map an Anthropic mid-stream `event: error` frame to a provider error with
1803
+ * the matching HTTP status, so overloaded and server errors stay retryable
1804
+ * and invalid requests do not retry.
1805
+ */
1806
+ function anthropicStreamError(provider, model, data) {
1807
+ const error = (data.error ?? {});
1808
+ const type = typeof error.type === "string" ? error.type : "error";
1809
+ const status = ANTHROPIC_STREAM_ERROR_STATUS[type] ?? 400;
1810
+ const message = typeof error.message === "string" ? error.message : type;
1811
+ return new ProviderHttpError(`${provider} model ${model}: stream error ${type}: ${message}`, provider, status, type, JSON.stringify(data));
1812
+ }
1813
+ // HTTP statuses Anthropic documents for each error type, so a mid-stream
1814
+ // error frame classifies for retry exactly like the same error as a response.
1815
+ const ANTHROPIC_STREAM_ERROR_STATUS = {
1816
+ invalid_request_error: 400,
1817
+ authentication_error: 401,
1818
+ billing_error: 402,
1819
+ permission_error: 403,
1820
+ not_found_error: 404,
1821
+ request_too_large: 413,
1822
+ rate_limit_error: 429,
1823
+ api_error: 500,
1824
+ timeout_error: 504,
1825
+ overloaded_error: 529,
1826
+ };
1419
1827
  async function* decodeAnthropicSSE(stream) {
1420
1828
  const decoder = new TextDecoder();
1421
1829
  const reader = stream.getReader();
@@ -1460,19 +1868,23 @@ export class ProviderHttpError extends Error {
1460
1868
  provider;
1461
1869
  status;
1462
1870
  statusText;
1463
- body;
1464
1871
  /**
1465
1872
  * Wait duration extracted from a `Retry-After` response header on 429
1466
1873
  * responses. When set, the resilience wrapper waits exactly this long
1467
1874
  * instead of using exponential backoff.
1468
1875
  */
1469
1876
  retryAfterMs;
1877
+ /** Response body, with echoed attachment payloads redacted. */
1878
+ body;
1470
1879
  constructor(message, provider, status, statusText, body, retryAfterMs) {
1471
- super(message);
1880
+ // A 4xx body often quotes the rejected request, including image and PDF
1881
+ // data URLs. Neither the message nor the body may carry those bytes into
1882
+ // logs, session entries, or events.
1883
+ super(redactAttachmentPayloads(message));
1472
1884
  this.provider = provider;
1473
1885
  this.status = status;
1474
1886
  this.statusText = statusText;
1475
- this.body = body;
1887
+ this.body = redactAttachmentPayloads(body);
1476
1888
  this.name = "ProviderHttpError";
1477
1889
  if (retryAfterMs !== undefined && Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
1478
1890
  this.retryAfterMs = retryAfterMs;