@openclaw/ai 2026.10.5-beta.3 → 2026.10.10-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +11 -0
  2. package/dist/{anthropic-BalhAzs-.mjs → anthropic-D6spfBri.mjs} +16 -18
  3. package/dist/{anthropic-payload-policy-DGblkHL5.d.mts → anthropic-payload-policy-Cr8xjazC.d.mts} +6 -3
  4. package/dist/{anthropic-stream-reducer-DkKeXXx4.mjs → anthropic-stream-reducer-CzPXOaLM.mjs} +59 -226
  5. package/dist/anthropic-tool-projection-BdAS3rtJ.mjs +165 -0
  6. package/dist/anthropic-tool-projection-DKH-aEWU.d.mts +51 -0
  7. package/dist/{api-registry-BhXXYdRA.d.mts → api-registry-gDt0faai.d.mts} +2 -2
  8. package/dist/{assistant-output-BuhRpLeD.mjs → assistant-output-6iFA1nbC.mjs} +2 -2
  9. package/dist/{azure-openai-responses-DfT9Ndd8.mjs → azure-openai-responses-0TqHwnlD.mjs} +8 -8
  10. package/dist/{cloudflare-5qSGvIUH.mjs → cloudflare-Dttf8jKq.mjs} +1 -1
  11. package/dist/{credential-redaction-BHxruEH6.d.mts → credential-redaction-XvsPf7Yi.d.mts} +1 -0
  12. package/dist/{diagnostics-tQasYct1.mjs → diagnostics-Cv7cW3pS.mjs} +3 -3
  13. package/dist/diagnostics.d.mts +6 -6
  14. package/dist/diagnostics.mjs +2 -2
  15. package/dist/{env-api-keys-CrxwdylR.mjs → env-api-keys-Xd8dm_aV.mjs} +10 -34
  16. package/dist/event-stream-CDpFza-M.d.mts +1 -0
  17. package/dist/{event-stream-BcqWLo_u.d.mts → event-stream-CzpE1g_o.d.mts} +1 -1
  18. package/dist/event-stream.d.mts +2 -2
  19. package/dist/{github-copilot-request-facts-DEE6gcB9.mjs → github-copilot-request-facts-F-EmvkpW.mjs} +1 -1
  20. package/dist/{google-interactions-9SSqsJg9.mjs → google-interactions-CTEBy9od.mjs} +19 -37
  21. package/dist/{google-messages-DsB7fmoQ.mjs → google-messages-DfpHVTaD.mjs} +18 -6
  22. package/dist/{google-provider-stream-CcEI2-MC.mjs → google-provider-stream-DJ8ANfsS.mjs} +6 -6
  23. package/dist/{google-shared-zGR0QUyS.mjs → google-shared-VTcCJLW3.mjs} +28 -41
  24. package/dist/{google-vertex-Dw_abY1w.mjs → google-vertex-Bkfizj7M.mjs} +3 -3
  25. package/dist/{google-sYI2wnY6.mjs → google-zWpkDSeN.mjs} +4 -4
  26. package/dist/{host-Bf3NjYNj.mjs → host-B2gk-d1H.mjs} +5 -11
  27. package/dist/{host-CTDz7LXD.d.mts → host-jJOffdlW.d.mts} +4 -6
  28. package/dist/{host-policy-BzZluO6_.mjs → host-policy-mpqGhbeM.mjs} +1 -1
  29. package/dist/{index-BYDvopUB.d.mts → index-DSprYWaz.d.mts} +7 -5
  30. package/dist/index.d.mts +7 -7
  31. package/dist/index.mjs +6 -6
  32. package/dist/internal/anthropic.d.mts +7 -53
  33. package/dist/internal/anthropic.mjs +6 -5
  34. package/dist/internal/google-model-family.d.mts +2 -0
  35. package/dist/internal/google-model-family.mjs +7 -3
  36. package/dist/internal/openai-completions-compat.d.mts +1 -1
  37. package/dist/internal/openai-completions-compat.mjs +1 -1
  38. package/dist/internal/openai-responses-payload-policy.d.mts +3 -3
  39. package/dist/internal/openai-responses-payload-policy.mjs +3 -3
  40. package/dist/internal/openai.d.mts +17 -26
  41. package/dist/internal/openai.mjs +10 -10
  42. package/dist/internal/retry-after.d.mts +1 -1
  43. package/dist/internal/retry-after.mjs +80 -55
  44. package/dist/internal/runtime.d.mts +9 -31
  45. package/dist/internal/runtime.mjs +10 -116
  46. package/dist/internal/shared.d.mts +9 -7
  47. package/dist/internal/shared.mjs +8 -6
  48. package/dist/internal/tool-schema.d.mts +83 -5
  49. package/dist/internal/tool-schema.mjs +4 -3
  50. package/dist/{mistral-dCDCR5ur.mjs → mistral-CATJrwne.mjs} +32 -35
  51. package/dist/model-request-body-BD5vy4rP.d.mts +17 -0
  52. package/dist/{number-coercion-C3hztWoY.mjs → number-coercion-37gmNkuA.mjs} +1 -1
  53. package/dist/{openai-chatgpt-responses-BHI3uCcA.mjs → openai-chatgpt-responses-CtdnpWwe.mjs} +95 -63
  54. package/dist/{openai-completions-CrVgnFrV.mjs → openai-completions-B6sET3oI.mjs} +10 -8
  55. package/dist/{openai-completions-compat-i-nLZxFy.d.mts → openai-completions-compat-1gsjP-KO.d.mts} +6 -3
  56. package/dist/{openai-completions-compat-CYX18uDk.mjs → openai-completions-compat-CFhQ3UVU.mjs} +7 -2
  57. package/dist/{openai-completions-transport-Dy4CZo9Q.mjs → openai-completions-transport-DviPEqw3.mjs} +370 -237
  58. package/dist/{openai-prompt-cache-r93BJhjm.mjs → openai-prompt-cache-DJ_P143P.mjs} +1 -1
  59. package/dist/{openai-prompt-cache-DIPMrMFy.d.mts → openai-prompt-cache-DgjD-UL5.d.mts} +2 -2
  60. package/dist/{openai-responses-D5oiAUOG.mjs → openai-responses-BXsJK-mD.mjs} +13 -15
  61. package/dist/{openai-responses-compaction-replay-B2FE4Nw8.d.mts → openai-responses-compaction-replay-Cvnl_nCq.d.mts} +5 -5
  62. package/dist/{openai-responses-contracts-DlKMMTxK.mjs → openai-responses-contracts-Bx-16mnf.mjs} +45 -6
  63. package/dist/{openai-responses-contracts-DKqMJ1Ct.d.mts → openai-responses-contracts-CQ4_AWjL.d.mts} +20 -8
  64. package/dist/{openai-responses-endpoint-CinGh4VZ.mjs → openai-responses-endpoint-D4v-eeYy.mjs} +55 -22
  65. package/dist/{openai-responses-payload-policy-C7GsA1y0.d.mts → openai-responses-payload-policy-BzM52TTH.d.mts} +9 -3
  66. package/dist/openai-responses-request-lifecycle-CTdAb2v1.mjs +246 -0
  67. package/dist/{openai-responses-shared-D-aDYAkJ.mjs → openai-responses-shared-Bv_1NtH9.mjs} +284 -160
  68. package/dist/{openai-responses-terminal-usage-BygjiAdi.d.mts → openai-responses-terminal-usage-CpVjkqn-.d.mts} +2 -2
  69. package/dist/{openai-tool-schema-DDPXsvJP.mjs → openai-tool-schema-Buv0GXFb.mjs} +170 -237
  70. package/dist/overflow-DJHXTNBQ.mjs +117 -0
  71. package/dist/{positive-integer-CqWjqSi9.mjs → positive-integer-Bb4Evc7L.mjs} +1 -1
  72. package/dist/prompt-cache-stability-D_MeCQFI.mjs +32 -0
  73. package/dist/{provider-error-xumb1V3F.d.mts → provider-error-CnaWYTRY.d.mts} +1 -0
  74. package/dist/{provider-error-CF9GWCs2.mjs → provider-error-qtZD2inE.mjs} +75 -13
  75. package/dist/{provider-options-CVrXZBtA.d.mts → provider-options-DeYeaflL.d.mts} +52 -6
  76. package/dist/{text-signature-Drb4Erb8.mjs → provider-replay-context-J6CfU3m1.mjs} +5 -14
  77. package/dist/{provider-transport-turn-state-BOpxgm-J.mjs → provider-transport-turn-state-Jxppzuc2.mjs} +5 -5
  78. package/dist/{provider-types-CHtRx0dI.d.mts → provider-types-ODq57rG_.d.mts} +3 -3
  79. package/dist/provider-types.d.mts +6 -6
  80. package/dist/providers.d.mts +2 -2
  81. package/dist/providers.mjs +11 -11
  82. package/dist/{reasoning-tag-text-partitioner-CpOy9-IQ.mjs → reasoning-tag-text-partitioner-DzlRubwU.mjs} +134 -47
  83. package/dist/{required-api-key-CFJvcFy_.mjs → required-api-key-D088S4Cd.mjs} +1 -1
  84. package/dist/{retry-after-CdCURCVg.d.mts → retry-after-sw-XX8aC.d.mts} +1 -1
  85. package/dist/sanitize-unicode-CRGuMONI.mjs +8 -0
  86. package/dist/sanitize-unicode-ZqVLLEKC.d.mts +27 -0
  87. package/dist/{session-resources-D1wgDQ8C.mjs → session-resources-vKvGIE3J.mjs} +1 -10
  88. package/dist/{simple-options-BAu4B54D.mjs → simple-options-BYgC6kse.mjs} +68 -79
  89. package/dist/{src-C44MKrW5.mjs → src-CyA0zJnt.mjs} +6 -2
  90. package/dist/{stream-Dd8DwRFL.mjs → stream-DLBirT0e.mjs} +8 -47
  91. package/dist/{stream-first-event-timeout-Dc42hKv6.mjs → stream-first-event-timeout-D_TfJHRJ.mjs} +1 -1
  92. package/dist/{string-coerce-CtgOVOSv.mjs → string-coerce-Cj8sqWHx.mjs} +26 -1
  93. package/dist/tool-schema-json-projection-B0hHDV7N.mjs +492 -0
  94. package/dist/{transport-stream-shared-BmpzDtdQ.d.mts → transport-stream-shared-8ru8eX4s.d.mts} +5 -5
  95. package/dist/{transport-stream-shared-CWGOuLcA.mjs → transport-stream-shared-CzQlAzJH.mjs} +27 -75
  96. package/dist/transports.d.mts +34 -28
  97. package/dist/transports.mjs +42 -48
  98. package/dist/{types-CQc6JNG4.mjs → types-BXd0kI8-.mjs} +1 -1
  99. package/dist/types-CBJthzJX.d.mts +1 -0
  100. package/dist/{types-Bd2T86VJ.d.mts → types-CVYzKrMl.d.mts} +20 -3
  101. package/dist/types.d.mts +6 -6
  102. package/dist/types.mjs +4 -4
  103. package/dist/{validation-ZX_sPVV0.mjs → validation-9FSkE8T-.mjs} +22 -3
  104. package/dist/{validation-DdGB1yy3.d.mts → validation-BQ5u20Ru.d.mts} +1 -1
  105. package/dist/validation.d.mts +1 -1
  106. package/dist/validation.mjs +1 -1
  107. package/package.json +3 -3
  108. package/dist/assistant-text-phase-Bn1hbvK9.mjs +0 -50
  109. package/dist/event-stream-6UNs-AhN.d.mts +0 -1
  110. package/dist/expect-lbe3Hgrh.mjs +0 -8
  111. package/dist/json-schema-Bp07Qui3.mjs +0 -22
  112. package/dist/openai-responses-request-lifecycle-NSIJo9jY.mjs +0 -67
  113. package/dist/openai-tool-projection-793cE3QX.d.mts +0 -37
  114. package/dist/openai-tool-schema-a5ysBBga.d.mts +0 -32
  115. package/dist/rolldown-runtime-BhDjJH2R.mjs +0 -15
  116. package/dist/sanitize-unicode-CjDG6jJx.d.mts +0 -5
  117. package/dist/string-normalization-I3ux50s9.mjs +0 -28
  118. package/dist/tool-schema-json-projection-B8sG1I9v.mjs +0 -180
  119. package/dist/types-Kdfw_04V.d.mts +0 -1
