@openclaw/ai 2026.9.1-beta.1 → 2026.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{anthropic-compaction-replay-nhKaCXu6.mjs → anthropic-compaction-replay-OMJZ0uyo.mjs} +37 -34
- package/dist/{anthropic-DI4PZKKB.mjs → anthropic-hk7F7ptG.mjs} +28 -25
- package/dist/{anthropic-payload-policy-B_0n0enE.d.mts → anthropic-payload-policy-DBT1itQ-.d.mts} +3 -3
- package/dist/{api-registry-CTd8NzcD.d.mts → api-registry-Cs6HGNqY.d.mts} +2 -2
- package/dist/{azure-openai-responses-D8dI0ekg.mjs → azure-openai-responses-CN4Fy5zV.mjs} +10 -7
- package/dist/{number-coercion-H9qHik3g.mjs → base64-CEFBpSkN.mjs} +73 -1
- package/dist/{diagnostics-COpOtRwq.mjs → diagnostics-CPeq9F7y.mjs} +5 -1
- package/dist/{diagnostics-BaTA9eVl.d.mts → diagnostics-DnPnOui6.d.mts} +5 -1
- package/dist/diagnostics-KhXK-QJI.mjs +136 -0
- package/dist/diagnostics.d.mts +8 -3
- package/dist/diagnostics.mjs +4 -3
- package/dist/{env-api-keys-DrgeBuva.mjs → env-api-keys-bktO00EJ.mjs} +2 -15
- package/dist/event-stream-DeDhbCc5.d.mts +1 -0
- package/dist/{event-stream-LiXePESD.d.mts → event-stream-vK_7r3bj.d.mts} +1 -1
- package/dist/event-stream.d.mts +2 -2
- package/dist/{google-Od-LLdVK.mjs → google-CC-nrwXg.mjs} +8 -6
- package/dist/{google-shared-Bgr9lFPw.mjs → google-shared-CjPY0hZM.mjs} +25 -23
- package/dist/{google-vertex-aerRSXc4.mjs → google-vertex-DCr0pyzQ.mjs} +7 -5
- package/dist/{host-D51fmkH6.mjs → host-BIaiBURL.mjs} +2 -2
- package/dist/{host-DsbPMFU6.d.mts → host-BztR4tQj.d.mts} +3 -3
- package/dist/index-AfaxKT8w.d.mts +111 -0
- package/dist/index.d.mts +10 -11
- package/dist/index.mjs +5 -5
- package/dist/internal/anthropic.d.mts +53 -52
- package/dist/internal/anthropic.mjs +5 -5
- package/dist/internal/openai-responses-payload-policy.d.mts +3 -3
- package/dist/internal/openai-responses-payload-policy.mjs +2 -3
- package/dist/internal/openai.d.mts +65 -63
- package/dist/internal/openai.mjs +9 -9
- package/dist/internal/retry-after.d.mts +2 -3
- package/dist/internal/runtime.d.mts +43 -43
- package/dist/internal/runtime.mjs +10 -8
- package/dist/internal/shared.d.mts +25 -25
- package/dist/internal/shared.mjs +95 -4
- package/dist/{mistral-EiHdymeb.mjs → mistral-B7etBd_H.mjs} +25 -20
- package/dist/{openai-chatgpt-responses-DHpF9o1e.mjs → openai-chatgpt-responses-BAJ4gq3i.mjs} +63 -122
- package/dist/{openai-completions-EFPiUGfS.mjs → openai-completions-D0QZ0AyB.mjs} +24 -20
- package/dist/{openai-completions-compat-BefmHT26.d.mts → openai-completions-compat-4IjSBpr6.d.mts} +5 -5
- package/dist/{openai-completions-stream-DUlGwRMz.mjs → openai-completions-stream-DZjwK8vp.mjs} +97 -90
- package/dist/{openai-responses-BogP8OjX.mjs → openai-responses-BEUlxfDu.mjs} +12 -8
- package/dist/openai-responses-compaction-window-DO7yV7az.mjs +686 -0
- package/dist/{openai-responses-contracts-Dvj_UtPy.d.mts → openai-responses-contracts-bPzSN_Ba.d.mts} +14 -5
- package/dist/{openai-responses-payload-policy-CNGFT9zr.d.mts → openai-responses-payload-policy-rLRPsSmB.d.mts} +1 -0
- package/dist/{openai-responses-prompt-observer-internal-Cd4hJG-S.mjs → openai-responses-prompt-observer-internal-C7x4IK7r.mjs} +4 -18
- package/dist/{openai-responses-shared-DJThc6jW.mjs → openai-responses-shared-DiAdpNAM.mjs} +274 -221
- package/dist/{openai-tool-schema-ho-hIkQf.mjs → openai-tool-schema-BMiHFH36.mjs} +14 -12
- package/dist/{provider-error-DDOs_Bz0.mjs → provider-error-B6EGq6gg.mjs} +14 -85
- package/dist/{provider-options-MdMBLzlU.d.mts → provider-options-CxFPtvh7.d.mts} +11 -3
- package/dist/{provider-transcript-transform-C01bQ5a3.mjs → provider-transcript-transform-WvJmFUAf.mjs} +1 -1
- package/dist/provider-types.d.mts +19 -20
- package/dist/providers.d.mts +5 -5
- package/dist/providers.mjs +9 -9
- package/dist/{reasoning-tag-text-partitioner-5ygO2rZc.mjs → reasoning-tag-text-partitioner-C-4uedDb.mjs} +93 -77
- package/dist/rolldown-runtime-BhDjJH2R.mjs +15 -0
- package/dist/{sanitize-unicode-DCkltN94.mjs → sanitize-unicode-S6binQG-.mjs} +2 -8
- package/dist/{simple-options-CFj7x3J4.mjs → simple-options-0PLDyJ-d.mjs} +42 -6
- package/dist/{src-Bu3FiFAG.mjs → src-C8U7lkoa.mjs} +75 -2
- package/dist/{stream-first-event-timeout-MK28puvq.mjs → stream-first-event-timeout-DcNjoFQE.mjs} +1 -1
- package/dist/{tool-schema-json-projection-qvTEs5Am.mjs → tool-schema-json-projection-BtZiml7r.mjs} +21 -31
- package/dist/{transport-stream-shared-rvaCyFYt.d.mts → transport-stream-shared-BrvFTkoO.d.mts} +5 -5
- package/dist/{transport-stream-shared-ljShVIZB.mjs → transport-stream-shared-CytPVLIg.mjs} +18 -5
- package/dist/{transport-utils-LJ1_rbi-.mjs → transport-utils-CtuS1Upe.mjs} +5 -8
- package/dist/transports.d.mts +120 -85
- package/dist/transports.mjs +218 -249
- package/dist/types-B5EFUmXs.d.mts +1 -0
- package/dist/{types-DhLoJbFm.d.mts → types-DbrhszyQ.d.mts} +27 -13
- package/dist/types.d.mts +7 -7
- package/dist/types.mjs +4 -4
- package/dist/{validation-Dk7q7NMN.d.mts → validation-BOwtcl9X.d.mts} +1 -1
- package/dist/{validation-B61OhAio.mjs → validation-CJZtym2g.mjs} +7 -5
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/package.json +5 -5
- package/dist/anthropic-BECQCNdF.d.mts +0 -98
- package/dist/event-stream-BKp4fOt_.d.mts +0 -1
- package/dist/index-Qbej8io0.d.mts +0 -3
- package/dist/openai-responses-contracts-QUY12X0B.mjs +0 -233
- package/dist/openai-responses-payload-policy-D8EdimYe.mjs +0 -204
- package/dist/provider-options-AvldWZt8.mjs +0 -21
- package/dist/tls-certificate-errors-DXSpluKI.mjs +0 -93
- package/dist/types-GiAjXatj.d.mts +0 -1
package/dist/transports.mjs
CHANGED
|
@@ -1,31 +1,30 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { d as resolveClaudeSonnet5ModelIdentity, g as supportsClaudeNativeXhighEffort, p as supportsClaudeAdaptiveThinking, u as resolveClaudeOpus5ModelIdentity } from "./src-Bu3FiFAG.mjs";
|
|
1
|
+
import { g as supportsClaudeAdaptiveThinking, m as resolveClaudeSonnet5ModelIdentity, p as resolveClaudeOpus5ModelIdentity, y as supportsClaudeNativeXhighEffort } from "./src-C8U7lkoa.mjs";
|
|
3
2
|
import { c as normalizeLowercaseStringOrEmpty, o as isRecord, s as hasNonEmptyString } from "./utf16-slice-qz3nsy87.mjs";
|
|
4
|
-
import { r as calculateCost } from "./sanitize-unicode-
|
|
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, h as defaultsClaudeAdaptiveThinking, 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-
|
|
6
|
-
import { i as
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
3
|
+
import { r as calculateCost } from "./sanitize-unicode-S6binQG-.mjs";
|
|
4
|
+
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, h as defaultsClaudeAdaptiveThinking, 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-BIaiBURL.mjs";
|
|
5
|
+
import { i as stableStringify } from "./provider-error-B6EGq6gg.mjs";
|
|
6
|
+
import { r as toErrorObject } from "./diagnostics-KhXK-QJI.mjs";
|
|
7
|
+
import { a as asNonNegativeFiniteNumber } from "./base64-CEFBpSkN.mjs";
|
|
9
8
|
import { n as uniqueStrings } from "./string-normalization--fwJ4S2q.mjs";
|
|
9
|
+
import { A as applyAnthropicCacheControlToMessages, C as applyAnthropicFallbackBoundary, D as createAnthropicInlineImageBudget, E as applyAnthropicRefusal, F as resolveAnthropicServerCompactionPlan, I as isAnthropicOAuthApiKey, L as omitFoundryBearerCredentialHeaders, M as applyAnthropicPayloadPolicyToParams, N as resolveAnthropicEphemeralCacheControl, O as normalizeAnthropicInlineContent, P as resolveAnthropicPayloadPolicy, R as usesFoundryBearerAuth, T as resolveAnthropicFallbackServingModelCost, _ as toClaudeCodeToolName, a as suppressAnthropicCompaction, b as ANTHROPIC_SERVER_SIDE_FALLBACKS, f as normalizeAnthropicToolCallId, g as resolveOriginalAnthropicToolName, h as reconcileAnthropicToolChoice, i as resolveNewestAnthropicCompaction, j as applyAnthropicEphemeralCacheControlMarkers, k as resolveAnthropicImageMediaType, m as projectAnthropicTools, n as createCompactionCapture, o as applyAnthropicMessageDeltaUsage, p as normalizeAnthropicToolChoice, r as isAnthropicReplayRejection, s as applyAnthropicMessageStartUsage, t as buildAnthropicReplayPlan, v as ANTHROPIC_OMITTED_REASONING_TEXT, w as readAnthropicFallbackBoundary, x as ANTHROPIC_SERVER_SIDE_FALLBACK_BETA, y as findActiveAnthropicToolTurnAssistantIndex } from "./anthropic-compaction-replay-OMJZ0uyo.mjs";
|
|
10
10
|
import { t as resolveCacheRetention } from "./cache-retention-0x979a5V.mjs";
|
|
11
|
-
import {
|
|
12
|
-
import { a as resolveProviderEndpoint, c as transformTransportMessages, i as resolveOpenAIStrictToolSetting, n as buildGuardedModelFetch } from "./tool-schema-json-projection-
|
|
13
|
-
import { a as isGoogleGemini3FlashModel, c as parseRetryAfterSeconds, f as resolveModelHeaderSentinels$1,
|
|
14
|
-
import {
|
|
15
|
-
import { S as quoteUnsafeIntegerLiterals, _ as transportAbortError, a as createWritableTransportEventStream, b as parseJsonObjectPreservingUnsafeIntegers, c as finalizeTransportStream, d as notifyProviderHttpMetadata, f as notifyProviderHttpResponse, g as sanitizeTransportPayloadText, h as sanitizeNonEmptyTransportPayloadText, i as createEmptyTransportUsage, l as mergeTransportHeaders, m as parseTerminalToolCallArguments, n as coerceTransportToolCallArguments, o as failTransportStream, p as notifyProviderStreamOpened, r as copyProviderAcceptanceObserver, s as finalizeTerminalToolCallArguments, t as assignTransportErrorDetails, u as mergeTransportMetadata, v as withProviderAcceptanceObserver, x as parseJsonPreservingUnsafeIntegers, y as withProviderResponseHook } from "./transport-stream-shared-
|
|
16
|
-
import { C as createDeepSeekTextFilter, E as tagUnresolvedTextAsCommentary, S as shouldOmitOllamaCompatResponseFormat, T as tagPendingCommentaryText, _ as hasToolCallHistory, a as buildOpenAISdkClientOptions, b as resolveOpenAICompletionsCompat, c as filterCodeModePayloadTools, d as readCodeModePayloadToolName, f as resolveCodeModeResponsesVisibleToolNames, g as convertMessages, h as resolveOpenAIReasoningEffortMap, i as buildOpenAIClientHeaders, l as getCompat, m as usesNativeOpenAICodexResponsesBackend, n as shouldEmitOpenAICompletionsReasoning, o as buildOpenAISdkRequestOptions, p as resolveOpenAIStrictToolFlagWithDiagnostics, r as assertCodeModeResponsesToolSurface, s as enforceCodeModeResponsesToolSurface, t as processCompletionsStream, u as isOpenAICodexResponsesModel, v as finalizeOpenAICompletionsToolCalls, x as resolveOpenAICompletionsResponseFormat, y as detectOpenAICompletionsCompat } from "./openai-completions-stream-
|
|
11
|
+
import { a as codeModeToolSurfaceObserver, d as stripSystemPromptCacheBoundary, m as sortPromptCacheToolsByName, o as reasoningTagTextPolicy, t as adjustMaxTokensForThinking } from "./simple-options-0PLDyJ-d.mjs";
|
|
12
|
+
import { a as resolveProviderEndpoint, c as transformTransportMessages, i as resolveOpenAIStrictToolSetting, n as buildGuardedModelFetch } from "./tool-schema-json-projection-BtZiml7r.mjs";
|
|
13
|
+
import { a as isGoogleGemini3FlashModel, c as parseRetryAfterSeconds, f as resolveModelHeaderSentinels$1, i as isCodeModeModelVisibleToolName, l as readResponseTextSnippet, m as supportsModelTools, n as createAbortError$1, o as isGoogleGemini3ProModel, p as sha256Hex, r as estimateStringChars, t as MALFORMED_STREAMING_FRAGMENT_ERROR_MESSAGE, u as redactIdentifier } from "./transport-utils-CtuS1Upe.mjs";
|
|
14
|
+
import { n as getEnvApiKey } from "./env-api-keys-bktO00EJ.mjs";
|
|
15
|
+
import { S as quoteUnsafeIntegerLiterals, _ as transportAbortError, a as createWritableTransportEventStream, b as parseJsonObjectPreservingUnsafeIntegers, c as finalizeTransportStream, d as notifyProviderHttpMetadata, f as notifyProviderHttpResponse, g as sanitizeTransportPayloadText, h as sanitizeNonEmptyTransportPayloadText, i as createEmptyTransportUsage, l as mergeTransportHeaders, m as parseTerminalToolCallArguments, n as coerceTransportToolCallArguments, o as failTransportStream, p as notifyProviderStreamOpened, r as copyProviderAcceptanceObserver, s as finalizeTerminalToolCallArguments, t as assignTransportErrorDetails, u as mergeTransportMetadata, v as withProviderAcceptanceObserver, x as parseJsonPreservingUnsafeIntegers, y as withProviderResponseHook } from "./transport-stream-shared-CytPVLIg.mjs";
|
|
16
|
+
import { C as createDeepSeekTextFilter, E as tagUnresolvedTextAsCommentary, S as shouldOmitOllamaCompatResponseFormat, T as tagPendingCommentaryText, _ as hasToolCallHistory, a as buildOpenAISdkClientOptions, b as resolveOpenAICompletionsCompat, c as filterCodeModePayloadTools, d as readCodeModePayloadToolName, f as resolveCodeModeResponsesVisibleToolNames, g as convertMessages, h as resolveOpenAIReasoningEffortMap, i as buildOpenAIClientHeaders, l as getCompat, m as usesNativeOpenAICodexResponsesBackend, n as shouldEmitOpenAICompletionsReasoning, o as buildOpenAISdkRequestOptions, p as resolveOpenAIStrictToolFlagWithDiagnostics, r as assertCodeModeResponsesToolSurface, s as enforceCodeModeResponsesToolSurface, t as processCompletionsStream, u as isOpenAICodexResponsesModel, v as finalizeOpenAICompletionsToolCalls, x as resolveOpenAICompletionsResponseFormat, y as detectOpenAICompletionsCompat } from "./openai-completions-stream-DZjwK8vp.mjs";
|
|
17
17
|
import { t as createDeferredEventBuffer } from "./deferred-event-buffer-DAvyP7qA.mjs";
|
|
18
18
|
import { r as parseStreamingJson, t as createToolArgumentPreviewSchedule } from "./json-parse-BuAJEbdW.mjs";
|
|
19
19
|
import { t as notifyLlmRequestActivity } from "./llm-request-activity-BjtkplhG.mjs";
|
|
20
20
|
import { t as googleFlashSupportsMinimalThinking } from "./google-thinking-level-C-V3tecN.mjs";
|
|
21
|
-
import { B as buildResponsesInputMessage, C as summarizeResponsesTools, G as
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import { i as
|
|
25
|
-
import { _ as isOpenAIGpt56Model, d as OpenAIResponsesWebSocketSafeRetryError, g as isOpenAIGpt55Model, h as isOpenAIGpt54MiniModel, i as OPENAI_RESPONSES_APIS, l as OpenAIResponsesWebSocketPostDispatchError, p as parseOpenAIResponsesWebSocketServerError, r as OPENAI_CODEX_RESPONSES_DEFAULT_INSTRUCTIONS, t as AZURE_RESPONSES_FIRST_EVENT_TIMEOUT_MS, u as OpenAIResponsesWebSocketPreDispatchError, v as normalizeOpenAIReasoningEffort, y as resolveOpenAIReasoningEffortForModel } from "./openai-responses-contracts-QUY12X0B.mjs";
|
|
26
|
-
import { i as resolveOpenAIResponsesServerCompactionPlan, n as resolveOpenAIResponsesCompactEndpointPlan, r as resolveOpenAIResponsesPayloadPolicy, t as applyOpenAIResponsesPayloadPolicy } from "./openai-responses-payload-policy-D8EdimYe.mjs";
|
|
21
|
+
import { B as buildResponsesInputMessage, C as summarizeResponsesTools, G as captureOpenAIResponsesCompaction, H as createOpenAIResponsesAssistantOutput, I as createResponsesStreamWithEncryptedContentRetry, J as resolveReplayableResponsesMessageId, K as resolveNewestOpenAIResponsesCompactionReplay, L as isInvalidEncryptedContentError, R as resolveAzureOpenAIApiVersion, S as summarizeResponsesPayload, U as CompactionReplayRefreshRequiredError, V as convertResponsesMessages, W as buildOpenAIResponsesReasoningReplayMetadata, X as resolveModelPayloadDebugMode, Y as emitModelTransportDebug, Z as resolveModelSseDebugMode, _ as safeDebugValue, b as summarizeOpenAITransportError, c as processResponsesStream, f as observeResponsesStream, g as normalizeResponsesFailedEvent, h as logResponsesFailedNoDetails, m as buildResponsesFailedNoDetailsObservation, n as applyResponsesServiceTierPricing, p as ResponsesStreamFailure, q as suppressOpenAIResponsesCompaction, v as stringifyRedactedEvent, x as summarizeResponsesFailedNoDetailsObservation, y as stringifyRedactedPayload, z as resolveNextResponsesEncryptedContentAttempt } from "./openai-responses-shared-DiAdpNAM.mjs";
|
|
22
|
+
import { A as readOpenAICompletionsReasoningBatch, C as createOpenAIProviderAcceptanceHook, D as measureUtf8AppendBytes, E as log, M as resolvePromptCacheKey, N as throwIfModelStreamAborted, O as parseOpenAICompletionsUsage, S as createModelStreamCooperativeScheduler, T as isOpenAICompletionsThinkingEnabled, b as reconcileOpenAIResponsesToolChoice, j as resolveOpenAIClientBaseUrl, k as readOpenAICompletionsContentDeltas, r as normalizeOpenAIStrictToolParameters, v as projectOpenAITools, w as createOpenAIResponseHook, x as GEMINI_THOUGHT_SIGNATURE_VALIDATOR_SKIP, y as reconcileOpenAICompletionsToolChoice } from "./openai-tool-schema-BMiHFH36.mjs";
|
|
23
|
+
import { i as getFirstStreamEventTimeoutMs, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "./stream-first-event-timeout-DcNjoFQE.mjs";
|
|
24
|
+
import { C as isOpenAIGpt54MiniModel, D as resolveOpenAIReasoningEffortForModel, E as normalizeOpenAIReasoningEffort, T as isOpenAIGpt56Model, _ as OpenAIResponsesWebSocketPostDispatchError, a as applyOpenAIResponsesPayloadPolicy, c as resolveOpenAIResponsesServerCompactionPlan, d as OPENAI_CODEX_RESPONSES_DEFAULT_INSTRUCTIONS, f as OPENAI_RESPONSES_APIS, i as sanitizeResponsesImagePayload, l as AZURE_RESPONSES_FIRST_EVENT_TIMEOUT_MS, n as isOpenAIResponsesCompactionOutput, o as resolveOpenAIResponsesCompactEndpointPlan, s as resolveOpenAIResponsesPayloadPolicy, t as createBoundedOpenAIResponsesCompactionFetch, v as OpenAIResponsesWebSocketPreDispatchError, w as isOpenAIGpt55Model, x as parseOpenAIResponsesWebSocketServerError, y as OpenAIResponsesWebSocketSafeRetryError } from "./openai-responses-compaction-window-DO7yV7az.mjs";
|
|
27
25
|
import { i as resolveAzureDeploymentNameFromMap, t as isOpenAICompatibleAzureResponsesBaseUrl } from "./azure-openai-responses-client-compat-C7K7QfUE.mjs";
|
|
28
26
|
import { n as registerSessionResourceCleanup } from "./session-resources-CkR4WWy1.mjs";
|
|
27
|
+
import { t as createResponsesPromptEgressObserver } from "./openai-responses-prompt-observer-internal-C7x4IK7r.mjs";
|
|
29
28
|
import { randomUUID } from "node:crypto";
|
|
30
29
|
import OpenAI, { AzureOpenAI } from "openai";
|
|
31
30
|
import { ResponsesWS } from "openai/resources/responses/ws.js";
|
|
@@ -35,12 +34,12 @@ import { ResponsesWS } from "openai/resources/responses/ws.js";
|
|
|
35
34
|
* Converts OpenClaw contexts/tools into Anthropic payloads, streams SSE events
|
|
36
35
|
* back into runtime output blocks, and applies provider request policy.
|
|
37
36
|
*/
|
|
38
|
-
const ANTHROPIC_MESSAGES_ERROR_BODY_MAX_BYTES =
|
|
37
|
+
const ANTHROPIC_MESSAGES_ERROR_BODY_MAX_BYTES = 8192;
|
|
39
38
|
const ANTHROPIC_MESSAGES_ERROR_BODY_MAX_CHARS = 400;
|
|
40
39
|
const ANTHROPIC_MESSAGES_ERROR_BODY_READ_IDLE_TIMEOUT_MS = 1e4;
|
|
41
40
|
const ANTHROPIC_MESSAGES_DEFAULT_MAX_TOKENS = 4096;
|
|
42
41
|
const ANTHROPIC_MESSAGES_FALLBACK_CONTEXT_DIVISOR = 4;
|
|
43
|
-
const ANTHROPIC_MESSAGES_SSE_PENDING_BUFFER_MAX_CHARS =
|
|
42
|
+
const ANTHROPIC_MESSAGES_SSE_PENDING_BUFFER_MAX_CHARS = 16777216;
|
|
44
43
|
function resolveAnthropicRequestModelId(model) {
|
|
45
44
|
if (isDirectAnthropicModel(model) && /^anthropic\//i.test(model.id)) return model.id.replace(/^anthropic\//i, "");
|
|
46
45
|
return model.id;
|
|
@@ -60,9 +59,6 @@ function resolveAnthropicMessagesMaxTokens(params) {
|
|
|
60
59
|
const contextWindow = resolvePositiveAnthropicTokenLimit(params.modelContextWindow);
|
|
61
60
|
return contextWindow === void 0 ? ANTHROPIC_MESSAGES_DEFAULT_MAX_TOKENS : Math.max(1, Math.min(ANTHROPIC_MESSAGES_DEFAULT_MAX_TOKENS, Math.floor(contextWindow / ANTHROPIC_MESSAGES_FALLBACK_CONTEXT_DIVISOR)));
|
|
62
61
|
}
|
|
63
|
-
function isAnthropicOAuthToken(apiKey) {
|
|
64
|
-
return (resolveSecretSentinel(apiKey) ?? apiKey).includes("sk-ant-oat");
|
|
65
|
-
}
|
|
66
62
|
function isDirectAnthropicModel(model) {
|
|
67
63
|
if (normalizeLowercaseStringOrEmpty(model.provider) !== "anthropic") return false;
|
|
68
64
|
const endpointClass = resolveProviderEndpoint(model).endpointClass;
|
|
@@ -482,7 +478,7 @@ function createAnthropicTransportClient(params) {
|
|
|
482
478
|
}
|
|
483
479
|
const betaFeatures = ["fine-grained-tool-streaming-2025-05-14"];
|
|
484
480
|
if (needsInterleavedBeta) betaFeatures.push("interleaved-thinking-2025-05-14");
|
|
485
|
-
if (
|
|
481
|
+
if (isAnthropicOAuthApiKey(apiKey)) {
|
|
486
482
|
const betaHeader = buildAnthropicBetaHeader(model, betaFeatures, { oauth: true });
|
|
487
483
|
return {
|
|
488
484
|
client: createAnthropicMessagesClient({
|
|
@@ -579,18 +575,19 @@ async function buildAnthropicParams(model, context, isOAuthToken, options) {
|
|
|
579
575
|
if (convertedTools.tools.length > 0) params.tools = convertedTools.tools;
|
|
580
576
|
}
|
|
581
577
|
if (mandatoryAdaptiveThinking || model.reasoning || supportsClaudeAdaptiveThinking(model)) {
|
|
582
|
-
if (mandatoryAdaptiveThinking || options?.thinkingEnabled)
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
578
|
+
if (mandatoryAdaptiveThinking || options?.thinkingEnabled) {
|
|
579
|
+
if (supportsClaudeAdaptiveThinking(model)) {
|
|
580
|
+
params.thinking = {
|
|
581
|
+
type: "adaptive",
|
|
582
|
+
display: options?.thinkingDisplay ?? "summarized"
|
|
583
|
+
};
|
|
584
|
+
const effort = options?.effort ?? (mandatoryAdaptiveThinking ? "high" : void 0);
|
|
585
|
+
if (effort) params.output_config = { effort };
|
|
586
|
+
} else params.thinking = {
|
|
587
|
+
type: "enabled",
|
|
588
|
+
budget_tokens: options?.thinkingBudgetTokens ?? 1024
|
|
586
589
|
};
|
|
587
|
-
|
|
588
|
-
if (effort) params.output_config = { effort };
|
|
589
|
-
} else params.thinking = {
|
|
590
|
-
type: "enabled",
|
|
591
|
-
budget_tokens: options?.thinkingBudgetTokens ?? 1024
|
|
592
|
-
};
|
|
593
|
-
else if (options?.thinkingEnabled === false) params.thinking = { type: "disabled" };
|
|
590
|
+
} else if (options?.thinkingEnabled === false) params.thinking = { type: "disabled" };
|
|
594
591
|
}
|
|
595
592
|
if (options?.metadata && typeof options.metadata.user_id === "string") params.metadata = { user_id: options.metadata.user_id };
|
|
596
593
|
if (options?.toolChoice) {
|
|
@@ -987,16 +984,18 @@ function createAnthropicMessagesTransportStreamFn() {
|
|
|
987
984
|
let appendedContent = false;
|
|
988
985
|
if (!hasNativeAnthropicDelta && typeof delta?.content === "string" && delta.content.length > 0) {
|
|
989
986
|
const text = sanitizeTransportPayloadText(delta.content);
|
|
990
|
-
if (text.length > 0)
|
|
991
|
-
block
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
987
|
+
if (text.length > 0) {
|
|
988
|
+
if (block?.type === "text" && index !== void 0) {
|
|
989
|
+
block.text += text;
|
|
990
|
+
eventSink.push({
|
|
991
|
+
type: "text_delta",
|
|
992
|
+
contentIndex: index,
|
|
993
|
+
delta: text,
|
|
994
|
+
partial: output
|
|
995
|
+
});
|
|
996
|
+
appendedContent = true;
|
|
997
|
+
} else appendedContent = appendReasoningContentTextDelta(event.index, text);
|
|
998
|
+
}
|
|
1000
999
|
}
|
|
1001
1000
|
if ((appendedThinking || appendedContent) && !hasNativeAnthropicDelta) continue;
|
|
1002
1001
|
}
|
|
@@ -1104,8 +1103,10 @@ function createAnthropicMessagesTransportStreamFn() {
|
|
|
1104
1103
|
if (event.type === "message_delta") {
|
|
1105
1104
|
const delta = event.delta;
|
|
1106
1105
|
const usage = event.usage;
|
|
1107
|
-
if (delta?.stop_reason)
|
|
1108
|
-
|
|
1106
|
+
if (delta?.stop_reason) {
|
|
1107
|
+
if (delta.stop_reason === "refusal") applyAnthropicRefusal(output, delta.stop_details, model.provider);
|
|
1108
|
+
else output.stopReason = mapAnthropicStopReason(delta.stop_reason);
|
|
1109
|
+
}
|
|
1109
1110
|
applyAnthropicMessageDeltaUsage(output.usage, usage, messageStartPromptUsage);
|
|
1110
1111
|
calculateCost(costModel, output.usage);
|
|
1111
1112
|
if (output.stopReason === "toolUse" || output.content.some((block) => block.type === "toolCall")) tagPendingCommentaryText(output.content);
|
|
@@ -1134,17 +1135,17 @@ function createAnthropicMessagesTransportStreamFn() {
|
|
|
1134
1135
|
output
|
|
1135
1136
|
});
|
|
1136
1137
|
} catch (error) {
|
|
1137
|
-
if (refusalBuffer) {
|
|
1138
|
-
refusalBuffer.discard();
|
|
1139
|
-
output.content = [];
|
|
1140
|
-
} else output.content = output.content.filter((block) => block.type !== "toolCall");
|
|
1141
|
-
if (usedCompactionReplay && isAnthropicReplayRejection(error)) suppressAnthropicCompaction(output, model, options);
|
|
1142
1138
|
failTransportStream({
|
|
1143
1139
|
stream,
|
|
1144
1140
|
output,
|
|
1145
1141
|
signal: options?.signal,
|
|
1146
1142
|
error,
|
|
1147
1143
|
cleanup: () => {
|
|
1144
|
+
if (refusalBuffer) {
|
|
1145
|
+
refusalBuffer.discard();
|
|
1146
|
+
output.content = [];
|
|
1147
|
+
} else output.content = output.content.filter((block) => block.type !== "toolCall");
|
|
1148
|
+
if (usedCompactionReplay && isAnthropicReplayRejection(error)) suppressAnthropicCompaction(output, model, options);
|
|
1148
1149
|
for (const block of output.content) delete block.index;
|
|
1149
1150
|
}
|
|
1150
1151
|
});
|
|
@@ -1595,10 +1596,11 @@ function convertTools(tools, compat, model) {
|
|
|
1595
1596
|
function buildOpenAICompletionsParams(model, context, options) {
|
|
1596
1597
|
const compat = getCompat(model);
|
|
1597
1598
|
const compatDetection = detectOpenAICompletionsCompat(model);
|
|
1598
|
-
|
|
1599
|
+
const completionsContext = context.systemPrompt ? {
|
|
1599
1600
|
...context,
|
|
1600
1601
|
systemPrompt: stripSystemPromptCacheBoundary(context.systemPrompt)
|
|
1601
|
-
} : context
|
|
1602
|
+
} : context;
|
|
1603
|
+
let messages = convertMessages(model, completionsContext, compat);
|
|
1602
1604
|
applyCompletionsReplay(messages, context, model, compat);
|
|
1603
1605
|
if (compat.strictMessageKeys) messages = stripCompletionMessagesToRoleContent(messages);
|
|
1604
1606
|
const cacheRetention = resolveCacheRetention(options?.cacheRetention);
|
|
@@ -1659,8 +1661,10 @@ function buildOpenAICompletionsParams(model, context, options) {
|
|
|
1659
1661
|
emitModelTransportDebug(log, `[completions] clamp_max_tokens provider=${model.provider} api=${model.api} model=${model.id} requested=${effectiveMaxTokens} output=${clampedMaxTokens} effectiveContext=${effectiveContextTokens} estimatedInput=${estimatedInputTokens}`);
|
|
1660
1662
|
}
|
|
1661
1663
|
}
|
|
1662
|
-
if (clampedMaxTokens)
|
|
1663
|
-
|
|
1664
|
+
if (clampedMaxTokens) {
|
|
1665
|
+
if (compat.maxTokensField === "max_tokens") params.max_tokens = clampedMaxTokens;
|
|
1666
|
+
else params.max_completion_tokens = clampedMaxTokens;
|
|
1667
|
+
}
|
|
1664
1668
|
}
|
|
1665
1669
|
const completionsReasoningEffort = resolveOpenAICompletionsReasoningEffort(options);
|
|
1666
1670
|
const resolvedCompletionsReasoningEffort = completionsReasoningEffort ? resolveOpenAIReasoningEffortForModel({
|
|
@@ -1831,11 +1835,8 @@ function createOpenAICompletionsTransportStreamFn() {
|
|
|
1831
1835
|
if (getCompat(model).requiresNonEmptyUserOrAssistantMessage) assertOpenAICompletionsPayloadHasConversationTurn(params, model);
|
|
1832
1836
|
const emitReasoning = shouldEmitOpenAICompletionsReasoning(model, options);
|
|
1833
1837
|
firstEventAbort = createFirstStreamEventAbortController(options?.signal);
|
|
1834
|
-
const { data: responseStream, response } = await client.chat.completions.create(params, buildOpenAISdkRequestOptions(model, firstEventAbort.signal, {
|
|
1835
|
-
|
|
1836
|
-
maxRetries: options?.maxRetries
|
|
1837
|
-
})).withResponse();
|
|
1838
|
-
await processCompletionsStream(withProviderResponseHook({
|
|
1838
|
+
const { data: responseStream, response } = await client.chat.completions.create(params, buildOpenAISdkRequestOptions(model, firstEventAbort.signal, { timeoutMs: options?.timeoutMs })).withResponse();
|
|
1839
|
+
const hookedResponseStream = withProviderResponseHook({
|
|
1839
1840
|
stream: responseStream,
|
|
1840
1841
|
signal: firstEventAbort.signal,
|
|
1841
1842
|
abort: firstEventAbort.abort,
|
|
@@ -1844,9 +1845,11 @@ function createOpenAICompletionsTransportStreamFn() {
|
|
|
1844
1845
|
type: "start",
|
|
1845
1846
|
partial: output
|
|
1846
1847
|
})
|
|
1847
|
-
})
|
|
1848
|
+
});
|
|
1849
|
+
await processCompletionsStream(hookedResponseStream, output, model, stream, {
|
|
1848
1850
|
signal: options?.signal,
|
|
1849
1851
|
emitReasoning,
|
|
1852
|
+
strictReasoningTags: reasoningTagTextPolicy.isStrict(options),
|
|
1850
1853
|
firstEventTimeoutMs: getFirstStreamEventTimeoutMs(options),
|
|
1851
1854
|
abortFirstEventStream: firstEventAbort.abort,
|
|
1852
1855
|
onFirstEventTimeout: getFirstStreamEventTimeoutHandler(options),
|
|
@@ -1911,7 +1914,7 @@ async function requestPreparedOpenAIResponsesCompaction(streamFn, model, context
|
|
|
1911
1914
|
}
|
|
1912
1915
|
//#endregion
|
|
1913
1916
|
//#region packages/ai/src/transports/openai-responses-continuation.ts
|
|
1914
|
-
const HTTP_CONTINUATION_IDLE_TTL_MS =
|
|
1917
|
+
const HTTP_CONTINUATION_IDLE_TTL_MS = 3e5;
|
|
1915
1918
|
const TURN_HEADERS = /* @__PURE__ */ new Set([
|
|
1916
1919
|
"traceparent",
|
|
1917
1920
|
"x-openclaw-turn-id",
|
|
@@ -1921,7 +1924,7 @@ function jsonValuesEqual(left, right) {
|
|
|
1921
1924
|
return stableStringify(JSON.parse(JSON.stringify(left))) === stableStringify(JSON.parse(JSON.stringify(right)));
|
|
1922
1925
|
}
|
|
1923
1926
|
function requestWithoutInput(request) {
|
|
1924
|
-
const { input: _input, previous_response_id: _previousResponseId, ...rest } = request;
|
|
1927
|
+
const { input: _input, previous_response_id: _previousResponseId, instructions: _instructions, tools: _tools, ...rest } = request;
|
|
1925
1928
|
if (!isRecord(rest.metadata)) return rest;
|
|
1926
1929
|
const metadata = Object.fromEntries(Object.entries(rest.metadata).filter(([key]) => key !== "openclaw_turn_id" && key !== "openclaw_turn_attempt"));
|
|
1927
1930
|
return {
|
|
@@ -1929,12 +1932,16 @@ function requestWithoutInput(request) {
|
|
|
1929
1932
|
metadata
|
|
1930
1933
|
};
|
|
1931
1934
|
}
|
|
1932
|
-
function normalizeAssistantReplayInput(input) {
|
|
1935
|
+
function normalizeAssistantReplayInput(input, fromResponse = false) {
|
|
1933
1936
|
return input.map((item) => {
|
|
1934
1937
|
if (!isRecord(item)) return item;
|
|
1935
1938
|
if (item.type === "reasoning") return { type: "reasoning" };
|
|
1936
1939
|
if (item.type !== "function_call" && !(item.type === "message" && item.role === "assistant")) return item;
|
|
1937
1940
|
const { id: _id, status: _status, ...stableItem } = item;
|
|
1941
|
+
if (fromResponse && item.type === "function_call") {
|
|
1942
|
+
const args = parseJsonObjectPreservingUnsafeIntegers(stableItem.arguments);
|
|
1943
|
+
stableItem.arguments = args ? JSON.stringify(args) : stableItem.arguments;
|
|
1944
|
+
}
|
|
1938
1945
|
if (item.type === "message" && Array.isArray(stableItem.content)) stableItem.content = stableItem.content.map((part) => {
|
|
1939
1946
|
if (!isRecord(part) || part.type !== "output_text") return part;
|
|
1940
1947
|
const { annotations: _annotations, logprobs: _logprobs, ...stablePart } = part;
|
|
@@ -1963,7 +1970,7 @@ function resolveResponsesContinuationRequest(continuation, request) {
|
|
|
1963
1970
|
request,
|
|
1964
1971
|
continuationStatus: "history_shorter"
|
|
1965
1972
|
};
|
|
1966
|
-
if (!jsonValuesEqual(normalizeAssistantReplayInput(currentInput.slice(0, previousInput.length)), normalizeAssistantReplayInput(previousInput)) || !jsonValuesEqual(normalizeAssistantReplayInput(currentInput.slice(previousInput.length, baselineLength)), normalizeAssistantReplayInput(continuation.lastResponseItems))) return {
|
|
1973
|
+
if (!jsonValuesEqual(normalizeAssistantReplayInput(currentInput.slice(0, previousInput.length)), normalizeAssistantReplayInput(previousInput)) || !jsonValuesEqual(normalizeAssistantReplayInput(currentInput.slice(previousInput.length, baselineLength)), normalizeAssistantReplayInput(continuation.lastResponseItems, true))) return {
|
|
1967
1974
|
request,
|
|
1968
1975
|
continuationStatus: "history_changed"
|
|
1969
1976
|
};
|
|
@@ -2112,18 +2119,28 @@ function sanitizeOpenAICodexResponsesParams(model, params) {
|
|
|
2112
2119
|
stripOpenAICodexResponsesUnsupportedTextFields(params);
|
|
2113
2120
|
return params;
|
|
2114
2121
|
}
|
|
2115
|
-
function
|
|
2122
|
+
function buildOpenAIResponsesInstructionsText(context) {
|
|
2116
2123
|
if (!context.systemPrompt) return;
|
|
2117
2124
|
return sanitizeTransportPayloadText(stripSystemPromptCacheBoundary(context.systemPrompt));
|
|
2118
2125
|
}
|
|
2119
|
-
function
|
|
2120
|
-
|
|
2126
|
+
function resolveOpenAIResponsesInstructions(model, context, usesInstructionsField) {
|
|
2127
|
+
if (!usesInstructionsField) return;
|
|
2128
|
+
const instructions = buildOpenAIResponsesInstructionsText(context);
|
|
2121
2129
|
if (instructions && instructions.trim().length > 0) return instructions;
|
|
2122
2130
|
return usesNativeOpenAICodexResponsesBackend(model) ? OPENAI_CODEX_RESPONSES_DEFAULT_INSTRUCTIONS : void 0;
|
|
2123
2131
|
}
|
|
2124
|
-
function
|
|
2132
|
+
function buildOpenAIResponsesCompactSystemMessage(model, instructions) {
|
|
2133
|
+
const compat = getCompat(model);
|
|
2134
|
+
const supportsDeveloperRole = typeof compat.supportsDeveloperRole === "boolean" ? compat.supportsDeveloperRole : void 0;
|
|
2135
|
+
const role = model.reasoning && supportsDeveloperRole !== false ? "developer" : "system";
|
|
2136
|
+
return buildResponsesInputMessage(role, [{
|
|
2137
|
+
type: "input_text",
|
|
2138
|
+
text: instructions
|
|
2139
|
+
}]);
|
|
2140
|
+
}
|
|
2141
|
+
function ensureOpenAIResponsesNonEmptyInput(messages, context) {
|
|
2125
2142
|
if (messages.length > 0 || !context.systemPrompt) return;
|
|
2126
|
-
if (!
|
|
2143
|
+
if (!buildOpenAIResponsesInstructionsText(context)) throw new Error("OpenAI Responses requires non-empty input when only systemPrompt is provided.");
|
|
2127
2144
|
messages.push(buildResponsesInputMessage("user", [{
|
|
2128
2145
|
type: "input_text",
|
|
2129
2146
|
text: " "
|
|
@@ -2137,16 +2154,12 @@ function resolveOpenAIResponsesTextFormat(responseFormat) {
|
|
|
2137
2154
|
return responseFormat;
|
|
2138
2155
|
}
|
|
2139
2156
|
function convertOpenAIResponsesMessagesForRequest(model, context, options, replayMode) {
|
|
2140
|
-
const isCodexResponses = isOpenAICodexResponsesModel(model);
|
|
2141
2157
|
const isNativeCodexResponses = usesNativeOpenAICodexResponsesBackend(model);
|
|
2142
|
-
const compat = getCompat(model);
|
|
2143
|
-
const supportsDeveloperRole = typeof compat.supportsDeveloperRole === "boolean" ? compat.supportsDeveloperRole : void 0;
|
|
2144
2158
|
const payloadPolicy = resolveOpenAIResponsesPayloadPolicy(model, { storeMode: "disable" });
|
|
2145
2159
|
const policyAllowsReplayIds = payloadPolicy.explicitStore !== false && !payloadPolicy.shouldStripStore;
|
|
2146
2160
|
const replayResponsesItemIds = !isNativeCodexResponses && (options?.replayResponsesItemIds ?? policyAllowsReplayIds);
|
|
2147
2161
|
return convertResponsesMessages(model, context, OPENAI_RESPONSES_TOOL_CALL_PROVIDERS, {
|
|
2148
|
-
includeSystemPrompt: !
|
|
2149
|
-
supportsDeveloperRole,
|
|
2162
|
+
includeSystemPrompt: !payloadPolicy.usesInstructionsField,
|
|
2150
2163
|
replayReasoningItems: true,
|
|
2151
2164
|
replayResponsesItemIds,
|
|
2152
2165
|
authProfileId: options?.authProfileId,
|
|
@@ -2155,19 +2168,19 @@ function convertOpenAIResponsesMessagesForRequest(model, context, options, repla
|
|
|
2155
2168
|
});
|
|
2156
2169
|
}
|
|
2157
2170
|
function buildOpenAIResponsesParams(model, context, options, metadata, replayMode = "checkpoint") {
|
|
2158
|
-
const isCodexResponses = isOpenAICodexResponsesModel(model);
|
|
2159
2171
|
const payloadPolicy = resolveOpenAIResponsesPayloadPolicy(model, { storeMode: "disable" });
|
|
2160
2172
|
const messages = convertOpenAIResponsesMessagesForRequest(model, context, options, replayMode);
|
|
2161
|
-
|
|
2173
|
+
ensureOpenAIResponsesNonEmptyInput(messages, context);
|
|
2162
2174
|
const cacheRetention = resolveCacheRetention(options?.cacheRetention);
|
|
2163
2175
|
const promptCacheKey = resolvePromptCacheKey(options, cacheRetention);
|
|
2176
|
+
const instructions = resolveOpenAIResponsesInstructions(model, context, payloadPolicy.usesInstructionsField);
|
|
2164
2177
|
const params = {
|
|
2165
2178
|
model: model.id,
|
|
2166
2179
|
input: messages,
|
|
2167
2180
|
stream: true,
|
|
2168
2181
|
prompt_cache_key: promptCacheKey,
|
|
2169
2182
|
prompt_cache_retention: getPromptCacheRetention(model.baseUrl, cacheRetention),
|
|
2170
|
-
...
|
|
2183
|
+
...instructions ? { instructions } : {},
|
|
2171
2184
|
...metadata ? { metadata } : {}
|
|
2172
2185
|
};
|
|
2173
2186
|
const effectiveMaxTokens = options?.maxTokens || model.maxTokens;
|
|
@@ -2189,9 +2202,10 @@ function buildOpenAIResponsesParams(model, context, options, metadata, replayMod
|
|
|
2189
2202
|
}
|
|
2190
2203
|
if (model.reasoning) {
|
|
2191
2204
|
if (options?.reasoningEffort || options?.reasoning || options?.reasoningSummary) {
|
|
2205
|
+
const requestedReasoningEffort = resolveOpenAIReasoningEffort(options);
|
|
2192
2206
|
const resolvedReasoningEffort = resolveOpenAIReasoningEffortForModel({
|
|
2193
2207
|
model,
|
|
2194
|
-
effort:
|
|
2208
|
+
effort: requestedReasoningEffort
|
|
2195
2209
|
});
|
|
2196
2210
|
const reasoningEffort = resolvedReasoningEffort ? raiseMinimalReasoningForResponsesWebSearch({
|
|
2197
2211
|
model,
|
|
@@ -2218,8 +2232,8 @@ function buildOpenAIResponsesParams(model, context, options, metadata, replayMod
|
|
|
2218
2232
|
}
|
|
2219
2233
|
//#endregion
|
|
2220
2234
|
//#region packages/ai/src/transports/openai-responses-websocket.ts
|
|
2221
|
-
const SESSION_WEBSOCKET_CACHE_TTL_MS =
|
|
2222
|
-
const SESSION_WEBSOCKET_MAX_AGE_MS =
|
|
2235
|
+
const SESSION_WEBSOCKET_CACHE_TTL_MS = 3e5;
|
|
2236
|
+
const SESSION_WEBSOCKET_MAX_AGE_MS = 33e5;
|
|
2223
2237
|
const WEBSOCKET_OPEN_STATE = 1;
|
|
2224
2238
|
const websocketSessionCache = /* @__PURE__ */ new Map();
|
|
2225
2239
|
const degradedWebSocketConnections = /* @__PURE__ */ new Map();
|
|
@@ -2472,149 +2486,6 @@ function closeOpenAIResponsesWebSocketSessions(sessionId) {
|
|
|
2472
2486
|
}
|
|
2473
2487
|
registerSessionResourceCleanup(closeOpenAIResponsesWebSocketSessions);
|
|
2474
2488
|
//#endregion
|
|
2475
|
-
//#region packages/media-core/src/inline-image-data-url.ts
|
|
2476
|
-
/** Prefix used to distinguish inline data URLs from remote/local image references. */
|
|
2477
|
-
const INLINE_IMAGE_DATA_URL_PREFIX = "data:";
|
|
2478
|
-
const IMAGE_SIGNATURES = [
|
|
2479
|
-
{
|
|
2480
|
-
mime: "image/png",
|
|
2481
|
-
matches: (buffer) => buffer.length >= 8 && buffer[0] === 137 && buffer[1] === 80 && buffer[2] === 78 && buffer[3] === 71 && buffer[4] === 13 && buffer[5] === 10 && buffer[6] === 26 && buffer[7] === 10
|
|
2482
|
-
},
|
|
2483
|
-
{
|
|
2484
|
-
mime: "image/jpeg",
|
|
2485
|
-
matches: (buffer) => buffer.length >= 3 && buffer[0] === 255 && buffer[1] === 216 && buffer[2] === 255
|
|
2486
|
-
},
|
|
2487
|
-
{
|
|
2488
|
-
mime: "image/webp",
|
|
2489
|
-
matches: (buffer) => buffer.length >= 12 && buffer.subarray(0, 4).toString("ascii") === "RIFF" && buffer.subarray(8, 12).toString("ascii") === "WEBP"
|
|
2490
|
-
},
|
|
2491
|
-
{
|
|
2492
|
-
mime: "image/gif",
|
|
2493
|
-
matches: (buffer) => buffer.length >= 6 && (buffer.subarray(0, 6).toString("ascii") === "GIF87a" || buffer.subarray(0, 6).toString("ascii") === "GIF89a")
|
|
2494
|
-
},
|
|
2495
|
-
{
|
|
2496
|
-
mime: "image/bmp",
|
|
2497
|
-
matches: (buffer) => buffer.length >= 2 && buffer[0] === 66 && buffer[1] === 77
|
|
2498
|
-
}
|
|
2499
|
-
];
|
|
2500
|
-
const HEIC_BRANDS = /* @__PURE__ */ new Set([
|
|
2501
|
-
"heic",
|
|
2502
|
-
"heix",
|
|
2503
|
-
"hevc",
|
|
2504
|
-
"hevx",
|
|
2505
|
-
"heis",
|
|
2506
|
-
"heim",
|
|
2507
|
-
"hevm",
|
|
2508
|
-
"hevs"
|
|
2509
|
-
]);
|
|
2510
|
-
const HEIF_BRANDS = /* @__PURE__ */ new Set(["mif1", "msf1"]);
|
|
2511
|
-
const IMAGE_SIGNATURE_PREFIX_BASE64_CHARS = 128;
|
|
2512
|
-
const INLINE_IMAGE_DATA_URL_MIMES = /* @__PURE__ */ new Set([
|
|
2513
|
-
"image/png",
|
|
2514
|
-
"image/jpeg",
|
|
2515
|
-
"image/webp",
|
|
2516
|
-
"image/gif"
|
|
2517
|
-
]);
|
|
2518
|
-
function startsWithDataUrl(value) {
|
|
2519
|
-
return value.slice(0, 5).toLowerCase() === INLINE_IMAGE_DATA_URL_PREFIX;
|
|
2520
|
-
}
|
|
2521
|
-
function sniffIsoBmffImageMime(buffer) {
|
|
2522
|
-
if (buffer.length < 12 || buffer.subarray(4, 8).toString("ascii") !== "ftyp") return;
|
|
2523
|
-
const brands = [buffer.subarray(8, 12).toString("ascii")];
|
|
2524
|
-
for (let offset = 16; offset + 4 <= buffer.length; offset += 4) brands.push(buffer.subarray(offset, offset + 4).toString("ascii"));
|
|
2525
|
-
if (brands.some((brand) => HEIC_BRANDS.has(brand))) return "image/heic";
|
|
2526
|
-
if (brands.some((brand) => HEIF_BRANDS.has(brand))) return "image/heif";
|
|
2527
|
-
}
|
|
2528
|
-
/** Sniffs supported inline image formats from decoded bytes. */
|
|
2529
|
-
function sniffInlineImageMime(buffer) {
|
|
2530
|
-
return IMAGE_SIGNATURES.find((signature) => signature.matches(buffer))?.mime ?? sniffIsoBmffImageMime(buffer);
|
|
2531
|
-
}
|
|
2532
|
-
function isImageMimeType(value) {
|
|
2533
|
-
return value.trim().toLowerCase().startsWith("image/");
|
|
2534
|
-
}
|
|
2535
|
-
/** Canonicalizes trusted inline image base64 and rejects malformed or non-image payloads. */
|
|
2536
|
-
function sanitizeInlineImageBase64(params) {
|
|
2537
|
-
if (!isImageMimeType(params.mimeType)) return;
|
|
2538
|
-
const canonicalPayload = canonicalizeBase64(params.base64);
|
|
2539
|
-
if (!canonicalPayload) return;
|
|
2540
|
-
const sniffedMimeType = sniffInlineImageMime(Buffer.from(canonicalPayload.slice(0, IMAGE_SIGNATURE_PREFIX_BASE64_CHARS), "base64"));
|
|
2541
|
-
if (!sniffedMimeType) return;
|
|
2542
|
-
return {
|
|
2543
|
-
mimeType: sniffedMimeType,
|
|
2544
|
-
base64: canonicalPayload
|
|
2545
|
-
};
|
|
2546
|
-
}
|
|
2547
|
-
function parseInlineImageDataUrl(value) {
|
|
2548
|
-
if (!startsWithDataUrl(value)) return {
|
|
2549
|
-
metadata: [],
|
|
2550
|
-
payload: value
|
|
2551
|
-
};
|
|
2552
|
-
const commaIndex = value.indexOf(",");
|
|
2553
|
-
if (commaIndex < 0) return;
|
|
2554
|
-
return {
|
|
2555
|
-
metadata: value.slice(5, commaIndex).split(";").map((part) => part.trim()),
|
|
2556
|
-
payload: value.slice(commaIndex + 1)
|
|
2557
|
-
};
|
|
2558
|
-
}
|
|
2559
|
-
function metadataAllowsImageBase64(metadata) {
|
|
2560
|
-
const [mimeType, ...options] = metadata;
|
|
2561
|
-
return mimeType !== void 0 && isImageMimeType(mimeType) && options.some((part) => part.toLowerCase() === "base64");
|
|
2562
|
-
}
|
|
2563
|
-
function sanitizeInlineImageDataUrlWithAllowedMimes(imageUrl, allowedMimes) {
|
|
2564
|
-
const parsed = parseInlineImageDataUrl(imageUrl);
|
|
2565
|
-
if (!parsed) return;
|
|
2566
|
-
if (parsed.metadata.length === 0) return imageUrl;
|
|
2567
|
-
if (!metadataAllowsImageBase64(parsed.metadata)) return;
|
|
2568
|
-
const [mimeType] = parsed.metadata;
|
|
2569
|
-
const sanitized = sanitizeInlineImageBase64({
|
|
2570
|
-
mimeType: mimeType ?? "",
|
|
2571
|
-
base64: parsed.payload
|
|
2572
|
-
});
|
|
2573
|
-
if (!sanitized) return;
|
|
2574
|
-
if (allowedMimes && !allowedMimes.has(sanitized.mimeType)) return;
|
|
2575
|
-
return `data:${sanitized.mimeType};base64,${sanitized.base64}`;
|
|
2576
|
-
}
|
|
2577
|
-
/** Canonicalizes provider-safe inline image data URLs and rejects unsupported formats. */
|
|
2578
|
-
function sanitizeInlineImageDataUrl(imageUrl) {
|
|
2579
|
-
return sanitizeInlineImageDataUrlWithAllowedMimes(imageUrl, INLINE_IMAGE_DATA_URL_MIMES);
|
|
2580
|
-
}
|
|
2581
|
-
//#endregion
|
|
2582
|
-
//#region packages/ai/src/transports/responses-image-payload-sanitizer.ts
|
|
2583
|
-
/**
|
|
2584
|
-
* Sanitizes OpenAI Responses payloads before transport. Invalid inline images
|
|
2585
|
-
* are replaced with text placeholders so the request remains valid and
|
|
2586
|
-
* auditable.
|
|
2587
|
-
*/
|
|
2588
|
-
const IMAGE_OMITTED_TEXT = "omitted image payload: invalid inline image data";
|
|
2589
|
-
function invalidSnakeImage() {
|
|
2590
|
-
return {
|
|
2591
|
-
type: "input_text",
|
|
2592
|
-
text: `[${IMAGE_OMITTED_TEXT}]`
|
|
2593
|
-
};
|
|
2594
|
-
}
|
|
2595
|
-
function sanitizeValue(value) {
|
|
2596
|
-
if (Array.isArray(value)) return value.map(sanitizeValue);
|
|
2597
|
-
if (!isRecord(value)) return value;
|
|
2598
|
-
if (value.type === "input_image" && typeof value.image_url === "string") {
|
|
2599
|
-
const imageUrl = sanitizeInlineImageDataUrl(value.image_url);
|
|
2600
|
-
return imageUrl ? {
|
|
2601
|
-
...value,
|
|
2602
|
-
image_url: imageUrl
|
|
2603
|
-
} : invalidSnakeImage();
|
|
2604
|
-
}
|
|
2605
|
-
const next = {};
|
|
2606
|
-
for (const [key, child] of Object.entries(value)) next[key] = sanitizeValue(child);
|
|
2607
|
-
return next;
|
|
2608
|
-
}
|
|
2609
|
-
/** Sanitize inline image fields inside a Responses API payload. */
|
|
2610
|
-
function sanitizeResponsesImagePayload(params) {
|
|
2611
|
-
if (!Array.isArray(params.input)) return params;
|
|
2612
|
-
return {
|
|
2613
|
-
...params,
|
|
2614
|
-
input: sanitizeValue(params.input)
|
|
2615
|
-
};
|
|
2616
|
-
}
|
|
2617
|
-
//#endregion
|
|
2618
2489
|
//#region packages/ai/src/transports/openai-responses-client.ts
|
|
2619
2490
|
function resolveNativeOpenAIResponsesWebSocketMode(model, transport) {
|
|
2620
2491
|
if (transport !== "websocket" && transport !== "websocket-cached" && transport !== "auto") return;
|
|
@@ -2648,37 +2519,35 @@ function resolveProviderTransportTurnState(model, params) {
|
|
|
2648
2519
|
}
|
|
2649
2520
|
});
|
|
2650
2521
|
}
|
|
2651
|
-
function createOpenAIResponsesClient(model, context, apiKey, optionHeaders, turnHeaders, sessionId) {
|
|
2522
|
+
function createOpenAIResponsesClient(model, context, apiKey, optionHeaders, turnHeaders, sessionId, fetchOverride) {
|
|
2652
2523
|
return new OpenAI({
|
|
2653
2524
|
apiKey,
|
|
2654
2525
|
baseURL: resolveOpenAIClientBaseUrl(model),
|
|
2655
2526
|
dangerouslyAllowBrowser: true,
|
|
2656
2527
|
defaultHeaders: buildOpenAIClientHeaders(model, context, optionHeaders, turnHeaders, sessionId),
|
|
2657
|
-
fetch: buildGuardedModelFetch(model),
|
|
2528
|
+
fetch: fetchOverride ?? buildGuardedModelFetch(model),
|
|
2658
2529
|
...buildOpenAISdkClientOptions(model)
|
|
2659
2530
|
});
|
|
2660
2531
|
}
|
|
2661
2532
|
async function postOpenAIResponsesCompaction(params) {
|
|
2533
|
+
const compactInput = typeof params.request.instructions === "string" && params.request.instructions.length > 0 ? [buildOpenAIResponsesCompactSystemMessage(params.model, params.request.instructions), ...params.request.input ?? []] : params.request.input;
|
|
2662
2534
|
const response = await params.client.post("/responses/compact", {
|
|
2663
|
-
...buildOpenAISdkRequestOptions(params.model, params.options?.signal, {
|
|
2664
|
-
timeoutMs: params.options?.timeoutMs,
|
|
2665
|
-
maxRetries: params.options?.maxRetries
|
|
2666
|
-
}),
|
|
2535
|
+
...buildOpenAISdkRequestOptions(params.model, params.options?.signal, { timeoutMs: params.options?.timeoutMs }),
|
|
2667
2536
|
body: {
|
|
2668
2537
|
model: params.request.model,
|
|
2669
|
-
input:
|
|
2538
|
+
input: compactInput
|
|
2670
2539
|
}
|
|
2671
2540
|
});
|
|
2672
2541
|
const output = isRecord(response) && Array.isArray(response.output) ? response.output : [];
|
|
2673
2542
|
const item = output.at(-1);
|
|
2674
2543
|
const retainedItems = output.slice(0, -1);
|
|
2675
|
-
const retainedMessagesAreValid = retainedItems.every((candidate) => isRecord(candidate) && candidate.type === "message" && (candidate.role === "user" || candidate.role === "developer" || candidate.role === "system") && Array.isArray(candidate.content));
|
|
2676
2544
|
const retainedUserMessageCount = retainedItems.filter((candidate) => isRecord(candidate) && candidate.type === "message" && candidate.role === "user" && Array.isArray(candidate.content)).length;
|
|
2677
2545
|
const inputUserMessageCount = Array.isArray(params.request.input) ? params.request.input.filter((candidate) => isRecord(candidate) && candidate.type === "message" && candidate.role === "user").length : 0;
|
|
2678
2546
|
const retainedMessagePrefixSupported = supportsNativeOpenAIResponsesEndpoint(params.model);
|
|
2679
2547
|
const usage = isRecord(response) && isRecord(response.usage) ? response.usage : void 0;
|
|
2680
|
-
if (!isRecord(response) || response.object !== "response.compaction" || !
|
|
2548
|
+
if (!isRecord(response) || response.object !== "response.compaction" || !isOpenAIResponsesCompactionOutput(output, params.model) || retainedItems.length > 0 && (!retainedMessagePrefixSupported || retainedUserMessageCount !== inputUserMessageCount) || !isRecord(item) || item.type !== "compaction" || typeof item.encrypted_content !== "string" || item.encrypted_content.length === 0 || !usage || typeof usage.input_tokens !== "number" || typeof usage.output_tokens !== "number") throw new Error("Responses compact endpoint did not return one trailing compaction item");
|
|
2681
2549
|
return {
|
|
2550
|
+
output,
|
|
2682
2551
|
item,
|
|
2683
2552
|
historyMode: retainedUserMessageCount > 0 ? "retained-users" : "compacted-prefix",
|
|
2684
2553
|
usage,
|
|
@@ -2709,7 +2578,7 @@ function createResponsesTransportExecutor(config) {
|
|
|
2709
2578
|
});
|
|
2710
2579
|
const websocketSessionPolicy = websocketMode ? turnState?.websocket : void 0;
|
|
2711
2580
|
const websocketHeaders = websocketMode ? buildOpenAIClientHeaders(model, context, options?.headers, websocketSessionPolicy?.headers, options?.sessionId) : void 0;
|
|
2712
|
-
const client = config.createClient(model, context, apiKey, options?.headers, turnState?.headers, options?.sessionId);
|
|
2581
|
+
const client = config.createClient(model, context, apiKey, options?.headers, turnState?.headers, options?.sessionId, compactRequest ? createBoundedOpenAIResponsesCompactionFetch(buildGuardedModelFetch(model)) : void 0);
|
|
2713
2582
|
const buildRequest = async (replayMode) => {
|
|
2714
2583
|
let params = config.buildRequest(model, context, responsesOptions, turnState?.metadata, replayMode);
|
|
2715
2584
|
const nextParams = await options?.onPayload?.(params, model);
|
|
@@ -2772,14 +2641,13 @@ function createResponsesTransportExecutor(config) {
|
|
|
2772
2641
|
firstEventAbort = firstEvent;
|
|
2773
2642
|
const requestOptions = buildOpenAISdkRequestOptions(model, firstEvent.signal, {
|
|
2774
2643
|
stream: config.streamRequest,
|
|
2775
|
-
timeoutMs: options?.timeoutMs
|
|
2776
|
-
maxRetries: options?.maxRetries
|
|
2644
|
+
timeoutMs: options?.timeoutMs
|
|
2777
2645
|
});
|
|
2778
2646
|
const websocketSignal = combineWebSocketTimeoutSignal(firstEvent.signal, model, requestOptions?.timeout);
|
|
2779
2647
|
emitModelTransportDebug(log, `[responses] start provider=${model.provider} api=${model.api} model=${model.id} requestIdHash=${redactIdentifier(options?.requestId, { len: 64 })} baseUrl=${formatModelTransportDebugBaseUrl(model.baseUrl)} timeoutMs=${safeDebugValue(requestOptions?.timeout)} apiKey=${apiKey ? "present" : "missing"} ${summarizeResponsesPayload(params)}`);
|
|
2780
2648
|
let continuationBaseline;
|
|
2781
2649
|
const createSseStream = async (initialRequest = continuationClaim?.request ?? params, initialAttemptKind = "initial", initialRejectedCompaction) => {
|
|
2782
|
-
const { stream: responseStream } = await
|
|
2650
|
+
const { stream: responseStream } = await createResponsesStreamWithEncryptedContentRetry({
|
|
2783
2651
|
client,
|
|
2784
2652
|
request: initialRequest,
|
|
2785
2653
|
requestOptions,
|
|
@@ -2933,7 +2801,6 @@ function createOpenAIResponsesTransportStreamFn() {
|
|
|
2933
2801
|
httpContinuation: true,
|
|
2934
2802
|
createClient: createOpenAIResponsesClient,
|
|
2935
2803
|
buildRequest: buildOpenAIResponsesParams,
|
|
2936
|
-
createResponseStream: createResponsesStreamWithEncryptedContentRetry,
|
|
2937
2804
|
pricingOptions: (options, model) => ({
|
|
2938
2805
|
serviceTier: options?.serviceTier,
|
|
2939
2806
|
applyServiceTierPricing: (usage, serviceTier) => applyResponsesServiceTierPricing(usage, serviceTier, model)
|
|
@@ -2945,27 +2812,23 @@ function createAzureOpenAIResponsesTransportStreamFn() {
|
|
|
2945
2812
|
outputApi: "azure-openai-responses",
|
|
2946
2813
|
firstEventTimeoutMs: AZURE_RESPONSES_FIRST_EVENT_TIMEOUT_MS,
|
|
2947
2814
|
createClient: createAzureOpenAIClient,
|
|
2948
|
-
buildRequest: (model, context, options, metadata, replayMode) => buildAzureOpenAIResponsesParams(model, context, options, resolveAzureDeploymentName(model), metadata, replayMode)
|
|
2949
|
-
createResponseStream: createResponsesStreamWithEncryptedContentRetry
|
|
2815
|
+
buildRequest: (model, context, options, metadata, replayMode) => buildAzureOpenAIResponsesParams(model, context, options, resolveAzureDeploymentName(model), metadata, replayMode)
|
|
2950
2816
|
});
|
|
2951
2817
|
}
|
|
2952
|
-
function normalizeAzureBaseUrl(baseUrl) {
|
|
2953
|
-
return baseUrl.replace(/\/+$/, "");
|
|
2954
|
-
}
|
|
2955
2818
|
function resolveAzureDeploymentName(model) {
|
|
2956
2819
|
return resolveAzureDeploymentNameFromMap({
|
|
2957
2820
|
modelId: model.id,
|
|
2958
2821
|
deploymentMap: process.env.AZURE_OPENAI_DEPLOYMENT_NAME_MAP
|
|
2959
2822
|
});
|
|
2960
2823
|
}
|
|
2961
|
-
function createAzureOpenAIClient(model, context, apiKey, optionHeaders, turnHeaders) {
|
|
2962
|
-
const baseURL =
|
|
2824
|
+
function createAzureOpenAIClient(model, context, apiKey, optionHeaders, turnHeaders, _sessionId, fetchOverride) {
|
|
2825
|
+
const baseURL = model.baseUrl.replace(/\/+$/, "");
|
|
2963
2826
|
const clientOptions = {
|
|
2964
2827
|
apiKey,
|
|
2965
2828
|
dangerouslyAllowBrowser: true,
|
|
2966
2829
|
defaultHeaders: buildOpenAIClientHeaders(model, context, optionHeaders, turnHeaders),
|
|
2967
2830
|
baseURL,
|
|
2968
|
-
fetch: buildGuardedModelFetch(model),
|
|
2831
|
+
fetch: fetchOverride ?? buildGuardedModelFetch(model),
|
|
2969
2832
|
...buildOpenAISdkClientOptions(model)
|
|
2970
2833
|
};
|
|
2971
2834
|
if (isOpenAICompatibleAzureResponsesBaseUrl(baseURL)) return new OpenAI(clientOptions);
|
|
@@ -3011,6 +2874,112 @@ const responsesTesting = {
|
|
|
3011
2874
|
if (process.env.VITEST || false) globalThis.openclawOpenAIResponsesTransportTestApi = responsesTesting;
|
|
3012
2875
|
//#endregion
|
|
3013
2876
|
//#region packages/ai/src/transports/provider-compaction-replay.ts
|
|
2877
|
+
function isAssistantReplayMessage(message) {
|
|
2878
|
+
return message.role === "assistant";
|
|
2879
|
+
}
|
|
2880
|
+
/** Resolve from prepared transport facts; never retain or return credential material. */
|
|
2881
|
+
function resolveCompactionReplayEligibility(model, options) {
|
|
2882
|
+
if (OPENAI_RESPONSES_APIS.has(model.api)) return true;
|
|
2883
|
+
return Boolean(options.apiKey?.trim()) && resolveAnthropicServerCompactionPlan(model, options.extraParams, options.apiKey).enabled;
|
|
2884
|
+
}
|
|
2885
|
+
function resolveCompactionSource(messages, model, identity) {
|
|
2886
|
+
if (identity.enabled === false) return;
|
|
2887
|
+
const assistants = messages.filter(isAssistantReplayMessage);
|
|
2888
|
+
const selected = (() => {
|
|
2889
|
+
if (OPENAI_RESPONSES_APIS.has(model.api)) {
|
|
2890
|
+
const responses = resolveNewestOpenAIResponsesCompactionReplay(assistants, model, identity);
|
|
2891
|
+
return responses ? {
|
|
2892
|
+
family: "responses",
|
|
2893
|
+
...responses
|
|
2894
|
+
} : void 0;
|
|
2895
|
+
}
|
|
2896
|
+
if (identity.enabled !== true) return;
|
|
2897
|
+
const anthropic = resolveNewestAnthropicCompaction(assistants, model, identity);
|
|
2898
|
+
return anthropic ? {
|
|
2899
|
+
family: "anthropic",
|
|
2900
|
+
...anthropic
|
|
2901
|
+
} : void 0;
|
|
2902
|
+
})();
|
|
2903
|
+
if (!selected) return;
|
|
2904
|
+
const owner = assistants.find((message) => message === selected.owner);
|
|
2905
|
+
return owner ? {
|
|
2906
|
+
...selected,
|
|
2907
|
+
owner
|
|
2908
|
+
} : void 0;
|
|
2909
|
+
}
|
|
2910
|
+
/** Manual recovery uses the durable client compactor, never a guessed retained-user prefix. */
|
|
2911
|
+
function requiresCompactionReplayRefresh(messages, model, identity) {
|
|
2912
|
+
const checkpoint = resolveCompactionSource(messages, model, identity);
|
|
2913
|
+
return checkpoint?.family === "responses" && checkpoint.mode === "refresh-required";
|
|
2914
|
+
}
|
|
2915
|
+
/** Carry a checkpoint immediately after reference-preserving history limiting, before repair. */
|
|
2916
|
+
function preserveCompactionReplayWindow(source, windowed, model, identity) {
|
|
2917
|
+
const checkpoint = resolveCompactionSource(source, model, identity);
|
|
2918
|
+
if (!checkpoint || windowed.some((message) => message === checkpoint.owner)) return windowed;
|
|
2919
|
+
const owner = checkpoint.owner;
|
|
2920
|
+
const replay = checkpoint.owner.providerReplay;
|
|
2921
|
+
const providerReplay = replay?.type === "openai-responses-retained-compaction" ? replay : {
|
|
2922
|
+
...replay,
|
|
2923
|
+
replayIndex: 0
|
|
2924
|
+
};
|
|
2925
|
+
const suffix = new Set(source.slice(source.indexOf(owner) + 1));
|
|
2926
|
+
return [{
|
|
2927
|
+
...owner,
|
|
2928
|
+
content: [],
|
|
2929
|
+
providerReplay
|
|
2930
|
+
}, ...windowed.filter((message) => suffix.has(message))];
|
|
2931
|
+
}
|
|
2932
|
+
function estimateResponsesWindow(checkpoint, estimate) {
|
|
2933
|
+
return checkpoint.output.reduce((tokens, entry) => {
|
|
2934
|
+
if (entry.type === "compaction") {
|
|
2935
|
+
const { encrypted_content, ...metadata } = entry;
|
|
2936
|
+
return tokens + estimate.text(encrypted_content) + estimate.json(metadata);
|
|
2937
|
+
}
|
|
2938
|
+
const { content, ...metadata } = entry;
|
|
2939
|
+
return tokens + estimate.json(metadata) + content.reduce((sum, block) => {
|
|
2940
|
+
if (block.type === "input_text") {
|
|
2941
|
+
const { text, ...fields } = block;
|
|
2942
|
+
return sum + estimate.text(text) + estimate.json(fields);
|
|
2943
|
+
}
|
|
2944
|
+
if (block.type === "input_image") {
|
|
2945
|
+
const { image_url: _imageUrl, ...fields } = block;
|
|
2946
|
+
return sum + estimate.image() + estimate.json(block.image_url?.startsWith("data:") ? fields : block);
|
|
2947
|
+
}
|
|
2948
|
+
return sum + estimate.json(block);
|
|
2949
|
+
}, 0);
|
|
2950
|
+
}, 0);
|
|
2951
|
+
}
|
|
2952
|
+
/** Estimate the canonical prefix and its tail once, independent of unbound usage snapshots. */
|
|
2953
|
+
function resolveCompactionReplayPressure(messages, model, identity, estimate) {
|
|
2954
|
+
const checkpoint = resolveCompactionSource(messages, model, identity);
|
|
2955
|
+
if (!checkpoint) return;
|
|
2956
|
+
if (checkpoint.family === "responses" && checkpoint.mode === "refresh-required") throw new CompactionReplayRefreshRequiredError();
|
|
2957
|
+
const ownerIndex = messages.findIndex((message) => message === checkpoint.owner);
|
|
2958
|
+
const owner = messages[ownerIndex];
|
|
2959
|
+
if (!owner) return;
|
|
2960
|
+
const prefixTokens = checkpoint.family === "anthropic" ? estimate.text(checkpoint.summary) : checkpoint.mode === "complete-window" ? estimateResponsesWindow(checkpoint, estimate) : estimate.text(checkpoint.item.encrypted_content);
|
|
2961
|
+
const { contextUsage: _staleContextUsage, ...usage } = checkpoint.owner.usage;
|
|
2962
|
+
const tail = [];
|
|
2963
|
+
for (const message of messages.slice(ownerIndex + 1)) {
|
|
2964
|
+
if (!isAssistantReplayMessage(message) || message.usage.contextUsage === void 0) {
|
|
2965
|
+
tail.push(message);
|
|
2966
|
+
continue;
|
|
2967
|
+
}
|
|
2968
|
+
const { contextUsage: _unboundContextUsage, ...billedUsage } = message.usage;
|
|
2969
|
+
tail.push({
|
|
2970
|
+
...message,
|
|
2971
|
+
usage: billedUsage
|
|
2972
|
+
});
|
|
2973
|
+
}
|
|
2974
|
+
return {
|
|
2975
|
+
messages: [{
|
|
2976
|
+
...owner,
|
|
2977
|
+
content: checkpoint.owner.content.slice(checkpoint.replayIndex),
|
|
2978
|
+
usage
|
|
2979
|
+
}, ...tail],
|
|
2980
|
+
prefixTokens
|
|
2981
|
+
};
|
|
2982
|
+
}
|
|
3014
2983
|
/** Whether provider replay state is a prefix-bound server compaction checkpoint. */
|
|
3015
2984
|
function isCompactionReplayCheckpoint(replay) {
|
|
3016
2985
|
const type = replay && typeof replay === "object" ? replay.type : void 0;
|
|
@@ -3306,4 +3275,4 @@ function prepareModelForSimpleCompletion(params) {
|
|
|
3306
3275
|
return applyProviderSimpleCompletionWrapper(apiRegistry, model, cfg);
|
|
3307
3276
|
}
|
|
3308
3277
|
//#endregion
|
|
3309
|
-
export { GEMINI_THOUGHT_SIGNATURE_VALIDATOR_SKIP, MALFORMED_STREAMING_FRAGMENT_ERROR_MESSAGE, applyAnthropicCacheControlToMessages, applyAnthropicEphemeralCacheControlMarkers, applyAnthropicPayloadPolicyToParams, applyOpenAIResponsesPayloadPolicy, assertCodeModeResponsesToolSurface, assignTransportErrorDetails, buildOpenAIClientHeaders, buildOpenAICompletionsParams, buildOpenAISdkClientOptions, buildOpenAISdkRequestOptions, buildTransportAwareSimpleStreamFn, canonicalizeMaxTokensParam, captureOpenAIResponsesCompaction, coerceTransportToolCallArguments, copyProviderAcceptanceObserver, createAnthropicMessagesTransportStreamFn, createAzureOpenAIResponsesTransportStreamFn, createBoundaryAwareStreamFnForModel, createDeepSeekTextFilter, createEmptyTransportUsage, createModelStreamCooperativeScheduler, createOpenAICompletionsTransportStreamFn, createOpenAIProviderAcceptanceHook, createOpenAIResponseHook, createOpenAIResponsesTransportStreamFn, createOpenClawTransportStreamFnForModel, createTransportAwareStreamFnForModel, createWritableTransportEventStream, detectOpenAICompletionsCompat, emitModelTransportDebug, enforceCodeModeResponsesToolSurface, failTransportStream, filterCodeModePayloadTools, finalizeTerminalToolCallArguments, finalizeTransportStream, flattenCompletionMessagesToStringContent, formatModelTransportDebugBaseUrl, formatModelTransportDebugUrl, getCompat, googleFlashSupportsMinimalThinking, hasOpenAICompatibleConversationTurn, isCodeModeModelVisibleToolName, isCompactionReplayCheckpoint, isOpenAICodexResponsesModel, isOpenAICompletionsThinkingEnabled, log, measureUtf8AppendBytes, mergeTransportHeaders, mergeTransportMetadata, normalizeCodexResponsesBaseUrlForOpenAISdk, notifyProviderHttpMetadata, notifyProviderHttpResponse, notifyProviderStreamOpened, parseJsonObjectPreservingUnsafeIntegers, parseJsonPreservingUnsafeIntegers, parseOpenAICompletionsUsage, parseTerminalToolCallArguments, prepareModelForSimpleCompletion, prepareTransportAwareSimpleModel, quoteUnsafeIntegerLiterals, readCodeModePayloadToolName, readOpenAICompletionsContentDeltas, readOpenAICompletionsReasoningBatch, replaceCompactionReplayOwnerContent, requestPreparedOpenAIResponsesCompaction, resolveAnthropicEphemeralCacheControl, resolveAnthropicMessagesUrl, resolveAnthropicPayloadPolicy, resolveAnthropicServerCompactionPlan, resolveCodeModeResponsesVisibleToolNames, resolveMaxTokensParam, resolveModelPayloadDebugMode, resolveModelSseDebugMode, resolveOpenAIClientBaseUrl, resolveOpenAICompletionsCompat, resolveOpenAIReasoningEffortMap, resolveOpenAIResponsesCompactEndpointPlan, resolveOpenAIResponsesPayloadPolicy, resolveOpenAIResponsesServerCompactionPlan, resolveOpenAIStrictToolFlagWithDiagnostics, resolvePromptCacheKey, resolveReplayableResponsesMessageId, resolveTransportAwareSimpleApi, sanitizeNonEmptyTransportPayloadText, sanitizeResponsesImagePayload, sanitizeTransportPayloadText, sortPromptCacheToolsByName as sortTransportToolsByName, stripCompactionReplayCheckpoint, stripCompactionReplayCheckpointInPlace, stripCompletionMessagesToRoleContent, throwIfModelStreamAborted, transportAbortError, usesNativeOpenAICodexResponsesBackend, withProviderAcceptanceObserver, withProviderResponseHook };
|
|
3278
|
+
export { CompactionReplayRefreshRequiredError, GEMINI_THOUGHT_SIGNATURE_VALIDATOR_SKIP, MALFORMED_STREAMING_FRAGMENT_ERROR_MESSAGE, applyAnthropicCacheControlToMessages, applyAnthropicEphemeralCacheControlMarkers, applyAnthropicPayloadPolicyToParams, applyOpenAIResponsesPayloadPolicy, assertCodeModeResponsesToolSurface, assignTransportErrorDetails, buildOpenAIClientHeaders, buildOpenAICompletionsParams, buildOpenAISdkClientOptions, buildOpenAISdkRequestOptions, buildTransportAwareSimpleStreamFn, canonicalizeMaxTokensParam, captureOpenAIResponsesCompaction, coerceTransportToolCallArguments, copyProviderAcceptanceObserver, createAnthropicMessagesTransportStreamFn, createAzureOpenAIResponsesTransportStreamFn, createBoundaryAwareStreamFnForModel, createDeepSeekTextFilter, createEmptyTransportUsage, createModelStreamCooperativeScheduler, createOpenAICompletionsTransportStreamFn, createOpenAIProviderAcceptanceHook, createOpenAIResponseHook, createOpenAIResponsesTransportStreamFn, createOpenClawTransportStreamFnForModel, createTransportAwareStreamFnForModel, createWritableTransportEventStream, detectOpenAICompletionsCompat, emitModelTransportDebug, enforceCodeModeResponsesToolSurface, failTransportStream, filterCodeModePayloadTools, finalizeTerminalToolCallArguments, finalizeTransportStream, flattenCompletionMessagesToStringContent, formatModelTransportDebugBaseUrl, formatModelTransportDebugUrl, getCompat, googleFlashSupportsMinimalThinking, hasOpenAICompatibleConversationTurn, isCodeModeModelVisibleToolName, isCompactionReplayCheckpoint, isOpenAICodexResponsesModel, isOpenAICompletionsThinkingEnabled, log, measureUtf8AppendBytes, mergeTransportHeaders, mergeTransportMetadata, normalizeCodexResponsesBaseUrlForOpenAISdk, notifyProviderHttpMetadata, notifyProviderHttpResponse, notifyProviderStreamOpened, parseJsonObjectPreservingUnsafeIntegers, parseJsonPreservingUnsafeIntegers, parseOpenAICompletionsUsage, parseTerminalToolCallArguments, prepareModelForSimpleCompletion, prepareTransportAwareSimpleModel, preserveCompactionReplayWindow, quoteUnsafeIntegerLiterals, readCodeModePayloadToolName, readOpenAICompletionsContentDeltas, readOpenAICompletionsReasoningBatch, replaceCompactionReplayOwnerContent, requestPreparedOpenAIResponsesCompaction, requiresCompactionReplayRefresh, resolveAnthropicEphemeralCacheControl, resolveAnthropicMessagesUrl, resolveAnthropicPayloadPolicy, resolveAnthropicServerCompactionPlan, resolveCodeModeResponsesVisibleToolNames, resolveCompactionReplayEligibility, resolveCompactionReplayPressure, resolveMaxTokensParam, resolveModelPayloadDebugMode, resolveModelSseDebugMode, resolveOpenAIClientBaseUrl, resolveOpenAICompletionsCompat, resolveOpenAIReasoningEffortMap, resolveOpenAIResponsesCompactEndpointPlan, resolveOpenAIResponsesPayloadPolicy, resolveOpenAIResponsesServerCompactionPlan, resolveOpenAIStrictToolFlagWithDiagnostics, resolvePromptCacheKey, resolveReplayableResponsesMessageId, resolveTransportAwareSimpleApi, sanitizeNonEmptyTransportPayloadText, sanitizeResponsesImagePayload, sanitizeTransportPayloadText, sortPromptCacheToolsByName as sortTransportToolsByName, stripCompactionReplayCheckpoint, stripCompactionReplayCheckpointInPlace, stripCompletionMessagesToRoleContent, throwIfModelStreamAborted, transportAbortError, usesNativeOpenAICodexResponsesBackend, withProviderAcceptanceObserver, withProviderResponseHook };
|