@openclaw/ai 2026.8.1-beta.1 → 2026.8.1-beta.3

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 (88) hide show
  1. package/dist/{anthropic-CE-7SkF6.mjs → anthropic-B8KwTtlb.mjs} +62 -37
  2. package/dist/{anthropic-SrGtwsJu.d.mts → anthropic-BECQCNdF.d.mts} +0 -2
  3. package/dist/{src-QkygScBs.mjs → anthropic-BQXQudmA.mjs} +0 -2
  4. package/dist/{anthropic-usage-Ma4iX6uG.mjs → anthropic-compaction-replay-4Zx7-aCr.mjs} +225 -103
  5. package/dist/anthropic-payload-policy-CSx7MoKH.d.mts +50 -0
  6. package/dist/{api-registry-EpJoVwM1.d.mts → api-registry-DFxSnFqG.d.mts} +1 -1
  7. package/dist/{azure-openai-responses-Cc_kasye.mjs → azure-openai-responses-Aa4mVcYG.mjs} +23 -29
  8. package/dist/diagnostics.d.mts +24 -1
  9. package/dist/diagnostics.mjs +2 -1
  10. package/dist/event-stream-BVVgDSdq.d.mts +1 -0
  11. package/dist/{event-stream-DRmDMRHH.d.mts → event-stream-D91-ohD_.d.mts} +3 -1
  12. package/dist/{event-stream-CEV9t6da.mjs → event-stream-uSMZJ3FA.mjs} +16 -3
  13. package/dist/event-stream.d.mts +1 -1
  14. package/dist/event-stream.mjs +1 -1
  15. package/dist/{google-shared-Cq2UKx1l.mjs → google-shared-M1dl64nz.mjs} +17 -19
  16. package/dist/google-thinking-level-C-V3tecN.mjs +9 -0
  17. package/dist/{google-vertex-CusxWzvE.mjs → google-vertex-DCJHM_a5.mjs} +5 -4
  18. package/dist/{google-CGQu21aw.mjs → google-yDRnipeq.mjs} +4 -4
  19. package/dist/host-DF_yxOsA.mjs +477 -0
  20. package/dist/{host-Dn4_SZI2.d.mts → host-DJq_FGcz.d.mts} +13 -8
  21. package/dist/index.d.mts +7 -7
  22. package/dist/index.mjs +7 -5
  23. package/dist/internal/anthropic.d.mts +21 -7
  24. package/dist/internal/anthropic.mjs +5 -5
  25. package/dist/internal/openai-responses-payload-policy.d.mts +3 -0
  26. package/dist/internal/openai-responses-payload-policy.mjs +3 -0
  27. package/dist/internal/openai.d.mts +6 -6
  28. package/dist/internal/openai.mjs +9 -7
  29. package/dist/internal/runtime.d.mts +19 -5
  30. package/dist/internal/runtime.mjs +85 -72
  31. package/dist/internal/shared.d.mts +17 -8
  32. package/dist/internal/shared.mjs +4 -5
  33. package/dist/{json-parse-BvXNt1-7.mjs → json-parse-CDnesDM_.mjs} +4 -6
  34. package/dist/{mistral-Dx6VzNjf.mjs → mistral-D6hRXI7A.mjs} +67 -72
  35. package/dist/{number-coercion-1Miyb5MO.mjs → number-coercion-H9qHik3g.mjs} +7 -2
  36. package/dist/openai-chatgpt-jwt-KWcgd0d_.mjs +19 -0
  37. package/dist/{openai-chatgpt-responses-SC9m0FSf.mjs → openai-chatgpt-responses-C339VIfT.mjs} +235 -146
  38. package/dist/{openai-completions-BaIpl93j.mjs → openai-completions-D88orSJ9.mjs} +88 -67
  39. package/dist/openai-completions-compat-B0KTleXp.d.mts +43 -0
  40. package/dist/{openai-responses-Bdx3V_Yu.mjs → openai-responses-BXEcr-Tp.mjs} +17 -24
  41. package/dist/openai-responses-contracts-CD75pQ0m.d.mts +68 -0
  42. package/dist/openai-responses-contracts-DvILoqBk.mjs +247 -0
  43. package/dist/openai-responses-payload-policy-BDo8CQsx.mjs +208 -0
  44. package/dist/openai-responses-payload-policy-CNGFT9zr.d.mts +41 -0
  45. package/dist/{openai-responses-prompt-observer-internal-DDZPxRfr.mjs → openai-responses-prompt-observer-internal-BG-1AsBI.mjs} +2 -3
  46. package/dist/{openai-responses-stream-internal-Bl8YyVtF.mjs → openai-responses-shared-Cvt5MgEm.mjs} +1287 -1039
  47. package/dist/{openai-reasoning-compat-DKebnIBL.mjs → openai-stop-reason-9OONKyAm.mjs} +222 -180
  48. package/dist/{openai-transport-shared-Cipt7egQ.mjs → openai-tool-projection-CHGLt03m.mjs} +239 -128
  49. package/dist/provider-error-C8mBRJDl.mjs +424 -0
  50. package/dist/provider-error-CzNw4BWX.d.mts +12 -0
  51. package/dist/provider-options-AvldWZt8.mjs +21 -0
  52. package/dist/{provider-options-C5kYML7i.d.mts → provider-options-Cc5ZQ6Aa.d.mts} +19 -3
  53. package/dist/provider-transcript-transform--gtf0ZbR.mjs +32 -0
  54. package/dist/provider-types.d.mts +31 -0
  55. package/dist/provider-types.mjs +8 -0
  56. package/dist/providers.d.mts +1 -1
  57. package/dist/providers.mjs +17 -19
  58. package/dist/{reasoning-tag-text-partitioner-CGDyLWUR.mjs → reasoning-tag-text-partitioner-5ygO2rZc.mjs} +17 -8
  59. package/dist/record-coerce-DdXsgUd_.mjs +23 -0
  60. package/dist/{model-utils-Dau5dlgm.mjs → sanitize-unicode-BP7HLLZn.mjs} +28 -2
  61. package/dist/session-resources-CkR4WWy1.mjs +21 -0
  62. package/dist/simple-options-oqsXB6U3.mjs +450 -0
  63. package/dist/src-D2H6yKkH.mjs +2 -0
  64. package/dist/{stream-first-event-timeout-BIBomOGq.mjs → stream-first-event-timeout-MK28puvq.mjs} +2 -2
  65. package/dist/string-coerce-fsri9iCu.mjs +34 -0
  66. package/dist/{tool-schema-json-projection-B1b-XCn5.mjs → tool-schema-json-projection-FEr-jOoZ.mjs} +20 -13
  67. package/dist/transport-utils-Bv0FHkd0.mjs +138 -0
  68. package/dist/transports.d.mts +199 -209
  69. package/dist/transports.mjs +1842 -1364
  70. package/dist/types-BDdaOVi2.mjs +6 -0
  71. package/dist/{types-CH7ReIcU.d.mts → types-DTAP49HF.d.mts} +35 -2
  72. package/dist/types.d.mts +5 -5
  73. package/dist/types.mjs +6 -4
  74. package/dist/utf16-slice-CvGodqok.mjs +29 -0
  75. package/dist/{validation-DAa_yFOM.mjs → validation-B61OhAio.mjs} +6 -6
  76. package/dist/{validation-CcPcuEbR.d.mts → validation-DYNNrU9u.d.mts} +1 -1
  77. package/dist/validation.d.mts +1 -1
  78. package/dist/validation.mjs +1 -1
  79. package/package.json +15 -1
  80. package/dist/host-Bl7Kgddo.mjs +0 -407
  81. package/dist/openai-chatgpt-jwt-DhAAzLkj.mjs +0 -39
  82. package/dist/openai-responses-contracts-BBKBfAqR.d.mts +0 -116
  83. package/dist/openai-responses-shared-CCyMvg7M.mjs +0 -403
  84. package/dist/provider-error-DI0Ts28U.mjs +0 -47
  85. package/dist/sanitize-unicode-DT5o51ur.mjs +0 -26
  86. package/dist/tool-result-text-Dvkp2Dus.mjs +0 -274
  87. package/dist/transform-messages-DfjpNXNQ.mjs +0 -2
  88. package/dist/transport-stream-shared-CPNv7A3r.mjs +0 -297
