@openclaw/ai 2026.10.10 → 2026.11.5-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -1
- package/dist/.source-module-urls/fe058cc430242ce2ab0dfbcbe153e240a52cf9c3072c3dc0a73e5f956b6ba49b.json +1 -0
- package/dist/anthropic-CTND83W3.mjs +182 -0
- package/dist/{anthropic-payload-policy-rqCq9sT_.d.mts → anthropic-payload-policy-CXCJ5Pmj.d.mts} +21 -4
- package/dist/{anthropic-stream-reducer-C__ByTq1.mjs → anthropic-stream-lifecycle-rJe4OH5H.mjs} +845 -649
- package/dist/{anthropic-tool-projection-JTvMo4KG.d.mts → anthropic-tool-projection-D5DyrL6C.d.mts} +6 -7
- package/dist/{anthropic-tool-projection-DA_KeluM.mjs → anthropic-tool-projection-dGRfr4iT.mjs} +22 -32
- package/dist/{api-registry-gDt0faai.d.mts → api-registry-DY2MLUyg.d.mts} +2 -2
- package/dist/assistant-output-CD4kY9gu.mjs +16 -0
- package/dist/{azure-openai-responses-DHzTwi-y.mjs → azure-openai-responses-BhoLtP4Z.mjs} +46 -52
- package/dist/{cloudflare-Dttf8jKq.mjs → cloudflare-BJ2_Xabx.mjs} +1 -1
- package/dist/{credential-redaction-XvsPf7Yi.d.mts → credential-redaction-DrgndwTJ.d.mts} +5 -3
- package/dist/{deferred-event-buffer-DAvyP7qA.mjs → deferred-event-buffer-tIGkTkTm.mjs} +1 -2
- package/dist/{diagnostics-Cv7cW3pS.mjs → diagnostics-CloVGQiK.mjs} +42 -19
- package/dist/{diagnostics-DzrF1h4J.mjs → diagnostics-o1PrVNQb.mjs} +11 -4
- package/dist/diagnostics.d.mts +6 -7
- package/dist/diagnostics.mjs +4 -4
- package/dist/{env-api-keys-Xd8dm_aV.mjs → env-api-keys-BuHc86ya.mjs} +1 -26
- package/dist/event-stream-B4ZcSvsu.d.mts +1 -0
- package/dist/{event-stream-CzpE1g_o.d.mts → event-stream-BYmtRe8-.d.mts} +1 -1
- package/dist/event-stream.d.mts +2 -2
- package/dist/event-stream.mjs +1 -2
- package/dist/expect-lbe3Hgrh.mjs +8 -0
- package/dist/{github-copilot-request-facts-F-EmvkpW.mjs → github-copilot-request-facts-BZ_EMo7X.mjs} +1 -1
- package/dist/{google-CZ6uGVkV.mjs → google-1uObh-eI.mjs} +7 -8
- package/dist/{google-interactions-qd4flmND.mjs → google-interactions-CY8Xb87S.mjs} +208 -233
- package/dist/{google-messages-B-svbJuN.mjs → google-messages-CwBqSoa4.mjs} +16 -13
- package/dist/{google-provider-stream-DlhaCvCf.mjs → google-provider-stream-D30s9EZp.mjs} +17 -10
- package/dist/{google-shared-Cif7nve-.mjs → google-shared-li0lmEZK.mjs} +70 -42
- package/dist/{google-vertex-BZTcYnWU.mjs → google-vertex-B5CHglca.mjs} +3 -3
- package/dist/{host-rCxf5Tjd.mjs → host-DX7ORpeH.mjs} +57 -46
- package/dist/{host-jJOffdlW.d.mts → host-ccbwPC3A.d.mts} +17 -9
- package/dist/{host-policy-Ci1cKluf.mjs → host-policy-jCZebuXx.mjs} +2 -2
- package/dist/index-Bczt0MnO.d.mts +17 -0
- package/dist/index.d.mts +8 -7
- package/dist/index.mjs +9 -7
- package/dist/internal/anthropic.d.mts +21 -26
- package/dist/internal/anthropic.mjs +6 -6
- package/dist/internal/google-model-family.mjs +1 -1
- package/dist/internal/google.d.mts +15 -0
- package/dist/internal/google.mjs +1 -0
- package/dist/internal/model-request-body.d.mts +37 -0
- package/dist/internal/model-request-body.mjs +106 -0
- package/dist/internal/openai-completions-compat.d.mts +5 -1
- package/dist/internal/openai-completions-compat.mjs +3 -2
- package/dist/internal/openai-responses-payload-policy.d.mts +2 -2
- package/dist/internal/openai-responses-payload-policy.mjs +2 -2
- package/dist/internal/openai.d.mts +14 -12
- package/dist/internal/openai.mjs +11 -10
- package/dist/internal/reasoning-tag-text-partitioner.d.mts +26 -0
- package/dist/{reasoning-tag-text-partitioner-DzlRubwU.mjs → internal/reasoning-tag-text-partitioner.mjs} +313 -122
- package/dist/internal/retry-after.d.mts +2 -2
- package/dist/internal/retry-after.mjs +165 -27
- package/dist/internal/runtime.d.mts +15 -41
- package/dist/internal/runtime.mjs +9 -10
- package/dist/internal/shared.d.mts +21 -25
- package/dist/internal/shared.mjs +9 -98
- package/dist/internal/tool-schema.d.mts +10 -10
- package/dist/internal/tool-schema.mjs +4 -4
- package/dist/{llm-request-activity-CfMuh5cC.mjs → llm-request-activity-DzaHoRAU.mjs} +2 -2
- package/dist/mistral-F5_asrmU.mjs +3741 -0
- package/dist/mistral.LICENSE +201 -0
- package/dist/{model-transport-url-BrsjjdjR.d.mts → model-transport-url-BdksnBqu.d.mts} +6 -8
- package/dist/{number-coercion-37gmNkuA.mjs → number-coercion-C7HsBgUL.mjs} +7 -2
- package/dist/observe-async-iterator-AlARO5wS.d.mts +178 -0
- package/dist/observe-async-iterator-DgmegcZR.mjs +181 -0
- package/dist/{openai-chatgpt-responses-iGYDPbmc.mjs → openai-chatgpt-responses-BIK7HROH.mjs} +61 -80
- package/dist/{openai-completions-CDy5u1mv.mjs → openai-completions-ClJ7QHEB.mjs} +5 -5
- package/dist/{openai-completions-compat-CBvb2eld.d.mts → openai-completions-compat-CJ-NsDzg.d.mts} +12 -6
- package/dist/{openai-completions-compat-CJ0OXZgi.mjs → openai-completions-compat-CstlTQuF.mjs} +74 -50
- package/dist/openai-completions-reasoning-replay-BwT1xwRI.mjs +45 -0
- package/dist/{openai-completions-transport-DLrm5EWi.mjs → openai-completions-transport-C6J4_oGf.mjs} +501 -563
- package/dist/{openai-prompt-cache-DgjD-UL5.d.mts → openai-prompt-cache-BZGaIWYh.d.mts} +4 -4
- package/dist/{openai-prompt-cache-h8vXRiaH.mjs → openai-prompt-cache-CgDoFhO0.mjs} +5 -4
- package/dist/openai-responses-Beifmf1s.mjs +89 -0
- package/dist/{openai-responses-compaction-replay-DUBbsfku.d.mts → openai-responses-compaction-replay-CNHk6k53.d.mts} +4 -4
- package/dist/{openai-responses-contracts-gnl6ZRs1.d.mts → openai-responses-contracts-BXMcvO7F.d.mts} +4 -10
- package/dist/{openai-responses-contracts-DCG51Us0.mjs → openai-responses-contracts-xU-n9AJJ.mjs} +36 -37
- package/dist/{openai-responses-endpoint-JbBT8IDv.mjs → openai-responses-endpoint-DCkURKS0.mjs} +55 -8
- package/dist/{openai-responses-payload-policy-BzM52TTH.d.mts → openai-responses-payload-policy-DyE30gdD.d.mts} +7 -7
- package/dist/{openai-responses-request-lifecycle-DuMpdA6y.mjs → openai-responses-request-lifecycle-o-ODC_rF.mjs} +12 -26
- package/dist/{openai-responses-shared-CNfHudFg.mjs → openai-responses-shared-CrFDkZ0N.mjs} +637 -389
- package/dist/{openai-responses-terminal-usage-CpVjkqn-.d.mts → openai-responses-terminal-usage-D7IhRA6i.d.mts} +9 -3
- package/dist/{openai-tool-schema-CGhEl7ao.mjs → openai-tool-schema-CsoYgnWy.mjs} +97 -122
- package/dist/otel-D-BkX8bB.mjs +766 -0
- package/dist/{overflow-OF3PgPbw.mjs → overflow-CpApyjG2.mjs} +1 -1
- package/dist/{positive-integer-Bb4Evc7L.mjs → positive-integer-DiqE5vNi.mjs} +2 -3
- package/dist/{prompt-cache-stability-D_MeCQFI.mjs → prompt-cache-stability-w-ICeyOI.mjs} +1 -1
- package/dist/{provider-error-qtZD2inE.mjs → provider-error-DD-fo4Rz.mjs} +71 -234
- package/dist/{provider-options-Bo8GzTGX.d.mts → provider-options-Mo8NM5d1.d.mts} +15 -4
- package/dist/{provider-replay-context-BC23HyZo.mjs → provider-replay-context-xyU7-CiT.mjs} +2 -2
- package/dist/provider-transcript-transform-BHq3Q4nc.mjs +32 -0
- package/dist/{provider-transport-turn-state-B11rmZpv.mjs → provider-transport-turn-state-DQd9K4Pd.mjs} +3 -3
- package/dist/{provider-types-ODq57rG_.d.mts → provider-types-B1e98js5.d.mts} +6 -4
- package/dist/provider-types.d.mts +7 -6
- package/dist/provider-types.mjs +2 -1
- package/dist/providers.d.mts +2 -2
- package/dist/providers.mjs +26 -29
- package/dist/{record-coerce-CNDovvft.mjs → record-coerce-BQaoiN3r.mjs} +4 -1
- package/dist/request-headers-DO4Mqhw1.mjs +10 -0
- package/dist/{required-api-key-D088S4Cd.mjs → required-api-key-2zZTkmsi.mjs} +1 -1
- package/dist/retry-after-DnHBlFS2.d.mts +45 -0
- package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
- package/dist/{sanitize-unicode-ZqVLLEKC.d.mts → sanitize-unicode-BISmUlUv.d.mts} +2 -2
- package/dist/{simple-options-BdJJbzZk.mjs → simple-options-tLSeECry.mjs} +108 -82
- package/dist/src-BUsVkrNt.mjs +105 -0
- package/dist/{src-CyA0zJnt.mjs → src-CQ7nH2mL.mjs} +4 -7
- package/dist/stable-stringify-CchQEmeA.mjs +84 -0
- package/dist/{stream-DQqGjhbq.mjs → stream-DrtAWu7c.mjs} +2 -6
- package/dist/{stream-first-event-timeout-D_TfJHRJ.mjs → stream-first-event-timeout-B7RcufAV.mjs} +16 -13
- package/dist/{string-coerce-Cj8sqWHx.mjs → string-coerce-BCuWMIrk.mjs} +1 -1
- package/dist/string-normalization-B8TDDBX_.mjs +32 -0
- package/dist/telemetry-B9f7K_Xe.mjs +582 -0
- package/dist/{tool-schema-json-projection-Cvq69Ajp.mjs → tool-schema-json-projection-BQpiJlXJ.mjs} +53 -69
- package/dist/{transport-stream-shared-DdnJGEj0.mjs → transport-stream-shared-D2uFMhMc.mjs} +177 -93
- package/dist/{transport-stream-shared-8ru8eX4s.d.mts → transport-stream-shared-D3IAU4jn.d.mts} +29 -15
- package/dist/{transport-utils-CcCAuFVS.mjs → transport-utils-Da_39MYi.mjs} +23 -38
- package/dist/transports.d.mts +39 -38
- package/dist/transports.mjs +214 -295
- package/dist/{types-CVYzKrMl.d.mts → types-BVdTf0YV.d.mts} +38 -3
- package/dist/types-Cb3-5WM9.d.mts +1 -0
- package/dist/{types-BXd0kI8-.mjs → types-OVEWUaDh.mjs} +3 -1
- package/dist/types.d.mts +7 -6
- package/dist/types.mjs +7 -5
- package/dist/{validation-9FSkE8T-.mjs → validation-DGXqfvkj.mjs} +45 -27
- package/dist/{validation-BQ5u20Ru.d.mts → validation-QmyD0E5A.d.mts} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -2
- package/package.json +40 -6
- package/dist/anthropic-B54Ts1tV.mjs +0 -221
- package/dist/assistant-output-DbgdWAhJ.mjs +0 -47
- package/dist/event-stream-CDpFza-M.d.mts +0 -1
- package/dist/index-DSprYWaz.d.mts +0 -185
- package/dist/mistral-C_ImzxlK.mjs +0 -512
- package/dist/model-request-body-BD5vy4rP.d.mts +0 -17
- package/dist/openai-responses-Cp2QPq7K.mjs +0 -87
- package/dist/retry-after-sw-XX8aC.d.mts +0 -15
- package/dist/types-CBJthzJX.d.mts +0 -1
|
@@ -1,31 +1,39 @@
|
|
|
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-BHq3Q4nc.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";
|
|
34
|
+
import { isDeepStrictEqual } from "node:util";
|
|
35
|
+
import { isProxy } from "node:util/types";
|
|
36
|
+
import { APIError } from "openai";
|
|
29
37
|
import { Stream } from "openai/core/streaming";
|
|
30
38
|
//#region packages/ai/src/transports/openai-transport-shared.ts
|
|
31
39
|
const OPENAI_RESPONSE_MODEL_HEADER_NAMES = /* @__PURE__ */ new Set(["openai-model", "x-openai-model"]);
|
|
@@ -40,6 +48,12 @@ const OPENAI_RESPONSE_MODEL_EVENT_TYPES = /* @__PURE__ */ new Set([
|
|
|
40
48
|
const OPENAI_DATED_MODEL_SUFFIX = /-(?:\d{8}|\d{4}-\d{2}-\d{2})$/;
|
|
41
49
|
const GEMINI_THOUGHT_SIGNATURE_VALIDATOR_SKIP = "skip_thought_signature_validator";
|
|
42
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
|
+
},
|
|
43
57
|
debug(message, data) {
|
|
44
58
|
getAiTransportHost().logDebug("openai-transport", () => ({
|
|
45
59
|
message,
|
|
@@ -519,41 +533,30 @@ function toOpenAIResponsesToolChoice(choice) {
|
|
|
519
533
|
};
|
|
520
534
|
}
|
|
521
535
|
//#endregion
|
|
522
|
-
//#region packages/ai/src/transports/openai-reasoning-compat.ts
|
|
523
|
-
/** Explicit model reasoning-effort compatibility metadata. */
|
|
524
|
-
function readCompatReasoningEffortMap(compat) {
|
|
525
|
-
const rawMap = asOptionalObjectRecord(asOptionalObjectRecord(compat)?.reasoningEffortMap);
|
|
526
|
-
if (!rawMap) return {};
|
|
527
|
-
return Object.fromEntries(Object.entries(rawMap).filter((entry) => typeof entry[1] === "string"));
|
|
528
|
-
}
|
|
529
|
-
/** Resolves the reasoning effort remap for an OpenAI-compatible model. */
|
|
530
|
-
function resolveOpenAIReasoningEffortMap(model, fallbackMap = {}) {
|
|
531
|
-
return {
|
|
532
|
-
...fallbackMap,
|
|
533
|
-
...readCompatReasoningEffortMap(model.compat)
|
|
534
|
-
};
|
|
535
|
-
}
|
|
536
|
-
//#endregion
|
|
537
536
|
//#region packages/ai/src/providers/openai-request-reasoning.ts
|
|
538
537
|
/** Preserve explicit off until the selected route maps it to its native value. */
|
|
539
538
|
function resolveOpenAISimpleReasoningEffort(model, reasoning) {
|
|
540
539
|
return reasoning === void 0 ? void 0 : clampThinkingLevel(model, reasoning);
|
|
541
540
|
}
|
|
542
|
-
function resolveOpenAIRequestReasoning(model, reasoning
|
|
541
|
+
function resolveOpenAIRequestReasoning(model, reasoning) {
|
|
543
542
|
const requested = normalizeOpenAIReasoningEffort(reasoning ?? "off");
|
|
544
543
|
const modelLevel = MODEL_CATALOG_THINKING_LEVELS.find((candidate) => candidate === requested);
|
|
545
544
|
const modelMapped = modelLevel ? model.thinkingLevelMap?.[modelLevel] : void 0;
|
|
546
545
|
const mapped = modelMapped === null ? null : resolveOpenAIReasoningEffortMapping(requested, resolveOpenAIReasoningEffortMap(model)) ?? modelMapped;
|
|
547
|
-
const intent = mapped !== void 0 ? mapped?.trim() : reasoning === void 0
|
|
546
|
+
const intent = mapped !== void 0 ? mapped?.trim() : reasoning === void 0 ? void 0 : requested;
|
|
548
547
|
const normalizedIntent = normalizeOpenAIReasoningEffort(intent ?? "off");
|
|
549
|
-
const
|
|
550
|
-
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({
|
|
551
551
|
model,
|
|
552
552
|
effort: requested,
|
|
553
553
|
fallbackMap: { [requested]: intent }
|
|
554
554
|
});
|
|
555
555
|
return {
|
|
556
|
-
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,
|
|
557
560
|
thinkingEnabled: intent === void 0 ? void 0 : model.reasoning && normalizedIntent !== "off" && normalizedIntent !== "none"
|
|
558
561
|
};
|
|
559
562
|
}
|
|
@@ -1019,11 +1022,49 @@ const TURN_HEADERS = /* @__PURE__ */ new Set([
|
|
|
1019
1022
|
"x-openclaw-turn-id",
|
|
1020
1023
|
"x-openclaw-turn-attempt"
|
|
1021
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
|
+
}
|
|
1022
1066
|
function jsonValuesEqual(left, right) {
|
|
1023
|
-
|
|
1024
|
-
const normalizedLeft = stableStringify(JSON.parse(leftJson));
|
|
1025
|
-
const rightJson = JSON.stringify(right);
|
|
1026
|
-
return leftJson === rightJson || normalizedLeft === stableStringify(JSON.parse(rightJson));
|
|
1067
|
+
return isDeepStrictEqual(projectJsonObject(left), projectJsonObject(right));
|
|
1027
1068
|
}
|
|
1028
1069
|
function requestWithoutInput(request) {
|
|
1029
1070
|
const { input: _input, previous_response_id: _previousResponseId, instructions: _instructions, tools: _tools, ...rest } = request;
|
|
@@ -1064,8 +1105,17 @@ function toolCallOwnerByReplayShape(calls) {
|
|
|
1064
1105
|
}
|
|
1065
1106
|
return ownerByReplayShape;
|
|
1066
1107
|
}
|
|
1067
|
-
function
|
|
1068
|
-
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);
|
|
1069
1119
|
const replayedCallIds = /* @__PURE__ */ new Set();
|
|
1070
1120
|
const lastCallPosition = /* @__PURE__ */ new Map();
|
|
1071
1121
|
const lastOutputPosition = /* @__PURE__ */ new Map();
|
|
@@ -1076,24 +1126,14 @@ function pendingResponsesToolCalls(calls, input) {
|
|
|
1076
1126
|
const positions = item.type === "function_call" ? lastCallPosition : item.type === "function_call_output" ? lastOutputPosition : void 0;
|
|
1077
1127
|
if (positions && owner !== void 0 && owner !== null) positions.set(owner, inputIndex);
|
|
1078
1128
|
}
|
|
1079
|
-
|
|
1129
|
+
const pendingToolCalls = uniqueCalls.filter((_call, index) => {
|
|
1080
1130
|
const callPosition = lastCallPosition.get(index);
|
|
1081
1131
|
return [...toolCallReplayShapes(_call)].some((shape) => replayedCallIds.has(shape)) && (callPosition === void 0 || (lastOutputPosition.get(index) ?? -1) < callPosition);
|
|
1082
1132
|
});
|
|
1083
|
-
}
|
|
1084
|
-
function recordResponsesContinuationState(previous, lastRequest, response, continued = false) {
|
|
1085
|
-
const calls = previous && continued ? [...previous.pendingToolCalls ?? [], ...responseToolCalls(previous.lastResponseItems)] : responseToolCalls(lastRequest.input ?? []);
|
|
1086
|
-
const seenCalls = /* @__PURE__ */ new Set();
|
|
1087
|
-
const pendingToolCalls = pendingResponsesToolCalls(calls.filter((call) => {
|
|
1088
|
-
const key = JSON.stringify([call.callId, call.itemId]);
|
|
1089
|
-
if (seenCalls.has(key)) return false;
|
|
1090
|
-
seenCalls.add(key);
|
|
1091
|
-
return true;
|
|
1092
|
-
}), lastRequest.input ?? []);
|
|
1093
1133
|
return {
|
|
1094
1134
|
lastRequest,
|
|
1095
1135
|
lastResponseId: response.id,
|
|
1096
|
-
lastResponseItems: response.output,
|
|
1136
|
+
lastResponseItems: response.output.filter((item) => item.type !== "web_search_call"),
|
|
1097
1137
|
pendingToolCalls
|
|
1098
1138
|
};
|
|
1099
1139
|
}
|
|
@@ -1145,57 +1185,11 @@ function normalizeContinuationHistory(input) {
|
|
|
1145
1185
|
}
|
|
1146
1186
|
return normalized;
|
|
1147
1187
|
}
|
|
1148
|
-
function continuationHistoryMatches(previousInput, currentInput) {
|
|
1149
|
-
for (const [index, previousItem] of previousInput.entries()) {
|
|
1150
|
-
const currentItem = currentInput[index];
|
|
1151
|
-
if (!isRecord(previousItem) || !isRecord(currentItem)) continue;
|
|
1152
|
-
if (previousItem.type === "function_call" && currentItem.type === "function_call") {
|
|
1153
|
-
if (typeof previousItem.call_id === "string" && typeof currentItem.call_id === "string" && !toolCallReplayShapes({
|
|
1154
|
-
callId: previousItem.call_id,
|
|
1155
|
-
...typeof previousItem.id === "string" ? { itemId: previousItem.id } : {}
|
|
1156
|
-
}).has(currentItem.call_id)) return false;
|
|
1157
|
-
}
|
|
1158
|
-
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;
|
|
1159
|
-
}
|
|
1160
|
-
const normalizedPrevious = normalizeContinuationHistory(previousInput);
|
|
1161
|
-
const normalizedCurrent = normalizeContinuationHistory(currentInput);
|
|
1162
|
-
return normalizedPrevious !== void 0 && normalizedCurrent !== void 0 && jsonValuesEqual(normalizedCurrent, normalizedPrevious);
|
|
1163
|
-
}
|
|
1164
1188
|
function responsesContinuationRequestFingerprint(request) {
|
|
1165
|
-
|
|
1166
|
-
return sha256Hex(stableStringify(JSON.parse(serialized)));
|
|
1189
|
+
return sha256StableValue(projectJsonObject(requestWithoutInput(request))).digest;
|
|
1167
1190
|
}
|
|
1168
1191
|
function responsesContinuationPrefixFingerprint(input, output = []) {
|
|
1169
|
-
|
|
1170
|
-
return sha256Hex(stableStringify(JSON.parse(serialized)));
|
|
1171
|
-
}
|
|
1172
|
-
function restoreRawCallIdsInDelta(delta, cachedResponseItems, replayedToolRound, pendingToolCalls) {
|
|
1173
|
-
const currentResponseCalls = responseToolCalls(cachedResponseItems);
|
|
1174
|
-
const replayedCalls = replayedToolRound.filter((item) => isRecord(item) && item.type === "function_call");
|
|
1175
|
-
if (currentResponseCalls.length !== replayedCalls.length) return;
|
|
1176
|
-
const cachedCalls = [...pendingToolCalls, ...currentResponseCalls];
|
|
1177
|
-
const currentCallOffset = pendingToolCalls.length;
|
|
1178
|
-
const ownerByReplayShape = toolCallOwnerByReplayShape(cachedCalls);
|
|
1179
|
-
for (const index of currentResponseCalls.keys()) {
|
|
1180
|
-
const replayedCallId = replayedCalls[index]?.call_id;
|
|
1181
|
-
if (typeof replayedCallId !== "string" || ownerByReplayShape.get(replayedCallId) !== currentCallOffset + index) return;
|
|
1182
|
-
}
|
|
1183
|
-
const restoredDelta = [];
|
|
1184
|
-
for (const item of delta) {
|
|
1185
|
-
if (!isRecord(item) || item.type !== "function_call_output" || typeof item.call_id !== "string") {
|
|
1186
|
-
restoredDelta.push(item);
|
|
1187
|
-
continue;
|
|
1188
|
-
}
|
|
1189
|
-
const owner = ownerByReplayShape.get(item.call_id);
|
|
1190
|
-
if (owner === void 0 || owner === null) return;
|
|
1191
|
-
const rawCallId = cachedCalls[owner]?.callId;
|
|
1192
|
-
if (!rawCallId) return;
|
|
1193
|
-
restoredDelta.push(rawCallId === item.call_id ? item : {
|
|
1194
|
-
...item,
|
|
1195
|
-
call_id: rawCallId
|
|
1196
|
-
});
|
|
1197
|
-
}
|
|
1198
|
-
return restoredDelta;
|
|
1192
|
+
return sha256StableValue(projectJsonObject([...normalizeAssistantReplayInput(input), ...normalizeAssistantReplayInput(output, true)])).digest;
|
|
1199
1193
|
}
|
|
1200
1194
|
function resolveResponsesContinuationRequest(continuation, request, steering) {
|
|
1201
1195
|
if (!continuation) return {
|
|
@@ -1225,15 +1219,70 @@ function resolveResponsesContinuationRequest(continuation, request, steering) {
|
|
|
1225
1219
|
const replayedToolRoundInput = currentInput.slice(previousInput.length, baselineLength);
|
|
1226
1220
|
const replayedToolRound = normalizeAssistantReplayInput(replayedToolRoundInput);
|
|
1227
1221
|
const historyToolRoundUnchanged = [false, true].some((ignoreCachedItemIds) => jsonValuesEqual(replayedToolRound, normalizeAssistantReplayInput(continuation.lastResponseItems, true, ignoreCachedItemIds)));
|
|
1228
|
-
|
|
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 {
|
|
1229
1243
|
request,
|
|
1230
1244
|
continuationStatus: "history_changed"
|
|
1231
1245
|
};
|
|
1232
|
-
const
|
|
1233
|
-
|
|
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 {
|
|
1234
1252
|
request,
|
|
1235
1253
|
continuationStatus: "history_changed"
|
|
1236
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
|
+
}
|
|
1237
1286
|
const restoredResponseInput = restoredInput;
|
|
1238
1287
|
return {
|
|
1239
1288
|
request: {
|
|
@@ -1284,51 +1333,64 @@ function connectionIdentity(params) {
|
|
|
1284
1333
|
headers
|
|
1285
1334
|
]));
|
|
1286
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
|
+
}
|
|
1287
1352
|
function claimOpenAIResponsesHttpContinuation(params) {
|
|
1288
1353
|
const owner = getAiTransportHost();
|
|
1289
1354
|
const key = `${getSessionResourceOwnerId(owner)}\0${params.sessionId}\0${connectionIdentity(params)}`;
|
|
1290
1355
|
const previous = httpContinuationEntries.get(key);
|
|
1291
1356
|
if (previous?.kind === "claimed") return;
|
|
1292
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;
|
|
1293
1362
|
const claimed = {
|
|
1294
1363
|
kind: "claimed",
|
|
1295
1364
|
sessionId: params.sessionId,
|
|
1296
1365
|
owner
|
|
1297
1366
|
};
|
|
1298
1367
|
httpContinuationEntries.set(key, claimed);
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
},
|
|
1326
|
-
release: () => deleteHttpContinuationIfOwned(key, claimed)
|
|
1327
|
-
};
|
|
1328
|
-
} catch (error) {
|
|
1329
|
-
deleteHttpContinuationIfOwned(key, claimed);
|
|
1330
|
-
throw error;
|
|
1331
|
-
}
|
|
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
|
+
};
|
|
1332
1394
|
}
|
|
1333
1395
|
registerSessionResourceCleanup((sessionId, owner) => {
|
|
1334
1396
|
for (const [key, entry] of httpContinuationEntries) if ((!owner || entry.owner === owner) && (!sessionId || entry.sessionId === sessionId)) deleteHttpContinuationIfOwned(key, entry);
|
|
@@ -1344,7 +1406,7 @@ function readResponsesInputReplayState(message) {
|
|
|
1344
1406
|
}
|
|
1345
1407
|
function readResponsesInputReplay(message) {
|
|
1346
1408
|
const replay = readResponsesInputReplayState(message);
|
|
1347
|
-
if (replay && typeof replay.afterResponseId === "string" &&
|
|
1409
|
+
if (replay && typeof replay.afterResponseId === "string" && isStringArray(replay.before) && isStringArray(replay.after)) return {
|
|
1348
1410
|
afterResponseId: replay.afterResponseId,
|
|
1349
1411
|
before: replay.before,
|
|
1350
1412
|
after: replay.after
|
|
@@ -1522,7 +1584,8 @@ function parseOpenAIResponsesTextSignature(signature) {
|
|
|
1522
1584
|
const phase = parsed.phase === "commentary" || parsed.phase === "final_answer" ? parsed.phase : void 0;
|
|
1523
1585
|
if (id !== void 0 || phase !== void 0) return {
|
|
1524
1586
|
id,
|
|
1525
|
-
phase
|
|
1587
|
+
phase,
|
|
1588
|
+
...typeof parsed.sources === "string" ? { sources: parsed.sources } : {}
|
|
1526
1589
|
};
|
|
1527
1590
|
return;
|
|
1528
1591
|
}
|
|
@@ -1548,10 +1611,18 @@ function buildResponsesInputMessage(role, content, source) {
|
|
|
1548
1611
|
...identity ? { [responsesInputSource]: identity } : {}
|
|
1549
1612
|
};
|
|
1550
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
|
+
}
|
|
1551
1623
|
function convertResponsesMessagesWithStyle(model, context, allowedToolCallProviders, options, conversionStyle) {
|
|
1552
1624
|
const messages = [];
|
|
1553
1625
|
const providerStyle = conversionStyle === "provider";
|
|
1554
|
-
const shouldReplayReasoningItems = options?.replayReasoningItems ?? true;
|
|
1555
1626
|
const shouldReplayResponsesItemIds = options?.replayResponsesItemIds ?? true;
|
|
1556
1627
|
const replayContext = buildProviderReplayContext(model, {
|
|
1557
1628
|
sessionId: options?.sessionId,
|
|
@@ -1594,7 +1665,7 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1594
1665
|
const transformedMessages = orderResponsesAsyncToolResults(transformMessages(replayPlan.messages));
|
|
1595
1666
|
if ((options?.includeSystemPrompt ?? true) && context.systemPrompt) messages.push(buildResponsesInputMessage(resolveResponsesInstructionRole(model), [{
|
|
1596
1667
|
type: "input_text",
|
|
1597
|
-
text:
|
|
1668
|
+
text: prepareSystemPrompt(context.systemPrompt, context.preparedSystemPrompt).instructions
|
|
1598
1669
|
}]));
|
|
1599
1670
|
if (replayPlan.compactedWindow) messages.push(...replayPlan.compactedWindow.map((item) => {
|
|
1600
1671
|
if (options?.retainUserProvenance && item.type === "message" && item.role === "user") return Object.assign({}, item, { [RESPONSES_RETAINED_USER]: true });
|
|
@@ -1618,12 +1689,9 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1618
1689
|
let msgIndex = 0;
|
|
1619
1690
|
const appendAssistant = createResponsesInputReplay(model);
|
|
1620
1691
|
const inHistorySystemUpdates = supportsNativeOpenAIResponsesEndpoint(model);
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
continue;
|
|
1625
|
-
}
|
|
1626
|
-
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), [{
|
|
1627
1695
|
type: "input_text",
|
|
1628
1696
|
text: sanitizeTransportPayloadText(runtimeContextContentToText(msg.content))
|
|
1629
1697
|
}]));
|
|
@@ -1635,18 +1703,14 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1635
1703
|
}] : msg.content.map((item) => item.type === "text" ? {
|
|
1636
1704
|
type: "input_text",
|
|
1637
1705
|
text: sanitizeTransportPayloadText(item.text)
|
|
1638
|
-
} :
|
|
1639
|
-
type: "input_image",
|
|
1640
|
-
detail: "auto",
|
|
1641
|
-
image_url: `data:${item.mimeType};base64,${item.data}`
|
|
1642
|
-
}).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");
|
|
1643
1707
|
if (content.length > 0) {
|
|
1644
1708
|
const input = buildResponsesInputMessage(role, content, msg);
|
|
1645
1709
|
if (options?.retainUserProvenance && role === "user" && !msg.synthetic && !msg.operatorMessage && !hasRuntimeContextMarker(msg)) Object.assign(input, { [RESPONSES_RETAINED_USER]: true });
|
|
1646
|
-
|
|
1647
|
-
}
|
|
1710
|
+
converted.push(input);
|
|
1711
|
+
}
|
|
1648
1712
|
} else if (msg.role === "assistant") {
|
|
1649
|
-
const output =
|
|
1713
|
+
const output = converted;
|
|
1650
1714
|
const sourceTurnKey = responsesAssistantTurnKey(msg);
|
|
1651
1715
|
const sourceFragmentId = msg.content.find((block) => block.type === "toolCall")?.id;
|
|
1652
1716
|
let textFallbackOrdinal = 0;
|
|
@@ -1654,7 +1718,7 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1654
1718
|
let seenReplayableReasoning = false;
|
|
1655
1719
|
const isDifferentModel = msg.model !== model.id && msg.provider === model.provider && msg.api === model.api;
|
|
1656
1720
|
for (const block of msg.content) if (block.type === "thinking") {
|
|
1657
|
-
if (
|
|
1721
|
+
if (block.thinkingSignature && (providerStyle || block.thinkingSignature.startsWith("{"))) {
|
|
1658
1722
|
let reasoningItem;
|
|
1659
1723
|
try {
|
|
1660
1724
|
reasoningItem = JSON.parse(block.thinkingSignature);
|
|
@@ -1677,18 +1741,20 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1677
1741
|
let msgId = resolveReplayableResponsesMessageId({
|
|
1678
1742
|
replayResponsesItemIds: shouldReplayResponsesItemIds,
|
|
1679
1743
|
textSignatureId: textSignature?.id,
|
|
1680
|
-
fallbackId: sourceTurnKey ? `msg_${shortHash(JSON.stringify([sourceTurnKey, sourceFragmentId]))}` : `msg_${
|
|
1744
|
+
fallbackId: sourceTurnKey ? `msg_${shortHash(JSON.stringify([sourceTurnKey, sourceFragmentId]))}` : `msg_${messageIndex}`,
|
|
1681
1745
|
fallbackOrdinal: textFallbackOrdinal,
|
|
1682
1746
|
previousReplayItemWasReasoning
|
|
1683
1747
|
});
|
|
1684
1748
|
if (!textSignature?.id) textFallbackOrdinal += 1;
|
|
1685
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;
|
|
1686
1752
|
const messageItem = {
|
|
1687
1753
|
type: "message",
|
|
1688
1754
|
role: "assistant",
|
|
1689
1755
|
content: [{
|
|
1690
1756
|
type: "output_text",
|
|
1691
|
-
text: sanitizeTransportPayloadText(
|
|
1757
|
+
text: sanitizeTransportPayloadText(providerText),
|
|
1692
1758
|
annotations: []
|
|
1693
1759
|
}],
|
|
1694
1760
|
status: "completed",
|
|
@@ -1717,8 +1783,7 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1717
1783
|
if (last?.type !== "reasoning" || !last.id?.startsWith("rs_") || typeof last.encrypted_content === "string" && last.encrypted_content.length > 0) break;
|
|
1718
1784
|
output.pop();
|
|
1719
1785
|
}
|
|
1720
|
-
|
|
1721
|
-
if (output.length === 0 && providerStyle) continue;
|
|
1786
|
+
return output;
|
|
1722
1787
|
} else if (msg.role === "toolResult") {
|
|
1723
1788
|
const textResult = extractToolResultText(msg.content);
|
|
1724
1789
|
const hasText = textResult.trim().length > 0;
|
|
@@ -1731,11 +1796,7 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1731
1796
|
if (hasImages && model.input.includes("image")) {
|
|
1732
1797
|
const parts = [];
|
|
1733
1798
|
let hasExplicitText = false;
|
|
1734
|
-
for (const item of msg.content) if (isImageWithMediaPayload(item)) parts.push(
|
|
1735
|
-
type: "input_image",
|
|
1736
|
-
detail: "auto",
|
|
1737
|
-
image_url: `data:${item.mimeType};base64,${item.data}`
|
|
1738
|
-
});
|
|
1799
|
+
for (const item of msg.content) if (isImageWithMediaPayload(item)) parts.push(buildResponsesInputImage(item));
|
|
1739
1800
|
else if (hasText && item.type === "text") {
|
|
1740
1801
|
const text = extractToolResultBlockText(item);
|
|
1741
1802
|
if (text) {
|
|
@@ -1759,13 +1820,52 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1759
1820
|
});
|
|
1760
1821
|
output = parts;
|
|
1761
1822
|
}
|
|
1762
|
-
|
|
1823
|
+
converted.push({
|
|
1763
1824
|
type: "function_call_output",
|
|
1764
1825
|
call_id: callId,
|
|
1765
1826
|
output
|
|
1766
1827
|
});
|
|
1767
1828
|
}
|
|
1768
|
-
|
|
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;
|
|
1769
1869
|
}
|
|
1770
1870
|
return messages;
|
|
1771
1871
|
}
|
|
@@ -1777,28 +1877,22 @@ function convertProviderResponsesMessages(model, context, allowedToolCallProvide
|
|
|
1777
1877
|
}
|
|
1778
1878
|
//#endregion
|
|
1779
1879
|
//#region packages/ai/src/transports/openai-responses-context-usage.ts
|
|
1780
|
-
const TOOL_CALL_PROVIDERS = /* @__PURE__ */ new Set([
|
|
1781
|
-
"openai",
|
|
1782
|
-
"opencode",
|
|
1783
|
-
"azure-openai-responses",
|
|
1784
|
-
"github-copilot"
|
|
1785
|
-
]);
|
|
1786
1880
|
function contextFingerprint(input, output = []) {
|
|
1787
1881
|
const reasoning = [...input, ...output].flatMap((item) => {
|
|
1788
1882
|
if (!isRecord(item) || item.type !== "reasoning") return [];
|
|
1789
1883
|
const { id: _id, status: _status, ...content } = item;
|
|
1790
1884
|
return [content];
|
|
1791
1885
|
});
|
|
1792
|
-
return
|
|
1886
|
+
return sha256StableValue({
|
|
1793
1887
|
prefix: responsesContinuationPrefixFingerprint(input, output),
|
|
1794
1888
|
reasoning
|
|
1795
|
-
})
|
|
1889
|
+
}).digest;
|
|
1796
1890
|
}
|
|
1797
1891
|
/** Bind measured usage to the admitted replay prefix, without copying its content. */
|
|
1798
1892
|
function recordResponsesContextUsage(message, model, identity, request, output, projection) {
|
|
1799
1893
|
const usage = message.usage.contextUsage;
|
|
1800
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;
|
|
1801
|
-
const replayOutput = (projection === "transport" ? convertResponsesMessages : convertProviderResponsesMessages)(model, { messages: [message] },
|
|
1895
|
+
const replayOutput = (projection === "transport" ? convertResponsesMessages : convertProviderResponsesMessages)(model, { messages: [message] }, OPENAI_RESPONSES_TOOL_CALL_PROVIDERS, {
|
|
1802
1896
|
...identity,
|
|
1803
1897
|
includeSystemPrompt: false
|
|
1804
1898
|
}).filter((item) => item.type !== "function_call_output");
|
|
@@ -1830,7 +1924,7 @@ function resolveResponsesContextUsageBoundary(messages, model, identity, systemP
|
|
|
1830
1924
|
const input = (projection === "transport" ? convertResponsesMessages : convertProviderResponsesMessages)(model, {
|
|
1831
1925
|
messages: messages.filter(isProviderMessage),
|
|
1832
1926
|
systemPrompt
|
|
1833
|
-
},
|
|
1927
|
+
}, OPENAI_RESPONSES_TOOL_CALL_PROVIDERS, {
|
|
1834
1928
|
...identity,
|
|
1835
1929
|
includeSystemPrompt: includeSystemPrompt === true
|
|
1836
1930
|
});
|
|
@@ -1925,20 +2019,6 @@ function summarizeResponsesTools(tools) {
|
|
|
1925
2019
|
const shown = names.slice(0, maxNames).join(",");
|
|
1926
2020
|
return `count=${tools.length}${shown ? ` ${label}=${shown}` : ""}`;
|
|
1927
2021
|
}
|
|
1928
|
-
function stringifyRedactedPayload(value) {
|
|
1929
|
-
try {
|
|
1930
|
-
const encoded = JSON.stringify(value, (key, child) => key === "encrypted_content" ? "<opaque data omitted>" : child);
|
|
1931
|
-
if (!encoded) return "<empty>";
|
|
1932
|
-
const redacted = redactSensitiveText(encoded);
|
|
1933
|
-
return redacted.length > 8e3 ? `${truncateUtf16Safe(redacted, 8e3)}…<truncated>` : redacted;
|
|
1934
|
-
} catch {
|
|
1935
|
-
return "<unserializable>";
|
|
1936
|
-
}
|
|
1937
|
-
}
|
|
1938
|
-
function stringifyRedactedEvent(value) {
|
|
1939
|
-
const redacted = stringifyRedactedPayload(value);
|
|
1940
|
-
return redacted.length > 2e3 ? `${truncateUtf16Safe(redacted, 2e3)}…<truncated>` : redacted;
|
|
1941
|
-
}
|
|
1942
2022
|
const RESPONSE_FAILED_FAILURE_FIELD_KEYS = [
|
|
1943
2023
|
"error",
|
|
1944
2024
|
"incomplete_details",
|
|
@@ -1956,10 +2036,6 @@ function buildResponsesFailedEventSummary(message, responseId, code, observation
|
|
|
1956
2036
|
...observation ? { observation } : {}
|
|
1957
2037
|
};
|
|
1958
2038
|
}
|
|
1959
|
-
function isResponseFailedIdentifierKey(key) {
|
|
1960
|
-
const normalized = key.replace(/[-_\s]/g, "").toLowerCase();
|
|
1961
|
-
return normalized.includes("request") && normalized.endsWith("id") || normalized.includes("provider") && normalized.endsWith("id");
|
|
1962
|
-
}
|
|
1963
2039
|
function collectResponseFailedIdentifierHashes(input) {
|
|
1964
2040
|
const out = [];
|
|
1965
2041
|
const seen = /* @__PURE__ */ new WeakSet();
|
|
@@ -1971,7 +2047,8 @@ function collectResponseFailedIdentifierHashes(input) {
|
|
|
1971
2047
|
if (out.length >= 12 || typeof key === "number" && key >= 8) break;
|
|
1972
2048
|
const childPath = typeof key === "number" ? `${path}[${key}]` : path ? `${path}.${key}` : key;
|
|
1973
2049
|
const childIdentifierKey = typeof key === "number" ? identifierKey : key;
|
|
1974
|
-
const
|
|
2050
|
+
const normalizedKey = childIdentifierKey.replace(/[-_\s]/g, "").toLowerCase();
|
|
2051
|
+
const isIdentifier = normalizedKey.includes("request") && normalizedKey.endsWith("id") || normalizedKey.includes("provider") && normalizedKey.endsWith("id");
|
|
1975
2052
|
const childString = typeof child === "string" || typeof child === "number" ? String(child).trim() : "";
|
|
1976
2053
|
if (isIdentifier && childString) out.push(`${childPath}=${redactIdentifier(childString, { len: 12 })}`);
|
|
1977
2054
|
else visit(child, childPath, depth + 1, isIdentifier ? childIdentifierKey : "");
|
|
@@ -1980,58 +2057,24 @@ function collectResponseFailedIdentifierHashes(input) {
|
|
|
1980
2057
|
visit(input, "", 0, "");
|
|
1981
2058
|
return out;
|
|
1982
2059
|
}
|
|
1983
|
-
function
|
|
1984
|
-
const
|
|
1985
|
-
const redact = (value, key, depth) => {
|
|
1986
|
-
if (typeof value === "string" || typeof value === "number") return key && isResponseFailedIdentifierKey(key) ? redactIdentifier(String(value), { len: 12 }) : value;
|
|
1987
|
-
if (depth > 6 || !value || typeof value !== "object") return value;
|
|
1988
|
-
if (seen.has(value)) return "<circular>";
|
|
1989
|
-
seen.add(value);
|
|
1990
|
-
if (Array.isArray(value)) return value.slice(0, 16).map((item) => redact(item, key, depth + 1));
|
|
1991
|
-
const out = {};
|
|
1992
|
-
for (const [childKey, child] of Object.entries(value)) out[childKey] = redact(child, childKey, depth + 1);
|
|
1993
|
-
return out;
|
|
1994
|
-
};
|
|
1995
|
-
return redact(input, "", 0);
|
|
1996
|
-
}
|
|
1997
|
-
function buildResponsesFailedFailureFields(response) {
|
|
1998
|
-
if (!response) return {};
|
|
1999
|
-
const fields = {};
|
|
2000
|
-
for (const key of RESPONSE_FAILED_FAILURE_FIELD_KEYS) if (response[key] !== void 0 && response[key] !== null) fields[key] = response[key];
|
|
2001
|
-
return fields;
|
|
2002
|
-
}
|
|
2003
|
-
function buildResponsesFailedNoDetailsObservation(event, model, response = isRecord(event.response) ? event.response : void 0) {
|
|
2004
|
-
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);
|
|
2005
2062
|
const metadataKeys = isRecord(response?.metadata) ? Object.keys(response.metadata).toSorted() : [];
|
|
2006
|
-
const responsePreview = {
|
|
2007
|
-
id: stringifyUnknown(response?.id),
|
|
2008
|
-
status: stringifyUnknown(response?.status),
|
|
2009
|
-
model: stringifyUnknown(response?.model),
|
|
2010
|
-
object: stringifyUnknown(response?.object),
|
|
2011
|
-
failureFields,
|
|
2012
|
-
metadataKeys
|
|
2013
|
-
};
|
|
2014
2063
|
return {
|
|
2015
2064
|
event: "openai_responses_response_failed_without_details",
|
|
2016
2065
|
provider: model.provider,
|
|
2017
2066
|
api: model.api,
|
|
2018
2067
|
transportModel: model.id,
|
|
2019
2068
|
providerRuntimeFailureKind: "no_error_details",
|
|
2020
|
-
responseId:
|
|
2021
|
-
responseStatus:
|
|
2022
|
-
responseModel:
|
|
2023
|
-
responseObject:
|
|
2069
|
+
responseId: stringifyUnknown(response?.id),
|
|
2070
|
+
responseStatus: stringifyUnknown(response?.status),
|
|
2071
|
+
responseModel: stringifyUnknown(response?.model),
|
|
2072
|
+
responseObject: stringifyUnknown(response?.object),
|
|
2024
2073
|
metadataKeys,
|
|
2025
2074
|
requestIdHashes: collectResponseFailedIdentifierHashes(event),
|
|
2026
|
-
|
|
2027
|
-
responsePreview: stringifyRedactedEvent(responsePreview)
|
|
2075
|
+
failureFieldNames
|
|
2028
2076
|
};
|
|
2029
2077
|
}
|
|
2030
|
-
function summarizeResponsesFailedNoDetailsObservation(observation) {
|
|
2031
|
-
const requestIds = observation.requestIdHashes.join(",");
|
|
2032
|
-
const metadataKeys = observation.metadataKeys.join(",");
|
|
2033
|
-
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}`;
|
|
2034
|
-
}
|
|
2035
2078
|
function normalizeResponsesFailedEvent(event, model) {
|
|
2036
2079
|
const response = isRecord(event.response) ? event.response : void 0;
|
|
2037
2080
|
const responseId = stringifyUnknown(response?.id) || void 0;
|
|
@@ -2056,7 +2099,9 @@ var ResponsesStreamFailure = class extends Error {
|
|
|
2056
2099
|
}
|
|
2057
2100
|
};
|
|
2058
2101
|
function logResponsesFailedNoDetails(observation) {
|
|
2059
|
-
|
|
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);
|
|
2060
2105
|
}
|
|
2061
2106
|
function summarizeResponsesPayload(params) {
|
|
2062
2107
|
if (!params || typeof params !== "object") return "payload=non-object";
|
|
@@ -2064,7 +2109,7 @@ function summarizeResponsesPayload(params) {
|
|
|
2064
2109
|
const input = record.input;
|
|
2065
2110
|
const reasoning = record.reasoning && typeof record.reasoning === "object" ? record.reasoning : void 0;
|
|
2066
2111
|
const text = record.text && typeof record.text === "object" ? record.text : void 0;
|
|
2067
|
-
|
|
2112
|
+
return [
|
|
2068
2113
|
`fields=${Object.keys(record).toSorted().join(",")}`,
|
|
2069
2114
|
`model=${safeDebugValue(record.model)}`,
|
|
2070
2115
|
`stream=${safeDebugValue(record.stream)}`,
|
|
@@ -2081,26 +2126,62 @@ function summarizeResponsesPayload(params) {
|
|
|
2081
2126
|
`store=${safeDebugValue(record.store)}`,
|
|
2082
2127
|
`promptCacheKey=${record.prompt_cache_key === void 0 ? "absent" : "present"}`,
|
|
2083
2128
|
`metadataKeys=${record.metadata && typeof record.metadata === "object" ? Object.keys(record.metadata).toSorted().join(",") : "none"}`
|
|
2084
|
-
];
|
|
2085
|
-
|
|
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;
|
|
2147
|
+
}
|
|
2148
|
+
function summarizeOpenAITransportError(error, signal) {
|
|
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}`);
|
|
2086
2161
|
return parts.join(" ");
|
|
2087
2162
|
}
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
const
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
`
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
|
|
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;
|
|
2169
|
+
if (signal?.aborted) {
|
|
2170
|
+
emitModelTransportError(log, "responses", () => `provider=${model.provider} api=${model.api} model=${model.id} ` + summarizeOpenAITransportError(error, requestSignal) + (incompleteReason ? ` incompleteReason=${incompleteReason}` : ""), signal);
|
|
2171
|
+
return;
|
|
2172
|
+
}
|
|
2173
|
+
return {
|
|
2174
|
+
abortReason: resolveOpenAITransportAbortReason(requestSignal),
|
|
2175
|
+
incompleteReason
|
|
2176
|
+
};
|
|
2101
2177
|
}
|
|
2102
2178
|
//#endregion
|
|
2103
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
|
+
]);
|
|
2104
2185
|
function isAsyncIterable(value) {
|
|
2105
2186
|
return (typeof value === "object" && value !== null || typeof value === "function") && Symbol.asyncIterator in value;
|
|
2106
2187
|
}
|
|
@@ -2110,11 +2191,7 @@ function readResponsesRecoveryEvent(event) {
|
|
|
2110
2191
|
return {
|
|
2111
2192
|
failure: record?.type === "response.failed" ? response?.error : record?.type === "error" ? record.error ?? record : void 0,
|
|
2112
2193
|
hasResponseOutput: Array.isArray(response?.output) && response.output.length > 0,
|
|
2113
|
-
isPrelude: record !== void 0 &&
|
|
2114
|
-
"response.created",
|
|
2115
|
-
"response.in_progress",
|
|
2116
|
-
"response.queued"
|
|
2117
|
-
].includes(String(record.type))
|
|
2194
|
+
isPrelude: record !== void 0 && PRELUDE_TYPES.has(String(record.type))
|
|
2118
2195
|
};
|
|
2119
2196
|
}
|
|
2120
2197
|
function isInvalidEncryptedContentError(error) {
|
|
@@ -2166,9 +2243,8 @@ async function resolveNextResponsesEncryptedContentAttempt(attempt, error, optio
|
|
|
2166
2243
|
request: reasoningStripped
|
|
2167
2244
|
};
|
|
2168
2245
|
}
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
let compactionStripped = options?.buildFullHistoryRequest ? await options.buildFullHistoryRequest() : locallyStripped;
|
|
2246
|
+
if (stripResponsesRequestCompaction(attempt.request) === attempt.request) return;
|
|
2247
|
+
let compactionStripped = await options.buildFullHistoryRequest();
|
|
2172
2248
|
compactionStripped = stripResponsesRequestCompaction(compactionStripped);
|
|
2173
2249
|
if (attempt.kind === "reasoning-stripped") compactionStripped = stripResponsesRequestEncryptedReasoning(compactionStripped);
|
|
2174
2250
|
return {
|
|
@@ -2181,20 +2257,59 @@ async function createResponsesStreamWithRecovery(params) {
|
|
|
2181
2257
|
async function* streamWithTerminalDrain(response, body) {
|
|
2182
2258
|
const reader = body.getReader();
|
|
2183
2259
|
let terminal = false;
|
|
2260
|
+
let firstFrame = true;
|
|
2261
|
+
const decoder = decodeSseFrames();
|
|
2184
2262
|
try {
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
}
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
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();
|
|
2197
2310
|
}
|
|
2311
|
+
} catch (error) {
|
|
2312
|
+
if (error instanceof APIError || !isRecord(error) || error.name !== "AbortError" && !String(error.message).includes("FetchRequestCanceledException")) throw error;
|
|
2198
2313
|
} finally {
|
|
2199
2314
|
if (!terminal) {
|
|
2200
2315
|
await reader.cancel().catch(() => void 0);
|
|
@@ -2290,7 +2405,7 @@ async function createResponsesStreamWithRecovery(params) {
|
|
|
2290
2405
|
} catch (error) {
|
|
2291
2406
|
let nextAttempt = (!responseAccepted ? recoverServiceTier(attempt, error) : void 0) ?? await resolveNextResponsesEncryptedContentAttempt(attempt, error, { buildFullHistoryRequest: params.buildFullHistoryRequest });
|
|
2292
2407
|
if (!nextAttempt && attempt.request.previous_response_id && error && typeof error === "object" && typeof error.status === "number" && isPreviousResponseRejection(error)) {
|
|
2293
|
-
const request = { ...
|
|
2408
|
+
const request = { ...await params.buildFullHistoryRequest() };
|
|
2294
2409
|
delete request.previous_response_id;
|
|
2295
2410
|
nextAttempt = {
|
|
2296
2411
|
kind: "continuation-rejected",
|
|
@@ -2364,6 +2479,81 @@ function resolveAzureOpenAIApiVersion(env = process.env) {
|
|
|
2364
2479
|
return env.AZURE_OPENAI_API_VERSION?.trim() || "preview";
|
|
2365
2480
|
}
|
|
2366
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
|
|
2367
2557
|
//#region packages/ai/src/providers/openai-responses-stream-compat.ts
|
|
2368
2558
|
const OPENAI_RESPONSES_OUTPUT_TEXT_CONTENT_PART_TYPE = "output_text";
|
|
2369
2559
|
const AZURE_RESPONSES_TEXT_CONTENT_PART_TYPE = "text";
|
|
@@ -2392,6 +2582,7 @@ function resolveResponsesMessageSnapshotCollapse(params) {
|
|
|
2392
2582
|
}
|
|
2393
2583
|
//#endregion
|
|
2394
2584
|
//#region packages/ai/src/transports/openai-responses-stream-slots-internal.ts
|
|
2585
|
+
const RESPONSES_BOOKKEEPING_TIMEOUT_MS = 9e5;
|
|
2395
2586
|
function createResponsesOutputTracker(params) {
|
|
2396
2587
|
const outputs = /* @__PURE__ */ new Map();
|
|
2397
2588
|
let currentEventType = "unknown";
|
|
@@ -2403,10 +2594,15 @@ function createResponsesOutputTracker(params) {
|
|
|
2403
2594
|
const callId = item.call_id ?? item.id;
|
|
2404
2595
|
return item.type === "function_call" && callId ? `function_call:${callId}` : void 0;
|
|
2405
2596
|
};
|
|
2406
|
-
const
|
|
2597
|
+
const peek = (item, outputIndex) => {
|
|
2407
2598
|
const key = identity(item);
|
|
2408
2599
|
const output = (outputIndex === void 0 ? void 0 : outputs.get(outputIndex)) ?? (key === void 0 ? void 0 : outputs.get(key));
|
|
2409
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;
|
|
2410
2606
|
if (output.type !== item.type || output.callId && item.call_id && output.callId !== item.call_id) throw new ResponsesOutputIdentityError({
|
|
2411
2607
|
outputIndex,
|
|
2412
2608
|
expectedType: output.type,
|
|
@@ -2425,7 +2621,7 @@ function createResponsesOutputTracker(params) {
|
|
|
2425
2621
|
sink.push(detachPartialSnapshot(event));
|
|
2426
2622
|
} };
|
|
2427
2623
|
},
|
|
2428
|
-
observeEvent(event) {
|
|
2624
|
+
observeEvent(event, outputSlots) {
|
|
2429
2625
|
currentEventType = event.type;
|
|
2430
2626
|
terminalAllowsRetry = false;
|
|
2431
2627
|
if (event.type === "response.output_item.added" || event.type === "response.output_item.done") providerToolObserved ||= isResponsesProviderTool(event.item);
|
|
@@ -2437,9 +2633,15 @@ function createResponsesOutputTracker(params) {
|
|
|
2437
2633
|
}
|
|
2438
2634
|
terminalAllowsRetry = event.type === "response.completed" && event.response.status === "completed" && event.response.error == null && event.response.incomplete_details == null && !terminalHasRefusal;
|
|
2439
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);
|
|
2440
2642
|
},
|
|
2441
2643
|
get,
|
|
2442
|
-
set(item, contentIndex, outputIndex, completed = false) {
|
|
2644
|
+
set(item, contentIndex, outputIndex, completed = false, completedProse) {
|
|
2443
2645
|
const output = get(item, outputIndex) ?? {
|
|
2444
2646
|
type: item.type,
|
|
2445
2647
|
contentIndex,
|
|
@@ -2449,6 +2651,7 @@ function createResponsesOutputTracker(params) {
|
|
|
2449
2651
|
contentIndex,
|
|
2450
2652
|
completed
|
|
2451
2653
|
});
|
|
2654
|
+
if (completedProse !== void 0) output.completedProse = completedProse;
|
|
2452
2655
|
if (item.call_id) output.callId = item.call_id;
|
|
2453
2656
|
if (outputIndex !== void 0) {
|
|
2454
2657
|
output.outputIndex = outputIndex;
|
|
@@ -2462,7 +2665,7 @@ function createResponsesOutputTracker(params) {
|
|
|
2462
2665
|
function appendResponsesPendingTextDelta(slot, delta, materialize) {
|
|
2463
2666
|
const offset = slot.pendingText?.length ?? 0;
|
|
2464
2667
|
slot.pendingText = `${slot.pendingText ?? ""}${delta}`;
|
|
2465
|
-
const priorText = slot.collapseCandidate?.
|
|
2668
|
+
const priorText = slot.collapseCandidate?.rendered.prose ?? "";
|
|
2466
2669
|
if (offset >= priorText.length || priorText.startsWith(delta.slice(0, priorText.length - offset), offset)) return;
|
|
2467
2670
|
materialize(slot);
|
|
2468
2671
|
}
|
|
@@ -2507,9 +2710,6 @@ function createResponsesOutputSlotTracker() {
|
|
|
2507
2710
|
}
|
|
2508
2711
|
//#endregion
|
|
2509
2712
|
//#region packages/ai/src/providers/openai-responses-tool-call-tracker.ts
|
|
2510
|
-
function readEventIdentity(event) {
|
|
2511
|
-
return { itemId: normalizeOptionalString(event.item_id) };
|
|
2512
|
-
}
|
|
2513
2713
|
function readResponsesToolCallItemIdentity(item) {
|
|
2514
2714
|
return {
|
|
2515
2715
|
itemId: normalizeOptionalString(item.id),
|
|
@@ -2545,7 +2745,7 @@ function createResponsesToolCallTracker() {
|
|
|
2545
2745
|
state.outputIndex = outputIndex;
|
|
2546
2746
|
indexedCalls.set(outputIndex, state);
|
|
2547
2747
|
},
|
|
2548
|
-
resolve(event, identity =
|
|
2748
|
+
resolve(event, identity = { itemId: normalizeOptionalString(event.item_id) }, allowUnmatchedIdentity = true) {
|
|
2549
2749
|
const outputIndex = readResponsesOutputIndex(event);
|
|
2550
2750
|
if (outputIndex !== void 0) {
|
|
2551
2751
|
const indexed = indexedCalls.get(outputIndex);
|
|
@@ -2592,17 +2792,19 @@ const STRING_DELTA_EVENTS = /* @__PURE__ */ new Set([
|
|
|
2592
2792
|
"response.refusal.delta",
|
|
2593
2793
|
"response.text.delta"
|
|
2594
2794
|
]);
|
|
2595
|
-
|
|
2596
|
-
|
|
2597
|
-
|
|
2598
|
-
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
|
|
2602
|
-
}
|
|
2603
|
-
}
|
|
2604
|
-
|
|
2605
|
-
|
|
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;
|
|
2606
2808
|
const eventTypes = /* @__PURE__ */ new Map();
|
|
2607
2809
|
let eventCount = 0;
|
|
2608
2810
|
let responseId;
|
|
@@ -2611,10 +2813,14 @@ async function* observeResponsesStream(stream, model, requestStartedAt, request,
|
|
|
2611
2813
|
let reasoningTokens;
|
|
2612
2814
|
let terminalType;
|
|
2613
2815
|
let incompleteReason;
|
|
2614
|
-
const requestDetails = `transport=${transport} requestedTier=${request?.service_tier ?? "unspecified"} max_output_tokens=${request?.max_output_tokens ?? "provider-default"}`;
|
|
2615
|
-
|
|
2616
|
-
|
|
2617
|
-
|
|
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) {
|
|
2618
2824
|
const record = isRecord(event) ? event : void 0;
|
|
2619
2825
|
const type = typeof record?.type === "string" ? record.type : "unknown";
|
|
2620
2826
|
const response = isRecord(record?.response) ? record.response : void 0;
|
|
@@ -2625,20 +2831,19 @@ async function* observeResponsesStream(stream, model, requestStartedAt, request,
|
|
|
2625
2831
|
const details = response.usage.output_tokens_details;
|
|
2626
2832
|
if (isRecord(details) && typeof details.reasoning_tokens === "number") reasoningTokens = details.reasoning_tokens;
|
|
2627
2833
|
}
|
|
2628
|
-
if (type
|
|
2834
|
+
if (isResponsesTerminalEventType(type)) {
|
|
2629
2835
|
terminalType = type;
|
|
2630
2836
|
const details = response?.incomplete_details;
|
|
2631
2837
|
if (isRecord(details) && typeof details.reason === "string") incompleteReason = details.reason;
|
|
2632
2838
|
}
|
|
2633
2839
|
eventCount += 1;
|
|
2634
2840
|
eventTypes.set(type, (eventTypes.get(type) ?? 0) + 1);
|
|
2635
|
-
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"}`);
|
|
2636
|
-
|
|
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(",")}`);
|
|
2637
2845
|
}
|
|
2638
|
-
}
|
|
2639
|
-
const types = [...eventTypes].map(([type, count]) => `${type}:${count}`).join(",");
|
|
2640
|
-
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}`);
|
|
2641
|
-
}
|
|
2846
|
+
});
|
|
2642
2847
|
}
|
|
2643
2848
|
//#endregion
|
|
2644
2849
|
//#region packages/ai/src/transports/openai-responses-stream-terminal-internal.ts
|
|
@@ -2670,6 +2875,10 @@ function createResponsesTerminalController(params) {
|
|
|
2670
2875
|
const { output, stream, model, options } = params;
|
|
2671
2876
|
const blocks = output.content;
|
|
2672
2877
|
const pendingReasoning = /* @__PURE__ */ new Set();
|
|
2878
|
+
const completedText = /* @__PURE__ */ new Map();
|
|
2879
|
+
const recordCompletedText = (index, text) => {
|
|
2880
|
+
completedText.set(index, text);
|
|
2881
|
+
};
|
|
2673
2882
|
const deferredToolCompletions = [];
|
|
2674
2883
|
const recordPendingReasoning = (contentIndex) => {
|
|
2675
2884
|
pendingReasoning.add(contentIndex);
|
|
@@ -2693,12 +2902,10 @@ function createResponsesTerminalController(params) {
|
|
|
2693
2902
|
if (item.encrypted_content && options?.reasoningReplayMetadata) Object.assign(block, { [OPENAI_RESPONSES_REASONING_REPLAY_BLOCK_META_KEY]: options.reasoningReplayMetadata });
|
|
2694
2903
|
}
|
|
2695
2904
|
};
|
|
2696
|
-
const appendText = (item, initialIndex) => {
|
|
2905
|
+
const appendText = (item, initialIndex, initialRender, preserveSignature = false) => {
|
|
2906
|
+
let rendered = initialRender;
|
|
2697
2907
|
let contentIndex = initialIndex;
|
|
2698
|
-
|
|
2699
|
-
const content = part;
|
|
2700
|
-
return content.type === "output_text" || content.type === "text" ? content.text ?? "" : content.refusal ?? "";
|
|
2701
|
-
}).join("");
|
|
2908
|
+
let text = rendered.text;
|
|
2702
2909
|
const block = contentIndex === void 0 ? void 0 : blocks[contentIndex];
|
|
2703
2910
|
const started = block?.type === "text" ? block : void 0;
|
|
2704
2911
|
if (!text && !started) return;
|
|
@@ -2706,11 +2913,12 @@ function createResponsesTerminalController(params) {
|
|
|
2706
2913
|
if (started && contentIndex !== void 0) {
|
|
2707
2914
|
const previousText = started.text;
|
|
2708
2915
|
started.text = text;
|
|
2709
|
-
started.textSignature =
|
|
2916
|
+
started.textSignature = preserveSignature ? withResponsesTextSources(started.textSignature, rendered) : responsesTextSignature(item.id, phase, rendered);
|
|
2710
2917
|
params.setLastTextBlock({
|
|
2711
2918
|
block: started,
|
|
2712
2919
|
index: contentIndex,
|
|
2713
|
-
phase
|
|
2920
|
+
phase,
|
|
2921
|
+
rendered
|
|
2714
2922
|
});
|
|
2715
2923
|
if (text.startsWith(previousText)) {
|
|
2716
2924
|
const delta = text.slice(previousText.length);
|
|
@@ -2722,30 +2930,33 @@ function createResponsesTerminalController(params) {
|
|
|
2722
2930
|
}
|
|
2723
2931
|
} else {
|
|
2724
2932
|
const previous = params.getLastTextBlock();
|
|
2725
|
-
|
|
2933
|
+
if (resolveResponsesMessageSnapshotCollapse({
|
|
2726
2934
|
prior: previous && {
|
|
2727
|
-
text: previous.
|
|
2935
|
+
text: previous.rendered.prose,
|
|
2728
2936
|
phase: previous.phase
|
|
2729
2937
|
},
|
|
2730
|
-
nextText:
|
|
2938
|
+
nextText: rendered.prose,
|
|
2731
2939
|
nextPhase: phase
|
|
2732
|
-
})
|
|
2733
|
-
|
|
2734
|
-
|
|
2735
|
-
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);
|
|
2736
2946
|
contentIndex = previous.index;
|
|
2737
2947
|
} else {
|
|
2738
2948
|
const newBlock = {
|
|
2739
2949
|
type: "text",
|
|
2740
2950
|
text,
|
|
2741
|
-
textSignature:
|
|
2951
|
+
textSignature: responsesTextSignature(item.id, phase, rendered)
|
|
2742
2952
|
};
|
|
2743
2953
|
blocks.push(newBlock);
|
|
2744
2954
|
contentIndex = blocks.length - 1;
|
|
2745
2955
|
params.setLastTextBlock({
|
|
2746
2956
|
block: newBlock,
|
|
2747
2957
|
index: contentIndex,
|
|
2748
|
-
phase
|
|
2958
|
+
phase,
|
|
2959
|
+
rendered
|
|
2749
2960
|
});
|
|
2750
2961
|
stream.push({
|
|
2751
2962
|
type: "text_start",
|
|
@@ -2754,6 +2965,7 @@ function createResponsesTerminalController(params) {
|
|
|
2754
2965
|
});
|
|
2755
2966
|
}
|
|
2756
2967
|
}
|
|
2968
|
+
recordCompletedText(contentIndex, rendered);
|
|
2757
2969
|
stream.push({
|
|
2758
2970
|
type: "text_end",
|
|
2759
2971
|
contentIndex,
|
|
@@ -2814,9 +3026,27 @@ function createResponsesTerminalController(params) {
|
|
|
2814
3026
|
}
|
|
2815
3027
|
for (const [terminalIndex, item] of items.entries()) if (item.type === "message") {
|
|
2816
3028
|
const tracked = params.outputs.get(item, terminalIndex);
|
|
2817
|
-
if (tracked?.completed)
|
|
2818
|
-
|
|
2819
|
-
|
|
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);
|
|
2820
3050
|
} else {
|
|
2821
3051
|
params.setLastTextBlock(null);
|
|
2822
3052
|
const alreadyCapturedCompaction = item.type === "compaction" && output.providerReplay?.type === "openai-responses-compaction" && output.providerReplay.id === item.id && output.providerReplay.data === item.encrypted_content;
|
|
@@ -2839,6 +3069,9 @@ function createResponsesTerminalController(params) {
|
|
|
2839
3069
|
};
|
|
2840
3070
|
const finalizeTerminalFacts = (response, responseId = response.id) => {
|
|
2841
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;
|
|
2842
3075
|
output.responseId = responseId || output.responseId;
|
|
2843
3076
|
output.responseModel = options?.resolveResponseModel ? options.resolveResponseModel()?.trim() || void 0 : response.model?.trim() || void 0;
|
|
2844
3077
|
const usage = mapResponsesTerminalUsage(response.usage);
|
|
@@ -2857,6 +3090,7 @@ function createResponsesTerminalController(params) {
|
|
|
2857
3090
|
};
|
|
2858
3091
|
else output.usage.usageReport = { state: "unavailable" };
|
|
2859
3092
|
calculateCost(model, output.usage);
|
|
3093
|
+
applyResponsesCacheWritePricing(output.usage, response.usage, options?.promptCacheTtl);
|
|
2860
3094
|
if (options?.applyServiceTierPricing) {
|
|
2861
3095
|
const tier = options.resolveServiceTier ? options.resolveServiceTier(response.service_tier, options.serviceTier) : response.service_tier ?? options.serviceTier;
|
|
2862
3096
|
options.applyServiceTierPricing(output.usage, tier);
|
|
@@ -2896,6 +3130,7 @@ function createResponsesTerminalController(params) {
|
|
|
2896
3130
|
finalizeFailedResponse: finalizeTerminalFacts,
|
|
2897
3131
|
recordIncompleteToolCall,
|
|
2898
3132
|
recoverTerminalOutput,
|
|
3133
|
+
recordCompletedText,
|
|
2899
3134
|
emitToolCallCompletion,
|
|
2900
3135
|
recordPendingReasoning,
|
|
2901
3136
|
releaseDeferredToolCompletions
|
|
@@ -2984,15 +3219,6 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
2984
3219
|
const materializeDeferredTextSlots = (except) => {
|
|
2985
3220
|
for (const slot of outputSlots.values()) if (slot !== except && slot.type === "text") materializeDeferredTextSlot(slot);
|
|
2986
3221
|
};
|
|
2987
|
-
const appendThinkingDelta = (slot, delta) => {
|
|
2988
|
-
appendAssistantThinking(slot.block, delta);
|
|
2989
|
-
stream.push({
|
|
2990
|
-
type: "thinking_delta",
|
|
2991
|
-
contentIndex: slot.contentIndex,
|
|
2992
|
-
delta,
|
|
2993
|
-
partial: output
|
|
2994
|
-
});
|
|
2995
|
-
};
|
|
2996
3222
|
const projectTextDelta = (slot, delta) => {
|
|
2997
3223
|
if (slot.pendingText !== null) appendResponsesPendingTextDelta(slot, delta, materializeDeferredTextSlot);
|
|
2998
3224
|
else if (slot.block && slot.contentIndex !== void 0) {
|
|
@@ -3060,7 +3286,7 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
3060
3286
|
complete();
|
|
3061
3287
|
};
|
|
3062
3288
|
};
|
|
3063
|
-
const guardedStream =
|
|
3289
|
+
const guardedStream = iterateModelStream(withFirstStreamEventTimeout(openaiStream, {
|
|
3064
3290
|
provider: model.provider,
|
|
3065
3291
|
api: model.api,
|
|
3066
3292
|
model: model.id,
|
|
@@ -3071,16 +3297,16 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
3071
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."
|
|
3072
3298
|
}), options?.signal);
|
|
3073
3299
|
try {
|
|
3074
|
-
for await (const
|
|
3075
|
-
|
|
3076
|
-
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);
|
|
3077
3303
|
if (event.type === "response.output_item.done" && event.item.type === "function_call" && event.item.status && event.item.status !== "completed" && !rejectedToolCall) try {
|
|
3078
3304
|
resolveCompletedResponsesToolCall(event.item);
|
|
3079
3305
|
} catch (error) {
|
|
3080
3306
|
terminal.recordIncompleteToolCall(event, event.item);
|
|
3081
3307
|
rejectedToolCall = { error };
|
|
3082
3308
|
}
|
|
3083
|
-
if (rejectedToolCall && event.type
|
|
3309
|
+
if (rejectedToolCall && !isResponsesTerminalEventType(event.type) && event.type !== "error") continue;
|
|
3084
3310
|
if (event.type === "response.created") output.responseId = event.response.id;
|
|
3085
3311
|
else if (event.type === "response.output_item.added") {
|
|
3086
3312
|
materializeDeferredTextSlots();
|
|
@@ -3104,6 +3330,7 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
3104
3330
|
argumentStreamReliable: true,
|
|
3105
3331
|
argumentsStreamed: false,
|
|
3106
3332
|
previewSchedule: createToolArgumentPreviewSchedule(),
|
|
3333
|
+
trailingWhitespaceChars: countToolCallTrailingWhitespace(toolCallBlock.partialJson),
|
|
3107
3334
|
...readResponsesToolCallItemIdentity(item)
|
|
3108
3335
|
};
|
|
3109
3336
|
streamingToolCalls.register(event, toolCallState);
|
|
@@ -3134,12 +3361,24 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
3134
3361
|
if (!lastPart) continue;
|
|
3135
3362
|
lastPart.text += delta;
|
|
3136
3363
|
}
|
|
3137
|
-
|
|
3364
|
+
appendAssistantThinking(slot.block, delta);
|
|
3365
|
+
stream.push({
|
|
3366
|
+
type: "thinking_delta",
|
|
3367
|
+
contentIndex: slot.contentIndex,
|
|
3368
|
+
delta,
|
|
3369
|
+
partial: output
|
|
3370
|
+
});
|
|
3138
3371
|
} else if (event.type === "response.content_part.added") {
|
|
3139
3372
|
const slot = outputSlots.resolve(event, "text");
|
|
3140
3373
|
if (!slot) continue;
|
|
3141
3374
|
slot.item.content = slot.item.content || [];
|
|
3142
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
|
+
}
|
|
3143
3382
|
} else if (event.type === "response.output_text.delta" || isAzureResponsesTextDeltaEvent(event) || event.type === "response.refusal.delta") {
|
|
3144
3383
|
const slot = outputSlots.resolve(event, "text");
|
|
3145
3384
|
if (!slot) continue;
|
|
@@ -3178,6 +3417,7 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
3178
3417
|
}
|
|
3179
3418
|
let delta;
|
|
3180
3419
|
if (event.type === "response.function_call_arguments.delta") {
|
|
3420
|
+
toolCall.trailingWhitespaceChars = countToolCallTrailingWhitespace(event.delta, toolCall.trailingWhitespaceChars);
|
|
3181
3421
|
toolCall.block.partialJson += event.delta;
|
|
3182
3422
|
toolCall.argumentsStreamed = true;
|
|
3183
3423
|
if (toolCall.previewSchedule(toolCall.block.partialJson.length)) toolCall.block.arguments = parseStreamingJson(toolCall.block.partialJson);
|
|
@@ -3186,6 +3426,7 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
3186
3426
|
const previousPartialJson = toolCall.block.partialJson;
|
|
3187
3427
|
const doneArguments = typeof event.arguments === "string" ? event.arguments : void 0;
|
|
3188
3428
|
if (doneArguments !== void 0 && (doneArguments.length > 0 || previousPartialJson === "")) {
|
|
3429
|
+
toolCall.trailingWhitespaceChars = countToolCallTrailingWhitespace(doneArguments);
|
|
3189
3430
|
toolCall.block.partialJson = doneArguments;
|
|
3190
3431
|
toolCall.block.arguments = parseStreamingJson(toolCall.block.partialJson);
|
|
3191
3432
|
toolCall.argumentStreamReliable = true;
|
|
@@ -3222,28 +3463,34 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
3222
3463
|
outputSlots.forget(outputSlot);
|
|
3223
3464
|
} else if (item.type === "message" && outputSlot?.type === "text" && (outputSlot.block || outputSlot.pendingText !== null)) {
|
|
3224
3465
|
const streamedText = outputSlot.pendingText ?? outputSlot.block?.text ?? "";
|
|
3225
|
-
const
|
|
3466
|
+
const rendered = renderResponsesMessageText(item.content ?? outputSlot.item.content ?? [{
|
|
3467
|
+
type: "text",
|
|
3468
|
+
text: streamedText
|
|
3469
|
+
}]);
|
|
3226
3470
|
const phase = item.phase ?? void 0;
|
|
3227
3471
|
const collapse = outputSlot.pendingText !== null ? resolveResponsesMessageSnapshotCollapse({
|
|
3228
3472
|
prior: outputSlot.collapseCandidate && {
|
|
3229
|
-
text: outputSlot.collapseCandidate.
|
|
3473
|
+
text: outputSlot.collapseCandidate.rendered.prose,
|
|
3230
3474
|
phase: outputSlot.collapseCandidate.phase
|
|
3231
3475
|
},
|
|
3232
|
-
nextText:
|
|
3476
|
+
nextText: rendered.prose,
|
|
3233
3477
|
nextPhase: phase
|
|
3234
3478
|
}) : { kind: "keep" };
|
|
3235
3479
|
outputSlot.pendingText = null;
|
|
3236
3480
|
if (collapse.kind === "extend" && outputSlot.collapseCandidate) {
|
|
3237
|
-
outputSlot.collapseCandidate.
|
|
3238
|
-
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);
|
|
3239
3485
|
stream.push({
|
|
3240
3486
|
type: "text_end",
|
|
3241
3487
|
contentIndex: outputSlot.collapseCandidate.index,
|
|
3242
|
-
content:
|
|
3488
|
+
content: extended.text,
|
|
3243
3489
|
partial: output
|
|
3244
3490
|
});
|
|
3245
3491
|
lastTextBlock = outputSlot.collapseCandidate;
|
|
3246
|
-
|
|
3492
|
+
terminal.recordCompletedText(outputSlot.collapseCandidate.index, extended);
|
|
3493
|
+
outputs.set(item, outputSlot.collapseCandidate.index, readResponsesOutputIndex(event) ?? outputSlot.outputIndex, true, rendered.prose);
|
|
3247
3494
|
} else {
|
|
3248
3495
|
if (!outputSlot.block) {
|
|
3249
3496
|
outputSlot.block = createTextBlock(item, "");
|
|
@@ -3255,16 +3502,18 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
3255
3502
|
partial: output
|
|
3256
3503
|
});
|
|
3257
3504
|
}
|
|
3258
|
-
outputSlot.block.text =
|
|
3259
|
-
outputSlot.block.textSignature =
|
|
3505
|
+
outputSlot.block.text = rendered.text;
|
|
3506
|
+
outputSlot.block.textSignature = responsesTextSignature(item.id, phase, rendered);
|
|
3260
3507
|
const contentIndex = outputSlot.contentIndex;
|
|
3261
3508
|
if (contentIndex === void 0) throw new Error("Responses stream finalized text without a content index");
|
|
3262
3509
|
lastTextBlock = {
|
|
3263
3510
|
block: outputSlot.block,
|
|
3264
3511
|
index: contentIndex,
|
|
3265
|
-
phase
|
|
3512
|
+
phase,
|
|
3513
|
+
rendered
|
|
3266
3514
|
};
|
|
3267
|
-
|
|
3515
|
+
terminal.recordCompletedText(contentIndex, rendered);
|
|
3516
|
+
outputs.set(item, contentIndex, readResponsesOutputIndex(event) ?? outputSlot.outputIndex, true, rendered.prose);
|
|
3268
3517
|
stream.push({
|
|
3269
3518
|
type: "text_end",
|
|
3270
3519
|
contentIndex,
|
|
@@ -3342,17 +3591,17 @@ function readOpenAIMisalignmentReview(value, continuationSupported) {
|
|
|
3342
3591
|
//#region packages/ai/src/providers/openai-responses-tools.ts
|
|
3343
3592
|
/** Projects direct provider descriptors before resolving their strict policy. */
|
|
3344
3593
|
function convertResponsesToolPayload(tools, options) {
|
|
3345
|
-
return convertPreparedResponsesTools(prepareOpenAITools(tools), resolveResponsesStrictToolSetting(options), options?.model);
|
|
3594
|
+
return convertPreparedResponsesTools(prepareOpenAITools(tools), resolveResponsesStrictToolSetting(options), options?.model, options?.mutableParameters);
|
|
3346
3595
|
}
|
|
3347
3596
|
/** The transport has already resolved policy before descriptor projection. */
|
|
3348
|
-
function prepareResponsesTools(tools, strictSetting, model) {
|
|
3597
|
+
function prepareResponsesTools(tools, strictSetting, model, mutableParameters) {
|
|
3349
3598
|
const prepared = prepareOpenAITools(tools);
|
|
3350
3599
|
return {
|
|
3351
3600
|
projection: prepared.projection,
|
|
3352
|
-
tools: convertPreparedResponsesTools(prepared, strictSetting, model)
|
|
3601
|
+
tools: convertPreparedResponsesTools(prepared, strictSetting, model, mutableParameters)
|
|
3353
3602
|
};
|
|
3354
3603
|
}
|
|
3355
|
-
function convertPreparedResponsesTools(prepared, strictSetting, model) {
|
|
3604
|
+
function convertPreparedResponsesTools(prepared, strictSetting, model, mutableParameters) {
|
|
3356
3605
|
const { projection, schemas } = prepared;
|
|
3357
3606
|
return withPreparedToolSchemaNormalization(schemas, () => {
|
|
3358
3607
|
const strict = model ? resolveOpenAIStrictToolFlagWithDiagnostics(projection, strictSetting, {
|
|
@@ -3360,7 +3609,7 @@ function convertPreparedResponsesTools(prepared, strictSetting, model) {
|
|
|
3360
3609
|
model
|
|
3361
3610
|
}) : resolveOpenAIProjectedToolsStrictToolFlag(projection, strictSetting);
|
|
3362
3611
|
return sortPromptCacheToolsByName(projection.tools).map((tool) => {
|
|
3363
|
-
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;
|
|
3364
3613
|
});
|
|
3365
3614
|
});
|
|
3366
3615
|
}
|
|
@@ -3368,7 +3617,7 @@ function resolveResponsesStrictToolSetting(options) {
|
|
|
3368
3617
|
if (options?.strict !== void 0) return options.strict;
|
|
3369
3618
|
if (options?.model) return getAiTransportHost().resolveOpenAIStrictToolSetting(options.model, {
|
|
3370
3619
|
transport: "stream",
|
|
3371
|
-
supportsStrictMode:
|
|
3620
|
+
supportsStrictMode: resolveOpenAICompletionsCompat(options.model).supportsStrictMode
|
|
3372
3621
|
});
|
|
3373
3622
|
return false;
|
|
3374
3623
|
}
|
|
@@ -3393,7 +3642,10 @@ function applyCommonResponsesParams(params, model, context, options, config) {
|
|
|
3393
3642
|
format: resolveOpenAIResponsesTextFormat(options.responseFormat)
|
|
3394
3643
|
};
|
|
3395
3644
|
if (context.tools) {
|
|
3396
|
-
const tools = convertResponsesToolPayload(context.tools, {
|
|
3645
|
+
const tools = convertResponsesToolPayload(context.tools, {
|
|
3646
|
+
model,
|
|
3647
|
+
mutableParameters: Boolean(options?.onPayload)
|
|
3648
|
+
});
|
|
3397
3649
|
if (tools.length > 0) params.tools = tools;
|
|
3398
3650
|
}
|
|
3399
3651
|
if (!model.reasoning) return;
|
|
@@ -3401,17 +3653,11 @@ function applyCommonResponsesParams(params, model, context, options, config) {
|
|
|
3401
3653
|
const effort = requestedEffort === void 0 ? void 0 : resolveOpenAIRequestReasoning(model, requestedEffort).effort;
|
|
3402
3654
|
if (effort === void 0) return;
|
|
3403
3655
|
params.reasoning = { effort };
|
|
3404
|
-
if (effort !== "none" && (options?.reasoningEffort || options?.reasoningSummary)) {
|
|
3405
|
-
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;
|
|
3406
3658
|
params.include = ["reasoning.encrypted_content"];
|
|
3407
3659
|
}
|
|
3408
3660
|
}
|
|
3409
|
-
function cleanStreamingScratchBuffers(output) {
|
|
3410
|
-
for (const block of output.content) {
|
|
3411
|
-
delete block.index;
|
|
3412
|
-
if (block.type === "toolCall") delete block.partialJson;
|
|
3413
|
-
}
|
|
3414
|
-
}
|
|
3415
3661
|
async function runResponsesStreamLifecycle(params) {
|
|
3416
3662
|
const { stream, output, options } = params;
|
|
3417
3663
|
let firstEventAbort;
|
|
@@ -3423,6 +3669,12 @@ async function runResponsesStreamLifecycle(params) {
|
|
|
3423
3669
|
let request = params.buildParams(model, replayMode);
|
|
3424
3670
|
const nextRequest = await options?.onPayload?.(request, model);
|
|
3425
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
|
+
}
|
|
3426
3678
|
return request;
|
|
3427
3679
|
};
|
|
3428
3680
|
const requestParams = await buildRequest("checkpoint");
|
|
@@ -3467,19 +3719,16 @@ async function runResponsesStreamLifecycle(params) {
|
|
|
3467
3719
|
});
|
|
3468
3720
|
const firstEventTimeoutMs = getFirstStreamEventTimeoutMs(options);
|
|
3469
3721
|
const onFirstEventTimeout = getFirstStreamEventTimeoutHandler(options);
|
|
3470
|
-
const processStreamOptions = params.processStreamOptions || firstEventTimeoutMs !== void 0 || onFirstEventTimeout !== void 0 ? {
|
|
3471
|
-
...params.processStreamOptions,
|
|
3472
|
-
firstEventTimeoutMs: params.processStreamOptions?.firstEventTimeoutMs ?? firstEventTimeoutMs,
|
|
3473
|
-
abortFirstEventStream: params.processStreamOptions?.abortFirstEventStream ?? firstEventAbort.abort,
|
|
3474
|
-
onFirstEventTimeout: params.processStreamOptions?.onFirstEventTimeout ?? onFirstEventTimeout,
|
|
3475
|
-
signal: params.processStreamOptions?.signal ?? options?.signal
|
|
3476
|
-
} : void 0;
|
|
3477
3722
|
const terminal = await processResponsesStream(hookedOpenAIStream, output, stream, model, {
|
|
3478
|
-
...processStreamOptions
|
|
3479
|
-
|
|
3480
|
-
|
|
3481
|
-
|
|
3482
|
-
|
|
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),
|
|
3483
3732
|
onServiceTier: (responseTier, response) => responsesServiceTierObserver.observe(options, requestedTier, responseTier, response),
|
|
3484
3733
|
canRetryIdentityConflict: () => hasOnlyResponsesFunctionTools(admittedRequest),
|
|
3485
3734
|
reasoningReplayMetadata: buildOpenAIResponsesReasoningReplayMetadata(model, {
|
|
@@ -3512,12 +3761,11 @@ async function runResponsesStreamLifecycle(params) {
|
|
|
3512
3761
|
stream,
|
|
3513
3762
|
output,
|
|
3514
3763
|
signal: options?.signal,
|
|
3515
|
-
error
|
|
3516
|
-
cleanup: () => cleanStreamingScratchBuffers(output)
|
|
3764
|
+
error
|
|
3517
3765
|
});
|
|
3518
3766
|
} finally {
|
|
3519
3767
|
firstEventAbort?.dispose();
|
|
3520
3768
|
}
|
|
3521
3769
|
}
|
|
3522
3770
|
//#endregion
|
|
3523
|
-
export { isConfigurationUpdate as $, summarizeResponsesPayload as A,
|
|
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 };
|