@openclaw/ai 2026.11.5-beta.4 → 2026.11.10-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -3
- package/dist/{anthropic-c499kyoI.mjs → anthropic-CBz5v2U3.mjs} +16 -15
- package/dist/{anthropic-payload-policy-DVk38bnY.d.mts → anthropic-payload-policy-BTrHSS_v.d.mts} +4 -8
- package/dist/{anthropic-stream-lifecycle-KkyqdnjW.mjs → anthropic-stream-lifecycle-96vq-4V9.mjs} +154 -89
- package/dist/{anthropic-tool-projection-DcvsDiyX.mjs → anthropic-tool-projection-A9GceDnD.mjs} +4 -5
- package/dist/{anthropic-tool-projection-DKAlondV.d.mts → anthropic-tool-projection-DCOX8qai.d.mts} +1 -3
- package/dist/{api-registry-DY2MLUyg.d.mts → api-registry-DUEK-a3o.d.mts} +2 -4
- package/dist/{assistant-message-events-CHMJgbhs.mjs → assistant-message-events-DtSjIQmB.mjs} +1 -2
- package/dist/{assistant-output-C3czmoN4.mjs → assistant-output-kYOaiso5.mjs} +2 -3
- package/dist/{azure-openai-responses-client-compat-D0dvJMbZ.mjs → azure-deployment-map-hwDQc3uL.mjs} +2 -16
- package/dist/{azure-openai-responses-CyuUQ3JJ.mjs → azure-openai-responses-CZheDTt_.mjs} +12 -13
- package/dist/azure-openai-responses-client-compat-DLsS6V6z.mjs +13 -0
- package/dist/{base64-C8CdcsjU.mjs → base64-FdymvxN9.mjs} +1 -2
- package/dist/cloudflare-BCLfDuew.mjs +15 -0
- package/dist/{credential-redaction-DrgndwTJ.d.mts → credential-redaction-BNv5SWQz.d.mts} +0 -2
- package/dist/{deferred-event-buffer-tIGkTkTm.mjs → deferred-event-buffer-BgT1IIfq.mjs} +1 -2
- package/dist/{diagnostics-CloVGQiK.mjs → diagnostics-BNlb1zlT.mjs} +12 -19
- package/dist/{diagnostics-o1PrVNQb.mjs → diagnostics-DP1SXgAW.mjs} +1 -2
- package/dist/diagnostics.d.mts +6 -10
- package/dist/diagnostics.mjs +3 -3
- package/dist/{env-api-keys-BuHc86ya.mjs → env-api-keys-DlUbTgKq.mjs} +1 -2
- package/dist/{event-stream-BYmtRe8-.d.mts → event-stream-BJS9Q8G_.d.mts} +1 -3
- package/dist/{event-stream-X2gmsUWv.mjs → event-stream-Bf6cK7-d.mjs} +1 -2
- package/dist/event-stream-CPiqa8PI.d.mts +1 -0
- package/dist/event-stream.d.mts +2 -2
- package/dist/event-stream.mjs +1 -1
- package/dist/{expect-lbe3Hgrh.mjs → expect-DqyhV9d8.mjs} +1 -2
- package/dist/github-copilot-headers-CqLRrd-i.mjs +22 -0
- package/dist/{github-copilot-request-facts-BZ_EMo7X.mjs → github-copilot-request-facts-BxuLEdNF.mjs} +2 -3
- package/dist/{google-DqG05iBa.mjs → google-BUgkXPYL.mjs} +6 -7
- package/dist/{google-interactions-B_xZUObF.mjs → google-interactions-84f0xFly.mjs} +36 -25
- package/dist/{google-messages-p2iBzsAp.mjs → google-messages-Dip5zphv.mjs} +16 -20
- package/dist/{google-provider-stream-DZ6tqteU.mjs → google-provider-stream-COaKMdQv.mjs} +14 -15
- package/dist/{google-shared-BMYt1xSI.mjs → google-shared-Dooy5JJL.mjs} +11 -14
- package/dist/{google-vertex-CAq2q1Ln.mjs → google-vertex--S8AlXUD.mjs} +4 -5
- package/dist/{google-video-slots-Bxt-OXO8.mjs → google-video-slots-CzdrKzrO.mjs} +2 -3
- package/dist/{host-DqX-64Pb.mjs → host-Cf7zb-48.mjs} +73 -89
- package/dist/{host-ccbwPC3A.d.mts → host-Dgpzj407.d.mts} +3 -5
- package/dist/{host-policy-Bk85E9ue.mjs → host-policy-B1qzS7Xe.mjs} +2 -3
- package/dist/{index-Bczt0MnO.d.mts → index-BDF5kurq.d.mts} +10 -10
- package/dist/index.d.mts +8 -10
- package/dist/index.mjs +11 -11
- package/dist/internal/anthropic.d.mts +10 -21
- package/dist/internal/anthropic.mjs +6 -6
- package/dist/internal/google-model-family.d.mts +1 -3
- package/dist/internal/google-model-family.mjs +2 -3
- package/dist/internal/google.d.mts +3 -5
- package/dist/internal/google.mjs +1 -1
- package/dist/internal/model-request-body.d.mts +5 -5
- package/dist/internal/model-request-body.mjs +19 -6
- package/dist/internal/openai-completions-compat.d.mts +1 -3
- package/dist/internal/openai-completions-compat.mjs +2 -2
- package/dist/internal/openai-responses-payload-policy.d.mts +2 -4
- package/dist/internal/openai-responses-payload-policy.mjs +2 -2
- package/dist/internal/openai.d.mts +10 -32
- package/dist/internal/openai.mjs +12 -11
- package/dist/internal/reasoning-tag-text-partitioner.d.mts +0 -4
- package/dist/internal/reasoning-tag-text-partitioner.mjs +64 -125
- package/dist/internal/retry-after.d.mts +1 -1
- package/dist/internal/retry-after.mjs +1 -2
- package/dist/internal/runtime.d.mts +9 -43
- package/dist/internal/runtime.mjs +14 -15
- package/dist/internal/session-resources.d.mts +11 -0
- package/dist/{session-resources-vKvGIE3J.mjs → internal/session-resources.mjs} +2 -3
- package/dist/internal/shared.d.mts +17 -26
- package/dist/internal/shared.mjs +10 -10
- package/dist/internal/tool-schema.d.mts +2 -22
- package/dist/internal/tool-schema.mjs +3 -3
- package/dist/{llm-request-activity-DzaHoRAU.mjs → llm-request-activity-v1liRqNt.mjs} +1 -2
- package/dist/{mistral-DIGInqJI.mjs → mistral-BAps5cN2.mjs} +713 -299
- package/dist/{model-transport-url-BdksnBqu.d.mts → model-transport-url-Dad-sfx2.d.mts} +0 -4
- package/dist/{number-coercion-C7HsBgUL.mjs → number-coercion-BO6bhGm6.mjs} +2 -3
- package/dist/{observe-async-iterator-DgmegcZR.mjs → observe-async-iterator-DdOlbgrr.mjs} +1 -2
- package/dist/{observe-async-iterator-AlARO5wS.d.mts → observe-async-iterator-DeB_Vxes.d.mts} +14 -7
- package/dist/openai-BtJTmLWF.mjs +21460 -0
- package/dist/{openai-chatgpt-jwt-KWcgd0d_.mjs → openai-chatgpt-jwt-v5F5jJmX.mjs} +1 -2
- package/dist/{openai-chatgpt-responses-B-MopEDG.mjs → openai-chatgpt-responses-CYXMKG89.mjs} +55 -56
- package/dist/{openai-completions-B62Yg3hQ.mjs → openai-completions-Bi4Ghg3V.mjs} +6 -7
- package/dist/{openai-completions-compat-CJ-NsDzg.d.mts → openai-completions-compat-BJBQ682M.d.mts} +10 -5
- package/dist/{openai-completions-compat-CS3dlDBR.mjs → openai-completions-compat-DZLGotNt.mjs} +19 -16
- package/dist/{openai-completions-reasoning-replay-BwT1xwRI.mjs → openai-completions-reasoning-replay-DyH5XzNo.mjs} +1 -2
- package/dist/{openai-completions-transport-BQ8dr3FV.mjs → openai-completions-transport-otONaRhv.mjs} +161 -535
- package/dist/{openai-prompt-cache-BZGaIWYh.d.mts → openai-prompt-cache-C5rwtmA_.d.mts} +2 -4
- package/dist/{openai-prompt-cache-3H_Fz0ya.mjs → openai-prompt-cache-CJv1bvw0.mjs} +3 -5
- package/dist/openai-provider-client-apBsWo9b.mjs +51 -0
- package/dist/{openai-responses-VUkMi_Bc.mjs → openai-responses-CiIAm8fJ.mjs} +14 -15
- package/dist/{openai-responses-compaction-replay-DXF5BjD2.d.mts → openai-responses-compaction-replay-CUw4owu9.d.mts} +6 -7
- package/dist/{openai-responses-contracts-Cb1IIRRG.d.mts → openai-responses-contracts-bYtvXSvv.d.mts} +7 -12
- package/dist/{openai-responses-contracts-xU-n9AJJ.mjs → openai-responses-contracts-eppTI5DQ.mjs} +11 -18
- package/dist/{openai-responses-endpoint-CqO3ejTe.mjs → openai-responses-endpoint-AeVu3HmP.mjs} +80 -34
- package/dist/{openai-responses-payload-policy-BsQaD-gD.d.mts → openai-responses-payload-policy-Cihgy9fC.d.mts} +0 -2
- package/dist/{openai-responses-request-lifecycle-DNITxJPO.mjs → openai-responses-request-lifecycle-DfE4xNHj.mjs} +120 -20
- package/dist/{openai-responses-shared-WMDQDwC6.mjs → openai-responses-shared-BAJzOqwt.mjs} +1651 -322
- package/dist/{openai-responses-terminal-usage-D7IhRA6i.d.mts → openai-responses-terminal-usage-BYXQTt9u.d.mts} +2 -4
- package/dist/openai-responses-websocket-DywDiO81.mjs +8143 -0
- package/dist/{openai-stop-reason-8s70vDXj.mjs → openai-stop-reason-cA0GUHlU.mjs} +4 -3
- package/dist/{openai-tool-schema-CvxySRyf.mjs → openai-tool-schema-Ca74_fkR.mjs} +17 -26
- package/dist/openai.LICENSE +201 -0
- package/dist/{otel-B2u5HGvm.mjs → otel-C5Cn7IFQ.mjs} +8 -8
- package/dist/{overflow-CpApyjG2.mjs → overflow-CM0yZomw.mjs} +2 -3
- package/dist/{positive-integer-DiqE5vNi.mjs → positive-integer-AM4ltyhP.mjs} +2 -3
- package/dist/{prompt-cache-stability-w-ICeyOI.mjs → prompt-cache-stability-oTx0nIsh.mjs} +3 -4
- package/dist/{prompt-cache-stability-Cwcjv_fx.d.mts → prompt-cache-stability-xNfkD-3g.d.mts} +0 -2
- package/dist/{provider-error-DD-fo4Rz.mjs → provider-error-B7aKA_dg.mjs} +24 -23
- package/dist/{provider-error-CnaWYTRY.d.mts → provider-error-DZMru0Jv.d.mts} +0 -2
- package/dist/{provider-options-BQ2Msop2.d.mts → provider-options-CR_UfgUE.d.mts} +15 -11
- package/dist/{provider-replay-context-5gFUstgv.mjs → provider-replay-context-CHJQzB0n.mjs} +5 -7
- package/dist/{provider-transcript-transform-Hr1kCoMX.mjs → provider-transcript-transform-C-WfgiLJ.mjs} +2 -3
- package/dist/{provider-transport-turn-state-d1uIBP1i.mjs → provider-transport-turn-state-BdMA1v46.mjs} +4 -27
- package/dist/{provider-types-B1e98js5.d.mts → provider-types-CfiTmXyw.d.mts} +3 -5
- package/dist/provider-types.d.mts +7 -7
- package/dist/provider-types.mjs +1 -2
- package/dist/providers.d.mts +2 -4
- package/dist/providers.mjs +14 -15
- package/dist/{record-coerce-BQaoiN3r.mjs → record-coerce-BgUo6bj4.mjs} +1 -2
- package/dist/{request-headers-DO4Mqhw1.mjs → request-headers-DJ4QrMC_.mjs} +1 -2
- package/dist/{required-api-key-2zZTkmsi.mjs → required-api-key-BniLGxy4.mjs} +2 -3
- package/dist/{retry-after-DnHBlFS2.d.mts → retry-after-f3ZIm8TA.d.mts} +0 -2
- package/dist/rolldown-runtime-DYf_mQCB.mjs +34 -0
- package/dist/{sanitize-unicode-CRGuMONI.mjs → sanitize-unicode-B3kUqQ-q.mjs} +1 -2
- package/dist/{sanitize-unicode-BISmUlUv.d.mts → sanitize-unicode-DlVtgmsw.d.mts} +2 -6
- package/dist/{session-affinity-DA4WHv1h.mjs → session-affinity-Czm9tjAm.mjs} +1 -2
- package/dist/{simple-options-CQNPKCEb.mjs → simple-options-D8CTqHvk.mjs} +40 -16
- package/dist/src-CNWvILd1.mjs +2 -0
- package/dist/{src-CQ7nH2mL.mjs → src-CmBmaGOV.mjs} +87 -20
- package/dist/{stable-stringify-CchQEmeA.mjs → stable-stringify-CGB-o900.mjs} +10 -8
- package/dist/{stream-DM-q0y5H.mjs → stream-BEE5qy7Z.mjs} +5 -7
- package/dist/{stream-first-event-timeout-B7RcufAV.mjs → stream-first-event-timeout-CWiv_y--.mjs} +2 -3
- package/dist/{streaming-byte-guard-DBXr1XYn.mjs → streaming-byte-guard-gOcUrHJF.mjs} +1 -2
- package/dist/{string-coerce-BCuWMIrk.mjs → string-coerce-CpcyRbc6.mjs} +1 -2
- package/dist/{string-normalization-B8TDDBX_.mjs → string-normalization-CS77PHD3.mjs} +2 -3
- package/dist/{telemetry-DJibfNKZ.mjs → telemetry-Cd4i-clM.mjs} +6 -8
- package/dist/{tool-schema-json-projection-BSHb4gaJ.mjs → tool-schema-json-projection-C13fPskA.mjs} +11 -16
- package/dist/{transport-stream-shared-CBVh6QEc.mjs → transport-stream-shared-DEpLe9fG.mjs} +24 -30
- package/dist/{transport-stream-shared-D3IAU4jn.d.mts → transport-stream-shared-DW4DoJLv.d.mts} +7 -8
- package/dist/{transport-utils-rxOHnq9y.mjs → transport-utils-Cx9L80PZ.mjs} +6 -8
- package/dist/transports.d.mts +29 -83
- package/dist/transports.mjs +39 -38
- package/dist/{types-BVdTf0YV.d.mts → types-BNp71XKW.d.mts} +11 -6
- package/dist/types-CwcLeW-7.d.mts +1 -0
- package/dist/{types-OVEWUaDh.mjs → types-DIBUKaTM.mjs} +1 -2
- package/dist/types.d.mts +7 -7
- package/dist/types.mjs +9 -9
- package/dist/{usage-CJH5D6Ea.mjs → usage-B8ggJtuG.mjs} +1 -2
- package/dist/{validation-QmyD0E5A.d.mts → validation-BFNWNeUl.d.mts} +1 -3
- package/dist/{validation-DGXqfvkj.mjs → validation-BO7nCOKO.mjs} +5 -8
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/dist/ws.LICENSE +20 -0
- package/dist/x509-transport-state-D4gFbgWG.mjs +40 -0
- package/package.json +13 -7
- package/dist/.source-module-urls/fe058cc430242ce2ab0dfbcbe153e240a52cf9c3072c3dc0a73e5f956b6ba49b.json +0 -1
- package/dist/cloudflare-BJ2_Xabx.mjs +0 -39
- package/dist/event-stream-B4ZcSvsu.d.mts +0 -1
- package/dist/rolldown-runtime-D7D4PA-g.mjs +0 -13
- package/dist/src-BUsVkrNt.mjs +0 -105
- package/dist/types-Cb3-5WM9.d.mts +0 -1
|
@@ -1,41 +1,38 @@
|
|
|
1
|
-
import "./src-
|
|
2
|
-
import { m as isRuntimeContextMessage, p as hasRuntimeContextMarker, v as runtimeContextContentToText } from "./types-
|
|
3
|
-
import { o as
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { l as readStringValue, o as normalizeOptionalString, r as normalizeLowercaseStringOrEmpty, s as normalizeStringifiedOptionalString } from "./string-coerce-
|
|
7
|
-
import { t as asFiniteNumber } from "./number-coercion-
|
|
8
|
-
import { t as observeAsyncIterator } from "./observe-async-iterator-
|
|
9
|
-
import { A as
|
|
10
|
-
import { A as resolveOpenAIReasoningEffortMapping, D as normalizeOpenAIReasoningEffort, F as MODEL_CATALOG_THINKING_LEVELS, M as supportsOpenAIReasoningEffort, N as supportsOpenAITemperature, O as resolveOpenAIModelReasoningEfforts, P as resolveOpenAIReasoningEffortMap, R as resolveOpenAIThinkingApi, a as OPENAI_RESPONSES_COMPACTION_REPLAY_TYPE, b as isResponsesServiceTierRejection, c as OPENAI_RESPONSES_RETAINED_COMPACTION_REPLAY_TYPE, g as isResponsesTerminalEventType, h as isPreviousResponseRejection, i as OPENAI_RESPONSES_APIS, k as resolveOpenAIReasoningEffortForModel, l as OPENAI_RESPONSES_TOOL_CALL_PROVIDERS, m as RESPONSE_FAILED_NO_DETAILS_MESSAGE, o as OPENAI_RESPONSES_REASONING_REPLAY_BLOCK_META_KEY, p as RESPONSES_RETAINED_USER, s as OPENAI_RESPONSES_REASONING_REPLAY_META_KEY, x as nextResponsesServiceTier, y as responsesServiceTierObserver } from "./openai-responses-contracts-
|
|
11
|
-
import {
|
|
12
|
-
import { r as readTransportDiagnosticLabel } from "./provider-error-
|
|
13
|
-
import "./
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import { n as
|
|
17
|
-
import
|
|
18
|
-
import { a as resolveOpenAICompletionsCompat, n as isKnownOpenAIEndpoint, s as usesNativeOpenAICodexResponsesBackend, u as resolveOpenAIResponsesTextFormat } from "./openai-completions-compat-
|
|
19
|
-
import { r as resolveModelRequestTimeoutMs } from "./host-policy-
|
|
20
|
-
import { r as sortPromptCacheToolsByName } from "./prompt-cache-stability-
|
|
21
|
-
import { a as describeToolResultMediaPlaceholder, c as extractToolResultText, f as preparedRequestSuffix, r as clampMaxTokensToModel, s as extractToolResultBlockText, u as codeModeToolSurfaceObserver
|
|
22
|
-
import {
|
|
23
|
-
import { C as sha256Hex, S as redactIdentifier, n as prepareRuntimeToolInputSchema, r as projectRuntimeToolInputSchema, w as sha256StableValue } from "./tool-schema-json-projection-
|
|
24
|
-
import { t as notifyLlmRequestActivity } from "./llm-request-activity-
|
|
25
|
-
import { n as isProviderReplayContext, r as providerReplayContextMatches, t as buildProviderReplayContext } from "./provider-replay-context-
|
|
26
|
-
import { t as transformProviderMessages } from "./provider-transcript-transform-
|
|
1
|
+
import "./src-CmBmaGOV.mjs";
|
|
2
|
+
import { m as isRuntimeContextMessage, p as hasRuntimeContextMarker, v as runtimeContextContentToText } from "./types-DIBUKaTM.mjs";
|
|
3
|
+
import { i as asOptionalRecord, o as isRecord, s as isStringArray } from "./record-coerce-BgUo6bj4.mjs";
|
|
4
|
+
import { o as readProviderRefusalReview, t as appendAssistantMessageDiagnostic } from "./diagnostics-DP1SXgAW.mjs";
|
|
5
|
+
import { r as appendAssistantThinking } from "./event-stream-Bf6cK7-d.mjs";
|
|
6
|
+
import { l as readStringValue, o as normalizeOptionalString, r as normalizeLowercaseStringOrEmpty, s as normalizeStringifiedOptionalString } from "./string-coerce-CpcyRbc6.mjs";
|
|
7
|
+
import { t as asFiniteNumber } from "./number-coercion-BO6bhGm6.mjs";
|
|
8
|
+
import { t as observeAsyncIterator } from "./observe-async-iterator-DdOlbgrr.mjs";
|
|
9
|
+
import { A as headersToRecord, L as isImageWithMediaPayload, M as calculateCost, N as clampThinkingLevel, a as resolveAiTransportHeaderSentinels, j as applyProviderReportedUsageCost, m as resolveFailedAssistantReplay, r as getAiTransportHost } from "./host-Cf7zb-48.mjs";
|
|
10
|
+
import { A as resolveOpenAIReasoningEffortMapping, D as normalizeOpenAIReasoningEffort, F as MODEL_CATALOG_THINKING_LEVELS, M as supportsOpenAIReasoningEffort, N as supportsOpenAITemperature, O as resolveOpenAIModelReasoningEfforts, P as resolveOpenAIReasoningEffortMap, R as resolveOpenAIThinkingApi, a as OPENAI_RESPONSES_COMPACTION_REPLAY_TYPE, b as isResponsesServiceTierRejection, c as OPENAI_RESPONSES_RETAINED_COMPACTION_REPLAY_TYPE, g as isResponsesTerminalEventType, h as isPreviousResponseRejection, i as OPENAI_RESPONSES_APIS, k as resolveOpenAIReasoningEffortForModel, l as OPENAI_RESPONSES_TOOL_CALL_PROVIDERS, m as RESPONSE_FAILED_NO_DETAILS_MESSAGE, o as OPENAI_RESPONSES_REASONING_REPLAY_BLOCK_META_KEY, p as RESPONSES_RETAINED_USER, s as OPENAI_RESPONSES_REASONING_REPLAY_META_KEY, x as nextResponsesServiceTier, y as responsesServiceTierObserver } from "./openai-responses-contracts-eppTI5DQ.mjs";
|
|
11
|
+
import { getSessionResourceOwnerId, registerSessionResourceCleanup } from "./internal/session-resources.mjs";
|
|
12
|
+
import { r as readTransportDiagnosticLabel } from "./provider-error-B7aKA_dg.mjs";
|
|
13
|
+
import { n as clampOpenAIPromptCacheKey } from "./openai-prompt-cache-CJv1bvw0.mjs";
|
|
14
|
+
import { a as resolveModelPayloadDebugMode, b as resolveResponsesTerminalStopReason, d as ResponsesOutputIdentityError, f as countToolCallTrailingWhitespace, g as applyResponsesCacheWritePricing, i as emitModelTransportError, m as isResponsesProviderTool, p as hasOnlyResponsesFunctionTools, r as emitModelTransportDebug, v as mapResponsesTerminalUsage, y as readResponsesReasoningTokens } from "./diagnostics-BNlb1zlT.mjs";
|
|
15
|
+
import { n as isCodeModeModelVisibleToolName } from "./transport-utils-Cx9L80PZ.mjs";
|
|
16
|
+
import { n as writeStableStringify, t as stableStringify } from "./stable-stringify-CGB-o900.mjs";
|
|
17
|
+
import "./src-CNWvILd1.mjs";
|
|
18
|
+
import { a as resolveOpenAICompletionsCompat, n as isKnownOpenAIEndpoint, s as usesNativeOpenAICodexResponsesBackend, u as resolveOpenAIResponsesTextFormat } from "./openai-completions-compat-DZLGotNt.mjs";
|
|
19
|
+
import { r as resolveModelRequestTimeoutMs } from "./host-policy-B1qzS7Xe.mjs";
|
|
20
|
+
import { r as sortPromptCacheToolsByName } from "./prompt-cache-stability-oTx0nIsh.mjs";
|
|
21
|
+
import { a as describeToolResultMediaPlaceholder, b as prepareSystemPrompt, c as extractToolResultText, f as preparedRequestSuffix, r as clampMaxTokensToModel, s as extractToolResultBlockText, u as codeModeToolSurfaceObserver } from "./simple-options-D8CTqHvk.mjs";
|
|
22
|
+
import { O as shortHash, S as transportAbortError, T as parseJsonObjectPreservingUnsafeIntegers, b as sanitizeTransportPayloadText, c as decodeSseFrames, d as finalizeTransportStream, f as iterateModelStream, g as notifyProviderHttpResponse, j as parseStreamingJson, k as createToolArgumentPreviewSchedule, l as failTransportStream, r as awaitProviderLifecycleCallback, t as IncompleteToolCallError, v as parseTerminalToolCallArguments, w as withProviderResponseHook } from "./transport-stream-shared-DEpLe9fG.mjs";
|
|
23
|
+
import { C as sha256Hex, S as redactIdentifier, n as prepareRuntimeToolInputSchema, r as projectRuntimeToolInputSchema, w as sha256StableValue } from "./tool-schema-json-projection-C13fPskA.mjs";
|
|
24
|
+
import { t as notifyLlmRequestActivity } from "./llm-request-activity-v1liRqNt.mjs";
|
|
25
|
+
import { n as isProviderReplayContext, r as providerReplayContextMatches, t as buildProviderReplayContext } from "./provider-replay-context-CHJQzB0n.mjs";
|
|
26
|
+
import { t as transformProviderMessages } from "./provider-transcript-transform-C-WfgiLJ.mjs";
|
|
27
27
|
import { prepareModelRequestBody } from "./internal/model-request-body.mjs";
|
|
28
|
-
import "./assistant-output-
|
|
29
|
-
import { n as resolveOpencodeSessionHeaders } from "./session-affinity-
|
|
30
|
-
import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "./stream-first-event-timeout-
|
|
31
|
-
import { a as resolveOpenAIProjectedToolsStrictToolFlag, m as withPreparedToolSchemaNormalization, r as normalizeOpenAIStrictToolParameters, t as findOpenAIStrictToolProjectionDiagnostics, x as prepareOpenAIFunctionTool } from "./openai-tool-schema-
|
|
32
|
-
import { a as
|
|
33
|
-
import { randomUUID } from "node:crypto";
|
|
34
|
-
import { isDeepStrictEqual } from "node:util";
|
|
28
|
+
import "./assistant-output-kYOaiso5.mjs";
|
|
29
|
+
import { n as resolveOpencodeSessionHeaders } from "./session-affinity-Czm9tjAm.mjs";
|
|
30
|
+
import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "./stream-first-event-timeout-CWiv_y--.mjs";
|
|
31
|
+
import { a as resolveOpenAIProjectedToolsStrictToolFlag, m as withPreparedToolSchemaNormalization, r as normalizeOpenAIStrictToolParameters, t as findOpenAIStrictToolProjectionDiagnostics, x as prepareOpenAIFunctionTool } from "./openai-tool-schema-Ca74_fkR.mjs";
|
|
32
|
+
import { a as getResponsesCompactionInputIdentity, c as readOpenAIResponsesCompactionWindow, d as isSanitizedFrozenResponsesInput, f as sanitizeResponsesImageInput, l as tagResponsesCompactionInput, n as supportsNativeOpenAIResponsesEndpoint, o as isOpenAIResponsesCompactionOutput, s as publishResponsesCompactionInput, u as buildResponsesInputImage } from "./openai-responses-endpoint-AeVu3HmP.mjs";
|
|
33
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
35
34
|
import { isProxy } from "node:util/types";
|
|
36
|
-
|
|
37
|
-
import { Stream } from "openai/core/streaming";
|
|
38
|
-
//#region packages/ai/src/transports/openai-transport-shared.ts
|
|
35
|
+
// packages/ai/src/transports/openai-transport-shared.ts
|
|
39
36
|
const OPENAI_RESPONSE_MODEL_HEADER_NAMES = /* @__PURE__ */ new Set(["openai-model", "x-openai-model"]);
|
|
40
37
|
const OPENAI_RESPONSE_MODEL_EVENT_TYPES = /* @__PURE__ */ new Set([
|
|
41
38
|
"response.created",
|
|
@@ -161,13 +158,14 @@ function readOpenAICompletionsReasoningBatch(delta, visibleReasoningDetailTypes)
|
|
|
161
158
|
const reasoningDetails = delta.reasoning_details;
|
|
162
159
|
if (Array.isArray(reasoningDetails)) for (const detail of reasoningDetails) {
|
|
163
160
|
if (!isRecord(detail)) continue;
|
|
164
|
-
|
|
165
|
-
if (
|
|
161
|
+
const detailText = detail.type === "reasoning.summary" ? detail.summary : detail.text;
|
|
162
|
+
if (typeof detailText !== "string" || !detailText) continue;
|
|
163
|
+
if (detail.type === "reasoning.text" || detail.type === "reasoning.summary") {
|
|
166
164
|
deltas ??= [];
|
|
167
165
|
appendOpenAICompletionsReasoningDelta(deltas, mirroredThinking, {
|
|
168
166
|
kind: "thinking",
|
|
169
167
|
signature: "reasoning_details",
|
|
170
|
-
text:
|
|
168
|
+
text: detailText
|
|
171
169
|
});
|
|
172
170
|
continue;
|
|
173
171
|
}
|
|
@@ -175,7 +173,7 @@ function readOpenAICompletionsReasoningBatch(delta, visibleReasoningDetailTypes)
|
|
|
175
173
|
deltas ??= [];
|
|
176
174
|
appendOpenAICompletionsReasoningDelta(deltas, mirroredThinking, {
|
|
177
175
|
kind: "text",
|
|
178
|
-
text:
|
|
176
|
+
text: detailText,
|
|
179
177
|
source: "reasoning_detail"
|
|
180
178
|
});
|
|
181
179
|
}
|
|
@@ -351,8 +349,7 @@ function readOpenAICompletionsContentPartDeltas(content) {
|
|
|
351
349
|
}];
|
|
352
350
|
return [];
|
|
353
351
|
}
|
|
354
|
-
|
|
355
|
-
//#region packages/ai/src/providers/openai-tool-projection.ts
|
|
352
|
+
// packages/ai/src/providers/openai-tool-projection.ts
|
|
356
353
|
function unreadableToolDiagnostic(toolIndex) {
|
|
357
354
|
return {
|
|
358
355
|
toolIndex,
|
|
@@ -532,8 +529,7 @@ function toOpenAIResponsesToolChoice(choice) {
|
|
|
532
529
|
} : tool)
|
|
533
530
|
};
|
|
534
531
|
}
|
|
535
|
-
|
|
536
|
-
//#region packages/ai/src/providers/openai-request-reasoning.ts
|
|
532
|
+
// packages/ai/src/providers/openai-request-reasoning.ts
|
|
537
533
|
/** Preserve explicit off until the selected route maps it to its native value. */
|
|
538
534
|
function resolveOpenAISimpleReasoningEffort(model, reasoning) {
|
|
539
535
|
return reasoning === void 0 ? void 0 : clampThinkingLevel(model, reasoning);
|
|
@@ -560,8 +556,7 @@ function resolveOpenAIRequestReasoning(model, reasoning) {
|
|
|
560
556
|
thinkingEnabled: intent === void 0 ? void 0 : model.reasoning && normalizedIntent !== "off" && normalizedIntent !== "none"
|
|
561
557
|
};
|
|
562
558
|
}
|
|
563
|
-
|
|
564
|
-
//#region packages/ai/src/transports/openai-transport-params.ts
|
|
559
|
+
// packages/ai/src/transports/openai-transport-params.ts
|
|
565
560
|
const MAX_OPENAI_STRICT_TOOL_DOWNGRADE_DIAGNOSTIC_KEYS = 256;
|
|
566
561
|
const loggedOpenAIStrictToolDowngradeDiagnosticKeys = /* @__PURE__ */ new Set();
|
|
567
562
|
const OPENAI_COMPLETIONS_APIS = /* @__PURE__ */ new Set(["openai-completions", "openclaw-openai-completions-transport"]);
|
|
@@ -765,8 +760,7 @@ function getCompat(model) {
|
|
|
765
760
|
strictMessageKeys: compat.strictMessageKeys === true
|
|
766
761
|
};
|
|
767
762
|
}
|
|
768
|
-
|
|
769
|
-
//#region packages/ai/src/transports/openai-responses-compaction-replay.ts
|
|
763
|
+
// packages/ai/src/transports/openai-responses-compaction-replay.ts
|
|
770
764
|
const OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE = "openai-responses-compaction-suppression";
|
|
771
765
|
const OPENAI_RESPONSES_COMPACTION_SUPPRESSION_DATA = "rejected";
|
|
772
766
|
function isOpenAIResponsesCompactionState(state) {
|
|
@@ -778,6 +772,10 @@ function isOpenAIResponsesCompactionState(state) {
|
|
|
778
772
|
function readOpenAIResponsesCompactionReplayState(value) {
|
|
779
773
|
return isRecord(value) && isProviderReplayContext(value) && isOpenAIResponsesCompactionState(value) ? value : void 0;
|
|
780
774
|
}
|
|
775
|
+
function readOpenAIResponsesItemRecoveryAnchor(replay) {
|
|
776
|
+
const state = readOpenAIResponsesCompactionReplayState(replay);
|
|
777
|
+
return state?.type === OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE && typeof state.itemRecovery === "string" ? state.itemRecovery : void 0;
|
|
778
|
+
}
|
|
781
779
|
function captureOpenAIResponsesCompaction(output, item, boundary, model, captureMetadata, compactedOutput, outputTokens) {
|
|
782
780
|
const metadata = captureMetadata ?? buildOpenAIResponsesReasoningReplayMetadata(model);
|
|
783
781
|
if (!item.encrypted_content) return;
|
|
@@ -801,7 +799,6 @@ function captureOpenAIResponsesCompaction(output, item, boundary, model, capture
|
|
|
801
799
|
model: metadata.model,
|
|
802
800
|
baseUrlHash: metadata.baseUrlHash,
|
|
803
801
|
...metadata.sessionHash ? { sessionHash: metadata.sessionHash } : {},
|
|
804
|
-
...metadata.authProfileHash ? { authProfileHash: metadata.authProfileHash } : {},
|
|
805
802
|
...compactedOutput ? { compactedWindow: {
|
|
806
803
|
state: "ready",
|
|
807
804
|
output: JSON.stringify(compactedOutput),
|
|
@@ -811,7 +808,7 @@ function captureOpenAIResponsesCompaction(output, item, boundary, model, capture
|
|
|
811
808
|
if (compactedOutput && !readOpenAIResponsesCompactionWindow(replay, model)) throw new Error("Responses compact endpoint checkpoint is invalid or exceeds 16 MiB");
|
|
812
809
|
output.providerReplay = replay;
|
|
813
810
|
}
|
|
814
|
-
function suppressOpenAIResponsesCompaction(output, model, options, rejectedCheckpoint) {
|
|
811
|
+
function suppressOpenAIResponsesCompaction(output, model, options, rejectedCheckpoint, itemRecovery) {
|
|
815
812
|
const context = buildProviderReplayContext(model, options);
|
|
816
813
|
if (!context.baseUrlHash) return;
|
|
817
814
|
output.providerReplay = {
|
|
@@ -819,7 +816,8 @@ function suppressOpenAIResponsesCompaction(output, model, options, rejectedCheck
|
|
|
819
816
|
type: OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE,
|
|
820
817
|
data: OPENAI_RESPONSES_COMPACTION_SUPPRESSION_DATA,
|
|
821
818
|
...context,
|
|
822
|
-
baseUrlHash: context.baseUrlHash
|
|
819
|
+
baseUrlHash: context.baseUrlHash,
|
|
820
|
+
...itemRecovery ? { itemRecovery } : {}
|
|
823
821
|
};
|
|
824
822
|
if (rejectedCheckpoint) options?.onCompactionRejected?.(rejectedCheckpoint);
|
|
825
823
|
}
|
|
@@ -850,7 +848,14 @@ function resolveNewestOpenAIResponsesCompactionReplay(messages, model, options)
|
|
|
850
848
|
if (message?.role !== "assistant") continue;
|
|
851
849
|
const replay = readOpenAIResponsesCompactionReplayState(message.providerReplay);
|
|
852
850
|
if (replay?.type === OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE) {
|
|
853
|
-
if (providerReplayContextMatches(replay,
|
|
851
|
+
if (providerReplayContextMatches(replay, typeof replay.itemRecovery === "string" ? {
|
|
852
|
+
...context,
|
|
853
|
+
sessionHash: replay.sessionHash
|
|
854
|
+
} : context)) return typeof replay.itemRecovery === "string" ? {
|
|
855
|
+
owner: message,
|
|
856
|
+
mode: "item-recovery",
|
|
857
|
+
anchor: replay.itemRecovery
|
|
858
|
+
} : void 0;
|
|
854
859
|
continue;
|
|
855
860
|
}
|
|
856
861
|
if (replay?.type !== "openai-responses-compaction" && replay?.type !== "openai-responses-retained-compaction") {
|
|
@@ -859,7 +864,7 @@ function resolveNewestOpenAIResponsesCompactionReplay(messages, model, options)
|
|
|
859
864
|
}
|
|
860
865
|
if (!providerReplayContextMatches(replay, context)) return;
|
|
861
866
|
if (replay.compactedWindow !== void 0 || replay.type === "openai-responses-retained-compaction") {
|
|
862
|
-
const output = readOpenAIResponsesCompactionWindow(replay, model);
|
|
867
|
+
const output = readOpenAIResponsesCompactionWindow(replay, model, getAiTransportHost().immutableData);
|
|
863
868
|
const item = output?.at(-1);
|
|
864
869
|
if (!output || item?.type !== "compaction") return {
|
|
865
870
|
owner: message,
|
|
@@ -874,13 +879,15 @@ function resolveNewestOpenAIResponsesCompactionReplay(messages, model, options)
|
|
|
874
879
|
replayIndex: replay.type === "openai-responses-retained-compaction" ? message.content.length : replay.replayIndex ?? 0
|
|
875
880
|
};
|
|
876
881
|
}
|
|
882
|
+
const item = {
|
|
883
|
+
type: "compaction",
|
|
884
|
+
...isSafeResponsesReplayItemId(replay.id) ? { id: replay.id } : {},
|
|
885
|
+
encrypted_content: replay.data
|
|
886
|
+
};
|
|
887
|
+
publishResponsesCompactionInput(replay, [item], getAiTransportHost().immutableData);
|
|
877
888
|
return {
|
|
878
889
|
owner: message,
|
|
879
|
-
item
|
|
880
|
-
type: "compaction",
|
|
881
|
-
...isSafeResponsesReplayItemId(replay.id) ? { id: replay.id } : {},
|
|
882
|
-
encrypted_content: replay.data
|
|
883
|
-
},
|
|
890
|
+
item,
|
|
884
891
|
mode: "compacted-prefix",
|
|
885
892
|
replayIndex: replay.replayIndex ?? 0
|
|
886
893
|
};
|
|
@@ -893,15 +900,44 @@ var CompactionReplayRefreshRequiredError = class extends Error {
|
|
|
893
900
|
}
|
|
894
901
|
};
|
|
895
902
|
function buildOpenAIResponsesCompactionReplayPlan(messages, model, options) {
|
|
896
|
-
if (options?.mode === "
|
|
903
|
+
if (typeof options?.mode === "object") return {
|
|
897
904
|
messages,
|
|
898
|
-
preserveUnframedToolResults: false
|
|
905
|
+
preserveUnframedToolResults: false,
|
|
906
|
+
itemRecovery: { anchor: options.mode.itemRecovery }
|
|
899
907
|
};
|
|
900
908
|
const compaction = resolveNewestOpenAIResponsesCompactionReplay(messages, model, options);
|
|
901
909
|
if (!compaction) return {
|
|
902
910
|
messages,
|
|
903
911
|
preserveUnframedToolResults: false
|
|
904
912
|
};
|
|
913
|
+
if (compaction.mode === "item-recovery") {
|
|
914
|
+
const owner = compaction.owner;
|
|
915
|
+
let replayMessages = messages;
|
|
916
|
+
if (resolveFailedAssistantReplay(owner, { pairingAware: false }) === "drop") {
|
|
917
|
+
const boundary = {
|
|
918
|
+
role: "assistant",
|
|
919
|
+
content: [],
|
|
920
|
+
stopReason: "stop",
|
|
921
|
+
api: owner.api,
|
|
922
|
+
provider: owner.provider,
|
|
923
|
+
model: owner.model,
|
|
924
|
+
usage: owner.usage,
|
|
925
|
+
timestamp: owner.timestamp,
|
|
926
|
+
providerReplay: owner.providerReplay
|
|
927
|
+
};
|
|
928
|
+
replayMessages = [...messages];
|
|
929
|
+
replayMessages.splice(messages.indexOf(owner), 0, boundary);
|
|
930
|
+
}
|
|
931
|
+
return {
|
|
932
|
+
messages: replayMessages,
|
|
933
|
+
preserveUnframedToolResults: false,
|
|
934
|
+
itemRecovery: { anchor: compaction.anchor }
|
|
935
|
+
};
|
|
936
|
+
}
|
|
937
|
+
if (options?.mode === "full-history") return {
|
|
938
|
+
messages,
|
|
939
|
+
preserveUnframedToolResults: false
|
|
940
|
+
};
|
|
905
941
|
if (compaction.mode === "refresh-required") throw new CompactionReplayRefreshRequiredError();
|
|
906
942
|
const ownerIndex = messages.indexOf(compaction.owner);
|
|
907
943
|
return {
|
|
@@ -920,8 +956,72 @@ function buildOpenAIResponsesReasoningReplayMetadata(model, options) {
|
|
|
920
956
|
...buildProviderReplayContext(model, options)
|
|
921
957
|
};
|
|
922
958
|
}
|
|
923
|
-
|
|
924
|
-
|
|
959
|
+
// packages/ai/src/transports/openai-responses-json-projection.ts
|
|
960
|
+
const frozenJsonProjections = /* @__PURE__ */ new WeakMap();
|
|
961
|
+
function projectJsonValue(value, key, ancestors) {
|
|
962
|
+
if (typeof value === "number") return Number.isFinite(value) ? value + 0 : null;
|
|
963
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
964
|
+
if (value === void 0 || typeof value === "symbol") return;
|
|
965
|
+
if (typeof value !== "object" || isProxy(value) || Object.getPrototypeOf(value) !== (Array.isArray(value) ? Array.prototype : Object.prototype) || "toJSON" in value || ancestors.has(value)) {
|
|
966
|
+
for (const ancestor of ancestors.keys()) ancestors.set(ancestor, false);
|
|
967
|
+
const projected = JSON.parse(JSON.stringify({
|
|
968
|
+
__proto__: null,
|
|
969
|
+
[key]: value
|
|
970
|
+
}));
|
|
971
|
+
return Object.hasOwn(projected, key) ? projected[key] : void 0;
|
|
972
|
+
}
|
|
973
|
+
const cached = frozenJsonProjections.get(value);
|
|
974
|
+
if (cached !== void 0) return cached;
|
|
975
|
+
const immutable = Object.isFrozen(value) && getAiTransportHost().immutableData?.isDeeplyFrozenPlainData(value);
|
|
976
|
+
ancestors.set(value, true);
|
|
977
|
+
try {
|
|
978
|
+
if (Array.isArray(value)) {
|
|
979
|
+
const result = [];
|
|
980
|
+
const length = value.length;
|
|
981
|
+
for (let index = 0; index < length; index++) result.push(projectJsonValue(value[index], String(index), ancestors) ?? null);
|
|
982
|
+
if (immutable && ancestors.get(value)) frozenJsonProjections.set(value, result);
|
|
983
|
+
return result;
|
|
984
|
+
}
|
|
985
|
+
const result = {};
|
|
986
|
+
for (const name of Object.keys(value)) {
|
|
987
|
+
const member = projectJsonValue(Reflect.get(value, name), name, ancestors);
|
|
988
|
+
if (member !== void 0) {
|
|
989
|
+
if (name in result) Object.defineProperty(result, name, {
|
|
990
|
+
value: member,
|
|
991
|
+
enumerable: true,
|
|
992
|
+
configurable: true,
|
|
993
|
+
writable: true
|
|
994
|
+
});
|
|
995
|
+
else result[name] = member;
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
if (immutable && ancestors.get(value)) frozenJsonProjections.set(value, result);
|
|
999
|
+
return result;
|
|
1000
|
+
} finally {
|
|
1001
|
+
ancestors.delete(value);
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
function projectJsonObject(value) {
|
|
1005
|
+
const projected = projectJsonValue(value, "", /* @__PURE__ */ new Map());
|
|
1006
|
+
return projected === void 0 ? JSON.parse("undefined") : projected;
|
|
1007
|
+
}
|
|
1008
|
+
function projectedJsonEqual(left, right) {
|
|
1009
|
+
if (left === right) return true;
|
|
1010
|
+
if (Array.isArray(left)) {
|
|
1011
|
+
if (!Array.isArray(right) || left.length !== right.length) return false;
|
|
1012
|
+
for (let index = 0; index < left.length; index++) if (!projectedJsonEqual(left[index], right[index])) return false;
|
|
1013
|
+
return true;
|
|
1014
|
+
}
|
|
1015
|
+
if (!isRecord(left) || !isRecord(right)) return false;
|
|
1016
|
+
let keys = 0;
|
|
1017
|
+
for (const key in left) if (Object.hasOwn(left, key)) {
|
|
1018
|
+
if (!Object.hasOwn(right, key) || !projectedJsonEqual(left[key], right[key])) return false;
|
|
1019
|
+
keys++;
|
|
1020
|
+
}
|
|
1021
|
+
for (const key in right) if (Object.hasOwn(right, key)) keys--;
|
|
1022
|
+
return keys === 0;
|
|
1023
|
+
}
|
|
1024
|
+
// packages/ai/src/transports/openai-responses-reasoning-update.ts
|
|
925
1025
|
function isConfigurationUpdate(value) {
|
|
926
1026
|
return isRecord(value) && value.type === "configuration_update" && isRecord(value.reasoning) && typeof value.reasoning.effort === "string";
|
|
927
1027
|
}
|
|
@@ -953,10 +1053,10 @@ function replayResponsesReasoningUpdates(previous, request, previousOutputLength
|
|
|
953
1053
|
const baselineLength = previous.input.length + previousOutputLength;
|
|
954
1054
|
const nextUser = input.findIndex((item, index) => index >= baselineLength && "role" in item && item.role === "user");
|
|
955
1055
|
if (nextUser === -1) return request;
|
|
956
|
-
input.splice(nextUser, 0, {
|
|
1056
|
+
input.splice(nextUser, 0, Object.freeze({
|
|
957
1057
|
type: "configuration_update",
|
|
958
|
-
reasoning: { effort: request.reasoning.effort }
|
|
959
|
-
});
|
|
1058
|
+
reasoning: Object.freeze({ effort: request.reasoning.effort })
|
|
1059
|
+
}));
|
|
960
1060
|
}
|
|
961
1061
|
if (input.length === request.input.length && activeEffort === request.reasoning.effort) return request;
|
|
962
1062
|
return {
|
|
@@ -968,8 +1068,66 @@ function replayResponsesReasoningUpdates(previous, request, previousOutputLength
|
|
|
968
1068
|
input
|
|
969
1069
|
};
|
|
970
1070
|
}
|
|
971
|
-
|
|
972
|
-
|
|
1071
|
+
// packages/ai/src/transports/openai-responses-replay.ts
|
|
1072
|
+
function normalizeOpenAIResponsesReasoningReplayItem(item, api) {
|
|
1073
|
+
if (api === "openai-chatgpt-responses") return Array.isArray(item.summary) ? item : {
|
|
1074
|
+
...item,
|
|
1075
|
+
summary: []
|
|
1076
|
+
};
|
|
1077
|
+
return {
|
|
1078
|
+
id: item.id,
|
|
1079
|
+
type: "reasoning",
|
|
1080
|
+
summary: [],
|
|
1081
|
+
...Array.isArray(item.content) && item.content.length === 0 ? { content: [] } : {},
|
|
1082
|
+
status: item.status,
|
|
1083
|
+
encrypted_content: item.encrypted_content
|
|
1084
|
+
};
|
|
1085
|
+
}
|
|
1086
|
+
/** Replay original bytes only while the normalized arguments still match the saved call. */
|
|
1087
|
+
function replayOpenAIResponsesToolArguments(block, providerStyle, sameModel) {
|
|
1088
|
+
const value = providerStyle ? JSON.stringify(block.arguments) : typeof block.arguments === "string" ? block.arguments : JSON.stringify(block.arguments ?? {});
|
|
1089
|
+
const signature = sameModel && block.argumentsSignature;
|
|
1090
|
+
return signature && signature.value === value && typeof signature.raw === "string" ? signature.raw : value;
|
|
1091
|
+
}
|
|
1092
|
+
/** New transcripts retain exact bytes; legacy callers may still replay normalized values. */
|
|
1093
|
+
function normalizeOpenAIResponsesToolArguments(value, replayed) {
|
|
1094
|
+
if (isRecord(replayed) && replayed.arguments === value) return value;
|
|
1095
|
+
const args = parseJsonObjectPreservingUnsafeIntegers(value);
|
|
1096
|
+
return args ? JSON.stringify(args) : value;
|
|
1097
|
+
}
|
|
1098
|
+
// packages/ai/src/transports/responses-image-payload-sanitizer.ts
|
|
1099
|
+
/**
|
|
1100
|
+
* Sanitizes OpenAI Responses payloads before transport. Invalid inline images
|
|
1101
|
+
* are replaced with text placeholders so the request remains valid and
|
|
1102
|
+
* auditable.
|
|
1103
|
+
*/
|
|
1104
|
+
/** Sanitize inline image fields inside a Responses API payload. */
|
|
1105
|
+
function sanitizeResponsesImagePayload(params) {
|
|
1106
|
+
if (!Array.isArray(params.input)) return params;
|
|
1107
|
+
return {
|
|
1108
|
+
...params,
|
|
1109
|
+
input: sanitizeResponsesImageInput(params.input, getAiTransportHost().immutableData)
|
|
1110
|
+
};
|
|
1111
|
+
}
|
|
1112
|
+
// packages/ai/src/transports/openai-responses-retained-bytes.ts
|
|
1113
|
+
function retainedJsonBytes(value, previous) {
|
|
1114
|
+
const jsonBytes = /* @__PURE__ */ new Map();
|
|
1115
|
+
const immutable = getAiTransportHost().immutableData;
|
|
1116
|
+
let valueBytes = 0;
|
|
1117
|
+
const skeleton = JSON.stringify(value, (_key, member) => {
|
|
1118
|
+
if (typeof member !== "string" && !(member && typeof member === "object" && (previous?.has(member) || isSanitizedFrozenResponsesInput(member) || immutable?.isDeeplyFrozenPlainData(member)))) return member;
|
|
1119
|
+
let bytes = jsonBytes.get(member) ?? previous?.get(member);
|
|
1120
|
+
if (bytes === void 0) bytes = Buffer.byteLength(JSON.stringify(member), "utf8") - 2;
|
|
1121
|
+
jsonBytes.set(member, bytes);
|
|
1122
|
+
valueBytes += bytes;
|
|
1123
|
+
return "";
|
|
1124
|
+
});
|
|
1125
|
+
return {
|
|
1126
|
+
retainedBytes: valueBytes + Buffer.byteLength(skeleton, "utf8"),
|
|
1127
|
+
jsonBytes
|
|
1128
|
+
};
|
|
1129
|
+
}
|
|
1130
|
+
// packages/ai/src/transports/openai-responses-tool-call-id-shape.ts
|
|
973
1131
|
/**
|
|
974
1132
|
* Pure OpenAI Responses `call_*`/`fc_*` tool-call-id shape helpers.
|
|
975
1133
|
*
|
|
@@ -1012,8 +1170,7 @@ function shouldNormalizeOpenAIResponsesToolCallId(id) {
|
|
|
1012
1170
|
if (pairing.itemId === void 0) return false;
|
|
1013
1171
|
return !OPENAI_RESPONSES_FUNCTION_CALL_ITEM_ID_RE.test(pairing.itemId);
|
|
1014
1172
|
}
|
|
1015
|
-
|
|
1016
|
-
//#region packages/ai/src/transports/openai-responses-continuation.ts
|
|
1173
|
+
// packages/ai/src/transports/openai-responses-continuation.ts
|
|
1017
1174
|
const HTTP_CONTINUATION_IDLE_TTL_MS = 54e5;
|
|
1018
1175
|
const MAX_HTTP_CONTINUATION_READY_ENTRIES = 1e3;
|
|
1019
1176
|
const MAX_HTTP_CONTINUATION_RETAINED_BYTES = 67108864;
|
|
@@ -1022,49 +1179,8 @@ const TURN_HEADERS = /* @__PURE__ */ new Set([
|
|
|
1022
1179
|
"x-openclaw-turn-id",
|
|
1023
1180
|
"x-openclaw-turn-attempt"
|
|
1024
1181
|
]);
|
|
1025
|
-
function projectJsonValue(value, key, ancestors) {
|
|
1026
|
-
if (typeof value === "number") return Number.isFinite(value) ? value + 0 : null;
|
|
1027
|
-
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
1028
|
-
if (value === void 0 || typeof value === "symbol") return;
|
|
1029
|
-
if (typeof value !== "object" || isProxy(value) || Object.getPrototypeOf(value) !== (Array.isArray(value) ? Array.prototype : Object.prototype) || "toJSON" in value || ancestors.has(value)) {
|
|
1030
|
-
const projected = JSON.parse(JSON.stringify({
|
|
1031
|
-
__proto__: null,
|
|
1032
|
-
[key]: value
|
|
1033
|
-
}));
|
|
1034
|
-
return Object.hasOwn(projected, key) ? projected[key] : void 0;
|
|
1035
|
-
}
|
|
1036
|
-
ancestors.add(value);
|
|
1037
|
-
try {
|
|
1038
|
-
if (Array.isArray(value)) {
|
|
1039
|
-
const result = [];
|
|
1040
|
-
const length = value.length;
|
|
1041
|
-
for (let index = 0; index < length; index++) result.push(projectJsonValue(value[index], String(index), ancestors) ?? null);
|
|
1042
|
-
return result;
|
|
1043
|
-
}
|
|
1044
|
-
const result = {};
|
|
1045
|
-
for (const name of Object.keys(value)) {
|
|
1046
|
-
const member = projectJsonValue(Reflect.get(value, name), name, ancestors);
|
|
1047
|
-
if (member !== void 0) {
|
|
1048
|
-
if (name in result) Object.defineProperty(result, name, {
|
|
1049
|
-
value: member,
|
|
1050
|
-
enumerable: true,
|
|
1051
|
-
configurable: true,
|
|
1052
|
-
writable: true
|
|
1053
|
-
});
|
|
1054
|
-
else result[name] = member;
|
|
1055
|
-
}
|
|
1056
|
-
}
|
|
1057
|
-
return result;
|
|
1058
|
-
} finally {
|
|
1059
|
-
ancestors.delete(value);
|
|
1060
|
-
}
|
|
1061
|
-
}
|
|
1062
|
-
function projectJsonObject(value) {
|
|
1063
|
-
const projected = projectJsonValue(value, "", /* @__PURE__ */ new Set());
|
|
1064
|
-
return projected === void 0 ? JSON.parse("undefined") : projected;
|
|
1065
|
-
}
|
|
1066
1182
|
function jsonValuesEqual(left, right) {
|
|
1067
|
-
return
|
|
1183
|
+
return projectedJsonEqual(projectJsonObject(left), projectJsonObject(right));
|
|
1068
1184
|
}
|
|
1069
1185
|
function requestWithoutInput(request) {
|
|
1070
1186
|
const { input: _input, previous_response_id: _previousResponseId, instructions: _instructions, tools: _tools, ...rest } = request;
|
|
@@ -1091,11 +1207,11 @@ function responseToolCalls(items) {
|
|
|
1091
1207
|
});
|
|
1092
1208
|
}
|
|
1093
1209
|
function toolCallReplayShapes(call) {
|
|
1094
|
-
return
|
|
1210
|
+
return [
|
|
1095
1211
|
call.callId,
|
|
1096
1212
|
canonicalizeToolCallId(call.callId, call.itemId),
|
|
1097
1213
|
canonicalizeToolCallId(call.callId, void 0)
|
|
1098
|
-
].filter((shape) => typeof shape === "string")
|
|
1214
|
+
].filter((shape) => typeof shape === "string");
|
|
1099
1215
|
}
|
|
1100
1216
|
function toolCallOwnerByReplayShape(calls) {
|
|
1101
1217
|
const ownerByReplayShape = /* @__PURE__ */ new Map();
|
|
@@ -1128,7 +1244,7 @@ function recordResponsesContinuationState(previous, lastRequest, response, conti
|
|
|
1128
1244
|
}
|
|
1129
1245
|
const pendingToolCalls = uniqueCalls.filter((_call, index) => {
|
|
1130
1246
|
const callPosition = lastCallPosition.get(index);
|
|
1131
|
-
return
|
|
1247
|
+
return toolCallReplayShapes(_call).some((shape) => replayedCallIds.has(shape)) && (callPosition === void 0 || (lastOutputPosition.get(index) ?? -1) < callPosition);
|
|
1132
1248
|
});
|
|
1133
1249
|
return {
|
|
1134
1250
|
lastRequest,
|
|
@@ -1137,11 +1253,12 @@ function recordResponsesContinuationState(previous, lastRequest, response, conti
|
|
|
1137
1253
|
pendingToolCalls
|
|
1138
1254
|
};
|
|
1139
1255
|
}
|
|
1140
|
-
function normalizeAssistantReplayInput(input, fromResponse = false, ignoreCachedItemIds = false) {
|
|
1141
|
-
return input.map((item) => {
|
|
1256
|
+
function normalizeAssistantReplayInput(input, fromResponse = false, ignoreCachedItemIds = false, replayedInput) {
|
|
1257
|
+
return input.map((item, index) => {
|
|
1142
1258
|
if (!isRecord(item)) return item;
|
|
1143
1259
|
if (item.type === "reasoning") return { type: "reasoning" };
|
|
1144
1260
|
if (item.type !== "function_call" && item.type !== "function_call_output" && !(item.type === "message" && item.role === "assistant")) return item;
|
|
1261
|
+
if (!fromResponse && getAiTransportHost().immutableData?.isDeeplyFrozenPlainData(item) && !("id" in item) && !("status" in item) && !("toJSON" in item) && (!("call_id" in item) || Object.prototype.propertyIsEnumerable.call(item, "call_id") && canonicalizeToolCallId(item.call_id, void 0) === item.call_id) && (item.type !== "message" || !Array.isArray(item.content) || !("toJSON" in item.content) && item.content.every((part) => !isRecord(part) || part.type !== "output_text" || !("annotations" in part) && !("logprobs" in part) && !("toJSON" in part)))) return item;
|
|
1145
1262
|
const { id: rawId, status: _status, ...stableItem } = item;
|
|
1146
1263
|
if (item.type === "function_call_output") {
|
|
1147
1264
|
if ("id" in item) stableItem.id = item.id;
|
|
@@ -1151,10 +1268,7 @@ function normalizeAssistantReplayInput(input, fromResponse = false, ignoreCached
|
|
|
1151
1268
|
const itemId = item.type === "function_call" && !(fromResponse && ignoreCachedItemIds) ? rawId : void 0;
|
|
1152
1269
|
stableItem.call_id = canonicalizeToolCallId(stableItem.call_id, itemId);
|
|
1153
1270
|
}
|
|
1154
|
-
if (fromResponse && item.type === "function_call")
|
|
1155
|
-
const args = parseJsonObjectPreservingUnsafeIntegers(stableItem.arguments);
|
|
1156
|
-
stableItem.arguments = args ? JSON.stringify(args) : stableItem.arguments;
|
|
1157
|
-
}
|
|
1271
|
+
if (fromResponse && item.type === "function_call") stableItem.arguments = normalizeOpenAIResponsesToolArguments(stableItem.arguments, replayedInput?.[index]);
|
|
1158
1272
|
if (item.type === "message" && Array.isArray(stableItem.content)) stableItem.content = stableItem.content.map((part) => {
|
|
1159
1273
|
if (!isRecord(part) || part.type !== "output_text") return part;
|
|
1160
1274
|
const { annotations: _annotations, logprobs: _logprobs, ...stablePart } = part;
|
|
@@ -1165,31 +1279,101 @@ function normalizeAssistantReplayInput(input, fromResponse = false, ignoreCached
|
|
|
1165
1279
|
}
|
|
1166
1280
|
function normalizeContinuationHistory(input) {
|
|
1167
1281
|
const normalized = normalizeAssistantReplayInput(input);
|
|
1282
|
+
const callOwners = /* @__PURE__ */ new Map();
|
|
1168
1283
|
const ownerByReplayShape = toolCallOwnerByReplayShape(responseToolCalls(input));
|
|
1169
1284
|
let callIndex = 0;
|
|
1170
1285
|
for (const [index, item] of input.entries()) {
|
|
1171
1286
|
const normalizedItem = normalized[index];
|
|
1172
1287
|
if (!isRecord(item) || !isRecord(normalizedItem)) continue;
|
|
1288
|
+
let callId;
|
|
1173
1289
|
if (item.type === "function_call") {
|
|
1174
1290
|
if (typeof normalizedItem.call_id !== "string") return;
|
|
1175
1291
|
const callOwner = ownerByReplayShape.get(normalizedItem.call_id);
|
|
1176
1292
|
if (callOwner !== callIndex) return;
|
|
1177
|
-
|
|
1293
|
+
callId = { callOwner };
|
|
1178
1294
|
callIndex += 1;
|
|
1179
|
-
|
|
1295
|
+
} else if (item.type === "function_call_output" && typeof item.call_id === "string") {
|
|
1296
|
+
const owner = ownerByReplayShape.get(item.call_id);
|
|
1297
|
+
if (owner === null) return;
|
|
1298
|
+
callId = owner === void 0 ? { unknownCallId: canonicalizeToolCallId(item.call_id, void 0) } : { callOwner: owner };
|
|
1299
|
+
} else continue;
|
|
1300
|
+
if (normalizedItem === item && !("toJSON" in normalized)) callOwners.set(index, callId);
|
|
1301
|
+
else {
|
|
1302
|
+
const ownedItem = normalizedItem === item ? { ...normalizedItem } : normalizedItem;
|
|
1303
|
+
ownedItem.call_id = callId;
|
|
1304
|
+
normalized[index] = ownedItem;
|
|
1180
1305
|
}
|
|
1181
|
-
if (item.type !== "function_call_output" || typeof item.call_id !== "string") continue;
|
|
1182
|
-
const owner = ownerByReplayShape.get(item.call_id);
|
|
1183
|
-
if (owner === null) return;
|
|
1184
|
-
normalizedItem.call_id = owner === void 0 ? { unknownCallId: canonicalizeToolCallId(item.call_id, void 0) } : { callOwner: owner };
|
|
1185
1306
|
}
|
|
1186
|
-
return
|
|
1307
|
+
return {
|
|
1308
|
+
items: normalized,
|
|
1309
|
+
callOwners
|
|
1310
|
+
};
|
|
1311
|
+
}
|
|
1312
|
+
function projectContinuationHistory(history) {
|
|
1313
|
+
const projected = projectJsonObject(history.items);
|
|
1314
|
+
if (Array.isArray(projected)) for (const [index, callId] of history.callOwners) {
|
|
1315
|
+
const item = projected[index];
|
|
1316
|
+
if (isRecord(item)) projected[index] = {
|
|
1317
|
+
...item,
|
|
1318
|
+
call_id: callId
|
|
1319
|
+
};
|
|
1320
|
+
}
|
|
1321
|
+
return projected;
|
|
1187
1322
|
}
|
|
1188
1323
|
function responsesContinuationRequestFingerprint(request) {
|
|
1189
1324
|
return sha256StableValue(projectJsonObject(requestWithoutInput(request))).digest;
|
|
1190
1325
|
}
|
|
1326
|
+
const emptyPrefix = { digest: createHash("sha256").update("[") };
|
|
1327
|
+
const prefixCheckpoints = /* @__PURE__ */ new WeakMap();
|
|
1328
|
+
function appendPrefixValues(digest, values, offset) {
|
|
1329
|
+
let text = "";
|
|
1330
|
+
let index = offset;
|
|
1331
|
+
const write = (chunk) => {
|
|
1332
|
+
text += chunk;
|
|
1333
|
+
if (text.length >= 16384) {
|
|
1334
|
+
digest.update(text);
|
|
1335
|
+
text = "";
|
|
1336
|
+
}
|
|
1337
|
+
};
|
|
1338
|
+
for (const value of values) {
|
|
1339
|
+
if (index > 0) write(",");
|
|
1340
|
+
writeStableStringify(projectJsonValue(value, String(index++), /* @__PURE__ */ new Map()) ?? null, write);
|
|
1341
|
+
}
|
|
1342
|
+
digest.update(text);
|
|
1343
|
+
}
|
|
1191
1344
|
function responsesContinuationPrefixFingerprint(input, output = []) {
|
|
1192
|
-
|
|
1345
|
+
const immutable = getAiTransportHost().immutableData;
|
|
1346
|
+
let prefix = emptyPrefix;
|
|
1347
|
+
let retainedDigest = emptyPrefix.digest;
|
|
1348
|
+
let retainedLength = 0;
|
|
1349
|
+
let length = 0;
|
|
1350
|
+
for (const item of input) {
|
|
1351
|
+
if (!item || typeof item !== "object") break;
|
|
1352
|
+
const compactionIdentity = getResponsesCompactionInputIdentity(item);
|
|
1353
|
+
const identity = compactionIdentity ?? item;
|
|
1354
|
+
let next = prefixCheckpoints.get(identity);
|
|
1355
|
+
if (!next && !compactionIdentity && !isSanitizedFrozenResponsesInput(item) && !immutable?.isDeeplyFrozenPlainData(item)) break;
|
|
1356
|
+
if (next?.previous !== prefix) {
|
|
1357
|
+
next = { previous: prefix };
|
|
1358
|
+
prefixCheckpoints.set(identity, next);
|
|
1359
|
+
}
|
|
1360
|
+
prefix = next;
|
|
1361
|
+
length++;
|
|
1362
|
+
if (next.digest) {
|
|
1363
|
+
retainedDigest = next.digest;
|
|
1364
|
+
retainedLength = length;
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
if (length > 0) {
|
|
1368
|
+
const digest = retainedDigest.copy();
|
|
1369
|
+
if (retainedLength < length) {
|
|
1370
|
+
appendPrefixValues(digest, normalizeAssistantReplayInput(input.slice(retainedLength, length)), retainedLength);
|
|
1371
|
+
prefix.digest = digest.copy();
|
|
1372
|
+
}
|
|
1373
|
+
if (length < input.length || output.length > 0) appendPrefixValues(digest, [...normalizeAssistantReplayInput(input.slice(length)), ...normalizeAssistantReplayInput(output, true, false, output)], length);
|
|
1374
|
+
return digest.update("]").digest("hex");
|
|
1375
|
+
}
|
|
1376
|
+
return sha256StableValue(projectJsonObject([...normalizeAssistantReplayInput(input), ...normalizeAssistantReplayInput(output, true, false, output)])).digest;
|
|
1193
1377
|
}
|
|
1194
1378
|
function resolveResponsesContinuationRequest(continuation, request, steering) {
|
|
1195
1379
|
if (!continuation) return {
|
|
@@ -1218,31 +1402,45 @@ function resolveResponsesContinuationRequest(continuation, request, steering) {
|
|
|
1218
1402
|
};
|
|
1219
1403
|
const replayedToolRoundInput = currentInput.slice(previousInput.length, baselineLength);
|
|
1220
1404
|
const replayedToolRound = normalizeAssistantReplayInput(replayedToolRoundInput);
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1405
|
+
if (![false, true].some((ignoreCachedItemIds) => jsonValuesEqual(replayedToolRound, normalizeAssistantReplayInput(continuation.lastResponseItems, true, ignoreCachedItemIds, replayedToolRoundInput)))) return {
|
|
1406
|
+
request,
|
|
1407
|
+
continuationStatus: "history_changed"
|
|
1408
|
+
};
|
|
1409
|
+
const immutable = getAiTransportHost().immutableData;
|
|
1410
|
+
let samePrefix = true;
|
|
1411
|
+
for (let index = 0; index < previousInput.length; index++) {
|
|
1412
|
+
const item = previousInput[index];
|
|
1413
|
+
if (item !== currentInput[index] || item === null || typeof item !== "object" || !(isSanitizedFrozenResponsesInput(item) || immutable?.isDeeplyFrozenPlainData(item))) {
|
|
1414
|
+
samePrefix = false;
|
|
1415
|
+
break;
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1418
|
+
if (!samePrefix) {
|
|
1419
|
+
const historyCurrentInput = currentInput.slice(0, previousInput.length);
|
|
1420
|
+
for (const [index, previousItem] of previousInput.entries()) {
|
|
1421
|
+
const currentItem = historyCurrentInput[index];
|
|
1422
|
+
if (!isRecord(previousItem) || !isRecord(currentItem)) continue;
|
|
1423
|
+
if (previousItem.type === "function_call" && currentItem.type === "function_call") {
|
|
1424
|
+
if (typeof previousItem.call_id === "string" && typeof currentItem.call_id === "string" && !toolCallReplayShapes({
|
|
1425
|
+
callId: previousItem.call_id,
|
|
1426
|
+
...typeof previousItem.id === "string" ? { itemId: previousItem.id } : {}
|
|
1427
|
+
}).includes(currentItem.call_id)) return {
|
|
1428
|
+
request,
|
|
1429
|
+
continuationStatus: "history_changed"
|
|
1430
|
+
};
|
|
1431
|
+
}
|
|
1432
|
+
if (previousItem.type === "function_call_output" && currentItem.type === "function_call_output" && typeof previousItem.call_id === "string" && typeof currentItem.call_id === "string" && currentItem.call_id !== previousItem.call_id && currentItem.call_id !== canonicalizeToolCallId(previousItem.call_id, void 0)) return {
|
|
1231
1433
|
request,
|
|
1232
1434
|
continuationStatus: "history_changed"
|
|
1233
1435
|
};
|
|
1234
1436
|
}
|
|
1235
|
-
|
|
1437
|
+
const normalizedPrevious = normalizeContinuationHistory(previousInput);
|
|
1438
|
+
const normalizedCurrent = normalizeContinuationHistory(historyCurrentInput);
|
|
1439
|
+
if (normalizedPrevious === void 0 || normalizedCurrent === void 0 || !projectedJsonEqual(projectContinuationHistory(normalizedCurrent), projectContinuationHistory(normalizedPrevious))) return {
|
|
1236
1440
|
request,
|
|
1237
1441
|
continuationStatus: "history_changed"
|
|
1238
1442
|
};
|
|
1239
1443
|
}
|
|
1240
|
-
const normalizedPrevious = normalizeContinuationHistory(previousInput);
|
|
1241
|
-
const normalizedCurrent = normalizeContinuationHistory(historyCurrentInput);
|
|
1242
|
-
if (!(normalizedPrevious !== void 0 && normalizedCurrent !== void 0 && jsonValuesEqual(normalizedCurrent, normalizedPrevious)) || !historyToolRoundUnchanged) return {
|
|
1243
|
-
request,
|
|
1244
|
-
continuationStatus: "history_changed"
|
|
1245
|
-
};
|
|
1246
1444
|
const delta = currentInput.slice(baselineLength);
|
|
1247
1445
|
const cachedResponseItems = continuation.lastResponseItems;
|
|
1248
1446
|
const pendingToolCalls = continuation.pendingToolCalls ?? [];
|
|
@@ -1333,22 +1531,6 @@ function connectionIdentity(params) {
|
|
|
1333
1531
|
headers
|
|
1334
1532
|
]));
|
|
1335
1533
|
}
|
|
1336
|
-
function retainedJsonBytes(value, previous) {
|
|
1337
|
-
const strings = /* @__PURE__ */ new Map();
|
|
1338
|
-
let stringBytes = 0;
|
|
1339
|
-
const skeleton = JSON.stringify(value, (_key, member) => {
|
|
1340
|
-
if (typeof member !== "string") return member;
|
|
1341
|
-
let bytes = strings.get(member) ?? previous?.get(member);
|
|
1342
|
-
if (bytes === void 0) bytes = Buffer.byteLength(JSON.stringify(member), "utf8") - 2;
|
|
1343
|
-
strings.set(member, bytes);
|
|
1344
|
-
stringBytes += bytes;
|
|
1345
|
-
return "";
|
|
1346
|
-
});
|
|
1347
|
-
return {
|
|
1348
|
-
retainedBytes: stringBytes + Buffer.byteLength(skeleton, "utf8"),
|
|
1349
|
-
strings
|
|
1350
|
-
};
|
|
1351
|
-
}
|
|
1352
1534
|
function claimOpenAIResponsesHttpContinuation(params) {
|
|
1353
1535
|
const owner = getAiTransportHost();
|
|
1354
1536
|
const key = `${getSessionResourceOwnerId(owner)}\0${params.sessionId}\0${connectionIdentity(params)}`;
|
|
@@ -1371,7 +1553,7 @@ function claimOpenAIResponsesHttpContinuation(params) {
|
|
|
1371
1553
|
commit: (effectiveRequest, response, dispatchedPreviousResponseId) => {
|
|
1372
1554
|
if (httpContinuationEntries.get(key) !== claimed) return;
|
|
1373
1555
|
const state = recordResponsesContinuationState(previous?.state, effectiveRequest, response, previous !== void 0 && dispatchedPreviousResponseId === previous.state.lastResponseId);
|
|
1374
|
-
const { retainedBytes,
|
|
1556
|
+
const { retainedBytes, jsonBytes } = retainedJsonBytes(state, previous?.jsonBytes);
|
|
1375
1557
|
if (retainedBytes > MAX_HTTP_CONTINUATION_RETAINED_BYTES) {
|
|
1376
1558
|
deleteHttpContinuationIfOwned(key, claimed);
|
|
1377
1559
|
return;
|
|
@@ -1383,7 +1565,7 @@ function claimOpenAIResponsesHttpContinuation(params) {
|
|
|
1383
1565
|
state,
|
|
1384
1566
|
idleTimer: owner.runInDetachedAsyncContext(() => createHttpContinuationTimer(key)),
|
|
1385
1567
|
retainedBytes,
|
|
1386
|
-
|
|
1568
|
+
jsonBytes
|
|
1387
1569
|
};
|
|
1388
1570
|
httpContinuationRetainedBytes += retainedBytes;
|
|
1389
1571
|
httpContinuationEntries.set(key, ready);
|
|
@@ -1395,8 +1577,7 @@ function claimOpenAIResponsesHttpContinuation(params) {
|
|
|
1395
1577
|
registerSessionResourceCleanup((sessionId, owner) => {
|
|
1396
1578
|
for (const [key, entry] of httpContinuationEntries) if ((!owner || entry.owner === owner) && (!sessionId || entry.sessionId === sessionId)) deleteHttpContinuationIfOwned(key, entry);
|
|
1397
1579
|
});
|
|
1398
|
-
|
|
1399
|
-
//#region packages/ai/src/transports/openai-responses-input-replay.ts
|
|
1580
|
+
// packages/ai/src/transports/openai-responses-input-replay.ts
|
|
1400
1581
|
function recordResponsesInputReplay(message, replay) {
|
|
1401
1582
|
if (replay) Object.assign(message, { openclawResponsesInputReplay: replay });
|
|
1402
1583
|
}
|
|
@@ -1456,30 +1637,7 @@ function createResponsesInputReplay(model) {
|
|
|
1456
1637
|
if (message.responseId && end) ends.set(message.responseId, end);
|
|
1457
1638
|
};
|
|
1458
1639
|
}
|
|
1459
|
-
|
|
1460
|
-
//#region packages/ai/src/transports/openai-responses-replay.ts
|
|
1461
|
-
/** Resolves the assistant message id that can be replayed to OpenAI Responses. */
|
|
1462
|
-
function resolveReplayableResponsesMessageId(params) {
|
|
1463
|
-
if (!params.replayResponsesItemIds) return;
|
|
1464
|
-
if (!params.textSignatureId) return params.fallbackOrdinal === 0 ? params.fallbackId : `${params.fallbackId}_${params.fallbackOrdinal}`;
|
|
1465
|
-
return params.previousReplayItemWasReasoning ? params.textSignatureId : void 0;
|
|
1466
|
-
}
|
|
1467
|
-
function normalizeOpenAIResponsesReasoningReplayItem(item, api) {
|
|
1468
|
-
if (api === "openai-chatgpt-responses") return Array.isArray(item.summary) ? item : {
|
|
1469
|
-
...item,
|
|
1470
|
-
summary: []
|
|
1471
|
-
};
|
|
1472
|
-
return {
|
|
1473
|
-
id: item.id,
|
|
1474
|
-
type: "reasoning",
|
|
1475
|
-
summary: [],
|
|
1476
|
-
...Array.isArray(item.content) && item.content.length === 0 ? { content: [] } : {},
|
|
1477
|
-
status: item.status,
|
|
1478
|
-
encrypted_content: item.encrypted_content
|
|
1479
|
-
};
|
|
1480
|
-
}
|
|
1481
|
-
//#endregion
|
|
1482
|
-
//#region packages/ai/src/utils/text-signature.ts
|
|
1640
|
+
// packages/ai/src/utils/text-signature.ts
|
|
1483
1641
|
function encodeTextSignatureV1(id, phase) {
|
|
1484
1642
|
return JSON.stringify({
|
|
1485
1643
|
v: 1,
|
|
@@ -1487,8 +1645,24 @@ function encodeTextSignatureV1(id, phase) {
|
|
|
1487
1645
|
...phase ? { phase } : {}
|
|
1488
1646
|
});
|
|
1489
1647
|
}
|
|
1490
|
-
|
|
1491
|
-
|
|
1648
|
+
function parseOpenAIResponsesTextSignature(signature) {
|
|
1649
|
+
if (!signature) return;
|
|
1650
|
+
if (signature.startsWith("{")) try {
|
|
1651
|
+
const parsed = JSON.parse(signature);
|
|
1652
|
+
if (parsed.v === 1) {
|
|
1653
|
+
const id = typeof parsed.id === "string" ? parsed.id : void 0;
|
|
1654
|
+
const phase = parsed.phase === "commentary" || parsed.phase === "final_answer" ? parsed.phase : void 0;
|
|
1655
|
+
if (id !== void 0 || phase !== void 0) return {
|
|
1656
|
+
id,
|
|
1657
|
+
phase,
|
|
1658
|
+
...typeof parsed.sources === "string" ? { sources: parsed.sources } : {}
|
|
1659
|
+
};
|
|
1660
|
+
return;
|
|
1661
|
+
}
|
|
1662
|
+
} catch {}
|
|
1663
|
+
return { id: signature };
|
|
1664
|
+
}
|
|
1665
|
+
// packages/ai/src/transports/openai-responses-replay-messages-internal.ts
|
|
1492
1666
|
function resolveResponsesInstructionRole(model) {
|
|
1493
1667
|
const supportsDeveloperRole = !isRecord(model.compat) || model.compat.supportsDeveloperRole !== false;
|
|
1494
1668
|
return model.reasoning && supportsDeveloperRole ? "developer" : "system";
|
|
@@ -1535,11 +1709,6 @@ function prepareOpenAIResponsesReasoningItemForReplay(item, context, blockMetada
|
|
|
1535
1709
|
if (blockMetadata === void 0 && !hasRawMetadata && options?.preserveUnattributedEncryptedContent === true || metadata && providerReplayContextMatches(metadata, context)) return normalizeOpenAIResponsesReasoningReplayItem(rest, context.api);
|
|
1536
1710
|
return normalizeOpenAIResponsesReasoningReplayItem(stripEncryptedReasoningContentFields(rest), context.api);
|
|
1537
1711
|
}
|
|
1538
|
-
function normalizeResponsesReplayItemId(id) {
|
|
1539
|
-
if (!id) return;
|
|
1540
|
-
if (id.length <= 64) return id;
|
|
1541
|
-
return `msg_${shortHash(id)}`;
|
|
1542
|
-
}
|
|
1543
1712
|
function responsesAssistantTurnKey(message) {
|
|
1544
1713
|
const id = message.turnId || message.responseId;
|
|
1545
1714
|
return id ? `${message.provider}:${message.api}:${message.model}:${id}` : void 0;
|
|
@@ -1575,23 +1744,6 @@ function orderResponsesAsyncToolResults(source) {
|
|
|
1575
1744
|
}
|
|
1576
1745
|
return ordered;
|
|
1577
1746
|
}
|
|
1578
|
-
function parseOpenAIResponsesTextSignature(signature) {
|
|
1579
|
-
if (!signature) return;
|
|
1580
|
-
if (signature.startsWith("{")) try {
|
|
1581
|
-
const parsed = JSON.parse(signature);
|
|
1582
|
-
if (parsed.v === 1) {
|
|
1583
|
-
const id = typeof parsed.id === "string" ? parsed.id : void 0;
|
|
1584
|
-
const phase = parsed.phase === "commentary" || parsed.phase === "final_answer" ? parsed.phase : void 0;
|
|
1585
|
-
if (id !== void 0 || phase !== void 0) return {
|
|
1586
|
-
id,
|
|
1587
|
-
phase,
|
|
1588
|
-
...typeof parsed.sources === "string" ? { sources: parsed.sources } : {}
|
|
1589
|
-
};
|
|
1590
|
-
return;
|
|
1591
|
-
}
|
|
1592
|
-
} catch {}
|
|
1593
|
-
return { id: signature };
|
|
1594
|
-
}
|
|
1595
1747
|
const responsesInputSource = Symbol("openclaw.responsesInputSource");
|
|
1596
1748
|
/** Source identity survives payload spreads but never enters serialized provider input. */
|
|
1597
1749
|
function bindResponsesInputMessage(source) {
|
|
@@ -1624,10 +1776,7 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1624
1776
|
const messages = [];
|
|
1625
1777
|
const providerStyle = conversionStyle === "provider";
|
|
1626
1778
|
const shouldReplayResponsesItemIds = options?.replayResponsesItemIds ?? true;
|
|
1627
|
-
const replayContext = buildProviderReplayContext(model, {
|
|
1628
|
-
sessionId: options?.sessionId,
|
|
1629
|
-
authProfileId: options?.authProfileId
|
|
1630
|
-
});
|
|
1779
|
+
const replayContext = buildProviderReplayContext(model, { sessionId: options?.sessionId });
|
|
1631
1780
|
const shouldNormalizeSameModelToolCallIds = model.provider === "github-copilot";
|
|
1632
1781
|
const sanitizeIdPart = (part) => {
|
|
1633
1782
|
const sanitized = part.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
@@ -1655,9 +1804,9 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1655
1804
|
};
|
|
1656
1805
|
const replayPlan = buildOpenAIResponsesCompactionReplayPlan(context.messages, model, {
|
|
1657
1806
|
sessionId: options?.sessionId,
|
|
1658
|
-
authProfileId: options?.authProfileId,
|
|
1659
1807
|
mode: options?.replayMode
|
|
1660
1808
|
});
|
|
1809
|
+
if (replayPlan.itemRecovery) options?.onItemRecovery?.();
|
|
1661
1810
|
const transformMessages = (source) => providerStyle ? transformProviderMessages(source, model, normalizeToolCallId) : getAiTransportHost().transformTransportMessages(source, model, normalizeToolCallId, {
|
|
1662
1811
|
normalizeSameModelToolCallIds: shouldNormalizeSameModelToolCallIds,
|
|
1663
1812
|
preserveUnframedToolResults: replayPlan.preserveUnframedToolResults || preparedRequestSuffix.has(context)
|
|
@@ -1667,10 +1816,13 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1667
1816
|
type: "input_text",
|
|
1668
1817
|
text: prepareSystemPrompt(context.systemPrompt, context.preparedSystemPrompt).instructions
|
|
1669
1818
|
}]));
|
|
1670
|
-
if (replayPlan.compactedWindow)
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1819
|
+
if (replayPlan.compactedWindow) {
|
|
1820
|
+
const window = replayPlan.compactedWindow.map((item) => {
|
|
1821
|
+
if (options?.retainUserProvenance && item.type === "message" && item.role === "user") return tagResponsesCompactionInput(item, RESPONSES_RETAINED_USER);
|
|
1822
|
+
return item;
|
|
1823
|
+
});
|
|
1824
|
+
messages.push(...options?.mutableInput ? cloneResponsesInputForPayloadHook(window) : window);
|
|
1825
|
+
}
|
|
1674
1826
|
let replayMessages = replayPlan.compaction ? [replayPlan.compaction, ...transformedMessages] : transformedMessages;
|
|
1675
1827
|
const isCarrier = (message) => "role" in message && hasRuntimeContextMarker(message);
|
|
1676
1828
|
if (replayMessages.some(isCarrier)) {
|
|
@@ -1687,16 +1839,21 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1687
1839
|
replayMessages = anchored;
|
|
1688
1840
|
}
|
|
1689
1841
|
let msgIndex = 0;
|
|
1842
|
+
let recoveryAnchor = replayPlan.itemRecovery?.anchor;
|
|
1843
|
+
let pastRecoveryBoundary = false;
|
|
1844
|
+
const recoveredCalls = recoveryAnchor ? /* @__PURE__ */ new Set() : void 0;
|
|
1845
|
+
const replayCallId = (id) => recoveryAnchor ? `call_${shortHash(`${recoveryAnchor}:${id}`)}` : id;
|
|
1690
1846
|
const appendAssistant = createResponsesInputReplay(model);
|
|
1691
|
-
const
|
|
1847
|
+
const nativeOpenAI = supportsNativeOpenAIResponsesEndpoint(model);
|
|
1692
1848
|
const convertMessage = (msg, messageIndex) => {
|
|
1849
|
+
const replayItemIds = shouldReplayResponsesItemIds && !recoveryAnchor;
|
|
1693
1850
|
const converted = [];
|
|
1694
|
-
if (
|
|
1851
|
+
if (nativeOpenAI && isRuntimeContextMessage(msg)) converted.push(buildResponsesInputMessage(resolveResponsesInstructionRole(model), [{
|
|
1695
1852
|
type: "input_text",
|
|
1696
1853
|
text: sanitizeTransportPayloadText(runtimeContextContentToText(msg.content))
|
|
1697
1854
|
}]));
|
|
1698
1855
|
else if (msg.role === "user") {
|
|
1699
|
-
const role = msg.operatorMessage &&
|
|
1856
|
+
const role = msg.operatorMessage && nativeOpenAI && (typeof msg.content === "string" || msg.content.every((block) => block.type === "text")) ? resolveResponsesInstructionRole(model) : "user";
|
|
1700
1857
|
const content = typeof msg.content === "string" ? [{
|
|
1701
1858
|
type: "input_text",
|
|
1702
1859
|
text: sanitizeTransportPayloadText(msg.content)
|
|
@@ -1711,13 +1868,13 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1711
1868
|
}
|
|
1712
1869
|
} else if (msg.role === "assistant") {
|
|
1713
1870
|
const output = converted;
|
|
1714
|
-
|
|
1715
|
-
const sourceFragmentId = msg.content.find((block) => block.type === "toolCall")?.id;
|
|
1871
|
+
let textFallbackId;
|
|
1716
1872
|
let textFallbackOrdinal = 0;
|
|
1717
|
-
let
|
|
1873
|
+
let previousReasoningHasId = false;
|
|
1718
1874
|
let seenReplayableReasoning = false;
|
|
1719
1875
|
const isDifferentModel = msg.model !== model.id && msg.provider === model.provider && msg.api === model.api;
|
|
1720
1876
|
for (const block of msg.content) if (block.type === "thinking") {
|
|
1877
|
+
if (recoveryAnchor) continue;
|
|
1721
1878
|
if (block.thinkingSignature && (providerStyle || block.thinkingSignature.startsWith("{"))) {
|
|
1722
1879
|
let reasoningItem;
|
|
1723
1880
|
try {
|
|
@@ -1727,26 +1884,29 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1727
1884
|
}
|
|
1728
1885
|
if (!isRecord(reasoningItem) || reasoningItem.type !== "reasoning") continue;
|
|
1729
1886
|
const replayableReasoningItem = prepareOpenAIResponsesReasoningItemForReplay(reasoningItem, replayContext, readOpenAIResponsesReasoningReplayBlockMetadata(isRecord(block) ? block : {}), providerStyle ? { preserveUnattributedEncryptedContent: true } : void 0);
|
|
1730
|
-
if (!
|
|
1731
|
-
|
|
1732
|
-
if (!replayableReasoningItem.encrypted_content) continue;
|
|
1733
|
-
}
|
|
1734
|
-
if (shouldReplayResponsesItemIds && !providerStyle && model.provider === "github-copilot" && !isSafeResponsesReplayItemId(replayableReasoningItem.id)) continue;
|
|
1887
|
+
if (replayableReasoningItem.encrypted_content && (nativeOpenAI || !replayItemIds)) delete replayableReasoningItem.id;
|
|
1888
|
+
else if (!replayItemIds || !providerStyle && model.provider === "github-copilot" && !isSafeResponsesReplayItemId(replayableReasoningItem.id)) continue;
|
|
1735
1889
|
output.push(replayableReasoningItem);
|
|
1736
|
-
|
|
1737
|
-
|
|
1890
|
+
const reasoningId = replayableReasoningItem.id;
|
|
1891
|
+
previousReasoningHasId = typeof reasoningId === "string";
|
|
1892
|
+
seenReplayableReasoning ||= typeof reasoningId === "string" && reasoningId.startsWith("rs_");
|
|
1738
1893
|
}
|
|
1739
1894
|
} else if (block.type === "text") {
|
|
1740
1895
|
const textSignature = parseOpenAIResponsesTextSignature(block.textSignature);
|
|
1741
|
-
let msgId
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1896
|
+
let msgId;
|
|
1897
|
+
if (replayItemIds) {
|
|
1898
|
+
if (textSignature?.id) msgId = previousReasoningHasId ? textSignature.id : void 0;
|
|
1899
|
+
else {
|
|
1900
|
+
if (!textFallbackId) {
|
|
1901
|
+
const sourceTurnKey = responsesAssistantTurnKey(msg);
|
|
1902
|
+
const sourceFragmentId = msg.content.find((item) => item.type === "toolCall")?.id;
|
|
1903
|
+
textFallbackId = sourceTurnKey ? `msg_${shortHash(JSON.stringify([sourceTurnKey, sourceFragmentId]))}` : `msg_${messageIndex}`;
|
|
1904
|
+
}
|
|
1905
|
+
msgId = textFallbackOrdinal === 0 ? textFallbackId : `${textFallbackId}_${textFallbackOrdinal}`;
|
|
1906
|
+
textFallbackOrdinal += 1;
|
|
1907
|
+
}
|
|
1908
|
+
}
|
|
1909
|
+
if (msgId && msgId.length > 64) msgId = `msg_${shortHash(msgId)}`;
|
|
1750
1910
|
const sources = textSignature?.sources;
|
|
1751
1911
|
const providerText = sources && block.text.endsWith(sources) ? block.text.slice(0, -sources.length) : block.text;
|
|
1752
1912
|
const messageItem = {
|
|
@@ -1762,21 +1922,21 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1762
1922
|
phase: textSignature?.phase
|
|
1763
1923
|
};
|
|
1764
1924
|
output.push(messageItem);
|
|
1765
|
-
|
|
1925
|
+
previousReasoningHasId = false;
|
|
1766
1926
|
} else if (block.type === "toolCall") {
|
|
1767
1927
|
const separatorIndex = block.id.indexOf("|");
|
|
1768
1928
|
const callId = separatorIndex === -1 ? block.id : block.id.slice(0, separatorIndex);
|
|
1769
1929
|
const itemIdRaw = separatorIndex === -1 ? void 0 : block.id.slice(separatorIndex + 1);
|
|
1770
|
-
const itemId =
|
|
1930
|
+
const itemId = replayItemIds && (!itemIdRaw?.startsWith("fc_") || seenReplayableReasoning && !isDifferentModel) ? itemIdRaw : void 0;
|
|
1771
1931
|
output.push({
|
|
1772
1932
|
type: "function_call",
|
|
1773
1933
|
...itemId ? { id: itemId } : {},
|
|
1774
|
-
call_id: callId,
|
|
1934
|
+
call_id: replayCallId(callId),
|
|
1775
1935
|
name: block.name,
|
|
1776
1936
|
...block.async ? { async: true } : {},
|
|
1777
|
-
arguments:
|
|
1937
|
+
arguments: replayOpenAIResponsesToolArguments(block, providerStyle, msg.model === model.id && msg.provider === model.provider && msg.api === model.api)
|
|
1778
1938
|
});
|
|
1779
|
-
|
|
1939
|
+
previousReasoningHasId = false;
|
|
1780
1940
|
}
|
|
1781
1941
|
while (true) {
|
|
1782
1942
|
const last = output.at(-1);
|
|
@@ -1822,7 +1982,7 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1822
1982
|
}
|
|
1823
1983
|
converted.push({
|
|
1824
1984
|
type: "function_call_output",
|
|
1825
|
-
call_id: callId,
|
|
1985
|
+
call_id: replayCallId(callId),
|
|
1826
1986
|
output
|
|
1827
1987
|
});
|
|
1828
1988
|
}
|
|
@@ -1833,20 +1993,25 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1833
1993
|
conversionStyle,
|
|
1834
1994
|
replayContext,
|
|
1835
1995
|
shouldReplayResponsesItemIds,
|
|
1836
|
-
|
|
1996
|
+
nativeOpenAI,
|
|
1837
1997
|
resolveResponsesInstructionRole(model),
|
|
1838
1998
|
model.input.includes("image"),
|
|
1839
1999
|
options?.retainUserProvenance === true
|
|
1840
2000
|
]);
|
|
1841
2001
|
for (const msg of replayMessages) {
|
|
2002
|
+
if ("role" in msg && msg.role === "assistant" && replayPlan.itemRecovery && readOpenAIResponsesItemRecoveryAnchor(msg.providerReplay) === replayPlan.itemRecovery.anchor) pastRecoveryBoundary = true;
|
|
1842
2003
|
if (!("role" in msg)) {
|
|
1843
|
-
messages.push(msg);
|
|
2004
|
+
messages.push(...options?.mutableInput ? cloneResponsesInputForPayloadHook([msg]) : [msg]);
|
|
1844
2005
|
continue;
|
|
1845
2006
|
}
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
2007
|
+
recoveryAnchor = !pastRecoveryBoundary || msg.role === "toolResult" && recoveredCalls?.has(msg.toolCallId) ? replayPlan.itemRecovery?.anchor : void 0;
|
|
2008
|
+
if (recoveryAnchor && msg.role === "assistant") {
|
|
2009
|
+
for (const block of msg.content) if (block.type === "toolCall") recoveredCalls?.add(block.id);
|
|
2010
|
+
}
|
|
2011
|
+
let projections = responsesMessageProjections.get(msg);
|
|
2012
|
+
const reusable = immutable && !preparedRequestSuffix.has(context) && (projections || immutable.isDeeplyFrozenPlainData(msg) && (typeof msg.content === "string" || !msg.content.some((block) => block.type === "image")));
|
|
2013
|
+
const key = recoveryAnchor ? `${projectionKey}:${msgIndex}:${recoveryAnchor}` : `${projectionKey}:${msgIndex}`;
|
|
2014
|
+
let output = reusable ? projections?.get(key) : void 0;
|
|
1850
2015
|
if (!output) {
|
|
1851
2016
|
output = convertMessage(msg, msgIndex);
|
|
1852
2017
|
if (reusable) {
|
|
@@ -1875,18 +2040,41 @@ function convertResponsesMessages(model, context, allowedToolCallProviders, opti
|
|
|
1875
2040
|
function convertProviderResponsesMessages(model, context, allowedToolCallProviders, options) {
|
|
1876
2041
|
return convertResponsesMessagesWithStyle(model, context, allowedToolCallProviders, options, "provider");
|
|
1877
2042
|
}
|
|
1878
|
-
|
|
1879
|
-
|
|
2043
|
+
// packages/ai/src/transports/openai-responses-context-usage.ts
|
|
2044
|
+
const preparedInput = Symbol("responsesContextUsageInput");
|
|
2045
|
+
/** Consume admission's projection once; context-replacing transforms do not inherit it. */
|
|
2046
|
+
function takeResponsesContextUsageInput(model, context, options) {
|
|
2047
|
+
const prepared = context[preparedInput];
|
|
2048
|
+
delete context[preparedInput];
|
|
2049
|
+
if (!prepared || prepared.model !== model || prepared.messages !== context.messages || prepared.systemPrompt !== context.systemPrompt || prepared.identity.sessionId !== options.sessionId || prepared.projection !== "transport" || prepared.includeSystemPrompt !== options.includeSystemPrompt || options.replayResponsesItemIds !== true || options.replayMode !== "checkpoint" || options.retainUserProvenance || preparedRequestSuffix.has(context) || prepared.includeSystemPrompt && context.preparedSystemPrompt) return;
|
|
2050
|
+
if (prepared.itemRecovery) options.onItemRecovery?.();
|
|
2051
|
+
return options.mutableInput ? cloneResponsesInputForPayloadHook(prepared.input) : prepared.input;
|
|
2052
|
+
}
|
|
2053
|
+
const reasoningJson = /* @__PURE__ */ new WeakMap();
|
|
1880
2054
|
function contextFingerprint(input, output = []) {
|
|
1881
|
-
const reasoning = [
|
|
1882
|
-
|
|
2055
|
+
const reasoning = [];
|
|
2056
|
+
for (const item of [...input, ...output]) {
|
|
2057
|
+
if (!isRecord(item) || item.type !== "reasoning") continue;
|
|
2058
|
+
const cached = reasoningJson.get(item);
|
|
2059
|
+
if (cached !== void 0) {
|
|
2060
|
+
reasoning.push(cached);
|
|
2061
|
+
continue;
|
|
2062
|
+
}
|
|
1883
2063
|
const { id: _id, status: _status, ...content } = item;
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
})
|
|
2064
|
+
reasoning.push({
|
|
2065
|
+
content,
|
|
2066
|
+
source: getAiTransportHost().immutableData?.isDeeplyFrozenPlainData(item) ? item : void 0
|
|
2067
|
+
});
|
|
2068
|
+
}
|
|
2069
|
+
const digest = createHash("sha256").update(`{"prefix":"${responsesContinuationPrefixFingerprint(input, output)}","reasoning":[`);
|
|
2070
|
+
let separator = "";
|
|
2071
|
+
for (const item of reasoning) {
|
|
2072
|
+
const json = typeof item === "string" ? item : stableStringify(item.content);
|
|
2073
|
+
if (typeof item !== "string" && item.source) reasoningJson.set(item.source, json);
|
|
2074
|
+
digest.update(separator).update(json);
|
|
2075
|
+
separator = ",";
|
|
2076
|
+
}
|
|
2077
|
+
return digest.update("]}").digest("hex");
|
|
1890
2078
|
}
|
|
1891
2079
|
/** Bind measured usage to the admitted replay prefix, without copying its content. */
|
|
1892
2080
|
function recordResponsesContextUsage(message, model, identity, request, output, projection) {
|
|
@@ -1912,7 +2100,7 @@ function recordResponsesContextUsage(message, model, identity, request, output,
|
|
|
1912
2100
|
} });
|
|
1913
2101
|
}
|
|
1914
2102
|
/** Only matching provider input may replace the conservative local pressure estimate. */
|
|
1915
|
-
function resolveResponsesContextUsageBoundary(messages, model, identity, systemPrompt) {
|
|
2103
|
+
function resolveResponsesContextUsageBoundary(messages, model, identity, systemPrompt, requestContext) {
|
|
1916
2104
|
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
1917
2105
|
const message = messages[index];
|
|
1918
2106
|
if (!message || !isAssistant(message)) continue;
|
|
@@ -1921,12 +2109,30 @@ function resolveResponsesContextUsageBoundary(messages, model, identity, systemP
|
|
|
1921
2109
|
if (!isRecord(state) || usage?.state !== "available") continue;
|
|
1922
2110
|
const { projection, prefixHash, prefixLength, promptTokens, totalTokens, includeSystemPrompt } = state;
|
|
1923
2111
|
if (!isProviderReplayContext(state) || !providerReplayContextMatches(state, buildProviderReplayContext(model, identity)) || message.provider !== model.provider || message.api !== model.api || message.model !== model.id || projection !== "transport" && projection !== "provider" || typeof prefixHash !== "string" || typeof prefixLength !== "number" || !Number.isSafeInteger(prefixLength) || prefixLength <= 0 || promptTokens !== usage.promptTokens || totalTokens !== usage.totalTokens || !Number.isSafeInteger(usage.totalTokens) || usage.totalTokens <= 0) return;
|
|
1924
|
-
const
|
|
2112
|
+
const convert = projection === "transport" ? convertResponsesMessages : convertProviderResponsesMessages;
|
|
2113
|
+
let itemRecovery = false;
|
|
2114
|
+
const input = convert(model, {
|
|
1925
2115
|
messages: messages.filter(isProviderMessage),
|
|
1926
2116
|
systemPrompt
|
|
1927
2117
|
}, OPENAI_RESPONSES_TOOL_CALL_PROVIDERS, {
|
|
1928
2118
|
...identity,
|
|
1929
|
-
includeSystemPrompt: includeSystemPrompt === true
|
|
2119
|
+
includeSystemPrompt: includeSystemPrompt === true,
|
|
2120
|
+
onItemRecovery: () => {
|
|
2121
|
+
itemRecovery = true;
|
|
2122
|
+
}
|
|
2123
|
+
});
|
|
2124
|
+
if (requestContext) Object.defineProperty(requestContext, preparedInput, {
|
|
2125
|
+
configurable: true,
|
|
2126
|
+
value: {
|
|
2127
|
+
model,
|
|
2128
|
+
itemRecovery,
|
|
2129
|
+
messages: requestContext.messages,
|
|
2130
|
+
systemPrompt,
|
|
2131
|
+
identity,
|
|
2132
|
+
projection,
|
|
2133
|
+
includeSystemPrompt: includeSystemPrompt === true,
|
|
2134
|
+
input
|
|
2135
|
+
}
|
|
1930
2136
|
});
|
|
1931
2137
|
if (input.length < prefixLength || contextFingerprint(input.slice(0, prefixLength)) !== prefixHash) return;
|
|
1932
2138
|
return {
|
|
@@ -1942,8 +2148,7 @@ function isAssistant(message) {
|
|
|
1942
2148
|
function isProviderMessage(message) {
|
|
1943
2149
|
return message.role === "user" || message.role === "assistant" || message.role === "toolResult";
|
|
1944
2150
|
}
|
|
1945
|
-
|
|
1946
|
-
//#region packages/ai/src/transports/openai-responses-debug.ts
|
|
2151
|
+
// packages/ai/src/transports/openai-responses-debug.ts
|
|
1947
2152
|
function stringifyUnknown(value) {
|
|
1948
2153
|
if (typeof value === "string") return value;
|
|
1949
2154
|
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
@@ -2175,23 +2380,1092 @@ function observeResponsesTransportFailure(params) {
|
|
|
2175
2380
|
incompleteReason
|
|
2176
2381
|
};
|
|
2177
2382
|
}
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2383
|
+
// node_modules/.pnpm/openai@7.47.0_@aws-sdk+credential-provider-node@3.972.92_@smithy+hash-node@4.5.2_@smith_33daae30d1dc2f3ab4c7fe2f318efdad/node_modules/openai/internal/errors.mjs
|
|
2384
|
+
function isAbortError(err) {
|
|
2385
|
+
return typeof err === "object" && err !== null && ("name" in err && err.name === "AbortError" || "message" in err && String(err.message).includes("FetchRequestCanceledException"));
|
|
2386
|
+
}
|
|
2387
|
+
const castToError = (err) => {
|
|
2388
|
+
if (err instanceof Error) return err;
|
|
2389
|
+
if (typeof err === "object" && err !== null) {
|
|
2390
|
+
try {
|
|
2391
|
+
if (Object.prototype.toString.call(err) === "[object Error]") {
|
|
2392
|
+
const hasCause = "cause" in err;
|
|
2393
|
+
const error = new Error(err.message, hasCause ? { cause: err.cause } : {});
|
|
2394
|
+
if (err.stack) error.stack = err.stack;
|
|
2395
|
+
if (hasCause && !Object.prototype.hasOwnProperty.call(error, "cause")) error.cause = err.cause;
|
|
2396
|
+
if (err.name) error.name = err.name;
|
|
2397
|
+
return error;
|
|
2398
|
+
}
|
|
2399
|
+
} catch {}
|
|
2400
|
+
try {
|
|
2401
|
+
return new Error(JSON.stringify(err));
|
|
2402
|
+
} catch {}
|
|
2403
|
+
}
|
|
2404
|
+
return new Error(err);
|
|
2405
|
+
};
|
|
2406
|
+
// node_modules/.pnpm/openai@7.47.0_@aws-sdk+credential-provider-node@3.972.92_@smithy+hash-node@4.5.2_@smith_33daae30d1dc2f3ab4c7fe2f318efdad/node_modules/openai/core/error.mjs
|
|
2407
|
+
var OpenAIError = class extends Error {};
|
|
2408
|
+
var APIError = class APIError extends OpenAIError {
|
|
2409
|
+
constructor(status, error, message, headers) {
|
|
2410
|
+
super(`${APIError.makeMessage(status, error, message)}`);
|
|
2411
|
+
this.status = status;
|
|
2412
|
+
this.headers = headers;
|
|
2413
|
+
this.requestID = headers?.get("x-request-id");
|
|
2414
|
+
this.error = error;
|
|
2415
|
+
const data = error;
|
|
2416
|
+
this.code = data?.["code"];
|
|
2417
|
+
this.param = data?.["param"];
|
|
2418
|
+
this.type = data?.["type"];
|
|
2419
|
+
}
|
|
2420
|
+
static makeMessage(status, error, message) {
|
|
2421
|
+
const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
|
|
2422
|
+
if (status && msg) return `${status} ${msg}`;
|
|
2423
|
+
if (status) return `${status} status code (no body)`;
|
|
2424
|
+
if (msg) return msg;
|
|
2425
|
+
return "(no status code or body)";
|
|
2426
|
+
}
|
|
2427
|
+
static generate(status, errorResponse, message, headers) {
|
|
2428
|
+
if (!status || !headers) return new APIConnectionError({
|
|
2429
|
+
message,
|
|
2430
|
+
cause: castToError(errorResponse)
|
|
2431
|
+
});
|
|
2432
|
+
const error = errorResponse?.["error"];
|
|
2433
|
+
if (status === 400) return new BadRequestError(status, error, message, headers);
|
|
2434
|
+
if (status === 401) return new AuthenticationError(status, error, message, headers);
|
|
2435
|
+
if (status === 403) return new PermissionDeniedError(status, error, message, headers);
|
|
2436
|
+
if (status === 404) return new NotFoundError(status, error, message, headers);
|
|
2437
|
+
if (status === 409) return new ConflictError(status, error, message, headers);
|
|
2438
|
+
if (status === 422) return new UnprocessableEntityError(status, error, message, headers);
|
|
2439
|
+
if (status === 429) return new RateLimitError(status, error, message, headers);
|
|
2440
|
+
if (status >= 500) return new InternalServerError(status, error, message, headers);
|
|
2441
|
+
return new APIError(status, error, message, headers);
|
|
2442
|
+
}
|
|
2443
|
+
};
|
|
2444
|
+
var APIUserAbortError = class extends APIError {
|
|
2445
|
+
constructor({ message } = {}) {
|
|
2446
|
+
super(void 0, void 0, message || "Request was aborted.", void 0);
|
|
2447
|
+
}
|
|
2448
|
+
};
|
|
2449
|
+
var APIConnectionError = class extends APIError {
|
|
2450
|
+
constructor({ message, cause }) {
|
|
2451
|
+
super(void 0, void 0, message || "Connection error.", void 0);
|
|
2452
|
+
if (cause) this.cause = cause;
|
|
2453
|
+
}
|
|
2454
|
+
};
|
|
2455
|
+
var APIConnectionTimeoutError = class extends APIConnectionError {
|
|
2456
|
+
constructor({ message } = {}) {
|
|
2457
|
+
super({ message: message ?? "Request timed out." });
|
|
2458
|
+
}
|
|
2459
|
+
};
|
|
2460
|
+
var BadRequestError = class extends APIError {};
|
|
2461
|
+
var AuthenticationError = class extends APIError {};
|
|
2462
|
+
var PermissionDeniedError = class extends APIError {};
|
|
2463
|
+
var NotFoundError = class extends APIError {};
|
|
2464
|
+
var ConflictError = class extends APIError {};
|
|
2465
|
+
var UnprocessableEntityError = class extends APIError {};
|
|
2466
|
+
var RateLimitError = class extends APIError {};
|
|
2467
|
+
var InternalServerError = class extends APIError {};
|
|
2468
|
+
var LengthFinishReasonError = class extends OpenAIError {
|
|
2469
|
+
constructor() {
|
|
2470
|
+
super(`Could not parse response content as the length limit was reached`);
|
|
2471
|
+
}
|
|
2472
|
+
};
|
|
2473
|
+
var ContentFilterFinishReasonError = class extends OpenAIError {
|
|
2474
|
+
constructor() {
|
|
2475
|
+
super(`Could not parse response content as the request was rejected by the content filter`);
|
|
2476
|
+
}
|
|
2477
|
+
};
|
|
2478
|
+
var InvalidWebhookSignatureError = class extends Error {
|
|
2479
|
+
constructor(message) {
|
|
2480
|
+
super(message);
|
|
2481
|
+
}
|
|
2482
|
+
};
|
|
2483
|
+
/**
|
|
2484
|
+
* Error thrown by the API server during OAuth token exchange.
|
|
2485
|
+
* Can have status codes 400, 401, or 403.
|
|
2486
|
+
* Other status codes from OAuth endpoints are raised as normal APIError types.
|
|
2487
|
+
*/
|
|
2488
|
+
var OAuthError = class extends APIError {
|
|
2489
|
+
constructor(status, error, headers) {
|
|
2490
|
+
let finalMessage = "OAuth2 authentication error";
|
|
2491
|
+
let error_code = void 0;
|
|
2492
|
+
if (error && typeof error === "object") {
|
|
2493
|
+
const errorData = error;
|
|
2494
|
+
error_code = errorData["error"];
|
|
2495
|
+
const description = errorData["error_description"];
|
|
2496
|
+
if (description && typeof description === "string") finalMessage = description;
|
|
2497
|
+
else if (error_code) finalMessage = error_code;
|
|
2498
|
+
}
|
|
2499
|
+
super(status, error, finalMessage, headers);
|
|
2500
|
+
this.error_code = error_code;
|
|
2501
|
+
}
|
|
2502
|
+
};
|
|
2503
|
+
var SubjectTokenProviderError = class extends OpenAIError {
|
|
2504
|
+
constructor(message, provider, cause) {
|
|
2505
|
+
super(message);
|
|
2506
|
+
this.provider = provider;
|
|
2507
|
+
this.cause = cause;
|
|
2508
|
+
}
|
|
2509
|
+
};
|
|
2510
|
+
// node_modules/.pnpm/openai@7.47.0_@aws-sdk+credential-provider-node@3.972.92_@smithy+hash-node@4.5.2_@smith_33daae30d1dc2f3ab4c7fe2f318efdad/node_modules/openai/internal/tslib.mjs
|
|
2511
|
+
function __classPrivateFieldSet(receiver, state, value, kind, f) {
|
|
2512
|
+
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
2513
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
2514
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
2515
|
+
return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
|
|
2516
|
+
}
|
|
2517
|
+
function __classPrivateFieldGet(receiver, state, kind, f) {
|
|
2518
|
+
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
2519
|
+
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
2520
|
+
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
2521
|
+
}
|
|
2522
|
+
// node_modules/.pnpm/openai@7.47.0_@aws-sdk+credential-provider-node@3.972.92_@smithy+hash-node@4.5.2_@smith_33daae30d1dc2f3ab4c7fe2f318efdad/node_modules/openai/internal/shims.mjs
|
|
2523
|
+
/**
|
|
2524
|
+
* This module provides internal shims and utility functions for environments where certain Node.js or global types may not be available.
|
|
2525
|
+
*
|
|
2526
|
+
* These are used to ensure we can provide a consistent behaviour between different JavaScript environments and good error
|
|
2527
|
+
* messages in cases where an environment isn't fully supported.
|
|
2528
|
+
*/
|
|
2529
|
+
function getDefaultFetch() {
|
|
2530
|
+
if (typeof fetch !== "undefined") return fetch;
|
|
2531
|
+
throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`");
|
|
2532
|
+
}
|
|
2533
|
+
function makeReadableStream(...args) {
|
|
2534
|
+
const ReadableStream = globalThis.ReadableStream;
|
|
2535
|
+
if (typeof ReadableStream === "undefined") throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");
|
|
2536
|
+
return new ReadableStream(...args);
|
|
2537
|
+
}
|
|
2538
|
+
function ReadableStreamFrom(iterable, strategy) {
|
|
2539
|
+
let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
|
|
2540
|
+
return makeReadableStream({
|
|
2541
|
+
start() {},
|
|
2542
|
+
async pull(controller) {
|
|
2543
|
+
const { done, value } = await iter.next();
|
|
2544
|
+
if (done) controller.close();
|
|
2545
|
+
else controller.enqueue(value);
|
|
2546
|
+
},
|
|
2547
|
+
async cancel() {
|
|
2548
|
+
await iter.return?.();
|
|
2549
|
+
}
|
|
2550
|
+
}, strategy);
|
|
2551
|
+
}
|
|
2552
|
+
/**
|
|
2553
|
+
* Most browsers don't yet have async iterable support for ReadableStream,
|
|
2554
|
+
* and Node has a very different way of reading bytes from its "ReadableStream".
|
|
2555
|
+
*
|
|
2556
|
+
* This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
|
|
2557
|
+
*/
|
|
2558
|
+
function ReadableStreamToAsyncIterable(stream) {
|
|
2559
|
+
if (stream[Symbol.asyncIterator]) return stream;
|
|
2560
|
+
const reader = stream.getReader();
|
|
2561
|
+
return {
|
|
2562
|
+
async next() {
|
|
2563
|
+
try {
|
|
2564
|
+
const result = await reader.read();
|
|
2565
|
+
if (result?.done) reader.releaseLock();
|
|
2566
|
+
return result;
|
|
2567
|
+
} catch (e) {
|
|
2568
|
+
reader.releaseLock();
|
|
2569
|
+
throw e;
|
|
2570
|
+
}
|
|
2571
|
+
},
|
|
2572
|
+
async return() {
|
|
2573
|
+
const cancelPromise = reader.cancel();
|
|
2574
|
+
reader.releaseLock();
|
|
2575
|
+
await cancelPromise;
|
|
2576
|
+
return {
|
|
2577
|
+
done: true,
|
|
2578
|
+
value: void 0
|
|
2579
|
+
};
|
|
2580
|
+
},
|
|
2581
|
+
[Symbol.asyncIterator]() {
|
|
2582
|
+
return this;
|
|
2583
|
+
}
|
|
2584
|
+
};
|
|
2585
|
+
}
|
|
2586
|
+
/**
|
|
2587
|
+
* Cancels a ReadableStream we don't need to consume.
|
|
2588
|
+
* See https://undici.nodejs.org/#/?id=garbage-collection
|
|
2589
|
+
*/
|
|
2590
|
+
async function CancelReadableStream(stream) {
|
|
2591
|
+
if (stream === null || typeof stream !== "object") return;
|
|
2592
|
+
if (stream[Symbol.asyncIterator]) {
|
|
2593
|
+
await stream[Symbol.asyncIterator]().return?.();
|
|
2594
|
+
return;
|
|
2595
|
+
}
|
|
2596
|
+
const reader = stream.getReader();
|
|
2597
|
+
const cancelPromise = reader.cancel();
|
|
2598
|
+
reader.releaseLock();
|
|
2599
|
+
await cancelPromise;
|
|
2600
|
+
}
|
|
2601
|
+
// node_modules/.pnpm/openai@7.47.0_@aws-sdk+credential-provider-node@3.972.92_@smithy+hash-node@4.5.2_@smith_33daae30d1dc2f3ab4c7fe2f318efdad/node_modules/openai/internal/utils/bytes.mjs
|
|
2602
|
+
let encodeUTF8_;
|
|
2603
|
+
/** Encodes text as UTF-8 bytes, reusing the platform encoder after its first call. */
|
|
2604
|
+
function encodeUTF8(str) {
|
|
2605
|
+
let encoder;
|
|
2606
|
+
return (encodeUTF8_ ?? (encoder = new globalThis.TextEncoder(), encodeUTF8_ = encoder.encode.bind(encoder)))(str);
|
|
2607
|
+
}
|
|
2608
|
+
let decodeUTF8_;
|
|
2609
|
+
/** Decodes UTF-8 bytes as text, reusing the platform decoder after its first call. */
|
|
2610
|
+
function decodeUTF8(bytes) {
|
|
2611
|
+
let decoder;
|
|
2612
|
+
return (decodeUTF8_ ?? (decoder = new globalThis.TextDecoder(), decodeUTF8_ = decoder.decode.bind(decoder)))(bytes);
|
|
2613
|
+
}
|
|
2614
|
+
// node_modules/.pnpm/openai@7.47.0_@aws-sdk+credential-provider-node@3.972.92_@smithy+hash-node@4.5.2_@smith_33daae30d1dc2f3ab4c7fe2f318efdad/node_modules/openai/internal/decoders/line.mjs
|
|
2615
|
+
var _LineDecoder_instances;
|
|
2616
|
+
var _LineDecoder_buffer;
|
|
2617
|
+
var _LineDecoder_start;
|
|
2618
|
+
var _LineDecoder_end;
|
|
2619
|
+
var _LineDecoder_searchIndex;
|
|
2620
|
+
var _LineDecoder_skipLeadingLF;
|
|
2621
|
+
var _LineDecoder_append;
|
|
2622
|
+
/** Maximum backing-buffer capacity retained when completed lines leave little active data. */
|
|
2623
|
+
const MAX_RETAINED_BUFFER_BYTES = 65536;
|
|
2624
|
+
/**
|
|
2625
|
+
* Incrementally decodes UTF-8 text into lines without losing partial characters
|
|
2626
|
+
* or newline sequences that span multiple chunks.
|
|
2627
|
+
*
|
|
2628
|
+
* Supports `\n`, `\r`, and `\r\n` line endings. Call {@link flush} after the
|
|
2629
|
+
* final chunk to emit a trailing line that does not end with a newline.
|
|
2630
|
+
*
|
|
2631
|
+
* Based on the line decoder used by the Python `httpx` project:
|
|
2632
|
+
* https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258
|
|
2633
|
+
*/
|
|
2634
|
+
var LineDecoder = class {
|
|
2635
|
+
/** Creates a decoder with no buffered bytes or pending newline continuation. */
|
|
2636
|
+
constructor() {
|
|
2637
|
+
_LineDecoder_instances.add(this);
|
|
2638
|
+
_LineDecoder_buffer.set(this, void 0);
|
|
2639
|
+
_LineDecoder_start.set(this, void 0);
|
|
2640
|
+
_LineDecoder_end.set(this, void 0);
|
|
2641
|
+
_LineDecoder_searchIndex.set(this, void 0);
|
|
2642
|
+
_LineDecoder_skipLeadingLF.set(this, void 0);
|
|
2643
|
+
__classPrivateFieldSet(this, _LineDecoder_buffer, /* @__PURE__ */ new Uint8Array(), "f");
|
|
2644
|
+
__classPrivateFieldSet(this, _LineDecoder_start, 0, "f");
|
|
2645
|
+
__classPrivateFieldSet(this, _LineDecoder_end, 0, "f");
|
|
2646
|
+
__classPrivateFieldSet(this, _LineDecoder_searchIndex, 0, "f");
|
|
2647
|
+
__classPrivateFieldSet(this, _LineDecoder_skipLeadingLF, false, "f");
|
|
2648
|
+
}
|
|
2649
|
+
/**
|
|
2650
|
+
* Appends a text or UTF-8 byte chunk and returns every newly completed line.
|
|
2651
|
+
*
|
|
2652
|
+
* Incomplete lines remain buffered for the next call. A trailing `\r`
|
|
2653
|
+
* completes its line immediately, and a following `\n` is consumed as its
|
|
2654
|
+
* continuation. `null` and `undefined` are ignored and do not flush buffered
|
|
2655
|
+
* content.
|
|
2656
|
+
*/
|
|
2657
|
+
decode(chunk) {
|
|
2658
|
+
if (chunk == null) return [];
|
|
2659
|
+
let binaryChunk;
|
|
2660
|
+
if (chunk instanceof ArrayBuffer) binaryChunk = new Uint8Array(chunk);
|
|
2661
|
+
else if (typeof chunk === "string") binaryChunk = encodeUTF8(chunk);
|
|
2662
|
+
else binaryChunk = chunk;
|
|
2663
|
+
if (binaryChunk.length === 0) return [];
|
|
2664
|
+
if (__classPrivateFieldGet(this, _LineDecoder_skipLeadingLF, "f")) {
|
|
2665
|
+
__classPrivateFieldSet(this, _LineDecoder_skipLeadingLF, false, "f");
|
|
2666
|
+
if (binaryChunk[0] === 10) binaryChunk = binaryChunk.subarray(1);
|
|
2667
|
+
if (binaryChunk.length === 0) return [];
|
|
2668
|
+
}
|
|
2669
|
+
__classPrivateFieldGet(this, _LineDecoder_instances, "m", _LineDecoder_append).call(this, binaryChunk);
|
|
2670
|
+
const lines = [];
|
|
2671
|
+
let patternIndex;
|
|
2672
|
+
while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_searchIndex, "f"), __classPrivateFieldGet(this, _LineDecoder_end, "f"))) != null) {
|
|
2673
|
+
const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_start, "f"), patternIndex.preceding));
|
|
2674
|
+
lines.push(line);
|
|
2675
|
+
__classPrivateFieldSet(this, _LineDecoder_start, patternIndex.index, "f");
|
|
2676
|
+
if (patternIndex.carriage) {
|
|
2677
|
+
if (__classPrivateFieldGet(this, _LineDecoder_start, "f") < __classPrivateFieldGet(this, _LineDecoder_end, "f") && __classPrivateFieldGet(this, _LineDecoder_buffer, "f")[__classPrivateFieldGet(this, _LineDecoder_start, "f")] === 10) __classPrivateFieldSet(this, _LineDecoder_start, __classPrivateFieldGet(this, _LineDecoder_start, "f") + 1, "f");
|
|
2678
|
+
else if (__classPrivateFieldGet(this, _LineDecoder_start, "f") === __classPrivateFieldGet(this, _LineDecoder_end, "f")) __classPrivateFieldSet(this, _LineDecoder_skipLeadingLF, true, "f");
|
|
2679
|
+
}
|
|
2680
|
+
__classPrivateFieldSet(this, _LineDecoder_searchIndex, __classPrivateFieldGet(this, _LineDecoder_start, "f"), "f");
|
|
2681
|
+
}
|
|
2682
|
+
__classPrivateFieldSet(this, _LineDecoder_searchIndex, __classPrivateFieldGet(this, _LineDecoder_end, "f"), "f");
|
|
2683
|
+
if (__classPrivateFieldGet(this, _LineDecoder_start, "f") === __classPrivateFieldGet(this, _LineDecoder_end, "f")) {
|
|
2684
|
+
__classPrivateFieldSet(this, _LineDecoder_start, 0, "f");
|
|
2685
|
+
__classPrivateFieldSet(this, _LineDecoder_end, 0, "f");
|
|
2686
|
+
__classPrivateFieldSet(this, _LineDecoder_searchIndex, 0, "f");
|
|
2687
|
+
if (__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length > MAX_RETAINED_BUFFER_BYTES) __classPrivateFieldSet(this, _LineDecoder_buffer, /* @__PURE__ */ new Uint8Array(), "f");
|
|
2688
|
+
} else if (lines.length > 0 && __classPrivateFieldGet(this, _LineDecoder_buffer, "f").length > MAX_RETAINED_BUFFER_BYTES) {
|
|
2689
|
+
const length = __classPrivateFieldGet(this, _LineDecoder_end, "f") - __classPrivateFieldGet(this, _LineDecoder_start, "f");
|
|
2690
|
+
if (length <= MAX_RETAINED_BUFFER_BYTES || __classPrivateFieldGet(this, _LineDecoder_buffer, "f").length > length * 4) {
|
|
2691
|
+
const capacity = length <= MAX_RETAINED_BUFFER_BYTES ? Math.min(Math.max(length * 2, 256), MAX_RETAINED_BUFFER_BYTES) : length * 2;
|
|
2692
|
+
const buffer = new Uint8Array(capacity);
|
|
2693
|
+
buffer.set(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_start, "f"), __classPrivateFieldGet(this, _LineDecoder_end, "f")));
|
|
2694
|
+
__classPrivateFieldSet(this, _LineDecoder_buffer, buffer, "f");
|
|
2695
|
+
__classPrivateFieldSet(this, _LineDecoder_start, 0, "f");
|
|
2696
|
+
__classPrivateFieldSet(this, _LineDecoder_end, length, "f");
|
|
2697
|
+
__classPrivateFieldSet(this, _LineDecoder_searchIndex, length, "f");
|
|
2698
|
+
}
|
|
2699
|
+
}
|
|
2700
|
+
return lines;
|
|
2701
|
+
}
|
|
2702
|
+
/** Emits the remaining unterminated line, or returns an empty array when idle. */
|
|
2703
|
+
flush() {
|
|
2704
|
+
__classPrivateFieldSet(this, _LineDecoder_skipLeadingLF, false, "f");
|
|
2705
|
+
if (__classPrivateFieldGet(this, _LineDecoder_start, "f") === __classPrivateFieldGet(this, _LineDecoder_end, "f")) return [];
|
|
2706
|
+
return this.decode("\n");
|
|
2707
|
+
}
|
|
2708
|
+
};
|
|
2709
|
+
_LineDecoder_buffer = /* @__PURE__ */ new WeakMap(), _LineDecoder_start = /* @__PURE__ */ new WeakMap(), _LineDecoder_end = /* @__PURE__ */ new WeakMap(), _LineDecoder_searchIndex = /* @__PURE__ */ new WeakMap(), _LineDecoder_skipLeadingLF = /* @__PURE__ */ new WeakMap(), _LineDecoder_instances = /* @__PURE__ */ new WeakSet(), _LineDecoder_append = function _LineDecoder_append(chunk) {
|
|
2710
|
+
if (__classPrivateFieldGet(this, _LineDecoder_end, "f") + chunk.length > __classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) {
|
|
2711
|
+
const length = __classPrivateFieldGet(this, _LineDecoder_end, "f") - __classPrivateFieldGet(this, _LineDecoder_start, "f");
|
|
2712
|
+
if (__classPrivateFieldGet(this, _LineDecoder_start, "f") >= __classPrivateFieldGet(this, _LineDecoder_buffer, "f").length / 2 && length + chunk.length <= __classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) __classPrivateFieldGet(this, _LineDecoder_buffer, "f").copyWithin(0, __classPrivateFieldGet(this, _LineDecoder_start, "f"), __classPrivateFieldGet(this, _LineDecoder_end, "f"));
|
|
2713
|
+
else {
|
|
2714
|
+
const capacity = Math.max(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length * 2, length + chunk.length, 256);
|
|
2715
|
+
const buffer = new Uint8Array(capacity);
|
|
2716
|
+
buffer.set(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_start, "f"), __classPrivateFieldGet(this, _LineDecoder_end, "f")));
|
|
2717
|
+
__classPrivateFieldSet(this, _LineDecoder_buffer, buffer, "f");
|
|
2718
|
+
}
|
|
2719
|
+
__classPrivateFieldSet(this, _LineDecoder_searchIndex, __classPrivateFieldGet(this, _LineDecoder_searchIndex, "f") - __classPrivateFieldGet(this, _LineDecoder_start, "f"), "f");
|
|
2720
|
+
__classPrivateFieldSet(this, _LineDecoder_end, length, "f");
|
|
2721
|
+
__classPrivateFieldSet(this, _LineDecoder_start, 0, "f");
|
|
2722
|
+
}
|
|
2723
|
+
__classPrivateFieldGet(this, _LineDecoder_buffer, "f").set(chunk, __classPrivateFieldGet(this, _LineDecoder_end, "f"));
|
|
2724
|
+
__classPrivateFieldSet(this, _LineDecoder_end, __classPrivateFieldGet(this, _LineDecoder_end, "f") + chunk.length, "f");
|
|
2725
|
+
};
|
|
2726
|
+
/** Individual characters recognized as possible line terminators. */
|
|
2727
|
+
LineDecoder.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]);
|
|
2728
|
+
/** Matches complete CRLF terminators as well as standalone CR and LF characters. */
|
|
2729
|
+
LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
|
|
2730
|
+
/**
|
|
2731
|
+
* Searches the active buffer range for the next CR or LF byte and returns its
|
|
2732
|
+
* zero-based position, the position immediately after it, and whether the byte
|
|
2733
|
+
* was a carriage return. Returns `null` when the range contains no newline byte.
|
|
2734
|
+
*
|
|
2735
|
+
* ```ts
|
|
2736
|
+
* findNewlineIndex(new TextEncoder().encode('abc\ndef'), 0, 7)
|
|
2737
|
+
* // => { preceding: 3, index: 4, carriage: false }
|
|
2738
|
+
* ```
|
|
2739
|
+
*/
|
|
2740
|
+
function findNewlineIndex(buffer, start, end) {
|
|
2741
|
+
const newline = 10;
|
|
2742
|
+
const carriage = 13;
|
|
2743
|
+
for (let i = start; i < end; i++) {
|
|
2744
|
+
if (buffer[i] === newline) return {
|
|
2745
|
+
preceding: i,
|
|
2746
|
+
index: i + 1,
|
|
2747
|
+
carriage: false
|
|
2748
|
+
};
|
|
2749
|
+
if (buffer[i] === carriage) return {
|
|
2750
|
+
preceding: i,
|
|
2751
|
+
index: i + 1,
|
|
2752
|
+
carriage: true
|
|
2753
|
+
};
|
|
2754
|
+
}
|
|
2755
|
+
return null;
|
|
2756
|
+
}
|
|
2757
|
+
/**
|
|
2758
|
+
* Finds the first blank-line separator used to delimit streamed event records.
|
|
2759
|
+
*
|
|
2760
|
+
* @returns The byte offset immediately after the first pair of consecutive
|
|
2761
|
+
* line endings, or `-1` when the buffer contains no complete separator.
|
|
2762
|
+
*/
|
|
2763
|
+
function findDoubleNewlineIndex(buffer) {
|
|
2764
|
+
for (let i = 0; i < buffer.length - 1; i++) {
|
|
2765
|
+
const firstEndingLength = lineEndingLength(buffer, i);
|
|
2766
|
+
if (firstEndingLength > 0) {
|
|
2767
|
+
const secondEndingIndex = i + firstEndingLength;
|
|
2768
|
+
const secondEndingLength = lineEndingLength(buffer, secondEndingIndex);
|
|
2769
|
+
if (secondEndingLength > 0) return secondEndingIndex + secondEndingLength;
|
|
2770
|
+
}
|
|
2771
|
+
}
|
|
2772
|
+
return -1;
|
|
2773
|
+
}
|
|
2774
|
+
function lineEndingLength(buffer, index) {
|
|
2775
|
+
const newline = 10;
|
|
2776
|
+
const carriage = 13;
|
|
2777
|
+
if (buffer[index] === newline) return 1;
|
|
2778
|
+
if (buffer[index] === carriage) return buffer[index + 1] === newline ? 2 : 1;
|
|
2779
|
+
return 0;
|
|
2780
|
+
}
|
|
2781
|
+
// node_modules/.pnpm/openai@7.47.0_@aws-sdk+credential-provider-node@3.972.92_@smithy+hash-node@4.5.2_@smith_33daae30d1dc2f3ab4c7fe2f318efdad/node_modules/openai/internal/utils/values.mjs
|
|
2782
|
+
const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
|
|
2783
|
+
const isAbsoluteURL = (url) => {
|
|
2784
|
+
return startsWithSchemeRegexp.test(url);
|
|
2785
|
+
};
|
|
2786
|
+
let isArray = (val) => (isArray = Array.isArray, isArray(val));
|
|
2787
|
+
let isReadonlyArray = isArray;
|
|
2788
|
+
/** Returns an object if the given value isn't an object, otherwise returns as-is */
|
|
2789
|
+
function maybeObj(x) {
|
|
2790
|
+
if (typeof x !== "object") return {};
|
|
2791
|
+
return x ?? {};
|
|
2792
|
+
}
|
|
2793
|
+
function isEmptyObj(obj) {
|
|
2794
|
+
if (!obj) return true;
|
|
2795
|
+
for (const _k in obj) return false;
|
|
2796
|
+
return true;
|
|
2797
|
+
}
|
|
2798
|
+
function hasOwn(obj, key) {
|
|
2799
|
+
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
2800
|
+
}
|
|
2801
|
+
function isObj(obj) {
|
|
2802
|
+
return obj != null && typeof obj === "object" && !Array.isArray(obj);
|
|
2803
|
+
}
|
|
2804
|
+
const validatePositiveInteger = (name, n) => {
|
|
2805
|
+
if (typeof n !== "number" || !Number.isInteger(n)) throw new OpenAIError(`${name} must be an integer`);
|
|
2806
|
+
if (n < 0) throw new OpenAIError(`${name} must be a positive integer`);
|
|
2807
|
+
return n;
|
|
2808
|
+
};
|
|
2809
|
+
const safeJSON = (text) => {
|
|
2810
|
+
try {
|
|
2811
|
+
return JSON.parse(text);
|
|
2812
|
+
} catch (err) {
|
|
2813
|
+
return;
|
|
2814
|
+
}
|
|
2815
|
+
};
|
|
2816
|
+
// node_modules/.pnpm/openai@7.47.0_@aws-sdk+credential-provider-node@3.972.92_@smithy+hash-node@4.5.2_@smith_33daae30d1dc2f3ab4c7fe2f318efdad/node_modules/openai/internal/utils/log.mjs
|
|
2817
|
+
const levelNumbers = {
|
|
2818
|
+
off: 0,
|
|
2819
|
+
error: 200,
|
|
2820
|
+
warn: 300,
|
|
2821
|
+
info: 400,
|
|
2822
|
+
debug: 500
|
|
2823
|
+
};
|
|
2824
|
+
const parseLogLevel = (maybeLevel, sourceName, client) => {
|
|
2825
|
+
if (!maybeLevel) return;
|
|
2826
|
+
if (hasOwn(levelNumbers, maybeLevel)) return maybeLevel;
|
|
2827
|
+
loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);
|
|
2828
|
+
};
|
|
2829
|
+
function noop() {}
|
|
2830
|
+
function makeLogFn(fnLevel, logger, logLevel) {
|
|
2831
|
+
if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) return noop;
|
|
2832
|
+
else return logger[fnLevel].bind(logger);
|
|
2833
|
+
}
|
|
2834
|
+
const noopLogger = {
|
|
2835
|
+
error: noop,
|
|
2836
|
+
warn: noop,
|
|
2837
|
+
info: noop,
|
|
2838
|
+
debug: noop
|
|
2839
|
+
};
|
|
2840
|
+
let cachedLoggers = /* @__PURE__ */ new WeakMap();
|
|
2841
|
+
function loggerFor(client) {
|
|
2842
|
+
const logger = client.logger;
|
|
2843
|
+
const logLevel = client.logLevel ?? "off";
|
|
2844
|
+
if (!logger) return noopLogger;
|
|
2845
|
+
const cachedLogger = cachedLoggers.get(logger);
|
|
2846
|
+
if (cachedLogger && cachedLogger[0] === logLevel) return cachedLogger[1];
|
|
2847
|
+
const levelLogger = {
|
|
2848
|
+
error: makeLogFn("error", logger, logLevel),
|
|
2849
|
+
warn: makeLogFn("warn", logger, logLevel),
|
|
2850
|
+
info: makeLogFn("info", logger, logLevel),
|
|
2851
|
+
debug: makeLogFn("debug", logger, logLevel)
|
|
2852
|
+
};
|
|
2853
|
+
cachedLoggers.set(logger, [logLevel, levelLogger]);
|
|
2854
|
+
return levelLogger;
|
|
2855
|
+
}
|
|
2856
|
+
const sensitiveQueryNames = /* @__PURE__ */ new Set([
|
|
2857
|
+
"apikey",
|
|
2858
|
+
"accesstoken",
|
|
2859
|
+
"refreshtoken",
|
|
2860
|
+
"sessiontoken",
|
|
2861
|
+
"sessionid",
|
|
2862
|
+
"idtoken",
|
|
2863
|
+
"authtoken",
|
|
2864
|
+
"authorization",
|
|
2865
|
+
"token",
|
|
2866
|
+
"password",
|
|
2867
|
+
"clientsecret",
|
|
2868
|
+
"signingsecret",
|
|
2869
|
+
"sig",
|
|
2870
|
+
"signature",
|
|
2871
|
+
"xgoogsignature",
|
|
2872
|
+
"xgoogcredential",
|
|
2873
|
+
"xamzsecuritytoken",
|
|
2874
|
+
"xamzsignature",
|
|
2875
|
+
"xamzcredential"
|
|
2184
2876
|
]);
|
|
2877
|
+
/** Recognizes credential-bearing query names across ordinary and provider authentication. */
|
|
2878
|
+
function isSensitiveQueryParameter(name) {
|
|
2879
|
+
const normalized = name.toLowerCase().replace(/[-_]/gu, "");
|
|
2880
|
+
return sensitiveQueryNames.has(normalized) || sensitiveQueryNames.has(normalized.replace(/^x/u, ""));
|
|
2881
|
+
}
|
|
2882
|
+
const sensitiveHeaderNames = /* @__PURE__ */ new Set([
|
|
2883
|
+
"authorization",
|
|
2884
|
+
"proxy-authorization",
|
|
2885
|
+
"api-key",
|
|
2886
|
+
"x-api-key",
|
|
2887
|
+
"x-amz-security-token",
|
|
2888
|
+
"cookie",
|
|
2889
|
+
"set-cookie",
|
|
2890
|
+
"x-session-token",
|
|
2891
|
+
"x-session-id",
|
|
2892
|
+
"x-auth-token",
|
|
2893
|
+
"x-id-token"
|
|
2894
|
+
]);
|
|
2895
|
+
/** Recognizes credential-bearing request headers across provider and workload authentication. */
|
|
2896
|
+
function isSensitiveHeader(name) {
|
|
2897
|
+
return sensitiveHeaderNames.has(name.toLowerCase().replace(/_/gu, "-")) || isSensitiveQueryParameter(name);
|
|
2898
|
+
}
|
|
2899
|
+
/** Removes credential-valued query parameters before a request URL reaches any logger. */
|
|
2900
|
+
function redactURL(value) {
|
|
2901
|
+
const url = new URL(value);
|
|
2902
|
+
url.username = "";
|
|
2903
|
+
url.password = "";
|
|
2904
|
+
url.hash = "";
|
|
2905
|
+
for (const name of url.searchParams.keys()) if (isSensitiveQueryParameter(name)) url.searchParams.set(name, "***");
|
|
2906
|
+
return url.href;
|
|
2907
|
+
}
|
|
2908
|
+
const formatRequestDetails = (details) => {
|
|
2909
|
+
if (details.options) {
|
|
2910
|
+
details.options = { ...details.options };
|
|
2911
|
+
delete details.options["headers"];
|
|
2912
|
+
if (details.options.path) {
|
|
2913
|
+
const path = details.options.path;
|
|
2914
|
+
const redacted = new URL(redactURL(new URL(path, "https://redacted.invalid").href));
|
|
2915
|
+
details.options.path = redacted.origin === "https://redacted.invalid" ? `${path.startsWith("/") ? "/" : ""}${redacted.pathname.slice(1)}${redacted.search}` : redacted.href;
|
|
2916
|
+
}
|
|
2917
|
+
if (details.options.query) details.options.query = Object.fromEntries(Object.entries(details.options.query).map(([name, value]) => [name, isSensitiveQueryParameter(name) ? "***" : value]));
|
|
2918
|
+
}
|
|
2919
|
+
if (details.url) details.url = redactURL(details.url);
|
|
2920
|
+
if (details.headers) details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [name, isSensitiveHeader(name) ? "***" : value]));
|
|
2921
|
+
if ("retryOfRequestLogID" in details) {
|
|
2922
|
+
if (details.retryOfRequestLogID) details.retryOf = details.retryOfRequestLogID;
|
|
2923
|
+
delete details.retryOfRequestLogID;
|
|
2924
|
+
}
|
|
2925
|
+
return details;
|
|
2926
|
+
};
|
|
2927
|
+
// node_modules/.pnpm/openai@7.47.0_@aws-sdk+credential-provider-node@3.972.92_@smithy+hash-node@4.5.2_@smith_33daae30d1dc2f3ab4c7fe2f318efdad/node_modules/openai/core/streaming.mjs
|
|
2928
|
+
var _Stream_instances;
|
|
2929
|
+
var _Stream_client;
|
|
2930
|
+
var _Stream_isTeeBranch;
|
|
2931
|
+
var _Stream_cancelIterator;
|
|
2932
|
+
function isTransportAbortError(error) {
|
|
2933
|
+
return !(error instanceof APIError) && isAbortError(error);
|
|
2934
|
+
}
|
|
2935
|
+
function createStreamTeeQueue() {
|
|
2936
|
+
let entries = [];
|
|
2937
|
+
let head = 0;
|
|
2938
|
+
let canceled = false;
|
|
2939
|
+
return {
|
|
2940
|
+
get length() {
|
|
2941
|
+
return entries.length - head;
|
|
2942
|
+
},
|
|
2943
|
+
get canceled() {
|
|
2944
|
+
return canceled;
|
|
2945
|
+
},
|
|
2946
|
+
enqueue(value) {
|
|
2947
|
+
if (!canceled) entries.push(value);
|
|
2948
|
+
},
|
|
2949
|
+
dequeue() {
|
|
2950
|
+
if (head === entries.length) return;
|
|
2951
|
+
const value = entries[head];
|
|
2952
|
+
entries[head] = void 0;
|
|
2953
|
+
head += 1;
|
|
2954
|
+
if (head === entries.length) {
|
|
2955
|
+
entries = [];
|
|
2956
|
+
head = 0;
|
|
2957
|
+
} else if (head >= 1024 && head * 2 >= entries.length) {
|
|
2958
|
+
entries = entries.slice(head);
|
|
2959
|
+
head = 0;
|
|
2960
|
+
}
|
|
2961
|
+
return value;
|
|
2962
|
+
},
|
|
2963
|
+
cancel() {
|
|
2964
|
+
canceled = true;
|
|
2965
|
+
entries.length = 0;
|
|
2966
|
+
head = 0;
|
|
2967
|
+
}
|
|
2968
|
+
};
|
|
2969
|
+
}
|
|
2970
|
+
/**
|
|
2971
|
+
* A single-consumption asynchronous API response stream.
|
|
2972
|
+
*
|
|
2973
|
+
* Use {@link Stream.tee} when two consumers need the same events. Breaking out of
|
|
2974
|
+
* a response-backed stream early aborts its request; branches created by `tee()`
|
|
2975
|
+
* instead share {@link Stream.controller} for explicit cancellation.
|
|
2976
|
+
*/
|
|
2977
|
+
var Stream = class Stream {
|
|
2978
|
+
/** Wraps an asynchronous event iterator and the controller that owns its request. */
|
|
2979
|
+
constructor(iterator, controller, client) {
|
|
2980
|
+
_Stream_instances.add(this);
|
|
2981
|
+
_Stream_client.set(this, void 0);
|
|
2982
|
+
_Stream_isTeeBranch.set(this, false);
|
|
2983
|
+
this.iterator = iterator;
|
|
2984
|
+
this.controller = controller;
|
|
2985
|
+
__classPrivateFieldSet(this, _Stream_client, client, "f");
|
|
2986
|
+
}
|
|
2987
|
+
/**
|
|
2988
|
+
* Decodes an SSE response into parsed JSON events.
|
|
2989
|
+
*
|
|
2990
|
+
* The resulting stream can be consumed only once, ignores events after `[DONE]`, and
|
|
2991
|
+
* surfaces API error payloads as `APIError` instances. When
|
|
2992
|
+
* `synthesizeEventData` is enabled, each item also includes its SSE event name.
|
|
2993
|
+
*/
|
|
2994
|
+
static fromSSEResponse(response, controller, client, synthesizeEventData) {
|
|
2995
|
+
let consumed = false;
|
|
2996
|
+
const logger = client ? loggerFor(client) : console;
|
|
2997
|
+
async function* iterator() {
|
|
2998
|
+
if (consumed) throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
|
|
2999
|
+
consumed = true;
|
|
3000
|
+
let done = false;
|
|
3001
|
+
let receivedCompletionSentinel = false;
|
|
3002
|
+
const messages = _iterSSEMessages(response, controller);
|
|
3003
|
+
const closeMessages = messages.return.bind(messages);
|
|
3004
|
+
messages.return = (value) => {
|
|
3005
|
+
if (!receivedCompletionSentinel) controller.abort();
|
|
3006
|
+
return closeMessages(value);
|
|
3007
|
+
};
|
|
3008
|
+
try {
|
|
3009
|
+
for await (const sse of messages) {
|
|
3010
|
+
if (sse.data === "[DONE]") {
|
|
3011
|
+
receivedCompletionSentinel = true;
|
|
3012
|
+
break;
|
|
3013
|
+
}
|
|
3014
|
+
if (sse.event === null || !sse.event.startsWith("thread.")) {
|
|
3015
|
+
let data;
|
|
3016
|
+
try {
|
|
3017
|
+
data = JSON.parse(sse.data);
|
|
3018
|
+
} catch {
|
|
3019
|
+
logger.error(`Could not parse message into JSON:`);
|
|
3020
|
+
logger.error(`From chunk:`);
|
|
3021
|
+
throw new SyntaxError("Error reading response: malformed server-sent event JSON.");
|
|
3022
|
+
}
|
|
3023
|
+
if (sse.event === "error") throw new APIError(void 0, data?.error ?? data, void 0, response.headers);
|
|
3024
|
+
if (data && data.error) throw new APIError(void 0, data.error, void 0, response.headers);
|
|
3025
|
+
yield synthesizeEventData ? {
|
|
3026
|
+
event: sse.event,
|
|
3027
|
+
data
|
|
3028
|
+
} : data;
|
|
3029
|
+
} else {
|
|
3030
|
+
let data;
|
|
3031
|
+
try {
|
|
3032
|
+
data = JSON.parse(sse.data);
|
|
3033
|
+
} catch {
|
|
3034
|
+
logger.error(`Could not parse message into JSON:`);
|
|
3035
|
+
logger.error(`From chunk:`);
|
|
3036
|
+
throw new SyntaxError("Error reading response: malformed server-sent event JSON.");
|
|
3037
|
+
}
|
|
3038
|
+
yield {
|
|
3039
|
+
event: sse.event,
|
|
3040
|
+
data
|
|
3041
|
+
};
|
|
3042
|
+
}
|
|
3043
|
+
}
|
|
3044
|
+
done = true;
|
|
3045
|
+
} catch (e) {
|
|
3046
|
+
if (receivedCompletionSentinel || isTransportAbortError(e) || controller.signal.aborted && e === controller.signal.reason) return;
|
|
3047
|
+
throw e;
|
|
3048
|
+
} finally {
|
|
3049
|
+
if (!done) controller.abort();
|
|
3050
|
+
}
|
|
3051
|
+
}
|
|
3052
|
+
return new Stream(iterator, controller, client);
|
|
3053
|
+
}
|
|
3054
|
+
/**
|
|
3055
|
+
* Generates a Stream from a newline-separated ReadableStream
|
|
3056
|
+
* where each item is a JSON value.
|
|
3057
|
+
*/
|
|
3058
|
+
static fromReadableStream(readableStream, controller, client) {
|
|
3059
|
+
let consumed = false;
|
|
3060
|
+
async function* iterLines() {
|
|
3061
|
+
const lineDecoder = new LineDecoder();
|
|
3062
|
+
const reader = readableStream.getReader();
|
|
3063
|
+
let closed = false;
|
|
3064
|
+
let cancelPromise;
|
|
3065
|
+
const cancel = () => {
|
|
3066
|
+
cancelPromise ?? (cancelPromise = reader.cancel());
|
|
3067
|
+
cancelPromise.catch(() => void 0);
|
|
3068
|
+
};
|
|
3069
|
+
controller.signal.addEventListener("abort", cancel, { once: true });
|
|
3070
|
+
try {
|
|
3071
|
+
if (controller.signal.aborted) {
|
|
3072
|
+
cancel();
|
|
3073
|
+
return;
|
|
3074
|
+
}
|
|
3075
|
+
while (true) {
|
|
3076
|
+
const { value: chunk, done } = await reader.read();
|
|
3077
|
+
if (done) {
|
|
3078
|
+
closed = true;
|
|
3079
|
+
break;
|
|
3080
|
+
}
|
|
3081
|
+
if (controller.signal.aborted) return;
|
|
3082
|
+
for (const line of lineDecoder.decode(chunk)) {
|
|
3083
|
+
if (controller.signal.aborted) return;
|
|
3084
|
+
yield line;
|
|
3085
|
+
}
|
|
3086
|
+
}
|
|
3087
|
+
if (controller.signal.aborted) return;
|
|
3088
|
+
for (const line of lineDecoder.flush()) {
|
|
3089
|
+
if (controller.signal.aborted) return;
|
|
3090
|
+
yield line;
|
|
3091
|
+
}
|
|
3092
|
+
} finally {
|
|
3093
|
+
controller.signal.removeEventListener("abort", cancel);
|
|
3094
|
+
if (!closed) cancel();
|
|
3095
|
+
reader.releaseLock();
|
|
3096
|
+
}
|
|
3097
|
+
}
|
|
3098
|
+
async function* iterator() {
|
|
3099
|
+
if (consumed) throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
|
|
3100
|
+
consumed = true;
|
|
3101
|
+
let done = false;
|
|
3102
|
+
try {
|
|
3103
|
+
for await (const line of iterLines()) if (line) {
|
|
3104
|
+
let data;
|
|
3105
|
+
try {
|
|
3106
|
+
data = JSON.parse(line);
|
|
3107
|
+
} catch (error) {
|
|
3108
|
+
if (error instanceof SyntaxError) throw new SyntaxError("Error reading response: malformed newline-delimited JSON.");
|
|
3109
|
+
throw error;
|
|
3110
|
+
}
|
|
3111
|
+
yield data;
|
|
3112
|
+
}
|
|
3113
|
+
done = true;
|
|
3114
|
+
} catch (e) {
|
|
3115
|
+
if (controller.signal.aborted || isAbortError(e)) return;
|
|
3116
|
+
throw e;
|
|
3117
|
+
} finally {
|
|
3118
|
+
if (!done) controller.abort();
|
|
3119
|
+
}
|
|
3120
|
+
}
|
|
3121
|
+
return new Stream(iterator, controller, client);
|
|
3122
|
+
}
|
|
3123
|
+
/** Starts consuming this stream; attempting to consume it again throws. */
|
|
3124
|
+
[(_Stream_client = /* @__PURE__ */ new WeakMap(), _Stream_isTeeBranch = /* @__PURE__ */ new WeakMap(), _Stream_instances = /* @__PURE__ */ new WeakSet(), Symbol.asyncIterator)]() {
|
|
3125
|
+
return this.iterator();
|
|
3126
|
+
}
|
|
3127
|
+
/** Beta-only iterator decoration for Agents helpers, preserving custom stream identity.
|
|
3128
|
+
* @internal
|
|
3129
|
+
*/
|
|
3130
|
+
__betaTransformIterator(transform) {
|
|
3131
|
+
this.iterator = transform(this.iterator.bind(this));
|
|
3132
|
+
}
|
|
3133
|
+
/**
|
|
3134
|
+
* Splits the stream into two streams which can be
|
|
3135
|
+
* independently read from at different speeds.
|
|
3136
|
+
* Closing a branch discards its buffered events without stopping its sibling.
|
|
3137
|
+
* Future reads on that branch finish immediately; previously issued `next()`
|
|
3138
|
+
* promises remain shared with its sibling and may still resolve with events.
|
|
3139
|
+
* Closing both branches invokes the source iterator's `return()` when available.
|
|
3140
|
+
* For {@link Stream.fromReadableStream}, closing both branches before iteration
|
|
3141
|
+
* starts does not cancel the supplied readable; cancel that readable directly.
|
|
3142
|
+
*/
|
|
3143
|
+
tee() {
|
|
3144
|
+
const { controller } = this;
|
|
3145
|
+
const left = createStreamTeeQueue();
|
|
3146
|
+
const right = createStreamTeeQueue();
|
|
3147
|
+
const iterator = this.iterator();
|
|
3148
|
+
const teeIterator = (queue) => ({
|
|
3149
|
+
next: () => {
|
|
3150
|
+
if (queue.canceled) return Promise.resolve({
|
|
3151
|
+
value: void 0,
|
|
3152
|
+
done: true
|
|
3153
|
+
});
|
|
3154
|
+
if (queue.length === 0) {
|
|
3155
|
+
const result = iterator.next();
|
|
3156
|
+
left.enqueue(result);
|
|
3157
|
+
right.enqueue(result);
|
|
3158
|
+
}
|
|
3159
|
+
return queue.dequeue();
|
|
3160
|
+
},
|
|
3161
|
+
return: async () => {
|
|
3162
|
+
if (!queue.canceled) {
|
|
3163
|
+
queue.cancel();
|
|
3164
|
+
if (left.canceled && right.canceled) await __classPrivateFieldGet(this, _Stream_instances, "m", _Stream_cancelIterator).call(this, iterator, controller);
|
|
3165
|
+
}
|
|
3166
|
+
return {
|
|
3167
|
+
value: void 0,
|
|
3168
|
+
done: true
|
|
3169
|
+
};
|
|
3170
|
+
}
|
|
3171
|
+
});
|
|
3172
|
+
const branch = (queue) => {
|
|
3173
|
+
const stream = new Stream(() => teeIterator(queue), controller, __classPrivateFieldGet(this, _Stream_client, "f"));
|
|
3174
|
+
__classPrivateFieldSet(stream, _Stream_isTeeBranch, true, "f");
|
|
3175
|
+
return stream;
|
|
3176
|
+
};
|
|
3177
|
+
return [branch(left), branch(right)];
|
|
3178
|
+
}
|
|
3179
|
+
/**
|
|
3180
|
+
* Converts this stream to a newline-separated ReadableStream of
|
|
3181
|
+
* JSON stringified values in the stream
|
|
3182
|
+
* which can be turned back into a Stream with `Stream.fromReadableStream()`.
|
|
3183
|
+
* Canceling a response-backed readable aborts its request. Canceling a tee
|
|
3184
|
+
* branch discards its buffered events and leaves sibling consumers running.
|
|
3185
|
+
* Read or serialization failures also release the iterator without replacing the original error.
|
|
3186
|
+
*/
|
|
3187
|
+
toReadableStream() {
|
|
3188
|
+
const { controller } = this;
|
|
3189
|
+
let iter;
|
|
3190
|
+
let cancellation;
|
|
3191
|
+
const cancel = () => cancellation ?? (cancellation = __classPrivateFieldGet(this, _Stream_instances, "m", _Stream_cancelIterator).call(this, iter, controller));
|
|
3192
|
+
return makeReadableStream({
|
|
3193
|
+
start: async () => {
|
|
3194
|
+
iter = this[Symbol.asyncIterator]();
|
|
3195
|
+
},
|
|
3196
|
+
async pull(ctrl) {
|
|
3197
|
+
try {
|
|
3198
|
+
const { value, done } = await iter.next();
|
|
3199
|
+
if (done) return ctrl.close();
|
|
3200
|
+
const bytes = encodeUTF8(JSON.stringify(value) + "\n");
|
|
3201
|
+
ctrl.enqueue(bytes);
|
|
3202
|
+
} catch (err) {
|
|
3203
|
+
ctrl.error(err);
|
|
3204
|
+
cancel().catch(() => void 0);
|
|
3205
|
+
}
|
|
3206
|
+
},
|
|
3207
|
+
cancel
|
|
3208
|
+
});
|
|
3209
|
+
}
|
|
3210
|
+
};
|
|
3211
|
+
_Stream_cancelIterator = async function _Stream_cancelIterator(iterator, controller) {
|
|
3212
|
+
const returnMethod = iterator.return;
|
|
3213
|
+
if (returnMethod) {
|
|
3214
|
+
if (!__classPrivateFieldGet(this, _Stream_isTeeBranch, "f")) controller.abort();
|
|
3215
|
+
await Reflect.apply(returnMethod, iterator, []);
|
|
3216
|
+
}
|
|
3217
|
+
};
|
|
3218
|
+
function createAbortableSSESource(body, signal) {
|
|
3219
|
+
const reader = typeof body.getReader === "function" ? body.getReader() : void 0;
|
|
3220
|
+
const source = reader ? {
|
|
3221
|
+
next: () => reader.read(),
|
|
3222
|
+
return: () => reader.cancel()
|
|
3223
|
+
} : ReadableStreamToAsyncIterable(body)[Symbol.asyncIterator]();
|
|
3224
|
+
const ended = {
|
|
3225
|
+
value: void 0,
|
|
3226
|
+
done: true
|
|
3227
|
+
};
|
|
3228
|
+
let closed = false;
|
|
3229
|
+
let canceled = false;
|
|
3230
|
+
let cancellation;
|
|
3231
|
+
let interrupt;
|
|
3232
|
+
const waitForAbort = () => new Promise((resolve) => {
|
|
3233
|
+
interrupt = resolve;
|
|
3234
|
+
});
|
|
3235
|
+
const cancel = () => {
|
|
3236
|
+
if (canceled || closed) return cancellation;
|
|
3237
|
+
canceled = true;
|
|
3238
|
+
try {
|
|
3239
|
+
cancellation = Promise.resolve(source.return?.());
|
|
3240
|
+
} catch (error) {
|
|
3241
|
+
cancellation = Promise.reject(error);
|
|
3242
|
+
}
|
|
3243
|
+
cancellation.catch(() => void 0);
|
|
3244
|
+
return cancellation;
|
|
3245
|
+
};
|
|
3246
|
+
const abort = () => {
|
|
3247
|
+
queueMicrotask(() => {
|
|
3248
|
+
interrupt?.();
|
|
3249
|
+
cancel();
|
|
3250
|
+
});
|
|
3251
|
+
};
|
|
3252
|
+
return {
|
|
3253
|
+
iterator: {
|
|
3254
|
+
async next() {
|
|
3255
|
+
if (signal.aborted) return ended;
|
|
3256
|
+
const aborted = waitForAbort().then(() => ended);
|
|
3257
|
+
try {
|
|
3258
|
+
const result = await Promise.race([source.next(), aborted]);
|
|
3259
|
+
if (signal.aborted) return ended;
|
|
3260
|
+
if (result.done) {
|
|
3261
|
+
closed = true;
|
|
3262
|
+
return ended;
|
|
3263
|
+
}
|
|
3264
|
+
return {
|
|
3265
|
+
value: result.value,
|
|
3266
|
+
done: false
|
|
3267
|
+
};
|
|
3268
|
+
} catch (error) {
|
|
3269
|
+
if (signal.aborted && (isAbortError(error) || error === signal.reason)) return ended;
|
|
3270
|
+
throw error;
|
|
3271
|
+
} finally {
|
|
3272
|
+
interrupt = void 0;
|
|
3273
|
+
}
|
|
3274
|
+
},
|
|
3275
|
+
async return() {
|
|
3276
|
+
const pending = cancel();
|
|
3277
|
+
if (pending && !signal.aborted) {
|
|
3278
|
+
const aborted = waitForAbort();
|
|
3279
|
+
try {
|
|
3280
|
+
if (!signal.aborted) await Promise.race([pending, aborted]);
|
|
3281
|
+
} finally {
|
|
3282
|
+
interrupt = void 0;
|
|
3283
|
+
}
|
|
3284
|
+
}
|
|
3285
|
+
return ended;
|
|
3286
|
+
},
|
|
3287
|
+
[Symbol.asyncIterator]() {
|
|
3288
|
+
return this;
|
|
3289
|
+
}
|
|
3290
|
+
},
|
|
3291
|
+
start() {
|
|
3292
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
3293
|
+
if (signal.aborted) abort();
|
|
3294
|
+
},
|
|
3295
|
+
async cleanup(failed) {
|
|
3296
|
+
let cleanupError;
|
|
3297
|
+
try {
|
|
3298
|
+
signal.removeEventListener("abort", abort);
|
|
3299
|
+
} catch (error) {
|
|
3300
|
+
cleanupError = error;
|
|
3301
|
+
}
|
|
3302
|
+
if (!closed) {
|
|
3303
|
+
const pending = cancel();
|
|
3304
|
+
if (pending && !failed && !signal.aborted) try {
|
|
3305
|
+
await pending;
|
|
3306
|
+
} catch (error) {
|
|
3307
|
+
cleanupError ?? (cleanupError = error);
|
|
3308
|
+
}
|
|
3309
|
+
}
|
|
3310
|
+
if (reader) try {
|
|
3311
|
+
reader.releaseLock();
|
|
3312
|
+
} catch (error) {
|
|
3313
|
+
cleanupError ?? (cleanupError = error);
|
|
3314
|
+
}
|
|
3315
|
+
if (cleanupError !== void 0 && !failed && !signal.aborted) throw cleanupError;
|
|
3316
|
+
}
|
|
3317
|
+
};
|
|
3318
|
+
}
|
|
3319
|
+
/**
|
|
3320
|
+
* Decodes complete SSE records from a response and aborts when its body is absent.
|
|
3321
|
+
* Complete events are decoded on demand without imposing a line or event size limit.
|
|
3322
|
+
*
|
|
3323
|
+
* @yields {ServerSentEvent} Each decoded server-sent event in wire order.
|
|
3324
|
+
*/
|
|
3325
|
+
async function* _iterSSEMessages(response, controller) {
|
|
3326
|
+
if (!response.body) {
|
|
3327
|
+
controller.abort();
|
|
3328
|
+
if (globalThis.navigator !== void 0 && globalThis.navigator.product === "ReactNative") throw new OpenAIError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`);
|
|
3329
|
+
throw new OpenAIError(`Attempted to iterate over a response with no body`);
|
|
3330
|
+
}
|
|
3331
|
+
const sseDecoder = new SSEDecoder();
|
|
3332
|
+
const lineDecoder = new LineDecoder();
|
|
3333
|
+
const { signal } = controller;
|
|
3334
|
+
const source = createAbortableSSESource(response.body, signal);
|
|
3335
|
+
let failed = false;
|
|
3336
|
+
try {
|
|
3337
|
+
source.start();
|
|
3338
|
+
for await (const sseChunk of iterSSEChunks(source.iterator)) {
|
|
3339
|
+
if (signal.aborted) return;
|
|
3340
|
+
for (const line of lineDecoder.decode(sseChunk)) {
|
|
3341
|
+
if (signal.aborted) return;
|
|
3342
|
+
const sse = sseDecoder.decode(line);
|
|
3343
|
+
if (sse) yield sse;
|
|
3344
|
+
}
|
|
3345
|
+
}
|
|
3346
|
+
if (signal.aborted) return;
|
|
3347
|
+
for (const line of lineDecoder.flush()) {
|
|
3348
|
+
if (signal.aborted) return;
|
|
3349
|
+
const sse = sseDecoder.decode(line);
|
|
3350
|
+
if (sse) yield sse;
|
|
3351
|
+
}
|
|
3352
|
+
if (signal.aborted) return;
|
|
3353
|
+
const pending = sseDecoder.flush();
|
|
3354
|
+
if (pending) yield pending;
|
|
3355
|
+
} catch (error) {
|
|
3356
|
+
failed = true;
|
|
3357
|
+
if (!signal.aborted || !isAbortError(error) && error !== signal.reason) throw error;
|
|
3358
|
+
} finally {
|
|
3359
|
+
await source.cleanup(failed);
|
|
3360
|
+
}
|
|
3361
|
+
}
|
|
3362
|
+
const DOUBLE_NEWLINE_DELIMITER_MAX_OVERLAP_BYTES = 3;
|
|
3363
|
+
/**
|
|
3364
|
+
* Given an async iterable iterator, iterates over it and yields full
|
|
3365
|
+
* SSE chunks, i.e. yields when a double new-line is encountered.
|
|
3366
|
+
*
|
|
3367
|
+
* @yields {Uint8Array} A complete SSE chunk.
|
|
3368
|
+
*/
|
|
3369
|
+
async function* iterSSEChunks(iterator) {
|
|
3370
|
+
let data = /* @__PURE__ */ new Uint8Array();
|
|
3371
|
+
let dataStart = 0;
|
|
3372
|
+
let dataEnd = 0;
|
|
3373
|
+
let searchStartIndex = 0;
|
|
3374
|
+
for await (const chunk of iterator) {
|
|
3375
|
+
if (chunk == null) continue;
|
|
3376
|
+
let binaryChunk;
|
|
3377
|
+
if (chunk instanceof ArrayBuffer) binaryChunk = new Uint8Array(chunk);
|
|
3378
|
+
else if (typeof chunk === "string") binaryChunk = encodeUTF8(chunk);
|
|
3379
|
+
else binaryChunk = chunk;
|
|
3380
|
+
if (dataEnd + binaryChunk.length > data.length) {
|
|
3381
|
+
const bufferedLength = dataEnd - dataStart;
|
|
3382
|
+
if (dataStart >= data.length / 2 && bufferedLength + binaryChunk.length <= data.length) data.copyWithin(0, dataStart, dataEnd);
|
|
3383
|
+
else {
|
|
3384
|
+
const newData = new Uint8Array(Math.max(data.length * 2, bufferedLength + binaryChunk.length));
|
|
3385
|
+
newData.set(data.subarray(dataStart, dataEnd));
|
|
3386
|
+
data = newData;
|
|
3387
|
+
}
|
|
3388
|
+
searchStartIndex -= dataStart;
|
|
3389
|
+
dataStart = 0;
|
|
3390
|
+
dataEnd = bufferedLength;
|
|
3391
|
+
}
|
|
3392
|
+
data.set(binaryChunk, dataEnd);
|
|
3393
|
+
dataEnd += binaryChunk.length;
|
|
3394
|
+
let patternIndex;
|
|
3395
|
+
while ((patternIndex = findDoubleNewlineIndex(data.subarray(searchStartIndex, dataEnd))) !== -1) {
|
|
3396
|
+
patternIndex += searchStartIndex;
|
|
3397
|
+
yield data.slice(dataStart, patternIndex);
|
|
3398
|
+
dataStart = patternIndex;
|
|
3399
|
+
searchStartIndex = dataStart;
|
|
3400
|
+
}
|
|
3401
|
+
searchStartIndex = Math.max(dataStart, dataEnd - DOUBLE_NEWLINE_DELIMITER_MAX_OVERLAP_BYTES);
|
|
3402
|
+
}
|
|
3403
|
+
if (dataEnd > dataStart) yield data.slice(dataStart, dataEnd);
|
|
3404
|
+
}
|
|
3405
|
+
var SSEDecoder = class {
|
|
3406
|
+
constructor() {
|
|
3407
|
+
this.event = null;
|
|
3408
|
+
this.data = [];
|
|
3409
|
+
this.chunks = [];
|
|
3410
|
+
}
|
|
3411
|
+
decode(line) {
|
|
3412
|
+
if (line.endsWith("\r")) line = line.slice(0, -1);
|
|
3413
|
+
if (!line) {
|
|
3414
|
+
if (!this.event && !this.data.length) return null;
|
|
3415
|
+
const sse = {
|
|
3416
|
+
event: this.event,
|
|
3417
|
+
data: this.data.join("\n"),
|
|
3418
|
+
raw: this.chunks
|
|
3419
|
+
};
|
|
3420
|
+
this.event = null;
|
|
3421
|
+
this.data = [];
|
|
3422
|
+
this.chunks = [];
|
|
3423
|
+
return sse;
|
|
3424
|
+
}
|
|
3425
|
+
this.chunks.push(line);
|
|
3426
|
+
if (line.startsWith(":")) return null;
|
|
3427
|
+
const [fieldname, , initialValue] = partition(line, ":");
|
|
3428
|
+
let value = initialValue;
|
|
3429
|
+
if (value.startsWith(" ")) value = value.slice(1);
|
|
3430
|
+
if (fieldname === "event") this.event = value;
|
|
3431
|
+
else if (fieldname === "data") this.data.push(value);
|
|
3432
|
+
return null;
|
|
3433
|
+
}
|
|
3434
|
+
/**
|
|
3435
|
+
* Emits a pending event at EOF when the stream omitted the trailing blank
|
|
3436
|
+
* line. Returns `null` when no event is in progress so a record that already
|
|
3437
|
+
* ended with a blank line is not delivered twice.
|
|
3438
|
+
*/
|
|
3439
|
+
flush() {
|
|
3440
|
+
return this.decode("");
|
|
3441
|
+
}
|
|
3442
|
+
};
|
|
3443
|
+
function partition(str, delimiter) {
|
|
3444
|
+
const index = str.indexOf(delimiter);
|
|
3445
|
+
if (index !== -1) return [
|
|
3446
|
+
str.slice(0, index),
|
|
3447
|
+
delimiter,
|
|
3448
|
+
str.slice(index + delimiter.length)
|
|
3449
|
+
];
|
|
3450
|
+
return [
|
|
3451
|
+
str,
|
|
3452
|
+
"",
|
|
3453
|
+
""
|
|
3454
|
+
];
|
|
3455
|
+
}
|
|
3456
|
+
// packages/ai/src/transports/openai-responses-replay-internal.ts
|
|
2185
3457
|
function isAsyncIterable(value) {
|
|
2186
3458
|
return (typeof value === "object" && value !== null || typeof value === "function") && Symbol.asyncIterator in value;
|
|
2187
3459
|
}
|
|
3460
|
+
function isEmittedResponsesItem(item, failedSnapshot = false) {
|
|
3461
|
+
return isRecord(item) && item.type !== "compaction" && !(failedSnapshot && (item.type === "message" || item.type === "reasoning"));
|
|
3462
|
+
}
|
|
2188
3463
|
function readResponsesRecoveryEvent(event) {
|
|
2189
3464
|
const record = isRecord(event) ? event : void 0;
|
|
2190
3465
|
const response = isRecord(record?.response) ? record.response : void 0;
|
|
2191
3466
|
return {
|
|
2192
3467
|
failure: record?.type === "response.failed" ? response?.error : record?.type === "error" ? record.error ?? record : void 0,
|
|
2193
|
-
hasResponseOutput: Array.isArray(response?.output) && response.output.
|
|
2194
|
-
isPrelude: record !== void 0 && PRELUDE_TYPES.has(String(record.type))
|
|
3468
|
+
hasResponseOutput: Array.isArray(response?.output) && response.output.some((item) => isEmittedResponsesItem(item, record?.type === "response.failed")) || isEmittedResponsesItem(record?.item) || typeof record?.type === "string" && (record.type.endsWith(".delta") || record.type.includes("_call"))
|
|
2195
3469
|
};
|
|
2196
3470
|
}
|
|
2197
3471
|
function isInvalidEncryptedContentError(error) {
|
|
@@ -2201,6 +3475,43 @@ function isInvalidEncryptedContentError(error) {
|
|
|
2201
3475
|
const message = typeof record.message === "string" ? record.message.toLowerCase() : "";
|
|
2202
3476
|
return message.includes("invalid_encrypted_content") || message.includes("thinking_signature_invalid") || (record.status === 400 || record.status == null && /(?:^|[\s(])400(?:[\s):]|$)/.test(message)) && (message.includes("could not decrypt the provided encrypted_content") || message.includes("encrypted content") && (message.includes("could not be verified") || message.includes("could not be decrypted or parsed")));
|
|
2203
3477
|
}
|
|
3478
|
+
function isResponsesItemConflict(error) {
|
|
3479
|
+
return isRecord(error) && error.code === "item_conflict";
|
|
3480
|
+
}
|
|
3481
|
+
/** One repair budget and durable replay receipt shared by HTTP and WebSocket recovery. */
|
|
3482
|
+
function createResponsesItemConflictRecovery(output, model, options) {
|
|
3483
|
+
let anchor;
|
|
3484
|
+
let attempted = false;
|
|
3485
|
+
let applied = false;
|
|
3486
|
+
return {
|
|
3487
|
+
applied: () => {
|
|
3488
|
+
applied = true;
|
|
3489
|
+
},
|
|
3490
|
+
async retry(buildRequest) {
|
|
3491
|
+
if (anchor || options?.signal?.aborted) throw Object.assign(/* @__PURE__ */ new Error("Saved conversation items could not be recovered"), { code: "item_conflict" });
|
|
3492
|
+
anchor = globalThis.crypto.randomUUID();
|
|
3493
|
+
attempted = true;
|
|
3494
|
+
const request = await buildRequest({ itemRecovery: anchor });
|
|
3495
|
+
delete request.previous_response_id;
|
|
3496
|
+
suppressOpenAIResponsesCompaction(output, model, options, void 0, anchor);
|
|
3497
|
+
log.warn(`[responses] item_conflict_recovery sessionHash=${redactIdentifier(options?.sessionId)} outcome=started`);
|
|
3498
|
+
return request;
|
|
3499
|
+
},
|
|
3500
|
+
reject(error) {
|
|
3501
|
+
if (!anchor && isResponsesItemConflict(error)) {
|
|
3502
|
+
anchor = globalThis.crypto.randomUUID();
|
|
3503
|
+
suppressOpenAIResponsesCompaction(output, model, options, void 0, anchor);
|
|
3504
|
+
}
|
|
3505
|
+
},
|
|
3506
|
+
finish() {
|
|
3507
|
+
if (anchor || applied) {
|
|
3508
|
+
const outcome = anchor && !attempted ? "deferred" : output.stopReason === "error" || output.stopReason === "aborted" ? "failed" : "recovered";
|
|
3509
|
+
output.itemConflictRecovery = outcome;
|
|
3510
|
+
log.info(`[responses] item_conflict_recovery sessionHash=${redactIdentifier(options?.sessionId)} outcome=${outcome}`);
|
|
3511
|
+
}
|
|
3512
|
+
}
|
|
3513
|
+
};
|
|
3514
|
+
}
|
|
2204
3515
|
function isOrphanedFunctionCallOutputError(error) {
|
|
2205
3516
|
if (!error || typeof error !== "object") return false;
|
|
2206
3517
|
const record = error;
|
|
@@ -2234,6 +3545,10 @@ function readOpenAIResponsesCompactionRejection(request) {
|
|
|
2234
3545
|
} : void 0;
|
|
2235
3546
|
}
|
|
2236
3547
|
async function resolveNextResponsesEncryptedContentAttempt(attempt, error, options) {
|
|
3548
|
+
if (isResponsesItemConflict(error)) return attempt.kind !== "items-reanchored" && options.buildItemConflictRequest ? {
|
|
3549
|
+
kind: "items-reanchored",
|
|
3550
|
+
request: await options.buildItemConflictRequest()
|
|
3551
|
+
} : void 0;
|
|
2237
3552
|
const orphanedFunctionOutput = isOrphanedFunctionCallOutputError(error);
|
|
2238
3553
|
if (!isInvalidEncryptedContentError(error) && !orphanedFunctionOutput || attempt.kind === "compaction-stripped") return;
|
|
2239
3554
|
if (!orphanedFunctionOutput && (attempt.kind === "initial" || attempt.kind === "continuation-rejected")) {
|
|
@@ -2403,7 +3718,10 @@ async function createResponsesStreamWithRecovery(params) {
|
|
|
2403
3718
|
attempt
|
|
2404
3719
|
};
|
|
2405
3720
|
} catch (error) {
|
|
2406
|
-
let nextAttempt = (!responseAccepted ? recoverServiceTier(attempt, error) : void 0) ?? await resolveNextResponsesEncryptedContentAttempt(attempt, error, {
|
|
3721
|
+
let nextAttempt = (!responseAccepted ? recoverServiceTier(attempt, error) : void 0) ?? await resolveNextResponsesEncryptedContentAttempt(attempt, error, {
|
|
3722
|
+
buildFullHistoryRequest: params.buildFullHistoryRequest,
|
|
3723
|
+
buildItemConflictRequest: params.buildItemConflictRequest
|
|
3724
|
+
});
|
|
2407
3725
|
if (!nextAttempt && attempt.request.previous_response_id && error && typeof error === "object" && typeof error.status === "number" && isPreviousResponseRejection(error)) {
|
|
2408
3726
|
const request = { ...await params.buildFullHistoryRequest() };
|
|
2409
3727
|
delete request.previous_response_id;
|
|
@@ -2413,7 +3731,7 @@ async function createResponsesStreamWithRecovery(params) {
|
|
|
2413
3731
|
};
|
|
2414
3732
|
}
|
|
2415
3733
|
if (!nextAttempt) throw error;
|
|
2416
|
-
const retryDescription = nextAttempt.request.service_tier !== attempt.request.service_tier ? "with a slower service tier" : nextAttempt.kind === "reasoning-stripped" ? "without encrypted reasoning content" : nextAttempt.kind === "compaction-stripped" ? "without encrypted compaction content" : "full history after rejected previous_response_id";
|
|
3734
|
+
const retryDescription = nextAttempt.request.service_tier !== attempt.request.service_tier ? "with a slower service tier" : nextAttempt.kind === "reasoning-stripped" ? "without encrypted reasoning content" : nextAttempt.kind === "compaction-stripped" ? "without encrypted compaction content" : nextAttempt.kind === "items-reanchored" ? "with reanchored conversation items" : "full history after rejected previous_response_id";
|
|
2417
3735
|
log.warn(`[responses] retrying ${retryDescription} provider=${params.model.provider} api=${params.model.api} model=${params.model.id}`);
|
|
2418
3736
|
attempt = nextAttempt;
|
|
2419
3737
|
}
|
|
@@ -2431,22 +3749,31 @@ async function createResponsesStreamWithRecovery(params) {
|
|
|
2431
3749
|
let rejectedEvent;
|
|
2432
3750
|
let sourceError;
|
|
2433
3751
|
const source = current.stream;
|
|
2434
|
-
const providerStream = {
|
|
2435
|
-
|
|
2436
|
-
|
|
2437
|
-
|
|
2438
|
-
|
|
2439
|
-
|
|
2440
|
-
|
|
3752
|
+
const providerStream = { [Symbol.asyncIterator]() {
|
|
3753
|
+
return observeAsyncIterator({
|
|
3754
|
+
iterator: () => source[Symbol.asyncIterator](),
|
|
3755
|
+
onEvent() {},
|
|
3756
|
+
onError(error) {
|
|
3757
|
+
sourceError = error;
|
|
3758
|
+
},
|
|
3759
|
+
async onClose(iterator) {
|
|
3760
|
+
try {
|
|
3761
|
+
await iterator?.return?.();
|
|
3762
|
+
} catch (error) {
|
|
3763
|
+
sourceError = error;
|
|
3764
|
+
throw error;
|
|
3765
|
+
}
|
|
3766
|
+
}
|
|
3767
|
+
});
|
|
2441
3768
|
} };
|
|
2442
3769
|
try {
|
|
2443
3770
|
for await (const event of params.wrapStream?.({
|
|
2444
3771
|
...current,
|
|
2445
3772
|
stream: providerStream
|
|
2446
3773
|
}) ?? providerStream) {
|
|
2447
|
-
const { failure, hasResponseOutput
|
|
3774
|
+
const { failure, hasResponseOutput } = readResponsesRecoveryEvent(event);
|
|
2448
3775
|
outputObserved ||= hasResponseOutput;
|
|
2449
|
-
if (isRecord(failure) && params.canRetryStream?.() === true && (isInvalidEncryptedContentError(failure) || !outputObserved && isResponsesServiceTierRejection(failure))) {
|
|
3776
|
+
if (isRecord(failure) && params.canRetryStream?.() === true && (isInvalidEncryptedContentError(failure) || !outputObserved && isResponsesItemConflict(failure) || !outputObserved && isResponsesServiceTierRejection(failure))) {
|
|
2450
3777
|
rejectedEvent = event;
|
|
2451
3778
|
const message = typeof failure.message === "string" ? failure.message : "";
|
|
2452
3779
|
throw Object.assign(new Error(message), {
|
|
@@ -2456,12 +3783,14 @@ async function createResponsesStreamWithRecovery(params) {
|
|
|
2456
3783
|
param: failure.param
|
|
2457
3784
|
});
|
|
2458
3785
|
}
|
|
2459
|
-
outputObserved ||= !isPrelude;
|
|
2460
3786
|
yield event;
|
|
2461
3787
|
}
|
|
2462
3788
|
return;
|
|
2463
3789
|
} catch (error) {
|
|
2464
|
-
const nextAttempt = params.canRetryStream?.() === true && !params.requestOptions?.signal?.aborted ? (!outputObserved && (rejectedEvent !== void 0 || sourceError === error) ? recoverServiceTier(current.attempt, error) : void 0) ?? await resolveNextResponsesEncryptedContentAttempt(current.attempt, error, {
|
|
3790
|
+
const nextAttempt = params.canRetryStream?.() === true && !params.requestOptions?.signal?.aborted ? (!outputObserved && (rejectedEvent !== void 0 || sourceError === error) ? recoverServiceTier(current.attempt, error) : void 0) ?? await resolveNextResponsesEncryptedContentAttempt(current.attempt, error, {
|
|
3791
|
+
buildFullHistoryRequest: params.buildFullHistoryRequest,
|
|
3792
|
+
buildItemConflictRequest: !outputObserved && (rejectedEvent !== void 0 || sourceError === error) ? params.buildItemConflictRequest : void 0
|
|
3793
|
+
}) : void 0;
|
|
2465
3794
|
if (!nextAttempt) {
|
|
2466
3795
|
if (rejectedEvent !== void 0) {
|
|
2467
3796
|
yield rejectedEvent;
|
|
@@ -2478,8 +3807,7 @@ async function createResponsesStreamWithRecovery(params) {
|
|
|
2478
3807
|
function resolveAzureOpenAIApiVersion(env = process.env) {
|
|
2479
3808
|
return env.AZURE_OPENAI_API_VERSION?.trim() || "preview";
|
|
2480
3809
|
}
|
|
2481
|
-
|
|
2482
|
-
//#region packages/ai/src/providers/openai-responses-message-text.ts
|
|
3810
|
+
// packages/ai/src/providers/openai-responses-message-text.ts
|
|
2483
3811
|
/** Keep provider prose separate from source formatting so terminal annotations can extend it. */
|
|
2484
3812
|
function renderResponsesMessageText(content) {
|
|
2485
3813
|
const citations = /* @__PURE__ */ new Map();
|
|
@@ -2553,8 +3881,7 @@ function extendResponsesMessageText(next, previous) {
|
|
|
2553
3881
|
text: citations.size > 0 ? next.prose + "\n\n" + [...citations.values()].join(" ") : next.prose
|
|
2554
3882
|
};
|
|
2555
3883
|
}
|
|
2556
|
-
|
|
2557
|
-
//#region packages/ai/src/providers/openai-responses-stream-compat.ts
|
|
3884
|
+
// packages/ai/src/providers/openai-responses-stream-compat.ts
|
|
2558
3885
|
const OPENAI_RESPONSES_OUTPUT_TEXT_CONTENT_PART_TYPE = "output_text";
|
|
2559
3886
|
const AZURE_RESPONSES_TEXT_CONTENT_PART_TYPE = "text";
|
|
2560
3887
|
const OPENAI_RESPONSES_OUTPUT_TEXT_DELTA_EVENT_TYPE = "response.output_text.delta";
|
|
@@ -2580,8 +3907,7 @@ function resolveResponsesMessageSnapshotCollapse(params) {
|
|
|
2580
3907
|
};
|
|
2581
3908
|
return { kind: "keep" };
|
|
2582
3909
|
}
|
|
2583
|
-
|
|
2584
|
-
//#region packages/ai/src/transports/openai-responses-stream-slots-internal.ts
|
|
3910
|
+
// packages/ai/src/transports/openai-responses-stream-slots-internal.ts
|
|
2585
3911
|
const RESPONSES_BOOKKEEPING_TIMEOUT_MS = 9e5;
|
|
2586
3912
|
function createResponsesOutputTracker(params) {
|
|
2587
3913
|
const outputs = /* @__PURE__ */ new Map();
|
|
@@ -2708,8 +4034,7 @@ function createResponsesOutputSlotTracker() {
|
|
|
2708
4034
|
}
|
|
2709
4035
|
};
|
|
2710
4036
|
}
|
|
2711
|
-
|
|
2712
|
-
//#region packages/ai/src/providers/openai-responses-tool-call-tracker.ts
|
|
4037
|
+
// packages/ai/src/providers/openai-responses-tool-call-tracker.ts
|
|
2713
4038
|
function readResponsesToolCallItemIdentity(item) {
|
|
2714
4039
|
return {
|
|
2715
4040
|
itemId: normalizeOptionalString(item.id),
|
|
@@ -2782,8 +4107,7 @@ function createResponsesToolCallTracker() {
|
|
|
2782
4107
|
}
|
|
2783
4108
|
};
|
|
2784
4109
|
}
|
|
2785
|
-
|
|
2786
|
-
//#region packages/ai/src/transports/openai-responses-stream-observer-internal.ts
|
|
4110
|
+
// packages/ai/src/transports/openai-responses-stream-observer-internal.ts
|
|
2787
4111
|
const STRING_DELTA_EVENTS = /* @__PURE__ */ new Set([
|
|
2788
4112
|
"response.function_call_arguments.delta",
|
|
2789
4113
|
"response.output_text.delta",
|
|
@@ -2845,8 +4169,7 @@ function observeResponsesStream(stream, model, requestStartedAt, request, transp
|
|
|
2845
4169
|
}
|
|
2846
4170
|
});
|
|
2847
4171
|
}
|
|
2848
|
-
|
|
2849
|
-
//#region packages/ai/src/transports/openai-responses-stream-terminal-internal.ts
|
|
4172
|
+
// packages/ai/src/transports/openai-responses-stream-terminal-internal.ts
|
|
2850
4173
|
function splitToolCallId(id) {
|
|
2851
4174
|
const separator = id.indexOf("|");
|
|
2852
4175
|
return separator === -1 ? [id, void 0] : [id.slice(0, separator), id.slice(separator + 1)];
|
|
@@ -2866,9 +4189,16 @@ function resolveCompletedResponsesToolCall(item, streamed) {
|
|
|
2866
4189
|
if (streamedName && completedName && streamedName !== completedName) throw new Error(`Responses stream changed tool-call function name from ${streamedName} to ${completedName}`);
|
|
2867
4190
|
const name = completedName ?? streamedName;
|
|
2868
4191
|
if (!name) throw new Error("Responses stream completed tool call without a function name");
|
|
4192
|
+
const raw = streamed?.rawArguments ?? streamed?.arguments ?? item.arguments;
|
|
4193
|
+
const argumentsValue = parseTerminalToolCallArguments(streamed?.arguments ?? item.arguments, "Responses stream completed tool call with invalid JSON arguments");
|
|
4194
|
+
const value = JSON.stringify(argumentsValue);
|
|
2869
4195
|
return {
|
|
2870
4196
|
name,
|
|
2871
|
-
arguments:
|
|
4197
|
+
arguments: argumentsValue,
|
|
4198
|
+
...typeof raw === "string" && raw !== value ? { argumentsSignature: {
|
|
4199
|
+
value,
|
|
4200
|
+
raw
|
|
4201
|
+
} } : {}
|
|
2872
4202
|
};
|
|
2873
4203
|
}
|
|
2874
4204
|
function createResponsesTerminalController(params) {
|
|
@@ -3136,8 +4466,7 @@ function createResponsesTerminalController(params) {
|
|
|
3136
4466
|
releaseDeferredToolCompletions
|
|
3137
4467
|
};
|
|
3138
4468
|
}
|
|
3139
|
-
|
|
3140
|
-
//#region packages/ai/src/transports/openai-responses-stream-internal.ts
|
|
4469
|
+
// packages/ai/src/transports/openai-responses-stream-internal.ts
|
|
3141
4470
|
async function processResponsesStream(openaiStream, output, sink, model, options) {
|
|
3142
4471
|
const streamingToolCalls = createResponsesToolCallTracker();
|
|
3143
4472
|
const outputSlots = createResponsesOutputSlotTracker();
|
|
@@ -3534,7 +4863,8 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
3534
4863
|
try {
|
|
3535
4864
|
validated = resolveCompletedResponsesToolCall(item, {
|
|
3536
4865
|
name: streamingToolCall?.providerName,
|
|
3537
|
-
arguments: parsedStreamedArguments ?? (completedArguments || streamedArguments)
|
|
4866
|
+
arguments: parsedStreamedArguments ?? (completedArguments || streamedArguments),
|
|
4867
|
+
rawArguments: parsedStreamedArguments ? streamedArguments : void 0
|
|
3538
4868
|
});
|
|
3539
4869
|
} catch (error) {
|
|
3540
4870
|
rejectedToolCall = { error };
|
|
@@ -3576,8 +4906,7 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
3576
4906
|
terminal.releaseDeferredToolCompletions();
|
|
3577
4907
|
}
|
|
3578
4908
|
}
|
|
3579
|
-
|
|
3580
|
-
//#region packages/ai/src/providers/openai-provider-refusal.ts
|
|
4909
|
+
// packages/ai/src/providers/openai-provider-refusal.ts
|
|
3581
4910
|
/** Responses uses snake_case; the ChatGPT app-server error envelope uses camelCase. */
|
|
3582
4911
|
function readOpenAIMisalignmentReview(value, continuationSupported) {
|
|
3583
4912
|
if (!isRecord(value)) return;
|
|
@@ -3587,8 +4916,7 @@ function readOpenAIMisalignmentReview(value, continuationSupported) {
|
|
|
3587
4916
|
...continuationSupported ? { continuation: value.steer } : {}
|
|
3588
4917
|
});
|
|
3589
4918
|
}
|
|
3590
|
-
|
|
3591
|
-
//#region packages/ai/src/providers/openai-responses-tools.ts
|
|
4919
|
+
// packages/ai/src/providers/openai-responses-tools.ts
|
|
3592
4920
|
/** Projects direct provider descriptors before resolving their strict policy. */
|
|
3593
4921
|
function convertResponsesToolPayload(tools, options) {
|
|
3594
4922
|
return convertPreparedResponsesTools(prepareOpenAITools(tools), resolveResponsesStrictToolSetting(options), options?.model, options?.mutableParameters);
|
|
@@ -3621,8 +4949,7 @@ function resolveResponsesStrictToolSetting(options) {
|
|
|
3621
4949
|
});
|
|
3622
4950
|
return false;
|
|
3623
4951
|
}
|
|
3624
|
-
|
|
3625
|
-
//#region packages/ai/src/providers/openai-responses-shared.ts
|
|
4952
|
+
// packages/ai/src/providers/openai-responses-shared.ts
|
|
3626
4953
|
function applyResponsesServiceTierPricing(usage, serviceTier, model) {
|
|
3627
4954
|
let multiplier = 1;
|
|
3628
4955
|
if (serviceTier === "flex") multiplier = .5;
|
|
@@ -3661,13 +4988,16 @@ function applyCommonResponsesParams(params, model, context, options, config) {
|
|
|
3661
4988
|
async function runResponsesStreamLifecycle(params) {
|
|
3662
4989
|
const { stream, output, options } = params;
|
|
3663
4990
|
let firstEventAbort;
|
|
4991
|
+
let itemRecovery;
|
|
3664
4992
|
try {
|
|
3665
4993
|
const model = params.resolveRequestModel?.(params.model) ?? params.model;
|
|
3666
|
-
|
|
4994
|
+
itemRecovery = createResponsesItemConflictRecovery(output, model, options);
|
|
4995
|
+
const recovery = itemRecovery;
|
|
4996
|
+
const client = await params.createClient(model);
|
|
3667
4997
|
const encodeBody = prepareModelRequestBody(options);
|
|
3668
4998
|
const buildRequest = async (replayMode) => {
|
|
3669
4999
|
let request = params.buildParams(model, replayMode);
|
|
3670
|
-
const nextRequest = await options?.onPayload?.(request, model);
|
|
5000
|
+
const nextRequest = await awaitProviderLifecycleCallback(options?.onPayload ? () => options.onPayload?.(request, model) : void 0, options?.signal);
|
|
3671
5001
|
if (nextRequest !== void 0) request = nextRequest;
|
|
3672
5002
|
if (options?.openclawCodeModeToolSurface === true) {
|
|
3673
5003
|
const visibleToolNames = resolveCodeModeResponsesVisibleToolNames(params.context ?? {});
|
|
@@ -3694,6 +5024,7 @@ async function runResponsesStreamLifecycle(params) {
|
|
|
3694
5024
|
model,
|
|
3695
5025
|
encodeBody,
|
|
3696
5026
|
buildFullHistoryRequest: () => buildRequest("full-history"),
|
|
5027
|
+
buildItemConflictRequest: () => recovery.retry(buildRequest),
|
|
3697
5028
|
onCompactionRejected: (checkpoint) => suppressOpenAIResponsesCompaction(output, model, options, checkpoint),
|
|
3698
5029
|
canRetryStream: () => output.content.length === 0,
|
|
3699
5030
|
onServiceTierRejected: (tier) => responsesServiceTierObserver.reject(options, tier),
|
|
@@ -3731,10 +5062,7 @@ async function runResponsesStreamLifecycle(params) {
|
|
|
3731
5062
|
resolveServiceTier: (responseTier, originalTier) => responseTier ?? (requestedTier === "priority" || requestedTier === "default" ? requestedTier : originalTier),
|
|
3732
5063
|
onServiceTier: (responseTier, response) => responsesServiceTierObserver.observe(options, requestedTier, responseTier, response),
|
|
3733
5064
|
canRetryIdentityConflict: () => hasOnlyResponsesFunctionTools(admittedRequest),
|
|
3734
|
-
reasoningReplayMetadata: buildOpenAIResponsesReasoningReplayMetadata(model, {
|
|
3735
|
-
sessionId: options?.sessionId,
|
|
3736
|
-
authProfileId: options?.authProfileId
|
|
3737
|
-
})
|
|
5065
|
+
reasoningReplayMetadata: buildOpenAIResponsesReasoningReplayMetadata(model, { sessionId: options?.sessionId })
|
|
3738
5066
|
});
|
|
3739
5067
|
if (terminal && admittedRequest && !options?.signal?.aborted) recordResponsesContextUsage(output, model, options, admittedRequest, terminal.output, "provider");
|
|
3740
5068
|
finalizeTransportStream({
|
|
@@ -3743,6 +5071,7 @@ async function runResponsesStreamLifecycle(params) {
|
|
|
3743
5071
|
signal: options?.signal
|
|
3744
5072
|
});
|
|
3745
5073
|
} catch (error) {
|
|
5074
|
+
itemRecovery?.reject(error);
|
|
3746
5075
|
const response = error instanceof ResponsesStreamFailure ? error.response : error;
|
|
3747
5076
|
const rawError = isRecord(response) && isRecord(response.error) ? response.error : response;
|
|
3748
5077
|
if (params.model.provider === "openai" && params.model.api === "openai-responses" && isRecord(rawError) && rawError.code === "misalignment_policy_violation") {
|
|
@@ -3764,8 +5093,8 @@ async function runResponsesStreamLifecycle(params) {
|
|
|
3764
5093
|
error
|
|
3765
5094
|
});
|
|
3766
5095
|
} finally {
|
|
5096
|
+
itemRecovery?.finish();
|
|
3767
5097
|
firstEventAbort?.dispose();
|
|
3768
5098
|
}
|
|
3769
5099
|
}
|
|
3770
|
-
|
|
3771
|
-
export { isConfigurationUpdate as $, summarizeResponsesPayload as A, log as At, recordResponsesInputReplay as B, isInvalidEncryptedContentError as C, toOpenAIResponsesToolChoice as Ct, ResponsesStreamFailure as D, createResponseModelTracker as Dt, resolveNextResponsesEncryptedContentAttempt as E, createOpenAIResponseHook as Et, convertProviderResponsesMessages as F, resolveOpenAIClientBaseUrl as Ft, responsesContinuationPrefixFingerprint as G, claimOpenAIResponsesHttpContinuation as H, convertResponsesMessages as I, resolvePromptCacheKey as It, OPENAI_RESPONSES_FUNCTION_CALL_ITEM_ID_RE as J, responsesContinuationRequestFingerprint as K, normalizeOpenAIResponsesReasoningReplayItem as L, withOpenAIErrorResponseHook as Lt, resolveResponsesContextUsageBoundary as M, parseOpenAICompletionsUsage as Mt, bindResponsesInputMessage as N, readOpenAICompletionsContentDeltas as Nt, observeResponsesTransportFailure as O, detachPartialSnapshot as Ot, buildResponsesInputMessage as P, readOpenAICompletionsReasoningBatch as Pt, splitOpenAIFunctionCallPairing as Q, resolveReplayableResponsesMessageId as R, createResponsesStreamWithRecovery as S, reconcileOpenAIResponsesToolChoice as St, resolveAzureOpenAIApiVersion as T, createOpenAIProviderAcceptanceHook as Tt, recordResponsesContinuationState as U, responsesInputFingerprint as V, resolveResponsesContinuationRequest as W, normalizeOpenAIResponsesFunctionCallId as X, OPENAI_RESPONSES_ID_MAX_LENGTH as Y, shouldNormalizeOpenAIResponsesToolCallId as Z, isAzureResponsesTextDeltaEventType as _, resolveOpenAIRequestReasoning as _t, prepareResponsesTools as a, resolveNewestOpenAIResponsesCompactionReplay as at, resolveResponsesMessageSnapshotCollapse as b, projectOpenAITools as bt, observeResponsesStream as c, buildOpenAIClientHeaders as ct, RESPONSES_BOOKKEEPING_TIMEOUT_MS as d, enforceCodeModeResponsesToolSurface as dt, replayResponsesReasoningUpdates as et, AZURE_RESPONSES_TEXT_CONTENT_PART_TYPE as f, filterCodeModePayloadTools as ft, isAzureResponsesTextDeltaEvent as g, resolveOpenAIStrictToolFlagWithDiagnostics as gt, OPENAI_RESPONSES_OUTPUT_TEXT_DELTA_EVENT_TYPE as h, resolveCodeModeResponsesVisibleToolNames as ht, convertResponsesToolPayload as i, captureOpenAIResponsesCompaction as it, recordResponsesContextUsage as j, measureUtf8AppendBytes as jt, safeDebugValue as k, isOpenAICompletionsThinkingEnabled as kt, createResponsesToolCallTracker as l, buildOpenAISdkClientOptions as lt, OPENAI_RESPONSES_OUTPUT_TEXT_CONTENT_PART_TYPE as m, readCodeModePayloadToolName as mt, applyResponsesServiceTierPricing as n, CompactionReplayRefreshRequiredError as nt, readOpenAIMisalignmentReview as o, suppressOpenAIResponsesCompaction as ot, AZURE_RESPONSES_TEXT_DELTA_EVENT_TYPE as p, getCompat as pt, OPENAI_RESPONSES_CALL_ID_RE as q, runResponsesStreamLifecycle as r, buildOpenAIResponsesReasoningReplayMetadata as rt, processResponsesStream as s, assertCodeModeResponsesToolSurface as st, applyCommonResponsesParams as t, supportsResponsesReasoningUpdate as tt, readResponsesToolCallItemIdentity as u, buildOpenAISdkRequestOptions as ut, isResponsesTextContentPartType as v, resolveOpenAISimpleReasoningEffort as vt, readResponsesRecoveryEvent as w, GEMINI_THOUGHT_SIGNATURE_VALIDATOR_SKIP as wt, commitResponsesEncryptedContentAttempt as x, reconcileOpenAICompletionsToolChoice as xt, isResponsesTextDeltaEventType as y, prepareOpenAITools as yt, readResponsesInputReplayState as z };
|
|
5100
|
+
export { APIConnectionTimeoutError as $, readOpenAIResponsesItemRecoveryAnchor as $t, formatRequestDetails as A, resolveOpenAIClientBaseUrl as An, recordResponsesInputReplay as At, isObj as B, normalizeOpenAIResponsesFunctionCallId as Bt, createResponsesStreamWithRecovery as C, detachPartialSnapshot as Cn, resolveResponsesContextUsageBoundary as Ct, resolveAzureOpenAIApiVersion as D, parseOpenAICompletionsUsage as Dn, convertProviderResponsesMessages as Dt, readResponsesRecoveryEvent as E, measureUtf8AppendBytes as En, buildResponsesInputMessage as Et, redactURL as F, responsesContinuationPrefixFingerprint as Ft, encodeUTF8 as G, normalizeOpenAIResponsesToolArguments as Gt, maybeObj as H, splitOpenAIFunctionCallPairing as Ht, hasOwn as I, responsesContinuationRequestFingerprint as It, ReadableStreamToAsyncIterable as J, replayResponsesReasoningUpdates as Jt, CancelReadableStream as K, replayOpenAIResponsesToolArguments as Kt, isAbsoluteURL as L, OPENAI_RESPONSES_CALL_ID_RE as Lt, isSensitiveQueryParameter as M, withOpenAIErrorResponseHook as Mn, claimOpenAIResponsesHttpContinuation as Mt, loggerFor as N, recordResponsesContinuationState as Nt, resolveNextResponsesEncryptedContentAttempt as O, readOpenAICompletionsContentDeltas as On, convertResponsesMessages as Ot, parseLogLevel as P, resolveResponsesContinuationRequest as Pt, APIConnectionError as Q, captureOpenAIResponsesCompaction as Qt, isArray as R, OPENAI_RESPONSES_FUNCTION_CALL_ITEM_ID_RE as Rt, createResponsesItemConflictRecovery as S, createResponseModelTracker as Sn, recordResponsesContextUsage as St, isResponsesItemConflict as T, log as Tn, bindResponsesInputMessage as Tt, safeJSON as U, sanitizeResponsesImagePayload as Ut, isReadonlyArray as V, shouldNormalizeOpenAIResponsesToolCallId as Vt, validatePositiveInteger as W, normalizeOpenAIResponsesReasoningReplayItem as Wt, __classPrivateFieldGet as X, CompactionReplayRefreshRequiredError as Xt, getDefaultFetch as Y, supportsResponsesReasoningUpdate as Yt, __classPrivateFieldSet as Z, buildOpenAIResponsesReasoningReplayMetadata as Zt, isAzureResponsesTextDeltaEventType as _, reconcileOpenAIResponsesToolChoice as _n, isAbortError as _t, prepareResponsesTools as a, buildOpenAISdkRequestOptions as an, ContentFilterFinishReasonError as at, resolveResponsesMessageSnapshotCollapse as b, createOpenAIProviderAcceptanceHook as bn, safeDebugValue as bt, observeResponsesStream as c, getCompat as cn, LengthFinishReasonError as ct, RESPONSES_BOOKKEEPING_TIMEOUT_MS as d, resolveOpenAIStrictToolFlagWithDiagnostics as dn, OpenAIError as dt, resolveNewestOpenAIResponsesCompactionReplay as en, APIError as et, AZURE_RESPONSES_TEXT_CONTENT_PART_TYPE as f, resolveOpenAIRequestReasoning as fn, PermissionDeniedError as ft, isAzureResponsesTextDeltaEvent as g, reconcileOpenAICompletionsToolChoice as gn, castToError as gt, OPENAI_RESPONSES_OUTPUT_TEXT_DELTA_EVENT_TYPE as h, projectOpenAITools as hn, UnprocessableEntityError as ht, convertResponsesToolPayload as i, buildOpenAISdkClientOptions as in, ConflictError as it, isSensitiveHeader as j, resolvePromptCacheKey as jn, responsesInputFingerprint as jt, Stream as k, readOpenAICompletionsReasoningBatch as kn, readResponsesInputReplayState as kt, createResponsesToolCallTracker as l, readCodeModePayloadToolName as ln, NotFoundError as lt, OPENAI_RESPONSES_OUTPUT_TEXT_CONTENT_PART_TYPE as m, prepareOpenAITools as mn, SubjectTokenProviderError as mt, applyResponsesServiceTierPricing as n, assertCodeModeResponsesToolSurface as nn, AuthenticationError as nt, readOpenAIMisalignmentReview as o, enforceCodeModeResponsesToolSurface as on, InternalServerError as ot, AZURE_RESPONSES_TEXT_DELTA_EVENT_TYPE as p, resolveOpenAISimpleReasoningEffort as pn, RateLimitError as pt, ReadableStreamFrom as q, isConfigurationUpdate as qt, runResponsesStreamLifecycle as r, buildOpenAIClientHeaders as rn, BadRequestError as rt, processResponsesStream as s, filterCodeModePayloadTools as sn, InvalidWebhookSignatureError as st, applyCommonResponsesParams as t, suppressOpenAIResponsesCompaction as tn, APIUserAbortError as tt, readResponsesToolCallItemIdentity as u, resolveCodeModeResponsesVisibleToolNames as un, OAuthError as ut, isResponsesTextContentPartType as v, toOpenAIResponsesToolChoice as vn, ResponsesStreamFailure as vt, isInvalidEncryptedContentError as w, isOpenAICompletionsThinkingEnabled as wn, takeResponsesContextUsageInput as wt, commitResponsesEncryptedContentAttempt as x, createOpenAIResponseHook as xn, summarizeResponsesPayload as xt, isResponsesTextDeltaEventType as y, GEMINI_THOUGHT_SIGNATURE_VALIDATOR_SKIP as yn, observeResponsesTransportFailure as yt, isEmptyObj as z, OPENAI_RESPONSES_ID_MAX_LENGTH as zt };
|