@openclaw/ai 2026.11.2 → 2026.11.3

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.
Files changed (34) hide show
  1. package/README.md +7 -0
  2. package/dist/{anthropic-CUVqVXTe.mjs → anthropic-lueA8LUg.mjs} +1 -1
  3. package/dist/{anthropic-payload-policy-rqCq9sT_.d.mts → anthropic-payload-policy-C0ki72BT.d.mts} +1 -1
  4. package/dist/{anthropic-tool-projection-JTvMo4KG.d.mts → anthropic-tool-projection-C2-d1eZ3.d.mts} +1 -1
  5. package/dist/{azure-openai-responses-I97-HnAv.mjs → azure-openai-responses-BvvXzZbi.mjs} +2 -2
  6. package/dist/{google-interactions-BYRQ49MR.mjs → google-interactions-CGINbsjO.mjs} +1 -1
  7. package/dist/internal/anthropic.d.mts +3 -3
  8. package/dist/internal/anthropic.mjs +1 -1
  9. package/dist/internal/openai-responses-payload-policy.d.mts +1 -1
  10. package/dist/internal/openai.d.mts +3 -3
  11. package/dist/internal/openai.mjs +5 -5
  12. package/dist/internal/runtime.mjs +1 -1
  13. package/dist/internal/shared.d.mts +1 -1
  14. package/dist/internal/tool-schema.d.mts +2 -2
  15. package/dist/openai-CiRi-nVE.mjs +20077 -0
  16. package/dist/{openai-chatgpt-responses-DgDVhpUI.mjs → openai-chatgpt-responses-BZa3SySh.mjs} +2 -2
  17. package/dist/{openai-completions-BdfBhFjx.mjs → openai-completions-CCZ_UHCk.mjs} +2 -2
  18. package/dist/openai-completions-transport-DFvSBbUT.mjs +10881 -0
  19. package/dist/{openai-responses-5KI4v8DN.mjs → openai-responses-DQsZKUoI.mjs} +3 -3
  20. package/dist/{openai-responses-compaction-replay-DUBbsfku.d.mts → openai-responses-compaction-replay-_sUXtcwU.d.mts} +2 -2
  21. package/dist/{openai-responses-contracts-gnl6ZRs1.d.mts → openai-responses-contracts-B1nkeLL6.d.mts} +1 -1
  22. package/dist/{openai-responses-request-lifecycle-WKXjj_th.mjs → openai-responses-request-lifecycle-CTqHc02t.mjs} +1 -1
  23. package/dist/{openai-responses-shared-iWBHb0Sq.mjs → openai-responses-shared-wx9v1MCn.mjs} +1079 -2
  24. package/dist/openai.LICENSE +201 -0
  25. package/dist/{provider-options-Bo8GzTGX.d.mts → provider-options-DAzsyi49.d.mts} +1 -1
  26. package/dist/{provider-transport-turn-state-BbaD56A1.mjs → provider-transport-turn-state-D_GjPJHe.mjs} +2 -2
  27. package/dist/providers.mjs +6 -6
  28. package/dist/{reasoning-tag-text-partitioner-DzlRubwU.mjs → reasoning-tag-text-partitioner-CU9A4Lg8.mjs} +2 -13
  29. package/dist/rolldown-runtime-B4iAMlE-.mjs +35 -0
  30. package/dist/transports.d.mts +5 -5
  31. package/dist/transports.mjs +3 -3
  32. package/dist/ws.LICENSE +20 -0
  33. package/package.json +1 -1
  34. package/dist/openai-completions-transport-CnFaKYO-.mjs +0 -3425