@@ -1,20 +1,19 @@
1
1
  import { n as getEnvApiKey, r as __exportAll } from "./env-api-keys-DrgeBuva.mjs";
2
- import { d as resolveClaudeSonnet5ModelIdentity, g as supportsClaudeNativeXhighEffort, p as supportsClaudeAdaptiveThinking, u as resolveClaudeOpus5ModelIdentity } from "./src-QkygScBs.mjs";
3
- import { t as AssistantMessageEventStream } from "./event-stream-CEV9t6da.mjs";
4
- import { a as ANTHROPIC_CLAUDE_CODE_BILLING_SYSTEM_BLOCK, d as requiresClaudeAdaptiveThinking, f as resolveAnthropicThinkingEffort, h as usesClaudeStreamingRefusalContract, i as transformMessages, l as mapAnthropicStopReason, m as usesClaudeFable5MessagesContract, n as getAiTransportHost, o as ANTHROPIC_CLAUDE_CODE_VERSION, r as resolveAiTransportHeaderSentinels, s as applyClaudeRequestContract, u as prepareClaudeNoPrefillRequestContext } from "./host-Bl7Kgddo.mjs";
5
- import { n as calculateCost } from "./model-utils-Dau5dlgm.mjs";
2
+ import { d as resolveClaudeSonnet5ModelIdentity, g as supportsClaudeNativeXhighEffort, p as supportsClaudeAdaptiveThinking, u as resolveClaudeOpus5ModelIdentity } from "./anthropic-BQXQudmA.mjs";
3
+ import { t as AssistantMessageEventStream } from "./event-stream-uSMZJ3FA.mjs";
4
+ import { r as calculateCost, t as sanitizeSurrogates } from "./sanitize-unicode-BP7HLLZn.mjs";
5
+ import { S as usesClaudeStreamingRefusalContract, _ as prepareClaudeNoPrefillRequestContext, a as describeToolResultMediaPlaceholder, c as extractToolResultText, d as isImageWithMediaPayload, f as ANTHROPIC_CLAUDE_CODE_BILLING_SYSTEM_BLOCK, g as mapAnthropicStopReason, m as applyClaudeRequestContract, n as getAiTransportHost, p as ANTHROPIC_CLAUDE_CODE_VERSION, r as resolveAiTransportHeaderSentinels, s as extractToolResultBlockText, v as requiresClaudeAdaptiveThinking, x as usesClaudeFable5MessagesContract, y as resolveAnthropicThinkingEffort } from "./host-DF_yxOsA.mjs";
6
+ import { a as isRecord } from "./record-coerce-DdXsgUd_.mjs";
7
+ import { n as projectProviderError } from "./provider-error-C8mBRJDl.mjs";
6
8
  import { t as resolveCacheRetention } from "./cache-retention-0x979a5V.mjs";
7
- import { t as sanitizeSurrogates } from "./sanitize-unicode-DT5o51ur.mjs";
8
- import { a as isImageWithMediaPayload, c as buildBaseOptions, h as stripSystemPromptCacheBoundary, l as clampMaxTokensToModel, m as splitSystemPromptCacheBoundary, n as extractToolResultBlockText, r as extractToolResultText, s as adjustMaxTokensForThinking, t as describeToolResultMediaPlaceholder } from "./tool-result-text-Dvkp2Dus.mjs";
9
- import { C as usesFoundryBearerAuth, E as resolveAnthropicImageMediaType, O as applyAnthropicCacheControlToMessages, S as omitFoundryBearerCredentialHeaders, T as normalizeAnthropicInlineContent, b as resolveAnthropicFallbackServingModelCost, c as normalizeAnthropicToolChoice, d as resolveOriginalAnthropicToolName, f as toClaudeCodeToolName, g as ANTHROPIC_SERVER_SIDE_FALLBACK_BETA, h as ANTHROPIC_SERVER_SIDE_FALLBACKS, l as projectAnthropicTools, m as findActiveAnthropicToolTurnAssistantIndex, n as applyAnthropicMessageStartUsage, p as ANTHROPIC_OMITTED_REASONING_TEXT, s as normalizeAnthropicToolCallId, t as applyAnthropicMessageDeltaUsage, u as reconcileAnthropicToolChoice, v as applyAnthropicFallbackBoundary, w as createAnthropicInlineImageBudget, x as applyAnthropicRefusal, y as readAnthropicFallbackBoundary } from "./anthropic-usage-Ma4iX6uG.mjs";
9
+ import { A as splitSystemPromptCacheBoundary, d as finalizeTerminalToolCallArguments, g as notifyProviderHttpResponse, j as stripSystemPromptCacheBoundary, n as buildBaseOptions, r as clampMaxTokensToModel, t as adjustMaxTokensForThinking, x as transportAbortError } from "./simple-options-oqsXB6U3.mjs";
10
+ import { A as resolveAnthropicImageMediaType, C as readAnthropicFallbackBoundary, D as usesFoundryBearerAuth, E as omitFoundryBearerCredentialHeaders, O as createAnthropicInlineImageBudget, S as applyAnthropicFallbackBoundary, T as applyAnthropicRefusal, _ as ANTHROPIC_OMITTED_REASONING_TEXT, a as applyAnthropicMessageDeltaUsage, b as ANTHROPIC_SERVER_SIDE_FALLBACK_BETA, d as normalizeAnthropicToolCallId, f as normalizeAnthropicToolChoice, g as toClaudeCodeToolName, h as resolveOriginalAnthropicToolName, i as suppressAnthropicCompaction, j as applyAnthropicCacheControlToMessages, k as normalizeAnthropicInlineContent, m as reconcileAnthropicToolChoice, n as createCompactionCapture, o as applyAnthropicMessageStartUsage, p as projectAnthropicTools, r as isAnthropicReplayRejection, t as buildAnthropicReplayPlan, v as findActiveAnthropicToolTurnAssistantIndex, w as resolveAnthropicFallbackServingModelCost, y as ANTHROPIC_SERVER_SIDE_FALLBACKS } from "./anthropic-compaction-replay-4Zx7-aCr.mjs";
10
11
  import { t as createDeferredEventBuffer } from "./deferred-event-buffer-DAvyP7qA.mjs";
