@openclaw/ai 2026.9.3 → 2026.9.5

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 (101) hide show
  1. package/README.md +1 -1
  2. package/dist/{anthropic-CZy5U0NY.mjs → anthropic-COtDvgtt.mjs} +16 -16
  3. package/dist/{anthropic-payload-policy-wuRCb6MH.d.mts → anthropic-payload-policy-5Erq1Nzy.d.mts} +3 -3
  4. package/dist/{anthropic-stream-reducer-B_yo_7pf.mjs → anthropic-stream-reducer-BvdYYWL8.mjs} +56 -47
  5. package/dist/{api-registry-CB1-1oQ2.d.mts → api-registry-Ba2Cv-ut.d.mts} +2 -2
  6. package/dist/{assistant-output-iqnlJCV2.mjs → assistant-output-BsEkB-vU.mjs} +1 -1
  7. package/dist/{azure-openai-responses-Crpa40QR.mjs → azure-openai-responses-YrgnD583.mjs} +6 -9
  8. package/dist/{base64-D-su8YVo.mjs → base64-BQOzsvUH.mjs} +4 -4
  9. package/dist/credential-redaction-BKv49aiv.d.mts +24 -0
  10. package/dist/{diagnostics-dV98PqIy.mjs → diagnostics-Dm4bisWG.mjs} +89 -2
  11. package/dist/diagnostics.d.mts +4 -23
  12. package/dist/diagnostics.mjs +3 -3
  13. package/dist/{event-stream-C1Z2piyk.d.mts → event-stream-CCoa-qSI.d.mts} +1 -1
  14. package/dist/event-stream-DmSCpi1T.d.mts +1 -0
  15. package/dist/event-stream.d.mts +2 -2
  16. package/dist/expect-lbe3Hgrh.mjs +8 -0
  17. package/dist/{google-BDPriaVe.mjs → google-BuhpRO9r.mjs} +7 -10
  18. package/dist/{google-messages-CVn9eFpF.mjs → google-messages-CyWnYlh0.mjs} +3 -4
  19. package/dist/{google-shared-BedY23XS.mjs → google-shared-BT5ZeNer.mjs} +13 -13
  20. package/dist/{google-vertex-DMz8XQCn.mjs → google-vertex-C7EplRvt.mjs} +5 -8
  21. package/dist/{host-CWuF-sS3.mjs → host-B4MeUNBc.mjs} +145 -12
  22. package/dist/{host-DK3wmS3e.d.mts → host-FZ1RA_qD.d.mts} +7 -3
  23. package/dist/{host-policy-CAopLRKA.mjs → host-policy-DUnXSx0I.mjs} +1 -1
  24. package/dist/{index-CQ6LTHw8.d.mts → index-DaF2QbwS.d.mts} +5 -10
  25. package/dist/index.d.mts +7 -8
  26. package/dist/index.mjs +5 -5
  27. package/dist/internal/anthropic.d.mts +6 -7
  28. package/dist/internal/anthropic.mjs +4 -4
  29. package/dist/internal/openai-completions-compat.d.mts +2 -0
  30. package/dist/internal/openai-completions-compat.mjs +2 -0
  31. package/dist/internal/openai-responses-payload-policy.d.mts +3 -3
  32. package/dist/internal/openai-responses-payload-policy.mjs +3 -2
  33. package/dist/internal/openai.d.mts +10 -53
  34. package/dist/internal/openai.mjs +11 -10
  35. package/dist/internal/runtime.d.mts +43 -10
  36. package/dist/internal/runtime.mjs +5 -11
  37. package/dist/internal/shared.d.mts +35 -5
  38. package/dist/internal/shared.mjs +4 -4
  39. package/dist/internal/tool-schema.d.mts +3 -3
  40. package/dist/internal/tool-schema.mjs +2 -2
  41. package/dist/{mistral--m-Jm6VZ.mjs → mistral-moA-mbwl.mjs} +9 -16
  42. package/dist/{openai-chatgpt-responses-nDZccFW-.mjs → openai-chatgpt-responses-DWID3EFO.mjs} +76 -33
  43. package/dist/{openai-completions-KuoZyx0d.mjs → openai-completions-DJ1Vm-CD.mjs} +12 -13
  44. package/dist/{openai-prompt-cache-BI0rkM-5.mjs → openai-completions-compat-CkwdxTZx.mjs} +5 -50
  45. package/dist/{openai-completions-compat-CXn3T1we.d.mts → openai-completions-compat-JE7gqxb9.d.mts} +4 -4
  46. package/dist/{openai-completions-stream-BQk3SkLD.mjs → openai-completions-stream-Bu98b0Hv.mjs} +128 -99
  47. package/dist/openai-prompt-cache-1wfaIszn.mjs +46 -0
  48. package/dist/{openai-prompt-cache-rrutvqxq.d.mts → openai-prompt-cache-CJ_xEevu.d.mts} +2 -2
  49. package/dist/{openai-provider-client-ha_WxTyj.mjs → openai-provider-client-DPo0Hmak.mjs} +2 -2
  50. package/dist/{openai-reasoning-effort-BK7FbcLT.mjs → openai-reasoning-effort-NlFZmfEu.mjs} +87 -19
  51. package/dist/{openai-responses-D99dOzKI.mjs → openai-responses-BejZzQCP.mjs} +9 -13
  52. package/dist/{openai-responses-compaction-window-D5jbzCi3.mjs → openai-responses-compaction-window-D6P5oZP5.mjs} +21 -140
  53. package/dist/openai-responses-contracts-DWrfMODE.mjs +81 -0
  54. package/dist/{openai-responses-contracts-B55afwRo.d.mts → openai-responses-contracts-Dflvrfa8.d.mts} +10 -39
  55. package/dist/{openai-responses-payload-policy-rLRPsSmB.d.mts → openai-responses-payload-policy-C7GsA1y0.d.mts} +5 -3
  56. package/dist/openai-responses-prompt-observer-internal-C15_-OwV.mjs +195 -0
  57. package/dist/{openai-responses-shared-ZyQEzS5i.mjs → openai-responses-shared-CwsziD_m.mjs} +390 -183
  58. package/dist/openai-responses-terminal-usage-Dl3J6zrf.d.mts +47 -0
  59. package/dist/{openai-tool-schema-CzjyYXun.mjs → openai-tool-schema-BO8rwyAD.mjs} +92 -68
  60. package/dist/{openai-transport-params-DNasp2fU.mjs → openai-transport-params-DQeuAvBl.mjs} +162 -51
  61. package/dist/positive-integer-DtjCkbue.mjs +8 -0
  62. package/dist/{provider-error-C6TbKiey.mjs → provider-error-DDqw9Qda.mjs} +140 -36
  63. package/dist/{provider-options-BXr9Ec83.d.mts → provider-options-DprLsWh9.d.mts} +9 -6
  64. package/dist/{provider-replay-context-BuSUaAk5.mjs → provider-replay-context-CnUSOwhr.mjs} +1 -1
  65. package/dist/{provider-transcript-transform-pPmUIwKt.mjs → provider-transcript-transform-BsRAhuWJ.mjs} +1 -1
  66. package/dist/provider-transport-turn-state-CkGToCD2.mjs +42 -0
  67. package/dist/{provider-types-CAV0Og3m.d.mts → provider-types-CAKRC7N5.d.mts} +3 -3
  68. package/dist/provider-types.d.mts +6 -7
  69. package/dist/providers.d.mts +2 -2
  70. package/dist/providers.mjs +10 -10
  71. package/dist/{reasoning-tag-text-partitioner-BQBi4B9d.mjs → reasoning-tag-text-partitioner-Dy9IO8Dc.mjs} +15 -14
  72. package/dist/{session-affinity-CCH7eYdB.mjs → session-affinity-Bcunsn4I.mjs} +5 -2
  73. package/dist/{simple-options-tcKOqnpF.mjs → simple-options-C6cFWj_f.mjs} +26 -5
  74. package/dist/{src-B2Q_6G8V.mjs → src-DeKjbE8I.mjs} +3 -6
  75. package/dist/{stream-first-event-timeout-2hfrquuz.mjs → stream-first-event-timeout-C9ZadkJW.mjs} +1 -1
  76. package/dist/{string-normalization-CmLIasuf.mjs → string-normalization-J9ZiLfGO.mjs} +13 -1
  77. package/dist/tool-schema-json-projection-CD9c_fK8.mjs +134 -0
  78. package/dist/{transport-stream-shared-DOxpGJ-H.d.mts → transport-stream-shared-BbUkFaHi.d.mts} +20 -36
  79. package/dist/{transport-stream-shared-Cu3ZPhNW.mjs → transport-stream-shared-D-6FQSHm.mjs} +223 -11
  80. package/dist/{transport-utils-CCooe-cr.mjs → transport-utils-1cyq5Y7x.mjs} +4 -7
  81. package/dist/transports.d.mts +51 -165
  82. package/dist/transports.mjs +172 -507
  83. package/dist/{types-Dy1q0CSu.d.mts → types-4_uVs5WH.d.mts} +49 -3
  84. package/dist/types-DkJfb4W3.d.mts +1 -0
  85. package/dist/types-LFWwv0cF.mjs +8 -0
  86. package/dist/types.d.mts +6 -7
  87. package/dist/types.mjs +4 -4
  88. package/dist/{validation-CaFUZN9B.d.mts → validation-Ctzu2DhF.d.mts} +1 -1
  89. package/dist/{validation-BDzVDnTs.mjs → validation-Dw7cb6BV.mjs} +1 -0
  90. package/dist/validation.d.mts +1 -1
  91. package/dist/validation.mjs +1 -1
  92. package/package.json +10 -5
  93. package/dist/diagnostics-DnPnOui6.d.mts +0 -29
  94. package/dist/event-stream-I_GlBsuZ.d.mts +0 -1
  95. package/dist/hash-CHgqbJmD.mjs +0 -16
  96. package/dist/json-parse-Dw_hnxsA.mjs +0 -146
  97. package/dist/openai-responses-prompt-observer-internal-tApyTLVu.mjs +0 -32
  98. package/dist/sanitize-unicode-Bb-v9meu.mjs +0 -83
  99. package/dist/tool-schema-json-projection-ClptDdAO.mjs +0 -82
  100. package/dist/types-BADKjDBI.d.mts +0 -1
  101. package/dist/types-BDdaOVi2.mjs +0 -6
