@openclaw/ai 2026.10.5 → 2026.10.10-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -0
- package/dist/{anthropic-DIIiiz99.mjs → anthropic-D6spfBri.mjs} +16 -18
- package/dist/{anthropic-payload-policy-DGblkHL5.d.mts → anthropic-payload-policy-Cr8xjazC.d.mts} +6 -3
- package/dist/{anthropic-stream-reducer-DfMVFm-r.mjs → anthropic-stream-reducer-CzPXOaLM.mjs} +55 -227
- package/dist/anthropic-tool-projection-BdAS3rtJ.mjs +165 -0
- package/dist/anthropic-tool-projection-DKH-aEWU.d.mts +51 -0
- package/dist/{api-registry-BhXXYdRA.d.mts → api-registry-gDt0faai.d.mts} +2 -2
- package/dist/{assistant-output-BuhRpLeD.mjs → assistant-output-6iFA1nbC.mjs} +2 -2
- package/dist/{azure-openai-responses-DGQnXRMs.mjs → azure-openai-responses-0TqHwnlD.mjs} +8 -8
- package/dist/{cloudflare-5qSGvIUH.mjs → cloudflare-Dttf8jKq.mjs} +1 -1
- package/dist/{credential-redaction-BHxruEH6.d.mts → credential-redaction-XvsPf7Yi.d.mts} +1 -0
- package/dist/{diagnostics-tQasYct1.mjs → diagnostics-Cv7cW3pS.mjs} +3 -3
- package/dist/diagnostics.d.mts +6 -6
- package/dist/diagnostics.mjs +2 -2
- package/dist/{env-api-keys-CrxwdylR.mjs → env-api-keys-Xd8dm_aV.mjs} +10 -34
- package/dist/event-stream-CDpFza-M.d.mts +1 -0
- package/dist/{event-stream-BcqWLo_u.d.mts → event-stream-CzpE1g_o.d.mts} +1 -1
- package/dist/event-stream.d.mts +2 -2
- package/dist/{github-copilot-request-facts-DEE6gcB9.mjs → github-copilot-request-facts-F-EmvkpW.mjs} +1 -1
- package/dist/{google-interactions-zIz70M2e.mjs → google-interactions-DVQ7AaSF.mjs} +29 -50
- package/dist/{google-messages-CNbUJK5E.mjs → google-messages-DfpHVTaD.mjs} +15 -5
- package/dist/{google-provider-stream-Cn0XF1MG.mjs → google-provider-stream-DJ8ANfsS.mjs} +6 -6
- package/dist/{google-shared-BPnWP4tT.mjs → google-shared-VTcCJLW3.mjs} +21 -29
- package/dist/{google-vertex-XQ7OQtaM.mjs → google-vertex-Bkfizj7M.mjs} +3 -3
- package/dist/{google-BlbTC1Xp.mjs → google-zWpkDSeN.mjs} +4 -4
- package/dist/{host-Bf3NjYNj.mjs → host-B2gk-d1H.mjs} +5 -11
- package/dist/{host-CTDz7LXD.d.mts → host-jJOffdlW.d.mts} +4 -6
- package/dist/{host-policy-BzZluO6_.mjs → host-policy-mpqGhbeM.mjs} +1 -1
- package/dist/{index-BYDvopUB.d.mts → index-DSprYWaz.d.mts} +7 -5
- package/dist/index.d.mts +7 -7
- package/dist/index.mjs +6 -6
- package/dist/internal/anthropic.d.mts +7 -53
- package/dist/internal/anthropic.mjs +6 -5
- package/dist/internal/google-model-family.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 +3 -3
- package/dist/internal/openai-responses-payload-policy.mjs +3 -3
- package/dist/internal/openai.d.mts +17 -26
- package/dist/internal/openai.mjs +10 -10
- package/dist/internal/retry-after.d.mts +1 -1
- package/dist/internal/retry-after.mjs +80 -55
- package/dist/internal/runtime.d.mts +9 -31
- package/dist/internal/runtime.mjs +10 -116
- package/dist/internal/shared.d.mts +9 -7
- package/dist/internal/shared.mjs +8 -6
- package/dist/internal/tool-schema.d.mts +83 -5
- package/dist/internal/tool-schema.mjs +4 -3
- package/dist/{mistral-dCDCR5ur.mjs → mistral-CATJrwne.mjs} +32 -35
- package/dist/model-request-body-BD5vy4rP.d.mts +17 -0
- package/dist/{number-coercion-C3hztWoY.mjs → number-coercion-37gmNkuA.mjs} +1 -1
- package/dist/{openai-chatgpt-responses-D8-q7cgy.mjs → openai-chatgpt-responses-CtdnpWwe.mjs} +95 -63
- package/dist/{openai-completions-CMN24pza.mjs → openai-completions-B6sET3oI.mjs} +10 -8
- package/dist/{openai-completions-compat-i-nLZxFy.d.mts → openai-completions-compat-1gsjP-KO.d.mts} +6 -3
- package/dist/{openai-completions-compat-CYX18uDk.mjs → openai-completions-compat-CFhQ3UVU.mjs} +7 -2
- package/dist/{openai-completions-transport-DuXQOxrH.mjs → openai-completions-transport-DviPEqw3.mjs} +369 -237
- package/dist/{openai-prompt-cache-r93BJhjm.mjs → openai-prompt-cache-DJ_P143P.mjs} +1 -1
- package/dist/{openai-prompt-cache-DIPMrMFy.d.mts → openai-prompt-cache-DgjD-UL5.d.mts} +2 -2
- package/dist/{openai-responses-BMxoJdTC.mjs → openai-responses-BXsJK-mD.mjs} +13 -15
- package/dist/{openai-responses-compaction-replay-B2FE4Nw8.d.mts → openai-responses-compaction-replay-Cvnl_nCq.d.mts} +5 -5
- package/dist/{openai-responses-contracts-DlKMMTxK.mjs → openai-responses-contracts-Bx-16mnf.mjs} +45 -6
- package/dist/{openai-responses-contracts-DKqMJ1Ct.d.mts → openai-responses-contracts-CQ4_AWjL.d.mts} +20 -8
- package/dist/{openai-responses-endpoint-CinGh4VZ.mjs → openai-responses-endpoint-D4v-eeYy.mjs} +55 -22
- package/dist/{openai-responses-payload-policy-C7GsA1y0.d.mts → openai-responses-payload-policy-BzM52TTH.d.mts} +9 -3
- package/dist/openai-responses-request-lifecycle-CTdAb2v1.mjs +246 -0
- package/dist/{openai-responses-shared-afo9-s16.mjs → openai-responses-shared-Bv_1NtH9.mjs} +284 -173
- package/dist/{openai-responses-terminal-usage-BygjiAdi.d.mts → openai-responses-terminal-usage-CpVjkqn-.d.mts} +2 -2
- package/dist/{openai-tool-schema-DDPXsvJP.mjs → openai-tool-schema-Buv0GXFb.mjs} +170 -237
- package/dist/overflow-DJHXTNBQ.mjs +117 -0
- package/dist/{positive-integer-CqWjqSi9.mjs → positive-integer-Bb4Evc7L.mjs} +1 -1
- package/dist/prompt-cache-stability-D_MeCQFI.mjs +32 -0
- package/dist/{provider-error-xumb1V3F.d.mts → provider-error-CnaWYTRY.d.mts} +1 -0
- package/dist/{provider-error-CF9GWCs2.mjs → provider-error-qtZD2inE.mjs} +75 -13
- package/dist/{provider-options-CVrXZBtA.d.mts → provider-options-DeYeaflL.d.mts} +52 -6
- package/dist/{transport-utils-34BQoXq3.mjs → provider-replay-context-J6CfU3m1.mjs} +28 -5
- package/dist/{provider-transport-turn-state-BYrELw8H.mjs → provider-transport-turn-state-Jxppzuc2.mjs} +5 -5
- package/dist/{provider-types-CHtRx0dI.d.mts → provider-types-ODq57rG_.d.mts} +3 -3
- package/dist/provider-types.d.mts +6 -6
- package/dist/providers.d.mts +2 -2
- package/dist/providers.mjs +11 -11
- package/dist/{reasoning-tag-text-partitioner-CpOy9-IQ.mjs → reasoning-tag-text-partitioner-DzlRubwU.mjs} +134 -47
- package/dist/{required-api-key-CFJvcFy_.mjs → required-api-key-D088S4Cd.mjs} +1 -1
- package/dist/{retry-after-CdCURCVg.d.mts → retry-after-sw-XX8aC.d.mts} +1 -1
- package/dist/sanitize-unicode-CRGuMONI.mjs +8 -0
- package/dist/sanitize-unicode-ZqVLLEKC.d.mts +27 -0
- package/dist/{session-resources-D1wgDQ8C.mjs → session-resources-vKvGIE3J.mjs} +1 -10
- package/dist/{simple-options-BAu4B54D.mjs → simple-options-BYgC6kse.mjs} +68 -79
- package/dist/{src-C44MKrW5.mjs → src-CyA0zJnt.mjs} +6 -2
- package/dist/{stream-Dd8DwRFL.mjs → stream-DLBirT0e.mjs} +8 -47
- package/dist/{stream-first-event-timeout-Dc42hKv6.mjs → stream-first-event-timeout-D_TfJHRJ.mjs} +1 -1
- package/dist/{string-coerce-CtgOVOSv.mjs → string-coerce-Cj8sqWHx.mjs} +26 -1
- package/dist/tool-schema-json-projection-B0hHDV7N.mjs +492 -0
- package/dist/{transport-stream-shared-BmpzDtdQ.d.mts → transport-stream-shared-8ru8eX4s.d.mts} +5 -5
- package/dist/{transport-stream-shared-CWGOuLcA.mjs → transport-stream-shared-CzQlAzJH.mjs} +27 -75
- package/dist/transports.d.mts +33 -28
- package/dist/transports.mjs +42 -48
- package/dist/{types-CQc6JNG4.mjs → types-BXd0kI8-.mjs} +1 -1
- package/dist/types-CBJthzJX.d.mts +1 -0
- package/dist/{types-Bd2T86VJ.d.mts → types-CVYzKrMl.d.mts} +20 -3
- package/dist/types.d.mts +6 -6
- package/dist/types.mjs +4 -4
- package/dist/{validation-ZX_sPVV0.mjs → validation-9FSkE8T-.mjs} +22 -3
- package/dist/{validation-DdGB1yy3.d.mts → validation-BQ5u20Ru.d.mts} +1 -1
- package/dist/validation.d.mts +1 -1
- package/dist/validation.mjs +1 -1
- package/package.json +3 -3
- package/dist/assistant-text-phase-mvdMcrY-.mjs +0 -50
- package/dist/event-stream-6UNs-AhN.d.mts +0 -1
- package/dist/expect-lbe3Hgrh.mjs +0 -8
- package/dist/json-schema-Bp07Qui3.mjs +0 -22
- package/dist/openai-responses-request-lifecycle-NSIJo9jY.mjs +0 -67
- package/dist/openai-tool-projection-793cE3QX.d.mts +0 -37
- package/dist/openai-tool-schema-a5ysBBga.d.mts +0 -32
- package/dist/rolldown-runtime-BhDjJH2R.mjs +0 -15
- package/dist/sanitize-unicode-CjDG6jJx.d.mts +0 -5
- package/dist/string-normalization-I3ux50s9.mjs +0 -28
- package/dist/text-signature-CUXnvk_c.mjs +0 -34
- package/dist/tool-schema-json-projection-B8sG1I9v.mjs +0 -180
- package/dist/types-Kdfw_04V.d.mts +0 -1
|
@@ -1,45 +1,31 @@
|
|
|
1
|
-
import "./src-
|
|
2
|
-
import { _ as runtimeContextContentToText, f as hasRuntimeContextMarker, p as isRuntimeContextMessage } from "./types-
|
|
1
|
+
import "./src-CyA0zJnt.mjs";
|
|
2
|
+
import { _ as runtimeContextContentToText, f as hasRuntimeContextMarker, p as isRuntimeContextMessage } from "./types-BXd0kI8-.mjs";
|
|
3
3
|
import { o as readProviderRefusalReview, t as appendAssistantMessageDiagnostic } from "./diagnostics-DzrF1h4J.mjs";
|
|
4
4
|
import { r as appendAssistantThinking } from "./event-stream-X2gmsUWv.mjs";
|
|
5
5
|
import { o as isRecord, r as asOptionalObjectRecord } from "./record-coerce-CNDovvft.mjs";
|
|
6
|
-
import {
|
|
7
|
-
import { t as asFiniteNumber } from "./number-coercion-
|
|
8
|
-
import { D as applyProviderReportedUsageCost, E as headersToRecord, N as isImageWithMediaPayload, O as calculateCost, a as resolveAiTransportHeaderSentinels, k as clampThinkingLevel, r as getAiTransportHost } from "./host-
|
|
9
|
-
import { A as
|
|
10
|
-
import { n as getSessionResourceOwnerId, r as registerSessionResourceCleanup } from "./session-resources-
|
|
11
|
-
import { c as stableStringify, s as truncateUtf16Safe } from "./provider-error-
|
|
12
|
-
import { n as clampOpenAIPromptCacheKey } from "./openai-prompt-cache-
|
|
13
|
-
import { _ as resolveResponsesTerminalStopReason, a as resolveModelPayloadDebugMode, d as hasOnlyResponsesFunctionTools, f as isResponsesProviderTool, g as readResponsesReasoningTokens, h as mapResponsesTerminalUsage,
|
|
14
|
-
import {
|
|
15
|
-
import { c as resolveOpenAIResponsesTextFormat, i as resolveOpenAICompletionsCompat, o as usesNativeOpenAICodexResponsesBackend } from "./openai-completions-compat-
|
|
16
|
-
import { r as resolveModelRequestTimeoutMs } from "./host-policy-
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import { n as
|
|
21
|
-
import { n as
|
|
6
|
+
import { l as readStringValue, o as normalizeOptionalString, r as normalizeLowercaseStringOrEmpty, s as normalizeStringifiedOptionalString } from "./string-coerce-Cj8sqWHx.mjs";
|
|
7
|
+
import { t as asFiniteNumber } from "./number-coercion-37gmNkuA.mjs";
|
|
8
|
+
import { D as applyProviderReportedUsageCost, E as headersToRecord, N as isImageWithMediaPayload, O as calculateCost, a as resolveAiTransportHeaderSentinels, k as clampThinkingLevel, r as getAiTransportHost } from "./host-B2gk-d1H.mjs";
|
|
9
|
+
import { A as supportsOpenAITemperature, D as resolveOpenAIReasoningEffortMapping, E as resolveOpenAIReasoningEffortForModel, L as resolveOpenAIThinkingApi, P as MODEL_CATALOG_THINKING_LEVELS, T as resolveOpenAIModelReasoningEfforts, _ as responsesServiceTierObserver, a as OPENAI_RESPONSES_COMPACTION_REPLAY_TYPE, c as OPENAI_RESPONSES_RETAINED_COMPACTION_REPLAY_TYPE, f as RESPONSES_RETAINED_USER, i as OPENAI_RESPONSES_APIS, k as supportsOpenAIReasoningEffort, m as isPreviousResponseRejection, o as OPENAI_RESPONSES_REASONING_REPLAY_BLOCK_META_KEY, p as RESPONSE_FAILED_NO_DETAILS_MESSAGE, s as OPENAI_RESPONSES_REASONING_REPLAY_META_KEY, v as isResponsesServiceTierRejection, w as normalizeOpenAIReasoningEffort, y as nextResponsesServiceTier } from "./openai-responses-contracts-Bx-16mnf.mjs";
|
|
10
|
+
import { n as getSessionResourceOwnerId, r as registerSessionResourceCleanup } from "./session-resources-vKvGIE3J.mjs";
|
|
11
|
+
import { c as stableStringify, s as truncateUtf16Safe } from "./provider-error-qtZD2inE.mjs";
|
|
12
|
+
import { n as clampOpenAIPromptCacheKey } from "./openai-prompt-cache-DJ_P143P.mjs";
|
|
13
|
+
import { _ as resolveResponsesTerminalStopReason, a as resolveModelPayloadDebugMode, d as hasOnlyResponsesFunctionTools, f as isResponsesProviderTool, g as readResponsesReasoningTokens, h as mapResponsesTerminalUsage, r as emitModelTransportDebug, u as ResponsesOutputIdentityError } from "./diagnostics-Cv7cW3pS.mjs";
|
|
14
|
+
import { c as redactSensitiveText, n as isProviderReplayContext, o as isCodeModeModelVisibleToolName, r as providerReplayContextMatches, t as buildProviderReplayContext } from "./provider-replay-context-J6CfU3m1.mjs";
|
|
15
|
+
import { c as resolveOpenAIResponsesTextFormat, i as resolveOpenAICompletionsCompat, o as usesNativeOpenAICodexResponsesBackend } from "./openai-completions-compat-CFhQ3UVU.mjs";
|
|
16
|
+
import { r as resolveModelRequestTimeoutMs } from "./host-policy-mpqGhbeM.mjs";
|
|
17
|
+
import { r as sortPromptCacheToolsByName } from "./prompt-cache-stability-D_MeCQFI.mjs";
|
|
18
|
+
import { d as extractToolResultBlockText, f as extractToolResultText, h as preparedRequestSuffix, l as describeToolResultMediaPlaceholder, r as clampMaxTokensToModel, s as prepareModelRequestBody, w as stripSystemPromptCacheBoundary } from "./simple-options-BYgC6kse.mjs";
|
|
19
|
+
import { A as shortHash, C as parseJsonObjectPreservingUnsafeIntegers, E as createToolArgumentPreviewSchedule, O as parseStreamingJson, S as withProviderResponseHook, b as transportAbortError, c as failTransportStream, d as iterateModelStream, g as parseTerminalToolCallArguments, m as notifyProviderHttpResponse, t as IncompleteToolCallError, u as finalizeTransportStream, v as sanitizeTransportPayloadText } from "./transport-stream-shared-CzQlAzJH.mjs";
|
|
20
|
+
import { C as redactIdentifier, n as prepareRuntimeToolInputSchema, r as projectRuntimeToolInputSchema, w as sha256Hex } from "./tool-schema-json-projection-B0hHDV7N.mjs";
|
|
21
|
+
import { n as transformProviderMessages } from "./assistant-output-6iFA1nbC.mjs";
|
|
22
22
|
import { t as notifyLlmRequestActivity } from "./llm-request-activity-CfMuh5cC.mjs";
|
|
23
23
|
import { n as resolveOpencodeSessionHeaders } from "./session-affinity-DA4WHv1h.mjs";
|
|
24
|
-
import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "./stream-first-event-timeout-
|
|
25
|
-
import { a as resolveOpenAIProjectedToolsStrictToolFlag,
|
|
26
|
-
import { a as
|
|
27
|
-
import {
|
|
28
|
-
|
|
29
|
-
function sha256Hex(input) {
|
|
30
|
-
return hash("sha256", input, "hex");
|
|
31
|
-
}
|
|
32
|
-
function sha256HexPrefixCore(input, length) {
|
|
33
|
-
return sha256Hex(input).slice(0, length);
|
|
34
|
-
}
|
|
35
|
-
/** Redacts an identifier to a stable hash label, or "-" for missing values. */
|
|
36
|
-
function redactIdentifier(value, opts) {
|
|
37
|
-
const trimmed = normalizeOptionalString(value);
|
|
38
|
-
if (!trimmed) return "-";
|
|
39
|
-
const len = opts?.len ?? 12;
|
|
40
|
-
return `sha256:${sha256HexPrefixCore(trimmed, Number.isFinite(len) ? Math.max(1, Math.floor(len)) : 12)}`;
|
|
41
|
-
}
|
|
42
|
-
//#endregion
|
|
24
|
+
import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "./stream-first-event-timeout-D_TfJHRJ.mjs";
|
|
25
|
+
import { a as resolveOpenAIProjectedToolsStrictToolFlag, b as prepareOpenAIFunctionTool, p as withPreparedToolSchemaNormalization, r as normalizeOpenAIStrictToolParameters, t as findOpenAIStrictToolProjectionDiagnostics } from "./openai-tool-schema-Buv0GXFb.mjs";
|
|
26
|
+
import { a as isOpenAIResponsesCompactionOutput, n as supportsNativeOpenAIResponsesEndpoint, o as readOpenAIResponsesCompactionWindow } from "./openai-responses-endpoint-D4v-eeYy.mjs";
|
|
27
|
+
import { randomUUID } from "node:crypto";
|
|
28
|
+
import { Stream } from "openai/core/streaming";
|
|
43
29
|
//#region packages/ai/src/transports/openai-transport-shared.ts
|
|
44
30
|
const OPENAI_RESPONSE_MODEL_HEADER_NAMES = /* @__PURE__ */ new Set(["openai-model", "x-openai-model"]);
|
|
45
31
|
const OPENAI_RESPONSE_MODEL_EVENT_TYPES = /* @__PURE__ */ new Set([
|
|
@@ -199,21 +185,11 @@ function readOpenAICompletionsReasoningBatch(delta, visibleReasoningDetailTypes)
|
|
|
199
185
|
hasVisibleText: mirroredThinking.length < deltas.length
|
|
200
186
|
};
|
|
201
187
|
}
|
|
202
|
-
function detachPartialSnapshot(event) {
|
|
203
|
-
const source = event;
|
|
204
|
-
if (!source.partial) return event;
|
|
205
|
-
const partial = source.partial;
|
|
206
|
-
return {
|
|
207
|
-
...event,
|
|
208
|
-
partial: {
|
|
209
|
-
...partial,
|
|
210
|
-
content: partial.content.map((block) => block.type === "text" ? Object.assign({}, block) : block)
|
|
211
|
-
}
|
|
212
|
-
};
|
|
213
|
-
}
|
|
214
188
|
function parseOpenAICompletionsUsage(rawUsage, model, options) {
|
|
215
|
-
const
|
|
216
|
-
const
|
|
189
|
+
const reportedCacheRead = rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.prompt_cache_hit_tokens ?? rawUsage.cached_tokens;
|
|
190
|
+
const reportedCacheWrite = rawUsage.prompt_tokens_details?.cache_write_tokens ?? rawUsage.prompt_tokens_details?.cache_creation_input_tokens ?? rawUsage.cache_creation_input_tokens;
|
|
191
|
+
const cacheRead = reportedCacheRead ?? 0;
|
|
192
|
+
const cacheWrite = reportedCacheWrite ?? 0;
|
|
217
193
|
const input = Math.max(0, (rawUsage.prompt_tokens || 0) - cacheRead - cacheWrite);
|
|
218
194
|
const output = rawUsage.completion_tokens || 0;
|
|
219
195
|
const reasoningTokens = asFiniteNumber(rawUsage.completion_tokens_details?.reasoning_tokens);
|
|
@@ -229,6 +205,7 @@ function parseOpenAICompletionsUsage(rawUsage, model, options) {
|
|
|
229
205
|
output,
|
|
230
206
|
cacheRead,
|
|
231
207
|
cacheWrite,
|
|
208
|
+
cacheTelemetry: { state: reportedCacheRead !== void 0 || reportedCacheWrite !== void 0 ? "available" : "unavailable" },
|
|
232
209
|
...options?.includeReasoningTokens !== false && reasoningTokens !== void 0 ? { reasoningTokens } : {},
|
|
233
210
|
contextUsage: hasCoherentContext ? {
|
|
234
211
|
state: "available",
|
|
@@ -261,6 +238,18 @@ function createOpenAIProviderAcceptanceHook(options, response, model) {
|
|
|
261
238
|
model
|
|
262
239
|
});
|
|
263
240
|
}
|
|
241
|
+
function withOpenAIErrorResponseHook(fetch, onResponse, model) {
|
|
242
|
+
return async (input, init) => {
|
|
243
|
+
const response = await fetch(input, init);
|
|
244
|
+
if (!response.ok) await notifyProviderHttpResponse({
|
|
245
|
+
options: { onResponse },
|
|
246
|
+
response,
|
|
247
|
+
model,
|
|
248
|
+
signal: init?.signal ?? (input instanceof Request ? input.signal : void 0)
|
|
249
|
+
});
|
|
250
|
+
return response;
|
|
251
|
+
};
|
|
252
|
+
}
|
|
264
253
|
/** Measure one UTF-8 append without double-counting a surrogate pair split across chunks. */
|
|
265
254
|
function measureUtf8AppendBytes(bufferEndsWithHighSurrogate, chunk) {
|
|
266
255
|
let bytes = Buffer.byteLength(chunk, "utf8");
|
|
@@ -400,8 +389,8 @@ function projectOpenAIToolDescriptors(tools, schemas) {
|
|
|
400
389
|
});
|
|
401
390
|
continue;
|
|
402
391
|
}
|
|
403
|
-
const prepared = schemas ? prepareRuntimeToolInputSchema(parameters ?? {}, `${name}.parameters
|
|
404
|
-
const schemaProjection = prepared?.projection ?? projectRuntimeToolInputSchema(parameters ?? {}, `${name}.parameters
|
|
392
|
+
const prepared = schemas ? prepareRuntimeToolInputSchema(parameters ?? {}, `${name}.parameters`, name) : void 0;
|
|
393
|
+
const schemaProjection = prepared?.projection ?? projectRuntimeToolInputSchema(parameters ?? {}, `${name}.parameters`, name);
|
|
405
394
|
if (!isRecord(schemaProjection.schema) || schemaProjection.violations.length > 0) {
|
|
406
395
|
diagnostics.push({
|
|
407
396
|
toolIndex,
|
|
@@ -560,7 +549,7 @@ function resolveOpenAIRequestReasoning(model, reasoning, offDefault = "none") {
|
|
|
560
549
|
const MAX_OPENAI_STRICT_TOOL_DOWNGRADE_DIAGNOSTIC_KEYS = 256;
|
|
561
550
|
const loggedOpenAIStrictToolDowngradeDiagnosticKeys = /* @__PURE__ */ new Set();
|
|
562
551
|
const OPENAI_COMPLETIONS_APIS = /* @__PURE__ */ new Set(["openai-completions", "openclaw-openai-completions-transport"]);
|
|
563
|
-
function readToolPayloadField
|
|
552
|
+
function readToolPayloadField(record, field) {
|
|
564
553
|
try {
|
|
565
554
|
return Object.hasOwn(record, field) ? record[field] : void 0;
|
|
566
555
|
} catch {
|
|
@@ -569,16 +558,16 @@ function readToolPayloadField$1(record, field) {
|
|
|
569
558
|
}
|
|
570
559
|
function readCodeModePayloadToolName(tool) {
|
|
571
560
|
if (!isRecord(tool)) return;
|
|
572
|
-
const name = readToolPayloadField
|
|
561
|
+
const name = readToolPayloadField(tool, "name");
|
|
573
562
|
if (typeof name === "string") return name;
|
|
574
|
-
const fn = readToolPayloadField
|
|
563
|
+
const fn = readToolPayloadField(tool, "function");
|
|
575
564
|
if (!isRecord(fn)) return;
|
|
576
|
-
const fnName = readToolPayloadField
|
|
565
|
+
const fnName = readToolPayloadField(fn, "name");
|
|
577
566
|
return typeof fnName === "string" ? fnName : void 0;
|
|
578
567
|
}
|
|
579
568
|
function readCodeModePayloadToolIdentity(tool, visibleToolNames, allowedHostedToolTypes) {
|
|
580
569
|
if (!isRecord(tool)) return;
|
|
581
|
-
const type = readToolPayloadField
|
|
570
|
+
const type = readToolPayloadField(tool, "type");
|
|
582
571
|
if (typeof type === "string" && allowedHostedToolTypes?.has(type)) {
|
|
583
572
|
try {
|
|
584
573
|
if (Object.hasOwn(tool, "name") || Object.hasOwn(tool, "function") || Object.hasOwn(tool, "functionDeclarations") || Object.hasOwn(tool, "function_declarations")) return false;
|
|
@@ -592,7 +581,7 @@ function readCodeModePayloadToolIdentity(tool, visibleToolNames, allowedHostedTo
|
|
|
592
581
|
}
|
|
593
582
|
function readCodeModePayloadToolIdentities(payload) {
|
|
594
583
|
if (!isRecord(payload)) return [];
|
|
595
|
-
const tools = readToolPayloadField
|
|
584
|
+
const tools = readToolPayloadField(payload, "tools");
|
|
596
585
|
if (!Array.isArray(tools)) return [];
|
|
597
586
|
return tools.flatMap((tool) => {
|
|
598
587
|
if (!isRecord(tool)) return [];
|
|
@@ -600,21 +589,21 @@ function readCodeModePayloadToolIdentities(payload) {
|
|
|
600
589
|
const name = readCodeModePayloadToolName(tool);
|
|
601
590
|
if (name) identities.push(`client:${name}`);
|
|
602
591
|
for (const key of ["functionDeclarations", "function_declarations"]) {
|
|
603
|
-
const declarations = readToolPayloadField
|
|
592
|
+
const declarations = readToolPayloadField(tool, key);
|
|
604
593
|
if (!Array.isArray(declarations)) continue;
|
|
605
594
|
for (const declaration of declarations) {
|
|
606
595
|
const declarationName = readCodeModePayloadToolName(declaration);
|
|
607
596
|
if (declarationName) identities.push(`client:${declarationName}`);
|
|
608
597
|
}
|
|
609
598
|
}
|
|
610
|
-
const type = readToolPayloadField
|
|
599
|
+
const type = readToolPayloadField(tool, "type");
|
|
611
600
|
if (typeof type === "string" && type !== "function") identities.push(`hosted:${type}`);
|
|
612
601
|
return identities;
|
|
613
602
|
});
|
|
614
603
|
}
|
|
615
604
|
function filterCodeModePayloadTools(payload, visibleToolNames, allowedHostedToolTypes, observer) {
|
|
616
605
|
if (!isRecord(payload)) return;
|
|
617
|
-
const tools = readToolPayloadField
|
|
606
|
+
const tools = readToolPayloadField(payload, "tools");
|
|
618
607
|
if (!Array.isArray(tools)) return;
|
|
619
608
|
const beforeToolIdentities = observer ? readCodeModePayloadToolIdentities(payload) : void 0;
|
|
620
609
|
payload.tools = tools.flatMap((tool) => {
|
|
@@ -624,7 +613,7 @@ function filterCodeModePayloadTools(payload, visibleToolNames, allowedHostedTool
|
|
|
624
613
|
if (!isRecord(tool)) return [];
|
|
625
614
|
const filteredGroups = {};
|
|
626
615
|
for (const key of ["functionDeclarations", "function_declarations"]) {
|
|
627
|
-
const declarations = readToolPayloadField
|
|
616
|
+
const declarations = readToolPayloadField(tool, key);
|
|
628
617
|
if (!Array.isArray(declarations)) continue;
|
|
629
618
|
const filtered = declarations.filter((declaration) => {
|
|
630
619
|
const declarationName = readCodeModePayloadToolName(declaration);
|
|
@@ -644,7 +633,7 @@ function resolveCodeModeResponsesVisibleToolNames(context) {
|
|
|
644
633
|
}
|
|
645
634
|
function enforceCodeModeResponsesToolSurface(payload, visibleToolNames, allowedHostedToolTypes, observer) {
|
|
646
635
|
if (!isRecord(payload)) return;
|
|
647
|
-
const tools = readToolPayloadField
|
|
636
|
+
const tools = readToolPayloadField(payload, "tools");
|
|
648
637
|
if (!Array.isArray(tools)) return;
|
|
649
638
|
const beforeToolIdentities = observer ? readCodeModePayloadToolIdentities(payload) : void 0;
|
|
650
639
|
payload.tools = tools.filter((tool) => Boolean(readCodeModePayloadToolIdentity(tool, visibleToolNames, allowedHostedToolTypes)));
|
|
@@ -654,7 +643,7 @@ function enforceCodeModeResponsesToolSurface(payload, visibleToolNames, allowedH
|
|
|
654
643
|
});
|
|
655
644
|
}
|
|
656
645
|
function assertCodeModeResponsesToolSurface(payload, visibleToolNames, allowedHostedToolTypes) {
|
|
657
|
-
const tools = isRecord(payload) ? readToolPayloadField
|
|
646
|
+
const tools = isRecord(payload) ? readToolPayloadField(payload, "tools") : void 0;
|
|
658
647
|
if (!Array.isArray(tools)) throw new Error("Code mode payload tool surface violation: expected exec,wait; got no tools");
|
|
659
648
|
const identities = tools.map((tool) => readCodeModePayloadToolIdentity(tool, visibleToolNames, allowedHostedToolTypes));
|
|
660
649
|
const names = identities.flatMap((identity) => typeof identity === "string" && identity.startsWith("client:") ? [identity.slice(7)] : []).toSorted((left, right) => left.localeCompare(right));
|
|
@@ -773,7 +762,7 @@ function isOpenAIResponsesCompactionState(state) {
|
|
|
773
762
|
function readOpenAIResponsesCompactionReplayState(value) {
|
|
774
763
|
return isRecord(value) && isProviderReplayContext(value) && isOpenAIResponsesCompactionState(value) ? value : void 0;
|
|
775
764
|
}
|
|
776
|
-
function captureOpenAIResponsesCompaction(output, item, boundary, model, captureMetadata, compactedOutput) {
|
|
765
|
+
function captureOpenAIResponsesCompaction(output, item, boundary, model, captureMetadata, compactedOutput, outputTokens) {
|
|
777
766
|
const metadata = captureMetadata ?? buildOpenAIResponsesReasoningReplayMetadata(model);
|
|
778
767
|
if (!item.encrypted_content) return;
|
|
779
768
|
if (!metadata?.baseUrlHash) {
|
|
@@ -799,7 +788,8 @@ function captureOpenAIResponsesCompaction(output, item, boundary, model, capture
|
|
|
799
788
|
...metadata.authProfileHash ? { authProfileHash: metadata.authProfileHash } : {},
|
|
800
789
|
...compactedOutput ? { compactedWindow: {
|
|
801
790
|
state: "ready",
|
|
802
|
-
output: JSON.stringify(compactedOutput)
|
|
791
|
+
output: JSON.stringify(compactedOutput),
|
|
792
|
+
...outputTokens !== void 0 ? { outputTokens } : {}
|
|
803
793
|
} } : {}
|
|
804
794
|
};
|
|
805
795
|
if (compactedOutput && !readOpenAIResponsesCompactionWindow(replay, model)) throw new Error("Responses compact endpoint checkpoint is invalid or exceeds 16 MiB");
|
|
@@ -863,6 +853,7 @@ function resolveNewestOpenAIResponsesCompactionReplay(messages, model, options)
|
|
|
863
853
|
owner: message,
|
|
864
854
|
mode: "complete-window",
|
|
865
855
|
output,
|
|
856
|
+
...replay.compactedWindow?.state === "ready" && replay.compactedWindow.outputTokens !== void 0 ? { outputTokens: replay.compactedWindow.outputTokens } : {},
|
|
866
857
|
item,
|
|
867
858
|
replayIndex: replay.type === "openai-responses-retained-compaction" ? message.content.length : replay.replayIndex ?? 0
|
|
868
859
|
};
|
|
@@ -1153,15 +1144,6 @@ function continuationHistoryMatches(previousInput, currentInput) {
|
|
|
1153
1144
|
}
|
|
1154
1145
|
if (previousItem.type === "function_call_output" && currentItem.type === "function_call_output" && typeof previousItem.call_id === "string" && typeof currentItem.call_id === "string" && currentItem.call_id !== previousItem.call_id && currentItem.call_id !== canonicalizeToolCallId(previousItem.call_id, void 0)) return false;
|
|
1155
1146
|
}
|
|
1156
|
-
const previousCalls = responseToolCalls(previousInput);
|
|
1157
|
-
const currentCalls = responseToolCalls(currentInput);
|
|
1158
|
-
if (previousCalls.length !== currentCalls.length) return false;
|
|
1159
|
-
for (const [index, previousCall] of previousCalls.entries()) {
|
|
1160
|
-
const currentCall = currentCalls[index];
|
|
1161
|
-
if (!currentCall) return false;
|
|
1162
|
-
const previousShapes = toolCallReplayShapes(previousCall);
|
|
1163
|
-
if (![...toolCallReplayShapes(currentCall)].some((shape) => previousShapes.has(shape))) return false;
|
|
1164
|
-
}
|
|
1165
1147
|
const normalizedPrevious = normalizeContinuationHistory(previousInput);
|
|
1166
1148
|
const normalizedCurrent = normalizeContinuationHistory(currentInput);
|
|
1167
1149
|
return normalizedPrevious !== void 0 && normalizedCurrent !== void 0 && jsonValuesEqual(normalizedCurrent, normalizedPrevious);
|
|
@@ -1312,7 +1294,6 @@ function claimOpenAIResponsesHttpContinuation(params) {
|
|
|
1312
1294
|
if (httpContinuationEntries.get(key) !== claimed) return;
|
|
1313
1295
|
const state = recordResponsesContinuationState(previous?.state, effectiveRequest, response, previous !== void 0 && dispatchedPreviousResponseId === previous.state.lastResponseId);
|
|
1314
1296
|
const retainedBytes = Buffer.byteLength(JSON.stringify(state), "utf8");
|
|
1315
|
-
if (httpContinuationEntries.get(key) !== claimed) return;
|
|
1316
1297
|
if (retainedBytes > MAX_HTTP_CONTINUATION_RETAINED_BYTES) {
|
|
1317
1298
|
deleteHttpContinuationIfOwned(key, claimed);
|
|
1318
1299
|
return;
|
|
@@ -1408,6 +1389,29 @@ function resolveReplayableResponsesMessageId(params) {
|
|
|
1408
1389
|
if (!params.textSignatureId) return params.fallbackOrdinal === 0 ? params.fallbackId : `${params.fallbackId}_${params.fallbackOrdinal}`;
|
|
1409
1390
|
return params.previousReplayItemWasReasoning ? params.textSignatureId : void 0;
|
|
1410
1391
|
}
|
|
1392
|
+
function normalizeOpenAIResponsesReasoningReplayItem(item, api) {
|
|
1393
|
+
if (api === "openai-chatgpt-responses") return Array.isArray(item.summary) ? item : {
|
|
1394
|
+
...item,
|
|
1395
|
+
summary: []
|
|
1396
|
+
};
|
|
1397
|
+
return {
|
|
1398
|
+
id: item.id,
|
|
1399
|
+
type: "reasoning",
|
|
1400
|
+
summary: [],
|
|
1401
|
+
...Array.isArray(item.content) && item.content.length === 0 ? { content: [] } : {},
|
|
1402
|
+
status: item.status,
|
|
1403
|
+
encrypted_content: item.encrypted_content
|
|
1404
|
+
};
|
|
1405
|
+
}
|
|
1406
|
+
//#endregion
|
|
1407
|
+
//#region packages/ai/src/utils/text-signature.ts
|
|
1408
|
+
function encodeTextSignatureV1(id, phase) {
|
|
1409
|
+
return JSON.stringify({
|
|
1410
|
+
v: 1,
|
|
1411
|
+
id,
|
|
1412
|
+
...phase ? { phase } : {}
|
|
1413
|
+
});
|
|
1414
|
+
}
|
|
1411
1415
|
//#endregion
|
|
1412
1416
|
//#region packages/ai/src/transports/openai-responses-replay-messages-internal.ts
|
|
1413
1417
|
function resolveResponsesInstructionRole(model) {
|
|
@@ -1448,33 +1452,27 @@ function readOpenAIResponsesReasoningReplayBlockMetadata(block) {
|
|
|
1448
1452
|
const value = block[OPENAI_RESPONSES_REASONING_REPLAY_BLOCK_META_KEY];
|
|
1449
1453
|
return isOpenAIResponsesReasoningReplayMetadata(value) ? value : null;
|
|
1450
1454
|
}
|
|
1451
|
-
function normalizeOpenAIResponsesReasoningReplayItem(item) {
|
|
1452
|
-
return Array.isArray(item.summary) ? item : {
|
|
1453
|
-
...item,
|
|
1454
|
-
summary: []
|
|
1455
|
-
};
|
|
1456
|
-
}
|
|
1457
1455
|
function prepareOpenAIResponsesReasoningItemForReplay(item, context, blockMetadata, options) {
|
|
1458
1456
|
const hasRawMetadata = Object.hasOwn(item, OPENAI_RESPONSES_REASONING_REPLAY_META_KEY);
|
|
1459
1457
|
const { [OPENAI_RESPONSES_REASONING_REPLAY_META_KEY]: rawMetadata, ...rest } = item;
|
|
1460
|
-
if (!("encrypted_content" in rest)) return normalizeOpenAIResponsesReasoningReplayItem(rest);
|
|
1458
|
+
if (!("encrypted_content" in rest)) return normalizeOpenAIResponsesReasoningReplayItem(rest, context.api);
|
|
1461
1459
|
const metadata = blockMetadata !== void 0 ? blockMetadata ?? void 0 : isOpenAIResponsesReasoningReplayMetadata(rawMetadata) ? rawMetadata : void 0;
|
|
1462
|
-
if (blockMetadata === void 0 && !hasRawMetadata && options?.preserveUnattributedEncryptedContent === true || metadata && providerReplayContextMatches(metadata, context)) return normalizeOpenAIResponsesReasoningReplayItem(rest);
|
|
1463
|
-
return normalizeOpenAIResponsesReasoningReplayItem(stripEncryptedReasoningContentFields(rest));
|
|
1460
|
+
if (blockMetadata === void 0 && !hasRawMetadata && options?.preserveUnattributedEncryptedContent === true || metadata && providerReplayContextMatches(metadata, context)) return normalizeOpenAIResponsesReasoningReplayItem(rest, context.api);
|
|
1461
|
+
return normalizeOpenAIResponsesReasoningReplayItem(stripEncryptedReasoningContentFields(rest), context.api);
|
|
1464
1462
|
}
|
|
1465
1463
|
function normalizeResponsesReplayItemId(id) {
|
|
1466
1464
|
if (!id) return;
|
|
1467
1465
|
if (id.length <= 64) return id;
|
|
1468
1466
|
return `msg_${shortHash(id)}`;
|
|
1469
1467
|
}
|
|
1468
|
+
function responsesAssistantTurnKey(message) {
|
|
1469
|
+
const id = message.turnId || message.responseId;
|
|
1470
|
+
return id ? `${message.provider}:${message.api}:${message.model}:${id}` : void 0;
|
|
1471
|
+
}
|
|
1470
1472
|
function orderResponsesAsyncToolResults(source) {
|
|
1471
|
-
const turnKey = (message) => {
|
|
1472
|
-
const id = message.turnId || message.responseId;
|
|
1473
|
-
return id ? `${message.provider}:${message.api}:${message.model}:${id}` : void 0;
|
|
1474
|
-
};
|
|
1475
1473
|
const lastAssistant = /* @__PURE__ */ new Map();
|
|
1476
1474
|
for (const [index, message] of source.entries()) if (message.role === "assistant") {
|
|
1477
|
-
const key =
|
|
1475
|
+
const key = responsesAssistantTurnKey(message);
|
|
1478
1476
|
if (key) lastAssistant.set(key, index);
|
|
1479
1477
|
}
|
|
1480
1478
|
const owners = /* @__PURE__ */ new Map();
|
|
@@ -1482,7 +1480,7 @@ function orderResponsesAsyncToolResults(source) {
|
|
|
1482
1480
|
const ordered = [];
|
|
1483
1481
|
for (const [index, message] of source.entries()) {
|
|
1484
1482
|
if (message.role === "assistant") {
|
|
1485
|
-
const key =
|
|
1483
|
+
const key = responsesAssistantTurnKey(message);
|
|
1486
1484
|
if (key) {
|
|
1487
1485
|
for (const block of message.content) if (block.type === "toolCall" && block.async) owners.set(block.id, key);
|
|
1488
1486
|
}
|
|
@@ -1578,14 +1576,17 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1578
1576
|
});
|
|
1579
1577
|
const transformMessages = (source) => providerStyle ? transformProviderMessages(source, model, normalizeToolCallId) : getAiTransportHost().transformTransportMessages(source, model, normalizeToolCallId, {
|
|
1580
1578
|
normalizeSameModelToolCallIds: shouldNormalizeSameModelToolCallIds,
|
|
1581
|
-
preserveUnframedToolResults: replayPlan.preserveUnframedToolResults
|
|
1579
|
+
preserveUnframedToolResults: replayPlan.preserveUnframedToolResults || preparedRequestSuffix.has(context)
|
|
1582
1580
|
});
|
|
1583
1581
|
const transformedMessages = orderResponsesAsyncToolResults(transformMessages(replayPlan.messages));
|
|
1584
1582
|
if ((options?.includeSystemPrompt ?? true) && context.systemPrompt) messages.push(buildResponsesInputMessage(resolveResponsesInstructionRole(model), [{
|
|
1585
1583
|
type: "input_text",
|
|
1586
1584
|
text: sanitizeTransportPayloadText(stripSystemPromptCacheBoundary(context.systemPrompt))
|
|
1587
1585
|
}]));
|
|
1588
|
-
if (replayPlan.compactedWindow) messages.push(...replayPlan.compactedWindow)
|
|
1586
|
+
if (replayPlan.compactedWindow) messages.push(...replayPlan.compactedWindow.map((item) => {
|
|
1587
|
+
if (options?.retainUserProvenance && item.type === "message" && item.role === "user") return Object.assign({}, item, { [RESPONSES_RETAINED_USER]: true });
|
|
1588
|
+
return item;
|
|
1589
|
+
}));
|
|
1589
1590
|
let replayMessages = replayPlan.compaction ? [replayPlan.compaction, ...transformedMessages] : transformedMessages;
|
|
1590
1591
|
const isCarrier = (message) => "role" in message && hasRuntimeContextMarker(message);
|
|
1591
1592
|
if (replayMessages.some(isCarrier)) {
|
|
@@ -1626,12 +1627,18 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1626
1627
|
detail: "auto",
|
|
1627
1628
|
image_url: `data:${item.mimeType};base64,${item.data}`
|
|
1628
1629
|
}).filter((item) => providerStyle || model.input.includes("image") || item.type !== "input_image");
|
|
1629
|
-
if (content.length > 0)
|
|
1630
|
-
|
|
1630
|
+
if (content.length > 0) {
|
|
1631
|
+
const input = buildResponsesInputMessage(role, content, msg);
|
|
1632
|
+
if (options?.retainUserProvenance && role === "user" && !msg.synthetic && !msg.operatorMessage && !hasRuntimeContextMarker(msg)) Object.assign(input, { [RESPONSES_RETAINED_USER]: true });
|
|
1633
|
+
messages.push(input);
|
|
1634
|
+
} else if (providerStyle) continue;
|
|
1631
1635
|
} else if (msg.role === "assistant") {
|
|
1632
1636
|
const output = [];
|
|
1637
|
+
const sourceTurnKey = responsesAssistantTurnKey(msg);
|
|
1638
|
+
const sourceFragmentId = msg.content.find((block) => block.type === "toolCall")?.id;
|
|
1633
1639
|
let textFallbackOrdinal = 0;
|
|
1634
1640
|
let previousReplayItemWasReasoning = false;
|
|
1641
|
+
let seenReplayableReasoning = false;
|
|
1635
1642
|
const isDifferentModel = msg.model !== model.id && msg.provider === model.provider && msg.api === model.api;
|
|
1636
1643
|
for (const block of msg.content) if (block.type === "thinking") {
|
|
1637
1644
|
if (shouldReplayReasoningItems && block.thinkingSignature && (providerStyle || block.thinkingSignature.startsWith("{"))) {
|
|
@@ -1647,13 +1654,14 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1647
1654
|
if (shouldReplayResponsesItemIds && !providerStyle && model.provider === "github-copilot" && !isSafeResponsesReplayItemId(replayableReasoningItem.id)) continue;
|
|
1648
1655
|
output.push(replayableReasoningItem);
|
|
1649
1656
|
previousReplayItemWasReasoning = true;
|
|
1657
|
+
seenReplayableReasoning ||= typeof replayableReasoningItem.id === "string" && replayableReasoningItem.id.startsWith("rs_");
|
|
1650
1658
|
}
|
|
1651
1659
|
} else if (block.type === "text") {
|
|
1652
1660
|
const textSignature = parseOpenAIResponsesTextSignature(block.textSignature);
|
|
1653
1661
|
let msgId = resolveReplayableResponsesMessageId({
|
|
1654
1662
|
replayResponsesItemIds: shouldReplayResponsesItemIds,
|
|
1655
1663
|
textSignatureId: textSignature?.id,
|
|
1656
|
-
fallbackId: `msg_${msgIndex}`,
|
|
1664
|
+
fallbackId: sourceTurnKey ? `msg_${shortHash(JSON.stringify([sourceTurnKey, sourceFragmentId]))}` : `msg_${msgIndex}`,
|
|
1657
1665
|
fallbackOrdinal: textFallbackOrdinal,
|
|
1658
1666
|
previousReplayItemWasReasoning
|
|
1659
1667
|
});
|
|
@@ -1677,7 +1685,7 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1677
1685
|
const separatorIndex = block.id.indexOf("|");
|
|
1678
1686
|
const callId = separatorIndex === -1 ? block.id : block.id.slice(0, separatorIndex);
|
|
1679
1687
|
const itemIdRaw = separatorIndex === -1 ? void 0 : block.id.slice(separatorIndex + 1);
|
|
1680
|
-
const itemId = shouldReplayResponsesItemIds && !
|
|
1688
|
+
const itemId = shouldReplayResponsesItemIds && (!itemIdRaw?.startsWith("fc_") || seenReplayableReasoning && !isDifferentModel) ? itemIdRaw : void 0;
|
|
1681
1689
|
output.push({
|
|
1682
1690
|
type: "function_call",
|
|
1683
1691
|
...itemId ? { id: itemId } : {},
|
|
@@ -1701,21 +1709,44 @@ function convertResponsesMessagesWithStyle(model, context, allowedToolCallProvid
|
|
|
1701
1709
|
const mediaPlaceholder = describeToolResultMediaPlaceholder(msg.content);
|
|
1702
1710
|
const hasImages = msg.content.some(isImageWithMediaPayload);
|
|
1703
1711
|
const separatorIndex = msg.toolCallId.indexOf("|");
|
|
1704
|
-
const
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1712
|
+
const rawCallId = separatorIndex === -1 ? msg.toolCallId : msg.toolCallId.slice(0, separatorIndex);
|
|
1713
|
+
const callId = preparedRequestSuffix.has(context) ? preparedRequestSuffix.toolCallId(context, rawCallId, normalizeToolCallId(rawCallId, model, model)) : rawCallId;
|
|
1714
|
+
let output = hasText ? textResult : mediaPlaceholder ?? "(no output)";
|
|
1715
|
+
if (hasImages && model.input.includes("image")) {
|
|
1716
|
+
const parts = [];
|
|
1717
|
+
let hasExplicitText = false;
|
|
1718
|
+
for (const item of msg.content) if (isImageWithMediaPayload(item)) parts.push({
|
|
1719
|
+
type: "input_image",
|
|
1720
|
+
detail: "auto",
|
|
1721
|
+
image_url: `data:${item.mimeType};base64,${item.data}`
|
|
1722
|
+
});
|
|
1723
|
+
else if (hasText && item.type === "text") {
|
|
1724
|
+
const text = extractToolResultBlockText(item);
|
|
1725
|
+
if (text) {
|
|
1726
|
+
const joinedText = `${hasExplicitText ? "\n" : ""}${text}`;
|
|
1727
|
+
hasExplicitText = true;
|
|
1728
|
+
const previous = parts.at(-1);
|
|
1729
|
+
if (previous?.type === "input_text") previous.text += joinedText;
|
|
1730
|
+
else parts.push({
|
|
1731
|
+
type: "input_text",
|
|
1732
|
+
text: joinedText
|
|
1733
|
+
});
|
|
1734
|
+
}
|
|
1735
|
+
}
|
|
1736
|
+
if (hasText && !hasExplicitText) parts.unshift({
|
|
1709
1737
|
type: "input_text",
|
|
1710
1738
|
text: textResult
|
|
1711
|
-
}
|
|
1739
|
+
});
|
|
1740
|
+
else if (!hasText && mediaPlaceholder === "(see attached media)") parts.unshift({
|
|
1712
1741
|
type: "input_text",
|
|
1713
1742
|
text: mediaPlaceholder
|
|
1714
|
-
}
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1743
|
+
});
|
|
1744
|
+
output = parts;
|
|
1745
|
+
}
|
|
1746
|
+
messages.push({
|
|
1747
|
+
type: "function_call_output",
|
|
1748
|
+
call_id: callId,
|
|
1749
|
+
output
|
|
1719
1750
|
});
|
|
1720
1751
|
}
|
|
1721
1752
|
msgIndex += 1;
|
|
@@ -1856,24 +1887,17 @@ function summarizeResponsesCompactionItems(input) {
|
|
|
1856
1887
|
`compactionInputIndexes=${compactions.map((item) => item.inputIndex).join(",") || "none"}`
|
|
1857
1888
|
];
|
|
1858
1889
|
}
|
|
1859
|
-
function readToolPayloadField(record, field) {
|
|
1860
|
-
try {
|
|
1861
|
-
return record[field];
|
|
1862
|
-
} catch {
|
|
1863
|
-
return;
|
|
1864
|
-
}
|
|
1865
|
-
}
|
|
1866
1890
|
function readResponsesToolDisplayName(tool) {
|
|
1867
1891
|
if (!tool || typeof tool !== "object") return "";
|
|
1868
1892
|
const record = tool;
|
|
1869
|
-
const name =
|
|
1893
|
+
const name = record.name;
|
|
1870
1894
|
if (typeof name === "string") return name;
|
|
1871
|
-
const fn =
|
|
1895
|
+
const fn = record.function;
|
|
1872
1896
|
if (fn && typeof fn === "object") {
|
|
1873
|
-
const fnName =
|
|
1897
|
+
const fnName = fn.name;
|
|
1874
1898
|
if (typeof fnName === "string") return fnName;
|
|
1875
1899
|
}
|
|
1876
|
-
const type =
|
|
1900
|
+
const type = record.type;
|
|
1877
1901
|
return typeof type === "string" && type !== "function" ? type : "";
|
|
1878
1902
|
}
|
|
1879
1903
|
function summarizeResponsesTools(tools) {
|
|
@@ -2138,6 +2162,59 @@ async function resolveNextResponsesEncryptedContentAttempt(attempt, error, optio
|
|
|
2138
2162
|
};
|
|
2139
2163
|
}
|
|
2140
2164
|
async function createResponsesStreamWithRecovery(params) {
|
|
2165
|
+
async function* streamWithTerminalDrain(response, body) {
|
|
2166
|
+
const reader = body.getReader();
|
|
2167
|
+
let terminal = false;
|
|
2168
|
+
try {
|
|
2169
|
+
const forwarded = new ReadableStream({
|
|
2170
|
+
async pull(controller) {
|
|
2171
|
+
const { done, value } = await reader.read();
|
|
2172
|
+
if (done) controller.close();
|
|
2173
|
+
else controller.enqueue(value);
|
|
2174
|
+
},
|
|
2175
|
+
cancel() {}
|
|
2176
|
+
}, { highWaterMark: 0 });
|
|
2177
|
+
const stream = Stream.fromSSEResponse(new Response(forwarded, response), new AbortController(), params.client);
|
|
2178
|
+
for await (const event of stream) {
|
|
2179
|
+
terminal ||= event?.type === "response.completed" || event?.type === "response.incomplete";
|
|
2180
|
+
yield event;
|
|
2181
|
+
}
|
|
2182
|
+
} finally {
|
|
2183
|
+
if (!terminal) {
|
|
2184
|
+
await reader.cancel().catch(() => void 0);
|
|
2185
|
+
reader.releaseLock();
|
|
2186
|
+
} else {
|
|
2187
|
+
const controller = new AbortController();
|
|
2188
|
+
const unregister = registerSessionResourceCleanup((sessionId) => {
|
|
2189
|
+
if (!sessionId) controller.abort();
|
|
2190
|
+
});
|
|
2191
|
+
const signal = AbortSignal.any([
|
|
2192
|
+
controller.signal,
|
|
2193
|
+
AbortSignal.timeout(250),
|
|
2194
|
+
...params.requestOptions?.signal ? [params.requestOptions.signal] : []
|
|
2195
|
+
]);
|
|
2196
|
+
const cancel = () => {
|
|
2197
|
+
reader.cancel().catch(() => void 0);
|
|
2198
|
+
};
|
|
2199
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
2200
|
+
(async () => {
|
|
2201
|
+
try {
|
|
2202
|
+
let bytes = 0;
|
|
2203
|
+
while (!signal.aborted && bytes < 65536) {
|
|
2204
|
+
const { done, value } = await reader.read();
|
|
2205
|
+
if (done) break;
|
|
2206
|
+
bytes += value.byteLength;
|
|
2207
|
+
}
|
|
2208
|
+
} catch {} finally {
|
|
2209
|
+
cancel();
|
|
2210
|
+
reader.releaseLock();
|
|
2211
|
+
signal.removeEventListener("abort", cancel);
|
|
2212
|
+
unregister();
|
|
2213
|
+
}
|
|
2214
|
+
})();
|
|
2215
|
+
}
|
|
2216
|
+
}
|
|
2217
|
+
}
|
|
2141
2218
|
const encodeBody = params.encodeBody ?? prepareModelRequestBody(void 0);
|
|
2142
2219
|
let tierCeiling;
|
|
2143
2220
|
const limitTier = (request) => tierCeiling && (request.service_tier === "ultrafast" || tierCeiling === "default" && request.service_tier === "priority") ? {
|
|
@@ -2190,7 +2267,7 @@ async function createResponsesStreamWithRecovery(params) {
|
|
|
2190
2267
|
});
|
|
2191
2268
|
if (!isAsyncIterable(data)) throw new Error("OpenAI Responses streaming request returned a non-stream response");
|
|
2192
2269
|
return {
|
|
2193
|
-
stream: data,
|
|
2270
|
+
stream: data instanceof Stream && response.body ? streamWithTerminalDrain(response, response.body) : data,
|
|
2194
2271
|
response,
|
|
2195
2272
|
attempt
|
|
2196
2273
|
};
|
|
@@ -2329,7 +2406,7 @@ function createResponsesOutputTracker(params) {
|
|
|
2329
2406
|
trackStream(sink) {
|
|
2330
2407
|
return { push(event) {
|
|
2331
2408
|
visibleTextEmitted ||= event.type === "text_delta" && event.delta.length > 0 || event.type === "text_end" && event.content.length > 0;
|
|
2332
|
-
sink.push(
|
|
2409
|
+
sink.push(event);
|
|
2333
2410
|
} };
|
|
2334
2411
|
},
|
|
2335
2412
|
observeEvent(event) {
|
|
@@ -2508,23 +2585,43 @@ async function* adaptResponsesStream(stream, signal) {
|
|
|
2508
2585
|
yield event;
|
|
2509
2586
|
}
|
|
2510
2587
|
}
|
|
2511
|
-
async function* observeResponsesStream(stream, model, requestStartedAt) {
|
|
2588
|
+
async function* observeResponsesStream(stream, model, requestStartedAt, request, transport = "sse") {
|
|
2512
2589
|
const startedAt = Date.now();
|
|
2513
2590
|
const eventTypes = /* @__PURE__ */ new Map();
|
|
2514
|
-
const debugMode = resolveModelSseDebugMode();
|
|
2515
2591
|
let eventCount = 0;
|
|
2592
|
+
let responseId;
|
|
2593
|
+
let servedTier;
|
|
2594
|
+
let outputTokens;
|
|
2595
|
+
let reasoningTokens;
|
|
2596
|
+
let terminalType;
|
|
2597
|
+
let incompleteReason;
|
|
2598
|
+
const requestDetails = `transport=${transport} requestedTier=${request?.service_tier ?? "unspecified"} max_output_tokens=${request?.max_output_tokens ?? "provider-default"}`;
|
|
2599
|
+
emitModelTransportDebug(log, `[responses] stream_start provider=${model.provider} api=${model.api} model=${model.id} ${requestDetails}`);
|
|
2516
2600
|
try {
|
|
2517
2601
|
for await (const event of stream) {
|
|
2518
|
-
const
|
|
2602
|
+
const record = isRecord(event) ? event : void 0;
|
|
2603
|
+
const type = typeof record?.type === "string" ? record.type : "unknown";
|
|
2604
|
+
const response = isRecord(record?.response) ? record.response : void 0;
|
|
2605
|
+
if (typeof response?.id === "string") responseId = response.id;
|
|
2606
|
+
if (typeof response?.service_tier === "string") servedTier = response.service_tier;
|
|
2607
|
+
if (isRecord(response?.usage)) {
|
|
2608
|
+
if (typeof response.usage.output_tokens === "number") outputTokens = response.usage.output_tokens;
|
|
2609
|
+
const details = response.usage.output_tokens_details;
|
|
2610
|
+
if (isRecord(details) && typeof details.reasoning_tokens === "number") reasoningTokens = details.reasoning_tokens;
|
|
2611
|
+
}
|
|
2612
|
+
if (type === "response.completed" || type === "response.incomplete" || type === "response.failed") {
|
|
2613
|
+
terminalType = type;
|
|
2614
|
+
const details = response?.incomplete_details;
|
|
2615
|
+
if (isRecord(details) && typeof details.reason === "string") incompleteReason = details.reason;
|
|
2616
|
+
}
|
|
2519
2617
|
eventCount += 1;
|
|
2520
2618
|
eventTypes.set(type, (eventTypes.get(type) ?? 0) + 1);
|
|
2521
|
-
if (eventCount === 1) emitModelTransportDebug(log, `[responses] first_event provider=${model.provider} api=${model.api} model=${model.id} elapsedMs=${Date.now() - (requestStartedAt ?? startedAt)} headersToEventMs=${Date.now() - startedAt} type=${type}`);
|
|
2522
|
-
if (debugMode === "peek" && eventCount <= 5) emitModelTransportDebug(log, `[responses] event_peek provider=${model.provider} api=${model.api} model=${model.id} index=${eventCount} type=${type} event=${stringifyRedactedEvent(event)}`);
|
|
2619
|
+
if (eventCount === 1) emitModelTransportDebug(log, `[responses] first_event provider=${model.provider} api=${model.api} model=${model.id} elapsedMs=${Date.now() - (requestStartedAt ?? startedAt)} headersToEventMs=${Date.now() - startedAt} type=${type} responseId=${responseId ?? "unknown"}`);
|
|
2523
2620
|
yield event;
|
|
2524
2621
|
}
|
|
2525
2622
|
} finally {
|
|
2526
2623
|
const types = [...eventTypes].map(([type, count]) => `${type}:${count}`).join(",");
|
|
2527
|
-
emitModelTransportDebug(log, `[responses] stream_done provider=${model.provider} api=${model.api} model=${model.id} elapsedMs=${Date.now() - startedAt} events=${eventCount} types=${types}`);
|
|
2624
|
+
emitModelTransportDebug(log, `[responses] stream_done provider=${model.provider} api=${model.api} model=${model.id} ${requestDetails} responseId=${responseId ?? "unknown"} servedTier=${servedTier ?? "unknown"} outputTokens=${outputTokens ?? "unknown"} reasoningTokens=${reasoningTokens ?? "unknown"} streamDurationMs=${Date.now() - startedAt} elapsedMs=${Date.now() - (requestStartedAt ?? startedAt)} terminal=${terminalType ?? "none"} incompleteReason=${incompleteReason ?? "none"} events=${eventCount} types=${types}`);
|
|
2528
2625
|
}
|
|
2529
2626
|
}
|
|
2530
2627
|
//#endregion
|
|
@@ -2556,22 +2653,28 @@ function resolveCompletedResponsesToolCall(item, streamed) {
|
|
|
2556
2653
|
function createResponsesTerminalController(params) {
|
|
2557
2654
|
const { output, stream, model, options } = params;
|
|
2558
2655
|
const blocks = output.content;
|
|
2656
|
+
const pendingReasoning = /* @__PURE__ */ new Set();
|
|
2657
|
+
const deferredToolCompletions = [];
|
|
2658
|
+
const recordPendingReasoning = (contentIndex) => {
|
|
2659
|
+
pendingReasoning.add(contentIndex);
|
|
2660
|
+
};
|
|
2661
|
+
const releaseDeferredToolCompletions = () => {
|
|
2662
|
+
for (const event of deferredToolCompletions) stream.push(event);
|
|
2663
|
+
deferredToolCompletions.length = 0;
|
|
2664
|
+
pendingReasoning.clear();
|
|
2665
|
+
};
|
|
2559
2666
|
let rejectedToolCallId;
|
|
2560
2667
|
const recordIncompleteToolCall = (event, item) => {
|
|
2561
2668
|
rejectedToolCallId = params.toolCalls.resolve(event, readResponsesToolCallItemIdentity(item))?.block.id ?? (item.call_id ? resolveResponsesToolCallId(item) : void 0);
|
|
2562
2669
|
};
|
|
2563
|
-
const
|
|
2670
|
+
const settleReasoning = (items) => {
|
|
2564
2671
|
for (const [outputIndex, item] of items.entries()) {
|
|
2565
|
-
if (item.type !== "reasoning"
|
|
2672
|
+
if (item.type !== "reasoning") continue;
|
|
2566
2673
|
const tracked = params.outputs.get(item, outputIndex);
|
|
2567
2674
|
const block = tracked && blocks[tracked.contentIndex];
|
|
2568
|
-
if (block?.type !== "thinking"
|
|
2569
|
-
|
|
2570
|
-
if (
|
|
2571
|
-
...stored,
|
|
2572
|
-
encrypted_content: item.encrypted_content
|
|
2573
|
-
});
|
|
2574
|
-
if (options?.reasoningReplayMetadata) Object.assign(block, { [OPENAI_RESPONSES_REASONING_REPLAY_BLOCK_META_KEY]: options.reasoningReplayMetadata });
|
|
2675
|
+
if (block?.type !== "thinking") continue;
|
|
2676
|
+
block.thinkingSignature = JSON.stringify(normalizeOpenAIResponsesReasoningReplayItem(item, model.api));
|
|
2677
|
+
if (item.encrypted_content && options?.reasoningReplayMetadata) Object.assign(block, { [OPENAI_RESPONSES_REASONING_REPLAY_BLOCK_META_KEY]: options.reasoningReplayMetadata });
|
|
2575
2678
|
}
|
|
2576
2679
|
};
|
|
2577
2680
|
const appendText = (item, initialIndex) => {
|
|
@@ -2663,12 +2766,19 @@ function createResponsesTerminalController(params) {
|
|
|
2663
2766
|
});
|
|
2664
2767
|
}
|
|
2665
2768
|
params.outputs.set(item, contentIndex, outputIndex, true);
|
|
2666
|
-
|
|
2769
|
+
const completion = {
|
|
2667
2770
|
type: "toolcall_end",
|
|
2668
2771
|
contentIndex,
|
|
2669
2772
|
toolCall,
|
|
2670
2773
|
partial: output
|
|
2671
|
-
}
|
|
2774
|
+
};
|
|
2775
|
+
if (toolCall.async) {
|
|
2776
|
+
for (const index of pendingReasoning) if (index < contentIndex) {
|
|
2777
|
+
deferredToolCompletions.push(completion);
|
|
2778
|
+
return;
|
|
2779
|
+
}
|
|
2780
|
+
}
|
|
2781
|
+
stream.push(completion);
|
|
2672
2782
|
};
|
|
2673
2783
|
const recoverTerminalOutput = (items, completeToolCall) => {
|
|
2674
2784
|
let hasCompletedLaterOutput = false;
|
|
@@ -2712,7 +2822,7 @@ function createResponsesTerminalController(params) {
|
|
|
2712
2822
|
}
|
|
2713
2823
|
};
|
|
2714
2824
|
const finalizeTerminalFacts = (response, responseId = response.id) => {
|
|
2715
|
-
options?.onServiceTier?.(response.service_tier);
|
|
2825
|
+
options?.onServiceTier?.(response.service_tier, response);
|
|
2716
2826
|
output.responseId = responseId || output.responseId;
|
|
2717
2827
|
output.responseModel = options?.resolveResponseModel ? options.resolveResponseModel()?.trim() || void 0 : response.model?.trim() || void 0;
|
|
2718
2828
|
const usage = mapResponsesTerminalUsage(response.usage);
|
|
@@ -2720,6 +2830,7 @@ function createResponsesTerminalController(params) {
|
|
|
2720
2830
|
if (usage) output.usage = {
|
|
2721
2831
|
...usage,
|
|
2722
2832
|
...reasoningTokens === void 0 ? {} : { reasoningTokens },
|
|
2833
|
+
usageReport: { state: "available" },
|
|
2723
2834
|
cost: {
|
|
2724
2835
|
input: 0,
|
|
2725
2836
|
output: 0,
|
|
@@ -2728,14 +2839,15 @@ function createResponsesTerminalController(params) {
|
|
|
2728
2839
|
total: 0
|
|
2729
2840
|
}
|
|
2730
2841
|
};
|
|
2842
|
+
else output.usage.usageReport = { state: "unavailable" };
|
|
2731
2843
|
calculateCost(model, output.usage);
|
|
2732
2844
|
if (options?.applyServiceTierPricing) {
|
|
2733
2845
|
const tier = options.resolveServiceTier ? options.resolveServiceTier(response.service_tier, options.serviceTier) : response.service_tier ?? options.serviceTier;
|
|
2734
2846
|
options.applyServiceTierPricing(output.usage, tier);
|
|
2735
2847
|
}
|
|
2736
2848
|
};
|
|
2737
|
-
const finalizeResponse = (response, terminalEventType,
|
|
2738
|
-
|
|
2849
|
+
const finalizeResponse = (response, terminalEventType, rejectedToolCall) => {
|
|
2850
|
+
settleReasoning(response.output ?? []);
|
|
2739
2851
|
finalizeTerminalFacts(response);
|
|
2740
2852
|
const terminal = resolveResponsesTerminalStopReason({
|
|
2741
2853
|
status: response.status,
|
|
@@ -2744,11 +2856,11 @@ function createResponsesTerminalController(params) {
|
|
|
2744
2856
|
hasToolCall: blocks.some((block) => block.type === "toolCall")
|
|
2745
2857
|
});
|
|
2746
2858
|
output.stopReason = terminal.stopReason;
|
|
2747
|
-
output.errorMessage = terminal.errorMessage;
|
|
2859
|
+
if (terminal.errorMessage !== void 0) output.errorMessage = terminal.errorMessage;
|
|
2748
2860
|
if (terminalEventType === "response.completed" && typeof response.end_turn === "boolean") output.endTurn = response.end_turn;
|
|
2749
2861
|
const incompleteReason = response.incomplete_details?.reason;
|
|
2750
2862
|
const incompleteCall = response.output?.find((item) => item.type === "function_call" && item.status && item.status !== "completed");
|
|
2751
|
-
const incompleteToolCallId = rejectedToolCallId ?? (terminalEventType === "response.incomplete" && !
|
|
2863
|
+
const incompleteToolCallId = rejectedToolCallId ?? (terminalEventType === "response.incomplete" && !rejectedToolCall ? params.toolCalls.values()[0]?.block.id : void 0) ?? (incompleteCall?.type === "function_call" && incompleteCall.call_id ? resolveResponsesToolCallId(incompleteCall) : void 0);
|
|
2752
2864
|
appendAssistantMessageDiagnostic(output, {
|
|
2753
2865
|
type: "openai_responses_terminal",
|
|
2754
2866
|
timestamp: Date.now(),
|
|
@@ -2760,14 +2872,17 @@ function createResponsesTerminalController(params) {
|
|
|
2760
2872
|
endTurn: typeof response.end_turn === "boolean" ? response.end_turn : response.end_turn === void 0 ? "absent" : "invalid"
|
|
2761
2873
|
}
|
|
2762
2874
|
});
|
|
2763
|
-
|
|
2875
|
+
const failure = rejectedToolCall ?? (terminalEventType === "response.incomplete" && params.toolCalls.hasActive() ? { error: new IncompleteToolCallError("Responses stream completed with unresolved tool calls") } : void 0);
|
|
2876
|
+
if (failure) throw output.errorMessage ? new Error(output.errorMessage) : failure.error;
|
|
2764
2877
|
};
|
|
2765
2878
|
return {
|
|
2766
2879
|
finalizeResponse,
|
|
2767
2880
|
finalizeFailedResponse: finalizeTerminalFacts,
|
|
2768
2881
|
recordIncompleteToolCall,
|
|
2769
2882
|
recoverTerminalOutput,
|
|
2770
|
-
emitToolCallCompletion
|
|
2883
|
+
emitToolCallCompletion,
|
|
2884
|
+
recordPendingReasoning,
|
|
2885
|
+
releaseDeferredToolCompletions
|
|
2771
2886
|
};
|
|
2772
2887
|
}
|
|
2773
2888
|
//#endregion
|
|
@@ -2792,17 +2907,19 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
2792
2907
|
});
|
|
2793
2908
|
const createOutputSlot = (event, item) => {
|
|
2794
2909
|
let slot;
|
|
2795
|
-
if (item.type === "reasoning")
|
|
2796
|
-
|
|
2797
|
-
item,
|
|
2798
|
-
block: {
|
|
2910
|
+
if (item.type === "reasoning") {
|
|
2911
|
+
slot = {
|
|
2799
2912
|
type: "thinking",
|
|
2800
|
-
|
|
2801
|
-
|
|
2802
|
-
|
|
2803
|
-
|
|
2804
|
-
|
|
2805
|
-
|
|
2913
|
+
item,
|
|
2914
|
+
block: {
|
|
2915
|
+
type: "thinking",
|
|
2916
|
+
thinking: ""
|
|
2917
|
+
},
|
|
2918
|
+
contentIndex: blocks.length,
|
|
2919
|
+
outputIndex: readResponsesOutputIndex(event)
|
|
2920
|
+
};
|
|
2921
|
+
terminal.recordPendingReasoning(slot.contentIndex);
|
|
2922
|
+
} else if (item.type === "message") {
|
|
2806
2923
|
const collapseCandidate = lastTextBlock;
|
|
2807
2924
|
const block = collapseCandidate ? null : createTextBlock(item, "");
|
|
2808
2925
|
slot = {
|
|
@@ -2916,7 +3033,7 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
2916
3033
|
if (tracked?.completed) continue;
|
|
2917
3034
|
const state = streamingToolCalls.resolve({ output_index: outputIndex }, readResponsesToolCallItemIdentity(item), allowUnmatchedIdentity);
|
|
2918
3035
|
if (tracked && !state) throw new Error("Responses stream completed with unresolved tool calls");
|
|
2919
|
-
const validated = resolveCompletedResponsesToolCall(item, { name: state?.
|
|
3036
|
+
const validated = resolveCompletedResponsesToolCall(item, { name: state?.providerName });
|
|
2920
3037
|
if (state) recovered.push(state);
|
|
2921
3038
|
prepared.set(outputIndex, () => finalizeToolCall(item, outputIndex, state, validated));
|
|
2922
3039
|
}
|
|
@@ -2966,6 +3083,7 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
2966
3083
|
const contentIndex = output.content.length;
|
|
2967
3084
|
const toolCallState = {
|
|
2968
3085
|
block: toolCallBlock,
|
|
3086
|
+
providerName: toolCallBlock.name,
|
|
2969
3087
|
contentIndex,
|
|
2970
3088
|
argumentStreamReliable: true,
|
|
2971
3089
|
argumentsStreamed: false,
|
|
@@ -3076,7 +3194,7 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
3076
3194
|
const summaryText = item.summary?.map((s) => s.text).join("\n\n") || "";
|
|
3077
3195
|
const contentText = item.content?.map((c) => c.text).join("\n\n") || "";
|
|
3078
3196
|
outputSlot.block.thinking = summaryText || contentText || outputSlot.block.thinking;
|
|
3079
|
-
outputSlot.block.thinkingSignature = JSON.stringify(item);
|
|
3197
|
+
outputSlot.block.thinkingSignature = JSON.stringify(normalizeOpenAIResponsesReasoningReplayItem(item, model.api));
|
|
3080
3198
|
outputs.set(item, outputSlot.contentIndex, readResponsesOutputIndex(event) ?? outputSlot.outputIndex, true);
|
|
3081
3199
|
if (item.encrypted_content && options?.reasoningReplayMetadata) outputSlot.block[OPENAI_RESPONSES_REASONING_REPLAY_BLOCK_META_KEY] = options.reasoningReplayMetadata;
|
|
3082
3200
|
stream.push({
|
|
@@ -3150,7 +3268,7 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
3150
3268
|
let validated;
|
|
3151
3269
|
try {
|
|
3152
3270
|
validated = resolveCompletedResponsesToolCall(item, {
|
|
3153
|
-
name: streamingToolCall?.
|
|
3271
|
+
name: streamingToolCall?.providerName,
|
|
3154
3272
|
arguments: parsedStreamedArguments ?? (completedArguments || streamedArguments)
|
|
3155
3273
|
});
|
|
3156
3274
|
} catch (error) {
|
|
@@ -3160,8 +3278,7 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
3160
3278
|
finalizeToolCall(item, readResponsesOutputIndex(event), streamingToolCall, validated);
|
|
3161
3279
|
}
|
|
3162
3280
|
} else if (event.type === "response.completed" || event.type === "response.incomplete") {
|
|
3163
|
-
terminal.finalizeResponse(event.response, event.type,
|
|
3164
|
-
if (rejectedToolCall) throw output.errorMessage ? new Error(output.errorMessage) : rejectedToolCall.error;
|
|
3281
|
+
terminal.finalizeResponse(event.response, event.type, rejectedToolCall);
|
|
3165
3282
|
if (event.type === "response.completed" || output.stopReason === "length") {
|
|
3166
3283
|
const items = event.response.output ?? [];
|
|
3167
3284
|
const completeToolCall = event.type === "response.completed" ? prepareTerminalToolCalls(items) : void 0;
|
|
@@ -3190,7 +3307,8 @@ async function processResponsesStream(openaiStream, output, sink, model, options
|
|
|
3190
3307
|
if (terminalResponse === void 0) throw new Error("OpenAI Responses stream ended before a terminal response event");
|
|
3191
3308
|
return terminalResponse ?? void 0;
|
|
3192
3309
|
} finally {
|
|
3193
|
-
for (const block of output.content) delete block.partialJson;
|
|
3310
|
+
for (const block of output.content) if (block.type === "toolCall") delete block.partialJson;
|
|
3311
|
+
terminal.releaseDeferredToolCompletions();
|
|
3194
3312
|
}
|
|
3195
3313
|
}
|
|
3196
3314
|
//#endregion
|
|
@@ -3226,14 +3344,7 @@ function convertPreparedResponsesTools(prepared, strictSetting, model) {
|
|
|
3226
3344
|
model
|
|
3227
3345
|
}) : resolveOpenAIProjectedToolsStrictToolFlag(projection, strictSetting);
|
|
3228
3346
|
return sortPromptCacheToolsByName(projection.tools).map((tool) => {
|
|
3229
|
-
|
|
3230
|
-
type: "function",
|
|
3231
|
-
name: tool.name,
|
|
3232
|
-
description: tool.description,
|
|
3233
|
-
parameters: normalizeOpenAIStrictToolParameters(tool.parameters, strict === true, model?.compat)
|
|
3234
|
-
};
|
|
3235
|
-
if (strict !== void 0) result.strict = strict;
|
|
3236
|
-
return result;
|
|
3347
|
+
return prepareOpenAIFunctionTool(tool.name, tool.description, normalizeOpenAIStrictToolParameters(tool.parameters, strict === true, model?.compat), strict).responses;
|
|
3237
3348
|
});
|
|
3238
3349
|
});
|
|
3239
3350
|
}
|
|
@@ -3282,7 +3393,7 @@ function applyCommonResponsesParams(params, model, context, options, config) {
|
|
|
3282
3393
|
function cleanStreamingScratchBuffers(output) {
|
|
3283
3394
|
for (const block of output.content) {
|
|
3284
3395
|
delete block.index;
|
|
3285
|
-
delete block.partialJson;
|
|
3396
|
+
if (block.type === "toolCall") delete block.partialJson;
|
|
3286
3397
|
}
|
|
3287
3398
|
}
|
|
3288
3399
|
async function runResponsesStreamLifecycle(params) {
|
|
@@ -3353,7 +3464,7 @@ async function runResponsesStreamLifecycle(params) {
|
|
|
3353
3464
|
const tier = requestedTier === "priority" || requestedTier === "default" ? requestedTier : originalTier;
|
|
3354
3465
|
return processStreamOptions?.resolveServiceTier ? processStreamOptions.resolveServiceTier(responseTier, tier) : responseTier ?? tier;
|
|
3355
3466
|
},
|
|
3356
|
-
onServiceTier: (responseTier) => responsesServiceTierObserver.observe(options, requestedTier, responseTier),
|
|
3467
|
+
onServiceTier: (responseTier, response) => responsesServiceTierObserver.observe(options, requestedTier, responseTier, response),
|
|
3357
3468
|
canRetryIdentityConflict: () => hasOnlyResponsesFunctionTools(admittedRequest),
|
|
3358
3469
|
reasoningReplayMetadata: buildOpenAIResponsesReasoningReplayMetadata(model, {
|
|
3359
3470
|
sessionId: options?.sessionId,
|
|
@@ -3393,4 +3504,4 @@ async function runResponsesStreamLifecycle(params) {
|
|
|
3393
3504
|
}
|
|
3394
3505
|
}
|
|
3395
3506
|
//#endregion
|
|
3396
|
-
export {
|
|
3507
|
+
export { isConfigurationUpdate as $, summarizeResponsesPayload as A, log as At, recordResponsesInputReplay as B, readResponsesRecoveryEvent as C, reconcileOpenAIResponsesToolChoice as Ct, logResponsesFailedNoDetails as D, createOpenAIResponseHook as Dt, ResponsesStreamFailure as E, createOpenAIProviderAcceptanceHook as Et, convertProviderResponsesMessages as F, resolveOpenAIClientBaseUrl as Ft, responsesContinuationPrefixFingerprint as G, claimOpenAIResponsesHttpContinuation as H, convertResponsesMessages as I, resolvePromptCacheKey as It, OPENAI_RESPONSES_FUNCTION_CALL_ITEM_ID_RE as J, responsesContinuationRequestFingerprint as K, normalizeOpenAIResponsesReasoningReplayItem as L, withOpenAIErrorResponseHook as Lt, resolveResponsesContextUsageBoundary as M, parseOpenAICompletionsUsage as Mt, bindResponsesInputMessage as N, readOpenAICompletionsContentDeltas as Nt, safeDebugValue as O, createResponseModelTracker as Ot, buildResponsesInputMessage as P, readOpenAICompletionsReasoningBatch as Pt, splitOpenAIFunctionCallPairing as Q, resolveReplayableResponsesMessageId as R, isInvalidEncryptedContentError as S, reconcileOpenAICompletionsToolChoice as St, resolveNextResponsesEncryptedContentAttempt as T, GEMINI_THOUGHT_SIGNATURE_VALIDATOR_SKIP as Tt, recordResponsesContinuationState as U, responsesInputFingerprint as V, resolveResponsesContinuationRequest as W, normalizeOpenAIResponsesFunctionCallId as X, OPENAI_RESPONSES_ID_MAX_LENGTH as Y, shouldNormalizeOpenAIResponsesToolCallId as Z, isResponsesTextContentPartType as _, resolveOpenAIRequestReasoning as _t, prepareResponsesTools as a, resolveNewestOpenAIResponsesCompactionReplay as at, commitResponsesEncryptedContentAttempt as b, prepareOpenAITools as bt, observeResponsesStream as c, buildOpenAIClientHeaders as ct, AZURE_RESPONSES_TEXT_CONTENT_PART_TYPE as d, enforceCodeModeResponsesToolSurface as dt, replayResponsesReasoningUpdates as et, AZURE_RESPONSES_TEXT_DELTA_EVENT_TYPE as f, filterCodeModePayloadTools as ft, isAzureResponsesTextDeltaEventType as g, resolveOpenAIStrictToolFlagWithDiagnostics as gt, isAzureResponsesTextDeltaEvent as h, resolveCodeModeResponsesVisibleToolNames as ht, convertResponsesToolPayload as i, captureOpenAIResponsesCompaction as it, recordResponsesContextUsage as j, measureUtf8AppendBytes as jt, summarizeOpenAITransportError as k, isOpenAICompletionsThinkingEnabled as kt, createResponsesToolCallTracker as l, buildOpenAISdkClientOptions as lt, OPENAI_RESPONSES_OUTPUT_TEXT_DELTA_EVENT_TYPE as m, readCodeModePayloadToolName as mt, applyResponsesServiceTierPricing as n, CompactionReplayRefreshRequiredError as nt, readOpenAIMisalignmentReview as o, suppressOpenAIResponsesCompaction as ot, OPENAI_RESPONSES_OUTPUT_TEXT_CONTENT_PART_TYPE as p, getCompat as pt, OPENAI_RESPONSES_CALL_ID_RE as q, runResponsesStreamLifecycle as r, buildOpenAIResponsesReasoningReplayMetadata as rt, processResponsesStream as s, assertCodeModeResponsesToolSurface as st, applyCommonResponsesParams as t, supportsResponsesReasoningUpdate as tt, readResponsesToolCallItemIdentity as u, buildOpenAISdkRequestOptions as ut, isResponsesTextDeltaEventType as v, resolveOpenAISimpleReasoningEffort as vt, resolveAzureOpenAIApiVersion as w, toOpenAIResponsesToolChoice as wt, createResponsesStreamWithRecovery as x, projectOpenAITools as xt, resolveResponsesMessageSnapshotCollapse as y, resolveOpenAIReasoningEffortMap as yt, readResponsesInputReplayState as z };
|