@@ -1,3425 +0,0 @@
1
- import { t as createReasoningTagTextPartitioner } from "./reasoning-tag-text-partitioner-DzlRubwU.mjs";
2
- import { _ as runtimeContextContentToText, f as hasRuntimeContextMarker, p as isRuntimeContextMessage } from "./types-BXd0kI8-.mjs";
3
- import { t as appendAssistantMessageDiagnostic } from "./diagnostics-DzrF1h4J.mjs";
4
- import { r as appendAssistantThinking } from "./event-stream-X2gmsUWv.mjs";
5
- import { i as asOptionalRecord, o as isRecord, r as asOptionalObjectRecord } from "./record-coerce-CNDovvft.mjs";
6
- import { c as readNonEmptyStringPreservingWhitespace, t as hasNonEmptyString } from "./string-coerce-Cj8sqWHx.mjs";
7
- import { n as asNonNegativeFiniteNumber, r as asPositiveFiniteNumber } from "./number-coercion-37gmNkuA.mjs";
8
- import { N as isImageWithMediaPayload, a as resolveAiTransportHeaderSentinels, r as getAiTransportHost } from "./host-CWt55nnF.mjs";
9
- import { L as resolveOpenAIThinkingApi, _ as responsesServiceTierObserver, b as applyOpenAICompletionsToolReasoning, d as OpenAIResponsesWebSocketSafeRetryError, h as parseOpenAIResponsesWebSocketServerError, j as supportsOpenAITemperature, l as OpenAIResponsesWebSocketPostDispatchError, r as OPENAI_CODEX_RESPONSES_DEFAULT_INSTRUCTIONS, t as AZURE_RESPONSES_FIRST_EVENT_TIMEOUT_MS, u as OpenAIResponsesWebSocketPreDispatchError, v as isResponsesServiceTierRejection, w as isOpenAIGpt6Model, y as nextResponsesServiceTier } from "./openai-responses-contracts-B5mGAbR6.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 { r as resolveOpenAIPromptCacheParams } from "./openai-prompt-cache-B9AvdoEo.mjs";
13
- import { i as emitModelTransportError, p as hasOnlyResponsesFunctionTools, r as emitModelTransportDebug, t as formatModelTransportDebugBaseUrl, u as DegenerateToolCallArgumentsError } from "./diagnostics-v7oVEW59.mjs";
14
- import { c as supportsModelTools, n as estimateStringChars } from "./transport-utils-DwOpuTjL.mjs";
15
- import { c as resolveOpenAIResponsesTextFormat, i as resolveOpenAICompletionsCompat, l as shouldOmitOllamaCompatResponseFormat, n as isNativeOpenAIEndpoint, o as usesNativeOpenAICodexResponsesBackend, r as isOpenAICodexResponsesModel, s as resolveOpenAICompletionsResponseFormat, t as detectOpenAICompletionsCompat } from "./openai-completions-compat-bNQXF1y9.mjs";
16
- import { i as resolveProviderEndpoint, t as buildGuardedModelFetch } from "./host-policy-Dm7PM6AD.mjs";
17
- import { i as resolveCacheRetention, r as buildCopilotDynamicHeaders } from "./cloudflare-Dttf8jKq.mjs";
18
- import { t as sanitizeSurrogates } from "./sanitize-unicode-CRGuMONI.mjs";
19
- import { r as sortPromptCacheToolsByName } from "./prompt-cache-stability-D_MeCQFI.mjs";
20
- import { C as splitSystemPromptRelocatableBoundary, S as splitSystemPromptCacheBoundary, T as stripSystemPromptRelocatableBoundary, f as extractToolResultText, g as reasoningTagTextPolicy, h as preparedRequestSuffix, l as describeToolResultMediaPlaceholder, m as codeModeToolSurfaceObserver, r as clampMaxTokensToModel, s as prepareModelRequestBody, w as stripSystemPromptCacheBoundary } from "./simple-options-xJkqrG_E.mjs";
21
- import { A as shortHash, E as createToolArgumentPreviewSchedule, M as racePromiseWithAbortSignal, O as parseStreamingJson, S as withProviderResponseHook, b as transportAbortError, c as failTransportStream, d as iterateModelStream, h as notifyProviderStreamOpened, l as finalizeTerminalToolCallArguments, s as createWritableTransportEventStream, u as finalizeTransportStream, v as sanitizeTransportPayloadText, y as throwIfModelStreamAborted } from "./transport-stream-shared-lhgkTOz3.mjs";
22
- import { C as redactIdentifier, w as sha256Hex } from "./tool-schema-json-projection-B1sTYwfH.mjs";
23
- import { n as getEnvApiKey } from "./env-api-keys-Xd8dm_aV.mjs";
24
- import { n as isProviderReplayContext, r as providerReplayContextMatches, t as buildProviderReplayContext } from "./provider-replay-context-4vxI7p4V.mjs";
25
- import { n as transformProviderMessages, t as createAssistantOutput } from "./assistant-output-BnQm3fov.mjs";
26
- import { t as notifyLlmRequestActivity } from "./llm-request-activity-CfMuh5cC.mjs";
27
- import { n as resolveOpencodeSessionHeaders } from "./session-affinity-DA4WHv1h.mjs";
28
- import { isGoogleGemini3ThinkingLevelModel } from "./internal/google-model-family.mjs";
29
- import "./types.mjs";
30
- import { $ as isConfigurationUpdate, A as summarizeResponsesPayload, At as isOpenAICompletionsThinkingEnabled, B as recordResponsesInputReplay, C as readResponsesRecoveryEvent, Ct as reconcileOpenAIResponsesToolChoice, D as logResponsesFailedNoDetails, E as ResponsesStreamFailure, Et as createOpenAIProviderAcceptanceHook, Ft as readOpenAICompletionsReasoningBatch, G as responsesContinuationPrefixFingerprint, H as claimOpenAIResponsesHttpContinuation, I as convertResponsesMessages, It as resolveOpenAIClientBaseUrl, K as responsesContinuationRequestFingerprint, Lt as resolvePromptCacheKey, Mt as measureUtf8AppendBytes, Nt as parseOpenAICompletionsUsage, O as safeDebugValue, Ot as createResponseModelTracker, P as buildResponsesInputMessage, Pt as readOpenAICompletionsContentDeltas, Rt as withOpenAIErrorResponseHook, S as isInvalidEncryptedContentError, St as reconcileOpenAICompletionsToolChoice, T as resolveNextResponsesEncryptedContentAttempt, Tt as GEMINI_THOUGHT_SIGNATURE_VALIDATOR_SKIP, U as recordResponsesContinuationState, V as responsesInputFingerprint, W as resolveResponsesContinuationRequest, _t as resolveOpenAIRequestReasoning, a as prepareResponsesTools, bt as prepareOpenAITools, c as observeResponsesStream, ct as buildOpenAIClientHeaders, dt as enforceCodeModeResponsesToolSurface, et as replayResponsesReasoningUpdates, gt as resolveOpenAIStrictToolFlagWithDiagnostics, ht as resolveCodeModeResponsesVisibleToolNames, j as recordResponsesContextUsage, jt as log, k as summarizeOpenAITransportError, kt as detachPartialSnapshot, lt as buildOpenAISdkClientOptions, n as applyResponsesServiceTierPricing, ot as suppressOpenAIResponsesCompaction, pt as getCompat, rt as buildOpenAIResponsesReasoningReplayMetadata, s as processResponsesStream, st as assertCodeModeResponsesToolSurface, tt as supportsResponsesReasoningUpdate, ut as buildOpenAISdkRequestOptions, vt as resolveOpenAISimpleReasoningEffort, w as resolveAzureOpenAIApiVersion, wt as toOpenAIResponsesToolChoice, x as createResponsesStreamWithRecovery, xt as projectOpenAITools, z as readResponsesInputReplayState } from "./openai-responses-shared-iWBHb0Sq.mjs";
31
- import { i as createOpenAIProviderClient, n as resolveProviderSimpleCompletionHeaders, r as resolveProviderTransportTurnState, t as filterProviderTurnHeadersForExplicitOpencodeSession } from "./provider-transport-turn-state-BbaD56A1.mjs";
32
- import { a as withFirstStreamEventTimeout, i as getFirstStreamEventTimeoutMs, r as getFirstStreamEventTimeoutHandler, t as createFirstStreamEventAbortController } from "./stream-first-event-timeout-D_TfJHRJ.mjs";
33
- import { t as boundResponseBody } from "./streaming-byte-guard-DBXr1XYn.mjs";
34
- import { b as prepareOpenAIFunctionTool, f as normalizeToolSchema, p as withPreparedToolSchemaNormalization, r as normalizeOpenAIStrictToolParameters } from "./openai-tool-schema-BTEU2xmN.mjs";
35
- import { t as requiresReasoningContentReplay } from "./openai-completions-reasoning-replay-BwT1xwRI.mjs";
36
- import { t as mapOpenAIStopReason } from "./openai-stop-reason-8s70vDXj.mjs";
37
- import { i as resolveAzureDeploymentNameFromMap, t as isOpenAICompatibleAzureResponsesBaseUrl } from "./azure-openai-responses-client-compat-D0dvJMbZ.mjs";
38
- import { a as isOpenAIResponsesCompactionOutput, c as applyOpenAIResponsesPayloadPolicy, d as resolveOpenAIResponsesPayloadPolicy, i as getOpenAIResponsesCompactionOutputError, n as supportsNativeOpenAIResponsesEndpoint, r as createBoundedOpenAIResponsesCompactionFetch, s as sanitizeResponsesImagePayload, t as isOfficialOpenAIResponsesBaseUrl } from "./openai-responses-endpoint-CfKR6N5f.mjs";
39
- import { a as createResponsesV2CompactionCollector, i as createResponsesPromptEgressObserver, n as responsesRequestLifecycle, o as claimResponsesCompactRequest, r as withResponsesRequestAcceptance, t as independentResponsesRequest } from "./openai-responses-request-lifecycle-WKXjj_th.mjs";
40
- import { randomUUID } from "node:crypto";
41
- import OpenAI, { AzureOpenAI } from "openai";
42
- import { ResponsesWS } from "openai/resources/responses/ws.js";
43
- //#region packages/ai/src/transports/deepseek-dsml-grammar.ts
44
- const DEEPSEEK_DSML_MARKERS = [
45
- "|",
46
- "|",
47
- "||"
48
- ].flatMap((bar) => [`${bar}DSML${bar}`, `${bar}DSML${bar} `]);
49
- const DEEPSEEK_DSML_TOOL_OPEN_TOKENS = DEEPSEEK_DSML_MARKERS.flatMap((marker) => [
50
- "calls",
51
- "tool_calls",
52
- "tool_call",
53
- "function_calls"
54
- ].map((kind) => `<${marker}${kind}>`));
55
- const DEEPSEEK_DSML_MARKER_PATTERN = `(${DEEPSEEK_DSML_MARKERS.map((marker) => marker.replaceAll("|", "\\|")).join("|")})`;
56
- function findEarliestDsmlToken(text, tokens, fromIndex = 0) {
57
- let best = null;
58
- for (const token of tokens) {
59
- const index = text.indexOf(token, fromIndex);
60
- if (index !== -1 && (!best || index < best.index)) best = {
61
- index,
62
- token
63
- };
64
- }
65
- return best;
66
- }
67
- function longestDsmlTokenPrefixSuffixLength(text, tokens, maxTokenLength) {
68
- const maxLength = Math.min(text.length, maxTokenLength - 1);
69
- for (let length = maxLength; length > 0; length--) {
70
- const suffix = text.slice(text.length - length);
71
- if (tokens.some((token) => token.startsWith(suffix))) return length;
72
- }
73
- return 0;
74
- }
75
- //#endregion
76
- //#region packages/ai/src/transports/deepseek-text-filter.ts
77
- /**
78
- * DeepSeek DSML streaming text filter.
79
- * Removes provider-emitted DSML tool markup while buffering split tag prefixes
80
- * across streamed chunks.
81
- */
82
- const DSML_OPEN_TOKENS = [...DEEPSEEK_DSML_TOOL_OPEN_TOKENS, ...DEEPSEEK_DSML_MARKERS.map((marker) => `<${marker}tool_use_error>`)];
83
- const MAX_OPEN_TOKEN_LEN = Math.max(...DSML_OPEN_TOKENS.map((token) => token.length));
84
- /** Create an incremental text filter that strips DeepSeek DSML tool blocks. */
85
- function createDeepSeekTextFilter() {
86
- let buffer = "";
87
- let closeToken;
88
- const consume = (final) => {
89
- const output = [];
90
- const emit = (text) => {
91
- if (text) output.push(text);
92
- };
93
- while (buffer) {
94
- if (closeToken) {
95
- const closeIndex = buffer.indexOf(closeToken);
96
- if (closeIndex !== -1) {
97
- buffer = buffer.slice(closeIndex + closeToken.length);
98
- closeToken = void 0;
99
- continue;
100
- }
101
- const keep = final ? 0 : Math.min(buffer.length, closeToken.length - 1);
102
- buffer = buffer.slice(buffer.length - keep);
103
- if (final) closeToken = void 0;
104
- return output;
105
- }
106
- const open = findEarliestDsmlToken(buffer, DSML_OPEN_TOKENS);
107
- if (open) {
108
- emit(buffer.slice(0, open.index));
109
- buffer = buffer.slice(open.index + open.token.length);
110
- closeToken = open.token.replace("<", "</");
111
- continue;
112
- }
113
- if (final) {
114
- emit(buffer);
115
- buffer = "";
116
- return output;
117
- }
118
- const keep = longestDsmlTokenPrefixSuffixLength(buffer, DSML_OPEN_TOKENS, MAX_OPEN_TOKEN_LEN);
119
- const emitLength = buffer.length - keep;
120
- if (emitLength <= 0) return output;
121
- emit(buffer.slice(0, emitLength));
122
- buffer = buffer.slice(emitLength);
123
- return output;
124
- }
125
- return output;
126
- };
127
- return {
128
- push(chunk) {
129
- buffer += chunk;
130
- return consume(false);
131
- },
132
- flush() {
133
- return consume(true);
134
- }
135
- };
136
- }
137
- //#endregion
138
- //#region packages/ai/src/transports/model-max-tokens-params.ts
139
- /**
140
- * Max-token parameter normalization across provider/native naming variants.
141
- * Callers canonicalize aliases before dispatch so payloads cannot carry
142
- * conflicting limits.
143
- */
144
- const MAX_TOKENS_PARAM_KEYS = [
145
- "maxTokens",
146
- "max_completion_tokens",
147
- "max_tokens"
148
- ];
149
- /** Resolve the first supported max-token parameter present in a params object. */
150
- function resolveMaxTokensParam(params) {
151
- if (!params) return;
152
- for (const key of MAX_TOKENS_PARAM_KEYS) {
153
- const resolved = asNonNegativeFiniteNumber(params[key]);
154
- if (resolved !== void 0) return resolved;
155
- }
156
- }
157
- /**
158
- * Canonicalize merged params to `maxTokens`, preserving source precedence from
159
- * left to right across the provided source objects.
160
- */
161
- function canonicalizeMaxTokensParam(params) {
162
- let resolved;
163
- for (const source of params.sources) {
164
- const sourceValue = resolveMaxTokensParam(source);
165
- if (sourceValue !== void 0) resolved = sourceValue;
166
- }
167
- if (resolved === void 0) return;
168
- for (const key of MAX_TOKENS_PARAM_KEYS) delete params.merged[key];
169
- params.merged.maxTokens = resolved;
170
- }
171
- //#endregion
172
- //#region packages/ai/src/transports/openai-compatible-conversation-turn.ts
173
- function hasNonEmptyContentPart(part) {
174
- if (!part || typeof part !== "object") return false;
175
- const record = part;
176
- if (record.type === "text") return hasNonEmptyString(record.text);
177
- return true;
178
- }
179
- function hasNonEmptyMessageContent(content) {
180
- if (hasNonEmptyString(content)) return true;
181
- if (!Array.isArray(content)) return false;
182
- return content.some(hasNonEmptyContentPart);
183
- }
184
- /** Returns whether an OpenAI-compatible messages payload contains a usable turn. */
185
- function hasOpenAICompatibleConversationTurn(messages) {
186
- if (!Array.isArray(messages)) return false;
187
- return messages.some((message) => {
188
- if (!message || typeof message !== "object") return false;
189
- const record = message;
190
- if (record.role === "user") return hasNonEmptyMessageContent(record.content);
191
- if (record.role === "assistant") {
192
- if (hasNonEmptyMessageContent(record.content)) return true;
193
- const toolCalls = record.tool_calls;
194
- return Array.isArray(toolCalls) && toolCalls.some((toolCall) => toolCall && typeof toolCall === "object");
195
- }
196
- return false;
197
- });
198
- }
199
- //#endregion
200
- //#region packages/ai/src/transports/openai-completions-cache-control.ts
201
- const shapedPayloads = /* @__PURE__ */ new WeakSet();
202
- function resolveCompletionsCacheControl(compat, retention, openRouterRoute) {
203
- if (compat.cacheControlFormat !== "anthropic" || retention === "none") return;
204
- return {
205
- type: "ephemeral",
206
- ...retention === "long" && compat.supportsLongCacheRetention && (openRouterRoute || compat.configuredSupportsLongCacheRetention === true) ? { ttl: "1h" } : {}
207
- };
208
- }
209
- /** Shared Chat Completions policy; repeated wrapper application preserves existing checkpoints. */
210
- function applyCompletionsAnthropicCacheControl(payload, cacheControl = { type: "ephemeral" }, cacheOptOutIndexes = /* @__PURE__ */ new Set(), markTools = true, markMessages = true) {
211
- if (shapedPayloads.has(payload)) return;
212
- shapedPayloads.add(payload);
213
- const messages = Array.isArray(payload.messages) ? payload.messages : [];
214
- const tools = Array.isArray(payload.tools) ? payload.tools : [];
215
- let lastToolIndex = -1;
216
- for (let index = 0; index < tools.length; index++) {
217
- const tool = tools[index];
218
- if (isRecord(tool)) {
219
- lastToolIndex = index;
220
- if (Object.hasOwn(tool, "cache_control")) {
221
- const unmarked = { ...tool };
222
- delete unmarked.cache_control;
223
- tools[index] = unmarked;
224
- }
225
- }
226
- }
227
- const blocks = messages.filter(isRecord).flatMap((message) => Array.isArray(message.content) ? message.content.filter(isRecord) : []);
228
- for (const block of blocks) delete block.cache_control;
229
- if (!cacheControl) return;
230
- const markText = (message, splitBoundary) => {
231
- if (typeof message.content === "string" && message.content) message.content = [{
232
- type: "text",
233
- text: message.content
234
- }];
235
- const content = message.content;
236
- if (!Array.isArray(content)) return false;
237
- for (let i = content.length - 1; i >= 0; i--) {
238
- const block = content[i];
239
- if (!isRecord(block) || block.type !== "text" || typeof block.text !== "string" || !block.text) continue;
240
- const split = splitBoundary ? splitSystemPromptCacheBoundary(block.text) : void 0;
241
- if (split) {
242
- content.splice(i, 1, ...split.stablePrefix ? [{
243
- type: "text",
244
- text: split.stablePrefix,
245
- cache_control: cacheControl
246
- }] : [], ...split.dynamicSuffix ? [{
247
- type: "text",
248
- text: split.dynamicSuffix
249
- }] : []);
250
- if (!split.stablePrefix) return false;
251
- } else block.cache_control = cacheControl;
252
- return true;
253
- }
254
- return false;
255
- };
256
- if (markTools && lastToolIndex >= 0) tools[lastToolIndex] = {
257
- ...tools[lastToolIndex],
258
- cache_control: cacheControl
259
- };
260
- if (!markMessages) return;
261
- const system = messages.find((message) => isRecord(message) && (message.role === "system" || message.role === "developer"));
262
- if (isRecord(system)) markText(system, true);
263
- for (let i = messages.length - 1; i >= 0; i--) {
264
- const message = messages[i];
265
- if (!cacheOptOutIndexes.has(i) && isRecord(message) && (message.role === "user" || message.role === "tool") && markText(message, false)) return;
266
- }
267
- }
268
- //#endregion
269
- //#region packages/ai/src/transports/openai-completions-string-content.ts
270
- /**
271
- * OpenAI Chat Completions compatibility helpers. Some providers only accept
272
- * role/content messages with plain string content instead of text block arrays.
273
- */
274
- /** Flatten string-only text block content arrays into newline-joined strings. */
275
- function flattenCompletionMessagesToStringContent(messages) {
276
- return messages.map((message) => {
277
- const record = asOptionalObjectRecord(message);
278
- const content = record?.content;
279
- if (!Array.isArray(content)) return message;
280
- const textParts = [];
281
- for (const item of content) {
282
- const part = asOptionalObjectRecord(item);
283
- if (part?.type !== "text" || typeof part.text !== "string") return message;
284
- textParts.push(part.text);
285
- }
286
- return {
287
- ...record,
288
- content: textParts.join("\n")
289
- };
290
- });
291
- }
292
- /** Strip completion messages to role/content fields for strict providers. */
293
- function stripCompletionMessagesToRoleContent(messages) {
294
- return messages.map((message) => {
295
- const record = asOptionalRecord(message);
296
- if (!record) return message;
297
- return {
298
- ...Object.hasOwn(record, "role") ? { role: record.role } : {},
299
- ...Object.hasOwn(record, "content") ? { content: record.content } : {}
300
- };
301
- });
302
- }
303
- //#endregion
304
- //#region packages/ai/src/providers/openai-completions-tool-calls.ts
305
- const MAX_BUFFERED_TOOL_CALL_ARGUMENT_BYTES = 256e3;
306
- const MAX_BUFFERED_LEGACY_FOLLOWING_DELTA_BYTES = 256e3;
307
- const MAX_BUFFERED_LEGACY_FOLLOWING_DELTAS = 1024;
308
- /** Keep encrypted provider reasoning attached to the first matching tool call. */
309
- function createOpenAIEncryptedToolCallReasoningTracker() {
310
- const firstBlocks = /* @__PURE__ */ new Map();
311
- const pendingDetails = /* @__PURE__ */ new Map();
312
- return {
313
- rememberToolCall(id, block, previousId = id) {
314
- const previous = firstBlocks.get(previousId);
315
- if (previousId !== id && previous?.block === block) {
316
- firstBlocks.delete(previousId);
317
- if (previous.signature && block.thoughtSignature === previous.signature) delete block.thoughtSignature;
318
- }
319
- if (!id || firstBlocks.has(id)) return;
320
- const pendingDetail = pendingDetails.get(id);
321
- firstBlocks.set(id, {
322
- block,
323
- signature: pendingDetail
324
- });
325
- if (pendingDetail) {
326
- block.thoughtSignature = pendingDetail;
327
- pendingDetails.delete(id);
328
- }
329
- },
330
- consumeDetails(details) {
331
- if (!Array.isArray(details)) return;
332
- for (const detail of details) {
333
- if (!isRecord(detail) || detail.type !== "reasoning.encrypted" || typeof detail.id !== "string" || detail.id.length === 0 || typeof detail.data !== "string" || detail.data.length === 0) continue;
334
- const serializedDetail = JSON.stringify(detail);
335
- const matchingBlock = firstBlocks.get(detail.id);
336
- if (matchingBlock) {
337
- matchingBlock.signature = serializedDetail;
338
- matchingBlock.block.thoughtSignature = serializedDetail;
339
- } else pendingDetails.set(detail.id, serializedDetail);
340
- }
341
- }
342
- };
343
- }
344
- function hasObservableContent(value) {
345
- if (typeof value === "string") return value.length > 0;
346
- if (Array.isArray(value)) return value.some(hasObservableContent);
347
- if (isRecord(value)) return Object.entries(value).some(([field, nestedValue]) => field !== "type" && field !== "id" && field !== "index" && hasObservableContent(nestedValue));
348
- return false;
349
- }
350
- function hasOpenAICompletionsDeltaContent(delta) {
351
- return Object.entries(delta).some(([field, value]) => field !== "role" && hasObservableContent(value));
352
- }
353
- /** Normalize the SDK's legacy single-function lane into its modern tool-call shape. */
354
- function createOpenAICompletionsToolCallDeltaNormalizer() {
355
- let sawModernToolCall = false;
356
- let pendingLegacyArgumentBytes = 0;
357
- let pendingFollowingDeltaBytes = 0;
358
- let pendingLegacyToolCall;
359
- const modernArguments = /* @__PURE__ */ new Map();
360
- const pendingFollowingDeltas = [];
361
- const takePendingFollowingDeltas = () => {
362
- pendingFollowingDeltaBytes = 0;
363
- return pendingFollowingDeltas.splice(0).map((delta) => ({
364
- delta,
365
- toolCalls: []
366
- }));
367
- };
368
- const bufferFollowingDelta = (delta) => {
369
- const nextDeltaBytes = Buffer.byteLength(JSON.stringify(delta), "utf8");
370
- if (pendingFollowingDeltaBytes + nextDeltaBytes > MAX_BUFFERED_LEGACY_FOLLOWING_DELTA_BYTES || pendingFollowingDeltas.length >= MAX_BUFFERED_LEGACY_FOLLOWING_DELTAS) throw new Error("Exceeded legacy tool-call content buffer limit");
371
- pendingFollowingDeltaBytes += nextDeltaBytes;
372
- pendingFollowingDeltas.push(delta);
373
- };
374
- return (delta, finishReason) => {
375
- const ordinaryDelta = { ...delta };
376
- delete ordinaryDelta.function_call;
377
- delete ordinaryDelta.tool_calls;
378
- if (delta.tool_calls && delta.tool_calls.length > 0) {
379
- for (const toolCall of delta.tool_calls) {
380
- const index = typeof toolCall.index === "number" ? toolCall.index : void 0;
381
- const state = (index === void 0 ? void 0 : modernArguments.get(index)) ?? (toolCall.id ? modernArguments.get(toolCall.id) : void 0) ?? {
382
- bytes: 0,
383
- pendingHighSurrogate: false
384
- };
385
- if (index !== void 0) modernArguments.set(index, state);
386
- if (toolCall.id) modernArguments.set(toolCall.id, state);
387
- const argumentDelta = toolCall.function?.arguments ?? "";
388
- const append = measureUtf8AppendBytes(state.pendingHighSurrogate, argumentDelta);
389
- state.bytes += append.bytes;
390
- if (state.bytes > MAX_BUFFERED_TOOL_CALL_ARGUMENT_BYTES) throw new Error("Exceeded tool-call argument buffer limit");
391
- state.pendingHighSurrogate = append.endsWithHighSurrogate;
392
- }
393
- const precedingDeltas = takePendingFollowingDeltas();
394
- sawModernToolCall = true;
395
- pendingLegacyArgumentBytes = 0;
396
- pendingLegacyToolCall = void 0;
397
- return [...precedingDeltas, {
398
- delta: ordinaryDelta,
399
- toolCalls: delta.tool_calls
400
- }];
401
- }
402
- const functionCall = delta.function_call;
403
- if (sawModernToolCall || !functionCall && !pendingLegacyToolCall) return [{
404
- delta: ordinaryDelta,
405
- toolCalls: []
406
- }];
407
- const hadPendingLegacyCall = pendingLegacyToolCall !== void 0;
408
- const leadingDeltas = [];
409
- if (hasOpenAICompletionsDeltaContent(ordinaryDelta)) {
410
- if (hadPendingLegacyCall) bufferFollowingDelta(ordinaryDelta);
411
- else leadingDeltas.push({
412
- delta: ordinaryDelta,
413
- toolCalls: []
414
- });
415
- }
416
- if (functionCall && (functionCall.name || functionCall.arguments)) {
417
- const nextFunctionName = pendingLegacyToolCall?.function?.name ? void 0 : functionCall.name;
418
- const nextArgumentBytes = Buffer.byteLength(functionCall.arguments ?? "", "utf8") + Buffer.byteLength(nextFunctionName ?? "", "utf8");
419
- if (pendingLegacyArgumentBytes + nextArgumentBytes > MAX_BUFFERED_TOOL_CALL_ARGUMENT_BYTES) throw new Error("Exceeded tool-call argument buffer limit");
420
- pendingLegacyArgumentBytes += nextArgumentBytes;
421
- pendingLegacyToolCall ??= {
422
- index: 0,
423
- id: `call_${randomUUID().replaceAll("-", "").slice(0, 24)}`,
424
- type: "function",
425
- function: {}
426
- };
427
- const pendingFunction = pendingLegacyToolCall.function ??= {};
428
- if (nextFunctionName) pendingFunction.name = nextFunctionName;
429
- if (functionCall.arguments) pendingFunction.arguments = (pendingFunction.arguments ?? "") + functionCall.arguments;
430
- }
431
- if (!pendingLegacyToolCall) return leadingDeltas.length > 0 ? leadingDeltas : [{
432
- delta: ordinaryDelta,
433
- toolCalls: []
434
- }];
435
- if (finishReason === "function_call") {
436
- const confirmedLegacyToolCall = pendingLegacyToolCall;
437
- pendingLegacyToolCall = void 0;
438
- pendingLegacyArgumentBytes = 0;
439
- return [
440
- ...leadingDeltas,
441
- {
442
- delta: {},
443
- toolCalls: [confirmedLegacyToolCall]
444
- },
445
- ...takePendingFollowingDeltas()
446
- ];
447
- }
448
- if (finishReason) {
449
- pendingLegacyArgumentBytes = 0;
450
- pendingLegacyToolCall = void 0;
451
- return [...leadingDeltas, ...takePendingFollowingDeltas()];
452
- }
453
- return leadingDeltas;
454
- };
455
- }
456
- /** Publish only executable calls; streaming scratch state never belongs in replay. */
457
- function finalizeOpenAICompletionsToolCalls(output, options = {}) {
458
- const isToolCall = (block) => block.type === "toolCall";
459
- const hasToolCalls = output.content.some(isToolCall);
460
- if (output.stopReason === "toolUse" && !hasToolCalls) output.stopReason = "stop";
461
- if (output.stopReason === "stop" && hasToolCalls && options.allowSilentToolCallPromotion !== false && !output.content.some((block) => block.type === "text" && block.text.trim().length > 0)) output.stopReason = "toolUse";
462
- if (output.stopReason !== "toolUse") {
463
- if (hasToolCalls) output.content = output.content.filter((block) => !isToolCall(block));
464
- return;
465
- }
466
- const toolCalls = output.content.filter(isToolCall);
467
- const rejectToolCalls = () => {
468
- output.stopReason = "error";
469
- output.errorMessage = "Provider returned an incomplete or malformed tool call";
470
- output.content = output.content.filter((candidate) => !isToolCall(candidate));
471
- };
472
- if (toolCalls.some((call) => typeof call.name !== "string" || call.name.trim().length === 0 || typeof call.partialJson !== "string" || call.partialJson.trim().length === 0)) {
473
- rejectToolCalls();
474
- return;
475
- }
476
- try {
477
- finalizeTerminalToolCallArguments(toolCalls, (call) => call.partialJson);
478
- } catch {
479
- rejectToolCalls();
480
- return;
481
- }
482
- for (let contentIndex = 0; contentIndex < output.content.length; contentIndex += 1) {
483
- const block = output.content[contentIndex];
484
- if (!block || !isToolCall(block)) continue;
485
- delete block.partialJson;
486
- delete block.streamIndex;
487
- options.onConfirmedToolCall?.(block, contentIndex);
488
- }
489
- }
490
- //#endregion
491
- //#region packages/ai/src/transports/openai-completions-context-budget-buffer.ts
492
- const MAX_CONTEXT_BUDGET_BUFFER_CHUNKS = 8192;
493
- const MAX_CONTEXT_BUDGET_BUFFER_BYTES = 4194304;
494
- async function bufferContextLimitedCompletions(source, signal) {
495
- const iterator = source[Symbol.asyncIterator]();
496
- const chunks = [];
497
- let bufferedBytes = 0;
498
- let overflow;
499
- let finished = false;
500
- let failed = false;
501
- let sourceError;
502
- let finishReason;
503
- try {
504
- for (;;) {
505
- const next = await iterator.next();
506
- if (next.done) {
507
- finished = true;
508
- break;
509
- }
510
- const chunk = next.value;
511
- const chunkBytes = Buffer.byteLength(JSON.stringify(chunk) ?? "", "utf8");
512
- if (chunks.length >= MAX_CONTEXT_BUDGET_BUFFER_CHUNKS || bufferedBytes + chunkBytes > MAX_CONTEXT_BUDGET_BUFFER_BYTES) {
513
- overflow = next;
514
- break;
515
- }
516
- chunks.push(chunk);
517
- bufferedBytes += chunkBytes;
518
- const chunkFinishReason = chunk?.choices?.[0]?.finish_reason;
519
- if (chunkFinishReason) finishReason = chunkFinishReason;
520
- signal?.throwIfAborted();
521
- }
522
- } catch (error) {
523
- failed = true;
524
- sourceError = error;
525
- iterator.return?.().catch(() => void 0);
526
- }
527
- return {
528
- bounded: overflow === void 0,
529
- failed,
530
- finishReason,
531
- stream: { async *[Symbol.asyncIterator]() {
532
- try {
533
- yield* chunks;
534
- if (failed) throw sourceError;
535
- if (overflow !== void 0) {
536
- yield overflow.value;
537
- for (;;) {
538
- const next = await iterator.next();
539
- if (next.done) {
540
- finished = true;
541
- return;
542
- }
543
- yield next.value;
544
- }
545
- }
546
- } finally {
547
- chunks.length = 0;
548
- if (!finished && !failed) iterator.return?.().catch(() => void 0);
549
- }
550
- } }
551
- };
552
- }
553
- //#endregion
554
- //#region packages/ai/src/transports/openai-completions-host.ts
555
- /**
556
- * Chat Completions accepts Azure AI Foundry hosts in addition to traditional
557
- * Azure OpenAI hosts. Do not replace this with isTraditionalAzureOpenAIHost,
558
- * which intentionally excludes the .services.ai.azure.com Foundry suffix.
559
- */
560
- function isAzureOpenAICompatibleHost(hostname) {
561
- return hostname.endsWith(".openai.azure.com") || hostname.endsWith(".services.ai.azure.com") || hostname.endsWith(".cognitiveservices.azure.com");
562
- }
563
- //#endregion
564
- //#region packages/ai/src/openai-completions-messages.ts
565
- /** Whether replayed messages require a tools marker for proxy compatibility. */
566
- function hasToolCallHistory(messages) {
567
- return messages.some((message) => message.role === "toolResult" || message.role === "assistant" && Array.isArray(message.content) && message.content.some((block) => block.type === "toolCall"));
568
- }
569
- /** Convert a normalized transcript to OpenAI Chat Completions messages. */
570
- function convertMessages(model, context, compat, options = {}) {
571
- const params = [];
572
- const supportsTools = options.supportsTools !== false;
573
- const normalizeToolCallId = (id) => {
574
- if (id.includes("|")) return id.slice(0, id.indexOf("|")).replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 40);
575
- if (model.provider === "openai") return id.length > 40 ? truncateUtf16Safe(id, 40) : id;
576
- return id;
577
- };
578
- const transformedMessages = transformProviderMessages(context.messages, model, normalizeToolCallId);
579
- let relocatableSplit;
580
- let systemParamIndex;
581
- if (context.systemPrompt) {
582
- const role = model.reasoning && compat.supportsDeveloperRole ? "developer" : "system";
583
- let systemPrompt;
584
- if (options.preserveSystemPromptCacheBoundary) systemPrompt = stripSystemPromptRelocatableBoundary(context.systemPrompt);
585
- else {
586
- const split = splitSystemPromptRelocatableBoundary(context.systemPrompt);
587
- if (split && split.relocatable.length > 0) relocatableSplit = split;
588
- systemPrompt = stripSystemPromptCacheBoundary(context.systemPrompt);
589
- }
590
- systemParamIndex = params.length;
591
- params.push({
592
- role,
593
- content: sanitizeSurrogates(systemPrompt)
594
- });
595
- }
596
- let lastRole = null;
597
- for (let i = 0; i < transformedMessages.length; i++) {
598
- const msg = transformedMessages[i];
599
- if (!msg) continue;
600
- if (compat.requiresAssistantAfterToolResult && lastRole === "toolResult" && msg.role === "user") params.push({
601
- role: "assistant",
602
- content: "I have processed the tool results."
603
- });
604
- if (isRuntimeContextMessage(msg)) {
605
- params.push({
606
- role: compat.supportsDeveloperRole ? "developer" : "user",
607
- content: sanitizeSurrogates(runtimeContextContentToText(msg.content))
608
- });
609
- options.cacheOptOutIndexes?.add(params.length - 1);
610
- } else if (msg.role === "user") {
611
- let userParam;
612
- if (typeof msg.content === "string") userParam = {
613
- role: "user",
614
- content: sanitizeSurrogates(msg.content)
615
- };
616
- else {
617
- const content = msg.content.map((item) => {
618
- if (item.type === "text") return {
619
- type: "text",
620
- text: sanitizeSurrogates(item.text)
621
- };
622
- if (item.type === "video") return {
623
- type: "video_url",
624
- video_url: { url: `data:${item.mimeType};base64,${item.data}` }
625
- };
626
- return {
627
- type: "image_url",
628
- image_url: { url: `data:${item.mimeType};base64,${item.data}` }
629
- };
630
- });
631
- if (content.length === 0) continue;
632
- userParam = {
633
- role: "user",
634
- content
635
- };
636
- }
637
- if (hasRuntimeContextMarker(msg)) options.cacheOptOutIndexes?.add(params.length);
638
- params.push(userParam);
639
- } else if (msg.role === "assistant") {
640
- const assistantMsg = {
641
- role: "assistant",
642
- content: compat.requiresAssistantAfterToolResult ? "" : null
643
- };
644
- const assistantTexts = [];
645
- const nonEmptyThinkingBlocks = [];
646
- const toolCalls = [];
647
- msg.content.forEach((block) => {
648
- if (block.type === "text" && block.text.trim().length > 0) assistantTexts.push(sanitizeSurrogates(block.text));
649
- else if (block.type === "thinking" && block.thinking.trim().length > 0) nonEmptyThinkingBlocks.push(block);
650
- else if (block.type === "toolCall") {
651
- if (supportsTools) toolCalls.push(block);
652
- else assistantTexts.push(sanitizeSurrogates(`[tool call id=${block.id} name=${block.name}] ${JSON.stringify(block.arguments)}`));
653
- }
654
- });
655
- if (nonEmptyThinkingBlocks.length > 0 && compat.requiresThinkingAsText) assistantMsg.content = [{
656
- type: "text",
657
- text: nonEmptyThinkingBlocks.map((block) => sanitizeSurrogates(block.thinking)).join("\n\n")
658
- }, ...assistantTexts.map((text) => ({
659
- type: "text",
660
- text
661
- }))];
662
- else {
663
- const assistantText = assistantTexts.join("\n");
664
- if (assistantText.length > 0) assistantMsg.content = assistantText;
665
- if (nonEmptyThinkingBlocks.length > 0) {
666
- let signature = nonEmptyThinkingBlocks.at(0)?.thinkingSignature;
667
- if (model.provider === "opencode-go" && signature === "reasoning") signature = "reasoning_content";
668
- if (signature && signature.length > 0) assistantMsg[signature] = nonEmptyThinkingBlocks.map((block) => block.thinking).join("\n");
669
- }
670
- }
671
- if (toolCalls.length > 0) {
672
- assistantMsg.tool_calls = toolCalls.map((toolCall) => ({
673
- id: toolCall.id,
674
- type: "function",
675
- function: {
676
- name: toolCall.name,
677
- arguments: JSON.stringify(toolCall.arguments)
678
- }
679
- }));
680
- const reasoningDetails = toolCalls.flatMap((toolCall) => {
681
- const signature = toolCall.thoughtSignature;
682
- if (!signature) return [];
683
- try {
684
- const parsed = JSON.parse(signature);
685
- return parsed ? [parsed] : [];
686
- } catch {
687
- return [];
688
- }
689
- });
690
- if (reasoningDetails.length > 0) assistantMsg.reasoning_details = reasoningDetails;
691
- }
692
- if (compat.requiresReasoningContentOnAssistantMessages && model.reasoning && assistantMsg.reasoning_content === void 0) assistantMsg.reasoning_content = "";
693
- const content = assistantMsg.content;
694
- if (!(content !== null && content !== void 0 && content.length > 0) && !assistantMsg.tool_calls) continue;
695
- params.push(assistantMsg);
696
- } else if (msg.role === "toolResult") {
697
- const imageContentParts = [];
698
- let j = i;
699
- while (j < transformedMessages.length) {
700
- const toolMsg = transformedMessages.at(j);
701
- if (toolMsg?.role !== "toolResult") break;
702
- const textResult = extractToolResultText(toolMsg.content);
703
- const mediaPlaceholder = describeToolResultMediaPlaceholder(toolMsg.content);
704
- const images = toolMsg.content.filter(isImageWithMediaPayload);
705
- const content = textResult.trim() ? textResult : mediaPlaceholder ?? "(no output)";
706
- if (supportsTools) {
707
- const toolResultMsg = {
708
- role: "tool",
709
- content,
710
- tool_call_id: preparedRequestSuffix.has(context) ? preparedRequestSuffix.toolCallId(context, toolMsg.toolCallId, normalizeToolCallId(toolMsg.toolCallId)) : toolMsg.toolCallId
711
- };
712
- if (compat.requiresToolResultName && toolMsg.toolName) toolResultMsg.name = toolMsg.toolName;
713
- params.push(toolResultMsg);
714
- } else {
715
- const text = sanitizeSurrogates(`[tool result id=${toolMsg.toolCallId} name=${toolMsg.toolName}] ${content}`);
716
- const previous = params.at(-1);
717
- if (previous?.role !== "assistant") params.push({
718
- role: "assistant",
719
- content: text
720
- });
721
- else if (Array.isArray(previous.content)) previous.content.push({
722
- type: "text",
723
- text
724
- });
725
- else previous.content = previous.content ? `${previous.content}\n${text}` : text;
726
- }
727
- if (images.length > 0 && model.input.includes("image")) {
728
- const boundedToolName = sanitizeSurrogates(truncateUtf16Safe(toolMsg.toolName ?? "", 64));
729
- imageContentParts.push({
730
- type: "text",
731
- text: `Image(s) from tool result #${j - i + 1}${boundedToolName ? ` (${boundedToolName})` : ""}:`
732
- });
733
- for (const block of images) imageContentParts.push({
734
- type: "image_url",
735
- image_url: { url: `data:${block.mimeType};base64,${block.data}` }
736
- });
737
- }
738
- j += 1;
739
- }
740
- i = j - 1;
741
- if (imageContentParts.length > 0) {
742
- if (supportsTools && compat.requiresAssistantAfterToolResult) params.push({
743
- role: "assistant",
744
- content: "I have processed the tool results."
745
- });
746
- params.push({
747
- role: "user",
748
- content: imageContentParts
749
- });
750
- lastRole = "user";
751
- } else lastRole = supportsTools ? "toolResult" : "assistant";
752
- continue;
753
- }
754
- lastRole = msg.role;
755
- }
756
- if (relocatableSplit !== void 0 && systemParamIndex !== void 0) relocateNonBehavioralRegion({
757
- params,
758
- systemParamIndex,
759
- split: relocatableSplit,
760
- cacheOptOutIndexes: options.cacheOptOutIndexes
761
- });
762
- return params;
763
- }
764
- /** Commit relocation only after finding an emitted carrier. */
765
- function relocateNonBehavioralRegion(args) {
766
- const text = sanitizeSurrogates(stripSystemPromptCacheBoundary(args.split.relocatable));
767
- for (let index = args.systemParamIndex + 1; index < args.params.length; index++) {
768
- const param = args.params[index];
769
- if (!param || param.role !== "user") continue;
770
- if (typeof param.content === "string") param.content = `${param.content}\n\n${text}`;
771
- else if (Array.isArray(param.content)) param.content = [...param.content, {
772
- type: "text",
773
- text
774
- }];
775
- else continue;
776
- const systemParam = args.params[args.systemParamIndex];
777
- if (systemParam) systemParam.content = sanitizeSurrogates(stripSystemPromptCacheBoundary(args.split.remainingPrompt));
778
- args.cacheOptOutIndexes?.add(index);
779
- return;
780
- }
781
- }
782
- //#endregion
783
- //#region packages/ai/src/transports/openai-completions-policy.ts
784
- function applyCompletionsReasoningAndRouting(params, model, reasoning, compat, mode) {
785
- const direct = mode === "direct";
786
- const nativeEffort = compat.thinkingFormat === "openrouter" ? void 0 : reasoning.effort;
787
- const enabled = reasoning.thinkingEnabled ?? false;
788
- if (model.reasoning && (!compat.thinkingOffControlUndeclared || reasoning.thinkingEnabled !== void 0 || !reasoning.thinkingExplicit)) {
789
- let allowScalarEffort = true;
790
- if (direct && compat.thinkingFormat === "zai") {
791
- params.thinking = enabled ? {
792
- type: "enabled",
793
- clear_thinking: false
794
- } : { type: "disabled" };
795
- allowScalarEffort = false;
796
- } else if (compat.thinkingFormat === "qwen") {
797
- params.enable_thinking = enabled;
798
- allowScalarEffort = false;
799
- } else if (compat.thinkingFormat === "qwen-chat-template") {
800
- const chatTemplateReasoningEffort = enabled && reasoning.thinkingExplicit && model.compat?.supportedReasoningEfforts?.length ? reasoning.effort : void 0;
801
- params.chat_template_kwargs = {
802
- enable_thinking: enabled,
803
- ...direct ? { preserve_thinking: true } : {},
804
- ...chatTemplateReasoningEffort ? { reasoning_effort: chatTemplateReasoningEffort } : {}
805
- };
806
- allowScalarEffort = false;
807
- } else if (compat.thinkingFormat === "together" || direct && compat.thinkingFormat === "deepseek") {
808
- if (compat.thinkingFormat === "deepseek") params.thinking = { type: enabled ? "enabled" : "disabled" };
809
- else params.reasoning = { enabled };
810
- allowScalarEffort = enabled;
811
- }
812
- if (allowScalarEffort && compat.supportsReasoningEffort && (direct ? nativeEffort !== void 0 : nativeEffort)) params.reasoning_effort = nativeEffort;
813
- }
814
- if (!direct) return;
815
- if (compat.openRouterRouting) params.provider = compat.openRouterRouting;
816
- if (model.baseUrl.includes("ai-gateway.vercel.sh") && model.compat?.vercelGatewayRouting) {
817
- const routing = model.compat.vercelGatewayRouting;
818
- if (routing.only || routing.order) {
819
- const gatewayOptions = {};
820
- if (routing.only) gatewayOptions.only = routing.only;
821
- if (routing.order) gatewayOptions.order = routing.order;
822
- params.providerOptions = { gateway: gatewayOptions };
823
- }
824
- }
825
- }
826
- //#endregion
827
- //#region packages/ai/src/transports/openai-completions-replay.ts
828
- function isGoogleOpenAICompatModel(model) {
829
- const endpointClass = detectOpenAICompletionsCompat(model).capabilities.endpointClass;
830
- return model.provider === "google" || endpointClass === "google-generative-ai" || endpointClass === "google-vertex";
831
- }
832
- const GOOGLE_COMPAT_THOUGHT_SIGNATURE_ELLIPSIS_RE = /[\u2026]|\.\.\./;
833
- const GOOGLE_COMPAT_THOUGHT_SIGNATURE_BASE64_RE = /^[A-Za-z0-9+/=]+$/;
834
- function hasGoogleCompatThoughtSignatureTruncationFootprint(value) {
835
- return GOOGLE_COMPAT_THOUGHT_SIGNATURE_ELLIPSIS_RE.test(value) || GOOGLE_COMPAT_THOUGHT_SIGNATURE_BASE64_RE.test(value) && value.length % 4 !== 0;
836
- }
837
- function injectToolCallThoughtSignatures(outgoingMessages, context, model) {
838
- if (!isGoogleOpenAICompatModel(model)) return;
839
- const sigById = /* @__PURE__ */ new Map();
840
- const fallbackSig = isGoogleGemini3ThinkingLevelModel(model.id) ? GEMINI_THOUGHT_SIGNATURE_VALIDATOR_SKIP : void 0;
841
- for (const msg of context.messages ?? []) {
842
- if (msg.role !== "assistant") continue;
843
- if (!Array.isArray(msg.content)) continue;
844
- for (const block of msg.content) {
845
- if (block.type !== "toolCall") continue;
846
- const id = block.id;
847
- const sig = block.thoughtSignature;
848
- if (typeof id === "string" && typeof sig === "string" && sig.length > 0) {
849
- const isSameRoute = msg.api === model.api && msg.provider === model.provider && msg.model === model.id;
850
- if (!isSameRoute && !fallbackSig) continue;
851
- sigById.set(id, isSameRoute ? sig : fallbackSig ?? sig);
852
- }
853
- }
854
- }
855
- if (sigById.size === 0 && !fallbackSig) return;
856
- for (const message of outgoingMessages) {
857
- const toolCalls = "tool_calls" in message ? message.tool_calls : void 0;
858
- if (!Array.isArray(toolCalls)) continue;
859
- for (const toolCall of toolCalls) {
860
- let sig = sigById.get(toolCall.id) ?? fallbackSig;
861
- if (sig) {
862
- if (hasGoogleCompatThoughtSignatureTruncationFootprint(sig.trim())) sig = fallbackSig;
863
- }
864
- if (!sig) continue;
865
- Object.assign(toolCall, { extra_content: { google: { thought_signature: sig } } });
866
- }
867
- }
868
- }
869
- const COMPLETIONS_REASONING_REPLAY_FIELDS = [
870
- "reasoning_details",
871
- "reasoning_content",
872
- "reasoning",
873
- "reasoning_text"
874
- ];
875
- function sanitizeOpenRouterReasoningReplayFields(record) {
876
- const reasoningDetails = record.reasoning_details;
877
- if (typeof reasoningDetails === "string") {
878
- if (reasoningDetails.length > 0 && typeof record.reasoning !== "string") record.reasoning = reasoningDetails;
879
- delete record.reasoning_details;
880
- } else if (reasoningDetails !== void 0 && !Array.isArray(reasoningDetails)) delete record.reasoning_details;
881
- for (const field of ["reasoning", "reasoning_content"]) if (field in record && (typeof record[field] !== "string" || record[field] === "")) delete record[field];
882
- const reasoningText = record.reasoning_text;
883
- if (typeof reasoningText === "string" && reasoningText.length > 0 && typeof record.reasoning !== "string" && typeof record.reasoning_content !== "string") record.reasoning = reasoningText;
884
- delete record.reasoning_text;
885
- }
886
- function shouldPreserveReasoningContentReplay(model, compat) {
887
- if (compat.requiresReasoningContentOnAssistantMessages || compat.thinkingFormat === "deepseek" || compat.thinkingFormat === "zai" || shouldTrustReasoningContentReplayMetadata(model)) return true;
888
- return requiresReasoningContentReplay(model.id);
889
- }
890
- function shouldPreserveOpenRouterReasoningReplay(model) {
891
- if (model.provider !== "openrouter") return true;
892
- const normalizedModelId = model.id.trim().toLowerCase();
893
- return !(normalizedModelId.startsWith("anthropic/") || normalizedModelId.startsWith("x-ai/"));
894
- }
895
- function shouldTrustReasoningContentReplayMetadata(model) {
896
- if (!model.reasoning) return false;
897
- if (model.provider.trim().toLowerCase() === "openai") return false;
898
- return shouldPreserveOpenRouterReasoningReplay(model);
899
- }
900
- function applyCompletionsReplay(outgoingMessages, context, model, compat) {
901
- injectToolCallThoughtSignatures(outgoingMessages, context, model);
902
- const preserveOpenRouterReasoning = compat.thinkingFormat === "openrouter" && shouldPreserveOpenRouterReasoningReplay(model);
903
- const preserveReasoningContent = shouldPreserveReasoningContentReplay(model, compat);
904
- for (const message of outgoingMessages) {
905
- if (message.role !== "assistant") continue;
906
- if (preserveOpenRouterReasoning) sanitizeOpenRouterReasoningReplayFields(message);
907
- else {
908
- const record = message;
909
- for (const field of COMPLETIONS_REASONING_REPLAY_FIELDS) {
910
- if (preserveReasoningContent && field === "reasoning_content" && typeof record[field] === "string") continue;
911
- delete record[field];
912
- }
913
- }
914
- }
915
- }
916
- //#endregion
917
- //#region packages/ai/src/transports/openai-completions-params.ts
918
- function isKnownOpenAICompletionsEndpoint(model) {
919
- if (!model.baseUrl.trim() || isNativeOpenAIEndpoint(model)) return true;
920
- const endpointClass = resolveProviderEndpoint(model).endpointClass;
921
- if (endpointClass === "openai-public" || endpointClass === "azure-openai") return true;
922
- const endpoint = URL.parse(model.baseUrl);
923
- return endpoint !== null && isAzureOpenAICompatibleHost(endpoint.hostname.toLowerCase());
924
- }
925
- function resolveOpenAICompletionsMaxTokens(model, options) {
926
- if (options?.maxTokens) return {
927
- maxTokens: options.maxTokens,
928
- clampToModelMaxTokens: true
929
- };
930
- const paramsMaxTokens = resolveMaxTokensParam(model.params);
931
- if (paramsMaxTokens) return {
932
- maxTokens: paramsMaxTokens,
933
- clampToModelMaxTokens: false
934
- };
935
- return {
936
- maxTokens: model.maxTokens,
937
- clampToModelMaxTokens: false
938
- };
939
- }
940
- const OPENAI_COMPLETIONS_INPUT_TOKEN_SAFETY_MARGIN = 1.25;
941
- const OPENAI_COMPLETIONS_IMAGE_CHAR_ESTIMATE = 8e3;
942
- const MIN_USEFUL_OUTPUT_TOKENS = 16;
943
- function estimateJsonChars(value, fallback) {
944
- try {
945
- return estimateStringChars(JSON.stringify(value));
946
- } catch {
947
- return fallback;
948
- }
949
- }
950
- function estimateOpenAICompletionsInputTokens(payload) {
951
- let adjustedChars = estimateOpenAICompletionsMessagesChars(payload.messages);
952
- if (payload.tools?.length) adjustedChars += estimateJsonChars(payload.tools, 1024);
953
- if (payload.response_format !== void 0) adjustedChars += estimateJsonChars(payload.response_format, 256);
954
- return Math.ceil(adjustedChars / 4 * OPENAI_COMPLETIONS_INPUT_TOKEN_SAFETY_MARGIN);
955
- }
956
- function estimateOpenAICompletionsMessagesChars(messages) {
957
- let adjustedChars = 0;
958
- for (const message of messages) {
959
- if (!message || typeof message !== "object") continue;
960
- const record = message;
961
- adjustedChars += estimateOpenAICompletionsContentChars(record.content);
962
- for (const field of COMPLETIONS_REASONING_REPLAY_FIELDS) adjustedChars += estimateOpenAICompletionsContentChars(record[field]);
963
- if (record.tool_calls !== void 0) adjustedChars += estimateJsonChars(record.tool_calls, 256);
964
- }
965
- return adjustedChars;
966
- }
967
- function estimateOpenAICompletionsContentChars(value) {
968
- if (typeof value === "string") return estimateStringChars(value);
969
- if (!Array.isArray(value)) return 0;
970
- let adjustedChars = 0;
971
- for (const block of value) {
972
- if (!block || typeof block !== "object") continue;
973
- const record = block;
974
- if (record.type === "image_url" || record.type === "input_image") {
975
- adjustedChars += OPENAI_COMPLETIONS_IMAGE_CHAR_ESTIMATE;
976
- continue;
977
- }
978
- const text = record.text;
979
- if (typeof text === "string") {
980
- adjustedChars += estimateStringChars(text);
981
- continue;
982
- }
983
- adjustedChars += estimateJsonChars(block, 256);
984
- }
985
- return adjustedChars;
986
- }
987
- function convertTools(tools, compat, model, mode) {
988
- const prepared = mode === "managed" ? prepareOpenAITools(tools) : void 0;
989
- const projection = prepared?.projection ?? projectOpenAITools(tools);
990
- const convert = () => {
991
- const strict = mode === "direct" ? compat.supportsStrictMode ? false : void 0 : resolveOpenAIStrictToolFlagWithDiagnostics(projection, getAiTransportHost().resolveOpenAIStrictToolSetting(model, {
992
- transport: "stream",
993
- supportsStrictMode: compat?.supportsStrictMode
994
- }), {
995
- transport: "completions",
996
- model
997
- });
998
- return {
999
- projection,
1000
- tools: sortPromptCacheToolsByName(projection.tools).map((tool) => {
1001
- const parameters = compat.requiresTypedUnionBranches ? normalizeToolSchema(tool.parameters, "moonshot") : tool.parameters;
1002
- return prepareOpenAIFunctionTool(tool.name, tool.description, mode === "direct" ? parameters : normalizeOpenAIStrictToolParameters(parameters, strict === true, model.compat), strict).completions;
1003
- })
1004
- };
1005
- };
1006
- return prepared ? withPreparedToolSchemaNormalization(prepared.schemas, convert) : convert();
1007
- }
1008
- function buildOpenAICompletionsParams(model, context, options) {
1009
- return buildOpenAICompletionsRequest(model, context, options, { mode: "managed" });
1010
- }
1011
- const contextOutputBudgets = /* @__PURE__ */ new WeakMap();
1012
- function completionsInputHash(payload) {
1013
- return shortHash(JSON.stringify([
1014
- payload.messages,
1015
- payload.tools,
1016
- payload.response_format
1017
- ]));
1018
- }
1019
- function resolveCompletionsContextOutputBudget(request, payload) {
1020
- const budget = contextOutputBudgets.get(request);
1021
- const limits = [payload.max_tokens, payload.max_completion_tokens].filter((value) => value !== void 0);
1022
- if (!budget || payload.model !== budget.model || !Array.isArray(payload.messages) || payload.tools !== void 0 && !Array.isArray(payload.tools) || limits.length === 0 || limits.some((value) => value !== budget.cap) || completionsInputHash(payload) !== budget.inputHash) return;
1023
- return budget.cap;
1024
- }
1025
- function buildOpenAICompletionsRequest(model, context, options, policy) {
1026
- let contextOutputCap;
1027
- const resolvedPolicy = policy.mode === "direct" ? policy : {
1028
- ...policy,
1029
- compat: getCompat(model)
1030
- };
1031
- const compat = resolvedPolicy.compat;
1032
- const managedCompat = resolvedPolicy.mode === "managed" ? resolvedPolicy.compat : void 0;
1033
- const endpointDetection = detectOpenAICompletionsCompat(model);
1034
- const compatDetection = policy.mode === "managed" ? endpointDetection : void 0;
1035
- const { endpointClass } = endpointDetection.capabilities;
1036
- const cacheRetention = policy.mode === "direct" ? policy.cacheRetention : resolveCacheRetention(options?.cacheRetention);
1037
- const cacheControl = resolveCompletionsCacheControl(compat, cacheRetention, endpointClass === "openrouter" || endpointClass === "default" && model.provider === "openrouter");
1038
- const markTools = endpointClass !== "modelstudio-native" && !(endpointClass === "default" && [
1039
- "modelstudio",
1040
- "dashscope",
1041
- "qwen"
1042
- ].includes(model.provider));
1043
- const cacheOptOutIndexes = /* @__PURE__ */ new Set();
1044
- const supportsTools = policy.mode === "direct" || supportsModelTools(model);
1045
- const convertedMessages = convertMessages(model, context, compat, {
1046
- cacheOptOutIndexes,
1047
- supportsTools,
1048
- preserveSystemPromptCacheBoundary: cacheControl !== void 0 && !managedCompat?.requiresStringContent
1049
- });
1050
- let messages = convertedMessages;
1051
- if (managedCompat) {
1052
- applyCompletionsReplay(convertedMessages, context, model, managedCompat);
1053
- if (managedCompat.strictMessageKeys) messages = stripCompletionMessagesToRoleContent(messages);
1054
- if (managedCompat.requiresStringContent) messages = flattenCompletionMessagesToStringContent(messages);
1055
- }
1056
- const promptCacheKey = resolvePromptCacheKey(options, cacheRetention);
1057
- const params = {
1058
- model: model.id,
1059
- messages,
1060
- stream: (options?.streaming ?? model.params?.streaming) !== false,
1061
- ...resolveOpenAIPromptCacheParams(model, cacheRetention, compat)
1062
- };
1063
- if (params.stream && compat.supportsUsageInStreaming) params.stream_options = { include_usage: true };
1064
- if (compat.supportsStore) params.store = false;
1065
- if (policy.mode === "direct" || compat.supportsPromptCacheKey && promptCacheKey) params.prompt_cache_key = compat.supportsPromptCacheKey ? promptCacheKey : void 0;
1066
- if (options?.temperature !== void 0) params.temperature = options.temperature;
1067
- if (policy.mode === "managed" && options?.topP !== void 0) params.top_p = options.topP;
1068
- const requestedResponseFormat = options?.responseFormat;
1069
- const responseFormat = policy.mode === "direct" && requestedResponseFormat === void 0 ? void 0 : resolveOpenAICompletionsResponseFormat(shouldOmitOllamaCompatResponseFormat({
1070
- provider: model.provider,
1071
- baseUrl: model.baseUrl,
1072
- hasTools: () => Boolean(context.tools?.length)
1073
- }) ? void 0 : requestedResponseFormat, compat.supportsJsonSchemaResponseFormat);
1074
- if (responseFormat !== void 0) params.response_format = responseFormat;
1075
- if (policy.mode === "managed" && options?.frequencyPenalty !== void 0) params.frequency_penalty = options.frequencyPenalty;
1076
- if (policy.mode === "managed" && options?.presencePenalty !== void 0) params.presence_penalty = options.presencePenalty;
1077
- if (policy.mode === "managed" && options?.seed !== void 0) params.seed = options.seed;
1078
- if (options?.stop !== void 0 && options.stop.length > 0) params.stop = options.stop;
1079
- let directToolProjection;
1080
- if (supportsTools) {
1081
- if (context.tools) {
1082
- const converted = convertTools(context.tools, compat, model, policy.mode);
1083
- if (policy.mode === "direct") directToolProjection = converted.projection;
1084
- if (converted.tools.length > 0 || policy.mode === "managed" && converted.projection.inputToolCount === 0 && converted.projection.diagnostics.length === 0) params.tools = converted.tools;
1085
- else if (hasToolCallHistory(context.messages)) params.tools = [];
1086
- if (policy.mode === "direct" && params.stream && compat.zaiToolStream && converted.tools.length > 0) params.tool_stream = true;
1087
- if (policy.mode === "managed" && options?.toolChoice) {
1088
- const toolChoice = reconcileOpenAICompletionsToolChoice(options.toolChoice, converted.projection);
1089
- if (toolChoice !== void 0) params.tool_choice = toolChoice;
1090
- } else if (compatDetection?.capabilities.usesExplicitProxyLikeEndpoint && params.tools?.length) params.tool_choice = "auto";
1091
- } else if (hasToolCallHistory(context.messages)) params.tools = [];
1092
- if (compatDetection?.capabilities.usesExplicitProxyLikeEndpoint && params.tools?.length === 0) {
1093
- delete params.tools;
1094
- delete params.tool_choice;
1095
- }
1096
- }
1097
- if (policy.mode === "direct" && compat.cacheControlFormat === "anthropic") applyCompletionsAnthropicCacheControl(params, cacheControl ?? null, cacheOptOutIndexes, markTools);
1098
- if (policy.mode === "direct" && options?.toolChoice) {
1099
- const toolChoice = reconcileOpenAICompletionsToolChoice(options.toolChoice, directToolProjection ?? projectOpenAITools([]));
1100
- if (toolChoice !== void 0) params.tool_choice = toolChoice;
1101
- }
1102
- const isOpenRouter = compat.thinkingFormat === "openrouter";
1103
- const usesBinaryOpenRouterThinking = isOpenRouter && (model.compat?.supportsReasoningEffort === false || model.compat?.supportedReasoningEfforts?.length === 0);
1104
- const simpleReasoning = options?.reasoning;
1105
- const requestedEffort = policy.mode === "direct" ? options?.reasoningEffort : options?.reasoningEffort ?? (simpleReasoning === "none" ? "none" : resolveOpenAISimpleReasoningEffort({
1106
- ...model,
1107
- compat: model.compat ?? void 0
1108
- }, simpleReasoning)) ?? (usesBinaryOpenRouterThinking ? void 0 : "high");
1109
- const thinkingExplicit = options?.openclawThinkingExplicit ?? (options?.reasoningEffort !== void 0 || options?.reasoning !== void 0);
1110
- const reasoning = {
1111
- ...resolveOpenAIRequestReasoning(model, requestedEffort, compat.reasoningEffortForOff),
1112
- thinkingExplicit
1113
- };
1114
- const { effort, thinkingEnabled } = reasoning;
1115
- {
1116
- const maxTokenBudget = policy.mode === "direct" ? {
1117
- maxTokens: options?.maxTokens,
1118
- clampToModelMaxTokens: true
1119
- } : resolveOpenAICompletionsMaxTokens(model, options);
1120
- const effectiveMaxTokens = maxTokenBudget.maxTokens;
1121
- const effectiveContextTokens = asPositiveFiniteNumber(model.contextTokens) ?? asPositiveFiniteNumber(model.contextWindow);
1122
- let clampedMaxTokens = effectiveMaxTokens;
1123
- const modelOutputLimit = asPositiveFiniteNumber(model.maxTokens);
1124
- const modelMaxTokens = modelOutputLimit === void 0 ? void 0 : Math.floor(modelOutputLimit);
1125
- if (maxTokenBudget.clampToModelMaxTokens && clampedMaxTokens !== void 0 && modelMaxTokens !== void 0 && clampedMaxTokens > modelMaxTokens) {
1126
- clampedMaxTokens = modelMaxTokens;
1127
- if (policy.mode === "managed") emitModelTransportDebug(log, `[completions] clamp_max_tokens provider=${model.provider} api=${model.api} model=${model.id} requested=${effectiveMaxTokens} output=${clampedMaxTokens} modelMaxTokens=${modelMaxTokens}`);
1128
- }
1129
- if (compatDetection?.capabilities.usesExplicitProxyLikeEndpoint && clampedMaxTokens !== void 0 && effectiveContextTokens !== void 0) {
1130
- const estimatedInputTokens = estimateOpenAICompletionsInputTokens(params);
1131
- const remainingBudget = Math.max(0, effectiveContextTokens - estimatedInputTokens - 1);
1132
- if (clampedMaxTokens > remainingBudget) {
1133
- if (remainingBudget < (params.tools?.length && params.tool_choice !== "none" ? Math.max(MIN_USEFUL_OUTPUT_TOKENS, Math.min(2048, Math.ceil((modelMaxTokens ?? 0) / 8))) : MIN_USEFUL_OUTPUT_TOKENS)) throw Object.assign(/* @__PURE__ */ new Error(`Context window exceeded: estimated input ${estimatedInputTokens} leaves only ${remainingBudget} output tokens within the ${effectiveContextTokens}-token context.`), { code: "context_length_exceeded" });
1134
- clampedMaxTokens = remainingBudget;
1135
- contextOutputCap = remainingBudget;
1136
- emitModelTransportDebug(log, `[completions] clamp_max_tokens provider=${model.provider} api=${model.api} model=${model.id} requested=${effectiveMaxTokens} output=${clampedMaxTokens} effectiveContext=${effectiveContextTokens} estimatedInput=${estimatedInputTokens}`);
1137
- }
1138
- }
1139
- if (policy.mode === "direct" ? options?.maxTokens : clampedMaxTokens) {
1140
- if (compat.maxTokensField === "max_tokens") params.max_tokens = clampedMaxTokens;
1141
- else params.max_completion_tokens = clampedMaxTokens;
1142
- }
1143
- }
1144
- if (isOpenRouter && model.reasoning) {
1145
- if (usesBinaryOpenRouterThinking && thinkingEnabled !== void 0) params.reasoning = { enabled: thinkingEnabled };
1146
- else if (effort !== void 0) params.reasoning = { effort };
1147
- }
1148
- applyCompletionsReasoningAndRouting(params, model, reasoning, compat, policy.mode);
1149
- if (policy.mode === "managed" && compat.cacheControlFormat === "anthropic") applyCompletionsAnthropicCacheControl(params, cacheControl ?? null, cacheOptOutIndexes, markTools, !managedCompat?.requiresStringContent);
1150
- if (params.tools?.length && isKnownOpenAICompletionsEndpoint(model)) applyOpenAICompletionsToolReasoning(params, model);
1151
- if (contextOutputCap !== void 0) contextOutputBudgets.set(params, {
1152
- model: params.model,
1153
- cap: contextOutputCap,
1154
- inputHash: completionsInputHash(params)
1155
- });
1156
- return params;
1157
- }
1158
- //#endregion
1159
- //#region packages/ai/src/transports/openai-completions-dsml.ts
1160
- const DEEPSEEK_DSML_INVOKE_OPEN_PREFIXES = DEEPSEEK_DSML_MARKERS.map((marker) => `<${marker}invoke`);
1161
- const DEEPSEEK_DSML_INVOKE_OPEN_TAG = new RegExp(`^<${DEEPSEEK_DSML_MARKER_PATTERN}invoke\\b[^<>]*>$`);
1162
- const DEEPSEEK_DSML_TOOL_MAX_OPEN_TOKEN_LEN = Math.max(...DEEPSEEK_DSML_TOOL_OPEN_TOKENS.map((token) => token.length));
1163
- const DEEPSEEK_DSML_RECOVERY_MAX_BOUNDARY_LEN = Math.max(...DEEPSEEK_DSML_TOOL_OPEN_TOKENS.map((token) => token.length + 1), ...DEEPSEEK_DSML_INVOKE_OPEN_PREFIXES.map((token) => token.length + 2));
1164
- const MAX_DSML_RECOVERY_BUFFER_BYTES = 256e3;
1165
- const DEEPSEEK_DSML_SCAN_BATCH_CHARS = 65536;
1166
- const DSML_NAME_ATTRIBUTE_RE = /\bname=("([^"]*)"|'([^']*)'|([^\s>]+))/;
1167
- function createDsmlRecoverer() {
1168
- let buffer = "";
1169
- let bufferBytes = 0;
1170
- let bufferEndsWithHighSurrogate = false;
1171
- let pendingScanChars = 0;
1172
- let activeOpenToken = null;
1173
- let blockScanState = { offset: 0 };
1174
- const resetBlockScan = () => {
1175
- activeOpenToken = null;
1176
- pendingScanChars = 0;
1177
- blockScanState = { offset: 0 };
1178
- };
1179
- const consume = (final) => {
1180
- const output = [];
1181
- while (buffer) {
1182
- const open = activeOpenToken ? {
1183
- index: 0,
1184
- token: activeOpenToken
1185
- } : findEarliestDsmlToken(buffer, DEEPSEEK_DSML_TOOL_OPEN_TOKENS);
1186
- if (!open) {
1187
- resetBlockScan();
1188
- if (final) {
1189
- output.push({
1190
- kind: "text",
1191
- text: buffer
1192
- });
1193
- buffer = "";
1194
- bufferBytes = 0;
1195
- bufferEndsWithHighSurrogate = false;
1196
- return output;
1197
- }
1198
- const keep = longestDsmlTokenPrefixSuffixLength(buffer, DEEPSEEK_DSML_TOOL_OPEN_TOKENS, DEEPSEEK_DSML_TOOL_MAX_OPEN_TOKEN_LEN);
1199
- const emitLength = buffer.length - keep;
1200
- if (emitLength > 0) {
1201
- const emitted = buffer.slice(0, emitLength);
1202
- output.push({
1203
- kind: "text",
1204
- text: emitted
1205
- });
1206
- bufferBytes -= Buffer.byteLength(emitted, "utf8");
1207
- buffer = buffer.slice(emitted.length);
1208
- if (!buffer) bufferEndsWithHighSurrogate = false;
1209
- }
1210
- return output;
1211
- }
1212
- if (open.index > 0) {
1213
- const prefix = buffer.slice(0, open.index);
1214
- output.push({
1215
- kind: "text",
1216
- text: prefix
1217
- });
1218
- bufferBytes -= Buffer.byteLength(prefix, "utf8");
1219
- buffer = buffer.slice(prefix.length);
1220
- resetBlockScan();
1221
- }
1222
- activeOpenToken = open.token;
1223
- if (blockScanState.offset === 0) blockScanState.offset = open.token.length;
1224
- const blockScan = scanDeepSeekDsmlToolBlock(buffer, open.token.replace("<", "</"), open.token.length, blockScanState);
1225
- if (blockScan.kind === "nested-open") throw new Error("Nested DeepSeek DSML recovery wrappers are not supported");
1226
- const close = blockScan.kind === "close" ? blockScan : null;
1227
- if (!close) {
1228
- if (final) {
1229
- output.push({
1230
- kind: "text",
1231
- text: buffer
1232
- });
1233
- buffer = "";
1234
- bufferBytes = 0;
1235
- bufferEndsWithHighSurrogate = false;
1236
- return output;
1237
- }
1238
- if (bufferBytes > MAX_DSML_RECOVERY_BUFFER_BYTES) throw new Error("Exceeded DeepSeek DSML recovery buffer limit");
1239
- return output;
1240
- }
1241
- resetBlockScan();
1242
- const body = buffer.slice(open.token.length, close.index);
1243
- const blockText = buffer.slice(0, close.index + close.token.length);
1244
- if (Buffer.byteLength(blockText, "utf8") > MAX_DSML_RECOVERY_BUFFER_BYTES) throw new Error("Exceeded DeepSeek DSML recovery buffer limit");
1245
- const recoveredToolCalls = parseDeepSeekDsmlToolCallBlock(body);
1246
- if (recoveredToolCalls.length > 0) output.push(...recoveredToolCalls);
1247
- else output.push({
1248
- kind: "text",
1249
- text: blockText
1250
- });
1251
- bufferBytes -= Buffer.byteLength(blockText, "utf8");
1252
- buffer = buffer.slice(blockText.length);
1253
- if (!buffer) bufferEndsWithHighSurrogate = false;
1254
- }
1255
- return output;
1256
- };
1257
- return {
1258
- push(chunk) {
1259
- const append = measureUtf8AppendBytes(bufferEndsWithHighSurrogate, chunk);
1260
- bufferBytes += append.bytes;
1261
- bufferEndsWithHighSurrogate = append.endsWithHighSurrogate;
1262
- buffer += chunk;
1263
- pendingScanChars += chunk.length;
1264
- if (activeOpenToken && pendingScanChars < DEEPSEEK_DSML_SCAN_BATCH_CHARS && !chunk.includes("<") && !chunk.includes(">") && bufferBytes <= MAX_DSML_RECOVERY_BUFFER_BYTES) return [];
1265
- pendingScanChars = 0;
1266
- return consume(false);
1267
- },
1268
- flush() {
1269
- return consume(true);
1270
- }
1271
- };
1272
- }
1273
- function parseDeepSeekDsmlToolCallBlock(body) {
1274
- const toolCalls = [];
1275
- const invokeOpenRegex = new RegExp(`<${DEEPSEEK_DSML_MARKER_PATTERN}invoke\\b([^<>]*)>`, "g");
1276
- let openMatch;
1277
- while ((openMatch = invokeOpenRegex.exec(body)) !== null) {
1278
- const invokeBodyStart = openMatch.index + openMatch[0].length;
1279
- const invokeCloseToken = `</${openMatch[1]}invoke>`;
1280
- const invokeCloseIndex = body.indexOf(invokeCloseToken, invokeBodyStart);
1281
- if (invokeCloseIndex === -1) break;
1282
- const invokeBody = body.slice(invokeBodyStart, invokeCloseIndex);
1283
- invokeOpenRegex.lastIndex = invokeCloseIndex + invokeCloseToken.length;
1284
- const invokeName = parseDsmlNameAttribute(openMatch[2] ?? "");
1285
- if (!invokeName) continue;
1286
- const parsedArguments = parseDeepSeekDsmlInvokeArguments(invokeBody);
1287
- if (!parsedArguments) continue;
1288
- toolCalls.push({
1289
- kind: "toolCall",
1290
- name: invokeName,
1291
- arguments: parsedArguments,
1292
- partialJson: JSON.stringify(parsedArguments)
1293
- });
1294
- }
1295
- return toolCalls;
1296
- }
1297
- function parseDeepSeekDsmlInvokeArguments(body) {
1298
- const args = {};
1299
- const parameterRegex = new RegExp(`<${DEEPSEEK_DSML_MARKER_PATTERN}parameter\\b([^>]*)>([\\s\\S]*?)</\\1parameter>`, "g");
1300
- let parameterMatch;
1301
- while ((parameterMatch = parameterRegex.exec(body)) !== null) {
1302
- const name = parseDsmlNameAttribute(parameterMatch[2] ?? "");
1303
- if (!name) continue;
1304
- const rawValue = parameterMatch[3] ?? "";
1305
- if (rawValue.length === 0) {
1306
- const stringAttribute = Array.from((parameterMatch[2] ?? "").matchAll(/(?:^|\s)([^\s=]+)=(?:"([^"]*)"|'([^']*)'|([^\s"']+))(?=\s|$)/g)).find((attribute) => attribute[1] === "string");
1307
- if ((stringAttribute?.[2] ?? stringAttribute?.[3] ?? stringAttribute?.[4]) !== "true") continue;
1308
- }
1309
- Object.defineProperty(args, name, {
1310
- value: decodeDeepSeekDsmlText(rawValue),
1311
- enumerable: true,
1312
- configurable: true,
1313
- writable: true
1314
- });
1315
- }
1316
- if (Object.keys(args).length > 0) return args;
1317
- const trimmed = body.trim();
1318
- if (!trimmed.startsWith("{")) return null;
1319
- try {
1320
- const parsed = JSON.parse(trimmed);
1321
- if (isRecord(parsed) && Object.keys(parsed).length > 0) return parsed;
1322
- } catch {
1323
- return null;
1324
- }
1325
- return null;
1326
- }
1327
- function parseDsmlNameAttribute(attributes) {
1328
- const match = DSML_NAME_ATTRIBUTE_RE.exec(attributes);
1329
- const value = match?.[2] ?? match?.[3] ?? match?.[4];
1330
- return value ? decodeDeepSeekDsmlText(value) : null;
1331
- }
1332
- function decodeDeepSeekDsmlText(value) {
1333
- return value.replaceAll("&quot;", "\"").replaceAll("&apos;", "'").replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&amp;", "&");
1334
- }
1335
- function scanDeepSeekDsmlToolBlock(text, closeToken, contentStartIndex, state) {
1336
- while (state.offset < text.length) {
1337
- if (state.invoke?.kind === "open") {
1338
- const nextOpen = text.indexOf("<", state.offset);
1339
- const nextClose = text.indexOf(">", state.offset);
1340
- if (nextClose === -1 && nextOpen === -1) {
1341
- state.offset = text.length;
1342
- return { kind: "incomplete" };
1343
- }
1344
- if (nextOpen !== -1 && (nextClose === -1 || nextOpen < nextClose)) {
1345
- state.invoke = void 0;
1346
- state.offset = nextOpen;
1347
- continue;
1348
- }
1349
- const invokeOpenTag = text.slice(state.invoke.start, nextClose + 1);
1350
- const open = DEEPSEEK_DSML_INVOKE_OPEN_TAG.exec(invokeOpenTag);
1351
- if (!open) {
1352
- state.offset = state.invoke.start + 1;
1353
- state.invoke = void 0;
1354
- continue;
1355
- }
1356
- state.invoke = {
1357
- kind: "body",
1358
- closeToken: `</${open[1]}invoke>`
1359
- };
1360
- state.offset = nextClose + 1;
1361
- continue;
1362
- }
1363
- if (state.invoke?.kind === "body") {
1364
- const invokeCloseIndex = text.indexOf(state.invoke.closeToken, state.offset);
1365
- if (invokeCloseIndex === -1) {
1366
- state.offset = Math.max(0, text.length - DEEPSEEK_DSML_RECOVERY_MAX_BOUNDARY_LEN + 1);
1367
- return { kind: "incomplete" };
1368
- }
1369
- state.offset = invokeCloseIndex + state.invoke.closeToken.length;
1370
- state.invoke = void 0;
1371
- continue;
1372
- }
1373
- const toolOpen = findEarliestDsmlToken(text, DEEPSEEK_DSML_TOOL_OPEN_TOKENS, state.offset);
1374
- const toolCloseIndex = text.indexOf(closeToken, state.offset);
1375
- const invokeOpen = findEarliestDsmlToken(text, DEEPSEEK_DSML_INVOKE_OPEN_PREFIXES, state.offset);
1376
- const next = [
1377
- toolOpen ? {
1378
- kind: "nested-open",
1379
- ...toolOpen
1380
- } : null,
1381
- toolCloseIndex === -1 ? null : {
1382
- kind: "close",
1383
- index: toolCloseIndex,
1384
- token: closeToken
1385
- },
1386
- invokeOpen ? {
1387
- kind: "invoke-open",
1388
- ...invokeOpen
1389
- } : null
1390
- ].filter((candidate) => candidate !== null).toSorted((left, right) => left.index - right.index)[0];
1391
- if (!next) {
1392
- state.offset = Math.max(contentStartIndex, text.length - DEEPSEEK_DSML_RECOVERY_MAX_BOUNDARY_LEN + 1);
1393
- return { kind: "incomplete" };
1394
- }
1395
- if (next.kind === "invoke-open") {
1396
- state.invoke = {
1397
- kind: "open",
1398
- start: next.index
1399
- };
1400
- state.offset = next.index + next.token.length;
1401
- continue;
1402
- }
1403
- return next;
1404
- }
1405
- return { kind: "incomplete" };
1406
- }
1407
- //#endregion
1408
- //#region packages/ai/src/transports/openai-completions-gemma.ts
1409
- const OPEN = "<|tool_call>";
1410
- const CLOSE = "<tool_call|>";
1411
- const QUOTE = "<|\"|>";
1412
- const MAX_RECOVERY_BYTES = 256e3;
1413
- function recoverGemmaCalls(text) {
1414
- const parts = [];
1415
- const opener = /\s*<\|tool_call>\s*call:([\w.-]+)\s*/y;
1416
- const token = /\s*(<\|"\|>[\s\S]*?<\|"\|>|[\w.+-]+|[{}[\],:])\s*/y;
1417
- let offset = 0;
1418
- while (offset < text.length) {
1419
- if (!text.slice(offset).trim()) {
1420
- parts.push({
1421
- kind: "text",
1422
- text: text.slice(offset)
1423
- });
1424
- break;
1425
- }
1426
- opener.lastIndex = offset;
1427
- const head = opener.exec(text);
1428
- const name = head?.[1];
1429
- if (!head || !name) return;
1430
- const leading = /^\s*/.exec(head[0])?.[0] ?? "";
1431
- if (leading) parts.push({
1432
- kind: "text",
1433
- text: leading
1434
- });
1435
- token.lastIndex = opener.lastIndex;
1436
- let depth = 0;
1437
- const json = [];
1438
- do {
1439
- const value = token.exec(text)?.[1];
1440
- if (!value || json.length === 0 && value !== "{") return;
1441
- if (value === "{") depth += 1;
1442
- else if (value === "}") depth -= 1;
1443
- json.push(value.startsWith(QUOTE) ? JSON.stringify(value.slice(5, -5)) : text[token.lastIndex] === ":" && /^[A-Za-z_][\w.-]*$/.test(value) ? JSON.stringify(value) : value);
1444
- } while (depth > 0);
1445
- if (!text.startsWith(CLOSE, token.lastIndex)) return;
1446
- try {
1447
- const argumentsValue = JSON.parse(json.join(" "));
1448
- if (!isRecord(argumentsValue)) return;
1449
- parts.push({
1450
- kind: "toolCall",
1451
- name,
1452
- arguments: argumentsValue,
1453
- partialJson: JSON.stringify(argumentsValue)
1454
- });
1455
- } catch {
1456
- return;
1457
- }
1458
- offset = token.lastIndex + 12;
1459
- }
1460
- return parts;
1461
- }
1462
- /** Buffer only a possible standalone call batch; prose and examples stay text. */
1463
- function createGemmaToolCallRecoverer() {
1464
- let buffer = "";
1465
- let bytes = 0;
1466
- let highSurrogate = false;
1467
- let passthrough = false;
1468
- return {
1469
- push(text) {
1470
- if (passthrough) return [{
1471
- kind: "text",
1472
- text
1473
- }];
1474
- const append = measureUtf8AppendBytes(highSurrogate, text);
1475
- bytes += append.bytes;
1476
- highSurrogate = append.endsWithHighSurrogate;
1477
- buffer += text;
1478
- const candidate = buffer.trimStart();
1479
- if (OPEN.startsWith(candidate) || candidate.startsWith(OPEN)) {
1480
- if (bytes > MAX_RECOVERY_BYTES) throw new Error("Exceeded Gemma tool-call recovery buffer limit");
1481
- return [];
1482
- }
1483
- passthrough = true;
1484
- const result = [{
1485
- kind: "text",
1486
- text: buffer
1487
- }];
1488
- buffer = "";
1489
- return result;
1490
- },
1491
- flush(allowRecovery = true) {
1492
- const text = buffer;
1493
- buffer = "";
1494
- passthrough ||= !allowRecovery;
1495
- const recovered = allowRecovery ? recoverGemmaCalls(text) : void 0;
1496
- return text ? recovered ?? [{
1497
- kind: "text",
1498
- text
1499
- }] : [];
1500
- }
1501
- };
1502
- }
1503
- //#endregion
1504
- //#region packages/ai/src/transports/openai-completions-stream.ts
1505
- function extractToolCallThoughtSignature(toolCall) {
1506
- const tc = toolCall;
1507
- if (!tc) return;
1508
- const extra = tc.extra_content?.google;
1509
- return readNonEmptyStringPreservingWhitespace(extra?.thought_signature) ?? readNonEmptyStringPreservingWhitespace(tc.function?.thought_signature) ?? readNonEmptyStringPreservingWhitespace(tc.thought_signature);
1510
- }
1511
- async function* observeOpenAICompletionsProgress(responseStream, signal) {
1512
- const maxUsageTokens = {
1513
- prompt: 0,
1514
- completion: 0,
1515
- total: 0,
1516
- reasoning: 0
1517
- };
1518
- for await (const rawChunk of responseStream) {
1519
- throwIfModelStreamAborted(signal);
1520
- if (rawChunk && typeof rawChunk === "object") {
1521
- const chunk = rawChunk;
1522
- const choice = Array.isArray(chunk.choices) ? chunk.choices[0] : void 0;
1523
- const usage = chunk.usage || choice?.usage;
1524
- let hasUsageProgress = false;
1525
- for (const [counter, reported] of [
1526
- ["prompt", usage?.prompt_tokens],
1527
- ["completion", usage?.completion_tokens],
1528
- ["total", usage?.total_tokens],
1529
- ["reasoning", usage?.completion_tokens_details?.reasoning_tokens]
1530
- ]) {
1531
- const tokens = asPositiveFiniteNumber(reported) ?? 0;
1532
- if (tokens > maxUsageTokens[counter]) {
1533
- maxUsageTokens[counter] = tokens;
1534
- hasUsageProgress = true;
1535
- }
1536
- }
1537
- const rawChoiceDelta = choice?.delta ?? choice?.message;
1538
- notifyLlmRequestActivity(signal, Boolean(hasUsageProgress || choice?.finish_reason || rawChoiceDelta && (rawChoiceDelta.tool_calls?.length || hasOpenAICompletionsDeltaContent(rawChoiceDelta))));
1539
- }
1540
- yield rawChunk;
1541
- }
1542
- }
1543
- async function processCompletionsStream(responseStream, output, model, stream, options) {
1544
- const MAX_POST_TOOL_CALL_BUFFER_BYTES = 256e3;
1545
- const directMode = options?.mode === "direct";
1546
- const emitReasoning = options?.emitReasoning ?? true;
1547
- const openAIModel = model;
1548
- const compat = getCompat(openAIModel);
1549
- const visibleReasoningDetailTypes = new Set(compat.visibleReasoningDetailTypes);
1550
- const deepSeekTextFilter = compat.emitsDsmlToolCalls ? createDeepSeekTextFilter() : null;
1551
- const deepSeekToolCallRecoverer = !directMode && compat.emitsDsmlToolCalls ? createDsmlRecoverer() : null;
1552
- const gemmaToolCallRecoverer = !directMode && /gemma-?4/i.test(model.id) ? createGemmaToolCallRecoverer() : null;
1553
- const reasoningTagTextPartitioner = createReasoningTagTextPartitioner();
1554
- if (options?.strictReasoningTags) reasoningTagTextPartitioner.markStrict();
1555
- let currentBlock = null;
1556
- const directContent = { block: null };
1557
- let currentTextSource;
1558
- let sawReasoning = false;
1559
- let pendingPostToolCallDeltas = [];
1560
- let pendingPostToolCallBytes = 0;
1561
- const toolCallBlocksByIndex = /* @__PURE__ */ new Map();
1562
- const toolCallBlocksById = /* @__PURE__ */ new Map();
1563
- const encryptedReasoning = createOpenAIEncryptedToolCallReasoningTracker();
1564
- const toolArgumentPreviewSchedules = /* @__PURE__ */ new WeakMap();
1565
- const blockIndices = /* @__PURE__ */ new WeakMap();
1566
- const normalizeToolCallDeltas = createOpenAICompletionsToolCallDeltaNormalizer();
1567
- let finishReason;
1568
- let sawNativeToolCallDelta = false;
1569
- const blockIndex = () => directMode && currentBlock && currentBlock.type !== "toolCall" ? blockIndices.get(currentBlock) ?? output.content.length - 1 : output.content.length - 1;
1570
- let chunkPushedEvent = false;
1571
- const pushStreamEvent = (event) => {
1572
- chunkPushedEvent = true;
1573
- stream.push(detachPartialSnapshot(event));
1574
- };
1575
- const appendToolCallBlock = (block) => {
1576
- output.content.push(block);
1577
- blockIndices.set(block, output.content.length - 1);
1578
- pushStreamEvent({
1579
- type: "toolcall_start",
1580
- contentIndex: blockIndices.get(block) ?? -1,
1581
- partial: output
1582
- });
1583
- };
1584
- const queuePostToolCallDelta = (next) => {
1585
- const nextBytes = Buffer.byteLength(next.text, "utf8");
1586
- if (pendingPostToolCallBytes + nextBytes > MAX_POST_TOOL_CALL_BUFFER_BYTES) throw new Error("Exceeded post-tool-call delta buffer limit");
1587
- pendingPostToolCallBytes += nextBytes;
1588
- const previous = pendingPostToolCallDeltas[pendingPostToolCallDeltas.length - 1];
1589
- if (!previous || previous.kind !== next.kind || previous.kind === "text" && next.kind === "text" && previous.source !== next.source || previous.kind === "thinking" && next.kind === "thinking" && previous.signature !== next.signature) {
1590
- pendingPostToolCallDeltas.push(next);
1591
- return;
1592
- }
1593
- previous.text += next.text;
1594
- };
1595
- const appendContentDelta = (delta) => {
1596
- flushPendingPostToolCallDeltas();
1597
- if (directMode && directContent.block?.type === delta.kind) currentBlock = directContent.block;
1598
- if (delta.kind === "text" && currentBlock?.type === "text" && currentTextSource !== delta.source) currentBlock = null;
1599
- if (!currentBlock || currentBlock.type !== delta.kind) {
1600
- options?.beforeContentBlock?.(delta.kind);
1601
- if (delta.kind === "text") {
1602
- currentBlock = {
1603
- type: "text",
1604
- text: ""
1605
- };
1606
- currentTextSource = delta.source;
1607
- } else currentBlock = {
1608
- type: "thinking",
1609
- thinking: "",
1610
- ...delta.signature ? { thinkingSignature: delta.signature } : {}
1611
- };
1612
- if (directMode) directContent.block = currentBlock;
1613
- output.content.push(currentBlock);
1614
- blockIndices.set(currentBlock, output.content.length - 1);
1615
- pushStreamEvent({
1616
- type: `${delta.kind}_start`,
1617
- contentIndex: blockIndex(),
1618
- partial: output
1619
- });
1620
- }
1621
- if (currentBlock.type === "thinking") appendAssistantThinking(currentBlock, delta.text);
1622
- else currentBlock.text += delta.text;
1623
- const event = {
1624
- contentIndex: blockIndex(),
1625
- delta: delta.text
1626
- };
1627
- if (delta.kind === "thinking") pushStreamEvent({
1628
- type: "thinking_delta",
1629
- ...event,
1630
- partial: output
1631
- });
1632
- else pushStreamEvent({
1633
- type: "text_delta",
1634
- ...event,
1635
- ...directMode ? { partial: output } : {}
1636
- });
1637
- };
1638
- const flushPendingPostToolCallDeltas = () => {
1639
- if (currentBlock?.type === "toolCall" || pendingPostToolCallDeltas.length === 0) return;
1640
- const bufferedDeltas = pendingPostToolCallDeltas;
1641
- pendingPostToolCallDeltas = [];
1642
- pendingPostToolCallBytes = 0;
1643
- for (const delta of bufferedDeltas) if (delta.kind === "text" || emitReasoning) appendContentDelta(delta);
1644
- };
1645
- const appendVisibleTextDelta = (text) => {
1646
- if (!text) return;
1647
- if (currentBlock?.type === "toolCall" && !directMode) queuePostToolCallDelta({
1648
- kind: "text",
1649
- text
1650
- });
1651
- else appendContentDelta({
1652
- kind: "text",
1653
- text
1654
- });
1655
- };
1656
- const appendReasoningDeltas = (reasoningDeltas) => {
1657
- for (const delta of reasoningDeltas) {
1658
- if (delta.kind === "thinking" && !emitReasoning) continue;
1659
- if (currentBlock?.type === "toolCall" && !directMode) {
1660
- queuePostToolCallDelta({ ...delta });
1661
- continue;
1662
- }
1663
- appendContentDelta(delta.kind === "thinking" && directMode && model.provider === "opencode-go" && delta.signature === "reasoning" ? {
1664
- ...delta,
1665
- signature: "reasoning_content"
1666
- } : delta);
1667
- }
1668
- };
1669
- const recoveredToolCallBlocks = /* @__PURE__ */ new Set();
1670
- const appendRecoveredToolCall = (toolCall) => {
1671
- if (currentBlock?.type === "toolCall") {
1672
- currentBlock = null;
1673
- flushPendingPostToolCallDeltas();
1674
- }
1675
- const block = {
1676
- type: "toolCall",
1677
- id: `call_${randomUUID().replaceAll("-", "").slice(0, 24)}`,
1678
- name: toolCall.name,
1679
- arguments: toolCall.arguments,
1680
- partialJson: toolCall.partialJson
1681
- };
1682
- recoveredToolCallBlocks.add(block);
1683
- currentBlock = block;
1684
- appendToolCallBlock(block);
1685
- pushStreamEvent({
1686
- type: "toolcall_delta",
1687
- contentIndex: blockIndices.get(block) ?? -1,
1688
- delta: toolCall.partialJson,
1689
- partial: output
1690
- });
1691
- };
1692
- const appendRecoveredParts = (recoveredParts) => {
1693
- for (const recoveredPart of recoveredParts) {
1694
- if (recoveredPart.kind === "toolCall") {
1695
- appendRecoveredToolCall(recoveredPart);
1696
- continue;
1697
- }
1698
- const parts = deepSeekTextFilter?.push(recoveredPart.text) ?? [recoveredPart.text];
1699
- for (const part of parts) appendVisibleTextDelta(part);
1700
- }
1701
- };
1702
- const appendPartitionedVisibleDelta = (delta) => {
1703
- if (delta.kind === "text") appendRecoveredParts(deepSeekToolCallRecoverer?.push(delta.text) ?? [{
1704
- kind: "text",
1705
- text: delta.text
1706
- }]);
1707
- };
1708
- const emitReasoningUsageActivity = (hasReasoningUsageActivity) => {
1709
- if (directMode || !hasReasoningUsageActivity || chunkPushedEvent || !emitReasoning) return;
1710
- const latestBlock = output.content[output.content.length - 1];
1711
- if (currentBlock?.type === "text" || currentBlock?.type === "toolCall") return;
1712
- if (latestBlock?.type === "text" || latestBlock?.type === "toolCall") return;
1713
- appendContentDelta({
1714
- kind: "thinking",
1715
- text: ""
1716
- });
1717
- };
1718
- const flushReasoningTagTextPartitioner = (allowRecovery = true) => {
1719
- const recoverUnclosed = allowRecovery && !sawReasoning && output.stopReason !== "length" && output.stopReason !== "error" && output.stopReason !== "aborted";
1720
- for (const delta of reasoningTagTextPartitioner.flush({ recoverUnclosed })) appendPartitionedVisibleDelta(delta);
1721
- };
1722
- const flushGemmaToolCallRecoverer = (allowRecovery = true) => {
1723
- for (const part of gemmaToolCallRecoverer?.flush(allowRecovery) ?? []) if (part.kind === "toolCall") appendRecoveredToolCall(part);
1724
- else for (const delta of reasoningTagTextPartitioner.pushVisible(part.text)) appendPartitionedVisibleDelta(delta);
1725
- };
1726
- const sealTextBeforeReasoning = () => {
1727
- if (currentBlock?.type !== "text" && !reasoningTagTextPartitioner.hasPending()) return;
1728
- flushReasoningTagTextPartitioner();
1729
- if (currentBlock?.type !== "text") return;
1730
- currentBlock = null;
1731
- if (directMode) directContent.block = null;
1732
- currentTextSource = void 0;
1733
- };
1734
- const beginReasoning = (hasFollowingVisibleText) => {
1735
- sawReasoning = true;
1736
- if (!hasFollowingVisibleText || !reasoningTagTextPartitioner.hasPendingSyntax()) sealTextBeforeReasoning();
1737
- };
1738
- const events = directMode ? responseStream : iterateModelStream(responseStream, options?.signal);
1739
- let maxReasoningTokens = 0;
1740
- let providerProcessingMs;
1741
- for await (const rawChunk of events) {
1742
- throwIfModelStreamAborted(options?.signal);
1743
- chunkPushedEvent = false;
1744
- if (!rawChunk || typeof rawChunk !== "object") continue;
1745
- const chunk = rawChunk;
1746
- output.responseId ||= chunk.id;
1747
- if (typeof chunk.model === "string" && chunk.model.length > 0 && chunk.model !== model.id) output.responseModel ||= chunk.model;
1748
- const choice = Array.isArray(chunk.choices) ? chunk.choices[0] : void 0;
1749
- const usage = chunk.usage || choice?.usage;
1750
- if (chunk.timings !== void 0 && (choice?.finish_reason || Array.isArray(chunk.choices) && chunk.choices.length === 0 && chunk.usage)) {
1751
- const promptMs = asNonNegativeFiniteNumber(chunk.timings?.prompt_ms);
1752
- const predictedMs = asNonNegativeFiniteNumber(chunk.timings?.predicted_ms);
1753
- providerProcessingMs = promptMs !== void 0 && predictedMs !== void 0 ? asNonNegativeFiniteNumber(promptMs + predictedMs) : void 0;
1754
- }
1755
- const reasoningTokens = asPositiveFiniteNumber(usage?.completion_tokens_details?.reasoning_tokens) ?? 0;
1756
- const hasReasoningUsageActivity = reasoningTokens > maxReasoningTokens;
1757
- maxReasoningTokens = Math.max(maxReasoningTokens, reasoningTokens);
1758
- if (usage) {
1759
- output.usage = parseOpenAICompletionsUsage(usage, model, { includeReasoningTokens: !directMode });
1760
- const terminalUsage = Boolean(finishReason || choice?.finish_reason || chunk.choices?.length === 0);
1761
- const completeCounts = [usage.prompt_tokens, usage.completion_tokens].every((value) => typeof value === "number" && Number.isFinite(value) && value >= 0);
1762
- output.usage.usageReport = { state: terminalUsage && completeCounts ? "available" : "unavailable" };
1763
- }
1764
- const rawChoiceDelta = choice?.delta ?? choice?.message;
1765
- if (!choice) {
1766
- emitReasoningUsageActivity(hasReasoningUsageActivity);
1767
- continue;
1768
- }
1769
- if (choice.finish_reason) {
1770
- const finishReasonResult = mapOpenAIStopReason(choice.finish_reason, { allowSingularToolCall: true });
1771
- output.stopReason = finishReasonResult.stopReason;
1772
- finishReason = finishReasonResult.stopReason;
1773
- if (finishReasonResult.errorMessage) output.errorMessage = finishReasonResult.errorMessage;
1774
- }
1775
- if (!rawChoiceDelta) {
1776
- emitReasoningUsageActivity(hasReasoningUsageActivity);
1777
- continue;
1778
- }
1779
- for (const normalizedDelta of normalizeToolCallDeltas(rawChoiceDelta, choice.finish_reason)) {
1780
- const choiceDelta = normalizedDelta.delta;
1781
- const deltaFields = choiceDelta;
1782
- const reasoningBatch = readOpenAICompletionsReasoningBatch(deltaFields, visibleReasoningDetailTypes);
1783
- const reasoningDeltas = reasoningBatch.deltas;
1784
- const hasReasoningThinking = reasoningBatch.hasThinking;
1785
- const contentDeltas = readOpenAICompletionsContentDeltas(choiceDelta.content, choiceDelta.refusal, reasoningBatch.mirroredThinking);
1786
- const lastVisibleTextIndex = contentDeltas.findLastIndex((delta) => delta.kind === "text");
1787
- const hasSameChunkVisibleText = reasoningBatch.hasVisibleText || lastVisibleTextIndex !== -1;
1788
- if (hasReasoningThinking) {
1789
- beginReasoning(hasSameChunkVisibleText);
1790
- appendReasoningDeltas(reasoningDeltas);
1791
- }
1792
- for (const [contentDeltaIndex, contentDelta] of contentDeltas.entries()) if (contentDelta.kind === "text") {
1793
- const parts = gemmaToolCallRecoverer?.push(contentDelta.text) ?? [contentDelta];
1794
- for (const part of parts) for (const routedDelta of reasoningTagTextPartitioner.pushVisible(part.text)) appendPartitionedVisibleDelta(routedDelta);
1795
- } else {
1796
- beginReasoning(contentDeltaIndex < lastVisibleTextIndex);
1797
- if (emitReasoning) {
1798
- if (currentBlock?.type === "toolCall" && !directMode) queuePostToolCallDelta(contentDelta);
1799
- else appendContentDelta(contentDelta);
1800
- }
1801
- }
1802
- if (!hasReasoningThinking) appendReasoningDeltas(reasoningDeltas);
1803
- const toolCallDeltas = normalizedDelta.toolCalls;
1804
- if (toolCallDeltas.length > 0) {
1805
- flushGemmaToolCallRecoverer(false);
1806
- sawNativeToolCallDelta = true;
1807
- flushReasoningTagTextPartitioner(false);
1808
- for (const toolCall of toolCallDeltas) {
1809
- const streamIndex = typeof toolCall.index === "number" ? toolCall.index : void 0;
1810
- let block = streamIndex !== void 0 ? toolCallBlocksByIndex.get(streamIndex) : void 0;
1811
- if (!block && toolCall.id) block = toolCallBlocksById.get(toolCall.id);
1812
- if (!block) {
1813
- if (currentBlock?.type === "toolCall") {
1814
- currentBlock = null;
1815
- flushPendingPostToolCallDeltas();
1816
- }
1817
- const initialSig = directMode ? void 0 : extractToolCallThoughtSignature(toolCall);
1818
- options?.beforeContentBlock?.("toolCall");
1819
- if (directMode && directContent.block?.type === "thinking") directContent.block = null;
1820
- block = {
1821
- type: "toolCall",
1822
- id: toolCall.id || "",
1823
- name: toolCall.function?.name || "",
1824
- arguments: {},
1825
- partialJson: "",
1826
- ...initialSig ? { thoughtSignature: initialSig } : {}
1827
- };
1828
- encryptedReasoning.rememberToolCall(block.id, block);
1829
- toolArgumentPreviewSchedules.set(block, createToolArgumentPreviewSchedule());
1830
- appendToolCallBlock(block);
1831
- }
1832
- if (streamIndex !== void 0 && !toolCallBlocksByIndex.has(streamIndex)) toolCallBlocksByIndex.set(streamIndex, block);
1833
- if (toolCall.id) {
1834
- const previousId = block.id;
1835
- if (!directMode || !block.id) block.id = toolCall.id;
1836
- toolCallBlocksById.set(toolCall.id, block);
1837
- if (block.id === toolCall.id) encryptedReasoning.rememberToolCall(toolCall.id, block, previousId);
1838
- }
1839
- currentBlock = block;
1840
- const conflictingId = directMode && block.id && toolCall.id && block.id !== toolCall.id;
1841
- if (toolCall.function?.name && !conflictingId) block.name = toolCall.function.name;
1842
- const deltaSig = directMode ? void 0 : extractToolCallThoughtSignature(toolCall);
1843
- if (deltaSig) block.thoughtSignature = deltaSig;
1844
- const toolArgumentsDelta = toolCall.function?.arguments;
1845
- if (toolArgumentsDelta) {
1846
- block.partialJson += toolArgumentsDelta;
1847
- if (toolArgumentPreviewSchedules.get(block)?.(block.partialJson.length)) block.arguments = parseStreamingJson(block.partialJson);
1848
- }
1849
- if (toolArgumentsDelta || directMode) pushStreamEvent({
1850
- type: "toolcall_delta",
1851
- contentIndex: blockIndices.get(block) ?? -1,
1852
- delta: toolArgumentsDelta ?? "",
1853
- partial: output
1854
- });
1855
- }
1856
- }
1857
- encryptedReasoning.consumeDetails(deltaFields.reasoning_details);
1858
- }
1859
- flushPendingPostToolCallDeltas();
1860
- emitReasoningUsageActivity(hasReasoningUsageActivity);
1861
- }
1862
- throwIfModelStreamAborted(options?.signal);
1863
- if (!finishReason && (directMode || options?.sawStreamDONE?.() === false)) throw new Error("Stream ended without finish_reason");
1864
- flushGemmaToolCallRecoverer();
1865
- flushReasoningTagTextPartitioner();
1866
- appendRecoveredParts(deepSeekToolCallRecoverer?.flush() ?? []);
1867
- for (const part of deepSeekTextFilter?.flush() ?? []) appendVisibleTextDelta(part);
1868
- currentBlock = null;
1869
- flushPendingPostToolCallDeltas();
1870
- if (sawNativeToolCallDelta && recoveredToolCallBlocks.size > 0) output.content = output.content.filter((block) => block.type !== "toolCall" || !recoveredToolCallBlocks.has(block));
1871
- finalizeOpenAICompletionsToolCalls(output, {
1872
- allowSilentToolCallPromotion: finishReason === "stop" || sawNativeToolCallDelta && (options?.sawStreamDONE?.() ?? false),
1873
- onConfirmedToolCall(block, contentIndex) {
1874
- if (directMode) return;
1875
- pushStreamEvent({
1876
- type: "toolcall_end",
1877
- contentIndex,
1878
- toolCall: block,
1879
- partial: output
1880
- });
1881
- }
1882
- });
1883
- output.usage.usageReport ??= { state: "unavailable" };
1884
- if ((!output.usage.contextUsage || output.usage.usageReport.state === "unavailable") && !options?.signal?.aborted && output.stopReason !== "error" && output.stopReason !== "aborted") {
1885
- output.usage.contextUsage = { state: "unavailable" };
1886
- if (!compat.supportsUsageInStreaming) warnMissingStreamingUsage(openAIModel);
1887
- }
1888
- if (providerProcessingMs !== void 0) appendAssistantMessageDiagnostic(output, {
1889
- type: "provider_timing",
1890
- timestamp: Date.now(),
1891
- details: { processingMs: providerProcessingMs }
1892
- });
1893
- }
1894
- const MAX_MISSING_USAGE_HINT_KEYS = 256;
1895
- const missingUsageHintKeys = /* @__PURE__ */ new Set();
1896
- function warnMissingStreamingUsage(model) {
1897
- if (detectOpenAICompletionsCompat(model).capabilities.endpointClass !== "custom") return;
1898
- const key = `${model.provider}/${model.id}`;
1899
- if (missingUsageHintKeys.has(key) || missingUsageHintKeys.size >= MAX_MISSING_USAGE_HINT_KEYS) return;
1900
- missingUsageHintKeys.add(key);
1901
- log.warn(`${key} returned no token usage; context size is estimated and token accounting is unavailable. If this endpoint supports stream_options.include_usage, set compat.supportsUsageInStreaming: true on the model in models.providers.${model.provider}.models.`, {
1902
- provider: model.provider,
1903
- model: model.id
1904
- });
1905
- }
1906
- function shouldEmitOpenAICompletionsReasoning(model, options) {
1907
- if (!model.reasoning) return false;
1908
- const effort = options?.reasoningEffort ?? options?.reasoning ?? "high";
1909
- return Boolean(effort) && isOpenAICompletionsThinkingEnabled(effort);
1910
- }
1911
- //#endregion
1912
- //#region packages/ai/src/providers/openai-web-search-tools.ts
1913
- function hasResponsesWebSearchTool(tools) {
1914
- if (!Array.isArray(tools)) return false;
1915
- return tools.some((tool) => {
1916
- if (!isRecord(tool)) return false;
1917
- if (tool.type === "web_search") return true;
1918
- if (tool.type === "function" && tool.name === "web_search") return true;
1919
- const fn = tool.function;
1920
- return isRecord(fn) && fn.name === "web_search";
1921
- });
1922
- }
1923
- //#endregion
1924
- //#region packages/ai/src/transports/openai-responses-params-internal.ts
1925
- const OPENAI_RESPONSES_TOOL_CALL_PROVIDERS = /* @__PURE__ */ new Set([
1926
- "openai",
1927
- "opencode",
1928
- "azure-openai-responses",
1929
- "github-copilot"
1930
- ]);
1931
- function raiseMinimalReasoningForResponsesWebSearch(params) {
1932
- if (params.effort !== "minimal" || !hasResponsesWebSearchTool(params.tools)) return params.effort;
1933
- for (const effort of [
1934
- "low",
1935
- "medium",
1936
- "high"
1937
- ]) {
1938
- const resolved = resolveOpenAIRequestReasoning(params.model, effort).effort;
1939
- if (resolved && resolved !== "none" && resolved !== "minimal") return resolved;
1940
- }
1941
- return params.effort;
1942
- }
1943
- const OPENAI_CODEX_RESPONSES_UNSUPPORTED_PARAMS = [
1944
- "max_output_tokens",
1945
- "metadata",
1946
- "prompt_cache_retention",
1947
- "prompt_cache_options",
1948
- "service_tier",
1949
- "temperature",
1950
- "top_p"
1951
- ];
1952
- function stripOpenAICodexResponsesUnsupportedTextFields(params) {
1953
- const text = params.text;
1954
- if (!text || typeof text !== "object" || Array.isArray(text)) return;
1955
- const sanitizedText = { ...text };
1956
- delete sanitizedText.format;
1957
- if (Object.keys(sanitizedText).length > 0) params.text = sanitizedText;
1958
- else delete params.text;
1959
- }
1960
- function sanitizeOpenAICodexResponsesParams(model, params) {
1961
- if (!usesNativeOpenAICodexResponsesBackend(model)) return params;
1962
- for (const key of OPENAI_CODEX_RESPONSES_UNSUPPORTED_PARAMS) delete params[key];
1963
- Object.assign(params, { store: false });
1964
- stripOpenAICodexResponsesUnsupportedTextFields(params);
1965
- return params;
1966
- }
1967
- function buildOpenAIResponsesInstructionsText(context) {
1968
- if (!context.systemPrompt) return;
1969
- return sanitizeTransportPayloadText(stripSystemPromptCacheBoundary(context.systemPrompt));
1970
- }
1971
- function resolveOpenAIResponsesInstructions(model, context, usesInstructionsField) {
1972
- if (!usesInstructionsField) return;
1973
- const instructions = buildOpenAIResponsesInstructionsText(context);
1974
- if (instructions && instructions.trim().length > 0) return instructions;
1975
- return usesNativeOpenAICodexResponsesBackend(model) ? OPENAI_CODEX_RESPONSES_DEFAULT_INSTRUCTIONS : void 0;
1976
- }
1977
- function buildOpenAIResponsesCompactSystemMessage(model, instructions) {
1978
- const compat = getCompat(model);
1979
- const role = model.reasoning && compat.supportsDeveloperRole ? "developer" : "system";
1980
- return buildResponsesInputMessage(role, [{
1981
- type: "input_text",
1982
- text: instructions
1983
- }]);
1984
- }
1985
- function ensureOpenAIResponsesNonEmptyInput(messages, context) {
1986
- if (messages.length > 0 || !context.systemPrompt) return;
1987
- if (!buildOpenAIResponsesInstructionsText(context)) throw new Error("OpenAI Responses requires non-empty input when only systemPrompt is provided.");
1988
- messages.push(buildResponsesInputMessage("user", [{
1989
- type: "input_text",
1990
- text: " "
1991
- }]));
1992
- }
1993
- function buildOpenAIResponsesParams(model, context, options, metadata, replayMode = "checkpoint", retainUserProvenance = false) {
1994
- const payloadPolicy = resolveOpenAIResponsesPayloadPolicy(model, { storeMode: "transport-default" });
1995
- const policyAllowsReplayIds = payloadPolicy.explicitStore !== false && !payloadPolicy.shouldStripStore;
1996
- const replayResponsesItemIds = !usesNativeOpenAICodexResponsesBackend(model) && (options?.replayResponsesItemIds ?? policyAllowsReplayIds);
1997
- const messages = convertResponsesMessages(model, context, OPENAI_RESPONSES_TOOL_CALL_PROVIDERS, {
1998
- includeSystemPrompt: !payloadPolicy.usesInstructionsField,
1999
- replayReasoningItems: true,
2000
- replayResponsesItemIds,
2001
- authProfileId: options?.authProfileId,
2002
- sessionId: options?.sessionId,
2003
- replayMode,
2004
- retainUserProvenance
2005
- });
2006
- ensureOpenAIResponsesNonEmptyInput(messages, context);
2007
- const cacheRetention = resolveCacheRetention(options?.cacheRetention);
2008
- const compat = getCompat(model);
2009
- const promptCacheKey = compat.supportsPromptCacheKey ? resolvePromptCacheKey(options, cacheRetention) : void 0;
2010
- const instructions = resolveOpenAIResponsesInstructions(model, context, payloadPolicy.usesInstructionsField);
2011
- const params = {
2012
- model: model.id,
2013
- input: messages,
2014
- stream: true,
2015
- prompt_cache_key: promptCacheKey,
2016
- ...resolveOpenAIPromptCacheParams(model, cacheRetention, compat),
2017
- ...instructions ? { instructions } : {},
2018
- ...metadata ? { metadata } : {}
2019
- };
2020
- const effectiveMaxTokens = options?.maxTokens || model.maxTokens;
2021
- if (effectiveMaxTokens) params.max_output_tokens = clampMaxTokensToModel(model, Math.max(effectiveMaxTokens, 16));
2022
- if (options?.temperature !== void 0 && supportsOpenAITemperature(model)) params.temperature = options.temperature;
2023
- if (options?.topP !== void 0 && (!isOpenAIGpt6Model(model) || resolveOpenAIThinkingApi(model.api) === "azure-openai-responses")) params.top_p = options.topP;
2024
- if (options?.responseFormat !== void 0) params.text = {
2025
- ...params.text,
2026
- format: resolveOpenAIResponsesTextFormat(options.responseFormat)
2027
- };
2028
- if (options?.serviceTier !== void 0 && payloadPolicy.allowsServiceTier) params.service_tier = options.serviceTier;
2029
- if (context.tools) {
2030
- const tools = context.tools;
2031
- const strict = getAiTransportHost().resolveOpenAIStrictToolSetting(model, {
2032
- transport: "stream",
2033
- supportsStrictMode: compat.supportsStrictMode
2034
- });
2035
- const { projection, tools: converted } = prepareResponsesTools(tools, strict, model);
2036
- if (converted.length > 0 || projection.inputToolCount === 0 && projection.diagnostics.length === 0) params.tools = converted;
2037
- if (options?.toolChoice) {
2038
- const toolChoice = reconcileOpenAIResponsesToolChoice(options.toolChoice, projection);
2039
- if (toolChoice !== void 0) params.tool_choice = toolChoice;
2040
- }
2041
- }
2042
- if (model.reasoning) {
2043
- const reasoning = options?.reasoning;
2044
- const requestedEffort = options?.reasoningEffort ?? (reasoning === "none" ? "none" : resolveOpenAISimpleReasoningEffort(model, reasoning)) ?? (options?.reasoningSummary ? "high" : payloadPolicy.defaultManagedReasoningEffort);
2045
- const resolvedEffort = requestedEffort === void 0 ? void 0 : resolveOpenAIRequestReasoning(model, requestedEffort).effort;
2046
- if (resolvedEffort !== void 0) {
2047
- const effort = raiseMinimalReasoningForResponsesWebSearch({
2048
- model,
2049
- effort: resolvedEffort,
2050
- tools: params.tools
2051
- });
2052
- const summary = effort !== "none" && (options?.reasoningEffort || options?.reasoning || options?.reasoningSummary) ? options.reasoningSummary || "auto" : void 0;
2053
- params.reasoning = {
2054
- effort,
2055
- ...summary ? { summary } : {}
2056
- };
2057
- if (summary) params.include = ["reasoning.encrypted_content"];
2058
- }
2059
- }
2060
- applyOpenAIResponsesPayloadPolicy(params, payloadPolicy);
2061
- return sanitizeOpenAICodexResponsesParams(model, params);
2062
- }
2063
- //#endregion
2064
- //#region packages/ai/src/transports/openai-responses-compact-client.ts
2065
- async function postOpenAIResponsesCompaction(params) {
2066
- const instructions = typeof params.request.instructions === "string" && params.request.instructions.length > 0 ? params.request.instructions : void 0;
2067
- const body = instructions && !supportsNativeOpenAIResponsesEndpoint(params.model) ? {
2068
- model: params.request.model,
2069
- input: [buildOpenAIResponsesCompactSystemMessage(params.model, instructions), ...params.request.input ?? []]
2070
- } : {
2071
- model: params.request.model,
2072
- input: params.request.input,
2073
- ...instructions ? { instructions } : {}
2074
- };
2075
- const response = await params.client.post("/responses/compact", {
2076
- ...buildOpenAISdkRequestOptions(params.model, params.options?.signal, { timeoutMs: params.options?.timeoutMs }),
2077
- body
2078
- });
2079
- if (!isRecord(response) || response.object !== "response.compaction") throw new Error("Responses compact endpoint must return a response.compaction object");
2080
- const output = response.output;
2081
- if (!isOpenAIResponsesCompactionOutput(output, params.model)) throw new Error(`Responses compact endpoint: ${getOpenAIResponsesCompactionOutputError(output, params.model)}`);
2082
- const window = output;
2083
- const item = window.at(-1);
2084
- if (window.length > 1 && !supportsNativeOpenAIResponsesEndpoint(params.model)) throw new Error("Responses compact endpoint: retained messages require native OpenAI");
2085
- const usage = isRecord(response.usage) ? response.usage : void 0;
2086
- if (!usage || typeof usage.input_tokens !== "number" || typeof usage.output_tokens !== "number") throw new Error("Responses compact endpoint: usage must include input_tokens and output_tokens");
2087
- return {
2088
- output: window,
2089
- item,
2090
- historyMode: window.length > 1 ? "retained-users" : "compacted-prefix",
2091
- usage,
2092
- model: params.model,
2093
- replayMetadata: buildOpenAIResponsesReasoningReplayMetadata(params.model, {
2094
- authProfileId: params.options?.authProfileId,
2095
- sessionId: params.options?.sessionId
2096
- })
2097
- };
2098
- }
2099
- //#endregion
2100
- //#region packages/ai/src/transports/openai-responses-reasoning-state.ts
2101
- /** Save only admitted settings and hashes, never another copy of the conversation. */
2102
- function recordResponsesReasoningState(message, model, identity, request, output) {
2103
- if (!supportsResponsesReasoningUpdate(request) || !isRecord(request.reasoning) || !request.input || request.previous_response_id || message.providerReplay || output.some((item) => isRecord(item) && item.type === "compaction")) return;
2104
- const reasoning = {
2105
- ...buildProviderReplayContext(model, identity),
2106
- effort: request.reasoning.effort,
2107
- controls: request.input.flatMap((item, index) => isConfigurationUpdate(item) ? [{
2108
- index,
2109
- item
2110
- }] : []),
2111
- inputLength: request.input.length,
2112
- outputLength: output.length,
2113
- prefixHash: responsesContinuationPrefixFingerprint(request.input, output),
2114
- requestHash: responsesContinuationRequestFingerprint(request)
2115
- };
2116
- Object.assign(message, { openclawResponsesInputReplay: {
2117
- ...readResponsesInputReplayState(message),
2118
- reasoning
2119
- } });
2120
- }
2121
- /** A cold transport can replay controls, but cannot resurrect a server response handle. */
2122
- function restoreResponsesReasoningState(context, model, identity, request) {
2123
- const latest = context.messages.findLast((message) => message.role === "assistant");
2124
- const state = latest ? readResponsesInputReplayState(latest)?.reasoning : void 0;
2125
- if (!isRecord(state)) return request;
2126
- const { effort, inputLength, outputLength, controls, prefixHash, requestHash } = state;
2127
- if (!isProviderReplayContext(state) || !providerReplayContextMatches(state, buildProviderReplayContext(model, identity)) || latest?.providerReplay || !supportsResponsesReasoningUpdate(request) || !isRecord(request.reasoning) || !request.input || request.previous_response_id || request.input.some(isConfigurationUpdate) || typeof effort !== "string" || typeof inputLength !== "number" || !Number.isSafeInteger(inputLength) || inputLength < 0 || typeof outputLength !== "number" || !Number.isSafeInteger(outputLength) || outputLength < 0 || !Array.isArray(controls) || controls.length > inputLength || inputLength + outputLength > request.input.length + controls.length) return request;
2128
- const previousInput = request.input.slice(0, inputLength - controls.length);
2129
- let lastIndex = -1;
2130
- for (const control of controls) {
2131
- if (!isRecord(control) || typeof control.index !== "number" || !Number.isSafeInteger(control.index) || control.index <= lastIndex || control.index > previousInput.length || !isConfigurationUpdate(control.item)) return request;
2132
- previousInput.splice(control.index, 0, control.item);
2133
- lastIndex = control.index;
2134
- }
2135
- const previous = {
2136
- ...request,
2137
- reasoning: {
2138
- ...request.reasoning,
2139
- effort
2140
- },
2141
- input: previousInput
2142
- };
2143
- if (responsesContinuationRequestFingerprint(previous) !== requestHash) return request;
2144
- const prepared = replayResponsesReasoningUpdates(previous, request, outputLength);
2145
- if (responsesContinuationPrefixFingerprint((prepared.input ?? []).slice(0, inputLength + outputLength)) !== prefixHash) return request;
2146
- return prepared;
2147
- }
2148
- //#endregion
2149
- //#region packages/ai/src/transports/openai-responses-request-fetch.ts
2150
- function withDefaultResponsesStreamEncoding(fetch) {
2151
- return (input, init) => {
2152
- const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));
2153
- if (headers.has("accept-encoding")) return fetch(input, init);
2154
- headers.set("accept-encoding", "identity");
2155
- return fetch(input, {
2156
- ...init,
2157
- headers
2158
- });
2159
- };
2160
- }
2161
- /** Preserve the existing fetch policy while binding explicit continuation dispatch to its signal. */
2162
- function createResponsesRequestFetch(model, options) {
2163
- const lifecycle = options.lifecycle;
2164
- if (lifecycle && options.compact) throw new Error("Provider review continuation cannot replace its reviewed input with compaction");
2165
- let fetchOverride = options.compact ? createBoundedOpenAIResponsesCompactionFetch(buildGuardedModelFetch(model)) : options.stream ? withDefaultResponsesStreamEncoding(buildGuardedModelFetch(model, void 0, { onSseComment: options.onSseComment })) : void 0;
2166
- if (lifecycle) {
2167
- const dispatchFetch = fetchOverride ?? buildGuardedModelFetch(model);
2168
- fetchOverride = async (input, init) => {
2169
- const signal = init?.signal ?? (input instanceof Request ? input.signal : void 0);
2170
- await lifecycle.beforeDispatch(signal ?? void 0);
2171
- signal?.throwIfAborted();
2172
- lifecycle.assertCurrent();
2173
- return dispatchFetch(input, init);
2174
- };
2175
- }
2176
- return fetchOverride;
2177
- }
2178
- //#endregion
2179
- //#region packages/ai/src/transports/openai-responses-steering.ts
2180
- function cloneWireRequest(request) {
2181
- const serialized = JSON.stringify(request);
2182
- return JSON.parse(serialized);
2183
- }
2184
- async function projectResponsesSteeringInput(request, project) {
2185
- const { input: activeInput, ...activeSettings } = cloneWireRequest(request);
2186
- if (!Array.isArray(activeInput)) return [];
2187
- const { input, ...settings } = cloneWireRequest(await project());
2188
- if (!Array.isArray(input) || stableStringify(settings) !== stableStringify(activeSettings) || stableStringify(input.slice(0, activeInput.length)) !== stableStringify(activeInput)) return [];
2189
- const projected = input.slice(activeInput.length);
2190
- return projected.every((item) => isRecord(item) && item.role === "user") ? projected : [];
2191
- }
2192
- /** One response owns admission; accepted input stays on this connection until continuation. */
2193
- function createResponsesSteering(params) {
2194
- let responseId;
2195
- let sealed = false;
2196
- let unsubscribe;
2197
- const pending = [];
2198
- const accepted = /* @__PURE__ */ new Map();
2199
- const acknowledged = /* @__PURE__ */ new Set();
2200
- const seal = () => {
2201
- sealed = true;
2202
- const cleanup = unsubscribe;
2203
- unsubscribe = void 0;
2204
- cleanup?.();
2205
- };
2206
- return {
2207
- get responseId() {
2208
- return responseId;
2209
- },
2210
- get pending() {
2211
- return pending.length > 0;
2212
- },
2213
- get acceptedInput() {
2214
- return [...accepted.values()].flat();
2215
- },
2216
- seal,
2217
- close(error) {
2218
- seal();
2219
- for (const submission of pending.splice(0)) submission.reject(error);
2220
- },
2221
- handle(event) {
2222
- if (!isRecord(event)) return false;
2223
- if (event.type === "response.created" && !responseId && !sealed) {
2224
- const response = isRecord(event.response) ? event.response : void 0;
2225
- if (typeof response?.id !== "string" || !response.id.trim()) throw new Error("Responses steering requires a response identity");
2226
- const activeResponseId = response.id;
2227
- responseId = activeResponseId;
2228
- const cleanup = params.onActiveResponse({
2229
- needsContinuation: params.needsContinuation,
2230
- steer(messages) {
2231
- if (sealed || messages.length === 0) return Promise.resolve(false);
2232
- params.assertActive();
2233
- const converted = params.toInput(messages);
2234
- const submit = (input) => {
2235
- if (sealed || input.length === 0) return Promise.resolve(false);
2236
- params.assertActive();
2237
- return new Promise((resolve, reject) => {
2238
- pending.push({
2239
- input,
2240
- resolve,
2241
- reject
2242
- });
2243
- params.send({
2244
- type: "response.steer",
2245
- previous_response_id: activeResponseId,
2246
- input
2247
- });
2248
- });
2249
- };
2250
- return Array.isArray(converted) ? submit(converted) : converted.then(submit);
2251
- }
2252
- });
2253
- if (sealed) cleanup?.();
2254
- else unsubscribe = cleanup;
2255
- return false;
2256
- }
2257
- if (event.type !== "response.steer.accepted" && event.type !== "response.steer.failed" && event.type !== "response.steer.pending") return false;
2258
- const steer = isRecord(event.steer) ? event.steer : void 0;
2259
- if (!responseId || steer?.previous_response_id !== responseId) throw new Error("Responses steering acknowledgement has an unexpected identity");
2260
- if (event.type === "response.steer.failed" && steer.id === void 0) {
2261
- const index = pending.findIndex((submission) => stableStringify(submission.input) === stableStringify(steer.input));
2262
- const submission = pending[index];
2263
- if (!submission) throw new Error("Responses steering acknowledgement has no pending submission");
2264
- pending.splice(index, 1);
2265
- submission.resolve(false);
2266
- return true;
2267
- }
2268
- if (typeof steer.id !== "string" || !steer.id.trim()) throw new Error("Responses steering acknowledgement has an unexpected identity");
2269
- if (event.type === "response.steer.pending") {
2270
- if (!accepted.has(steer.id)) throw new Error("Responses steering pending event has no accepted submission");
2271
- return true;
2272
- }
2273
- if (event.type === "response.steer.failed" && accepted.has(steer.id)) throw new Error("OpenAI could not apply accepted steering; the queued message remains in the conversation");
2274
- if (acknowledged.has(steer.id)) throw new Error("Responses steering acknowledgement was already applied");
2275
- const submission = pending.shift();
2276
- if (!submission) throw new Error("Responses steering acknowledgement has no pending submission");
2277
- acknowledged.add(steer.id);
2278
- if (event.type === "response.steer.accepted") {
2279
- accepted.set(steer.id, submission.input);
2280
- submission.resolve(true);
2281
- } else submission.resolve(false);
2282
- return true;
2283
- }
2284
- };
2285
- }
2286
- /** Accepted steering is prepended by the server, so never repeat it in response.create. */
2287
- function omitAcceptedSteering(input, accepted) {
2288
- const remaining = [...input];
2289
- for (const message of accepted) {
2290
- const index = remaining.findIndex((item) => stableStringify(item) === stableStringify(message));
2291
- if (index < 0) throw new Error("Responses steering continuation no longer contains the accepted user input");
2292
- remaining.splice(index, 1);
2293
- }
2294
- return remaining;
2295
- }
2296
- //#endregion
2297
- //#region packages/ai/src/transports/openai-responses-websocket-recovery.ts
2298
- /** Owns safe WebSocket rejection recovery; transport selection and session leases stay with the caller. */
2299
- function createRecoverableResponsesWebSocketStream(params) {
2300
- const { trackedWebSocketStream, websocket, websocketSignal, options, output, buildRequest, createSseStream, closeWebSocketForFallback, logWebSocketFallback, startStream } = params;
2301
- return { async *[Symbol.asyncIterator]() {
2302
- let acceptance = "pending";
2303
- let outputObserved = false;
2304
- try {
2305
- for await (const event of trackedWebSocketStream) {
2306
- const { failure, hasResponseOutput, isPrelude } = readResponsesRecoveryEvent(event);
2307
- outputObserved ||= hasResponseOutput;
2308
- if (isResponsesServiceTierRejection(failure) && !websocket.hasActiveResponse) throw new OpenAIResponsesWebSocketSafeRetryError("invalid_request_error", void 0, "service_tier", "Invalid service_tier argument", failure);
2309
- outputObserved ||= !isPrelude;
2310
- if (acceptance === "pending") {
2311
- acceptance = "observing";
2312
- await notifyProviderStreamOpened({
2313
- options,
2314
- cancelStream: () => websocket.finish({ keep: false })
2315
- });
2316
- acceptance = "accepted";
2317
- }
2318
- startStream();
2319
- yield event;
2320
- }
2321
- } catch (error) {
2322
- if (error instanceof OpenAIResponsesWebSocketSafeRetryError) {
2323
- if (isResponsesServiceTierRejection(error)) {
2324
- const nextTier = nextResponsesServiceTier(websocket.request.service_tier, error);
2325
- if (!nextTier || outputObserved || acceptance === "observing" || output.content.length || websocketSignal.aborted || websocket.hasActiveResponse) throw error;
2326
- closeWebSocketForFallback("service_tier_rejected");
2327
- const rejectedTier = websocket.request.service_tier;
2328
- if (rejectedTier === "ultrafast" || rejectedTier === "priority") responsesServiceTierObserver.reject(options, rejectedTier);
2329
- yield* await createSseStream({
2330
- ...await buildRequest("full-history"),
2331
- service_tier: nextTier
2332
- });
2333
- return;
2334
- }
2335
- const encryptedContentRejected = isInvalidEncryptedContentError(error);
2336
- const recovery = encryptedContentRejected ? await resolveNextResponsesEncryptedContentAttempt({
2337
- kind: "initial",
2338
- request: {
2339
- ...websocket.request,
2340
- stream: true
2341
- }
2342
- }, error, { buildFullHistoryRequest: () => buildRequest("full-history") }) : void 0;
2343
- if (encryptedContentRejected && !recovery) throw error;
2344
- closeWebSocketForFallback(`safe_server_error code=${error.code} status=${safeDebugValue(error.status)} param=${safeDebugValue(error.param)}`);
2345
- yield* await createSseStream(recovery?.request ?? await buildRequest("full-history"), recovery?.kind ?? "continuation-rejected", recovery?.rejectedCompaction);
2346
- return;
2347
- }
2348
- if (websocketSignal.aborted || !(error instanceof OpenAIResponsesWebSocketPreDispatchError)) throw error;
2349
- params.setTransportToSse();
2350
- logWebSocketFallback("before_first_event");
2351
- yield* await createSseStream();
2352
- }
2353
- } };
2354
- }
2355
- //#endregion
2356
- //#region packages/ai/src/transports/openai-responses-websocket.ts
2357
- const SESSION_WEBSOCKET_CACHE_TTL_MS = 3e5;
2358
- const SESSION_WEBSOCKET_MAX_AGE_MS = 33e5;
2359
- const WEBSOCKET_OPEN_STATE = 1;
2360
- function resolveNativeOpenAIResponsesWebSocketMode(model, transport) {
2361
- if (transport !== "websocket" && transport !== "websocket-cached" && transport !== "auto") return;
2362
- if (getAiTransportHost().requiresManagedTransport(model)) return;
2363
- return supportsNativeOpenAIResponsesEndpoint(model) ? transport : void 0;
2364
- }
2365
- function combineWebSocketTimeoutSignal(signal, model, timeoutMs) {
2366
- const resolvedTimeoutMs = timeoutMs !== void 0 && Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : getAiTransportHost().resolveModelRequestTimeoutMs(model);
2367
- if (resolvedTimeoutMs === void 0 || !Number.isFinite(resolvedTimeoutMs)) return signal;
2368
- return AbortSignal.any([signal, AbortSignal.timeout(Math.max(1, resolvedTimeoutMs))]);
2369
- }
2370
- const websocketSessionCache = /* @__PURE__ */ new Map();
2371
- const degradedWebSocketConnections = /* @__PURE__ */ new Map();
2372
- function closeWebSocketSilently(socket, reason = "done") {
2373
- try {
2374
- socket.close({
2375
- code: 1e3,
2376
- reason
2377
- });
2378
- } catch {}
2379
- }
2380
- function invalidateOwnedWebSocketSession(cacheKey, entry, reason = "done") {
2381
- if (entry.idleTimer) {
2382
- clearTimeout(entry.idleTimer);
2383
- entry.idleTimer = void 0;
2384
- }
2385
- closeWebSocketSilently(entry.socket, reason);
2386
- entry.steeringContinuation?.steering.close(/* @__PURE__ */ new Error("Responses steering connection closed"));
2387
- entry.steeringContinuation?.iterator.return?.().catch(() => void 0);
2388
- entry.steeringContinuation = void 0;
2389
- if (websocketSessionCache.get(cacheKey) === entry) websocketSessionCache.delete(cacheKey);
2390
- }
2391
- function scheduleSessionWebSocketExpiry(cacheKey, entry) {
2392
- if (entry.idleTimer) clearTimeout(entry.idleTimer);
2393
- entry.idleTimer = setTimeout(() => {
2394
- if (entry.busy) return;
2395
- invalidateOwnedWebSocketSession(cacheKey, entry, "idle_timeout");
2396
- }, SESSION_WEBSOCKET_CACHE_TTL_MS);
2397
- entry.idleTimer.unref?.();
2398
- }
2399
- function prepareWebSocketConnection(client, headers) {
2400
- if (!isOfficialOpenAIResponsesBaseUrl(client.baseURL)) throw new Error("OpenAI Responses WebSocket requires the official API endpoint");
2401
- if (typeof client.apiKey !== "string" || client.apiKey.length === 0) throw new Error("OpenAI Responses WebSocket requires an API key");
2402
- const owner = getAiTransportHost();
2403
- const resolvedApiKey = owner.resolveSecretSentinel(client.apiKey);
2404
- const resolvedHeaders = { ...resolveAiTransportHeaderSentinels(headers) };
2405
- for (const key of Object.keys(resolvedHeaders)) {
2406
- const normalizedKey = key.toLowerCase();
2407
- if (normalizedKey === "authorization" || normalizedKey === "traceparent") delete resolvedHeaders[key];
2408
- }
2409
- if (!resolvedApiKey) throw new Error("OpenAI Responses WebSocket requires a resolved API key");
2410
- return {
2411
- client: client.withOptions({ apiKey: resolvedApiKey }),
2412
- headers: resolvedHeaders,
2413
- owner,
2414
- ownerId: getSessionResourceOwnerId(owner),
2415
- identity: sha256Hex(JSON.stringify([
2416
- resolvedApiKey,
2417
- client.baseURL,
2418
- Object.entries(resolvedHeaders).toSorted(([a], [b]) => a.localeCompare(b))
2419
- ]))
2420
- };
2421
- }
2422
- function createWebSocket(connection, onError) {
2423
- const socket = new ResponsesWS(connection.client, {
2424
- headers: connection.headers,
2425
- maxQueueSize: 1
2426
- });
2427
- socket.on("error", () => onError(socket));
2428
- return socket;
2429
- }
2430
- function createTransientWebSocketLease(connection) {
2431
- const socket = createWebSocket(connection, (failedSocket) => closeWebSocketSilently(failedSocket, "transport_error"));
2432
- return {
2433
- socket,
2434
- iterator: socket.stream(),
2435
- reusedConnection: false,
2436
- release: () => closeWebSocketSilently(socket)
2437
- };
2438
- }
2439
- function createCachedWebSocketLease(cacheKey, entry, reusedConnection) {
2440
- entry.busy = true;
2441
- const steeringContinuation = entry.steeringContinuation;
2442
- entry.steeringContinuation = void 0;
2443
- return {
2444
- socket: entry.socket,
2445
- iterator: steeringContinuation?.iterator ?? entry.socket.stream(),
2446
- entry,
2447
- reusedConnection,
2448
- steeringContinuation,
2449
- release: ({ keep } = {}) => {
2450
- if (!keep || entry.socket.socket.readyState !== WEBSOCKET_OPEN_STATE) {
2451
- invalidateOwnedWebSocketSession(cacheKey, entry);
2452
- return;
2453
- }
2454
- entry.busy = false;
2455
- scheduleSessionWebSocketExpiry(cacheKey, entry);
2456
- }
2457
- };
2458
- }
2459
- function acquireWebSocket(params, connection) {
2460
- if (params.mode === "websocket" || !params.sessionId) return createTransientWebSocketLease(connection);
2461
- const cacheKey = `${connection.ownerId}\0${params.sessionId}\0${connection.identity}`;
2462
- const cached = websocketSessionCache.get(cacheKey);
2463
- if (cached) {
2464
- if (cached.idleTimer) {
2465
- clearTimeout(cached.idleTimer);
2466
- cached.idleTimer = void 0;
2467
- }
2468
- if (cached.busy) return createTransientWebSocketLease(connection);
2469
- const expired = Date.now() - cached.createdAt >= SESSION_WEBSOCKET_MAX_AGE_MS;
2470
- if (!expired && cached.socket.socket.readyState === WEBSOCKET_OPEN_STATE) return createCachedWebSocketLease(cacheKey, cached, true);
2471
- invalidateOwnedWebSocketSession(cacheKey, cached, expired ? "connection_age_limit" : "done");
2472
- }
2473
- const entry = {
2474
- socket: createWebSocket(connection, (failedSocket) => {
2475
- const failedEntry = websocketSessionCache.get(cacheKey);
2476
- if (failedEntry?.socket === failedSocket) invalidateOwnedWebSocketSession(cacheKey, failedEntry, "transport_error");
2477
- else closeWebSocketSilently(failedSocket, "transport_error");
2478
- }),
2479
- sessionId: params.sessionId,
2480
- owner: connection.owner,
2481
- busy: true,
2482
- createdAt: Date.now()
2483
- };
2484
- websocketSessionCache.set(cacheKey, entry);
2485
- return createCachedWebSocketLease(cacheKey, entry, false);
2486
- }
2487
- function sanitizeWebSocketRequest(request) {
2488
- const { stream: _stream, background: _background, ...websocketRequest } = request;
2489
- return websocketRequest;
2490
- }
2491
- async function nextWebSocketMessage(iterator, signal) {
2492
- if (signal?.aborted) throw transportAbortError(signal);
2493
- return await racePromiseWithAbortSignal(iterator.next(), signal, transportAbortError);
2494
- }
2495
- function readServerEvent(message) {
2496
- if (message.type === "message") return message.message;
2497
- if (message.type === "error") throw parseOpenAIResponsesWebSocketServerError(message.error) ?? new Error("OpenAI Responses WebSocket transport failed", { cause: message.error });
2498
- if (message.type === "close") throw new Error(`OpenAI Responses WebSocket closed before completion (code ${message.code})`);
2499
- }
2500
- function createOpenAIResponsesWebSocketStream(params) {
2501
- const connection = prepareWebSocketConnection(params.client, params.headers);
2502
- let fullRequest = sanitizeWebSocketRequest(params.request);
2503
- const requestModel = typeof fullRequest.model === "string" ? fullRequest.model : "";
2504
- const degradationKey = `${connection.ownerId}\0${params.sessionId ?? ""}\0${connection.identity}\0${requestModel}`;
2505
- const degraded = degradedWebSocketConnections.get(degradationKey);
2506
- if (degraded && degraded.retryAt > Date.now()) throw new OpenAIResponsesWebSocketPreDispatchError(/* @__PURE__ */ new Error("OpenAI Responses WebSocket is cooling down after a transport failure"));
2507
- if (degraded) clearTimeout(degraded.expiryTimer);
2508
- degradedWebSocketConnections.delete(degradationKey);
2509
- const markDegraded = () => {
2510
- const cooldownMs = params.degradeCooldownMs;
2511
- if (cooldownMs === void 0 || !Number.isFinite(cooldownMs) || cooldownMs <= 0) return;
2512
- const entry = {
2513
- sessionId: params.sessionId,
2514
- owner: connection.owner,
2515
- retryAt: Date.now() + cooldownMs,
2516
- expiryTimer: setTimeout(() => {
2517
- if (degradedWebSocketConnections.get(degradationKey) === entry) degradedWebSocketConnections.delete(degradationKey);
2518
- }, cooldownMs)
2519
- };
2520
- entry.expiryTimer.unref?.();
2521
- degradedWebSocketConnections.set(degradationKey, entry);
2522
- };
2523
- let lease;
2524
- try {
2525
- lease = acquireWebSocket(params, connection);
2526
- } catch (error) {
2527
- markDegraded();
2528
- throw new OpenAIResponsesWebSocketPreDispatchError(error);
2529
- }
2530
- let prepared;
2531
- let previousContinuation;
2532
- const resumedSteering = lease.steeringContinuation;
2533
- const steeringMode = resumedSteering ? resumedSteering.requiresInput ? "required-input" : "automatic" : void 0;
2534
- try {
2535
- const continuation = previousContinuation = lease.entry?.continuation;
2536
- if (continuation && lease.entry) {
2537
- lease.entry.continuation = void 0;
2538
- prepared = resolveResponsesContinuationRequest(continuation, fullRequest, steeringMode);
2539
- } else {
2540
- fullRequest = params.restoreRequest?.(fullRequest) ?? fullRequest;
2541
- prepared = {
2542
- request: fullRequest,
2543
- continuationStatus: lease.entry ? "no_previous_response" : "socket_not_cached"
2544
- };
2545
- }
2546
- } catch (error) {
2547
- lease.iterator.return?.().catch(() => void 0);
2548
- lease.release({ keep: false });
2549
- throw error;
2550
- }
2551
- let streamStarted = false;
2552
- let terminalResponse;
2553
- let terminalReceived = false;
2554
- let released = false;
2555
- let retainIterator = false;
2556
- let deferredInput = false;
2557
- let inputReplay;
2558
- if (resumedSteering) try {
2559
- if (prepared.continuationStatus !== "continued" || !prepared.request.previous_response_id) throw new Error("Responses steering continuation changed its request or history");
2560
- const input = omitAcceptedSteering(prepared.request.input ?? [], resumedSteering.acceptedInput);
2561
- if (!resumedSteering.requiresInput && (stableStringify(fullRequest.instructions) !== stableStringify(resumedSteering.instructions) || stableStringify(fullRequest.tools) !== stableStringify(resumedSteering.tools))) throw new Error("Responses automatic steering continuation cannot change instructions or tools");
2562
- const baseline = prepared.fullRequest ?? fullRequest;
2563
- const priorLength = (baseline.input?.length ?? 0) - (prepared.request.input?.length ?? 0);
2564
- const fingerprints = input.map(responsesInputFingerprint);
2565
- if (fingerprints.length > 0) inputReplay = {
2566
- afterResponseId: prepared.request.previous_response_id,
2567
- before: resumedSteering.requiresInput ? fingerprints : [],
2568
- after: resumedSteering.requiresInput ? [] : fingerprints
2569
- };
2570
- const delivered = resumedSteering.requiresInput ? input : [];
2571
- prepared.fullRequest = {
2572
- ...baseline,
2573
- input: [
2574
- ...(baseline.input ?? []).slice(0, priorLength),
2575
- ...resumedSteering.acceptedInput,
2576
- ...delivered
2577
- ]
2578
- };
2579
- prepared.request = {
2580
- ...prepared.request,
2581
- input: delivered
2582
- };
2583
- deferredInput = !resumedSteering.requiresInput && input.length > 0;
2584
- } catch (error) {
2585
- lease.iterator.return?.().catch(() => void 0);
2586
- lease.release({ keep: false });
2587
- throw new OpenAIResponsesWebSocketPostDispatchError(error);
2588
- }
2589
- const steering = lease.entry && params.onActiveResponse && params.steeringInput ? createResponsesSteering({
2590
- onActiveResponse: params.onActiveResponse,
2591
- toInput: params.steeringInput,
2592
- send: (event) => lease.socket.sendRaw(JSON.stringify(event)),
2593
- needsContinuation: () => deferredInput,
2594
- assertActive: () => {
2595
- if (released || terminalReceived || params.signal?.aborted) throw new Error("Responses steering is no longer active");
2596
- }
2597
- }) : void 0;
2598
- const finish = ({ keep = true } = {}) => {
2599
- if (released) return;
2600
- released = true;
2601
- if (keep && lease.entry && terminalResponse) lease.entry.continuation = recordResponsesContinuationState(previousContinuation, prepared.fullRequest ?? fullRequest, terminalResponse, previousContinuation?.lastResponseId === prepared.request.previous_response_id);
2602
- lease.release({ keep });
2603
- };
2604
- return {
2605
- stream: { async *[Symbol.asyncIterator]() {
2606
- if (streamStarted) throw new Error("OpenAI Responses WebSocket stream can only be consumed once");
2607
- streamStarted = true;
2608
- const iterator = lease.iterator;
2609
- let requestDispatched = false;
2610
- try {
2611
- if (params.signal?.aborted) throw transportAbortError(params.signal);
2612
- if (resumedSteering) {
2613
- requestDispatched = true;
2614
- if (resumedSteering.requiresInput) lease.socket.send({
2615
- ...prepared.request,
2616
- type: "response.create"
2617
- });
2618
- }
2619
- for (;;) {
2620
- const buffered = resumedSteering?.buffered.shift();
2621
- const next = buffered ? {
2622
- value: buffered,
2623
- done: false
2624
- } : await nextWebSocketMessage(iterator, params.signal);
2625
- if (next.done) throw new Error("OpenAI Responses WebSocket closed before a terminal response event");
2626
- if (next.value.type === "open") {
2627
- if (!requestDispatched) {
2628
- requestDispatched = true;
2629
- lease.socket.send({
2630
- ...prepared.request,
2631
- type: "response.create"
2632
- });
2633
- }
2634
- continue;
2635
- }
2636
- const event = readServerEvent(next.value);
2637
- if (!event) continue;
2638
- if (isRecord(event) && typeof event.type === "string" && event.type.startsWith("response.steer.")) {
2639
- if ((isRecord(event.steer) && event.steer.previous_response_id === steering?.responseId ? steering : resumedSteering?.steering ?? steering)?.handle(event)) continue;
2640
- }
2641
- steering?.handle(event);
2642
- if (event.type === "response.completed") terminalResponse = event.response;
2643
- terminalReceived = event.type === "response.completed" || event.type === "response.incomplete" || event.type === "response.failed";
2644
- if (terminalReceived) {
2645
- steering?.seal();
2646
- if (event.type === "response.failed") steering?.close(/* @__PURE__ */ new Error("Responses failed before steering could be applied"));
2647
- const continuationBuffer = [];
2648
- for (;;) {
2649
- if (!steering?.pending) break;
2650
- const acknowledgement = await nextWebSocketMessage(iterator, params.signal);
2651
- if (acknowledgement.done) throw new Error("Responses closed before acknowledging steering");
2652
- const acknowledgedEvent = readServerEvent(acknowledgement.value);
2653
- if (!steering.handle(acknowledgedEvent)) continuationBuffer.push(acknowledgement.value);
2654
- }
2655
- const acceptedInput = steering?.acceptedInput ?? [];
2656
- const isSteered = event.type === "response.incomplete" && isRecord(event.response.incomplete_details) && event.response.incomplete_details.reason === "steered";
2657
- if (lease.entry && steering && acceptedInput.length > 0 && (event.type === "response.completed" || isSteered)) {
2658
- if (event.type === "response.incomplete") terminalResponse = event.response;
2659
- lease.entry.steeringContinuation = {
2660
- iterator,
2661
- buffered: continuationBuffer,
2662
- acceptedInput,
2663
- requiresInput: (terminalResponse?.output ?? []).some((item) => (item.type === "function_call" || item.type === "custom_tool_call") && !(isRecord(item) && item.async === true) || item.type === "mcp_approval_request"),
2664
- steering,
2665
- instructions: fullRequest.instructions,
2666
- tools: fullRequest.tools
2667
- };
2668
- retainIterator = true;
2669
- if (isSteered) {
2670
- yield {
2671
- ...event,
2672
- type: "response.completed",
2673
- response: {
2674
- ...event.response,
2675
- status: "completed",
2676
- incomplete_details: null
2677
- }
2678
- };
2679
- return;
2680
- }
2681
- }
2682
- }
2683
- yield event;
2684
- if (terminalReceived) {
2685
- degradedWebSocketConnections.delete(degradationKey);
2686
- return;
2687
- }
2688
- }
2689
- } catch (error) {
2690
- const steeringDispatched = Boolean(steering?.pending || steering?.acceptedInput.length || resumedSteering);
2691
- steering?.close(error instanceof Error ? error : /* @__PURE__ */ new Error("Responses steering failed"));
2692
- if (lease.entry) lease.entry.continuation = void 0;
2693
- const safeRetry = error instanceof OpenAIResponsesWebSocketSafeRetryError && !steeringDispatched;
2694
- if (!params.callerSignal?.aborted && !safeRetry) markDegraded();
2695
- if (!requestDispatched && !params.signal?.aborted) throw new OpenAIResponsesWebSocketPreDispatchError(error);
2696
- if (!requestDispatched || params.callerSignal?.aborted || safeRetry) throw error;
2697
- throw new OpenAIResponsesWebSocketPostDispatchError(error);
2698
- } finally {
2699
- steering?.seal();
2700
- if (!retainIterator) {
2701
- steering?.close(/* @__PURE__ */ new Error("Responses stream ended before steering was confirmed"));
2702
- await iterator.return?.().catch(() => void 0);
2703
- }
2704
- if (!terminalReceived) finish({ keep: false });
2705
- }
2706
- } },
2707
- request: prepared.request,
2708
- fullRequest: prepared.fullRequest ?? fullRequest,
2709
- reusedConnection: lease.reusedConnection,
2710
- continuationStatus: prepared.continuationStatus,
2711
- inputReplay,
2712
- get hasActiveResponse() {
2713
- return Boolean(steering?.responseId || resumedSteering);
2714
- },
2715
- finish
2716
- };
2717
- }
2718
- function closeOpenAIResponsesWebSocketSessions(sessionId, owner) {
2719
- for (const [cacheKey, entry] of websocketSessionCache) {
2720
- if (owner && entry.owner !== owner || sessionId && entry.sessionId !== sessionId) continue;
2721
- invalidateOwnedWebSocketSession(cacheKey, entry, "session_cleanup");
2722
- }
2723
- for (const [key, entry] of degradedWebSocketConnections) if ((!owner || entry.owner === owner) && (!sessionId || entry.sessionId === sessionId)) {
2724
- clearTimeout(entry.expiryTimer);
2725
- degradedWebSocketConnections.delete(key);
2726
- }
2727
- }
2728
- registerSessionResourceCleanup(closeOpenAIResponsesWebSocketSessions);
2729
- //#endregion
2730
- //#region packages/ai/src/transports/openai-responses-client.ts
2731
- function createOpenAIResponsesClient(model, apiKey, defaultHeaders, fetchOverride) {
2732
- return new OpenAI({
2733
- apiKey,
2734
- baseURL: resolveOpenAIClientBaseUrl(model),
2735
- dangerouslyAllowBrowser: true,
2736
- defaultHeaders,
2737
- fetch: fetchOverride ?? buildGuardedModelFetch(model),
2738
- ...buildOpenAISdkClientOptions(model)
2739
- });
2740
- }
2741
- function createResponsesTransportExecutor(config) {
2742
- return (model, context, options) => {
2743
- const responsesOptions = options;
2744
- const independent = independentResponsesRequest.has(options);
2745
- const compactRequest = claimResponsesCompactRequest(responsesOptions);
2746
- const v2Compaction = compactRequest?.mode === "v2" ? createResponsesV2CompactionCollector(compactRequest.replayBudget) : void 0;
2747
- const { eventStream, stream } = createWritableTransportEventStream();
2748
- (async () => {
2749
- const output = createAssistantOutput(model, config.outputApi);
2750
- let firstEventAbort;
2751
- let continuationClaim;
2752
- const requestLifecycle = responsesRequestLifecycle.get(options);
2753
- try {
2754
- if (compactRequest && requestLifecycle) throw new Error("Provider review continuation cannot replace its reviewed input with compaction");
2755
- const apiKey = options?.apiKey || getEnvApiKey(model.provider) || "";
2756
- const websocketMode = independent ? void 0 : resolveNativeOpenAIResponsesWebSocketMode(model, responsesOptions?.transport);
2757
- const encodeBody = prepareModelRequestBody(websocketMode || compactRequest?.mode === "endpoint" ? void 0 : options);
2758
- const turnState = resolveProviderTransportTurnState(model, {
2759
- sessionId: options?.sessionId,
2760
- turnId: randomUUID(),
2761
- attempt: 1,
2762
- transport: websocketMode ? "websocket" : "stream"
2763
- });
2764
- const websocketSessionPolicy = websocketMode ? turnState?.websocket : void 0;
2765
- const httpTurnHeaders = filterProviderTurnHeadersForExplicitOpencodeSession(model, options, turnState?.headers);
2766
- const websocketTurnHeaders = filterProviderTurnHeadersForExplicitOpencodeSession(model, options, websocketSessionPolicy?.headers);
2767
- const websocketHeaders = websocketMode ? buildOpenAIClientHeaders(model, context, options?.headers, websocketTurnHeaders, options?.sessionId, options?.cacheRetention) : void 0;
2768
- const httpHeaders = buildOpenAIClientHeaders(model, context, options?.headers, httpTurnHeaders, options?.sessionId, options?.cacheRetention);
2769
- const fetchOverride = withOpenAIErrorResponseHook(createResponsesRequestFetch(model, {
2770
- compact: compactRequest?.mode === "endpoint",
2771
- stream: config.streamRequest,
2772
- lifecycle: requestLifecycle,
2773
- onSseComment: () => notifyLlmRequestActivity(options?.signal, false)
2774
- }) ?? buildGuardedModelFetch(model), options?.onResponse, model);
2775
- const client = config.createClient(model, apiKey, httpHeaders, fetchOverride);
2776
- const nativeAstra = model.id === "gpt-6-astra" && supportsNativeOpenAIResponsesEndpoint(model);
2777
- const asyncToolExecutionEligible = nativeAstra && options?.asyncToolExecution === true && !responsesOptions?.openclawCodeModeToolSurface;
2778
- const prepareRequest = async (request) => {
2779
- let params = request;
2780
- const preserveUsers = v2Compaction?.preserveUsers(request.input ?? []);
2781
- const nextParams = await options?.onPayload?.(params, model);
2782
- if (nextParams !== void 0) params = nextParams;
2783
- if (preserveUsers) params = {
2784
- ...params,
2785
- input: preserveUsers(params.input ?? [])
2786
- };
2787
- params = sanitizeOpenAICodexResponsesParams(model, params);
2788
- params = v2Compaction ? v2Compaction.sanitizeImages(params) : sanitizeResponsesImagePayload(params);
2789
- if (responsesOptions?.openclawCodeModeToolSurface === true) {
2790
- const visibleToolNames = resolveCodeModeResponsesVisibleToolNames(context);
2791
- const allowedHostedToolTypes = responsesOptions?.openclawCodeModeAllowedHostedToolTypes;
2792
- enforceCodeModeResponsesToolSurface(params, visibleToolNames, allowedHostedToolTypes, codeModeToolSurfaceObserver.get(options));
2793
- assertCodeModeResponsesToolSurface(params, visibleToolNames, allowedHostedToolTypes);
2794
- }
2795
- if (asyncToolExecutionEligible && params.model === "gpt-6-astra" && params.multi_agent?.enabled !== true && params.tools) {
2796
- const synchronousTools = new Set(context.tools?.flatMap((tool) => tool.async === false ? [tool.name] : []));
2797
- params.tools = params.tools.map((tool) => tool.type === "function" && !synchronousTools.has(tool.name) ? {
2798
- ...tool,
2799
- async: true
2800
- } : tool);
2801
- }
2802
- if (v2Compaction) {
2803
- params.input = [...params.input ?? [], { type: "compaction_trigger" }];
2804
- v2Compaction.assertReplayFits(params.input, model);
2805
- }
2806
- return params;
2807
- };
2808
- const buildRequest = (replayMode, requestContext = context) => prepareRequest(config.buildRequest(model, requestContext, responsesOptions, turnState?.metadata, replayMode, Boolean(v2Compaction)));
2809
- let params = await buildRequest("checkpoint");
2810
- const asyncTools = !compactRequest && asyncToolExecutionEligible && params.model === "gpt-6-astra" && params.multi_agent?.enabled !== true;
2811
- if (compactRequest?.mode === "endpoint") {
2812
- const compacted = await postOpenAIResponsesCompaction({
2813
- client,
2814
- model,
2815
- request: params,
2816
- options: responsesOptions
2817
- });
2818
- output.usage.input = compacted.usage.input_tokens;
2819
- output.usage.output = compacted.usage.output_tokens;
2820
- output.usage.totalTokens = compacted.usage.input_tokens + compacted.usage.output_tokens;
2821
- output.usage.usageReport = { state: "available" };
2822
- compactRequest.resolve(compacted);
2823
- finalizeTransportStream({
2824
- stream,
2825
- output,
2826
- signal: options?.signal
2827
- });
2828
- return;
2829
- }
2830
- const sessionId = options?.sessionId;
2831
- if (config.httpContinuation && !compactRequest && !independent && !websocketMode && !getAiTransportHost().requiresManagedTransport(model) && (supportsNativeOpenAIResponsesEndpoint(model) || resolveOpenAIResponsesPayloadPolicy(model).explicitContinuationOptIn) && sessionId && (params.store === true || supportsResponsesReasoningUpdate(params)) && !params.previous_response_id) {
2832
- const restoreRequest = () => restoreResponsesReasoningState(context, model, responsesOptions, params);
2833
- continuationClaim = claimOpenAIResponsesHttpContinuation({
2834
- sessionId,
2835
- apiKey,
2836
- baseUrl: model.baseUrl,
2837
- headers: httpHeaders,
2838
- request: params,
2839
- restoreRequest
2840
- });
2841
- params = continuationClaim?.fullRequest ?? restoreRequest();
2842
- }
2843
- const observePrompt = createResponsesPromptEgressObserver(responsesOptions, context.systemPrompt);
2844
- const requestStartedAt = Date.now();
2845
- let started = false;
2846
- const startStream = () => {
2847
- if (!started) {
2848
- started = true;
2849
- stream.push({
2850
- type: "start",
2851
- partial: output
2852
- });
2853
- }
2854
- };
2855
- const firstEvent = createFirstStreamEventAbortController(options?.signal);
2856
- firstEventAbort = firstEvent;
2857
- const requestOptions = buildOpenAISdkRequestOptions(model, firstEvent.signal, {
2858
- stream: config.streamRequest,
2859
- timeoutMs: options?.timeoutMs
2860
- });
2861
- const websocketSignal = combineWebSocketTimeoutSignal(firstEvent.signal, model, requestOptions?.timeout);
2862
- emitModelTransportDebug(log, `[responses] start provider=${model.provider} api=${model.api} model=${model.id} requestIdHash=${redactIdentifier(options?.requestId, { len: 64 })} baseUrl=${formatModelTransportDebugBaseUrl(model.baseUrl)} timeoutMs=${safeDebugValue(requestOptions?.timeout)} apiKey=${apiKey ? "present" : "missing"} ${summarizeResponsesPayload(params)}`);
2863
- const responseModelTracker = createResponseModelTracker(isOpenAICodexResponsesModel(model));
2864
- let continuationBaseline;
2865
- let dispatchedPreviousResponseId;
2866
- let contextUsageEligible = true;
2867
- let requestedTier;
2868
- const createSseStream = async (initialRequest = continuationClaim?.request ?? params, initialAttemptKind = "initial", initialRejectedCompaction) => {
2869
- const { stream: responseStream } = await createResponsesStreamWithRecovery({
2870
- client,
2871
- request: initialRequest,
2872
- requestOptions,
2873
- model,
2874
- encodeBody,
2875
- observePrompt,
2876
- initialAttemptKind,
2877
- initialRejectedCompaction,
2878
- buildFullHistoryRequest: () => buildRequest("full-history"),
2879
- onCompactionRejected: (checkpoint) => suppressOpenAIResponsesCompaction(output, model, responsesOptions, checkpoint),
2880
- canRetryStream: () => output.content.length === 0,
2881
- onServiceTierRejected: (tier) => responsesServiceTierObserver.reject(options, tier),
2882
- wrapStream: ({ stream: rawResponseStream, response, attempt }) => {
2883
- requestedTier = attempt.request.service_tier;
2884
- contextUsageEligible &&= attempt.kind === "initial";
2885
- dispatchedPreviousResponseId = attempt.request.previous_response_id;
2886
- continuationBaseline = attempt.request.previous_response_id ? params : attempt.request;
2887
- const trackedResponseStream = responseModelTracker.track(response, rawResponseStream);
2888
- return withProviderResponseHook({
2889
- stream: observeResponsesStream(v2Compaction ? v2Compaction.observe(trackedResponseStream) : trackedResponseStream, model, requestStartedAt, attempt.request),
2890
- signal: firstEvent.signal,
2891
- abort: firstEvent.abort,
2892
- hook: createOpenAIProviderAcceptanceHook(options, response, model),
2893
- onReady: () => {
2894
- emitModelTransportDebug(log, `[responses] headers provider=${model.provider} api=${model.api} model=${model.id} transport=sse elapsedMs=${Date.now() - requestStartedAt}`);
2895
- startStream();
2896
- }
2897
- });
2898
- }
2899
- });
2900
- return responseStream;
2901
- };
2902
- let responseStream;
2903
- let websocketBaseline;
2904
- let finishWebSocket;
2905
- let transport = "sse";
2906
- const logWebSocketFallback = (reason) => emitModelTransportDebug(log, `[responses] websocket_fallback provider=${model.provider} api=${model.api} model=${model.id} reason=${reason}`);
2907
- const closeWebSocketForFallback = (reason) => {
2908
- finishWebSocket?.({ keep: false });
2909
- finishWebSocket = void 0;
2910
- transport = "sse";
2911
- logWebSocketFallback(reason);
2912
- };
2913
- if (websocketMode) try {
2914
- const websocket = createOpenAIResponsesWebSocketStream({
2915
- client,
2916
- request: params,
2917
- restoreRequest: (request) => restoreResponsesReasoningState(context, model, responsesOptions, request),
2918
- mode: websocketMode,
2919
- sessionId: options?.sessionId,
2920
- headers: websocketHeaders,
2921
- signal: websocketSignal,
2922
- callerSignal: options?.signal,
2923
- degradeCooldownMs: websocketSessionPolicy?.degradeCooldownMs,
2924
- onActiveResponse: !compactRequest && nativeAstra && params.model === "gpt-6-astra" ? options?.onActiveResponse : void 0,
2925
- steeringInput: (messages) => {
2926
- contextUsageEligible = false;
2927
- return projectResponsesSteeringInput(params, () => buildRequest("checkpoint", {
2928
- ...context,
2929
- messages: [...context.messages, ...messages]
2930
- }));
2931
- }
2932
- });
2933
- finishWebSocket = websocket.finish;
2934
- requestedTier = websocket.request.service_tier;
2935
- websocketBaseline = websocket.fullRequest;
2936
- recordResponsesInputReplay(output, websocket.inputReplay);
2937
- contextUsageEligible &&= websocket.inputReplay === void 0;
2938
- observePrompt?.(websocket.request, {
2939
- egress: "responses-websocket",
2940
- payloadVariant: "initial"
2941
- });
2942
- transport = "websocket";
2943
- emitModelTransportDebug(log, `[responses] websocket_selected provider=${model.provider} api=${model.api} model=${model.id} mode=${websocketMode} reused=${websocket.reusedConnection} continuation=${websocket.continuationStatus === "continued"} continuationStatus=${websocket.continuationStatus} sessionIdHash=${redactIdentifier(options?.sessionId)} headersHash=${redactIdentifier(JSON.stringify(Object.entries(websocketHeaders ?? {}).toSorted(([a], [b]) => a.localeCompare(b))))}`);
2944
- responseStream = createRecoverableResponsesWebSocketStream({
2945
- trackedWebSocketStream: observeResponsesStream(v2Compaction ? v2Compaction.observe(responseModelTracker.track(void 0, websocket.stream)) : responseModelTracker.track(void 0, websocket.stream), model, requestStartedAt, websocket.request, "websocket"),
2946
- websocket,
2947
- websocketSignal,
2948
- options,
2949
- output,
2950
- buildRequest,
2951
- createSseStream,
2952
- closeWebSocketForFallback,
2953
- logWebSocketFallback,
2954
- startStream,
2955
- setTransportToSse: () => {
2956
- transport = "sse";
2957
- }
2958
- });
2959
- } catch (error) {
2960
- if (error instanceof OpenAIResponsesWebSocketPostDispatchError) throw error;
2961
- closeWebSocketForFallback("setup_failure");
2962
- responseStream = await createSseStream();
2963
- }
2964
- else responseStream = await createSseStream();
2965
- try {
2966
- const acceptedResponseStream = withResponsesRequestAcceptance(responseStream, requestLifecycle, transport === "websocket" ? websocketSignal : firstEvent.signal);
2967
- const terminal = await processResponsesStream(acceptedResponseStream, output, stream, model, {
2968
- canRetryIdentityConflict: () => hasOnlyResponsesFunctionTools(transport === "websocket" ? websocketBaseline : continuationBaseline),
2969
- ...config.pricingOptions?.(responsesOptions, model),
2970
- resolveServiceTier: (responseTier, originalTier) => responseTier ?? (requestedTier === "priority" || requestedTier === "default" ? requestedTier : originalTier),
2971
- onServiceTier: (tier, response) => responsesServiceTierObserver.observe(options, requestedTier, tier, response),
2972
- firstEventTimeoutMs: getFirstStreamEventTimeoutMs(options) ?? config.firstEventTimeoutMs,
2973
- abortFirstEventStream: firstEvent.abort,
2974
- onFirstEventTimeout: getFirstStreamEventTimeoutHandler(options),
2975
- signal: options?.signal,
2976
- reasoningReplayMetadata: buildOpenAIResponsesReasoningReplayMetadata(model, {
2977
- authProfileId: responsesOptions?.authProfileId,
2978
- sessionId: options?.sessionId
2979
- }),
2980
- asyncToolExecution: asyncTools,
2981
- ...responseModelTracker.terminalOptions
2982
- });
2983
- finishWebSocket?.();
2984
- if (options?.signal?.aborted) throw transportAbortError(options.signal);
2985
- if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error(output.errorMessage ?? "An unknown error occurred");
2986
- const admitted = !independent && (transport === "websocket" ? websocketBaseline : continuationBaseline);
2987
- if (v2Compaction && compactRequest) {
2988
- const compacted = v2Compaction.finish({
2989
- terminal,
2990
- input: params.input ?? [],
2991
- model,
2992
- options: responsesOptions
2993
- });
2994
- compactRequest.resolve({
2995
- ...compacted,
2996
- modelUsage: output.usage
2997
- });
2998
- finalizeTransportStream({
2999
- stream,
3000
- output,
3001
- signal: options?.signal
3002
- });
3003
- return;
3004
- }
3005
- if (terminal && admitted && supportsNativeOpenAIResponsesEndpoint(model)) recordResponsesReasoningState(output, model, responsesOptions, admitted, terminal.output);
3006
- if (continuationClaim && continuationBaseline && terminal) continuationClaim.commit(continuationBaseline, terminal, dispatchedPreviousResponseId);
3007
- if (terminal && admitted && contextUsageEligible) recordResponsesContextUsage(output, model, responsesOptions, admitted, terminal.output, "transport");
3008
- } catch (error) {
3009
- finishWebSocket?.({ keep: false });
3010
- throw error;
3011
- }
3012
- emitModelTransportDebug(log, `[responses] completed provider=${model.provider} api=${model.api} model=${model.id} transport=${transport} elapsedMs=${Date.now() - requestStartedAt}`);
3013
- finalizeTransportStream({
3014
- stream,
3015
- output,
3016
- signal: options?.signal
3017
- });
3018
- } catch (error) {
3019
- if (error instanceof DegenerateToolCallArgumentsError) firstEventAbort?.abort(error);
3020
- if (requestLifecycle) await requestLifecycle.settle().catch(() => void 0);
3021
- if (compactRequest) {
3022
- compactRequest.reject(error);
3023
- failTransportStream({
3024
- stream,
3025
- output,
3026
- signal: options?.signal,
3027
- error
3028
- });
3029
- return;
3030
- }
3031
- if (error instanceof ResponsesStreamFailure && error.observation) logResponsesFailedNoDetails(error.observation);
3032
- const incompleteReason = output.diagnostics?.find(({ type }) => type === "openai_responses_terminal")?.details?.incompleteReason;
3033
- emitModelTransportError(log, "responses", `provider=${model.provider} api=${model.api} model=${model.id} ` + summarizeOpenAITransportError(error, firstEventAbort?.signal ?? options?.signal) + (typeof incompleteReason === "string" ? ` incompleteReason=${incompleteReason}` : ""), options?.signal);
3034
- failTransportStream({
3035
- stream,
3036
- output,
3037
- signal: options?.signal,
3038
- error
3039
- });
3040
- } finally {
3041
- continuationClaim?.release();
3042
- firstEventAbort?.dispose();
3043
- }
3044
- })();
3045
- return eventStream;
3046
- };
3047
- }
3048
- function createOpenAIResponsesTransportStreamFn() {
3049
- return createResponsesTransportExecutor({
3050
- streamRequest: true,
3051
- httpContinuation: true,
3052
- createClient: createOpenAIResponsesClient,
3053
- buildRequest: buildOpenAIResponsesParams,
3054
- pricingOptions: (options, model) => ({
3055
- serviceTier: options?.serviceTier,
3056
- applyServiceTierPricing: (usage, serviceTier) => applyResponsesServiceTierPricing(usage, serviceTier, model)
3057
- })
3058
- });
3059
- }
3060
- function createAzureOpenAIResponsesTransportStreamFn() {
3061
- return createResponsesTransportExecutor({
3062
- outputApi: "azure-openai-responses",
3063
- firstEventTimeoutMs: AZURE_RESPONSES_FIRST_EVENT_TIMEOUT_MS,
3064
- createClient: createAzureOpenAIClient,
3065
- buildRequest: (model, context, options, metadata, replayMode) => {
3066
- const deploymentName = resolveAzureDeploymentNameFromMap({
3067
- modelId: model.id,
3068
- deploymentMap: process.env.AZURE_OPENAI_DEPLOYMENT_NAME_MAP
3069
- });
3070
- const params = buildOpenAIResponsesParams(model, context, options, metadata, replayMode);
3071
- params.model = deploymentName;
3072
- delete params.store;
3073
- return params;
3074
- }
3075
- });
3076
- }
3077
- function createAzureOpenAIClient(model, apiKey, defaultHeaders, fetchOverride) {
3078
- const baseURL = model.baseUrl.replace(/\/+$/, "");
3079
- const clientOptions = {
3080
- apiKey,
3081
- dangerouslyAllowBrowser: true,
3082
- defaultHeaders,
3083
- baseURL,
3084
- fetch: fetchOverride ?? buildGuardedModelFetch(model),
3085
- ...buildOpenAISdkClientOptions(model)
3086
- };
3087
- if (isOpenAICompatibleAzureResponsesBaseUrl(baseURL)) return new OpenAI(clientOptions);
3088
- return new AzureOpenAI({
3089
- ...clientOptions,
3090
- apiVersion: resolveAzureOpenAIApiVersion()
3091
- });
3092
- }
3093
- //#endregion
3094
- //#region packages/ai/src/transports/openai-completions-transport.ts
3095
- function assertOpenAICompletionsPayloadHasConversationTurn(params, model) {
3096
- const messages = params.messages;
3097
- if (!Array.isArray(messages) || hasOpenAICompatibleConversationTurn(messages)) return;
3098
- throw new Error(`OpenAI-compatible chat payload for ${model.provider}/${model.id} contains no non-empty user or assistant messages after compaction and transport transforms; refusing to send a system/tool-only request. Start a new user turn or repair the compacted session history.`);
3099
- }
3100
- const SSE_DONE_LINE_RE = /^data:[ \t]*\[DONE\][ \t]*$/i;
3101
- const SSE_DONE_MAX_LINE_CHARS = 1024;
3102
- function createSseDoneDetector() {
3103
- const decoder = new TextDecoder();
3104
- let line = "";
3105
- let lineOverflowed = false;
3106
- let sawDone = false;
3107
- const finishLine = () => {
3108
- if (!lineOverflowed && SSE_DONE_LINE_RE.test(line)) sawDone = true;
3109
- line = "";
3110
- lineOverflowed = false;
3111
- };
3112
- const observeText = (text) => {
3113
- for (const char of text) {
3114
- if (char === "\n" || char === "\r") {
3115
- finishLine();
3116
- continue;
3117
- }
3118
- if (!lineOverflowed && line.length < SSE_DONE_MAX_LINE_CHARS) line += char;
3119
- else lineOverflowed = true;
3120
- }
3121
- };
3122
- return {
3123
- observe(chunk) {
3124
- if (!sawDone) observeText(decoder.decode(chunk, { stream: true }));
3125
- },
3126
- finish() {
3127
- if (sawDone) return;
3128
- observeText(decoder.decode());
3129
- if (line || lineOverflowed) finishLine();
3130
- },
3131
- sawDone: () => sawDone
3132
- };
3133
- }
3134
- function buildOpenAICompletionsClientConfig(model, headers) {
3135
- const defaultQuery = {};
3136
- let baseURL = model.baseUrl;
3137
- let isAzureHost = false;
3138
- const parsed = URL.parse(model.baseUrl);
3139
- if (parsed) {
3140
- isAzureHost = isAzureOpenAICompatibleHost(parsed.hostname.toLowerCase());
3141
- parsed.searchParams.forEach((value, key) => {
3142
- if (value) defaultQuery[key] = value;
3143
- });
3144
- parsed.search = "";
3145
- baseURL = parsed.toString().replace(/\/$/, "");
3146
- }
3147
- if (isAzureHost) {
3148
- const apiVersionHeader = Object.keys(headers).find((key) => key.toLowerCase() === "api-version");
3149
- if (apiVersionHeader) {
3150
- const apiVersion = headers[apiVersionHeader]?.trim();
3151
- delete headers[apiVersionHeader];
3152
- if (apiVersion && !defaultQuery["api-version"]) defaultQuery["api-version"] = apiVersion;
3153
- }
3154
- }
3155
- return {
3156
- baseURL: resolveOpenAIClientBaseUrl(model, baseURL),
3157
- defaultHeaders: headers,
3158
- defaultQuery: Object.keys(defaultQuery).length > 0 ? defaultQuery : void 0
3159
- };
3160
- }
3161
- function createDirectCompletionsEventStream(output, stream) {
3162
- const finishedBlocks = /* @__PURE__ */ new Set();
3163
- const contentIndices = /* @__PURE__ */ new WeakMap();
3164
- let openTextBlock;
3165
- let openThinkingBlock;
3166
- const finishBlock = (block) => {
3167
- const contentIndex = contentIndices.get(block);
3168
- if (contentIndex === void 0 || finishedBlocks.has(block)) return;
3169
- finishedBlocks.add(block);
3170
- if (block.type === "text") {
3171
- openTextBlock = void 0;
3172
- stream.push({
3173
- type: "text_end",
3174
- contentIndex,
3175
- content: block.text,
3176
- partial: output
3177
- });
3178
- } else if (block.type === "thinking") {
3179
- openThinkingBlock = void 0;
3180
- stream.push({
3181
- type: "thinking_end",
3182
- contentIndex,
3183
- content: block.thinking,
3184
- partial: output
3185
- });
3186
- } else if (block.type === "toolCall") stream.push({
3187
- type: "toolcall_end",
3188
- contentIndex,
3189
- toolCall: block,
3190
- partial: output
3191
- });
3192
- };
3193
- return {
3194
- stream: { push(event) {
3195
- if (event.type === "text_start" || event.type === "thinking_start" || event.type === "toolcall_start") {
3196
- const block = output.content[event.contentIndex];
3197
- if (block) {
3198
- contentIndices.set(block, event.contentIndex);
3199
- if (block.type === "text") openTextBlock = block;
3200
- else if (block.type === "thinking") openThinkingBlock = block;
3201
- }
3202
- }
3203
- stream.push(event);
3204
- } },
3205
- beforeContentBlock: (nextType) => {
3206
- if (openThinkingBlock) finishBlock(openThinkingBlock);
3207
- if (openTextBlock && nextType !== "toolCall") finishBlock(openTextBlock);
3208
- },
3209
- finish(includeToolCalls) {
3210
- for (const block of output.content) if (block.type !== "toolCall" || includeToolCalls) finishBlock(block);
3211
- }
3212
- };
3213
- }
3214
- function createOpenAICompletionsTransportStreamFn() {
3215
- const streamResponses = createOpenAIResponsesTransportStreamFn();
3216
- return (model, context, options) => {
3217
- const completionsOptions = options;
3218
- if (model.reasoning && context.tools?.length && supportsModelTools(model) && isNativeOpenAIEndpoint(model)) {
3219
- const toolChoice = completionsOptions?.toolChoice;
3220
- const responsesOptions = {
3221
- ...options,
3222
- ...completionsOptions?.reasoning === void 0 && completionsOptions?.reasoningEffort === void 0 ? { reasoningEffort: "high" } : {},
3223
- ...toolChoice && typeof toolChoice === "object" ? { toolChoice: toOpenAIResponsesToolChoice(toolChoice) } : {}
3224
- };
3225
- return streamResponses(getAiTransportHost().inheritManagedTransport(model, {
3226
- ...model,
3227
- api: "openai-responses"
3228
- }), context, responsesOptions);
3229
- }
3230
- return streamOpenAICompletionsRequest(model, context, completionsOptions, "managed");
3231
- };
3232
- }
3233
- function streamOpenAICompletionsRequest(model, context, options, mode) {
3234
- const { eventStream, stream } = createWritableTransportEventStream();
3235
- (async () => {
3236
- const output = createAssistantOutput(model);
3237
- let discardCandidate = false;
3238
- let firstEventAbort;
3239
- try {
3240
- const apiKey = options?.apiKey || getEnvApiKey(model.provider) || "";
3241
- const directEmitReasoning = Boolean(mode === "direct" && model.reasoning && options?.reasoningEffort && isOpenAICompletionsThinkingEnabled(options.reasoningEffort));
3242
- const cacheRetention = resolveCacheRetention(options?.cacheRetention);
3243
- const policy = mode === "direct" ? {
3244
- mode,
3245
- compat: resolveOpenAICompletionsCompat(model),
3246
- cacheRetention
3247
- } : { mode };
3248
- const { client, sawStreamDONE } = policy.mode === "direct" ? {
3249
- client: createDirectCompletionsClient(model, context, apiKey, options, cacheRetention === "none" ? void 0 : options?.sessionId, policy.compat),
3250
- sawStreamDONE: void 0
3251
- } : createManagedCompletionsClient(model, context, options, apiKey, cacheRetention);
3252
- const builtParams = buildOpenAICompletionsRequest(model, context, options, policy);
3253
- let params = builtParams;
3254
- const encodeBody = prepareModelRequestBody(options);
3255
- const nextParams = await options?.onPayload?.(params, model);
3256
- if (nextParams !== void 0) params = nextParams;
3257
- if (mode === "managed") {
3258
- if (options?.openclawCodeModeToolSurface === true) {
3259
- const visibleToolNames = resolveCodeModeResponsesVisibleToolNames(context);
3260
- enforceCodeModeResponsesToolSurface(params, visibleToolNames, void 0, codeModeToolSurfaceObserver.get(options));
3261
- assertCodeModeResponsesToolSurface(params, visibleToolNames);
3262
- }
3263
- if (getCompat(model).requiresNonEmptyUserOrAssistantMessage) assertOpenAICompletionsPayloadHasConversationTurn(params, model);
3264
- }
3265
- const contextOutputBudget = resolveCompletionsContextOutputBudget(builtParams, params);
3266
- const emitReasoning = mode === "direct" ? directEmitReasoning : shouldEmitOpenAICompletionsReasoning(model, options);
3267
- firstEventAbort = createFirstStreamEventAbortController(options?.signal);
3268
- const requestOptions = mode === "direct" ? {
3269
- ...await encodeBody(params),
3270
- signal: firstEventAbort.signal,
3271
- ...options?.timeoutMs !== void 0 ? { timeout: options.timeoutMs } : {},
3272
- maxRetries: 0
3273
- } : {
3274
- ...buildOpenAISdkRequestOptions(model, firstEventAbort.signal, { timeoutMs: options?.timeoutMs }),
3275
- ...await encodeBody(params)
3276
- };
3277
- const request = client.chat.completions.create(params, requestOptions);
3278
- const response = await request.asResponse();
3279
- const hookedResponseStream = withProviderResponseHook({
3280
- stream: { async *[Symbol.asyncIterator]() {
3281
- if (!params.stream) {
3282
- yield await boundResponseBody(response, {
3283
- maxBytes: 16777216,
3284
- onOverflow: ({ maxBytes }) => /* @__PURE__ */ new Error(`Chat Completions JSON response exceeds ${maxBytes} bytes`)
3285
- }).json();
3286
- return;
3287
- }
3288
- const data = await request;
3289
- if (Symbol.asyncIterator in data) yield* data;
3290
- else yield data;
3291
- } },
3292
- signal: firstEventAbort.signal,
3293
- abort: firstEventAbort.abort,
3294
- hook: createOpenAIProviderAcceptanceHook(options, response, model),
3295
- onReady: () => {
3296
- if (contextOutputBudget === void 0) stream.push({
3297
- type: "start",
3298
- partial: output
3299
- });
3300
- }
3301
- });
3302
- const providerStream = observeOpenAICompletionsProgress(withFirstStreamEventTimeout(hookedResponseStream, {
3303
- provider: model.provider,
3304
- api: model.api,
3305
- model: model.id,
3306
- timeoutMs: getFirstStreamEventTimeoutMs(options) ?? 0,
3307
- stage: "completions",
3308
- abort: firstEventAbort.abort,
3309
- onTimeout: getFirstStreamEventTimeoutHandler(options),
3310
- hint: "The provider may be stalled while parsing the tool payload; retry with a smaller tool surface or enable OPENCLAW_DEBUG_MODEL_PAYLOAD=tools to inspect exposed tools."
3311
- }), options?.signal);
3312
- const buffered = contextOutputBudget === void 0 ? void 0 : await bufferContextLimitedCompletions(providerStream, options?.signal);
3313
- discardCandidate = Boolean(buffered?.bounded && (buffered.failed || buffered.finishReason === "length"));
3314
- if (buffered && !discardCandidate) stream.push({
3315
- type: "start",
3316
- partial: output
3317
- });
3318
- const directEvents = mode === "direct" ? createDirectCompletionsEventStream(output, stream) : void 0;
3319
- try {
3320
- await processCompletionsStream(buffered?.stream ?? providerStream, output, model, discardCandidate ? { push() {} } : directEvents?.stream ?? stream, {
3321
- ...directEvents ? {
3322
- mode: "direct",
3323
- beforeContentBlock: directEvents.beforeContentBlock
3324
- } : { mode: "managed" },
3325
- signal: discardCandidate ? void 0 : options?.signal,
3326
- emitReasoning,
3327
- strictReasoningTags: reasoningTagTextPolicy.isStrict(options),
3328
- sawStreamDONE
3329
- });
3330
- if (discardCandidate) throw new Error(`Context length exceeded: automatic output budget of ${contextOutputBudget} tokens exhausted before completion.`);
3331
- if (directEvents) {
3332
- if (options?.signal?.aborted) throw transportAbortError(options.signal);
3333
- if (output.stopReason === "aborted" || output.stopReason === "error") throw new Error(output.errorMessage || (output.stopReason === "aborted" ? "Request was aborted" : "Provider returned an invalid tool call"));
3334
- }
3335
- } catch (error) {
3336
- directEvents?.finish(false);
3337
- throw error;
3338
- }
3339
- directEvents?.finish(output.stopReason === "toolUse");
3340
- finalizeTransportStream({
3341
- stream,
3342
- output,
3343
- signal: options?.signal
3344
- });
3345
- } catch (error) {
3346
- if (discardCandidate) output.content = [];
3347
- failTransportStream({
3348
- stream,
3349
- output,
3350
- signal: options?.signal,
3351
- error,
3352
- cleanup: () => {
3353
- finalizeOpenAICompletionsToolCalls(output, { allowSilentToolCallPromotion: false });
3354
- if (mode === "direct") for (const block of output.content) {
3355
- delete block.index;
3356
- if (block.type === "toolCall") delete block.partialJson;
3357
- delete block.streamIndex;
3358
- }
3359
- }
3360
- });
3361
- } finally {
3362
- firstEventAbort?.dispose();
3363
- }
3364
- })();
3365
- return eventStream;
3366
- }
3367
- function createDirectCompletionsClient(model, context, apiKey, options, sessionId, compat) {
3368
- if (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);
3369
- const headers = { ...model.headers };
3370
- if (model.provider === "github-copilot") Object.assign(headers, buildCopilotDynamicHeaders(context.messages));
3371
- if (sessionId && compat.sessionAffinity !== "none") {
3372
- if (compat.sessionAffinity === "openrouter") headers["x-session-id"] = sessionId;
3373
- else {
3374
- headers.session_id = sessionId;
3375
- headers["x-client-request-id"] = sessionId;
3376
- headers["x-session-affinity"] = sessionId;
3377
- }
3378
- }
3379
- return createOpenAIProviderClient(model, apiKey, headers, resolveProviderSimpleCompletionHeaders(model, options), options?.onResponse);
3380
- }
3381
- function createManagedCompletionsClient(model, context, options, apiKey, cacheRetention) {
3382
- const turnState = resolveProviderTransportTurnState(model, {
3383
- sessionId: options?.sessionId,
3384
- turnId: randomUUID(),
3385
- attempt: 1,
3386
- transport: "stream"
3387
- });
3388
- const optionHeaders = resolveOpencodeSessionHeaders(model, options);
3389
- const turnHeaders = filterProviderTurnHeadersForExplicitOpencodeSession(model, options, turnState?.headers);
3390
- const doneDetector = createSseDoneDetector();
3391
- const baseFetch = withOpenAIErrorResponseHook(buildGuardedModelFetch(model, void 0, { onSseComment: () => notifyLlmRequestActivity(options?.signal, false) }), options?.onResponse, model);
3392
- const doneDetectingFetch = async (url, init) => {
3393
- const response = await baseFetch(url, init);
3394
- if (!response.body || !response.ok) return response;
3395
- if (typeof TransformStream === "undefined" || !response.body.pipeThrough) return response;
3396
- const transformed = response.body.pipeThrough(new TransformStream({
3397
- transform(chunk, controller) {
3398
- doneDetector.observe(chunk);
3399
- controller.enqueue(chunk);
3400
- },
3401
- flush() {
3402
- doneDetector.finish();
3403
- }
3404
- }));
3405
- return new Response(transformed, response);
3406
- };
3407
- const clientConfig = buildOpenAICompletionsClientConfig(model, buildOpenAIClientHeaders(model, context, {
3408
- ...turnHeaders,
3409
- ...optionHeaders
3410
- }, void 0, resolvePromptCacheKey(options, cacheRetention), cacheRetention));
3411
- return {
3412
- client: new OpenAI({
3413
- apiKey,
3414
- baseURL: clientConfig.baseURL,
3415
- dangerouslyAllowBrowser: true,
3416
- defaultHeaders: clientConfig.defaultHeaders,
3417
- defaultQuery: clientConfig.defaultQuery,
3418
- fetch: doneDetectingFetch,
3419
- ...buildOpenAISdkClientOptions(model)
3420
- }),
3421
- sawStreamDONE: doneDetector.sawDone
3422
- };
3423
- }
3424
- //#endregion
3425
- export { hasResponsesWebSearchTool as a, flattenCompletionMessagesToStringContent as c, hasOpenAICompatibleConversationTurn as d, canonicalizeMaxTokensParam as f, createOpenAIResponsesTransportStreamFn as i, stripCompletionMessagesToRoleContent as l, createDeepSeekTextFilter as m, streamOpenAICompletionsRequest as n, buildOpenAICompletionsParams as o, resolveMaxTokensParam as p, createAzureOpenAIResponsesTransportStreamFn as r, convertMessages as s, createOpenAICompletionsTransportStreamFn as t, applyCompletionsAnthropicCacheControl as u };