@openclaw/ai 2026.11.5-beta.4 → 2026.11.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.source-module-urls/fe058cc430242ce2ab0dfbcbe153e240a52cf9c3072c3dc0a73e5f956b6ba49b.json +1 -1
- package/dist/{anthropic-c499kyoI.mjs → anthropic-BNkSFJGp.mjs} +5 -5
- package/dist/{anthropic-payload-policy-DVk38bnY.d.mts → anthropic-payload-policy-DxijyMFH.d.mts} +3 -3
- package/dist/{anthropic-stream-lifecycle-KkyqdnjW.mjs → anthropic-stream-lifecycle-Dp5TblwC.mjs} +9 -10
- package/dist/{anthropic-tool-projection-DKAlondV.d.mts → anthropic-tool-projection-DX_igbpX.d.mts} +1 -1
- package/dist/{anthropic-tool-projection-DcvsDiyX.mjs → anthropic-tool-projection-DpN77rtb.mjs} +1 -1
- package/dist/{api-registry-DY2MLUyg.d.mts → api-registry-CCdcCPSA.d.mts} +2 -2
- package/dist/{assistant-output-C3czmoN4.mjs → assistant-output-BEE6TWdj.mjs} +1 -1
- package/dist/{azure-openai-responses-client-compat-D0dvJMbZ.mjs → azure-deployment-map-DKJ8Xc4c.mjs} +1 -14
- package/dist/{azure-openai-responses-CyuUQ3JJ.mjs → azure-openai-responses-BjX0owXR.mjs} +6 -6
- package/dist/azure-openai-responses-client-compat-a5PrPIdL.mjs +14 -0
- package/dist/diagnostics.d.mts +3 -3
- package/dist/{event-stream-BYmtRe8-.d.mts → event-stream-CDyUvxkI.d.mts} +1 -1
- package/dist/event-stream-X0f18GAs.d.mts +1 -0
- package/dist/event-stream.d.mts +2 -2
- package/dist/{google-DqG05iBa.mjs → google-BJwjWpAX.mjs} +2 -2
- package/dist/{google-interactions-B_xZUObF.mjs → google-interactions-BEOEOp0d.mjs} +10 -10
- package/dist/{google-messages-p2iBzsAp.mjs → google-messages-Bja86PP8.mjs} +3 -3
- package/dist/{google-provider-stream-DZ6tqteU.mjs → google-provider-stream-GYgtu60C.mjs} +6 -6
- package/dist/{google-shared-BMYt1xSI.mjs → google-shared-7sAuYDNq.mjs} +5 -5
- package/dist/{google-vertex-CAq2q1Ln.mjs → google-vertex-2zavNJkj.mjs} +2 -2
- package/dist/{host-ccbwPC3A.d.mts → host-C2_6_j-L.d.mts} +3 -3
- package/dist/{host-DqX-64Pb.mjs → host-DZ29cEYd.mjs} +1 -1
- package/dist/{host-policy-Bk85E9ue.mjs → host-policy-DqFgGiV6.mjs} +1 -1
- package/dist/{index-Bczt0MnO.d.mts → index-DkF8J4yH.d.mts} +3 -3
- package/dist/index.d.mts +6 -6
- package/dist/index.mjs +2 -2
- package/dist/internal/anthropic.d.mts +6 -6
- package/dist/internal/anthropic.mjs +4 -4
- package/dist/internal/google.d.mts +3 -3
- package/dist/internal/google.mjs +1 -1
- package/dist/internal/openai-completions-compat.d.mts +1 -1
- package/dist/internal/openai-completions-compat.mjs +1 -1
- package/dist/internal/openai-responses-payload-policy.d.mts +1 -1
- package/dist/internal/openai-responses-payload-policy.mjs +2 -2
- package/dist/internal/openai.d.mts +10 -10
- package/dist/internal/openai.mjs +10 -9
- package/dist/internal/runtime.d.mts +8 -8
- package/dist/internal/runtime.mjs +4 -4
- package/dist/internal/shared.d.mts +8 -8
- package/dist/internal/shared.mjs +3 -3
- package/dist/internal/tool-schema.d.mts +2 -2
- package/dist/internal/tool-schema.mjs +3 -3
- package/dist/{mistral-DIGInqJI.mjs → mistral-CjTsnfIz.mjs} +8 -8
- package/dist/{openai-chatgpt-responses-B-MopEDG.mjs → openai-chatgpt-responses-BinD_u6y.mjs} +13 -18
- package/dist/{openai-completions-B62Yg3hQ.mjs → openai-completions-B380Vg0n.mjs} +3 -3
- package/dist/{openai-completions-compat-CJ-NsDzg.d.mts → openai-completions-compat-CEj778te.d.mts} +3 -3
- package/dist/{openai-completions-compat-CS3dlDBR.mjs → openai-completions-compat-CmyT3piu.mjs} +2 -2
- package/dist/{openai-completions-transport-BQ8dr3FV.mjs → openai-completions-transport-BGoKrb3z.mjs} +59 -440
- package/dist/{openai-tool-schema-CvxySRyf.mjs → openai-function-tool-DUT14vv6.mjs} +22 -22
- package/dist/{openai-prompt-cache-BZGaIWYh.d.mts → openai-prompt-cache-C_XCgsDn.d.mts} +2 -2
- package/dist/{openai-prompt-cache-3H_Fz0ya.mjs → openai-prompt-cache-DV1t-7dP.mjs} +1 -1
- package/dist/{openai-responses-VUkMi_Bc.mjs → openai-responses-ClgomgWG.mjs} +6 -7
- package/dist/{openai-responses-compaction-replay-DXF5BjD2.d.mts → openai-responses-compaction-replay-6MNmDBBu.d.mts} +6 -5
- package/dist/{openai-responses-contracts-xU-n9AJJ.mjs → openai-responses-contracts-BpyK1Ygq.mjs} +1 -1
- package/dist/{openai-responses-contracts-Cb1IIRRG.d.mts → openai-responses-contracts-D-saZnr_.d.mts} +5 -5
- package/dist/{openai-responses-endpoint-CqO3ejTe.mjs → openai-responses-endpoint-BGwjxesS.mjs} +1 -1
- package/dist/{openai-responses-request-lifecycle-DNITxJPO.mjs → openai-responses-request-lifecycle-pjoJ2KB8.mjs} +6 -6
- package/dist/{openai-responses-shared-WMDQDwC6.mjs → openai-responses-shared-BE2zSjin.mjs} +2034 -1926
- package/dist/{openai-responses-terminal-usage-D7IhRA6i.d.mts → openai-responses-terminal-usage-CuXS9TCK.d.mts} +2 -2
- package/dist/openai-responses-websocket-Bzo4ykRX.mjs +385 -0
- package/dist/{otel-B2u5HGvm.mjs → otel-VKlSbm9p.mjs} +1 -1
- package/dist/{provider-options-BQ2Msop2.d.mts → provider-options-Bo0XJEeK.d.mts} +3 -3
- package/dist/{provider-replay-context-5gFUstgv.mjs → provider-replay-context-BAwe7OIR.mjs} +3 -4
- package/dist/{provider-transcript-transform-Hr1kCoMX.mjs → provider-transcript-transform-BA4B0NIr.mjs} +1 -1
- package/dist/{provider-transport-turn-state-d1uIBP1i.mjs → provider-transport-turn-state-BU7KCpkK.mjs} +22 -4
- package/dist/{provider-types-B1e98js5.d.mts → provider-types-wHqA9oSz.d.mts} +3 -3
- package/dist/provider-types.d.mts +5 -5
- package/dist/providers.d.mts +2 -2
- package/dist/providers.mjs +10 -10
- package/dist/{sanitize-unicode-BISmUlUv.d.mts → sanitize-unicode-D0B2CDXP.d.mts} +2 -2
- package/dist/{simple-options-CQNPKCEb.mjs → simple-options-BPzChce1.mjs} +3 -3
- package/dist/{stream-DM-q0y5H.mjs → stream-WbisbzUF.mjs} +1 -1
- package/dist/{telemetry-DJibfNKZ.mjs → telemetry-BS2h0FVa.mjs} +2 -2
- package/dist/{tool-schema-json-projection-BSHb4gaJ.mjs → tool-schema-json-projection-C9KSjPuG.mjs} +1 -1
- package/dist/{transport-stream-shared-D3IAU4jn.d.mts → transport-stream-shared-Cwd9ZIqy.d.mts} +4 -4
- package/dist/{transport-stream-shared-CBVh6QEc.mjs → transport-stream-shared-DtOk207K.mjs} +1 -1
- package/dist/{transport-utils-rxOHnq9y.mjs → transport-utils-Czu6bnbQ.mjs} +2 -2
- package/dist/transports.d.mts +15 -14
- package/dist/transports.mjs +14 -14
- package/dist/{types-BVdTf0YV.d.mts → types-DrqxFIh9.d.mts} +5 -0
- package/dist/types-g3molYjD.d.mts +1 -0
- package/dist/types.d.mts +5 -5
- package/dist/{validation-QmyD0E5A.d.mts → validation-ByHJvdN2.d.mts} +1 -1
- package/dist/validation.d.mts +1 -1
- package/package.json +1 -1
- package/dist/event-stream-B4ZcSvsu.d.mts +0 -1
- package/dist/types-Cb3-5WM9.d.mts +0 -1
|
@@ -6,30 +6,30 @@ import { i as asOptionalRecord, o as isRecord, s as isStringArray } from "./reco
|
|
|
6
6
|
import { l as readStringValue, o as normalizeOptionalString, r as normalizeLowercaseStringOrEmpty, s as normalizeStringifiedOptionalString } from "./string-coerce-BCuWMIrk.mjs";
|
|
7
7
|
import { t as asFiniteNumber } from "./number-coercion-C7HsBgUL.mjs";
|
|
8
8
|
import { t as observeAsyncIterator } from "./observe-async-iterator-DgmegcZR.mjs";
|
|
9
|
-
import { A as applyProviderReportedUsageCost, I as isImageWithMediaPayload, M as clampThinkingLevel, a as resolveAiTransportHeaderSentinels, j as calculateCost, k as headersToRecord, r as getAiTransportHost } from "./host-
|
|
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-
|
|
9
|
+
import { A as applyProviderReportedUsageCost, I as isImageWithMediaPayload, M as clampThinkingLevel, a as resolveAiTransportHeaderSentinels, j as calculateCost, k as headersToRecord, m as resolveFailedAssistantReplay, r as getAiTransportHost } from "./host-DZ29cEYd.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-BpyK1Ygq.mjs";
|
|
11
11
|
import { n as getSessionResourceOwnerId, r as registerSessionResourceCleanup } from "./session-resources-vKvGIE3J.mjs";
|
|
12
12
|
import { r as readTransportDiagnosticLabel } from "./provider-error-DD-fo4Rz.mjs";
|
|
13
13
|
import "./src-BUsVkrNt.mjs";
|
|
14
|
-
import { n as clampOpenAIPromptCacheKey } from "./openai-prompt-cache-
|
|
14
|
+
import { n as clampOpenAIPromptCacheKey } from "./openai-prompt-cache-DV1t-7dP.mjs";
|
|
15
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-
|
|
16
|
+
import { n as isCodeModeModelVisibleToolName } from "./transport-utils-Czu6bnbQ.mjs";
|
|
17
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-
|
|
19
|
-
import { r as resolveModelRequestTimeoutMs } from "./host-policy-
|
|
18
|
+
import { a as resolveOpenAICompletionsCompat, n as isKnownOpenAIEndpoint, s as usesNativeOpenAICodexResponsesBackend, u as resolveOpenAIResponsesTextFormat } from "./openai-completions-compat-CmyT3piu.mjs";
|
|
19
|
+
import { r as resolveModelRequestTimeoutMs } from "./host-policy-DqFgGiV6.mjs";
|
|
20
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-
|
|
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-
|
|
23
|
-
import { C as sha256Hex, S as redactIdentifier, n as prepareRuntimeToolInputSchema, r as projectRuntimeToolInputSchema, w as sha256StableValue } from "./tool-schema-json-projection-
|
|
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-BPzChce1.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-DtOk207K.mjs";
|
|
23
|
+
import { C as sha256Hex, S as redactIdentifier, n as prepareRuntimeToolInputSchema, r as projectRuntimeToolInputSchema, w as sha256StableValue } from "./tool-schema-json-projection-C9KSjPuG.mjs";
|
|
24
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-
|
|
26
|
-
import { t as transformProviderMessages } from "./provider-transcript-transform-
|
|
25
|
+
import { n as isProviderReplayContext, r as providerReplayContextMatches, t as buildProviderReplayContext } from "./provider-replay-context-BAwe7OIR.mjs";
|
|
26
|
+
import { t as transformProviderMessages } from "./provider-transcript-transform-BA4B0NIr.mjs";
|
|
27
27
|
import { prepareModelRequestBody } from "./internal/model-request-body.mjs";
|
|
28
|
-
import "./assistant-output-
|
|
28
|
+
import "./assistant-output-BEE6TWdj.mjs";
|
|
29
29
|
import { n as resolveOpencodeSessionHeaders } from "./session-affinity-DA4WHv1h.mjs";
|
|
30
|
+
import { a as isOpenAIResponsesCompactionOutput, n as supportsNativeOpenAIResponsesEndpoint, o as readOpenAIResponsesCompactionWindow, s as buildResponsesInputImage } from "./openai-responses-endpoint-BGwjxesS.mjs";
|
|
31
|
+
import { h as withPreparedToolSchemaNormalization, i as normalizeOpenAIStrictToolParameters, n as findOpenAIStrictToolProjectionDiagnostics, o as resolveOpenAIProjectedToolsStrictToolFlag, t as prepareOpenAIFunctionTool } from "./openai-function-tool-DUT14vv6.mjs";
|
|
30
32
|
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-CvxySRyf.mjs";
|
|
32
|
-
import { a as isOpenAIResponsesCompactionOutput, n as supportsNativeOpenAIResponsesEndpoint, o as readOpenAIResponsesCompactionWindow, s as buildResponsesInputImage } from "./openai-responses-endpoint-CqO3ejTe.mjs";
|
|
33
33
|
import { randomUUID } from "node:crypto";
|
|
34
34
|
import { isDeepStrictEqual } from "node:util";
|
|
35
35
|
import { isProxy } from "node:util/types";
|
|
@@ -352,1529 +352,1929 @@ function readOpenAICompletionsContentPartDeltas(content) {
|
|
|
352
352
|
return [];
|
|
353
353
|
}
|
|
354
354
|
//#endregion
|
|
355
|
-
//#region packages/ai/src/
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
355
|
+
//#region packages/ai/src/transports/openai-responses-compaction-replay.ts
|
|
356
|
+
const OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE = "openai-responses-compaction-suppression";
|
|
357
|
+
const OPENAI_RESPONSES_COMPACTION_SUPPRESSION_DATA = "rejected";
|
|
358
|
+
function isOpenAIResponsesCompactionState(state) {
|
|
359
|
+
if (typeof state.baseUrlHash !== "string" || state.v !== 1) return false;
|
|
360
|
+
if (state.type === OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE) return state.data === OPENAI_RESPONSES_COMPACTION_SUPPRESSION_DATA;
|
|
361
|
+
const retained = state.type === OPENAI_RESPONSES_RETAINED_COMPACTION_REPLAY_TYPE;
|
|
362
|
+
return (retained || state.type === "openai-responses-compaction") && typeof state.data === "string" && state.data.length > 0 && (state.id === void 0 || typeof state.id === "string") && (state.replayIndex === void 0 || !retained && typeof state.replayIndex === "number" && Number.isSafeInteger(state.replayIndex) && state.replayIndex >= 0);
|
|
363
|
+
}
|
|
364
|
+
function readOpenAIResponsesCompactionReplayState(value) {
|
|
365
|
+
return isRecord(value) && isProviderReplayContext(value) && isOpenAIResponsesCompactionState(value) ? value : void 0;
|
|
366
|
+
}
|
|
367
|
+
function readOpenAIResponsesItemRecoveryAnchor(replay) {
|
|
368
|
+
const state = readOpenAIResponsesCompactionReplayState(replay);
|
|
369
|
+
return state?.type === OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE && typeof state.itemRecovery === "string" ? state.itemRecovery : void 0;
|
|
370
|
+
}
|
|
371
|
+
function captureOpenAIResponsesCompaction(output, item, boundary, model, captureMetadata, compactedOutput, outputTokens) {
|
|
372
|
+
const metadata = captureMetadata ?? buildOpenAIResponsesReasoningReplayMetadata(model);
|
|
373
|
+
if (!item.encrypted_content) return;
|
|
374
|
+
if (!metadata?.baseUrlHash) {
|
|
375
|
+
log.debug("[responses] skipping compaction capture: missing base URL hash");
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
const currentReplay = readOpenAIResponsesCompactionReplayState(output.providerReplay);
|
|
379
|
+
if (typeof boundary === "number" && currentReplay?.type === "openai-responses-compaction" && (currentReplay.replayIndex ?? -1) > boundary) return;
|
|
380
|
+
if (compactedOutput && !isOpenAIResponsesCompactionOutput(compactedOutput, model)) throw new Error("Responses compact endpoint checkpoint is invalid");
|
|
381
|
+
const replay = {
|
|
382
|
+
v: 1,
|
|
383
|
+
...boundary === "retained-users" ? { type: OPENAI_RESPONSES_RETAINED_COMPACTION_REPLAY_TYPE } : {
|
|
384
|
+
type: OPENAI_RESPONSES_COMPACTION_REPLAY_TYPE,
|
|
385
|
+
replayIndex: boundary
|
|
386
|
+
},
|
|
387
|
+
...item.id ? { id: item.id } : {},
|
|
388
|
+
data: item.encrypted_content,
|
|
389
|
+
provider: metadata.provider,
|
|
390
|
+
api: metadata.api,
|
|
391
|
+
model: metadata.model,
|
|
392
|
+
baseUrlHash: metadata.baseUrlHash,
|
|
393
|
+
...metadata.sessionHash ? { sessionHash: metadata.sessionHash } : {},
|
|
394
|
+
...compactedOutput ? { compactedWindow: {
|
|
395
|
+
state: "ready",
|
|
396
|
+
output: JSON.stringify(compactedOutput),
|
|
397
|
+
...outputTokens !== void 0 ? { outputTokens } : {}
|
|
398
|
+
} } : {}
|
|
360
399
|
};
|
|
400
|
+
if (compactedOutput && !readOpenAIResponsesCompactionWindow(replay, model)) throw new Error("Responses compact endpoint checkpoint is invalid or exceeds 16 MiB");
|
|
401
|
+
output.providerReplay = replay;
|
|
361
402
|
}
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
403
|
+
function suppressOpenAIResponsesCompaction(output, model, options, rejectedCheckpoint, itemRecovery) {
|
|
404
|
+
const context = buildProviderReplayContext(model, options);
|
|
405
|
+
if (!context.baseUrlHash) return;
|
|
406
|
+
output.providerReplay = {
|
|
407
|
+
v: 1,
|
|
408
|
+
type: OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE,
|
|
409
|
+
data: OPENAI_RESPONSES_COMPACTION_SUPPRESSION_DATA,
|
|
410
|
+
...context,
|
|
411
|
+
baseUrlHash: context.baseUrlHash,
|
|
412
|
+
...itemRecovery ? { itemRecovery } : {}
|
|
413
|
+
};
|
|
414
|
+
if (rejectedCheckpoint) options?.onCompactionRejected?.(rejectedCheckpoint);
|
|
365
415
|
}
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
const schemas = /* @__PURE__ */ new Map();
|
|
416
|
+
function createCompactionTracker(output, model, options) {
|
|
417
|
+
const replayIndexes = /* @__PURE__ */ new Map();
|
|
369
418
|
return {
|
|
370
|
-
|
|
371
|
-
|
|
419
|
+
added(item, replayIndex) {
|
|
420
|
+
if (item.type === "compaction" && item.id) replayIndexes.set(item.id, replayIndex);
|
|
421
|
+
},
|
|
422
|
+
completed(item, fallbackReplayIndex) {
|
|
423
|
+
if (item.type !== "compaction" || !item.encrypted_content) return;
|
|
424
|
+
captureOpenAIResponsesCompaction(output, {
|
|
425
|
+
type: "compaction",
|
|
426
|
+
...item.id ? { id: item.id } : {},
|
|
427
|
+
encrypted_content: item.encrypted_content
|
|
428
|
+
}, (item.id ? replayIndexes.get(item.id) : void 0) ?? fallbackReplayIndex, model, options?.reasoningReplayMetadata);
|
|
429
|
+
if (item.id) replayIndexes.delete(item.id);
|
|
430
|
+
}
|
|
372
431
|
};
|
|
373
432
|
}
|
|
374
|
-
function
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
try {
|
|
393
|
-
const candidate = tools[toolIndex];
|
|
394
|
-
if (!candidate) {
|
|
395
|
-
diagnostics.push(unreadableToolDiagnostic(toolIndex));
|
|
396
|
-
continue;
|
|
397
|
-
}
|
|
398
|
-
tool = candidate;
|
|
399
|
-
readPath += ".name";
|
|
400
|
-
const nameValue = tool.name;
|
|
401
|
-
if (typeof nameValue !== "string" || !nameValue) {
|
|
402
|
-
diagnostics.push({
|
|
403
|
-
toolIndex,
|
|
404
|
-
violations: [`${readPath} is empty`]
|
|
405
|
-
});
|
|
406
|
-
continue;
|
|
407
|
-
}
|
|
408
|
-
name = nameValue;
|
|
409
|
-
readPath = `${name}.parameters`;
|
|
410
|
-
parameters = tool.parameters;
|
|
411
|
-
} catch {
|
|
412
|
-
diagnostics.push({
|
|
413
|
-
toolIndex,
|
|
414
|
-
...name ? { toolName: name } : {},
|
|
415
|
-
violations: [`${readPath} is unreadable`]
|
|
416
|
-
});
|
|
433
|
+
function isSafeResponsesReplayItemId(id) {
|
|
434
|
+
return typeof id === "string" && id.length > 0 && id.length <= 64;
|
|
435
|
+
}
|
|
436
|
+
function resolveNewestOpenAIResponsesCompactionReplay(messages, model, options) {
|
|
437
|
+
const context = buildProviderReplayContext(model, options);
|
|
438
|
+
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
|
439
|
+
const message = messages[index];
|
|
440
|
+
if (message?.role !== "assistant") continue;
|
|
441
|
+
const replay = readOpenAIResponsesCompactionReplayState(message.providerReplay);
|
|
442
|
+
if (replay?.type === OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE) {
|
|
443
|
+
if (providerReplayContextMatches(replay, typeof replay.itemRecovery === "string" ? {
|
|
444
|
+
...context,
|
|
445
|
+
sessionHash: replay.sessionHash
|
|
446
|
+
} : context)) return typeof replay.itemRecovery === "string" ? {
|
|
447
|
+
owner: message,
|
|
448
|
+
mode: "item-recovery",
|
|
449
|
+
anchor: replay.itemRecovery
|
|
450
|
+
} : void 0;
|
|
417
451
|
continue;
|
|
418
452
|
}
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
if (!isRecord(schemaProjection.schema) || schemaProjection.violations.length > 0) {
|
|
422
|
-
diagnostics.push({
|
|
423
|
-
toolIndex,
|
|
424
|
-
toolName: name,
|
|
425
|
-
violations: schemaProjection.violations.length > 0 ? schemaProjection.violations : [`${name}.parameters must be a JSON object schema`]
|
|
426
|
-
});
|
|
453
|
+
if (replay?.type !== "openai-responses-compaction" && replay?.type !== "openai-responses-retained-compaction") {
|
|
454
|
+
if (message.providerReplay?.type === "openai-responses-compaction" || message.providerReplay?.type === "openai-responses-retained-compaction") return;
|
|
427
455
|
continue;
|
|
428
456
|
}
|
|
429
|
-
if (
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
457
|
+
if (!providerReplayContextMatches(replay, context)) return;
|
|
458
|
+
if (replay.compactedWindow !== void 0 || replay.type === "openai-responses-retained-compaction") {
|
|
459
|
+
const output = readOpenAIResponsesCompactionWindow(replay, model);
|
|
460
|
+
const item = output?.at(-1);
|
|
461
|
+
if (!output || item?.type !== "compaction") return {
|
|
462
|
+
owner: message,
|
|
463
|
+
mode: "refresh-required"
|
|
464
|
+
};
|
|
465
|
+
return {
|
|
466
|
+
owner: message,
|
|
467
|
+
mode: "complete-window",
|
|
468
|
+
output,
|
|
469
|
+
...replay.compactedWindow?.state === "ready" && replay.compactedWindow.outputTokens !== void 0 ? { outputTokens: replay.compactedWindow.outputTokens } : {},
|
|
470
|
+
item,
|
|
471
|
+
replayIndex: replay.type === "openai-responses-retained-compaction" ? message.content.length : replay.replayIndex ?? 0
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
return {
|
|
475
|
+
owner: message,
|
|
476
|
+
item: {
|
|
477
|
+
type: "compaction",
|
|
478
|
+
...isSafeResponsesReplayItemId(replay.id) ? { id: replay.id } : {},
|
|
479
|
+
encrypted_content: replay.data
|
|
480
|
+
},
|
|
481
|
+
mode: "compacted-prefix",
|
|
482
|
+
replayIndex: replay.replayIndex ?? 0
|
|
483
|
+
};
|
|
441
484
|
}
|
|
442
|
-
return {
|
|
443
|
-
inputToolCount,
|
|
444
|
-
tools: projectedTools,
|
|
445
|
-
diagnostics
|
|
446
|
-
};
|
|
447
485
|
}
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
if (projection.tools.length === 0) throw new Error(`${label} tool_choice requires a tool, but no tools survived schema conversion`);
|
|
453
|
-
return choice;
|
|
454
|
-
}
|
|
455
|
-
if (choice === "none" || !isRecord(choice)) return choice;
|
|
456
|
-
const choiceType = choice.type;
|
|
457
|
-
if (!responses && choiceType === "custom") throw new Error("OpenAI Chat Completions custom tool_choice is unsupported because this adapter emits function tools only");
|
|
458
|
-
if (choiceType === "function") {
|
|
459
|
-
const functionChoice = responses ? choice : choice.function;
|
|
460
|
-
const functionName = isRecord(functionChoice) ? functionChoice.name : void 0;
|
|
461
|
-
if (typeof functionName !== "string") return choice;
|
|
462
|
-
if (!projection.tools.some((tool) => tool.name === functionName)) throw new Error(`${label} tool_choice requested unavailable tool "${functionName}" after schema conversion`);
|
|
463
|
-
return responses ? {
|
|
464
|
-
type: "function",
|
|
465
|
-
name: functionName
|
|
466
|
-
} : {
|
|
467
|
-
type: "function",
|
|
468
|
-
function: { name: functionName }
|
|
469
|
-
};
|
|
486
|
+
var CompactionReplayRefreshRequiredError = class extends Error {
|
|
487
|
+
constructor() {
|
|
488
|
+
super("Provider compaction checkpoint needs rebuilding. Run /compact to rebuild from saved conversation history.");
|
|
489
|
+
this.name = "CompactionReplayRefreshRequiredError";
|
|
470
490
|
}
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
if (
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
const
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
491
|
+
};
|
|
492
|
+
function buildOpenAIResponsesCompactionReplayPlan(messages, model, options) {
|
|
493
|
+
if (typeof options?.mode === "object") return {
|
|
494
|
+
messages,
|
|
495
|
+
preserveUnframedToolResults: false,
|
|
496
|
+
itemRecovery: { anchor: options.mode.itemRecovery }
|
|
497
|
+
};
|
|
498
|
+
const compaction = resolveNewestOpenAIResponsesCompactionReplay(messages, model, options);
|
|
499
|
+
if (!compaction) return {
|
|
500
|
+
messages,
|
|
501
|
+
preserveUnframedToolResults: false
|
|
502
|
+
};
|
|
503
|
+
if (compaction.mode === "item-recovery") {
|
|
504
|
+
const owner = compaction.owner;
|
|
505
|
+
let replayMessages = messages;
|
|
506
|
+
if (resolveFailedAssistantReplay(owner, { pairingAware: false }) === "drop") {
|
|
507
|
+
const boundary = {
|
|
508
|
+
role: "assistant",
|
|
509
|
+
content: [],
|
|
510
|
+
stopReason: "stop",
|
|
511
|
+
api: owner.api,
|
|
512
|
+
provider: owner.provider,
|
|
513
|
+
model: owner.model,
|
|
514
|
+
usage: owner.usage,
|
|
515
|
+
timestamp: owner.timestamp,
|
|
516
|
+
providerReplay: owner.providerReplay
|
|
517
|
+
};
|
|
518
|
+
replayMessages = [...messages];
|
|
519
|
+
replayMessages.splice(messages.indexOf(owner), 0, boundary);
|
|
494
520
|
}
|
|
521
|
+
return {
|
|
522
|
+
messages: replayMessages,
|
|
523
|
+
preserveUnframedToolResults: false,
|
|
524
|
+
itemRecovery: { anchor: compaction.anchor }
|
|
525
|
+
};
|
|
495
526
|
}
|
|
496
|
-
if (
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
}
|
|
527
|
+
if (options?.mode === "full-history") return {
|
|
528
|
+
messages,
|
|
529
|
+
preserveUnframedToolResults: false
|
|
530
|
+
};
|
|
531
|
+
if (compaction.mode === "refresh-required") throw new CompactionReplayRefreshRequiredError();
|
|
532
|
+
const ownerIndex = messages.indexOf(compaction.owner);
|
|
533
|
+
return {
|
|
534
|
+
messages: [{
|
|
535
|
+
...compaction.owner,
|
|
536
|
+
content: compaction.owner.content.slice(compaction.replayIndex)
|
|
537
|
+
}, ...messages.slice(ownerIndex + 1)],
|
|
538
|
+
...compaction.mode === "complete-window" ? { compactedWindow: compaction.output } : { compaction: compaction.item },
|
|
539
|
+
preserveUnframedToolResults: true
|
|
510
540
|
};
|
|
511
541
|
}
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
542
|
+
function buildOpenAIResponsesReasoningReplayMetadata(model, options) {
|
|
543
|
+
return {
|
|
544
|
+
v: 1,
|
|
545
|
+
source: "openai-responses",
|
|
546
|
+
...buildProviderReplayContext(model, options)
|
|
547
|
+
};
|
|
515
548
|
}
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
549
|
+
//#endregion
|
|
550
|
+
//#region packages/ai/src/utils/text-signature.ts
|
|
551
|
+
function encodeTextSignatureV1(id, phase) {
|
|
552
|
+
return JSON.stringify({
|
|
553
|
+
v: 1,
|
|
554
|
+
id,
|
|
555
|
+
...phase ? { phase } : {}
|
|
556
|
+
});
|
|
519
557
|
}
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
if (
|
|
523
|
-
|
|
524
|
-
|
|
558
|
+
function parseOpenAIResponsesTextSignature(signature) {
|
|
559
|
+
if (!signature) return;
|
|
560
|
+
if (signature.startsWith("{")) try {
|
|
561
|
+
const parsed = JSON.parse(signature);
|
|
562
|
+
if (parsed.v === 1) {
|
|
563
|
+
const id = typeof parsed.id === "string" ? parsed.id : void 0;
|
|
564
|
+
const phase = parsed.phase === "commentary" || parsed.phase === "final_answer" ? parsed.phase : void 0;
|
|
565
|
+
if (id !== void 0 || phase !== void 0) return {
|
|
566
|
+
id,
|
|
567
|
+
phase,
|
|
568
|
+
...typeof parsed.sources === "string" ? { sources: parsed.sources } : {}
|
|
569
|
+
};
|
|
570
|
+
return;
|
|
571
|
+
}
|
|
572
|
+
} catch {}
|
|
573
|
+
return { id: signature };
|
|
574
|
+
}
|
|
575
|
+
//#endregion
|
|
576
|
+
//#region packages/ai/src/transports/openai-responses-input-replay.ts
|
|
577
|
+
function recordResponsesInputReplay(message, replay) {
|
|
578
|
+
if (replay) Object.assign(message, { openclawResponsesInputReplay: replay });
|
|
579
|
+
}
|
|
580
|
+
function readResponsesInputReplayState(message) {
|
|
581
|
+
const replay = "openclawResponsesInputReplay" in message ? message.openclawResponsesInputReplay : void 0;
|
|
582
|
+
return isRecord(replay) ? replay : void 0;
|
|
583
|
+
}
|
|
584
|
+
function readResponsesInputReplay(message) {
|
|
585
|
+
const replay = readResponsesInputReplayState(message);
|
|
586
|
+
if (replay && typeof replay.afterResponseId === "string" && isStringArray(replay.before) && isStringArray(replay.after)) return {
|
|
587
|
+
afterResponseId: replay.afterResponseId,
|
|
588
|
+
before: replay.before,
|
|
589
|
+
after: replay.after
|
|
525
590
|
};
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
591
|
+
}
|
|
592
|
+
function responsesInputFingerprint(item) {
|
|
593
|
+
if (isRecord(item) && (item.type === "function_call_output" || item.type === "custom_tool_call_output") && typeof item.call_id === "string") return sha256Hex(stableStringify({
|
|
594
|
+
type: item.type,
|
|
595
|
+
call_id: item.call_id
|
|
596
|
+
}));
|
|
597
|
+
return sha256Hex(stableStringify(item));
|
|
598
|
+
}
|
|
599
|
+
/** Reconstruct delivery order without rewriting durable local completion events. */
|
|
600
|
+
function createResponsesInputReplay(model) {
|
|
601
|
+
const starts = /* @__PURE__ */ new Map();
|
|
602
|
+
const ends = /* @__PURE__ */ new Map();
|
|
603
|
+
const fingerprints = /* @__PURE__ */ new Map();
|
|
604
|
+
const fingerprint = (item) => {
|
|
605
|
+
const value = fingerprints.get(item) ?? responsesInputFingerprint(item);
|
|
606
|
+
fingerprints.set(item, value);
|
|
607
|
+
return value;
|
|
608
|
+
};
|
|
609
|
+
return (input, output, message) => {
|
|
610
|
+
const key = message.turnId || message.responseId;
|
|
611
|
+
const start = (key ? starts.get(key) : void 0) ?? output[0];
|
|
612
|
+
if (key && start) starts.set(key, start);
|
|
613
|
+
input.push(...output);
|
|
614
|
+
let end = input.at(-1);
|
|
615
|
+
const replay = readResponsesInputReplay(message);
|
|
616
|
+
const parent = replay ? ends.get(replay.afterResponseId) : void 0;
|
|
617
|
+
if (replay && parent && message.provider === model.provider && message.api === model.api && message.model === model.id) {
|
|
618
|
+
const take = (keys) => {
|
|
619
|
+
const moved = [];
|
|
620
|
+
for (const inputKey of keys.toReversed()) {
|
|
621
|
+
const boundary = input.indexOf(parent);
|
|
622
|
+
const index = input.findLastIndex((item, position) => position > boundary && fingerprint(item) === inputKey);
|
|
623
|
+
if (index > boundary) moved.unshift(...input.splice(index, 1));
|
|
624
|
+
}
|
|
625
|
+
return moved;
|
|
626
|
+
};
|
|
627
|
+
const before = take(replay.before);
|
|
628
|
+
const after = take(replay.after);
|
|
629
|
+
input.splice(start ? input.indexOf(start) : input.length, 0, ...before);
|
|
630
|
+
end = input.at(-1);
|
|
631
|
+
input.push(...after);
|
|
632
|
+
}
|
|
633
|
+
if (message.responseId && end) ends.set(message.responseId, end);
|
|
533
634
|
};
|
|
534
635
|
}
|
|
535
636
|
//#endregion
|
|
536
|
-
//#region packages/ai/src/
|
|
537
|
-
/**
|
|
538
|
-
function
|
|
539
|
-
|
|
637
|
+
//#region packages/ai/src/transports/openai-responses-replay.ts
|
|
638
|
+
/** Resolves the assistant message id that can be replayed to OpenAI Responses. */
|
|
639
|
+
function resolveReplayableResponsesMessageId(params) {
|
|
640
|
+
if (!params.replayResponsesItemIds) return;
|
|
641
|
+
if (!params.textSignatureId) return params.fallbackOrdinal === 0 ? params.fallbackId : `${params.fallbackId}_${params.fallbackOrdinal}`;
|
|
642
|
+
return params.previousReplayItemWasReasoning ? params.textSignatureId : void 0;
|
|
540
643
|
}
|
|
541
|
-
function
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
const intent = mapped !== void 0 ? mapped?.trim() : reasoning === void 0 ? void 0 : requested;
|
|
547
|
-
const normalizedIntent = normalizeOpenAIReasoningEffort(intent ?? "off");
|
|
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
|
-
model,
|
|
552
|
-
effort: requested,
|
|
553
|
-
fallbackMap: { [requested]: intent }
|
|
554
|
-
});
|
|
644
|
+
function normalizeOpenAIResponsesReasoningReplayItem(item, api) {
|
|
645
|
+
if (api === "openai-chatgpt-responses") return Array.isArray(item.summary) ? item : {
|
|
646
|
+
...item,
|
|
647
|
+
summary: []
|
|
648
|
+
};
|
|
555
649
|
return {
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
650
|
+
id: item.id,
|
|
651
|
+
type: "reasoning",
|
|
652
|
+
summary: [],
|
|
653
|
+
...Array.isArray(item.content) && item.content.length === 0 ? { content: [] } : {},
|
|
654
|
+
status: item.status,
|
|
655
|
+
encrypted_content: item.encrypted_content
|
|
561
656
|
};
|
|
562
657
|
}
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
const
|
|
566
|
-
const
|
|
567
|
-
|
|
568
|
-
function readToolPayloadField(record, field) {
|
|
569
|
-
try {
|
|
570
|
-
return Object.hasOwn(record, field) ? record[field] : void 0;
|
|
571
|
-
} catch {
|
|
572
|
-
return;
|
|
573
|
-
}
|
|
658
|
+
/** Replay original bytes only while the normalized arguments still match the saved call. */
|
|
659
|
+
function replayOpenAIResponsesToolArguments(block, providerStyle, sameModel) {
|
|
660
|
+
const value = providerStyle ? JSON.stringify(block.arguments) : typeof block.arguments === "string" ? block.arguments : JSON.stringify(block.arguments ?? {});
|
|
661
|
+
const signature = sameModel && block.argumentsSignature;
|
|
662
|
+
return signature && signature.value === value && typeof signature.raw === "string" ? signature.raw : value;
|
|
574
663
|
}
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
if (!isRecord(fn)) return;
|
|
581
|
-
const fnName = readToolPayloadField(fn, "name");
|
|
582
|
-
return typeof fnName === "string" ? fnName : void 0;
|
|
664
|
+
//#endregion
|
|
665
|
+
//#region packages/ai/src/transports/openai-responses-replay-messages-internal.ts
|
|
666
|
+
function resolveResponsesInstructionRole(model) {
|
|
667
|
+
const supportsDeveloperRole = !isRecord(model.compat) || model.compat.supportsDeveloperRole !== false;
|
|
668
|
+
return model.reasoning && supportsDeveloperRole ? "developer" : "system";
|
|
583
669
|
}
|
|
584
|
-
function
|
|
585
|
-
if (!
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
return
|
|
670
|
+
function stripEncryptedReasoningContentFields(value) {
|
|
671
|
+
if (!value || typeof value !== "object") return value;
|
|
672
|
+
if (Array.isArray(value)) {
|
|
673
|
+
let changed = false;
|
|
674
|
+
const next = value.map((item) => {
|
|
675
|
+
const stripped = stripEncryptedReasoningContentFields(item);
|
|
676
|
+
changed ||= !Object.is(stripped, item);
|
|
677
|
+
return stripped;
|
|
678
|
+
});
|
|
679
|
+
return changed ? next : value;
|
|
680
|
+
}
|
|
681
|
+
const source = value;
|
|
682
|
+
if (source.type === "compaction") return value;
|
|
683
|
+
let changed = false;
|
|
684
|
+
const next = {};
|
|
685
|
+
for (const [key, child] of Object.entries(source)) {
|
|
686
|
+
if (key === "encrypted_content") {
|
|
687
|
+
changed = true;
|
|
688
|
+
continue;
|
|
592
689
|
}
|
|
593
|
-
|
|
690
|
+
const stripped = stripEncryptedReasoningContentFields(child);
|
|
691
|
+
changed ||= !Object.is(stripped, child);
|
|
692
|
+
next[key] = stripped;
|
|
594
693
|
}
|
|
595
|
-
|
|
596
|
-
return typeof name === "string" && isCodeModeModelVisibleToolName(name, visibleToolNames) ? `client:${name}` : void 0;
|
|
694
|
+
return changed ? next : value;
|
|
597
695
|
}
|
|
598
|
-
function
|
|
599
|
-
|
|
600
|
-
const tools = readToolPayloadField(payload, "tools");
|
|
601
|
-
if (!Array.isArray(tools)) return [];
|
|
602
|
-
return tools.flatMap((tool) => {
|
|
603
|
-
if (!isRecord(tool)) return [];
|
|
604
|
-
const identities = [];
|
|
605
|
-
const name = readCodeModePayloadToolName(tool);
|
|
606
|
-
if (name) identities.push(`client:${name}`);
|
|
607
|
-
for (const key of ["functionDeclarations", "function_declarations"]) {
|
|
608
|
-
const declarations = readToolPayloadField(tool, key);
|
|
609
|
-
if (!Array.isArray(declarations)) continue;
|
|
610
|
-
for (const declaration of declarations) {
|
|
611
|
-
const declarationName = readCodeModePayloadToolName(declaration);
|
|
612
|
-
if (declarationName) identities.push(`client:${declarationName}`);
|
|
613
|
-
}
|
|
614
|
-
}
|
|
615
|
-
const type = readToolPayloadField(tool, "type");
|
|
616
|
-
if (typeof type === "string" && type !== "function") identities.push(`hosted:${type}`);
|
|
617
|
-
return identities;
|
|
618
|
-
});
|
|
696
|
+
function isOpenAIResponsesReasoningReplayMetadata(value) {
|
|
697
|
+
return isProviderReplayContext(value) && value.v === 1 && value.source === "openai-responses";
|
|
619
698
|
}
|
|
620
|
-
function
|
|
621
|
-
if (!
|
|
622
|
-
const
|
|
623
|
-
|
|
624
|
-
const beforeToolIdentities = observer ? readCodeModePayloadToolIdentities(payload) : void 0;
|
|
625
|
-
payload.tools = tools.flatMap((tool) => {
|
|
626
|
-
const identity = readCodeModePayloadToolIdentity(tool, visibleToolNames, allowedHostedToolTypes);
|
|
627
|
-
if (identity) return [tool];
|
|
628
|
-
if (identity === false) return [];
|
|
629
|
-
if (!isRecord(tool)) return [];
|
|
630
|
-
const filteredGroups = {};
|
|
631
|
-
for (const key of ["functionDeclarations", "function_declarations"]) {
|
|
632
|
-
const declarations = readToolPayloadField(tool, key);
|
|
633
|
-
if (!Array.isArray(declarations)) continue;
|
|
634
|
-
const filtered = declarations.filter((declaration) => {
|
|
635
|
-
const declarationName = readCodeModePayloadToolName(declaration);
|
|
636
|
-
return typeof declarationName === "string" && isCodeModeModelVisibleToolName(declarationName, visibleToolNames);
|
|
637
|
-
});
|
|
638
|
-
if (filtered.length > 0) filteredGroups[key] = filtered;
|
|
639
|
-
}
|
|
640
|
-
return Object.keys(filteredGroups).length > 0 ? [filteredGroups] : [];
|
|
641
|
-
});
|
|
642
|
-
if (beforeToolIdentities) observer?.({
|
|
643
|
-
beforeToolIdentities,
|
|
644
|
-
afterToolIdentities: readCodeModePayloadToolIdentities(payload)
|
|
645
|
-
});
|
|
699
|
+
function readOpenAIResponsesReasoningReplayBlockMetadata(block) {
|
|
700
|
+
if (!Object.hasOwn(block, "openclawReasoningReplay")) return;
|
|
701
|
+
const value = block[OPENAI_RESPONSES_REASONING_REPLAY_BLOCK_META_KEY];
|
|
702
|
+
return isOpenAIResponsesReasoningReplayMetadata(value) ? value : null;
|
|
646
703
|
}
|
|
647
|
-
function
|
|
648
|
-
|
|
704
|
+
function prepareOpenAIResponsesReasoningItemForReplay(item, context, blockMetadata, options) {
|
|
705
|
+
const hasRawMetadata = Object.hasOwn(item, OPENAI_RESPONSES_REASONING_REPLAY_META_KEY);
|
|
706
|
+
const { [OPENAI_RESPONSES_REASONING_REPLAY_META_KEY]: rawMetadata, ...rest } = item;
|
|
707
|
+
if (!("encrypted_content" in rest)) return normalizeOpenAIResponsesReasoningReplayItem(rest, context.api);
|
|
708
|
+
const metadata = blockMetadata !== void 0 ? blockMetadata ?? void 0 : isOpenAIResponsesReasoningReplayMetadata(rawMetadata) ? rawMetadata : void 0;
|
|
709
|
+
if (blockMetadata === void 0 && !hasRawMetadata && options?.preserveUnattributedEncryptedContent === true || metadata && providerReplayContextMatches(metadata, context)) return normalizeOpenAIResponsesReasoningReplayItem(rest, context.api);
|
|
710
|
+
return normalizeOpenAIResponsesReasoningReplayItem(stripEncryptedReasoningContentFields(rest), context.api);
|
|
649
711
|
}
|
|
650
|
-
function
|
|
651
|
-
if (!
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
const beforeToolIdentities = observer ? readCodeModePayloadToolIdentities(payload) : void 0;
|
|
655
|
-
payload.tools = tools.filter((tool) => Boolean(readCodeModePayloadToolIdentity(tool, visibleToolNames, allowedHostedToolTypes)));
|
|
656
|
-
if (beforeToolIdentities) observer?.({
|
|
657
|
-
beforeToolIdentities,
|
|
658
|
-
afterToolIdentities: readCodeModePayloadToolIdentities(payload)
|
|
659
|
-
});
|
|
712
|
+
function normalizeResponsesReplayItemId(id) {
|
|
713
|
+
if (!id) return;
|
|
714
|
+
if (id.length <= 64) return id;
|
|
715
|
+
return `msg_${shortHash(id)}`;
|
|
660
716
|
}
|
|
661
|
-
function
|
|
662
|
-
const
|
|
663
|
-
|
|
664
|
-
const identities = tools.map((tool) => readCodeModePayloadToolIdentity(tool, visibleToolNames, allowedHostedToolTypes));
|
|
665
|
-
const names = identities.flatMap((identity) => typeof identity === "string" && identity.startsWith("client:") ? [identity.slice(7)] : []).toSorted((left, right) => left.localeCompare(right));
|
|
666
|
-
if (names.length >= 2 && identities.every((identity) => typeof identity === "string") && new Set(identities).size === identities.length && names.includes("exec") && names.includes("wait")) return;
|
|
667
|
-
throw new Error(`Code mode payload tool surface violation: expected exec,wait plus direct-only tools; got ${names.length > 0 ? names.join(",") : "none"}`);
|
|
717
|
+
function responsesAssistantTurnKey(message) {
|
|
718
|
+
const id = message.turnId || message.responseId;
|
|
719
|
+
return id ? `${message.provider}:${message.api}:${message.model}:${id}` : void 0;
|
|
668
720
|
}
|
|
669
|
-
function
|
|
670
|
-
const
|
|
671
|
-
|
|
672
|
-
const
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
if (loggedOpenAIStrictToolDowngradeDiagnosticKeys.has(key)) return null;
|
|
684
|
-
if (loggedOpenAIStrictToolDowngradeDiagnosticKeys.size >= MAX_OPENAI_STRICT_TOOL_DOWNGRADE_DIAGNOSTIC_KEYS) loggedOpenAIStrictToolDowngradeDiagnosticKeys.clear();
|
|
685
|
-
loggedOpenAIStrictToolDowngradeDiagnosticKeys.add(key);
|
|
686
|
-
const sample = diagnostics.slice(0, 5).map((entry) => ({
|
|
687
|
-
tool: entry.toolName ?? `tool[${entry.toolIndex}]`,
|
|
688
|
-
violations: entry.violations.slice(0, 8)
|
|
689
|
-
}));
|
|
690
|
-
return {
|
|
691
|
-
message: `OpenAI ${context.transport} tool schema strict mode downgraded to strict=false for ${context.model.provider ?? "unknown"}/${context.model.id ?? "unknown"} because ${diagnostics.length} tool schema(s) are not strict-compatible`,
|
|
692
|
-
data: {
|
|
693
|
-
transport: context.transport,
|
|
694
|
-
provider: context.model.provider,
|
|
695
|
-
model: context.model.id,
|
|
696
|
-
incompatibleToolCount: diagnostics.length,
|
|
697
|
-
sample
|
|
721
|
+
function orderResponsesAsyncToolResults(source) {
|
|
722
|
+
const lastAssistant = /* @__PURE__ */ new Map();
|
|
723
|
+
for (const [index, message] of source.entries()) if (message.role === "assistant") {
|
|
724
|
+
const key = responsesAssistantTurnKey(message);
|
|
725
|
+
if (key) lastAssistant.set(key, index);
|
|
726
|
+
}
|
|
727
|
+
const owners = /* @__PURE__ */ new Map();
|
|
728
|
+
const pending = /* @__PURE__ */ new Map();
|
|
729
|
+
const ordered = [];
|
|
730
|
+
for (const [index, message] of source.entries()) {
|
|
731
|
+
if (message.role === "assistant") {
|
|
732
|
+
const key = responsesAssistantTurnKey(message);
|
|
733
|
+
if (key) {
|
|
734
|
+
for (const block of message.content) if (block.type === "toolCall" && block.async) owners.set(block.id, key);
|
|
698
735
|
}
|
|
699
|
-
}
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
const
|
|
708
|
-
if (
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
"session_id",
|
|
712
|
-
"x-client-request-id",
|
|
713
|
-
"x-session-affinity"
|
|
714
|
-
];
|
|
715
|
-
const configuredHeaders = new Set(Object.keys(providerHeaders).map((key) => key.toLowerCase()));
|
|
716
|
-
for (const name of affinityHeaders) if (!configuredHeaders.has(name)) providerHeaders[name] = affinityValue;
|
|
736
|
+
}
|
|
737
|
+
const owner = message.role === "toolResult" ? owners.get(message.toolCallId) : void 0;
|
|
738
|
+
const lastIndex = owner ? lastAssistant.get(owner) : void 0;
|
|
739
|
+
if (lastIndex !== void 0 && lastIndex > index) {
|
|
740
|
+
const results = pending.get(lastIndex) ?? [];
|
|
741
|
+
results.push(message);
|
|
742
|
+
pending.set(lastIndex, results);
|
|
743
|
+
} else ordered.push(message);
|
|
744
|
+
const results = pending.get(index);
|
|
745
|
+
if (results) {
|
|
746
|
+
ordered.push(...results);
|
|
747
|
+
pending.delete(index);
|
|
717
748
|
}
|
|
718
749
|
}
|
|
719
|
-
|
|
720
|
-
...optionHeaders,
|
|
721
|
-
...turnHeaders
|
|
722
|
-
};
|
|
723
|
-
const resolvedHeaders = getAiTransportHost().resolveProviderRequestHeaders({
|
|
724
|
-
provider: model.provider,
|
|
725
|
-
api: model.api,
|
|
726
|
-
baseUrl: model.baseUrl,
|
|
727
|
-
providerHeaders,
|
|
728
|
-
callerHeaders: Object.keys(callerHeaders).length > 0 ? callerHeaders : void 0,
|
|
729
|
-
precedence: "caller-wins",
|
|
730
|
-
model
|
|
731
|
-
}) ?? {};
|
|
732
|
-
const sendSessionIdHeader = (OPENAI_RESPONSES_APIS.has(model.api) && model.compat && "sendSessionIdHeader" in model.compat ? model.compat?.sendSessionIdHeader : void 0) ?? usesNativeOpenAICodexResponsesBackend(model);
|
|
733
|
-
if (sessionId && cacheRetention !== "none" && sendSessionIdHeader && !Object.keys(resolvedHeaders).some((key) => normalizeLowercaseStringOrEmpty(key) === "session_id")) resolvedHeaders.session_id = clampOpenAIPromptCacheKey(sessionId) ?? sessionId;
|
|
734
|
-
return resolveOpencodeSessionHeaders(model, {
|
|
735
|
-
sessionId,
|
|
736
|
-
headers: resolvedHeaders
|
|
737
|
-
}) ?? resolvedHeaders;
|
|
738
|
-
}
|
|
739
|
-
function buildOpenAISdkClientOptions(model) {
|
|
740
|
-
const timeout = resolveModelRequestTimeoutMs(model);
|
|
741
|
-
return {
|
|
742
|
-
...timeout === void 0 ? {} : { timeout },
|
|
743
|
-
maxRetries: 0
|
|
744
|
-
};
|
|
750
|
+
return ordered;
|
|
745
751
|
}
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
};
|
|
752
|
+
const responsesInputSource = Symbol("openclaw.responsesInputSource");
|
|
753
|
+
/** Source identity survives payload spreads but never enters serialized provider input. */
|
|
754
|
+
function bindResponsesInputMessage(source) {
|
|
755
|
+
const identity = {};
|
|
756
|
+
Object.defineProperty(source, responsesInputSource, {
|
|
757
|
+
value: identity,
|
|
758
|
+
enumerable: true
|
|
759
|
+
});
|
|
760
|
+
return (input) => typeof input === "object" && input !== null && Reflect.get(input, responsesInputSource) === identity;
|
|
756
761
|
}
|
|
757
|
-
function
|
|
758
|
-
const
|
|
759
|
-
const compat = model.compat ?? {};
|
|
762
|
+
function buildResponsesInputMessage(role, content, source) {
|
|
763
|
+
const identity = source && Reflect.get(source, responsesInputSource);
|
|
760
764
|
return {
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
strictMessageKeys: compat.strictMessageKeys === true
|
|
765
|
+
type: "message",
|
|
766
|
+
role,
|
|
767
|
+
content,
|
|
768
|
+
...identity ? { [responsesInputSource]: identity } : {}
|
|
766
769
|
};
|
|
767
770
|
}
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
return (retained || state.type === "openai-responses-compaction") && typeof state.data === "string" && state.data.length > 0 && (state.id === void 0 || typeof state.id === "string") && (state.replayIndex === void 0 || !retained && typeof state.replayIndex === "number" && Number.isSafeInteger(state.replayIndex) && state.replayIndex >= 0);
|
|
777
|
-
}
|
|
778
|
-
function readOpenAIResponsesCompactionReplayState(value) {
|
|
779
|
-
return isRecord(value) && isProviderReplayContext(value) && isOpenAIResponsesCompactionState(value) ? value : void 0;
|
|
771
|
+
const responsesMessageProjections = /* @__PURE__ */ new WeakMap();
|
|
772
|
+
/** Detach hook-editable JSON containers while retaining scalar strings. */
|
|
773
|
+
function cloneResponsesInputForPayloadHook(value) {
|
|
774
|
+
if (!value || typeof value !== "object") return value;
|
|
775
|
+
if (Array.isArray(value)) return value.map(cloneResponsesInputForPayloadHook);
|
|
776
|
+
const copy = { ...value };
|
|
777
|
+
for (const key of Object.keys(copy)) Reflect.set(copy, key, cloneResponsesInputForPayloadHook(Reflect.get(value, key)));
|
|
778
|
+
return copy;
|
|
780
779
|
}
|
|
781
|
-
function
|
|
782
|
-
const
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
if (compactedOutput && !isOpenAIResponsesCompactionOutput(compactedOutput, model)) throw new Error("Responses compact endpoint checkpoint is invalid");
|
|
791
|
-
const replay = {
|
|
792
|
-
v: 1,
|
|
793
|
-
...boundary === "retained-users" ? { type: OPENAI_RESPONSES_RETAINED_COMPACTION_REPLAY_TYPE } : {
|
|
794
|
-
type: OPENAI_RESPONSES_COMPACTION_REPLAY_TYPE,
|
|
795
|
-
replayIndex: boundary
|
|
796
|
-
},
|
|
797
|
-
...item.id ? { id: item.id } : {},
|
|
798
|
-
data: item.encrypted_content,
|
|
799
|
-
provider: metadata.provider,
|
|
800
|
-
api: metadata.api,
|
|
801
|
-
model: metadata.model,
|
|
802
|
-
baseUrlHash: metadata.baseUrlHash,
|
|
803
|
-
...metadata.sessionHash ? { sessionHash: metadata.sessionHash } : {},
|
|
804
|
-
...metadata.authProfileHash ? { authProfileHash: metadata.authProfileHash } : {},
|
|
805
|
-
...compactedOutput ? { compactedWindow: {
|
|
806
|
-
state: "ready",
|
|
807
|
-
output: JSON.stringify(compactedOutput),
|
|
808
|
-
...outputTokens !== void 0 ? { outputTokens } : {}
|
|
809
|
-
} } : {}
|
|
780
|
+
function convertResponsesMessagesWithStyle(model, context, allowedToolCallProviders, options, conversionStyle) {
|
|
781
|
+
const messages = [];
|
|
782
|
+
const providerStyle = conversionStyle === "provider";
|
|
783
|
+
const shouldReplayResponsesItemIds = options?.replayResponsesItemIds ?? true;
|
|
784
|
+
const replayContext = buildProviderReplayContext(model, { sessionId: options?.sessionId });
|
|
785
|
+
const shouldNormalizeSameModelToolCallIds = model.provider === "github-copilot";
|
|
786
|
+
const sanitizeIdPart = (part) => {
|
|
787
|
+
const sanitized = part.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
788
|
+
return providerStyle ? sanitized : sanitized.replace(/_+$/, "");
|
|
810
789
|
};
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
function suppressOpenAIResponsesCompaction(output, model, options, rejectedCheckpoint) {
|
|
815
|
-
const context = buildProviderReplayContext(model, options);
|
|
816
|
-
if (!context.baseUrlHash) return;
|
|
817
|
-
output.providerReplay = {
|
|
818
|
-
v: 1,
|
|
819
|
-
type: OPENAI_RESPONSES_COMPACTION_SUPPRESSION_TYPE,
|
|
820
|
-
data: OPENAI_RESPONSES_COMPACTION_SUPPRESSION_DATA,
|
|
821
|
-
...context,
|
|
822
|
-
baseUrlHash: context.baseUrlHash
|
|
790
|
+
const normalizeIdPart = (part) => {
|
|
791
|
+
const sanitized = sanitizeIdPart(part);
|
|
792
|
+
return (sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized).replace(/_+$/, "");
|
|
823
793
|
};
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
794
|
+
const buildForeignResponsesItemId = (itemId) => `fc_${shortHash(itemId)}`;
|
|
795
|
+
const buildSameProviderCopilotResponsesItemId = (itemId) => {
|
|
796
|
+
const sanitized = sanitizeIdPart(itemId);
|
|
797
|
+
const candidate = sanitized.startsWith("fc_") ? sanitized : `fc_${sanitized}`;
|
|
798
|
+
return candidate.length > 64 ? buildForeignResponsesItemId(itemId) : candidate;
|
|
799
|
+
};
|
|
800
|
+
const normalizeToolCallId = (id, _targetModel, source) => {
|
|
801
|
+
if (!allowedToolCallProviders.has(model.provider) || !id.includes("|")) return normalizeIdPart(id);
|
|
802
|
+
const separatorIndex = id.indexOf("|");
|
|
803
|
+
const callId = id.slice(0, separatorIndex);
|
|
804
|
+
const itemId = id.slice(separatorIndex + 1);
|
|
805
|
+
const normalizedCallId = normalizeIdPart(callId);
|
|
806
|
+
let normalizedItemId = source.provider !== model.provider || source.api !== model.api ? buildForeignResponsesItemId(itemId) : model.provider === "github-copilot" ? providerStyle ? normalizeIdPart(itemId) : buildSameProviderCopilotResponsesItemId(itemId) : normalizeIdPart(itemId);
|
|
807
|
+
if (!normalizedItemId.startsWith("fc_")) normalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);
|
|
808
|
+
return `${normalizedCallId}|${normalizedItemId}`;
|
|
809
|
+
};
|
|
810
|
+
const replayPlan = buildOpenAIResponsesCompactionReplayPlan(context.messages, model, {
|
|
811
|
+
sessionId: options?.sessionId,
|
|
812
|
+
mode: options?.replayMode
|
|
813
|
+
});
|
|
814
|
+
if (replayPlan.itemRecovery) options?.onItemRecovery?.();
|
|
815
|
+
const transformMessages = (source) => providerStyle ? transformProviderMessages(source, model, normalizeToolCallId) : getAiTransportHost().transformTransportMessages(source, model, normalizeToolCallId, {
|
|
816
|
+
normalizeSameModelToolCallIds: shouldNormalizeSameModelToolCallIds,
|
|
817
|
+
preserveUnframedToolResults: replayPlan.preserveUnframedToolResults || preparedRequestSuffix.has(context)
|
|
818
|
+
});
|
|
819
|
+
const transformedMessages = orderResponsesAsyncToolResults(transformMessages(replayPlan.messages));
|
|
820
|
+
if ((options?.includeSystemPrompt ?? true) && context.systemPrompt) messages.push(buildResponsesInputMessage(resolveResponsesInstructionRole(model), [{
|
|
821
|
+
type: "input_text",
|
|
822
|
+
text: prepareSystemPrompt(context.systemPrompt, context.preparedSystemPrompt).instructions
|
|
823
|
+
}]));
|
|
824
|
+
if (replayPlan.compactedWindow) messages.push(...replayPlan.compactedWindow.map((item) => {
|
|
825
|
+
if (options?.retainUserProvenance && item.type === "message" && item.role === "user") return Object.assign({}, item, { [RESPONSES_RETAINED_USER]: true });
|
|
826
|
+
return item;
|
|
827
|
+
}));
|
|
828
|
+
let replayMessages = replayPlan.compaction ? [replayPlan.compaction, ...transformedMessages] : transformedMessages;
|
|
829
|
+
const isCarrier = (message) => "role" in message && hasRuntimeContextMarker(message);
|
|
830
|
+
if (replayMessages.some(isCarrier)) {
|
|
831
|
+
const anchored = [];
|
|
832
|
+
let insertionIndex = replayPlan.compactedWindow ? 0 : void 0;
|
|
833
|
+
for (const message of replayMessages) {
|
|
834
|
+
if (isCarrier(message) && insertionIndex !== void 0) {
|
|
835
|
+
anchored.splice(insertionIndex++, 0, message);
|
|
836
|
+
continue;
|
|
837
|
+
}
|
|
838
|
+
anchored.push(message);
|
|
839
|
+
if (!isCarrier(message) && ("role" in message ? message.role === "user" : message.type === "compaction")) insertionIndex = anchored.length;
|
|
840
|
+
}
|
|
841
|
+
replayMessages = anchored;
|
|
842
|
+
}
|
|
843
|
+
let msgIndex = 0;
|
|
844
|
+
let recoveryAnchor = replayPlan.itemRecovery?.anchor;
|
|
845
|
+
let pastRecoveryBoundary = false;
|
|
846
|
+
const recoveredCalls = recoveryAnchor ? /* @__PURE__ */ new Set() : void 0;
|
|
847
|
+
const replayCallId = (id) => recoveryAnchor ? `call_${shortHash(`${recoveryAnchor}:${id}`)}` : id;
|
|
848
|
+
const appendAssistant = createResponsesInputReplay(model);
|
|
849
|
+
const inHistorySystemUpdates = supportsNativeOpenAIResponsesEndpoint(model);
|
|
850
|
+
const convertMessage = (msg, messageIndex) => {
|
|
851
|
+
const replayItemIds = shouldReplayResponsesItemIds && !recoveryAnchor;
|
|
852
|
+
const converted = [];
|
|
853
|
+
if (inHistorySystemUpdates && isRuntimeContextMessage(msg)) converted.push(buildResponsesInputMessage(resolveResponsesInstructionRole(model), [{
|
|
854
|
+
type: "input_text",
|
|
855
|
+
text: sanitizeTransportPayloadText(runtimeContextContentToText(msg.content))
|
|
856
|
+
}]));
|
|
857
|
+
else if (msg.role === "user") {
|
|
858
|
+
const role = msg.operatorMessage && inHistorySystemUpdates && (typeof msg.content === "string" || msg.content.every((block) => block.type === "text")) ? resolveResponsesInstructionRole(model) : "user";
|
|
859
|
+
const content = typeof msg.content === "string" ? [{
|
|
860
|
+
type: "input_text",
|
|
861
|
+
text: sanitizeTransportPayloadText(msg.content)
|
|
862
|
+
}] : msg.content.map((item) => item.type === "text" ? {
|
|
863
|
+
type: "input_text",
|
|
864
|
+
text: sanitizeTransportPayloadText(item.text)
|
|
865
|
+
} : buildResponsesInputImage(item)).filter((item) => providerStyle || model.input.includes("image") || item.type !== "input_image");
|
|
866
|
+
if (content.length > 0) {
|
|
867
|
+
const input = buildResponsesInputMessage(role, content, msg);
|
|
868
|
+
if (options?.retainUserProvenance && role === "user" && !msg.synthetic && !msg.operatorMessage && !hasRuntimeContextMarker(msg)) Object.assign(input, { [RESPONSES_RETAINED_USER]: true });
|
|
869
|
+
converted.push(input);
|
|
870
|
+
}
|
|
871
|
+
} else if (msg.role === "assistant") {
|
|
872
|
+
const output = converted;
|
|
873
|
+
const sourceTurnKey = responsesAssistantTurnKey(msg);
|
|
874
|
+
const sourceFragmentId = msg.content.find((block) => block.type === "toolCall")?.id;
|
|
875
|
+
let textFallbackOrdinal = 0;
|
|
876
|
+
let previousReasoningHasId = false;
|
|
877
|
+
let seenReplayableReasoning = false;
|
|
878
|
+
const isDifferentModel = msg.model !== model.id && msg.provider === model.provider && msg.api === model.api;
|
|
879
|
+
for (const block of msg.content) if (block.type === "thinking") {
|
|
880
|
+
if (recoveryAnchor) continue;
|
|
881
|
+
if (block.thinkingSignature && (providerStyle || block.thinkingSignature.startsWith("{"))) {
|
|
882
|
+
let reasoningItem;
|
|
883
|
+
try {
|
|
884
|
+
reasoningItem = JSON.parse(block.thinkingSignature);
|
|
885
|
+
} catch {
|
|
886
|
+
continue;
|
|
887
|
+
}
|
|
888
|
+
if (!isRecord(reasoningItem) || reasoningItem.type !== "reasoning") continue;
|
|
889
|
+
const replayableReasoningItem = prepareOpenAIResponsesReasoningItemForReplay(reasoningItem, replayContext, readOpenAIResponsesReasoningReplayBlockMetadata(isRecord(block) ? block : {}), providerStyle ? { preserveUnattributedEncryptedContent: true } : void 0);
|
|
890
|
+
if (replayableReasoningItem.encrypted_content && (inHistorySystemUpdates || !replayItemIds)) delete replayableReasoningItem.id;
|
|
891
|
+
else if (!replayItemIds || !providerStyle && model.provider === "github-copilot" && !isSafeResponsesReplayItemId(replayableReasoningItem.id)) continue;
|
|
892
|
+
output.push(replayableReasoningItem);
|
|
893
|
+
const reasoningId = replayableReasoningItem.id;
|
|
894
|
+
previousReasoningHasId = typeof reasoningId === "string";
|
|
895
|
+
seenReplayableReasoning ||= typeof reasoningId === "string" && reasoningId.startsWith("rs_");
|
|
896
|
+
}
|
|
897
|
+
} else if (block.type === "text") {
|
|
898
|
+
const textSignature = parseOpenAIResponsesTextSignature(block.textSignature);
|
|
899
|
+
let msgId = resolveReplayableResponsesMessageId({
|
|
900
|
+
replayResponsesItemIds: replayItemIds,
|
|
901
|
+
textSignatureId: textSignature?.id,
|
|
902
|
+
fallbackId: sourceTurnKey ? `msg_${shortHash(JSON.stringify([sourceTurnKey, sourceFragmentId]))}` : `msg_${messageIndex}`,
|
|
903
|
+
fallbackOrdinal: textFallbackOrdinal,
|
|
904
|
+
previousReplayItemWasReasoning: previousReasoningHasId
|
|
905
|
+
});
|
|
906
|
+
if (!textSignature?.id) textFallbackOrdinal += 1;
|
|
907
|
+
msgId = normalizeResponsesReplayItemId(msgId);
|
|
908
|
+
const sources = textSignature?.sources;
|
|
909
|
+
const providerText = sources && block.text.endsWith(sources) ? block.text.slice(0, -sources.length) : block.text;
|
|
910
|
+
const messageItem = {
|
|
911
|
+
type: "message",
|
|
912
|
+
role: "assistant",
|
|
913
|
+
content: [{
|
|
914
|
+
type: "output_text",
|
|
915
|
+
text: sanitizeTransportPayloadText(providerText),
|
|
916
|
+
annotations: []
|
|
917
|
+
}],
|
|
918
|
+
status: "completed",
|
|
919
|
+
...msgId ? { id: msgId } : {},
|
|
920
|
+
phase: textSignature?.phase
|
|
921
|
+
};
|
|
922
|
+
output.push(messageItem);
|
|
923
|
+
previousReasoningHasId = false;
|
|
924
|
+
} else if (block.type === "toolCall") {
|
|
925
|
+
const separatorIndex = block.id.indexOf("|");
|
|
926
|
+
const callId = separatorIndex === -1 ? block.id : block.id.slice(0, separatorIndex);
|
|
927
|
+
const itemIdRaw = separatorIndex === -1 ? void 0 : block.id.slice(separatorIndex + 1);
|
|
928
|
+
const itemId = replayItemIds && (!itemIdRaw?.startsWith("fc_") || seenReplayableReasoning && !isDifferentModel) ? itemIdRaw : void 0;
|
|
929
|
+
output.push({
|
|
930
|
+
type: "function_call",
|
|
931
|
+
...itemId ? { id: itemId } : {},
|
|
932
|
+
call_id: replayCallId(callId),
|
|
933
|
+
name: block.name,
|
|
934
|
+
...block.async ? { async: true } : {},
|
|
935
|
+
arguments: replayOpenAIResponsesToolArguments(block, providerStyle, msg.model === model.id && msg.provider === model.provider && msg.api === model.api)
|
|
936
|
+
});
|
|
937
|
+
previousReasoningHasId = false;
|
|
938
|
+
}
|
|
939
|
+
while (true) {
|
|
940
|
+
const last = output.at(-1);
|
|
941
|
+
if (last?.type !== "reasoning" || !last.id?.startsWith("rs_") || typeof last.encrypted_content === "string" && last.encrypted_content.length > 0) break;
|
|
942
|
+
output.pop();
|
|
943
|
+
}
|
|
944
|
+
return output;
|
|
945
|
+
} else if (msg.role === "toolResult") {
|
|
946
|
+
const textResult = extractToolResultText(msg.content);
|
|
947
|
+
const hasText = textResult.trim().length > 0;
|
|
948
|
+
const mediaPlaceholder = describeToolResultMediaPlaceholder(msg.content);
|
|
949
|
+
const hasImages = msg.content.some(isImageWithMediaPayload);
|
|
950
|
+
const separatorIndex = msg.toolCallId.indexOf("|");
|
|
951
|
+
const rawCallId = separatorIndex === -1 ? msg.toolCallId : msg.toolCallId.slice(0, separatorIndex);
|
|
952
|
+
const callId = preparedRequestSuffix.has(context) ? preparedRequestSuffix.toolCallId(context, rawCallId, normalizeToolCallId(rawCallId, model, model)) : rawCallId;
|
|
953
|
+
let output = hasText ? textResult : mediaPlaceholder ?? "(no output)";
|
|
954
|
+
if (hasImages && model.input.includes("image")) {
|
|
955
|
+
const parts = [];
|
|
956
|
+
let hasExplicitText = false;
|
|
957
|
+
for (const item of msg.content) if (isImageWithMediaPayload(item)) parts.push(buildResponsesInputImage(item));
|
|
958
|
+
else if (hasText && item.type === "text") {
|
|
959
|
+
const text = extractToolResultBlockText(item);
|
|
960
|
+
if (text) {
|
|
961
|
+
const joinedText = `${hasExplicitText ? "\n" : ""}${text}`;
|
|
962
|
+
hasExplicitText = true;
|
|
963
|
+
const previous = parts.at(-1);
|
|
964
|
+
if (previous?.type === "input_text") previous.text += joinedText;
|
|
965
|
+
else parts.push({
|
|
966
|
+
type: "input_text",
|
|
967
|
+
text: joinedText
|
|
968
|
+
});
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
if (hasText && !hasExplicitText) parts.unshift({
|
|
972
|
+
type: "input_text",
|
|
973
|
+
text: textResult
|
|
974
|
+
});
|
|
975
|
+
else if (!hasText && mediaPlaceholder === "(see attached media)") parts.unshift({
|
|
976
|
+
type: "input_text",
|
|
977
|
+
text: mediaPlaceholder
|
|
978
|
+
});
|
|
979
|
+
output = parts;
|
|
980
|
+
}
|
|
981
|
+
converted.push({
|
|
982
|
+
type: "function_call_output",
|
|
983
|
+
call_id: replayCallId(callId),
|
|
984
|
+
output
|
|
985
|
+
});
|
|
840
986
|
}
|
|
987
|
+
return converted;
|
|
841
988
|
};
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
989
|
+
const immutable = getAiTransportHost().immutableData;
|
|
990
|
+
const projectionKey = JSON.stringify([
|
|
991
|
+
conversionStyle,
|
|
992
|
+
replayContext,
|
|
993
|
+
shouldReplayResponsesItemIds,
|
|
994
|
+
inHistorySystemUpdates,
|
|
995
|
+
resolveResponsesInstructionRole(model),
|
|
996
|
+
model.input.includes("image"),
|
|
997
|
+
options?.retainUserProvenance === true
|
|
998
|
+
]);
|
|
999
|
+
for (const msg of replayMessages) {
|
|
1000
|
+
if ("role" in msg && msg.role === "assistant" && replayPlan.itemRecovery && readOpenAIResponsesItemRecoveryAnchor(msg.providerReplay) === replayPlan.itemRecovery.anchor) pastRecoveryBoundary = true;
|
|
1001
|
+
if (!("role" in msg)) {
|
|
1002
|
+
messages.push(msg);
|
|
854
1003
|
continue;
|
|
855
1004
|
}
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
1005
|
+
recoveryAnchor = !pastRecoveryBoundary || msg.role === "toolResult" && recoveredCalls?.has(msg.toolCallId) ? replayPlan.itemRecovery?.anchor : void 0;
|
|
1006
|
+
if (recoveryAnchor && msg.role === "assistant") {
|
|
1007
|
+
for (const block of msg.content) if (block.type === "toolCall") recoveredCalls?.add(block.id);
|
|
859
1008
|
}
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
1009
|
+
const reusable = immutable && !preparedRequestSuffix.has(context) && immutable.isDeeplyFrozenPlainData(msg) && (typeof msg.content === "string" || !msg.content.some((block) => block.type === "image"));
|
|
1010
|
+
const key = recoveryAnchor ? `${projectionKey}:${msgIndex}:${recoveryAnchor}` : `${projectionKey}:${msgIndex}`;
|
|
1011
|
+
let projections = reusable ? responsesMessageProjections.get(msg) : void 0;
|
|
1012
|
+
let output = projections?.get(key);
|
|
1013
|
+
if (!output) {
|
|
1014
|
+
output = convertMessage(msg, msgIndex);
|
|
1015
|
+
if (reusable) {
|
|
1016
|
+
immutable.freezeJsonSnapshot(output);
|
|
1017
|
+
if (!projections) {
|
|
1018
|
+
projections = /* @__PURE__ */ new Map();
|
|
1019
|
+
responsesMessageProjections.set(msg, projections);
|
|
1020
|
+
}
|
|
1021
|
+
if (projections.size >= 8) {
|
|
1022
|
+
const oldest = projections.keys().next().value;
|
|
1023
|
+
if (oldest !== void 0) projections.delete(oldest);
|
|
1024
|
+
}
|
|
1025
|
+
projections.set(key, output);
|
|
1026
|
+
}
|
|
876
1027
|
}
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
...isSafeResponsesReplayItemId(replay.id) ? { id: replay.id } : {},
|
|
882
|
-
encrypted_content: replay.data
|
|
883
|
-
},
|
|
884
|
-
mode: "compacted-prefix",
|
|
885
|
-
replayIndex: replay.replayIndex ?? 0
|
|
886
|
-
};
|
|
1028
|
+
if (reusable && options?.mutableInput) output = cloneResponsesInputForPayloadHook(output);
|
|
1029
|
+
if (msg.role === "assistant") appendAssistant(messages, output, msg);
|
|
1030
|
+
else messages.push(...output);
|
|
1031
|
+
if (output.length > 0 || !providerStyle) msgIndex += 1;
|
|
887
1032
|
}
|
|
1033
|
+
return messages;
|
|
888
1034
|
}
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
super("Provider compaction checkpoint needs rebuilding. Run /compact to rebuild from saved conversation history.");
|
|
892
|
-
this.name = "CompactionReplayRefreshRequiredError";
|
|
893
|
-
}
|
|
894
|
-
};
|
|
895
|
-
function buildOpenAIResponsesCompactionReplayPlan(messages, model, options) {
|
|
896
|
-
if (options?.mode === "full-history") return {
|
|
897
|
-
messages,
|
|
898
|
-
preserveUnframedToolResults: false
|
|
899
|
-
};
|
|
900
|
-
const compaction = resolveNewestOpenAIResponsesCompactionReplay(messages, model, options);
|
|
901
|
-
if (!compaction) return {
|
|
902
|
-
messages,
|
|
903
|
-
preserveUnframedToolResults: false
|
|
904
|
-
};
|
|
905
|
-
if (compaction.mode === "refresh-required") throw new CompactionReplayRefreshRequiredError();
|
|
906
|
-
const ownerIndex = messages.indexOf(compaction.owner);
|
|
907
|
-
return {
|
|
908
|
-
messages: [{
|
|
909
|
-
...compaction.owner,
|
|
910
|
-
content: compaction.owner.content.slice(compaction.replayIndex)
|
|
911
|
-
}, ...messages.slice(ownerIndex + 1)],
|
|
912
|
-
...compaction.mode === "complete-window" ? { compactedWindow: compaction.output } : { compaction: compaction.item },
|
|
913
|
-
preserveUnframedToolResults: true
|
|
914
|
-
};
|
|
1035
|
+
function convertResponsesMessages(model, context, allowedToolCallProviders, options) {
|
|
1036
|
+
return convertResponsesMessagesWithStyle(model, context, allowedToolCallProviders, options, "transport");
|
|
915
1037
|
}
|
|
916
|
-
function
|
|
1038
|
+
function convertProviderResponsesMessages(model, context, allowedToolCallProviders, options) {
|
|
1039
|
+
return convertResponsesMessagesWithStyle(model, context, allowedToolCallProviders, options, "provider");
|
|
1040
|
+
}
|
|
1041
|
+
//#endregion
|
|
1042
|
+
//#region packages/ai/src/transports/openai-responses-replay-internal.ts
|
|
1043
|
+
function isAsyncIterable(value) {
|
|
1044
|
+
return (typeof value === "object" && value !== null || typeof value === "function") && Symbol.asyncIterator in value;
|
|
1045
|
+
}
|
|
1046
|
+
function isEmittedResponsesItem(item, failedSnapshot = false) {
|
|
1047
|
+
return isRecord(item) && item.type !== "compaction" && !(failedSnapshot && (item.type === "message" || item.type === "reasoning"));
|
|
1048
|
+
}
|
|
1049
|
+
function readResponsesRecoveryEvent(event) {
|
|
1050
|
+
const record = isRecord(event) ? event : void 0;
|
|
1051
|
+
const response = isRecord(record?.response) ? record.response : void 0;
|
|
917
1052
|
return {
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
...buildProviderReplayContext(model, options)
|
|
1053
|
+
failure: record?.type === "response.failed" ? response?.error : record?.type === "error" ? record.error ?? record : void 0,
|
|
1054
|
+
hasResponseOutput: Array.isArray(response?.output) && response.output.some((item) => isEmittedResponsesItem(item, record?.type === "response.failed")) || isEmittedResponsesItem(record?.item) || typeof record?.type === "string" && (record.type.endsWith(".delta") || record.type.includes("_call"))
|
|
921
1055
|
};
|
|
922
1056
|
}
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
1057
|
+
function isInvalidEncryptedContentError(error) {
|
|
1058
|
+
if (!error || typeof error !== "object") return false;
|
|
1059
|
+
const record = error;
|
|
1060
|
+
if (record.code === "invalid_encrypted_content" || record.code === "thinking_signature_invalid") return true;
|
|
1061
|
+
const message = typeof record.message === "string" ? record.message.toLowerCase() : "";
|
|
1062
|
+
return message.includes("invalid_encrypted_content") || message.includes("thinking_signature_invalid") || (record.status === 400 || record.status == null && /(?:^|[\s(])400(?:[\s):]|$)/.test(message)) && (message.includes("could not decrypt the provided encrypted_content") || message.includes("encrypted content") && (message.includes("could not be verified") || message.includes("could not be decrypted or parsed")));
|
|
927
1063
|
}
|
|
928
|
-
function
|
|
929
|
-
|
|
930
|
-
return request.model === "gpt-6-astra" && (mode === void 0 || mode === "standard") && (!isRecord(request.multi_agent) || request.multi_agent.enabled !== true) && request.truncation !== "auto" && (!Array.isArray(request.context_management) || !request.context_management.some((item) => isRecord(item) && item.type === "compaction"));
|
|
1064
|
+
function isResponsesItemConflict(error) {
|
|
1065
|
+
return isRecord(error) && error.code === "item_conflict";
|
|
931
1066
|
}
|
|
932
|
-
|
|
933
|
-
|
|
1067
|
+
/** One repair budget and durable replay receipt shared by HTTP and WebSocket recovery. */
|
|
1068
|
+
function createResponsesItemConflictRecovery(output, model, options) {
|
|
1069
|
+
let anchor;
|
|
1070
|
+
let attempted = false;
|
|
1071
|
+
let applied = false;
|
|
1072
|
+
return {
|
|
1073
|
+
applied: () => {
|
|
1074
|
+
applied = true;
|
|
1075
|
+
},
|
|
1076
|
+
async retry(buildRequest) {
|
|
1077
|
+
if (anchor || options?.signal?.aborted) throw Object.assign(/* @__PURE__ */ new Error("Saved conversation items could not be recovered"), { code: "item_conflict" });
|
|
1078
|
+
anchor = globalThis.crypto.randomUUID();
|
|
1079
|
+
attempted = true;
|
|
1080
|
+
const request = await buildRequest({ itemRecovery: anchor });
|
|
1081
|
+
delete request.previous_response_id;
|
|
1082
|
+
suppressOpenAIResponsesCompaction(output, model, options, void 0, anchor);
|
|
1083
|
+
log.warn(`[responses] item_conflict_recovery sessionHash=${redactIdentifier(options?.sessionId)} outcome=started`);
|
|
1084
|
+
return request;
|
|
1085
|
+
},
|
|
1086
|
+
reject(error) {
|
|
1087
|
+
if (!anchor && isResponsesItemConflict(error)) {
|
|
1088
|
+
anchor = globalThis.crypto.randomUUID();
|
|
1089
|
+
suppressOpenAIResponsesCompaction(output, model, options, void 0, anchor);
|
|
1090
|
+
}
|
|
1091
|
+
},
|
|
1092
|
+
finish() {
|
|
1093
|
+
if (anchor || applied) {
|
|
1094
|
+
const outcome = anchor && !attempted ? "deferred" : output.stopReason === "error" || output.stopReason === "aborted" ? "failed" : "recovered";
|
|
1095
|
+
log.info(`[responses] item_conflict_recovery sessionHash=${redactIdentifier(options?.sessionId)} outcome=${outcome}`);
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
};
|
|
934
1099
|
}
|
|
935
|
-
function
|
|
936
|
-
|
|
1100
|
+
function isOrphanedFunctionCallOutputError(error) {
|
|
1101
|
+
if (!error || typeof error !== "object") return false;
|
|
1102
|
+
const record = error;
|
|
1103
|
+
const message = typeof record.message === "string" ? record.message : "";
|
|
1104
|
+
return /No tool call found for function call output with call_id [A-Za-z0-9_-]+/.test(message);
|
|
937
1105
|
}
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
input.splice(index, 0, item);
|
|
945
|
-
activeEffort = item.reasoning.effort;
|
|
946
|
-
}
|
|
947
|
-
if (steering === "required-input") return input.length === request.input.length ? request : {
|
|
1106
|
+
function commitResponsesEncryptedContentAttempt(attempt, commit) {
|
|
1107
|
+
if (attempt.kind === "compaction-stripped") commit(attempt.rejectedCompaction);
|
|
1108
|
+
}
|
|
1109
|
+
function stripResponsesRequestEncryptedReasoning(request) {
|
|
1110
|
+
const stripped = stripEncryptedReasoningContentFields(request.input);
|
|
1111
|
+
return stripped === request.input ? request : {
|
|
948
1112
|
...request,
|
|
949
|
-
input
|
|
1113
|
+
input: stripped
|
|
950
1114
|
};
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
input.splice(nextUser, 0, {
|
|
957
|
-
type: "configuration_update",
|
|
958
|
-
reasoning: { effort: request.reasoning.effort }
|
|
959
|
-
});
|
|
960
|
-
}
|
|
961
|
-
if (input.length === request.input.length && activeEffort === request.reasoning.effort) return request;
|
|
962
|
-
return {
|
|
1115
|
+
}
|
|
1116
|
+
function stripResponsesRequestCompaction(request) {
|
|
1117
|
+
if (!Array.isArray(request.input)) return request;
|
|
1118
|
+
const input = request.input.filter((item) => !(item !== null && typeof item === "object" && item.type === "compaction"));
|
|
1119
|
+
return input.length === request.input.length ? request : {
|
|
963
1120
|
...request,
|
|
964
|
-
reasoning: {
|
|
965
|
-
...request.reasoning,
|
|
966
|
-
effort: previous.reasoning.effort
|
|
967
|
-
},
|
|
968
1121
|
input
|
|
969
1122
|
};
|
|
970
1123
|
}
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
const
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
1124
|
+
function readOpenAIResponsesCompactionRejection(request) {
|
|
1125
|
+
if (!Array.isArray(request.input)) return;
|
|
1126
|
+
const item = request.input.find((candidate) => candidate !== null && typeof candidate === "object" && candidate.type === "compaction" && typeof candidate.encrypted_content === "string");
|
|
1127
|
+
return item ? {
|
|
1128
|
+
data: item.encrypted_content,
|
|
1129
|
+
...typeof item.id === "string" ? { id: item.id } : {}
|
|
1130
|
+
} : void 0;
|
|
1131
|
+
}
|
|
1132
|
+
async function resolveNextResponsesEncryptedContentAttempt(attempt, error, options) {
|
|
1133
|
+
if (isResponsesItemConflict(error)) return attempt.kind !== "items-reanchored" && options.buildItemConflictRequest ? {
|
|
1134
|
+
kind: "items-reanchored",
|
|
1135
|
+
request: await options.buildItemConflictRequest()
|
|
1136
|
+
} : void 0;
|
|
1137
|
+
const orphanedFunctionOutput = isOrphanedFunctionCallOutputError(error);
|
|
1138
|
+
if (!isInvalidEncryptedContentError(error) && !orphanedFunctionOutput || attempt.kind === "compaction-stripped") return;
|
|
1139
|
+
if (!orphanedFunctionOutput && (attempt.kind === "initial" || attempt.kind === "continuation-rejected")) {
|
|
1140
|
+
const reasoningStripped = stripResponsesRequestEncryptedReasoning(attempt.request);
|
|
1141
|
+
if (reasoningStripped !== attempt.request) return {
|
|
1142
|
+
kind: "reasoning-stripped",
|
|
1143
|
+
request: reasoningStripped
|
|
1144
|
+
};
|
|
1145
|
+
}
|
|
1146
|
+
if (stripResponsesRequestCompaction(attempt.request) === attempt.request) return;
|
|
1147
|
+
let compactionStripped = await options.buildFullHistoryRequest();
|
|
1148
|
+
compactionStripped = stripResponsesRequestCompaction(compactionStripped);
|
|
1149
|
+
if (attempt.kind === "reasoning-stripped") compactionStripped = stripResponsesRequestEncryptedReasoning(compactionStripped);
|
|
988
1150
|
return {
|
|
989
|
-
|
|
990
|
-
|
|
1151
|
+
kind: "compaction-stripped",
|
|
1152
|
+
request: compactionStripped,
|
|
1153
|
+
rejectedCompaction: readOpenAIResponsesCompactionRejection(attempt.request)
|
|
991
1154
|
};
|
|
992
1155
|
}
|
|
993
|
-
function
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
const
|
|
1019
|
-
const
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1156
|
+
async function createResponsesStreamWithRecovery(params) {
|
|
1157
|
+
async function* streamWithTerminalDrain(response, body) {
|
|
1158
|
+
const reader = body.getReader();
|
|
1159
|
+
let terminal = false;
|
|
1160
|
+
let firstFrame = true;
|
|
1161
|
+
const decoder = decodeSseFrames();
|
|
1162
|
+
try {
|
|
1163
|
+
frames: for (let next = decoder.next(); !next.done;) {
|
|
1164
|
+
if (next.value === void 0) {
|
|
1165
|
+
next = decoder.next(await reader.read());
|
|
1166
|
+
continue;
|
|
1167
|
+
}
|
|
1168
|
+
const { frame } = next.value;
|
|
1169
|
+
let eventName = null;
|
|
1170
|
+
let data;
|
|
1171
|
+
let start = 0;
|
|
1172
|
+
let cr = frame.indexOf("\r");
|
|
1173
|
+
let lf = frame.indexOf("\n");
|
|
1174
|
+
while (start < frame.length) {
|
|
1175
|
+
const end = cr < 0 ? lf < 0 ? frame.length : lf : lf < 0 ? cr : Math.min(cr, lf);
|
|
1176
|
+
const lineStart = !(firstFrame && start === 0) && frame.charCodeAt(start) === 65279 ? start + 1 : start;
|
|
1177
|
+
start = end + (frame[end] === "\r" && frame[end + 1] === "\n" ? 2 : 1);
|
|
1178
|
+
if (cr >= 0 && cr < start) cr = frame.indexOf("\r", start);
|
|
1179
|
+
if (lf >= 0 && lf < start) lf = frame.indexOf("\n", start);
|
|
1180
|
+
if (lineStart < end) {
|
|
1181
|
+
const fieldLength = frame.startsWith("data", lineStart) ? 4 : frame.startsWith("event", lineStart) ? 5 : 0;
|
|
1182
|
+
const colon = lineStart + fieldLength;
|
|
1183
|
+
if (fieldLength && (colon === end || frame[colon] === ":")) {
|
|
1184
|
+
const value = colon === end ? "" : frame.slice(colon + (frame[colon + 1] === " " ? 2 : 1), end);
|
|
1185
|
+
if (fieldLength === 5) eventName = value;
|
|
1186
|
+
else data = data === void 0 ? value : `${data}\n${value}`;
|
|
1187
|
+
}
|
|
1188
|
+
if (start < frame.length) continue;
|
|
1189
|
+
}
|
|
1190
|
+
if (!eventName && data === void 0) continue;
|
|
1191
|
+
if (data === "[DONE]") break frames;
|
|
1192
|
+
let event;
|
|
1193
|
+
try {
|
|
1194
|
+
event = JSON.parse(data ?? "");
|
|
1195
|
+
} catch {
|
|
1196
|
+
throw new SyntaxError("Error reading response: malformed server-sent event JSON.");
|
|
1197
|
+
}
|
|
1198
|
+
if (eventName?.startsWith("thread.")) event = {
|
|
1199
|
+
event: eventName,
|
|
1200
|
+
data: event
|
|
1201
|
+
};
|
|
1202
|
+
else if (eventName === "error" || isRecord(event) && event.error) throw new APIError(void 0, isRecord(event) ? event.error ?? event : event, void 0, response.headers);
|
|
1203
|
+
terminal ||= isRecord(event) && (event.type === "response.completed" || event.type === "response.incomplete");
|
|
1204
|
+
yield event;
|
|
1205
|
+
eventName = null;
|
|
1206
|
+
data = void 0;
|
|
1207
|
+
}
|
|
1208
|
+
firstFrame = false;
|
|
1209
|
+
next = decoder.next();
|
|
1210
|
+
}
|
|
1211
|
+
} catch (error) {
|
|
1212
|
+
if (error instanceof APIError || !isRecord(error) || error.name !== "AbortError" && !String(error.message).includes("FetchRequestCanceledException")) throw error;
|
|
1213
|
+
} finally {
|
|
1214
|
+
if (!terminal) {
|
|
1215
|
+
await reader.cancel().catch(() => void 0);
|
|
1216
|
+
reader.releaseLock();
|
|
1217
|
+
} else {
|
|
1218
|
+
const controller = new AbortController();
|
|
1219
|
+
const unregister = registerSessionResourceCleanup((sessionId) => {
|
|
1220
|
+
if (!sessionId) controller.abort();
|
|
1221
|
+
});
|
|
1222
|
+
const signal = AbortSignal.any([
|
|
1223
|
+
controller.signal,
|
|
1224
|
+
AbortSignal.timeout(250),
|
|
1225
|
+
...params.requestOptions?.signal ? [params.requestOptions.signal] : []
|
|
1226
|
+
]);
|
|
1227
|
+
const cancel = () => {
|
|
1228
|
+
reader.cancel().catch(() => void 0);
|
|
1229
|
+
};
|
|
1230
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
1231
|
+
(async () => {
|
|
1232
|
+
try {
|
|
1233
|
+
let bytes = 0;
|
|
1234
|
+
while (!signal.aborted && bytes < 65536) {
|
|
1235
|
+
const { done, value } = await reader.read();
|
|
1236
|
+
if (done) break;
|
|
1237
|
+
bytes += value.byteLength;
|
|
1238
|
+
}
|
|
1239
|
+
} catch {} finally {
|
|
1240
|
+
cancel();
|
|
1241
|
+
reader.releaseLock();
|
|
1242
|
+
signal.removeEventListener("abort", cancel);
|
|
1243
|
+
unregister();
|
|
1244
|
+
}
|
|
1245
|
+
})();
|
|
1246
|
+
}
|
|
1043
1247
|
}
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1248
|
+
}
|
|
1249
|
+
const encodeBody = params.encodeBody ?? prepareModelRequestBody(void 0);
|
|
1250
|
+
let tierCeiling;
|
|
1251
|
+
const limitTier = (request) => tierCeiling && (request.service_tier === "ultrafast" || tierCeiling === "default" && request.service_tier === "priority") ? {
|
|
1252
|
+
...request,
|
|
1253
|
+
service_tier: tierCeiling
|
|
1254
|
+
} : request;
|
|
1255
|
+
const recoverServiceTier = (attempt, error) => {
|
|
1256
|
+
if (params.requestOptions?.signal?.aborted || !supportsNativeOpenAIResponsesEndpoint(params.model)) return;
|
|
1257
|
+
const tier = attempt.request.service_tier;
|
|
1258
|
+
const next = nextResponsesServiceTier(tier, error);
|
|
1259
|
+
if (!next || tier !== "ultrafast" && tier !== "priority") return;
|
|
1260
|
+
tierCeiling = next;
|
|
1261
|
+
params.onServiceTierRejected?.(tier);
|
|
1262
|
+
log.info(`[responses] rejected ${tier} tier; retrying with ${next}`);
|
|
1263
|
+
return {
|
|
1264
|
+
...attempt,
|
|
1265
|
+
request: {
|
|
1266
|
+
...attempt.request,
|
|
1267
|
+
service_tier: next
|
|
1268
|
+
}
|
|
1269
|
+
};
|
|
1270
|
+
};
|
|
1271
|
+
const send = async (initialAttempt) => {
|
|
1272
|
+
let attempt = initialAttempt;
|
|
1273
|
+
for (;;) {
|
|
1274
|
+
const cappedRequest = limitTier(attempt.request);
|
|
1275
|
+
if (cappedRequest !== attempt.request) attempt = {
|
|
1276
|
+
kind: attempt.kind,
|
|
1277
|
+
request: cappedRequest,
|
|
1278
|
+
rejectedCompaction: attempt.rejectedCompaction
|
|
1279
|
+
};
|
|
1280
|
+
params.observePrompt?.(attempt.request, {
|
|
1281
|
+
egress: "responses-sdk",
|
|
1282
|
+
payloadVariant: attempt.kind
|
|
1283
|
+
});
|
|
1284
|
+
const bodyOptions = await encodeBody(attempt.request);
|
|
1285
|
+
let responseAccepted = false;
|
|
1286
|
+
try {
|
|
1287
|
+
const { data, response } = await params.client.responses.create(attempt.request, {
|
|
1288
|
+
...params.requestOptions,
|
|
1289
|
+
...bodyOptions,
|
|
1290
|
+
headers: {
|
|
1291
|
+
...bodyOptions.headers,
|
|
1292
|
+
...params.requestOptions?.headers
|
|
1293
|
+
}
|
|
1294
|
+
}).withResponse();
|
|
1295
|
+
responseAccepted = true;
|
|
1296
|
+
commitResponsesEncryptedContentAttempt(attempt, (checkpoint) => {
|
|
1297
|
+
if (checkpoint) params.onCompactionRejected?.(checkpoint);
|
|
1053
1298
|
});
|
|
1054
|
-
|
|
1299
|
+
if (!isAsyncIterable(data)) throw new Error("OpenAI Responses streaming request returned a non-stream response");
|
|
1300
|
+
return {
|
|
1301
|
+
stream: data instanceof Stream && response.body ? streamWithTerminalDrain(response, response.body) : data,
|
|
1302
|
+
response,
|
|
1303
|
+
attempt
|
|
1304
|
+
};
|
|
1305
|
+
} catch (error) {
|
|
1306
|
+
let nextAttempt = (!responseAccepted ? recoverServiceTier(attempt, error) : void 0) ?? await resolveNextResponsesEncryptedContentAttempt(attempt, error, {
|
|
1307
|
+
buildFullHistoryRequest: params.buildFullHistoryRequest,
|
|
1308
|
+
buildItemConflictRequest: params.buildItemConflictRequest
|
|
1309
|
+
});
|
|
1310
|
+
if (!nextAttempt && attempt.request.previous_response_id && error && typeof error === "object" && typeof error.status === "number" && isPreviousResponseRejection(error)) {
|
|
1311
|
+
const request = { ...await params.buildFullHistoryRequest() };
|
|
1312
|
+
delete request.previous_response_id;
|
|
1313
|
+
nextAttempt = {
|
|
1314
|
+
kind: "continuation-rejected",
|
|
1315
|
+
request
|
|
1316
|
+
};
|
|
1317
|
+
}
|
|
1318
|
+
if (!nextAttempt) throw error;
|
|
1319
|
+
const retryDescription = nextAttempt.request.service_tier !== attempt.request.service_tier ? "with a slower service tier" : nextAttempt.kind === "reasoning-stripped" ? "without encrypted reasoning content" : nextAttempt.kind === "compaction-stripped" ? "without encrypted compaction content" : nextAttempt.kind === "items-reanchored" ? "with reanchored conversation items" : "full history after rejected previous_response_id";
|
|
1320
|
+
log.warn(`[responses] retrying ${retryDescription} provider=${params.model.provider} api=${params.model.api} model=${params.model.id}`);
|
|
1321
|
+
attempt = nextAttempt;
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
};
|
|
1325
|
+
const result = await send({
|
|
1326
|
+
kind: params.initialAttemptKind ?? "initial",
|
|
1327
|
+
request: params.request,
|
|
1328
|
+
...params.initialRejectedCompaction ? { rejectedCompaction: params.initialRejectedCompaction } : {}
|
|
1329
|
+
});
|
|
1330
|
+
return { stream: { async *[Symbol.asyncIterator]() {
|
|
1331
|
+
let current = result;
|
|
1332
|
+
let outputObserved = false;
|
|
1333
|
+
for (;;) {
|
|
1334
|
+
let rejectedEvent;
|
|
1335
|
+
let sourceError;
|
|
1336
|
+
const source = current.stream;
|
|
1337
|
+
const providerStream = { async *[Symbol.asyncIterator]() {
|
|
1338
|
+
try {
|
|
1339
|
+
yield* source;
|
|
1340
|
+
} catch (error) {
|
|
1341
|
+
sourceError = error;
|
|
1342
|
+
throw error;
|
|
1343
|
+
}
|
|
1344
|
+
} };
|
|
1345
|
+
try {
|
|
1346
|
+
for await (const event of params.wrapStream?.({
|
|
1347
|
+
...current,
|
|
1348
|
+
stream: providerStream
|
|
1349
|
+
}) ?? providerStream) {
|
|
1350
|
+
const { failure, hasResponseOutput } = readResponsesRecoveryEvent(event);
|
|
1351
|
+
outputObserved ||= hasResponseOutput;
|
|
1352
|
+
if (isRecord(failure) && params.canRetryStream?.() === true && (isInvalidEncryptedContentError(failure) || !outputObserved && isResponsesItemConflict(failure) || !outputObserved && isResponsesServiceTierRejection(failure))) {
|
|
1353
|
+
rejectedEvent = event;
|
|
1354
|
+
const message = typeof failure.message === "string" ? failure.message : "";
|
|
1355
|
+
throw Object.assign(new Error(message), {
|
|
1356
|
+
code: failure.code,
|
|
1357
|
+
status: failure.status,
|
|
1358
|
+
type: failure.type,
|
|
1359
|
+
param: failure.param
|
|
1360
|
+
});
|
|
1361
|
+
}
|
|
1362
|
+
yield event;
|
|
1363
|
+
}
|
|
1364
|
+
return;
|
|
1365
|
+
} catch (error) {
|
|
1366
|
+
const nextAttempt = params.canRetryStream?.() === true && !params.requestOptions?.signal?.aborted ? (!outputObserved && (rejectedEvent !== void 0 || sourceError === error) ? recoverServiceTier(current.attempt, error) : void 0) ?? await resolveNextResponsesEncryptedContentAttempt(current.attempt, error, {
|
|
1367
|
+
buildFullHistoryRequest: params.buildFullHistoryRequest,
|
|
1368
|
+
buildItemConflictRequest: !outputObserved && (rejectedEvent !== void 0 || sourceError === error) ? params.buildItemConflictRequest : void 0
|
|
1369
|
+
}) : void 0;
|
|
1370
|
+
if (!nextAttempt) {
|
|
1371
|
+
if (rejectedEvent !== void 0) {
|
|
1372
|
+
yield rejectedEvent;
|
|
1373
|
+
return;
|
|
1374
|
+
}
|
|
1375
|
+
throw error;
|
|
1376
|
+
}
|
|
1377
|
+
log.warn(`[responses] retrying explicitly rejected stream provider=${params.model.provider} api=${params.model.api} model=${params.model.id}`);
|
|
1378
|
+
current = await send(nextAttempt);
|
|
1055
1379
|
}
|
|
1056
1380
|
}
|
|
1057
|
-
|
|
1058
|
-
} finally {
|
|
1059
|
-
ancestors.delete(value);
|
|
1060
|
-
}
|
|
1381
|
+
} } };
|
|
1061
1382
|
}
|
|
1062
|
-
function
|
|
1063
|
-
|
|
1064
|
-
return projected === void 0 ? JSON.parse("undefined") : projected;
|
|
1383
|
+
function resolveAzureOpenAIApiVersion(env = process.env) {
|
|
1384
|
+
return env.AZURE_OPENAI_API_VERSION?.trim() || "preview";
|
|
1065
1385
|
}
|
|
1066
|
-
|
|
1067
|
-
|
|
1386
|
+
//#endregion
|
|
1387
|
+
//#region packages/ai/src/transports/openai-transport-params.ts
|
|
1388
|
+
const MAX_OPENAI_STRICT_TOOL_DOWNGRADE_DIAGNOSTIC_KEYS = 256;
|
|
1389
|
+
const loggedOpenAIStrictToolDowngradeDiagnosticKeys = /* @__PURE__ */ new Set();
|
|
1390
|
+
const OPENAI_COMPLETIONS_APIS = /* @__PURE__ */ new Set(["openai-completions", "openclaw-openai-completions-transport"]);
|
|
1391
|
+
function readToolPayloadField(record, field) {
|
|
1392
|
+
try {
|
|
1393
|
+
return Object.hasOwn(record, field) ? record[field] : void 0;
|
|
1394
|
+
} catch {
|
|
1395
|
+
return;
|
|
1396
|
+
}
|
|
1068
1397
|
}
|
|
1069
|
-
function
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1398
|
+
function readCodeModePayloadToolName(tool) {
|
|
1399
|
+
if (!isRecord(tool)) return;
|
|
1400
|
+
const name = readToolPayloadField(tool, "name");
|
|
1401
|
+
if (typeof name === "string") return name;
|
|
1402
|
+
const fn = readToolPayloadField(tool, "function");
|
|
1403
|
+
if (!isRecord(fn)) return;
|
|
1404
|
+
const fnName = readToolPayloadField(fn, "name");
|
|
1405
|
+
return typeof fnName === "string" ? fnName : void 0;
|
|
1077
1406
|
}
|
|
1078
|
-
function
|
|
1079
|
-
if (
|
|
1080
|
-
const
|
|
1081
|
-
if (
|
|
1082
|
-
|
|
1407
|
+
function readCodeModePayloadToolIdentity(tool, visibleToolNames, allowedHostedToolTypes) {
|
|
1408
|
+
if (!isRecord(tool)) return;
|
|
1409
|
+
const type = readToolPayloadField(tool, "type");
|
|
1410
|
+
if (typeof type === "string" && allowedHostedToolTypes?.has(type)) {
|
|
1411
|
+
try {
|
|
1412
|
+
if (Object.hasOwn(tool, "name") || Object.hasOwn(tool, "function") || Object.hasOwn(tool, "functionDeclarations") || Object.hasOwn(tool, "function_declarations")) return false;
|
|
1413
|
+
} catch {
|
|
1414
|
+
return false;
|
|
1415
|
+
}
|
|
1416
|
+
return `hosted:${type}`;
|
|
1417
|
+
}
|
|
1418
|
+
const name = readCodeModePayloadToolName(tool);
|
|
1419
|
+
return typeof name === "string" && isCodeModeModelVisibleToolName(name, visibleToolNames) ? `client:${name}` : void 0;
|
|
1083
1420
|
}
|
|
1084
|
-
function
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1421
|
+
function readCodeModePayloadToolIdentities(payload) {
|
|
1422
|
+
if (!isRecord(payload)) return [];
|
|
1423
|
+
const tools = readToolPayloadField(payload, "tools");
|
|
1424
|
+
if (!Array.isArray(tools)) return [];
|
|
1425
|
+
return tools.flatMap((tool) => {
|
|
1426
|
+
if (!isRecord(tool)) return [];
|
|
1427
|
+
const identities = [];
|
|
1428
|
+
const name = readCodeModePayloadToolName(tool);
|
|
1429
|
+
if (name) identities.push(`client:${name}`);
|
|
1430
|
+
for (const key of ["functionDeclarations", "function_declarations"]) {
|
|
1431
|
+
const declarations = readToolPayloadField(tool, key);
|
|
1432
|
+
if (!Array.isArray(declarations)) continue;
|
|
1433
|
+
for (const declaration of declarations) {
|
|
1434
|
+
const declarationName = readCodeModePayloadToolName(declaration);
|
|
1435
|
+
if (declarationName) identities.push(`client:${declarationName}`);
|
|
1436
|
+
}
|
|
1437
|
+
}
|
|
1438
|
+
const type = readToolPayloadField(tool, "type");
|
|
1439
|
+
if (typeof type === "string" && type !== "function") identities.push(`hosted:${type}`);
|
|
1440
|
+
return identities;
|
|
1091
1441
|
});
|
|
1092
1442
|
}
|
|
1093
|
-
function
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1443
|
+
function filterCodeModePayloadTools(payload, visibleToolNames, allowedHostedToolTypes, observer) {
|
|
1444
|
+
if (!isRecord(payload)) return;
|
|
1445
|
+
const tools = readToolPayloadField(payload, "tools");
|
|
1446
|
+
if (!Array.isArray(tools)) return;
|
|
1447
|
+
const beforeToolIdentities = observer ? readCodeModePayloadToolIdentities(payload) : void 0;
|
|
1448
|
+
payload.tools = tools.flatMap((tool) => {
|
|
1449
|
+
const identity = readCodeModePayloadToolIdentity(tool, visibleToolNames, allowedHostedToolTypes);
|
|
1450
|
+
if (identity) return [tool];
|
|
1451
|
+
if (identity === false) return [];
|
|
1452
|
+
if (!isRecord(tool)) return [];
|
|
1453
|
+
const filteredGroups = {};
|
|
1454
|
+
for (const key of ["functionDeclarations", "function_declarations"]) {
|
|
1455
|
+
const declarations = readToolPayloadField(tool, key);
|
|
1456
|
+
if (!Array.isArray(declarations)) continue;
|
|
1457
|
+
const filtered = declarations.filter((declaration) => {
|
|
1458
|
+
const declarationName = readCodeModePayloadToolName(declaration);
|
|
1459
|
+
return typeof declarationName === "string" && isCodeModeModelVisibleToolName(declarationName, visibleToolNames);
|
|
1460
|
+
});
|
|
1461
|
+
if (filtered.length > 0) filteredGroups[key] = filtered;
|
|
1462
|
+
}
|
|
1463
|
+
return Object.keys(filteredGroups).length > 0 ? [filteredGroups] : [];
|
|
1464
|
+
});
|
|
1465
|
+
if (beforeToolIdentities) observer?.({
|
|
1466
|
+
beforeToolIdentities,
|
|
1467
|
+
afterToolIdentities: readCodeModePayloadToolIdentities(payload)
|
|
1468
|
+
});
|
|
1099
1469
|
}
|
|
1100
|
-
function
|
|
1101
|
-
|
|
1102
|
-
for (const [index, call] of calls.entries()) for (const replayShape of toolCallReplayShapes(call)) {
|
|
1103
|
-
const owner = ownerByReplayShape.get(replayShape);
|
|
1104
|
-
ownerByReplayShape.set(replayShape, owner === void 0 || owner === index ? index : null);
|
|
1105
|
-
}
|
|
1106
|
-
return ownerByReplayShape;
|
|
1470
|
+
function resolveCodeModeResponsesVisibleToolNames(context) {
|
|
1471
|
+
return new Set((context.tools ?? []).map(readCodeModePayloadToolName).filter((name) => typeof name === "string"));
|
|
1107
1472
|
}
|
|
1108
|
-
function
|
|
1109
|
-
|
|
1110
|
-
const
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
const input = lastRequest.input ?? [];
|
|
1118
|
-
const ownerByReplayShape = toolCallOwnerByReplayShape(uniqueCalls);
|
|
1119
|
-
const replayedCallIds = /* @__PURE__ */ new Set();
|
|
1120
|
-
const lastCallPosition = /* @__PURE__ */ new Map();
|
|
1121
|
-
const lastOutputPosition = /* @__PURE__ */ new Map();
|
|
1122
|
-
for (const [inputIndex, item] of input.entries()) {
|
|
1123
|
-
if (!isRecord(item) || typeof item.call_id !== "string") continue;
|
|
1124
|
-
const owner = ownerByReplayShape.get(item.call_id);
|
|
1125
|
-
if (item.type === "function_call") replayedCallIds.add(item.call_id);
|
|
1126
|
-
const positions = item.type === "function_call" ? lastCallPosition : item.type === "function_call_output" ? lastOutputPosition : void 0;
|
|
1127
|
-
if (positions && owner !== void 0 && owner !== null) positions.set(owner, inputIndex);
|
|
1128
|
-
}
|
|
1129
|
-
const pendingToolCalls = uniqueCalls.filter((_call, index) => {
|
|
1130
|
-
const callPosition = lastCallPosition.get(index);
|
|
1131
|
-
return [...toolCallReplayShapes(_call)].some((shape) => replayedCallIds.has(shape)) && (callPosition === void 0 || (lastOutputPosition.get(index) ?? -1) < callPosition);
|
|
1473
|
+
function enforceCodeModeResponsesToolSurface(payload, visibleToolNames, allowedHostedToolTypes, observer) {
|
|
1474
|
+
if (!isRecord(payload)) return;
|
|
1475
|
+
const tools = readToolPayloadField(payload, "tools");
|
|
1476
|
+
if (!Array.isArray(tools)) return;
|
|
1477
|
+
const beforeToolIdentities = observer ? readCodeModePayloadToolIdentities(payload) : void 0;
|
|
1478
|
+
payload.tools = tools.filter((tool) => Boolean(readCodeModePayloadToolIdentity(tool, visibleToolNames, allowedHostedToolTypes)));
|
|
1479
|
+
if (beforeToolIdentities) observer?.({
|
|
1480
|
+
beforeToolIdentities,
|
|
1481
|
+
afterToolIdentities: readCodeModePayloadToolIdentities(payload)
|
|
1132
1482
|
});
|
|
1133
|
-
return {
|
|
1134
|
-
lastRequest,
|
|
1135
|
-
lastResponseId: response.id,
|
|
1136
|
-
lastResponseItems: response.output.filter((item) => item.type !== "web_search_call"),
|
|
1137
|
-
pendingToolCalls
|
|
1138
|
-
};
|
|
1139
1483
|
}
|
|
1140
|
-
function
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1484
|
+
function assertCodeModeResponsesToolSurface(payload, visibleToolNames, allowedHostedToolTypes) {
|
|
1485
|
+
const tools = isRecord(payload) ? readToolPayloadField(payload, "tools") : void 0;
|
|
1486
|
+
if (!Array.isArray(tools)) throw new Error("Code mode payload tool surface violation: expected exec,wait; got no tools");
|
|
1487
|
+
const identities = tools.map((tool) => readCodeModePayloadToolIdentity(tool, visibleToolNames, allowedHostedToolTypes));
|
|
1488
|
+
const names = identities.flatMap((identity) => typeof identity === "string" && identity.startsWith("client:") ? [identity.slice(7)] : []).toSorted((left, right) => left.localeCompare(right));
|
|
1489
|
+
if (names.length >= 2 && identities.every((identity) => typeof identity === "string") && new Set(identities).size === identities.length && names.includes("exec") && names.includes("wait")) return;
|
|
1490
|
+
throw new Error(`Code mode payload tool surface violation: expected exec,wait plus direct-only tools; got ${names.length > 0 ? names.join(",") : "none"}`);
|
|
1491
|
+
}
|
|
1492
|
+
function resolveOpenAIStrictToolFlagWithDiagnostics(projection, strictSetting, context) {
|
|
1493
|
+
const strict = resolveOpenAIProjectedToolsStrictToolFlag(projection, strictSetting);
|
|
1494
|
+
if (strictSetting === true && strict === false) getAiTransportHost().logDebug("openai-transport", () => {
|
|
1495
|
+
const diagnostics = findOpenAIStrictToolProjectionDiagnostics(projection);
|
|
1496
|
+
const key = sha256Hex(JSON.stringify({
|
|
1497
|
+
transport: context.transport,
|
|
1498
|
+
provider: context.model.provider ?? null,
|
|
1499
|
+
model: context.model.id ?? null,
|
|
1500
|
+
diagnostics: diagnostics.map((entry) => ({
|
|
1501
|
+
toolIndex: entry.toolIndex,
|
|
1502
|
+
toolName: entry.toolName ?? null,
|
|
1503
|
+
violations: entry.violations
|
|
1504
|
+
}))
|
|
1505
|
+
}));
|
|
1506
|
+
if (loggedOpenAIStrictToolDowngradeDiagnosticKeys.has(key)) return null;
|
|
1507
|
+
if (loggedOpenAIStrictToolDowngradeDiagnosticKeys.size >= MAX_OPENAI_STRICT_TOOL_DOWNGRADE_DIAGNOSTIC_KEYS) loggedOpenAIStrictToolDowngradeDiagnosticKeys.clear();
|
|
1508
|
+
loggedOpenAIStrictToolDowngradeDiagnosticKeys.add(key);
|
|
1509
|
+
const sample = diagnostics.slice(0, 5).map((entry) => ({
|
|
1510
|
+
tool: entry.toolName ?? `tool[${entry.toolIndex}]`,
|
|
1511
|
+
violations: entry.violations.slice(0, 8)
|
|
1512
|
+
}));
|
|
1513
|
+
return {
|
|
1514
|
+
message: `OpenAI ${context.transport} tool schema strict mode downgraded to strict=false for ${context.model.provider ?? "unknown"}/${context.model.id ?? "unknown"} because ${diagnostics.length} tool schema(s) are not strict-compatible`,
|
|
1515
|
+
data: {
|
|
1516
|
+
transport: context.transport,
|
|
1517
|
+
provider: context.model.provider,
|
|
1518
|
+
model: context.model.id,
|
|
1519
|
+
incompatibleToolCount: diagnostics.length,
|
|
1520
|
+
sample
|
|
1521
|
+
}
|
|
1522
|
+
};
|
|
1164
1523
|
});
|
|
1524
|
+
return strict;
|
|
1165
1525
|
}
|
|
1166
|
-
function
|
|
1167
|
-
const
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1526
|
+
function buildOpenAIClientHeaders(model, context, optionHeaders, turnHeaders, sessionId, cacheRetention) {
|
|
1527
|
+
const providerHeaders = { ...model.headers };
|
|
1528
|
+
if (model.provider === "github-copilot") Object.assign(providerHeaders, getAiTransportHost().buildCopilotDynamicHeaders(context.messages));
|
|
1529
|
+
if (OPENAI_COMPLETIONS_APIS.has(model.api) && sessionId && cacheRetention !== "none") {
|
|
1530
|
+
const { sessionAffinity } = resolveOpenAICompletionsCompat(model);
|
|
1531
|
+
if (sessionAffinity !== "none") {
|
|
1532
|
+
const affinityValue = clampOpenAIPromptCacheKey(sessionId) ?? sessionId;
|
|
1533
|
+
const affinityHeaders = sessionAffinity === "openrouter" ? ["x-session-id"] : [
|
|
1534
|
+
"session_id",
|
|
1535
|
+
"x-client-request-id",
|
|
1536
|
+
"x-session-affinity"
|
|
1537
|
+
];
|
|
1538
|
+
const configuredHeaders = new Set(Object.keys(providerHeaders).map((key) => key.toLowerCase()));
|
|
1539
|
+
for (const name of affinityHeaders) if (!configuredHeaders.has(name)) providerHeaders[name] = affinityValue;
|
|
1180
1540
|
}
|
|
1181
|
-
if (item.type !== "function_call_output" || typeof item.call_id !== "string") continue;
|
|
1182
|
-
const owner = ownerByReplayShape.get(item.call_id);
|
|
1183
|
-
if (owner === null) return;
|
|
1184
|
-
normalizedItem.call_id = owner === void 0 ? { unknownCallId: canonicalizeToolCallId(item.call_id, void 0) } : { callOwner: owner };
|
|
1185
1541
|
}
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
return sha256StableValue(projectJsonObject(requestWithoutInput(request))).digest;
|
|
1190
|
-
}
|
|
1191
|
-
function responsesContinuationPrefixFingerprint(input, output = []) {
|
|
1192
|
-
return sha256StableValue(projectJsonObject([...normalizeAssistantReplayInput(input), ...normalizeAssistantReplayInput(output, true)])).digest;
|
|
1193
|
-
}
|
|
1194
|
-
function resolveResponsesContinuationRequest(continuation, request, steering) {
|
|
1195
|
-
if (!continuation) return {
|
|
1196
|
-
request,
|
|
1197
|
-
continuationStatus: "no_previous_response"
|
|
1198
|
-
};
|
|
1199
|
-
if (request.previous_response_id) return {
|
|
1200
|
-
request,
|
|
1201
|
-
continuationStatus: "explicit_previous_response_id"
|
|
1542
|
+
const callerHeaders = {
|
|
1543
|
+
...optionHeaders,
|
|
1544
|
+
...turnHeaders
|
|
1202
1545
|
};
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1546
|
+
const resolvedHeaders = getAiTransportHost().resolveProviderRequestHeaders({
|
|
1547
|
+
provider: model.provider,
|
|
1548
|
+
api: model.api,
|
|
1549
|
+
baseUrl: model.baseUrl,
|
|
1550
|
+
providerHeaders,
|
|
1551
|
+
callerHeaders: Object.keys(callerHeaders).length > 0 ? callerHeaders : void 0,
|
|
1552
|
+
precedence: "caller-wins",
|
|
1553
|
+
model
|
|
1554
|
+
}) ?? {};
|
|
1555
|
+
const sendSessionIdHeader = (OPENAI_RESPONSES_APIS.has(model.api) && model.compat && "sendSessionIdHeader" in model.compat ? model.compat?.sendSessionIdHeader : void 0) ?? usesNativeOpenAICodexResponsesBackend(model);
|
|
1556
|
+
if (sessionId && cacheRetention !== "none" && sendSessionIdHeader && !Object.keys(resolvedHeaders).some((key) => normalizeLowercaseStringOrEmpty(key) === "session_id")) resolvedHeaders.session_id = clampOpenAIPromptCacheKey(sessionId) ?? sessionId;
|
|
1557
|
+
return resolveOpencodeSessionHeaders(model, {
|
|
1558
|
+
sessionId,
|
|
1559
|
+
headers: resolvedHeaders
|
|
1560
|
+
}) ?? resolvedHeaders;
|
|
1561
|
+
}
|
|
1562
|
+
function buildOpenAISdkClientOptions(model) {
|
|
1563
|
+
const timeout = resolveModelRequestTimeoutMs(model);
|
|
1564
|
+
return {
|
|
1565
|
+
...timeout === void 0 ? {} : { timeout },
|
|
1566
|
+
maxRetries: 0
|
|
1206
1567
|
};
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1568
|
+
}
|
|
1569
|
+
function buildOpenAISdkRequestOptions(model, signal, options) {
|
|
1570
|
+
const timeout = resolveModelRequestTimeoutMs(model, options?.timeoutMs);
|
|
1571
|
+
const headers = options?.stream === true && usesNativeOpenAICodexResponsesBackend(model) ? { Accept: "text/event-stream" } : void 0;
|
|
1572
|
+
if (timeout === void 0 && !signal && !headers) return;
|
|
1573
|
+
return {
|
|
1574
|
+
...headers ? { headers } : {},
|
|
1575
|
+
...signal ? { signal } : {},
|
|
1576
|
+
...timeout !== void 0 ? { timeout } : {},
|
|
1577
|
+
maxRetries: 0
|
|
1211
1578
|
};
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
const
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1579
|
+
}
|
|
1580
|
+
function getCompat(model) {
|
|
1581
|
+
const resolved = resolveOpenAICompletionsCompat(model);
|
|
1582
|
+
const compat = model.compat ?? {};
|
|
1583
|
+
return {
|
|
1584
|
+
...resolved,
|
|
1585
|
+
reasoningEffortMap: resolveOpenAIReasoningEffortMap(model, {}),
|
|
1586
|
+
openRouterRouting: resolved.openRouterRouting ?? {},
|
|
1587
|
+
requiresStringContent: compat.requiresStringContent ?? false,
|
|
1588
|
+
strictMessageKeys: compat.strictMessageKeys === true
|
|
1218
1589
|
};
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
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 {
|
|
1243
|
-
request,
|
|
1244
|
-
continuationStatus: "history_changed"
|
|
1590
|
+
}
|
|
1591
|
+
//#endregion
|
|
1592
|
+
//#region packages/ai/src/providers/openai-tool-projection.ts
|
|
1593
|
+
function unreadableToolDiagnostic(toolIndex) {
|
|
1594
|
+
return {
|
|
1595
|
+
toolIndex,
|
|
1596
|
+
violations: [`tool[${toolIndex}] is unreadable`]
|
|
1245
1597
|
};
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1598
|
+
}
|
|
1599
|
+
/** Snapshots direct/custom tool descriptors before OpenAI payload construction. */
|
|
1600
|
+
function projectOpenAITools(tools) {
|
|
1601
|
+
return projectOpenAIToolDescriptors(tools);
|
|
1602
|
+
}
|
|
1603
|
+
/** Package-private facts are consumed before the projection or payload can escape. */
|
|
1604
|
+
function prepareOpenAITools(tools) {
|
|
1605
|
+
const schemas = /* @__PURE__ */ new Map();
|
|
1606
|
+
return {
|
|
1607
|
+
projection: projectOpenAIToolDescriptors(tools, schemas),
|
|
1608
|
+
schemas
|
|
1254
1609
|
};
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1610
|
+
}
|
|
1611
|
+
function projectOpenAIToolDescriptors(tools, schemas) {
|
|
1612
|
+
let inputToolCount;
|
|
1613
|
+
try {
|
|
1614
|
+
inputToolCount = tools.length;
|
|
1615
|
+
} catch {
|
|
1616
|
+
return {
|
|
1617
|
+
inputToolCount: 0,
|
|
1618
|
+
tools: [],
|
|
1619
|
+
diagnostics: [unreadableToolDiagnostic(0)]
|
|
1263
1620
|
};
|
|
1264
1621
|
}
|
|
1265
|
-
const
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1622
|
+
const projectedTools = [];
|
|
1623
|
+
const diagnostics = [];
|
|
1624
|
+
for (let toolIndex = 0; toolIndex < inputToolCount; toolIndex += 1) {
|
|
1625
|
+
let tool;
|
|
1626
|
+
let name;
|
|
1627
|
+
let parameters;
|
|
1628
|
+
let readPath = `tool[${toolIndex}]`;
|
|
1629
|
+
try {
|
|
1630
|
+
const candidate = tools[toolIndex];
|
|
1631
|
+
if (!candidate) {
|
|
1632
|
+
diagnostics.push(unreadableToolDiagnostic(toolIndex));
|
|
1633
|
+
continue;
|
|
1634
|
+
}
|
|
1635
|
+
tool = candidate;
|
|
1636
|
+
readPath += ".name";
|
|
1637
|
+
const nameValue = tool.name;
|
|
1638
|
+
if (typeof nameValue !== "string" || !nameValue) {
|
|
1639
|
+
diagnostics.push({
|
|
1640
|
+
toolIndex,
|
|
1641
|
+
violations: [`${readPath} is empty`]
|
|
1642
|
+
});
|
|
1643
|
+
continue;
|
|
1644
|
+
}
|
|
1645
|
+
name = nameValue;
|
|
1646
|
+
readPath = `${name}.parameters`;
|
|
1647
|
+
parameters = tool.parameters;
|
|
1648
|
+
} catch {
|
|
1649
|
+
diagnostics.push({
|
|
1650
|
+
toolIndex,
|
|
1651
|
+
...name ? { toolName: name } : {},
|
|
1652
|
+
violations: [`${readPath} is unreadable`]
|
|
1653
|
+
});
|
|
1269
1654
|
continue;
|
|
1270
1655
|
}
|
|
1271
|
-
const
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
}
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
}
|
|
1293
|
-
...prepared !== request ? { fullRequest: prepared } : {},
|
|
1294
|
-
continuationStatus: "continued"
|
|
1295
|
-
};
|
|
1296
|
-
}
|
|
1297
|
-
const httpContinuationEntries = /* @__PURE__ */ new Map();
|
|
1298
|
-
const readyHttpContinuationEntries = /* @__PURE__ */ new Map();
|
|
1299
|
-
let httpContinuationRetainedBytes = 0;
|
|
1300
|
-
function createHttpContinuationTimer(key) {
|
|
1301
|
-
const timer = setTimeout(() => {
|
|
1302
|
-
const entry = httpContinuationEntries.get(key);
|
|
1303
|
-
if (entry?.kind === "ready" && entry.idleTimer === timer) deleteHttpContinuationIfOwned(key, entry);
|
|
1304
|
-
}, HTTP_CONTINUATION_IDLE_TTL_MS);
|
|
1305
|
-
timer.unref?.();
|
|
1306
|
-
return timer;
|
|
1307
|
-
}
|
|
1308
|
-
function deleteHttpContinuationIfOwned(key, entry) {
|
|
1309
|
-
if (httpContinuationEntries.get(key) !== entry) return;
|
|
1310
|
-
if (entry.kind === "ready") {
|
|
1311
|
-
clearTimeout(entry.idleTimer);
|
|
1312
|
-
httpContinuationRetainedBytes -= entry.retainedBytes;
|
|
1313
|
-
readyHttpContinuationEntries.delete(key);
|
|
1314
|
-
}
|
|
1315
|
-
httpContinuationEntries.delete(key);
|
|
1316
|
-
}
|
|
1317
|
-
function evictReadyEntriesForCapacity(pendingBytes) {
|
|
1318
|
-
for (;;) {
|
|
1319
|
-
const overCapacity = readyHttpContinuationEntries.size >= MAX_HTTP_CONTINUATION_READY_ENTRIES;
|
|
1320
|
-
const overBudget = httpContinuationRetainedBytes + pendingBytes > MAX_HTTP_CONTINUATION_RETAINED_BYTES;
|
|
1321
|
-
if (!overCapacity && !overBudget) return;
|
|
1322
|
-
const oldest = readyHttpContinuationEntries.entries().next();
|
|
1323
|
-
if (oldest.done) return;
|
|
1324
|
-
const [oldestKey, oldestEntry] = oldest.value;
|
|
1325
|
-
deleteHttpContinuationIfOwned(oldestKey, oldestEntry);
|
|
1656
|
+
const prepared = schemas ? prepareRuntimeToolInputSchema(parameters ?? {}, `${name}.parameters`, name) : void 0;
|
|
1657
|
+
const schemaProjection = prepared?.projection ?? projectRuntimeToolInputSchema(parameters ?? {}, `${name}.parameters`, name);
|
|
1658
|
+
if (!isRecord(schemaProjection.schema) || schemaProjection.violations.length > 0) {
|
|
1659
|
+
diagnostics.push({
|
|
1660
|
+
toolIndex,
|
|
1661
|
+
toolName: name,
|
|
1662
|
+
violations: schemaProjection.violations.length > 0 ? schemaProjection.violations : [`${name}.parameters must be a JSON object schema`]
|
|
1663
|
+
});
|
|
1664
|
+
continue;
|
|
1665
|
+
}
|
|
1666
|
+
if (prepared?.normalization) schemas?.set(schemaProjection.schema, prepared.normalization);
|
|
1667
|
+
let descriptionValue;
|
|
1668
|
+
try {
|
|
1669
|
+
descriptionValue = tool.description;
|
|
1670
|
+
} catch {}
|
|
1671
|
+
const description = typeof descriptionValue === "string" ? descriptionValue : void 0;
|
|
1672
|
+
projectedTools.push({
|
|
1673
|
+
toolIndex,
|
|
1674
|
+
name,
|
|
1675
|
+
...description !== void 0 ? { description } : {},
|
|
1676
|
+
parameters: schemaProjection.schema
|
|
1677
|
+
});
|
|
1326
1678
|
}
|
|
1327
|
-
}
|
|
1328
|
-
function connectionIdentity(params) {
|
|
1329
|
-
const headers = Object.entries(resolveAiTransportHeaderSentinels(params.headers) ?? {}).map(([name, value]) => [name.toLowerCase(), value]).filter(([name]) => !TURN_HEADERS.has(name)).toSorted(([a], [b]) => a.localeCompare(b));
|
|
1330
|
-
return sha256Hex(JSON.stringify([
|
|
1331
|
-
getAiTransportHost().resolveSecretSentinel(params.apiKey),
|
|
1332
|
-
params.baseUrl,
|
|
1333
|
-
headers
|
|
1334
|
-
]));
|
|
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
1679
|
return {
|
|
1348
|
-
|
|
1349
|
-
|
|
1680
|
+
inputToolCount,
|
|
1681
|
+
tools: projectedTools,
|
|
1682
|
+
diagnostics
|
|
1350
1683
|
};
|
|
1351
1684
|
}
|
|
1352
|
-
function
|
|
1353
|
-
const
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
const
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1685
|
+
function reconcileToolChoice(choice, projection, responses) {
|
|
1686
|
+
const label = responses ? "OpenAI Responses" : "OpenAI Chat Completions";
|
|
1687
|
+
if (choice === "auto") return projection.tools.length > 0 ? choice : void 0;
|
|
1688
|
+
if (choice === "required") {
|
|
1689
|
+
if (projection.tools.length === 0) throw new Error(`${label} tool_choice requires a tool, but no tools survived schema conversion`);
|
|
1690
|
+
return choice;
|
|
1691
|
+
}
|
|
1692
|
+
if (choice === "none" || !isRecord(choice)) return choice;
|
|
1693
|
+
const choiceType = choice.type;
|
|
1694
|
+
if (!responses && choiceType === "custom") throw new Error("OpenAI Chat Completions custom tool_choice is unsupported because this adapter emits function tools only");
|
|
1695
|
+
if (choiceType === "function") {
|
|
1696
|
+
const functionChoice = responses ? choice : choice.function;
|
|
1697
|
+
const functionName = isRecord(functionChoice) ? functionChoice.name : void 0;
|
|
1698
|
+
if (typeof functionName !== "string") return choice;
|
|
1699
|
+
if (!projection.tools.some((tool) => tool.name === functionName)) throw new Error(`${label} tool_choice requested unavailable tool "${functionName}" after schema conversion`);
|
|
1700
|
+
return responses ? {
|
|
1701
|
+
type: "function",
|
|
1702
|
+
name: functionName
|
|
1703
|
+
} : {
|
|
1704
|
+
type: "function",
|
|
1705
|
+
function: { name: functionName }
|
|
1706
|
+
};
|
|
1707
|
+
}
|
|
1708
|
+
if (choiceType !== "allowed_tools") return choice;
|
|
1709
|
+
const allowedConfig = responses ? choice : choice.allowed_tools;
|
|
1710
|
+
if (!isRecord(allowedConfig)) return choice;
|
|
1711
|
+
const { mode, tools } = allowedConfig;
|
|
1712
|
+
if (mode !== "auto" && mode !== "required" || !Array.isArray(tools)) return choice;
|
|
1713
|
+
const responseTools = [];
|
|
1714
|
+
const completionTools = [];
|
|
1715
|
+
for (const tool of tools) {
|
|
1716
|
+
if (!isRecord(tool) || tool.type !== "function") {
|
|
1717
|
+
if (responses) responseTools.push(tool);
|
|
1718
|
+
continue;
|
|
1719
|
+
}
|
|
1720
|
+
const functionChoice = responses ? tool : tool.function;
|
|
1721
|
+
const functionName = isRecord(functionChoice) ? functionChoice.name : void 0;
|
|
1722
|
+
if (typeof functionName === "string" && projection.tools.some((projectedTool) => projectedTool.name === functionName)) {
|
|
1723
|
+
if (responses) responseTools.push({
|
|
1724
|
+
type: "function",
|
|
1725
|
+
name: functionName
|
|
1726
|
+
});
|
|
1727
|
+
else completionTools.push({
|
|
1728
|
+
type: "function",
|
|
1729
|
+
function: { name: functionName }
|
|
1730
|
+
});
|
|
1731
|
+
}
|
|
1732
|
+
}
|
|
1733
|
+
if (responseTools.length === 0 && completionTools.length === 0) {
|
|
1734
|
+
if (mode === "auto") return "none";
|
|
1735
|
+
throw new Error(`${label} tool_choice requires a tool, but no allowed tools survived schema conversion`);
|
|
1736
|
+
}
|
|
1737
|
+
return responses ? {
|
|
1738
|
+
type: "allowed_tools",
|
|
1739
|
+
mode,
|
|
1740
|
+
tools: responseTools
|
|
1741
|
+
} : {
|
|
1742
|
+
type: "allowed_tools",
|
|
1743
|
+
allowed_tools: {
|
|
1744
|
+
mode,
|
|
1745
|
+
tools: completionTools
|
|
1746
|
+
}
|
|
1393
1747
|
};
|
|
1394
1748
|
}
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
//#endregion
|
|
1399
|
-
//#region packages/ai/src/transports/openai-responses-input-replay.ts
|
|
1400
|
-
function recordResponsesInputReplay(message, replay) {
|
|
1401
|
-
if (replay) Object.assign(message, { openclawResponsesInputReplay: replay });
|
|
1402
|
-
}
|
|
1403
|
-
function readResponsesInputReplayState(message) {
|
|
1404
|
-
const replay = "openclawResponsesInputReplay" in message ? message.openclawResponsesInputReplay : void 0;
|
|
1405
|
-
return isRecord(replay) ? replay : void 0;
|
|
1406
|
-
}
|
|
1407
|
-
function readResponsesInputReplay(message) {
|
|
1408
|
-
const replay = readResponsesInputReplayState(message);
|
|
1409
|
-
if (replay && typeof replay.afterResponseId === "string" && isStringArray(replay.before) && isStringArray(replay.after)) return {
|
|
1410
|
-
afterResponseId: replay.afterResponseId,
|
|
1411
|
-
before: replay.before,
|
|
1412
|
-
after: replay.after
|
|
1413
|
-
};
|
|
1749
|
+
/** Keeps Responses tool choices aligned with surviving function schemas. */
|
|
1750
|
+
function reconcileOpenAIResponsesToolChoice(choice, projection) {
|
|
1751
|
+
return reconcileToolChoice(choice, projection, true);
|
|
1414
1752
|
}
|
|
1415
|
-
function
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
call_id: item.call_id
|
|
1419
|
-
}));
|
|
1420
|
-
return sha256Hex(stableStringify(item));
|
|
1753
|
+
/** Keeps Chat Completions tool choices aligned with surviving function schemas. */
|
|
1754
|
+
function reconcileOpenAICompletionsToolChoice(choice, projection) {
|
|
1755
|
+
return reconcileToolChoice(choice, projection, false);
|
|
1421
1756
|
}
|
|
1422
|
-
/**
|
|
1423
|
-
function
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
const fingerprint = (item) => {
|
|
1428
|
-
const value = fingerprints.get(item) ?? responsesInputFingerprint(item);
|
|
1429
|
-
fingerprints.set(item, value);
|
|
1430
|
-
return value;
|
|
1757
|
+
/** Re-expresses an object Chat Completions tool choice in the Responses wire shape. */
|
|
1758
|
+
function toOpenAIResponsesToolChoice(choice) {
|
|
1759
|
+
if (choice.type === "function") return {
|
|
1760
|
+
type: "function",
|
|
1761
|
+
name: choice.function.name
|
|
1431
1762
|
};
|
|
1432
|
-
return
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
const parent = replay ? ends.get(replay.afterResponseId) : void 0;
|
|
1440
|
-
if (replay && parent && message.provider === model.provider && message.api === model.api && message.model === model.id) {
|
|
1441
|
-
const take = (keys) => {
|
|
1442
|
-
const moved = [];
|
|
1443
|
-
for (const inputKey of keys.toReversed()) {
|
|
1444
|
-
const boundary = input.indexOf(parent);
|
|
1445
|
-
const index = input.findLastIndex((item, position) => position > boundary && fingerprint(item) === inputKey);
|
|
1446
|
-
if (index > boundary) moved.unshift(...input.splice(index, 1));
|
|
1447
|
-
}
|
|
1448
|
-
return moved;
|
|
1449
|
-
};
|
|
1450
|
-
const before = take(replay.before);
|
|
1451
|
-
const after = take(replay.after);
|
|
1452
|
-
input.splice(start ? input.indexOf(start) : input.length, 0, ...before);
|
|
1453
|
-
end = input.at(-1);
|
|
1454
|
-
input.push(...after);
|
|
1455
|
-
}
|
|
1456
|
-
if (message.responseId && end) ends.set(message.responseId, end);
|
|
1763
|
+
return {
|
|
1764
|
+
type: "allowed_tools",
|
|
1765
|
+
mode: choice.allowed_tools.mode,
|
|
1766
|
+
tools: choice.allowed_tools.tools.map((tool) => tool.type === "function" && isRecord(tool.function) && typeof tool.function.name === "string" ? {
|
|
1767
|
+
type: "function",
|
|
1768
|
+
name: tool.function.name
|
|
1769
|
+
} : tool)
|
|
1457
1770
|
};
|
|
1458
1771
|
}
|
|
1459
1772
|
//#endregion
|
|
1460
|
-
//#region packages/ai/src/
|
|
1461
|
-
/**
|
|
1462
|
-
function
|
|
1463
|
-
|
|
1464
|
-
if (!params.textSignatureId) return params.fallbackOrdinal === 0 ? params.fallbackId : `${params.fallbackId}_${params.fallbackOrdinal}`;
|
|
1465
|
-
return params.previousReplayItemWasReasoning ? params.textSignatureId : void 0;
|
|
1773
|
+
//#region packages/ai/src/providers/openai-request-reasoning.ts
|
|
1774
|
+
/** Preserve explicit off until the selected route maps it to its native value. */
|
|
1775
|
+
function resolveOpenAISimpleReasoningEffort(model, reasoning) {
|
|
1776
|
+
return reasoning === void 0 ? void 0 : clampThinkingLevel(model, reasoning);
|
|
1466
1777
|
}
|
|
1467
|
-
function
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1778
|
+
function resolveOpenAIRequestReasoning(model, reasoning) {
|
|
1779
|
+
const requested = normalizeOpenAIReasoningEffort(reasoning ?? "off");
|
|
1780
|
+
const modelLevel = MODEL_CATALOG_THINKING_LEVELS.find((candidate) => candidate === requested);
|
|
1781
|
+
const modelMapped = modelLevel ? model.thinkingLevelMap?.[modelLevel] : void 0;
|
|
1782
|
+
const mapped = modelMapped === null ? null : resolveOpenAIReasoningEffortMapping(requested, resolveOpenAIReasoningEffortMap(model)) ?? modelMapped;
|
|
1783
|
+
const intent = mapped !== void 0 ? mapped?.trim() : reasoning === void 0 ? void 0 : requested;
|
|
1784
|
+
const normalizedIntent = normalizeOpenAIReasoningEffort(intent ?? "off");
|
|
1785
|
+
const disabled = requested === "off" || requested === "none";
|
|
1786
|
+
const supported = resolveOpenAIModelReasoningEfforts(disabled && resolveOpenAIThinkingApi(model.api) !== "openai-chatgpt-responses" && !isKnownOpenAIEndpoint(model) ? { compat: model.compat } : model);
|
|
1787
|
+
const effort = !model.reasoning || supported?.length === 0 || intent === void 0 ? void 0 : supported === void 0 ? disabled && mapped === void 0 ? void 0 : intent : resolveOpenAIReasoningEffortForModel({
|
|
1788
|
+
model,
|
|
1789
|
+
effort: requested,
|
|
1790
|
+
fallbackMap: { [requested]: intent }
|
|
1791
|
+
});
|
|
1472
1792
|
return {
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
encrypted_content: item.encrypted_content
|
|
1793
|
+
effort: effort === "none" && resolveOpenAIThinkingApi(model.api) === "openai-chatgpt-responses" && !supportsOpenAIReasoningEffort(model.id === "gpt-6-sol" || model.id === "gpt-6-luna" ? model : {
|
|
1794
|
+
compat: model.compat,
|
|
1795
|
+
thinkingLevelMap: model.thinkingLevelMap
|
|
1796
|
+
}, "none") ? void 0 : effort,
|
|
1797
|
+
thinkingEnabled: intent === void 0 ? void 0 : model.reasoning && normalizedIntent !== "off" && normalizedIntent !== "none"
|
|
1479
1798
|
};
|
|
1480
1799
|
}
|
|
1481
1800
|
//#endregion
|
|
1482
|
-
//#region packages/ai/src/
|
|
1483
|
-
function
|
|
1484
|
-
return
|
|
1485
|
-
v: 1,
|
|
1486
|
-
id,
|
|
1487
|
-
...phase ? { phase } : {}
|
|
1488
|
-
});
|
|
1801
|
+
//#region packages/ai/src/transports/openai-responses-reasoning-update.ts
|
|
1802
|
+
function isConfigurationUpdate(value) {
|
|
1803
|
+
return isRecord(value) && value.type === "configuration_update" && isRecord(value.reasoning) && typeof value.reasoning.effort === "string";
|
|
1489
1804
|
}
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
const supportsDeveloperRole = !isRecord(model.compat) || model.compat.supportsDeveloperRole !== false;
|
|
1494
|
-
return model.reasoning && supportsDeveloperRole ? "developer" : "system";
|
|
1805
|
+
function isResponsesReasoningUpdateCompatible(request) {
|
|
1806
|
+
const mode = isRecord(request.reasoning) ? request.reasoning.mode : void 0;
|
|
1807
|
+
return request.model === "gpt-6-astra" && (mode === void 0 || mode === "standard") && (!isRecord(request.multi_agent) || request.multi_agent.enabled !== true) && request.truncation !== "auto" && (!Array.isArray(request.context_management) || !request.context_management.some((item) => isRecord(item) && item.type === "compaction"));
|
|
1495
1808
|
}
|
|
1496
|
-
function
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1809
|
+
function supportsResponsesReasoningUpdate(request) {
|
|
1810
|
+
return isResponsesReasoningUpdateCompatible(request) && isRecord(request.reasoning) && typeof request.reasoning.effort === "string";
|
|
1811
|
+
}
|
|
1812
|
+
function canReferenceResponsesReasoningHistory(previous, request) {
|
|
1813
|
+
return !previous.input?.some(isConfigurationUpdate) || isResponsesReasoningUpdateCompatible(request);
|
|
1814
|
+
}
|
|
1815
|
+
/** Rehydrate input controls only provisionally; continuation must validate the full prefix. */
|
|
1816
|
+
function replayResponsesReasoningUpdates(previous, request, previousOutputLength, steering) {
|
|
1817
|
+
if (steering !== "required-input" && (!supportsResponsesReasoningUpdate(previous) || !supportsResponsesReasoningUpdate(request)) || !Array.isArray(previous.input) || !Array.isArray(request.input) || request.input.some(isConfigurationUpdate)) return request;
|
|
1818
|
+
const input = [...request.input];
|
|
1819
|
+
let activeEffort = isRecord(previous.reasoning) ? previous.reasoning.effort : void 0;
|
|
1820
|
+
for (const [index, item] of previous.input.entries()) if (isConfigurationUpdate(item)) {
|
|
1821
|
+
input.splice(index, 0, item);
|
|
1822
|
+
activeEffort = item.reasoning.effort;
|
|
1506
1823
|
}
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1824
|
+
if (steering === "required-input") return input.length === request.input.length ? request : {
|
|
1825
|
+
...request,
|
|
1826
|
+
input
|
|
1827
|
+
};
|
|
1828
|
+
if (!isRecord(previous.reasoning) || !isRecord(request.reasoning) || typeof request.reasoning.effort !== "string") return request;
|
|
1829
|
+
if (activeEffort !== request.reasoning.effort && steering !== "automatic") {
|
|
1830
|
+
const baselineLength = previous.input.length + previousOutputLength;
|
|
1831
|
+
const nextUser = input.findIndex((item, index) => index >= baselineLength && "role" in item && item.role === "user");
|
|
1832
|
+
if (nextUser === -1) return request;
|
|
1833
|
+
input.splice(nextUser, 0, {
|
|
1834
|
+
type: "configuration_update",
|
|
1835
|
+
reasoning: { effort: request.reasoning.effort }
|
|
1836
|
+
});
|
|
1519
1837
|
}
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1838
|
+
if (input.length === request.input.length && activeEffort === request.reasoning.effort) return request;
|
|
1839
|
+
return {
|
|
1840
|
+
...request,
|
|
1841
|
+
reasoning: {
|
|
1842
|
+
...request.reasoning,
|
|
1843
|
+
effort: previous.reasoning.effort
|
|
1844
|
+
},
|
|
1845
|
+
input
|
|
1846
|
+
};
|
|
1524
1847
|
}
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1848
|
+
//#endregion
|
|
1849
|
+
//#region packages/ai/src/transports/openai-responses-tool-call-id-shape.ts
|
|
1850
|
+
/**
|
|
1851
|
+
* Pure OpenAI Responses `call_*`/`fc_*` tool-call-id shape helpers.
|
|
1852
|
+
*
|
|
1853
|
+
* Moved out of embedded-agent-helpers/openai.ts (the AgentMessage[]-walking
|
|
1854
|
+
* caller lives in src/agents and imports from packages/ai, so the reverse
|
|
1855
|
+
* import direction is not available) so the continuation transport can
|
|
1856
|
+
* recognize its own cached raw ids after this same reshaping and restore
|
|
1857
|
+
* them on a replayed wire request -- see openai-responses-continuation.ts.
|
|
1858
|
+
*/
|
|
1859
|
+
const OPENAI_RESPONSES_ID_MAX_LENGTH = 64;
|
|
1860
|
+
const OPENAI_RESPONSES_CALL_ID_RE = /^call_[A-Za-z0-9_-]{1,59}$/;
|
|
1861
|
+
const OPENAI_RESPONSES_FUNCTION_CALL_ITEM_ID_RE = /^fc_[A-Za-z0-9_-]{1,61}$/;
|
|
1862
|
+
function splitOpenAIFunctionCallPairing(id) {
|
|
1863
|
+
const separator = id.indexOf("|");
|
|
1864
|
+
if (separator <= 0 || separator >= id.length - 1) return { callId: id };
|
|
1865
|
+
return {
|
|
1866
|
+
callId: id.slice(0, separator),
|
|
1867
|
+
itemId: id.slice(separator + 1)
|
|
1868
|
+
};
|
|
1529
1869
|
}
|
|
1530
|
-
function
|
|
1531
|
-
const
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
const
|
|
1535
|
-
|
|
1536
|
-
|
|
1870
|
+
function normalizeOpenAIResponsesIdPart(value, prefix) {
|
|
1871
|
+
const trimmed = value.trim();
|
|
1872
|
+
if ((prefix === "call_" ? OPENAI_RESPONSES_CALL_ID_RE : OPENAI_RESPONSES_FUNCTION_CALL_ITEM_ID_RE).test(trimmed)) return trimmed;
|
|
1873
|
+
const rawTail = trimmed.startsWith(prefix) ? trimmed.slice(prefix.length) : trimmed;
|
|
1874
|
+
const hash = sha256Hex(trimmed || prefix).slice(0, 10);
|
|
1875
|
+
const maxTailLength = 64 - prefix.length;
|
|
1876
|
+
const hashSuffix = `_${hash}`;
|
|
1877
|
+
return `${prefix}${`${rawTail.replace(/[^A-Za-z0-9_-]/g, "_").replace(/^_+|_+$/g, "").slice(0, Math.max(1, maxTailLength - hashSuffix.length)) || "id"}${hashSuffix}`.slice(0, maxTailLength)}`;
|
|
1537
1878
|
}
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1879
|
+
/** Same shaping `normalizeOpenAIResponsesToolCallIds` applies to a replayed `call_id`/`call_id|fc_id` pair. */
|
|
1880
|
+
function normalizeOpenAIResponsesFunctionCallId(id) {
|
|
1881
|
+
const { callId, itemId } = splitOpenAIFunctionCallPairing(id);
|
|
1882
|
+
const normalizedCallId = normalizeOpenAIResponsesIdPart(itemId ? `${callId}|${itemId}` : callId, "call_");
|
|
1883
|
+
if (!itemId) return normalizedCallId;
|
|
1884
|
+
return `${normalizedCallId}|${normalizeOpenAIResponsesIdPart(itemId, "fc_")}`;
|
|
1542
1885
|
}
|
|
1543
|
-
function
|
|
1544
|
-
const
|
|
1545
|
-
|
|
1886
|
+
function shouldNormalizeOpenAIResponsesToolCallId(id) {
|
|
1887
|
+
const pairing = splitOpenAIFunctionCallPairing(id);
|
|
1888
|
+
if (!OPENAI_RESPONSES_CALL_ID_RE.test(pairing.callId)) return true;
|
|
1889
|
+
if (pairing.itemId === void 0) return false;
|
|
1890
|
+
return !OPENAI_RESPONSES_FUNCTION_CALL_ITEM_ID_RE.test(pairing.itemId);
|
|
1546
1891
|
}
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1892
|
+
//#endregion
|
|
1893
|
+
//#region packages/ai/src/transports/openai-responses-continuation.ts
|
|
1894
|
+
const HTTP_CONTINUATION_IDLE_TTL_MS = 54e5;
|
|
1895
|
+
const MAX_HTTP_CONTINUATION_READY_ENTRIES = 1e3;
|
|
1896
|
+
const MAX_HTTP_CONTINUATION_RETAINED_BYTES = 67108864;
|
|
1897
|
+
const TURN_HEADERS = /* @__PURE__ */ new Set([
|
|
1898
|
+
"traceparent",
|
|
1899
|
+
"x-openclaw-turn-id",
|
|
1900
|
+
"x-openclaw-turn-attempt"
|
|
1901
|
+
]);
|
|
1902
|
+
function projectJsonValue(value, key, ancestors) {
|
|
1903
|
+
if (typeof value === "number") return Number.isFinite(value) ? value + 0 : null;
|
|
1904
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
1905
|
+
if (value === void 0 || typeof value === "symbol") return;
|
|
1906
|
+
if (typeof value !== "object" || isProxy(value) || Object.getPrototypeOf(value) !== (Array.isArray(value) ? Array.prototype : Object.prototype) || "toJSON" in value || ancestors.has(value)) {
|
|
1907
|
+
const projected = JSON.parse(JSON.stringify({
|
|
1908
|
+
__proto__: null,
|
|
1909
|
+
[key]: value
|
|
1910
|
+
}));
|
|
1911
|
+
return Object.hasOwn(projected, key) ? projected[key] : void 0;
|
|
1552
1912
|
}
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
for (const block of message.content) if (block.type === "toolCall" && block.async) owners.set(block.id, key);
|
|
1561
|
-
}
|
|
1913
|
+
ancestors.add(value);
|
|
1914
|
+
try {
|
|
1915
|
+
if (Array.isArray(value)) {
|
|
1916
|
+
const result = [];
|
|
1917
|
+
const length = value.length;
|
|
1918
|
+
for (let index = 0; index < length; index++) result.push(projectJsonValue(value[index], String(index), ancestors) ?? null);
|
|
1919
|
+
return result;
|
|
1562
1920
|
}
|
|
1563
|
-
const
|
|
1564
|
-
const
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1921
|
+
const result = {};
|
|
1922
|
+
for (const name of Object.keys(value)) {
|
|
1923
|
+
const member = projectJsonValue(Reflect.get(value, name), name, ancestors);
|
|
1924
|
+
if (member !== void 0) {
|
|
1925
|
+
if (name in result) Object.defineProperty(result, name, {
|
|
1926
|
+
value: member,
|
|
1927
|
+
enumerable: true,
|
|
1928
|
+
configurable: true,
|
|
1929
|
+
writable: true
|
|
1930
|
+
});
|
|
1931
|
+
else result[name] = member;
|
|
1932
|
+
}
|
|
1574
1933
|
}
|
|
1934
|
+
return result;
|
|
1935
|
+
} finally {
|
|
1936
|
+
ancestors.delete(value);
|
|
1575
1937
|
}
|
|
1576
|
-
return ordered;
|
|
1577
1938
|
}
|
|
1578
|
-
function
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
const parsed = JSON.parse(signature);
|
|
1582
|
-
if (parsed.v === 1) {
|
|
1583
|
-
const id = typeof parsed.id === "string" ? parsed.id : void 0;
|
|
1584
|
-
const phase = parsed.phase === "commentary" || parsed.phase === "final_answer" ? parsed.phase : void 0;
|
|
1585
|
-
if (id !== void 0 || phase !== void 0) return {
|
|
1586
|
-
id,
|
|
1587
|
-
phase,
|
|
1588
|
-
...typeof parsed.sources === "string" ? { sources: parsed.sources } : {}
|
|
1589
|
-
};
|
|
1590
|
-
return;
|
|
1591
|
-
}
|
|
1592
|
-
} catch {}
|
|
1593
|
-
return { id: signature };
|
|
1939
|
+
function projectJsonObject(value) {
|
|
1940
|
+
const projected = projectJsonValue(value, "", /* @__PURE__ */ new Set());
|
|
1941
|
+
return projected === void 0 ? JSON.parse("undefined") : projected;
|
|
1594
1942
|
}
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1943
|
+
function jsonValuesEqual(left, right) {
|
|
1944
|
+
return isDeepStrictEqual(projectJsonObject(left), projectJsonObject(right));
|
|
1945
|
+
}
|
|
1946
|
+
function requestWithoutInput(request) {
|
|
1947
|
+
const { input: _input, previous_response_id: _previousResponseId, instructions: _instructions, tools: _tools, ...rest } = request;
|
|
1948
|
+
if (!isRecord(rest.metadata)) return rest;
|
|
1949
|
+
const metadata = Object.fromEntries(Object.entries(rest.metadata).filter(([key]) => key !== "openclaw_turn_id" && key !== "openclaw_turn_attempt"));
|
|
1950
|
+
return {
|
|
1951
|
+
...rest,
|
|
1952
|
+
metadata
|
|
1953
|
+
};
|
|
1954
|
+
}
|
|
1955
|
+
function canonicalizeToolCallId(callId, itemId) {
|
|
1956
|
+
if (typeof callId !== "string") return callId;
|
|
1957
|
+
const paired = typeof itemId === "string" && itemId ? `${callId}|${itemId}` : callId;
|
|
1958
|
+
if (!shouldNormalizeOpenAIResponsesToolCallId(paired)) return callId;
|
|
1959
|
+
return splitOpenAIFunctionCallPairing(normalizeOpenAIResponsesFunctionCallId(paired)).callId;
|
|
1960
|
+
}
|
|
1961
|
+
function responseToolCalls(items) {
|
|
1962
|
+
return items.flatMap((item) => {
|
|
1963
|
+
if (!isRecord(item) || item.type !== "function_call" || typeof item.call_id !== "string") return [];
|
|
1964
|
+
return [{
|
|
1965
|
+
callId: item.call_id,
|
|
1966
|
+
...typeof item.id === "string" ? { itemId: item.id } : {}
|
|
1967
|
+
}];
|
|
1602
1968
|
});
|
|
1603
|
-
return (input) => typeof input === "object" && input !== null && Reflect.get(input, responsesInputSource) === identity;
|
|
1604
1969
|
}
|
|
1605
|
-
function
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
...identity ? { [responsesInputSource]: identity } : {}
|
|
1612
|
-
};
|
|
1970
|
+
function toolCallReplayShapes(call) {
|
|
1971
|
+
return new Set([
|
|
1972
|
+
call.callId,
|
|
1973
|
+
canonicalizeToolCallId(call.callId, call.itemId),
|
|
1974
|
+
canonicalizeToolCallId(call.callId, void 0)
|
|
1975
|
+
].filter((shape) => typeof shape === "string"));
|
|
1613
1976
|
}
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
return copy;
|
|
1977
|
+
function toolCallOwnerByReplayShape(calls) {
|
|
1978
|
+
const ownerByReplayShape = /* @__PURE__ */ new Map();
|
|
1979
|
+
for (const [index, call] of calls.entries()) for (const replayShape of toolCallReplayShapes(call)) {
|
|
1980
|
+
const owner = ownerByReplayShape.get(replayShape);
|
|
1981
|
+
ownerByReplayShape.set(replayShape, owner === void 0 || owner === index ? index : null);
|
|
1982
|
+
}
|
|
1983
|
+
return ownerByReplayShape;
|
|
1622
1984
|
}
|
|
1623
|
-
function
|
|
1624
|
-
const
|
|
1625
|
-
const
|
|
1626
|
-
const
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
const shouldNormalizeSameModelToolCallIds = model.provider === "github-copilot";
|
|
1632
|
-
const sanitizeIdPart = (part) => {
|
|
1633
|
-
const sanitized = part.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
1634
|
-
return providerStyle ? sanitized : sanitized.replace(/_+$/, "");
|
|
1635
|
-
};
|
|
1636
|
-
const normalizeIdPart = (part) => {
|
|
1637
|
-
const sanitized = sanitizeIdPart(part);
|
|
1638
|
-
return (sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized).replace(/_+$/, "");
|
|
1639
|
-
};
|
|
1640
|
-
const buildForeignResponsesItemId = (itemId) => `fc_${shortHash(itemId)}`;
|
|
1641
|
-
const buildSameProviderCopilotResponsesItemId = (itemId) => {
|
|
1642
|
-
const sanitized = sanitizeIdPart(itemId);
|
|
1643
|
-
const candidate = sanitized.startsWith("fc_") ? sanitized : `fc_${sanitized}`;
|
|
1644
|
-
return candidate.length > 64 ? buildForeignResponsesItemId(itemId) : candidate;
|
|
1645
|
-
};
|
|
1646
|
-
const normalizeToolCallId = (id, _targetModel, source) => {
|
|
1647
|
-
if (!allowedToolCallProviders.has(model.provider) || !id.includes("|")) return normalizeIdPart(id);
|
|
1648
|
-
const separatorIndex = id.indexOf("|");
|
|
1649
|
-
const callId = id.slice(0, separatorIndex);
|
|
1650
|
-
const itemId = id.slice(separatorIndex + 1);
|
|
1651
|
-
const normalizedCallId = normalizeIdPart(callId);
|
|
1652
|
-
let normalizedItemId = source.provider !== model.provider || source.api !== model.api ? buildForeignResponsesItemId(itemId) : model.provider === "github-copilot" ? providerStyle ? normalizeIdPart(itemId) : buildSameProviderCopilotResponsesItemId(itemId) : normalizeIdPart(itemId);
|
|
1653
|
-
if (!normalizedItemId.startsWith("fc_")) normalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);
|
|
1654
|
-
return `${normalizedCallId}|${normalizedItemId}`;
|
|
1655
|
-
};
|
|
1656
|
-
const replayPlan = buildOpenAIResponsesCompactionReplayPlan(context.messages, model, {
|
|
1657
|
-
sessionId: options?.sessionId,
|
|
1658
|
-
authProfileId: options?.authProfileId,
|
|
1659
|
-
mode: options?.replayMode
|
|
1985
|
+
function recordResponsesContinuationState(previous, lastRequest, response, continued = false) {
|
|
1986
|
+
const calls = previous && continued ? [...previous.pendingToolCalls ?? [], ...responseToolCalls(previous.lastResponseItems)] : responseToolCalls(lastRequest.input ?? []);
|
|
1987
|
+
const seenCalls = /* @__PURE__ */ new Set();
|
|
1988
|
+
const uniqueCalls = calls.filter((call) => {
|
|
1989
|
+
const key = JSON.stringify([call.callId, call.itemId]);
|
|
1990
|
+
if (seenCalls.has(key)) return false;
|
|
1991
|
+
seenCalls.add(key);
|
|
1992
|
+
return true;
|
|
1660
1993
|
});
|
|
1661
|
-
const
|
|
1662
|
-
|
|
1663
|
-
|
|
1994
|
+
const input = lastRequest.input ?? [];
|
|
1995
|
+
const ownerByReplayShape = toolCallOwnerByReplayShape(uniqueCalls);
|
|
1996
|
+
const replayedCallIds = /* @__PURE__ */ new Set();
|
|
1997
|
+
const lastCallPosition = /* @__PURE__ */ new Map();
|
|
1998
|
+
const lastOutputPosition = /* @__PURE__ */ new Map();
|
|
1999
|
+
for (const [inputIndex, item] of input.entries()) {
|
|
2000
|
+
if (!isRecord(item) || typeof item.call_id !== "string") continue;
|
|
2001
|
+
const owner = ownerByReplayShape.get(item.call_id);
|
|
2002
|
+
if (item.type === "function_call") replayedCallIds.add(item.call_id);
|
|
2003
|
+
const positions = item.type === "function_call" ? lastCallPosition : item.type === "function_call_output" ? lastOutputPosition : void 0;
|
|
2004
|
+
if (positions && owner !== void 0 && owner !== null) positions.set(owner, inputIndex);
|
|
2005
|
+
}
|
|
2006
|
+
const pendingToolCalls = uniqueCalls.filter((_call, index) => {
|
|
2007
|
+
const callPosition = lastCallPosition.get(index);
|
|
2008
|
+
return [...toolCallReplayShapes(_call)].some((shape) => replayedCallIds.has(shape)) && (callPosition === void 0 || (lastOutputPosition.get(index) ?? -1) < callPosition);
|
|
1664
2009
|
});
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
const
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
if (
|
|
1681
|
-
anchored.splice(insertionIndex++, 0, message);
|
|
1682
|
-
continue;
|
|
1683
|
-
}
|
|
1684
|
-
anchored.push(message);
|
|
1685
|
-
if (!isCarrier(message) && ("role" in message ? message.role === "user" : message.type === "compaction")) insertionIndex = anchored.length;
|
|
2010
|
+
return {
|
|
2011
|
+
lastRequest,
|
|
2012
|
+
lastResponseId: response.id,
|
|
2013
|
+
lastResponseItems: response.output.filter((item) => item.type !== "web_search_call"),
|
|
2014
|
+
pendingToolCalls
|
|
2015
|
+
};
|
|
2016
|
+
}
|
|
2017
|
+
function normalizeAssistantReplayInput(input, fromResponse = false, ignoreCachedItemIds = false, replayedInput) {
|
|
2018
|
+
return input.map((item, index) => {
|
|
2019
|
+
if (!isRecord(item)) return item;
|
|
2020
|
+
if (item.type === "reasoning") return { type: "reasoning" };
|
|
2021
|
+
if (item.type !== "function_call" && item.type !== "function_call_output" && !(item.type === "message" && item.role === "assistant")) return item;
|
|
2022
|
+
const { id: rawId, status: _status, ...stableItem } = item;
|
|
2023
|
+
if (item.type === "function_call_output") {
|
|
2024
|
+
if ("id" in item) stableItem.id = item.id;
|
|
2025
|
+
if ("status" in item) stableItem.status = item.status;
|
|
1686
2026
|
}
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
text: sanitizeTransportPayloadText(runtimeContextContentToText(msg.content))
|
|
1697
|
-
}]));
|
|
1698
|
-
else if (msg.role === "user") {
|
|
1699
|
-
const role = msg.operatorMessage && inHistorySystemUpdates && (typeof msg.content === "string" || msg.content.every((block) => block.type === "text")) ? resolveResponsesInstructionRole(model) : "user";
|
|
1700
|
-
const content = typeof msg.content === "string" ? [{
|
|
1701
|
-
type: "input_text",
|
|
1702
|
-
text: sanitizeTransportPayloadText(msg.content)
|
|
1703
|
-
}] : msg.content.map((item) => item.type === "text" ? {
|
|
1704
|
-
type: "input_text",
|
|
1705
|
-
text: sanitizeTransportPayloadText(item.text)
|
|
1706
|
-
} : buildResponsesInputImage(item)).filter((item) => providerStyle || model.input.includes("image") || item.type !== "input_image");
|
|
1707
|
-
if (content.length > 0) {
|
|
1708
|
-
const input = buildResponsesInputMessage(role, content, msg);
|
|
1709
|
-
if (options?.retainUserProvenance && role === "user" && !msg.synthetic && !msg.operatorMessage && !hasRuntimeContextMarker(msg)) Object.assign(input, { [RESPONSES_RETAINED_USER]: true });
|
|
1710
|
-
converted.push(input);
|
|
1711
|
-
}
|
|
1712
|
-
} else if (msg.role === "assistant") {
|
|
1713
|
-
const output = converted;
|
|
1714
|
-
const sourceTurnKey = responsesAssistantTurnKey(msg);
|
|
1715
|
-
const sourceFragmentId = msg.content.find((block) => block.type === "toolCall")?.id;
|
|
1716
|
-
let textFallbackOrdinal = 0;
|
|
1717
|
-
let previousReplayItemWasReasoning = false;
|
|
1718
|
-
let seenReplayableReasoning = false;
|
|
1719
|
-
const isDifferentModel = msg.model !== model.id && msg.provider === model.provider && msg.api === model.api;
|
|
1720
|
-
for (const block of msg.content) if (block.type === "thinking") {
|
|
1721
|
-
if (block.thinkingSignature && (providerStyle || block.thinkingSignature.startsWith("{"))) {
|
|
1722
|
-
let reasoningItem;
|
|
1723
|
-
try {
|
|
1724
|
-
reasoningItem = JSON.parse(block.thinkingSignature);
|
|
1725
|
-
} catch {
|
|
1726
|
-
continue;
|
|
1727
|
-
}
|
|
1728
|
-
if (!isRecord(reasoningItem) || reasoningItem.type !== "reasoning") continue;
|
|
1729
|
-
const replayableReasoningItem = prepareOpenAIResponsesReasoningItemForReplay(reasoningItem, replayContext, readOpenAIResponsesReasoningReplayBlockMetadata(isRecord(block) ? block : {}), providerStyle ? { preserveUnattributedEncryptedContent: true } : void 0);
|
|
1730
|
-
if (!shouldReplayResponsesItemIds) {
|
|
1731
|
-
delete replayableReasoningItem.id;
|
|
1732
|
-
if (!replayableReasoningItem.encrypted_content) continue;
|
|
1733
|
-
}
|
|
1734
|
-
if (shouldReplayResponsesItemIds && !providerStyle && model.provider === "github-copilot" && !isSafeResponsesReplayItemId(replayableReasoningItem.id)) continue;
|
|
1735
|
-
output.push(replayableReasoningItem);
|
|
1736
|
-
previousReplayItemWasReasoning = true;
|
|
1737
|
-
seenReplayableReasoning ||= typeof replayableReasoningItem.id === "string" && replayableReasoningItem.id.startsWith("rs_");
|
|
1738
|
-
}
|
|
1739
|
-
} else if (block.type === "text") {
|
|
1740
|
-
const textSignature = parseOpenAIResponsesTextSignature(block.textSignature);
|
|
1741
|
-
let msgId = resolveReplayableResponsesMessageId({
|
|
1742
|
-
replayResponsesItemIds: shouldReplayResponsesItemIds,
|
|
1743
|
-
textSignatureId: textSignature?.id,
|
|
1744
|
-
fallbackId: sourceTurnKey ? `msg_${shortHash(JSON.stringify([sourceTurnKey, sourceFragmentId]))}` : `msg_${messageIndex}`,
|
|
1745
|
-
fallbackOrdinal: textFallbackOrdinal,
|
|
1746
|
-
previousReplayItemWasReasoning
|
|
1747
|
-
});
|
|
1748
|
-
if (!textSignature?.id) textFallbackOrdinal += 1;
|
|
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;
|
|
1752
|
-
const messageItem = {
|
|
1753
|
-
type: "message",
|
|
1754
|
-
role: "assistant",
|
|
1755
|
-
content: [{
|
|
1756
|
-
type: "output_text",
|
|
1757
|
-
text: sanitizeTransportPayloadText(providerText),
|
|
1758
|
-
annotations: []
|
|
1759
|
-
}],
|
|
1760
|
-
status: "completed",
|
|
1761
|
-
...msgId ? { id: msgId } : {},
|
|
1762
|
-
phase: textSignature?.phase
|
|
1763
|
-
};
|
|
1764
|
-
output.push(messageItem);
|
|
1765
|
-
previousReplayItemWasReasoning = false;
|
|
1766
|
-
} else if (block.type === "toolCall") {
|
|
1767
|
-
const separatorIndex = block.id.indexOf("|");
|
|
1768
|
-
const callId = separatorIndex === -1 ? block.id : block.id.slice(0, separatorIndex);
|
|
1769
|
-
const itemIdRaw = separatorIndex === -1 ? void 0 : block.id.slice(separatorIndex + 1);
|
|
1770
|
-
const itemId = shouldReplayResponsesItemIds && (!itemIdRaw?.startsWith("fc_") || seenReplayableReasoning && !isDifferentModel) ? itemIdRaw : void 0;
|
|
1771
|
-
output.push({
|
|
1772
|
-
type: "function_call",
|
|
1773
|
-
...itemId ? { id: itemId } : {},
|
|
1774
|
-
call_id: callId,
|
|
1775
|
-
name: block.name,
|
|
1776
|
-
...block.async ? { async: true } : {},
|
|
1777
|
-
arguments: providerStyle ? JSON.stringify(block.arguments) : typeof block.arguments === "string" ? block.arguments : JSON.stringify(block.arguments ?? {})
|
|
1778
|
-
});
|
|
1779
|
-
previousReplayItemWasReasoning = false;
|
|
1780
|
-
}
|
|
1781
|
-
while (true) {
|
|
1782
|
-
const last = output.at(-1);
|
|
1783
|
-
if (last?.type !== "reasoning" || !last.id?.startsWith("rs_") || typeof last.encrypted_content === "string" && last.encrypted_content.length > 0) break;
|
|
1784
|
-
output.pop();
|
|
1785
|
-
}
|
|
1786
|
-
return output;
|
|
1787
|
-
} else if (msg.role === "toolResult") {
|
|
1788
|
-
const textResult = extractToolResultText(msg.content);
|
|
1789
|
-
const hasText = textResult.trim().length > 0;
|
|
1790
|
-
const mediaPlaceholder = describeToolResultMediaPlaceholder(msg.content);
|
|
1791
|
-
const hasImages = msg.content.some(isImageWithMediaPayload);
|
|
1792
|
-
const separatorIndex = msg.toolCallId.indexOf("|");
|
|
1793
|
-
const rawCallId = separatorIndex === -1 ? msg.toolCallId : msg.toolCallId.slice(0, separatorIndex);
|
|
1794
|
-
const callId = preparedRequestSuffix.has(context) ? preparedRequestSuffix.toolCallId(context, rawCallId, normalizeToolCallId(rawCallId, model, model)) : rawCallId;
|
|
1795
|
-
let output = hasText ? textResult : mediaPlaceholder ?? "(no output)";
|
|
1796
|
-
if (hasImages && model.input.includes("image")) {
|
|
1797
|
-
const parts = [];
|
|
1798
|
-
let hasExplicitText = false;
|
|
1799
|
-
for (const item of msg.content) if (isImageWithMediaPayload(item)) parts.push(buildResponsesInputImage(item));
|
|
1800
|
-
else if (hasText && item.type === "text") {
|
|
1801
|
-
const text = extractToolResultBlockText(item);
|
|
1802
|
-
if (text) {
|
|
1803
|
-
const joinedText = `${hasExplicitText ? "\n" : ""}${text}`;
|
|
1804
|
-
hasExplicitText = true;
|
|
1805
|
-
const previous = parts.at(-1);
|
|
1806
|
-
if (previous?.type === "input_text") previous.text += joinedText;
|
|
1807
|
-
else parts.push({
|
|
1808
|
-
type: "input_text",
|
|
1809
|
-
text: joinedText
|
|
1810
|
-
});
|
|
1811
|
-
}
|
|
1812
|
-
}
|
|
1813
|
-
if (hasText && !hasExplicitText) parts.unshift({
|
|
1814
|
-
type: "input_text",
|
|
1815
|
-
text: textResult
|
|
1816
|
-
});
|
|
1817
|
-
else if (!hasText && mediaPlaceholder === "(see attached media)") parts.unshift({
|
|
1818
|
-
type: "input_text",
|
|
1819
|
-
text: mediaPlaceholder
|
|
1820
|
-
});
|
|
1821
|
-
output = parts;
|
|
2027
|
+
if ("call_id" in stableItem) {
|
|
2028
|
+
const itemId = item.type === "function_call" && !(fromResponse && ignoreCachedItemIds) ? rawId : void 0;
|
|
2029
|
+
stableItem.call_id = canonicalizeToolCallId(stableItem.call_id, itemId);
|
|
2030
|
+
}
|
|
2031
|
+
if (fromResponse && item.type === "function_call") {
|
|
2032
|
+
const replayed = replayedInput?.[index];
|
|
2033
|
+
if (!isRecord(replayed) || replayed.arguments !== stableItem.arguments) {
|
|
2034
|
+
const args = parseJsonObjectPreservingUnsafeIntegers(stableItem.arguments);
|
|
2035
|
+
stableItem.arguments = args ? JSON.stringify(args) : stableItem.arguments;
|
|
1822
2036
|
}
|
|
1823
|
-
converted.push({
|
|
1824
|
-
type: "function_call_output",
|
|
1825
|
-
call_id: callId,
|
|
1826
|
-
output
|
|
1827
|
-
});
|
|
1828
2037
|
}
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
for (const
|
|
1842
|
-
|
|
1843
|
-
|
|
2038
|
+
if (item.type === "message" && Array.isArray(stableItem.content)) stableItem.content = stableItem.content.map((part) => {
|
|
2039
|
+
if (!isRecord(part) || part.type !== "output_text") return part;
|
|
2040
|
+
const { annotations: _annotations, logprobs: _logprobs, ...stablePart } = part;
|
|
2041
|
+
return stablePart;
|
|
2042
|
+
});
|
|
2043
|
+
return stableItem;
|
|
2044
|
+
});
|
|
2045
|
+
}
|
|
2046
|
+
function normalizeContinuationHistory(input) {
|
|
2047
|
+
const normalized = normalizeAssistantReplayInput(input);
|
|
2048
|
+
const ownerByReplayShape = toolCallOwnerByReplayShape(responseToolCalls(input));
|
|
2049
|
+
let callIndex = 0;
|
|
2050
|
+
for (const [index, item] of input.entries()) {
|
|
2051
|
+
const normalizedItem = normalized[index];
|
|
2052
|
+
if (!isRecord(item) || !isRecord(normalizedItem)) continue;
|
|
2053
|
+
if (item.type === "function_call") {
|
|
2054
|
+
if (typeof normalizedItem.call_id !== "string") return;
|
|
2055
|
+
const callOwner = ownerByReplayShape.get(normalizedItem.call_id);
|
|
2056
|
+
if (callOwner !== callIndex) return;
|
|
2057
|
+
normalizedItem.call_id = { callOwner };
|
|
2058
|
+
callIndex += 1;
|
|
1844
2059
|
continue;
|
|
1845
2060
|
}
|
|
1846
|
-
|
|
1847
|
-
const
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
2061
|
+
if (item.type !== "function_call_output" || typeof item.call_id !== "string") continue;
|
|
2062
|
+
const owner = ownerByReplayShape.get(item.call_id);
|
|
2063
|
+
if (owner === null) return;
|
|
2064
|
+
normalizedItem.call_id = owner === void 0 ? { unknownCallId: canonicalizeToolCallId(item.call_id, void 0) } : { callOwner: owner };
|
|
2065
|
+
}
|
|
2066
|
+
return normalized;
|
|
2067
|
+
}
|
|
2068
|
+
function responsesContinuationRequestFingerprint(request) {
|
|
2069
|
+
return sha256StableValue(projectJsonObject(requestWithoutInput(request))).digest;
|
|
2070
|
+
}
|
|
2071
|
+
function responsesContinuationPrefixFingerprint(input, output = []) {
|
|
2072
|
+
return sha256StableValue(projectJsonObject([...normalizeAssistantReplayInput(input), ...normalizeAssistantReplayInput(output, true, false, output)])).digest;
|
|
2073
|
+
}
|
|
2074
|
+
function resolveResponsesContinuationRequest(continuation, request, steering) {
|
|
2075
|
+
if (!continuation) return {
|
|
2076
|
+
request,
|
|
2077
|
+
continuationStatus: "no_previous_response"
|
|
2078
|
+
};
|
|
2079
|
+
if (request.previous_response_id) return {
|
|
2080
|
+
request,
|
|
2081
|
+
continuationStatus: "explicit_previous_response_id"
|
|
2082
|
+
};
|
|
2083
|
+
if (!canReferenceResponsesReasoningHistory(continuation.lastRequest, request)) return {
|
|
2084
|
+
request,
|
|
2085
|
+
continuationStatus: "request_changed"
|
|
2086
|
+
};
|
|
2087
|
+
const prepared = replayResponsesReasoningUpdates(continuation.lastRequest, request, continuation.lastResponseItems.length, steering);
|
|
2088
|
+
if (steering !== "required-input" && !jsonValuesEqual(requestWithoutInput(prepared), requestWithoutInput(continuation.lastRequest))) return {
|
|
2089
|
+
request,
|
|
2090
|
+
continuationStatus: "request_changed"
|
|
2091
|
+
};
|
|
2092
|
+
const currentInput = prepared.input ?? [];
|
|
2093
|
+
const previousInput = continuation.lastRequest.input ?? [];
|
|
2094
|
+
const baselineLength = previousInput.length + continuation.lastResponseItems.length;
|
|
2095
|
+
if (currentInput.length < baselineLength) return {
|
|
2096
|
+
request,
|
|
2097
|
+
continuationStatus: "history_shorter"
|
|
2098
|
+
};
|
|
2099
|
+
const replayedToolRoundInput = currentInput.slice(previousInput.length, baselineLength);
|
|
2100
|
+
const replayedToolRound = normalizeAssistantReplayInput(replayedToolRoundInput);
|
|
2101
|
+
const historyToolRoundUnchanged = [false, true].some((ignoreCachedItemIds) => jsonValuesEqual(replayedToolRound, normalizeAssistantReplayInput(continuation.lastResponseItems, true, ignoreCachedItemIds, replayedToolRoundInput)));
|
|
2102
|
+
const historyCurrentInput = currentInput.slice(0, previousInput.length);
|
|
2103
|
+
for (const [index, previousItem] of previousInput.entries()) {
|
|
2104
|
+
const currentItem = historyCurrentInput[index];
|
|
2105
|
+
if (!isRecord(previousItem) || !isRecord(currentItem)) continue;
|
|
2106
|
+
if (previousItem.type === "function_call" && currentItem.type === "function_call") {
|
|
2107
|
+
if (typeof previousItem.call_id === "string" && typeof currentItem.call_id === "string" && !toolCallReplayShapes({
|
|
2108
|
+
callId: previousItem.call_id,
|
|
2109
|
+
...typeof previousItem.id === "string" ? { itemId: previousItem.id } : {}
|
|
2110
|
+
}).has(currentItem.call_id)) return {
|
|
2111
|
+
request,
|
|
2112
|
+
continuationStatus: "history_changed"
|
|
2113
|
+
};
|
|
1864
2114
|
}
|
|
1865
|
-
if (
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
2115
|
+
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 {
|
|
2116
|
+
request,
|
|
2117
|
+
continuationStatus: "history_changed"
|
|
2118
|
+
};
|
|
1869
2119
|
}
|
|
1870
|
-
|
|
2120
|
+
const normalizedPrevious = normalizeContinuationHistory(previousInput);
|
|
2121
|
+
const normalizedCurrent = normalizeContinuationHistory(historyCurrentInput);
|
|
2122
|
+
if (!(normalizedPrevious !== void 0 && normalizedCurrent !== void 0 && jsonValuesEqual(normalizedCurrent, normalizedPrevious)) || !historyToolRoundUnchanged) return {
|
|
2123
|
+
request,
|
|
2124
|
+
continuationStatus: "history_changed"
|
|
2125
|
+
};
|
|
2126
|
+
const delta = currentInput.slice(baselineLength);
|
|
2127
|
+
const cachedResponseItems = continuation.lastResponseItems;
|
|
2128
|
+
const pendingToolCalls = continuation.pendingToolCalls ?? [];
|
|
2129
|
+
const currentResponseCalls = responseToolCalls(cachedResponseItems);
|
|
2130
|
+
const replayedCalls = replayedToolRoundInput.filter((item) => isRecord(item) && item.type === "function_call");
|
|
2131
|
+
if (currentResponseCalls.length !== replayedCalls.length) return {
|
|
2132
|
+
request,
|
|
2133
|
+
continuationStatus: "history_changed"
|
|
2134
|
+
};
|
|
2135
|
+
const cachedCalls = [...pendingToolCalls, ...currentResponseCalls];
|
|
2136
|
+
const currentCallOffset = pendingToolCalls.length;
|
|
2137
|
+
const ownerByReplayShape = toolCallOwnerByReplayShape(cachedCalls);
|
|
2138
|
+
for (const index of currentResponseCalls.keys()) {
|
|
2139
|
+
const replayedCallId = replayedCalls[index]?.call_id;
|
|
2140
|
+
if (typeof replayedCallId !== "string" || ownerByReplayShape.get(replayedCallId) !== currentCallOffset + index) return {
|
|
2141
|
+
request,
|
|
2142
|
+
continuationStatus: "history_changed"
|
|
2143
|
+
};
|
|
2144
|
+
}
|
|
2145
|
+
const restoredInput = [];
|
|
2146
|
+
for (const item of delta) {
|
|
2147
|
+
if (!isRecord(item) || item.type !== "function_call_output" || typeof item.call_id !== "string") {
|
|
2148
|
+
restoredInput.push(item);
|
|
2149
|
+
continue;
|
|
2150
|
+
}
|
|
2151
|
+
const owner = ownerByReplayShape.get(item.call_id);
|
|
2152
|
+
if (owner === void 0 || owner === null) return {
|
|
2153
|
+
request,
|
|
2154
|
+
continuationStatus: "history_changed"
|
|
2155
|
+
};
|
|
2156
|
+
const rawCallId = cachedCalls[owner]?.callId;
|
|
2157
|
+
if (!rawCallId) return {
|
|
2158
|
+
request,
|
|
2159
|
+
continuationStatus: "history_changed"
|
|
2160
|
+
};
|
|
2161
|
+
restoredInput.push(rawCallId === item.call_id ? item : {
|
|
2162
|
+
...item,
|
|
2163
|
+
call_id: rawCallId
|
|
2164
|
+
});
|
|
2165
|
+
}
|
|
2166
|
+
const restoredResponseInput = restoredInput;
|
|
2167
|
+
return {
|
|
2168
|
+
request: {
|
|
2169
|
+
...prepared,
|
|
2170
|
+
previous_response_id: continuation.lastResponseId,
|
|
2171
|
+
input: restoredResponseInput
|
|
2172
|
+
},
|
|
2173
|
+
...prepared !== request ? { fullRequest: prepared } : {},
|
|
2174
|
+
continuationStatus: "continued"
|
|
2175
|
+
};
|
|
1871
2176
|
}
|
|
1872
|
-
|
|
1873
|
-
|
|
2177
|
+
const httpContinuationEntries = /* @__PURE__ */ new Map();
|
|
2178
|
+
const readyHttpContinuationEntries = /* @__PURE__ */ new Map();
|
|
2179
|
+
let httpContinuationRetainedBytes = 0;
|
|
2180
|
+
function createHttpContinuationTimer(key) {
|
|
2181
|
+
const timer = setTimeout(() => {
|
|
2182
|
+
const entry = httpContinuationEntries.get(key);
|
|
2183
|
+
if (entry?.kind === "ready" && entry.idleTimer === timer) deleteHttpContinuationIfOwned(key, entry);
|
|
2184
|
+
}, HTTP_CONTINUATION_IDLE_TTL_MS);
|
|
2185
|
+
timer.unref?.();
|
|
2186
|
+
return timer;
|
|
1874
2187
|
}
|
|
1875
|
-
function
|
|
1876
|
-
|
|
2188
|
+
function deleteHttpContinuationIfOwned(key, entry) {
|
|
2189
|
+
if (httpContinuationEntries.get(key) !== entry) return;
|
|
2190
|
+
if (entry.kind === "ready") {
|
|
2191
|
+
clearTimeout(entry.idleTimer);
|
|
2192
|
+
httpContinuationRetainedBytes -= entry.retainedBytes;
|
|
2193
|
+
readyHttpContinuationEntries.delete(key);
|
|
2194
|
+
}
|
|
2195
|
+
httpContinuationEntries.delete(key);
|
|
2196
|
+
}
|
|
2197
|
+
function evictReadyEntriesForCapacity(pendingBytes) {
|
|
2198
|
+
for (;;) {
|
|
2199
|
+
const overCapacity = readyHttpContinuationEntries.size >= MAX_HTTP_CONTINUATION_READY_ENTRIES;
|
|
2200
|
+
const overBudget = httpContinuationRetainedBytes + pendingBytes > MAX_HTTP_CONTINUATION_RETAINED_BYTES;
|
|
2201
|
+
if (!overCapacity && !overBudget) return;
|
|
2202
|
+
const oldest = readyHttpContinuationEntries.entries().next();
|
|
2203
|
+
if (oldest.done) return;
|
|
2204
|
+
const [oldestKey, oldestEntry] = oldest.value;
|
|
2205
|
+
deleteHttpContinuationIfOwned(oldestKey, oldestEntry);
|
|
2206
|
+
}
|
|
2207
|
+
}
|
|
2208
|
+
function connectionIdentity(params) {
|
|
2209
|
+
const headers = Object.entries(resolveAiTransportHeaderSentinels(params.headers) ?? {}).map(([name, value]) => [name.toLowerCase(), value]).filter(([name]) => !TURN_HEADERS.has(name)).toSorted(([a], [b]) => a.localeCompare(b));
|
|
2210
|
+
return sha256Hex(JSON.stringify([
|
|
2211
|
+
getAiTransportHost().resolveSecretSentinel(params.apiKey),
|
|
2212
|
+
params.baseUrl,
|
|
2213
|
+
headers
|
|
2214
|
+
]));
|
|
2215
|
+
}
|
|
2216
|
+
function retainedJsonBytes(value, previous) {
|
|
2217
|
+
const strings = /* @__PURE__ */ new Map();
|
|
2218
|
+
let stringBytes = 0;
|
|
2219
|
+
const skeleton = JSON.stringify(value, (_key, member) => {
|
|
2220
|
+
if (typeof member !== "string") return member;
|
|
2221
|
+
let bytes = strings.get(member) ?? previous?.get(member);
|
|
2222
|
+
if (bytes === void 0) bytes = Buffer.byteLength(JSON.stringify(member), "utf8") - 2;
|
|
2223
|
+
strings.set(member, bytes);
|
|
2224
|
+
stringBytes += bytes;
|
|
2225
|
+
return "";
|
|
2226
|
+
});
|
|
2227
|
+
return {
|
|
2228
|
+
retainedBytes: stringBytes + Buffer.byteLength(skeleton, "utf8"),
|
|
2229
|
+
strings
|
|
2230
|
+
};
|
|
2231
|
+
}
|
|
2232
|
+
function claimOpenAIResponsesHttpContinuation(params) {
|
|
2233
|
+
const owner = getAiTransportHost();
|
|
2234
|
+
const key = `${getSessionResourceOwnerId(owner)}\0${params.sessionId}\0${connectionIdentity(params)}`;
|
|
2235
|
+
const previous = httpContinuationEntries.get(key);
|
|
2236
|
+
if (previous?.kind === "claimed") return;
|
|
2237
|
+
if (previous) deleteHttpContinuationIfOwned(key, previous);
|
|
2238
|
+
const request = previous ? params.request : params.restoreRequest?.() ?? params.request;
|
|
2239
|
+
const resolved = resolveResponsesContinuationRequest(previous?.state, request);
|
|
2240
|
+
const fullRequest = resolved.fullRequest ?? request;
|
|
2241
|
+
const continuationRequest = params.request.store === false ? fullRequest : resolved.request;
|
|
2242
|
+
const claimed = {
|
|
2243
|
+
kind: "claimed",
|
|
2244
|
+
sessionId: params.sessionId,
|
|
2245
|
+
owner
|
|
2246
|
+
};
|
|
2247
|
+
httpContinuationEntries.set(key, claimed);
|
|
2248
|
+
return {
|
|
2249
|
+
request: continuationRequest,
|
|
2250
|
+
fullRequest,
|
|
2251
|
+
commit: (effectiveRequest, response, dispatchedPreviousResponseId) => {
|
|
2252
|
+
if (httpContinuationEntries.get(key) !== claimed) return;
|
|
2253
|
+
const state = recordResponsesContinuationState(previous?.state, effectiveRequest, response, previous !== void 0 && dispatchedPreviousResponseId === previous.state.lastResponseId);
|
|
2254
|
+
const { retainedBytes, strings } = retainedJsonBytes(state, previous?.strings);
|
|
2255
|
+
if (retainedBytes > MAX_HTTP_CONTINUATION_RETAINED_BYTES) {
|
|
2256
|
+
deleteHttpContinuationIfOwned(key, claimed);
|
|
2257
|
+
return;
|
|
2258
|
+
}
|
|
2259
|
+
evictReadyEntriesForCapacity(retainedBytes);
|
|
2260
|
+
const ready = {
|
|
2261
|
+
...claimed,
|
|
2262
|
+
kind: "ready",
|
|
2263
|
+
state,
|
|
2264
|
+
idleTimer: owner.runInDetachedAsyncContext(() => createHttpContinuationTimer(key)),
|
|
2265
|
+
retainedBytes,
|
|
2266
|
+
strings
|
|
2267
|
+
};
|
|
2268
|
+
httpContinuationRetainedBytes += retainedBytes;
|
|
2269
|
+
httpContinuationEntries.set(key, ready);
|
|
2270
|
+
readyHttpContinuationEntries.set(key, ready);
|
|
2271
|
+
},
|
|
2272
|
+
release: () => deleteHttpContinuationIfOwned(key, claimed)
|
|
2273
|
+
};
|
|
1877
2274
|
}
|
|
2275
|
+
registerSessionResourceCleanup((sessionId, owner) => {
|
|
2276
|
+
for (const [key, entry] of httpContinuationEntries) if ((!owner || entry.owner === owner) && (!sessionId || entry.sessionId === sessionId)) deleteHttpContinuationIfOwned(key, entry);
|
|
2277
|
+
});
|
|
1878
2278
|
//#endregion
|
|
1879
2279
|
//#region packages/ai/src/transports/openai-responses-context-usage.ts
|
|
1880
2280
|
function contextFingerprint(input, output = []) {
|
|
@@ -1929,554 +2329,251 @@ function resolveResponsesContextUsageBoundary(messages, model, identity, systemP
|
|
|
1929
2329
|
includeSystemPrompt: includeSystemPrompt === true
|
|
1930
2330
|
});
|
|
1931
2331
|
if (input.length < prefixLength || contextFingerprint(input.slice(0, prefixLength)) !== prefixHash) return;
|
|
1932
|
-
return {
|
|
1933
|
-
index,
|
|
1934
|
-
totalTokens: usage.totalTokens,
|
|
1935
|
-
suffix: input.slice(prefixLength)
|
|
1936
|
-
};
|
|
1937
|
-
}
|
|
1938
|
-
}
|
|
1939
|
-
function isAssistant(message) {
|
|
1940
|
-
return message.role === "assistant";
|
|
1941
|
-
}
|
|
1942
|
-
function isProviderMessage(message) {
|
|
1943
|
-
return message.role === "user" || message.role === "assistant" || message.role === "toolResult";
|
|
1944
|
-
}
|
|
1945
|
-
//#endregion
|
|
1946
|
-
//#region packages/ai/src/transports/openai-responses-debug.ts
|
|
1947
|
-
function stringifyUnknown(value) {
|
|
1948
|
-
if (typeof value === "string") return value;
|
|
1949
|
-
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
1950
|
-
return "";
|
|
1951
|
-
}
|
|
1952
|
-
function safeDebugValue(value) {
|
|
1953
|
-
if (value == null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") return String(value);
|
|
1954
|
-
return Array.isArray(value) ? "array" : typeof value;
|
|
1955
|
-
}
|
|
1956
|
-
function responseInputTextChars(input) {
|
|
1957
|
-
if (typeof input === "string") return input.length;
|
|
1958
|
-
if (Array.isArray(input)) return input.reduce((total, item) => total + responseInputTextChars(item), 0);
|
|
1959
|
-
if (!input || typeof input !== "object") return 0;
|
|
1960
|
-
const record = input;
|
|
1961
|
-
let total = 0;
|
|
1962
|
-
if (typeof record.text === "string") total += record.text.length;
|
|
1963
|
-
if (typeof record.content === "string") total += record.content.length;
|
|
1964
|
-
else if (Array.isArray(record.content)) total += responseInputTextChars(record.content);
|
|
1965
|
-
return total;
|
|
1966
|
-
}
|
|
1967
|
-
function responseInputRoles(input) {
|
|
1968
|
-
if (!Array.isArray(input)) return "";
|
|
1969
|
-
const roles = /* @__PURE__ */ new Set();
|
|
1970
|
-
for (const item of input) if (item && typeof item === "object") {
|
|
1971
|
-
const role = item.role;
|
|
1972
|
-
if (typeof role === "string" && role.trim()) roles.add(role.trim());
|
|
1973
|
-
}
|
|
1974
|
-
return [...roles].toSorted().join(",");
|
|
1975
|
-
}
|
|
1976
|
-
function responseInputItemShape(input) {
|
|
1977
|
-
if (!Array.isArray(input)) return "none";
|
|
1978
|
-
return input.map((item) => {
|
|
1979
|
-
if (!isRecord(item) || typeof item.type !== "string") return "unknown";
|
|
1980
|
-
if (item.type === "message" && typeof item.role === "string") return `message:${item.role}`;
|
|
1981
|
-
return item.type;
|
|
1982
|
-
}).join(",") || "none";
|
|
1983
|
-
}
|
|
1984
|
-
function summarizeResponsesCompactionItems(input) {
|
|
1985
|
-
const compactions = (Array.isArray(input) ? input : []).flatMap((item, inputIndex) => {
|
|
1986
|
-
if (!isRecord(item) || item.type !== "compaction") return [];
|
|
1987
|
-
return [{
|
|
1988
|
-
idHash: typeof item.id === "string" ? sha256Hex(item.id) : void 0,
|
|
1989
|
-
inputIndex,
|
|
1990
|
-
payloadHash: typeof item.encrypted_content === "string" ? sha256Hex(item.encrypted_content) : void 0
|
|
1991
|
-
}];
|
|
1992
|
-
});
|
|
1993
|
-
return [
|
|
1994
|
-
`compactionItems=${compactions.length}`,
|
|
1995
|
-
`compactionIdHashes=${compactions.flatMap((item) => item.idHash ?? []).join(",") || "none"}`,
|
|
1996
|
-
`compactionPayloadHashes=${compactions.flatMap((item) => item.payloadHash ?? []).join(",") || "none"}`,
|
|
1997
|
-
`compactionInputIndexes=${compactions.map((item) => item.inputIndex).join(",") || "none"}`
|
|
1998
|
-
];
|
|
1999
|
-
}
|
|
2000
|
-
function readResponsesToolDisplayName(tool) {
|
|
2001
|
-
if (!tool || typeof tool !== "object") return "";
|
|
2002
|
-
const record = tool;
|
|
2003
|
-
const name = record.name;
|
|
2004
|
-
if (typeof name === "string") return name;
|
|
2005
|
-
const fn = record.function;
|
|
2006
|
-
if (fn && typeof fn === "object") {
|
|
2007
|
-
const fnName = fn.name;
|
|
2008
|
-
if (typeof fnName === "string") return fnName;
|
|
2009
|
-
}
|
|
2010
|
-
const type = record.type;
|
|
2011
|
-
return typeof type === "string" && type !== "function" ? type : "";
|
|
2012
|
-
}
|
|
2013
|
-
function summarizeResponsesTools(tools) {
|
|
2014
|
-
if (!Array.isArray(tools)) return "count=0";
|
|
2015
|
-
const names = tools.map(readResponsesToolDisplayName).filter(Boolean);
|
|
2016
|
-
const mode = resolveModelPayloadDebugMode();
|
|
2017
|
-
const maxNames = mode === "tools" || mode === "full-redacted" ? names.length : 12;
|
|
2018
|
-
const label = maxNames >= names.length ? "names" : "sample";
|
|
2019
|
-
const shown = names.slice(0, maxNames).join(",");
|
|
2020
|
-
return `count=${tools.length}${shown ? ` ${label}=${shown}` : ""}`;
|
|
2021
|
-
}
|
|
2022
|
-
const RESPONSE_FAILED_FAILURE_FIELD_KEYS = [
|
|
2023
|
-
"error",
|
|
2024
|
-
"incomplete_details",
|
|
2025
|
-
"status_details",
|
|
2026
|
-
"failure_reason",
|
|
2027
|
-
"last_error",
|
|
2028
|
-
"provider_error",
|
|
2029
|
-
"error_details"
|
|
2030
|
-
];
|
|
2031
|
-
function buildResponsesFailedEventSummary(message, responseId, code, observation) {
|
|
2032
|
-
return {
|
|
2033
|
-
message,
|
|
2034
|
-
...responseId ? { responseId } : {},
|
|
2035
|
-
...code ? { code } : {},
|
|
2036
|
-
...observation ? { observation } : {}
|
|
2037
|
-
};
|
|
2038
|
-
}
|
|
2039
|
-
function collectResponseFailedIdentifierHashes(input) {
|
|
2040
|
-
const out = [];
|
|
2041
|
-
const seen = /* @__PURE__ */ new WeakSet();
|
|
2042
|
-
const visit = (value, path, depth, identifierKey) => {
|
|
2043
|
-
if (out.length >= 12 || depth > 4 || !value || typeof value !== "object" || seen.has(value)) return;
|
|
2044
|
-
seen.add(value);
|
|
2045
|
-
const entries = Array.isArray(value) ? value.entries() : Object.entries(value);
|
|
2046
|
-
for (const [key, child] of entries) {
|
|
2047
|
-
if (out.length >= 12 || typeof key === "number" && key >= 8) break;
|
|
2048
|
-
const childPath = typeof key === "number" ? `${path}[${key}]` : path ? `${path}.${key}` : key;
|
|
2049
|
-
const childIdentifierKey = typeof key === "number" ? identifierKey : key;
|
|
2050
|
-
const normalizedKey = childIdentifierKey.replace(/[-_\s]/g, "").toLowerCase();
|
|
2051
|
-
const isIdentifier = normalizedKey.includes("request") && normalizedKey.endsWith("id") || normalizedKey.includes("provider") && normalizedKey.endsWith("id");
|
|
2052
|
-
const childString = typeof child === "string" || typeof child === "number" ? String(child).trim() : "";
|
|
2053
|
-
if (isIdentifier && childString) out.push(`${childPath}=${redactIdentifier(childString, { len: 12 })}`);
|
|
2054
|
-
else visit(child, childPath, depth + 1, isIdentifier ? childIdentifierKey : "");
|
|
2055
|
-
}
|
|
2056
|
-
};
|
|
2057
|
-
visit(input, "", 0, "");
|
|
2058
|
-
return out;
|
|
2059
|
-
}
|
|
2060
|
-
function buildResponsesFailedNoDetailsObservation(event, model, response) {
|
|
2061
|
-
const failureFieldNames = RESPONSE_FAILED_FAILURE_FIELD_KEYS.filter((key) => response?.[key] !== void 0 && response[key] !== null);
|
|
2062
|
-
const metadataKeys = isRecord(response?.metadata) ? Object.keys(response.metadata).toSorted() : [];
|
|
2063
|
-
return {
|
|
2064
|
-
event: "openai_responses_response_failed_without_details",
|
|
2065
|
-
provider: model.provider,
|
|
2066
|
-
api: model.api,
|
|
2067
|
-
transportModel: model.id,
|
|
2068
|
-
providerRuntimeFailureKind: "no_error_details",
|
|
2069
|
-
responseId: stringifyUnknown(response?.id),
|
|
2070
|
-
responseStatus: stringifyUnknown(response?.status),
|
|
2071
|
-
responseModel: stringifyUnknown(response?.model),
|
|
2072
|
-
responseObject: stringifyUnknown(response?.object),
|
|
2073
|
-
metadataKeys,
|
|
2074
|
-
requestIdHashes: collectResponseFailedIdentifierHashes(event),
|
|
2075
|
-
failureFieldNames
|
|
2076
|
-
};
|
|
2077
|
-
}
|
|
2078
|
-
function normalizeResponsesFailedEvent(event, model) {
|
|
2079
|
-
const response = isRecord(event.response) ? event.response : void 0;
|
|
2080
|
-
const responseId = stringifyUnknown(response?.id) || void 0;
|
|
2081
|
-
const error = isRecord(response?.error) ? response.error : void 0;
|
|
2082
|
-
if (error) {
|
|
2083
|
-
const code = stringifyUnknown(error.code).trim();
|
|
2084
|
-
const message = stringifyUnknown(error.message).trim();
|
|
2085
|
-
if (code || message) return buildResponsesFailedEventSummary(`${code || "unknown"}: ${message || "no message"}`, responseId, code || void 0);
|
|
2086
|
-
}
|
|
2087
|
-
const incompleteReason = stringifyUnknown((isRecord(response?.incomplete_details) ? response.incomplete_details : void 0)?.reason);
|
|
2088
|
-
if (incompleteReason) return buildResponsesFailedEventSummary(`incomplete: ${incompleteReason}`, responseId);
|
|
2089
|
-
return buildResponsesFailedEventSummary(RESPONSE_FAILED_NO_DETAILS_MESSAGE, responseId, void 0, buildResponsesFailedNoDetailsObservation(event, model, response));
|
|
2090
|
-
}
|
|
2091
|
-
var ResponsesStreamFailure = class extends Error {
|
|
2092
|
-
constructor(failure, response) {
|
|
2093
|
-
super(failure.message);
|
|
2094
|
-
this.name = "ResponsesStreamFailure";
|
|
2095
|
-
this.responseId = failure.responseId;
|
|
2096
|
-
this.response = response;
|
|
2097
|
-
this.code = failure.code;
|
|
2098
|
-
this.observation = failure.observation;
|
|
2099
|
-
}
|
|
2100
|
-
};
|
|
2101
|
-
function logResponsesFailedNoDetails(observation) {
|
|
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);
|
|
2105
|
-
}
|
|
2106
|
-
function summarizeResponsesPayload(params) {
|
|
2107
|
-
if (!params || typeof params !== "object") return "payload=non-object";
|
|
2108
|
-
const record = params;
|
|
2109
|
-
const input = record.input;
|
|
2110
|
-
const reasoning = record.reasoning && typeof record.reasoning === "object" ? record.reasoning : void 0;
|
|
2111
|
-
const text = record.text && typeof record.text === "object" ? record.text : void 0;
|
|
2112
|
-
return [
|
|
2113
|
-
`fields=${Object.keys(record).toSorted().join(",")}`,
|
|
2114
|
-
`model=${safeDebugValue(record.model)}`,
|
|
2115
|
-
`stream=${safeDebugValue(record.stream)}`,
|
|
2116
|
-
`inputItems=${Array.isArray(input) ? input.length : typeof input}`,
|
|
2117
|
-
`inputItemShape=${responseInputItemShape(input)}`,
|
|
2118
|
-
`inputRoles=${responseInputRoles(input) || "none"}`,
|
|
2119
|
-
`inputTextChars=${responseInputTextChars(input)}`,
|
|
2120
|
-
`tools=${summarizeResponsesTools(record.tools)}`,
|
|
2121
|
-
`reasoningEffort=${safeDebugValue(reasoning?.effort)}`,
|
|
2122
|
-
`reasoningSummary=${safeDebugValue(reasoning?.summary)}`,
|
|
2123
|
-
`textVerbosity=${safeDebugValue(text?.verbosity)}`,
|
|
2124
|
-
`serviceTier=${safeDebugValue(record.service_tier)}`,
|
|
2125
|
-
...summarizeResponsesCompactionItems(input),
|
|
2126
|
-
`store=${safeDebugValue(record.store)}`,
|
|
2127
|
-
`promptCacheKey=${record.prompt_cache_key === void 0 ? "absent" : "present"}`,
|
|
2128
|
-
`metadataKeys=${record.metadata && typeof record.metadata === "object" ? Object.keys(record.metadata).toSorted().join(",") : "none"}`
|
|
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}`);
|
|
2161
|
-
return parts.join(" ");
|
|
2162
|
-
}
|
|
2163
|
-
/** Protocol-specific labels join the shared failure line; caller aborts keep their own diagnostic. */
|
|
2164
|
-
function observeResponsesTransportFailure(params) {
|
|
2165
|
-
const { error, model, output, signal, requestSignal } = params;
|
|
2166
|
-
if (error instanceof ResponsesStreamFailure && error.observation) logResponsesFailedNoDetails(error.observation);
|
|
2167
|
-
const incomplete = output.diagnostics?.find(({ type }) => type === "openai_responses_terminal")?.details?.incompleteReason;
|
|
2168
|
-
const incompleteReason = typeof incomplete === "string" ? incomplete : void 0;
|
|
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;
|
|
2332
|
+
return {
|
|
2333
|
+
index,
|
|
2334
|
+
totalTokens: usage.totalTokens,
|
|
2335
|
+
suffix: input.slice(prefixLength)
|
|
2336
|
+
};
|
|
2172
2337
|
}
|
|
2173
|
-
return {
|
|
2174
|
-
abortReason: resolveOpenAITransportAbortReason(requestSignal),
|
|
2175
|
-
incompleteReason
|
|
2176
|
-
};
|
|
2177
2338
|
}
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
const PRELUDE_TYPES = /* @__PURE__ */ new Set([
|
|
2181
|
-
"response.created",
|
|
2182
|
-
"response.in_progress",
|
|
2183
|
-
"response.queued"
|
|
2184
|
-
]);
|
|
2185
|
-
function isAsyncIterable(value) {
|
|
2186
|
-
return (typeof value === "object" && value !== null || typeof value === "function") && Symbol.asyncIterator in value;
|
|
2339
|
+
function isAssistant(message) {
|
|
2340
|
+
return message.role === "assistant";
|
|
2187
2341
|
}
|
|
2188
|
-
function
|
|
2189
|
-
|
|
2190
|
-
const response = isRecord(record?.response) ? record.response : void 0;
|
|
2191
|
-
return {
|
|
2192
|
-
failure: record?.type === "response.failed" ? response?.error : record?.type === "error" ? record.error ?? record : void 0,
|
|
2193
|
-
hasResponseOutput: Array.isArray(response?.output) && response.output.length > 0,
|
|
2194
|
-
isPrelude: record !== void 0 && PRELUDE_TYPES.has(String(record.type))
|
|
2195
|
-
};
|
|
2342
|
+
function isProviderMessage(message) {
|
|
2343
|
+
return message.role === "user" || message.role === "assistant" || message.role === "toolResult";
|
|
2196
2344
|
}
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
if (
|
|
2201
|
-
|
|
2202
|
-
return
|
|
2345
|
+
//#endregion
|
|
2346
|
+
//#region packages/ai/src/transports/openai-responses-debug.ts
|
|
2347
|
+
function stringifyUnknown(value) {
|
|
2348
|
+
if (typeof value === "string") return value;
|
|
2349
|
+
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
2350
|
+
return "";
|
|
2203
2351
|
}
|
|
2204
|
-
function
|
|
2205
|
-
if (
|
|
2206
|
-
|
|
2207
|
-
const message = typeof record.message === "string" ? record.message : "";
|
|
2208
|
-
return /No tool call found for function call output with call_id [A-Za-z0-9_-]+/.test(message);
|
|
2352
|
+
function safeDebugValue(value) {
|
|
2353
|
+
if (value == null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") return String(value);
|
|
2354
|
+
return Array.isArray(value) ? "array" : typeof value;
|
|
2209
2355
|
}
|
|
2210
|
-
function
|
|
2211
|
-
if (
|
|
2356
|
+
function responseInputTextChars(input) {
|
|
2357
|
+
if (typeof input === "string") return input.length;
|
|
2358
|
+
if (Array.isArray(input)) return input.reduce((total, item) => total + responseInputTextChars(item), 0);
|
|
2359
|
+
if (!input || typeof input !== "object") return 0;
|
|
2360
|
+
const record = input;
|
|
2361
|
+
let total = 0;
|
|
2362
|
+
if (typeof record.text === "string") total += record.text.length;
|
|
2363
|
+
if (typeof record.content === "string") total += record.content.length;
|
|
2364
|
+
else if (Array.isArray(record.content)) total += responseInputTextChars(record.content);
|
|
2365
|
+
return total;
|
|
2212
2366
|
}
|
|
2213
|
-
function
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
2217
|
-
|
|
2218
|
-
|
|
2367
|
+
function responseInputRoles(input) {
|
|
2368
|
+
if (!Array.isArray(input)) return "";
|
|
2369
|
+
const roles = /* @__PURE__ */ new Set();
|
|
2370
|
+
for (const item of input) if (item && typeof item === "object") {
|
|
2371
|
+
const role = item.role;
|
|
2372
|
+
if (typeof role === "string" && role.trim()) roles.add(role.trim());
|
|
2373
|
+
}
|
|
2374
|
+
return [...roles].toSorted().join(",");
|
|
2219
2375
|
}
|
|
2220
|
-
function
|
|
2221
|
-
if (!Array.isArray(
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
};
|
|
2376
|
+
function responseInputItemShape(input) {
|
|
2377
|
+
if (!Array.isArray(input)) return "none";
|
|
2378
|
+
return input.map((item) => {
|
|
2379
|
+
if (!isRecord(item) || typeof item.type !== "string") return "unknown";
|
|
2380
|
+
if (item.type === "message" && typeof item.role === "string") return `message:${item.role}`;
|
|
2381
|
+
return item.type;
|
|
2382
|
+
}).join(",") || "none";
|
|
2227
2383
|
}
|
|
2228
|
-
function
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2384
|
+
function summarizeResponsesCompactionItems(input) {
|
|
2385
|
+
const compactions = (Array.isArray(input) ? input : []).flatMap((item, inputIndex) => {
|
|
2386
|
+
if (!isRecord(item) || item.type !== "compaction") return [];
|
|
2387
|
+
return [{
|
|
2388
|
+
idHash: typeof item.id === "string" ? sha256Hex(item.id) : void 0,
|
|
2389
|
+
inputIndex,
|
|
2390
|
+
payloadHash: typeof item.encrypted_content === "string" ? sha256Hex(item.encrypted_content) : void 0
|
|
2391
|
+
}];
|
|
2392
|
+
});
|
|
2393
|
+
return [
|
|
2394
|
+
`compactionItems=${compactions.length}`,
|
|
2395
|
+
`compactionIdHashes=${compactions.flatMap((item) => item.idHash ?? []).join(",") || "none"}`,
|
|
2396
|
+
`compactionPayloadHashes=${compactions.flatMap((item) => item.payloadHash ?? []).join(",") || "none"}`,
|
|
2397
|
+
`compactionInputIndexes=${compactions.map((item) => item.inputIndex).join(",") || "none"}`
|
|
2398
|
+
];
|
|
2235
2399
|
}
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2400
|
+
function readResponsesToolDisplayName(tool) {
|
|
2401
|
+
if (!tool || typeof tool !== "object") return "";
|
|
2402
|
+
const record = tool;
|
|
2403
|
+
const name = record.name;
|
|
2404
|
+
if (typeof name === "string") return name;
|
|
2405
|
+
const fn = record.function;
|
|
2406
|
+
if (fn && typeof fn === "object") {
|
|
2407
|
+
const fnName = fn.name;
|
|
2408
|
+
if (typeof fnName === "string") return fnName;
|
|
2245
2409
|
}
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
compactionStripped = stripResponsesRequestCompaction(compactionStripped);
|
|
2249
|
-
if (attempt.kind === "reasoning-stripped") compactionStripped = stripResponsesRequestEncryptedReasoning(compactionStripped);
|
|
2250
|
-
return {
|
|
2251
|
-
kind: "compaction-stripped",
|
|
2252
|
-
request: compactionStripped,
|
|
2253
|
-
rejectedCompaction: readOpenAIResponsesCompactionRejection(attempt.request)
|
|
2254
|
-
};
|
|
2410
|
+
const type = record.type;
|
|
2411
|
+
return typeof type === "string" && type !== "function" ? type : "";
|
|
2255
2412
|
}
|
|
2256
|
-
|
|
2257
|
-
|
|
2258
|
-
|
|
2259
|
-
|
|
2260
|
-
|
|
2261
|
-
|
|
2262
|
-
|
|
2263
|
-
|
|
2264
|
-
|
|
2265
|
-
|
|
2266
|
-
|
|
2267
|
-
|
|
2268
|
-
|
|
2269
|
-
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
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();
|
|
2310
|
-
}
|
|
2311
|
-
} catch (error) {
|
|
2312
|
-
if (error instanceof APIError || !isRecord(error) || error.name !== "AbortError" && !String(error.message).includes("FetchRequestCanceledException")) throw error;
|
|
2313
|
-
} finally {
|
|
2314
|
-
if (!terminal) {
|
|
2315
|
-
await reader.cancel().catch(() => void 0);
|
|
2316
|
-
reader.releaseLock();
|
|
2317
|
-
} else {
|
|
2318
|
-
const controller = new AbortController();
|
|
2319
|
-
const unregister = registerSessionResourceCleanup((sessionId) => {
|
|
2320
|
-
if (!sessionId) controller.abort();
|
|
2321
|
-
});
|
|
2322
|
-
const signal = AbortSignal.any([
|
|
2323
|
-
controller.signal,
|
|
2324
|
-
AbortSignal.timeout(250),
|
|
2325
|
-
...params.requestOptions?.signal ? [params.requestOptions.signal] : []
|
|
2326
|
-
]);
|
|
2327
|
-
const cancel = () => {
|
|
2328
|
-
reader.cancel().catch(() => void 0);
|
|
2329
|
-
};
|
|
2330
|
-
signal.addEventListener("abort", cancel, { once: true });
|
|
2331
|
-
(async () => {
|
|
2332
|
-
try {
|
|
2333
|
-
let bytes = 0;
|
|
2334
|
-
while (!signal.aborted && bytes < 65536) {
|
|
2335
|
-
const { done, value } = await reader.read();
|
|
2336
|
-
if (done) break;
|
|
2337
|
-
bytes += value.byteLength;
|
|
2338
|
-
}
|
|
2339
|
-
} catch {} finally {
|
|
2340
|
-
cancel();
|
|
2341
|
-
reader.releaseLock();
|
|
2342
|
-
signal.removeEventListener("abort", cancel);
|
|
2343
|
-
unregister();
|
|
2344
|
-
}
|
|
2345
|
-
})();
|
|
2346
|
-
}
|
|
2347
|
-
}
|
|
2348
|
-
}
|
|
2349
|
-
const encodeBody = params.encodeBody ?? prepareModelRequestBody(void 0);
|
|
2350
|
-
let tierCeiling;
|
|
2351
|
-
const limitTier = (request) => tierCeiling && (request.service_tier === "ultrafast" || tierCeiling === "default" && request.service_tier === "priority") ? {
|
|
2352
|
-
...request,
|
|
2353
|
-
service_tier: tierCeiling
|
|
2354
|
-
} : request;
|
|
2355
|
-
const recoverServiceTier = (attempt, error) => {
|
|
2356
|
-
if (params.requestOptions?.signal?.aborted || !supportsNativeOpenAIResponsesEndpoint(params.model)) return;
|
|
2357
|
-
const tier = attempt.request.service_tier;
|
|
2358
|
-
const next = nextResponsesServiceTier(tier, error);
|
|
2359
|
-
if (!next || tier !== "ultrafast" && tier !== "priority") return;
|
|
2360
|
-
tierCeiling = next;
|
|
2361
|
-
params.onServiceTierRejected?.(tier);
|
|
2362
|
-
log.info(`[responses] rejected ${tier} tier; retrying with ${next}`);
|
|
2363
|
-
return {
|
|
2364
|
-
...attempt,
|
|
2365
|
-
request: {
|
|
2366
|
-
...attempt.request,
|
|
2367
|
-
service_tier: next
|
|
2368
|
-
}
|
|
2369
|
-
};
|
|
2413
|
+
function summarizeResponsesTools(tools) {
|
|
2414
|
+
if (!Array.isArray(tools)) return "count=0";
|
|
2415
|
+
const names = tools.map(readResponsesToolDisplayName).filter(Boolean);
|
|
2416
|
+
const mode = resolveModelPayloadDebugMode();
|
|
2417
|
+
const maxNames = mode === "tools" || mode === "full-redacted" ? names.length : 12;
|
|
2418
|
+
const label = maxNames >= names.length ? "names" : "sample";
|
|
2419
|
+
const shown = names.slice(0, maxNames).join(",");
|
|
2420
|
+
return `count=${tools.length}${shown ? ` ${label}=${shown}` : ""}`;
|
|
2421
|
+
}
|
|
2422
|
+
const RESPONSE_FAILED_FAILURE_FIELD_KEYS = [
|
|
2423
|
+
"error",
|
|
2424
|
+
"incomplete_details",
|
|
2425
|
+
"status_details",
|
|
2426
|
+
"failure_reason",
|
|
2427
|
+
"last_error",
|
|
2428
|
+
"provider_error",
|
|
2429
|
+
"error_details"
|
|
2430
|
+
];
|
|
2431
|
+
function buildResponsesFailedEventSummary(message, responseId, code, observation) {
|
|
2432
|
+
return {
|
|
2433
|
+
message,
|
|
2434
|
+
...responseId ? { responseId } : {},
|
|
2435
|
+
...code ? { code } : {},
|
|
2436
|
+
...observation ? { observation } : {}
|
|
2370
2437
|
};
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
|
|
2380
|
-
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
const
|
|
2385
|
-
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
...params.requestOptions,
|
|
2389
|
-
...bodyOptions,
|
|
2390
|
-
headers: {
|
|
2391
|
-
...bodyOptions.headers,
|
|
2392
|
-
...params.requestOptions?.headers
|
|
2393
|
-
}
|
|
2394
|
-
}).withResponse();
|
|
2395
|
-
responseAccepted = true;
|
|
2396
|
-
commitResponsesEncryptedContentAttempt(attempt, (checkpoint) => {
|
|
2397
|
-
if (checkpoint) params.onCompactionRejected?.(checkpoint);
|
|
2398
|
-
});
|
|
2399
|
-
if (!isAsyncIterable(data)) throw new Error("OpenAI Responses streaming request returned a non-stream response");
|
|
2400
|
-
return {
|
|
2401
|
-
stream: data instanceof Stream && response.body ? streamWithTerminalDrain(response, response.body) : data,
|
|
2402
|
-
response,
|
|
2403
|
-
attempt
|
|
2404
|
-
};
|
|
2405
|
-
} catch (error) {
|
|
2406
|
-
let nextAttempt = (!responseAccepted ? recoverServiceTier(attempt, error) : void 0) ?? await resolveNextResponsesEncryptedContentAttempt(attempt, error, { buildFullHistoryRequest: params.buildFullHistoryRequest });
|
|
2407
|
-
if (!nextAttempt && attempt.request.previous_response_id && error && typeof error === "object" && typeof error.status === "number" && isPreviousResponseRejection(error)) {
|
|
2408
|
-
const request = { ...await params.buildFullHistoryRequest() };
|
|
2409
|
-
delete request.previous_response_id;
|
|
2410
|
-
nextAttempt = {
|
|
2411
|
-
kind: "continuation-rejected",
|
|
2412
|
-
request
|
|
2413
|
-
};
|
|
2414
|
-
}
|
|
2415
|
-
if (!nextAttempt) throw error;
|
|
2416
|
-
const retryDescription = nextAttempt.request.service_tier !== attempt.request.service_tier ? "with a slower service tier" : nextAttempt.kind === "reasoning-stripped" ? "without encrypted reasoning content" : nextAttempt.kind === "compaction-stripped" ? "without encrypted compaction content" : "full history after rejected previous_response_id";
|
|
2417
|
-
log.warn(`[responses] retrying ${retryDescription} provider=${params.model.provider} api=${params.model.api} model=${params.model.id}`);
|
|
2418
|
-
attempt = nextAttempt;
|
|
2419
|
-
}
|
|
2438
|
+
}
|
|
2439
|
+
function collectResponseFailedIdentifierHashes(input) {
|
|
2440
|
+
const out = [];
|
|
2441
|
+
const seen = /* @__PURE__ */ new WeakSet();
|
|
2442
|
+
const visit = (value, path, depth, identifierKey) => {
|
|
2443
|
+
if (out.length >= 12 || depth > 4 || !value || typeof value !== "object" || seen.has(value)) return;
|
|
2444
|
+
seen.add(value);
|
|
2445
|
+
const entries = Array.isArray(value) ? value.entries() : Object.entries(value);
|
|
2446
|
+
for (const [key, child] of entries) {
|
|
2447
|
+
if (out.length >= 12 || typeof key === "number" && key >= 8) break;
|
|
2448
|
+
const childPath = typeof key === "number" ? `${path}[${key}]` : path ? `${path}.${key}` : key;
|
|
2449
|
+
const childIdentifierKey = typeof key === "number" ? identifierKey : key;
|
|
2450
|
+
const normalizedKey = childIdentifierKey.replace(/[-_\s]/g, "").toLowerCase();
|
|
2451
|
+
const isIdentifier = normalizedKey.includes("request") && normalizedKey.endsWith("id") || normalizedKey.includes("provider") && normalizedKey.endsWith("id");
|
|
2452
|
+
const childString = typeof child === "string" || typeof child === "number" ? String(child).trim() : "";
|
|
2453
|
+
if (isIdentifier && childString) out.push(`${childPath}=${redactIdentifier(childString, { len: 12 })}`);
|
|
2454
|
+
else visit(child, childPath, depth + 1, isIdentifier ? childIdentifierKey : "");
|
|
2420
2455
|
}
|
|
2421
2456
|
};
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
request: params.request,
|
|
2425
|
-
...params.initialRejectedCompaction ? { rejectedCompaction: params.initialRejectedCompaction } : {}
|
|
2426
|
-
});
|
|
2427
|
-
return { stream: { async *[Symbol.asyncIterator]() {
|
|
2428
|
-
let current = result;
|
|
2429
|
-
let outputObserved = false;
|
|
2430
|
-
for (;;) {
|
|
2431
|
-
let rejectedEvent;
|
|
2432
|
-
let sourceError;
|
|
2433
|
-
const source = current.stream;
|
|
2434
|
-
const providerStream = { async *[Symbol.asyncIterator]() {
|
|
2435
|
-
try {
|
|
2436
|
-
yield* source;
|
|
2437
|
-
} catch (error) {
|
|
2438
|
-
sourceError = error;
|
|
2439
|
-
throw error;
|
|
2440
|
-
}
|
|
2441
|
-
} };
|
|
2442
|
-
try {
|
|
2443
|
-
for await (const event of params.wrapStream?.({
|
|
2444
|
-
...current,
|
|
2445
|
-
stream: providerStream
|
|
2446
|
-
}) ?? providerStream) {
|
|
2447
|
-
const { failure, hasResponseOutput, isPrelude } = readResponsesRecoveryEvent(event);
|
|
2448
|
-
outputObserved ||= hasResponseOutput;
|
|
2449
|
-
if (isRecord(failure) && params.canRetryStream?.() === true && (isInvalidEncryptedContentError(failure) || !outputObserved && isResponsesServiceTierRejection(failure))) {
|
|
2450
|
-
rejectedEvent = event;
|
|
2451
|
-
const message = typeof failure.message === "string" ? failure.message : "";
|
|
2452
|
-
throw Object.assign(new Error(message), {
|
|
2453
|
-
code: failure.code,
|
|
2454
|
-
status: failure.status,
|
|
2455
|
-
type: failure.type,
|
|
2456
|
-
param: failure.param
|
|
2457
|
-
});
|
|
2458
|
-
}
|
|
2459
|
-
outputObserved ||= !isPrelude;
|
|
2460
|
-
yield event;
|
|
2461
|
-
}
|
|
2462
|
-
return;
|
|
2463
|
-
} catch (error) {
|
|
2464
|
-
const nextAttempt = params.canRetryStream?.() === true && !params.requestOptions?.signal?.aborted ? (!outputObserved && (rejectedEvent !== void 0 || sourceError === error) ? recoverServiceTier(current.attempt, error) : void 0) ?? await resolveNextResponsesEncryptedContentAttempt(current.attempt, error, { buildFullHistoryRequest: params.buildFullHistoryRequest }) : void 0;
|
|
2465
|
-
if (!nextAttempt) {
|
|
2466
|
-
if (rejectedEvent !== void 0) {
|
|
2467
|
-
yield rejectedEvent;
|
|
2468
|
-
return;
|
|
2469
|
-
}
|
|
2470
|
-
throw error;
|
|
2471
|
-
}
|
|
2472
|
-
log.warn(`[responses] retrying explicitly rejected stream provider=${params.model.provider} api=${params.model.api} model=${params.model.id}`);
|
|
2473
|
-
current = await send(nextAttempt);
|
|
2474
|
-
}
|
|
2475
|
-
}
|
|
2476
|
-
} } };
|
|
2457
|
+
visit(input, "", 0, "");
|
|
2458
|
+
return out;
|
|
2477
2459
|
}
|
|
2478
|
-
function
|
|
2479
|
-
|
|
2460
|
+
function buildResponsesFailedNoDetailsObservation(event, model, response) {
|
|
2461
|
+
const failureFieldNames = RESPONSE_FAILED_FAILURE_FIELD_KEYS.filter((key) => response?.[key] !== void 0 && response[key] !== null);
|
|
2462
|
+
const metadataKeys = isRecord(response?.metadata) ? Object.keys(response.metadata).toSorted() : [];
|
|
2463
|
+
return {
|
|
2464
|
+
event: "openai_responses_response_failed_without_details",
|
|
2465
|
+
provider: model.provider,
|
|
2466
|
+
api: model.api,
|
|
2467
|
+
transportModel: model.id,
|
|
2468
|
+
providerRuntimeFailureKind: "no_error_details",
|
|
2469
|
+
responseId: stringifyUnknown(response?.id),
|
|
2470
|
+
responseStatus: stringifyUnknown(response?.status),
|
|
2471
|
+
responseModel: stringifyUnknown(response?.model),
|
|
2472
|
+
responseObject: stringifyUnknown(response?.object),
|
|
2473
|
+
metadataKeys,
|
|
2474
|
+
requestIdHashes: collectResponseFailedIdentifierHashes(event),
|
|
2475
|
+
failureFieldNames
|
|
2476
|
+
};
|
|
2477
|
+
}
|
|
2478
|
+
function normalizeResponsesFailedEvent(event, model) {
|
|
2479
|
+
const response = isRecord(event.response) ? event.response : void 0;
|
|
2480
|
+
const responseId = stringifyUnknown(response?.id) || void 0;
|
|
2481
|
+
const error = isRecord(response?.error) ? response.error : void 0;
|
|
2482
|
+
if (error) {
|
|
2483
|
+
const code = stringifyUnknown(error.code).trim();
|
|
2484
|
+
const message = stringifyUnknown(error.message).trim();
|
|
2485
|
+
if (code || message) return buildResponsesFailedEventSummary(`${code || "unknown"}: ${message || "no message"}`, responseId, code || void 0);
|
|
2486
|
+
}
|
|
2487
|
+
const incompleteReason = stringifyUnknown((isRecord(response?.incomplete_details) ? response.incomplete_details : void 0)?.reason);
|
|
2488
|
+
if (incompleteReason) return buildResponsesFailedEventSummary(`incomplete: ${incompleteReason}`, responseId);
|
|
2489
|
+
return buildResponsesFailedEventSummary(RESPONSE_FAILED_NO_DETAILS_MESSAGE, responseId, void 0, buildResponsesFailedNoDetailsObservation(event, model, response));
|
|
2490
|
+
}
|
|
2491
|
+
var ResponsesStreamFailure = class extends Error {
|
|
2492
|
+
constructor(failure, response) {
|
|
2493
|
+
super(failure.message);
|
|
2494
|
+
this.name = "ResponsesStreamFailure";
|
|
2495
|
+
this.responseId = failure.responseId;
|
|
2496
|
+
this.response = response;
|
|
2497
|
+
this.code = failure.code;
|
|
2498
|
+
this.observation = failure.observation;
|
|
2499
|
+
}
|
|
2500
|
+
};
|
|
2501
|
+
function logResponsesFailedNoDetails(observation) {
|
|
2502
|
+
const requestIds = observation.requestIdHashes.join(",");
|
|
2503
|
+
const metadataKeys = observation.metadataKeys.join(",");
|
|
2504
|
+
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);
|
|
2505
|
+
}
|
|
2506
|
+
function summarizeResponsesPayload(params) {
|
|
2507
|
+
if (!params || typeof params !== "object") return "payload=non-object";
|
|
2508
|
+
const record = params;
|
|
2509
|
+
const input = record.input;
|
|
2510
|
+
const reasoning = record.reasoning && typeof record.reasoning === "object" ? record.reasoning : void 0;
|
|
2511
|
+
const text = record.text && typeof record.text === "object" ? record.text : void 0;
|
|
2512
|
+
return [
|
|
2513
|
+
`fields=${Object.keys(record).toSorted().join(",")}`,
|
|
2514
|
+
`model=${safeDebugValue(record.model)}`,
|
|
2515
|
+
`stream=${safeDebugValue(record.stream)}`,
|
|
2516
|
+
`inputItems=${Array.isArray(input) ? input.length : typeof input}`,
|
|
2517
|
+
`inputItemShape=${responseInputItemShape(input)}`,
|
|
2518
|
+
`inputRoles=${responseInputRoles(input) || "none"}`,
|
|
2519
|
+
`inputTextChars=${responseInputTextChars(input)}`,
|
|
2520
|
+
`tools=${summarizeResponsesTools(record.tools)}`,
|
|
2521
|
+
`reasoningEffort=${safeDebugValue(reasoning?.effort)}`,
|
|
2522
|
+
`reasoningSummary=${safeDebugValue(reasoning?.summary)}`,
|
|
2523
|
+
`textVerbosity=${safeDebugValue(text?.verbosity)}`,
|
|
2524
|
+
`serviceTier=${safeDebugValue(record.service_tier)}`,
|
|
2525
|
+
...summarizeResponsesCompactionItems(input),
|
|
2526
|
+
`store=${safeDebugValue(record.store)}`,
|
|
2527
|
+
`promptCacheKey=${record.prompt_cache_key === void 0 ? "absent" : "present"}`,
|
|
2528
|
+
`metadataKeys=${record.metadata && typeof record.metadata === "object" ? Object.keys(record.metadata).toSorted().join(",") : "none"}`
|
|
2529
|
+
].join(" ");
|
|
2530
|
+
}
|
|
2531
|
+
const ABORT_REASON_LABELS = /* @__PURE__ */ new Map([
|
|
2532
|
+
["LlmIdleTimeoutError", "idle_timeout"],
|
|
2533
|
+
["LlmNoProgressError", "no_progress"],
|
|
2534
|
+
["FirstStreamEventTimeoutError", "first_event_timeout"],
|
|
2535
|
+
["OPENCLAW_SESSION_WATCHDOG", "session_watchdog"],
|
|
2536
|
+
["degenerate_output", "degenerate_output"],
|
|
2537
|
+
["OPENCLAW_RESTART_ABORT", "restart"],
|
|
2538
|
+
["ERR_STALE_GATEWAY_LIFECYCLE", "restart"],
|
|
2539
|
+
["AGENT_RUN_SUPERSEDED_ABORT", "superseded"]
|
|
2540
|
+
]);
|
|
2541
|
+
function resolveOpenAITransportAbortReason(signal) {
|
|
2542
|
+
if (!signal?.aborted) return;
|
|
2543
|
+
const reason = isRecord(signal.reason) ? signal.reason : void 0;
|
|
2544
|
+
const defaultReason = reason?.name === "TimeoutError" ? "request_deadline" : "caller_abort";
|
|
2545
|
+
const reasonKey = reason?.code ?? reason?.name;
|
|
2546
|
+
return (typeof reasonKey === "string" ? ABORT_REASON_LABELS.get(reasonKey) : void 0) ?? defaultReason;
|
|
2547
|
+
}
|
|
2548
|
+
function summarizeOpenAITransportError(error, signal) {
|
|
2549
|
+
const record = isRecord(error) ? error : void 0;
|
|
2550
|
+
const cause = record?.cause && typeof record.cause === "object" ? record.cause : void 0;
|
|
2551
|
+
const parts = record ? Object.entries({
|
|
2552
|
+
name: readTransportDiagnosticLabel(record.name),
|
|
2553
|
+
status: readTransportDiagnosticLabel(record.status),
|
|
2554
|
+
code: readTransportDiagnosticLabel(record.code),
|
|
2555
|
+
type: readTransportDiagnosticLabel(record.type),
|
|
2556
|
+
causeName: readTransportDiagnosticLabel(cause?.name),
|
|
2557
|
+
causeCode: readTransportDiagnosticLabel(cause?.code)
|
|
2558
|
+
}).flatMap(([key, value]) => value === void 0 ? [] : [`${key}=${value}`]) : [`type=${typeof error}`];
|
|
2559
|
+
const abortReason = resolveOpenAITransportAbortReason(signal);
|
|
2560
|
+
if (abortReason) parts.push(`abortReason=${abortReason}`);
|
|
2561
|
+
return parts.join(" ");
|
|
2562
|
+
}
|
|
2563
|
+
/** Protocol-specific labels join the shared failure line; caller aborts keep their own diagnostic. */
|
|
2564
|
+
function observeResponsesTransportFailure(params) {
|
|
2565
|
+
const { error, model, output, signal, requestSignal } = params;
|
|
2566
|
+
if (error instanceof ResponsesStreamFailure && error.observation) logResponsesFailedNoDetails(error.observation);
|
|
2567
|
+
const incomplete = output.diagnostics?.find(({ type }) => type === "openai_responses_terminal")?.details?.incompleteReason;
|
|
2568
|
+
const incompleteReason = typeof incomplete === "string" ? incomplete : void 0;
|
|
2569
|
+
if (signal?.aborted) {
|
|
2570
|
+
emitModelTransportError(log, "responses", () => `provider=${model.provider} api=${model.api} model=${model.id} ` + summarizeOpenAITransportError(error, requestSignal) + (incompleteReason ? ` incompleteReason=${incompleteReason}` : ""), signal);
|
|
2571
|
+
return;
|
|
2572
|
+
}
|
|
2573
|
+
return {
|
|
2574
|
+
abortReason: resolveOpenAITransportAbortReason(requestSignal),
|
|
2575
|
+
incompleteReason
|
|
2576
|
+
};
|
|
2480
2577
|
}
|
|
2481
2578
|
//#endregion
|
|
2482
2579
|
//#region packages/ai/src/providers/openai-responses-message-text.ts
|
|
@@ -2866,9 +2963,16 @@ function resolveCompletedResponsesToolCall(item, streamed) {
|
|
|
2866
2963
|
if (streamedName && completedName && streamedName !== completedName) throw new Error(`Responses stream changed tool-call function name from ${streamedName} to ${completedName}`);
|
|
2867
2964
|
const name = completedName ?? streamedName;
|
|
2868
2965
|
if (!name) throw new Error("Responses stream completed tool call without a function name");
|
|
2966
|
+
const raw = streamed?.rawArguments ?? streamed?.arguments ?? item.arguments;
|
|
2967
|
+
const argumentsValue = parseTerminalToolCallArguments(streamed?.arguments ?? item.arguments, "Responses stream completed tool call with invalid JSON arguments");
|
|
2968
|
+
const value = JSON.stringify(argumentsValue);
|
|
2869
2969
|
return {
|
|
2870
2970
|
name,
|
|
2871
|
-
arguments:
|
|
2971
|
+
arguments: argumentsValue,
|
|
2972
|
+
...typeof raw === "string" && raw !== value ? { argumentsSignature: {
|
|
2973
|
+
value,
|
|
2974
|
+
raw
|
|
2975
|
+
} } : {}
|
|
2872
2976
|
};
|
|
2873
2977
|
}
|
|
2874
2978
|
function createResponsesTerminalController(params) {
|
|
@@ -3534,7 +3638,8 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
3534
3638
|
try {
|
|
3535
3639
|
validated = resolveCompletedResponsesToolCall(item, {
|
|
3536
3640
|
name: streamingToolCall?.providerName,
|
|
3537
|
-
arguments: parsedStreamedArguments ?? (completedArguments || streamedArguments)
|
|
3641
|
+
arguments: parsedStreamedArguments ?? (completedArguments || streamedArguments),
|
|
3642
|
+
rawArguments: parsedStreamedArguments ? streamedArguments : void 0
|
|
3538
3643
|
});
|
|
3539
3644
|
} catch (error) {
|
|
3540
3645
|
rejectedToolCall = { error };
|
|
@@ -3660,9 +3765,12 @@ function applyCommonResponsesParams(params, model, context, options, config) {
|
|
|
3660
3765
|
}
|
|
3661
3766
|
async function runResponsesStreamLifecycle(params) {
|
|
3662
3767
|
const { stream, output, options } = params;
|
|
3768
|
+
let itemRecovery;
|
|
3663
3769
|
let firstEventAbort;
|
|
3664
3770
|
try {
|
|
3665
3771
|
const model = params.resolveRequestModel?.(params.model) ?? params.model;
|
|
3772
|
+
itemRecovery = createResponsesItemConflictRecovery(output, model, options);
|
|
3773
|
+
const recovery = itemRecovery;
|
|
3666
3774
|
const client = params.createClient(model);
|
|
3667
3775
|
const encodeBody = prepareModelRequestBody(options);
|
|
3668
3776
|
const buildRequest = async (replayMode) => {
|
|
@@ -3694,6 +3802,7 @@ async function runResponsesStreamLifecycle(params) {
|
|
|
3694
3802
|
model,
|
|
3695
3803
|
encodeBody,
|
|
3696
3804
|
buildFullHistoryRequest: () => buildRequest("full-history"),
|
|
3805
|
+
buildItemConflictRequest: () => recovery.retry(buildRequest),
|
|
3697
3806
|
onCompactionRejected: (checkpoint) => suppressOpenAIResponsesCompaction(output, model, options, checkpoint),
|
|
3698
3807
|
canRetryStream: () => output.content.length === 0,
|
|
3699
3808
|
onServiceTierRejected: (tier) => responsesServiceTierObserver.reject(options, tier),
|
|
@@ -3731,10 +3840,7 @@ async function runResponsesStreamLifecycle(params) {
|
|
|
3731
3840
|
resolveServiceTier: (responseTier, originalTier) => responseTier ?? (requestedTier === "priority" || requestedTier === "default" ? requestedTier : originalTier),
|
|
3732
3841
|
onServiceTier: (responseTier, response) => responsesServiceTierObserver.observe(options, requestedTier, responseTier, response),
|
|
3733
3842
|
canRetryIdentityConflict: () => hasOnlyResponsesFunctionTools(admittedRequest),
|
|
3734
|
-
reasoningReplayMetadata: buildOpenAIResponsesReasoningReplayMetadata(model, {
|
|
3735
|
-
sessionId: options?.sessionId,
|
|
3736
|
-
authProfileId: options?.authProfileId
|
|
3737
|
-
})
|
|
3843
|
+
reasoningReplayMetadata: buildOpenAIResponsesReasoningReplayMetadata(model, { sessionId: options?.sessionId })
|
|
3738
3844
|
});
|
|
3739
3845
|
if (terminal && admittedRequest && !options?.signal?.aborted) recordResponsesContextUsage(output, model, options, admittedRequest, terminal.output, "provider");
|
|
3740
3846
|
finalizeTransportStream({
|
|
@@ -3743,6 +3849,7 @@ async function runResponsesStreamLifecycle(params) {
|
|
|
3743
3849
|
signal: options?.signal
|
|
3744
3850
|
});
|
|
3745
3851
|
} catch (error) {
|
|
3852
|
+
itemRecovery?.reject(error);
|
|
3746
3853
|
const response = error instanceof ResponsesStreamFailure ? error.response : error;
|
|
3747
3854
|
const rawError = isRecord(response) && isRecord(response.error) ? response.error : response;
|
|
3748
3855
|
if (params.model.provider === "openai" && params.model.api === "openai-responses" && isRecord(rawError) && rawError.code === "misalignment_policy_violation") {
|
|
@@ -3764,8 +3871,9 @@ async function runResponsesStreamLifecycle(params) {
|
|
|
3764
3871
|
error
|
|
3765
3872
|
});
|
|
3766
3873
|
} finally {
|
|
3874
|
+
itemRecovery?.finish();
|
|
3767
3875
|
firstEventAbort?.dispose();
|
|
3768
3876
|
}
|
|
3769
3877
|
}
|
|
3770
3878
|
//#endregion
|
|
3771
|
-
export {
|
|
3879
|
+
export { filterCodeModePayloadTools as $, responsesContinuationPrefixFingerprint as A, createOpenAIResponseHook as At, supportsResponsesReasoningUpdate as B, resolvePromptCacheKey as Bt, safeDebugValue as C, buildOpenAIResponsesReasoningReplayMetadata as Ct, claimOpenAIResponsesHttpContinuation as D, suppressOpenAIResponsesCompaction as Dt, resolveResponsesContextUsageBoundary as E, resolveNewestOpenAIResponsesCompactionReplay as Et, normalizeOpenAIResponsesFunctionCallId as F, measureUtf8AppendBytes as Ft, reconcileOpenAICompletionsToolChoice as G, resolveOpenAISimpleReasoningEffort as H, shouldNormalizeOpenAIResponsesToolCallId as I, parseOpenAICompletionsUsage as It, assertCodeModeResponsesToolSurface as J, reconcileOpenAIResponsesToolChoice as K, splitOpenAIFunctionCallPairing as L, readOpenAICompletionsContentDeltas as Lt, OPENAI_RESPONSES_CALL_ID_RE as M, detachPartialSnapshot as Mt, OPENAI_RESPONSES_FUNCTION_CALL_ITEM_ID_RE as N, isOpenAICompletionsThinkingEnabled as Nt, recordResponsesContinuationState as O, GEMINI_THOUGHT_SIGNATURE_VALIDATOR_SKIP as Ot, OPENAI_RESPONSES_ID_MAX_LENGTH as P, log as Pt, enforceCodeModeResponsesToolSurface as Q, isConfigurationUpdate as R, readOpenAICompletionsReasoningBatch as Rt, observeResponsesTransportFailure as S, CompactionReplayRefreshRequiredError as St, recordResponsesContextUsage as T, readOpenAIResponsesItemRecoveryAnchor as Tt, prepareOpenAITools as U, resolveOpenAIRequestReasoning as V, withOpenAIErrorResponseHook as Vt, projectOpenAITools as W, buildOpenAISdkClientOptions as X, buildOpenAIClientHeaders as Y, buildOpenAISdkRequestOptions as Z, isAzureResponsesTextDeltaEventType as _, replayOpenAIResponsesToolArguments as _t, prepareResponsesTools as a, createResponsesItemConflictRecovery as at, resolveResponsesMessageSnapshotCollapse as b, recordResponsesInputReplay as bt, observeResponsesStream as c, isResponsesItemConflict as ct, RESPONSES_BOOKKEEPING_TIMEOUT_MS as d, resolveNextResponsesEncryptedContentAttempt as dt, getCompat as et, AZURE_RESPONSES_TEXT_CONTENT_PART_TYPE as f, bindResponsesInputMessage as ft, isAzureResponsesTextDeltaEvent as g, normalizeOpenAIResponsesReasoningReplayItem as gt, OPENAI_RESPONSES_OUTPUT_TEXT_DELTA_EVENT_TYPE as h, convertResponsesMessages as ht, convertResponsesToolPayload as i, commitResponsesEncryptedContentAttempt as it, responsesContinuationRequestFingerprint as j, createResponseModelTracker as jt, resolveResponsesContinuationRequest as k, createOpenAIProviderAcceptanceHook as kt, createResponsesToolCallTracker as l, readResponsesRecoveryEvent as lt, OPENAI_RESPONSES_OUTPUT_TEXT_CONTENT_PART_TYPE as m, convertProviderResponsesMessages as mt, applyResponsesServiceTierPricing as n, resolveCodeModeResponsesVisibleToolNames as nt, readOpenAIMisalignmentReview as o, createResponsesStreamWithRecovery as ot, AZURE_RESPONSES_TEXT_DELTA_EVENT_TYPE as p, buildResponsesInputMessage as pt, toOpenAIResponsesToolChoice as q, runResponsesStreamLifecycle as r, resolveOpenAIStrictToolFlagWithDiagnostics as rt, processResponsesStream as s, isInvalidEncryptedContentError as st, applyCommonResponsesParams as t, readCodeModePayloadToolName as tt, readResponsesToolCallItemIdentity as u, resolveAzureOpenAIApiVersion as ut, isResponsesTextContentPartType as v, resolveReplayableResponsesMessageId as vt, summarizeResponsesPayload as w, captureOpenAIResponsesCompaction as wt, ResponsesStreamFailure as x, responsesInputFingerprint as xt, isResponsesTextDeltaEventType as y, readResponsesInputReplayState as yt, replayResponsesReasoningUpdates as z, resolveOpenAIClientBaseUrl as zt };
|