package/README.md CHANGED
@@ -24,7 +24,7 @@ provider plugin hooks, and diagnostics logging) can be injected with
24
24
  `configureAiTransportHost`; the defaults are inert.
25
25
 
26
26
  The explicit `@openclaw/ai/internal/anthropic`, `google-model-family`, `openai`,
27
- `openai-responses-payload-policy`, `retry-after`, `runtime`, `shared`, and
27
+ `openai-completions-compat`, `openai-responses-payload-policy`, `retry-after`, `runtime`, `shared`, and
28
28
  `tool-schema` subpaths exist for the OpenClaw application itself.
29
29
  They carry no semver guarantee and can change or disappear in any release; do
30
30
  not depend on them outside OpenClaw.
@@ -1,19 +1,18 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.mjs";
2
- import { _ as supportsClaudeAdaptiveThinking, h as resolveClaudeSonnet5ModelIdentity, m as resolveClaudeOpus5ModelIdentity } from "./src-B2Q_6G8V.mjs";
2
+ import { _ as supportsClaudeAdaptiveThinking, h as resolveClaudeSonnet5ModelIdentity, m as resolveClaudeOpus5ModelIdentity } from "./src-DeKjbE8I.mjs";
3
3
  import { t as AssistantMessageEventStream } from "./event-stream-D8PARQfL.mjs";
4
- import { S as usesClaudeStreamingRefusalContract, _ as prepareClaudeNoPrefillRequestContext, m as applyClaudeRequestContract, n as getAiTransportHost, p as ANTHROPIC_CLAUDE_CODE_VERSION, r as resolveAiTransportHeaderSentinels, v as requiresClaudeAdaptiveThinking, x as usesClaudeFable5MessagesContract, y as resolveAnthropicThinkingEffort } from "./host-CWuF-sS3.mjs";
5
- import { t as MALFORMED_STREAMING_FRAGMENT_ERROR_MESSAGE } from "./transport-utils-CCooe-cr.mjs";
6
- import { C as applyAnthropicThinkingBindingControls, D as ANTHROPIC_SERVER_SIDE_FALLBACKS, H as resolveAnthropicContextManagementBetaHeader, I as applyAnthropicRequestCacheControl, J as usesFoundryBearerAuth, K as isAnthropicOAuthApiKey, L as buildAnthropicSystemBlocks, N as applyAnthropicContextManagementToRequest, O as ANTHROPIC_SERVER_SIDE_FALLBACK_BETA, V as resolveAnthropicCacheOptions, d as convertAnthropicTools, f as buildAnthropicReplayPlan, g as normalizeAnthropicToolCallId, h as suppressAnthropicCompaction, l as buildAnthropicGenerationParams, p as isAnthropicReplayRejection, q as omitFoundryBearerCredentialHeaders, t as consumeAnthropicStream, u as convertAnthropicMessages, z as isDirectAnthropicModel } from "./anthropic-stream-reducer-B_yo_7pf.mjs";
4
+ import { E as resolveAnthropicThinkingEffort, O as usesClaudeFable5MessagesContract, T as requiresClaudeAdaptiveThinking, b as ANTHROPIC_CLAUDE_CODE_VERSION, k as usesClaudeStreamingRefusalContract, n as getAiTransportHost, r as resolveAiTransportHeaderSentinels, w as prepareClaudeNoPrefillRequestContext, x as applyClaudeRequestContract } from "./host-B4MeUNBc.mjs";
5
+ import { t as MALFORMED_STREAMING_FRAGMENT_ERROR_MESSAGE } from "./transport-utils-1cyq5Y7x.mjs";
6
+ import { C as applyAnthropicThinkingBindingControls, D as ANTHROPIC_SERVER_SIDE_FALLBACKS, H as resolveAnthropicContextManagementBetaHeader, I as applyAnthropicRequestCacheControl, J as usesFoundryBearerAuth, K as isAnthropicOAuthApiKey, L as buildAnthropicSystemBlocks, N as applyAnthropicContextManagementToRequest, O as ANTHROPIC_SERVER_SIDE_FALLBACK_BETA, V as resolveAnthropicCacheOptions, d as convertAnthropicTools, f as buildAnthropicReplayPlan, g as normalizeAnthropicToolCallId, h as suppressAnthropicCompaction, l as buildAnthropicGenerationParams, p as isAnthropicReplayRejection, q as omitFoundryBearerCredentialHeaders, t as consumeAnthropicStream, u as convertAnthropicMessages, z as isDirectAnthropicModel } from "./anthropic-stream-reducer-BvdYYWL8.mjs";
7
7
  import { t as resolveCacheRetention } from "./cache-retention-0x979a5V.mjs";