package/README.md CHANGED
@@ -26,12 +26,23 @@ runtime-local policy can use `createNodeLlmRuntime`; it preserves that host acro
26
26
  provider work without replacing the process default. `createLlmRuntime` continues
27
27
  to use the process-default host.
28
28
 
29
+ OpenAI HTTP adapters report rejected response status and headers through
30
+ `onResponse` before consuming the error body. Successful streaming responses
31
+ invoke the callback before the first event. Retry and failover policy remains
32
+ with the application.
33
+
29
34
  Hosts that attach request state to async contexts should supply
30
35
  `runInDetachedAsyncContext` from a context-free root initialized before requests
31
36
  start. Retained HTTP continuation timers use it at creation so completed caller
32
37
  state can be collected while the response remains reusable for 90 minutes.
33
38
  The default host runs the callback directly, including in browsers.
34
39
 
40
+ Tool-call stream producers expose cumulative argument text as `partialJson` on
41
+ the active content block while emitting `toolcall_delta`. This transient buffer
42
+ supports input progress; completed tool calls retain only parsed `arguments`.
43
+ It is the live block, not a per-event snapshot: a consumer that lags behind the
44
+ producer reads the latest value, or none once the call has finished.
45
+
35
46
  The explicit `@openclaw/ai/internal/anthropic`, `google-model-family`, `openai`,
36
47
  `openai-completions-compat`, `openai-responses-payload-policy`, `retry-after`, `runtime`, `shared`, and
37
48
  `tool-schema` subpaths exist for the OpenClaw application itself.
@@ -1,18 +1,18 @@
1
- import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.mjs";
2
- import { w as supportsClaudeAdaptiveThinking } from "./src-C44MKrW5.mjs";
1
+ import { n as __exportAll } from "./reasoning-tag-text-partitioner-DzlRubwU.mjs";
2
+ import { w as supportsClaudeAdaptiveThinking } from "./src-CyA0zJnt.mjs";
3
3
  import { t as AssistantMessageEventStream } from "./event-stream-X2gmsUWv.mjs";
