@openclaw/ai 2026.11.3 → 2026.11.5-beta.2
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/README.md +11 -8
- package/dist/.source-module-urls/fe058cc430242ce2ab0dfbcbe153e240a52cf9c3072c3dc0a73e5f956b6ba49b.json +1 -0
- package/dist/anthropic-DEKgalVg.mjs +182 -0
- package/dist/{anthropic-payload-policy-C0ki72BT.d.mts → anthropic-payload-policy-CXCJ5Pmj.d.mts} +21 -4
- package/dist/{anthropic-stream-reducer-yWDb5Cct.mjs → anthropic-stream-lifecycle-DF2qVvg1.mjs} +845 -649
- package/dist/{anthropic-tool-projection-C2-d1eZ3.d.mts → anthropic-tool-projection-D5DyrL6C.d.mts} +6 -7
- package/dist/{anthropic-tool-projection-DZOKfAmL.mjs → anthropic-tool-projection-dGRfr4iT.mjs} +22 -32
- package/dist/{api-registry-gDt0faai.d.mts → api-registry-DY2MLUyg.d.mts} +2 -2
- package/dist/assistant-output-CD4kY9gu.mjs +16 -0
- package/dist/{azure-openai-responses-BvvXzZbi.mjs → azure-openai-responses-DbQV5RTx.mjs} +47 -53
- package/dist/{cloudflare-Dttf8jKq.mjs → cloudflare-BJ2_Xabx.mjs} +1 -1
- package/dist/{credential-redaction-XvsPf7Yi.d.mts → credential-redaction-DrgndwTJ.d.mts} +5 -3
- package/dist/{deferred-event-buffer-DAvyP7qA.mjs → deferred-event-buffer-tIGkTkTm.mjs} +1 -2
- package/dist/{diagnostics-v7oVEW59.mjs → diagnostics-CloVGQiK.mjs} +27 -20
- package/dist/{diagnostics-DzrF1h4J.mjs → diagnostics-o1PrVNQb.mjs} +11 -4
- package/dist/diagnostics.d.mts +6 -7
- package/dist/diagnostics.mjs +4 -4
- package/dist/{env-api-keys-Xd8dm_aV.mjs → env-api-keys-BuHc86ya.mjs} +1 -26
- package/dist/event-stream-B4ZcSvsu.d.mts +1 -0
- package/dist/{event-stream-CzpE1g_o.d.mts → event-stream-BYmtRe8-.d.mts} +1 -1
- package/dist/event-stream.d.mts +2 -2
- package/dist/event-stream.mjs +1 -2
- package/dist/expect-lbe3Hgrh.mjs +8 -0
- package/dist/{github-copilot-request-facts-F-EmvkpW.mjs → github-copilot-request-facts-BZ_EMo7X.mjs} +1 -1
- package/dist/{google-Cpi_cLKZ.mjs → google-B1g82bn4.mjs} +7 -8
- package/dist/{google-interactions-CGINbsjO.mjs → google-interactions-Ckr0Z99Z.mjs} +243 -269
- package/dist/{google-messages-DQMgG5yG.mjs → google-messages-A-9d3y5V.mjs} +52 -18
- package/dist/{google-provider-stream-BHd0cST9.mjs → google-provider-stream-CNVh4gpm.mjs} +19 -11
- package/dist/{google-shared-vtag8bj5.mjs → google-shared-WNM86ZcW.mjs} +72 -42
- package/dist/{google-vertex-eKoUnW7N.mjs → google-vertex-CXjleC6g.mjs} +3 -3
- package/dist/{google-video-slots-D8tPH8wX.mjs → google-video-slots-Bxt-OXO8.mjs} +1 -1
- package/dist/{host-CWt55nnF.mjs → host-DX7ORpeH.mjs} +46 -39
- package/dist/{host-jJOffdlW.d.mts → host-ccbwPC3A.d.mts} +17 -9
- package/dist/{host-policy-Dm7PM6AD.mjs → host-policy-jCZebuXx.mjs} +2 -2
- package/dist/index-Bczt0MnO.d.mts +17 -0
- package/dist/index.d.mts +8 -7
- package/dist/index.mjs +9 -7
- package/dist/internal/anthropic.d.mts +21 -26
- package/dist/internal/anthropic.mjs +6 -6
- package/dist/internal/google-model-family.mjs +1 -1
- package/dist/internal/google.d.mts +15 -0
- package/dist/internal/google.mjs +1 -0
- package/dist/internal/model-request-body.d.mts +37 -0
- package/dist/internal/model-request-body.mjs +106 -0
- package/dist/internal/openai-completions-compat.d.mts +1 -1
- package/dist/internal/openai-completions-compat.mjs +1 -1
- package/dist/internal/openai-responses-payload-policy.d.mts +2 -2
- package/dist/internal/openai-responses-payload-policy.mjs +2 -2
- package/dist/internal/openai.d.mts +14 -12
- package/dist/internal/openai.mjs +11 -10
- package/dist/internal/reasoning-tag-text-partitioner.d.mts +26 -0
- package/dist/{reasoning-tag-text-partitioner-CU9A4Lg8.mjs → internal/reasoning-tag-text-partitioner.mjs} +313 -111
- package/dist/internal/retry-after.d.mts +2 -2
- package/dist/internal/retry-after.mjs +96 -32
- package/dist/internal/runtime.d.mts +15 -41
- package/dist/internal/runtime.mjs +9 -10
- package/dist/internal/shared.d.mts +21 -25
- package/dist/internal/shared.mjs +9 -98
- package/dist/internal/tool-schema.d.mts +10 -10
- package/dist/internal/tool-schema.mjs +4 -4
- package/dist/{llm-request-activity-CfMuh5cC.mjs → llm-request-activity-DzaHoRAU.mjs} +2 -2
- package/dist/mistral-CjHkvsqR.mjs +3741 -0
- package/dist/{openai.LICENSE → mistral.LICENSE} +1 -1
- package/dist/{model-transport-url-BrsjjdjR.d.mts → model-transport-url-BdksnBqu.d.mts} +6 -8
- package/dist/{number-coercion-37gmNkuA.mjs → number-coercion-C7HsBgUL.mjs} +7 -2
- package/dist/observe-async-iterator-AlARO5wS.d.mts +178 -0
- package/dist/observe-async-iterator-DgmegcZR.mjs +181 -0
- package/dist/{openai-chatgpt-responses-BZa3SySh.mjs → openai-chatgpt-responses-CwS5JP7A.mjs} +61 -80
- package/dist/{openai-completions-compat-CBvb2eld.d.mts → openai-completions-compat-CJ-NsDzg.d.mts} +12 -6
- package/dist/{openai-completions-compat-bNQXF1y9.mjs → openai-completions-compat-CstlTQuF.mjs} +74 -50
- package/dist/{openai-completions-CCZ_UHCk.mjs → openai-completions-sj4S-RXQ.mjs} +5 -5
- package/dist/openai-completions-transport-BDAIA0_P.mjs +3406 -0
- package/dist/{openai-prompt-cache-DgjD-UL5.d.mts → openai-prompt-cache-BZGaIWYh.d.mts} +4 -4
- package/dist/{openai-prompt-cache-B9AvdoEo.mjs → openai-prompt-cache-CgDoFhO0.mjs} +5 -4
- package/dist/{openai-responses-compaction-replay-_sUXtcwU.d.mts → openai-responses-compaction-replay-CNHk6k53.d.mts} +4 -4
- package/dist/{openai-responses-contracts-B1nkeLL6.d.mts → openai-responses-contracts-BXMcvO7F.d.mts} +4 -10
- package/dist/{openai-responses-contracts-B5mGAbR6.mjs → openai-responses-contracts-xU-n9AJJ.mjs} +36 -37
- package/dist/{openai-responses-endpoint-CfKR6N5f.mjs → openai-responses-endpoint-DCkURKS0.mjs} +55 -8
- package/dist/openai-responses-ev_c6oTy.mjs +89 -0
- package/dist/{openai-responses-payload-policy-BzM52TTH.d.mts → openai-responses-payload-policy-DyE30gdD.d.mts} +7 -7
- package/dist/{openai-responses-request-lifecycle-CTqHc02t.mjs → openai-responses-request-lifecycle-BuOs0mwI.mjs} +12 -26
- package/dist/{openai-responses-shared-wx9v1MCn.mjs → openai-responses-shared-BmRQnUPP.mjs} +633 -1493
- package/dist/{openai-responses-terminal-usage-CpVjkqn-.d.mts → openai-responses-terminal-usage-D7IhRA6i.d.mts} +9 -3
- package/dist/{openai-tool-schema-BTEU2xmN.mjs → openai-tool-schema-CsoYgnWy.mjs} +97 -122
- package/dist/otel-Buswj0Mf.mjs +766 -0
- package/dist/{overflow-OF3PgPbw.mjs → overflow-CpApyjG2.mjs} +1 -1
- package/dist/{positive-integer-Bb4Evc7L.mjs → positive-integer-DiqE5vNi.mjs} +2 -3
- package/dist/{prompt-cache-stability-D_MeCQFI.mjs → prompt-cache-stability-w-ICeyOI.mjs} +1 -1
- package/dist/{provider-error-qtZD2inE.mjs → provider-error-DD-fo4Rz.mjs} +71 -234
- package/dist/{provider-options-DAzsyi49.d.mts → provider-options-Mo8NM5d1.d.mts} +16 -5
- package/dist/{provider-replay-context-4vxI7p4V.mjs → provider-replay-context-xyU7-CiT.mjs} +2 -2
- package/dist/provider-transcript-transform-DtaxNcC1.mjs +32 -0
- package/dist/{provider-transport-turn-state-D_GjPJHe.mjs → provider-transport-turn-state-BIS8maBK.mjs} +4 -4
- package/dist/{provider-types-CWl4VXvE.d.mts → provider-types-B1e98js5.d.mts} +3 -3
- package/dist/provider-types.d.mts +7 -6
- package/dist/providers.d.mts +2 -2
- package/dist/providers.mjs +26 -29
- package/dist/{record-coerce-CNDovvft.mjs → record-coerce-BQaoiN3r.mjs} +4 -1
- package/dist/request-headers-DO4Mqhw1.mjs +10 -0
- package/dist/{required-api-key-D088S4Cd.mjs → required-api-key-2zZTkmsi.mjs} +1 -1
- package/dist/{retry-after-BrmTv0jL.d.mts → retry-after-DnHBlFS2.d.mts} +21 -1
- package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
- package/dist/{sanitize-unicode-ZqVLLEKC.d.mts → sanitize-unicode-BISmUlUv.d.mts} +2 -2
- package/dist/{simple-options-xJkqrG_E.mjs → simple-options-tLSeECry.mjs} +108 -82
- package/dist/src-BUsVkrNt.mjs +105 -0
- package/dist/{src-CyA0zJnt.mjs → src-CQ7nH2mL.mjs} +4 -7
- package/dist/stable-stringify-CchQEmeA.mjs +84 -0
- package/dist/{stream-C4YDqhFj.mjs → stream-DrtAWu7c.mjs} +2 -6
- package/dist/{stream-first-event-timeout-D_TfJHRJ.mjs → stream-first-event-timeout-B7RcufAV.mjs} +16 -13
- package/dist/{string-coerce-Cj8sqWHx.mjs → string-coerce-BCuWMIrk.mjs} +1 -1
- package/dist/string-normalization-B8TDDBX_.mjs +32 -0
- package/dist/telemetry-CvK1yQg7.mjs +582 -0
- package/dist/{tool-schema-json-projection-B1sTYwfH.mjs → tool-schema-json-projection-BQpiJlXJ.mjs} +53 -69
- package/dist/{transport-stream-shared-lhgkTOz3.mjs → transport-stream-shared-D2uFMhMc.mjs} +177 -93
- package/dist/{transport-stream-shared-8ru8eX4s.d.mts → transport-stream-shared-D3IAU4jn.d.mts} +29 -15
- package/dist/{transport-utils-DwOpuTjL.mjs → transport-utils-Da_39MYi.mjs} +23 -38
- package/dist/transports.d.mts +42 -39
- package/dist/transports.mjs +215 -296
- package/dist/{types-CVYzKrMl.d.mts → types-BVdTf0YV.d.mts} +38 -3
- package/dist/types-Cb3-5WM9.d.mts +1 -0
- package/dist/{types-BXd0kI8-.mjs → types-OVEWUaDh.mjs} +3 -1
- package/dist/types.d.mts +7 -6
- package/dist/types.mjs +7 -5
- package/dist/{validation-9FSkE8T-.mjs → validation-DGXqfvkj.mjs} +45 -27
- package/dist/{validation-BQ5u20Ru.d.mts → validation-QmyD0E5A.d.mts} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -2
- package/package.json +40 -6
- package/dist/anthropic-lueA8LUg.mjs +0 -221
- package/dist/assistant-output-BnQm3fov.mjs +0 -47
- package/dist/event-stream-CDpFza-M.d.mts +0 -1
- package/dist/index-DSprYWaz.d.mts +0 -185
- package/dist/mistral-CQ7aoWg2.mjs +0 -512
- package/dist/model-request-body-BD5vy4rP.d.mts +0 -17
- package/dist/openai-CiRi-nVE.mjs +0 -20077
- package/dist/openai-completions-transport-DFvSBbUT.mjs +0 -10881
- package/dist/openai-responses-DQsZKUoI.mjs +0 -87
- package/dist/rolldown-runtime-B4iAMlE-.mjs +0 -35
- package/dist/types-CBJthzJX.d.mts +0 -1
- package/dist/ws.LICENSE +0 -20
package/dist/{anthropic-stream-reducer-yWDb5Cct.mjs → anthropic-stream-lifecycle-DF2qVvg1.mjs}
RENAMED
|
@@ -1,29 +1,33 @@
|
|
|
1
|
-
import { E as supportsClaudeInHistorySystemMessages, O as supportsClaudeNativeXhighEffort, S as resolveClaudeSonnet5ModelIdentity, b as resolveClaudeOpus5ModelIdentity, d as requiresClaudeBetweenToolsThinking, g as resolveClaudeModelIdentity, h as resolveClaudeHaiku55ModelIdentity, k as supportsClaudeServerCompaction, m as resolveClaudeFable5ModelIdentity, u as bindsClaudeThinkingPrefix, w as supportsClaudeAdaptiveThinking, x as resolveClaudeSonnet55ModelIdentity, y as resolveClaudeOpus55ModelIdentity } from "./src-
|
|
2
|
-
import {
|
|
1
|
+
import { E as supportsClaudeInHistorySystemMessages, O as supportsClaudeNativeXhighEffort, S as resolveClaudeSonnet5ModelIdentity, b as resolveClaudeOpus5ModelIdentity, d as requiresClaudeBetweenToolsThinking, g as resolveClaudeModelIdentity, h as resolveClaudeHaiku55ModelIdentity, k as supportsClaudeServerCompaction, m as resolveClaudeFable5ModelIdentity, u as bindsClaudeThinkingPrefix, w as supportsClaudeAdaptiveThinking, x as resolveClaudeSonnet55ModelIdentity, y as resolveClaudeOpus55ModelIdentity } from "./src-CQ7nH2mL.mjs";
|
|
2
|
+
import { p as hasRuntimeContextMarker } from "./types-OVEWUaDh.mjs";
|
|
3
3
|
import { r as appendAssistantThinking } from "./event-stream-X2gmsUWv.mjs";
|
|
4
|
-
import { a as asRecord,
|
|
5
|
-
import { a as normalizeOptionalLowercaseString, i as normalizeNullableString } from "./string-coerce-
|
|
6
|
-
import { n as asNonNegativeFiniteNumber } from "./number-coercion-
|
|
7
|
-
import { N as isImageWithMediaPayload, O as calculateCost, S as
|
|
8
|
-
import "./transport-utils-
|
|
4
|
+
import { a as asRecord, c as readStringField, o as isRecord, r as asOptionalObjectRecord } from "./record-coerce-BQaoiN3r.mjs";
|
|
5
|
+
import { a as normalizeOptionalLowercaseString, i as normalizeNullableString } from "./string-coerce-BCuWMIrk.mjs";
|
|
6
|
+
import { n as asNonNegativeFiniteNumber } from "./number-coercion-C7HsBgUL.mjs";
|
|
7
|
+
import { C as resolveAnthropicThinkingEffort, N as isImageWithMediaPayload, O as calculateCost, S as requiresClaudeAdaptiveThinking, T as usesClaudeStreamingRefusalContract, g as applyClaudeRequestContract, h as ANTHROPIC_CLAUDE_CODE_VERSION, r as getAiTransportHost, u as STREAM_ERROR_FALLBACK_TEXT, v as defaultsClaudeAdaptiveThinking, w as usesClaudeFable5MessagesContract, y as mapAnthropicStopReason } from "./host-DX7ORpeH.mjs";
|
|
8
|
+
import "./transport-utils-Da_39MYi.mjs";
|
|
9
9
|
import { n as estimateBase64DecodedBytes } from "./base64-C8CdcsjU.mjs";
|
|
10
|
-
import { a as resolveProviderRequestCapabilities, i as resolveProviderEndpoint } from "./host-policy-
|
|
11
|
-
import { i as resolveCacheRetention } from "./cloudflare-
|
|
10
|
+
import { a as resolveProviderRequestCapabilities, i as resolveProviderEndpoint } from "./host-policy-jCZebuXx.mjs";
|
|
11
|
+
import { i as resolveCacheRetention } from "./cloudflare-BJ2_Xabx.mjs";
|
|
12
12
|
import { t as sanitizeSurrogates } from "./sanitize-unicode-CRGuMONI.mjs";
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import { t as parsePositiveInteger } from "./positive-integer-
|
|
16
|
-
import { n as
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import { t as
|
|
13
|
+
import { C as stripSystemPromptCacheBoundary, a as describeToolResultMediaPlaceholder, c as extractToolResultText, f as preparedRequestSuffix, s as extractToolResultBlockText, t as adjustMaxTokensForThinking, w as stripSystemPromptRelocatableBoundary, x as splitSystemPromptCacheBoundary } from "./simple-options-tLSeECry.mjs";
|
|
14
|
+
import { A as parseStreamingJson, O as createToolArgumentPreviewSchedule, c as failTransportStream, d as iterateModelStream, h as notifyProviderHttpResponse, i as copyProviderAcceptanceObserver, l as finalizeTerminalToolCallArguments, r as coerceTransportToolCallArguments, u as finalizeTransportStream, w as parseJsonObjectPreservingUnsafeIntegers, x as transportAbortError, y as sanitizeTransportPayloadText } from "./transport-stream-shared-D2uFMhMc.mjs";
|
|
15
|
+
import { t as parsePositiveInteger } from "./positive-integer-DiqE5vNi.mjs";
|
|
16
|
+
import { a as reconcileAnthropicToolChoice, i as projectAnthropicTools, n as normalizeAnthropicToolChoice, o as resolveOriginalAnthropicToolName, s as toClaudeCodeToolName, t as normalizeAnthropicToolCallId } from "./anthropic-tool-projection-dGRfr4iT.mjs";
|
|
17
|
+
import { t as createDeferredEventBuffer } from "./deferred-event-buffer-tIGkTkTm.mjs";
|
|
18
|
+
import { t as notifyLlmRequestActivity } from "./llm-request-activity-DzaHoRAU.mjs";
|
|
19
|
+
import { n as isProviderReplayContext, r as providerReplayContextMatches, t as buildProviderReplayContext } from "./provider-replay-context-xyU7-CiT.mjs";
|
|
20
|
+
import { t as transformProviderMessages } from "./provider-transcript-transform-DtaxNcC1.mjs";
|
|
21
|
+
import { markEncodedModelRequestBody } from "./internal/model-request-body.mjs";
|
|
22
|
+
import { t as createAssistantOutput } from "./assistant-output-CD4kY9gu.mjs";
|
|
23
|
+
import { isProxy } from "node:util/types";
|
|
20
24
|
//#region packages/ai/src/providers/anthropic-auth-headers.ts
|
|
21
25
|
/** Inspect resolved credential shape for auth routing without exposing its value. */
|
|
22
26
|
function isAnthropicOAuthApiKey(apiKey) {
|
|
23
27
|
return typeof apiKey === "string" && getAiTransportHost().resolveSecretSentinel(apiKey).includes("sk-ant-oat");
|
|
24
28
|
}
|
|
25
29
|
function usesFoundryBearerAuth(model) {
|
|
26
|
-
return model.provider === "microsoft-foundry" && (model.authHeader === true || Object.entries(model.headers ?? {}).some(([key, value]) => key.toLowerCase() === "authorization" && /^bearer\s+\S+/i.test(value.trim())));
|
|
30
|
+
return model.provider === "microsoft-foundry" && (model.authHeader === true || Object.entries(model.headers ?? {}).some(([key, value]) => key.toLowerCase() === "authorization" && value !== null && /^bearer\s+\S+/i.test(value.trim())));
|
|
27
31
|
}
|
|
28
32
|
function omitFoundryBearerCredentialHeaders(headers) {
|
|
29
33
|
if (!headers) return;
|
|
@@ -211,7 +215,44 @@ function applyAnthropicRequestCacheControl(payload, cacheControl, supportsCacheC
|
|
|
211
215
|
if (isRecord(lastTool)) lastTool.cache_control = cacheControl;
|
|
212
216
|
}
|
|
213
217
|
const usedMarkers = countAnthropicCacheControlMarkers(payload.system) + countAnthropicCacheControlMarkers(payload.tools);
|
|
214
|
-
|
|
218
|
+
const messages = payload.messages;
|
|
219
|
+
const markerLimit = ANTHROPIC_CACHE_CONTROL_LIMIT - usedMarkers;
|
|
220
|
+
if (!Array.isArray(messages) || messages.length === 0 || markerLimit <= 0) return;
|
|
221
|
+
let stableEnd = messages.length;
|
|
222
|
+
for (const index of cacheBreakpointOptOutMessageIndexes) stableEnd = Math.min(stableEnd, index);
|
|
223
|
+
let marked = 0;
|
|
224
|
+
for (let i = stableEnd - 1; i >= 0 && marked < Math.min(markerLimit, 2); i--) {
|
|
225
|
+
const record = messages[i];
|
|
226
|
+
if (!isRecord(record) || record.role !== "user") continue;
|
|
227
|
+
const content = record.content;
|
|
228
|
+
const blocks = typeof content === "string" ? [{
|
|
229
|
+
type: "text",
|
|
230
|
+
text: content
|
|
231
|
+
}] : content;
|
|
232
|
+
if (!Array.isArray(blocks)) continue;
|
|
233
|
+
for (let j = blocks.length - 1; j >= 0; j--) {
|
|
234
|
+
const blockRecord = blocks[j];
|
|
235
|
+
if (!isRecord(blockRecord)) continue;
|
|
236
|
+
if (blockRecord.type === "text" || blockRecord.type === "image" || blockRecord.type === "tool_result") {
|
|
237
|
+
if (Object.isFrozen(record) || Object.isFrozen(blocks) || Object.isFrozen(blockRecord)) {
|
|
238
|
+
const markedBlocks = blocks.slice();
|
|
239
|
+
markedBlocks[j] = {
|
|
240
|
+
...blockRecord,
|
|
241
|
+
cache_control: cacheControl
|
|
242
|
+
};
|
|
243
|
+
messages[i] = {
|
|
244
|
+
...record,
|
|
245
|
+
content: markedBlocks
|
|
246
|
+
};
|
|
247
|
+
} else {
|
|
248
|
+
blockRecord.cache_control = cacheControl;
|
|
249
|
+
if (typeof content === "string") record.content = blocks;
|
|
250
|
+
}
|
|
251
|
+
marked++;
|
|
252
|
+
break;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
215
256
|
}
|
|
216
257
|
function normalizeAnthropicSystemBlocks(system, cacheControl) {
|
|
217
258
|
if (!Array.isArray(system)) return;
|
|
@@ -252,33 +293,6 @@ function normalizeAnthropicSystemBlocks(system, cacheControl) {
|
|
|
252
293
|
}
|
|
253
294
|
if (cacheControl) system.splice(0, system.length, ...normalizedBlocks);
|
|
254
295
|
}
|
|
255
|
-
/** Apply one shared deepest-stable-message cache breakpoint policy. */
|
|
256
|
-
function applyAnthropicCacheControlToMessages(messages, cacheControl, markerLimit, cacheBreakpointOptOutMessageIndexes) {
|
|
257
|
-
if (!Array.isArray(messages) || messages.length === 0 || markerLimit <= 0) return;
|
|
258
|
-
let stableEnd = messages.length;
|
|
259
|
-
for (const index of cacheBreakpointOptOutMessageIndexes) stableEnd = Math.min(stableEnd, index);
|
|
260
|
-
let marked = 0;
|
|
261
|
-
for (let i = stableEnd - 1; i >= 0 && marked < Math.min(markerLimit, 2); i--) {
|
|
262
|
-
const record = messages[i];
|
|
263
|
-
if (!isRecord(record) || record.role !== "user") continue;
|
|
264
|
-
const content = record.content;
|
|
265
|
-
const blocks = typeof content === "string" ? [{
|
|
266
|
-
type: "text",
|
|
267
|
-
text: content
|
|
268
|
-
}] : content;
|
|
269
|
-
if (!Array.isArray(blocks)) continue;
|
|
270
|
-
for (let j = blocks.length - 1; j >= 0; j--) {
|
|
271
|
-
const blockRecord = blocks[j];
|
|
272
|
-
if (!isRecord(blockRecord)) continue;
|
|
273
|
-
if (blockRecord.type === "text" || blockRecord.type === "image" || blockRecord.type === "tool_result") {
|
|
274
|
-
blockRecord.cache_control = cacheControl;
|
|
275
|
-
if (typeof content === "string") record.content = blocks;
|
|
276
|
-
marked++;
|
|
277
|
-
break;
|
|
278
|
-
}
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
296
|
function countAnthropicCacheControlMarkers(blocks) {
|
|
283
297
|
if (!Array.isArray(blocks)) return 0;
|
|
284
298
|
let count = 0;
|
|
@@ -430,6 +444,211 @@ function applyAnthropicEphemeralCacheControlMarkers(payloadObj, cacheControl = {
|
|
|
430
444
|
}
|
|
431
445
|
}
|
|
432
446
|
//#endregion
|
|
447
|
+
//#region packages/ai/src/providers/anthropic-refusal.ts
|
|
448
|
+
function applyAnthropicRefusal(output, stopDetails, provider) {
|
|
449
|
+
const record = asOptionalObjectRecord(stopDetails);
|
|
450
|
+
const details = {
|
|
451
|
+
category: normalizeNullableString(record?.category),
|
|
452
|
+
explanation: normalizeNullableString(record?.explanation)
|
|
453
|
+
};
|
|
454
|
+
const category = details.category ? ` (category: ${details.category})` : "";
|
|
455
|
+
const explanation = details.explanation ? `: ${details.explanation}` : ".";
|
|
456
|
+
output.stopReason = "error";
|
|
457
|
+
output.errorMessage = `Anthropic refusal${category}${explanation}`;
|
|
458
|
+
output.diagnostics = [...output.diagnostics ?? [], {
|
|
459
|
+
type: "provider_refusal",
|
|
460
|
+
timestamp: Date.now(),
|
|
461
|
+
details: {
|
|
462
|
+
provider,
|
|
463
|
+
category: details.category,
|
|
464
|
+
explanation: details.explanation
|
|
465
|
+
}
|
|
466
|
+
}];
|
|
467
|
+
}
|
|
468
|
+
//#endregion
|
|
469
|
+
//#region packages/ai/src/providers/anthropic-thinking-replay.ts
|
|
470
|
+
const ANTHROPIC_OMITTED_REASONING_TEXT = "[assistant reasoning omitted]";
|
|
471
|
+
function applyAnthropicThinkingBindingControls(params, directApiKeyBetaHeader) {
|
|
472
|
+
if (directApiKeyBetaHeader === void 0 || !isRecord(params.thinking) || params.thinking.type !== "adaptive") return;
|
|
473
|
+
params.thinking.block_binding = { prefix_mismatch_behavior: "drop_block" };
|
|
474
|
+
const betas = directApiKeyBetaHeader.split(",").map((beta) => beta.trim()).filter(Boolean);
|
|
475
|
+
return { "anthropic-beta": [.../* @__PURE__ */ new Set([...betas, "thinking-binding-controls-2026-08-01"])].join(",") };
|
|
476
|
+
}
|
|
477
|
+
function readAnthropicInputTransformations(event) {
|
|
478
|
+
if (!isRecord(event) || event.type !== "message_start" && event.type !== "message_delta") return;
|
|
479
|
+
const transformations = (isRecord(event.message) ? event.message : void 0)?.input_transformations ?? event.input_transformations;
|
|
480
|
+
return Array.isArray(transformations) ? transformations : void 0;
|
|
481
|
+
}
|
|
482
|
+
function logAnthropicThinkingDrops(transformations) {
|
|
483
|
+
const drops = transformations?.filter((entry) => isRecord(entry) && entry.type === "thinking_dropped" && typeof entry.reason === "string" && /^(?:prefix|model|organization|end_user)_binding_mismatch$/.test(entry.reason) && typeof entry.path === "string" && /^messages\.\d{1,10}\.content\.\d{1,10}$/.test(entry.path));
|
|
484
|
+
if (!drops?.length) return;
|
|
485
|
+
const paths = drops.slice(0, 5).map(({ reason, path }) => `${reason} at ${path}`);
|
|
486
|
+
getAiTransportHost().logWarn("anthropic", `replayed thinking dropped: ${drops.length} block(s) (${paths.join(", ")}${drops.length > 5 ? ", …" : ""})`);
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Anthropic tool results continue the preceding assistant turn. Preserve that
|
|
490
|
+
* turn's signed thinking even when the next request disables new thinking.
|
|
491
|
+
*/
|
|
492
|
+
function findActiveAnthropicToolTurnAssistantIndex(messages) {
|
|
493
|
+
const toolResultIds = /* @__PURE__ */ new Set();
|
|
494
|
+
let index = messages.length - 1;
|
|
495
|
+
while (index >= 0) {
|
|
496
|
+
const message = asOptionalObjectRecord(messages[index]);
|
|
497
|
+
if (message?.role === "user" && isRecord(message.operatorMessage)) {
|
|
498
|
+
index -= 1;
|
|
499
|
+
continue;
|
|
500
|
+
}
|
|
501
|
+
if (message?.role !== "toolResult") break;
|
|
502
|
+
if (typeof message.toolCallId === "string") toolResultIds.add(message.toolCallId);
|
|
503
|
+
index -= 1;
|
|
504
|
+
}
|
|
505
|
+
if (toolResultIds.size === 0) return -1;
|
|
506
|
+
const assistant = asOptionalObjectRecord(messages[index]);
|
|
507
|
+
if (assistant?.role !== "assistant" || !Array.isArray(assistant.content)) return -1;
|
|
508
|
+
const toolCallIds = /* @__PURE__ */ new Set();
|
|
509
|
+
for (const block of assistant.content) {
|
|
510
|
+
const record = asOptionalObjectRecord(block);
|
|
511
|
+
if (!record) continue;
|
|
512
|
+
if ((record.type === "toolCall" || record.type === "tool_use" || record.type === "function_call") && typeof record.id === "string") toolCallIds.add(record.id);
|
|
513
|
+
}
|
|
514
|
+
return [...toolResultIds].every((toolCallId) => toolCallIds.has(toolCallId)) ? index : -1;
|
|
515
|
+
}
|
|
516
|
+
//#endregion
|
|
517
|
+
//#region packages/ai/src/providers/anthropic-usage.ts
|
|
518
|
+
const BILLED_USAGE_KEYS = [
|
|
519
|
+
"input",
|
|
520
|
+
"output",
|
|
521
|
+
"cacheRead",
|
|
522
|
+
"cacheWrite",
|
|
523
|
+
"cacheWrite1h",
|
|
524
|
+
"cacheWrite5m"
|
|
525
|
+
];
|
|
526
|
+
function readAnthropicBilledUsage(usage, missingCacheTokens) {
|
|
527
|
+
return {
|
|
528
|
+
input: readAnthropicUsageTokenCount(usage.input_tokens),
|
|
529
|
+
output: readAnthropicUsageTokenCount(usage.output_tokens),
|
|
530
|
+
cacheRead: readAnthropicUsageTokenCount(usage.cache_read_input_tokens ?? missingCacheTokens),
|
|
531
|
+
cacheWrite: readAnthropicUsageTokenCount(usage.cache_creation_input_tokens ?? missingCacheTokens),
|
|
532
|
+
...readAnthropicCacheWriteUsage(usage)
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
function applyAnthropicBilledUsage(target, resolved) {
|
|
536
|
+
for (const key of BILLED_USAGE_KEYS) {
|
|
537
|
+
const value = resolved[key];
|
|
538
|
+
if (value !== void 0) target[key] = value;
|
|
539
|
+
}
|
|
540
|
+
target.totalTokens = target.input + target.output + target.cacheRead + target.cacheWrite;
|
|
541
|
+
}
|
|
542
|
+
function readAnthropicIterationUsage(value) {
|
|
543
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return;
|
|
544
|
+
const { input, output, cacheRead, cacheWrite, cacheWrite1h, cacheWrite5m } = readAnthropicBilledUsage(value);
|
|
545
|
+
if (input === void 0 || output === void 0 || cacheRead === void 0 || cacheWrite === void 0) return;
|
|
546
|
+
return {
|
|
547
|
+
input,
|
|
548
|
+
output,
|
|
549
|
+
cacheRead,
|
|
550
|
+
cacheWrite,
|
|
551
|
+
cacheWrite1h,
|
|
552
|
+
cacheWrite5m
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
function readAnthropicUsageTokenCount(value) {
|
|
556
|
+
return asNonNegativeFiniteNumber(value);
|
|
557
|
+
}
|
|
558
|
+
function readAnthropicCacheWriteUsage(usage) {
|
|
559
|
+
if (!usage.cache_creation || typeof usage.cache_creation !== "object") return {};
|
|
560
|
+
const cacheCreation = usage.cache_creation;
|
|
561
|
+
const cacheWrite5m = readAnthropicUsageTokenCount(cacheCreation.ephemeral_5m_input_tokens);
|
|
562
|
+
const cacheWrite1h = readAnthropicUsageTokenCount(cacheCreation.ephemeral_1h_input_tokens);
|
|
563
|
+
return {
|
|
564
|
+
...cacheWrite5m !== void 0 ? { cacheWrite5m } : {},
|
|
565
|
+
...cacheWrite1h !== void 0 ? { cacheWrite1h } : {}
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
function readAnthropicPromptUsageSnapshot(usage) {
|
|
569
|
+
const input = readAnthropicUsageTokenCount(usage.input_tokens);
|
|
570
|
+
const cacheRead = usage.cache_read_input_tokens == null ? 0 : readAnthropicUsageTokenCount(usage.cache_read_input_tokens);
|
|
571
|
+
const cacheWrite = usage.cache_creation_input_tokens == null ? 0 : readAnthropicUsageTokenCount(usage.cache_creation_input_tokens);
|
|
572
|
+
if (input === void 0 || cacheRead === void 0 || cacheWrite === void 0) return;
|
|
573
|
+
return {
|
|
574
|
+
input,
|
|
575
|
+
cacheRead,
|
|
576
|
+
cacheWrite
|
|
577
|
+
};
|
|
578
|
+
}
|
|
579
|
+
function readLastAnthropicIterationUsage(usage) {
|
|
580
|
+
if (usage.iterations == null) return { state: "absent" };
|
|
581
|
+
if (!Array.isArray(usage.iterations) || usage.iterations.length === 0) return { state: "invalid" };
|
|
582
|
+
const iteration = readAnthropicIterationUsage(usage.iterations.at(-1));
|
|
583
|
+
if (!iteration) return { state: "invalid" };
|
|
584
|
+
const contextPromptTokens = iteration.input + iteration.cacheRead + iteration.cacheWrite;
|
|
585
|
+
return {
|
|
586
|
+
state: "valid",
|
|
587
|
+
usage: {
|
|
588
|
+
contextPromptTokens,
|
|
589
|
+
totalTokens: contextPromptTokens + iteration.output
|
|
590
|
+
}
|
|
591
|
+
};
|
|
592
|
+
}
|
|
593
|
+
function readAnthropicCompactionBilledUsage(iterations) {
|
|
594
|
+
if (!Array.isArray(iterations) || iterations.length === 0) return;
|
|
595
|
+
let sawCompaction = false;
|
|
596
|
+
const billed = {
|
|
597
|
+
input: 0,
|
|
598
|
+
output: 0,
|
|
599
|
+
cacheRead: 0,
|
|
600
|
+
cacheWrite: 0
|
|
601
|
+
};
|
|
602
|
+
for (const iteration of iterations) {
|
|
603
|
+
const resolved = readAnthropicIterationUsage(iteration);
|
|
604
|
+
if (!resolved) return;
|
|
605
|
+
sawCompaction ||= iteration.type === "compaction";
|
|
606
|
+
for (const key of BILLED_USAGE_KEYS) {
|
|
607
|
+
const value = resolved[key];
|
|
608
|
+
if (value !== void 0) billed[key] = (billed[key] ?? 0) + value;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
return sawCompaction ? billed : void 0;
|
|
612
|
+
}
|
|
613
|
+
/** Record independent billing buckets without treating zero placeholders as context proof. */
|
|
614
|
+
function applyAnthropicMessageStartUsage(target, payload) {
|
|
615
|
+
const promptUsage = readAnthropicPromptUsageSnapshot(payload);
|
|
616
|
+
const promptTokens = promptUsage ? promptUsage.input + promptUsage.cacheRead + promptUsage.cacheWrite : 0;
|
|
617
|
+
const resolved = readAnthropicBilledUsage(payload, 0);
|
|
618
|
+
applyAnthropicBilledUsage(target, resolved);
|
|
619
|
+
if (promptTokens > 0 && resolved.output !== void 0) target.contextUsage = {
|
|
620
|
+
state: "available",
|
|
621
|
+
promptTokens,
|
|
622
|
+
totalTokens: promptTokens + target.output
|
|
623
|
+
};
|
|
624
|
+
return promptTokens > 0 ? promptUsage : void 0;
|
|
625
|
+
}
|
|
626
|
+
/** Keep billing and context distinct; omitted usage preserves the last snapshot. */
|
|
627
|
+
function applyAnthropicMessageDeltaUsage(target, usage, messageStartPromptUsage) {
|
|
628
|
+
if (!usage) return;
|
|
629
|
+
const billedIterations = readAnthropicCompactionBilledUsage(usage.iterations);
|
|
630
|
+
const reported = readAnthropicBilledUsage(usage);
|
|
631
|
+
applyAnthropicBilledUsage(target, {
|
|
632
|
+
...reported,
|
|
633
|
+
...billedIterations
|
|
634
|
+
});
|
|
635
|
+
const iterationUsage = readLastAnthropicIterationUsage(usage);
|
|
636
|
+
if (iterationUsage.state === "valid") target.contextUsage = {
|
|
637
|
+
state: "available",
|
|
638
|
+
promptTokens: iterationUsage.usage.contextPromptTokens,
|
|
639
|
+
totalTokens: iterationUsage.usage.totalTokens
|
|
640
|
+
};
|
|
641
|
+
else if (iterationUsage.state === "invalid") target.contextUsage = { state: "unavailable" };
|
|
642
|
+
else if (reported.output !== void 0 && (messageStartPromptUsage !== void 0 || (reported.cacheRead !== void 0 || reported.cacheWrite !== void 0) && readAnthropicPromptUsageSnapshot(usage) !== void 0)) {
|
|
643
|
+
const promptTokens = target.input + target.cacheRead + target.cacheWrite;
|
|
644
|
+
target.contextUsage = {
|
|
645
|
+
state: "available",
|
|
646
|
+
promptTokens,
|
|
647
|
+
totalTokens: promptTokens + target.output
|
|
648
|
+
};
|
|
649
|
+
} else target.contextUsage = { state: "unavailable" };
|
|
650
|
+
}
|
|
651
|
+
//#endregion
|
|
433
652
|
//#region packages/ai/src/transports/anthropic-compaction-replay.ts
|
|
434
653
|
const ANTHROPIC_COMPACTION_REPLAY_TYPE = "anthropic-compaction";
|
|
435
654
|
const ANTHROPIC_COMPACTION_SUPPRESSION_TYPE = "anthropic-compaction-suppression";
|
|
@@ -590,52 +809,95 @@ async function normalizeAnthropicInlineContent(content, budget) {
|
|
|
590
809
|
return normalized;
|
|
591
810
|
}
|
|
592
811
|
//#endregion
|
|
593
|
-
//#region packages/ai/src/
|
|
594
|
-
const
|
|
595
|
-
function
|
|
596
|
-
if (
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
812
|
+
//#region packages/ai/src/transports/anthropic-request-body.ts
|
|
813
|
+
const fragments = /* @__PURE__ */ new WeakMap();
|
|
814
|
+
function copyPlainData(value, retainFrozen = false, copies = /* @__PURE__ */ new Map()) {
|
|
815
|
+
if (!value || typeof value !== "object") return value;
|
|
816
|
+
if (retainFrozen && getAiTransportHost().immutableData?.isDeeplyFrozenPlainData(value)) return value;
|
|
817
|
+
if (copies.has(value)) return copies.get(value);
|
|
818
|
+
const copy = Array.isArray(value) ? [] : { ...value };
|
|
819
|
+
if (Array.isArray(value)) Reflect.set(copy, "length", value.length);
|
|
820
|
+
if (Object.getPrototypeOf(value) === null) Object.setPrototypeOf(copy, null);
|
|
821
|
+
copies.set(value, copy);
|
|
822
|
+
for (const key of Reflect.ownKeys(value)) {
|
|
823
|
+
if (Array.isArray(value) && key === "length") continue;
|
|
824
|
+
const child = copyPlainData(Reflect.get(value, key), retainFrozen, copies);
|
|
825
|
+
if (Object.hasOwn(copy, key) || key !== "__proto__" && Object.prototype.propertyIsEnumerable.call(value, key)) Reflect.set(copy, key, child);
|
|
826
|
+
else Object.defineProperty(copy, key, {
|
|
827
|
+
value: child,
|
|
828
|
+
enumerable: Object.prototype.propertyIsEnumerable.call(value, key),
|
|
829
|
+
writable: true,
|
|
830
|
+
configurable: true
|
|
831
|
+
});
|
|
832
|
+
}
|
|
833
|
+
return copy;
|
|
834
|
+
}
|
|
835
|
+
function samePlainData(left, right, seen = /* @__PURE__ */ new Map()) {
|
|
836
|
+
if (Object.is(left, right)) return true;
|
|
837
|
+
if (!left || !right || typeof left !== "object" || typeof right !== "object") return false;
|
|
838
|
+
if (isProxy(right) || Object.getPrototypeOf(left) !== Object.getPrototypeOf(right)) return false;
|
|
839
|
+
if (seen.has(left)) return seen.get(left) === right;
|
|
840
|
+
seen.set(left, right);
|
|
841
|
+
const keys = Reflect.ownKeys(left);
|
|
842
|
+
const otherKeys = Reflect.ownKeys(right);
|
|
843
|
+
if (keys.length !== otherKeys.length || Array.isArray(left) && left.length !== Reflect.get(right, "length")) return false;
|
|
844
|
+
let index = 0;
|
|
845
|
+
for (const key of keys) {
|
|
846
|
+
const descriptor = Object.getOwnPropertyDescriptor(right, key);
|
|
847
|
+
if (key !== otherKeys[index++] || descriptor === void 0 || !("value" in descriptor) || Object.prototype.propertyIsEnumerable.call(left, key) !== descriptor.enumerable || !samePlainData(Reflect.get(left, key), descriptor.value, seen)) return false;
|
|
848
|
+
}
|
|
849
|
+
return true;
|
|
850
|
+
}
|
|
851
|
+
/** Hooks receive editable containers; any edit opts the whole request out of fragment reuse. */
|
|
852
|
+
async function applyAnthropicPayloadHook(params, model, options) {
|
|
853
|
+
if (!options?.onPayload) return { params };
|
|
854
|
+
const plain = getAiTransportHost().immutableData?.isPlainData;
|
|
855
|
+
const snapshot = plain?.(params) ? copyPlainData(params, true) : void 0;
|
|
856
|
+
const editable = snapshot ? copyPlainData(params) : {
|
|
857
|
+
...params,
|
|
858
|
+
messages: params.messages.map((message) => plain?.(message) ? copyPlainData(message) : message)
|
|
859
|
+
};
|
|
860
|
+
const replacement = await options.onPayload(editable, model);
|
|
861
|
+
const unchanged = (replacement === void 0 || replacement === editable) && snapshot !== void 0 && samePlainData(snapshot, editable);
|
|
862
|
+
return {
|
|
863
|
+
params: replacement === void 0 ? editable : replacement,
|
|
864
|
+
messageSources: unchanged ? snapshot.messages : null
|
|
865
|
+
};
|
|
600
866
|
}
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
const
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
const
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
867
|
+
/** Assemble immutable history bytes while encoding the envelope and mutable tail each time. */
|
|
868
|
+
function serializeAnthropicRequestBody(payload, messageSources) {
|
|
869
|
+
const immutable = getAiTransportHost().immutableData;
|
|
870
|
+
if (messageSources === null || !immutable?.isPlainData || messageSources === void 0 && !immutable.isPlainData(payload) || "toJSON" in Object.prototype || "toJSON" in Array.prototype || !Array.isArray(payload.messages)) return JSON.stringify(payload);
|
|
871
|
+
const messages = messageSources ?? payload.messages;
|
|
872
|
+
const parts = [];
|
|
873
|
+
let envelope = "{";
|
|
874
|
+
let separator = "";
|
|
875
|
+
for (const key of Object.keys(payload)) {
|
|
876
|
+
const value = Reflect.get(payload, key);
|
|
877
|
+
if (key === "messages") {
|
|
878
|
+
parts.push(`${envelope}${separator}"messages":[`);
|
|
879
|
+
envelope = "]";
|
|
880
|
+
for (let index = 0; index < messages.length; index++) {
|
|
881
|
+
const message = messages[index];
|
|
882
|
+
const reusable = message !== null && typeof message === "object" && immutable.isDeeplyFrozenPlainData(message);
|
|
883
|
+
let fragment = reusable ? fragments.get(message) : void 0;
|
|
884
|
+
if (!fragment) {
|
|
885
|
+
fragment = new Blob(["," + JSON.stringify(message)]);
|
|
886
|
+
if (reusable) fragments.set(message, fragment);
|
|
887
|
+
}
|
|
888
|
+
parts.push(index === 0 ? fragment.slice(1) : fragment);
|
|
889
|
+
}
|
|
890
|
+
} else {
|
|
891
|
+
const json = JSON.stringify(value);
|
|
892
|
+
if (json === void 0) continue;
|
|
893
|
+
envelope += `${separator}${JSON.stringify(key)}:${json}`;
|
|
624
894
|
}
|
|
625
|
-
|
|
626
|
-
if (typeof message.toolCallId === "string") toolResultIds.add(message.toolCallId);
|
|
627
|
-
index -= 1;
|
|
628
|
-
}
|
|
629
|
-
if (toolResultIds.size === 0) return -1;
|
|
630
|
-
const assistant = asOptionalObjectRecord(messages[index]);
|
|
631
|
-
if (assistant?.role !== "assistant" || !Array.isArray(assistant.content)) return -1;
|
|
632
|
-
const toolCallIds = /* @__PURE__ */ new Set();
|
|
633
|
-
for (const block of assistant.content) {
|
|
634
|
-
const record = asOptionalObjectRecord(block);
|
|
635
|
-
if (!record) continue;
|
|
636
|
-
if ((record.type === "toolCall" || record.type === "tool_use" || record.type === "function_call") && typeof record.id === "string") toolCallIds.add(record.id);
|
|
895
|
+
separator = ",";
|
|
637
896
|
}
|
|
638
|
-
|
|
897
|
+
parts.push(`${envelope}}`);
|
|
898
|
+
const body = new Blob(parts, { type: "application/json" });
|
|
899
|
+
markEncodedModelRequestBody(body, payload.stream);
|
|
900
|
+
return body;
|
|
639
901
|
}
|
|
640
902
|
//#endregion
|
|
641
903
|
//#region packages/ai/src/transports/anthropic-transport-options.ts
|
|
@@ -674,7 +936,6 @@ function resolveAnthropicTransportOptions(model, options, apiKey) {
|
|
|
674
936
|
headers: options?.headers,
|
|
675
937
|
onPayload: options?.onPayload,
|
|
676
938
|
onResponse: options?.onResponse,
|
|
677
|
-
maxRetryDelayMs: options?.maxRetryDelayMs,
|
|
678
939
|
metadata: options?.metadata,
|
|
679
940
|
interleavedThinking: options?.interleavedThinking,
|
|
680
941
|
toolChoice: options?.toolChoice,
|
|
@@ -697,7 +958,7 @@ function applyAnthropicThinkingOptions(model, resolved, options, profile) {
|
|
|
697
958
|
resolved.thinkingEnabled = false;
|
|
698
959
|
return reasoning;
|
|
699
960
|
}
|
|
700
|
-
if (!reasoning || supportsClaudeAdaptiveThinking(model)
|
|
961
|
+
if (!reasoning || supportsClaudeAdaptiveThinking(model)) {
|
|
701
962
|
resolved.thinkingEnabled = Boolean(reasoning) || defaultsClaudeAdaptiveThinking(model);
|
|
702
963
|
if (resolved.thinkingEnabled) resolved.effort = resolveAnthropicThinkingEffort(model, reasoning);
|
|
703
964
|
return reasoning;
|
|
@@ -725,6 +986,7 @@ function resolveCompletionTokenReservation(model, maxTokens, reasoning) {
|
|
|
725
986
|
}
|
|
726
987
|
//#endregion
|
|
727
988
|
//#region packages/ai/src/transports/anthropic-messages.ts
|
|
989
|
+
const anthropicMessageProjections = /* @__PURE__ */ new WeakMap();
|
|
728
990
|
const NON_VISION_USER_IMAGE_PLACEHOLDER = "(image omitted: model does not support images)";
|
|
729
991
|
async function convertContentBlocks(content, model, imageBudget, profile, isError) {
|
|
730
992
|
const mediaPlaceholder = describeToolResultMediaPlaceholder(content);
|
|
@@ -734,18 +996,16 @@ async function convertContentBlocks(content, model, imageBudget, profile, isErro
|
|
|
734
996
|
}
|
|
735
997
|
const blocks = [];
|
|
736
998
|
for (const block of content) {
|
|
737
|
-
|
|
738
|
-
if (!record) continue;
|
|
999
|
+
if (!asOptionalObjectRecord(block)) continue;
|
|
739
1000
|
const blockText = extractToolResultBlockText(block);
|
|
740
1001
|
if (blockText) blocks.push({
|
|
741
1002
|
type: "text",
|
|
742
1003
|
text: blockText
|
|
743
1004
|
});
|
|
744
|
-
if (!isImageWithMediaPayload(
|
|
745
|
-
const [normalizedImage] = await normalizeAnthropicInlineContent([{
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
mimeType: typeof record.mimeType === "string" ? record.mimeType : profile === "provider" ? "image/jpeg" : "image/png"
|
|
1005
|
+
if (!isImageWithMediaPayload(block)) continue;
|
|
1006
|
+
const [normalizedImage] = await normalizeAnthropicInlineContent([typeof block.mimeType === "string" ? block : {
|
|
1007
|
+
...block,
|
|
1008
|
+
mimeType: profile === "provider" ? "image/jpeg" : "image/png"
|
|
749
1009
|
}], imageBudget);
|
|
750
1010
|
if (normalizedImage?.type !== "image") continue;
|
|
751
1011
|
blocks.push({
|
|
@@ -763,38 +1023,61 @@ async function convertContentBlocks(content, model, imageBudget, profile, isErro
|
|
|
763
1023
|
});
|
|
764
1024
|
return blocks;
|
|
765
1025
|
}
|
|
766
|
-
|
|
767
|
-
|
|
1026
|
+
/** Assemble both public Messages routes without changing their replay/default profiles. */
|
|
1027
|
+
async function buildAnthropicRequest(model, context, options, profile, isOAuthToken, serverSideFallback, claudeCodeVersion) {
|
|
1028
|
+
const managed = profile === "transport";
|
|
1029
|
+
const maxTokens = managed ? resolveAnthropicMessagesMaxTokens({
|
|
1030
|
+
modelContextWindow: model.contextWindow,
|
|
1031
|
+
modelMaxTokens: model.maxTokens,
|
|
1032
|
+
requestedMaxTokens: options?.maxTokens
|
|
1033
|
+
}) : options?.maxTokens ?? model.maxTokens;
|
|
1034
|
+
if (managed && maxTokens === void 0) throw new Error(`Anthropic Messages transport requires a positive maxTokens value for ${model.provider}/${model.id}`);
|
|
1035
|
+
const { cacheControl, supportsCacheControlOnTools } = resolveAnthropicCacheOptions(model, options?.cacheRetention);
|
|
1036
|
+
const system = buildAnthropicSystemBlocks(context.systemPrompt, isOAuthToken, cacheControl, claudeCodeVersion);
|
|
1037
|
+
let toolProjection;
|
|
1038
|
+
let eagerToolInputStreaming = false;
|
|
1039
|
+
if (context.tools) {
|
|
1040
|
+
const tools = context.tools;
|
|
1041
|
+
eagerToolInputStreaming = !managed && (model.compat?.supportsEagerToolInputStreaming ?? model.provider !== "fireworks");
|
|
1042
|
+
toolProjection = projectAnthropicTools(tools, (name) => isOAuthToken ? toClaudeCodeToolName(name) : name);
|
|
1043
|
+
}
|
|
1044
|
+
const replayPlan = buildAnthropicReplayPlan(context.messages, model, {
|
|
1045
|
+
enabled: !isOAuthToken && options?.anthropicServerCompaction === true,
|
|
1046
|
+
authProfileId: options?.authProfileId,
|
|
1047
|
+
sessionId: options?.sessionId
|
|
1048
|
+
});
|
|
1049
|
+
const cacheBreakpointOptOutMessageIndexes = /* @__PURE__ */ new Set();
|
|
1050
|
+
const transformed = managed ? getAiTransportHost().transformTransportMessages(replayPlan.messages, model, normalizeAnthropicToolCallId, { preserveUnframedToolResults: preparedRequestSuffix.has(context) }) : transformProviderMessages(replayPlan.messages, model, normalizeAnthropicToolCallId);
|
|
1051
|
+
const allowReasoningContentReplay = managed && resolveProviderEndpoint(model).endpointClass === "xiaomi-native";
|
|
1052
|
+
const allowEmptySignature = model.compat?.allowEmptySignature;
|
|
1053
|
+
const compaction = replayPlan.compaction;
|
|
1054
|
+
const replayThinkingEnabled = requiresClaudeAdaptiveThinking(model) || options?.thinkingEnabled === true;
|
|
1055
|
+
const messages = [];
|
|
768
1056
|
const appendMessage = (message) => {
|
|
769
|
-
if (message.role === "system" && (!
|
|
1057
|
+
if (message.role === "system" && (!messages.length || messages.at(-1)?.role === "assistant")) messages.push({
|
|
770
1058
|
role: "user",
|
|
771
1059
|
content: "."
|
|
772
1060
|
});
|
|
773
|
-
if (message.role === "user" &&
|
|
1061
|
+
if (message.role === "user" && messages.at(-1)?.role === "system") messages.push({
|
|
774
1062
|
role: "assistant",
|
|
775
1063
|
content: [{
|
|
776
1064
|
type: "text",
|
|
777
1065
|
text: STREAM_ERROR_FALLBACK_TEXT
|
|
778
1066
|
}]
|
|
779
1067
|
});
|
|
780
|
-
|
|
1068
|
+
messages.push(message);
|
|
781
1069
|
};
|
|
782
1070
|
const modelRetainsRuntimeContext = bindsClaudeThinkingPrefix(model);
|
|
783
1071
|
const inHistorySystemUpdates = !isOAuthToken && isDirectAnthropicModel(model) && supportsClaudeInHistorySystemMessages(model);
|
|
784
1072
|
const imageBudget = createAnthropicInlineImageBudget();
|
|
785
|
-
const
|
|
786
|
-
const
|
|
787
|
-
const managed = options.profile === "transport";
|
|
788
|
-
const activeToolTurnAssistantIndex = replayThinkingEnabled ? -1 : findActiveAnthropicToolTurnAssistantIndex(transformedMessages);
|
|
789
|
-
for (let i = 0; i < transformedMessages.length; i += 1) {
|
|
790
|
-
const msg = transformedMessages[i];
|
|
791
|
-
if (!msg) continue;
|
|
1073
|
+
const activeToolTurnAssistantIndex = replayThinkingEnabled ? -1 : findActiveAnthropicToolTurnAssistantIndex(transformed);
|
|
1074
|
+
const convertMessage = async (msg, i, end) => {
|
|
792
1075
|
if (msg.role === "user") {
|
|
793
1076
|
const operatorMessage = inHistorySystemUpdates ? msg.operatorMessage : void 0;
|
|
794
1077
|
const sourceContent = msg.content;
|
|
795
1078
|
let content;
|
|
796
1079
|
if (typeof sourceContent === "string") {
|
|
797
|
-
if (sourceContent.trim().length === 0)
|
|
1080
|
+
if (sourceContent.trim().length === 0) return;
|
|
798
1081
|
content = sanitizeTransportPayloadText(sourceContent);
|
|
799
1082
|
} else {
|
|
800
1083
|
content = (!managed || model.input.includes("image") ? await normalizeAnthropicInlineContent(sourceContent, imageBudget) : sourceContent.map((item) => item.type === "image" ? {
|
|
@@ -811,22 +1094,19 @@ async function convertAnthropicMessages(transformedMessages, model, isOAuthToken
|
|
|
811
1094
|
data: item.data
|
|
812
1095
|
}
|
|
813
1096
|
}).filter((block) => block.type === "text" ? block.text.trim().length > 0 : !managed || model.input.includes("image"));
|
|
814
|
-
if (content.length === 0)
|
|
1097
|
+
if (content.length === 0) return;
|
|
815
1098
|
}
|
|
816
|
-
|
|
1099
|
+
return {
|
|
817
1100
|
role: operatorMessage ? "system" : "user",
|
|
818
1101
|
content: operatorMessage ? typeof content === "string" ? [{
|
|
819
1102
|
type: "text",
|
|
820
1103
|
text: content
|
|
821
1104
|
}] : content.filter((block) => block.type === "text") : content,
|
|
822
1105
|
...operatorMessage?.turnScoped ? { clear_at: "next_user_message" } : {}
|
|
823
|
-
}
|
|
824
|
-
const runtimeContextRetained = msg.runtimeContext !== void 0 ? msg.runtimeContext.retained : msg.runtimeContextCarrierRetained;
|
|
825
|
-
if (hasRuntimeContextMarker(msg) && !(runtimeContextRetained ?? modelRetainsRuntimeContext)) options.cacheBreakpointOptOutMessageIndexes?.add(params.length - 1);
|
|
826
|
-
continue;
|
|
1106
|
+
};
|
|
827
1107
|
}
|
|
828
1108
|
if (msg.role === "assistant") {
|
|
829
|
-
const blocks = i === 0 &&
|
|
1109
|
+
const blocks = i === 0 && compaction ? [compaction] : [];
|
|
830
1110
|
const reasoningContent = [];
|
|
831
1111
|
let omittedThinking = false;
|
|
832
1112
|
for (const block of msg.content) {
|
|
@@ -854,7 +1134,7 @@ async function convertAnthropicMessages(transformedMessages, model, isOAuthToken
|
|
|
854
1134
|
}
|
|
855
1135
|
const hasNativeThinkingSignature = Boolean(thinkingSignature) && !isReasoningContent;
|
|
856
1136
|
if (block.thinking.trim().length === 0 && !hasNativeThinkingSignature) continue;
|
|
857
|
-
if (!thinkingSignature && !
|
|
1137
|
+
if (!thinkingSignature && !allowEmptySignature) blocks.push({
|
|
858
1138
|
type: "text",
|
|
859
1139
|
text: sanitizeTransportPayloadText(block.thinking)
|
|
860
1140
|
});
|
|
@@ -891,40 +1171,103 @@ async function convertAnthropicMessages(transformedMessages, model, isOAuthToken
|
|
|
891
1171
|
thinking: "",
|
|
892
1172
|
signature: "reasoning_content"
|
|
893
1173
|
});
|
|
894
|
-
|
|
1174
|
+
return assistantMsg;
|
|
895
1175
|
}
|
|
896
|
-
|
|
1176
|
+
return;
|
|
897
1177
|
}
|
|
898
1178
|
if (msg.role === "toolResult") {
|
|
899
1179
|
const toolResults = [];
|
|
900
|
-
let j = i;
|
|
901
|
-
|
|
902
|
-
const nextMsg = transformedMessages.at(j);
|
|
1180
|
+
for (let j = i; j < end; j++) {
|
|
1181
|
+
const nextMsg = transformed.at(j);
|
|
903
1182
|
if (nextMsg?.role !== "toolResult") break;
|
|
904
1183
|
toolResults.push({
|
|
905
1184
|
type: "tool_result",
|
|
906
|
-
tool_use_id: preparedRequestSuffix.has(
|
|
907
|
-
content: await convertContentBlocks(nextMsg.content, model, imageBudget,
|
|
1185
|
+
tool_use_id: preparedRequestSuffix.has(context) ? preparedRequestSuffix.toolCallId(context, nextMsg.toolCallId, normalizeAnthropicToolCallId(nextMsg.toolCallId)) : nextMsg.toolCallId,
|
|
1186
|
+
content: await convertContentBlocks(nextMsg.content, model, imageBudget, profile, nextMsg.isError),
|
|
908
1187
|
is_error: nextMsg.isError
|
|
909
1188
|
});
|
|
910
|
-
j += 1;
|
|
911
1189
|
}
|
|
912
|
-
|
|
913
|
-
appendMessage({
|
|
1190
|
+
return {
|
|
914
1191
|
role: "user",
|
|
915
1192
|
content: toolResults
|
|
916
|
-
}
|
|
1193
|
+
};
|
|
1194
|
+
}
|
|
1195
|
+
};
|
|
1196
|
+
const immutable = getAiTransportHost().immutableData;
|
|
1197
|
+
const projectionKey = JSON.stringify([
|
|
1198
|
+
profile,
|
|
1199
|
+
model.provider,
|
|
1200
|
+
model.api,
|
|
1201
|
+
model.id,
|
|
1202
|
+
model.baseUrl,
|
|
1203
|
+
model.input.includes("image"),
|
|
1204
|
+
isOAuthToken,
|
|
1205
|
+
allowReasoningContentReplay,
|
|
1206
|
+
allowEmptySignature,
|
|
1207
|
+
replayThinkingEnabled,
|
|
1208
|
+
inHistorySystemUpdates
|
|
1209
|
+
]);
|
|
1210
|
+
const activeProjectionKey = `${projectionKey}:active`;
|
|
1211
|
+
const canReuse = (message) => Boolean(immutable?.isPlainData) && immutable?.isDeeplyFrozenPlainData(message) && (typeof message.content === "string" || !message.content.some((block) => block.type === "image"));
|
|
1212
|
+
for (let i = 0; i < transformed.length;) {
|
|
1213
|
+
const msg = transformed[i];
|
|
1214
|
+
if (!msg) {
|
|
1215
|
+
i++;
|
|
1216
|
+
continue;
|
|
1217
|
+
}
|
|
1218
|
+
let end = i + 1;
|
|
1219
|
+
if (msg.role === "toolResult") while (transformed[end]?.role === "toolResult") end++;
|
|
1220
|
+
let reusable = !compaction && !preparedRequestSuffix.has(context) && canReuse(msg);
|
|
1221
|
+
for (let j = i + 1; reusable && j < end; j++) {
|
|
1222
|
+
const following = transformed[j];
|
|
1223
|
+
reusable = following !== void 0 && canReuse(following);
|
|
1224
|
+
}
|
|
1225
|
+
const key = i === activeToolTurnAssistantIndex ? activeProjectionKey : projectionKey;
|
|
1226
|
+
let projections = reusable ? anthropicMessageProjections.get(msg) : void 0;
|
|
1227
|
+
const projection = projections?.find((entry) => entry.key === key && entry.followingSources.length === end - i - 1 && entry.followingSources.every((source, index) => source === transformed[i + index + 1]));
|
|
1228
|
+
let output = projection?.message;
|
|
1229
|
+
if (!projection) {
|
|
1230
|
+
output = await convertMessage(msg, i, end);
|
|
1231
|
+
if (reusable && immutable) {
|
|
1232
|
+
immutable.freezeJsonSnapshot(output);
|
|
1233
|
+
if (!projections) {
|
|
1234
|
+
projections = [];
|
|
1235
|
+
anthropicMessageProjections.set(msg, projections);
|
|
1236
|
+
}
|
|
1237
|
+
if (projections.length >= 8) projections.shift();
|
|
1238
|
+
projections.push({
|
|
1239
|
+
key,
|
|
1240
|
+
followingSources: transformed.slice(i + 1, end),
|
|
1241
|
+
message: output
|
|
1242
|
+
});
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
if (output) {
|
|
1246
|
+
appendMessage(output);
|
|
1247
|
+
if (msg.role === "user") {
|
|
1248
|
+
const runtimeContextRetained = msg.runtimeContext !== void 0 ? msg.runtimeContext.retained : msg.runtimeContextCarrierRetained;
|
|
1249
|
+
if (hasRuntimeContextMarker(msg) && !(runtimeContextRetained ?? modelRetainsRuntimeContext)) cacheBreakpointOptOutMessageIndexes.add(messages.length - 1);
|
|
1250
|
+
}
|
|
917
1251
|
}
|
|
1252
|
+
i = end;
|
|
918
1253
|
}
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
const params = {
|
|
1254
|
+
if (managed && messages.length === 0) messages.push({
|
|
1255
|
+
role: "user",
|
|
1256
|
+
content: "."
|
|
1257
|
+
});
|
|
1258
|
+
const params = {
|
|
1259
|
+
model: managed && isDirectAnthropicModel(model) ? model.id.replace(/^anthropic\//i, "") : model.id,
|
|
1260
|
+
messages,
|
|
1261
|
+
max_tokens: maxTokens ?? model.maxTokens,
|
|
1262
|
+
stream: true
|
|
1263
|
+
};
|
|
1264
|
+
if (system) params.system = system;
|
|
1265
|
+
if (serverSideFallback) Object.assign(params, { fallbacks: ANTHROPIC_SERVER_SIDE_FALLBACKS });
|
|
1266
|
+
const generationParams = {};
|
|
924
1267
|
const mandatoryAdaptiveThinking = requiresClaudeAdaptiveThinking(model);
|
|
925
|
-
if (options?.temperature !== void 0 && !options?.thinkingEnabled && !supportsClaudeNativeXhighEffort(model))
|
|
926
|
-
if (options?.stop !== void 0 && options.stop.length > 0)
|
|
927
|
-
if (toolProjection && toolProjection.tools.length > 0)
|
|
1268
|
+
if (options?.temperature !== void 0 && !options?.thinkingEnabled && !supportsClaudeNativeXhighEffort(model)) generationParams.temperature = options.temperature;
|
|
1269
|
+
if (options?.stop !== void 0 && options.stop.length > 0) generationParams.stop_sequences = options.stop;
|
|
1270
|
+
if (toolProjection && toolProjection.tools.length > 0) generationParams.tools = toolProjection.tools.map((tool) => ({
|
|
928
1271
|
name: tool.wireName,
|
|
929
1272
|
description: tool.description,
|
|
930
1273
|
input_schema: tool.inputSchema,
|
|
@@ -934,82 +1277,29 @@ function buildAnthropicGenerationParams({ model, options, toolProjection, eagerT
|
|
|
934
1277
|
if (mandatoryAdaptiveThinking || options?.thinkingEnabled) {
|
|
935
1278
|
const display = options?.thinkingDisplay ?? "summarized";
|
|
936
1279
|
if (supportsClaudeAdaptiveThinking(model)) {
|
|
937
|
-
|
|
1280
|
+
generationParams.thinking = {
|
|
938
1281
|
type: "adaptive",
|
|
939
1282
|
display
|
|
940
1283
|
};
|
|
941
1284
|
const effort = options?.effort ?? (mandatoryAdaptiveThinking ? resolveAnthropicThinkingEffort(model, void 0) : void 0);
|
|
942
|
-
if (effort)
|
|
943
|
-
} else
|
|
1285
|
+
if (effort) generationParams.output_config = { effort };
|
|
1286
|
+
} else generationParams.thinking = {
|
|
944
1287
|
type: "enabled",
|
|
945
1288
|
budget_tokens: options?.thinkingBudgetTokens ?? 1024,
|
|
946
1289
|
...profile === "provider" ? { display } : {}
|
|
947
1290
|
};
|
|
948
|
-
} else if (options?.thinkingEnabled === false)
|
|
1291
|
+
} else if (options?.thinkingEnabled === false) generationParams.thinking = requiresClaudeBetweenToolsThinking(model) ? { type: "between_tools" } : { type: "disabled" };
|
|
949
1292
|
}
|
|
950
1293
|
if (options?.metadata) {
|
|
951
1294
|
const userId = options.metadata.user_id;
|
|
952
|
-
if (typeof userId === "string")
|
|
1295
|
+
if (typeof userId === "string") generationParams.metadata = { user_id: userId };
|
|
953
1296
|
}
|
|
954
1297
|
if (options?.toolChoice) {
|
|
955
1298
|
const normalizedToolChoice = normalizeAnthropicToolChoice(resolveClaudeHaiku55ModelIdentity(model) === void 0 && (mandatoryAdaptiveThinking || options?.thinkingEnabled === true || resolveClaudeSonnet55ModelIdentity(model) !== void 0), options.toolChoice);
|
|
956
1299
|
const projectedToolChoice = toolProjection ? reconcileAnthropicToolChoice(normalizedToolChoice, toolProjection) : normalizedToolChoice;
|
|
957
|
-
if (projectedToolChoice)
|
|
1300
|
+
if (projectedToolChoice) generationParams.tool_choice = projectedToolChoice;
|
|
958
1301
|
}
|
|
959
|
-
|
|
960
|
-
}
|
|
961
|
-
/** Assemble both public Messages routes without changing their replay/default profiles. */
|
|
962
|
-
async function buildAnthropicRequest(model, context, options, profile, isOAuthToken, serverSideFallback, claudeCodeVersion) {
|
|
963
|
-
const managed = profile === "transport";
|
|
964
|
-
const maxTokens = managed ? resolveAnthropicMessagesMaxTokens({
|
|
965
|
-
modelContextWindow: model.contextWindow,
|
|
966
|
-
modelMaxTokens: model.maxTokens,
|
|
967
|
-
requestedMaxTokens: options?.maxTokens
|
|
968
|
-
}) : options?.maxTokens ?? model.maxTokens;
|
|
969
|
-
if (managed && maxTokens === void 0) throw new Error(`Anthropic Messages transport requires a positive maxTokens value for ${model.provider}/${model.id}`);
|
|
970
|
-
const { cacheControl, supportsCacheControlOnTools } = resolveAnthropicCacheOptions(model, options?.cacheRetention);
|
|
971
|
-
const system = buildAnthropicSystemBlocks(context.systemPrompt, isOAuthToken, cacheControl, claudeCodeVersion);
|
|
972
|
-
let toolProjection;
|
|
973
|
-
let eagerToolInputStreaming = false;
|
|
974
|
-
if (context.tools) {
|
|
975
|
-
const tools = context.tools;
|
|
976
|
-
eagerToolInputStreaming = !managed && (model.compat?.supportsEagerToolInputStreaming ?? model.provider !== "fireworks");
|
|
977
|
-
toolProjection = projectAnthropicTools(tools, (name) => isOAuthToken ? toClaudeCodeToolName(name) : name);
|
|
978
|
-
}
|
|
979
|
-
const replayPlan = buildAnthropicReplayPlan(context.messages, model, {
|
|
980
|
-
enabled: !isOAuthToken && options?.anthropicServerCompaction === true,
|
|
981
|
-
authProfileId: options?.authProfileId,
|
|
982
|
-
sessionId: options?.sessionId
|
|
983
|
-
});
|
|
984
|
-
const cacheBreakpointOptOutMessageIndexes = /* @__PURE__ */ new Set();
|
|
985
|
-
const messages = await convertAnthropicMessages(managed ? getAiTransportHost().transformTransportMessages(replayPlan.messages, model, normalizeAnthropicToolCallId, { preserveUnframedToolResults: preparedRequestSuffix.has(context) }) : transformProviderMessages(replayPlan.messages, model, normalizeAnthropicToolCallId), model, isOAuthToken, {
|
|
986
|
-
profile,
|
|
987
|
-
context,
|
|
988
|
-
allowReasoningContentReplay: managed && resolveProviderEndpoint(model).endpointClass === "xiaomi-native",
|
|
989
|
-
allowEmptySignature: model.compat?.allowEmptySignature,
|
|
990
|
-
compaction: replayPlan.compaction,
|
|
991
|
-
replayThinkingEnabled: requiresClaudeAdaptiveThinking(model) || options?.thinkingEnabled === true,
|
|
992
|
-
cacheBreakpointOptOutMessageIndexes
|
|
993
|
-
});
|
|
994
|
-
if (managed && messages.length === 0) messages.push({
|
|
995
|
-
role: "user",
|
|
996
|
-
content: "."
|
|
997
|
-
});
|
|
998
|
-
const params = {
|
|
999
|
-
model: managed && isDirectAnthropicModel(model) ? model.id.replace(/^anthropic\//i, "") : model.id,
|
|
1000
|
-
messages,
|
|
1001
|
-
max_tokens: maxTokens ?? model.maxTokens,
|
|
1002
|
-
stream: true
|
|
1003
|
-
};
|
|
1004
|
-
if (system) params.system = system;
|
|
1005
|
-
if (serverSideFallback) Object.assign(params, { fallbacks: ANTHROPIC_SERVER_SIDE_FALLBACKS });
|
|
1006
|
-
Object.assign(params, buildAnthropicGenerationParams({
|
|
1007
|
-
model,
|
|
1008
|
-
options,
|
|
1009
|
-
toolProjection,
|
|
1010
|
-
eagerToolInputStreaming,
|
|
1011
|
-
profile
|
|
1012
|
-
}));
|
|
1302
|
+
Object.assign(params, generationParams);
|
|
1013
1303
|
applyAnthropicRequestCacheControl(params, cacheControl, supportsCacheControlOnTools, cacheBreakpointOptOutMessageIndexes);
|
|
1014
1304
|
return {
|
|
1015
1305
|
params,
|
|
@@ -1021,487 +1311,393 @@ async function buildAnthropicRequest(model, context, options, profile, isOAuthTo
|
|
|
1021
1311
|
async function prepareAnthropicRequest(initialParams, model, options, directApiKeyBetaHeader) {
|
|
1022
1312
|
let params = initialParams;
|
|
1023
1313
|
applyAnthropicContextManagementToRequest(params, model, options, directApiKeyBetaHeader);
|
|
1024
|
-
const
|
|
1025
|
-
|
|
1314
|
+
const hooked = await applyAnthropicPayloadHook(params, model, options);
|
|
1315
|
+
params = hooked.params;
|
|
1026
1316
|
applyClaudeRequestContract(params, model);
|
|
1027
1317
|
const betaHeader = resolveAnthropicRequestBetaHeader(params, directApiKeyBetaHeader);
|
|
1028
1318
|
const headers = applyAnthropicThinkingBindingControls(params, betaHeader) ?? (betaHeader ? { "anthropic-beta": betaHeader } : void 0);
|
|
1029
1319
|
return {
|
|
1030
1320
|
params,
|
|
1031
|
-
headers
|
|
1032
|
-
|
|
1033
|
-
}
|
|
1034
|
-
//#endregion
|
|
1035
|
-
//#region packages/ai/src/providers/anthropic-refusal.ts
|
|
1036
|
-
function applyAnthropicRefusal(output, stopDetails, provider) {
|
|
1037
|
-
const record = asOptionalObjectRecord(stopDetails);
|
|
1038
|
-
const details = {
|
|
1039
|
-
category: normalizeNullableString(record?.category),
|
|
1040
|
-
explanation: normalizeNullableString(record?.explanation)
|
|
1321
|
+
headers,
|
|
1322
|
+
messageSources: hooked.messageSources
|
|
1041
1323
|
};
|
|
1042
|
-
const category = details.category ? ` (category: ${details.category})` : "";
|
|
1043
|
-
const explanation = details.explanation ? `: ${details.explanation}` : ".";
|
|
1044
|
-
output.stopReason = "error";
|
|
1045
|
-
output.errorMessage = `Anthropic refusal${category}${explanation}`;
|
|
1046
|
-
output.diagnostics = [...output.diagnostics ?? [], {
|
|
1047
|
-
type: "provider_refusal",
|
|
1048
|
-
timestamp: Date.now(),
|
|
1049
|
-
details: {
|
|
1050
|
-
provider,
|
|
1051
|
-
category: details.category,
|
|
1052
|
-
explanation: details.explanation
|
|
1053
|
-
}
|
|
1054
|
-
}];
|
|
1055
1324
|
}
|
|
1056
1325
|
//#endregion
|
|
1057
|
-
//#region packages/ai/src/
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
"
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
];
|
|
1065
|
-
function readAnthropicBilledUsage(usage, missingCacheTokens) {
|
|
1066
|
-
return {
|
|
1067
|
-
input: readAnthropicUsageTokenCount(usage.input_tokens),
|
|
1068
|
-
output: readAnthropicUsageTokenCount(usage.output_tokens),
|
|
1069
|
-
cacheRead: readAnthropicUsageTokenCount(usage.cache_read_input_tokens ?? missingCacheTokens),
|
|
1070
|
-
cacheWrite: readAnthropicUsageTokenCount(usage.cache_creation_input_tokens ?? missingCacheTokens),
|
|
1071
|
-
cacheWrite1h: readAnthropicCacheWriteUsage(usage).cacheWrite1h
|
|
1072
|
-
};
|
|
1073
|
-
}
|
|
1074
|
-
function applyAnthropicBilledUsage(target, resolved) {
|
|
1075
|
-
for (const key of BILLED_USAGE_KEYS) {
|
|
1076
|
-
const value = resolved[key];
|
|
1077
|
-
if (value !== void 0) target[key] = value;
|
|
1078
|
-
}
|
|
1079
|
-
target.totalTokens = target.input + target.output + target.cacheRead + target.cacheWrite;
|
|
1080
|
-
}
|
|
1081
|
-
function readAnthropicIterationUsage(value) {
|
|
1082
|
-
if (!value || typeof value !== "object" || Array.isArray(value)) return;
|
|
1083
|
-
const { input, output, cacheRead, cacheWrite, cacheWrite1h } = readAnthropicBilledUsage(value);
|
|
1084
|
-
if (input === void 0 || output === void 0 || cacheRead === void 0 || cacheWrite === void 0) return;
|
|
1085
|
-
return {
|
|
1086
|
-
input,
|
|
1087
|
-
output,
|
|
1088
|
-
cacheRead,
|
|
1089
|
-
cacheWrite,
|
|
1090
|
-
cacheWrite1h: cacheWrite1h ?? 0
|
|
1091
|
-
};
|
|
1092
|
-
}
|
|
1093
|
-
function readAnthropicUsageTokenCount(value) {
|
|
1094
|
-
return asNonNegativeFiniteNumber(value);
|
|
1095
|
-
}
|
|
1096
|
-
function readAnthropicCacheWriteUsage(usage) {
|
|
1097
|
-
if (!usage.cache_creation || typeof usage.cache_creation !== "object") return {};
|
|
1098
|
-
const cacheCreation = usage.cache_creation;
|
|
1099
|
-
const cacheWrite5m = readAnthropicUsageTokenCount(cacheCreation.ephemeral_5m_input_tokens);
|
|
1100
|
-
const cacheWrite1h = readAnthropicUsageTokenCount(cacheCreation.ephemeral_1h_input_tokens);
|
|
1101
|
-
return {
|
|
1102
|
-
...cacheWrite5m !== void 0 ? { cacheWrite5m } : {},
|
|
1103
|
-
...cacheWrite1h !== void 0 ? { cacheWrite1h } : {}
|
|
1104
|
-
};
|
|
1105
|
-
}
|
|
1106
|
-
function readAnthropicPromptUsageSnapshot(usage) {
|
|
1107
|
-
const input = readAnthropicUsageTokenCount(usage.input_tokens);
|
|
1108
|
-
const cacheRead = usage.cache_read_input_tokens == null ? 0 : readAnthropicUsageTokenCount(usage.cache_read_input_tokens);
|
|
1109
|
-
const cacheWrite = usage.cache_creation_input_tokens == null ? 0 : readAnthropicUsageTokenCount(usage.cache_creation_input_tokens);
|
|
1110
|
-
if (input === void 0 || cacheRead === void 0 || cacheWrite === void 0) return;
|
|
1111
|
-
return {
|
|
1112
|
-
input,
|
|
1113
|
-
cacheRead,
|
|
1114
|
-
cacheWrite
|
|
1115
|
-
};
|
|
1116
|
-
}
|
|
1117
|
-
function readLastAnthropicIterationUsage(usage) {
|
|
1118
|
-
if (usage.iterations == null) return { state: "absent" };
|
|
1119
|
-
if (!Array.isArray(usage.iterations) || usage.iterations.length === 0) return { state: "invalid" };
|
|
1120
|
-
const iteration = readAnthropicIterationUsage(usage.iterations.at(-1));
|
|
1121
|
-
if (!iteration) return { state: "invalid" };
|
|
1122
|
-
const contextPromptTokens = iteration.input + iteration.cacheRead + iteration.cacheWrite;
|
|
1123
|
-
return {
|
|
1124
|
-
state: "valid",
|
|
1125
|
-
usage: {
|
|
1126
|
-
contextPromptTokens,
|
|
1127
|
-
totalTokens: contextPromptTokens + iteration.output
|
|
1128
|
-
}
|
|
1129
|
-
};
|
|
1130
|
-
}
|
|
1131
|
-
function readAnthropicCompactionBilledUsage(iterations) {
|
|
1132
|
-
if (!Array.isArray(iterations) || iterations.length === 0) return;
|
|
1133
|
-
let sawCompaction = false;
|
|
1134
|
-
const billed = {
|
|
1135
|
-
input: 0,
|
|
1136
|
-
output: 0,
|
|
1137
|
-
cacheRead: 0,
|
|
1138
|
-
cacheWrite: 0,
|
|
1139
|
-
cacheWrite1h: 0
|
|
1140
|
-
};
|
|
1141
|
-
for (const iteration of iterations) {
|
|
1142
|
-
const resolved = readAnthropicIterationUsage(iteration);
|
|
1143
|
-
if (!resolved) return;
|
|
1144
|
-
sawCompaction ||= iteration.type === "compaction";
|
|
1145
|
-
for (const key of BILLED_USAGE_KEYS) billed[key] += resolved[key];
|
|
1146
|
-
}
|
|
1147
|
-
return sawCompaction ? billed : void 0;
|
|
1148
|
-
}
|
|
1149
|
-
/** Record independent billing buckets without treating zero placeholders as context proof. */
|
|
1150
|
-
function applyAnthropicMessageStartUsage(target, payload) {
|
|
1151
|
-
const promptUsage = readAnthropicPromptUsageSnapshot(payload);
|
|
1152
|
-
const promptTokens = promptUsage ? promptUsage.input + promptUsage.cacheRead + promptUsage.cacheWrite : 0;
|
|
1153
|
-
const resolved = readAnthropicBilledUsage(payload, 0);
|
|
1154
|
-
applyAnthropicBilledUsage(target, resolved);
|
|
1155
|
-
if (promptTokens > 0 && resolved.output !== void 0) target.contextUsage = {
|
|
1156
|
-
state: "available",
|
|
1157
|
-
promptTokens,
|
|
1158
|
-
totalTokens: promptTokens + target.output
|
|
1159
|
-
};
|
|
1160
|
-
return promptTokens > 0 ? promptUsage : void 0;
|
|
1161
|
-
}
|
|
1162
|
-
/** Keep billing and context distinct; omitted usage preserves the last snapshot. */
|
|
1163
|
-
function applyAnthropicMessageDeltaUsage(target, usage, messageStartPromptUsage) {
|
|
1164
|
-
if (!usage) return;
|
|
1165
|
-
const billedIterations = readAnthropicCompactionBilledUsage(usage.iterations);
|
|
1166
|
-
const reported = readAnthropicBilledUsage(usage);
|
|
1167
|
-
applyAnthropicBilledUsage(target, billedIterations ?? reported);
|
|
1168
|
-
const iterationUsage = readLastAnthropicIterationUsage(usage);
|
|
1169
|
-
if (iterationUsage.state === "valid") target.contextUsage = {
|
|
1170
|
-
state: "available",
|
|
1171
|
-
promptTokens: iterationUsage.usage.contextPromptTokens,
|
|
1172
|
-
totalTokens: iterationUsage.usage.totalTokens
|
|
1173
|
-
};
|
|
1174
|
-
else if (iterationUsage.state === "invalid") target.contextUsage = { state: "unavailable" };
|
|
1175
|
-
else if (reported.output !== void 0 && (messageStartPromptUsage !== void 0 || (reported.cacheRead !== void 0 || reported.cacheWrite !== void 0) && readAnthropicPromptUsageSnapshot(usage) !== void 0)) {
|
|
1176
|
-
const promptTokens = target.input + target.cacheRead + target.cacheWrite;
|
|
1177
|
-
target.contextUsage = {
|
|
1178
|
-
state: "available",
|
|
1179
|
-
promptTokens,
|
|
1180
|
-
totalTokens: promptTokens + target.output
|
|
1181
|
-
};
|
|
1182
|
-
} else target.contextUsage = { state: "unavailable" };
|
|
1183
|
-
}
|
|
1184
|
-
//#endregion
|
|
1185
|
-
//#region packages/ai/src/transports/anthropic-stream-reducer.ts
|
|
1186
|
-
/** One Messages protocol reducer; entry points retain their established preview/replay contracts. */
|
|
1187
|
-
async function consumeAnthropicStream(params) {
|
|
1188
|
-
const { model, options, output, stream, refusalBuffer, isOAuthToken, toolProjection } = params;
|
|
1189
|
-
const managed = params.profile === "transport";
|
|
1190
|
-
const eventSink = refusalBuffer ?? stream;
|
|
1191
|
-
let costModel = model;
|
|
1192
|
-
let messageStartPromptUsage;
|
|
1193
|
-
let inputTransformations;
|
|
1326
|
+
//#region packages/ai/src/transports/anthropic-stream-lifecycle.ts
|
|
1327
|
+
/** Entry points retain their SDK/fetch adapters; request and terminal ownership is shared. */
|
|
1328
|
+
async function runAnthropicStreamLifecycle(params) {
|
|
1329
|
+
const { model, stream, options, profile } = params;
|
|
1330
|
+
const output = createAssistantOutput(model, "anthropic-messages");
|
|
1331
|
+
const refusalBuffer = usesClaudeStreamingRefusalContract(model) ? createDeferredEventBuffer(stream) : void 0;
|
|
1332
|
+
let replayedCompaction;
|
|
1194
1333
|
try {
|
|
1195
|
-
const
|
|
1196
|
-
const
|
|
1197
|
-
|
|
1198
|
-
const
|
|
1199
|
-
const
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
const allowReasoningContentReplay = managed && resolveProviderEndpoint(model).endpointClass === "xiaomi-native";
|
|
1203
|
-
const reasoningContentBlocks = {
|
|
1204
|
-
thinking: /* @__PURE__ */ new Map(),
|
|
1205
|
-
text: /* @__PURE__ */ new Map()
|
|
1206
|
-
};
|
|
1207
|
-
let sawMessageStart = false;
|
|
1208
|
-
let sawMessageStop = false;
|
|
1209
|
-
let sawStopReason = false;
|
|
1210
|
-
const emitContentEnd = (block, contentIndex) => {
|
|
1211
|
-
eventSink.push({
|
|
1212
|
-
type: `${block.type}_end`,
|
|
1213
|
-
contentIndex,
|
|
1214
|
-
content: block.type === "thinking" ? block.thinking : block.text,
|
|
1215
|
-
partial: output
|
|
1216
|
-
});
|
|
1334
|
+
const prepared = await params.prepare();
|
|
1335
|
+
const built = await buildAnthropicRequest(model, prepared.context, prepared.options, profile, prepared.isOAuthToken, prepared.serverSideFallback, prepared.claudeCodeVersion);
|
|
1336
|
+
replayedCompaction = built.replayedCompaction;
|
|
1337
|
+
const { params: body, headers, messageSources } = await prepareAnthropicRequest(built.params, model, prepared.options, prepared.directApiKeyBetaHeader);
|
|
1338
|
+
const wireBody = {
|
|
1339
|
+
...body,
|
|
1340
|
+
stream: true
|
|
1217
1341
|
};
|
|
1218
|
-
const
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
};
|
|
1241
|
-
const eventIndexKey = (eventIndex) => typeof eventIndex === "number" ? eventIndex : -1;
|
|
1242
|
-
const appendReasoningContentDelta = (kind, eventIndex, rawText) => {
|
|
1243
|
-
if (typeof rawText !== "string") return false;
|
|
1244
|
-
const text = sanitizeTransportPayloadText(rawText);
|
|
1245
|
-
if (text.length === 0) return false;
|
|
1246
|
-
const indexes = reasoningContentBlocks[kind];
|
|
1247
|
-
const key = eventIndexKey(eventIndex);
|
|
1248
|
-
let contentIndex = indexes.get(key);
|
|
1249
|
-
let block = contentIndex === void 0 ? void 0 : blocks[contentIndex];
|
|
1250
|
-
if (contentIndex === void 0 || !block || block.type !== kind) {
|
|
1251
|
-
block = kind === "thinking" ? {
|
|
1252
|
-
type: "thinking",
|
|
1253
|
-
thinking: "",
|
|
1254
|
-
thinkingSignature: "reasoning_content"
|
|
1255
|
-
} : {
|
|
1256
|
-
type: "text",
|
|
1257
|
-
text: ""
|
|
1342
|
+
const { response, events } = await prepared.request(wireBody, headers, () => serializeAnthropicRequestBody(wireBody, messageSources));
|
|
1343
|
+
await notifyProviderHttpResponse({
|
|
1344
|
+
options: prepared.options,
|
|
1345
|
+
response,
|
|
1346
|
+
model
|
|
1347
|
+
});
|
|
1348
|
+
await prepared.checkResponse?.(response);
|
|
1349
|
+
await (async () => {
|
|
1350
|
+
const reducerOptions = prepared.options ?? {};
|
|
1351
|
+
const isOAuthToken = prepared.isOAuthToken;
|
|
1352
|
+
const toolProjection = built.toolProjection;
|
|
1353
|
+
const managed = profile === "transport";
|
|
1354
|
+
const eventSink = refusalBuffer ?? stream;
|
|
1355
|
+
let costModel = model;
|
|
1356
|
+
const applyServingModelCost = (servingModelId) => {
|
|
1357
|
+
costModel = {
|
|
1358
|
+
...model,
|
|
1359
|
+
cost: resolveAnthropicFallbackServingModelCost({
|
|
1360
|
+
requestedModelId: model.id,
|
|
1361
|
+
servingModelId,
|
|
1362
|
+
requestedCost: model.cost
|
|
1363
|
+
})
|
|
1258
1364
|
};
|
|
1259
|
-
output.content.push(block);
|
|
1260
|
-
contentIndex = output.content.length - 1;
|
|
1261
|
-
indexes.set(key, contentIndex);
|
|
1262
|
-
emitContentStart(kind, contentIndex);
|
|
1263
|
-
}
|
|
1264
|
-
if (block.type === "thinking") block.thinkingSignature = "reasoning_content";
|
|
1265
|
-
appendContentDelta(block, contentIndex, text);
|
|
1266
|
-
return true;
|
|
1267
|
-
};
|
|
1268
|
-
const finishReasoningContentSidecars = (eventIndex) => {
|
|
1269
|
-
const key = eventIndexKey(eventIndex);
|
|
1270
|
-
for (const kind of ["thinking", "text"]) {
|
|
1271
|
-
const indexes = reasoningContentBlocks[kind];
|
|
1272
|
-
const contentIndex = indexes.get(key);
|
|
1273
|
-
if (contentIndex === void 0) continue;
|
|
1274
|
-
indexes.delete(key);
|
|
1275
|
-
const block = output.content[contentIndex];
|
|
1276
|
-
if (block?.type === kind) emitContentEnd(block, contentIndex);
|
|
1277
|
-
}
|
|
1278
|
-
};
|
|
1279
|
-
for await (const rawEvent of iterateModelStream(params.events, options.signal)) {
|
|
1280
|
-
const event = asRecord(rawEvent);
|
|
1281
|
-
inputTransformations = readAnthropicInputTransformations(event) ?? inputTransformations;
|
|
1282
|
-
if (managed) notifyLlmRequestActivity(options.signal);
|
|
1283
|
-
if (event.type === "error") {
|
|
1284
|
-
const error = asOptionalObjectRecord(event.error);
|
|
1285
|
-
throw Object.assign(new Error(readStringField(error, "message") || "Anthropic Messages stream failed"), { error });
|
|
1286
|
-
}
|
|
1287
|
-
if (event.type === "message_start") {
|
|
1288
|
-
sawMessageStart = true;
|
|
1289
|
-
const message = asOptionalObjectRecord(event.message);
|
|
1290
|
-
const usage = asRecord(message?.usage);
|
|
1291
|
-
output.responseId = typeof message?.id === "string" ? message.id : void 0;
|
|
1292
|
-
output.responseModel = typeof message?.model === "string" ? message.model : void 0;
|
|
1293
|
-
messageStartPromptUsage = applyAnthropicMessageStartUsage(output.usage, usage);
|
|
1294
1365
|
calculateCost(costModel, output.usage);
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
const
|
|
1307
|
-
const
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1366
|
+
};
|
|
1367
|
+
let messageStartPromptUsage;
|
|
1368
|
+
let inputTransformations;
|
|
1369
|
+
try {
|
|
1370
|
+
const blocks = output.content;
|
|
1371
|
+
const blockIndexes = /* @__PURE__ */ new Map();
|
|
1372
|
+
const toolArgumentPreviewSchedules = /* @__PURE__ */ new WeakMap();
|
|
1373
|
+
const seededToolArguments = /* @__PURE__ */ new WeakMap();
|
|
1374
|
+
const sealedToolCalls = [];
|
|
1375
|
+
const compactionCapture = createCompactionCapture(output, model, reducerOptions);
|
|
1376
|
+
const pendingThinkingSignatures = /* @__PURE__ */ new Map();
|
|
1377
|
+
const allowReasoningContentReplay = managed && resolveProviderEndpoint(model).endpointClass === "xiaomi-native";
|
|
1378
|
+
const reasoningContentBlocks = {
|
|
1379
|
+
thinking: /* @__PURE__ */ new Map(),
|
|
1380
|
+
text: /* @__PURE__ */ new Map()
|
|
1381
|
+
};
|
|
1382
|
+
let sawMessageStart = false;
|
|
1383
|
+
let sawMessageStop = false;
|
|
1384
|
+
let sawStopReason = false;
|
|
1385
|
+
let sawFallbackBoundary = false;
|
|
1386
|
+
let terminalFallbackModel;
|
|
1387
|
+
const emitContentEnd = (block, contentIndex) => {
|
|
1388
|
+
eventSink.push({
|
|
1389
|
+
type: `${block.type}_end`,
|
|
1390
|
+
contentIndex,
|
|
1391
|
+
content: block.type === "thinking" ? block.thinking : block.text,
|
|
1392
|
+
partial: output
|
|
1319
1393
|
});
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
cost: resolveAnthropicFallbackServingModelCost({
|
|
1323
|
-
requestedModelId: model.id,
|
|
1324
|
-
servingModelId: fallbackBoundary.toModel,
|
|
1325
|
-
requestedCost: model.cost
|
|
1326
|
-
})
|
|
1327
|
-
};
|
|
1328
|
-
calculateCost(costModel, output.usage);
|
|
1394
|
+
};
|
|
1395
|
+
const emitContentStart = (kind, contentIndex, delta = "") => {
|
|
1329
1396
|
eventSink.push({
|
|
1330
|
-
type:
|
|
1397
|
+
type: `${kind}_start`,
|
|
1398
|
+
contentIndex,
|
|
1331
1399
|
partial: output
|
|
1332
1400
|
});
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
}
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
const block = contentBlock.type === "text" ? {
|
|
1344
|
-
type: "text",
|
|
1345
|
-
text: typeof contentBlock.text === "string" ? sanitizeTransportPayloadText(contentBlock.text) : "",
|
|
1346
|
-
index
|
|
1347
|
-
} : contentBlock.type === "thinking" ? {
|
|
1348
|
-
type: "thinking",
|
|
1349
|
-
thinking: typeof contentBlock.thinking === "string" ? contentBlock.thinking : "",
|
|
1350
|
-
thinkingSignature: typeof contentBlock.signature === "string" ? contentBlock.signature : "",
|
|
1351
|
-
index
|
|
1352
|
-
} : {
|
|
1353
|
-
type: "thinking",
|
|
1354
|
-
thinking: "[Reasoning redacted]",
|
|
1355
|
-
thinkingSignature: typeof contentBlock.data === "string" ? contentBlock.data : "",
|
|
1356
|
-
redacted: true,
|
|
1357
|
-
index
|
|
1358
|
-
};
|
|
1359
|
-
const delta = block.type === "text" ? block.text : block.redacted ? "" : block.thinking;
|
|
1360
|
-
output.content.push(block);
|
|
1361
|
-
const contentIndex = output.content.length - 1;
|
|
1362
|
-
blockIndexes.set(index, contentIndex);
|
|
1363
|
-
emitContentStart(block.type, contentIndex, delta);
|
|
1364
|
-
continue;
|
|
1365
|
-
}
|
|
1366
|
-
if (contentBlock?.type === "tool_use") {
|
|
1367
|
-
const block = {
|
|
1368
|
-
type: "toolCall",
|
|
1369
|
-
id: typeof contentBlock.id === "string" ? contentBlock.id : "",
|
|
1370
|
-
name: typeof contentBlock.name === "string" ? isOAuthToken ? resolveOriginalAnthropicToolName(contentBlock.name, toolProjection) : contentBlock.name : "",
|
|
1371
|
-
arguments: asRecord(contentBlock.input),
|
|
1372
|
-
partialJson: "",
|
|
1373
|
-
index
|
|
1374
|
-
};
|
|
1375
|
-
output.content.push(block);
|
|
1376
|
-
blockIndexes.set(index, output.content.length - 1);
|
|
1377
|
-
seededToolArguments.set(block, managed ? block.arguments : contentBlock.input ?? {});
|
|
1378
|
-
toolArgumentPreviewSchedules.set(block, createToolArgumentPreviewSchedule());
|
|
1401
|
+
if (delta.length > 0) eventSink.push({
|
|
1402
|
+
type: `${kind}_delta`,
|
|
1403
|
+
contentIndex,
|
|
1404
|
+
delta,
|
|
1405
|
+
partial: output
|
|
1406
|
+
});
|
|
1407
|
+
};
|
|
1408
|
+
const appendContentDelta = (block, contentIndex, delta) => {
|
|
1409
|
+
if (block.type === "thinking") appendAssistantThinking(block, delta);
|
|
1410
|
+
else block.text += delta;
|
|
1379
1411
|
eventSink.push({
|
|
1380
|
-
type:
|
|
1381
|
-
contentIndex
|
|
1412
|
+
type: `${block.type}_delta`,
|
|
1413
|
+
contentIndex,
|
|
1414
|
+
delta,
|
|
1382
1415
|
partial: output
|
|
1383
1416
|
});
|
|
1384
|
-
}
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1417
|
+
};
|
|
1418
|
+
const eventIndexKey = (eventIndex) => typeof eventIndex === "number" ? eventIndex : -1;
|
|
1419
|
+
const appendReasoningContentDelta = (kind, eventIndex, rawText) => {
|
|
1420
|
+
if (typeof rawText !== "string") return false;
|
|
1421
|
+
const text = sanitizeTransportPayloadText(rawText);
|
|
1422
|
+
if (text.length === 0) return false;
|
|
1423
|
+
const indexes = reasoningContentBlocks[kind];
|
|
1424
|
+
const key = eventIndexKey(eventIndex);
|
|
1425
|
+
let contentIndex = indexes.get(key);
|
|
1426
|
+
let block = contentIndex === void 0 ? void 0 : blocks[contentIndex];
|
|
1427
|
+
if (contentIndex === void 0 || !block || block.type !== kind) {
|
|
1428
|
+
block = kind === "thinking" ? {
|
|
1429
|
+
type: "thinking",
|
|
1430
|
+
thinking: "",
|
|
1431
|
+
thinkingSignature: "reasoning_content"
|
|
1432
|
+
} : {
|
|
1433
|
+
type: "text",
|
|
1434
|
+
text: ""
|
|
1435
|
+
};
|
|
1436
|
+
output.content.push(block);
|
|
1437
|
+
contentIndex = output.content.length - 1;
|
|
1438
|
+
indexes.set(key, contentIndex);
|
|
1439
|
+
emitContentStart(kind, contentIndex);
|
|
1440
|
+
}
|
|
1441
|
+
if (block.type === "thinking") block.thinkingSignature = "reasoning_content";
|
|
1442
|
+
appendContentDelta(block, contentIndex, text);
|
|
1443
|
+
return true;
|
|
1444
|
+
};
|
|
1445
|
+
const finishReasoningContentSidecars = (eventIndex) => {
|
|
1446
|
+
const key = eventIndexKey(eventIndex);
|
|
1447
|
+
for (const kind of ["thinking", "text"]) {
|
|
1448
|
+
const indexes = reasoningContentBlocks[kind];
|
|
1449
|
+
const contentIndex = indexes.get(key);
|
|
1450
|
+
if (contentIndex === void 0) continue;
|
|
1451
|
+
indexes.delete(key);
|
|
1452
|
+
const block = output.content[contentIndex];
|
|
1453
|
+
if (block?.type === kind) emitContentEnd(block, contentIndex);
|
|
1454
|
+
}
|
|
1455
|
+
};
|
|
1456
|
+
for await (const rawEvent of iterateModelStream(events, reducerOptions.signal)) {
|
|
1457
|
+
const event = asRecord(rawEvent);
|
|
1458
|
+
inputTransformations = readAnthropicInputTransformations(event) ?? inputTransformations;
|
|
1459
|
+
if (managed) notifyLlmRequestActivity(reducerOptions.signal);
|
|
1460
|
+
if (event.type === "error") {
|
|
1461
|
+
const error = asOptionalObjectRecord(event.error);
|
|
1462
|
+
throw Object.assign(new Error(readStringField(error, "message") || "Anthropic Messages stream failed"), { error });
|
|
1463
|
+
}
|
|
1464
|
+
if (event.type === "message_start") {
|
|
1465
|
+
sawMessageStart = true;
|
|
1466
|
+
const message = asOptionalObjectRecord(event.message);
|
|
1467
|
+
const usage = asRecord(message?.usage);
|
|
1468
|
+
output.responseId = typeof message?.id === "string" ? message.id : void 0;
|
|
1469
|
+
output.responseModel = typeof message?.model === "string" ? message.model : void 0;
|
|
1470
|
+
messageStartPromptUsage = applyAnthropicMessageStartUsage(output.usage, usage);
|
|
1471
|
+
calculateCost(costModel, output.usage);
|
|
1472
|
+
eventSink.push({
|
|
1473
|
+
type: "start",
|
|
1474
|
+
partial: output
|
|
1475
|
+
});
|
|
1476
|
+
continue;
|
|
1477
|
+
}
|
|
1478
|
+
if (event.type === "message_stop") {
|
|
1479
|
+
sawMessageStop = true;
|
|
1480
|
+
continue;
|
|
1481
|
+
}
|
|
1482
|
+
if (event.type === "content_block_start") {
|
|
1483
|
+
const contentBlock = asOptionalObjectRecord(event.content_block);
|
|
1484
|
+
const index = typeof event.index === "number" ? event.index : -1;
|
|
1485
|
+
if (reducerOptions.anthropicServerCompaction === true && compactionCapture.begin(index, contentBlock, output.content.length)) continue;
|
|
1486
|
+
const fallbackBoundary = refusalBuffer ? readAnthropicFallbackBoundary(contentBlock) : null;
|
|
1487
|
+
if (fallbackBoundary) {
|
|
1488
|
+
sawFallbackBoundary = true;
|
|
1489
|
+
refusalBuffer?.discard();
|
|
1490
|
+
sealedToolCalls.length = 0;
|
|
1491
|
+
blockIndexes.clear();
|
|
1492
|
+
pendingThinkingSignatures.clear();
|
|
1493
|
+
applyAnthropicFallbackBoundary({
|
|
1494
|
+
output,
|
|
1495
|
+
boundary: fallbackBoundary,
|
|
1496
|
+
provider: model.provider
|
|
1497
|
+
});
|
|
1498
|
+
applyServingModelCost(fallbackBoundary.toModel);
|
|
1499
|
+
eventSink.push({
|
|
1500
|
+
type: "start",
|
|
1501
|
+
partial: output
|
|
1502
|
+
});
|
|
1503
|
+
for (const [i, block] of blocks.entries()) {
|
|
1504
|
+
if (block.type !== "text") continue;
|
|
1505
|
+
emitContentStart("text", i, block.text);
|
|
1506
|
+
emitContentEnd(block, i);
|
|
1507
|
+
}
|
|
1508
|
+
continue;
|
|
1509
|
+
}
|
|
1510
|
+
pendingThinkingSignatures.delete(index);
|
|
1511
|
+
if (contentBlock?.type === "text" || contentBlock?.type === "thinking" || contentBlock?.type === "redacted_thinking") {
|
|
1512
|
+
const block = contentBlock.type === "text" ? {
|
|
1513
|
+
type: "text",
|
|
1514
|
+
text: typeof contentBlock.text === "string" ? sanitizeTransportPayloadText(contentBlock.text) : ""
|
|
1515
|
+
} : contentBlock.type === "thinking" ? {
|
|
1516
|
+
type: "thinking",
|
|
1517
|
+
thinking: typeof contentBlock.thinking === "string" ? contentBlock.thinking : "",
|
|
1518
|
+
thinkingSignature: typeof contentBlock.signature === "string" ? contentBlock.signature : ""
|
|
1519
|
+
} : {
|
|
1520
|
+
type: "thinking",
|
|
1521
|
+
thinking: "[Reasoning redacted]",
|
|
1522
|
+
thinkingSignature: typeof contentBlock.data === "string" ? contentBlock.data : "",
|
|
1523
|
+
redacted: true
|
|
1524
|
+
};
|
|
1525
|
+
const delta = block.type === "text" ? block.text : block.redacted ? "" : block.thinking;
|
|
1526
|
+
output.content.push(block);
|
|
1527
|
+
const contentIndex = output.content.length - 1;
|
|
1528
|
+
blockIndexes.set(index, contentIndex);
|
|
1529
|
+
emitContentStart(block.type, contentIndex, delta);
|
|
1530
|
+
continue;
|
|
1531
|
+
}
|
|
1532
|
+
if (contentBlock?.type === "tool_use") {
|
|
1533
|
+
const block = {
|
|
1534
|
+
type: "toolCall",
|
|
1535
|
+
id: typeof contentBlock.id === "string" ? contentBlock.id : "",
|
|
1536
|
+
name: typeof contentBlock.name === "string" ? isOAuthToken ? resolveOriginalAnthropicToolName(contentBlock.name, toolProjection) : contentBlock.name : "",
|
|
1537
|
+
arguments: asRecord(contentBlock.input),
|
|
1538
|
+
partialJson: ""
|
|
1539
|
+
};
|
|
1540
|
+
output.content.push(block);
|
|
1541
|
+
blockIndexes.set(index, output.content.length - 1);
|
|
1542
|
+
seededToolArguments.set(block, managed ? block.arguments : contentBlock.input ?? {});
|
|
1543
|
+
toolArgumentPreviewSchedules.set(block, createToolArgumentPreviewSchedule());
|
|
1544
|
+
eventSink.push({
|
|
1545
|
+
type: "toolcall_start",
|
|
1546
|
+
contentIndex: output.content.length - 1,
|
|
1547
|
+
partial: output
|
|
1548
|
+
});
|
|
1404
1549
|
}
|
|
1550
|
+
continue;
|
|
1551
|
+
}
|
|
1552
|
+
if (event.type === "content_block_delta") {
|
|
1553
|
+
const delta = asOptionalObjectRecord(event.delta);
|
|
1554
|
+
const eventIndex = typeof event.index === "number" ? event.index : void 0;
|
|
1555
|
+
if (eventIndex !== void 0 && compactionCapture.delta(eventIndex, delta)) continue;
|
|
1556
|
+
let index = eventIndex === void 0 ? void 0 : blockIndexes.get(eventIndex);
|
|
1557
|
+
let block = index === void 0 ? void 0 : blocks[index];
|
|
1558
|
+
if (allowReasoningContentReplay) {
|
|
1559
|
+
const appendedThinking = appendReasoningContentDelta("thinking", event.index, delta?.reasoning_content);
|
|
1560
|
+
const hasNativeAnthropicDelta = delta?.type === "text_delta" && typeof delta.text === "string" || delta?.type === "thinking_delta" && typeof delta.thinking === "string" || delta?.type === "input_json_delta" && typeof delta.partial_json === "string" || delta?.type === "signature_delta" && typeof delta.signature === "string";
|
|
1561
|
+
let appendedContent = false;
|
|
1562
|
+
if (!hasNativeAnthropicDelta && typeof delta?.content === "string" && delta.content.length > 0) {
|
|
1563
|
+
const text = sanitizeTransportPayloadText(delta.content);
|
|
1564
|
+
if (text.length > 0) {
|
|
1565
|
+
if (block?.type === "text" && index !== void 0) {
|
|
1566
|
+
appendContentDelta(block, index, text);
|
|
1567
|
+
appendedContent = true;
|
|
1568
|
+
} else appendedContent = appendReasoningContentDelta("text", event.index, text);
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
if ((appendedThinking || appendedContent) && !hasNativeAnthropicDelta) continue;
|
|
1572
|
+
}
|
|
1573
|
+
if (managed && !block && delta?.type === "text_delta" && typeof delta.text === "string") {
|
|
1574
|
+
block = {
|
|
1575
|
+
type: "text",
|
|
1576
|
+
text: ""
|
|
1577
|
+
};
|
|
1578
|
+
output.content.push(block);
|
|
1579
|
+
index = output.content.length - 1;
|
|
1580
|
+
if (typeof event.index === "number") blockIndexes.set(event.index, index);
|
|
1581
|
+
emitContentStart("text", index);
|
|
1582
|
+
}
|
|
1583
|
+
if (index === void 0) continue;
|
|
1584
|
+
if (block?.type === "text" && delta?.type === "text_delta" && typeof delta.text === "string") {
|
|
1585
|
+
appendContentDelta(block, index, delta.text);
|
|
1586
|
+
continue;
|
|
1587
|
+
}
|
|
1588
|
+
if (block?.type === "thinking" && delta?.type === "thinking_delta" && typeof delta.thinking === "string") {
|
|
1589
|
+
appendContentDelta(block, index, delta.thinking);
|
|
1590
|
+
continue;
|
|
1591
|
+
}
|
|
1592
|
+
if (block?.type === "toolCall" && delta?.type === "input_json_delta" && typeof delta.partial_json === "string") {
|
|
1593
|
+
const partialJson = `${block.partialJson ?? ""}${delta.partial_json}`;
|
|
1594
|
+
block.partialJson = partialJson;
|
|
1595
|
+
if (toolArgumentPreviewSchedules.get(block)?.(partialJson.length)) block.arguments = managed ? coerceTransportToolCallArguments(parseJsonObjectPreservingUnsafeIntegers(partialJson) ?? parseStreamingJson(partialJson)) : parseStreamingJson(partialJson);
|
|
1596
|
+
eventSink.push({
|
|
1597
|
+
type: "toolcall_delta",
|
|
1598
|
+
contentIndex: index,
|
|
1599
|
+
delta: delta.partial_json,
|
|
1600
|
+
partial: output
|
|
1601
|
+
});
|
|
1602
|
+
continue;
|
|
1603
|
+
}
|
|
1604
|
+
if (block?.type === "thinking" && delta?.type === "signature_delta" && typeof delta.signature === "string") {
|
|
1605
|
+
const signatureIndex = eventIndexKey(event.index);
|
|
1606
|
+
const pendingSignature = pendingThinkingSignatures.get(signatureIndex);
|
|
1607
|
+
if (pendingSignature === void 0) {
|
|
1608
|
+
block.thinkingSignature = "";
|
|
1609
|
+
pendingThinkingSignatures.set(signatureIndex, delta.signature);
|
|
1610
|
+
} else pendingThinkingSignatures.set(signatureIndex, pendingSignature + delta.signature);
|
|
1611
|
+
}
|
|
1612
|
+
continue;
|
|
1613
|
+
}
|
|
1614
|
+
if (event.type === "content_block_stop") {
|
|
1615
|
+
const eventIndex = typeof event.index === "number" ? event.index : void 0;
|
|
1616
|
+
if (eventIndex !== void 0 && compactionCapture.complete(eventIndex)) continue;
|
|
1617
|
+
const pendingSignature = eventIndex === void 0 ? void 0 : pendingThinkingSignatures.get(eventIndex);
|
|
1618
|
+
if (eventIndex !== void 0) pendingThinkingSignatures.delete(eventIndex);
|
|
1619
|
+
const index = eventIndex === void 0 ? void 0 : blockIndexes.get(eventIndex);
|
|
1620
|
+
const block = index === void 0 ? void 0 : blocks[index];
|
|
1621
|
+
if (eventIndex === void 0 || index === void 0 || !block) {
|
|
1622
|
+
finishReasoningContentSidecars(event.index);
|
|
1623
|
+
continue;
|
|
1624
|
+
}
|
|
1625
|
+
blockIndexes.delete(eventIndex);
|
|
1626
|
+
if (block.type === "thinking" && pendingSignature !== void 0) block.thinkingSignature = pendingSignature;
|
|
1627
|
+
if (block.type === "toolCall") sealedToolCalls.push({
|
|
1628
|
+
block,
|
|
1629
|
+
contentIndex: index
|
|
1630
|
+
});
|
|
1631
|
+
else emitContentEnd(block, index);
|
|
1632
|
+
finishReasoningContentSidecars(event.index);
|
|
1633
|
+
continue;
|
|
1634
|
+
}
|
|
1635
|
+
if (event.type === "message_delta") {
|
|
1636
|
+
logAnthropicContextEdits(event);
|
|
1637
|
+
const delta = asOptionalObjectRecord(event.delta);
|
|
1638
|
+
const usage = asOptionalObjectRecord(event.usage);
|
|
1639
|
+
if (typeof delta?.stop_reason === "string" && delta.stop_reason) {
|
|
1640
|
+
sawStopReason = true;
|
|
1641
|
+
const iteration = Array.isArray(usage?.iterations) ? asOptionalObjectRecord(usage.iterations.at(-1)) : void 0;
|
|
1642
|
+
terminalFallbackModel = iteration?.type === "fallback_message" && typeof iteration.model === "string" && iteration.model.trim() ? iteration.model : void 0;
|
|
1643
|
+
if (delta.stop_reason === "refusal") applyAnthropicRefusal(output, delta.stop_details, model.provider);
|
|
1644
|
+
else output.stopReason = mapAnthropicStopReason(delta.stop_reason);
|
|
1645
|
+
}
|
|
1646
|
+
applyAnthropicMessageDeltaUsage(output.usage, usage, messageStartPromptUsage);
|
|
1647
|
+
if (sawStopReason && messageStartPromptUsage && typeof usage?.output_tokens === "number") output.usage.usageReport = { state: "available" };
|
|
1648
|
+
calculateCost(costModel, output.usage);
|
|
1405
1649
|
}
|
|
1406
|
-
if ((appendedThinking || appendedContent) && !hasNativeAnthropicDelta) continue;
|
|
1407
|
-
}
|
|
1408
|
-
if (managed && !block && delta?.type === "text_delta" && typeof delta.text === "string") {
|
|
1409
|
-
block = {
|
|
1410
|
-
type: "text",
|
|
1411
|
-
text: "",
|
|
1412
|
-
index: typeof event.index === "number" ? event.index : blocks.length
|
|
1413
|
-
};
|
|
1414
|
-
output.content.push(block);
|
|
1415
|
-
index = output.content.length - 1;
|
|
1416
|
-
if (typeof event.index === "number") blockIndexes.set(event.index, index);
|
|
1417
|
-
emitContentStart("text", index);
|
|
1418
|
-
}
|
|
1419
|
-
if (index === void 0) continue;
|
|
1420
|
-
if (block?.type === "text" && delta?.type === "text_delta" && typeof delta.text === "string") {
|
|
1421
|
-
appendContentDelta(block, index, delta.text);
|
|
1422
|
-
continue;
|
|
1423
1650
|
}
|
|
1424
|
-
if (
|
|
1425
|
-
|
|
1426
|
-
|
|
1651
|
+
if ((isDirectAnthropicModel(model) || !managed && refusalBuffer) && !sawMessageStop) throw new Error("Anthropic stream ended before message_stop");
|
|
1652
|
+
if (reducerOptions.signal?.aborted) throw transportAbortError(reducerOptions.signal);
|
|
1653
|
+
if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error(output.errorMessage ?? "An unknown error occurred");
|
|
1654
|
+
if ([...blockIndexes.values()].some((index) => blocks[index]?.type === "toolCall")) throw new Error("Provider completed stream with an incomplete tool call");
|
|
1655
|
+
if ((sawMessageStart || blocks.length > 0) && !sawMessageStop && !sawStopReason) throw new Error("Anthropic stream ended before a terminal event");
|
|
1656
|
+
finalizeTerminalToolCallArguments(sealedToolCalls.map(({ block }) => block), (block) => block.partialJson && block.partialJson.length > 0 ? block.partialJson : seededToolArguments.get(block), void 0, { repairStringLiterals: true });
|
|
1657
|
+
if (refusalBuffer && terminalFallbackModel && !sawFallbackBoundary) {
|
|
1658
|
+
output.responseModel = terminalFallbackModel;
|
|
1659
|
+
applyServingModelCost(terminalFallbackModel);
|
|
1660
|
+
output.diagnostics = [...output.diagnostics ?? [], {
|
|
1661
|
+
type: "provider_fallback",
|
|
1662
|
+
timestamp: Date.now(),
|
|
1663
|
+
details: {
|
|
1664
|
+
provider: model.provider,
|
|
1665
|
+
fromModel: model.id,
|
|
1666
|
+
toModel: terminalFallbackModel
|
|
1667
|
+
}
|
|
1668
|
+
}];
|
|
1427
1669
|
}
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
block.partialJson = partialJson;
|
|
1431
|
-
if (toolArgumentPreviewSchedules.get(block)?.(partialJson.length)) block.arguments = managed ? coerceTransportToolCallArguments(parseJsonObjectPreservingUnsafeIntegers(partialJson) ?? parseStreamingJson(partialJson)) : parseStreamingJson(partialJson);
|
|
1670
|
+
for (const sealed of sealedToolCalls) {
|
|
1671
|
+
delete sealed.block.partialJson;
|
|
1432
1672
|
eventSink.push({
|
|
1433
|
-
type: "
|
|
1434
|
-
contentIndex:
|
|
1435
|
-
|
|
1673
|
+
type: "toolcall_end",
|
|
1674
|
+
contentIndex: sealed.contentIndex,
|
|
1675
|
+
toolCall: sealed.block,
|
|
1436
1676
|
partial: output
|
|
1437
1677
|
});
|
|
1438
|
-
continue;
|
|
1439
1678
|
}
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
if (pendingSignature === void 0) {
|
|
1444
|
-
block.thinkingSignature = "";
|
|
1445
|
-
pendingThinkingSignatures.set(signatureIndex, delta.signature);
|
|
1446
|
-
} else pendingThinkingSignatures.set(signatureIndex, pendingSignature + delta.signature);
|
|
1447
|
-
}
|
|
1448
|
-
continue;
|
|
1679
|
+
refusalBuffer?.flush();
|
|
1680
|
+
} finally {
|
|
1681
|
+
logAnthropicThinkingDrops(inputTransformations);
|
|
1449
1682
|
}
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
if (
|
|
1465
|
-
block,
|
|
1466
|
-
contentIndex: index
|
|
1467
|
-
});
|
|
1468
|
-
else emitContentEnd(block, index);
|
|
1469
|
-
finishReasoningContentSidecars(event.index);
|
|
1470
|
-
continue;
|
|
1471
|
-
}
|
|
1472
|
-
if (event.type === "message_delta") {
|
|
1473
|
-
logAnthropicContextEdits(event);
|
|
1474
|
-
const delta = asOptionalObjectRecord(event.delta);
|
|
1475
|
-
const usage = asOptionalObjectRecord(event.usage);
|
|
1476
|
-
if (typeof delta?.stop_reason === "string" && delta.stop_reason) {
|
|
1477
|
-
sawStopReason = true;
|
|
1478
|
-
if (delta.stop_reason === "refusal") applyAnthropicRefusal(output, delta.stop_details, model.provider);
|
|
1479
|
-
else output.stopReason = mapAnthropicStopReason(delta.stop_reason);
|
|
1480
|
-
}
|
|
1481
|
-
applyAnthropicMessageDeltaUsage(output.usage, usage, messageStartPromptUsage);
|
|
1482
|
-
if (sawStopReason && messageStartPromptUsage && typeof usage?.output_tokens === "number") output.usage.usageReport = { state: "available" };
|
|
1483
|
-
calculateCost(costModel, output.usage);
|
|
1683
|
+
})();
|
|
1684
|
+
finalizeTransportStream({
|
|
1685
|
+
stream,
|
|
1686
|
+
output
|
|
1687
|
+
});
|
|
1688
|
+
} catch (error) {
|
|
1689
|
+
failTransportStream({
|
|
1690
|
+
stream,
|
|
1691
|
+
output,
|
|
1692
|
+
signal: options?.signal,
|
|
1693
|
+
error,
|
|
1694
|
+
cleanup: () => {
|
|
1695
|
+
refusalBuffer?.discard();
|
|
1696
|
+
output.content = refusalBuffer ? [] : output.content.filter((block) => block.type !== "toolCall");
|
|
1697
|
+
if (replayedCompaction && isAnthropicReplayRejection(profile === "provider" ? error : output)) suppressAnthropicCompaction(output, model, options, replayedCompaction);
|
|
1484
1698
|
}
|
|
1485
|
-
}
|
|
1486
|
-
if ((isDirectAnthropicModel(model) || !managed && refusalBuffer) && !sawMessageStop) throw new Error("Anthropic stream ended before message_stop");
|
|
1487
|
-
if (options.signal?.aborted) throw transportAbortError(options.signal);
|
|
1488
|
-
if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error(output.errorMessage ?? "An unknown error occurred");
|
|
1489
|
-
if ([...blockIndexes.values()].some((index) => blocks[index]?.type === "toolCall")) throw new Error("Provider completed stream with an incomplete tool call");
|
|
1490
|
-
if ((sawMessageStart || blocks.length > 0) && !sawMessageStop && !sawStopReason) throw new Error("Anthropic stream ended before a terminal event");
|
|
1491
|
-
finalizeTerminalToolCallArguments(sealedToolCalls.map(({ block }) => block), (block) => block.partialJson && block.partialJson.length > 0 ? block.partialJson : seededToolArguments.get(block), void 0, { repairStringLiterals: true });
|
|
1492
|
-
for (const sealed of sealedToolCalls) {
|
|
1493
|
-
delete sealed.block.partialJson;
|
|
1494
|
-
eventSink.push({
|
|
1495
|
-
type: "toolcall_end",
|
|
1496
|
-
contentIndex: sealed.contentIndex,
|
|
1497
|
-
toolCall: sealed.block,
|
|
1498
|
-
partial: output
|
|
1499
|
-
});
|
|
1500
|
-
}
|
|
1501
|
-
refusalBuffer?.flush();
|
|
1502
|
-
} finally {
|
|
1503
|
-
logAnthropicThinkingDrops(inputTransformations);
|
|
1699
|
+
});
|
|
1504
1700
|
}
|
|
1505
1701
|
}
|
|
1506
1702
|
//#endregion
|
|
1507
|
-
export {
|
|
1703
|
+
export { resolveAnthropicServerCompactionPlan as A, usesFoundryBearerAuth as B, isAnthropicServerToolClearingEnabled as C, resolveAnthropicEphemeralCacheControl as D, resolveAnthropicCacheOptions as E, applyAnthropicFallbackBoundary as F, readAnthropicFallbackBoundary as I, resolveAnthropicFallbackServingModelCost as L, ANTHROPIC_SERVER_SIDE_FALLBACKS as M, ANTHROPIC_SERVER_SIDE_FALLBACK_BETA as N, resolveAnthropicPayloadPolicy as O, CLAUDE_OPUS_FALLBACK_MODEL_COST as P, isAnthropicOAuthApiKey as R, buildAnthropicSystemBlocks as S, logAnthropicContextEdits as T, applyAnthropicRefusal as _, resolveNewestAnthropicCompaction as a, applyAnthropicPayloadPolicyToParams as b, readAnthropicCacheWriteUsage as c, readLastAnthropicIterationUsage as d, ANTHROPIC_OMITTED_REASONING_TEXT as f, readAnthropicInputTransformations as g, logAnthropicThinkingDrops as h, resolveCompletionTokenReservation as i, supportsAnthropicServerSideFallback as j, resolveAnthropicRequestBetaHeader as k, readAnthropicPromptUsageSnapshot as l, findActiveAnthropicToolTurnAssistantIndex as m, applyAnthropicThinkingOptions as n, applyAnthropicMessageDeltaUsage as o, applyAnthropicThinkingBindingControls as p, resolveAnthropicTransportOptions as r, applyAnthropicMessageStartUsage as s, runAnthropicStreamLifecycle as t, readAnthropicUsageTokenCount as u, applyAnthropicContextManagementToRequest as v, isDirectAnthropicModel as w, applyAnthropicRequestCacheControl as x, applyAnthropicEphemeralCacheControlMarkers as y, omitFoundryBearerCredentialHeaders as z };
|