8
- import { n as buildBaseOptions, r as clampMaxTokensToModel, t as adjustMaxTokensForThinking } from "./simple-options-tcKOqnpF.mjs";
8
+ import { n as buildBaseOptions, r as clampMaxTokensToModel, t as adjustMaxTokensForThinking } from "./simple-options-C6cFWj_f.mjs";
9
9
  import { n as getEnvApiKey } from "./env-api-keys-bktO00EJ.mjs";
10
- import { c as finalizeTransportStream, f as notifyProviderHttpResponse, t as assignTransportErrorDetails } from "./transport-stream-shared-Cu3ZPhNW.mjs";
10
+ import { T as parseJsonWithRepair, l as finalizeTransportStream, n as assignTransportErrorDetails, p as notifyProviderHttpResponse } from "./transport-stream-shared-D-6FQSHm.mjs";
11
11
  import { t as createDeferredEventBuffer } from "./deferred-event-buffer-DAvyP7qA.mjs";
12
- import { n as parseJsonWithRepair } from "./json-parse-Dw_hnxsA.mjs";
13
12
  import { t as notifyLlmRequestActivity } from "./llm-request-activity-BjtkplhG.mjs";
14
- import { t as createAssistantOutput } from "./assistant-output-iqnlJCV2.mjs";
15
- import { t as resolveOpencodeSessionHeaders } from "./session-affinity-CCH7eYdB.mjs";
16
- import { t as transformProviderMessages } from "./provider-transcript-transform-pPmUIwKt.mjs";
13
+ import { t as createAssistantOutput } from "./assistant-output-BsEkB-vU.mjs";
14
+ import { n as resolveOpencodeSessionHeaders } from "./session-affinity-Bcunsn4I.mjs";
15
+ import { t as transformProviderMessages } from "./provider-transcript-transform-BsRAhuWJ.mjs";
17
16
  import { i as resolveCloudflareBaseUrl, n as hasCopilotVisionInput, t as buildCopilotDynamicHeaders } from "./github-copilot-headers-B37TB3rB.mjs";
18
17
  import Anthropic from "@anthropic-ai/sdk";
19
18
  import { Stream } from "@anthropic-ai/sdk/core/streaming.js";
@@ -107,7 +106,7 @@ const streamAnthropic = (model, context, options) => {
107
106
  ...requestOptions?.signal ? { signal: requestOptions.signal } : {},
108
107
  ...requestOptions?.timeoutMs !== void 0 ? { timeout: requestOptions.timeoutMs } : {},
109
108
  maxRetries: 0,
110
- headers: applyAnthropicThinkingBindingControls(params, betaHeader) ?? (betaHeader !== void 0 ? { "anthropic-beta": betaHeader } : void 0)
109
+ headers: applyAnthropicThinkingBindingControls(params, betaHeader) ?? (betaHeader ? { "anthropic-beta": betaHeader } : void 0)
111
110
  };
112
111
  const response = await client.messages.create({
113
112
  ...params,
@@ -191,8 +190,7 @@ const streamSimpleAnthropic = (model, context, options) => {
191
190
  });
192
191
  if (!reasoning) return streamAnthropic(model, context, {
193
192
  ...base,
194
- thinkingEnabled: mandatoryAdaptiveThinking,
195
- ...mandatoryAdaptiveThinking ? { effort: "high" } : {}
193
+ thinkingEnabled: mandatoryAdaptiveThinking
196
194
  });
197
195
  if (supportsClaudeAdaptiveThinking(model)) {
198
196
  const effort = resolveAnthropicThinkingEffort(model, reasoning);
@@ -202,7 +200,7 @@ const streamSimpleAnthropic = (model, context, options) => {
202
200
  effort
203
201
  });
204
202
  }
205
- const adjusted = adjustMaxTokensForThinking(base.maxTokens, model.maxTokens, reasoning, options?.thinkingBudgets);
203
+ const adjusted = adjustMaxTokensForThinking(base.maxTokens, model.maxTokens ?? base.maxTokens, reasoning, options?.thinkingBudgets);
206
204
  const thinkingEnabled = adjusted.thinkingBudget >= ANTHROPIC_MIN_THINKING_BUDGET_TOKENS;
207
205
  const maxTokens = thinkingEnabled ? adjusted.maxTokens : clampMaxTokensToModel(model, options?.maxTokens ?? model.maxTokens);
208
206
  return streamAnthropic(model, context, {
@@ -342,13 +340,15 @@ async function buildParams(model, context, isOAuthTokenResult, options, serverSi
342
340
  authProfileId: options?.authProfileId,
343
341
  sessionId: options?.sessionId
344
342
  });
343
+ const cacheBreakpointOptOutMessageIndexes = /* @__PURE__ */ new Set();
345
344
  const params = {
346
345
  model: model.id,
347
346
  messages: await convertAnthropicMessages(transformProviderMessages(replayPlan.messages, model, normalizeAnthropicToolCallId), model, isOAuthTokenResult, {
348
347
  profile: "provider",
349
348
  allowEmptySignature: compat.allowEmptySignature,
350
349
  compaction: replayPlan.compaction,
351
- replayThinkingEnabled
350
+ replayThinkingEnabled,
351
+ cacheBreakpointOptOutMessageIndexes
352
352
  }),
353
353
  max_tokens: options?.maxTokens ?? model.maxTokens,
354
354
  stream: true
@@ -362,7 +362,7 @@ async function buildParams(model, context, isOAuthTokenResult, options, serverSi
362
362
  toolProjection,
363
363
  profile: "provider"
364
364
  }));