4
- import { T as usesClaudeStreamingRefusalContract, _ as buildAnthropicClaudeCodeIdentity, a as resolveAiTransportHeaderSentinels, b as prepareClaudeNoPrefillRequestContext, r as getAiTransportHost } from "./host-Bf3NjYNj.mjs";
5
- import { d as streamFragmentError } from "./text-signature-Drb4Erb8.mjs";
6
- import { D as suppressAnthropicCompaction, J as isAnthropicOAuthApiKey, P as isDirectAnthropicModel, T as isAnthropicReplayRejection, V as supportsAnthropicServerSideFallback, X as usesFoundryBearerAuth, Y as omitFoundryBearerCredentialHeaders, d as applyAnthropicThinkingOptions, l as buildAnthropicRequest, t as consumeAnthropicStream, u as prepareAnthropicRequest } from "./anthropic-stream-reducer-DkKeXXx4.mjs";
7
- import { i as resolveCacheRetention, n as resolveCloudflareBaseUrl, r as buildCopilotDynamicHeaders } from "./cloudflare-5qSGvIUH.mjs";
8
- import { D as parseJsonWithRepair, m as notifyProviderHttpResponse, n as assignTransportErrorDetails, u as finalizeTransportStream } from "./transport-stream-shared-CWGOuLcA.mjs";
9
- import { n as buildBaseOptions, r as clampMaxTokensToModel } from "./simple-options-BAu4B54D.mjs";
10
- import { n as getEnvApiKey } from "./env-api-keys-CrxwdylR.mjs";
4
+ import { T as usesClaudeStreamingRefusalContract, _ as buildAnthropicClaudeCodeIdentity, a as resolveAiTransportHeaderSentinels, b as prepareClaudeNoPrefillRequestContext, r as getAiTransportHost } from "./host-B2gk-d1H.mjs";
5
+ import { u as streamFragmentError } from "./provider-replay-context-J6CfU3m1.mjs";
6
+ import { F as supportsAnthropicServerSideFallback, H as isAnthropicOAuthApiKey, O as isDirectAnthropicModel, U as omitFoundryBearerCredentialHeaders, W as usesFoundryBearerAuth, d as applyAnthropicThinkingOptions, l as buildAnthropicRequest, t as consumeAnthropicStream, u as prepareAnthropicRequest, x as suppressAnthropicCompaction, y as isAnthropicReplayRejection } from "./anthropic-stream-reducer-CzPXOaLM.mjs";
7
+ import { i as resolveCacheRetention, n as resolveCloudflareBaseUrl, r as buildCopilotDynamicHeaders } from "./cloudflare-Dttf8jKq.mjs";
8
+ import { n as buildBaseOptions, r as clampMaxTokensToModel } from "./simple-options-BYgC6kse.mjs";
9
+ import { D as parseJsonWithRepair, m as notifyProviderHttpResponse, n as assignTransportErrorDetails, u as finalizeTransportStream } from "./transport-stream-shared-CzQlAzJH.mjs";
10
+ import { n as getEnvApiKey } from "./env-api-keys-Xd8dm_aV.mjs";
11
11
  import { t as createDeferredEventBuffer } from "./deferred-event-buffer-DAvyP7qA.mjs";
12
- import { t as createAssistantOutput } from "./assistant-output-BuhRpLeD.mjs";
12
+ import { t as createAssistantOutput } from "./assistant-output-6iFA1nbC.mjs";
13
13
  import { t as notifyLlmRequestActivity } from "./llm-request-activity-CfMuh5cC.mjs";
14
14
  import { n as resolveOpencodeSessionHeaders } from "./session-affinity-DA4WHv1h.mjs";
15
- import { t as requireApiKey } from "./required-api-key-CFJvcFy_.mjs";
15
+ import { t as requireApiKey } from "./required-api-key-D088S4Cd.mjs";
16
16
  import Anthropic from "@anthropic-ai/sdk";
17
17
  import { Stream } from "@anthropic-ai/sdk/core/streaming.js";
18
18
  //#region packages/ai/src/providers/anthropic.ts