11
- import { n as parseStreamingJson, t as parseJsonWithRepair } from "./json-parse-BvXNt1-7.mjs";
12
+ import { n as parseStreamingJson, t as parseJsonWithRepair } from "./json-parse-CDnesDM_.mjs";
12
13
  import { t as notifyLlmRequestActivity } from "./llm-request-activity-BjtkplhG.mjs";
13
- import { d as transportAbortError, f as MALFORMED_STREAMING_FRAGMENT_ERROR_MESSAGE } from "./transport-stream-shared-CPNv7A3r.mjs";
14
- import { t as headersToRecord } from "./headers-B_e4-1J0.mjs";
15
- import { t as formatProviderError } from "./provider-error-DI0Ts28U.mjs";
14
+ import { t as MALFORMED_STREAMING_FRAGMENT_ERROR_MESSAGE } from "./transport-utils-Bv0FHkd0.mjs";
15
+ import { t as transformProviderMessages } from "./provider-transcript-transform--gtf0ZbR.mjs";
16
16
  import { i as resolveCloudflareBaseUrl, n as hasCopilotVisionInput, t as buildCopilotDynamicHeaders } from "./github-copilot-headers-NCJtz9i0.mjs";
17
- import "./transform-messages-DfjpNXNQ.mjs";
18
17
  import Anthropic from "@anthropic-ai/sdk";
19
18
  import { Stream } from "@anthropic-ai/sdk/core/streaming.js";
20
19
  //#region packages/ai/src/providers/anthropic.ts