365
- applyAnthropicRequestCacheControl(params, cacheControl, supportsCacheControlOnTools);
365
+ applyAnthropicRequestCacheControl(params, cacheControl, supportsCacheControlOnTools, cacheBreakpointOptOutMessageIndexes);
366
366
  return {
367
367
  params,
368
368
  toolProjection,
@@ -1,6 +1,6 @@
1
- import "./index-CQ6LTHw8.mjs";
2
- import { D as Model } from "./types-Dy1q0CSu.mjs";
3
- import { t as AnthropicContextManagementOptions } from "./provider-options-BXr9Ec83.mjs";
1
+ import "./index-DaF2QbwS.mjs";
2
+ import { O as Model } from "./types-4_uVs5WH.mjs";
3
+ import { t as AnthropicContextManagementOptions } from "./provider-options-DprLsWh9.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. */
@@ -1,19 +1,18 @@
1
- import { _ as supportsClaudeAdaptiveThinking, b as supportsClaudeNativeXhighEffort, d as resolveClaudeModelIdentity, m as resolveClaudeOpus5ModelIdentity, u as resolveClaudeFable5ModelIdentity } from "./src-B2Q_6G8V.mjs";
1
+ import { _ as supportsClaudeAdaptiveThinking, b as supportsClaudeNativeXhighEffort, d as resolveClaudeModelIdentity, m as resolveClaudeOpus5ModelIdentity, s as bindsClaudeThinkingPrefix, u as resolveClaudeFable5ModelIdentity } from "./src-DeKjbE8I.mjs";
2
2
  import { r as appendAssistantThinking } from "./event-stream-D8PARQfL.mjs";
3
3
  import { i as normalizeOptionalLowercaseString, r as normalizeNullableString } from "./string-coerce-fsri9iCu.mjs";
4
- import { r as calculateCost, t as sanitizeSurrogates } from "./sanitize-unicode-Bb-v9meu.mjs";
5
- import { a as describeToolResultMediaPlaceholder, c as extractToolResultText, d as isImageWithMediaPayload, f as ANTHROPIC_CLAUDE_CODE_BILLING_SYSTEM_BLOCK, g as mapAnthropicStopReason, n as getAiTransportHost, s as extractToolResultBlockText, v as requiresClaudeAdaptiveThinking } from "./host-CWuF-sS3.mjs";
6
4
  import { a as asRecord, o as isRecord, r as asOptionalObjectRecord, s as readStringField } from "./record-coerce-DwRYMj3t.mjs";
7
- import { i as asNonNegativeFiniteNumber, n as estimateBase64DecodedBytes } from "./base64-D-su8YVo.mjs";
8
- import { a as parsePositiveInteger } from "./transport-utils-CCooe-cr.mjs";
9
- import { a as resolveProviderRequestCapabilities, i as resolveProviderEndpoint } from "./host-policy-CAopLRKA.mjs";
5
+ import { C as mapAnthropicStopReason, E as resolveAnthropicThinkingEffort, T as requiresClaudeAdaptiveThinking, _ as isImageWithMediaPayload, d as describeToolResultMediaPlaceholder, j as calculateCost, m as extractToolResultText, n as getAiTransportHost, p as extractToolResultBlockText, v as sanitizeSurrogates, y as ANTHROPIC_CLAUDE_CODE_BILLING_SYSTEM_BLOCK } from "./host-B4MeUNBc.mjs";
6
+ import { i as asNonNegativeFiniteNumber, n as estimateBase64DecodedBytes } from "./base64-BQOzsvUH.mjs";
7
+ import "./transport-utils-1cyq5Y7x.mjs";
8
+ import { a as resolveProviderRequestCapabilities, i as resolveProviderEndpoint } from "./host-policy-DUnXSx0I.mjs";
10
9
  import { t as resolveCacheRetention } from "./cache-retention-0x979a5V.mjs";
11
- import { d as stripSystemPromptCacheBoundary, m as sortPromptCacheToolsByName, u as splitSystemPromptCacheBoundary } from "./simple-options-tcKOqnpF.mjs";
12
- import { t as projectRuntimeToolInputSchema } from "./tool-schema-json-projection-ClptDdAO.mjs";
13
- import { _ as transportAbortError, b as parseJsonObjectPreservingUnsafeIntegers, g as sanitizeTransportPayloadText, h as sanitizeNonEmptyTransportPayloadText, n as coerceTransportToolCallArguments, s as finalizeTerminalToolCallArguments } from "./transport-stream-shared-Cu3ZPhNW.mjs";
14
- import { n as providerReplayContextMatches, t as buildProviderReplayContext } from "./provider-replay-context-BuSUaAk5.mjs";
10
+ import { f as splitSystemPromptCacheBoundary, h as stripSystemPromptRelocatableBoundary, m as stripSystemPromptCacheBoundary, v as sortPromptCacheToolsByName } from "./simple-options-C6cFWj_f.mjs";
11
+ import { t as parsePositiveInteger } from "./positive-integer-DtjCkbue.mjs";
12
+ import { n as projectRuntimeToolInputSchema } from "./tool-schema-json-projection-CD9c_fK8.mjs";
13
+ import { E as parseStreamingJson, _ as sanitizeTransportPayloadText, c as finalizeTerminalToolCallArguments, g as sanitizeNonEmptyTransportPayloadText, r as coerceTransportToolCallArguments, v as transportAbortError, w as createToolArgumentPreviewSchedule, x as parseJsonObjectPreservingUnsafeIntegers } from "./transport-stream-shared-D-6FQSHm.mjs";
14
+ import { n as providerReplayContextMatches, t as buildProviderReplayContext } from "./provider-replay-context-CnUSOwhr.mjs";
15
15
  import { i as tagPendingCommentaryText } from "./assistant-text-phase-C20rxWwP.mjs";
16
- import { r as parseStreamingJson, t as createToolArgumentPreviewSchedule } from "./json-parse-Dw_hnxsA.mjs";
17
16
  import { t as notifyLlmRequestActivity } from "./llm-request-activity-BjtkplhG.mjs";
18
17
  //#region packages/ai/src/providers/anthropic-auth-headers.ts
19
18
  /** Inspect resolved credential shape for auth routing without exposing its value. */
@@ -148,11 +147,14 @@ function applyAnthropicCacheControlToSystem(system, cacheControl) {
148
147
  continue;
149
148
  }
150
149
  const record = block;
151
- if (record.type !== "text" || typeof record.text !== "string") {
150
+ const blockText = record.text;
151
+ if (record.type !== "text" || typeof blockText !== "string") {
152
152
  normalizedBlocks.push(block);
153
153
  continue;
154
154
  }
155
- const split = splitSystemPromptCacheBoundary(record.text);
155
+ const text = stripSystemPromptRelocatableBoundary(blockText);
156
+ record.text = text;
157
+ const split = splitSystemPromptCacheBoundary(text);
156
158
  if (!split) {
157
159
  if (record.cache_control === void 0) record.cache_control = cacheControl;
158
160
  normalizedBlocks.push(record);
@@ -547,39 +549,34 @@ const schemaMapKeywords = /* @__PURE__ */ new Set([
547
549
  "patternProperties",
548
550
  "properties"
549
551
  ]);
552
+ /** Normalize the detached JSON projection and report tuple changes to enclosing schemas. */
550
553
  function normalizeAnthropicJsonSchema(schema) {
551
- if (!isRecord(schema)) return schema;
554
+ if (!isRecord(schema)) return false;
552
555
  let changed = false;
553
- const normalized = { ...schema };
554
556
  for (const [key, value] of Object.entries(schema)) {
555
557
  if (schemaValueKeywords.has(key) && !Array.isArray(value)) {
556
- const next = normalizeAnthropicJsonSchema(value);
557
- normalized[key] = next;
558
- changed ||= next !== value;
558
+ changed = normalizeAnthropicJsonSchema(value) || changed;
559
559
  continue;
560
560
  }
561
561
  if (schemaArrayKeywords.has(key) && Array.isArray(value)) {
562
- const next = value.map(normalizeAnthropicJsonSchema);
563
- normalized[key] = next;
564
- changed ||= next.some((entry, index) => entry !== value[index]);
562
+ for (const entry of value) changed = normalizeAnthropicJsonSchema(entry) || changed;
565
563
  continue;
566
564
  }
567
- if (schemaMapKeywords.has(key) && isRecord(value)) {
568
- const next = Object.fromEntries(Object.entries(value).map(([entryKey, entryValue]) => [entryKey, normalizeAnthropicJsonSchema(entryValue)]));
569
- normalized[key] = next;
570
- changed ||= Object.entries(value).some(([entryKey, entryValue]) => next[entryKey] !== entryValue);
571
- }
565
+ if (schemaMapKeywords.has(key) && isRecord(value)) for (const entry of Object.values(value)) changed = normalizeAnthropicJsonSchema(entry) || changed;
572
566
  }
573
567
  if (Array.isArray(schema.items)) {
574
- normalized.prefixItems = schema.items.map(normalizeAnthropicJsonSchema);
568
+ for (const entry of schema.items) normalizeAnthropicJsonSchema(entry);
569
+ schema.prefixItems = schema.items;
575
570
  const additionalItems = schema.additionalItems;
576
- if (typeof additionalItems === "boolean" || isRecord(additionalItems)) normalized.items = normalizeAnthropicJsonSchema(additionalItems);
577
- else delete normalized.items;
578
- delete normalized.additionalItems;
571
+ if (typeof additionalItems === "boolean" || isRecord(additionalItems)) {
572
+ normalizeAnthropicJsonSchema(additionalItems);
573
+ schema.items = additionalItems;
574
+ } else delete schema.items;
575
+ delete schema.additionalItems;
579
576
  changed = true;
580
577
  }
581
- if (changed) delete normalized.$schema;
582
- return changed ? normalized : schema;
578
+ if (changed) delete schema.$schema;
579
+ return changed;
583
580
  }
584
581
  /** Snapshots direct/custom tool descriptors before Anthropic payload construction. */
585
582
  function projectAnthropicTools(tools, toWireName) {
@@ -598,11 +595,8 @@ function projectAnthropicTools(tools, toWireName) {
598
595
  unavailableOriginalNames.add(name);
599
596
  continue;
600
597
  }
601
- const anthropicSchema = normalizeAnthropicJsonSchema(schemaProjection.schema);
602
- if (!isRecord(anthropicSchema)) {
603
- unavailableOriginalNames.add(name);
604
- continue;
605
- }
598
+ const anthropicSchema = schemaProjection.schema;
599
+ normalizeAnthropicJsonSchema(anthropicSchema);
606
600
  const properties = anthropicSchema.properties;
607
601
  const required = anthropicSchema.required;
608
602
  if (properties !== void 0 && properties !== null && !isRecord(properties) || required !== void 0 && required !== null && (!Array.isArray(required) || required.some((entry) => typeof entry !== "string"))) {
@@ -680,21 +674,23 @@ function createCompactionCapture(output, model, options) {
680
674
  const content = typeof block.content === "string" ? block.content : "";
681
675
  pending.set(index, {
682
676
  content,
683
- replayIndex
677
+ replayIndex,
678
+ ...typeof block.encrypted_content === "string" || block.encrypted_content === null ? { encryptedContent: block.encrypted_content } : {}
684
679
  });
685
680
  return true;
686
681
  },
687
682
  delta(index, delta) {
688
683
  const capture = pending.get(index);
689
684
  if (!capture || delta?.type !== "compaction_delta") return false;
690
- capture.content = typeof delta.content === "string" ? delta.content : capture.content;
685
+ if (typeof delta.content === "string") capture.content += delta.content;
686
+ if (typeof delta.encrypted_content === "string" || delta.encrypted_content === null) capture.encryptedContent = delta.encrypted_content;
691
687
  return true;
692
688
  },
693
689
  complete(index) {
694
690
  const capture = pending.get(index);
695
691
  if (!capture) return false;
696
692
  pending.delete(index);
697
- captureAnthropicCompaction(output, capture.content, capture.replayIndex, model, options);
693
+ captureAnthropicCompaction(output, capture, model, options);
698
694
  return true;
699
695
  }
700
696
  };
@@ -702,18 +698,20 @@ function createCompactionCapture(output, model, options) {
702
698
  function isAnthropicCompactionState(state) {
703
699
  if (state.v !== 1 || typeof state.data !== "string" || typeof state.provider !== "string" || typeof state.api !== "string" || typeof state.model !== "string" || typeof state.baseUrlHash !== "string" || state.sessionHash !== void 0 && typeof state.sessionHash !== "string" || state.authProfileHash !== void 0 && typeof state.authProfileHash !== "string") return false;
704
700
  if (state.type === ANTHROPIC_COMPACTION_SUPPRESSION_TYPE) return state.data === ANTHROPIC_COMPACTION_SUPPRESSION_DATA;
705
- return state.type === ANTHROPIC_COMPACTION_REPLAY_TYPE && state.data.length > 0 && (state.replayIndex === void 0 || typeof state.replayIndex === "number" && Number.isSafeInteger(state.replayIndex) && state.replayIndex >= 0);
701
+ return state.type === ANTHROPIC_COMPACTION_REPLAY_TYPE && state.data.length > 0 && (state.encryptedContent === void 0 || state.encryptedContent === null || typeof state.encryptedContent === "string") && (state.replayIndex === void 0 || typeof state.replayIndex === "number" && Number.isSafeInteger(state.replayIndex) && state.replayIndex >= 0);
706
702
  }
707
703
  function readAnthropicCompactionState(value) {
708
704
  return isRecord(value) && isAnthropicCompactionState(value) ? value : void 0;
709
705
  }
710
- function captureAnthropicCompaction(output, summary, replayIndex, model, options) {
706
+ function captureAnthropicCompaction(output, capture, model, options) {
707
+ const { content: summary, replayIndex, encryptedContent } = capture;
711
708
  const context = buildProviderReplayContext(model, options);
712
709
  if (!summary || !context.baseUrlHash || !Number.isSafeInteger(replayIndex) || replayIndex < 0) return;
713
710
  output.providerReplay = {
714
711
  v: 1,
715
712
  type: ANTHROPIC_COMPACTION_REPLAY_TYPE,
716
713
  data: summary,
714
+ ...encryptedContent !== void 0 ? { encryptedContent } : {},
717
715
  replayIndex,
718
716
  ...context,
719
717
  baseUrlHash: context.baseUrlHash
@@ -746,7 +744,8 @@ function resolveNewestAnthropicCompaction(messages, model, options) {
746
744
  return {
747
745
  owner: message,
748
746
  replayIndex: replayState.replayIndex ?? 0,
749
- summary: replayState.data
747
+ summary: replayState.data,
748
+ ...replayState.encryptedContent !== void 0 ? { encryptedContent: replayState.encryptedContent } : {}
750
749
  };
751
750
  }
752
751
  }
@@ -762,7 +761,8 @@ function buildAnthropicReplayPlan(messages, model, options) {
762
761
  }, ...messages.slice(ownerIndex + 1)],
763
762
  compaction: {
764
763
  type: "compaction",
765
- content: checkpoint.summary
764
+ content: checkpoint.summary,
765
+ ...checkpoint.encryptedContent !== void 0 ? { encrypted_content: checkpoint.encryptedContent } : {}
766
766
  }
767
767
  };
768
768
  }
@@ -772,12 +772,13 @@ function isAnthropicReplayRejection(error) {
772
772
  const record = error;
773
773
  const nested = record.error && typeof record.error === "object" && !Array.isArray(record.error) ? record.error : void 0;
774
774
  const text = [
775
+ record.errorMessage,
775
776
  record.message,
776
777
  record.code,
777
778
  nested?.message,
778
779
  nested?.code
779
780
  ].filter((value) => typeof value === "string").join(" ").toLowerCase();
780
- return (record.status === 400 || text.startsWith("http 400:")) && (text.includes("compaction") || text.includes("context_management"));
781
+ return (record.status === 400 || record.errorCode === "400" || text.startsWith("http 400:")) && (text.includes("compaction") || text.includes("context_management"));
781
782
  }
782
783
  //#endregion
783
784
  //#region packages/ai/src/internal/anthropic-inline-images.ts
@@ -856,6 +857,7 @@ async function convertContentBlocks(content, model, imageBudget, profile, isErro
856
857
  }
857
858
  async function convertAnthropicMessages(transformedMessages, model, isOAuthToken, options) {
858
859
  const params = [];
860
+ const retainRuntimeContext = bindsClaudeThinkingPrefix(model);
859
861
  const imageBudget = createAnthropicInlineImageBudget();
860
862
  const allowReasoningContentReplay = options.allowReasoningContentReplay === true;
861
863
  const replayThinkingEnabled = options.replayThinkingEnabled !== false;
@@ -867,6 +869,7 @@ async function convertAnthropicMessages(transformedMessages, model, isOAuthToken
867
869
  if (msg.role === "user") {
868
870
  if (typeof msg.content === "string") {
869
871
  if (msg.content.trim().length > 0) {
872
+ if (msg.runtimeContextCarrier && !retainRuntimeContext) options.cacheBreakpointOptOutMessageIndexes?.add(params.length);
870
873
  const userParam = {
871
874
  role: "user",
872
875
  content: sanitizeTransportPayloadText(msg.content)
@@ -892,6 +895,7 @@ async function convertAnthropicMessages(transformedMessages, model, isOAuthToken
892
895
  let filteredBlocks = !managed || model.input.includes("image") ? blocks : blocks.filter((block) => block.type !== "image");
893
896
  filteredBlocks = filteredBlocks.filter((block) => block.type !== "text" || block.text.trim().length > 0);
894
897
  if (filteredBlocks.length === 0) continue;
898
+ if (msg.runtimeContextCarrier && !retainRuntimeContext) options.cacheBreakpointOptOutMessageIndexes?.add(params.length);
895
899
  const userParam = {
896
900
  role: "user",
897
901
  content: filteredBlocks
@@ -1017,7 +1021,7 @@ function buildAnthropicGenerationParams({ model, options, tools, toolProjection,
1017
1021
  type: "adaptive",
1018
1022
  display
1019
1023
  };
1020
- const effort = options?.effort ?? (mandatoryAdaptiveThinking ? "high" : void 0);
1024
+ const effort = options?.effort ?? (mandatoryAdaptiveThinking ? resolveAnthropicThinkingEffort(model, void 0) : void 0);
1021
1025
  if (effort) params.output_config = { effort };
1022
1026
  } else params.thinking = {
1023
1027
  type: "enabled",
@@ -1238,7 +1242,9 @@ async function consumeAnthropicStream(params) {
1238
1242
  const allowReasoningContentReplay = managed && resolveProviderEndpoint(model).endpointClass === "xiaomi-native";
1239
1243
  const reasoningContentThinkingBlocks = /* @__PURE__ */ new Map();
1240
1244
  const reasoningContentTextBlocks = /* @__PURE__ */ new Map();
1245
+ let sawMessageStart = false;
1241
1246
  let sawMessageStop = false;
1247
+ let sawStopReason = false;
1242
1248
  const pendingTextEnds = [];
1243
1249
  const flushPendingTextEnds = () => {
1244
1250
  for (const event of pendingTextEnds) eventSink.push(event);
@@ -1346,6 +1352,7 @@ async function consumeAnthropicStream(params) {
1346
1352
  throw new Error(readStringField(error, "message") || "Anthropic Messages stream failed");
1347
1353
  }
1348
1354
  if (event.type === "message_start") {
1355
+ sawMessageStart = true;
1349
1356
  const message = asOptionalObjectRecord(event.message);
1350
1357
  const usage = asRecord(message?.usage);
1351
1358
  output.responseId = typeof message?.id === "string" ? message.id : void 0;
@@ -1635,6 +1642,7 @@ async function consumeAnthropicStream(params) {
1635
1642
  const delta = asOptionalObjectRecord(event.delta);
1636
1643
  const usage = asOptionalObjectRecord(event.usage);
1637
1644
  if (typeof delta?.stop_reason === "string" && delta.stop_reason) {
1645
+ sawStopReason = true;
1638
1646
  if (delta.stop_reason === "refusal") applyAnthropicRefusal(output, delta.stop_details, model.provider);
1639
1647
  else output.stopReason = mapAnthropicStopReason(delta.stop_reason);
1640
1648
  }
@@ -1648,7 +1656,8 @@ async function consumeAnthropicStream(params) {
1648
1656
  if (options.signal?.aborted) throw transportAbortError(options.signal);
1649
1657
  if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error(output.errorMessage ?? "An unknown error occurred");
1650
1658
  if ([...blockIndexes.values()].some((index) => blocks[index]?.type === "toolCall")) throw new Error("Provider completed stream with an incomplete tool call");
1651
- finalizeTerminalToolCallArguments(sealedToolCalls.map(({ block }) => block), (block) => block.partialJson && block.partialJson.length > 0 ? block.partialJson : seededToolArguments.get(block));
1659
+ if ((sawMessageStart || blocks.length > 0) && !sawMessageStop && !sawStopReason) throw new Error("Anthropic stream ended before a terminal event");
1660
+ finalizeTerminalToolCallArguments(sealedToolCalls.map(({ block }) => block), (block) => block.partialJson && block.partialJson.length > 0 ? block.partialJson : seededToolArguments.get(block), void 0, { repairStringLiterals: true });
1652
1661
  for (const sealed of sealedToolCalls) {
1653
1662
  delete sealed.block.partialJson;
1654
1663
  eventSink.push({
@@ -1,5 +1,5 @@
1
- import "./index-CQ6LTHw8.mjs";
2
- import { D as Model, J as StreamOptions, W as SimpleStreamOptions, d as Context, n as Api, q as StreamFunction, s as AssistantMessageEventStreamContract } from "./types-Dy1q0CSu.mjs";
1
+ import "./index-DaF2QbwS.mjs";
2
+ import { G as SimpleStreamOptions, J as StreamFunction, O as Model, Y as StreamOptions, d as Context, n as Api, s as AssistantMessageEventStreamContract } from "./types-4_uVs5WH.mjs";
3
3
  //#region packages/ai/src/api-registry.d.ts
4
4
  /** Runtime stream adapter signature stored in the API provider registry. */
5
5
  type ApiStreamFunction = (model: Model, context: Context, options?: StreamOptions) => AssistantMessageEventStreamContract;
@@ -1,4 +1,4 @@
1
- import { i as createEmptyTransportUsage } from "./transport-stream-shared-Cu3ZPhNW.mjs";
1
+ import { a as createEmptyTransportUsage } from "./transport-stream-shared-D-6FQSHm.mjs";
2
2
  //#region packages/ai/src/transports/assistant-output.ts
3
3
  function createAssistantOutput(model, api = model.api) {
4
4
  return {
@@ -1,9 +1,10 @@
1
1
  import { t as AssistantMessageEventStream } from "./event-stream-D8PARQfL.mjs";
2
- import { n as getAiTransportHost } from "./host-CWuF-sS3.mjs";
3
- import { n as clampOpenAIPromptCacheKey } from "./openai-prompt-cache-BI0rkM-5.mjs";
4
- import { n as buildBaseOptions } from "./simple-options-tcKOqnpF.mjs";
2
+ import { n as getAiTransportHost } from "./host-B4MeUNBc.mjs";
3
+ import { n as clampOpenAIPromptCacheKey } from "./openai-prompt-cache-1wfaIszn.mjs";
4
+ import { n as buildBaseOptions } from "./simple-options-C6cFWj_f.mjs";
5
+ import { g as resolveOpenAISimpleReasoningEffort } from "./openai-transport-params-DQeuAvBl.mjs";
5
6
  import { n as getEnvApiKey } from "./env-api-keys-bktO00EJ.mjs";
6
- import { a as resolveResponsesReasoningEffort, i as createResponsesAssistantOutput, r as convertResponsesMessages, s as runResponsesStreamLifecycle, t as applyCommonResponsesParams } from "./openai-responses-shared-ZyQEzS5i.mjs";
7
+ import { a as runResponsesStreamLifecycle, i as createResponsesAssistantOutput, r as convertResponsesMessages, t as applyCommonResponsesParams } from "./openai-responses-shared-CwsziD_m.mjs";
7
8
  import { i as resolveAzureDeploymentNameFromMap, t as isOpenAICompatibleAzureResponsesBaseUrl } from "./azure-openai-responses-client-compat-C7K7QfUE.mjs";
8
9
  import OpenAI, { AzureOpenAI } from "openai";
9
10
  //#region packages/ai/src/providers/azure-openai-responses.ts
@@ -20,9 +21,6 @@ function resolveDeploymentName(model, options) {
20
21
  deploymentMap: process.env.AZURE_OPENAI_DEPLOYMENT_NAME_MAP
21
22
  });
22
23
  }
23
- /**
24
- * Generate function for Azure OpenAI Responses API
25
- */
26
24
  const streamAzureOpenAIResponses = (model, context, options) => {
27
25
  const stream = new AssistantMessageEventStream();
28
26
  const output = createResponsesAssistantOutput(model, "azure-openai-responses");
@@ -50,11 +48,10 @@ const streamSimpleAzureOpenAIResponses = (model, context, options) => {
50
48
  if (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);
51
49
  const base = buildBaseOptions(model, options, apiKey);
52
50
  const authProfileId = options?.authProfileId;
53
- const reasoningEffort = resolveResponsesReasoningEffort(model, options?.reasoning);
54
51
  return streamAzureOpenAIResponses(model, context, {
55
52
  ...base,
56
53
  authProfileId,
57
- reasoningEffort: reasoningEffort === "max" ? "xhigh" : reasoningEffort
54
+ reasoningEffort: resolveOpenAISimpleReasoningEffort(model, options?.reasoning)
58
55
  });
59
56
  };
60
57
  function normalizeAzureBaseUrl(baseUrl) {
@@ -45,10 +45,10 @@ function parseStrictPositiveInteger(value) {
45
45
  //#region packages/media-core/src/base64.ts
46
46
  /** Estimates decoded bytes without allocating a cleaned copy of the base64 payload. */
47
47
  function estimateBase64DecodedBytes(base64) {
48
- let effectiveLen = 0;
49
- for (let i = 0; i < base64.length; i += 1) {
50
- if (base64.charCodeAt(i) <= 32) continue;
51
- effectiveLen += 1;
48
+ let effectiveLen = base64.length;
49
+ const firstWhitespace = base64.search(/[\x00-\x20]/);
50
+ if (firstWhitespace !== -1) {
51
+ for (let i = firstWhitespace; i < base64.length; i += 1) if (base64.charCodeAt(i) <= 32) effectiveLen -= 1;
52
52
  }
53
53
  if (effectiveLen === 0) return 0;
54
54
  let padding = 0;
@@ -0,0 +1,24 @@
1
+ //#region packages/ai/src/utils/credential-redaction.d.ts
2
+ type DiagnosticMediaField = {
3
+ kind: "context";
4
+ } | {
5
+ kind: "redacted";
6
+ bytes?: number;
7
+ source?: string | Uint8Array;
8
+ };
9
+ type DiagnosticProjectionPolicy = {
10
+ omitField?: (key: string) => boolean;
11
+ propertyScope?: "enumerable" | "error";
12
+ projectBinary?: (binary: Uint8Array) => unknown;
13
+ projectMedia?: (key: string, media: Extract<DiagnosticMediaField, {
14
+ kind: "redacted";
15
+ }>) => Record<string, unknown>;
16
+ };
17
+ /** Fresh records need no native-object probe while their prototype stays ordinary. */
18
+ declare function createDiagnosticRecord(): Record<string, unknown>;
19
+ declare function projectDiagnosticValue(value: unknown, policy?: DiagnosticProjectionPolicy, seen?: WeakSet<object>, mediaPayload?: boolean, state?: {
20
+ changed: boolean;
21
+ nodesRemaining: number;
22
+ }): unknown;
23
+ //#endregion
24
+ export { createDiagnosticRecord as n, projectDiagnosticValue as r, DiagnosticProjectionPolicy as t };
@@ -1,5 +1,7 @@
1
+ import { a as isProviderRefusalAssistantError } from "./diagnostics-CPeq9F7y.mjs";
1
2
  import { n as normalizeLowercaseStringOrEmpty } from "./string-coerce-fsri9iCu.mjs";
2
- import "./provider-error-C6TbKiey.mjs";
3
+ import "./provider-error-DDqw9Qda.mjs";
4
+ import { r as asFiniteNumber } from "./base64-BQOzsvUH.mjs";
3
5
  //#region packages/normalization-core/src/error-coercion.ts
4
6
  function readProperty(value, key) {
5
7
  try {
@@ -59,6 +61,7 @@ function collectNestedErrorCandidates(err) {
59
61
  readProperty(current, "reason"),
60
62
  readProperty(current, "original"),
61
63
  readProperty(current, "error"),
64
+ readProperty(current, "suppressed"),
62
65
  readProperty(current, "data")
63
66
  ];
64
67
  const errors = readProperty(current, "errors");
@@ -67,6 +70,90 @@ function collectNestedErrorCandidates(err) {
67
70
  });
68
71
  }
69
72
  //#endregion
73
+ //#region packages/ai/src/providers/openai-responses-terminal-usage.ts
74
+ /**
75
+ * Canonical mapping for terminal OpenAI Responses events.
76
+ *
77
+ * `response.completed`, `response.incomplete`, and `response.failed` are terminal and can carry
78
+ * usage, so every Responses path finalizes through the helpers here. Keeping one owner prevents
79
+ * package and managed transports from drifting on token buckets, service-tier pricing, or future
80
+ * terminal-event semantics.
81
+ */
82
+ /** A known output ceiling can resume sampling after admitted tools have settled. */
83
+ function isResponsesOutputLimitToolCallError(message) {
84
+ return message.stopReason === "error" && message.errorCode === "incomplete_tool_call" && !isProviderRefusalAssistantError(message) && message.diagnostics?.some(({ type, details }) => type === "openai_responses_terminal" && details?.eventType === "response.incomplete" && details.incompleteReason === "max_output_tokens") === true;
85
+ }
86
+ function readReportedCount(value) {
87
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
88
+ }
89
+ function readCount(value) {
90
+ return readReportedCount(value) ?? 0;
91
+ }
92
+ /**
93
+ * Split a terminal usage payload into the priced buckets.
94
+ *
95
+ * OpenAI includes cache reads and writes in `input_tokens`, so both are subtracted out of the
96
+ * billable input bucket. `total_tokens` comes from the payload, but never below the sum of the
97
+ * split buckets: proxies routinely omit it (reporting 0 would understate the turn), and a payload
98
+ * whose `cached_tokens` exceeds `input_tokens` clamps the input bucket, leaving the reported total
99
+ * short of what the buckets actually price.
100
+ */
101
+ function mapResponsesTerminalUsage(usage) {
102
+ if (!usage) return;
103
+ const cacheRead = readCount(usage.input_tokens_details?.cached_tokens);
104
+ const cacheWrite = readCount(usage.input_tokens_details?.cache_write_tokens);
105
+ const input = Math.max(0, readCount(usage.input_tokens) - cacheRead - cacheWrite);
106
+ const output = readCount(usage.output_tokens);
107
+ const bucketTotal = input + output + cacheRead + cacheWrite;
108
+ const totalTokens = Math.max(bucketTotal, readCount(usage.total_tokens));
109
+ const reportedInput = readReportedCount(usage.input_tokens);
110
+ const reportedOutput = readReportedCount(usage.output_tokens);
111
+ const reportedTotal = readReportedCount(usage.total_tokens);
112
+ return {
113
+ input,
114
+ output,
115
+ cacheRead,
116
+ cacheWrite,
117
+ contextUsage: reportedInput !== void 0 && (reportedOutput !== void 0 || reportedTotal !== void 0 && reportedTotal >= reportedInput) && cacheRead + cacheWrite <= reportedInput ? {
118
+ state: "available",
119
+ promptTokens: reportedInput,
120
+ totalTokens: Math.max(totalTokens, reportedInput + (reportedOutput ?? 0))
121
+ } : { state: "unavailable" },
122
+ totalTokens
123
+ };
124
+ }
125
+ /** Reasoning tokens are reported by the agent path only; the package path does not track them. */
126
+ function readResponsesReasoningTokens(usage) {
127
+ return asFiniteNumber(usage?.output_tokens_details?.reasoning_tokens);
128
+ }
129
+ function mapResponsesTerminalStopReason(status) {
130
+ if (!status) return "stop";
131
+ switch (status) {
132
+ case "completed": return "stop";
133
+ case "incomplete": return "length";
134
+ case "failed":
135
+ case "cancelled": return "error";
136
+ case "in_progress":
137
+ case "queued": return "stop";
138
+ default: throw new Error(`Unhandled stop reason: ${String(status)}`);
139
+ }
140
+ }
141
+ /**
142
+ * Resolve the terminal stop reason, including the two overrides every Responses path shares: a
143
+ * content-filtered turn is a provider error rather than a truncated answer, and a turn that
144
+ * produced tool calls reports `toolUse` instead of a plain stop.
145
+ */
146
+ function resolveResponsesTerminalStopReason(params) {
147
+ const status = params.status ?? (params.terminalEventType === "response.incomplete" ? "incomplete" : void 0);
148
+ if (status === "incomplete" && params.incompleteReason === "content_filter") return {
149
+ stopReason: "error",
150
+ errorMessage: "Provider incomplete_reason: content_filter"
151
+ };
152
+ const stopReason = mapResponsesTerminalStopReason(status);
153
+ if (stopReason === "stop" && params.hasToolCall) return { stopReason: "toolUse" };
154
+ return { stopReason };
155
+ }
156
+ //#endregion
70
157
  //#region packages/ai/src/utils/retryable-network-errors.ts
71
158
  const WEBSOCKET_NON_RETRYABLE_CLOSE_ERROR_CODE = "ERR_WEBSOCKET_NON_RETRYABLE_CLOSE";
72
159
  const TRANSIENT_NETWORK_CODES = /* @__PURE__ */ new Set([
@@ -208,4 +295,4 @@ function formatModelTransportDebugBaseUrl(rawUrl) {
208
295
  return rawUrl ? formatModelTransportDebugUrl(rawUrl) : "default";
209
296
  }
210
297
  //#endregion
211
- export { resolveModelSseDebugMode as a, isTransientNetworkError as c, resolveModelPayloadDebugMode as i, extractErrorCodeOrErrno as l, formatModelTransportDebugUrl as n, WEBSOCKET_NON_RETRYABLE_CLOSE_ERROR_CODE as o, emitModelTransportDebug as r, hasRetryableConnectionErrorCode as s, formatModelTransportDebugBaseUrl as t, toErrorObject as u };
298
+ export { resolveModelSseDebugMode as a, isTransientNetworkError as c, readResponsesReasoningTokens as d, resolveResponsesTerminalStopReason as f, resolveModelPayloadDebugMode as i, isResponsesOutputLimitToolCallError as l, toErrorObject as m, formatModelTransportDebugUrl as n, WEBSOCKET_NON_RETRYABLE_CLOSE_ERROR_CODE as o, extractErrorCodeOrErrno as p, emitModelTransportDebug as r, hasRetryableConnectionErrorCode as s, formatModelTransportDebugBaseUrl as t, mapResponsesTerminalUsage as u };
@@ -1,31 +1,12 @@
1
- import { a as extractDiagnosticError, i as createAssistantMessageDiagnostic, n as DiagnosticErrorInfo, o as formatThrownValue, r as appendAssistantMessageDiagnostic, s as isProviderRefusalAssistantError, t as AssistantMessageDiagnostic } from "./diagnostics-DnPnOui6.mjs";
1
+ import { dt as DiagnosticErrorInfo, ft as appendAssistantMessageDiagnostic, gt as isProviderRefusalAssistantError, ht as formatThrownValue, mt as extractDiagnosticError, pt as createAssistantMessageDiagnostic, ut as AssistantMessageDiagnostic } from "./types-4_uVs5WH.mjs";
2
+ import { n as isResponsesOutputLimitToolCallError } from "./openai-responses-terminal-usage-Dl3J6zrf.mjs";
2
3
  import { n as ProviderErrorRedactor, r as configureProviderErrorRedactor } from "./provider-error-CzNw4BWX.mjs";
4
+ import { r as projectDiagnosticValue, t as DiagnosticProjectionPolicy } from "./credential-redaction-BKv49aiv.mjs";
3
5
  import { n as formatModelTransportDebugUrl, r as emitModelTransportDebug, t as formatModelTransportDebugBaseUrl } from "./model-transport-url-DKocrEsb.mjs";
4
- //#region packages/ai/src/utils/credential-redaction.d.ts
5
- type DiagnosticMediaField = {
6
- kind: "context";
7
- } | {
8
- kind: "redacted";
9
- bytes?: number;
10
- source?: string | Uint8Array;
11
- };
12
- type DiagnosticProjectionPolicy = {
13
- omitField?: (key: string) => boolean;
14
- propertyScope?: "enumerable" | "error";
15
- projectBinary?: (binary: Uint8Array) => unknown;
16
- projectMedia?: (key: string, media: Extract<DiagnosticMediaField, {
17
- kind: "redacted";
18
- }>) => Record<string, unknown>;
19
- };
20
- export declare function projectDiagnosticValue(value: unknown, policy?: DiagnosticProjectionPolicy, seen?: WeakSet<object>, mediaPayload?: boolean, state?: {
21
- changed: boolean;
22
- nodesRemaining: number;
23
- }): unknown;
24
- //#endregion
25
6
  //#region packages/ai/src/utils/retryable-network-errors.d.ts
26
7
  export declare const WEBSOCKET_NON_RETRYABLE_CLOSE_ERROR_CODE = "ERR_WEBSOCKET_NON_RETRYABLE_CLOSE";
27
8
  export declare function hasRetryableConnectionErrorCode(message: string): boolean;
28
9
  /** Returns true when any nested error proves a transient network failure. */
29
10
  export declare function isTransientNetworkError(err: unknown): boolean;
30
11
  //#endregion
31
- export { AssistantMessageDiagnostic, DiagnosticErrorInfo, type DiagnosticProjectionPolicy, type ProviderErrorRedactor, appendAssistantMessageDiagnostic, configureProviderErrorRedactor, createAssistantMessageDiagnostic, emitModelTransportDebug, extractDiagnosticError, formatModelTransportDebugBaseUrl, formatModelTransportDebugUrl, formatThrownValue, isProviderRefusalAssistantError };
12
+ export { AssistantMessageDiagnostic, DiagnosticErrorInfo, type DiagnosticProjectionPolicy, type ProviderErrorRedactor, appendAssistantMessageDiagnostic, configureProviderErrorRedactor, createAssistantMessageDiagnostic, emitModelTransportDebug, extractDiagnosticError, formatModelTransportDebugBaseUrl, formatModelTransportDebugUrl, formatThrownValue, isProviderRefusalAssistantError, isResponsesOutputLimitToolCallError, projectDiagnosticValue };