@@ -59,11 +59,11 @@ const streamAnthropic = (model, context, options) => {
59
59
  (async () => {
60
60
  const output = createAssistantOutput(model);
61
61
  const refusalBuffer = usesClaudeStreamingRefusalContract(model) ? createDeferredEventBuffer(stream) : void 0;
62
- let usedCompactionReplay = false;
62
+ let replayedCompaction;
63
63
  try {
64
64
  const { client, isOAuthToken, serverSideFallback, directApiKeyBetaHeader, claudeCodeVersion } = createClient(model, requestContext, requestOptions);
65
65
  const builtParams = await buildAnthropicRequest(model, requestContext, requestOptions, "provider", isOAuthToken, serverSideFallback, claudeCodeVersion);
66
- usedCompactionReplay = builtParams.usedCompactionReplay;
66
+ replayedCompaction = builtParams.replayedCompaction;
67
67
  const { params, headers } = await prepareAnthropicRequest(builtParams.params, model, requestOptions, directApiKeyBetaHeader);
68
68
  const sdkRequestOptions = {
69
69
  ...requestOptions?.signal ? { signal: requestOptions.signal } : {},
@@ -98,15 +98,12 @@ const streamAnthropic = (model, context, options) => {
98
98
  } catch (error) {
99
99
  const terminal = assignTransportErrorDetails(output, error, requestOptions?.signal);
100
100
  output.content = output.content.filter((block) => block.type !== "toolCall");
101
- for (const block of output.content) {
102
- delete block.index;
103
- delete block.partialJson;
104
- }
101
+ for (const block of output.content) delete block.index;
105
102
  if (refusalBuffer) {
106
103
  refusalBuffer.discard();
107
104
  output.content = [];
108
105
  }
109
- if (usedCompactionReplay && isAnthropicReplayRejection(error)) suppressAnthropicCompaction(output, model, requestOptions);
106
+ if (replayedCompaction && isAnthropicReplayRejection(error)) suppressAnthropicCompaction(output, model, requestOptions, replayedCompaction);
110
107
  stream.push({
111
108
  type: "error",
112
109
  reason: terminal.stopReason,
@@ -135,6 +132,7 @@ const streamSimpleAnthropic = (model, context, options) => {
135
132
  anthropicServerCompaction: options?.anthropicServerCompaction,
136
133
  anthropicCompactThreshold: options?.anthropicCompactThreshold,
137
134
  cacheTtlPruning: options?.cacheTtlPruning,
135
+ onCompactionRejected: options?.onCompactionRejected,
138
136
  authProfileId: options?.authProfileId,
139
137
  maxTokens: clampMaxTokensToModel(model, options?.maxTokens ?? model.maxTokens),
140
138
  toolChoice: options?.toolChoice,
@@ -1,6 +1,6 @@
1
- import "./index-BYDvopUB.mjs";
2
- import { k as Model } from "./types-Bd2T86VJ.mjs";
3
- import { t as AnthropicContextManagementOptions } from "./provider-options-CVrXZBtA.mjs";
1
+ import "./index-DSprYWaz.mjs";
2
+ import { k as Model } from "./types-CVYzKrMl.mjs";
3
+ import { t as AnthropicContextManagementOptions } from "./provider-options-DeYeaflL.mjs";
4
4
  import { TextBlockParam } from "@anthropic-ai/sdk/resources/messages.js";
5
5
  //#region packages/ai/src/transports/anthropic-payload-policy.d.ts
6
6
  /** @deprecated Anthropic-family provider payload helper; do not use from third-party plugins. */
@@ -26,9 +26,12 @@ type AnthropicPayloadPolicyInput = {
26
26
  type AnthropicPayloadPolicy = ReturnType<typeof resolveAnthropicPayloadPolicy>;
27
27
  /** Resolve the server-compaction gate and effective threshold for an Anthropic route. */
28
28
  declare function resolveAnthropicServerCompactionPlan(model: {
29
+ id?: string;
30
+ params?: Record<string, unknown>;
29
31
  provider?: unknown;
30
32
  api?: unknown;
31
33
  baseUrl?: string;
34
+ contextTokens?: unknown;
32
35
  contextWindow?: unknown;
33
36
  }, extraParams?: Record<string, unknown>, apiKey?: string): {
34
37
  enabled: boolean;
@@ -1,20 +1,20 @@
1
- import { E as supportsClaudeInHistorySystemMessages, O as supportsClaudeNativeXhighEffort, S as resolveClaudeSonnet5ModelIdentity, b as resolveClaudeOpus5ModelIdentity, d as requiresClaudeBetweenToolsThinking, g as resolveClaudeModelIdentity, h as resolveClaudeHaiku55ModelIdentity, m as resolveClaudeFable5ModelIdentity, u as bindsClaudeThinkingPrefix, w as supportsClaudeAdaptiveThinking, x as resolveClaudeSonnet55ModelIdentity, y as resolveClaudeOpus55ModelIdentity } from "./src-C44MKrW5.mjs";
2
- import { f as hasRuntimeContextMarker } from "./types-CQc6JNG4.mjs";
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-CyA0zJnt.mjs";
2
+ import { f as hasRuntimeContextMarker } from "./types-BXd0kI8-.mjs";
3
3
  import { r as appendAssistantThinking } from "./event-stream-X2gmsUWv.mjs";
4
4
  import { a as asRecord, o as isRecord, r as asOptionalObjectRecord, s as readStringField } from "./record-coerce-CNDovvft.mjs";
5
- import { i as normalizeOptionalLowercaseString, r as normalizeNullableString } from "./string-coerce-CtgOVOSv.mjs";
6
- import { n as asNonNegativeFiniteNumber } from "./number-coercion-C3hztWoY.mjs";
7
- import { N as isImageWithMediaPayload, O as calculateCost, S as resolveAnthropicThinkingEffort, g as applyClaudeRequestContract, h as ANTHROPIC_CLAUDE_CODE_VERSION, r as getAiTransportHost, u as STREAM_ERROR_FALLBACK_TEXT, v as defaultsClaudeAdaptiveThinking, w as usesClaudeFable5MessagesContract, x as requiresClaudeAdaptiveThinking, y as mapAnthropicStopReason } from "./host-Bf3NjYNj.mjs";
8
- import { i as providerReplayContextMatches, n as buildProviderReplayContext, r as isProviderReplayContext } from "./text-signature-Drb4Erb8.mjs";
5
+ import { a as normalizeOptionalLowercaseString, i as normalizeNullableString } from "./string-coerce-Cj8sqWHx.mjs";
6
+ import { n as asNonNegativeFiniteNumber } from "./number-coercion-37gmNkuA.mjs";
7
+ import { N as isImageWithMediaPayload, O as calculateCost, S as resolveAnthropicThinkingEffort, g as applyClaudeRequestContract, h as ANTHROPIC_CLAUDE_CODE_VERSION, r as getAiTransportHost, u as STREAM_ERROR_FALLBACK_TEXT, v as defaultsClaudeAdaptiveThinking, w as usesClaudeFable5MessagesContract, x as requiresClaudeAdaptiveThinking, y as mapAnthropicStopReason } from "./host-B2gk-d1H.mjs";
8
+ import { n as isProviderReplayContext, r as providerReplayContextMatches, t as buildProviderReplayContext } from "./provider-replay-context-J6CfU3m1.mjs";
9
9
  import { n as estimateBase64DecodedBytes } from "./base64-C8CdcsjU.mjs";
10
- import { a as resolveProviderRequestCapabilities, i as resolveProviderEndpoint } from "./host-policy-BzZluO6_.mjs";
11
- import { i as resolveCacheRetention } from "./cloudflare-5qSGvIUH.mjs";
12
- import { C as parseJsonObjectPreservingUnsafeIntegers, E as createToolArgumentPreviewSchedule, O as parseStreamingJson, P as sanitizeSurrogates, b as transportAbortError, d as iterateModelStream, i as copyProviderAcceptanceObserver, l as finalizeTerminalToolCallArguments, r as coerceTransportToolCallArguments, v as sanitizeTransportPayloadText } from "./transport-stream-shared-CWGOuLcA.mjs";
13
- import { C as stripSystemPromptCacheBoundary, D as sortPromptCacheToolsByName, d as describeToolResultMediaPlaceholder, m as extractToolResultText, p as extractToolResultBlockText, t as adjustMaxTokensForThinking, w as stripSystemPromptRelocatableBoundary, x as splitSystemPromptCacheBoundary } from "./simple-options-BAu4B54D.mjs";
14
- import { t as parsePositiveInteger } from "./positive-integer-CqWjqSi9.mjs";
15
- import { n as transformProviderMessages } from "./assistant-output-BuhRpLeD.mjs";
16
- import { i as SCHEMA_MAP_KEYS, n as projectRuntimeToolInputSchema } from "./tool-schema-json-projection-B8sG1I9v.mjs";
17
- import { i as tagPendingCommentaryText } from "./assistant-text-phase-Bn1hbvK9.mjs";
10
+ import { a as resolveProviderRequestCapabilities, i as resolveProviderEndpoint } from "./host-policy-mpqGhbeM.mjs";
11
+ import { i as resolveCacheRetention } from "./cloudflare-Dttf8jKq.mjs";
12
+ import { t as sanitizeSurrogates } from "./sanitize-unicode-CRGuMONI.mjs";
13
+ import { S as splitSystemPromptCacheBoundary, T as stripSystemPromptRelocatableBoundary, d as extractToolResultBlockText, f as extractToolResultText, h as preparedRequestSuffix, l as describeToolResultMediaPlaceholder, t as adjustMaxTokensForThinking, w as stripSystemPromptCacheBoundary } from "./simple-options-BYgC6kse.mjs";
14
+ import { C as parseJsonObjectPreservingUnsafeIntegers, E as createToolArgumentPreviewSchedule, O as parseStreamingJson, b as transportAbortError, d as iterateModelStream, i as copyProviderAcceptanceObserver, l as finalizeTerminalToolCallArguments, r as coerceTransportToolCallArguments, v as sanitizeTransportPayloadText } from "./transport-stream-shared-CzQlAzJH.mjs";
15
+ import { t as parsePositiveInteger } from "./positive-integer-Bb4Evc7L.mjs";
16
+ import { n as transformProviderMessages } from "./assistant-output-6iFA1nbC.mjs";
17
+ import { a as reconcileAnthropicToolChoice, i as projectAnthropicTools, n as normalizeAnthropicToolChoice, o as resolveOriginalAnthropicToolName, s as toClaudeCodeToolName, t as normalizeAnthropicToolCallId } from "./anthropic-tool-projection-BdAS3rtJ.mjs";
18
18
  import { t as notifyLlmRequestActivity } from "./llm-request-activity-CfMuh5cC.mjs";
19
19
  //#region packages/ai/src/providers/anthropic-auth-headers.ts
20
20
  /** Inspect resolved credential shape for auth routing without exposing its value. */
@@ -121,19 +121,22 @@ function applyAnthropicFallbackBoundary(params) {
121
121
  //#region packages/ai/src/transports/anthropic-payload-policy.ts
122
122
  const ANTHROPIC_CACHE_CONTROL_LIMIT = 4;
123
123
  const ANTHROPIC_COMPACT_THRESHOLD_MIN = 5e4;
124
+ const ANTHROPIC_COMPACTION_INSTRUCTIONS = "Summarize the transcript inside <summary></summary> tags. Include the current state, decisions, and next steps needed to continue the task in the next context window. Do not call any tools while writing this summary; respond with text only.";
124
125
  /** Resolve the Anthropic input-token trigger, including the API's minimum. */
125
- function resolveAnthropicCompactThreshold(contextWindow, configured) {
126
+ function resolveAnthropicCompactThreshold(model, configured) {
126
127
  const configuredThreshold = parsePositiveInteger(configured);
127
128
  if (configuredThreshold !== void 0) return Math.max(ANTHROPIC_COMPACT_THRESHOLD_MIN, configuredThreshold);
128
- const resolvedContextWindow = parsePositiveInteger(contextWindow);
129
- return Math.max(ANTHROPIC_COMPACT_THRESHOLD_MIN, Math.floor((resolvedContextWindow ?? 0) * .7));
129
+ const contextTokens = parsePositiveInteger(model.contextTokens);
130
+ const contextWindow = parsePositiveInteger(model.contextWindow);
131
+ return Math.max(ANTHROPIC_COMPACT_THRESHOLD_MIN, Math.floor((contextTokens && contextWindow ? Math.min(contextTokens, contextWindow) : contextTokens ?? contextWindow ?? 0) * .7));
130
132
  }
131
133
  /** Resolve the server-compaction gate and effective threshold for an Anthropic route. */
132
134
  function resolveAnthropicServerCompactionPlan(model, extraParams, apiKey) {
133
- const enabled = extraParams?.anthropicServerCompaction === true && !isAnthropicOAuthApiKey(apiKey) && normalizeOptionalLowercaseString(model.api) === "anthropic-messages" && isDirectAnthropicModel(model);
135
+ const configured = extraParams?.anthropicServerCompaction;
136
+ const enabled = configured !== false && (configured === true || supportsClaudeServerCompaction(model)) && !isAnthropicOAuthApiKey(apiKey) && normalizeOptionalLowercaseString(model.api) === "anthropic-messages" && isDirectAnthropicModel(model);
134
137
  return {
135
138
  enabled,
136
- ...enabled ? { threshold: resolveAnthropicCompactThreshold(model.contextWindow, extraParams?.anthropicCompactThreshold) } : {}
139
+ ...enabled ? { threshold: resolveAnthropicCompactThreshold(model, extraParams?.anthropicCompactThreshold) } : {}
137
140
  };
138
141
  }
139
142
  function isDirectAnthropicModel(model, env = process.env) {
@@ -251,12 +254,12 @@ function normalizeAnthropicSystemBlocks(system, cacheControl) {
251
254
  /** Apply one shared deepest-stable-message cache breakpoint policy. */
252
255
  function applyAnthropicCacheControlToMessages(messages, cacheControl, markerLimit, cacheBreakpointOptOutMessageIndexes) {
253
256
  if (!Array.isArray(messages) || messages.length === 0 || markerLimit <= 0) return;
254
- let fallbackToolResult;
255
- for (let i = messages.length - 1; i >= 0; i--) {
256
- const message = messages[i];
257
- if (!message || typeof message !== "object") continue;
258
- const record = message;
259
- if (record.role !== "user" || cacheBreakpointOptOutMessageIndexes.has(i)) continue;
257
+ let stableEnd = messages.length;
258
+ for (const index of cacheBreakpointOptOutMessageIndexes) stableEnd = Math.min(stableEnd, index);
259
+ let marked = 0;
260
+ for (let i = stableEnd - 1; i >= 0 && marked < Math.min(markerLimit, 2); i--) {
261
+ const record = messages[i];
262
+ if (!isRecord(record) || record.role !== "user") continue;
260
263
  const content = record.content;
261
264
  const blocks = typeof content === "string" ? [{
262
265
  type: "text",
@@ -264,23 +267,16 @@ function applyAnthropicCacheControlToMessages(messages, cacheControl, markerLimi
264
267
  }] : content;
265
268
  if (!Array.isArray(blocks)) continue;
266
269
  for (let j = blocks.length - 1; j >= 0; j--) {
267
- const block = blocks[j];
268
- if (!block || typeof block !== "object") continue;
269
- const blockRecord = block;
270
- if (blockRecord.type === "text" || blockRecord.type === "image") {
271
- if (fallbackToolResult && markerLimit === 1) {
272
- fallbackToolResult.cache_control = cacheControl;
273
- return;
274
- }
270
+ const blockRecord = blocks[j];
271
+ if (!isRecord(blockRecord)) continue;
272
+ if (blockRecord.type === "text" || blockRecord.type === "image" || blockRecord.type === "tool_result") {
275
273
  blockRecord.cache_control = cacheControl;
276
274
  if (typeof content === "string") record.content = blocks;
277
- if (fallbackToolResult && markerLimit > 1) fallbackToolResult.cache_control = cacheControl;
278
- return;
275
+ marked++;
276
+ break;
279
277
  }
280
- if (blockRecord.type === "tool_result" && fallbackToolResult === void 0) fallbackToolResult = blockRecord;
281
278
  }
282
279
  }
283
- if (fallbackToolResult) fallbackToolResult.cache_control = cacheControl;
284
280
  }
285
281
  function countAnthropicCacheControlMarkers(blocks) {
286
282
  if (!Array.isArray(blocks)) return 0;
@@ -301,7 +297,7 @@ function resolveAnthropicPayloadPolicy(input, model) {
301
297
  return {
302
298
  allowsServiceTier: capabilities.allowsAnthropicServiceTier,
303
299
  cacheControl: input.enableCacheControl === true ? resolveAnthropicEphemeralCacheControl(input.baseUrl, input.cacheRetention) : void 0,
304
- compactThreshold: serverCompactionPlan.threshold ?? resolveAnthropicCompactThreshold(input.contextWindow, input.extraParams?.anthropicCompactThreshold),
300
+ compactThreshold: serverCompactionPlan.threshold ?? resolveAnthropicCompactThreshold(input, input.extraParams?.anthropicCompactThreshold),
305
301
  serviceTier: input.serviceTier,
306
302
  useServerCompaction: input.enableServerCompaction === true && serverCompactionPlan.enabled,
307
303
  ...input.cacheTtlPruning && normalizeOptionalLowercaseString(input.api) === "anthropic-messages" && isDirectAnthropicModel(input) ? { toolClearing: {
@@ -354,7 +350,8 @@ function applyAnthropicContextManagementEdits(payload, policy) {
354
350
  trigger: {
355
351
  type: "input_tokens",
356
352
  value: policy.compactThreshold
357
- }
353
+ },
354
+ instructions: ANTHROPIC_COMPACTION_INSTRUCTIONS
358
355
  });
359
356
  if (edits.length > 0) payload.context_management = { edits };
360
357
  }
@@ -363,7 +360,7 @@ function applyAnthropicContextManagementToRequest(payload, model, options, direc
363
360
  applyAnthropicContextManagementEdits(payload, resolveAnthropicPayloadPolicy({
364
361
  ...model,
365
362
  api: "anthropic-messages",
366
- enableServerCompaction: true,
363
+ enableServerCompaction: options?.anthropicServerCompaction === true,
367
364
  extraParams: { ...options },
368
365
  cacheTtlPruning: options?.cacheTtlPruning
369
366
  }));
@@ -487,7 +484,11 @@ function captureAnthropicCompaction(output, capture, model, options) {
487
484
  baseUrlHash: context.baseUrlHash
488
485
  };
489
486
  }
490
- function suppressAnthropicCompaction(output, model, options) {
487
+ /**
488
+ * Record a rejected replay on the failed output and notify the transcript owner, which must
489
+ * durably strip the checkpoint: hosts may persist failed turns without their replay state.
490
+ */
491
+ function suppressAnthropicCompaction(output, model, options, rejected) {
491
492
  const context = buildProviderReplayContext(model, options);
492
493
  if (!context.baseUrlHash) return;
493
494
  output.providerReplay = {
@@ -497,6 +498,7 @@ function suppressAnthropicCompaction(output, model, options) {
497
498
  ...context,
498
499
  baseUrlHash: context.baseUrlHash
499
500
  };
501
+ options?.onCompactionRejected?.({ data: rejected.content });
500
502
  }
501
503
  function resolveNewestAnthropicCompaction(messages, model, options) {
502
504
  const context = buildProviderReplayContext(model, options);
@@ -635,168 +637,6 @@ function findActiveAnthropicToolTurnAssistantIndex(messages) {
635
637
  return [...toolResultIds].every((toolCallId) => toolCallIds.has(toolCallId)) ? index : -1;
636
638
  }
637
639
  //#endregion
638
- //#region packages/ai/src/providers/anthropic-tool-projection.ts
639
- const CLAUDE_CODE_TOOL_LOOKUP = new Map([
640
- "Read",
641
- "Write",
642
- "Edit",
643
- "Bash",
644
- "Grep",
645
- "Glob",
646
- "AskUserQuestion",
647
- "EnterPlanMode",
648
- "ExitPlanMode",
649
- "KillShell",
650
- "NotebookEdit",
651
- "Skill",
652
- "Task",
653
- "TaskOutput",
654
- "TodoWrite",
655
- "WebFetch",
656
- "WebSearch"
657
- ].map((name) => [name.toLowerCase(), name]));
658
- /** Preserve Claude Code's canonical tool casing for subscription OAuth requests. */
659
- function toClaudeCodeToolName(name) {
660
- return CLAUDE_CODE_TOOL_LOOKUP.get(name.toLowerCase()) ?? name;
661
- }
662
- /** Anthropic rejects forced tools while extended thinking is enabled. */
663
- function normalizeAnthropicToolChoice(thinkingEnabled, toolChoice) {
664
- if (thinkingEnabled && (toolChoice === "any" || typeof toolChoice === "object" && toolChoice.type === "tool")) return { type: "auto" };
665
- return typeof toolChoice === "string" ? { type: toolChoice } : toolChoice;
666
- }
667
- /** Anthropic tool identifiers accept only ASCII word characters and dashes. */
668
- function normalizeAnthropicToolCallId(id) {
669
- return id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64);
670
- }
671
- function isProviderSupportedViolation(violation) {
672
- return violation.endsWith(".$dynamicRef") || violation.endsWith(".$dynamicAnchor");
673
- }
674
- const schemaValueKeywords = /* @__PURE__ */ new Set([
675
- "additionalProperties",
676
- "contains",
677
- "contentSchema",
678
- "else",
679
- "if",
680
- "items",
681
- "not",
682
- "propertyNames",
683
- "then",
684
- "unevaluatedItems",
685
- "unevaluatedProperties"
686
- ]);
687
- const schemaArrayKeywords = /* @__PURE__ */ new Set([
688
- "allOf",
689
- "anyOf",
690
- "oneOf",
691
- "prefixItems"
692
- ]);
693
- /** Normalize the detached JSON projection and report tuple changes to enclosing schemas. */
694
- function normalizeAnthropicJsonSchema(schema) {
695
- if (!isRecord(schema)) return false;
696
- let changed = false;
697
- for (const [key, value] of Object.entries(schema)) {
698
- if (schemaValueKeywords.has(key) && !Array.isArray(value)) {
699
- changed = normalizeAnthropicJsonSchema(value) || changed;
700
- continue;
701
- }
702
- if (schemaArrayKeywords.has(key) && Array.isArray(value)) {
703
- for (const entry of value) changed = normalizeAnthropicJsonSchema(entry) || changed;
704
- continue;
705
- }
706
- if (SCHEMA_MAP_KEYS.has(key) && isRecord(value)) for (const entry of Object.values(value)) changed = normalizeAnthropicJsonSchema(entry) || changed;
707
- }
708
- if (Array.isArray(schema.items)) {
709
- for (const entry of schema.items) normalizeAnthropicJsonSchema(entry);
710
- schema.prefixItems = schema.items;
711
- const additionalItems = schema.additionalItems;
712
- if (typeof additionalItems === "boolean" || isRecord(additionalItems)) {
713
- normalizeAnthropicJsonSchema(additionalItems);
714
- schema.items = additionalItems;
715
- } else delete schema.items;
716
- delete schema.additionalItems;
717
- changed = true;
718
- }
719
- if (changed) delete schema.$schema;
720
- return changed;
721
- }
722
- /** Snapshots direct/custom tool descriptors before Anthropic payload construction. */
723
- function projectAnthropicTools(tools, toWireName) {
724
- const projectedTools = [];
725
- const originalNameByWireName = /* @__PURE__ */ new Map();
726
- const unavailableOriginalNames = /* @__PURE__ */ new Set();
727
- for (const tool of tools) {
728
- let projectedTool;
729
- let originalName;
730
- try {
731
- const name = tool.name;
732
- originalName = name;
733
- if (!name) continue;
734
- const schemaProjection = projectRuntimeToolInputSchema(tool.parameters, `${name}.parameters`);
735
- if (!isRecord(schemaProjection.schema) || schemaProjection.violations.some((violation) => !isProviderSupportedViolation(violation))) {
736
- unavailableOriginalNames.add(name);
737
- continue;
738
- }
739
- const anthropicSchema = schemaProjection.schema;
740
- normalizeAnthropicJsonSchema(anthropicSchema);
741
- const properties = anthropicSchema.properties;
742
- const required = anthropicSchema.required;
743
- if (properties !== void 0 && properties !== null && !isRecord(properties) || required !== void 0 && required !== null && (!Array.isArray(required) || required.some((entry) => typeof entry !== "string"))) {
744
- unavailableOriginalNames.add(name);
745
- continue;
746
- }
747
- let description;
748
- try {
749
- description = typeof tool.description === "string" ? tool.description : void 0;
750
- } catch {}
751
- projectedTool = {
752
- originalName: name,
753
- wireName: toWireName(name),
754
- ...description ? { description } : {},
755
- inputSchema: {
756
- ...anthropicSchema,
757
- type: "object",
758
- properties: properties ?? {},
759
- required: required ?? []
760
- }
761
- };
762
- } catch {
763
- if (originalName) unavailableOriginalNames.add(originalName);
764
- continue;
765
- }
766
- const conflictingName = originalNameByWireName.get(projectedTool.wireName);
767
- if (conflictingName !== void 0 && conflictingName !== projectedTool.originalName) throw new Error(`Anthropic tool names "${conflictingName}" and "${projectedTool.originalName}" both map to "${projectedTool.wireName}"`);
768
- originalNameByWireName.set(projectedTool.wireName, projectedTool.originalName);
769
- projectedTools.push(projectedTool);
770
- }
771
- return {
772
- inputToolCount: tools.length,
773
- unavailableOriginalNames,
774
- tools: sortPromptCacheToolsByName(projectedTools)
775
- };
776
- }
777
- /** Keeps forced Anthropic tool choices aligned with the projected wire names. */
778
- function reconcileAnthropicToolChoice(choice, projection) {
779
- if (projection.inputToolCount === 0) return choice;
780
- if (choice.type === "tool") {
781
- const requestedName = choice.name;
782
- const matchedTool = projection.tools.find((tool) => tool.originalName === requestedName) ?? (projection.unavailableOriginalNames.has(requestedName) ? void 0 : projection.tools.find((tool) => tool.wireName === requestedName));
783
- if (!matchedTool) throw new Error(`Anthropic tool_choice requested unavailable tool "${requestedName}" after schema conversion`);
784
- return {
785
- ...choice,
786
- name: matchedTool.wireName
787
- };
788
- }
789
- if (projection.tools.length === 0) {
790
- if (choice.type === "auto") return;
791
- if (choice.type === "any") throw new Error("Anthropic tool_choice requires a tool, but no tools survived schema conversion");
792
- }
793
- return choice;
794
- }
795
- /** Maps Claude Code wire names without trusting every direct/custom descriptor. */
796
- function resolveOriginalAnthropicToolName(name, projection) {
797
- return projection?.tools.find((tool) => tool.wireName === name)?.originalName ?? name;
798
- }
799
- //#endregion
800
640
  //#region packages/ai/src/transports/anthropic-transport-options.ts
801
641
  const ANTHROPIC_MESSAGES_DEFAULT_MAX_TOKENS = 4096;
802
642
  const ANTHROPIC_MESSAGES_FALLBACK_CONTEXT_DIVISOR = 4;
@@ -925,6 +765,10 @@ async function convertContentBlocks(content, model, imageBudget, profile, isErro
925
765
  async function convertAnthropicMessages(transformedMessages, model, isOAuthToken, options) {
926
766
  const params = [];
927
767
  const appendMessage = (message) => {
768
+ if (message.role === "system" && (!params.length || params.at(-1)?.role === "assistant")) params.push({
769
+ role: "user",
770
+ content: "."
771
+ });
928
772
  if (message.role === "user" && params.at(-1)?.role === "system") params.push({
929
773
  role: "assistant",
930
774
  content: [{
@@ -1058,7 +902,7 @@ async function convertAnthropicMessages(transformedMessages, model, isOAuthToken
1058
902
  if (nextMsg?.role !== "toolResult") break;
1059
903
  toolResults.push({
1060
904
  type: "tool_result",
1061
- tool_use_id: nextMsg.toolCallId,
905
+ tool_use_id: preparedRequestSuffix.has(options.context) ? preparedRequestSuffix.toolCallId(options.context, nextMsg.toolCallId, normalizeAnthropicToolCallId(nextMsg.toolCallId)) : nextMsg.toolCallId,
1062
906
  content: await convertContentBlocks(nextMsg.content, model, imageBudget, options.profile, nextMsg.isError),
1063
907
  is_error: nextMsg.isError
1064
908
  });
@@ -1137,8 +981,9 @@ async function buildAnthropicRequest(model, context, options, profile, isOAuthTo
1137
981
  sessionId: options?.sessionId
1138
982
  });
1139
983
  const cacheBreakpointOptOutMessageIndexes = /* @__PURE__ */ new Set();
1140
- const messages = await convertAnthropicMessages(managed ? getAiTransportHost().transformTransportMessages(replayPlan.messages, model, normalizeAnthropicToolCallId, void 0) : transformProviderMessages(replayPlan.messages, model, normalizeAnthropicToolCallId), model, isOAuthToken, {
984
+ const messages = await convertAnthropicMessages(managed ? getAiTransportHost().transformTransportMessages(replayPlan.messages, model, normalizeAnthropicToolCallId, { preserveUnframedToolResults: preparedRequestSuffix.has(context) }) : transformProviderMessages(replayPlan.messages, model, normalizeAnthropicToolCallId), model, isOAuthToken, {
1141
985
  profile,
986
+ context,
1142
987
  allowReasoningContentReplay: managed && resolveProviderEndpoint(model).endpointClass === "xiaomi-native",
1143
988
  allowEmptySignature: model.compat?.allowEmptySignature,
1144
989
  compaction: replayPlan.compaction,
@@ -1168,7 +1013,7 @@ async function buildAnthropicRequest(model, context, options, profile, isOAuthTo
1168
1013
  return {
1169
1014
  params,
1170
1015
  toolProjection,
1171
- usedCompactionReplay: replayPlan.compaction !== void 0
1016
+ replayedCompaction: replayPlan.compaction
1172
1017
  };
1173
1018
  }
1174
1019
  /** Apply caller payload edits before restoring required request contracts and beta headers. */
@@ -1361,21 +1206,13 @@ async function consumeAnthropicStream(params) {
1361
1206
  let sawMessageStart = false;
1362
1207
  let sawMessageStop = false;
1363
1208
  let sawStopReason = false;
1364
- const pendingTextEnds = [];
1365
- const flushPendingTextEnds = (classifyToolTurn = false) => {
1366
- if (managed && classifyToolTurn && (output.stopReason === "toolUse" || output.content.some((block) => block.type === "toolCall"))) tagPendingCommentaryText(output.content);
1367
- for (const event of pendingTextEnds) eventSink.push(event);
1368
- pendingTextEnds.length = 0;
1369
- };
1370
- const emitContentEnd = (block, contentIndex, deferText) => {
1371
- const event = {
1209
+ const emitContentEnd = (block, contentIndex) => {
1210
+ eventSink.push({
1372
1211
  type: `${block.type}_end`,
1373
1212
  contentIndex,
1374
1213
  content: block.type === "thinking" ? block.thinking : block.text,
1375
1214
  partial: output
1376
- };
1377
- if (managed && deferText && event.type === "text_end") pendingTextEnds.push(event);
1378
- else eventSink.push(event);
1215
+ });
1379
1216
  };
1380
1217
  const emitContentStart = (kind, contentIndex, delta = "") => {
1381
1218
  eventSink.push({
@@ -1435,7 +1272,7 @@ async function consumeAnthropicStream(params) {
1435
1272
  if (contentIndex === void 0) continue;
1436
1273
  indexes.delete(key);
1437
1274
  const block = output.content[contentIndex];
1438
- if (block?.type === kind) emitContentEnd(block, contentIndex, false);
1275
+ if (block?.type === kind) emitContentEnd(block, contentIndex);
1439
1276
  }
1440
1277
  };
1441
1278
  for await (const rawEvent of iterateModelStream(params.events, options.signal)) {
@@ -1472,7 +1309,6 @@ async function consumeAnthropicStream(params) {
1472
1309
  if (fallbackBoundary) {
1473
1310
  refusalBuffer?.discard();
1474
1311
  sealedToolCalls.length = 0;
1475
- pendingTextEnds.length = 0;
1476
1312
  blockIndexes.clear();
1477
1313
  pendingThinkingSignatures.clear();
1478
1314
  applyAnthropicFallbackBoundary({
@@ -1497,7 +1333,7 @@ async function consumeAnthropicStream(params) {
1497
1333
  if (block.type !== "text") continue;
1498
1334
  delete block.index;
1499
1335
  emitContentStart("text", i, block.text);
1500
- emitContentEnd(block, i, true);
1336
+ emitContentEnd(block, i);
1501
1337
  }
1502
1338
  continue;
1503
1339
  }
@@ -1527,8 +1363,6 @@ async function consumeAnthropicStream(params) {
1527
1363
  continue;
1528
1364
  }
1529
1365
  if (contentBlock?.type === "tool_use") {
1530
- if (managed) tagPendingCommentaryText(output.content);
1531
- flushPendingTextEnds();
1532
1366
  const block = {
1533
1367
  type: "toolCall",
1534
1368
  id: typeof contentBlock.id === "string" ? contentBlock.id : "",
@@ -1630,7 +1464,7 @@ async function consumeAnthropicStream(params) {
1630
1464
  block,
1631
1465
  contentIndex: index
1632
1466
  });
1633
- else emitContentEnd(block, index, true);
1467
+ else emitContentEnd(block, index);
1634
1468
  finishReasoningContentSidecars(event.index);
1635
1469
  continue;
1636
1470
  }
@@ -1644,8 +1478,8 @@ async function consumeAnthropicStream(params) {
1644
1478
  else output.stopReason = mapAnthropicStopReason(delta.stop_reason);
1645
1479
  }
1646
1480
  applyAnthropicMessageDeltaUsage(output.usage, usage, messageStartPromptUsage);
1481
+ if (sawStopReason && messageStartPromptUsage && typeof usage?.output_tokens === "number") output.usage.usageReport = { state: "available" };
1647
1482
  calculateCost(costModel, output.usage);
1648
- flushPendingTextEnds(true);
1649
1483
  }
1650
1484
  }
1651
1485
  if ((isDirectAnthropicModel(model) || !managed && refusalBuffer) && !sawMessageStop) throw new Error("Anthropic stream ended before message_stop");
@@ -1664,10 +1498,9 @@ async function consumeAnthropicStream(params) {
1664
1498
  });
1665
1499
  }
1666
1500
  refusalBuffer?.flush();
1667
- flushPendingTextEnds(true);
1668
1501
  } finally {
1669
1502
  logAnthropicThinkingDrops(inputTransformations);
1670
1503
  }
1671
1504
  }
1672
1505
  //#endregion
1673
- export { applyAnthropicPayloadPolicyToParams as A, resolveAnthropicServerCompactionPlan as B, logAnthropicThinkingDrops as C, suppressAnthropicCompaction as D, resolveNewestAnthropicCompaction as E, logAnthropicContextEdits as F, applyAnthropicFallbackBoundary as G, ANTHROPIC_SERVER_SIDE_FALLBACKS as H, resolveAnthropicCacheOptions as I, isAnthropicOAuthApiKey as J, readAnthropicFallbackBoundary as K, resolveAnthropicEphemeralCacheControl as L, buildAnthropicSystemBlocks as M, isAnthropicServerToolClearingEnabled as N, applyAnthropicContextManagementToRequest as O, isDirectAnthropicModel as P, resolveAnthropicPayloadPolicy as R, findActiveAnthropicToolTurnAssistantIndex as S, isAnthropicReplayRejection as T, ANTHROPIC_SERVER_SIDE_FALLBACK_BETA as U, supportsAnthropicServerSideFallback as V, CLAUDE_OPUS_FALLBACK_MODEL_COST as W, usesFoundryBearerAuth as X, omitFoundryBearerCredentialHeaders as Y, reconcileAnthropicToolChoice as _, readAnthropicPromptUsageSnapshot as a, ANTHROPIC_OMITTED_REASONING_TEXT as b, applyAnthropicRefusal as c, applyAnthropicThinkingOptions as d, resolveAnthropicTransportOptions as f, projectAnthropicTools as g, normalizeAnthropicToolChoice as h, readAnthropicCacheWriteUsage as i, applyAnthropicRequestCacheControl as j, applyAnthropicEphemeralCacheControlMarkers as k, buildAnthropicRequest as l, normalizeAnthropicToolCallId as m, applyAnthropicMessageDeltaUsage as n, readAnthropicUsageTokenCount as o, resolveCompletionTokenReservation as p, resolveAnthropicFallbackServingModelCost as q, applyAnthropicMessageStartUsage as r, readLastAnthropicIterationUsage as s, consumeAnthropicStream as t, prepareAnthropicRequest as u, resolveOriginalAnthropicToolName as v, readAnthropicInputTransformations as w, applyAnthropicThinkingBindingControls as x, toClaudeCodeToolName as y, resolveAnthropicRequestBetaHeader as z };
1506
+ export { resolveAnthropicCacheOptions as A, readAnthropicFallbackBoundary as B, applyAnthropicEphemeralCacheControlMarkers as C, isAnthropicServerToolClearingEnabled as D, buildAnthropicSystemBlocks as E, supportsAnthropicServerSideFallback as F, isAnthropicOAuthApiKey as H, ANTHROPIC_SERVER_SIDE_FALLBACKS as I, ANTHROPIC_SERVER_SIDE_FALLBACK_BETA as L, resolveAnthropicPayloadPolicy as M, resolveAnthropicRequestBetaHeader as N, isDirectAnthropicModel as O, resolveAnthropicServerCompactionPlan as P, CLAUDE_OPUS_FALLBACK_MODEL_COST as R, applyAnthropicContextManagementToRequest as S, applyAnthropicRequestCacheControl as T, omitFoundryBearerCredentialHeaders as U, resolveAnthropicFallbackServingModelCost as V, usesFoundryBearerAuth as W, logAnthropicThinkingDrops as _, readAnthropicPromptUsageSnapshot as a, resolveNewestAnthropicCompaction as b, applyAnthropicRefusal as c, applyAnthropicThinkingOptions as d, resolveAnthropicTransportOptions as f, findActiveAnthropicToolTurnAssistantIndex as g, applyAnthropicThinkingBindingControls as h, readAnthropicCacheWriteUsage as i, resolveAnthropicEphemeralCacheControl as j, logAnthropicContextEdits as k, buildAnthropicRequest as l, ANTHROPIC_OMITTED_REASONING_TEXT as m, applyAnthropicMessageDeltaUsage as n, readAnthropicUsageTokenCount as o, resolveCompletionTokenReservation as p, applyAnthropicMessageStartUsage as r, readLastAnthropicIterationUsage as s, consumeAnthropicStream as t, prepareAnthropicRequest as u, readAnthropicInputTransformations as v, applyAnthropicPayloadPolicyToParams as w, suppressAnthropicCompaction as x, isAnthropicReplayRejection as y, applyAnthropicFallbackBoundary as z };