@@ -159,6 +158,7 @@ const streamAnthropic = (model, context, options) => {
159
158
  const eventSink = refusalBuffer ?? stream;
160
159
  let costModel = model;
161
160
  let messageStartPromptUsage;
161
+ let usedCompactionReplay = false;
162
162
  try {
163
163
  let client;
164
164
  let isOAuth;
@@ -183,6 +183,7 @@ const streamAnthropic = (model, context, options) => {
183
183
  serverSideFallback = created.serverSideFallback;
184
184
  }
185
185
  const builtParams = await buildParams(model, requestContext, isOAuth, requestOptions, serverSideFallback);
186
+ usedCompactionReplay = builtParams.usedCompactionReplay;
186
187
  let params = builtParams.params;
187
188
  const toolProjection = builtParams.toolProjection;
188
189
  const nextParams = await requestOptions?.onPayload?.(params, model);
@@ -197,12 +198,15 @@ const streamAnthropic = (model, context, options) => {
197
198
  ...params,
198
199
  stream: true
199
200
  }, sdkRequestOptions).asResponse();
200
- await requestOptions?.onResponse?.({
201
- status: response.status,
202
- headers: headersToRecord(response.headers)
203
- }, model);
201
+ await notifyProviderHttpResponse({
202
+ options: requestOptions,
203
+ response,
204
+ model
205
+ });
204
206
  const blocks = output.content;
205
207
  const blockIndexes = /* @__PURE__ */ new Map();
208
+ const sealedToolCalls = [];
209
+ const compactionCapture = createCompactionCapture(output, model, requestOptions);
206
210
  for await (const event of iterateAnthropicEvents(response, refusalBuffer !== void 0)) if (event.type === "message_start") {
207
211
  output.responseId = event.message.id;
208
212
  output.responseModel = event.message.model;
@@ -213,9 +217,12 @@ const streamAnthropic = (model, context, options) => {
213
217
  partial: output
214
218
  });
215
219
  } else if (event.type === "content_block_start") {
220
+ const rawContentBlock = isRecord(event.content_block) ? event.content_block : void 0;
221
+ if (requestOptions?.anthropicServerCompaction === true && compactionCapture.begin(event.index, rawContentBlock, output.content.length)) continue;
216
222
  const fallbackBoundary = refusalBuffer ? readAnthropicFallbackBoundary(event.content_block) : null;
217
223
  if (fallbackBoundary) {
218
224
  refusalBuffer?.discard();
225
+ sealedToolCalls.length = 0;
219
226
  blockIndexes.clear();
220
227
  applyAnthropicFallbackBoundary({
221
228
  output,
@@ -316,7 +323,9 @@ const streamAnthropic = (model, context, options) => {
316
323
  });
317
324
  }
318
325
  } else if (event.type === "content_block_delta") {
319
- if (event.delta.type === "text_delta") {
326
+ const rawDelta = isRecord(event.delta) ? event.delta : void 0;
327
+ if (compactionCapture.delta(event.index, rawDelta)) continue;
328
+ else if (event.delta.type === "text_delta") {
320
329
  const index = blockIndexes.get(event.index);
321
330
  const block = index === void 0 ? void 0 : blocks[index];
322
331
  if (index !== void 0 && block?.type === "text") {
@@ -344,7 +353,7 @@ const streamAnthropic = (model, context, options) => {
344
353
  const index = blockIndexes.get(event.index);
345
354
  const block = index === void 0 ? void 0 : blocks[index];
346
355
  if (index !== void 0 && block?.type === "toolCall") {
347
- block.partialJson += event.delta.partial_json;
356
+ block.partialJson = (block.partialJson ?? "") + event.delta.partial_json;
348
357
  block.arguments = parseStreamingJson(block.partialJson);
349
358
  eventSink.push({
350
359
  type: "toolcall_delta",
@@ -362,6 +371,7 @@ const streamAnthropic = (model, context, options) => {
362
371
  }
363
372
  }
364
373
  } else if (event.type === "content_block_stop") {
374
+ if (compactionCapture.complete(event.index)) continue;
365
375
  const index = blockIndexes.get(event.index);
366
376
  const block = index === void 0 ? void 0 : blocks[index];
367
377
  if (index !== void 0 && block) {
@@ -379,16 +389,10 @@ const streamAnthropic = (model, context, options) => {
379
389
  content: block.thinking,
380
390
  partial: output
381
391
  });
382
- else if (block.type === "toolCall") {
383
- block.arguments = parseStreamingJson(block.partialJson);
384
- delete block.partialJson;
385
- eventSink.push({
386
- type: "toolcall_end",
387
- contentIndex: index,
388
- toolCall: block,
389
- partial: output
390
- });
391
- }
392
+ else if (block.type === "toolCall") sealedToolCalls.push({
393
+ block,
394
+ contentIndex: index
395
+ });
392
396
  }
393
397
  } else if (event.type === "message_delta") {
394
398
  if (event.delta.stop_reason) if (event.delta.stop_reason === "refusal") applyAnthropicRefusal(output, event.delta.stop_details, model.provider);
@@ -398,6 +402,17 @@ const streamAnthropic = (model, context, options) => {
398
402
  }
399
403
  if (requestOptions?.signal?.aborted) throw transportAbortError(requestOptions.signal);
400
404
  if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error(output.errorMessage ?? "An unknown error occurred");
405
+ if ([...blockIndexes.values()].some((index) => blocks[index]?.type === "toolCall")) throw new Error("Provider completed stream with an incomplete tool call");
406
+ finalizeTerminalToolCallArguments(sealedToolCalls.map(({ block }) => block), (block) => block.partialJson && block.partialJson.length > 0 ? block.partialJson : block.arguments);
407
+ for (const sealed of sealedToolCalls) {
408
+ delete sealed.block.partialJson;
409
+ eventSink.push({
410
+ type: "toolcall_end",
411
+ contentIndex: sealed.contentIndex,
412
+ toolCall: sealed.block,
413
+ partial: output
414
+ });
415
+ }
401
416
  refusalBuffer?.flush();
402
417
  stream.push({
403
418
  type: "done",
@@ -406,6 +421,7 @@ const streamAnthropic = (model, context, options) => {
406
421
  });
407
422
  stream.end();
408
423
  } catch (error) {
424
+ output.content = output.content.filter((block) => block.type !== "toolCall");
409
425
  for (const block of output.content) {
410
426
  delete block.index;
411
427
  delete block.partialJson;
@@ -414,11 +430,12 @@ const streamAnthropic = (model, context, options) => {
414
430
  refusalBuffer.discard();
415
431
  output.content = [];
416
432
  }
417
- output.stopReason = requestOptions?.signal?.aborted ? "aborted" : "error";
418
- output.errorMessage = formatProviderError(error);
433
+ if (usedCompactionReplay && isAnthropicReplayRejection(error)) suppressAnthropicCompaction(output, model, requestOptions);
434
+ const terminal = projectProviderError(error, requestOptions?.signal);
435
+ Object.assign(output, terminal);
419
436
  stream.push({
420
437
  type: "error",
421
- reason: output.stopReason,
438
+ reason: terminal.stopReason,
422
439
  error: output
423
440
  });
424
441
  stream.end();
@@ -442,6 +459,8 @@ const streamSimpleAnthropic = (model, context, options) => {
442
459
  if (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);
443
460
  const base = {
444
461
  ...buildBaseOptions(model, options, apiKey),
462
+ anthropicServerCompaction: options?.anthropicServerCompaction,
463
+ authProfileId: options?.authProfileId,
445
464
  maxTokens: clampMaxTokensToModel(model, options?.maxTokens ?? model.maxTokens),
446
465
  toolChoice: options?.toolChoice
447
466
  };
@@ -612,9 +631,14 @@ async function buildParams(model, context, isOAuthTokenResult, options, serverSi
612
631
  const systemCacheControlCount = countNativeCacheControlMarkers(system);
613
632
  const toolCacheControlCount = countNativeCacheControlMarkers(tools);
614
633
  const messageCacheControlLimit = Math.max(0, ANTHROPIC_CACHE_CONTROL_LIMIT - systemCacheControlCount - toolCacheControlCount);
634
+ const replayPlan = buildAnthropicReplayPlan(context.messages, model, {
635
+ enabled: !isOAuthTokenResult && options?.anthropicServerCompaction === true,
636
+ authProfileId: options?.authProfileId,
637
+ sessionId: options?.sessionId
638
+ });
615
639
  const params = {
616
640
  model: model.id,
617
- messages: await convertMessages(context.messages, model, isOAuthTokenResult, cacheControl, messageCacheControlLimit, replayThinkingEnabled, compat.allowEmptySignature),
641
+ messages: await convertMessages(replayPlan.messages, model, isOAuthTokenResult, cacheControl, messageCacheControlLimit, replayThinkingEnabled, compat.allowEmptySignature, replayPlan.compaction),
618
642
  max_tokens: options?.maxTokens ?? model.maxTokens,
619
643
  stream: true
620
644
  };
@@ -632,7 +656,7 @@ async function buildParams(model, context, isOAuthTokenResult, options, serverSi
632
656
  display
633
657
  };
634
658
  const effort = options?.effort ?? (mandatoryAdaptiveThinking ? "high" : void 0);
635
- if (effort) params.output_config = effort === "xhigh" ? { effort } : { effort };
659
+ if (effort) params.output_config = { effort };
636
660
  } else params.thinking = {
637
661
  type: "enabled",
638
662
  budget_tokens: options?.thinkingBudgetTokens ?? ANTHROPIC_MIN_THINKING_BUDGET_TOKENS,
@@ -651,14 +675,15 @@ async function buildParams(model, context, isOAuthTokenResult, options, serverSi
651
675
  }
652
676
  return {
653
677
  params,
654
- toolProjection
678
+ toolProjection,
679
+ usedCompactionReplay: replayPlan.compaction !== void 0
655
680
  };
656
681
  }
657
- async function convertMessages(messages, model, isOAuthTokenValue, cacheControl, messageCacheControlLimit = 4, replayThinkingEnabled = true, allowEmptySignature = false) {
682
+ async function convertMessages(messages, model, isOAuthTokenValue, cacheControl, messageCacheControlLimit = 4, replayThinkingEnabled = true, allowEmptySignature = false, compaction) {
658
683
  const params = [];
659
684
  const imageBudget = createAnthropicInlineImageBudget();
660
685
  const cacheBreakpointOptOutParamIndexes = /* @__PURE__ */ new Set();
661
- const transformedMessages = transformMessages(messages, model, normalizeAnthropicToolCallId);
686
+ const transformedMessages = transformProviderMessages(messages, model, normalizeAnthropicToolCallId);
662
687
  const activeToolTurnAssistantIndex = replayThinkingEnabled ? -1 : findActiveAnthropicToolTurnAssistantIndex(transformedMessages);
663
688
  for (let i = 0; i < transformedMessages.length; i++) {
664
689
  const msg = transformedMessages[i];
@@ -699,7 +724,7 @@ async function convertMessages(messages, model, isOAuthTokenValue, cacheControl,
699
724
  });
700
725
  }
701
726
  } else if (msg.role === "assistant") {
702
- const blocks = [];
727
+ const blocks = i === 0 && compaction ? [compaction] : [];
703
728
  let omittedThinking = false;
704
729
  for (const block of msg.content) if (block.type === "text") {
705
730
  if (block.text.trim().length === 0) continue;
@@ -8,8 +8,6 @@ type ClaudeEffortModelRef = ClaudeModelRef & {
8
8
  };
9
9
  declare const CLAUDE_FABLE_5_THINKING_PROFILE: {
10
10
  readonly levels: readonly [{
11
- readonly id: "off";
12
- }, {
13
11
  readonly id: "minimal";
14
12
  }, {
15
13
  readonly id: "low";
@@ -1,4 +1,3 @@
1
- import "./validation-DAa_yFOM.mjs";
2
1
  //#region packages/llm-core/src/model-contracts/anthropic.ts
3
2
  function normalizeClaudeModelId(modelId) {
4
3
  const normalized = modelId?.trim().toLowerCase() ?? "";
@@ -6,7 +5,6 @@ function normalizeClaudeModelId(modelId) {
6
5
  }
7
6
  const CLAUDE_FABLE_5_THINKING_PROFILE = {
8
7
  levels: [
9
- { id: "off" },
10
8
  { id: "minimal" },
11
9
  { id: "low" },
12
10
  { id: "medium" },
@@ -1,8 +1,13 @@
1
- import { o as resolveClaudeFable5ModelIdentity, s as resolveClaudeModelIdentity, u as resolveClaudeOpus5ModelIdentity } from "./src-QkygScBs.mjs";
2
- import { b as isRecord, n as getAiTransportHost } from "./host-Bl7Kgddo.mjs";
1
+ import { o as resolveClaudeFable5ModelIdentity, s as resolveClaudeModelIdentity, u as resolveClaudeOpus5ModelIdentity } from "./anthropic-BQXQudmA.mjs";
2
+ import { i as normalizeOptionalLowercaseString, r as normalizeNullableString } from "./string-coerce-fsri9iCu.mjs";
3
+ import { n as getAiTransportHost } from "./host-DF_yxOsA.mjs";
4
+ import { a as isRecord } from "./record-coerce-DdXsgUd_.mjs";
5
+ import { a as estimateBase64DecodedBytes } from "./provider-error-C8mBRJDl.mjs";
6
+ import { r as asNonNegativeFiniteNumber, s as parseStrictPositiveInteger } from "./number-coercion-H9qHik3g.mjs";
3
7
  import { t as resolveCacheRetention } from "./cache-retention-0x979a5V.mjs";
4
- import { h as stripSystemPromptCacheBoundary, m as splitSystemPromptCacheBoundary, v as sortPromptCacheToolsByName } from "./tool-result-text-Dvkp2Dus.mjs";
5
- import { o as resolveProviderRequestCapabilities, t as projectRuntimeToolInputSchema } from "./tool-schema-json-projection-B1b-XCn5.mjs";
8
+ import { A as splitSystemPromptCacheBoundary, P as sortPromptCacheToolsByName, j as stripSystemPromptCacheBoundary } from "./simple-options-oqsXB6U3.mjs";
9
+ import { a as resolveProviderEndpoint, o as resolveProviderRequestCapabilities, t as projectRuntimeToolInputSchema } from "./tool-schema-json-projection-FEr-jOoZ.mjs";
10
+ import { t as shortHash } from "./hash-CHgqbJmD.mjs";
6
11
  //#region packages/ai/src/transports/anthropic-payload-policy.ts
7
12
  /**
8
13
  * Anthropic-family request payload policy helpers.
@@ -10,6 +15,29 @@ import { o as resolveProviderRequestCapabilities, t as projectRuntimeToolInputSc
10
15
  * capabilities allow them.
11
16
  */
12
17
  const ANTHROPIC_CACHE_CONTROL_LIMIT = 4;
18
+ const ANTHROPIC_COMPACT_THRESHOLD_MIN = 5e4;
19
+ function parsePositiveInteger(value) {
20
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) return Math.floor(value);
21
+ return typeof value === "string" ? parseStrictPositiveInteger(value) : void 0;
22
+ }
23
+ /** Resolve the Anthropic input-token trigger, including the API's minimum. */
24
+ function resolveAnthropicCompactThreshold(contextWindow, configured) {
25
+ const configuredThreshold = parsePositiveInteger(configured);
26
+ if (configuredThreshold !== void 0) return Math.max(ANTHROPIC_COMPACT_THRESHOLD_MIN, configuredThreshold);
27
+ const resolvedContextWindow = parsePositiveInteger(contextWindow);
28
+ return Math.max(ANTHROPIC_COMPACT_THRESHOLD_MIN, resolvedContextWindow === void 0 ? ANTHROPIC_COMPACT_THRESHOLD_MIN : Math.floor(resolvedContextWindow * .7));
29
+ }
30
+ /** Resolve the server-compaction gate and effective threshold for an Anthropic route. */
31
+ function resolveAnthropicServerCompactionPlan(model, extraParams) {
32
+ const provider = normalizeOptionalLowercaseString(model.provider);
33
+ const api = normalizeOptionalLowercaseString(model.api);
34
+ const endpointClass = resolveProviderEndpoint(model).endpointClass;
35
+ const enabled = extraParams?.anthropicServerCompaction === true && provider === "anthropic" && api === "anthropic-messages" && (endpointClass === "default" || endpointClass === "anthropic-public");
36
+ return {
37
+ enabled,
38
+ ...enabled ? { threshold: resolveAnthropicCompactThreshold(model.contextWindow, extraParams?.anthropicCompactThreshold) } : {}
39
+ };
40
+ }
13
41
  function resolveBaseUrlHostname(baseUrl) {
14
42
  try {
15
43
  return new URL(baseUrl).hostname;
@@ -122,17 +150,21 @@ function countAnthropicCacheControlMarkers(blocks) {
122
150
  return count;
123
151
  }
124
152
  /** @deprecated Anthropic-family provider payload helper; do not use from third-party plugins. */
125
- function resolveAnthropicPayloadPolicy(input) {
153
+ function resolveAnthropicPayloadPolicy(input, model) {
154
+ const capabilities = resolveProviderRequestCapabilities({
155
+ provider: input.provider,
156
+ api: input.api,
157
+ baseUrl: input.baseUrl,
158
+ capability: "llm",
159
+ transport: "stream"
160
+ }, model);
161
+ const serverCompactionPlan = resolveAnthropicServerCompactionPlan(input, input.extraParams);
126
162
  return {
127
- allowsServiceTier: resolveProviderRequestCapabilities({
128
- provider: input.provider,
129
- api: input.api,
130
- baseUrl: input.baseUrl,
131
- capability: "llm",
132
- transport: "stream"
133
- }).allowsAnthropicServiceTier,
163
+ allowsServiceTier: capabilities.allowsAnthropicServiceTier,
134
164
  cacheControl: input.enableCacheControl === true ? resolveAnthropicEphemeralCacheControl(input.baseUrl, input.cacheRetention) : void 0,
135
- serviceTier: input.serviceTier
165
+ compactThreshold: serverCompactionPlan.threshold ?? resolveAnthropicCompactThreshold(input.contextWindow, input.extraParams?.anthropicCompactThreshold),
166
+ serviceTier: input.serviceTier,
167
+ useServerCompaction: input.enableServerCompaction === true && serverCompactionPlan.enabled
136
168
  };
137
169
  }
138
170
  /** @deprecated Anthropic-family provider payload helper; do not use from third-party plugins. */
@@ -140,6 +172,13 @@ function applyAnthropicPayloadPolicyToParams(payloadObj, policy, cacheBreakpoint
140
172
  if (policy.allowsServiceTier && policy.serviceTier !== void 0 && payloadObj.service_tier === void 0) payloadObj.service_tier = policy.serviceTier;
141
173
  if (policy.cacheControl) applyAnthropicCacheControlToSystem(payloadObj.system, policy.cacheControl);
142
174
  else stripAnthropicSystemPromptBoundary(payloadObj.system);
175
+ if (policy.useServerCompaction && payloadObj.context_management === void 0) payloadObj.context_management = { edits: [{
176
+ type: "compact_20260112",
177
+ trigger: {
178
+ type: "input_tokens",
179
+ value: policy.compactThreshold
180
+ }
181
+ }] };
143
182
  if (!policy.cacheControl) return;
144
183
  const usedMarkers = countAnthropicCacheControlMarkers(payloadObj.system) + countAnthropicCacheControlMarkers(payloadObj.tools);
145
184
  applyAnthropicCacheControlToMessages(payloadObj.messages, policy.cacheControl, ANTHROPIC_CACHE_CONTROL_LIMIT - usedMarkers, cacheBreakpointOptOutMessageIndexes);
@@ -176,83 +215,6 @@ function applyAnthropicEphemeralCacheControlMarkers(payloadObj, cacheControl = {
176
215
  }
177
216
  }
178
217
  //#endregion
179
- //#region packages/media-core/src/base64.ts
180
- /** Estimates decoded bytes without allocating a cleaned copy of the base64 payload. */
181
- function estimateBase64DecodedBytes(base64) {
182
- let effectiveLen = 0;
183
- for (let i = 0; i < base64.length; i += 1) {
184
- if (base64.charCodeAt(i) <= 32) continue;
185
- effectiveLen += 1;
186
- }
187
- if (effectiveLen === 0) return 0;
188
- let padding = 0;
189
- let end = base64.length - 1;
190
- while (end >= 0 && base64.charCodeAt(end) <= 32) end -= 1;
191
- if (end >= 0 && base64[end] === "=") {
192
- padding = 1;
193
- end -= 1;
194
- while (end >= 0 && base64.charCodeAt(end) <= 32) end -= 1;
195
- if (end >= 0 && base64[end] === "=") padding = 2;
196
- }
197
- const estimated = Math.floor(effectiveLen * 3 / 4) - padding;
198
- return Math.max(0, estimated);
199
- }
200
- const CANONICALIZE_BASE64_CHUNK_SIZE = 8192;
201
- function isBase64DataChar(code) {
202
- return code >= 65 && code <= 90 || code >= 97 && code <= 122 || code >= 48 && code <= 57 || code === 43 || code === 47;
203
- }
204
- function base64DataValue(code) {
205
- if (code >= 65 && code <= 90) return code - 65;
206
- if (code >= 97 && code <= 122) return code - 97 + 26;
207
- if (code >= 48 && code <= 57) return code - 48 + 52;
208
- return code === 43 ? 62 : 63;
209
- }
210
- /**
211
- * Normalizes and validates a base64 string, returning canonical no-whitespace
212
- * base64 only when the input has valid alphabet, padding, and length.
213
- */
214
- function canonicalizeBase64(base64) {
215
- const chunks = [];
216
- let current = "";
217
- let cleanedLength = 0;
218
- let padding = 0;
219
- let sawPadding = false;
220
- let lastDataCode = 0;
221
- const append = (char) => {
222
- current += char;
223
- cleanedLength += 1;
224
- if (current.length >= CANONICALIZE_BASE64_CHUNK_SIZE) {
225
- chunks.push(current);
226
- current = "";
227
- }
228
- };
229
- for (let i = 0; i < base64.length; i += 1) {
230
- const code = base64.charCodeAt(i);
231
- if (code <= 32) continue;
232
- if (code === 61) {
233
- padding += 1;
234
- if (padding > 2) return;
235
- sawPadding = true;
236
- append("=");
237
- continue;
238
- }
239
- if (sawPadding || !isBase64DataChar(code)) return;
240
- lastDataCode = code;
241
- append(base64[i] ?? "");
242
- }
243
- if (cleanedLength === 0) return;
244
- const remainder = cleanedLength % 4;
245
- if (remainder !== 0) {
246
- if (sawPadding || remainder === 1) return;
247
- current += "=".repeat(4 - remainder);
248
- }
249
- const effectivePadding = remainder === 0 ? padding : 4 - remainder;
250
- const padBitMask = effectivePadding === 2 ? 15 : effectivePadding === 1 ? 3 : 0;
251
- if (padBitMask !== 0 && (base64DataValue(lastDataCode) & padBitMask) !== 0) return;
252
- if (current) chunks.push(current);
253
- return chunks.join("");
254
- }
255
- //#endregion
256
218
  //#region packages/ai/src/internal/anthropic-inline-images.ts
257
219
  const ANTHROPIC_IMAGE_MEDIA_TYPE_SET = /* @__PURE__ */ new Set([
258
220
  "image/jpeg",
@@ -307,9 +269,6 @@ function omitFoundryBearerCredentialHeaders(headers) {
307
269
  }
308
270
  //#endregion
309
271
  //#region packages/ai/src/providers/anthropic-refusal.ts
310
- function readNullableString(value) {
311
- return typeof value === "string" && value.trim() ? value.trim() : null;
312
- }
313
272
  function readAnthropicRefusalDetails(value) {
314
273
  if (!value || typeof value !== "object") return {
315
274
  category: null,
@@ -317,8 +276,8 @@ function readAnthropicRefusalDetails(value) {
317
276
  };
318
277
  const details = value;
319
278
  return {
320
- category: readNullableString(details.category),
321
- explanation: readNullableString(details.explanation)
279
+ category: normalizeNullableString(details.category),
280
+ explanation: normalizeNullableString(details.explanation)
322
281
  };
323
282
  }
324
283
  function formatAnthropicRefusalMessage(details) {
@@ -618,7 +577,7 @@ function resolveOriginalAnthropicToolName(name, projection) {
618
577
  //#endregion
619
578
  //#region packages/ai/src/providers/anthropic-usage.ts
620
579
  function readAnthropicUsageTokenCount(value) {
621
- return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
580
+ return asNonNegativeFiniteNumber(value);
622
581
  }
623
582
  function readAnthropicCacheWriteUsage(usage) {
624
583
  if (!usage.cache_creation || typeof usage.cache_creation !== "object") return {};
@@ -661,6 +620,33 @@ function readLastAnthropicIterationUsage(usage) {
661
620
  }
662
621
  };
663
622
  }
623
+ function readAnthropicCompactionBilledUsage(iterations) {
624
+ if (!Array.isArray(iterations) || iterations.length === 0) return;
625
+ let sawCompaction = false;
626
+ const billed = {
627
+ input: 0,
628
+ output: 0,
629
+ cacheRead: 0,
630
+ cacheWrite: 0,
631
+ cacheWrite1h: 0
632
+ };
633
+ for (const iteration of iterations) {
634
+ if (!iteration || typeof iteration !== "object" || Array.isArray(iteration)) return;
635
+ const record = iteration;
636
+ const input = readAnthropicUsageTokenCount(record.input_tokens);
637
+ const output = readAnthropicUsageTokenCount(record.output_tokens);
638
+ const cacheRead = readAnthropicUsageTokenCount(record.cache_read_input_tokens);
639
+ const cacheWrite = readAnthropicUsageTokenCount(record.cache_creation_input_tokens);
640
+ if (input === void 0 || output === void 0 || cacheRead === void 0 || cacheWrite === void 0) return;
641
+ sawCompaction ||= record.type === "compaction";
642
+ billed.input += input;
643
+ billed.output += output;
644
+ billed.cacheRead += cacheRead;
645
+ billed.cacheWrite += cacheWrite;
646
+ billed.cacheWrite1h += readAnthropicCacheWriteUsage(record).cacheWrite1h ?? 0;
647
+ }
648
+ return sawCompaction ? billed : void 0;
649
+ }
664
650
  /** Record independent billing buckets without treating zero placeholders as context proof. */
665
651
  function applyAnthropicMessageStartUsage(target, payload) {
666
652
  const promptUsage = readAnthropicPromptUsageSnapshot(payload);
@@ -686,16 +672,23 @@ function applyAnthropicMessageStartUsage(target, payload) {
686
672
  /** Keep cumulative billing separate from the final server-side iteration context. */
687
673
  function applyAnthropicMessageDeltaUsage(target, payload, messageStartPromptUsage) {
688
674
  const usage = payload ?? {};
675
+ const billedIterations = readAnthropicCompactionBilledUsage(usage.iterations);
689
676
  const inputTokens = readAnthropicUsageTokenCount(usage.input_tokens);
690
- if (inputTokens !== void 0) target.input = inputTokens;
691
677
  const outputTokens = readAnthropicUsageTokenCount(usage.output_tokens);
692
- if (outputTokens !== void 0) target.output = outputTokens;
693
678
  const cacheReadTokens = readAnthropicUsageTokenCount(usage.cache_read_input_tokens);
694
- if (cacheReadTokens !== void 0) target.cacheRead = cacheReadTokens;
695
679
  const cacheWriteTokens = readAnthropicUsageTokenCount(usage.cache_creation_input_tokens);
696
- if (cacheWriteTokens !== void 0) target.cacheWrite = cacheWriteTokens;
697
- const { cacheWrite1h } = readAnthropicCacheWriteUsage(usage);
698
- if (cacheWrite1h !== void 0) target.cacheWrite1h = cacheWrite1h;
680
+ const resolved = billedIterations ?? {
681
+ input: inputTokens,
682
+ output: outputTokens,
683
+ cacheRead: cacheReadTokens,
684
+ cacheWrite: cacheWriteTokens,
685
+ cacheWrite1h: readAnthropicCacheWriteUsage(usage).cacheWrite1h
686
+ };
687
+ if (resolved.input !== void 0) target.input = resolved.input;
688
+ if (resolved.output !== void 0) target.output = resolved.output;
689
+ if (resolved.cacheRead !== void 0) target.cacheRead = resolved.cacheRead;
690
+ if (resolved.cacheWrite !== void 0) target.cacheWrite = resolved.cacheWrite;
691
+ if (resolved.cacheWrite1h !== void 0) target.cacheWrite1h = resolved.cacheWrite1h;
699
692
  target.totalTokens = target.input + target.output + target.cacheRead + target.cacheWrite;
700
693
  const iterationUsage = readLastAnthropicIterationUsage(usage);
701
694
  if (iterationUsage.state === "valid") target.contextUsage = {
@@ -714,4 +707,133 @@ function applyAnthropicMessageDeltaUsage(target, payload, messageStartPromptUsag
714
707
  } else target.contextUsage = { state: "unavailable" };
715
708
  }
716
709
  //#endregion
717
- export { applyAnthropicPayloadPolicyToParams as A, usesFoundryBearerAuth as C, canonicalizeBase64 as D, resolveAnthropicImageMediaType as E, resolveAnthropicPayloadPolicy as M, applyAnthropicCacheControlToMessages as O, omitFoundryBearerCredentialHeaders as S, normalizeAnthropicInlineContent as T, CLAUDE_OPUS_FALLBACK_MODEL_COST as _, readAnthropicUsageTokenCount as a, resolveAnthropicFallbackServingModelCost as b, normalizeAnthropicToolChoice as c, resolveOriginalAnthropicToolName as d, toClaudeCodeToolName as f, ANTHROPIC_SERVER_SIDE_FALLBACK_BETA as g, ANTHROPIC_SERVER_SIDE_FALLBACKS as h, readAnthropicPromptUsageSnapshot as i, resolveAnthropicEphemeralCacheControl as j, applyAnthropicEphemeralCacheControlMarkers as k, projectAnthropicTools as l, findActiveAnthropicToolTurnAssistantIndex as m, applyAnthropicMessageStartUsage as n, readLastAnthropicIterationUsage as o, ANTHROPIC_OMITTED_REASONING_TEXT as p, readAnthropicCacheWriteUsage as r, normalizeAnthropicToolCallId as s, applyAnthropicMessageDeltaUsage as t, reconcileAnthropicToolChoice as u, applyAnthropicFallbackBoundary as v, createAnthropicInlineImageBudget as w, applyAnthropicRefusal as x, readAnthropicFallbackBoundary as y };
710
+ //#region packages/ai/src/transports/anthropic-compaction-replay.ts
711
+ const ANTHROPIC_COMPACTION_REPLAY_TYPE = "anthropic-compaction";
712
+ const ANTHROPIC_COMPACTION_SUPPRESSION_TYPE = "anthropic-compaction-suppression";
713
+ const ANTHROPIC_COMPACTION_SUPPRESSION_DATA = "rejected";
714
+ function createCompactionCapture(output, model, options) {
715
+ const pending = /* @__PURE__ */ new Map();
716
+ return {
717
+ begin(index, block, replayIndex) {
718
+ if (block?.type !== "compaction") return false;
719
+ const content = typeof block.content === "string" ? block.content : "";
720
+ pending.set(index, {
721
+ content,
722
+ replayIndex
723
+ });
724
+ return true;
725
+ },
726
+ delta(index, delta) {
727
+ const capture = pending.get(index);
728
+ if (!capture || delta?.type !== "compaction_delta") return false;
729
+ capture.content = typeof delta.content === "string" ? delta.content : capture.content;
730
+ return true;
731
+ },
732
+ complete(index) {
733
+ const capture = pending.get(index);
734
+ if (!capture) return false;
735
+ pending.delete(index);
736
+ captureAnthropicCompaction(output, capture.content, capture.replayIndex, model, options);
737
+ return true;
738
+ }
739
+ };
740
+ }
741
+ function hashReplayValue(value) {
742
+ const normalized = value?.trim();
743
+ return normalized ? shortHash(normalized) : void 0;
744
+ }
745
+ function buildAnthropicReplayContext(model, options) {
746
+ return {
747
+ provider: model.provider,
748
+ api: model.api,
749
+ model: model.id,
750
+ baseUrlHash: hashReplayValue(model.baseUrl),
751
+ sessionHash: hashReplayValue(options?.sessionId),
752
+ authProfileHash: hashReplayValue(options?.authProfileId)
753
+ };
754
+ }
755
+ function isAnthropicCompactionState(state) {
756
+ 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;
757
+ if (state.type === ANTHROPIC_COMPACTION_SUPPRESSION_TYPE) return state.data === ANTHROPIC_COMPACTION_SUPPRESSION_DATA;
758
+ 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);
759
+ }
760
+ function readAnthropicCompactionState(value) {
761
+ return isRecord(value) && isAnthropicCompactionState(value) ? value : void 0;
762
+ }
763
+ function replayContextMatches(state, context) {
764
+ return state.provider === context.provider && state.api === context.api && state.model === context.model && state.baseUrlHash === context.baseUrlHash && state.sessionHash === context.sessionHash && state.authProfileHash === context.authProfileHash;
765
+ }
766
+ function captureAnthropicCompaction(output, summary, replayIndex, model, options) {
767
+ const context = buildAnthropicReplayContext(model, options);
768
+ if (!summary || !context.baseUrlHash || !Number.isSafeInteger(replayIndex) || replayIndex < 0) return;
769
+ output.providerReplay = {
770
+ v: 1,
771
+ type: ANTHROPIC_COMPACTION_REPLAY_TYPE,
772
+ data: summary,
773
+ replayIndex,
774
+ ...context,
775
+ baseUrlHash: context.baseUrlHash
776
+ };
777
+ }
778
+ function suppressAnthropicCompaction(output, model, options) {
779
+ const context = buildAnthropicReplayContext(model, options);
780
+ if (!context.baseUrlHash) return;
781
+ output.providerReplay = {
782
+ v: 1,
783
+ type: ANTHROPIC_COMPACTION_SUPPRESSION_TYPE,
784
+ data: ANTHROPIC_COMPACTION_SUPPRESSION_DATA,
785
+ ...context,
786
+ baseUrlHash: context.baseUrlHash
787
+ };
788
+ }
789
+ function resolveNewestAnthropicCompaction(messages, model, options) {
790
+ const context = buildAnthropicReplayContext(model, options);
791
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
792
+ const message = messages[index];
793
+ if (message?.role !== "assistant") continue;
794
+ const replayState = readAnthropicCompactionState(message.providerReplay);
795
+ if (replayState?.type === ANTHROPIC_COMPACTION_SUPPRESSION_TYPE) {
796
+ if (replayContextMatches(replayState, context)) return;
797
+ continue;
798
+ }
799
+ if (message.providerReplay?.type !== ANTHROPIC_COMPACTION_REPLAY_TYPE) continue;
800
+ if (!replayState) return;
801
+ if (!replayContextMatches(replayState, context)) return;
802
+ return {
803
+ owner: message,
804
+ replayIndex: replayState.replayIndex ?? 0,
805
+ summary: replayState.data
806
+ };
807
+ }
808
+ }
809
+ function buildAnthropicReplayPlan(messages, model, options) {
810
+ if (options?.enabled !== true) return { messages };
811
+ const checkpoint = resolveNewestAnthropicCompaction(messages, model, options);
812
+ if (!checkpoint) return { messages };
813
+ const ownerIndex = messages.indexOf(checkpoint.owner);
814
+ return {
815
+ messages: [{
816
+ ...checkpoint.owner,
817
+ content: checkpoint.owner.content.slice(checkpoint.replayIndex)
818
+ }, ...messages.slice(ownerIndex + 1)],
819
+ compaction: {
820
+ type: "compaction",
821
+ content: checkpoint.summary
822
+ }
823
+ };
824
+ }
825
+ /** Match Anthropic's 400 response when a replay block is no longer accepted. */
826
+ function isAnthropicReplayRejection(error) {
827
+ if (!error || typeof error !== "object") return false;
828
+ const record = error;
829
+ const nested = record.error && typeof record.error === "object" && !Array.isArray(record.error) ? record.error : void 0;
830
+ const text = [
831
+ record.message,
832
+ record.code,
833
+ nested?.message,
834
+ nested?.code
835
+ ].filter((value) => typeof value === "string").join(" ").toLowerCase();
836
+ return (record.status === 400 || text.startsWith("http 400:")) && (text.includes("compaction") || text.includes("context_management"));
837
+ }
838
+ //#endregion
839
+ export { resolveAnthropicImageMediaType as A, readAnthropicFallbackBoundary as C, usesFoundryBearerAuth as D, omitFoundryBearerCredentialHeaders as E, resolveAnthropicPayloadPolicy as F, resolveAnthropicServerCompactionPlan as I, applyAnthropicEphemeralCacheControlMarkers as M, applyAnthropicPayloadPolicyToParams as N, createAnthropicInlineImageBudget as O, resolveAnthropicEphemeralCacheControl as P, applyAnthropicFallbackBoundary as S, applyAnthropicRefusal as T, ANTHROPIC_OMITTED_REASONING_TEXT as _, applyAnthropicMessageDeltaUsage as a, ANTHROPIC_SERVER_SIDE_FALLBACK_BETA as b, readAnthropicPromptUsageSnapshot as c, normalizeAnthropicToolCallId as d, normalizeAnthropicToolChoice as f, toClaudeCodeToolName as g, resolveOriginalAnthropicToolName as h, suppressAnthropicCompaction as i, applyAnthropicCacheControlToMessages as j, normalizeAnthropicInlineContent as k, readAnthropicUsageTokenCount as l, reconcileAnthropicToolChoice as m, createCompactionCapture as n, applyAnthropicMessageStartUsage as o, projectAnthropicTools as p, isAnthropicReplayRejection as r, readAnthropicCacheWriteUsage as s, buildAnthropicReplayPlan as t, readLastAnthropicIterationUsage as u, findActiveAnthropicToolTurnAssistantIndex as v, resolveAnthropicFallbackServingModelCost as w, CLAUDE_OPUS_FALLBACK_MODEL_COST as x, ANTHROPIC_SERVER_SIDE_FALLBACKS as y };