@openclaw/ai 2026.10.10 → 2026.11.5-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -1
- package/dist/.source-module-urls/fe058cc430242ce2ab0dfbcbe153e240a52cf9c3072c3dc0a73e5f956b6ba49b.json +1 -0
- package/dist/anthropic-CTND83W3.mjs +182 -0
- package/dist/{anthropic-payload-policy-rqCq9sT_.d.mts → anthropic-payload-policy-CXCJ5Pmj.d.mts} +21 -4
- package/dist/{anthropic-stream-reducer-C__ByTq1.mjs → anthropic-stream-lifecycle-rJe4OH5H.mjs} +845 -649
- package/dist/{anthropic-tool-projection-JTvMo4KG.d.mts → anthropic-tool-projection-D5DyrL6C.d.mts} +6 -7
- package/dist/{anthropic-tool-projection-DA_KeluM.mjs → anthropic-tool-projection-dGRfr4iT.mjs} +22 -32
- package/dist/{api-registry-gDt0faai.d.mts → api-registry-DY2MLUyg.d.mts} +2 -2
- package/dist/assistant-output-CD4kY9gu.mjs +16 -0
- package/dist/{azure-openai-responses-DHzTwi-y.mjs → azure-openai-responses-BhoLtP4Z.mjs} +46 -52
- package/dist/{cloudflare-Dttf8jKq.mjs → cloudflare-BJ2_Xabx.mjs} +1 -1
- package/dist/{credential-redaction-XvsPf7Yi.d.mts → credential-redaction-DrgndwTJ.d.mts} +5 -3
- package/dist/{deferred-event-buffer-DAvyP7qA.mjs → deferred-event-buffer-tIGkTkTm.mjs} +1 -2
- package/dist/{diagnostics-Cv7cW3pS.mjs → diagnostics-CloVGQiK.mjs} +42 -19
- package/dist/{diagnostics-DzrF1h4J.mjs → diagnostics-o1PrVNQb.mjs} +11 -4
- package/dist/diagnostics.d.mts +6 -7
- package/dist/diagnostics.mjs +4 -4
- package/dist/{env-api-keys-Xd8dm_aV.mjs → env-api-keys-BuHc86ya.mjs} +1 -26
- package/dist/event-stream-B4ZcSvsu.d.mts +1 -0
- package/dist/{event-stream-CzpE1g_o.d.mts → event-stream-BYmtRe8-.d.mts} +1 -1
- package/dist/event-stream.d.mts +2 -2
- package/dist/event-stream.mjs +1 -2
- package/dist/expect-lbe3Hgrh.mjs +8 -0
- package/dist/{github-copilot-request-facts-F-EmvkpW.mjs → github-copilot-request-facts-BZ_EMo7X.mjs} +1 -1
- package/dist/{google-CZ6uGVkV.mjs → google-1uObh-eI.mjs} +7 -8
- package/dist/{google-interactions-qd4flmND.mjs → google-interactions-CY8Xb87S.mjs} +208 -233
- package/dist/{google-messages-B-svbJuN.mjs → google-messages-CwBqSoa4.mjs} +16 -13
- package/dist/{google-provider-stream-DlhaCvCf.mjs → google-provider-stream-D30s9EZp.mjs} +17 -10
- package/dist/{google-shared-Cif7nve-.mjs → google-shared-li0lmEZK.mjs} +70 -42
- package/dist/{google-vertex-BZTcYnWU.mjs → google-vertex-B5CHglca.mjs} +3 -3
- package/dist/{host-rCxf5Tjd.mjs → host-DX7ORpeH.mjs} +57 -46
- package/dist/{host-jJOffdlW.d.mts → host-ccbwPC3A.d.mts} +17 -9
- package/dist/{host-policy-Ci1cKluf.mjs → host-policy-jCZebuXx.mjs} +2 -2
- package/dist/index-Bczt0MnO.d.mts +17 -0
- package/dist/index.d.mts +8 -7
- package/dist/index.mjs +9 -7
- package/dist/internal/anthropic.d.mts +21 -26
- package/dist/internal/anthropic.mjs +6 -6
- package/dist/internal/google-model-family.mjs +1 -1
- package/dist/internal/google.d.mts +15 -0
- package/dist/internal/google.mjs +1 -0
- package/dist/internal/model-request-body.d.mts +37 -0
- package/dist/internal/model-request-body.mjs +106 -0
- package/dist/internal/openai-completions-compat.d.mts +5 -1
- package/dist/internal/openai-completions-compat.mjs +3 -2
- package/dist/internal/openai-responses-payload-policy.d.mts +2 -2
- package/dist/internal/openai-responses-payload-policy.mjs +2 -2
- package/dist/internal/openai.d.mts +14 -12
- package/dist/internal/openai.mjs +11 -10
- package/dist/internal/reasoning-tag-text-partitioner.d.mts +26 -0
- package/dist/{reasoning-tag-text-partitioner-DzlRubwU.mjs → internal/reasoning-tag-text-partitioner.mjs} +313 -122
- package/dist/internal/retry-after.d.mts +2 -2
- package/dist/internal/retry-after.mjs +165 -27
- package/dist/internal/runtime.d.mts +15 -41
- package/dist/internal/runtime.mjs +9 -10
- package/dist/internal/shared.d.mts +21 -25
- package/dist/internal/shared.mjs +9 -98
- package/dist/internal/tool-schema.d.mts +10 -10
- package/dist/internal/tool-schema.mjs +4 -4
- package/dist/{llm-request-activity-CfMuh5cC.mjs → llm-request-activity-DzaHoRAU.mjs} +2 -2
- package/dist/mistral-F5_asrmU.mjs +3741 -0
- package/dist/mistral.LICENSE +201 -0
- package/dist/{model-transport-url-BrsjjdjR.d.mts → model-transport-url-BdksnBqu.d.mts} +6 -8
- package/dist/{number-coercion-37gmNkuA.mjs → number-coercion-C7HsBgUL.mjs} +7 -2
- package/dist/observe-async-iterator-AlARO5wS.d.mts +178 -0
- package/dist/observe-async-iterator-DgmegcZR.mjs +181 -0
- package/dist/{openai-chatgpt-responses-iGYDPbmc.mjs → openai-chatgpt-responses-BIK7HROH.mjs} +61 -80
- package/dist/{openai-completions-CDy5u1mv.mjs → openai-completions-ClJ7QHEB.mjs} +5 -5
- package/dist/{openai-completions-compat-CBvb2eld.d.mts → openai-completions-compat-CJ-NsDzg.d.mts} +12 -6
- package/dist/{openai-completions-compat-CJ0OXZgi.mjs → openai-completions-compat-CstlTQuF.mjs} +74 -50
- package/dist/openai-completions-reasoning-replay-BwT1xwRI.mjs +45 -0
- package/dist/{openai-completions-transport-DLrm5EWi.mjs → openai-completions-transport-C6J4_oGf.mjs} +501 -563
- package/dist/{openai-prompt-cache-DgjD-UL5.d.mts → openai-prompt-cache-BZGaIWYh.d.mts} +4 -4
- package/dist/{openai-prompt-cache-h8vXRiaH.mjs → openai-prompt-cache-CgDoFhO0.mjs} +5 -4
- package/dist/openai-responses-Beifmf1s.mjs +89 -0
- package/dist/{openai-responses-compaction-replay-DUBbsfku.d.mts → openai-responses-compaction-replay-CNHk6k53.d.mts} +4 -4
- package/dist/{openai-responses-contracts-gnl6ZRs1.d.mts → openai-responses-contracts-BXMcvO7F.d.mts} +4 -10
- package/dist/{openai-responses-contracts-DCG51Us0.mjs → openai-responses-contracts-xU-n9AJJ.mjs} +36 -37
- package/dist/{openai-responses-endpoint-JbBT8IDv.mjs → openai-responses-endpoint-DCkURKS0.mjs} +55 -8
- package/dist/{openai-responses-payload-policy-BzM52TTH.d.mts → openai-responses-payload-policy-DyE30gdD.d.mts} +7 -7
- package/dist/{openai-responses-request-lifecycle-DuMpdA6y.mjs → openai-responses-request-lifecycle-o-ODC_rF.mjs} +12 -26
- package/dist/{openai-responses-shared-CNfHudFg.mjs → openai-responses-shared-CrFDkZ0N.mjs} +637 -389
- package/dist/{openai-responses-terminal-usage-CpVjkqn-.d.mts → openai-responses-terminal-usage-D7IhRA6i.d.mts} +9 -3
- package/dist/{openai-tool-schema-CGhEl7ao.mjs → openai-tool-schema-CsoYgnWy.mjs} +97 -122
- package/dist/otel-D-BkX8bB.mjs +766 -0
- package/dist/{overflow-OF3PgPbw.mjs → overflow-CpApyjG2.mjs} +1 -1
- package/dist/{positive-integer-Bb4Evc7L.mjs → positive-integer-DiqE5vNi.mjs} +2 -3
- package/dist/{prompt-cache-stability-D_MeCQFI.mjs → prompt-cache-stability-w-ICeyOI.mjs} +1 -1
- package/dist/{provider-error-qtZD2inE.mjs → provider-error-DD-fo4Rz.mjs} +71 -234
- package/dist/{provider-options-Bo8GzTGX.d.mts → provider-options-Mo8NM5d1.d.mts} +15 -4
- package/dist/{provider-replay-context-BC23HyZo.mjs → provider-replay-context-xyU7-CiT.mjs} +2 -2
- package/dist/provider-transcript-transform-BHq3Q4nc.mjs +32 -0
- package/dist/{provider-transport-turn-state-B11rmZpv.mjs → provider-transport-turn-state-DQd9K4Pd.mjs} +3 -3
- package/dist/{provider-types-ODq57rG_.d.mts → provider-types-B1e98js5.d.mts} +6 -4
- package/dist/provider-types.d.mts +7 -6
- package/dist/provider-types.mjs +2 -1
- package/dist/providers.d.mts +2 -2
- package/dist/providers.mjs +26 -29
- package/dist/{record-coerce-CNDovvft.mjs → record-coerce-BQaoiN3r.mjs} +4 -1
- package/dist/request-headers-DO4Mqhw1.mjs +10 -0
- package/dist/{required-api-key-D088S4Cd.mjs → required-api-key-2zZTkmsi.mjs} +1 -1
- package/dist/retry-after-DnHBlFS2.d.mts +45 -0
- package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
- package/dist/{sanitize-unicode-ZqVLLEKC.d.mts → sanitize-unicode-BISmUlUv.d.mts} +2 -2
- package/dist/{simple-options-BdJJbzZk.mjs → simple-options-tLSeECry.mjs} +108 -82
- package/dist/src-BUsVkrNt.mjs +105 -0
- package/dist/{src-CyA0zJnt.mjs → src-CQ7nH2mL.mjs} +4 -7
- package/dist/stable-stringify-CchQEmeA.mjs +84 -0
- package/dist/{stream-DQqGjhbq.mjs → stream-DrtAWu7c.mjs} +2 -6
- package/dist/{stream-first-event-timeout-D_TfJHRJ.mjs → stream-first-event-timeout-B7RcufAV.mjs} +16 -13
- package/dist/{string-coerce-Cj8sqWHx.mjs → string-coerce-BCuWMIrk.mjs} +1 -1
- package/dist/string-normalization-B8TDDBX_.mjs +32 -0
- package/dist/telemetry-B9f7K_Xe.mjs +582 -0
- package/dist/{tool-schema-json-projection-Cvq69Ajp.mjs → tool-schema-json-projection-BQpiJlXJ.mjs} +53 -69
- package/dist/{transport-stream-shared-DdnJGEj0.mjs → transport-stream-shared-D2uFMhMc.mjs} +177 -93
- package/dist/{transport-stream-shared-8ru8eX4s.d.mts → transport-stream-shared-D3IAU4jn.d.mts} +29 -15
- package/dist/{transport-utils-CcCAuFVS.mjs → transport-utils-Da_39MYi.mjs} +23 -38
- package/dist/transports.d.mts +39 -38
- package/dist/transports.mjs +214 -295
- package/dist/{types-CVYzKrMl.d.mts → types-BVdTf0YV.d.mts} +38 -3
- package/dist/types-Cb3-5WM9.d.mts +1 -0
- package/dist/{types-BXd0kI8-.mjs → types-OVEWUaDh.mjs} +3 -1
- package/dist/types.d.mts +7 -6
- package/dist/types.mjs +7 -5
- package/dist/{validation-9FSkE8T-.mjs → validation-DGXqfvkj.mjs} +45 -27
- package/dist/{validation-BQ5u20Ru.d.mts → validation-QmyD0E5A.d.mts} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -2
- package/package.json +40 -6
- package/dist/anthropic-B54Ts1tV.mjs +0 -221
- package/dist/assistant-output-DbgdWAhJ.mjs +0 -47
- package/dist/event-stream-CDpFza-M.d.mts +0 -1
- package/dist/index-DSprYWaz.d.mts +0 -185
- package/dist/mistral-C_ImzxlK.mjs +0 -512
- package/dist/model-request-body-BD5vy4rP.d.mts +0 -17
- package/dist/openai-responses-Cp2QPq7K.mjs +0 -87
- package/dist/retry-after-sw-XX8aC.d.mts +0 -15
- package/dist/types-CBJthzJX.d.mts +0 -1
package/dist/{openai-completions-transport-DLrm5EWi.mjs → openai-completions-transport-C6J4_oGf.mjs}
RENAMED
|
@@ -1,42 +1,51 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
3
|
-
import { t as appendAssistantMessageDiagnostic } from "./diagnostics-
|
|
1
|
+
import "./src-CQ7nH2mL.mjs";
|
|
2
|
+
import { m as isRuntimeContextMessage, p as hasRuntimeContextMarker, v as runtimeContextContentToText } from "./types-OVEWUaDh.mjs";
|
|
3
|
+
import { s as recordSuppressedReasoning, t as appendAssistantMessageDiagnostic } from "./diagnostics-o1PrVNQb.mjs";
|
|
4
|
+
import { t as omitNullRequestHeaders } from "./request-headers-DO4Mqhw1.mjs";
|
|
4
5
|
import { r as appendAssistantThinking } from "./event-stream-X2gmsUWv.mjs";
|
|
5
|
-
import { i as asOptionalRecord, o as isRecord, r as asOptionalObjectRecord } from "./record-coerce-
|
|
6
|
-
import { c as readNonEmptyStringPreservingWhitespace, t as hasNonEmptyString } from "./string-coerce-
|
|
7
|
-
import { n as asNonNegativeFiniteNumber, r as asPositiveFiniteNumber } from "./number-coercion-
|
|
8
|
-
import { N as isImageWithMediaPayload, a as resolveAiTransportHeaderSentinels, r as getAiTransportHost } from "./host-
|
|
9
|
-
import { N as
|
|
6
|
+
import { i as asOptionalRecord, o as isRecord, r as asOptionalObjectRecord } from "./record-coerce-BQaoiN3r.mjs";
|
|
7
|
+
import { c as readNonEmptyStringPreservingWhitespace, t as hasNonEmptyString } from "./string-coerce-BCuWMIrk.mjs";
|
|
8
|
+
import { n as asNonNegativeFiniteNumber, r as asPositiveFiniteNumber } from "./number-coercion-C7HsBgUL.mjs";
|
|
9
|
+
import { N as isImageWithMediaPayload, O as calculateCost, a as resolveAiTransportHeaderSentinels, r as getAiTransportHost } from "./host-DX7ORpeH.mjs";
|
|
10
|
+
import { E as isOpenAIGpt6Model, N as supportsOpenAITemperature, R as resolveOpenAIThinkingApi, S as applyOpenAICompletionsToolReasoning, _ as parseOpenAIResponsesWebSocketServerError, b as isResponsesServiceTierRejection, d as OpenAIResponsesWebSocketPreDispatchError, f as OpenAIResponsesWebSocketSafeRetryError, g as isResponsesTerminalEventType, l as OPENAI_RESPONSES_TOOL_CALL_PROVIDERS, r as OPENAI_CODEX_RESPONSES_DEFAULT_INSTRUCTIONS, t as AZURE_RESPONSES_FIRST_EVENT_TIMEOUT_MS, u as OpenAIResponsesWebSocketPostDispatchError, x as nextResponsesServiceTier, y as responsesServiceTierObserver } from "./openai-responses-contracts-xU-n9AJJ.mjs";
|
|
10
11
|
import { n as getSessionResourceOwnerId, r as registerSessionResourceCleanup } from "./session-resources-vKvGIE3J.mjs";
|
|
11
|
-
import { c as
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
12
|
+
import { c as truncateUtf16Safe } from "./provider-error-DD-fo4Rz.mjs";
|
|
13
|
+
import { t as estimateStringChars } from "./src-BUsVkrNt.mjs";
|
|
14
|
+
import { r as resolveOpenAIPromptCacheParams } from "./openai-prompt-cache-CgDoFhO0.mjs";
|
|
15
|
+
import { g as applyResponsesCacheWritePricing, p as hasOnlyResponsesFunctionTools, r as emitModelTransportDebug, t as formatModelTransportDebugBaseUrl, u as DegenerateToolCallArgumentsError, v as mapResponsesTerminalUsage, y as readResponsesReasoningTokens } from "./diagnostics-CloVGQiK.mjs";
|
|
16
|
+
import { o as supportsModelTools } from "./transport-utils-Da_39MYi.mjs";
|
|
17
|
+
import { t as stableStringify } from "./stable-stringify-CchQEmeA.mjs";
|
|
18
|
+
import { t as createZeroUsage } from "./usage-CJH5D6Ea.mjs";
|
|
19
|
+
import { a as resolveOpenAICompletionsCompat, c as isAzureOpenAICompatibleHost, d as shouldOmitOllamaCompatResponseFormat, i as isOpenAICodexResponsesModel, l as resolveOpenAICompletionsResponseFormat, n as isKnownOpenAIEndpoint, r as isNativeOpenAIEndpoint, s as usesNativeOpenAICodexResponsesBackend, t as detectOpenAICompletionsCompat, u as resolveOpenAIResponsesTextFormat } from "./openai-completions-compat-CstlTQuF.mjs";
|
|
20
|
+
import { t as buildGuardedModelFetch } from "./host-policy-jCZebuXx.mjs";
|
|
21
|
+
import { i as resolveCacheRetention, r as buildCopilotDynamicHeaders } from "./cloudflare-BJ2_Xabx.mjs";
|
|
18
22
|
import { t as sanitizeSurrogates } from "./sanitize-unicode-CRGuMONI.mjs";
|
|
19
|
-
import { r as sortPromptCacheToolsByName } from "./prompt-cache-stability-
|
|
20
|
-
import { C as
|
|
21
|
-
import { A as
|
|
22
|
-
import { C as
|
|
23
|
-
import { n as getEnvApiKey } from "./env-api-keys-
|
|
24
|
-
import {
|
|
25
|
-
import { n as
|
|
26
|
-
import { t as
|
|
23
|
+
import { r as sortPromptCacheToolsByName } from "./prompt-cache-stability-w-ICeyOI.mjs";
|
|
24
|
+
import { C as stripSystemPromptCacheBoundary, S as splitSystemPromptRelocatableBoundary, a as describeToolResultMediaPlaceholder, c as extractToolResultText, d as measuredRequestPressure, f as preparedRequestSuffix, p as reasoningTagTextPolicy, r as clampMaxTokensToModel, u as codeModeToolSurfaceObserver, w as stripSystemPromptRelocatableBoundary, x as splitSystemPromptCacheBoundary, y as prepareSystemPrompt } from "./simple-options-tLSeECry.mjs";
|
|
25
|
+
import { A as parseStreamingJson, C as withProviderResponseHook, D as shortHash, N as racePromiseWithAbortSignal, O as createToolArgumentPreviewSchedule, b as throwIfModelStreamAborted, c as failTransportStream, d as iterateModelStream, g as notifyProviderStreamOpened, l as finalizeTerminalToolCallArguments, o as createWritableTransportEventStream, u as finalizeTransportStream, x as transportAbortError } from "./transport-stream-shared-D2uFMhMc.mjs";
|
|
26
|
+
import { C as sha256Hex, S as redactIdentifier } from "./tool-schema-json-projection-BQpiJlXJ.mjs";
|
|
27
|
+
import { n as getEnvApiKey } from "./env-api-keys-BuHc86ya.mjs";
|
|
28
|
+
import { t as notifyLlmRequestActivity } from "./llm-request-activity-DzaHoRAU.mjs";
|
|
29
|
+
import { n as isProviderReplayContext, r as providerReplayContextMatches, t as buildProviderReplayContext } from "./provider-replay-context-xyU7-CiT.mjs";
|
|
30
|
+
import { t as transformProviderMessages } from "./provider-transcript-transform-BHq3Q4nc.mjs";
|
|
31
|
+
import { prepareModelRequestBody } from "./internal/model-request-body.mjs";
|
|
32
|
+
import { PROVIDER_MODEL_INPUT, resolveProviderContext } from "./provider-types.mjs";
|
|
33
|
+
import { t as createAssistantOutput } from "./assistant-output-CD4kY9gu.mjs";
|
|
27
34
|
import { n as resolveOpencodeSessionHeaders } from "./session-affinity-DA4WHv1h.mjs";
|
|
28
35
|
import { isGoogleGemini3ThinkingLevelModel } from "./internal/google-model-family.mjs";
|
|
29
36
|
import "./types.mjs";
|
|
30
|
-
import { $ as isConfigurationUpdate, A as summarizeResponsesPayload, At as
|
|
31
|
-
import { i as createOpenAIProviderClient, n as resolveProviderSimpleCompletionHeaders, r as resolveProviderTransportTurnState, t as filterProviderTurnHeadersForExplicitOpencodeSession } from "./provider-transport-turn-state-
|
|
32
|
-
import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "./stream-first-event-timeout-
|
|
37
|
+
import { $ as isConfigurationUpdate, A as summarizeResponsesPayload, At as log, B as recordResponsesInputReplay, C as isInvalidEncryptedContentError, Ct as toOpenAIResponsesToolChoice, Dt as createResponseModelTracker, E as resolveNextResponsesEncryptedContentAttempt, Ft as resolveOpenAIClientBaseUrl, G as responsesContinuationPrefixFingerprint, H as claimOpenAIResponsesHttpContinuation, I as convertResponsesMessages, It as resolvePromptCacheKey, K as responsesContinuationRequestFingerprint, Lt as withOpenAIErrorResponseHook, Mt as parseOpenAICompletionsUsage, Nt as readOpenAICompletionsContentDeltas, O as observeResponsesTransportFailure, Ot as detachPartialSnapshot, P as buildResponsesInputMessage, Pt as readOpenAICompletionsReasoningBatch, S as createResponsesStreamWithRecovery, St as reconcileOpenAIResponsesToolChoice, T as resolveAzureOpenAIApiVersion, Tt as createOpenAIProviderAcceptanceHook, U as recordResponsesContinuationState, V as responsesInputFingerprint, W as resolveResponsesContinuationRequest, _t as resolveOpenAIRequestReasoning, a as prepareResponsesTools, bt as projectOpenAITools, c as observeResponsesStream, ct as buildOpenAIClientHeaders, dt as enforceCodeModeResponsesToolSurface, et as replayResponsesReasoningUpdates, gt as resolveOpenAIStrictToolFlagWithDiagnostics, ht as resolveCodeModeResponsesVisibleToolNames, j as recordResponsesContextUsage, jt as measureUtf8AppendBytes, k as safeDebugValue, kt as isOpenAICompletionsThinkingEnabled, lt as buildOpenAISdkClientOptions, n as applyResponsesServiceTierPricing, ot as suppressOpenAIResponsesCompaction, pt as getCompat, rt as buildOpenAIResponsesReasoningReplayMetadata, s as processResponsesStream, st as assertCodeModeResponsesToolSurface, tt as supportsResponsesReasoningUpdate, ut as buildOpenAISdkRequestOptions, vt as resolveOpenAISimpleReasoningEffort, w as readResponsesRecoveryEvent, wt as GEMINI_THOUGHT_SIGNATURE_VALIDATOR_SKIP, xt as reconcileOpenAICompletionsToolChoice, yt as prepareOpenAITools, z as readResponsesInputReplayState } from "./openai-responses-shared-CrFDkZ0N.mjs";
|
|
38
|
+
import { i as createOpenAIProviderClient, n as resolveProviderSimpleCompletionHeaders, r as resolveProviderTransportTurnState, t as filterProviderTurnHeadersForExplicitOpencodeSession } from "./provider-transport-turn-state-DQd9K4Pd.mjs";
|
|
39
|
+
import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "./stream-first-event-timeout-B7RcufAV.mjs";
|
|
33
40
|
import { t as boundResponseBody } from "./streaming-byte-guard-DBXr1XYn.mjs";
|
|
34
|
-
import {
|
|
41
|
+
import { m as withPreparedToolSchemaNormalization, p as normalizeToolSchema, r as normalizeOpenAIStrictToolParameters, x as prepareOpenAIFunctionTool } from "./openai-tool-schema-CsoYgnWy.mjs";
|
|
42
|
+
import { t as requiresReasoningContentReplay } from "./openai-completions-reasoning-replay-BwT1xwRI.mjs";
|
|
35
43
|
import { t as mapOpenAIStopReason } from "./openai-stop-reason-8s70vDXj.mjs";
|
|
36
44
|
import { i as resolveAzureDeploymentNameFromMap, t as isOpenAICompatibleAzureResponsesBaseUrl } from "./azure-openai-responses-client-compat-D0dvJMbZ.mjs";
|
|
37
|
-
import { a as isOpenAIResponsesCompactionOutput, c as
|
|
38
|
-
import { a as createResponsesV2CompactionCollector, i as createResponsesPromptEgressObserver, n as responsesRequestLifecycle, o as claimResponsesCompactRequest, r as withResponsesRequestAcceptance, t as independentResponsesRequest } from "./openai-responses-request-lifecycle-
|
|
45
|
+
import { a as isOpenAIResponsesCompactionOutput, c as sanitizeResponsesImagePayload, f as resolveOpenAIResponsesPayloadPolicy, i as getOpenAIResponsesCompactionOutputError, l as applyOpenAIResponsesPayloadPolicy, n as supportsNativeOpenAIResponsesEndpoint, r as createBoundedOpenAIResponsesCompactionFetch, t as isOfficialOpenAIResponsesBaseUrl } from "./openai-responses-endpoint-DCkURKS0.mjs";
|
|
46
|
+
import { a as createResponsesV2CompactionCollector, i as createResponsesPromptEgressObserver, n as responsesRequestLifecycle, o as claimResponsesCompactRequest, r as withResponsesRequestAcceptance, t as independentResponsesRequest } from "./openai-responses-request-lifecycle-o-ODC_rF.mjs";
|
|
39
47
|
import { randomUUID } from "node:crypto";
|
|
48
|
+
import { isDeepStrictEqual } from "node:util";
|
|
40
49
|
import OpenAI, { AzureOpenAI } from "openai";
|
|
41
50
|
import { ResponsesWS } from "openai/resources/responses/ws.js";
|
|
42
51
|
//#region packages/ai/src/transports/deepseek-dsml-grammar.ts
|
|
@@ -169,16 +178,15 @@ function canonicalizeMaxTokensParam(params) {
|
|
|
169
178
|
}
|
|
170
179
|
//#endregion
|
|
171
180
|
//#region packages/ai/src/transports/openai-compatible-conversation-turn.ts
|
|
172
|
-
function hasNonEmptyContentPart(part) {
|
|
173
|
-
if (!part || typeof part !== "object") return false;
|
|
174
|
-
const record = part;
|
|
175
|
-
if (record.type === "text") return hasNonEmptyString(record.text);
|
|
176
|
-
return true;
|
|
177
|
-
}
|
|
178
181
|
function hasNonEmptyMessageContent(content) {
|
|
179
182
|
if (hasNonEmptyString(content)) return true;
|
|
180
183
|
if (!Array.isArray(content)) return false;
|
|
181
|
-
return content.some(
|
|
184
|
+
return content.some((part) => {
|
|
185
|
+
if (!part || typeof part !== "object") return false;
|
|
186
|
+
const record = part;
|
|
187
|
+
if (record.type === "text") return hasNonEmptyString(record.text);
|
|
188
|
+
return true;
|
|
189
|
+
});
|
|
182
190
|
}
|
|
183
191
|
/** Returns whether an OpenAI-compatible messages payload contains a usable turn. */
|
|
184
192
|
function hasOpenAICompatibleConversationTurn(messages) {
|
|
@@ -206,7 +214,7 @@ function resolveCompletionsCacheControl(compat, retention, openRouterRoute) {
|
|
|
206
214
|
};
|
|
207
215
|
}
|
|
208
216
|
/** Shared Chat Completions policy; repeated wrapper application preserves existing checkpoints. */
|
|
209
|
-
function applyCompletionsAnthropicCacheControl(payload, cacheControl = { type: "ephemeral" }, cacheOptOutIndexes = /* @__PURE__ */ new Set(), markTools = true, markMessages = true) {
|
|
217
|
+
function applyCompletionsAnthropicCacheControl(payload, cacheControl = { type: "ephemeral" }, cacheOptOutIndexes = /* @__PURE__ */ new Set(), markTools = true, markMessages = true, systemOnly = false) {
|
|
210
218
|
if (shapedPayloads.has(payload)) return;
|
|
211
219
|
shapedPayloads.add(payload);
|
|
212
220
|
const messages = Array.isArray(payload.messages) ? payload.messages : [];
|
|
@@ -252,13 +260,14 @@ function applyCompletionsAnthropicCacheControl(payload, cacheControl = { type: "
|
|
|
252
260
|
}
|
|
253
261
|
return false;
|
|
254
262
|
};
|
|
255
|
-
if (markTools && lastToolIndex >= 0) tools[lastToolIndex] = {
|
|
263
|
+
if (!systemOnly && markTools && lastToolIndex >= 0) tools[lastToolIndex] = {
|
|
256
264
|
...tools[lastToolIndex],
|
|
257
265
|
cache_control: cacheControl
|
|
258
266
|
};
|
|
259
267
|
if (!markMessages) return;
|
|
260
268
|
const system = messages.find((message) => isRecord(message) && (message.role === "system" || message.role === "developer"));
|
|
261
269
|
if (isRecord(system)) markText(system, true);
|
|
270
|
+
if (systemOnly) return;
|
|
262
271
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
263
272
|
const message = messages[i];
|
|
264
273
|
if (!cacheOptOutIndexes.has(i) && isRecord(message) && (message.role === "user" || message.role === "tool") && markText(message, false)) return;
|
|
@@ -364,12 +373,6 @@ function createOpenAICompletionsToolCallDeltaNormalizer() {
|
|
|
364
373
|
toolCalls: []
|
|
365
374
|
}));
|
|
366
375
|
};
|
|
367
|
-
const bufferFollowingDelta = (delta) => {
|
|
368
|
-
const nextDeltaBytes = Buffer.byteLength(JSON.stringify(delta), "utf8");
|
|
369
|
-
if (pendingFollowingDeltaBytes + nextDeltaBytes > MAX_BUFFERED_LEGACY_FOLLOWING_DELTA_BYTES || pendingFollowingDeltas.length >= MAX_BUFFERED_LEGACY_FOLLOWING_DELTAS) throw new Error("Exceeded legacy tool-call content buffer limit");
|
|
370
|
-
pendingFollowingDeltaBytes += nextDeltaBytes;
|
|
371
|
-
pendingFollowingDeltas.push(delta);
|
|
372
|
-
};
|
|
373
376
|
return (delta, finishReason) => {
|
|
374
377
|
const ordinaryDelta = { ...delta };
|
|
375
378
|
delete ordinaryDelta.function_call;
|
|
@@ -406,8 +409,12 @@ function createOpenAICompletionsToolCallDeltaNormalizer() {
|
|
|
406
409
|
const hadPendingLegacyCall = pendingLegacyToolCall !== void 0;
|
|
407
410
|
const leadingDeltas = [];
|
|
408
411
|
if (hasOpenAICompletionsDeltaContent(ordinaryDelta)) {
|
|
409
|
-
if (hadPendingLegacyCall)
|
|
410
|
-
|
|
412
|
+
if (hadPendingLegacyCall) {
|
|
413
|
+
const nextDeltaBytes = Buffer.byteLength(JSON.stringify(ordinaryDelta), "utf8");
|
|
414
|
+
if (pendingFollowingDeltaBytes + nextDeltaBytes > MAX_BUFFERED_LEGACY_FOLLOWING_DELTA_BYTES || pendingFollowingDeltas.length >= MAX_BUFFERED_LEGACY_FOLLOWING_DELTAS) throw new Error("Exceeded legacy tool-call content buffer limit");
|
|
415
|
+
pendingFollowingDeltaBytes += nextDeltaBytes;
|
|
416
|
+
pendingFollowingDeltas.push(ordinaryDelta);
|
|
417
|
+
} else leadingDeltas.push({
|
|
411
418
|
delta: ordinaryDelta,
|
|
412
419
|
toolCalls: []
|
|
413
420
|
});
|
|
@@ -482,84 +489,10 @@ function finalizeOpenAICompletionsToolCalls(output, options = {}) {
|
|
|
482
489
|
const block = output.content[contentIndex];
|
|
483
490
|
if (!block || !isToolCall(block)) continue;
|
|
484
491
|
delete block.partialJson;
|
|
485
|
-
delete block.streamIndex;
|
|
486
492
|
options.onConfirmedToolCall?.(block, contentIndex);
|
|
487
493
|
}
|
|
488
494
|
}
|
|
489
495
|
//#endregion
|
|
490
|
-
//#region packages/ai/src/transports/openai-completions-context-budget-buffer.ts
|
|
491
|
-
const MAX_CONTEXT_BUDGET_BUFFER_CHUNKS = 8192;
|
|
492
|
-
const MAX_CONTEXT_BUDGET_BUFFER_BYTES = 4194304;
|
|
493
|
-
async function bufferContextLimitedCompletions(source, signal) {
|
|
494
|
-
const iterator = source[Symbol.asyncIterator]();
|
|
495
|
-
const chunks = [];
|
|
496
|
-
let bufferedBytes = 0;
|
|
497
|
-
let overflow;
|
|
498
|
-
let finished = false;
|
|
499
|
-
let failed = false;
|
|
500
|
-
let sourceError;
|
|
501
|
-
let finishReason;
|
|
502
|
-
try {
|
|
503
|
-
for (;;) {
|
|
504
|
-
const next = await iterator.next();
|
|
505
|
-
if (next.done) {
|
|
506
|
-
finished = true;
|
|
507
|
-
break;
|
|
508
|
-
}
|
|
509
|
-
const chunk = next.value;
|
|
510
|
-
const chunkBytes = Buffer.byteLength(JSON.stringify(chunk) ?? "", "utf8");
|
|
511
|
-
if (chunks.length >= MAX_CONTEXT_BUDGET_BUFFER_CHUNKS || bufferedBytes + chunkBytes > MAX_CONTEXT_BUDGET_BUFFER_BYTES) {
|
|
512
|
-
overflow = next;
|
|
513
|
-
break;
|
|
514
|
-
}
|
|
515
|
-
chunks.push(chunk);
|
|
516
|
-
bufferedBytes += chunkBytes;
|
|
517
|
-
const chunkFinishReason = chunk?.choices?.[0]?.finish_reason;
|
|
518
|
-
if (chunkFinishReason) finishReason = chunkFinishReason;
|
|
519
|
-
signal?.throwIfAborted();
|
|
520
|
-
}
|
|
521
|
-
} catch (error) {
|
|
522
|
-
failed = true;
|
|
523
|
-
sourceError = error;
|
|
524
|
-
iterator.return?.().catch(() => void 0);
|
|
525
|
-
}
|
|
526
|
-
return {
|
|
527
|
-
bounded: overflow === void 0,
|
|
528
|
-
failed,
|
|
529
|
-
finishReason,
|
|
530
|
-
stream: { async *[Symbol.asyncIterator]() {
|
|
531
|
-
try {
|
|
532
|
-
yield* chunks;
|
|
533
|
-
if (failed) throw sourceError;
|
|
534
|
-
if (overflow !== void 0) {
|
|
535
|
-
yield overflow.value;
|
|
536
|
-
for (;;) {
|
|
537
|
-
const next = await iterator.next();
|
|
538
|
-
if (next.done) {
|
|
539
|
-
finished = true;
|
|
540
|
-
return;
|
|
541
|
-
}
|
|
542
|
-
yield next.value;
|
|
543
|
-
}
|
|
544
|
-
}
|
|
545
|
-
} finally {
|
|
546
|
-
chunks.length = 0;
|
|
547
|
-
if (!finished && !failed) iterator.return?.().catch(() => void 0);
|
|
548
|
-
}
|
|
549
|
-
} }
|
|
550
|
-
};
|
|
551
|
-
}
|
|
552
|
-
//#endregion
|
|
553
|
-
//#region packages/ai/src/transports/openai-completions-host.ts
|
|
554
|
-
/**
|
|
555
|
-
* Chat Completions accepts Azure AI Foundry hosts in addition to traditional
|
|
556
|
-
* Azure OpenAI hosts. Do not replace this with isTraditionalAzureOpenAIHost,
|
|
557
|
-
* which intentionally excludes the .services.ai.azure.com Foundry suffix.
|
|
558
|
-
*/
|
|
559
|
-
function isAzureOpenAICompatibleHost(hostname) {
|
|
560
|
-
return hostname.endsWith(".openai.azure.com") || hostname.endsWith(".services.ai.azure.com") || hostname.endsWith(".cognitiveservices.azure.com");
|
|
561
|
-
}
|
|
562
|
-
//#endregion
|
|
563
496
|
//#region packages/ai/src/openai-completions-messages.ts
|
|
564
497
|
/** Whether replayed messages require a tools marker for proxy compatibility. */
|
|
565
498
|
function hasToolCallHistory(messages) {
|
|
@@ -569,6 +502,8 @@ function hasToolCallHistory(messages) {
|
|
|
569
502
|
function convertMessages(model, context, compat, options = {}) {
|
|
570
503
|
const params = [];
|
|
571
504
|
const supportsTools = options.supportsTools !== false;
|
|
505
|
+
const declaredToolNames = options.declaredToolNames ?? new Set(context.tools?.map((tool) => tool.name));
|
|
506
|
+
const toolNamesByCallId = /* @__PURE__ */ new Map();
|
|
572
507
|
const normalizeToolCallId = (id) => {
|
|
573
508
|
if (id.includes("|")) return id.slice(0, id.indexOf("|")).replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 40);
|
|
574
509
|
if (model.provider === "openai") return id.length > 40 ? truncateUtf16Safe(id, 40) : id;
|
|
@@ -647,7 +582,8 @@ function convertMessages(model, context, compat, options = {}) {
|
|
|
647
582
|
if (block.type === "text" && block.text.trim().length > 0) assistantTexts.push(sanitizeSurrogates(block.text));
|
|
648
583
|
else if (block.type === "thinking" && block.thinking.trim().length > 0) nonEmptyThinkingBlocks.push(block);
|
|
649
584
|
else if (block.type === "toolCall") {
|
|
650
|
-
|
|
585
|
+
toolNamesByCallId.set(block.id, block.name);
|
|
586
|
+
if (supportsTools && declaredToolNames.has(block.name)) toolCalls.push(block);
|
|
651
587
|
else assistantTexts.push(sanitizeSurrogates(`[tool call id=${block.id} name=${block.name}] ${JSON.stringify(block.arguments)}`));
|
|
652
588
|
}
|
|
653
589
|
});
|
|
@@ -694,6 +630,7 @@ function convertMessages(model, context, compat, options = {}) {
|
|
|
694
630
|
params.push(assistantMsg);
|
|
695
631
|
} else if (msg.role === "toolResult") {
|
|
696
632
|
const imageContentParts = [];
|
|
633
|
+
const textResults = [];
|
|
697
634
|
let j = i;
|
|
698
635
|
while (j < transformedMessages.length) {
|
|
699
636
|
const toolMsg = transformedMessages.at(j);
|
|
@@ -702,27 +639,18 @@ function convertMessages(model, context, compat, options = {}) {
|
|
|
702
639
|
const mediaPlaceholder = describeToolResultMediaPlaceholder(toolMsg.content);
|
|
703
640
|
const images = toolMsg.content.filter(isImageWithMediaPayload);
|
|
704
641
|
const content = textResult.trim() ? textResult : mediaPlaceholder ?? "(no output)";
|
|
705
|
-
|
|
642
|
+
const normalizedId = normalizeToolCallId(toolMsg.toolCallId);
|
|
643
|
+
const pairedToolName = toolNamesByCallId.get(toolMsg.toolCallId) ?? toolNamesByCallId.get(normalizedId);
|
|
644
|
+
const isNativeResult = pairedToolName !== void 0 ? declaredToolNames.has(pairedToolName) : preparedRequestSuffix.hasToolCall(context, toolMsg.toolCallId) || preparedRequestSuffix.hasToolCall(context, normalizedId);
|
|
645
|
+
if (supportsTools && isNativeResult) {
|
|
706
646
|
const toolResultMsg = {
|
|
707
647
|
role: "tool",
|
|
708
648
|
content,
|
|
709
|
-
tool_call_id: preparedRequestSuffix.has(context) ? preparedRequestSuffix.toolCallId(context, toolMsg.toolCallId,
|
|
649
|
+
tool_call_id: preparedRequestSuffix.has(context) ? preparedRequestSuffix.toolCallId(context, toolMsg.toolCallId, normalizedId) : toolMsg.toolCallId
|
|
710
650
|
};
|
|
711
651
|
if (compat.requiresToolResultName && toolMsg.toolName) toolResultMsg.name = toolMsg.toolName;
|
|
712
652
|
params.push(toolResultMsg);
|
|
713
|
-
} else {
|
|
714
|
-
const text = sanitizeSurrogates(`[tool result id=${toolMsg.toolCallId} name=${toolMsg.toolName}] ${content}`);
|
|
715
|
-
const previous = params.at(-1);
|
|
716
|
-
if (previous?.role !== "assistant") params.push({
|
|
717
|
-
role: "assistant",
|
|
718
|
-
content: text
|
|
719
|
-
});
|
|
720
|
-
else if (Array.isArray(previous.content)) previous.content.push({
|
|
721
|
-
type: "text",
|
|
722
|
-
text
|
|
723
|
-
});
|
|
724
|
-
else previous.content = previous.content ? `${previous.content}\n${text}` : text;
|
|
725
|
-
}
|
|
653
|
+
} else textResults.push(sanitizeSurrogates(`[tool result id=${toolMsg.toolCallId} name=${toolMsg.toolName}] ${content}`));
|
|
726
654
|
if (images.length > 0 && model.input.includes("image")) {
|
|
727
655
|
const boundedToolName = sanitizeSurrogates(truncateUtf16Safe(toolMsg.toolName ?? "", 64));
|
|
728
656
|
imageContentParts.push({
|
|
@@ -737,8 +665,21 @@ function convertMessages(model, context, compat, options = {}) {
|
|
|
737
665
|
j += 1;
|
|
738
666
|
}
|
|
739
667
|
i = j - 1;
|
|
668
|
+
if (textResults.length > 0) {
|
|
669
|
+
const previous = params.at(-1);
|
|
670
|
+
const text = textResults.join("\n");
|
|
671
|
+
if (previous?.role !== "assistant") params.push({
|
|
672
|
+
role: "assistant",
|
|
673
|
+
content: text
|
|
674
|
+
});
|
|
675
|
+
else if (Array.isArray(previous.content)) previous.content.push(...textResults.map((result) => ({
|
|
676
|
+
type: "text",
|
|
677
|
+
text: result
|
|
678
|
+
})));
|
|
679
|
+
else previous.content = previous.content ? `${previous.content}\n${text}` : text;
|
|
680
|
+
}
|
|
740
681
|
if (imageContentParts.length > 0) {
|
|
741
|
-
if (supportsTools && compat.requiresAssistantAfterToolResult) params.push({
|
|
682
|
+
if (supportsTools && textResults.length === 0 && compat.requiresAssistantAfterToolResult) params.push({
|
|
742
683
|
role: "assistant",
|
|
743
684
|
content: "I have processed the tool results."
|
|
744
685
|
});
|
|
@@ -747,80 +688,30 @@ function convertMessages(model, context, compat, options = {}) {
|
|
|
747
688
|
content: imageContentParts
|
|
748
689
|
});
|
|
749
690
|
lastRole = "user";
|
|
750
|
-
} else lastRole = supportsTools ? "toolResult" : "assistant";
|
|
691
|
+
} else lastRole = supportsTools && textResults.length === 0 ? "toolResult" : "assistant";
|
|
751
692
|
continue;
|
|
752
693
|
}
|
|
753
694
|
lastRole = msg.role;
|
|
754
695
|
}
|
|
755
|
-
if (relocatableSplit !== void 0 && systemParamIndex !== void 0)
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
type: "text",
|
|
772
|
-
text
|
|
773
|
-
}];
|
|
774
|
-
else continue;
|
|
775
|
-
const systemParam = args.params[args.systemParamIndex];
|
|
776
|
-
if (systemParam) systemParam.content = sanitizeSurrogates(stripSystemPromptCacheBoundary(args.split.remainingPrompt));
|
|
777
|
-
args.cacheOptOutIndexes?.add(index);
|
|
778
|
-
return;
|
|
779
|
-
}
|
|
780
|
-
}
|
|
781
|
-
//#endregion
|
|
782
|
-
//#region packages/ai/src/transports/openai-completions-policy.ts
|
|
783
|
-
function applyCompletionsReasoningAndRouting(params, model, reasoning, compat, mode) {
|
|
784
|
-
const direct = mode === "direct";
|
|
785
|
-
const nativeEffort = compat.thinkingFormat === "openrouter" ? void 0 : reasoning.effort;
|
|
786
|
-
const enabled = reasoning.thinkingEnabled ?? false;
|
|
787
|
-
if (model.reasoning && (!compat.thinkingOffControlUndeclared || reasoning.thinkingEnabled !== void 0 || !reasoning.thinkingExplicit)) {
|
|
788
|
-
let allowScalarEffort = true;
|
|
789
|
-
if (direct && compat.thinkingFormat === "zai") {
|
|
790
|
-
params.thinking = enabled ? {
|
|
791
|
-
type: "enabled",
|
|
792
|
-
clear_thinking: false
|
|
793
|
-
} : { type: "disabled" };
|
|
794
|
-
allowScalarEffort = false;
|
|
795
|
-
} else if (compat.thinkingFormat === "qwen") {
|
|
796
|
-
params.enable_thinking = enabled;
|
|
797
|
-
allowScalarEffort = false;
|
|
798
|
-
} else if (compat.thinkingFormat === "qwen-chat-template") {
|
|
799
|
-
const chatTemplateReasoningEffort = enabled && reasoning.thinkingExplicit && model.compat?.supportedReasoningEfforts?.length ? reasoning.effort : void 0;
|
|
800
|
-
params.chat_template_kwargs = {
|
|
801
|
-
enable_thinking: enabled,
|
|
802
|
-
...direct ? { preserve_thinking: true } : {},
|
|
803
|
-
...chatTemplateReasoningEffort ? { reasoning_effort: chatTemplateReasoningEffort } : {}
|
|
804
|
-
};
|
|
805
|
-
allowScalarEffort = false;
|
|
806
|
-
} else if (compat.thinkingFormat === "together" || direct && compat.thinkingFormat === "deepseek") {
|
|
807
|
-
if (compat.thinkingFormat === "deepseek") params.thinking = { type: enabled ? "enabled" : "disabled" };
|
|
808
|
-
else params.reasoning = { enabled };
|
|
809
|
-
allowScalarEffort = enabled;
|
|
810
|
-
}
|
|
811
|
-
if (allowScalarEffort && compat.supportsReasoningEffort && (direct ? nativeEffort !== void 0 : nativeEffort)) params.reasoning_effort = nativeEffort;
|
|
812
|
-
}
|
|
813
|
-
if (!direct) return;
|
|
814
|
-
if (compat.openRouterRouting) params.provider = compat.openRouterRouting;
|
|
815
|
-
if (model.baseUrl.includes("ai-gateway.vercel.sh") && model.compat?.vercelGatewayRouting) {
|
|
816
|
-
const routing = model.compat.vercelGatewayRouting;
|
|
817
|
-
if (routing.only || routing.order) {
|
|
818
|
-
const gatewayOptions = {};
|
|
819
|
-
if (routing.only) gatewayOptions.only = routing.only;
|
|
820
|
-
if (routing.order) gatewayOptions.order = routing.order;
|
|
821
|
-
params.providerOptions = { gateway: gatewayOptions };
|
|
696
|
+
if (relocatableSplit !== void 0 && systemParamIndex !== void 0) {
|
|
697
|
+
const cacheOptOutIndexes = options.cacheOptOutIndexes;
|
|
698
|
+
const text = sanitizeSurrogates(stripSystemPromptCacheBoundary(relocatableSplit.relocatable));
|
|
699
|
+
for (let index = systemParamIndex + 1; index < params.length; index++) {
|
|
700
|
+
const param = params[index];
|
|
701
|
+
if (!param || param.role !== "user") continue;
|
|
702
|
+
if (typeof param.content === "string") param.content = `${param.content}\n\n${text}`;
|
|
703
|
+
else if (Array.isArray(param.content)) param.content = [...param.content, {
|
|
704
|
+
type: "text",
|
|
705
|
+
text
|
|
706
|
+
}];
|
|
707
|
+
else continue;
|
|
708
|
+
const systemParam = params[systemParamIndex];
|
|
709
|
+
if (systemParam) systemParam.content = sanitizeSurrogates(stripSystemPromptCacheBoundary(relocatableSplit.remainingPrompt));
|
|
710
|
+
cacheOptOutIndexes?.add(index);
|
|
711
|
+
break;
|
|
822
712
|
}
|
|
823
713
|
}
|
|
714
|
+
return params;
|
|
824
715
|
}
|
|
825
716
|
//#endregion
|
|
826
717
|
//#region packages/ai/src/transports/openai-completions-replay.ts
|
|
@@ -882,76 +773,33 @@ function sanitizeOpenRouterReasoningReplayFields(record) {
|
|
|
882
773
|
if (typeof reasoningText === "string" && reasoningText.length > 0 && typeof record.reasoning !== "string" && typeof record.reasoning_content !== "string") record.reasoning = reasoningText;
|
|
883
774
|
delete record.reasoning_text;
|
|
884
775
|
}
|
|
885
|
-
const REASONING_CONTENT_REPLAY_MODEL_IDS = /* @__PURE__ */ new Set([
|
|
886
|
-
"deepseek-v4-flash",
|
|
887
|
-
"deepseek-v4-pro",
|
|
888
|
-
"kimi-for-coding",
|
|
889
|
-
"kimi-k2.5",
|
|
890
|
-
"kimi-k2.6",
|
|
891
|
-
"kimi-k2.7-code",
|
|
892
|
-
"kimi-k2.7-code-highspeed",
|
|
893
|
-
"kimi-k3",
|
|
894
|
-
"kimi-k3.1-pro",
|
|
895
|
-
"kimi-k3.1-pro-highspeed",
|
|
896
|
-
"kimi-k2-thinking",
|
|
897
|
-
"kimi-k2-thinking-turbo",
|
|
898
|
-
"mimo-v2-pro",
|
|
899
|
-
"mimo-v2-omni",
|
|
900
|
-
"mimo-v2.5",
|
|
901
|
-
"mimo-v2.5-pro",
|
|
902
|
-
"mimo-v2.6-flash",
|
|
903
|
-
"mimo-v2.6-pro",
|
|
904
|
-
"mimo-v2.6-pro-ultraspeed"
|
|
905
|
-
]);
|
|
906
|
-
const REASONING_CONTENT_REPLAY_TIER_SUFFIXES = [
|
|
907
|
-
"-free",
|
|
908
|
-
"-paid",
|
|
909
|
-
"-trial"
|
|
910
|
-
];
|
|
911
|
-
function stripReasoningContentReplayTierSuffix(modelId) {
|
|
912
|
-
for (const suffix of REASONING_CONTENT_REPLAY_TIER_SUFFIXES) if (modelId.length > suffix.length && modelId.endsWith(suffix)) return modelId.slice(0, -suffix.length);
|
|
913
|
-
return modelId;
|
|
914
|
-
}
|
|
915
|
-
function getReasoningContentReplayModelIdCandidates(modelId) {
|
|
916
|
-
if (typeof modelId !== "string") return [];
|
|
917
|
-
const normalized = modelId.trim().toLowerCase();
|
|
918
|
-
if (!normalized) return [];
|
|
919
|
-
const parts = normalized.split("/").filter(Boolean);
|
|
920
|
-
const finalPart = parts[parts.length - 1] ?? normalized;
|
|
921
|
-
const candidates = [finalPart];
|
|
922
|
-
const colonParts = finalPart.split(":").filter(Boolean);
|
|
923
|
-
if (colonParts.length > 1) candidates.push(colonParts[0] ?? "", colonParts[colonParts.length - 1] ?? "");
|
|
924
|
-
for (const candidate of candidates.slice()) {
|
|
925
|
-
const stripped = stripReasoningContentReplayTierSuffix(candidate);
|
|
926
|
-
if (stripped !== candidate) candidates.push(stripped);
|
|
927
|
-
}
|
|
928
|
-
return uniqueStrings(candidates.filter(Boolean));
|
|
929
|
-
}
|
|
930
|
-
function shouldPreserveReasoningContentReplay(model, compat) {
|
|
931
|
-
if (compat.requiresReasoningContentOnAssistantMessages || compat.thinkingFormat === "deepseek" || compat.thinkingFormat === "zai" || shouldTrustReasoningContentReplayMetadata(model)) return true;
|
|
932
|
-
return getReasoningContentReplayModelIdCandidates(model.id).some((modelId) => REASONING_CONTENT_REPLAY_MODEL_IDS.has(modelId));
|
|
933
|
-
}
|
|
934
776
|
function shouldPreserveOpenRouterReasoningReplay(model) {
|
|
935
777
|
if (model.provider !== "openrouter") return true;
|
|
936
778
|
const normalizedModelId = model.id.trim().toLowerCase();
|
|
937
779
|
return !(normalizedModelId.startsWith("anthropic/") || normalizedModelId.startsWith("x-ai/"));
|
|
938
780
|
}
|
|
939
|
-
function shouldTrustReasoningContentReplayMetadata(model) {
|
|
940
|
-
if (!model.reasoning) return false;
|
|
941
|
-
if (model.provider.trim().toLowerCase() === "openai") return false;
|
|
942
|
-
return shouldPreserveOpenRouterReasoningReplay(model);
|
|
943
|
-
}
|
|
944
781
|
function applyCompletionsReplay(outgoingMessages, context, model, compat) {
|
|
945
782
|
injectToolCallThoughtSignatures(outgoingMessages, context, model);
|
|
946
783
|
const preserveOpenRouterReasoning = compat.thinkingFormat === "openrouter" && shouldPreserveOpenRouterReasoningReplay(model);
|
|
947
|
-
const preserveReasoningContent =
|
|
784
|
+
const preserveReasoningContent = compat.requiresReasoningContentOnAssistantMessages || compat.thinkingFormat === "deepseek" || compat.thinkingFormat === "zai" || model.reasoning && model.provider.trim().toLowerCase() !== "openai" && shouldPreserveOpenRouterReasoningReplay(model) || requiresReasoningContentReplay(model.id);
|
|
948
785
|
for (const message of outgoingMessages) {
|
|
949
786
|
if (message.role !== "assistant") continue;
|
|
950
787
|
if (preserveOpenRouterReasoning) sanitizeOpenRouterReasoningReplayFields(message);
|
|
951
788
|
else {
|
|
952
789
|
const record = message;
|
|
790
|
+
const requiresReasoningContent = model.compat?.requiresReasoningContentOnAssistantMessages === true;
|
|
791
|
+
if (preserveReasoningContent && requiresReasoningContent) {
|
|
792
|
+
for (const field of [
|
|
793
|
+
"reasoning_content",
|
|
794
|
+
"reasoning",
|
|
795
|
+
"reasoning_text"
|
|
796
|
+
]) if (typeof record[field] === "string" && record[field].length > 0) {
|
|
797
|
+
record.reasoning_content = record[field];
|
|
798
|
+
break;
|
|
799
|
+
}
|
|
800
|
+
}
|
|
953
801
|
for (const field of COMPLETIONS_REASONING_REPLAY_FIELDS) {
|
|
954
|
-
if (preserveReasoningContent && field === "reasoning_content" && typeof record[field] === "string") continue;
|
|
802
|
+
if (preserveReasoningContent && field !== "reasoning_details" && (!requiresReasoningContent || field === "reasoning_content") && typeof record[field] === "string") continue;
|
|
955
803
|
delete record[field];
|
|
956
804
|
}
|
|
957
805
|
}
|
|
@@ -959,30 +807,9 @@ function applyCompletionsReplay(outgoingMessages, context, model, compat) {
|
|
|
959
807
|
}
|
|
960
808
|
//#endregion
|
|
961
809
|
//#region packages/ai/src/transports/openai-completions-params.ts
|
|
962
|
-
function isKnownOpenAICompletionsEndpoint(model) {
|
|
963
|
-
if (!model.baseUrl.trim() || isNativeOpenAIEndpoint(model)) return true;
|
|
964
|
-
const endpointClass = resolveProviderEndpoint(model).endpointClass;
|
|
965
|
-
if (endpointClass === "openai-public" || endpointClass === "azure-openai") return true;
|
|
966
|
-
const endpoint = URL.parse(model.baseUrl);
|
|
967
|
-
return endpoint !== null && isAzureOpenAICompatibleHost(endpoint.hostname.toLowerCase());
|
|
968
|
-
}
|
|
969
|
-
function resolveOpenAICompletionsMaxTokens(model, options) {
|
|
970
|
-
if (options?.maxTokens) return {
|
|
971
|
-
maxTokens: options.maxTokens,
|
|
972
|
-
clampToModelMaxTokens: true
|
|
973
|
-
};
|
|
974
|
-
const paramsMaxTokens = resolveMaxTokensParam(model.params);
|
|
975
|
-
if (paramsMaxTokens) return {
|
|
976
|
-
maxTokens: paramsMaxTokens,
|
|
977
|
-
clampToModelMaxTokens: false
|
|
978
|
-
};
|
|
979
|
-
return {
|
|
980
|
-
maxTokens: model.maxTokens,
|
|
981
|
-
clampToModelMaxTokens: false
|
|
982
|
-
};
|
|
983
|
-
}
|
|
984
810
|
const OPENAI_COMPLETIONS_INPUT_TOKEN_SAFETY_MARGIN = 1.25;
|
|
985
811
|
const OPENAI_COMPLETIONS_IMAGE_CHAR_ESTIMATE = 8e3;
|
|
812
|
+
const OPENAI_COMPLETIONS_VIDEO_CHAR_ESTIMATE = 96e3;
|
|
986
813
|
const MIN_USEFUL_OUTPUT_TOKENS = 16;
|
|
987
814
|
function estimateJsonChars(value, fallback) {
|
|
988
815
|
try {
|
|
@@ -1019,6 +846,10 @@ function estimateOpenAICompletionsContentChars(value) {
|
|
|
1019
846
|
adjustedChars += OPENAI_COMPLETIONS_IMAGE_CHAR_ESTIMATE;
|
|
1020
847
|
continue;
|
|
1021
848
|
}
|
|
849
|
+
if (record.type === "video_url" || record.type === "input_video") {
|
|
850
|
+
adjustedChars += OPENAI_COMPLETIONS_VIDEO_CHAR_ESTIMATE;
|
|
851
|
+
continue;
|
|
852
|
+
}
|
|
1022
853
|
const text = record.text;
|
|
1023
854
|
if (typeof text === "string") {
|
|
1024
855
|
adjustedChars += estimateStringChars(text);
|
|
@@ -1028,7 +859,7 @@ function estimateOpenAICompletionsContentChars(value) {
|
|
|
1028
859
|
}
|
|
1029
860
|
return adjustedChars;
|
|
1030
861
|
}
|
|
1031
|
-
function convertTools(tools, compat, model, mode) {
|
|
862
|
+
function convertTools(tools, compat, model, mode, mutableParameters) {
|
|
1032
863
|
const prepared = mode === "managed" ? prepareOpenAITools(tools) : void 0;
|
|
1033
864
|
const projection = prepared?.projection ?? projectOpenAITools(tools);
|
|
1034
865
|
const convert = () => {
|
|
@@ -1043,7 +874,7 @@ function convertTools(tools, compat, model, mode) {
|
|
|
1043
874
|
projection,
|
|
1044
875
|
tools: sortPromptCacheToolsByName(projection.tools).map((tool) => {
|
|
1045
876
|
const parameters = compat.requiresTypedUnionBranches ? normalizeToolSchema(tool.parameters, "moonshot") : tool.parameters;
|
|
1046
|
-
return prepareOpenAIFunctionTool(tool.name, tool.description, mode === "direct" ? parameters : normalizeOpenAIStrictToolParameters(parameters, strict === true, model.compat), strict).completions;
|
|
877
|
+
return prepareOpenAIFunctionTool(tool.name, tool.description, mode === "direct" ? parameters : normalizeOpenAIStrictToolParameters(parameters, strict === true, model.compat), strict, mutableParameters).completions;
|
|
1047
878
|
})
|
|
1048
879
|
};
|
|
1049
880
|
};
|
|
@@ -1086,14 +917,20 @@ function buildOpenAICompletionsRequest(model, context, options, policy) {
|
|
|
1086
917
|
].includes(model.provider));
|
|
1087
918
|
const cacheOptOutIndexes = /* @__PURE__ */ new Set();
|
|
1088
919
|
const supportsTools = policy.mode === "direct" || supportsModelTools(model);
|
|
1089
|
-
const
|
|
920
|
+
const converted = supportsTools && context.tools ? convertTools(context.tools, compat, model, policy.mode, Boolean(options?.onPayload)) : void 0;
|
|
921
|
+
const convertedMessages = convertMessages({
|
|
922
|
+
...model,
|
|
923
|
+
input: options?.[PROVIDER_MODEL_INPUT] ?? model.input,
|
|
924
|
+
compat
|
|
925
|
+
}, context, compat, {
|
|
1090
926
|
cacheOptOutIndexes,
|
|
1091
927
|
supportsTools,
|
|
928
|
+
declaredToolNames: new Set(converted?.projection.tools.map((tool) => tool.name)),
|
|
1092
929
|
preserveSystemPromptCacheBoundary: cacheControl !== void 0 && !managedCompat?.requiresStringContent
|
|
1093
930
|
});
|
|
931
|
+
applyCompletionsReplay(convertedMessages, context, model, compat);
|
|
1094
932
|
let messages = convertedMessages;
|
|
1095
933
|
if (managedCompat) {
|
|
1096
|
-
applyCompletionsReplay(convertedMessages, context, model, managedCompat);
|
|
1097
934
|
if (managedCompat.strictMessageKeys) messages = stripCompletionMessagesToRoleContent(messages);
|
|
1098
935
|
if (managedCompat.requiresStringContent) messages = flattenCompletionMessagesToStringContent(messages);
|
|
1099
936
|
}
|
|
@@ -1122,8 +959,7 @@ function buildOpenAICompletionsRequest(model, context, options, policy) {
|
|
|
1122
959
|
if (options?.stop !== void 0 && options.stop.length > 0) params.stop = options.stop;
|
|
1123
960
|
let directToolProjection;
|
|
1124
961
|
if (supportsTools) {
|
|
1125
|
-
if (
|
|
1126
|
-
const converted = convertTools(context.tools, compat, model, policy.mode);
|
|
962
|
+
if (converted) {
|
|
1127
963
|
if (policy.mode === "direct") directToolProjection = converted.projection;
|
|
1128
964
|
if (converted.tools.length > 0 || policy.mode === "managed" && converted.projection.inputToolCount === 0 && converted.projection.diagnostics.length === 0) params.tools = converted.tools;
|
|
1129
965
|
else if (hasToolCallHistory(context.messages)) params.tools = [];
|
|
@@ -1138,7 +974,7 @@ function buildOpenAICompletionsRequest(model, context, options, policy) {
|
|
|
1138
974
|
delete params.tool_choice;
|
|
1139
975
|
}
|
|
1140
976
|
}
|
|
1141
|
-
if (policy.mode === "direct" && compat.cacheControlFormat === "anthropic") applyCompletionsAnthropicCacheControl(params, cacheControl ?? null, cacheOptOutIndexes, markTools);
|
|
977
|
+
if (policy.mode === "direct" && compat.cacheControlFormat === "anthropic") applyCompletionsAnthropicCacheControl(params, cacheControl ?? null, cacheOptOutIndexes, markTools, true, compat.cacheControlSystemOnly);
|
|
1142
978
|
if (policy.mode === "direct" && options?.toolChoice) {
|
|
1143
979
|
const toolChoice = reconcileOpenAICompletionsToolChoice(options.toolChoice, directToolProjection ?? projectOpenAITools([]));
|
|
1144
980
|
if (toolChoice !== void 0) params.tool_choice = toolChoice;
|
|
@@ -1151,33 +987,28 @@ function buildOpenAICompletionsRequest(model, context, options, policy) {
|
|
|
1151
987
|
compat: model.compat ?? void 0
|
|
1152
988
|
}, simpleReasoning)) ?? (usesBinaryOpenRouterThinking ? void 0 : "high");
|
|
1153
989
|
const thinkingExplicit = options?.openclawThinkingExplicit ?? (options?.reasoningEffort !== void 0 || options?.reasoning !== void 0);
|
|
1154
|
-
const
|
|
1155
|
-
|
|
1156
|
-
thinkingExplicit
|
|
1157
|
-
};
|
|
1158
|
-
const { effort, thinkingEnabled } = reasoning;
|
|
990
|
+
const { effort, thinkingEnabled } = resolveOpenAIRequestReasoning(model, requestedEffort);
|
|
991
|
+
const direct = policy.mode === "direct";
|
|
1159
992
|
{
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
} : resolveOpenAICompletionsMaxTokens(model, options);
|
|
1164
|
-
const effectiveMaxTokens = maxTokenBudget.maxTokens;
|
|
993
|
+
let effectiveMaxTokens = options?.maxTokens;
|
|
994
|
+
const clampToModelMaxTokens = direct || Boolean(effectiveMaxTokens);
|
|
995
|
+
if (!direct && !effectiveMaxTokens) effectiveMaxTokens = resolveMaxTokensParam(model.params) || model.maxTokens;
|
|
1165
996
|
const effectiveContextTokens = asPositiveFiniteNumber(model.contextTokens) ?? asPositiveFiniteNumber(model.contextWindow);
|
|
1166
997
|
let clampedMaxTokens = effectiveMaxTokens;
|
|
1167
998
|
const modelOutputLimit = asPositiveFiniteNumber(model.maxTokens);
|
|
1168
999
|
const modelMaxTokens = modelOutputLimit === void 0 ? void 0 : Math.floor(modelOutputLimit);
|
|
1169
|
-
if (
|
|
1000
|
+
if (clampToModelMaxTokens && clampedMaxTokens !== void 0 && modelMaxTokens !== void 0 && clampedMaxTokens > modelMaxTokens) {
|
|
1170
1001
|
clampedMaxTokens = modelMaxTokens;
|
|
1171
|
-
if (policy.mode === "managed") emitModelTransportDebug(log, `[completions] clamp_max_tokens provider=${model.provider} api=${model.api} model=${model.id} requested=${effectiveMaxTokens} output=${clampedMaxTokens} modelMaxTokens=${modelMaxTokens}`);
|
|
1002
|
+
if (policy.mode === "managed") emitModelTransportDebug(log, () => `[completions] clamp_max_tokens provider=${model.provider} api=${model.api} model=${model.id} requested=${effectiveMaxTokens} output=${clampedMaxTokens} modelMaxTokens=${modelMaxTokens}`);
|
|
1172
1003
|
}
|
|
1173
1004
|
if (compatDetection?.capabilities.usesExplicitProxyLikeEndpoint && clampedMaxTokens !== void 0 && effectiveContextTokens !== void 0) {
|
|
1174
|
-
const estimatedInputTokens = estimateOpenAICompletionsInputTokens(params);
|
|
1005
|
+
const estimatedInputTokens = (params.response_format === void 0 ? measuredRequestPressure.get(model, context) : void 0) ?? estimateOpenAICompletionsInputTokens(params);
|
|
1175
1006
|
const remainingBudget = Math.max(0, effectiveContextTokens - estimatedInputTokens - 1);
|
|
1176
1007
|
if (clampedMaxTokens > remainingBudget) {
|
|
1177
1008
|
if (remainingBudget < (params.tools?.length && params.tool_choice !== "none" ? Math.max(MIN_USEFUL_OUTPUT_TOKENS, Math.min(2048, Math.ceil((modelMaxTokens ?? 0) / 8))) : MIN_USEFUL_OUTPUT_TOKENS)) throw Object.assign(/* @__PURE__ */ new Error(`Context window exceeded: estimated input ${estimatedInputTokens} leaves only ${remainingBudget} output tokens within the ${effectiveContextTokens}-token context.`), { code: "context_length_exceeded" });
|
|
1178
1009
|
clampedMaxTokens = remainingBudget;
|
|
1179
1010
|
contextOutputCap = remainingBudget;
|
|
1180
|
-
emitModelTransportDebug(log, `[completions] clamp_max_tokens provider=${model.provider} api=${model.api} model=${model.id} requested=${effectiveMaxTokens} output=${clampedMaxTokens} effectiveContext=${effectiveContextTokens} estimatedInput=${estimatedInputTokens}`);
|
|
1011
|
+
emitModelTransportDebug(log, () => `[completions] clamp_max_tokens provider=${model.provider} api=${model.api} model=${model.id} requested=${effectiveMaxTokens} output=${clampedMaxTokens} effectiveContext=${effectiveContextTokens} estimatedInput=${estimatedInputTokens}`);
|
|
1181
1012
|
}
|
|
1182
1013
|
}
|
|
1183
1014
|
if (policy.mode === "direct" ? options?.maxTokens : clampedMaxTokens) {
|
|
@@ -1189,9 +1020,49 @@ function buildOpenAICompletionsRequest(model, context, options, policy) {
|
|
|
1189
1020
|
if (usesBinaryOpenRouterThinking && thinkingEnabled !== void 0) params.reasoning = { enabled: thinkingEnabled };
|
|
1190
1021
|
else if (effort !== void 0) params.reasoning = { effort };
|
|
1191
1022
|
}
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1023
|
+
const nativeEffort = compat.thinkingFormat === "openrouter" ? void 0 : effort;
|
|
1024
|
+
const enabled = thinkingEnabled ?? false;
|
|
1025
|
+
const useBinaryThinking = direct || thinkingEnabled === false && (nativeEffort === void 0 || !compat.supportsReasoningEffort);
|
|
1026
|
+
if (model.reasoning && (!compat.thinkingOffControlUndeclared || thinkingEnabled === true || !thinkingExplicit)) {
|
|
1027
|
+
let allowScalarEffort = true;
|
|
1028
|
+
if (useBinaryThinking && compat.thinkingFormat === "zai") {
|
|
1029
|
+
params.thinking = enabled ? {
|
|
1030
|
+
type: "enabled",
|
|
1031
|
+
clear_thinking: false
|
|
1032
|
+
} : { type: "disabled" };
|
|
1033
|
+
allowScalarEffort = false;
|
|
1034
|
+
} else if (compat.thinkingFormat === "qwen") {
|
|
1035
|
+
params.enable_thinking = enabled;
|
|
1036
|
+
allowScalarEffort = false;
|
|
1037
|
+
} else if (compat.thinkingFormat === "qwen-chat-template") {
|
|
1038
|
+
const chatTemplateReasoningEffort = enabled && thinkingExplicit && model.compat?.supportedReasoningEfforts?.length ? effort : void 0;
|
|
1039
|
+
params.chat_template_kwargs = {
|
|
1040
|
+
enable_thinking: enabled,
|
|
1041
|
+
...direct ? { preserve_thinking: true } : {},
|
|
1042
|
+
...chatTemplateReasoningEffort ? { reasoning_effort: chatTemplateReasoningEffort } : {}
|
|
1043
|
+
};
|
|
1044
|
+
allowScalarEffort = false;
|
|
1045
|
+
} else if (compat.thinkingFormat === "together" || useBinaryThinking && compat.thinkingFormat === "deepseek") {
|
|
1046
|
+
if (compat.thinkingFormat === "deepseek") params.thinking = { type: enabled ? "enabled" : "disabled" };
|
|
1047
|
+
else params.reasoning = { enabled };
|
|
1048
|
+
allowScalarEffort = enabled;
|
|
1049
|
+
}
|
|
1050
|
+
if (allowScalarEffort && compat.supportsReasoningEffort && (direct ? nativeEffort !== void 0 : nativeEffort)) params.reasoning_effort = nativeEffort;
|
|
1051
|
+
}
|
|
1052
|
+
if (direct) {
|
|
1053
|
+
if (compat.openRouterRouting) params.provider = compat.openRouterRouting;
|
|
1054
|
+
if (model.baseUrl.includes("ai-gateway.vercel.sh") && model.compat?.vercelGatewayRouting) {
|
|
1055
|
+
const routing = model.compat.vercelGatewayRouting;
|
|
1056
|
+
if (routing.only || routing.order) {
|
|
1057
|
+
const gatewayOptions = {};
|
|
1058
|
+
if (routing.only) gatewayOptions.only = routing.only;
|
|
1059
|
+
if (routing.order) gatewayOptions.order = routing.order;
|
|
1060
|
+
params.providerOptions = { gateway: gatewayOptions };
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
if (policy.mode === "managed" && compat.cacheControlFormat === "anthropic") applyCompletionsAnthropicCacheControl(params, cacheControl ?? null, cacheOptOutIndexes, markTools, !managedCompat?.requiresStringContent, compat.cacheControlSystemOnly);
|
|
1065
|
+
if (params.tools?.length && isKnownOpenAIEndpoint(model)) applyOpenAICompletionsToolReasoning(params, model);
|
|
1195
1066
|
if (contextOutputCap !== void 0) contextOutputBudgets.set(params, {
|
|
1196
1067
|
model: params.model,
|
|
1197
1068
|
cap: contextOutputCap,
|
|
@@ -1546,6 +1417,7 @@ function createGemmaToolCallRecoverer() {
|
|
|
1546
1417
|
}
|
|
1547
1418
|
//#endregion
|
|
1548
1419
|
//#region packages/ai/src/transports/openai-completions-stream.ts
|
|
1420
|
+
let reasoningParserModule;
|
|
1549
1421
|
function extractToolCallThoughtSignature(toolCall) {
|
|
1550
1422
|
const tc = toolCall;
|
|
1551
1423
|
if (!tc) return;
|
|
@@ -1585,6 +1457,7 @@ async function* observeOpenAICompletionsProgress(responseStream, signal) {
|
|
|
1585
1457
|
}
|
|
1586
1458
|
}
|
|
1587
1459
|
async function processCompletionsStream(responseStream, output, model, stream, options) {
|
|
1460
|
+
const { createReasoningTagTextPartitioner } = await (reasoningParserModule ??= import("./internal/reasoning-tag-text-partitioner.mjs"));
|
|
1588
1461
|
const MAX_POST_TOOL_CALL_BUFFER_BYTES = 256e3;
|
|
1589
1462
|
const directMode = options?.mode === "direct";
|
|
1590
1463
|
const emitReasoning = options?.emitReasoning ?? true;
|
|
@@ -1600,6 +1473,7 @@ async function processCompletionsStream(responseStream, output, model, stream, o
|
|
|
1600
1473
|
const directContent = { block: null };
|
|
1601
1474
|
let currentTextSource;
|
|
1602
1475
|
let sawReasoning = false;
|
|
1476
|
+
let suppressedReasoning = false;
|
|
1603
1477
|
let pendingPostToolCallDeltas = [];
|
|
1604
1478
|
let pendingPostToolCallBytes = 0;
|
|
1605
1479
|
const toolCallBlocksByIndex = /* @__PURE__ */ new Map();
|
|
@@ -1787,10 +1661,13 @@ async function processCompletionsStream(responseStream, output, model, stream, o
|
|
|
1787
1661
|
chunkPushedEvent = false;
|
|
1788
1662
|
if (!rawChunk || typeof rawChunk !== "object") continue;
|
|
1789
1663
|
const chunk = rawChunk;
|
|
1790
|
-
output.responseId ||= chunk.id;
|
|
1791
|
-
if (typeof chunk.model === "string" && chunk.model.length > 0 && chunk.model !== model.id) output.responseModel ||= chunk.model;
|
|
1792
1664
|
const choice = Array.isArray(chunk.choices) ? chunk.choices[0] : void 0;
|
|
1793
1665
|
const usage = chunk.usage || choice?.usage;
|
|
1666
|
+
const rawChoiceDelta = choice?.delta ?? choice?.message;
|
|
1667
|
+
if (Boolean(choice?.finish_reason || rawChoiceDelta && (rawChoiceDelta.tool_calls?.length || hasOpenAICompletionsDeltaContent(rawChoiceDelta)) || asNonNegativeFiniteNumber(usage?.prompt_tokens) !== void 0 || asNonNegativeFiniteNumber(usage?.completion_tokens) !== void 0 || asNonNegativeFiniteNumber(usage?.total_tokens) !== void 0 || asNonNegativeFiniteNumber(usage?.completion_tokens_details?.reasoning_tokens) !== void 0)) {
|
|
1668
|
+
output.responseId ||= chunk.id;
|
|
1669
|
+
if (typeof chunk.model === "string" && chunk.model.length > 0 && chunk.model !== model.id) output.responseModel ||= chunk.model;
|
|
1670
|
+
}
|
|
1794
1671
|
if (chunk.timings !== void 0 && (choice?.finish_reason || Array.isArray(chunk.choices) && chunk.choices.length === 0 && chunk.usage)) {
|
|
1795
1672
|
const promptMs = asNonNegativeFiniteNumber(chunk.timings?.prompt_ms);
|
|
1796
1673
|
const predictedMs = asNonNegativeFiniteNumber(chunk.timings?.predicted_ms);
|
|
@@ -1805,7 +1682,6 @@ async function processCompletionsStream(responseStream, output, model, stream, o
|
|
|
1805
1682
|
const completeCounts = [usage.prompt_tokens, usage.completion_tokens].every((value) => typeof value === "number" && Number.isFinite(value) && value >= 0);
|
|
1806
1683
|
output.usage.usageReport = { state: terminalUsage && completeCounts ? "available" : "unavailable" };
|
|
1807
1684
|
}
|
|
1808
|
-
const rawChoiceDelta = choice?.delta ?? choice?.message;
|
|
1809
1685
|
if (!choice) {
|
|
1810
1686
|
emitReasoningUsageActivity(hasReasoningUsageActivity);
|
|
1811
1687
|
continue;
|
|
@@ -1826,6 +1702,10 @@ async function processCompletionsStream(responseStream, output, model, stream, o
|
|
|
1826
1702
|
const reasoningBatch = readOpenAICompletionsReasoningBatch(deltaFields, visibleReasoningDetailTypes);
|
|
1827
1703
|
const reasoningDeltas = reasoningBatch.deltas;
|
|
1828
1704
|
const hasReasoningThinking = reasoningBatch.hasThinking;
|
|
1705
|
+
if (hasReasoningThinking && !model.reasoning && !emitReasoning && !suppressedReasoning) {
|
|
1706
|
+
suppressedReasoning = true;
|
|
1707
|
+
recordSuppressedReasoning(output);
|
|
1708
|
+
}
|
|
1829
1709
|
const contentDeltas = readOpenAICompletionsContentDeltas(choiceDelta.content, choiceDelta.refusal, reasoningBatch.mirroredThinking);
|
|
1830
1710
|
const lastVisibleTextIndex = contentDeltas.findLastIndex((delta) => delta.kind === "text");
|
|
1831
1711
|
const hasSameChunkVisibleText = reasoningBatch.hasVisibleText || lastVisibleTextIndex !== -1;
|
|
@@ -1934,6 +1814,10 @@ async function processCompletionsStream(responseStream, output, model, stream, o
|
|
|
1934
1814
|
timestamp: Date.now(),
|
|
1935
1815
|
details: { processingMs: providerProcessingMs }
|
|
1936
1816
|
});
|
|
1817
|
+
if (suppressedReasoning) {
|
|
1818
|
+
const error = recordSuppressedReasoning(output);
|
|
1819
|
+
if (error) throw error;
|
|
1820
|
+
}
|
|
1937
1821
|
}
|
|
1938
1822
|
const MAX_MISSING_USAGE_HINT_KEYS = 256;
|
|
1939
1823
|
const missingUsageHintKeys = /* @__PURE__ */ new Set();
|
|
@@ -1947,10 +1831,11 @@ function warnMissingStreamingUsage(model) {
|
|
|
1947
1831
|
model: model.id
|
|
1948
1832
|
});
|
|
1949
1833
|
}
|
|
1950
|
-
function shouldEmitOpenAICompletionsReasoning(model, options) {
|
|
1834
|
+
function shouldEmitOpenAICompletionsReasoning(model, options, mode = "managed") {
|
|
1835
|
+
if (model.compat?.requiresReasoningContentOnAssistantMessages || requiresReasoningContentReplay(model.id)) return true;
|
|
1951
1836
|
if (!model.reasoning) return false;
|
|
1952
|
-
const effort = options?.reasoningEffort ?? options?.reasoning ?? "high";
|
|
1953
|
-
return Boolean(effort
|
|
1837
|
+
const effort = options?.reasoningEffort ?? (mode === "managed" ? options?.reasoning ?? "high" : void 0);
|
|
1838
|
+
return Boolean(effort && isOpenAICompletionsThinkingEnabled(effort));
|
|
1954
1839
|
}
|
|
1955
1840
|
//#endregion
|
|
1956
1841
|
//#region packages/ai/src/providers/openai-web-search-tools.ts
|
|
@@ -1966,24 +1851,6 @@ function hasResponsesWebSearchTool(tools) {
|
|
|
1966
1851
|
}
|
|
1967
1852
|
//#endregion
|
|
1968
1853
|
//#region packages/ai/src/transports/openai-responses-params-internal.ts
|
|
1969
|
-
const OPENAI_RESPONSES_TOOL_CALL_PROVIDERS = /* @__PURE__ */ new Set([
|
|
1970
|
-
"openai",
|
|
1971
|
-
"opencode",
|
|
1972
|
-
"azure-openai-responses",
|
|
1973
|
-
"github-copilot"
|
|
1974
|
-
]);
|
|
1975
|
-
function raiseMinimalReasoningForResponsesWebSearch(params) {
|
|
1976
|
-
if (params.effort !== "minimal" || !hasResponsesWebSearchTool(params.tools)) return params.effort;
|
|
1977
|
-
for (const effort of [
|
|
1978
|
-
"low",
|
|
1979
|
-
"medium",
|
|
1980
|
-
"high"
|
|
1981
|
-
]) {
|
|
1982
|
-
const resolved = resolveOpenAIRequestReasoning(params.model, effort).effort;
|
|
1983
|
-
if (resolved && resolved !== "none" && resolved !== "minimal") return resolved;
|
|
1984
|
-
}
|
|
1985
|
-
return params.effort;
|
|
1986
|
-
}
|
|
1987
1854
|
const OPENAI_CODEX_RESPONSES_UNSUPPORTED_PARAMS = [
|
|
1988
1855
|
"max_output_tokens",
|
|
1989
1856
|
"metadata",
|
|
@@ -2010,13 +1877,7 @@ function sanitizeOpenAICodexResponsesParams(model, params) {
|
|
|
2010
1877
|
}
|
|
2011
1878
|
function buildOpenAIResponsesInstructionsText(context) {
|
|
2012
1879
|
if (!context.systemPrompt) return;
|
|
2013
|
-
return
|
|
2014
|
-
}
|
|
2015
|
-
function resolveOpenAIResponsesInstructions(model, context, usesInstructionsField) {
|
|
2016
|
-
if (!usesInstructionsField) return;
|
|
2017
|
-
const instructions = buildOpenAIResponsesInstructionsText(context);
|
|
2018
|
-
if (instructions && instructions.trim().length > 0) return instructions;
|
|
2019
|
-
return usesNativeOpenAICodexResponsesBackend(model) ? OPENAI_CODEX_RESPONSES_DEFAULT_INSTRUCTIONS : void 0;
|
|
1880
|
+
return prepareSystemPrompt(context.systemPrompt, context.preparedSystemPrompt).instructions;
|
|
2020
1881
|
}
|
|
2021
1882
|
function buildOpenAIResponsesCompactSystemMessage(model, instructions) {
|
|
2022
1883
|
const compat = getCompat(model);
|
|
@@ -2026,38 +1887,37 @@ function buildOpenAIResponsesCompactSystemMessage(model, instructions) {
|
|
|
2026
1887
|
text: instructions
|
|
2027
1888
|
}]);
|
|
2028
1889
|
}
|
|
2029
|
-
function ensureOpenAIResponsesNonEmptyInput(messages, context) {
|
|
2030
|
-
if (messages.length > 0 || !context.systemPrompt) return;
|
|
2031
|
-
if (!buildOpenAIResponsesInstructionsText(context)) throw new Error("OpenAI Responses requires non-empty input when only systemPrompt is provided.");
|
|
2032
|
-
messages.push(buildResponsesInputMessage("user", [{
|
|
2033
|
-
type: "input_text",
|
|
2034
|
-
text: " "
|
|
2035
|
-
}]));
|
|
2036
|
-
}
|
|
2037
1890
|
function buildOpenAIResponsesParams(model, context, options, metadata, replayMode = "checkpoint", retainUserProvenance = false) {
|
|
2038
1891
|
const payloadPolicy = resolveOpenAIResponsesPayloadPolicy(model, { storeMode: "transport-default" });
|
|
2039
1892
|
const policyAllowsReplayIds = payloadPolicy.explicitStore !== false && !payloadPolicy.shouldStripStore;
|
|
2040
1893
|
const replayResponsesItemIds = !usesNativeOpenAICodexResponsesBackend(model) && (options?.replayResponsesItemIds ?? policyAllowsReplayIds);
|
|
2041
1894
|
const messages = convertResponsesMessages(model, context, OPENAI_RESPONSES_TOOL_CALL_PROVIDERS, {
|
|
2042
1895
|
includeSystemPrompt: !payloadPolicy.usesInstructionsField,
|
|
2043
|
-
replayReasoningItems: true,
|
|
2044
1896
|
replayResponsesItemIds,
|
|
2045
1897
|
authProfileId: options?.authProfileId,
|
|
1898
|
+
mutableInput: Boolean(options?.onPayload),
|
|
2046
1899
|
sessionId: options?.sessionId,
|
|
2047
1900
|
replayMode,
|
|
2048
1901
|
retainUserProvenance
|
|
2049
1902
|
});
|
|
2050
|
-
|
|
1903
|
+
if (messages.length === 0 && context.systemPrompt) {
|
|
1904
|
+
if (!buildOpenAIResponsesInstructionsText(context)) throw new Error("OpenAI Responses requires non-empty input when only systemPrompt is provided.");
|
|
1905
|
+
messages.push(buildResponsesInputMessage("user", [{
|
|
1906
|
+
type: "input_text",
|
|
1907
|
+
text: " "
|
|
1908
|
+
}]));
|
|
1909
|
+
}
|
|
2051
1910
|
const cacheRetention = resolveCacheRetention(options?.cacheRetention);
|
|
2052
1911
|
const compat = getCompat(model);
|
|
2053
1912
|
const promptCacheKey = compat.supportsPromptCacheKey ? resolvePromptCacheKey(options, cacheRetention) : void 0;
|
|
2054
|
-
|
|
1913
|
+
let instructions = payloadPolicy.usesInstructionsField ? buildOpenAIResponsesInstructionsText(context) : void 0;
|
|
1914
|
+
if (payloadPolicy.usesInstructionsField && (!instructions || instructions.trim().length === 0)) instructions = usesNativeOpenAICodexResponsesBackend(model) ? OPENAI_CODEX_RESPONSES_DEFAULT_INSTRUCTIONS : void 0;
|
|
2055
1915
|
const params = {
|
|
2056
1916
|
model: model.id,
|
|
2057
1917
|
input: messages,
|
|
2058
1918
|
stream: true,
|
|
2059
1919
|
prompt_cache_key: promptCacheKey,
|
|
2060
|
-
...resolveOpenAIPromptCacheParams(model, cacheRetention, compat),
|
|
1920
|
+
...resolveOpenAIPromptCacheParams(model, cacheRetention, compat, options?.promptCacheTtl),
|
|
2061
1921
|
...instructions ? { instructions } : {},
|
|
2062
1922
|
...metadata ? { metadata } : {}
|
|
2063
1923
|
};
|
|
@@ -2076,7 +1936,7 @@ function buildOpenAIResponsesParams(model, context, options, metadata, replayMod
|
|
|
2076
1936
|
transport: "stream",
|
|
2077
1937
|
supportsStrictMode: compat.supportsStrictMode
|
|
2078
1938
|
});
|
|
2079
|
-
const { projection, tools: converted } = prepareResponsesTools(tools, strict, model);
|
|
1939
|
+
const { projection, tools: converted } = prepareResponsesTools(tools, strict, model, Boolean(options?.onPayload));
|
|
2080
1940
|
if (converted.length > 0 || projection.inputToolCount === 0 && projection.diagnostics.length === 0) params.tools = converted;
|
|
2081
1941
|
if (options?.toolChoice) {
|
|
2082
1942
|
const toolChoice = reconcileOpenAIResponsesToolChoice(options.toolChoice, projection);
|
|
@@ -2088,17 +1948,24 @@ function buildOpenAIResponsesParams(model, context, options, metadata, replayMod
|
|
|
2088
1948
|
const requestedEffort = options?.reasoningEffort ?? (reasoning === "none" ? "none" : resolveOpenAISimpleReasoningEffort(model, reasoning)) ?? (options?.reasoningSummary ? "high" : payloadPolicy.defaultManagedReasoningEffort);
|
|
2089
1949
|
const resolvedEffort = requestedEffort === void 0 ? void 0 : resolveOpenAIRequestReasoning(model, requestedEffort).effort;
|
|
2090
1950
|
if (resolvedEffort !== void 0) {
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
1951
|
+
let effort = resolvedEffort;
|
|
1952
|
+
if (effort === "minimal" && hasResponsesWebSearchTool(params.tools)) for (const candidate of [
|
|
1953
|
+
"low",
|
|
1954
|
+
"medium",
|
|
1955
|
+
"high"
|
|
1956
|
+
]) {
|
|
1957
|
+
const resolved = resolveOpenAIRequestReasoning(model, candidate).effort;
|
|
1958
|
+
if (resolved && resolved !== "none" && resolved !== "minimal") {
|
|
1959
|
+
effort = resolved;
|
|
1960
|
+
break;
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
const summary = effort !== "none" && (options?.reasoningEffort || options?.reasoning || options?.reasoningSummary !== void 0) ? options.reasoningSummary === void 0 ? "auto" : options.reasoningSummary : void 0;
|
|
2097
1964
|
params.reasoning = {
|
|
2098
1965
|
effort,
|
|
2099
|
-
...summary ? { summary } : {}
|
|
1966
|
+
...summary !== void 0 ? { summary } : {}
|
|
2100
1967
|
};
|
|
2101
|
-
if (summary) params.include = ["reasoning.encrypted_content"];
|
|
1968
|
+
if (summary !== void 0) params.include = ["reasoning.encrypted_content"];
|
|
2102
1969
|
}
|
|
2103
1970
|
}
|
|
2104
1971
|
applyOpenAIResponsesPayloadPolicy(params, payloadPolicy);
|
|
@@ -2128,11 +1995,21 @@ async function postOpenAIResponsesCompaction(params) {
|
|
|
2128
1995
|
if (window.length > 1 && !supportsNativeOpenAIResponsesEndpoint(params.model)) throw new Error("Responses compact endpoint: retained messages require native OpenAI");
|
|
2129
1996
|
const usage = isRecord(response.usage) ? response.usage : void 0;
|
|
2130
1997
|
if (!usage || typeof usage.input_tokens !== "number" || typeof usage.output_tokens !== "number") throw new Error("Responses compact endpoint: usage must include input_tokens and output_tokens");
|
|
1998
|
+
const reasoningTokens = readResponsesReasoningTokens(usage);
|
|
1999
|
+
const modelUsage = {
|
|
2000
|
+
...createZeroUsage(),
|
|
2001
|
+
...mapResponsesTerminalUsage(usage),
|
|
2002
|
+
...reasoningTokens === void 0 ? {} : { reasoningTokens },
|
|
2003
|
+
usageReport: { state: "available" }
|
|
2004
|
+
};
|
|
2005
|
+
calculateCost(params.model, modelUsage);
|
|
2006
|
+
applyResponsesCacheWritePricing(modelUsage, usage);
|
|
2131
2007
|
return {
|
|
2132
2008
|
output: window,
|
|
2133
2009
|
item,
|
|
2134
2010
|
historyMode: window.length > 1 ? "retained-users" : "compacted-prefix",
|
|
2135
2011
|
usage,
|
|
2012
|
+
modelUsage,
|
|
2136
2013
|
model: params.model,
|
|
2137
2014
|
replayMetadata: buildOpenAIResponsesReasoningReplayMetadata(params.model, {
|
|
2138
2015
|
authProfileId: params.options?.authProfileId,
|
|
@@ -2229,20 +2106,21 @@ async function projectResponsesSteeringInput(request, project) {
|
|
|
2229
2106
|
const { input: activeInput, ...activeSettings } = cloneWireRequest(request);
|
|
2230
2107
|
if (!Array.isArray(activeInput)) return [];
|
|
2231
2108
|
const { input, ...settings } = cloneWireRequest(await project());
|
|
2232
|
-
if (!Array.isArray(input) ||
|
|
2109
|
+
if (!Array.isArray(input) || !isDeepStrictEqual(settings, activeSettings) || !isDeepStrictEqual(input.slice(0, activeInput.length), activeInput)) return [];
|
|
2233
2110
|
const projected = input.slice(activeInput.length);
|
|
2234
2111
|
return projected.every((item) => isRecord(item) && item.role === "user") ? projected : [];
|
|
2235
2112
|
}
|
|
2236
2113
|
/** One response owns admission; accepted input stays on this connection until continuation. */
|
|
2237
2114
|
function createResponsesSteering(params) {
|
|
2115
|
+
const needsContinuation = params.needsContinuation;
|
|
2238
2116
|
let responseId;
|
|
2239
|
-
let
|
|
2117
|
+
let active = params;
|
|
2240
2118
|
let unsubscribe;
|
|
2241
2119
|
const pending = [];
|
|
2242
2120
|
const accepted = /* @__PURE__ */ new Map();
|
|
2243
2121
|
const acknowledged = /* @__PURE__ */ new Set();
|
|
2244
2122
|
const seal = () => {
|
|
2245
|
-
|
|
2123
|
+
active = void 0;
|
|
2246
2124
|
const cleanup = unsubscribe;
|
|
2247
2125
|
unsubscribe = void 0;
|
|
2248
2126
|
cleanup?.();
|
|
@@ -2264,27 +2142,28 @@ function createResponsesSteering(params) {
|
|
|
2264
2142
|
},
|
|
2265
2143
|
handle(event) {
|
|
2266
2144
|
if (!isRecord(event)) return false;
|
|
2267
|
-
if (event.type === "response.created" && !responseId &&
|
|
2145
|
+
if (event.type === "response.created" && !responseId && active) {
|
|
2268
2146
|
const response = isRecord(event.response) ? event.response : void 0;
|
|
2269
2147
|
if (typeof response?.id !== "string" || !response.id.trim()) throw new Error("Responses steering requires a response identity");
|
|
2270
2148
|
const activeResponseId = response.id;
|
|
2271
2149
|
responseId = activeResponseId;
|
|
2272
|
-
const cleanup =
|
|
2273
|
-
needsContinuation:
|
|
2150
|
+
const cleanup = active.onActiveResponse({
|
|
2151
|
+
needsContinuation: needsContinuation === void 0 ? void 0 : () => needsContinuation,
|
|
2274
2152
|
steer(messages) {
|
|
2275
|
-
if (
|
|
2276
|
-
|
|
2277
|
-
const converted =
|
|
2153
|
+
if (!active || messages.length === 0) return Promise.resolve(false);
|
|
2154
|
+
active.assertActive();
|
|
2155
|
+
const converted = active.toInput(messages);
|
|
2278
2156
|
const submit = (input) => {
|
|
2279
|
-
|
|
2280
|
-
|
|
2157
|
+
const callbacks = active;
|
|
2158
|
+
if (!callbacks || input.length === 0) return Promise.resolve(false);
|
|
2159
|
+
callbacks.assertActive();
|
|
2281
2160
|
return new Promise((resolve, reject) => {
|
|
2282
2161
|
pending.push({
|
|
2283
2162
|
input,
|
|
2284
2163
|
resolve,
|
|
2285
2164
|
reject
|
|
2286
2165
|
});
|
|
2287
|
-
|
|
2166
|
+
callbacks.send({
|
|
2288
2167
|
type: "response.steer",
|
|
2289
2168
|
previous_response_id: activeResponseId,
|
|
2290
2169
|
input
|
|
@@ -2294,7 +2173,7 @@ function createResponsesSteering(params) {
|
|
|
2294
2173
|
return Array.isArray(converted) ? submit(converted) : converted.then(submit);
|
|
2295
2174
|
}
|
|
2296
2175
|
});
|
|
2297
|
-
if (
|
|
2176
|
+
if (!active) cleanup?.();
|
|
2298
2177
|
else unsubscribe = cleanup;
|
|
2299
2178
|
return false;
|
|
2300
2179
|
}
|
|
@@ -2403,7 +2282,7 @@ const SESSION_WEBSOCKET_MAX_AGE_MS = 33e5;
|
|
|
2403
2282
|
const WEBSOCKET_OPEN_STATE = 1;
|
|
2404
2283
|
function resolveNativeOpenAIResponsesWebSocketMode(model, transport) {
|
|
2405
2284
|
if (transport !== "websocket" && transport !== "websocket-cached" && transport !== "auto") return;
|
|
2406
|
-
if (getAiTransportHost().requiresManagedTransport(model)) return;
|
|
2285
|
+
if (getAiTransportHost().requiresManagedTransport(model, "fetch")) return;
|
|
2407
2286
|
return supportsNativeOpenAIResponsesEndpoint(model) ? transport : void 0;
|
|
2408
2287
|
}
|
|
2409
2288
|
function combineWebSocketTimeoutSignal(signal, model, timeoutMs) {
|
|
@@ -2434,25 +2313,42 @@ function invalidateOwnedWebSocketSession(cacheKey, entry, reason = "done") {
|
|
|
2434
2313
|
}
|
|
2435
2314
|
function scheduleSessionWebSocketExpiry(cacheKey, entry) {
|
|
2436
2315
|
if (entry.idleTimer) clearTimeout(entry.idleTimer);
|
|
2437
|
-
entry.idleTimer = setTimeout(() => {
|
|
2316
|
+
entry.idleTimer = entry.owner.runInDetachedAsyncContext(() => setTimeout(() => {
|
|
2438
2317
|
if (entry.busy) return;
|
|
2439
2318
|
invalidateOwnedWebSocketSession(cacheKey, entry, "idle_timeout");
|
|
2440
|
-
}, SESSION_WEBSOCKET_CACHE_TTL_MS);
|
|
2319
|
+
}, SESSION_WEBSOCKET_CACHE_TTL_MS));
|
|
2441
2320
|
entry.idleTimer.unref?.();
|
|
2442
2321
|
}
|
|
2322
|
+
function markDegradedWebSocketConnection(key, owner, sessionId, cooldownMs) {
|
|
2323
|
+
if (cooldownMs === void 0 || !Number.isFinite(cooldownMs) || cooldownMs <= 0) return;
|
|
2324
|
+
const entry = {
|
|
2325
|
+
sessionId,
|
|
2326
|
+
owner,
|
|
2327
|
+
retryAt: Date.now() + cooldownMs,
|
|
2328
|
+
expiryTimer: owner.runInDetachedAsyncContext(() => setTimeout(() => {
|
|
2329
|
+
if (degradedWebSocketConnections.get(key) === entry) degradedWebSocketConnections.delete(key);
|
|
2330
|
+
}, cooldownMs))
|
|
2331
|
+
};
|
|
2332
|
+
entry.expiryTimer.unref?.();
|
|
2333
|
+
degradedWebSocketConnections.set(key, entry);
|
|
2334
|
+
}
|
|
2443
2335
|
function prepareWebSocketConnection(client, headers) {
|
|
2444
2336
|
if (!isOfficialOpenAIResponsesBaseUrl(client.baseURL)) throw new Error("OpenAI Responses WebSocket requires the official API endpoint");
|
|
2445
2337
|
if (typeof client.apiKey !== "string" || client.apiKey.length === 0) throw new Error("OpenAI Responses WebSocket requires an API key");
|
|
2446
2338
|
const owner = getAiTransportHost();
|
|
2447
2339
|
const resolvedApiKey = owner.resolveSecretSentinel(client.apiKey);
|
|
2448
|
-
const resolvedHeaders = { ...resolveAiTransportHeaderSentinels(headers) };
|
|
2340
|
+
const resolvedHeaders = { ...omitNullRequestHeaders(resolveAiTransportHeaderSentinels(headers)) };
|
|
2449
2341
|
for (const key of Object.keys(resolvedHeaders)) {
|
|
2450
2342
|
const normalizedKey = key.toLowerCase();
|
|
2451
2343
|
if (normalizedKey === "authorization" || normalizedKey === "traceparent") delete resolvedHeaders[key];
|
|
2452
2344
|
}
|
|
2453
2345
|
if (!resolvedApiKey) throw new Error("OpenAI Responses WebSocket requires a resolved API key");
|
|
2454
2346
|
return {
|
|
2455
|
-
client: client.withOptions({
|
|
2347
|
+
client: client.withOptions({
|
|
2348
|
+
apiKey: resolvedApiKey,
|
|
2349
|
+
fetch: void 0,
|
|
2350
|
+
logger: void 0
|
|
2351
|
+
}),
|
|
2456
2352
|
headers: resolvedHeaders,
|
|
2457
2353
|
owner,
|
|
2458
2354
|
ownerId: getSessionResourceOwnerId(owner),
|
|
@@ -2464,10 +2360,10 @@ function prepareWebSocketConnection(client, headers) {
|
|
|
2464
2360
|
};
|
|
2465
2361
|
}
|
|
2466
2362
|
function createWebSocket(connection, onError) {
|
|
2467
|
-
const socket = new ResponsesWS(connection.client, {
|
|
2363
|
+
const socket = connection.owner.runInDetachedAsyncContext(() => new ResponsesWS(connection.client, {
|
|
2468
2364
|
headers: connection.headers,
|
|
2469
2365
|
maxQueueSize: 1
|
|
2470
|
-
});
|
|
2366
|
+
}));
|
|
2471
2367
|
socket.on("error", () => onError(socket));
|
|
2472
2368
|
return socket;
|
|
2473
2369
|
}
|
|
@@ -2490,7 +2386,8 @@ function createCachedWebSocketLease(cacheKey, entry, reusedConnection) {
|
|
|
2490
2386
|
entry,
|
|
2491
2387
|
reusedConnection,
|
|
2492
2388
|
steeringContinuation,
|
|
2493
|
-
release: (
|
|
2389
|
+
release: (options = {}) => {
|
|
2390
|
+
const { keep } = options;
|
|
2494
2391
|
if (!keep || entry.socket.socket.readyState !== WEBSOCKET_OPEN_STATE) {
|
|
2495
2392
|
invalidateOwnedWebSocketSession(cacheKey, entry);
|
|
2496
2393
|
return;
|
|
@@ -2550,20 +2447,7 @@ function createOpenAIResponsesWebSocketStream(params) {
|
|
|
2550
2447
|
if (degraded && degraded.retryAt > Date.now()) throw new OpenAIResponsesWebSocketPreDispatchError(/* @__PURE__ */ new Error("OpenAI Responses WebSocket is cooling down after a transport failure"));
|
|
2551
2448
|
if (degraded) clearTimeout(degraded.expiryTimer);
|
|
2552
2449
|
degradedWebSocketConnections.delete(degradationKey);
|
|
2553
|
-
const markDegraded = () =>
|
|
2554
|
-
const cooldownMs = params.degradeCooldownMs;
|
|
2555
|
-
if (cooldownMs === void 0 || !Number.isFinite(cooldownMs) || cooldownMs <= 0) return;
|
|
2556
|
-
const entry = {
|
|
2557
|
-
sessionId: params.sessionId,
|
|
2558
|
-
owner: connection.owner,
|
|
2559
|
-
retryAt: Date.now() + cooldownMs,
|
|
2560
|
-
expiryTimer: setTimeout(() => {
|
|
2561
|
-
if (degradedWebSocketConnections.get(degradationKey) === entry) degradedWebSocketConnections.delete(degradationKey);
|
|
2562
|
-
}, cooldownMs)
|
|
2563
|
-
};
|
|
2564
|
-
entry.expiryTimer.unref?.();
|
|
2565
|
-
degradedWebSocketConnections.set(degradationKey, entry);
|
|
2566
|
-
};
|
|
2450
|
+
const markDegraded = () => markDegradedWebSocketConnection(degradationKey, connection.owner, params.sessionId, params.degradeCooldownMs);
|
|
2567
2451
|
let lease;
|
|
2568
2452
|
try {
|
|
2569
2453
|
lease = acquireWebSocket(params, connection);
|
|
@@ -2634,7 +2518,7 @@ function createOpenAIResponsesWebSocketStream(params) {
|
|
|
2634
2518
|
onActiveResponse: params.onActiveResponse,
|
|
2635
2519
|
toInput: params.steeringInput,
|
|
2636
2520
|
send: (event) => lease.socket.sendRaw(JSON.stringify(event)),
|
|
2637
|
-
needsContinuation:
|
|
2521
|
+
needsContinuation: deferredInput,
|
|
2638
2522
|
assertActive: () => {
|
|
2639
2523
|
if (released || terminalReceived || params.signal?.aborted) throw new Error("Responses steering is no longer active");
|
|
2640
2524
|
}
|
|
@@ -2684,7 +2568,7 @@ function createOpenAIResponsesWebSocketStream(params) {
|
|
|
2684
2568
|
}
|
|
2685
2569
|
steering?.handle(event);
|
|
2686
2570
|
if (event.type === "response.completed") terminalResponse = event.response;
|
|
2687
|
-
terminalReceived = event.type
|
|
2571
|
+
terminalReceived = isResponsesTerminalEventType(event.type);
|
|
2688
2572
|
if (terminalReceived) {
|
|
2689
2573
|
steering?.seal();
|
|
2690
2574
|
if (event.type === "response.failed") steering?.close(/* @__PURE__ */ new Error("Responses failed before steering could be applied"));
|
|
@@ -2792,6 +2676,7 @@ function createResponsesTransportExecutor(config) {
|
|
|
2792
2676
|
(async () => {
|
|
2793
2677
|
const output = createAssistantOutput(model, config.outputApi);
|
|
2794
2678
|
let firstEventAbort;
|
|
2679
|
+
let requestSignal = options?.signal;
|
|
2795
2680
|
let continuationClaim;
|
|
2796
2681
|
const requestLifecycle = responsesRequestLifecycle.get(options);
|
|
2797
2682
|
try {
|
|
@@ -2814,7 +2699,7 @@ function createResponsesTransportExecutor(config) {
|
|
|
2814
2699
|
compact: compactRequest?.mode === "endpoint",
|
|
2815
2700
|
stream: config.streamRequest,
|
|
2816
2701
|
lifecycle: requestLifecycle,
|
|
2817
|
-
onSseComment: () => notifyLlmRequestActivity(options?.signal, false)
|
|
2702
|
+
onSseComment: () => notifyLlmRequestActivity(options?.signal, false, 9e5)
|
|
2818
2703
|
}) ?? buildGuardedModelFetch(model), options?.onResponse, model);
|
|
2819
2704
|
const client = config.createClient(model, apiKey, httpHeaders, fetchOverride);
|
|
2820
2705
|
const nativeAstra = model.id === "gpt-6-astra" && supportsNativeOpenAIResponsesEndpoint(model);
|
|
@@ -2859,10 +2744,7 @@ function createResponsesTransportExecutor(config) {
|
|
|
2859
2744
|
request: params,
|
|
2860
2745
|
options: responsesOptions
|
|
2861
2746
|
});
|
|
2862
|
-
output.usage
|
|
2863
|
-
output.usage.output = compacted.usage.output_tokens;
|
|
2864
|
-
output.usage.totalTokens = compacted.usage.input_tokens + compacted.usage.output_tokens;
|
|
2865
|
-
output.usage.usageReport = { state: "available" };
|
|
2747
|
+
output.usage = compacted.modelUsage;
|
|
2866
2748
|
compactRequest.resolve(compacted);
|
|
2867
2749
|
finalizeTransportStream({
|
|
2868
2750
|
stream,
|
|
@@ -2884,7 +2766,7 @@ function createResponsesTransportExecutor(config) {
|
|
|
2884
2766
|
});
|
|
2885
2767
|
params = continuationClaim?.fullRequest ?? restoreRequest();
|
|
2886
2768
|
}
|
|
2887
|
-
const observePrompt = createResponsesPromptEgressObserver(responsesOptions, context
|
|
2769
|
+
const observePrompt = createResponsesPromptEgressObserver(responsesOptions, context);
|
|
2888
2770
|
const requestStartedAt = Date.now();
|
|
2889
2771
|
let started = false;
|
|
2890
2772
|
const startStream = () => {
|
|
@@ -2903,13 +2785,14 @@ function createResponsesTransportExecutor(config) {
|
|
|
2903
2785
|
timeoutMs: options?.timeoutMs
|
|
2904
2786
|
});
|
|
2905
2787
|
const websocketSignal = combineWebSocketTimeoutSignal(firstEvent.signal, model, requestOptions?.timeout);
|
|
2906
|
-
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)}`);
|
|
2788
|
+
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)}`);
|
|
2907
2789
|
const responseModelTracker = createResponseModelTracker(isOpenAICodexResponsesModel(model));
|
|
2908
2790
|
let continuationBaseline;
|
|
2909
2791
|
let dispatchedPreviousResponseId;
|
|
2910
2792
|
let contextUsageEligible = true;
|
|
2911
2793
|
let requestedTier;
|
|
2912
2794
|
const createSseStream = async (initialRequest = continuationClaim?.request ?? params, initialAttemptKind = "initial", initialRejectedCompaction) => {
|
|
2795
|
+
requestSignal = firstEvent.signal;
|
|
2913
2796
|
const { stream: responseStream } = await createResponsesStreamWithRecovery({
|
|
2914
2797
|
client,
|
|
2915
2798
|
request: initialRequest,
|
|
@@ -2935,7 +2818,7 @@ function createResponsesTransportExecutor(config) {
|
|
|
2935
2818
|
abort: firstEvent.abort,
|
|
2936
2819
|
hook: createOpenAIProviderAcceptanceHook(options, response, model),
|
|
2937
2820
|
onReady: () => {
|
|
2938
|
-
emitModelTransportDebug(log, `[responses] headers provider=${model.provider} api=${model.api} model=${model.id} transport=sse elapsedMs=${Date.now() - requestStartedAt}`);
|
|
2821
|
+
emitModelTransportDebug(log, () => `[responses] headers provider=${model.provider} api=${model.api} model=${model.id} transport=sse elapsedMs=${Date.now() - requestStartedAt}`);
|
|
2939
2822
|
startStream();
|
|
2940
2823
|
}
|
|
2941
2824
|
});
|
|
@@ -2947,70 +2830,73 @@ function createResponsesTransportExecutor(config) {
|
|
|
2947
2830
|
let websocketBaseline;
|
|
2948
2831
|
let finishWebSocket;
|
|
2949
2832
|
let transport = "sse";
|
|
2950
|
-
const logWebSocketFallback = (reason) => emitModelTransportDebug(log, `[responses] websocket_fallback provider=${model.provider} api=${model.api} model=${model.id} reason=${reason}`);
|
|
2833
|
+
const logWebSocketFallback = (reason) => emitModelTransportDebug(log, () => `[responses] websocket_fallback provider=${model.provider} api=${model.api} model=${model.id} reason=${reason}`);
|
|
2951
2834
|
const closeWebSocketForFallback = (reason) => {
|
|
2952
2835
|
finishWebSocket?.({ keep: false });
|
|
2953
2836
|
finishWebSocket = void 0;
|
|
2954
2837
|
transport = "sse";
|
|
2955
2838
|
logWebSocketFallback(reason);
|
|
2956
2839
|
};
|
|
2957
|
-
if (websocketMode)
|
|
2958
|
-
|
|
2959
|
-
|
|
2960
|
-
|
|
2961
|
-
|
|
2962
|
-
|
|
2963
|
-
|
|
2964
|
-
|
|
2965
|
-
|
|
2966
|
-
|
|
2967
|
-
|
|
2968
|
-
|
|
2969
|
-
|
|
2970
|
-
|
|
2971
|
-
|
|
2972
|
-
|
|
2973
|
-
|
|
2974
|
-
|
|
2975
|
-
|
|
2976
|
-
|
|
2977
|
-
|
|
2978
|
-
|
|
2979
|
-
|
|
2980
|
-
|
|
2981
|
-
|
|
2982
|
-
|
|
2983
|
-
|
|
2984
|
-
|
|
2985
|
-
|
|
2986
|
-
|
|
2987
|
-
|
|
2988
|
-
|
|
2989
|
-
|
|
2990
|
-
|
|
2991
|
-
|
|
2992
|
-
|
|
2993
|
-
|
|
2994
|
-
|
|
2995
|
-
|
|
2996
|
-
|
|
2997
|
-
|
|
2998
|
-
|
|
2999
|
-
|
|
3000
|
-
|
|
3001
|
-
|
|
3002
|
-
|
|
3003
|
-
|
|
3004
|
-
|
|
3005
|
-
|
|
3006
|
-
|
|
3007
|
-
|
|
3008
|
-
|
|
2840
|
+
if (websocketMode) {
|
|
2841
|
+
requestSignal = websocketSignal;
|
|
2842
|
+
try {
|
|
2843
|
+
const websocket = createOpenAIResponsesWebSocketStream({
|
|
2844
|
+
client,
|
|
2845
|
+
request: params,
|
|
2846
|
+
restoreRequest: (request) => restoreResponsesReasoningState(context, model, responsesOptions, request),
|
|
2847
|
+
mode: websocketMode,
|
|
2848
|
+
sessionId: options?.sessionId,
|
|
2849
|
+
headers: websocketHeaders,
|
|
2850
|
+
signal: websocketSignal,
|
|
2851
|
+
callerSignal: options?.signal,
|
|
2852
|
+
degradeCooldownMs: websocketSessionPolicy?.degradeCooldownMs,
|
|
2853
|
+
onActiveResponse: !compactRequest && nativeAstra && params.model === "gpt-6-astra" ? options?.onActiveResponse : void 0,
|
|
2854
|
+
steeringInput: (messages) => {
|
|
2855
|
+
contextUsageEligible = false;
|
|
2856
|
+
return projectResponsesSteeringInput(params, () => buildRequest("checkpoint", {
|
|
2857
|
+
...context,
|
|
2858
|
+
messages: [...context.messages, ...messages]
|
|
2859
|
+
}));
|
|
2860
|
+
}
|
|
2861
|
+
});
|
|
2862
|
+
finishWebSocket = websocket.finish;
|
|
2863
|
+
requestedTier = websocket.request.service_tier;
|
|
2864
|
+
websocketBaseline = websocket.fullRequest;
|
|
2865
|
+
recordResponsesInputReplay(output, websocket.inputReplay);
|
|
2866
|
+
contextUsageEligible &&= websocket.inputReplay === void 0;
|
|
2867
|
+
observePrompt?.(websocket.request, {
|
|
2868
|
+
egress: "responses-websocket",
|
|
2869
|
+
payloadVariant: "initial"
|
|
2870
|
+
});
|
|
2871
|
+
transport = "websocket";
|
|
2872
|
+
emitModelTransportDebug(log, () => `[responses] websocket_selected provider=${model.provider} api=${model.api} model=${model.id} mode=${websocketMode} reused=${websocket.reusedConnection} continuation=${websocket.continuationStatus === "continued"} continuationStatus=${websocket.continuationStatus} sessionIdHash=${redactIdentifier(options?.sessionId)} headersHash=${redactIdentifier(JSON.stringify(Object.entries(websocketHeaders ?? {}).toSorted(([a], [b]) => a.localeCompare(b))))}`);
|
|
2873
|
+
responseStream = createRecoverableResponsesWebSocketStream({
|
|
2874
|
+
trackedWebSocketStream: observeResponsesStream(v2Compaction ? v2Compaction.observe(responseModelTracker.track(void 0, websocket.stream)) : responseModelTracker.track(void 0, websocket.stream), model, requestStartedAt, websocket.request, "websocket"),
|
|
2875
|
+
websocket,
|
|
2876
|
+
websocketSignal,
|
|
2877
|
+
options,
|
|
2878
|
+
output,
|
|
2879
|
+
buildRequest,
|
|
2880
|
+
createSseStream,
|
|
2881
|
+
closeWebSocketForFallback,
|
|
2882
|
+
logWebSocketFallback,
|
|
2883
|
+
startStream,
|
|
2884
|
+
setTransportToSse: () => {
|
|
2885
|
+
transport = "sse";
|
|
2886
|
+
}
|
|
2887
|
+
});
|
|
2888
|
+
} catch (error) {
|
|
2889
|
+
if (error instanceof OpenAIResponsesWebSocketPostDispatchError) throw error;
|
|
2890
|
+
closeWebSocketForFallback("setup_failure");
|
|
2891
|
+
responseStream = await createSseStream();
|
|
2892
|
+
}
|
|
2893
|
+
} else responseStream = await createSseStream();
|
|
3009
2894
|
try {
|
|
3010
2895
|
const acceptedResponseStream = withResponsesRequestAcceptance(responseStream, requestLifecycle, transport === "websocket" ? websocketSignal : firstEvent.signal);
|
|
3011
2896
|
const terminal = await processResponsesStream(acceptedResponseStream, output, stream, model, {
|
|
3012
2897
|
canRetryIdentityConflict: () => hasOnlyResponsesFunctionTools(transport === "websocket" ? websocketBaseline : continuationBaseline),
|
|
3013
2898
|
...config.pricingOptions?.(responsesOptions, model),
|
|
2899
|
+
promptCacheTtl: params.prompt_cache_options?.ttl,
|
|
3014
2900
|
resolveServiceTier: (responseTier, originalTier) => responseTier ?? (requestedTier === "priority" || requestedTier === "default" ? requestedTier : originalTier),
|
|
3015
2901
|
onServiceTier: (tier, response) => responsesServiceTierObserver.observe(options, requestedTier, tier, response),
|
|
3016
2902
|
firstEventTimeoutMs: getFirstStreamEventTimeoutMs(options) ?? config.firstEventTimeoutMs,
|
|
@@ -3053,13 +2939,14 @@ function createResponsesTransportExecutor(config) {
|
|
|
3053
2939
|
finishWebSocket?.({ keep: false });
|
|
3054
2940
|
throw error;
|
|
3055
2941
|
}
|
|
3056
|
-
emitModelTransportDebug(log, `[responses] completed provider=${model.provider} api=${model.api} model=${model.id} transport=${transport} elapsedMs=${Date.now() - requestStartedAt}`);
|
|
2942
|
+
emitModelTransportDebug(log, () => `[responses] completed provider=${model.provider} api=${model.api} model=${model.id} transport=${transport} elapsedMs=${Date.now() - requestStartedAt}`);
|
|
3057
2943
|
finalizeTransportStream({
|
|
3058
2944
|
stream,
|
|
3059
2945
|
output,
|
|
3060
2946
|
signal: options?.signal
|
|
3061
2947
|
});
|
|
3062
2948
|
} catch (error) {
|
|
2949
|
+
if (error instanceof DegenerateToolCallArgumentsError) firstEventAbort?.abort(error);
|
|
3063
2950
|
if (requestLifecycle) await requestLifecycle.settle().catch(() => void 0);
|
|
3064
2951
|
if (compactRequest) {
|
|
3065
2952
|
compactRequest.reject(error);
|
|
@@ -3071,14 +2958,18 @@ function createResponsesTransportExecutor(config) {
|
|
|
3071
2958
|
});
|
|
3072
2959
|
return;
|
|
3073
2960
|
}
|
|
3074
|
-
if (error instanceof ResponsesStreamFailure && error.observation) logResponsesFailedNoDetails(error.observation);
|
|
3075
|
-
const incompleteReason = output.diagnostics?.find(({ type }) => type === "openai_responses_terminal")?.details?.incompleteReason;
|
|
3076
|
-
emitModelTransportError(log, "responses", `provider=${model.provider} api=${model.api} model=${model.id} ` + summarizeOpenAITransportError(error) + (typeof incompleteReason === "string" ? ` incompleteReason=${incompleteReason}` : ""), options?.signal);
|
|
3077
2961
|
failTransportStream({
|
|
3078
2962
|
stream,
|
|
3079
2963
|
output,
|
|
3080
2964
|
signal: options?.signal,
|
|
3081
|
-
error
|
|
2965
|
+
error,
|
|
2966
|
+
diagnostic: observeResponsesTransportFailure({
|
|
2967
|
+
error,
|
|
2968
|
+
model,
|
|
2969
|
+
output,
|
|
2970
|
+
signal: options?.signal,
|
|
2971
|
+
requestSignal
|
|
2972
|
+
})
|
|
3082
2973
|
});
|
|
3083
2974
|
} finally {
|
|
3084
2975
|
continuationClaim?.release();
|
|
@@ -3140,6 +3031,8 @@ function assertOpenAICompletionsPayloadHasConversationTurn(params, model) {
|
|
|
3140
3031
|
if (!Array.isArray(messages) || hasOpenAICompatibleConversationTurn(messages)) return;
|
|
3141
3032
|
throw new Error(`OpenAI-compatible chat payload for ${model.provider}/${model.id} contains no non-empty user or assistant messages after compaction and transport transforms; refusing to send a system/tool-only request. Start a new user turn or repair the compacted session history.`);
|
|
3142
3033
|
}
|
|
3034
|
+
const MAX_CONTEXT_BUDGET_BUFFER_CHUNKS = 8192;
|
|
3035
|
+
const MAX_CONTEXT_BUDGET_BUFFER_BYTES = 4194304;
|
|
3143
3036
|
const SSE_DONE_LINE_RE = /^data:[ \t]*\[DONE\][ \t]*$/i;
|
|
3144
3037
|
const SSE_DONE_MAX_LINE_CHARS = 1024;
|
|
3145
3038
|
function createSseDoneDetector() {
|
|
@@ -3153,12 +3046,9 @@ function createSseDoneDetector() {
|
|
|
3153
3046
|
lineOverflowed = false;
|
|
3154
3047
|
};
|
|
3155
3048
|
const observeText = (text) => {
|
|
3156
|
-
for (const
|
|
3157
|
-
if (
|
|
3158
|
-
|
|
3159
|
-
continue;
|
|
3160
|
-
}
|
|
3161
|
-
if (!lineOverflowed && line.length < SSE_DONE_MAX_LINE_CHARS) line += char;
|
|
3049
|
+
for (const [index, segment] of text.split(/[\r\n]/).entries()) {
|
|
3050
|
+
if (index > 0) finishLine();
|
|
3051
|
+
if (!lineOverflowed && line.length + segment.length <= SSE_DONE_MAX_LINE_CHARS) line += segment;
|
|
3162
3052
|
else lineOverflowed = true;
|
|
3163
3053
|
}
|
|
3164
3054
|
};
|
|
@@ -3174,33 +3064,6 @@ function createSseDoneDetector() {
|
|
|
3174
3064
|
sawDone: () => sawDone
|
|
3175
3065
|
};
|
|
3176
3066
|
}
|
|
3177
|
-
function buildOpenAICompletionsClientConfig(model, headers) {
|
|
3178
|
-
const defaultQuery = {};
|
|
3179
|
-
let baseURL = model.baseUrl;
|
|
3180
|
-
let isAzureHost = false;
|
|
3181
|
-
const parsed = URL.parse(model.baseUrl);
|
|
3182
|
-
if (parsed) {
|
|
3183
|
-
isAzureHost = isAzureOpenAICompatibleHost(parsed.hostname.toLowerCase());
|
|
3184
|
-
parsed.searchParams.forEach((value, key) => {
|
|
3185
|
-
if (value) defaultQuery[key] = value;
|
|
3186
|
-
});
|
|
3187
|
-
parsed.search = "";
|
|
3188
|
-
baseURL = parsed.toString().replace(/\/$/, "");
|
|
3189
|
-
}
|
|
3190
|
-
if (isAzureHost) {
|
|
3191
|
-
const apiVersionHeader = Object.keys(headers).find((key) => key.toLowerCase() === "api-version");
|
|
3192
|
-
if (apiVersionHeader) {
|
|
3193
|
-
const apiVersion = headers[apiVersionHeader]?.trim();
|
|
3194
|
-
delete headers[apiVersionHeader];
|
|
3195
|
-
if (apiVersion && !defaultQuery["api-version"]) defaultQuery["api-version"] = apiVersion;
|
|
3196
|
-
}
|
|
3197
|
-
}
|
|
3198
|
-
return {
|
|
3199
|
-
baseURL: resolveOpenAIClientBaseUrl(model, baseURL),
|
|
3200
|
-
defaultHeaders: headers,
|
|
3201
|
-
defaultQuery: Object.keys(defaultQuery).length > 0 ? defaultQuery : void 0
|
|
3202
|
-
};
|
|
3203
|
-
}
|
|
3204
3067
|
function createDirectCompletionsEventStream(output, stream) {
|
|
3205
3068
|
const finishedBlocks = /* @__PURE__ */ new Set();
|
|
3206
3069
|
const contentIndices = /* @__PURE__ */ new WeakMap();
|
|
@@ -3280,8 +3143,8 @@ function streamOpenAICompletionsRequest(model, context, options, mode) {
|
|
|
3280
3143
|
let discardCandidate = false;
|
|
3281
3144
|
let firstEventAbort;
|
|
3282
3145
|
try {
|
|
3146
|
+
const requestContext = await resolveProviderContext(context, options);
|
|
3283
3147
|
const apiKey = options?.apiKey || getEnvApiKey(model.provider) || "";
|
|
3284
|
-
const directEmitReasoning = Boolean(mode === "direct" && model.reasoning && options?.reasoningEffort && isOpenAICompletionsThinkingEnabled(options.reasoningEffort));
|
|
3285
3148
|
const cacheRetention = resolveCacheRetention(options?.cacheRetention);
|
|
3286
3149
|
const policy = mode === "direct" ? {
|
|
3287
3150
|
mode,
|
|
@@ -3289,10 +3152,89 @@ function streamOpenAICompletionsRequest(model, context, options, mode) {
|
|
|
3289
3152
|
cacheRetention
|
|
3290
3153
|
} : { mode };
|
|
3291
3154
|
const { client, sawStreamDONE } = policy.mode === "direct" ? {
|
|
3292
|
-
client:
|
|
3155
|
+
client: (() => {
|
|
3156
|
+
const sessionId = cacheRetention === "none" ? void 0 : options?.sessionId;
|
|
3157
|
+
const compat = policy.compat;
|
|
3158
|
+
if (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);
|
|
3159
|
+
const headers = { ...model.headers };
|
|
3160
|
+
if (model.provider === "github-copilot") Object.assign(headers, buildCopilotDynamicHeaders(context.messages));
|
|
3161
|
+
if (sessionId && compat.sessionAffinity !== "none") {
|
|
3162
|
+
if (compat.sessionAffinity === "openrouter") headers["x-session-id"] = sessionId;
|
|
3163
|
+
else {
|
|
3164
|
+
headers.session_id = sessionId;
|
|
3165
|
+
headers["x-client-request-id"] = sessionId;
|
|
3166
|
+
headers["x-session-affinity"] = sessionId;
|
|
3167
|
+
}
|
|
3168
|
+
}
|
|
3169
|
+
return createOpenAIProviderClient(model, apiKey, headers, resolveProviderSimpleCompletionHeaders(model, options), options?.onResponse);
|
|
3170
|
+
})(),
|
|
3293
3171
|
sawStreamDONE: void 0
|
|
3294
|
-
} :
|
|
3295
|
-
|
|
3172
|
+
} : (() => {
|
|
3173
|
+
const turnState = resolveProviderTransportTurnState(model, {
|
|
3174
|
+
sessionId: options?.sessionId,
|
|
3175
|
+
turnId: randomUUID(),
|
|
3176
|
+
attempt: 1,
|
|
3177
|
+
transport: "stream"
|
|
3178
|
+
});
|
|
3179
|
+
const optionHeaders = resolveOpencodeSessionHeaders(model, options);
|
|
3180
|
+
const turnHeaders = filterProviderTurnHeadersForExplicitOpencodeSession(model, options, turnState?.headers);
|
|
3181
|
+
const doneDetector = createSseDoneDetector();
|
|
3182
|
+
const baseFetch = withOpenAIErrorResponseHook(buildGuardedModelFetch(model, void 0, { onSseComment: () => notifyLlmRequestActivity(options?.signal, false) }), options?.onResponse, model);
|
|
3183
|
+
const doneDetectingFetch = async (url, init) => {
|
|
3184
|
+
const response = await baseFetch(url, init);
|
|
3185
|
+
if (!response.body || !response.ok) return response;
|
|
3186
|
+
if (typeof TransformStream === "undefined" || !response.body.pipeThrough) return response;
|
|
3187
|
+
const transformed = response.body.pipeThrough(new TransformStream({
|
|
3188
|
+
transform(chunk, controller) {
|
|
3189
|
+
doneDetector.observe(chunk);
|
|
3190
|
+
controller.enqueue(chunk);
|
|
3191
|
+
},
|
|
3192
|
+
flush() {
|
|
3193
|
+
doneDetector.finish();
|
|
3194
|
+
}
|
|
3195
|
+
}));
|
|
3196
|
+
return new Response(transformed, response);
|
|
3197
|
+
};
|
|
3198
|
+
const headers = buildOpenAIClientHeaders(model, context, {
|
|
3199
|
+
...turnHeaders,
|
|
3200
|
+
...optionHeaders
|
|
3201
|
+
}, void 0, resolvePromptCacheKey(options, cacheRetention), cacheRetention);
|
|
3202
|
+
const defaultQuery = {};
|
|
3203
|
+
let baseURL = model.baseUrl;
|
|
3204
|
+
let isAzureHost = false;
|
|
3205
|
+
const parsed = URL.parse(model.baseUrl);
|
|
3206
|
+
if (parsed) {
|
|
3207
|
+
isAzureHost = isAzureOpenAICompatibleHost(parsed.hostname.toLowerCase());
|
|
3208
|
+
parsed.searchParams.forEach((value, key) => {
|
|
3209
|
+
if (value) defaultQuery[key] = value;
|
|
3210
|
+
});
|
|
3211
|
+
parsed.search = "";
|
|
3212
|
+
baseURL = parsed.toString().replace(/\/$/, "");
|
|
3213
|
+
}
|
|
3214
|
+
if (isAzureHost) {
|
|
3215
|
+
const apiVersionHeader = Object.keys(headers).find((key) => key.toLowerCase() === "api-version");
|
|
3216
|
+
if (apiVersionHeader) {
|
|
3217
|
+
const apiVersion = headers[apiVersionHeader]?.trim();
|
|
3218
|
+
delete headers[apiVersionHeader];
|
|
3219
|
+
if (apiVersion && !defaultQuery["api-version"]) defaultQuery["api-version"] = apiVersion;
|
|
3220
|
+
}
|
|
3221
|
+
}
|
|
3222
|
+
const resolvedBaseURL = resolveOpenAIClientBaseUrl(model, baseURL);
|
|
3223
|
+
const resolvedDefaultQuery = Object.keys(defaultQuery).length > 0 ? defaultQuery : void 0;
|
|
3224
|
+
return {
|
|
3225
|
+
client: new OpenAI({
|
|
3226
|
+
apiKey,
|
|
3227
|
+
baseURL: resolvedBaseURL,
|
|
3228
|
+
dangerouslyAllowBrowser: true,
|
|
3229
|
+
defaultHeaders: headers,
|
|
3230
|
+
defaultQuery: resolvedDefaultQuery,
|
|
3231
|
+
fetch: doneDetectingFetch,
|
|
3232
|
+
...buildOpenAISdkClientOptions(model)
|
|
3233
|
+
}),
|
|
3234
|
+
sawStreamDONE: doneDetector.sawDone
|
|
3235
|
+
};
|
|
3236
|
+
})();
|
|
3237
|
+
const builtParams = buildOpenAICompletionsRequest(model, requestContext, options, policy);
|
|
3296
3238
|
let params = builtParams;
|
|
3297
3239
|
const encodeBody = prepareModelRequestBody(options);
|
|
3298
3240
|
const nextParams = await options?.onPayload?.(params, model);
|
|
@@ -3306,7 +3248,7 @@ function streamOpenAICompletionsRequest(model, context, options, mode) {
|
|
|
3306
3248
|
if (getCompat(model).requiresNonEmptyUserOrAssistantMessage) assertOpenAICompletionsPayloadHasConversationTurn(params, model);
|
|
3307
3249
|
}
|
|
3308
3250
|
const contextOutputBudget = resolveCompletionsContextOutputBudget(builtParams, params);
|
|
3309
|
-
const emitReasoning =
|
|
3251
|
+
const emitReasoning = shouldEmitOpenAICompletionsReasoning(model, options, mode);
|
|
3310
3252
|
firstEventAbort = createFirstStreamEventAbortController(options?.signal);
|
|
3311
3253
|
const requestOptions = mode === "direct" ? {
|
|
3312
3254
|
...await encodeBody(params),
|
|
@@ -3352,7 +3294,65 @@ function streamOpenAICompletionsRequest(model, context, options, mode) {
|
|
|
3352
3294
|
onTimeout: getFirstStreamEventTimeoutHandler(options),
|
|
3353
3295
|
hint: "The provider may be stalled while parsing the tool payload; retry with a smaller tool surface or enable OPENCLAW_DEBUG_MODEL_PAYLOAD=tools to inspect exposed tools."
|
|
3354
3296
|
}), options?.signal);
|
|
3355
|
-
const buffered = contextOutputBudget === void 0 ? void 0 : await
|
|
3297
|
+
const buffered = contextOutputBudget === void 0 ? void 0 : await (async () => {
|
|
3298
|
+
const iterator = providerStream[Symbol.asyncIterator]();
|
|
3299
|
+
const chunks = [];
|
|
3300
|
+
let bufferedBytes = 0;
|
|
3301
|
+
let overflow;
|
|
3302
|
+
let finished = false;
|
|
3303
|
+
let failed = false;
|
|
3304
|
+
let sourceError;
|
|
3305
|
+
let finishReason;
|
|
3306
|
+
try {
|
|
3307
|
+
for (;;) {
|
|
3308
|
+
const next = await iterator.next();
|
|
3309
|
+
if (next.done) {
|
|
3310
|
+
finished = true;
|
|
3311
|
+
break;
|
|
3312
|
+
}
|
|
3313
|
+
const chunk = next.value;
|
|
3314
|
+
const chunkBytes = Buffer.byteLength(JSON.stringify(chunk) ?? "", "utf8");
|
|
3315
|
+
if (chunks.length >= MAX_CONTEXT_BUDGET_BUFFER_CHUNKS || bufferedBytes + chunkBytes > MAX_CONTEXT_BUDGET_BUFFER_BYTES) {
|
|
3316
|
+
overflow = next;
|
|
3317
|
+
break;
|
|
3318
|
+
}
|
|
3319
|
+
chunks.push(chunk);
|
|
3320
|
+
bufferedBytes += chunkBytes;
|
|
3321
|
+
const chunkFinishReason = chunk?.choices?.[0]?.finish_reason;
|
|
3322
|
+
if (chunkFinishReason) finishReason = chunkFinishReason;
|
|
3323
|
+
options?.signal?.throwIfAborted();
|
|
3324
|
+
}
|
|
3325
|
+
} catch (error) {
|
|
3326
|
+
failed = true;
|
|
3327
|
+
sourceError = error;
|
|
3328
|
+
iterator.return?.(void 0).catch(() => void 0);
|
|
3329
|
+
}
|
|
3330
|
+
return {
|
|
3331
|
+
bounded: overflow === void 0,
|
|
3332
|
+
failed,
|
|
3333
|
+
finishReason,
|
|
3334
|
+
stream: { async *[Symbol.asyncIterator]() {
|
|
3335
|
+
try {
|
|
3336
|
+
yield* chunks;
|
|
3337
|
+
if (failed) throw sourceError;
|
|
3338
|
+
if (overflow !== void 0) {
|
|
3339
|
+
yield overflow.value;
|
|
3340
|
+
for (;;) {
|
|
3341
|
+
const next = await iterator.next();
|
|
3342
|
+
if (next.done) {
|
|
3343
|
+
finished = true;
|
|
3344
|
+
return;
|
|
3345
|
+
}
|
|
3346
|
+
yield next.value;
|
|
3347
|
+
}
|
|
3348
|
+
}
|
|
3349
|
+
} finally {
|
|
3350
|
+
chunks.length = 0;
|
|
3351
|
+
if (!finished && !failed) iterator.return?.(void 0).catch(() => void 0);
|
|
3352
|
+
}
|
|
3353
|
+
} }
|
|
3354
|
+
};
|
|
3355
|
+
})();
|
|
3356
3356
|
discardCandidate = Boolean(buffered?.bounded && (buffered.failed || buffered.finishReason === "length"));
|
|
3357
3357
|
if (buffered && !discardCandidate) stream.push({
|
|
3358
3358
|
type: "start",
|
|
@@ -3394,11 +3394,6 @@ function streamOpenAICompletionsRequest(model, context, options, mode) {
|
|
|
3394
3394
|
error,
|
|
3395
3395
|
cleanup: () => {
|
|
3396
3396
|
finalizeOpenAICompletionsToolCalls(output, { allowSilentToolCallPromotion: false });
|
|
3397
|
-
if (mode === "direct") for (const block of output.content) {
|
|
3398
|
-
delete block.index;
|
|
3399
|
-
if (block.type === "toolCall") delete block.partialJson;
|
|
3400
|
-
delete block.streamIndex;
|
|
3401
|
-
}
|
|
3402
3397
|
}
|
|
3403
3398
|
});
|
|
3404
3399
|
} finally {
|
|
@@ -3407,62 +3402,5 @@ function streamOpenAICompletionsRequest(model, context, options, mode) {
|
|
|
3407
3402
|
})();
|
|
3408
3403
|
return eventStream;
|
|
3409
3404
|
}
|
|
3410
|
-
function createDirectCompletionsClient(model, context, apiKey, options, sessionId, compat) {
|
|
3411
|
-
if (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);
|
|
3412
|
-
const headers = { ...model.headers };
|
|
3413
|
-
if (model.provider === "github-copilot") Object.assign(headers, buildCopilotDynamicHeaders(context.messages));
|
|
3414
|
-
if (sessionId && compat.sessionAffinity !== "none") {
|
|
3415
|
-
if (compat.sessionAffinity === "openrouter") headers["x-session-id"] = sessionId;
|
|
3416
|
-
else {
|
|
3417
|
-
headers.session_id = sessionId;
|
|
3418
|
-
headers["x-client-request-id"] = sessionId;
|
|
3419
|
-
headers["x-session-affinity"] = sessionId;
|
|
3420
|
-
}
|
|
3421
|
-
}
|
|
3422
|
-
return createOpenAIProviderClient(model, apiKey, headers, resolveProviderSimpleCompletionHeaders(model, options), options?.onResponse);
|
|
3423
|
-
}
|
|
3424
|
-
function createManagedCompletionsClient(model, context, options, apiKey, cacheRetention) {
|
|
3425
|
-
const turnState = resolveProviderTransportTurnState(model, {
|
|
3426
|
-
sessionId: options?.sessionId,
|
|
3427
|
-
turnId: randomUUID(),
|
|
3428
|
-
attempt: 1,
|
|
3429
|
-
transport: "stream"
|
|
3430
|
-
});
|
|
3431
|
-
const optionHeaders = resolveOpencodeSessionHeaders(model, options);
|
|
3432
|
-
const turnHeaders = filterProviderTurnHeadersForExplicitOpencodeSession(model, options, turnState?.headers);
|
|
3433
|
-
const doneDetector = createSseDoneDetector();
|
|
3434
|
-
const baseFetch = withOpenAIErrorResponseHook(buildGuardedModelFetch(model, void 0, { onSseComment: () => notifyLlmRequestActivity(options?.signal, false) }), options?.onResponse, model);
|
|
3435
|
-
const doneDetectingFetch = async (url, init) => {
|
|
3436
|
-
const response = await baseFetch(url, init);
|
|
3437
|
-
if (!response.body || !response.ok) return response;
|
|
3438
|
-
if (typeof TransformStream === "undefined" || !response.body.pipeThrough) return response;
|
|
3439
|
-
const transformed = response.body.pipeThrough(new TransformStream({
|
|
3440
|
-
transform(chunk, controller) {
|
|
3441
|
-
doneDetector.observe(chunk);
|
|
3442
|
-
controller.enqueue(chunk);
|
|
3443
|
-
},
|
|
3444
|
-
flush() {
|
|
3445
|
-
doneDetector.finish();
|
|
3446
|
-
}
|
|
3447
|
-
}));
|
|
3448
|
-
return new Response(transformed, response);
|
|
3449
|
-
};
|
|
3450
|
-
const clientConfig = buildOpenAICompletionsClientConfig(model, buildOpenAIClientHeaders(model, context, {
|
|
3451
|
-
...turnHeaders,
|
|
3452
|
-
...optionHeaders
|
|
3453
|
-
}, void 0, resolvePromptCacheKey(options, cacheRetention), cacheRetention));
|
|
3454
|
-
return {
|
|
3455
|
-
client: new OpenAI({
|
|
3456
|
-
apiKey,
|
|
3457
|
-
baseURL: clientConfig.baseURL,
|
|
3458
|
-
dangerouslyAllowBrowser: true,
|
|
3459
|
-
defaultHeaders: clientConfig.defaultHeaders,
|
|
3460
|
-
defaultQuery: clientConfig.defaultQuery,
|
|
3461
|
-
fetch: doneDetectingFetch,
|
|
3462
|
-
...buildOpenAISdkClientOptions(model)
|
|
3463
|
-
}),
|
|
3464
|
-
sawStreamDONE: doneDetector.sawDone
|
|
3465
|
-
};
|
|
3466
|
-
}
|
|
3467
3405
|
//#endregion
|
|
3468
3406
|
export { hasResponsesWebSearchTool as a, flattenCompletionMessagesToStringContent as c, hasOpenAICompatibleConversationTurn as d, canonicalizeMaxTokensParam as f, createOpenAIResponsesTransportStreamFn as i, stripCompletionMessagesToRoleContent as l, createDeepSeekTextFilter as m, streamOpenAICompletionsRequest as n, buildOpenAICompletionsParams as o, resolveMaxTokensParam as p, createAzureOpenAIResponsesTransportStreamFn as r, convertMessages as s, createOpenAICompletionsTransportStreamFn as t, applyCompletionsAnthropicCacheControl as u };
|