@openclaw/ai 2026.11.3 → 2026.11.5-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -8
- package/dist/.source-module-urls/fe058cc430242ce2ab0dfbcbe153e240a52cf9c3072c3dc0a73e5f956b6ba49b.json +1 -0
- package/dist/anthropic-DEKgalVg.mjs +182 -0
- package/dist/{anthropic-payload-policy-C0ki72BT.d.mts → anthropic-payload-policy-CXCJ5Pmj.d.mts} +21 -4
- package/dist/{anthropic-stream-reducer-yWDb5Cct.mjs → anthropic-stream-lifecycle-DF2qVvg1.mjs} +845 -649
- package/dist/{anthropic-tool-projection-C2-d1eZ3.d.mts → anthropic-tool-projection-D5DyrL6C.d.mts} +6 -7
- package/dist/{anthropic-tool-projection-DZOKfAmL.mjs → anthropic-tool-projection-dGRfr4iT.mjs} +22 -32
- package/dist/{api-registry-gDt0faai.d.mts → api-registry-DY2MLUyg.d.mts} +2 -2
- package/dist/assistant-output-CD4kY9gu.mjs +16 -0
- package/dist/{azure-openai-responses-BvvXzZbi.mjs → azure-openai-responses-DbQV5RTx.mjs} +47 -53
- package/dist/{cloudflare-Dttf8jKq.mjs → cloudflare-BJ2_Xabx.mjs} +1 -1
- package/dist/{credential-redaction-XvsPf7Yi.d.mts → credential-redaction-DrgndwTJ.d.mts} +5 -3
- package/dist/{deferred-event-buffer-DAvyP7qA.mjs → deferred-event-buffer-tIGkTkTm.mjs} +1 -2
- package/dist/{diagnostics-v7oVEW59.mjs → diagnostics-CloVGQiK.mjs} +27 -20
- package/dist/{diagnostics-DzrF1h4J.mjs → diagnostics-o1PrVNQb.mjs} +11 -4
- package/dist/diagnostics.d.mts +6 -7
- package/dist/diagnostics.mjs +4 -4
- package/dist/{env-api-keys-Xd8dm_aV.mjs → env-api-keys-BuHc86ya.mjs} +1 -26
- package/dist/event-stream-B4ZcSvsu.d.mts +1 -0
- package/dist/{event-stream-CzpE1g_o.d.mts → event-stream-BYmtRe8-.d.mts} +1 -1
- package/dist/event-stream.d.mts +2 -2
- package/dist/event-stream.mjs +1 -2
- package/dist/expect-lbe3Hgrh.mjs +8 -0
- package/dist/{github-copilot-request-facts-F-EmvkpW.mjs → github-copilot-request-facts-BZ_EMo7X.mjs} +1 -1
- package/dist/{google-Cpi_cLKZ.mjs → google-B1g82bn4.mjs} +7 -8
- package/dist/{google-interactions-CGINbsjO.mjs → google-interactions-Ckr0Z99Z.mjs} +243 -269
- package/dist/{google-messages-DQMgG5yG.mjs → google-messages-A-9d3y5V.mjs} +52 -18
- package/dist/{google-provider-stream-BHd0cST9.mjs → google-provider-stream-CNVh4gpm.mjs} +19 -11
- package/dist/{google-shared-vtag8bj5.mjs → google-shared-WNM86ZcW.mjs} +72 -42
- package/dist/{google-vertex-eKoUnW7N.mjs → google-vertex-CXjleC6g.mjs} +3 -3
- package/dist/{google-video-slots-D8tPH8wX.mjs → google-video-slots-Bxt-OXO8.mjs} +1 -1
- package/dist/{host-CWt55nnF.mjs → host-DX7ORpeH.mjs} +46 -39
- package/dist/{host-jJOffdlW.d.mts → host-ccbwPC3A.d.mts} +17 -9
- package/dist/{host-policy-Dm7PM6AD.mjs → host-policy-jCZebuXx.mjs} +2 -2
- package/dist/index-Bczt0MnO.d.mts +17 -0
- package/dist/index.d.mts +8 -7
- package/dist/index.mjs +9 -7
- package/dist/internal/anthropic.d.mts +21 -26
- package/dist/internal/anthropic.mjs +6 -6
- package/dist/internal/google-model-family.mjs +1 -1
- package/dist/internal/google.d.mts +15 -0
- package/dist/internal/google.mjs +1 -0
- package/dist/internal/model-request-body.d.mts +37 -0
- package/dist/internal/model-request-body.mjs +106 -0
- package/dist/internal/openai-completions-compat.d.mts +1 -1
- package/dist/internal/openai-completions-compat.mjs +1 -1
- package/dist/internal/openai-responses-payload-policy.d.mts +2 -2
- package/dist/internal/openai-responses-payload-policy.mjs +2 -2
- package/dist/internal/openai.d.mts +14 -12
- package/dist/internal/openai.mjs +11 -10
- package/dist/internal/reasoning-tag-text-partitioner.d.mts +26 -0
- package/dist/{reasoning-tag-text-partitioner-CU9A4Lg8.mjs → internal/reasoning-tag-text-partitioner.mjs} +313 -111
- package/dist/internal/retry-after.d.mts +2 -2
- package/dist/internal/retry-after.mjs +96 -32
- package/dist/internal/runtime.d.mts +15 -41
- package/dist/internal/runtime.mjs +9 -10
- package/dist/internal/shared.d.mts +21 -25
- package/dist/internal/shared.mjs +9 -98
- package/dist/internal/tool-schema.d.mts +10 -10
- package/dist/internal/tool-schema.mjs +4 -4
- package/dist/{llm-request-activity-CfMuh5cC.mjs → llm-request-activity-DzaHoRAU.mjs} +2 -2
- package/dist/mistral-CjHkvsqR.mjs +3741 -0
- package/dist/{openai.LICENSE → mistral.LICENSE} +1 -1
- package/dist/{model-transport-url-BrsjjdjR.d.mts → model-transport-url-BdksnBqu.d.mts} +6 -8
- package/dist/{number-coercion-37gmNkuA.mjs → number-coercion-C7HsBgUL.mjs} +7 -2
- package/dist/observe-async-iterator-AlARO5wS.d.mts +178 -0
- package/dist/observe-async-iterator-DgmegcZR.mjs +181 -0
- package/dist/{openai-chatgpt-responses-BZa3SySh.mjs → openai-chatgpt-responses-CwS5JP7A.mjs} +61 -80
- package/dist/{openai-completions-compat-CBvb2eld.d.mts → openai-completions-compat-CJ-NsDzg.d.mts} +12 -6
- package/dist/{openai-completions-compat-bNQXF1y9.mjs → openai-completions-compat-CstlTQuF.mjs} +74 -50
- package/dist/{openai-completions-CCZ_UHCk.mjs → openai-completions-sj4S-RXQ.mjs} +5 -5
- package/dist/openai-completions-transport-BDAIA0_P.mjs +3406 -0
- package/dist/{openai-prompt-cache-DgjD-UL5.d.mts → openai-prompt-cache-BZGaIWYh.d.mts} +4 -4
- package/dist/{openai-prompt-cache-B9AvdoEo.mjs → openai-prompt-cache-CgDoFhO0.mjs} +5 -4
- package/dist/{openai-responses-compaction-replay-_sUXtcwU.d.mts → openai-responses-compaction-replay-CNHk6k53.d.mts} +4 -4
- package/dist/{openai-responses-contracts-B1nkeLL6.d.mts → openai-responses-contracts-BXMcvO7F.d.mts} +4 -10
- package/dist/{openai-responses-contracts-B5mGAbR6.mjs → openai-responses-contracts-xU-n9AJJ.mjs} +36 -37
- package/dist/{openai-responses-endpoint-CfKR6N5f.mjs → openai-responses-endpoint-DCkURKS0.mjs} +55 -8
- package/dist/openai-responses-ev_c6oTy.mjs +89 -0
- package/dist/{openai-responses-payload-policy-BzM52TTH.d.mts → openai-responses-payload-policy-DyE30gdD.d.mts} +7 -7
- package/dist/{openai-responses-request-lifecycle-CTqHc02t.mjs → openai-responses-request-lifecycle-BuOs0mwI.mjs} +12 -26
- package/dist/{openai-responses-shared-wx9v1MCn.mjs → openai-responses-shared-BmRQnUPP.mjs} +633 -1493
- package/dist/{openai-responses-terminal-usage-CpVjkqn-.d.mts → openai-responses-terminal-usage-D7IhRA6i.d.mts} +9 -3
- package/dist/{openai-tool-schema-BTEU2xmN.mjs → openai-tool-schema-CsoYgnWy.mjs} +97 -122
- package/dist/otel-Buswj0Mf.mjs +766 -0
- package/dist/{overflow-OF3PgPbw.mjs → overflow-CpApyjG2.mjs} +1 -1
- package/dist/{positive-integer-Bb4Evc7L.mjs → positive-integer-DiqE5vNi.mjs} +2 -3
- package/dist/{prompt-cache-stability-D_MeCQFI.mjs → prompt-cache-stability-w-ICeyOI.mjs} +1 -1
- package/dist/{provider-error-qtZD2inE.mjs → provider-error-DD-fo4Rz.mjs} +71 -234
- package/dist/{provider-options-DAzsyi49.d.mts → provider-options-Mo8NM5d1.d.mts} +16 -5
- package/dist/{provider-replay-context-4vxI7p4V.mjs → provider-replay-context-xyU7-CiT.mjs} +2 -2
- package/dist/provider-transcript-transform-DtaxNcC1.mjs +32 -0
- package/dist/{provider-transport-turn-state-D_GjPJHe.mjs → provider-transport-turn-state-BIS8maBK.mjs} +4 -4
- package/dist/{provider-types-CWl4VXvE.d.mts → provider-types-B1e98js5.d.mts} +3 -3
- package/dist/provider-types.d.mts +7 -6
- package/dist/providers.d.mts +2 -2
- package/dist/providers.mjs +26 -29
- package/dist/{record-coerce-CNDovvft.mjs → record-coerce-BQaoiN3r.mjs} +4 -1
- package/dist/request-headers-DO4Mqhw1.mjs +10 -0
- package/dist/{required-api-key-D088S4Cd.mjs → required-api-key-2zZTkmsi.mjs} +1 -1
- package/dist/{retry-after-BrmTv0jL.d.mts → retry-after-DnHBlFS2.d.mts} +21 -1
- package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
- package/dist/{sanitize-unicode-ZqVLLEKC.d.mts → sanitize-unicode-BISmUlUv.d.mts} +2 -2
- package/dist/{simple-options-xJkqrG_E.mjs → simple-options-tLSeECry.mjs} +108 -82
- package/dist/src-BUsVkrNt.mjs +105 -0
- package/dist/{src-CyA0zJnt.mjs → src-CQ7nH2mL.mjs} +4 -7
- package/dist/stable-stringify-CchQEmeA.mjs +84 -0
- package/dist/{stream-C4YDqhFj.mjs → stream-DrtAWu7c.mjs} +2 -6
- package/dist/{stream-first-event-timeout-D_TfJHRJ.mjs → stream-first-event-timeout-B7RcufAV.mjs} +16 -13
- package/dist/{string-coerce-Cj8sqWHx.mjs → string-coerce-BCuWMIrk.mjs} +1 -1
- package/dist/string-normalization-B8TDDBX_.mjs +32 -0
- package/dist/telemetry-CvK1yQg7.mjs +582 -0
- package/dist/{tool-schema-json-projection-B1sTYwfH.mjs → tool-schema-json-projection-BQpiJlXJ.mjs} +53 -69
- package/dist/{transport-stream-shared-lhgkTOz3.mjs → transport-stream-shared-D2uFMhMc.mjs} +177 -93
- package/dist/{transport-stream-shared-8ru8eX4s.d.mts → transport-stream-shared-D3IAU4jn.d.mts} +29 -15
- package/dist/{transport-utils-DwOpuTjL.mjs → transport-utils-Da_39MYi.mjs} +23 -38
- package/dist/transports.d.mts +42 -39
- package/dist/transports.mjs +215 -296
- package/dist/{types-CVYzKrMl.d.mts → types-BVdTf0YV.d.mts} +38 -3
- package/dist/types-Cb3-5WM9.d.mts +1 -0
- package/dist/{types-BXd0kI8-.mjs → types-OVEWUaDh.mjs} +3 -1
- package/dist/types.d.mts +7 -6
- package/dist/types.mjs +7 -5
- package/dist/{validation-9FSkE8T-.mjs → validation-DGXqfvkj.mjs} +45 -27
- package/dist/{validation-BQ5u20Ru.d.mts → validation-QmyD0E5A.d.mts} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -2
- package/package.json +40 -6
- package/dist/anthropic-lueA8LUg.mjs +0 -221
- package/dist/assistant-output-BnQm3fov.mjs +0 -47
- package/dist/event-stream-CDpFza-M.d.mts +0 -1
- package/dist/index-DSprYWaz.d.mts +0 -185
- package/dist/mistral-CQ7aoWg2.mjs +0 -512
- package/dist/model-request-body-BD5vy4rP.d.mts +0 -17
- package/dist/openai-CiRi-nVE.mjs +0 -20077
- package/dist/openai-completions-transport-DFvSBbUT.mjs +0 -10881
- package/dist/openai-responses-DQsZKUoI.mjs +0 -87
- package/dist/rolldown-runtime-B4iAMlE-.mjs +0 -35
- package/dist/types-CBJthzJX.d.mts +0 -1
- package/dist/ws.LICENSE +0 -20
|
@@ -1,1109 +1,40 @@
|
|
|
1
|
-
import "./src-
|
|
2
|
-
import {
|
|
3
|
-
import { o as readProviderRefusalReview, t as appendAssistantMessageDiagnostic } from "./diagnostics-
|
|
1
|
+
import "./src-CQ7nH2mL.mjs";
|
|
2
|
+
import { m as isRuntimeContextMessage, p as hasRuntimeContextMarker, v as runtimeContextContentToText } from "./types-OVEWUaDh.mjs";
|
|
3
|
+
import { o as readProviderRefusalReview, t as appendAssistantMessageDiagnostic } from "./diagnostics-o1PrVNQb.mjs";
|
|
4
4
|
import { r as appendAssistantThinking } from "./event-stream-X2gmsUWv.mjs";
|
|
5
|
-
import { o as isRecord,
|
|
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 {
|
|
9
|
-
import {
|
|
5
|
+
import { i as asOptionalRecord, o as isRecord, s as isStringArray } from "./record-coerce-BQaoiN3r.mjs";
|
|
6
|
+
import { l as readStringValue, o as normalizeOptionalString, r as normalizeLowercaseStringOrEmpty, s as normalizeStringifiedOptionalString } from "./string-coerce-BCuWMIrk.mjs";
|
|
7
|
+
import { t as asFiniteNumber } from "./number-coercion-C7HsBgUL.mjs";
|
|
8
|
+
import { t as observeAsyncIterator } from "./observe-async-iterator-DgmegcZR.mjs";
|
|
9
|
+
import { D as applyProviderReportedUsageCost, E as headersToRecord, N as isImageWithMediaPayload, O as calculateCost, a as resolveAiTransportHeaderSentinels, k as clampThinkingLevel, r as getAiTransportHost } from "./host-DX7ORpeH.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-xU-n9AJJ.mjs";
|
|
10
11
|
import { n as getSessionResourceOwnerId, r as registerSessionResourceCleanup } from "./session-resources-vKvGIE3J.mjs";
|
|
11
|
-
import {
|
|
12
|
-
import
|
|
13
|
-
import {
|
|
14
|
-
import { a as
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import { n as
|
|
23
|
-
import { t as notifyLlmRequestActivity } from "./llm-request-activity-
|
|
12
|
+
import { r as readTransportDiagnosticLabel } from "./provider-error-DD-fo4Rz.mjs";
|
|
13
|
+
import "./src-BUsVkrNt.mjs";
|
|
14
|
+
import { n as clampOpenAIPromptCacheKey } from "./openai-prompt-cache-CgDoFhO0.mjs";
|
|
15
|
+
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-CloVGQiK.mjs";
|
|
16
|
+
import { n as isCodeModeModelVisibleToolName } from "./transport-utils-Da_39MYi.mjs";
|
|
17
|
+
import { t as stableStringify } from "./stable-stringify-CchQEmeA.mjs";
|
|
18
|
+
import { a as resolveOpenAICompletionsCompat, n as isKnownOpenAIEndpoint, s as usesNativeOpenAICodexResponsesBackend, u as resolveOpenAIResponsesTextFormat } from "./openai-completions-compat-CstlTQuF.mjs";
|
|
19
|
+
import { r as resolveModelRequestTimeoutMs } from "./host-policy-jCZebuXx.mjs";
|
|
20
|
+
import { r as sortPromptCacheToolsByName } from "./prompt-cache-stability-w-ICeyOI.mjs";
|
|
21
|
+
import { a as describeToolResultMediaPlaceholder, c as extractToolResultText, f as preparedRequestSuffix, r as clampMaxTokensToModel, s as extractToolResultBlockText, u as codeModeToolSurfaceObserver, y as prepareSystemPrompt } from "./simple-options-tLSeECry.mjs";
|
|
22
|
+
import { A as parseStreamingJson, C as withProviderResponseHook, D as shortHash, O as createToolArgumentPreviewSchedule, _ as parseTerminalToolCallArguments, c as failTransportStream, d as iterateModelStream, h as notifyProviderHttpResponse, s as decodeSseFrames, t as IncompleteToolCallError, u as finalizeTransportStream, w as parseJsonObjectPreservingUnsafeIntegers, x as transportAbortError, y as sanitizeTransportPayloadText } from "./transport-stream-shared-D2uFMhMc.mjs";
|
|
23
|
+
import { C as sha256Hex, S as redactIdentifier, n as prepareRuntimeToolInputSchema, r as projectRuntimeToolInputSchema, w as sha256StableValue } from "./tool-schema-json-projection-BQpiJlXJ.mjs";
|
|
24
|
+
import { t as notifyLlmRequestActivity } from "./llm-request-activity-DzaHoRAU.mjs";
|
|
25
|
+
import { n as isProviderReplayContext, r as providerReplayContextMatches, t as buildProviderReplayContext } from "./provider-replay-context-xyU7-CiT.mjs";
|
|
26
|
+
import { t as transformProviderMessages } from "./provider-transcript-transform-DtaxNcC1.mjs";
|
|
27
|
+
import { prepareModelRequestBody } from "./internal/model-request-body.mjs";
|
|
28
|
+
import "./assistant-output-CD4kY9gu.mjs";
|
|
24
29
|
import { n as resolveOpencodeSessionHeaders } from "./session-affinity-DA4WHv1h.mjs";
|
|
25
|
-
import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "./stream-first-event-timeout-
|
|
26
|
-
import { a as resolveOpenAIProjectedToolsStrictToolFlag,
|
|
27
|
-
import { a as isOpenAIResponsesCompactionOutput, n as supportsNativeOpenAIResponsesEndpoint, o as readOpenAIResponsesCompactionWindow } from "./openai-responses-endpoint-
|
|
30
|
+
import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "./stream-first-event-timeout-B7RcufAV.mjs";
|
|
31
|
+
import { a as resolveOpenAIProjectedToolsStrictToolFlag, m as withPreparedToolSchemaNormalization, r as normalizeOpenAIStrictToolParameters, t as findOpenAIStrictToolProjectionDiagnostics, x as prepareOpenAIFunctionTool } from "./openai-tool-schema-CsoYgnWy.mjs";
|
|
32
|
+
import { a as isOpenAIResponsesCompactionOutput, n as supportsNativeOpenAIResponsesEndpoint, o as readOpenAIResponsesCompactionWindow, s as buildResponsesInputImage } from "./openai-responses-endpoint-DCkURKS0.mjs";
|
|
28
33
|
import { randomUUID } from "node:crypto";
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
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");
|
|
34
|
-
return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
|
|
35
|
-
}
|
|
36
|
-
function __classPrivateFieldGet(receiver, state, kind, f) {
|
|
37
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
38
|
-
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");
|
|
39
|
-
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
40
|
-
}
|
|
41
|
-
//#endregion
|
|
42
|
-
//#region node_modules/.pnpm/openai@7.28.0_@aws-sdk+credential-provider-node@3.972.84_@smithy+hash-node@4.5.2_@smith_228c78b5ff380a7908ad856e85d64d8d/node_modules/openai/internal/errors.mjs
|
|
43
|
-
function isAbortError(err) {
|
|
44
|
-
return typeof err === "object" && err !== null && ("name" in err && err.name === "AbortError" || "message" in err && String(err.message).includes("FetchRequestCanceledException"));
|
|
45
|
-
}
|
|
46
|
-
const castToError = (err) => {
|
|
47
|
-
if (err instanceof Error) return err;
|
|
48
|
-
if (typeof err === "object" && err !== null) {
|
|
49
|
-
try {
|
|
50
|
-
if (Object.prototype.toString.call(err) === "[object Error]") {
|
|
51
|
-
const hasCause = "cause" in err;
|
|
52
|
-
const error = new Error(err.message, hasCause ? { cause: err.cause } : {});
|
|
53
|
-
if (err.stack) error.stack = err.stack;
|
|
54
|
-
if (hasCause && !Object.prototype.hasOwnProperty.call(error, "cause")) error.cause = err.cause;
|
|
55
|
-
if (err.name) error.name = err.name;
|
|
56
|
-
return error;
|
|
57
|
-
}
|
|
58
|
-
} catch {}
|
|
59
|
-
try {
|
|
60
|
-
return new Error(JSON.stringify(err));
|
|
61
|
-
} catch {}
|
|
62
|
-
}
|
|
63
|
-
return new Error(err);
|
|
64
|
-
};
|
|
65
|
-
//#endregion
|
|
66
|
-
//#region node_modules/.pnpm/openai@7.28.0_@aws-sdk+credential-provider-node@3.972.84_@smithy+hash-node@4.5.2_@smith_228c78b5ff380a7908ad856e85d64d8d/node_modules/openai/core/error.mjs
|
|
67
|
-
var OpenAIError = class extends Error {};
|
|
68
|
-
var APIError = class APIError extends OpenAIError {
|
|
69
|
-
constructor(status, error, message, headers) {
|
|
70
|
-
super(`${APIError.makeMessage(status, error, message)}`);
|
|
71
|
-
this.status = status;
|
|
72
|
-
this.headers = headers;
|
|
73
|
-
this.requestID = headers?.get("x-request-id");
|
|
74
|
-
this.error = error;
|
|
75
|
-
const data = error;
|
|
76
|
-
this.code = data?.["code"];
|
|
77
|
-
this.param = data?.["param"];
|
|
78
|
-
this.type = data?.["type"];
|
|
79
|
-
}
|
|
80
|
-
static makeMessage(status, error, message) {
|
|
81
|
-
const msg = error?.message ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message;
|
|
82
|
-
if (status && msg) return `${status} ${msg}`;
|
|
83
|
-
if (status) return `${status} status code (no body)`;
|
|
84
|
-
if (msg) return msg;
|
|
85
|
-
return "(no status code or body)";
|
|
86
|
-
}
|
|
87
|
-
static generate(status, errorResponse, message, headers) {
|
|
88
|
-
if (!status || !headers) return new APIConnectionError({
|
|
89
|
-
message,
|
|
90
|
-
cause: castToError(errorResponse)
|
|
91
|
-
});
|
|
92
|
-
const error = errorResponse?.["error"];
|
|
93
|
-
if (status === 400) return new BadRequestError(status, error, message, headers);
|
|
94
|
-
if (status === 401) return new AuthenticationError(status, error, message, headers);
|
|
95
|
-
if (status === 403) return new PermissionDeniedError(status, error, message, headers);
|
|
96
|
-
if (status === 404) return new NotFoundError(status, error, message, headers);
|
|
97
|
-
if (status === 409) return new ConflictError(status, error, message, headers);
|
|
98
|
-
if (status === 422) return new UnprocessableEntityError(status, error, message, headers);
|
|
99
|
-
if (status === 429) return new RateLimitError(status, error, message, headers);
|
|
100
|
-
if (status >= 500) return new InternalServerError(status, error, message, headers);
|
|
101
|
-
return new APIError(status, error, message, headers);
|
|
102
|
-
}
|
|
103
|
-
};
|
|
104
|
-
var APIUserAbortError = class extends APIError {
|
|
105
|
-
constructor({ message } = {}) {
|
|
106
|
-
super(void 0, void 0, message || "Request was aborted.", void 0);
|
|
107
|
-
}
|
|
108
|
-
};
|
|
109
|
-
var APIConnectionError = class extends APIError {
|
|
110
|
-
constructor({ message, cause }) {
|
|
111
|
-
super(void 0, void 0, message || "Connection error.", void 0);
|
|
112
|
-
if (cause) this.cause = cause;
|
|
113
|
-
}
|
|
114
|
-
};
|
|
115
|
-
var APIConnectionTimeoutError = class extends APIConnectionError {
|
|
116
|
-
constructor({ message } = {}) {
|
|
117
|
-
super({ message: message ?? "Request timed out." });
|
|
118
|
-
}
|
|
119
|
-
};
|
|
120
|
-
var BadRequestError = class extends APIError {};
|
|
121
|
-
var AuthenticationError = class extends APIError {};
|
|
122
|
-
var PermissionDeniedError = class extends APIError {};
|
|
123
|
-
var NotFoundError = class extends APIError {};
|
|
124
|
-
var ConflictError = class extends APIError {};
|
|
125
|
-
var UnprocessableEntityError = class extends APIError {};
|
|
126
|
-
var RateLimitError = class extends APIError {};
|
|
127
|
-
var InternalServerError = class extends APIError {};
|
|
128
|
-
var LengthFinishReasonError = class extends OpenAIError {
|
|
129
|
-
constructor() {
|
|
130
|
-
super(`Could not parse response content as the length limit was reached`);
|
|
131
|
-
}
|
|
132
|
-
};
|
|
133
|
-
var ContentFilterFinishReasonError = class extends OpenAIError {
|
|
134
|
-
constructor() {
|
|
135
|
-
super(`Could not parse response content as the request was rejected by the content filter`);
|
|
136
|
-
}
|
|
137
|
-
};
|
|
138
|
-
var InvalidWebhookSignatureError = class extends Error {
|
|
139
|
-
constructor(message) {
|
|
140
|
-
super(message);
|
|
141
|
-
}
|
|
142
|
-
};
|
|
143
|
-
/**
|
|
144
|
-
* Error thrown by the API server during OAuth token exchange.
|
|
145
|
-
* Can have status codes 400, 401, or 403.
|
|
146
|
-
* Other status codes from OAuth endpoints are raised as normal APIError types.
|
|
147
|
-
*/
|
|
148
|
-
var OAuthError = class extends APIError {
|
|
149
|
-
constructor(status, error, headers) {
|
|
150
|
-
let finalMessage = "OAuth2 authentication error";
|
|
151
|
-
let error_code = void 0;
|
|
152
|
-
if (error && typeof error === "object") {
|
|
153
|
-
const errorData = error;
|
|
154
|
-
error_code = errorData["error"];
|
|
155
|
-
const description = errorData["error_description"];
|
|
156
|
-
if (description && typeof description === "string") finalMessage = description;
|
|
157
|
-
else if (error_code) finalMessage = error_code;
|
|
158
|
-
}
|
|
159
|
-
super(status, error, finalMessage, headers);
|
|
160
|
-
this.error_code = error_code;
|
|
161
|
-
}
|
|
162
|
-
};
|
|
163
|
-
var SubjectTokenProviderError = class extends OpenAIError {
|
|
164
|
-
constructor(message, provider, cause) {
|
|
165
|
-
super(message);
|
|
166
|
-
this.provider = provider;
|
|
167
|
-
this.cause = cause;
|
|
168
|
-
}
|
|
169
|
-
};
|
|
170
|
-
//#endregion
|
|
171
|
-
//#region node_modules/.pnpm/openai@7.28.0_@aws-sdk+credential-provider-node@3.972.84_@smithy+hash-node@4.5.2_@smith_228c78b5ff380a7908ad856e85d64d8d/node_modules/openai/internal/utils/values.mjs
|
|
172
|
-
const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;
|
|
173
|
-
const isAbsoluteURL = (url) => {
|
|
174
|
-
return startsWithSchemeRegexp.test(url);
|
|
175
|
-
};
|
|
176
|
-
let isArray = (val) => (isArray = Array.isArray, isArray(val));
|
|
177
|
-
let isReadonlyArray = isArray;
|
|
178
|
-
/** Returns an object if the given value isn't an object, otherwise returns as-is */
|
|
179
|
-
function maybeObj(x) {
|
|
180
|
-
if (typeof x !== "object") return {};
|
|
181
|
-
return x ?? {};
|
|
182
|
-
}
|
|
183
|
-
function isEmptyObj(obj) {
|
|
184
|
-
if (!obj) return true;
|
|
185
|
-
for (const _k in obj) return false;
|
|
186
|
-
return true;
|
|
187
|
-
}
|
|
188
|
-
function hasOwn(obj, key) {
|
|
189
|
-
return Object.prototype.hasOwnProperty.call(obj, key);
|
|
190
|
-
}
|
|
191
|
-
function isObj(obj) {
|
|
192
|
-
return obj != null && typeof obj === "object" && !Array.isArray(obj);
|
|
193
|
-
}
|
|
194
|
-
const validatePositiveInteger = (name, n) => {
|
|
195
|
-
if (typeof n !== "number" || !Number.isInteger(n)) throw new OpenAIError(`${name} must be an integer`);
|
|
196
|
-
if (n < 0) throw new OpenAIError(`${name} must be a positive integer`);
|
|
197
|
-
return n;
|
|
198
|
-
};
|
|
199
|
-
const safeJSON = (text) => {
|
|
200
|
-
try {
|
|
201
|
-
return JSON.parse(text);
|
|
202
|
-
} catch (err) {
|
|
203
|
-
return;
|
|
204
|
-
}
|
|
205
|
-
};
|
|
206
|
-
//#endregion
|
|
207
|
-
//#region node_modules/.pnpm/openai@7.28.0_@aws-sdk+credential-provider-node@3.972.84_@smithy+hash-node@4.5.2_@smith_228c78b5ff380a7908ad856e85d64d8d/node_modules/openai/internal/shims.mjs
|
|
208
|
-
/**
|
|
209
|
-
* This module provides internal shims and utility functions for environments where certain Node.js or global types may not be available.
|
|
210
|
-
*
|
|
211
|
-
* These are used to ensure we can provide a consistent behaviour between different JavaScript environments and good error
|
|
212
|
-
* messages in cases where an environment isn't fully supported.
|
|
213
|
-
*/
|
|
214
|
-
function getDefaultFetch() {
|
|
215
|
-
if (typeof fetch !== "undefined") return fetch;
|
|
216
|
-
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`");
|
|
217
|
-
}
|
|
218
|
-
function makeReadableStream(...args) {
|
|
219
|
-
const ReadableStream = globalThis.ReadableStream;
|
|
220
|
-
if (typeof ReadableStream === "undefined") throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");
|
|
221
|
-
return new ReadableStream(...args);
|
|
222
|
-
}
|
|
223
|
-
function ReadableStreamFrom(iterable) {
|
|
224
|
-
let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator]();
|
|
225
|
-
return makeReadableStream({
|
|
226
|
-
start() {},
|
|
227
|
-
async pull(controller) {
|
|
228
|
-
const { done, value } = await iter.next();
|
|
229
|
-
if (done) controller.close();
|
|
230
|
-
else controller.enqueue(value);
|
|
231
|
-
},
|
|
232
|
-
async cancel() {
|
|
233
|
-
await iter.return?.();
|
|
234
|
-
}
|
|
235
|
-
});
|
|
236
|
-
}
|
|
237
|
-
/**
|
|
238
|
-
* Most browsers don't yet have async iterable support for ReadableStream,
|
|
239
|
-
* and Node has a very different way of reading bytes from its "ReadableStream".
|
|
240
|
-
*
|
|
241
|
-
* This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
|
|
242
|
-
*/
|
|
243
|
-
function ReadableStreamToAsyncIterable(stream) {
|
|
244
|
-
if (stream[Symbol.asyncIterator]) return stream;
|
|
245
|
-
const reader = stream.getReader();
|
|
246
|
-
return {
|
|
247
|
-
async next() {
|
|
248
|
-
try {
|
|
249
|
-
const result = await reader.read();
|
|
250
|
-
if (result?.done) reader.releaseLock();
|
|
251
|
-
return result;
|
|
252
|
-
} catch (e) {
|
|
253
|
-
reader.releaseLock();
|
|
254
|
-
throw e;
|
|
255
|
-
}
|
|
256
|
-
},
|
|
257
|
-
async return() {
|
|
258
|
-
const cancelPromise = reader.cancel();
|
|
259
|
-
reader.releaseLock();
|
|
260
|
-
await cancelPromise;
|
|
261
|
-
return {
|
|
262
|
-
done: true,
|
|
263
|
-
value: void 0
|
|
264
|
-
};
|
|
265
|
-
},
|
|
266
|
-
[Symbol.asyncIterator]() {
|
|
267
|
-
return this;
|
|
268
|
-
}
|
|
269
|
-
};
|
|
270
|
-
}
|
|
271
|
-
/**
|
|
272
|
-
* Cancels a ReadableStream we don't need to consume.
|
|
273
|
-
* See https://undici.nodejs.org/#/?id=garbage-collection
|
|
274
|
-
*/
|
|
275
|
-
async function CancelReadableStream(stream) {
|
|
276
|
-
if (stream === null || typeof stream !== "object") return;
|
|
277
|
-
if (stream[Symbol.asyncIterator]) {
|
|
278
|
-
await stream[Symbol.asyncIterator]().return?.();
|
|
279
|
-
return;
|
|
280
|
-
}
|
|
281
|
-
const reader = stream.getReader();
|
|
282
|
-
const cancelPromise = reader.cancel();
|
|
283
|
-
reader.releaseLock();
|
|
284
|
-
await cancelPromise;
|
|
285
|
-
}
|
|
286
|
-
//#endregion
|
|
287
|
-
//#region node_modules/.pnpm/openai@7.28.0_@aws-sdk+credential-provider-node@3.972.84_@smithy+hash-node@4.5.2_@smith_228c78b5ff380a7908ad856e85d64d8d/node_modules/openai/internal/utils/bytes.mjs
|
|
288
|
-
let encodeUTF8_;
|
|
289
|
-
/** Encodes text as UTF-8 bytes, reusing the platform encoder after its first call. */
|
|
290
|
-
function encodeUTF8(str) {
|
|
291
|
-
let encoder;
|
|
292
|
-
return (encodeUTF8_ ?? (encoder = new globalThis.TextEncoder(), encodeUTF8_ = encoder.encode.bind(encoder)))(str);
|
|
293
|
-
}
|
|
294
|
-
let decodeUTF8_;
|
|
295
|
-
/** Decodes UTF-8 bytes as text, reusing the platform decoder after its first call. */
|
|
296
|
-
function decodeUTF8(bytes) {
|
|
297
|
-
let decoder;
|
|
298
|
-
return (decodeUTF8_ ?? (decoder = new globalThis.TextDecoder(), decodeUTF8_ = decoder.decode.bind(decoder)))(bytes);
|
|
299
|
-
}
|
|
300
|
-
//#endregion
|
|
301
|
-
//#region node_modules/.pnpm/openai@7.28.0_@aws-sdk+credential-provider-node@3.972.84_@smithy+hash-node@4.5.2_@smith_228c78b5ff380a7908ad856e85d64d8d/node_modules/openai/internal/decoders/line.mjs
|
|
302
|
-
var _LineDecoder_instances;
|
|
303
|
-
var _LineDecoder_buffer;
|
|
304
|
-
var _LineDecoder_start;
|
|
305
|
-
var _LineDecoder_end;
|
|
306
|
-
var _LineDecoder_searchIndex;
|
|
307
|
-
var _LineDecoder_skipLeadingLF;
|
|
308
|
-
var _LineDecoder_append;
|
|
309
|
-
/** Maximum backing-buffer capacity retained when completed lines leave little active data. */
|
|
310
|
-
const MAX_RETAINED_BUFFER_BYTES = 65536;
|
|
311
|
-
/**
|
|
312
|
-
* Incrementally decodes UTF-8 text into lines without losing partial characters
|
|
313
|
-
* or newline sequences that span multiple chunks.
|
|
314
|
-
*
|
|
315
|
-
* Supports `\n`, `\r`, and `\r\n` line endings. Call {@link flush} after the
|
|
316
|
-
* final chunk to emit a trailing line that does not end with a newline.
|
|
317
|
-
*
|
|
318
|
-
* Based on the line decoder used by the Python `httpx` project:
|
|
319
|
-
* https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258
|
|
320
|
-
*/
|
|
321
|
-
var LineDecoder = class {
|
|
322
|
-
/** Creates a decoder with no buffered bytes or pending newline continuation. */
|
|
323
|
-
constructor() {
|
|
324
|
-
_LineDecoder_instances.add(this);
|
|
325
|
-
_LineDecoder_buffer.set(this, void 0);
|
|
326
|
-
_LineDecoder_start.set(this, void 0);
|
|
327
|
-
_LineDecoder_end.set(this, void 0);
|
|
328
|
-
_LineDecoder_searchIndex.set(this, void 0);
|
|
329
|
-
_LineDecoder_skipLeadingLF.set(this, void 0);
|
|
330
|
-
__classPrivateFieldSet(this, _LineDecoder_buffer, /* @__PURE__ */ new Uint8Array(), "f");
|
|
331
|
-
__classPrivateFieldSet(this, _LineDecoder_start, 0, "f");
|
|
332
|
-
__classPrivateFieldSet(this, _LineDecoder_end, 0, "f");
|
|
333
|
-
__classPrivateFieldSet(this, _LineDecoder_searchIndex, 0, "f");
|
|
334
|
-
__classPrivateFieldSet(this, _LineDecoder_skipLeadingLF, false, "f");
|
|
335
|
-
}
|
|
336
|
-
/**
|
|
337
|
-
* Appends a text or UTF-8 byte chunk and returns every newly completed line.
|
|
338
|
-
*
|
|
339
|
-
* Incomplete lines remain buffered for the next call. A trailing `\r`
|
|
340
|
-
* completes its line immediately, and a following `\n` is consumed as its
|
|
341
|
-
* continuation. `null` and `undefined` are ignored and do not flush buffered
|
|
342
|
-
* content.
|
|
343
|
-
*/
|
|
344
|
-
decode(chunk) {
|
|
345
|
-
if (chunk == null) return [];
|
|
346
|
-
let binaryChunk;
|
|
347
|
-
if (chunk instanceof ArrayBuffer) binaryChunk = new Uint8Array(chunk);
|
|
348
|
-
else if (typeof chunk === "string") binaryChunk = encodeUTF8(chunk);
|
|
349
|
-
else binaryChunk = chunk;
|
|
350
|
-
if (binaryChunk.length === 0) return [];
|
|
351
|
-
if (__classPrivateFieldGet(this, _LineDecoder_skipLeadingLF, "f")) {
|
|
352
|
-
__classPrivateFieldSet(this, _LineDecoder_skipLeadingLF, false, "f");
|
|
353
|
-
if (binaryChunk[0] === 10) binaryChunk = binaryChunk.subarray(1);
|
|
354
|
-
if (binaryChunk.length === 0) return [];
|
|
355
|
-
}
|
|
356
|
-
__classPrivateFieldGet(this, _LineDecoder_instances, "m", _LineDecoder_append).call(this, binaryChunk);
|
|
357
|
-
const lines = [];
|
|
358
|
-
let patternIndex;
|
|
359
|
-
while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_searchIndex, "f"), __classPrivateFieldGet(this, _LineDecoder_end, "f"))) != null) {
|
|
360
|
-
const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_start, "f"), patternIndex.preceding));
|
|
361
|
-
lines.push(line);
|
|
362
|
-
__classPrivateFieldSet(this, _LineDecoder_start, patternIndex.index, "f");
|
|
363
|
-
if (patternIndex.carriage) {
|
|
364
|
-
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");
|
|
365
|
-
else if (__classPrivateFieldGet(this, _LineDecoder_start, "f") === __classPrivateFieldGet(this, _LineDecoder_end, "f")) __classPrivateFieldSet(this, _LineDecoder_skipLeadingLF, true, "f");
|
|
366
|
-
}
|
|
367
|
-
__classPrivateFieldSet(this, _LineDecoder_searchIndex, __classPrivateFieldGet(this, _LineDecoder_start, "f"), "f");
|
|
368
|
-
}
|
|
369
|
-
__classPrivateFieldSet(this, _LineDecoder_searchIndex, __classPrivateFieldGet(this, _LineDecoder_end, "f"), "f");
|
|
370
|
-
if (__classPrivateFieldGet(this, _LineDecoder_start, "f") === __classPrivateFieldGet(this, _LineDecoder_end, "f")) {
|
|
371
|
-
__classPrivateFieldSet(this, _LineDecoder_start, 0, "f");
|
|
372
|
-
__classPrivateFieldSet(this, _LineDecoder_end, 0, "f");
|
|
373
|
-
__classPrivateFieldSet(this, _LineDecoder_searchIndex, 0, "f");
|
|
374
|
-
if (__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length > MAX_RETAINED_BUFFER_BYTES) __classPrivateFieldSet(this, _LineDecoder_buffer, /* @__PURE__ */ new Uint8Array(), "f");
|
|
375
|
-
} else if (lines.length > 0 && __classPrivateFieldGet(this, _LineDecoder_buffer, "f").length > MAX_RETAINED_BUFFER_BYTES) {
|
|
376
|
-
const length = __classPrivateFieldGet(this, _LineDecoder_end, "f") - __classPrivateFieldGet(this, _LineDecoder_start, "f");
|
|
377
|
-
if (length <= MAX_RETAINED_BUFFER_BYTES || __classPrivateFieldGet(this, _LineDecoder_buffer, "f").length > length * 4) {
|
|
378
|
-
const capacity = length <= MAX_RETAINED_BUFFER_BYTES ? Math.min(Math.max(length * 2, 256), MAX_RETAINED_BUFFER_BYTES) : length * 2;
|
|
379
|
-
const buffer = new Uint8Array(capacity);
|
|
380
|
-
buffer.set(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_start, "f"), __classPrivateFieldGet(this, _LineDecoder_end, "f")));
|
|
381
|
-
__classPrivateFieldSet(this, _LineDecoder_buffer, buffer, "f");
|
|
382
|
-
__classPrivateFieldSet(this, _LineDecoder_start, 0, "f");
|
|
383
|
-
__classPrivateFieldSet(this, _LineDecoder_end, length, "f");
|
|
384
|
-
__classPrivateFieldSet(this, _LineDecoder_searchIndex, length, "f");
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
return lines;
|
|
388
|
-
}
|
|
389
|
-
/** Emits the remaining unterminated line, or returns an empty array when idle. */
|
|
390
|
-
flush() {
|
|
391
|
-
__classPrivateFieldSet(this, _LineDecoder_skipLeadingLF, false, "f");
|
|
392
|
-
if (__classPrivateFieldGet(this, _LineDecoder_start, "f") === __classPrivateFieldGet(this, _LineDecoder_end, "f")) return [];
|
|
393
|
-
return this.decode("\n");
|
|
394
|
-
}
|
|
395
|
-
};
|
|
396
|
-
_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) {
|
|
397
|
-
if (__classPrivateFieldGet(this, _LineDecoder_end, "f") + chunk.length > __classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) {
|
|
398
|
-
const length = __classPrivateFieldGet(this, _LineDecoder_end, "f") - __classPrivateFieldGet(this, _LineDecoder_start, "f");
|
|
399
|
-
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"));
|
|
400
|
-
else {
|
|
401
|
-
const capacity = Math.max(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length * 2, length + chunk.length, 256);
|
|
402
|
-
const buffer = new Uint8Array(capacity);
|
|
403
|
-
buffer.set(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_start, "f"), __classPrivateFieldGet(this, _LineDecoder_end, "f")));
|
|
404
|
-
__classPrivateFieldSet(this, _LineDecoder_buffer, buffer, "f");
|
|
405
|
-
}
|
|
406
|
-
__classPrivateFieldSet(this, _LineDecoder_searchIndex, __classPrivateFieldGet(this, _LineDecoder_searchIndex, "f") - __classPrivateFieldGet(this, _LineDecoder_start, "f"), "f");
|
|
407
|
-
__classPrivateFieldSet(this, _LineDecoder_end, length, "f");
|
|
408
|
-
__classPrivateFieldSet(this, _LineDecoder_start, 0, "f");
|
|
409
|
-
}
|
|
410
|
-
__classPrivateFieldGet(this, _LineDecoder_buffer, "f").set(chunk, __classPrivateFieldGet(this, _LineDecoder_end, "f"));
|
|
411
|
-
__classPrivateFieldSet(this, _LineDecoder_end, __classPrivateFieldGet(this, _LineDecoder_end, "f") + chunk.length, "f");
|
|
412
|
-
};
|
|
413
|
-
/** Individual characters recognized as possible line terminators. */
|
|
414
|
-
LineDecoder.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r"]);
|
|
415
|
-
/** Matches complete CRLF terminators as well as standalone CR and LF characters. */
|
|
416
|
-
LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
|
|
417
|
-
/**
|
|
418
|
-
* Searches the active buffer range for the next CR or LF byte and returns its
|
|
419
|
-
* zero-based position, the position immediately after it, and whether the byte
|
|
420
|
-
* was a carriage return. Returns `null` when the range contains no newline byte.
|
|
421
|
-
*
|
|
422
|
-
* ```ts
|
|
423
|
-
* findNewlineIndex(new TextEncoder().encode('abc\ndef'), 0, 7)
|
|
424
|
-
* // => { preceding: 3, index: 4, carriage: false }
|
|
425
|
-
* ```
|
|
426
|
-
*/
|
|
427
|
-
function findNewlineIndex(buffer, start, end) {
|
|
428
|
-
const newline = 10;
|
|
429
|
-
const carriage = 13;
|
|
430
|
-
for (let i = start; i < end; i++) {
|
|
431
|
-
if (buffer[i] === newline) return {
|
|
432
|
-
preceding: i,
|
|
433
|
-
index: i + 1,
|
|
434
|
-
carriage: false
|
|
435
|
-
};
|
|
436
|
-
if (buffer[i] === carriage) return {
|
|
437
|
-
preceding: i,
|
|
438
|
-
index: i + 1,
|
|
439
|
-
carriage: true
|
|
440
|
-
};
|
|
441
|
-
}
|
|
442
|
-
return null;
|
|
443
|
-
}
|
|
444
|
-
/**
|
|
445
|
-
* Finds the first blank-line separator used to delimit streamed event records.
|
|
446
|
-
*
|
|
447
|
-
* @returns The byte offset immediately after the first pair of consecutive
|
|
448
|
-
* line endings, or `-1` when the buffer contains no complete separator.
|
|
449
|
-
*/
|
|
450
|
-
function findDoubleNewlineIndex(buffer) {
|
|
451
|
-
for (let i = 0; i < buffer.length - 1; i++) {
|
|
452
|
-
const firstEndingLength = lineEndingLength(buffer, i);
|
|
453
|
-
if (firstEndingLength > 0) {
|
|
454
|
-
const secondEndingIndex = i + firstEndingLength;
|
|
455
|
-
const secondEndingLength = lineEndingLength(buffer, secondEndingIndex);
|
|
456
|
-
if (secondEndingLength > 0) return secondEndingIndex + secondEndingLength;
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
return -1;
|
|
460
|
-
}
|
|
461
|
-
function lineEndingLength(buffer, index) {
|
|
462
|
-
const newline = 10;
|
|
463
|
-
const carriage = 13;
|
|
464
|
-
if (buffer[index] === newline) return 1;
|
|
465
|
-
if (buffer[index] === carriage) return buffer[index + 1] === newline ? 2 : 1;
|
|
466
|
-
return 0;
|
|
467
|
-
}
|
|
468
|
-
//#endregion
|
|
469
|
-
//#region node_modules/.pnpm/openai@7.28.0_@aws-sdk+credential-provider-node@3.972.84_@smithy+hash-node@4.5.2_@smith_228c78b5ff380a7908ad856e85d64d8d/node_modules/openai/internal/utils/log.mjs
|
|
470
|
-
const levelNumbers = {
|
|
471
|
-
off: 0,
|
|
472
|
-
error: 200,
|
|
473
|
-
warn: 300,
|
|
474
|
-
info: 400,
|
|
475
|
-
debug: 500
|
|
476
|
-
};
|
|
477
|
-
const parseLogLevel = (maybeLevel, sourceName, client) => {
|
|
478
|
-
if (!maybeLevel) return;
|
|
479
|
-
if (hasOwn(levelNumbers, maybeLevel)) return maybeLevel;
|
|
480
|
-
loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`);
|
|
481
|
-
};
|
|
482
|
-
function noop() {}
|
|
483
|
-
function makeLogFn(fnLevel, logger, logLevel) {
|
|
484
|
-
if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) return noop;
|
|
485
|
-
else return logger[fnLevel].bind(logger);
|
|
486
|
-
}
|
|
487
|
-
const noopLogger = {
|
|
488
|
-
error: noop,
|
|
489
|
-
warn: noop,
|
|
490
|
-
info: noop,
|
|
491
|
-
debug: noop
|
|
492
|
-
};
|
|
493
|
-
let cachedLoggers = /* @__PURE__ */ new WeakMap();
|
|
494
|
-
function loggerFor(client) {
|
|
495
|
-
const logger = client.logger;
|
|
496
|
-
const logLevel = client.logLevel ?? "off";
|
|
497
|
-
if (!logger) return noopLogger;
|
|
498
|
-
const cachedLogger = cachedLoggers.get(logger);
|
|
499
|
-
if (cachedLogger && cachedLogger[0] === logLevel) return cachedLogger[1];
|
|
500
|
-
const levelLogger = {
|
|
501
|
-
error: makeLogFn("error", logger, logLevel),
|
|
502
|
-
warn: makeLogFn("warn", logger, logLevel),
|
|
503
|
-
info: makeLogFn("info", logger, logLevel),
|
|
504
|
-
debug: makeLogFn("debug", logger, logLevel)
|
|
505
|
-
};
|
|
506
|
-
cachedLoggers.set(logger, [logLevel, levelLogger]);
|
|
507
|
-
return levelLogger;
|
|
508
|
-
}
|
|
509
|
-
const sensitiveQueryNames = /* @__PURE__ */ new Set([
|
|
510
|
-
"apikey",
|
|
511
|
-
"accesstoken",
|
|
512
|
-
"refreshtoken",
|
|
513
|
-
"sessiontoken",
|
|
514
|
-
"sessionid",
|
|
515
|
-
"idtoken",
|
|
516
|
-
"authtoken",
|
|
517
|
-
"authorization",
|
|
518
|
-
"token",
|
|
519
|
-
"password",
|
|
520
|
-
"clientsecret",
|
|
521
|
-
"signingsecret",
|
|
522
|
-
"xamzsecuritytoken",
|
|
523
|
-
"xamzsignature",
|
|
524
|
-
"xamzcredential"
|
|
525
|
-
]);
|
|
526
|
-
/** Recognizes credential-bearing query names across ordinary and provider authentication. */
|
|
527
|
-
function isSensitiveQueryParameter(name) {
|
|
528
|
-
const normalized = name.toLowerCase().replace(/[-_]/gu, "");
|
|
529
|
-
return sensitiveQueryNames.has(normalized) || sensitiveQueryNames.has(normalized.replace(/^x/u, ""));
|
|
530
|
-
}
|
|
531
|
-
const sensitiveHeaderNames = /* @__PURE__ */ new Set([
|
|
532
|
-
"authorization",
|
|
533
|
-
"proxy-authorization",
|
|
534
|
-
"api-key",
|
|
535
|
-
"x-api-key",
|
|
536
|
-
"x-amz-security-token",
|
|
537
|
-
"cookie",
|
|
538
|
-
"set-cookie",
|
|
539
|
-
"x-session-token",
|
|
540
|
-
"x-session-id",
|
|
541
|
-
"x-auth-token",
|
|
542
|
-
"x-id-token"
|
|
543
|
-
]);
|
|
544
|
-
/** Recognizes credential-bearing request headers across provider and workload authentication. */
|
|
545
|
-
function isSensitiveHeader(name) {
|
|
546
|
-
return sensitiveHeaderNames.has(name.toLowerCase().replace(/_/gu, "-")) || isSensitiveQueryParameter(name);
|
|
547
|
-
}
|
|
548
|
-
/** Removes credential-valued query parameters before a request URL reaches any logger. */
|
|
549
|
-
function redactURL(value) {
|
|
550
|
-
const url = new URL(value);
|
|
551
|
-
url.username = "";
|
|
552
|
-
url.password = "";
|
|
553
|
-
url.hash = "";
|
|
554
|
-
for (const name of url.searchParams.keys()) if (isSensitiveQueryParameter(name)) url.searchParams.set(name, "***");
|
|
555
|
-
return url.href;
|
|
556
|
-
}
|
|
557
|
-
const formatRequestDetails = (details) => {
|
|
558
|
-
if (details.options) {
|
|
559
|
-
details.options = { ...details.options };
|
|
560
|
-
delete details.options["headers"];
|
|
561
|
-
if (details.options.path) {
|
|
562
|
-
const path = details.options.path;
|
|
563
|
-
const redacted = new URL(redactURL(new URL(path, "https://redacted.invalid").href));
|
|
564
|
-
details.options.path = redacted.origin === "https://redacted.invalid" ? `${path.startsWith("/") ? "/" : ""}${redacted.pathname.slice(1)}${redacted.search}` : redacted.href;
|
|
565
|
-
}
|
|
566
|
-
if (details.options.query) details.options.query = Object.fromEntries(Object.entries(details.options.query).map(([name, value]) => [name, isSensitiveQueryParameter(name) ? "***" : value]));
|
|
567
|
-
}
|
|
568
|
-
if (details.url) details.url = redactURL(details.url);
|
|
569
|
-
if (details.headers) details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [name, isSensitiveHeader(name) ? "***" : value]));
|
|
570
|
-
if ("retryOfRequestLogID" in details) {
|
|
571
|
-
if (details.retryOfRequestLogID) details.retryOf = details.retryOfRequestLogID;
|
|
572
|
-
delete details.retryOfRequestLogID;
|
|
573
|
-
}
|
|
574
|
-
return details;
|
|
575
|
-
};
|
|
576
|
-
//#endregion
|
|
577
|
-
//#region node_modules/.pnpm/openai@7.28.0_@aws-sdk+credential-provider-node@3.972.84_@smithy+hash-node@4.5.2_@smith_228c78b5ff380a7908ad856e85d64d8d/node_modules/openai/core/streaming.mjs
|
|
578
|
-
var _Stream_instances;
|
|
579
|
-
var _Stream_client;
|
|
580
|
-
var _Stream_isTeeBranch;
|
|
581
|
-
var _Stream_cancelIterator;
|
|
582
|
-
function isTransportAbortError(error) {
|
|
583
|
-
return !(error instanceof APIError) && isAbortError(error);
|
|
584
|
-
}
|
|
585
|
-
function createStreamTeeQueue() {
|
|
586
|
-
let entries = [];
|
|
587
|
-
let head = 0;
|
|
588
|
-
let canceled = false;
|
|
589
|
-
return {
|
|
590
|
-
get length() {
|
|
591
|
-
return entries.length - head;
|
|
592
|
-
},
|
|
593
|
-
get canceled() {
|
|
594
|
-
return canceled;
|
|
595
|
-
},
|
|
596
|
-
enqueue(value) {
|
|
597
|
-
if (!canceled) entries.push(value);
|
|
598
|
-
},
|
|
599
|
-
dequeue() {
|
|
600
|
-
if (head === entries.length) return;
|
|
601
|
-
const value = entries[head];
|
|
602
|
-
entries[head] = void 0;
|
|
603
|
-
head += 1;
|
|
604
|
-
if (head === entries.length) {
|
|
605
|
-
entries = [];
|
|
606
|
-
head = 0;
|
|
607
|
-
} else if (head >= 1024 && head * 2 >= entries.length) {
|
|
608
|
-
entries = entries.slice(head);
|
|
609
|
-
head = 0;
|
|
610
|
-
}
|
|
611
|
-
return value;
|
|
612
|
-
},
|
|
613
|
-
cancel() {
|
|
614
|
-
canceled = true;
|
|
615
|
-
entries.length = 0;
|
|
616
|
-
head = 0;
|
|
617
|
-
}
|
|
618
|
-
};
|
|
619
|
-
}
|
|
620
|
-
/**
|
|
621
|
-
* A single-consumption asynchronous API response stream.
|
|
622
|
-
*
|
|
623
|
-
* Use {@link Stream.tee} when two consumers need the same events. Breaking out of
|
|
624
|
-
* a response-backed stream early aborts its request; branches created by `tee()`
|
|
625
|
-
* instead share {@link Stream.controller} for explicit cancellation.
|
|
626
|
-
*/
|
|
627
|
-
var Stream = class Stream {
|
|
628
|
-
/** Wraps an asynchronous event iterator and the controller that owns its request. */
|
|
629
|
-
constructor(iterator, controller, client) {
|
|
630
|
-
_Stream_instances.add(this);
|
|
631
|
-
_Stream_client.set(this, void 0);
|
|
632
|
-
_Stream_isTeeBranch.set(this, false);
|
|
633
|
-
this.iterator = iterator;
|
|
634
|
-
this.controller = controller;
|
|
635
|
-
__classPrivateFieldSet(this, _Stream_client, client, "f");
|
|
636
|
-
}
|
|
637
|
-
/**
|
|
638
|
-
* Decodes an SSE response into parsed JSON events.
|
|
639
|
-
*
|
|
640
|
-
* The resulting stream can be consumed only once, ignores events after `[DONE]`, and
|
|
641
|
-
* surfaces API error payloads as `APIError` instances. When
|
|
642
|
-
* `synthesizeEventData` is enabled, each item also includes its SSE event name.
|
|
643
|
-
*/
|
|
644
|
-
static fromSSEResponse(response, controller, client, synthesizeEventData) {
|
|
645
|
-
let consumed = false;
|
|
646
|
-
const logger = client ? loggerFor(client) : console;
|
|
647
|
-
async function* iterator() {
|
|
648
|
-
if (consumed) throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
|
|
649
|
-
consumed = true;
|
|
650
|
-
let done = false;
|
|
651
|
-
let receivedCompletionSentinel = false;
|
|
652
|
-
const messages = _iterSSEMessages(response, controller);
|
|
653
|
-
const closeMessages = messages.return.bind(messages);
|
|
654
|
-
messages.return = (value) => {
|
|
655
|
-
if (!receivedCompletionSentinel) controller.abort();
|
|
656
|
-
return closeMessages(value);
|
|
657
|
-
};
|
|
658
|
-
try {
|
|
659
|
-
for await (const sse of messages) {
|
|
660
|
-
if (sse.data === "[DONE]") {
|
|
661
|
-
receivedCompletionSentinel = true;
|
|
662
|
-
break;
|
|
663
|
-
}
|
|
664
|
-
if (sse.event === null || !sse.event.startsWith("thread.")) {
|
|
665
|
-
let data;
|
|
666
|
-
try {
|
|
667
|
-
data = JSON.parse(sse.data);
|
|
668
|
-
} catch {
|
|
669
|
-
logger.error(`Could not parse message into JSON:`);
|
|
670
|
-
logger.error(`From chunk:`);
|
|
671
|
-
throw new SyntaxError("Error reading response: malformed server-sent event JSON.");
|
|
672
|
-
}
|
|
673
|
-
if (sse.event === "error") throw new APIError(void 0, data?.error ?? data, void 0, response.headers);
|
|
674
|
-
if (data && data.error) throw new APIError(void 0, data.error, void 0, response.headers);
|
|
675
|
-
yield synthesizeEventData ? {
|
|
676
|
-
event: sse.event,
|
|
677
|
-
data
|
|
678
|
-
} : data;
|
|
679
|
-
} else {
|
|
680
|
-
let data;
|
|
681
|
-
try {
|
|
682
|
-
data = JSON.parse(sse.data);
|
|
683
|
-
} catch {
|
|
684
|
-
logger.error(`Could not parse message into JSON:`);
|
|
685
|
-
logger.error(`From chunk:`);
|
|
686
|
-
throw new SyntaxError("Error reading response: malformed server-sent event JSON.");
|
|
687
|
-
}
|
|
688
|
-
yield {
|
|
689
|
-
event: sse.event,
|
|
690
|
-
data
|
|
691
|
-
};
|
|
692
|
-
}
|
|
693
|
-
}
|
|
694
|
-
done = true;
|
|
695
|
-
} catch (e) {
|
|
696
|
-
if (receivedCompletionSentinel || isTransportAbortError(e) || controller.signal.aborted && e === controller.signal.reason) return;
|
|
697
|
-
throw e;
|
|
698
|
-
} finally {
|
|
699
|
-
if (!done) controller.abort();
|
|
700
|
-
}
|
|
701
|
-
}
|
|
702
|
-
return new Stream(iterator, controller, client);
|
|
703
|
-
}
|
|
704
|
-
/**
|
|
705
|
-
* Generates a Stream from a newline-separated ReadableStream
|
|
706
|
-
* where each item is a JSON value.
|
|
707
|
-
*/
|
|
708
|
-
static fromReadableStream(readableStream, controller, client) {
|
|
709
|
-
let consumed = false;
|
|
710
|
-
async function* iterLines() {
|
|
711
|
-
const lineDecoder = new LineDecoder();
|
|
712
|
-
const reader = readableStream.getReader();
|
|
713
|
-
let closed = false;
|
|
714
|
-
let cancelPromise;
|
|
715
|
-
const cancel = () => {
|
|
716
|
-
cancelPromise ?? (cancelPromise = reader.cancel());
|
|
717
|
-
cancelPromise.catch(() => void 0);
|
|
718
|
-
};
|
|
719
|
-
controller.signal.addEventListener("abort", cancel, { once: true });
|
|
720
|
-
try {
|
|
721
|
-
if (controller.signal.aborted) {
|
|
722
|
-
cancel();
|
|
723
|
-
return;
|
|
724
|
-
}
|
|
725
|
-
while (true) {
|
|
726
|
-
const { value: chunk, done } = await reader.read();
|
|
727
|
-
if (done) {
|
|
728
|
-
closed = true;
|
|
729
|
-
break;
|
|
730
|
-
}
|
|
731
|
-
if (controller.signal.aborted) return;
|
|
732
|
-
for (const line of lineDecoder.decode(chunk)) {
|
|
733
|
-
if (controller.signal.aborted) return;
|
|
734
|
-
yield line;
|
|
735
|
-
}
|
|
736
|
-
}
|
|
737
|
-
if (controller.signal.aborted) return;
|
|
738
|
-
for (const line of lineDecoder.flush()) {
|
|
739
|
-
if (controller.signal.aborted) return;
|
|
740
|
-
yield line;
|
|
741
|
-
}
|
|
742
|
-
} finally {
|
|
743
|
-
controller.signal.removeEventListener("abort", cancel);
|
|
744
|
-
if (!closed) cancel();
|
|
745
|
-
reader.releaseLock();
|
|
746
|
-
}
|
|
747
|
-
}
|
|
748
|
-
async function* iterator() {
|
|
749
|
-
if (consumed) throw new OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
|
|
750
|
-
consumed = true;
|
|
751
|
-
let done = false;
|
|
752
|
-
try {
|
|
753
|
-
for await (const line of iterLines()) if (line) {
|
|
754
|
-
let data;
|
|
755
|
-
try {
|
|
756
|
-
data = JSON.parse(line);
|
|
757
|
-
} catch (error) {
|
|
758
|
-
if (error instanceof SyntaxError) throw new SyntaxError("Error reading response: malformed newline-delimited JSON.");
|
|
759
|
-
throw error;
|
|
760
|
-
}
|
|
761
|
-
yield data;
|
|
762
|
-
}
|
|
763
|
-
done = true;
|
|
764
|
-
} catch (e) {
|
|
765
|
-
if (controller.signal.aborted || isAbortError(e)) return;
|
|
766
|
-
throw e;
|
|
767
|
-
} finally {
|
|
768
|
-
if (!done) controller.abort();
|
|
769
|
-
}
|
|
770
|
-
}
|
|
771
|
-
return new Stream(iterator, controller, client);
|
|
772
|
-
}
|
|
773
|
-
/** Starts consuming this stream; attempting to consume it again throws. */
|
|
774
|
-
[(_Stream_client = /* @__PURE__ */ new WeakMap(), _Stream_isTeeBranch = /* @__PURE__ */ new WeakMap(), _Stream_instances = /* @__PURE__ */ new WeakSet(), Symbol.asyncIterator)]() {
|
|
775
|
-
return this.iterator();
|
|
776
|
-
}
|
|
777
|
-
/** Beta-only iterator decoration for Agents helpers, preserving custom stream identity.
|
|
778
|
-
* @internal
|
|
779
|
-
*/
|
|
780
|
-
__betaTransformIterator(transform) {
|
|
781
|
-
this.iterator = transform(this.iterator.bind(this));
|
|
782
|
-
}
|
|
783
|
-
/**
|
|
784
|
-
* Splits the stream into two streams which can be
|
|
785
|
-
* independently read from at different speeds.
|
|
786
|
-
* Closing a branch discards its buffered events without stopping its sibling.
|
|
787
|
-
* Future reads on that branch finish immediately; previously issued `next()`
|
|
788
|
-
* promises remain shared with its sibling and may still resolve with events.
|
|
789
|
-
* Closing both branches invokes the source iterator's `return()` when available.
|
|
790
|
-
* For {@link Stream.fromReadableStream}, closing both branches before iteration
|
|
791
|
-
* starts does not cancel the supplied readable; cancel that readable directly.
|
|
792
|
-
*/
|
|
793
|
-
tee() {
|
|
794
|
-
const { controller } = this;
|
|
795
|
-
const left = createStreamTeeQueue();
|
|
796
|
-
const right = createStreamTeeQueue();
|
|
797
|
-
const iterator = this.iterator();
|
|
798
|
-
const teeIterator = (queue) => ({
|
|
799
|
-
next: () => {
|
|
800
|
-
if (queue.canceled) return Promise.resolve({
|
|
801
|
-
value: void 0,
|
|
802
|
-
done: true
|
|
803
|
-
});
|
|
804
|
-
if (queue.length === 0) {
|
|
805
|
-
const result = iterator.next();
|
|
806
|
-
left.enqueue(result);
|
|
807
|
-
right.enqueue(result);
|
|
808
|
-
}
|
|
809
|
-
return queue.dequeue();
|
|
810
|
-
},
|
|
811
|
-
return: async () => {
|
|
812
|
-
if (!queue.canceled) {
|
|
813
|
-
queue.cancel();
|
|
814
|
-
if (left.canceled && right.canceled) await __classPrivateFieldGet(this, _Stream_instances, "m", _Stream_cancelIterator).call(this, iterator, controller);
|
|
815
|
-
}
|
|
816
|
-
return {
|
|
817
|
-
value: void 0,
|
|
818
|
-
done: true
|
|
819
|
-
};
|
|
820
|
-
}
|
|
821
|
-
});
|
|
822
|
-
const branch = (queue) => {
|
|
823
|
-
const stream = new Stream(() => teeIterator(queue), controller, __classPrivateFieldGet(this, _Stream_client, "f"));
|
|
824
|
-
__classPrivateFieldSet(stream, _Stream_isTeeBranch, true, "f");
|
|
825
|
-
return stream;
|
|
826
|
-
};
|
|
827
|
-
return [branch(left), branch(right)];
|
|
828
|
-
}
|
|
829
|
-
/**
|
|
830
|
-
* Converts this stream to a newline-separated ReadableStream of
|
|
831
|
-
* JSON stringified values in the stream
|
|
832
|
-
* which can be turned back into a Stream with `Stream.fromReadableStream()`.
|
|
833
|
-
* Canceling a response-backed readable aborts its request. Canceling a tee
|
|
834
|
-
* branch discards its buffered events and leaves sibling consumers running.
|
|
835
|
-
* Read or serialization failures also release the iterator without replacing the original error.
|
|
836
|
-
*/
|
|
837
|
-
toReadableStream() {
|
|
838
|
-
const { controller } = this;
|
|
839
|
-
let iter;
|
|
840
|
-
let cancellation;
|
|
841
|
-
const cancel = () => cancellation ?? (cancellation = __classPrivateFieldGet(this, _Stream_instances, "m", _Stream_cancelIterator).call(this, iter, controller));
|
|
842
|
-
return makeReadableStream({
|
|
843
|
-
start: async () => {
|
|
844
|
-
iter = this[Symbol.asyncIterator]();
|
|
845
|
-
},
|
|
846
|
-
async pull(ctrl) {
|
|
847
|
-
try {
|
|
848
|
-
const { value, done } = await iter.next();
|
|
849
|
-
if (done) return ctrl.close();
|
|
850
|
-
const bytes = encodeUTF8(JSON.stringify(value) + "\n");
|
|
851
|
-
ctrl.enqueue(bytes);
|
|
852
|
-
} catch (err) {
|
|
853
|
-
ctrl.error(err);
|
|
854
|
-
cancel().catch(() => void 0);
|
|
855
|
-
}
|
|
856
|
-
},
|
|
857
|
-
cancel
|
|
858
|
-
});
|
|
859
|
-
}
|
|
860
|
-
};
|
|
861
|
-
_Stream_cancelIterator = async function _Stream_cancelIterator(iterator, controller) {
|
|
862
|
-
const returnMethod = iterator.return;
|
|
863
|
-
if (returnMethod) {
|
|
864
|
-
if (!__classPrivateFieldGet(this, _Stream_isTeeBranch, "f")) controller.abort();
|
|
865
|
-
await Reflect.apply(returnMethod, iterator, []);
|
|
866
|
-
}
|
|
867
|
-
};
|
|
868
|
-
function createAbortableSSESource(body, signal) {
|
|
869
|
-
const reader = typeof body.getReader === "function" ? body.getReader() : void 0;
|
|
870
|
-
const source = reader ? {
|
|
871
|
-
next: () => reader.read(),
|
|
872
|
-
return: () => reader.cancel()
|
|
873
|
-
} : ReadableStreamToAsyncIterable(body)[Symbol.asyncIterator]();
|
|
874
|
-
const ended = {
|
|
875
|
-
value: void 0,
|
|
876
|
-
done: true
|
|
877
|
-
};
|
|
878
|
-
let closed = false;
|
|
879
|
-
let canceled = false;
|
|
880
|
-
let cancellation;
|
|
881
|
-
let interrupt;
|
|
882
|
-
const waitForAbort = () => new Promise((resolve) => {
|
|
883
|
-
interrupt = resolve;
|
|
884
|
-
});
|
|
885
|
-
const cancel = () => {
|
|
886
|
-
if (canceled || closed) return cancellation;
|
|
887
|
-
canceled = true;
|
|
888
|
-
try {
|
|
889
|
-
cancellation = Promise.resolve(source.return?.());
|
|
890
|
-
} catch (error) {
|
|
891
|
-
cancellation = Promise.reject(error);
|
|
892
|
-
}
|
|
893
|
-
cancellation.catch(() => void 0);
|
|
894
|
-
return cancellation;
|
|
895
|
-
};
|
|
896
|
-
const abort = () => {
|
|
897
|
-
queueMicrotask(() => {
|
|
898
|
-
interrupt?.();
|
|
899
|
-
cancel();
|
|
900
|
-
});
|
|
901
|
-
};
|
|
902
|
-
return {
|
|
903
|
-
iterator: {
|
|
904
|
-
async next() {
|
|
905
|
-
if (signal.aborted) return ended;
|
|
906
|
-
const aborted = waitForAbort().then(() => ended);
|
|
907
|
-
try {
|
|
908
|
-
const result = await Promise.race([source.next(), aborted]);
|
|
909
|
-
if (signal.aborted) return ended;
|
|
910
|
-
if (result.done) {
|
|
911
|
-
closed = true;
|
|
912
|
-
return ended;
|
|
913
|
-
}
|
|
914
|
-
return {
|
|
915
|
-
value: result.value,
|
|
916
|
-
done: false
|
|
917
|
-
};
|
|
918
|
-
} catch (error) {
|
|
919
|
-
if (signal.aborted && (isAbortError(error) || error === signal.reason)) return ended;
|
|
920
|
-
throw error;
|
|
921
|
-
} finally {
|
|
922
|
-
interrupt = void 0;
|
|
923
|
-
}
|
|
924
|
-
},
|
|
925
|
-
async return() {
|
|
926
|
-
const pending = cancel();
|
|
927
|
-
if (pending && !signal.aborted) {
|
|
928
|
-
const aborted = waitForAbort();
|
|
929
|
-
try {
|
|
930
|
-
if (!signal.aborted) await Promise.race([pending, aborted]);
|
|
931
|
-
} finally {
|
|
932
|
-
interrupt = void 0;
|
|
933
|
-
}
|
|
934
|
-
}
|
|
935
|
-
return ended;
|
|
936
|
-
},
|
|
937
|
-
[Symbol.asyncIterator]() {
|
|
938
|
-
return this;
|
|
939
|
-
}
|
|
940
|
-
},
|
|
941
|
-
start() {
|
|
942
|
-
signal.addEventListener("abort", abort, { once: true });
|
|
943
|
-
if (signal.aborted) abort();
|
|
944
|
-
},
|
|
945
|
-
async cleanup(failed) {
|
|
946
|
-
let cleanupError;
|
|
947
|
-
try {
|
|
948
|
-
signal.removeEventListener("abort", abort);
|
|
949
|
-
} catch (error) {
|
|
950
|
-
cleanupError = error;
|
|
951
|
-
}
|
|
952
|
-
if (!closed) {
|
|
953
|
-
const pending = cancel();
|
|
954
|
-
if (pending && !failed && !signal.aborted) try {
|
|
955
|
-
await pending;
|
|
956
|
-
} catch (error) {
|
|
957
|
-
cleanupError ?? (cleanupError = error);
|
|
958
|
-
}
|
|
959
|
-
}
|
|
960
|
-
if (reader) try {
|
|
961
|
-
reader.releaseLock();
|
|
962
|
-
} catch (error) {
|
|
963
|
-
cleanupError ?? (cleanupError = error);
|
|
964
|
-
}
|
|
965
|
-
if (cleanupError !== void 0 && !failed && !signal.aborted) throw cleanupError;
|
|
966
|
-
}
|
|
967
|
-
};
|
|
968
|
-
}
|
|
969
|
-
/**
|
|
970
|
-
* Decodes complete SSE records from a response and aborts when its body is absent.
|
|
971
|
-
* Complete events are decoded on demand without imposing a line or event size limit.
|
|
972
|
-
*
|
|
973
|
-
* @yields {ServerSentEvent} Each decoded server-sent event in wire order.
|
|
974
|
-
*/
|
|
975
|
-
async function* _iterSSEMessages(response, controller) {
|
|
976
|
-
if (!response.body) {
|
|
977
|
-
controller.abort();
|
|
978
|
-
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`);
|
|
979
|
-
throw new OpenAIError(`Attempted to iterate over a response with no body`);
|
|
980
|
-
}
|
|
981
|
-
const sseDecoder = new SSEDecoder();
|
|
982
|
-
const lineDecoder = new LineDecoder();
|
|
983
|
-
const { signal } = controller;
|
|
984
|
-
const source = createAbortableSSESource(response.body, signal);
|
|
985
|
-
let failed = false;
|
|
986
|
-
try {
|
|
987
|
-
source.start();
|
|
988
|
-
for await (const sseChunk of iterSSEChunks(source.iterator)) {
|
|
989
|
-
if (signal.aborted) return;
|
|
990
|
-
for (const line of lineDecoder.decode(sseChunk)) {
|
|
991
|
-
if (signal.aborted) return;
|
|
992
|
-
const sse = sseDecoder.decode(line);
|
|
993
|
-
if (sse) yield sse;
|
|
994
|
-
}
|
|
995
|
-
}
|
|
996
|
-
if (signal.aborted) return;
|
|
997
|
-
for (const line of lineDecoder.flush()) {
|
|
998
|
-
if (signal.aborted) return;
|
|
999
|
-
const sse = sseDecoder.decode(line);
|
|
1000
|
-
if (sse) yield sse;
|
|
1001
|
-
}
|
|
1002
|
-
if (signal.aborted) return;
|
|
1003
|
-
const pending = sseDecoder.flush();
|
|
1004
|
-
if (pending) yield pending;
|
|
1005
|
-
} catch (error) {
|
|
1006
|
-
failed = true;
|
|
1007
|
-
if (!signal.aborted || !isAbortError(error) && error !== signal.reason) throw error;
|
|
1008
|
-
} finally {
|
|
1009
|
-
await source.cleanup(failed);
|
|
1010
|
-
}
|
|
1011
|
-
}
|
|
1012
|
-
const DOUBLE_NEWLINE_DELIMITER_MAX_OVERLAP_BYTES = 3;
|
|
1013
|
-
/**
|
|
1014
|
-
* Given an async iterable iterator, iterates over it and yields full
|
|
1015
|
-
* SSE chunks, i.e. yields when a double new-line is encountered.
|
|
1016
|
-
*
|
|
1017
|
-
* @yields {Uint8Array} A complete SSE chunk.
|
|
1018
|
-
*/
|
|
1019
|
-
async function* iterSSEChunks(iterator) {
|
|
1020
|
-
let data = /* @__PURE__ */ new Uint8Array();
|
|
1021
|
-
let dataStart = 0;
|
|
1022
|
-
let dataEnd = 0;
|
|
1023
|
-
let searchStartIndex = 0;
|
|
1024
|
-
for await (const chunk of iterator) {
|
|
1025
|
-
if (chunk == null) continue;
|
|
1026
|
-
let binaryChunk;
|
|
1027
|
-
if (chunk instanceof ArrayBuffer) binaryChunk = new Uint8Array(chunk);
|
|
1028
|
-
else if (typeof chunk === "string") binaryChunk = encodeUTF8(chunk);
|
|
1029
|
-
else binaryChunk = chunk;
|
|
1030
|
-
if (dataEnd + binaryChunk.length > data.length) {
|
|
1031
|
-
const bufferedLength = dataEnd - dataStart;
|
|
1032
|
-
if (dataStart >= data.length / 2 && bufferedLength + binaryChunk.length <= data.length) data.copyWithin(0, dataStart, dataEnd);
|
|
1033
|
-
else {
|
|
1034
|
-
const newData = new Uint8Array(Math.max(data.length * 2, bufferedLength + binaryChunk.length));
|
|
1035
|
-
newData.set(data.subarray(dataStart, dataEnd));
|
|
1036
|
-
data = newData;
|
|
1037
|
-
}
|
|
1038
|
-
searchStartIndex -= dataStart;
|
|
1039
|
-
dataStart = 0;
|
|
1040
|
-
dataEnd = bufferedLength;
|
|
1041
|
-
}
|
|
1042
|
-
data.set(binaryChunk, dataEnd);
|
|
1043
|
-
dataEnd += binaryChunk.length;
|
|
1044
|
-
let patternIndex;
|
|
1045
|
-
while ((patternIndex = findDoubleNewlineIndex(data.subarray(searchStartIndex, dataEnd))) !== -1) {
|
|
1046
|
-
patternIndex += searchStartIndex;
|
|
1047
|
-
yield data.slice(dataStart, patternIndex);
|
|
1048
|
-
dataStart = patternIndex;
|
|
1049
|
-
searchStartIndex = dataStart;
|
|
1050
|
-
}
|
|
1051
|
-
searchStartIndex = Math.max(dataStart, dataEnd - DOUBLE_NEWLINE_DELIMITER_MAX_OVERLAP_BYTES);
|
|
1052
|
-
}
|
|
1053
|
-
if (dataEnd > dataStart) yield data.slice(dataStart, dataEnd);
|
|
1054
|
-
}
|
|
1055
|
-
var SSEDecoder = class {
|
|
1056
|
-
constructor() {
|
|
1057
|
-
this.event = null;
|
|
1058
|
-
this.data = [];
|
|
1059
|
-
this.chunks = [];
|
|
1060
|
-
}
|
|
1061
|
-
decode(line) {
|
|
1062
|
-
if (line.endsWith("\r")) line = line.slice(0, -1);
|
|
1063
|
-
if (!line) {
|
|
1064
|
-
if (!this.event && !this.data.length) return null;
|
|
1065
|
-
const sse = {
|
|
1066
|
-
event: this.event,
|
|
1067
|
-
data: this.data.join("\n"),
|
|
1068
|
-
raw: this.chunks
|
|
1069
|
-
};
|
|
1070
|
-
this.event = null;
|
|
1071
|
-
this.data = [];
|
|
1072
|
-
this.chunks = [];
|
|
1073
|
-
return sse;
|
|
1074
|
-
}
|
|
1075
|
-
this.chunks.push(line);
|
|
1076
|
-
if (line.startsWith(":")) return null;
|
|
1077
|
-
const [fieldname, , initialValue] = partition(line, ":");
|
|
1078
|
-
let value = initialValue;
|
|
1079
|
-
if (value.startsWith(" ")) value = value.slice(1);
|
|
1080
|
-
if (fieldname === "event") this.event = value;
|
|
1081
|
-
else if (fieldname === "data") this.data.push(value);
|
|
1082
|
-
return null;
|
|
1083
|
-
}
|
|
1084
|
-
/**
|
|
1085
|
-
* Emits a pending event at EOF when the stream omitted the trailing blank
|
|
1086
|
-
* line. Returns `null` when no event is in progress so a record that already
|
|
1087
|
-
* ended with a blank line is not delivered twice.
|
|
1088
|
-
*/
|
|
1089
|
-
flush() {
|
|
1090
|
-
return this.decode("");
|
|
1091
|
-
}
|
|
1092
|
-
};
|
|
1093
|
-
function partition(str, delimiter) {
|
|
1094
|
-
const index = str.indexOf(delimiter);
|
|
1095
|
-
if (index !== -1) return [
|
|
1096
|
-
str.slice(0, index),
|
|
1097
|
-
delimiter,
|
|
1098
|
-
str.slice(index + delimiter.length)
|
|
1099
|
-
];
|
|
1100
|
-
return [
|
|
1101
|
-
str,
|
|
1102
|
-
"",
|
|
1103
|
-
""
|
|
1104
|
-
];
|
|
1105
|
-
}
|
|
1106
|
-
//#endregion
|
|
34
|
+
import { isDeepStrictEqual } from "node:util";
|
|
35
|
+
import { isProxy } from "node:util/types";
|
|
36
|
+
import { APIError } from "openai";
|
|
37
|
+
import { Stream } from "openai/core/streaming";
|
|
1107
38
|
//#region packages/ai/src/transports/openai-transport-shared.ts
|
|
1108
39
|
const OPENAI_RESPONSE_MODEL_HEADER_NAMES = /* @__PURE__ */ new Set(["openai-model", "x-openai-model"]);
|
|
1109
40
|
const OPENAI_RESPONSE_MODEL_EVENT_TYPES = /* @__PURE__ */ new Set([
|
|
@@ -1117,6 +48,12 @@ const OPENAI_RESPONSE_MODEL_EVENT_TYPES = /* @__PURE__ */ new Set([
|
|
|
1117
48
|
const OPENAI_DATED_MODEL_SUFFIX = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/;
|
|
1118
49
|
const GEMINI_THOUGHT_SIGNATURE_VALIDATOR_SKIP = "skip_thought_signature_validator";
|
|
1119
50
|
const log = {
|
|
51
|
+
isEnabled(level) {
|
|
52
|
+
return getAiTransportHost().isLogEnabled?.("openai-transport", level) !== false;
|
|
53
|
+
},
|
|
54
|
+
debugLazy(build) {
|
|
55
|
+
getAiTransportHost().logDebug("openai-transport", () => ({ message: build() }));
|
|
56
|
+
},
|
|
1120
57
|
debug(message, data) {
|
|
1121
58
|
getAiTransportHost().logDebug("openai-transport", () => ({
|
|
1122
59
|
message,
|
|
@@ -1596,41 +533,30 @@ function toOpenAIResponsesToolChoice(choice) {
|
|
|
1596
533
|
};
|
|
1597
534
|
}
|
|
1598
535
|
//#endregion
|
|
1599
|
-
//#region packages/ai/src/transports/openai-reasoning-compat.ts
|
|
1600
|
-
/** Explicit model reasoning-effort compatibility metadata. */
|
|
1601
|
-
function readCompatReasoningEffortMap(compat) {
|
|
1602
|
-
const rawMap = asOptionalObjectRecord(asOptionalObjectRecord(compat)?.reasoningEffortMap);
|
|
1603
|
-
if (!rawMap) return {};
|
|
1604
|
-
return Object.fromEntries(Object.entries(rawMap).filter((entry) => typeof entry[1] === "string"));
|
|
1605
|
-
}
|
|
1606
|
-
/** Resolves the reasoning effort remap for an OpenAI-compatible model. */
|
|
1607
|
-
function resolveOpenAIReasoningEffortMap(model, fallbackMap = {}) {
|
|
1608
|
-
return {
|
|
1609
|
-
...fallbackMap,
|
|
1610
|
-
...readCompatReasoningEffortMap(model.compat)
|
|
1611
|
-
};
|
|
1612
|
-
}
|
|
1613
|
-
//#endregion
|
|
1614
536
|
//#region packages/ai/src/providers/openai-request-reasoning.ts
|
|
1615
537
|
/** Preserve explicit off until the selected route maps it to its native value. */
|
|
1616
538
|
function resolveOpenAISimpleReasoningEffort(model, reasoning) {
|
|
1617
539
|
return reasoning === void 0 ? void 0 : clampThinkingLevel(model, reasoning);
|
|
1618
540
|
}
|
|
1619
|
-
function resolveOpenAIRequestReasoning(model, reasoning
|
|
541
|
+
function resolveOpenAIRequestReasoning(model, reasoning) {
|
|
1620
542
|
const requested = normalizeOpenAIReasoningEffort(reasoning ?? "off");
|
|
1621
543
|
const modelLevel = MODEL_CATALOG_THINKING_LEVELS.find((candidate) => candidate === requested);
|
|
1622
544
|
const modelMapped = modelLevel ? model.thinkingLevelMap?.[modelLevel] : void 0;
|
|
1623
545
|
const mapped = modelMapped === null ? null : resolveOpenAIReasoningEffortMapping(requested, resolveOpenAIReasoningEffortMap(model)) ?? modelMapped;
|
|
1624
|
-
const intent = mapped !== void 0 ? mapped?.trim() : reasoning === void 0
|
|
546
|
+
const intent = mapped !== void 0 ? mapped?.trim() : reasoning === void 0 ? void 0 : requested;
|
|
1625
547
|
const normalizedIntent = normalizeOpenAIReasoningEffort(intent ?? "off");
|
|
1626
|
-
const
|
|
1627
|
-
const
|
|
548
|
+
const disabled = requested === "off" || requested === "none";
|
|
549
|
+
const supported = resolveOpenAIModelReasoningEfforts(disabled && resolveOpenAIThinkingApi(model.api) !== "openai-chatgpt-responses" && !isKnownOpenAIEndpoint(model) ? { compat: model.compat } : model);
|
|
550
|
+
const effort = !model.reasoning || supported?.length === 0 || intent === void 0 ? void 0 : supported === void 0 ? disabled && mapped === void 0 ? void 0 : intent : resolveOpenAIReasoningEffortForModel({
|
|
1628
551
|
model,
|
|
1629
552
|
effort: requested,
|
|
1630
553
|
fallbackMap: { [requested]: intent }
|
|
1631
554
|
});
|
|
1632
555
|
return {
|
|
1633
|
-
effort: effort === "none" && resolveOpenAIThinkingApi(model.api) === "openai-chatgpt-responses" && !supportsOpenAIReasoningEffort(model.id === "gpt-6-sol" || model.id === "gpt-6-luna" ? model : {
|
|
556
|
+
effort: effort === "none" && resolveOpenAIThinkingApi(model.api) === "openai-chatgpt-responses" && !supportsOpenAIReasoningEffort(model.id === "gpt-6-sol" || model.id === "gpt-6-luna" ? model : {
|
|
557
|
+
compat: model.compat,
|
|
558
|
+
thinkingLevelMap: model.thinkingLevelMap
|
|
559
|
+
}, "none") ? void 0 : effort,
|
|
1634
560
|
thinkingEnabled: intent === void 0 ? void 0 : model.reasoning && normalizedIntent !== "off" && normalizedIntent !== "none"
|
|
1635
561
|
};
|
|
1636
562
|
}
|
|
@@ -2096,11 +1022,49 @@ const TURN_HEADERS = /* @__PURE__ */ new Set([
|
|
|
2096
1022
|
"x-openclaw-turn-id",
|
|
2097
1023
|
"x-openclaw-turn-attempt"
|
|
2098
1024
|
]);
|
|
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
|
+
}
|
|
2099
1066
|
function jsonValuesEqual(left, right) {
|
|
2100
|
-
|
|
2101
|
-
const normalizedLeft = stableStringify(JSON.parse(leftJson));
|
|
2102
|
-
const rightJson = JSON.stringify(right);
|
|
2103
|
-
return leftJson === rightJson || normalizedLeft === stableStringify(JSON.parse(rightJson));
|
|
1067
|
+
return isDeepStrictEqual(projectJsonObject(left), projectJsonObject(right));
|
|
2104
1068
|
}
|
|
2105
1069
|
function requestWithoutInput(request) {
|
|
2106
1070
|
const { input: _input, previous_response_id: _previousResponseId, instructions: _instructions, tools: _tools, ...rest } = request;
|
|
@@ -2141,8 +1105,17 @@ function toolCallOwnerByReplayShape(calls) {
|
|
|
2141
1105
|
}
|
|
2142
1106
|
return ownerByReplayShape;
|
|
2143
1107
|
}
|
|
2144
|
-
function
|
|
2145
|
-
const
|
|
1108
|
+
function recordResponsesContinuationState(previous, lastRequest, response, continued = false) {
|
|
1109
|
+
const calls = previous && continued ? [...previous.pendingToolCalls ?? [], ...responseToolCalls(previous.lastResponseItems)] : responseToolCalls(lastRequest.input ?? []);
|
|
1110
|
+
const seenCalls = /* @__PURE__ */ new Set();
|
|
1111
|
+
const uniqueCalls = calls.filter((call) => {
|
|
1112
|
+
const key = JSON.stringify([call.callId, call.itemId]);
|
|
1113
|
+
if (seenCalls.has(key)) return false;
|
|
1114
|
+
seenCalls.add(key);
|
|
1115
|
+
return true;
|
|
1116
|
+
});
|
|
1117
|
+
const input = lastRequest.input ?? [];
|
|
1118
|
+
const ownerByReplayShape = toolCallOwnerByReplayShape(uniqueCalls);
|
|
2146
1119
|
const replayedCallIds = /* @__PURE__ */ new Set();
|
|
2147
1120
|
const lastCallPosition = /* @__PURE__ */ new Map();
|
|
2148
1121
|
const lastOutputPosition = /* @__PURE__ */ new Map();
|
|
@@ -2153,24 +1126,14 @@ function pendingResponsesToolCalls(calls, input) {
|
|
|
2153
1126
|
const positions = item.type === "function_call" ? lastCallPosition : item.type === "function_call_output" ? lastOutputPosition : void 0;
|
|
2154
1127
|
if (positions && owner !== void 0 && owner !== null) positions.set(owner, inputIndex);
|
|
2155
1128
|
}
|
|
2156
|
-
|
|
1129
|
+
const pendingToolCalls = uniqueCalls.filter((_call, index) => {
|
|
2157
1130
|
const callPosition = lastCallPosition.get(index);
|
|
2158
1131
|
return [...toolCallReplayShapes(_call)].some((shape) => replayedCallIds.has(shape)) && (callPosition === void 0 || (lastOutputPosition.get(index) ?? -1) < callPosition);
|
|
2159
1132
|
});
|
|
2160
|
-
}
|
|
2161
|
-
function recordResponsesContinuationState(previous, lastRequest, response, continued = false) {
|
|
2162
|
-
const calls = previous && continued ? [...previous.pendingToolCalls ?? [], ...responseToolCalls(previous.lastResponseItems)] : responseToolCalls(lastRequest.input ?? []);
|
|
2163
|
-
const seenCalls = /* @__PURE__ */ new Set();
|
|
2164
|
-
const pendingToolCalls = pendingResponsesToolCalls(calls.filter((call) => {
|
|
2165
|
-
const key = JSON.stringify([call.callId, call.itemId]);
|
|
2166
|
-
if (seenCalls.has(key)) return false;
|
|
2167
|
-
seenCalls.add(key);
|
|
2168
|
-
return true;
|
|
2169
|
-
}), lastRequest.input ?? []);
|
|
2170
1133
|
return {
|
|
2171
1134
|
lastRequest,
|
|
2172
1135
|
lastResponseId: response.id,
|
|
2173
|
-
lastResponseItems: response.output,
|
|
1136
|
+
lastResponseItems: response.output.filter((item) => item.type !== "web_search_call"),
|
|
2174
1137
|
pendingToolCalls
|
|
2175
1138
|
};
|
|
2176
1139
|
}
|
|
@@ -2222,57 +1185,11 @@ function normalizeContinuationHistory(input) {
|
|
|
2222
1185
|
}
|
|
2223
1186
|
return normalized;
|
|
2224
1187
|
}
|
|
2225
|
-
function continuationHistoryMatches(previousInput, currentInput) {
|
|
2226
|
-
for (const [index, previousItem] of previousInput.entries()) {
|
|
2227
|
-
const currentItem = currentInput[index];
|
|
2228
|
-
if (!isRecord(previousItem) || !isRecord(currentItem)) continue;
|
|
2229
|
-
if (previousItem.type === "function_call" && currentItem.type === "function_call") {
|
|
2230
|
-
if (typeof previousItem.call_id === "string" && typeof currentItem.call_id === "string" && !toolCallReplayShapes({
|
|
2231
|
-
callId: previousItem.call_id,
|
|
2232
|
-
...typeof previousItem.id === "string" ? { itemId: previousItem.id } : {}
|
|
2233
|
-
}).has(currentItem.call_id)) return false;
|
|
2234
|
-
}
|
|
2235
|
-
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 false;
|
|
2236
|
-
}
|
|
2237
|
-
const normalizedPrevious = normalizeContinuationHistory(previousInput);
|
|
2238
|
-
const normalizedCurrent = normalizeContinuationHistory(currentInput);
|
|
2239
|
-
return normalizedPrevious !== void 0 && normalizedCurrent !== void 0 && jsonValuesEqual(normalizedCurrent, normalizedPrevious);
|
|
2240
|
-
}
|
|
2241
1188
|
function responsesContinuationRequestFingerprint(request) {
|
|
2242
|
-
|
|
2243
|
-
return sha256Hex(stableStringify(JSON.parse(serialized)));
|
|
1189
|
+
return sha256StableValue(projectJsonObject(requestWithoutInput(request))).digest;
|
|
2244
1190
|
}
|
|
2245
1191
|
function responsesContinuationPrefixFingerprint(input, output = []) {
|
|
2246
|
-
|
|
2247
|
-
return sha256Hex(stableStringify(JSON.parse(serialized)));
|
|
2248
|
-
}
|
|
2249
|
-
function restoreRawCallIdsInDelta(delta, cachedResponseItems, replayedToolRound, pendingToolCalls) {
|
|
2250
|
-
const currentResponseCalls = responseToolCalls(cachedResponseItems);
|
|
2251
|
-
const replayedCalls = replayedToolRound.filter((item) => isRecord(item) && item.type === "function_call");
|
|
2252
|
-
if (currentResponseCalls.length !== replayedCalls.length) return;
|
|
2253
|
-
const cachedCalls = [...pendingToolCalls, ...currentResponseCalls];
|
|
2254
|
-
const currentCallOffset = pendingToolCalls.length;
|
|
2255
|
-
const ownerByReplayShape = toolCallOwnerByReplayShape(cachedCalls);
|
|
2256
|
-
for (const index of currentResponseCalls.keys()) {
|
|
2257
|
-
const replayedCallId = replayedCalls[index]?.call_id;
|
|
2258
|
-
if (typeof replayedCallId !== "string" || ownerByReplayShape.get(replayedCallId) !== currentCallOffset + index) return;
|
|
2259
|
-
}
|
|
2260
|
-
const restoredDelta = [];
|
|
2261
|
-
for (const item of delta) {
|
|
2262
|
-
if (!isRecord(item) || item.type !== "function_call_output" || typeof item.call_id !== "string") {
|
|
2263
|
-
restoredDelta.push(item);
|
|
2264
|
-
continue;
|
|
2265
|
-
}
|
|
2266
|
-
const owner = ownerByReplayShape.get(item.call_id);
|
|
2267
|
-
if (owner === void 0 || owner === null) return;
|
|
2268
|
-
const rawCallId = cachedCalls[owner]?.callId;
|
|
2269
|
-
if (!rawCallId) return;
|
|
2270
|
-
restoredDelta.push(rawCallId === item.call_id ? item : {
|
|
2271
|
-
...item,
|
|
2272
|
-
call_id: rawCallId
|
|
2273
|
-
});
|
|
2274
|
-
}
|
|
2275
|
-
return restoredDelta;
|
|
1192
|
+
return sha256StableValue(projectJsonObject([...normalizeAssistantReplayInput(input), ...normalizeAssistantReplayInput(output, true)])).digest;
|
|
2276
1193
|
}
|
|
2277
1194
|
function resolveResponsesContinuationRequest(continuation, request, steering) {
|
|
2278
1195
|
if (!continuation) return {
|
|
@@ -2302,15 +1219,70 @@ function resolveResponsesContinuationRequest(continuation, request, steering) {
|
|
|
2302
1219
|
const replayedToolRoundInput = currentInput.slice(previousInput.length, baselineLength);
|
|
2303
1220
|
const replayedToolRound = normalizeAssistantReplayInput(replayedToolRoundInput);
|
|
2304
1221
|
const historyToolRoundUnchanged = [false, true].some((ignoreCachedItemIds) => jsonValuesEqual(replayedToolRound, normalizeAssistantReplayInput(continuation.lastResponseItems, true, ignoreCachedItemIds)));
|
|
2305
|
-
|
|
1222
|
+
const historyCurrentInput = currentInput.slice(0, previousInput.length);
|
|
1223
|
+
for (const [index, previousItem] of previousInput.entries()) {
|
|
1224
|
+
const currentItem = historyCurrentInput[index];
|
|
1225
|
+
if (!isRecord(previousItem) || !isRecord(currentItem)) continue;
|
|
1226
|
+
if (previousItem.type === "function_call" && currentItem.type === "function_call") {
|
|
1227
|
+
if (typeof previousItem.call_id === "string" && typeof currentItem.call_id === "string" && !toolCallReplayShapes({
|
|
1228
|
+
callId: previousItem.call_id,
|
|
1229
|
+
...typeof previousItem.id === "string" ? { itemId: previousItem.id } : {}
|
|
1230
|
+
}).has(currentItem.call_id)) return {
|
|
1231
|
+
request,
|
|
1232
|
+
continuationStatus: "history_changed"
|
|
1233
|
+
};
|
|
1234
|
+
}
|
|
1235
|
+
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 {
|
|
1236
|
+
request,
|
|
1237
|
+
continuationStatus: "history_changed"
|
|
1238
|
+
};
|
|
1239
|
+
}
|
|
1240
|
+
const normalizedPrevious = normalizeContinuationHistory(previousInput);
|
|
1241
|
+
const normalizedCurrent = normalizeContinuationHistory(historyCurrentInput);
|
|
1242
|
+
if (!(normalizedPrevious !== void 0 && normalizedCurrent !== void 0 && jsonValuesEqual(normalizedCurrent, normalizedPrevious)) || !historyToolRoundUnchanged) return {
|
|
2306
1243
|
request,
|
|
2307
1244
|
continuationStatus: "history_changed"
|
|
2308
1245
|
};
|
|
2309
|
-
const
|
|
2310
|
-
|
|
1246
|
+
const delta = currentInput.slice(baselineLength);
|
|
1247
|
+
const cachedResponseItems = continuation.lastResponseItems;
|
|
1248
|
+
const pendingToolCalls = continuation.pendingToolCalls ?? [];
|
|
1249
|
+
const currentResponseCalls = responseToolCalls(cachedResponseItems);
|
|
1250
|
+
const replayedCalls = replayedToolRoundInput.filter((item) => isRecord(item) && item.type === "function_call");
|
|
1251
|
+
if (currentResponseCalls.length !== replayedCalls.length) return {
|
|
2311
1252
|
request,
|
|
2312
1253
|
continuationStatus: "history_changed"
|
|
2313
1254
|
};
|
|
1255
|
+
const cachedCalls = [...pendingToolCalls, ...currentResponseCalls];
|
|
1256
|
+
const currentCallOffset = pendingToolCalls.length;
|
|
1257
|
+
const ownerByReplayShape = toolCallOwnerByReplayShape(cachedCalls);
|
|
1258
|
+
for (const index of currentResponseCalls.keys()) {
|
|
1259
|
+
const replayedCallId = replayedCalls[index]?.call_id;
|
|
1260
|
+
if (typeof replayedCallId !== "string" || ownerByReplayShape.get(replayedCallId) !== currentCallOffset + index) return {
|
|
1261
|
+
request,
|
|
1262
|
+
continuationStatus: "history_changed"
|
|
1263
|
+
};
|
|
1264
|
+
}
|
|
1265
|
+
const restoredInput = [];
|
|
1266
|
+
for (const item of delta) {
|
|
1267
|
+
if (!isRecord(item) || item.type !== "function_call_output" || typeof item.call_id !== "string") {
|
|
1268
|
+
restoredInput.push(item);
|
|
1269
|
+
continue;
|
|
1270
|
+
}
|
|
1271
|
+
const owner = ownerByReplayShape.get(item.call_id);
|
|
1272
|
+
if (owner === void 0 || owner === null) return {
|
|
1273
|
+
request,
|
|
1274
|
+
continuationStatus: "history_changed"
|
|
1275
|
+
};
|
|
1276
|
+
const rawCallId = cachedCalls[owner]?.callId;
|
|
1277
|
+
if (!rawCallId) return {
|
|
1278
|
+
request,
|
|
1279
|
+
continuationStatus: "history_changed"
|
|
1280
|
+
};
|
|
1281
|
+
restoredInput.push(rawCallId === item.call_id ? item : {
|
|
1282
|
+
...item,
|
|
1283
|
+
call_id: rawCallId
|
|
1284
|
+
});
|
|
1285
|
+
}
|
|
2314
1286
|
const restoredResponseInput = restoredInput;
|
|
2315
1287
|
return {
|
|
2316
1288
|
request: {
|
|
@@ -2361,51 +1333,64 @@ function connectionIdentity(params) {
|
|
|
2361
1333
|
headers
|
|
2362
1334
|
]));
|
|
2363
1335
|
}
|
|
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
|
+
}
|
|
2364
1352
|
function claimOpenAIResponsesHttpContinuation(params) {
|
|
2365
1353
|
const owner = getAiTransportHost();
|
|
2366
1354
|
const key = `${getSessionResourceOwnerId(owner)}\0${params.sessionId}\0${connectionIdentity(params)}`;
|
|
2367
1355
|
const previous = httpContinuationEntries.get(key);
|
|
2368
1356
|
if (previous?.kind === "claimed") return;
|
|
2369
1357
|
if (previous) deleteHttpContinuationIfOwned(key, previous);
|
|
1358
|
+
const request = previous ? params.request : params.restoreRequest?.() ?? params.request;
|
|
1359
|
+
const resolved = resolveResponsesContinuationRequest(previous?.state, request);
|
|
1360
|
+
const fullRequest = resolved.fullRequest ?? request;
|
|
1361
|
+
const continuationRequest = params.request.store === false ? fullRequest : resolved.request;
|
|
2370
1362
|
const claimed = {
|
|
2371
1363
|
kind: "claimed",
|
|
2372
1364
|
sessionId: params.sessionId,
|
|
2373
1365
|
owner
|
|
2374
1366
|
};
|
|
2375
1367
|
httpContinuationEntries.set(key, claimed);
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2398
|
-
|
|
2399
|
-
|
|
2400
|
-
|
|
2401
|
-
|
|
2402
|
-
},
|
|
2403
|
-
release: () => deleteHttpContinuationIfOwned(key, claimed)
|
|
2404
|
-
};
|
|
2405
|
-
} catch (error) {
|
|
2406
|
-
deleteHttpContinuationIfOwned(key, claimed);
|
|
2407
|
-
throw error;
|
|
2408
|
-
}
|
|
1368
|
+
return {
|
|
1369
|
+
request: continuationRequest,
|
|
1370
|
+
fullRequest,
|
|
1371
|
+
commit: (effectiveRequest, response, dispatchedPreviousResponseId) => {
|
|
1372
|
+
if (httpContinuationEntries.get(key) !== claimed) return;
|
|
1373
|
+
const state = recordResponsesContinuationState(previous?.state, effectiveRequest, response, previous !== void 0 && dispatchedPreviousResponseId === previous.state.lastResponseId);
|
|
1374
|
+
const { retainedBytes, strings } = retainedJsonBytes(state, previous?.strings);
|
|
1375
|
+
if (retainedBytes > MAX_HTTP_CONTINUATION_RETAINED_BYTES) {
|
|
1376
|
+
deleteHttpContinuationIfOwned(key, claimed);
|
|
1377
|
+
return;
|
|
1378
|
+
}
|
|
1379
|
+
evictReadyEntriesForCapacity(retainedBytes);
|
|
1380
|
+
const ready = {
|
|
1381
|
+
...claimed,
|
|
1382
|
+
kind: "ready",
|
|
1383
|
+
state,
|
|
1384
|
+
idleTimer: owner.runInDetachedAsyncContext(() => createHttpContinuationTimer(key)),
|
|
1385
|
+
retainedBytes,
|
|
1386
|
+
strings
|
|
1387
|
+
};
|
|
1388
|
+
httpContinuationRetainedBytes += retainedBytes;
|
|
1389
|
+
httpContinuationEntries.set(key, ready);
|
|
1390
|
+
readyHttpContinuationEntries.set(key, ready);
|
|
1391
|
+
},
|
|
1392
|
+
release: () => deleteHttpContinuationIfOwned(key, claimed)
|
|
1393
|
+
};
|
|
2409
1394
|
}
|
|
2410
1395
|
registerSessionResourceCleanup((sessionId, owner) => {
|
|
2411
1396
|
for (const [key, entry] of httpContinuationEntries) if ((!owner || entry.owner === owner) && (!sessionId || entry.sessionId === sessionId)) deleteHttpContinuationIfOwned(key, entry);
|
|
@@ -2421,7 +1406,7 @@ function readResponsesInputReplayState(message) {
|
|
|
2421
1406
|
}
|
|
2422
1407
|
function readResponsesInputReplay(message) {
|
|
2423
1408
|
const replay = readResponsesInputReplayState(message);
|
|
2424
|
-
if (replay && typeof replay.afterResponseId === "string" &&
|
|
1409
|
+
if (replay && typeof replay.afterResponseId === "string" && isStringArray(replay.before) && isStringArray(replay.after)) return {
|
|
2425
1410
|
afterResponseId: replay.afterResponseId,
|
|
2426
1411
|
before: replay.before,
|
|
2427
1412
|
after: replay.after
|
|
@@ -2599,7 +1584,8 @@ function parseOpenAIResponsesTextSignature(signature) {
|
|
|
2599
1584
|
const phase = parsed.phase === "commentary" || parsed.phase === "final_answer" ? parsed.phase : void 0;
|
|
2600
1585
|
if (id !== void 0 || phase !== void 0) return {
|
|
2601
1586
|
id,
|
|
2602
|
-
phase
|
|
1587
|
+
phase,
|
|
1588
|
+
...typeof parsed.sources === "string" ? { sources: parsed.sources } : {}
|
|
2603
1589
|
};
|
|
2604
1590
|
return;
|
|
2605
1591
|
}
|
|
@@ -2625,10 +1611,18 @@ function buildResponsesInputMessage(role, content, source) {
|
|
|
2625
1611
|
...identity ? { [responsesInputSource]: identity } : {}
|
|
2626
1612
|
};
|
|
2627
1613
|
}
|
|
1614
|
+
const responsesMessageProjections = /* @__PURE__ */ new WeakMap();
|
|
1615
|
+
/** Detach hook-editable JSON containers while retaining scalar strings. */
|
|
1616
|
+
function cloneResponsesInputForPayloadHook(value) {
|
|
1617
|
+
if (!value || typeof value !== "object") return value;
|
|
1618
|
+
if (Array.isArray(value)) return value.map(cloneResponsesInputForPayloadHook);
|
|
1619
|
+
const copy = { ...value };
|
|
1620
|
+
for (const key of Object.keys(copy)) Reflect.set(copy, key, cloneResponsesInputForPayloadHook(Reflect.get(value, key)));
|
|
1621
|
+
return copy;
|
|
1622
|
+
}
|
|
2628
1623
|
function convertResponsesMessagesWithStyle(model, context, allowedToolCallProviders, options, conversionStyle) {
|
|
2629
1624
|
const messages = [];
|
|
2630
1625
|
const providerStyle = conversionStyle === "provider";
|
|
2631
|
-
const shouldReplayReasoningItems = options?.replayReasoningItems ?? true;
|
|
2632
1626
|
const shouldReplayResponsesItemIds = options?.replayResponsesItemIds ?? true;
|
|
2633
1627
|
const replayContext = buildProviderReplayContext(model, {
|
|
2634
1628
|
sessionId: options?.sessionId,
|
|
@@ -2671,7 +1665,7 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
2671
1665
|
const transformedMessages = orderResponsesAsyncToolResults(transformMessages(replayPlan.messages));
|
|
2672
1666
|
if ((options?.includeSystemPrompt ?? true) && context.systemPrompt) messages.push(buildResponsesInputMessage(resolveResponsesInstructionRole(model), [{
|
|
2673
1667
|
type: "input_text",
|
|
2674
|
-
text:
|
|
1668
|
+
text: prepareSystemPrompt(context.systemPrompt, context.preparedSystemPrompt).instructions
|
|
2675
1669
|
}]));
|
|
2676
1670
|
if (replayPlan.compactedWindow) messages.push(...replayPlan.compactedWindow.map((item) => {
|
|
2677
1671
|
if (options?.retainUserProvenance && item.type === "message" && item.role === "user") return Object.assign({}, item, { [RESPONSES_RETAINED_USER]: true });
|
|
@@ -2695,12 +1689,9 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
2695
1689
|
let msgIndex = 0;
|
|
2696
1690
|
const appendAssistant = createResponsesInputReplay(model);
|
|
2697
1691
|
const inHistorySystemUpdates = supportsNativeOpenAIResponsesEndpoint(model);
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
continue;
|
|
2702
|
-
}
|
|
2703
|
-
if (inHistorySystemUpdates && isRuntimeContextMessage(msg)) messages.push(buildResponsesInputMessage(resolveResponsesInstructionRole(model), [{
|
|
1692
|
+
const convertMessage = (msg, messageIndex) => {
|
|
1693
|
+
const converted = [];
|
|
1694
|
+
if (inHistorySystemUpdates && isRuntimeContextMessage(msg)) converted.push(buildResponsesInputMessage(resolveResponsesInstructionRole(model), [{
|
|
2704
1695
|
type: "input_text",
|
|
2705
1696
|
text: sanitizeTransportPayloadText(runtimeContextContentToText(msg.content))
|
|
2706
1697
|
}]));
|
|
@@ -2712,18 +1703,14 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
2712
1703
|
}] : msg.content.map((item) => item.type === "text" ? {
|
|
2713
1704
|
type: "input_text",
|
|
2714
1705
|
text: sanitizeTransportPayloadText(item.text)
|
|
2715
|
-
} :
|
|
2716
|
-
type: "input_image",
|
|
2717
|
-
detail: "auto",
|
|
2718
|
-
image_url: `data:${item.mimeType};base64,${item.data}`
|
|
2719
|
-
}).filter((item) => providerStyle || model.input.includes("image") || item.type !== "input_image");
|
|
1706
|
+
} : buildResponsesInputImage(item)).filter((item) => providerStyle || model.input.includes("image") || item.type !== "input_image");
|
|
2720
1707
|
if (content.length > 0) {
|
|
2721
1708
|
const input = buildResponsesInputMessage(role, content, msg);
|
|
2722
1709
|
if (options?.retainUserProvenance && role === "user" && !msg.synthetic && !msg.operatorMessage && !hasRuntimeContextMarker(msg)) Object.assign(input, { [RESPONSES_RETAINED_USER]: true });
|
|
2723
|
-
|
|
2724
|
-
}
|
|
1710
|
+
converted.push(input);
|
|
1711
|
+
}
|
|
2725
1712
|
} else if (msg.role === "assistant") {
|
|
2726
|
-
const output =
|
|
1713
|
+
const output = converted;
|
|
2727
1714
|
const sourceTurnKey = responsesAssistantTurnKey(msg);
|
|
2728
1715
|
const sourceFragmentId = msg.content.find((block) => block.type === "toolCall")?.id;
|
|
2729
1716
|
let textFallbackOrdinal = 0;
|
|
@@ -2731,7 +1718,7 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
2731
1718
|
let seenReplayableReasoning = false;
|
|
2732
1719
|
const isDifferentModel = msg.model !== model.id && msg.provider === model.provider && msg.api === model.api;
|
|
2733
1720
|
for (const block of msg.content) if (block.type === "thinking") {
|
|
2734
|
-
if (
|
|
1721
|
+
if (block.thinkingSignature && (providerStyle || block.thinkingSignature.startsWith("{"))) {
|
|
2735
1722
|
let reasoningItem;
|
|
2736
1723
|
try {
|
|
2737
1724
|
reasoningItem = JSON.parse(block.thinkingSignature);
|
|
@@ -2754,18 +1741,20 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
2754
1741
|
let msgId = resolveReplayableResponsesMessageId({
|
|
2755
1742
|
replayResponsesItemIds: shouldReplayResponsesItemIds,
|
|
2756
1743
|
textSignatureId: textSignature?.id,
|
|
2757
|
-
fallbackId: sourceTurnKey ? `msg_${shortHash(JSON.stringify([sourceTurnKey, sourceFragmentId]))}` : `msg_${
|
|
1744
|
+
fallbackId: sourceTurnKey ? `msg_${shortHash(JSON.stringify([sourceTurnKey, sourceFragmentId]))}` : `msg_${messageIndex}`,
|
|
2758
1745
|
fallbackOrdinal: textFallbackOrdinal,
|
|
2759
1746
|
previousReplayItemWasReasoning
|
|
2760
1747
|
});
|
|
2761
1748
|
if (!textSignature?.id) textFallbackOrdinal += 1;
|
|
2762
1749
|
msgId = normalizeResponsesReplayItemId(msgId);
|
|
1750
|
+
const sources = textSignature?.sources;
|
|
1751
|
+
const providerText = sources && block.text.endsWith(sources) ? block.text.slice(0, -sources.length) : block.text;
|
|
2763
1752
|
const messageItem = {
|
|
2764
1753
|
type: "message",
|
|
2765
1754
|
role: "assistant",
|
|
2766
1755
|
content: [{
|
|
2767
1756
|
type: "output_text",
|
|
2768
|
-
text: sanitizeTransportPayloadText(
|
|
1757
|
+
text: sanitizeTransportPayloadText(providerText),
|
|
2769
1758
|
annotations: []
|
|
2770
1759
|
}],
|
|
2771
1760
|
status: "completed",
|
|
@@ -2794,8 +1783,7 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
2794
1783
|
if (last?.type !== "reasoning" || !last.id?.startsWith("rs_") || typeof last.encrypted_content === "string" && last.encrypted_content.length > 0) break;
|
|
2795
1784
|
output.pop();
|
|
2796
1785
|
}
|
|
2797
|
-
|
|
2798
|
-
if (output.length === 0 && providerStyle) continue;
|
|
1786
|
+
return output;
|
|
2799
1787
|
} else if (msg.role === "toolResult") {
|
|
2800
1788
|
const textResult = extractToolResultText(msg.content);
|
|
2801
1789
|
const hasText = textResult.trim().length > 0;
|
|
@@ -2808,11 +1796,7 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
2808
1796
|
if (hasImages && model.input.includes("image")) {
|
|
2809
1797
|
const parts = [];
|
|
2810
1798
|
let hasExplicitText = false;
|
|
2811
|
-
for (const item of msg.content) if (isImageWithMediaPayload(item)) parts.push(
|
|
2812
|
-
type: "input_image",
|
|
2813
|
-
detail: "auto",
|
|
2814
|
-
image_url: `data:${item.mimeType};base64,${item.data}`
|
|
2815
|
-
});
|
|
1799
|
+
for (const item of msg.content) if (isImageWithMediaPayload(item)) parts.push(buildResponsesInputImage(item));
|
|
2816
1800
|
else if (hasText && item.type === "text") {
|
|
2817
1801
|
const text = extractToolResultBlockText(item);
|
|
2818
1802
|
if (text) {
|
|
@@ -2836,13 +1820,52 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
2836
1820
|
});
|
|
2837
1821
|
output = parts;
|
|
2838
1822
|
}
|
|
2839
|
-
|
|
1823
|
+
converted.push({
|
|
2840
1824
|
type: "function_call_output",
|
|
2841
1825
|
call_id: callId,
|
|
2842
1826
|
output
|
|
2843
1827
|
});
|
|
2844
1828
|
}
|
|
2845
|
-
|
|
1829
|
+
return converted;
|
|
1830
|
+
};
|
|
1831
|
+
const immutable = getAiTransportHost().immutableData;
|
|
1832
|
+
const projectionKey = JSON.stringify([
|
|
1833
|
+
conversionStyle,
|
|
1834
|
+
replayContext,
|
|
1835
|
+
shouldReplayResponsesItemIds,
|
|
1836
|
+
inHistorySystemUpdates,
|
|
1837
|
+
resolveResponsesInstructionRole(model),
|
|
1838
|
+
model.input.includes("image"),
|
|
1839
|
+
options?.retainUserProvenance === true
|
|
1840
|
+
]);
|
|
1841
|
+
for (const msg of replayMessages) {
|
|
1842
|
+
if (!("role" in msg)) {
|
|
1843
|
+
messages.push(msg);
|
|
1844
|
+
continue;
|
|
1845
|
+
}
|
|
1846
|
+
const reusable = immutable && !preparedRequestSuffix.has(context) && immutable.isDeeplyFrozenPlainData(msg) && (typeof msg.content === "string" || !msg.content.some((block) => block.type === "image"));
|
|
1847
|
+
const key = `${projectionKey}:${msgIndex}`;
|
|
1848
|
+
let projections = reusable ? responsesMessageProjections.get(msg) : void 0;
|
|
1849
|
+
let output = projections?.get(key);
|
|
1850
|
+
if (!output) {
|
|
1851
|
+
output = convertMessage(msg, msgIndex);
|
|
1852
|
+
if (reusable) {
|
|
1853
|
+
immutable.freezeJsonSnapshot(output);
|
|
1854
|
+
if (!projections) {
|
|
1855
|
+
projections = /* @__PURE__ */ new Map();
|
|
1856
|
+
responsesMessageProjections.set(msg, projections);
|
|
1857
|
+
}
|
|
1858
|
+
if (projections.size >= 8) {
|
|
1859
|
+
const oldest = projections.keys().next().value;
|
|
1860
|
+
if (oldest !== void 0) projections.delete(oldest);
|
|
1861
|
+
}
|
|
1862
|
+
projections.set(key, output);
|
|
1863
|
+
}
|
|
1864
|
+
}
|
|
1865
|
+
if (reusable && options?.mutableInput) output = cloneResponsesInputForPayloadHook(output);
|
|
1866
|
+
if (msg.role === "assistant") appendAssistant(messages, output, msg);
|
|
1867
|
+
else messages.push(...output);
|
|
1868
|
+
if (output.length > 0 || !providerStyle) msgIndex += 1;
|
|
2846
1869
|
}
|
|
2847
1870
|
return messages;
|
|
2848
1871
|
}
|
|
@@ -2854,28 +1877,22 @@ function convertProviderResponsesMessages(model, context, allowedToolCallProvide
|
|
|
2854
1877
|
}
|
|
2855
1878
|
//#endregion
|
|
2856
1879
|
//#region packages/ai/src/transports/openai-responses-context-usage.ts
|
|
2857
|
-
const TOOL_CALL_PROVIDERS = /* @__PURE__ */ new Set([
|
|
2858
|
-
"openai",
|
|
2859
|
-
"opencode",
|
|
2860
|
-
"azure-openai-responses",
|
|
2861
|
-
"github-copilot"
|
|
2862
|
-
]);
|
|
2863
1880
|
function contextFingerprint(input, output = []) {
|
|
2864
1881
|
const reasoning = [...input, ...output].flatMap((item) => {
|
|
2865
1882
|
if (!isRecord(item) || item.type !== "reasoning") return [];
|
|
2866
1883
|
const { id: _id, status: _status, ...content } = item;
|
|
2867
1884
|
return [content];
|
|
2868
1885
|
});
|
|
2869
|
-
return
|
|
1886
|
+
return sha256StableValue({
|
|
2870
1887
|
prefix: responsesContinuationPrefixFingerprint(input, output),
|
|
2871
1888
|
reasoning
|
|
2872
|
-
})
|
|
1889
|
+
}).digest;
|
|
2873
1890
|
}
|
|
2874
1891
|
/** Bind measured usage to the admitted replay prefix, without copying its content. */
|
|
2875
1892
|
function recordResponsesContextUsage(message, model, identity, request, output, projection) {
|
|
2876
1893
|
const usage = message.usage.contextUsage;
|
|
2877
1894
|
if (usage?.state !== "available" || !Number.isSafeInteger(usage.totalTokens) || usage.totalTokens <= 0 || message.stopReason === "error" || message.stopReason === "aborted" || message.providerReplay || request.previous_response_id || !Array.isArray(request.input) || !request.input.some((item) => isRecord(item) && item.type === "compaction") || !Array.isArray(output) || output.some((item) => isRecord(item) && item.type === "compaction")) return;
|
|
2878
|
-
const replayOutput = (projection === "transport" ? convertResponsesMessages : convertProviderResponsesMessages)(model, { messages: [message] },
|
|
1895
|
+
const replayOutput = (projection === "transport" ? convertResponsesMessages : convertProviderResponsesMessages)(model, { messages: [message] }, OPENAI_RESPONSES_TOOL_CALL_PROVIDERS, {
|
|
2879
1896
|
...identity,
|
|
2880
1897
|
includeSystemPrompt: false
|
|
2881
1898
|
}).filter((item) => item.type !== "function_call_output");
|
|
@@ -2907,7 +1924,7 @@ function resolveResponsesContextUsageBoundary(messages, model, identity, systemP
|
|
|
2907
1924
|
const input = (projection === "transport" ? convertResponsesMessages : convertProviderResponsesMessages)(model, {
|
|
2908
1925
|
messages: messages.filter(isProviderMessage),
|
|
2909
1926
|
systemPrompt
|
|
2910
|
-
},
|
|
1927
|
+
}, OPENAI_RESPONSES_TOOL_CALL_PROVIDERS, {
|
|
2911
1928
|
...identity,
|
|
2912
1929
|
includeSystemPrompt: includeSystemPrompt === true
|
|
2913
1930
|
});
|
|
@@ -3002,20 +2019,6 @@ function summarizeResponsesTools(tools) {
|
|
|
3002
2019
|
const shown = names.slice(0, maxNames).join(",");
|
|
3003
2020
|
return `count=${tools.length}${shown ? ` ${label}=${shown}` : ""}`;
|
|
3004
2021
|
}
|
|
3005
|
-
function stringifyRedactedPayload(value) {
|
|
3006
|
-
try {
|
|
3007
|
-
const encoded = JSON.stringify(value, (key, child) => key === "encrypted_content" ? "<opaque data omitted>" : child);
|
|
3008
|
-
if (!encoded) return "<empty>";
|
|
3009
|
-
const redacted = redactSensitiveText(encoded);
|
|
3010
|
-
return redacted.length > 8e3 ? `${truncateUtf16Safe(redacted, 8e3)}…<truncated>` : redacted;
|
|
3011
|
-
} catch {
|
|
3012
|
-
return "<unserializable>";
|
|
3013
|
-
}
|
|
3014
|
-
}
|
|
3015
|
-
function stringifyRedactedEvent(value) {
|
|
3016
|
-
const redacted = stringifyRedactedPayload(value);
|
|
3017
|
-
return redacted.length > 2e3 ? `${truncateUtf16Safe(redacted, 2e3)}…<truncated>` : redacted;
|
|
3018
|
-
}
|
|
3019
2022
|
const RESPONSE_FAILED_FAILURE_FIELD_KEYS = [
|
|
3020
2023
|
"error",
|
|
3021
2024
|
"incomplete_details",
|
|
@@ -3033,10 +2036,6 @@ function buildResponsesFailedEventSummary(message, responseId, code, observation
|
|
|
3033
2036
|
...observation ? { observation } : {}
|
|
3034
2037
|
};
|
|
3035
2038
|
}
|
|
3036
|
-
function isResponseFailedIdentifierKey(key) {
|
|
3037
|
-
const normalized = key.replace(/[-_\s]/g, "").toLowerCase();
|
|
3038
|
-
return normalized.includes("request") && normalized.endsWith("id") || normalized.includes("provider") && normalized.endsWith("id");
|
|
3039
|
-
}
|
|
3040
2039
|
function collectResponseFailedIdentifierHashes(input) {
|
|
3041
2040
|
const out = [];
|
|
3042
2041
|
const seen = /* @__PURE__ */ new WeakSet();
|
|
@@ -3048,7 +2047,8 @@ function collectResponseFailedIdentifierHashes(input) {
|
|
|
3048
2047
|
if (out.length >= 12 || typeof key === "number" && key >= 8) break;
|
|
3049
2048
|
const childPath = typeof key === "number" ? `${path}[${key}]` : path ? `${path}.${key}` : key;
|
|
3050
2049
|
const childIdentifierKey = typeof key === "number" ? identifierKey : key;
|
|
3051
|
-
const
|
|
2050
|
+
const normalizedKey = childIdentifierKey.replace(/[-_\s]/g, "").toLowerCase();
|
|
2051
|
+
const isIdentifier = normalizedKey.includes("request") && normalizedKey.endsWith("id") || normalizedKey.includes("provider") && normalizedKey.endsWith("id");
|
|
3052
2052
|
const childString = typeof child === "string" || typeof child === "number" ? String(child).trim() : "";
|
|
3053
2053
|
if (isIdentifier && childString) out.push(`${childPath}=${redactIdentifier(childString, { len: 12 })}`);
|
|
3054
2054
|
else visit(child, childPath, depth + 1, isIdentifier ? childIdentifierKey : "");
|
|
@@ -3057,58 +2057,24 @@ function collectResponseFailedIdentifierHashes(input) {
|
|
|
3057
2057
|
visit(input, "", 0, "");
|
|
3058
2058
|
return out;
|
|
3059
2059
|
}
|
|
3060
|
-
function
|
|
3061
|
-
const
|
|
3062
|
-
const redact = (value, key, depth) => {
|
|
3063
|
-
if (typeof value === "string" || typeof value === "number") return key && isResponseFailedIdentifierKey(key) ? redactIdentifier(String(value), { len: 12 }) : value;
|
|
3064
|
-
if (depth > 6 || !value || typeof value !== "object") return value;
|
|
3065
|
-
if (seen.has(value)) return "<circular>";
|
|
3066
|
-
seen.add(value);
|
|
3067
|
-
if (Array.isArray(value)) return value.slice(0, 16).map((item) => redact(item, key, depth + 1));
|
|
3068
|
-
const out = {};
|
|
3069
|
-
for (const [childKey, child] of Object.entries(value)) out[childKey] = redact(child, childKey, depth + 1);
|
|
3070
|
-
return out;
|
|
3071
|
-
};
|
|
3072
|
-
return redact(input, "", 0);
|
|
3073
|
-
}
|
|
3074
|
-
function buildResponsesFailedFailureFields(response) {
|
|
3075
|
-
if (!response) return {};
|
|
3076
|
-
const fields = {};
|
|
3077
|
-
for (const key of RESPONSE_FAILED_FAILURE_FIELD_KEYS) if (response[key] !== void 0 && response[key] !== null) fields[key] = response[key];
|
|
3078
|
-
return fields;
|
|
3079
|
-
}
|
|
3080
|
-
function buildResponsesFailedNoDetailsObservation(event, model, response = isRecord(event.response) ? event.response : void 0) {
|
|
3081
|
-
const failureFields = redactResponseFailedDiagnosticValue(buildResponsesFailedFailureFields(response));
|
|
2060
|
+
function buildResponsesFailedNoDetailsObservation(event, model, response) {
|
|
2061
|
+
const failureFieldNames = RESPONSE_FAILED_FAILURE_FIELD_KEYS.filter((key) => response?.[key] !== void 0 && response[key] !== null);
|
|
3082
2062
|
const metadataKeys = isRecord(response?.metadata) ? Object.keys(response.metadata).toSorted() : [];
|
|
3083
|
-
const responsePreview = {
|
|
3084
|
-
id: stringifyUnknown(response?.id),
|
|
3085
|
-
status: stringifyUnknown(response?.status),
|
|
3086
|
-
model: stringifyUnknown(response?.model),
|
|
3087
|
-
object: stringifyUnknown(response?.object),
|
|
3088
|
-
failureFields,
|
|
3089
|
-
metadataKeys
|
|
3090
|
-
};
|
|
3091
2063
|
return {
|
|
3092
2064
|
event: "openai_responses_response_failed_without_details",
|
|
3093
2065
|
provider: model.provider,
|
|
3094
2066
|
api: model.api,
|
|
3095
2067
|
transportModel: model.id,
|
|
3096
2068
|
providerRuntimeFailureKind: "no_error_details",
|
|
3097
|
-
responseId:
|
|
3098
|
-
responseStatus:
|
|
3099
|
-
responseModel:
|
|
3100
|
-
responseObject:
|
|
2069
|
+
responseId: stringifyUnknown(response?.id),
|
|
2070
|
+
responseStatus: stringifyUnknown(response?.status),
|
|
2071
|
+
responseModel: stringifyUnknown(response?.model),
|
|
2072
|
+
responseObject: stringifyUnknown(response?.object),
|
|
3101
2073
|
metadataKeys,
|
|
3102
2074
|
requestIdHashes: collectResponseFailedIdentifierHashes(event),
|
|
3103
|
-
|
|
3104
|
-
responsePreview: stringifyRedactedEvent(responsePreview)
|
|
2075
|
+
failureFieldNames
|
|
3105
2076
|
};
|
|
3106
2077
|
}
|
|
3107
|
-
function summarizeResponsesFailedNoDetailsObservation(observation) {
|
|
3108
|
-
const requestIds = observation.requestIdHashes.join(",");
|
|
3109
|
-
const metadataKeys = observation.metadataKeys.join(",");
|
|
3110
|
-
return `responseId=${safeDebugValue(observation.responseId || void 0)} responseStatus=${safeDebugValue(observation.responseStatus || void 0)} responseModel=${safeDebugValue(observation.responseModel || void 0)} requestIds=${requestIds || "none"} metadataKeys=${metadataKeys || "none"} failureFields=${observation.failureFieldsPreview}`;
|
|
3111
|
-
}
|
|
3112
2078
|
function normalizeResponsesFailedEvent(event, model) {
|
|
3113
2079
|
const response = isRecord(event.response) ? event.response : void 0;
|
|
3114
2080
|
const responseId = stringifyUnknown(response?.id) || void 0;
|
|
@@ -3133,7 +2099,9 @@ var ResponsesStreamFailure = class extends Error {
|
|
|
3133
2099
|
}
|
|
3134
2100
|
};
|
|
3135
2101
|
function logResponsesFailedNoDetails(observation) {
|
|
3136
|
-
|
|
2102
|
+
const requestIds = observation.requestIdHashes.join(",");
|
|
2103
|
+
const metadataKeys = observation.metadataKeys.join(",");
|
|
2104
|
+
log.warn(`[responses] response.failed missing error details provider=${observation.provider} api=${observation.api} model=${observation.transportModel} responseId=${safeDebugValue(observation.responseId || void 0)} responseStatus=${safeDebugValue(observation.responseStatus || void 0)} responseModel=${safeDebugValue(observation.responseModel || void 0)} requestIds=${requestIds || "none"} metadataKeys=${metadataKeys || "none"} failureFields=${observation.failureFieldNames.join(",") || "none"}`, observation);
|
|
3137
2105
|
}
|
|
3138
2106
|
function summarizeResponsesPayload(params) {
|
|
3139
2107
|
if (!params || typeof params !== "object") return "payload=non-object";
|
|
@@ -3141,7 +2109,7 @@ function summarizeResponsesPayload(params) {
|
|
|
3141
2109
|
const input = record.input;
|
|
3142
2110
|
const reasoning = record.reasoning && typeof record.reasoning === "object" ? record.reasoning : void 0;
|
|
3143
2111
|
const text = record.text && typeof record.text === "object" ? record.text : void 0;
|
|
3144
|
-
|
|
2112
|
+
return [
|
|
3145
2113
|
`fields=${Object.keys(record).toSorted().join(",")}`,
|
|
3146
2114
|
`model=${safeDebugValue(record.model)}`,
|
|
3147
2115
|
`stream=${safeDebugValue(record.stream)}`,
|
|
@@ -3158,54 +2126,62 @@ function summarizeResponsesPayload(params) {
|
|
|
3158
2126
|
`store=${safeDebugValue(record.store)}`,
|
|
3159
2127
|
`promptCacheKey=${record.prompt_cache_key === void 0 ? "absent" : "present"}`,
|
|
3160
2128
|
`metadataKeys=${record.metadata && typeof record.metadata === "object" ? Object.keys(record.metadata).toSorted().join(",") : "none"}`
|
|
3161
|
-
];
|
|
3162
|
-
|
|
3163
|
-
|
|
2129
|
+
].join(" ");
|
|
2130
|
+
}
|
|
2131
|
+
const ABORT_REASON_LABELS = /* @__PURE__ */ new Map([
|
|
2132
|
+
["LlmIdleTimeoutError", "idle_timeout"],
|
|
2133
|
+
["LlmNoProgressError", "no_progress"],
|
|
2134
|
+
["FirstStreamEventTimeoutError", "first_event_timeout"],
|
|
2135
|
+
["OPENCLAW_SESSION_WATCHDOG", "session_watchdog"],
|
|
2136
|
+
["degenerate_output", "degenerate_output"],
|
|
2137
|
+
["OPENCLAW_RESTART_ABORT", "restart"],
|
|
2138
|
+
["ERR_STALE_GATEWAY_LIFECYCLE", "restart"],
|
|
2139
|
+
["AGENT_RUN_SUPERSEDED_ABORT", "superseded"]
|
|
2140
|
+
]);
|
|
2141
|
+
function resolveOpenAITransportAbortReason(signal) {
|
|
2142
|
+
if (!signal?.aborted) return;
|
|
2143
|
+
const reason = isRecord(signal.reason) ? signal.reason : void 0;
|
|
2144
|
+
const defaultReason = reason?.name === "TimeoutError" ? "request_deadline" : "caller_abort";
|
|
2145
|
+
const reasonKey = reason?.code ?? reason?.name;
|
|
2146
|
+
return (typeof reasonKey === "string" ? ABORT_REASON_LABELS.get(reasonKey) : void 0) ?? defaultReason;
|
|
3164
2147
|
}
|
|
3165
2148
|
function summarizeOpenAITransportError(error, signal) {
|
|
3166
|
-
|
|
3167
|
-
const
|
|
3168
|
-
const
|
|
3169
|
-
|
|
3170
|
-
|
|
3171
|
-
|
|
3172
|
-
|
|
3173
|
-
|
|
3174
|
-
|
|
3175
|
-
|
|
3176
|
-
|
|
3177
|
-
|
|
2149
|
+
const record = isRecord(error) ? error : void 0;
|
|
2150
|
+
const cause = record?.cause && typeof record.cause === "object" ? record.cause : void 0;
|
|
2151
|
+
const parts = record ? Object.entries({
|
|
2152
|
+
name: readTransportDiagnosticLabel(record.name),
|
|
2153
|
+
status: readTransportDiagnosticLabel(record.status),
|
|
2154
|
+
code: readTransportDiagnosticLabel(record.code),
|
|
2155
|
+
type: readTransportDiagnosticLabel(record.type),
|
|
2156
|
+
causeName: readTransportDiagnosticLabel(cause?.name),
|
|
2157
|
+
causeCode: readTransportDiagnosticLabel(cause?.code)
|
|
2158
|
+
}).flatMap(([key, value]) => value === void 0 ? [] : [`${key}=${value}`]) : [`type=${typeof error}`];
|
|
2159
|
+
const abortReason = resolveOpenAITransportAbortReason(signal);
|
|
2160
|
+
if (abortReason) parts.push(`abortReason=${abortReason}`);
|
|
2161
|
+
return parts.join(" ");
|
|
2162
|
+
}
|
|
2163
|
+
/** Protocol-specific labels join the shared failure line; caller aborts keep their own diagnostic. */
|
|
2164
|
+
function observeResponsesTransportFailure(params) {
|
|
2165
|
+
const { error, model, output, signal, requestSignal } = params;
|
|
2166
|
+
if (error instanceof ResponsesStreamFailure && error.observation) logResponsesFailedNoDetails(error.observation);
|
|
2167
|
+
const incomplete = output.diagnostics?.find(({ type }) => type === "openai_responses_terminal")?.details?.incompleteReason;
|
|
2168
|
+
const incompleteReason = typeof incomplete === "string" ? incomplete : void 0;
|
|
3178
2169
|
if (signal?.aborted) {
|
|
3179
|
-
|
|
3180
|
-
|
|
3181
|
-
switch (reason?.code ?? reason?.name) {
|
|
3182
|
-
case "LlmIdleTimeoutError":
|
|
3183
|
-
abortReason = "idle_timeout";
|
|
3184
|
-
break;
|
|
3185
|
-
case "LlmNoProgressError":
|
|
3186
|
-
abortReason = "no_progress";
|
|
3187
|
-
break;
|
|
3188
|
-
case "FirstStreamEventTimeoutError":
|
|
3189
|
-
abortReason = "first_event_timeout";
|
|
3190
|
-
break;
|
|
3191
|
-
case "OPENCLAW_SESSION_WATCHDOG":
|
|
3192
|
-
abortReason = "session_watchdog";
|
|
3193
|
-
break;
|
|
3194
|
-
case "degenerate_output":
|
|
3195
|
-
abortReason = "degenerate_output";
|
|
3196
|
-
break;
|
|
3197
|
-
case "OPENCLAW_RESTART_ABORT":
|
|
3198
|
-
case "ERR_STALE_GATEWAY_LIFECYCLE":
|
|
3199
|
-
abortReason = "restart";
|
|
3200
|
-
break;
|
|
3201
|
-
case "AGENT_RUN_SUPERSEDED_ABORT": abortReason = "superseded";
|
|
3202
|
-
}
|
|
3203
|
-
parts.push(`abortReason=${abortReason}`);
|
|
2170
|
+
emitModelTransportError(log, "responses", () => `provider=${model.provider} api=${model.api} model=${model.id} ` + summarizeOpenAITransportError(error, requestSignal) + (incompleteReason ? ` incompleteReason=${incompleteReason}` : ""), signal);
|
|
2171
|
+
return;
|
|
3204
2172
|
}
|
|
3205
|
-
return
|
|
2173
|
+
return {
|
|
2174
|
+
abortReason: resolveOpenAITransportAbortReason(requestSignal),
|
|
2175
|
+
incompleteReason
|
|
2176
|
+
};
|
|
3206
2177
|
}
|
|
3207
2178
|
//#endregion
|
|
3208
2179
|
//#region packages/ai/src/transports/openai-responses-replay-internal.ts
|
|
2180
|
+
const PRELUDE_TYPES = /* @__PURE__ */ new Set([
|
|
2181
|
+
"response.created",
|
|
2182
|
+
"response.in_progress",
|
|
2183
|
+
"response.queued"
|
|
2184
|
+
]);
|
|
3209
2185
|
function isAsyncIterable(value) {
|
|
3210
2186
|
return (typeof value === "object" && value !== null || typeof value === "function") && Symbol.asyncIterator in value;
|
|
3211
2187
|
}
|
|
@@ -3215,11 +2191,7 @@ function readResponsesRecoveryEvent(event) {
|
|
|
3215
2191
|
return {
|
|
3216
2192
|
failure: record?.type === "response.failed" ? response?.error : record?.type === "error" ? record.error ?? record : void 0,
|
|
3217
2193
|
hasResponseOutput: Array.isArray(response?.output) && response.output.length > 0,
|
|
3218
|
-
isPrelude: record !== void 0 &&
|
|
3219
|
-
"response.created",
|
|
3220
|
-
"response.in_progress",
|
|
3221
|
-
"response.queued"
|
|
3222
|
-
].includes(String(record.type))
|
|
2194
|
+
isPrelude: record !== void 0 && PRELUDE_TYPES.has(String(record.type))
|
|
3223
2195
|
};
|
|
3224
2196
|
}
|
|
3225
2197
|
function isInvalidEncryptedContentError(error) {
|
|
@@ -3271,9 +2243,8 @@ async function resolveNextResponsesEncryptedContentAttempt(attempt, error, optio
|
|
|
3271
2243
|
request: reasoningStripped
|
|
3272
2244
|
};
|
|
3273
2245
|
}
|
|
3274
|
-
|
|
3275
|
-
|
|
3276
|
-
let compactionStripped = options?.buildFullHistoryRequest ? await options.buildFullHistoryRequest() : locallyStripped;
|
|
2246
|
+
if (stripResponsesRequestCompaction(attempt.request) === attempt.request) return;
|
|
2247
|
+
let compactionStripped = await options.buildFullHistoryRequest();
|
|
3277
2248
|
compactionStripped = stripResponsesRequestCompaction(compactionStripped);
|
|
3278
2249
|
if (attempt.kind === "reasoning-stripped") compactionStripped = stripResponsesRequestEncryptedReasoning(compactionStripped);
|
|
3279
2250
|
return {
|
|
@@ -3286,20 +2257,59 @@ async function createResponsesStreamWithRecovery(params) {
|
|
|
3286
2257
|
async function* streamWithTerminalDrain(response, body) {
|
|
3287
2258
|
const reader = body.getReader();
|
|
3288
2259
|
let terminal = false;
|
|
2260
|
+
let firstFrame = true;
|
|
2261
|
+
const decoder = decodeSseFrames();
|
|
3289
2262
|
try {
|
|
3290
|
-
|
|
3291
|
-
|
|
3292
|
-
|
|
3293
|
-
|
|
3294
|
-
|
|
3295
|
-
}
|
|
3296
|
-
|
|
3297
|
-
|
|
3298
|
-
|
|
3299
|
-
|
|
3300
|
-
|
|
3301
|
-
|
|
2263
|
+
frames: for (let next = decoder.next(); !next.done;) {
|
|
2264
|
+
if (next.value === void 0) {
|
|
2265
|
+
next = decoder.next(await reader.read());
|
|
2266
|
+
continue;
|
|
2267
|
+
}
|
|
2268
|
+
const { frame } = next.value;
|
|
2269
|
+
let eventName = null;
|
|
2270
|
+
let data;
|
|
2271
|
+
let start = 0;
|
|
2272
|
+
let cr = frame.indexOf("\r");
|
|
2273
|
+
let lf = frame.indexOf("\n");
|
|
2274
|
+
while (start < frame.length) {
|
|
2275
|
+
const end = cr < 0 ? lf < 0 ? frame.length : lf : lf < 0 ? cr : Math.min(cr, lf);
|
|
2276
|
+
const lineStart = !(firstFrame && start === 0) && frame.charCodeAt(start) === 65279 ? start + 1 : start;
|
|
2277
|
+
start = end + (frame[end] === "\r" && frame[end + 1] === "\n" ? 2 : 1);
|
|
2278
|
+
if (cr >= 0 && cr < start) cr = frame.indexOf("\r", start);
|
|
2279
|
+
if (lf >= 0 && lf < start) lf = frame.indexOf("\n", start);
|
|
2280
|
+
if (lineStart < end) {
|
|
2281
|
+
const fieldLength = frame.startsWith("data", lineStart) ? 4 : frame.startsWith("event", lineStart) ? 5 : 0;
|
|
2282
|
+
const colon = lineStart + fieldLength;
|
|
2283
|
+
if (fieldLength && (colon === end || frame[colon] === ":")) {
|
|
2284
|
+
const value = colon === end ? "" : frame.slice(colon + (frame[colon + 1] === " " ? 2 : 1), end);
|
|
2285
|
+
if (fieldLength === 5) eventName = value;
|
|
2286
|
+
else data = data === void 0 ? value : `${data}\n${value}`;
|
|
2287
|
+
}
|
|
2288
|
+
if (start < frame.length) continue;
|
|
2289
|
+
}
|
|
2290
|
+
if (!eventName && data === void 0) continue;
|
|
2291
|
+
if (data === "[DONE]") break frames;
|
|
2292
|
+
let event;
|
|
2293
|
+
try {
|
|
2294
|
+
event = JSON.parse(data ?? "");
|
|
2295
|
+
} catch {
|
|
2296
|
+
throw new SyntaxError("Error reading response: malformed server-sent event JSON.");
|
|
2297
|
+
}
|
|
2298
|
+
if (eventName?.startsWith("thread.")) event = {
|
|
2299
|
+
event: eventName,
|
|
2300
|
+
data: event
|
|
2301
|
+
};
|
|
2302
|
+
else if (eventName === "error" || isRecord(event) && event.error) throw new APIError(void 0, isRecord(event) ? event.error ?? event : event, void 0, response.headers);
|
|
2303
|
+
terminal ||= isRecord(event) && (event.type === "response.completed" || event.type === "response.incomplete");
|
|
2304
|
+
yield event;
|
|
2305
|
+
eventName = null;
|
|
2306
|
+
data = void 0;
|
|
2307
|
+
}
|
|
2308
|
+
firstFrame = false;
|
|
2309
|
+
next = decoder.next();
|
|
3302
2310
|
}
|
|
2311
|
+
} catch (error) {
|
|
2312
|
+
if (error instanceof APIError || !isRecord(error) || error.name !== "AbortError" && !String(error.message).includes("FetchRequestCanceledException")) throw error;
|
|
3303
2313
|
} finally {
|
|
3304
2314
|
if (!terminal) {
|
|
3305
2315
|
await reader.cancel().catch(() => void 0);
|
|
@@ -3395,7 +2405,7 @@ async function createResponsesStreamWithRecovery(params) {
|
|
|
3395
2405
|
} catch (error) {
|
|
3396
2406
|
let nextAttempt = (!responseAccepted ? recoverServiceTier(attempt, error) : void 0) ?? await resolveNextResponsesEncryptedContentAttempt(attempt, error, { buildFullHistoryRequest: params.buildFullHistoryRequest });
|
|
3397
2407
|
if (!nextAttempt && attempt.request.previous_response_id && error && typeof error === "object" && typeof error.status === "number" && isPreviousResponseRejection(error)) {
|
|
3398
|
-
const request = { ...
|
|
2408
|
+
const request = { ...await params.buildFullHistoryRequest() };
|
|
3399
2409
|
delete request.previous_response_id;
|
|
3400
2410
|
nextAttempt = {
|
|
3401
2411
|
kind: "continuation-rejected",
|
|
@@ -3469,6 +2479,81 @@ function resolveAzureOpenAIApiVersion(env = process.env) {
|
|
|
3469
2479
|
return env.AZURE_OPENAI_API_VERSION?.trim() || "preview";
|
|
3470
2480
|
}
|
|
3471
2481
|
//#endregion
|
|
2482
|
+
//#region packages/ai/src/providers/openai-responses-message-text.ts
|
|
2483
|
+
/** Keep provider prose separate from source formatting so terminal annotations can extend it. */
|
|
2484
|
+
function renderResponsesMessageText(content) {
|
|
2485
|
+
const citations = /* @__PURE__ */ new Map();
|
|
2486
|
+
return extendResponsesMessageText({
|
|
2487
|
+
prose: content.map((part) => {
|
|
2488
|
+
if (!isRecord(part)) return "";
|
|
2489
|
+
if (part.type !== "output_text" && part.type !== "text") return typeof part.refusal === "string" ? part.refusal : "";
|
|
2490
|
+
for (const annotation of Array.isArray(part.annotations) ? part.annotations : []) {
|
|
2491
|
+
if (!isRecord(annotation) || annotation.type !== "url_citation" || typeof annotation.url !== "string") continue;
|
|
2492
|
+
let url;
|
|
2493
|
+
try {
|
|
2494
|
+
url = new URL(annotation.url);
|
|
2495
|
+
} catch {
|
|
2496
|
+
continue;
|
|
2497
|
+
}
|
|
2498
|
+
if (url.protocol !== "https:" && url.protocol !== "http:" || citations.has(url.href)) continue;
|
|
2499
|
+
const title = (typeof annotation.title === "string" && annotation.title.trim() ? annotation.title : url.hostname).replace(/\s+/gu, " ").replace(/[!-/:-@[-`{-~]/g, "\\$&");
|
|
2500
|
+
const href = url.href.replace(/[()<>\\\s]/gu, (character) => "%" + character.charCodeAt(0).toString(16).toUpperCase());
|
|
2501
|
+
citations.set(url.href, "[" + title + "](" + href + ")");
|
|
2502
|
+
}
|
|
2503
|
+
return typeof part.text === "string" ? part.text : "";
|
|
2504
|
+
}).join(""),
|
|
2505
|
+
citations
|
|
2506
|
+
});
|
|
2507
|
+
}
|
|
2508
|
+
/** The visible source links after provider prose; replay must strip them. */
|
|
2509
|
+
function responsesMessageSources(text) {
|
|
2510
|
+
return text.text.length > text.prose.length ? text.text.slice(text.prose.length) : void 0;
|
|
2511
|
+
}
|
|
2512
|
+
/**
|
|
2513
|
+
* V1 text signature for a rendered Responses message. `sources` names the rendered link suffix
|
|
2514
|
+
* so replay sends the provider's own text. It stays Responses-internal, not in the shared encoder.
|
|
2515
|
+
*/
|
|
2516
|
+
function responsesTextSignature(id, phase, text) {
|
|
2517
|
+
const sources = responsesMessageSources(text);
|
|
2518
|
+
return JSON.stringify({
|
|
2519
|
+
v: 1,
|
|
2520
|
+
id,
|
|
2521
|
+
...phase ? { phase } : {},
|
|
2522
|
+
...sources ? { sources } : {}
|
|
2523
|
+
});
|
|
2524
|
+
}
|
|
2525
|
+
/** Point a kept V1 signature at the current source suffix; other signatures carry none. */
|
|
2526
|
+
function withResponsesTextSources(signature, text) {
|
|
2527
|
+
if (!signature?.startsWith("{")) return signature;
|
|
2528
|
+
try {
|
|
2529
|
+
const parsed = JSON.parse(signature);
|
|
2530
|
+
if (!parsed || typeof parsed !== "object" || !("v" in parsed) || parsed.v !== 1) return signature;
|
|
2531
|
+
const sources = responsesMessageSources(text);
|
|
2532
|
+
const rest = Object.fromEntries(Object.entries(parsed).filter(([key]) => key !== "sources"));
|
|
2533
|
+
return JSON.stringify({
|
|
2534
|
+
...rest,
|
|
2535
|
+
...sources ? { sources } : {}
|
|
2536
|
+
});
|
|
2537
|
+
} catch {
|
|
2538
|
+
return signature;
|
|
2539
|
+
}
|
|
2540
|
+
}
|
|
2541
|
+
/** Merge source state only after matching cumulative provider prose, never formatted links. */
|
|
2542
|
+
function extendResponsesMessageText(next, previous) {
|
|
2543
|
+
if (previous && !next.prose.startsWith(previous.prose)) return previous;
|
|
2544
|
+
let citations = next.citations;
|
|
2545
|
+
if (previous) {
|
|
2546
|
+
const combined = new Map(previous.citations);
|
|
2547
|
+
for (const [url, link] of next.citations) if (!combined.has(url)) combined.set(url, link);
|
|
2548
|
+
citations = combined;
|
|
2549
|
+
}
|
|
2550
|
+
return {
|
|
2551
|
+
prose: next.prose,
|
|
2552
|
+
citations,
|
|
2553
|
+
text: citations.size > 0 ? next.prose + "\n\n" + [...citations.values()].join(" ") : next.prose
|
|
2554
|
+
};
|
|
2555
|
+
}
|
|
2556
|
+
//#endregion
|
|
3472
2557
|
//#region packages/ai/src/providers/openai-responses-stream-compat.ts
|
|
3473
2558
|
const OPENAI_RESPONSES_OUTPUT_TEXT_CONTENT_PART_TYPE = "output_text";
|
|
3474
2559
|
const AZURE_RESPONSES_TEXT_CONTENT_PART_TYPE = "text";
|
|
@@ -3497,6 +2582,7 @@ function resolveResponsesMessageSnapshotCollapse(params) {
|
|
|
3497
2582
|
}
|
|
3498
2583
|
//#endregion
|
|
3499
2584
|
//#region packages/ai/src/transports/openai-responses-stream-slots-internal.ts
|
|
2585
|
+
const RESPONSES_BOOKKEEPING_TIMEOUT_MS = 9e5;
|
|
3500
2586
|
function createResponsesOutputTracker(params) {
|
|
3501
2587
|
const outputs = /* @__PURE__ */ new Map();
|
|
3502
2588
|
let currentEventType = "unknown";
|
|
@@ -3508,10 +2594,15 @@ function createResponsesOutputTracker(params) {
|
|
|
3508
2594
|
const callId = item.call_id ?? item.id;
|
|
3509
2595
|
return item.type === "function_call" && callId ? `function_call:${callId}` : void 0;
|
|
3510
2596
|
};
|
|
3511
|
-
const
|
|
2597
|
+
const peek = (item, outputIndex) => {
|
|
3512
2598
|
const key = identity(item);
|
|
3513
2599
|
const output = (outputIndex === void 0 ? void 0 : outputs.get(outputIndex)) ?? (key === void 0 ? void 0 : outputs.get(key));
|
|
3514
2600
|
if (!output || outputIndex !== void 0 && output.outputIndex !== void 0 && output.outputIndex !== outputIndex) return;
|
|
2601
|
+
return output;
|
|
2602
|
+
};
|
|
2603
|
+
const get = (item, outputIndex) => {
|
|
2604
|
+
const output = peek(item, outputIndex);
|
|
2605
|
+
if (!output) return;
|
|
3515
2606
|
if (output.type !== item.type || output.callId && item.call_id && output.callId !== item.call_id) throw new ResponsesOutputIdentityError({
|
|
3516
2607
|
outputIndex,
|
|
3517
2608
|
expectedType: output.type,
|
|
@@ -3530,7 +2621,7 @@ function createResponsesOutputTracker(params) {
|
|
|
3530
2621
|
sink.push(detachPartialSnapshot(event));
|
|
3531
2622
|
} };
|
|
3532
2623
|
},
|
|
3533
|
-
observeEvent(event) {
|
|
2624
|
+
observeEvent(event, outputSlots) {
|
|
3534
2625
|
currentEventType = event.type;
|
|
3535
2626
|
terminalAllowsRetry = false;
|
|
3536
2627
|
if (event.type === "response.output_item.added" || event.type === "response.output_item.done") providerToolObserved ||= isResponsesProviderTool(event.item);
|
|
@@ -3542,9 +2633,15 @@ function createResponsesOutputTracker(params) {
|
|
|
3542
2633
|
}
|
|
3543
2634
|
terminalAllowsRetry = event.type === "response.completed" && event.response.status === "completed" && event.response.error == null && event.response.incomplete_details == null && !terminalHasRefusal;
|
|
3544
2635
|
}
|
|
2636
|
+
if (event.type.endsWith(".delta") && "delta" in event) return typeof event.delta === "string" && event.delta.length > 0;
|
|
2637
|
+
if ((event.type === "response.output_item.added" || event.type === "response.output_item.done") && (event.item.type === "reasoning" || event.item.type === "message" || event.item.type === "function_call")) {
|
|
2638
|
+
const previous = peek(event.item, readResponsesOutputIndex(event));
|
|
2639
|
+
return event.type === "response.output_item.added" ? previous === void 0 && !outputSlots.resolveOutputItem(event, event.item) : previous?.completed !== true;
|
|
2640
|
+
}
|
|
2641
|
+
return isResponsesTerminalEventType(event.type);
|
|
3545
2642
|
},
|
|
3546
2643
|
get,
|
|
3547
|
-
set(item, contentIndex, outputIndex, completed = false) {
|
|
2644
|
+
set(item, contentIndex, outputIndex, completed = false, completedProse) {
|
|
3548
2645
|
const output = get(item, outputIndex) ?? {
|
|
3549
2646
|
type: item.type,
|
|
3550
2647
|
contentIndex,
|
|
@@ -3554,6 +2651,7 @@ function createResponsesOutputTracker(params) {
|
|
|
3554
2651
|
contentIndex,
|
|
3555
2652
|
completed
|
|
3556
2653
|
});
|
|
2654
|
+
if (completedProse !== void 0) output.completedProse = completedProse;
|
|
3557
2655
|
if (item.call_id) output.callId = item.call_id;
|
|
3558
2656
|
if (outputIndex !== void 0) {
|
|
3559
2657
|
output.outputIndex = outputIndex;
|
|
@@ -3567,7 +2665,7 @@ function createResponsesOutputTracker(params) {
|
|
|
3567
2665
|
function appendResponsesPendingTextDelta(slot, delta, materialize) {
|
|
3568
2666
|
const offset = slot.pendingText?.length ?? 0;
|
|
3569
2667
|
slot.pendingText = `${slot.pendingText ?? ""}${delta}`;
|
|
3570
|
-
const priorText = slot.collapseCandidate?.
|
|
2668
|
+
const priorText = slot.collapseCandidate?.rendered.prose ?? "";
|
|
3571
2669
|
if (offset >= priorText.length || priorText.startsWith(delta.slice(0, priorText.length - offset), offset)) return;
|
|
3572
2670
|
materialize(slot);
|
|
3573
2671
|
}
|
|
@@ -3612,9 +2710,6 @@ function createResponsesOutputSlotTracker() {
|
|
|
3612
2710
|
}
|
|
3613
2711
|
//#endregion
|
|
3614
2712
|
//#region packages/ai/src/providers/openai-responses-tool-call-tracker.ts
|
|
3615
|
-
function readEventIdentity(event) {
|
|
3616
|
-
return { itemId: normalizeOptionalString(event.item_id) };
|
|
3617
|
-
}
|
|
3618
2713
|
function readResponsesToolCallItemIdentity(item) {
|
|
3619
2714
|
return {
|
|
3620
2715
|
itemId: normalizeOptionalString(item.id),
|
|
@@ -3650,7 +2745,7 @@ function createResponsesToolCallTracker() {
|
|
|
3650
2745
|
state.outputIndex = outputIndex;
|
|
3651
2746
|
indexedCalls.set(outputIndex, state);
|
|
3652
2747
|
},
|
|
3653
|
-
resolve(event, identity =
|
|
2748
|
+
resolve(event, identity = { itemId: normalizeOptionalString(event.item_id) }, allowUnmatchedIdentity = true) {
|
|
3654
2749
|
const outputIndex = readResponsesOutputIndex(event);
|
|
3655
2750
|
if (outputIndex !== void 0) {
|
|
3656
2751
|
const indexed = indexedCalls.get(outputIndex);
|
|
@@ -3697,17 +2792,19 @@ const STRING_DELTA_EVENTS = /* @__PURE__ */ new Set([
|
|
|
3697
2792
|
"response.refusal.delta",
|
|
3698
2793
|
"response.text.delta"
|
|
3699
2794
|
]);
|
|
3700
|
-
|
|
3701
|
-
|
|
3702
|
-
|
|
3703
|
-
|
|
3704
|
-
|
|
3705
|
-
|
|
3706
|
-
|
|
3707
|
-
}
|
|
3708
|
-
}
|
|
3709
|
-
|
|
3710
|
-
|
|
2795
|
+
function adaptResponsesStreamEvent(rawEvent) {
|
|
2796
|
+
const event = isRecord(rawEvent) && rawEvent.type === void 0 && rawEvent.object === "response" && typeof rawEvent.status === "string" && isResponsesTerminalEventType("response." + rawEvent.status) ? {
|
|
2797
|
+
type: "response." + rawEvent.status,
|
|
2798
|
+
response: rawEvent
|
|
2799
|
+
} : rawEvent;
|
|
2800
|
+
if (!isRecord(event) || typeof event.type !== "string") throw new Error("Responses stream delivered a malformed event without a string type");
|
|
2801
|
+
if (STRING_DELTA_EVENTS.has(event.type) && typeof event.delta !== "string") throw new Error(`Responses stream delivered malformed ${event.type} delta`);
|
|
2802
|
+
if ((event.type === "response.output_item.added" || event.type === "response.output_item.done") && !isRecord(event.item)) throw new Error(`Responses stream delivered malformed ${event.type} item`);
|
|
2803
|
+
if ((event.type === "response.created" || isResponsesTerminalEventType(event.type)) && !isRecord(event.response)) throw new Error(`Responses stream delivered malformed ${event.type} response`);
|
|
2804
|
+
return event;
|
|
2805
|
+
}
|
|
2806
|
+
function observeResponsesStream(stream, model, requestStartedAt, request, transport = "sse") {
|
|
2807
|
+
let startedAt = 0;
|
|
3711
2808
|
const eventTypes = /* @__PURE__ */ new Map();
|
|
3712
2809
|
let eventCount = 0;
|
|
3713
2810
|
let responseId;
|
|
@@ -3716,10 +2813,14 @@ async function* observeResponsesStream(stream, model, requestStartedAt, request,
|
|
|
3716
2813
|
let reasoningTokens;
|
|
3717
2814
|
let terminalType;
|
|
3718
2815
|
let incompleteReason;
|
|
3719
|
-
const requestDetails = `transport=${transport} requestedTier=${request?.service_tier ?? "unspecified"} max_output_tokens=${request?.max_output_tokens ?? "provider-default"}`;
|
|
3720
|
-
|
|
3721
|
-
|
|
3722
|
-
|
|
2816
|
+
const requestDetails = () => `transport=${transport} requestedTier=${request?.service_tier ?? "unspecified"} max_output_tokens=${request?.max_output_tokens ?? "provider-default"}`;
|
|
2817
|
+
return observeAsyncIterator({
|
|
2818
|
+
iterator: () => stream[Symbol.asyncIterator](),
|
|
2819
|
+
onStart() {
|
|
2820
|
+
startedAt = Date.now();
|
|
2821
|
+
emitModelTransportDebug(log, () => `[responses] stream_start provider=${model.provider} api=${model.api} model=${model.id} ${requestDetails()}`);
|
|
2822
|
+
},
|
|
2823
|
+
onEvent(event) {
|
|
3723
2824
|
const record = isRecord(event) ? event : void 0;
|
|
3724
2825
|
const type = typeof record?.type === "string" ? record.type : "unknown";
|
|
3725
2826
|
const response = isRecord(record?.response) ? record.response : void 0;
|
|
@@ -3730,20 +2831,19 @@ async function* observeResponsesStream(stream, model, requestStartedAt, request,
|
|
|
3730
2831
|
const details = response.usage.output_tokens_details;
|
|
3731
2832
|
if (isRecord(details) && typeof details.reasoning_tokens === "number") reasoningTokens = details.reasoning_tokens;
|
|
3732
2833
|
}
|
|
3733
|
-
if (type
|
|
2834
|
+
if (isResponsesTerminalEventType(type)) {
|
|
3734
2835
|
terminalType = type;
|
|
3735
2836
|
const details = response?.incomplete_details;
|
|
3736
2837
|
if (isRecord(details) && typeof details.reason === "string") incompleteReason = details.reason;
|
|
3737
2838
|
}
|
|
3738
2839
|
eventCount += 1;
|
|
3739
2840
|
eventTypes.set(type, (eventTypes.get(type) ?? 0) + 1);
|
|
3740
|
-
if (eventCount === 1) emitModelTransportDebug(log, `[responses] first_event provider=${model.provider} api=${model.api} model=${model.id} elapsedMs=${Date.now() - (requestStartedAt ?? startedAt)} headersToEventMs=${Date.now() - startedAt} type=${type} responseId=${responseId ?? "unknown"}`);
|
|
3741
|
-
|
|
2841
|
+
if (eventCount === 1) emitModelTransportDebug(log, () => `[responses] first_event provider=${model.provider} api=${model.api} model=${model.id} elapsedMs=${Date.now() - (requestStartedAt ?? startedAt)} headersToEventMs=${Date.now() - startedAt} type=${type} responseId=${responseId ?? "unknown"}`);
|
|
2842
|
+
},
|
|
2843
|
+
onFinally() {
|
|
2844
|
+
emitModelTransportDebug(log, () => `[responses] stream_done provider=${model.provider} api=${model.api} model=${model.id} ${requestDetails()} responseId=${responseId ?? "unknown"} servedTier=${servedTier ?? "unknown"} outputTokens=${outputTokens ?? "unknown"} reasoningTokens=${reasoningTokens ?? "unknown"} streamDurationMs=${Date.now() - startedAt} elapsedMs=${Date.now() - (requestStartedAt ?? startedAt)} terminal=${terminalType ?? "none"} incompleteReason=${incompleteReason ?? "none"} events=${eventCount} types=${[...eventTypes].map(([type, count]) => `${type}:${count}`).join(",")}`);
|
|
3742
2845
|
}
|
|
3743
|
-
}
|
|
3744
|
-
const types = [...eventTypes].map(([type, count]) => `${type}:${count}`).join(",");
|
|
3745
|
-
emitModelTransportDebug(log, `[responses] stream_done provider=${model.provider} api=${model.api} model=${model.id} ${requestDetails} responseId=${responseId ?? "unknown"} servedTier=${servedTier ?? "unknown"} outputTokens=${outputTokens ?? "unknown"} reasoningTokens=${reasoningTokens ?? "unknown"} streamDurationMs=${Date.now() - startedAt} elapsedMs=${Date.now() - (requestStartedAt ?? startedAt)} terminal=${terminalType ?? "none"} incompleteReason=${incompleteReason ?? "none"} events=${eventCount} types=${types}`);
|
|
3746
|
-
}
|
|
2846
|
+
});
|
|
3747
2847
|
}
|
|
3748
2848
|
//#endregion
|
|
3749
2849
|
//#region packages/ai/src/transports/openai-responses-stream-terminal-internal.ts
|
|
@@ -3775,6 +2875,10 @@ function createResponsesTerminalController(params) {
|
|
|
3775
2875
|
const { output, stream, model, options } = params;
|
|
3776
2876
|
const blocks = output.content;
|
|
3777
2877
|
const pendingReasoning = /* @__PURE__ */ new Set();
|
|
2878
|
+
const completedText = /* @__PURE__ */ new Map();
|
|
2879
|
+
const recordCompletedText = (index, text) => {
|
|
2880
|
+
completedText.set(index, text);
|
|
2881
|
+
};
|
|
3778
2882
|
const deferredToolCompletions = [];
|
|
3779
2883
|
const recordPendingReasoning = (contentIndex) => {
|
|
3780
2884
|
pendingReasoning.add(contentIndex);
|
|
@@ -3798,12 +2902,10 @@ function createResponsesTerminalController(params) {
|
|
|
3798
2902
|
if (item.encrypted_content && options?.reasoningReplayMetadata) Object.assign(block, { [OPENAI_RESPONSES_REASONING_REPLAY_BLOCK_META_KEY]: options.reasoningReplayMetadata });
|
|
3799
2903
|
}
|
|
3800
2904
|
};
|
|
3801
|
-
const appendText = (item, initialIndex) => {
|
|
2905
|
+
const appendText = (item, initialIndex, initialRender, preserveSignature = false) => {
|
|
2906
|
+
let rendered = initialRender;
|
|
3802
2907
|
let contentIndex = initialIndex;
|
|
3803
|
-
|
|
3804
|
-
const content = part;
|
|
3805
|
-
return content.type === "output_text" || content.type === "text" ? content.text ?? "" : content.refusal ?? "";
|
|
3806
|
-
}).join("");
|
|
2908
|
+
let text = rendered.text;
|
|
3807
2909
|
const block = contentIndex === void 0 ? void 0 : blocks[contentIndex];
|
|
3808
2910
|
const started = block?.type === "text" ? block : void 0;
|
|
3809
2911
|
if (!text && !started) return;
|
|
@@ -3811,11 +2913,12 @@ function createResponsesTerminalController(params) {
|
|
|
3811
2913
|
if (started && contentIndex !== void 0) {
|
|
3812
2914
|
const previousText = started.text;
|
|
3813
2915
|
started.text = text;
|
|
3814
|
-
started.textSignature =
|
|
2916
|
+
started.textSignature = preserveSignature ? withResponsesTextSources(started.textSignature, rendered) : responsesTextSignature(item.id, phase, rendered);
|
|
3815
2917
|
params.setLastTextBlock({
|
|
3816
2918
|
block: started,
|
|
3817
2919
|
index: contentIndex,
|
|
3818
|
-
phase
|
|
2920
|
+
phase,
|
|
2921
|
+
rendered
|
|
3819
2922
|
});
|
|
3820
2923
|
if (text.startsWith(previousText)) {
|
|
3821
2924
|
const delta = text.slice(previousText.length);
|
|
@@ -3827,30 +2930,33 @@ function createResponsesTerminalController(params) {
|
|
|
3827
2930
|
}
|
|
3828
2931
|
} else {
|
|
3829
2932
|
const previous = params.getLastTextBlock();
|
|
3830
|
-
|
|
2933
|
+
if (resolveResponsesMessageSnapshotCollapse({
|
|
3831
2934
|
prior: previous && {
|
|
3832
|
-
text: previous.
|
|
2935
|
+
text: previous.rendered.prose,
|
|
3833
2936
|
phase: previous.phase
|
|
3834
2937
|
},
|
|
3835
|
-
nextText:
|
|
2938
|
+
nextText: rendered.prose,
|
|
3836
2939
|
nextPhase: phase
|
|
3837
|
-
})
|
|
3838
|
-
|
|
3839
|
-
|
|
3840
|
-
previous.
|
|
2940
|
+
}).kind === "extend" && previous) {
|
|
2941
|
+
rendered = extendResponsesMessageText(rendered, previous.rendered);
|
|
2942
|
+
text = rendered.text;
|
|
2943
|
+
previous.rendered = rendered;
|
|
2944
|
+
previous.block.text = text;
|
|
2945
|
+
previous.block.textSignature = responsesTextSignature(item.id, phase, rendered);
|
|
3841
2946
|
contentIndex = previous.index;
|
|
3842
2947
|
} else {
|
|
3843
2948
|
const newBlock = {
|
|
3844
2949
|
type: "text",
|
|
3845
2950
|
text,
|
|
3846
|
-
textSignature:
|
|
2951
|
+
textSignature: responsesTextSignature(item.id, phase, rendered)
|
|
3847
2952
|
};
|
|
3848
2953
|
blocks.push(newBlock);
|
|
3849
2954
|
contentIndex = blocks.length - 1;
|
|
3850
2955
|
params.setLastTextBlock({
|
|
3851
2956
|
block: newBlock,
|
|
3852
2957
|
index: contentIndex,
|
|
3853
|
-
phase
|
|
2958
|
+
phase,
|
|
2959
|
+
rendered
|
|
3854
2960
|
});
|
|
3855
2961
|
stream.push({
|
|
3856
2962
|
type: "text_start",
|
|
@@ -3859,6 +2965,7 @@ function createResponsesTerminalController(params) {
|
|
|
3859
2965
|
});
|
|
3860
2966
|
}
|
|
3861
2967
|
}
|
|
2968
|
+
recordCompletedText(contentIndex, rendered);
|
|
3862
2969
|
stream.push({
|
|
3863
2970
|
type: "text_end",
|
|
3864
2971
|
contentIndex,
|
|
@@ -3919,9 +3026,27 @@ function createResponsesTerminalController(params) {
|
|
|
3919
3026
|
}
|
|
3920
3027
|
for (const [terminalIndex, item] of items.entries()) if (item.type === "message") {
|
|
3921
3028
|
const tracked = params.outputs.get(item, terminalIndex);
|
|
3922
|
-
if (tracked?.completed)
|
|
3923
|
-
|
|
3924
|
-
|
|
3029
|
+
if (tracked?.completed) {
|
|
3030
|
+
const block = blocks[tracked.contentIndex];
|
|
3031
|
+
const previous = completedText.get(tracked.contentIndex);
|
|
3032
|
+
if (block?.type === "text" && previous && tracked.completedProse !== void 0) {
|
|
3033
|
+
const incoming = renderResponsesMessageText(item.content ?? []);
|
|
3034
|
+
if (!incoming.prose.startsWith(tracked.completedProse)) continue;
|
|
3035
|
+
const rendered = extendResponsesMessageText({
|
|
3036
|
+
prose: previous.prose.startsWith(incoming.prose) ? previous.prose : incoming.prose,
|
|
3037
|
+
citations: incoming.citations
|
|
3038
|
+
}, previous);
|
|
3039
|
+
if (rendered.text !== block.text) {
|
|
3040
|
+
const cursor = params.getLastTextBlock();
|
|
3041
|
+
appendText(item, tracked.contentIndex, rendered, tracked.completedProse !== previous.prose);
|
|
3042
|
+
if (cursor?.index !== tracked.contentIndex) params.setLastTextBlock(cursor);
|
|
3043
|
+
}
|
|
3044
|
+
}
|
|
3045
|
+
continue;
|
|
3046
|
+
}
|
|
3047
|
+
const rendered = renderResponsesMessageText(item.content ?? []);
|
|
3048
|
+
const appendedIndex = appendText(item, tracked?.contentIndex, rendered);
|
|
3049
|
+
if (appendedIndex !== void 0) params.outputs.set(item, appendedIndex, terminalIndex, true, rendered.prose);
|
|
3925
3050
|
} else {
|
|
3926
3051
|
params.setLastTextBlock(null);
|
|
3927
3052
|
const alreadyCapturedCompaction = item.type === "compaction" && output.providerReplay?.type === "openai-responses-compaction" && output.providerReplay.id === item.id && output.providerReplay.data === item.encrypted_content;
|
|
@@ -3944,6 +3069,9 @@ function createResponsesTerminalController(params) {
|
|
|
3944
3069
|
};
|
|
3945
3070
|
const finalizeTerminalFacts = (response, responseId = response.id) => {
|
|
3946
3071
|
options?.onServiceTier?.(response.service_tier, response);
|
|
3072
|
+
const cyber = asOptionalRecord(asOptionalRecord(response)?.access_programs)?.cyber;
|
|
3073
|
+
if (cyber === null || cyber === "standard" || cyber === "daybreak_blue" || cyber === "daybreak_red") output.responseAccessProgram = cyber;
|
|
3074
|
+
else delete output.responseAccessProgram;
|
|
3947
3075
|
output.responseId = responseId || output.responseId;
|
|
3948
3076
|
output.responseModel = options?.resolveResponseModel ? options.resolveResponseModel()?.trim() || void 0 : response.model?.trim() || void 0;
|
|
3949
3077
|
const usage = mapResponsesTerminalUsage(response.usage);
|
|
@@ -3962,6 +3090,7 @@ function createResponsesTerminalController(params) {
|
|
|
3962
3090
|
};
|
|
3963
3091
|
else output.usage.usageReport = { state: "unavailable" };
|
|
3964
3092
|
calculateCost(model, output.usage);
|
|
3093
|
+
applyResponsesCacheWritePricing(output.usage, response.usage, options?.promptCacheTtl);
|
|
3965
3094
|
if (options?.applyServiceTierPricing) {
|
|
3966
3095
|
const tier = options.resolveServiceTier ? options.resolveServiceTier(response.service_tier, options.serviceTier) : response.service_tier ?? options.serviceTier;
|
|
3967
3096
|
options.applyServiceTierPricing(output.usage, tier);
|
|
@@ -4001,6 +3130,7 @@ function createResponsesTerminalController(params) {
|
|
|
4001
3130
|
finalizeFailedResponse: finalizeTerminalFacts,
|
|
4002
3131
|
recordIncompleteToolCall,
|
|
4003
3132
|
recoverTerminalOutput,
|
|
3133
|
+
recordCompletedText,
|
|
4004
3134
|
emitToolCallCompletion,
|
|
4005
3135
|
recordPendingReasoning,
|
|
4006
3136
|
releaseDeferredToolCompletions
|
|
@@ -4089,15 +3219,6 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
4089
3219
|
const materializeDeferredTextSlots = (except) => {
|
|
4090
3220
|
for (const slot of outputSlots.values()) if (slot !== except && slot.type === "text") materializeDeferredTextSlot(slot);
|
|
4091
3221
|
};
|
|
4092
|
-
const appendThinkingDelta = (slot, delta) => {
|
|
4093
|
-
appendAssistantThinking(slot.block, delta);
|
|
4094
|
-
stream.push({
|
|
4095
|
-
type: "thinking_delta",
|
|
4096
|
-
contentIndex: slot.contentIndex,
|
|
4097
|
-
delta,
|
|
4098
|
-
partial: output
|
|
4099
|
-
});
|
|
4100
|
-
};
|
|
4101
3222
|
const projectTextDelta = (slot, delta) => {
|
|
4102
3223
|
if (slot.pendingText !== null) appendResponsesPendingTextDelta(slot, delta, materializeDeferredTextSlot);
|
|
4103
3224
|
else if (slot.block && slot.contentIndex !== void 0) {
|
|
@@ -4165,7 +3286,7 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
4165
3286
|
complete();
|
|
4166
3287
|
};
|
|
4167
3288
|
};
|
|
4168
|
-
const guardedStream =
|
|
3289
|
+
const guardedStream = iterateModelStream(withFirstStreamEventTimeout(openaiStream, {
|
|
4169
3290
|
provider: model.provider,
|
|
4170
3291
|
api: model.api,
|
|
4171
3292
|
model: model.id,
|
|
@@ -4176,16 +3297,16 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
4176
3297
|
hint: "The provider may be stalled while parsing the tool payload; retry with a smaller tool surface or enable OPENCLAW_DEBUG_MODEL_PAYLOAD=tools to inspect exposed tools."
|
|
4177
3298
|
}), options?.signal);
|
|
4178
3299
|
try {
|
|
4179
|
-
for await (const
|
|
4180
|
-
|
|
4181
|
-
notifyLlmRequestActivity(options?.signal);
|
|
3300
|
+
for await (const rawEvent of guardedStream) {
|
|
3301
|
+
const event = adaptResponsesStreamEvent(rawEvent);
|
|
3302
|
+
notifyLlmRequestActivity(options?.signal, outputs.observeEvent(event, outputSlots), RESPONSES_BOOKKEEPING_TIMEOUT_MS);
|
|
4182
3303
|
if (event.type === "response.output_item.done" && event.item.type === "function_call" && event.item.status && event.item.status !== "completed" && !rejectedToolCall) try {
|
|
4183
3304
|
resolveCompletedResponsesToolCall(event.item);
|
|
4184
3305
|
} catch (error) {
|
|
4185
3306
|
terminal.recordIncompleteToolCall(event, event.item);
|
|
4186
3307
|
rejectedToolCall = { error };
|
|
4187
3308
|
}
|
|
4188
|
-
if (rejectedToolCall && event.type
|
|
3309
|
+
if (rejectedToolCall && !isResponsesTerminalEventType(event.type) && event.type !== "error") continue;
|
|
4189
3310
|
if (event.type === "response.created") output.responseId = event.response.id;
|
|
4190
3311
|
else if (event.type === "response.output_item.added") {
|
|
4191
3312
|
materializeDeferredTextSlots();
|
|
@@ -4240,12 +3361,24 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
4240
3361
|
if (!lastPart) continue;
|
|
4241
3362
|
lastPart.text += delta;
|
|
4242
3363
|
}
|
|
4243
|
-
|
|
3364
|
+
appendAssistantThinking(slot.block, delta);
|
|
3365
|
+
stream.push({
|
|
3366
|
+
type: "thinking_delta",
|
|
3367
|
+
contentIndex: slot.contentIndex,
|
|
3368
|
+
delta,
|
|
3369
|
+
partial: output
|
|
3370
|
+
});
|
|
4244
3371
|
} else if (event.type === "response.content_part.added") {
|
|
4245
3372
|
const slot = outputSlots.resolve(event, "text");
|
|
4246
3373
|
if (!slot) continue;
|
|
4247
3374
|
slot.item.content = slot.item.content || [];
|
|
4248
3375
|
if (event.part.type === "output_text" || event.part.type === "text" || event.part.type === "refusal") slot.item.content.push(event.part);
|
|
3376
|
+
} else if (event.type === "response.output_text.annotation.added") {
|
|
3377
|
+
const part = outputSlots.resolve(event, "text")?.item.content?.[event.content_index];
|
|
3378
|
+
if (part?.type === "output_text" && event.annotation !== null) {
|
|
3379
|
+
part.annotations ??= [];
|
|
3380
|
+
part.annotations.push(event.annotation);
|
|
3381
|
+
}
|
|
4249
3382
|
} else if (event.type === "response.output_text.delta" || isAzureResponsesTextDeltaEvent(event) || event.type === "response.refusal.delta") {
|
|
4250
3383
|
const slot = outputSlots.resolve(event, "text");
|
|
4251
3384
|
if (!slot) continue;
|
|
@@ -4330,28 +3463,34 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
4330
3463
|
outputSlots.forget(outputSlot);
|
|
4331
3464
|
} else if (item.type === "message" && outputSlot?.type === "text" && (outputSlot.block || outputSlot.pendingText !== null)) {
|
|
4332
3465
|
const streamedText = outputSlot.pendingText ?? outputSlot.block?.text ?? "";
|
|
4333
|
-
const
|
|
3466
|
+
const rendered = renderResponsesMessageText(item.content ?? outputSlot.item.content ?? [{
|
|
3467
|
+
type: "text",
|
|
3468
|
+
text: streamedText
|
|
3469
|
+
}]);
|
|
4334
3470
|
const phase = item.phase ?? void 0;
|
|
4335
3471
|
const collapse = outputSlot.pendingText !== null ? resolveResponsesMessageSnapshotCollapse({
|
|
4336
3472
|
prior: outputSlot.collapseCandidate && {
|
|
4337
|
-
text: outputSlot.collapseCandidate.
|
|
3473
|
+
text: outputSlot.collapseCandidate.rendered.prose,
|
|
4338
3474
|
phase: outputSlot.collapseCandidate.phase
|
|
4339
3475
|
},
|
|
4340
|
-
nextText:
|
|
3476
|
+
nextText: rendered.prose,
|
|
4341
3477
|
nextPhase: phase
|
|
4342
3478
|
}) : { kind: "keep" };
|
|
4343
3479
|
outputSlot.pendingText = null;
|
|
4344
3480
|
if (collapse.kind === "extend" && outputSlot.collapseCandidate) {
|
|
4345
|
-
outputSlot.collapseCandidate.
|
|
4346
|
-
outputSlot.collapseCandidate.
|
|
3481
|
+
const extended = extendResponsesMessageText(rendered, outputSlot.collapseCandidate.rendered);
|
|
3482
|
+
outputSlot.collapseCandidate.rendered = extended;
|
|
3483
|
+
outputSlot.collapseCandidate.block.text = extended.text;
|
|
3484
|
+
outputSlot.collapseCandidate.block.textSignature = responsesTextSignature(item.id, phase, extended);
|
|
4347
3485
|
stream.push({
|
|
4348
3486
|
type: "text_end",
|
|
4349
3487
|
contentIndex: outputSlot.collapseCandidate.index,
|
|
4350
|
-
content:
|
|
3488
|
+
content: extended.text,
|
|
4351
3489
|
partial: output
|
|
4352
3490
|
});
|
|
4353
3491
|
lastTextBlock = outputSlot.collapseCandidate;
|
|
4354
|
-
|
|
3492
|
+
terminal.recordCompletedText(outputSlot.collapseCandidate.index, extended);
|
|
3493
|
+
outputs.set(item, outputSlot.collapseCandidate.index, readResponsesOutputIndex(event) ?? outputSlot.outputIndex, true, rendered.prose);
|
|
4355
3494
|
} else {
|
|
4356
3495
|
if (!outputSlot.block) {
|
|
4357
3496
|
outputSlot.block = createTextBlock(item, "");
|
|
@@ -4363,16 +3502,18 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
4363
3502
|
partial: output
|
|
4364
3503
|
});
|
|
4365
3504
|
}
|
|
4366
|
-
outputSlot.block.text =
|
|
4367
|
-
outputSlot.block.textSignature =
|
|
3505
|
+
outputSlot.block.text = rendered.text;
|
|
3506
|
+
outputSlot.block.textSignature = responsesTextSignature(item.id, phase, rendered);
|
|
4368
3507
|
const contentIndex = outputSlot.contentIndex;
|
|
4369
3508
|
if (contentIndex === void 0) throw new Error("Responses stream finalized text without a content index");
|
|
4370
3509
|
lastTextBlock = {
|
|
4371
3510
|
block: outputSlot.block,
|
|
4372
3511
|
index: contentIndex,
|
|
4373
|
-
phase
|
|
3512
|
+
phase,
|
|
3513
|
+
rendered
|
|
4374
3514
|
};
|
|
4375
|
-
|
|
3515
|
+
terminal.recordCompletedText(contentIndex, rendered);
|
|
3516
|
+
outputs.set(item, contentIndex, readResponsesOutputIndex(event) ?? outputSlot.outputIndex, true, rendered.prose);
|
|
4376
3517
|
stream.push({
|
|
4377
3518
|
type: "text_end",
|
|
4378
3519
|
contentIndex,
|
|
@@ -4450,17 +3591,17 @@ function readOpenAIMisalignmentReview(value, continuationSupported) {
|
|
|
4450
3591
|
//#region packages/ai/src/providers/openai-responses-tools.ts
|
|
4451
3592
|
/** Projects direct provider descriptors before resolving their strict policy. */
|
|
4452
3593
|
function convertResponsesToolPayload(tools, options) {
|
|
4453
|
-
return convertPreparedResponsesTools(prepareOpenAITools(tools), resolveResponsesStrictToolSetting(options), options?.model);
|
|
3594
|
+
return convertPreparedResponsesTools(prepareOpenAITools(tools), resolveResponsesStrictToolSetting(options), options?.model, options?.mutableParameters);
|
|
4454
3595
|
}
|
|
4455
3596
|
/** The transport has already resolved policy before descriptor projection. */
|
|
4456
|
-
function prepareResponsesTools(tools, strictSetting, model) {
|
|
3597
|
+
function prepareResponsesTools(tools, strictSetting, model, mutableParameters) {
|
|
4457
3598
|
const prepared = prepareOpenAITools(tools);
|
|
4458
3599
|
return {
|
|
4459
3600
|
projection: prepared.projection,
|
|
4460
|
-
tools: convertPreparedResponsesTools(prepared, strictSetting, model)
|
|
3601
|
+
tools: convertPreparedResponsesTools(prepared, strictSetting, model, mutableParameters)
|
|
4461
3602
|
};
|
|
4462
3603
|
}
|
|
4463
|
-
function convertPreparedResponsesTools(prepared, strictSetting, model) {
|
|
3604
|
+
function convertPreparedResponsesTools(prepared, strictSetting, model, mutableParameters) {
|
|
4464
3605
|
const { projection, schemas } = prepared;
|
|
4465
3606
|
return withPreparedToolSchemaNormalization(schemas, () => {
|
|
4466
3607
|
const strict = model ? resolveOpenAIStrictToolFlagWithDiagnostics(projection, strictSetting, {
|
|
@@ -4468,7 +3609,7 @@ function convertPreparedResponsesTools(prepared, strictSetting, model) {
|
|
|
4468
3609
|
model
|
|
4469
3610
|
}) : resolveOpenAIProjectedToolsStrictToolFlag(projection, strictSetting);
|
|
4470
3611
|
return sortPromptCacheToolsByName(projection.tools).map((tool) => {
|
|
4471
|
-
return prepareOpenAIFunctionTool(tool.name, tool.description, normalizeOpenAIStrictToolParameters(tool.parameters, strict === true, model?.compat), strict).responses;
|
|
3612
|
+
return prepareOpenAIFunctionTool(tool.name, tool.description, normalizeOpenAIStrictToolParameters(tool.parameters, strict === true, model?.compat), strict, mutableParameters).responses;
|
|
4472
3613
|
});
|
|
4473
3614
|
});
|
|
4474
3615
|
}
|
|
@@ -4476,7 +3617,7 @@ function resolveResponsesStrictToolSetting(options) {
|
|
|
4476
3617
|
if (options?.strict !== void 0) return options.strict;
|
|
4477
3618
|
if (options?.model) return getAiTransportHost().resolveOpenAIStrictToolSetting(options.model, {
|
|
4478
3619
|
transport: "stream",
|
|
4479
|
-
supportsStrictMode:
|
|
3620
|
+
supportsStrictMode: resolveOpenAICompletionsCompat(options.model).supportsStrictMode
|
|
4480
3621
|
});
|
|
4481
3622
|
return false;
|
|
4482
3623
|
}
|
|
@@ -4501,7 +3642,10 @@ function applyCommonResponsesParams(params, model, context, options, config) {
|
|
|
4501
3642
|
format: resolveOpenAIResponsesTextFormat(options.responseFormat)
|
|
4502
3643
|
};
|
|
4503
3644
|
if (context.tools) {
|
|
4504
|
-
const tools = convertResponsesToolPayload(context.tools, {
|
|
3645
|
+
const tools = convertResponsesToolPayload(context.tools, {
|
|
3646
|
+
model,
|
|
3647
|
+
mutableParameters: Boolean(options?.onPayload)
|
|
3648
|
+
});
|
|
4505
3649
|
if (tools.length > 0) params.tools = tools;
|
|
4506
3650
|
}
|
|
4507
3651
|
if (!model.reasoning) return;
|
|
@@ -4509,17 +3653,11 @@ function applyCommonResponsesParams(params, model, context, options, config) {
|
|
|
4509
3653
|
const effort = requestedEffort === void 0 ? void 0 : resolveOpenAIRequestReasoning(model, requestedEffort).effort;
|
|
4510
3654
|
if (effort === void 0) return;
|
|
4511
3655
|
params.reasoning = { effort };
|
|
4512
|
-
if (effort !== "none" && (options?.reasoningEffort || options?.reasoningSummary)) {
|
|
4513
|
-
params.reasoning.summary = options?.reasoningSummary
|
|
3656
|
+
if (effort !== "none" && (options?.reasoningEffort || options?.reasoningSummary !== void 0)) {
|
|
3657
|
+
params.reasoning.summary = options?.reasoningSummary === void 0 ? "auto" : options.reasoningSummary;
|
|
4514
3658
|
params.include = ["reasoning.encrypted_content"];
|
|
4515
3659
|
}
|
|
4516
3660
|
}
|
|
4517
|
-
function cleanStreamingScratchBuffers(output) {
|
|
4518
|
-
for (const block of output.content) {
|
|
4519
|
-
delete block.index;
|
|
4520
|
-
if (block.type === "toolCall") delete block.partialJson;
|
|
4521
|
-
}
|
|
4522
|
-
}
|
|
4523
3661
|
async function runResponsesStreamLifecycle(params) {
|
|
4524
3662
|
const { stream, output, options } = params;
|
|
4525
3663
|
let firstEventAbort;
|
|
@@ -4531,6 +3669,12 @@ async function runResponsesStreamLifecycle(params) {
|
|
|
4531
3669
|
let request = params.buildParams(model, replayMode);
|
|
4532
3670
|
const nextRequest = await options?.onPayload?.(request, model);
|
|
4533
3671
|
if (nextRequest !== void 0) request = nextRequest;
|
|
3672
|
+
if (options?.openclawCodeModeToolSurface === true) {
|
|
3673
|
+
const visibleToolNames = resolveCodeModeResponsesVisibleToolNames(params.context ?? {});
|
|
3674
|
+
const allowedHostedToolTypes = options.openclawCodeModeAllowedHostedToolTypes;
|
|
3675
|
+
enforceCodeModeResponsesToolSurface(request, visibleToolNames, allowedHostedToolTypes, codeModeToolSurfaceObserver.get(options));
|
|
3676
|
+
assertCodeModeResponsesToolSurface(request, visibleToolNames, allowedHostedToolTypes);
|
|
3677
|
+
}
|
|
4534
3678
|
return request;
|
|
4535
3679
|
};
|
|
4536
3680
|
const requestParams = await buildRequest("checkpoint");
|
|
@@ -4575,19 +3719,16 @@ async function runResponsesStreamLifecycle(params) {
|
|
|
4575
3719
|
});
|
|
4576
3720
|
const firstEventTimeoutMs = getFirstStreamEventTimeoutMs(options);
|
|
4577
3721
|
const onFirstEventTimeout = getFirstStreamEventTimeoutHandler(options);
|
|
4578
|
-
const processStreamOptions = params.processStreamOptions || firstEventTimeoutMs !== void 0 || onFirstEventTimeout !== void 0 ? {
|
|
4579
|
-
...params.processStreamOptions,
|
|
4580
|
-
firstEventTimeoutMs: params.processStreamOptions?.firstEventTimeoutMs ?? firstEventTimeoutMs,
|
|
4581
|
-
abortFirstEventStream: params.processStreamOptions?.abortFirstEventStream ?? firstEventAbort.abort,
|
|
4582
|
-
onFirstEventTimeout: params.processStreamOptions?.onFirstEventTimeout ?? onFirstEventTimeout,
|
|
4583
|
-
signal: params.processStreamOptions?.signal ?? options?.signal
|
|
4584
|
-
} : void 0;
|
|
4585
3722
|
const terminal = await processResponsesStream(hookedOpenAIStream, output, stream, model, {
|
|
4586
|
-
...processStreamOptions
|
|
4587
|
-
|
|
4588
|
-
|
|
4589
|
-
|
|
4590
|
-
|
|
3723
|
+
...params.processStreamOptions || firstEventTimeoutMs !== void 0 || onFirstEventTimeout !== void 0 ? {
|
|
3724
|
+
...params.processStreamOptions,
|
|
3725
|
+
firstEventTimeoutMs,
|
|
3726
|
+
abortFirstEventStream: firstEventAbort.abort,
|
|
3727
|
+
onFirstEventTimeout,
|
|
3728
|
+
signal: options?.signal
|
|
3729
|
+
} : void 0,
|
|
3730
|
+
promptCacheTtl: requestParams.prompt_cache_options?.ttl,
|
|
3731
|
+
resolveServiceTier: (responseTier, originalTier) => responseTier ?? (requestedTier === "priority" || requestedTier === "default" ? requestedTier : originalTier),
|
|
4591
3732
|
onServiceTier: (responseTier, response) => responsesServiceTierObserver.observe(options, requestedTier, responseTier, response),
|
|
4592
3733
|
canRetryIdentityConflict: () => hasOnlyResponsesFunctionTools(admittedRequest),
|
|
4593
3734
|
reasoningReplayMetadata: buildOpenAIResponsesReasoningReplayMetadata(model, {
|
|
@@ -4620,12 +3761,11 @@ async function runResponsesStreamLifecycle(params) {
|
|
|
4620
3761
|
stream,
|
|
4621
3762
|
output,
|
|
4622
3763
|
signal: options?.signal,
|
|
4623
|
-
error
|
|
4624
|
-
cleanup: () => cleanStreamingScratchBuffers(output)
|
|
3764
|
+
error
|
|
4625
3765
|
});
|
|
4626
3766
|
} finally {
|
|
4627
3767
|
firstEventAbort?.dispose();
|
|
4628
3768
|
}
|
|
4629
3769
|
}
|
|
4630
3770
|
//#endregion
|
|
4631
|
-
export { isConfigurationUpdate as $,
|
|
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 };
|