@code-yeongyu/senpi-ai 2026.7.25-2 → 2026.7.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/anthropic-messages.d.ts.map +1 -1
- package/dist/api/anthropic-messages.js +135 -16
- package/dist/api/anthropic-messages.js.map +1 -1
- package/dist/api/azure-openai-responses.js +1 -1
- package/dist/api/azure-openai-responses.js.map +1 -1
- package/dist/api/bedrock-converse-stream.d.ts.map +1 -1
- package/dist/api/bedrock-converse-stream.js +1 -4
- package/dist/api/bedrock-converse-stream.js.map +1 -1
- package/dist/api/google-shared.d.ts.map +1 -1
- package/dist/api/google-shared.js +4 -3
- package/dist/api/google-shared.js.map +1 -1
- package/dist/api/openai-codex-responses.js +2 -2
- package/dist/api/openai-codex-responses.js.map +1 -1
- package/dist/api/openai-responses-shared.d.ts +1 -0
- package/dist/api/openai-responses-shared.d.ts.map +1 -1
- package/dist/api/openai-responses-shared.js +67 -31
- package/dist/api/openai-responses-shared.js.map +1 -1
- package/dist/api/openai-responses.js +1 -1
- package/dist/api/openai-responses.js.map +1 -1
- package/dist/providers/data/.manifest.json +1 -1
- package/dist/providers/data/openrouter.json +1 -1
- package/dist/utils/retry.d.ts.map +1 -1
- package/dist/utils/retry.js +10 -0
- package/dist/utils/retry.js.map +1 -1
- package/dist/utils/stop-details.d.ts +1 -1
- package/dist/utils/stop-details.d.ts.map +1 -1
- package/dist/utils/stop-details.js +7 -3
- package/dist/utils/stop-details.js.map +1 -1
- package/dist/utils/tool-call-id.d.ts +9 -0
- package/dist/utils/tool-call-id.d.ts.map +1 -0
- package/dist/utils/tool-call-id.js +16 -0
- package/dist/utils/tool-call-id.js.map +1 -0
- package/package.json +2 -2
|
@@ -33,6 +33,24 @@ function parseTextSignature(signature) {
|
|
|
33
33
|
}
|
|
34
34
|
return { id: signature };
|
|
35
35
|
}
|
|
36
|
+
/**
|
|
37
|
+
* Parse a persisted reasoning-item signature, rejecting anything that is not a
|
|
38
|
+
* genuine Responses reasoning item. Foreign providers store non-JSON markers
|
|
39
|
+
* (Kimi's "reasoning_content") or opaque payloads (Anthropic signatures) in
|
|
40
|
+
* the same field; an unguarded JSON.parse turns a provenance mix-up into a
|
|
41
|
+
* client-side throw, and blindly pushing the parsed value leaks invalid items.
|
|
42
|
+
*/
|
|
43
|
+
function parseReasoningSignature(signature) {
|
|
44
|
+
if (!signature)
|
|
45
|
+
return undefined;
|
|
46
|
+
try {
|
|
47
|
+
const parsed = JSON.parse(signature);
|
|
48
|
+
return parsed?.type === "reasoning" ? parsed : undefined;
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
36
54
|
function convertToolResultOutput(model, content) {
|
|
37
55
|
const textResult = content
|
|
38
56
|
.filter((c) => c.type === "text")
|
|
@@ -56,6 +74,7 @@ function convertToolResultOutput(model, content) {
|
|
|
56
74
|
}
|
|
57
75
|
return output;
|
|
58
76
|
}
|
|
77
|
+
export const CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL = "custom";
|
|
59
78
|
function isResponseCustomToolCallItem(item) {
|
|
60
79
|
return item.type === "custom_tool_call";
|
|
61
80
|
}
|
|
@@ -108,12 +127,15 @@ export function convertResponsesMessages(model, context, allowedToolCallProvider
|
|
|
108
127
|
return normalized.length > 64 ? normalized.slice(0, 64) : normalized;
|
|
109
128
|
};
|
|
110
129
|
const normalizeToolCallId = (id, _targetModel, source) => {
|
|
111
|
-
if (!allowedToolCallProviders.has(model.provider))
|
|
112
|
-
return normalizeIdPart(id);
|
|
113
130
|
if (!id.includes("|"))
|
|
114
131
|
return normalizeIdPart(id);
|
|
115
132
|
const [callId, itemId] = id.split("|");
|
|
116
133
|
const normalizedCallId = normalizeIdPart(callId);
|
|
134
|
+
if (itemId === CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL) {
|
|
135
|
+
return `${normalizedCallId}|${CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL}`;
|
|
136
|
+
}
|
|
137
|
+
if (!allowedToolCallProviders.has(model.provider))
|
|
138
|
+
return normalizeIdPart(id);
|
|
117
139
|
const isForeignToolCall = source.provider !== model.provider || source.api !== model.api;
|
|
118
140
|
let normalizedItemId = isForeignToolCall ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId);
|
|
119
141
|
// OpenAI Responses API requires item id to start with "fc"
|
|
@@ -170,43 +192,56 @@ export function convertResponsesMessages(model, context, allowedToolCallProvider
|
|
|
170
192
|
assistantMsg.provider === model.provider &&
|
|
171
193
|
assistantMsg.api === model.api;
|
|
172
194
|
let textBlockIndex = 0;
|
|
195
|
+
const pushAssistantText = (text, textSignature) => {
|
|
196
|
+
const parsedSignature = parseTextSignature(textSignature);
|
|
197
|
+
const fallbackMessageId = textBlockIndex === 0 ? `msg_pi_${msgIndex}` : `msg_pi_${msgIndex}_${textBlockIndex}`;
|
|
198
|
+
textBlockIndex++;
|
|
199
|
+
// OpenAI requires id to be max 64 characters
|
|
200
|
+
let msgId = parsedSignature?.id;
|
|
201
|
+
if (!msgId) {
|
|
202
|
+
msgId = fallbackMessageId;
|
|
203
|
+
}
|
|
204
|
+
else if (msgId.length > 64) {
|
|
205
|
+
msgId = `msg_${shortHash(msgId)}`;
|
|
206
|
+
}
|
|
207
|
+
output.push({
|
|
208
|
+
type: "message",
|
|
209
|
+
role: "assistant",
|
|
210
|
+
content: [{ type: "output_text", text: sanitizeSurrogates(text), annotations: [] }],
|
|
211
|
+
status: "completed",
|
|
212
|
+
id: msgId,
|
|
213
|
+
phase: parsedSignature?.phase,
|
|
214
|
+
});
|
|
215
|
+
};
|
|
173
216
|
for (const block of msg.content) {
|
|
174
217
|
if (block.type === "thinking") {
|
|
175
|
-
|
|
176
|
-
|
|
218
|
+
const reasoningItem = parseReasoningSignature(block.thinkingSignature);
|
|
219
|
+
if (reasoningItem) {
|
|
177
220
|
output.push(reasoningItem);
|
|
178
221
|
}
|
|
222
|
+
else if (block.thinkingSignature && block.thinking.trim() !== "") {
|
|
223
|
+
// A signed thinking block whose signature is not a real reasoning
|
|
224
|
+
// item (foreign provenance or corrupted state): demote to plain
|
|
225
|
+
// text, mirroring the cross-model policy in transformMessages.
|
|
226
|
+
pushAssistantText(block.thinking);
|
|
227
|
+
}
|
|
228
|
+
// Signed foreign blocks with no text are intentionally dropped.
|
|
179
229
|
}
|
|
180
230
|
else if (block.type === "providerNative") {
|
|
181
231
|
}
|
|
182
232
|
else if (block.type === "text") {
|
|
183
233
|
const textBlock = block;
|
|
184
|
-
|
|
185
|
-
const fallbackMessageId = textBlockIndex === 0 ? `msg_pi_${msgIndex}` : `msg_pi_${msgIndex}_${textBlockIndex}`;
|
|
186
|
-
textBlockIndex++;
|
|
187
|
-
// OpenAI requires id to be max 64 characters
|
|
188
|
-
let msgId = parsedSignature?.id;
|
|
189
|
-
if (!msgId) {
|
|
190
|
-
msgId = fallbackMessageId;
|
|
191
|
-
}
|
|
192
|
-
else if (msgId.length > 64) {
|
|
193
|
-
msgId = `msg_${shortHash(msgId)}`;
|
|
194
|
-
}
|
|
195
|
-
output.push({
|
|
196
|
-
type: "message",
|
|
197
|
-
role: "assistant",
|
|
198
|
-
content: [{ type: "output_text", text: sanitizeSurrogates(textBlock.text), annotations: [] }],
|
|
199
|
-
status: "completed",
|
|
200
|
-
id: msgId,
|
|
201
|
-
phase: parsedSignature?.phase,
|
|
202
|
-
});
|
|
234
|
+
pushAssistantText(textBlock.text, textBlock.textSignature);
|
|
203
235
|
}
|
|
204
236
|
else if (block.type === "toolCall") {
|
|
205
237
|
const toolCall = block;
|
|
206
238
|
const [callId, itemIdRaw] = toolCall.id.split("|");
|
|
207
239
|
const customInputProperty = options?.grammarToolInputProperties?.get(toolCall.name);
|
|
208
|
-
const
|
|
209
|
-
|
|
240
|
+
const isPersistedFreeform = itemIdRaw === CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL;
|
|
241
|
+
const isFreeform = isFreeformToolName(toolCall.name, context.tools) || isPersistedFreeform;
|
|
242
|
+
let itemId = isPersistedFreeform ? undefined : itemIdRaw;
|
|
243
|
+
// An active grammar declaration wins over sentinel recovery below: its
|
|
244
|
+
// named input property is richer than the persisted freeform fallback.
|
|
210
245
|
// For different-model messages, set id to undefined to avoid pairing validation.
|
|
211
246
|
// OpenAI tracks which fc_xxx IDs were paired with rs_xxx reasoning items.
|
|
212
247
|
// By omitting the id, we avoid triggering that validation (like cross-provider does).
|
|
@@ -219,7 +254,7 @@ export function convertResponsesMessages(model, context, allowedToolCallProvider
|
|
|
219
254
|
if (customInputProperty !== undefined) {
|
|
220
255
|
output.push({
|
|
221
256
|
type: "custom_tool_call",
|
|
222
|
-
id: itemId,
|
|
257
|
+
...(itemId !== undefined ? { id: itemId } : {}),
|
|
223
258
|
call_id: callId,
|
|
224
259
|
name: toolCall.name,
|
|
225
260
|
input: sanitizeSurrogates(getGrammarToolInput(toolCall.name, toolCall.arguments, customInputProperty)),
|
|
@@ -249,9 +284,10 @@ export function convertResponsesMessages(model, context, allowedToolCallProvider
|
|
|
249
284
|
messages.push(...output.map((item) => withContextProvenance(item, msg, options?.sealContextProvenance)));
|
|
250
285
|
}
|
|
251
286
|
else if (msg.role === "toolResult") {
|
|
252
|
-
const [callId] = msg.toolCallId.split("|");
|
|
287
|
+
const [callId, itemIdRaw] = msg.toolCallId.split("|");
|
|
253
288
|
const output = convertToolResultOutput(model, msg.content);
|
|
254
289
|
const customInputProperty = options?.grammarToolInputProperties?.get(msg.toolName);
|
|
290
|
+
const isPersistedFreeform = itemIdRaw === CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL;
|
|
255
291
|
if (customInputProperty !== undefined) {
|
|
256
292
|
messages.push(withContextProvenance({
|
|
257
293
|
type: "custom_tool_call_output",
|
|
@@ -259,7 +295,7 @@ export function convertResponsesMessages(model, context, allowedToolCallProvider
|
|
|
259
295
|
output,
|
|
260
296
|
}, msg, options?.sealContextProvenance));
|
|
261
297
|
}
|
|
262
|
-
else if (isFreeformToolName(msg.toolName, context.tools)) {
|
|
298
|
+
else if (isFreeformToolName(msg.toolName, context.tools) || isPersistedFreeform) {
|
|
263
299
|
messages.push(withContextProvenance({
|
|
264
300
|
type: "custom_tool_call_output",
|
|
265
301
|
call_id: callId,
|
|
@@ -426,7 +462,7 @@ export async function processResponsesStream(openaiStream, output, stream, model
|
|
|
426
462
|
const input = item.input || "";
|
|
427
463
|
const block = {
|
|
428
464
|
type: "toolCall",
|
|
429
|
-
id: `${item.call_id}|${item.id ??
|
|
465
|
+
id: `${item.call_id}|${item.id ?? CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL}`,
|
|
430
466
|
name: item.name,
|
|
431
467
|
arguments: { [inputProperty]: input },
|
|
432
468
|
customInput: {
|
|
@@ -468,8 +504,8 @@ export async function processResponsesStream(openaiStream, output, stream, model
|
|
|
468
504
|
const block = reasoningBlocksById.get(item.id);
|
|
469
505
|
if (!block?.thinkingSignature)
|
|
470
506
|
continue;
|
|
471
|
-
const storedItem =
|
|
472
|
-
if (storedItem.encrypted_content)
|
|
507
|
+
const storedItem = parseReasoningSignature(block.thinkingSignature);
|
|
508
|
+
if (!storedItem || storedItem.encrypted_content)
|
|
473
509
|
continue;
|
|
474
510
|
block.thinkingSignature = JSON.stringify({
|
|
475
511
|
...storedItem,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-responses-shared.js","sourceRoot":"","sources":["../../src/api/openai-responses-shared.ts"],"names":[],"mappings":"AAgBA,OAAO,EACN,wBAAwB,EAExB,4BAA4B,EAC5B,oBAAoB,GACpB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAiB7C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EACN,+BAA+B,EAE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AK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,UAAU,IAAI,CAAC,CAAC,aAAa,IAAI,KAAK,CAAC,CAAC,CAAC;IACpH,IAAI,CAAC,wBAAwB,IAAI,CAAC,oBAAoB,EAAE,CAAC;QACxD,MAAM,IAAI,KAAK,CAAC,gEAAgE,CAAC,CAAC;IACnF,CAAC;AACF,CAAC;AAED,SAAS,aAAa,CAAC,MAAmD;IACzE,IAAI,CAAC,MAAM;QAAE,OAAO,MAAM,CAAC;IAC3B,QAAQ,MAAM,EAAE,CAAC;QAChB,KAAK,WAAW;YACf,OAAO,MAAM,CAAC;QACf,KAAK,YAAY;YAChB,OAAO,QAAQ,CAAC;QACjB,KAAK,QAAQ,CAAC;QACd,KAAK,WAAW;YACf,OAAO,OAAO,CAAC;QAChB,0BAA0B;QAC1B,KAAK,aAAa,CAAC;QACnB,KAAK,QAAQ;YACZ,OAAO,MAAM,CAAC;QACf,SAAS,CAAC;YACT,MAAM,WAAW,GAAU,MAAM,CAAC;YAClC,MAAM,IAAI,KAAK,CAAC,0BAA0B,WAAW,EAAE,CAAC,CAAC;QAC1D,CAAC;IACF,CAAC;AACF,CAAC","sourcesContent":["import type OpenAI from \"openai\";\nimport type {\n\tResponseInputItem as OpenAIResponseInputItem,\n\tTool as OpenAITool,\n\tResponseCreateParamsStreaming,\n\tResponseFunctionCallOutputItemList,\n\tResponseInput,\n\tResponseInputContent,\n\tResponseInputImage,\n\tResponseInputText,\n\tResponseOutputItem,\n\tResponseOutputMessage,\n\tResponseReasoningItem,\n\tResponseStreamEvent,\n\tResponseToolSearchOutputItemParam,\n} from \"openai/resources/responses/responses.js\";\nimport {\n\tCONTEXT_PROVENANCE_FIELD,\n\ttype ContextProvenance,\n\tcontextProvenanceFingerprint,\n\tgetContextProvenance,\n} from \"../context-provenance.ts\";\nimport { calculateCost } from \"../models.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tImageContent,\n\tModel,\n\tProviderNativeContent,\n\tStopReason,\n\tTextContent,\n\tTextSignatureV1,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n\tUsage,\n} from \"../types.ts\";\nimport type { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { parseStreamingJson } from \"../utils/json-parse.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport {\n\tappendGrammarToolInputJsonDelta,\n\ttype GrammarToolInputJsonBuffer,\n\tgetGrammarToolInput,\n\tresolveGrammarConstrainedSampling,\n\tresolveJsonSchemaStrictSampling,\n} from \"./constrained-sampling.ts\";\nimport { transformMessages } from \"./transform-messages.ts\";\n\n// =============================================================================\n// Utilities\n// =============================================================================\n\nfunction encodeTextSignatureV1(id: string, phase?: TextSignatureV1[\"phase\"]): string {\n\tconst payload: TextSignatureV1 = { v: 1, id };\n\tif (phase) payload.phase = phase;\n\treturn JSON.stringify(payload);\n}\n\nfunction parseTextSignature(\n\tsignature: string | undefined,\n): { id: string; phase?: TextSignatureV1[\"phase\"] } | undefined {\n\tif (!signature) return undefined;\n\tif (signature.startsWith(\"{\")) {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(signature) as Partial<TextSignatureV1>;\n\t\t\tif (parsed.v === 1 && typeof parsed.id === \"string\") {\n\t\t\t\tif (parsed.phase === \"commentary\" || parsed.phase === \"final_answer\") {\n\t\t\t\t\treturn { id: parsed.id, phase: parsed.phase };\n\t\t\t\t}\n\t\t\t\treturn { id: parsed.id };\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through to legacy plain-string handling.\n\t\t}\n\t}\n\treturn { id: signature };\n}\n\ntype ToolResultOutputContent = Array<ResponseInputText | ResponseInputImage>;\n\nfunction convertToolResultOutput<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontent: readonly (TextContent | ImageContent)[],\n): string | ToolResultOutputContent {\n\tconst textResult = content\n\t\t.filter((c): c is TextContent => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\tconst images = content.filter((c): c is ImageContent => c.type === \"image\");\n\tconst hasText = textResult.length > 0;\n\n\tif (images.length === 0 || !model.input.includes(\"image\")) {\n\t\treturn sanitizeSurrogates(hasText ? textResult : images.length > 0 ? \"(see attached image)\" : \"(no tool output)\");\n\t}\n\n\tconst output: ToolResultOutputContent = [];\n\tif (hasText) {\n\t\toutput.push({ type: \"input_text\", text: sanitizeSurrogates(textResult) });\n\t}\n\tfor (const image of images) {\n\t\toutput.push({\n\t\t\ttype: \"input_image\",\n\t\t\tdetail: \"auto\",\n\t\t\timage_url: `data:${image.mimeType};base64,${image.data}`,\n\t\t});\n\t}\n\treturn output;\n}\n\nexport interface OpenAIResponsesStreamOptions {\n\tserviceTier?: ResponseCreateParamsStreaming[\"service_tier\"];\n\tgrammarToolInputProperties?: ReadonlyMap<string, string>;\n\tresolveServiceTier?: (\n\t\tresponseServiceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\t\trequestServiceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\t) => ResponseCreateParamsStreaming[\"service_tier\"] | undefined;\n\tapplyServiceTierPricing?: (\n\t\tusage: Usage,\n\t\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\t) => void;\n}\n\nexport interface ConvertResponsesMessagesOptions {\n\tincludeSystemPrompt?: boolean;\n\tpreserveThinking?: boolean;\n\tpreserveTextSignatures?: boolean;\n\tgrammarToolInputProperties?: ReadonlyMap<string, string>;\n\tdeferredTools?: ReadonlyMap<string, Tool>;\n\ttoolOptions?: ConvertResponsesToolsOptions;\n\t/** Internal request-local provenance sealing pass. Never serialized to provider payloads. */\n\tsealContextProvenance?: boolean;\n}\n\nexport interface ConvertResponsesToolsOptions {\n\tstrict?: boolean | null;\n\tsupportsStrictMode?: boolean;\n\tsupportsOpenAIGrammarTools?: boolean;\n\tdeferLoading?: boolean;\n}\n\ntype ResponseCustomToolCallItem = {\n\ttype: \"custom_tool_call\";\n\tid?: string;\n\tcall_id: string;\n\tname: string;\n\tinput?: string;\n};\n\ntype ResponseCustomToolCallOutputItem = {\n\ttype: \"custom_tool_call_output\";\n\tcall_id: string;\n\tname?: string;\n\toutput: string | ResponseFunctionCallOutputItemList;\n};\n\ntype ResponseInputItem = OpenAIResponseInputItem | ResponseCustomToolCallItem | ResponseCustomToolCallOutputItem;\n\ntype ResponseFunctionTool = Extract<OpenAITool, { type: \"function\" }>;\n\nfunction isResponseCustomToolCallItem(item: { type?: string }): item is ResponseCustomToolCallItem {\n\treturn item.type === \"custom_tool_call\";\n}\n\nfunction isFreeformTool(tool: Tool): boolean {\n\treturn tool.freeform !== undefined;\n}\n\nfunction isFreeformToolName(toolName: string, tools: Tool[] | undefined): boolean {\n\treturn tools?.some((tool) => tool.name === toolName && isFreeformTool(tool)) ?? false;\n}\n\nfunction getFreeformToolInput(argumentsValue: Record<string, unknown>): string {\n\treturn typeof argumentsValue.input === \"string\" ? argumentsValue.input : JSON.stringify(argumentsValue);\n}\n\nfunction contextProvenanceForInput(message: unknown, seal: boolean | undefined): ContextProvenance | undefined {\n\tconst provenance = getContextProvenance(message);\n\tif (!provenance) return undefined;\n\tconst fingerprint = contextProvenanceFingerprint(message);\n\tif (fingerprint === undefined) return undefined;\n\tconst stored = provenance.integrity;\n\tif (stored === undefined && seal) {\n\t\tprovenance.integrity = fingerprint;\n\t\treturn provenance;\n\t}\n\treturn stored === fingerprint ? provenance : undefined;\n}\n\nfunction withContextProvenance<T extends object>(item: T, message: unknown, seal: boolean | undefined): T {\n\tconst provenance = contextProvenanceForInput(message, seal);\n\tif (provenance) {\n\t\tObject.defineProperty(item, CONTEXT_PROVENANCE_FIELD, {\n\t\t\tvalue: provenance,\n\t\t\tenumerable: false,\n\t\t});\n\t}\n\treturn item;\n}\n// =============================================================================\n// Message conversion\n// =============================================================================\n\nexport function convertResponsesMessages<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\tallowedToolCallProviders: ReadonlySet<string>,\n\toptions?: ConvertResponsesMessagesOptions,\n): ResponseInput {\n\tconst messages: ResponseInputItem[] = [];\n\tconst loadedToolNames = new Set<string>();\n\n\tconst normalizeIdPart = (part: string): string => {\n\t\tconst sanitized = part.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n\t\tconst normalized = sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;\n\t\treturn normalized.replace(/_+$/, \"\");\n\t};\n\n\tconst buildForeignResponsesItemId = (itemId: string): string => {\n\t\tconst normalized = `fc_${shortHash(itemId)}`;\n\t\treturn normalized.length > 64 ? normalized.slice(0, 64) : normalized;\n\t};\n\n\tconst normalizeToolCallId = (id: string, _targetModel: Model<TApi>, source: AssistantMessage): string => {\n\t\tif (!allowedToolCallProviders.has(model.provider)) return normalizeIdPart(id);\n\t\tif (!id.includes(\"|\")) return normalizeIdPart(id);\n\t\tconst [callId, itemId] = id.split(\"|\");\n\t\tconst normalizedCallId = normalizeIdPart(callId);\n\t\tconst isForeignToolCall = source.provider !== model.provider || source.api !== model.api;\n\t\tlet normalizedItemId = isForeignToolCall ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId);\n\t\t// OpenAI Responses API requires item id to start with \"fc\"\n\t\tif (!normalizedItemId.startsWith(\"fc_\")) {\n\t\t\tnormalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);\n\t\t}\n\t\treturn `${normalizedCallId}|${normalizedItemId}`;\n\t};\n\n\tconst transformedMessages = transformMessages(context.messages, model, normalizeToolCallId, {\n\t\tpreserveThinking: options?.preserveThinking,\n\t\tpreserveTextSignatures: options?.preserveTextSignatures,\n\t});\n\n\tconst includeSystemPrompt = options?.includeSystemPrompt ?? true;\n\tif (includeSystemPrompt && context.systemPrompt) {\n\t\tconst compat = model.compat as { supportsDeveloperRole?: boolean } | undefined;\n\t\tconst role = model.reasoning && compat?.supportsDeveloperRole !== false ? \"developer\" : \"system\";\n\t\tmessages.push({\n\t\t\trole,\n\t\t\tcontent: sanitizeSurrogates(context.systemPrompt),\n\t\t});\n\t}\n\n\tlet msgIndex = 0;\n\tfor (const msg of transformedMessages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tmessages.push(\n\t\t\t\t\twithContextProvenance(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\t\tcontent: [{ type: \"input_text\", text: sanitizeSurrogates(msg.content) }],\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmsg,\n\t\t\t\t\t\toptions?.sealContextProvenance,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst content: ResponseInputContent[] = msg.content.map((item): ResponseInputContent => {\n\t\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"input_text\",\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(item.text),\n\t\t\t\t\t\t} satisfies ResponseInputText;\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\timage_url: `data:${item.mimeType};base64,${item.data}`,\n\t\t\t\t\t} satisfies ResponseInputImage;\n\t\t\t\t});\n\t\t\t\tif (content.length === 0) continue;\n\t\t\t\tmessages.push(withContextProvenance({ role: \"user\", content }, msg, options?.sealContextProvenance));\n\t\t\t}\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst output: ResponseInputItem[] = [];\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isDifferentModel =\n\t\t\t\tassistantMsg.model !== model.id &&\n\t\t\t\tassistantMsg.provider === model.provider &&\n\t\t\t\tassistantMsg.api === model.api;\n\t\t\tlet textBlockIndex = 0;\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\tif (block.thinkingSignature) {\n\t\t\t\t\t\tconst reasoningItem = JSON.parse(block.thinkingSignature) as ResponseReasoningItem;\n\t\t\t\t\t\toutput.push(reasoningItem);\n\t\t\t\t\t}\n\t\t\t\t} else if (block.type === \"providerNative\") {\n\t\t\t\t} else if (block.type === \"text\") {\n\t\t\t\t\tconst textBlock = block as TextContent;\n\t\t\t\t\tconst parsedSignature = parseTextSignature(textBlock.textSignature);\n\t\t\t\t\tconst fallbackMessageId =\n\t\t\t\t\t\ttextBlockIndex === 0 ? `msg_pi_${msgIndex}` : `msg_pi_${msgIndex}_${textBlockIndex}`;\n\t\t\t\t\ttextBlockIndex++;\n\t\t\t\t\t// OpenAI requires id to be max 64 characters\n\t\t\t\t\tlet msgId = parsedSignature?.id;\n\t\t\t\t\tif (!msgId) {\n\t\t\t\t\t\tmsgId = fallbackMessageId;\n\t\t\t\t\t} else if (msgId.length > 64) {\n\t\t\t\t\t\tmsgId = `msg_${shortHash(msgId)}`;\n\t\t\t\t\t}\n\t\t\t\t\toutput.push({\n\t\t\t\t\t\ttype: \"message\",\n\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\tcontent: [{ type: \"output_text\", text: sanitizeSurrogates(textBlock.text), annotations: [] }],\n\t\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\t\tid: msgId,\n\t\t\t\t\t\tphase: parsedSignature?.phase,\n\t\t\t\t\t} satisfies ResponseOutputMessage);\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tconst [callId, itemIdRaw] = toolCall.id.split(\"|\");\n\t\t\t\t\tconst customInputProperty = options?.grammarToolInputProperties?.get(toolCall.name);\n\t\t\t\t\tconst isFreeform = isFreeformToolName(toolCall.name, context.tools);\n\t\t\t\t\tlet itemId: string | undefined = itemIdRaw;\n\n\t\t\t\t\t// For different-model messages, set id to undefined to avoid pairing validation.\n\t\t\t\t\t// OpenAI tracks which fc_xxx IDs were paired with rs_xxx reasoning items.\n\t\t\t\t\t// By omitting the id, we avoid triggering that validation (like cross-provider does).\n\t\t\t\t\t// Function-call item ids must begin with fc_ while freeform calls can replay\n\t\t\t\t\t// without the local <call_id>|custom sentinel.\n\t\t\t\t\tif (\n\t\t\t\t\t\t(isDifferentModel && itemId?.startsWith(\"fc_\")) ||\n\t\t\t\t\t\t(!isFreeform && customInputProperty === undefined && !itemId?.startsWith(\"fc_\"))\n\t\t\t\t\t) {\n\t\t\t\t\t\titemId = undefined;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (customInputProperty !== undefined) {\n\t\t\t\t\t\toutput.push({\n\t\t\t\t\t\t\ttype: \"custom_tool_call\",\n\t\t\t\t\t\t\tid: itemId,\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\tname: toolCall.name,\n\t\t\t\t\t\t\tinput: sanitizeSurrogates(\n\t\t\t\t\t\t\t\tgetGrammarToolInput(toolCall.name, toolCall.arguments, customInputProperty),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t} satisfies ResponseCustomToolCallItem);\n\t\t\t\t\t} else if (isFreeform) {\n\t\t\t\t\t\toutput.push({\n\t\t\t\t\t\t\ttype: \"custom_tool_call\",\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\tname: toolCall.name,\n\t\t\t\t\t\t\tinput: getFreeformToolInput(toolCall.arguments),\n\t\t\t\t\t\t} satisfies ResponseCustomToolCallItem);\n\t\t\t\t\t} else {\n\t\t\t\t\t\toutput.push({\n\t\t\t\t\t\t\ttype: \"function_call\",\n\t\t\t\t\t\t\t...(itemId?.startsWith(\"fc_\") ? { id: itemId } : {}),\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\tname: toolCall.name,\n\t\t\t\t\t\t\targuments: JSON.stringify(toolCall.arguments),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (output.length === 0) continue;\n\t\t\tmessages.push(...output.map((item) => withContextProvenance(item, msg, options?.sealContextProvenance)));\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\tconst [callId] = msg.toolCallId.split(\"|\");\n\t\t\tconst output = convertToolResultOutput(model, msg.content);\n\t\t\tconst customInputProperty = options?.grammarToolInputProperties?.get(msg.toolName);\n\n\t\t\tif (customInputProperty !== undefined) {\n\t\t\t\tmessages.push(\n\t\t\t\t\twithContextProvenance(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"custom_tool_call_output\",\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\toutput,\n\t\t\t\t\t\t} satisfies ResponseCustomToolCallOutputItem,\n\t\t\t\t\t\tmsg,\n\t\t\t\t\t\toptions?.sealContextProvenance,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else if (isFreeformToolName(msg.toolName, context.tools)) {\n\t\t\t\tmessages.push(\n\t\t\t\t\twithContextProvenance(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"custom_tool_call_output\",\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\tname: msg.toolName,\n\t\t\t\t\t\t\toutput,\n\t\t\t\t\t\t} satisfies ResponseCustomToolCallOutputItem,\n\t\t\t\t\t\tmsg,\n\t\t\t\t\t\toptions?.sealContextProvenance,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tmessages.push(\n\t\t\t\t\twithContextProvenance(\n\t\t\t\t\t\t{ type: \"function_call_output\", call_id: callId, output },\n\t\t\t\t\t\tmsg,\n\t\t\t\t\t\toptions?.sealContextProvenance,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst deferredTools: Tool[] = [];\n\t\t\tfor (const name of msg.addedToolNames ?? []) {\n\t\t\t\tconst tool = options?.deferredTools?.get(name);\n\t\t\t\tif (!tool || loadedToolNames.has(name)) continue;\n\t\t\t\tloadedToolNames.add(name);\n\t\t\t\tdeferredTools.push(tool);\n\t\t\t}\n\t\t\tif (deferredTools.length > 0) {\n\t\t\t\tconst names = deferredTools.map((tool) => tool.name);\n\t\t\t\tconst searchCallId = `pi_tool_load_${shortHash(`${msg.toolCallId}:${names.join(\",\")}`)}`;\n\t\t\t\tmessages.push(\n\t\t\t\t\twithContextProvenance(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"tool_search_call\",\n\t\t\t\t\t\t\tcall_id: searchCallId,\n\t\t\t\t\t\t\texecution: \"client\",\n\t\t\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\t\t\targuments: { query: names.join(\" \"), limit: names.length },\n\t\t\t\t\t\t} satisfies ResponseInputItem,\n\t\t\t\t\t\tmsg,\n\t\t\t\t\t\toptions?.sealContextProvenance,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tmessages.push(\n\t\t\t\t\twithContextProvenance(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"tool_search_output\",\n\t\t\t\t\t\t\tcall_id: searchCallId,\n\t\t\t\t\t\t\texecution: \"client\",\n\t\t\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\t\t\ttools: convertResponsesTools(deferredTools, {\n\t\t\t\t\t\t\t\t...options?.toolOptions,\n\t\t\t\t\t\t\t\tdeferLoading: true,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t} satisfies ResponseToolSearchOutputItemParam,\n\t\t\t\t\t\tmsg,\n\t\t\t\t\t\toptions?.sealContextProvenance,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tmsgIndex++;\n\t}\n\n\treturn messages as ResponseInput;\n}\n\n// =============================================================================\n// Tool conversion\n// =============================================================================\n\nexport function convertResponsesTools(tools: readonly Tool[], options?: ConvertResponsesToolsOptions): OpenAITool[] {\n\tconst defaultStrict = options?.strict === undefined ? false : options.strict;\n\tconst supportsStrictMode = options?.supportsStrictMode ?? true;\n\tconst supportsOpenAIGrammarTools = options?.supportsOpenAIGrammarTools ?? false;\n\n\treturn tools.map((tool) => {\n\t\tconst grammar = resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools);\n\t\tif (grammar) {\n\t\t\treturn {\n\t\t\t\ttype: \"custom\",\n\t\t\t\tname: tool.name,\n\t\t\t\tdescription: tool.description,\n\t\t\t\tformat: {\n\t\t\t\t\ttype: \"grammar\",\n\t\t\t\t\tsyntax: grammar.format,\n\t\t\t\t\tdefinition: grammar.definition,\n\t\t\t\t},\n\t\t\t\t...(options?.deferLoading ? { defer_loading: true } : {}),\n\t\t\t} satisfies OpenAITool;\n\t\t}\n\t\tif (tool.freeform) {\n\t\t\treturn {\n\t\t\t\ttype: \"custom\",\n\t\t\t\tname: tool.name,\n\t\t\t\tdescription: tool.description,\n\t\t\t\tformat: tool.freeform,\n\t\t\t\t...(options?.deferLoading ? { defer_loading: true } : {}),\n\t\t\t} as OpenAITool;\n\t\t}\n\n\t\tconst constrainedStrict = resolveJsonSchemaStrictSampling(tool, supportsStrictMode);\n\t\tconst functionTool: Omit<ResponseFunctionTool, \"strict\"> & {\n\t\t\tstrict?: ResponseFunctionTool[\"strict\"];\n\t\t} = {\n\t\t\ttype: \"function\",\n\t\t\tname: tool.name,\n\t\t\tdescription: tool.description,\n\t\t\tparameters: tool.parameters as ResponseFunctionTool[\"parameters\"], // TypeBox already generates JSON Schema\n\t\t\t...(options?.deferLoading ? { defer_loading: true } : {}),\n\t\t};\n\t\tif (supportsStrictMode) {\n\t\t\tfunctionTool.strict = constrainedStrict ?? defaultStrict;\n\t\t}\n\t\treturn functionTool as OpenAITool;\n\t});\n}\n\n// =============================================================================\n// Stream processing\n// =============================================================================\n\ntype StreamingToolCall = ToolCall & {\n\tpartialJson?: string;\n\tcustomInput?: {\n\t\tproperty: string;\n\t\tjsonBuffer: GrammarToolInputJsonBuffer;\n\t};\n};\n\nfunction getCustomToolCallInput(block: StreamingToolCall): string {\n\tconst property = block.customInput?.property;\n\tif (property === undefined) return \"\";\n\tconst value = block.arguments[property];\n\treturn typeof value === \"string\" ? value : \"\";\n}\n\nfunction appendCustomToolCallInput(block: StreamingToolCall, nextInput: string, close: boolean): string | undefined {\n\tconst customInput = block.customInput;\n\tif (!customInput) return undefined;\n\tconst delta = appendGrammarToolInputJsonDelta(customInput.jsonBuffer, customInput.property, nextInput, close);\n\tblock.arguments = { [customInput.property]: nextInput };\n\treturn delta;\n}\n\ntype ResponsesOutputSlot =\n\t| { type: \"thinking\"; block: ThinkingContent; contentIndex: number }\n\t| { type: \"text\"; block: TextContent; contentIndex: number }\n\t| { type: \"toolCall\"; block: StreamingToolCall; contentIndex: number }\n\t| { type: \"providerNative\"; block: ProviderNativeContent; contentIndex: number };\n\ntype ToolCallOutputSlot = Extract<ResponsesOutputSlot, { type: \"toolCall\" }>;\n\nexport async function processResponsesStream<TApi extends Api>(\n\topenaiStream: AsyncIterable<ResponseStreamEvent>,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tmodel: Model<TApi>,\n\toptions?: OpenAIResponsesStreamOptions,\n): Promise<void> {\n\tlet sawTerminalResponseEvent = false;\n\tconst outputSlots = new Map<number, ResponsesOutputSlot>();\n\tconst reasoningBlocksById = new Map<string, ThinkingContent>();\n\tconst getSlot = <TType extends ResponsesOutputSlot[\"type\"]>(\n\t\toutputIndex: number,\n\t\ttype: TType,\n\t): Extract<ResponsesOutputSlot, { type: TType }> | undefined => {\n\t\tconst slot = outputSlots.get(outputIndex);\n\t\treturn slot?.type === type ? (slot as Extract<ResponsesOutputSlot, { type: TType }>) : undefined;\n\t};\n\tconst pushToolCallDelta = (slot: ToolCallOutputSlot, delta: string | undefined): void => {\n\t\tif (delta === undefined) return;\n\t\tstream.push({\n\t\t\ttype: \"toolcall_delta\",\n\t\t\tcontentIndex: slot.contentIndex,\n\t\t\tdelta,\n\t\t\tpartial: output,\n\t\t});\n\t};\n\tconst createSlot = (\n\t\toutputIndex: number,\n\t\titem: ResponseOutputItem | ResponseCustomToolCallItem,\n\t): ResponsesOutputSlot | undefined => {\n\t\tif (item.type === \"reasoning\") {\n\t\t\tconst block: ThinkingContent = { type: \"thinking\", thinking: \"\" };\n\t\t\toutput.content.push(block);\n\t\t\tconst slot = {\n\t\t\t\ttype: \"thinking\",\n\t\t\t\tblock,\n\t\t\t\tcontentIndex: output.content.length - 1,\n\t\t\t} satisfies ResponsesOutputSlot;\n\t\t\toutputSlots.set(outputIndex, slot);\n\t\t\tstream.push({ type: \"thinking_start\", contentIndex: slot.contentIndex, partial: output });\n\t\t\treturn slot;\n\t\t}\n\t\tif (item.type === \"message\") {\n\t\t\tconst block: TextContent = { type: \"text\", text: \"\" };\n\t\t\toutput.content.push(block);\n\t\t\tconst slot = { type: \"text\", block, contentIndex: output.content.length - 1 } satisfies ResponsesOutputSlot;\n\t\t\toutputSlots.set(outputIndex, slot);\n\t\t\tstream.push({ type: \"text_start\", contentIndex: slot.contentIndex, partial: output });\n\t\t\treturn slot;\n\t\t}\n\t\tif (item.type === \"function_call\") {\n\t\t\tconst block: StreamingToolCall = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: `${item.call_id}|${item.id}`,\n\t\t\t\tname: item.name,\n\t\t\t\targuments: {},\n\t\t\t\tpartialJson: item.arguments || \"\",\n\t\t\t};\n\t\t\toutput.content.push(block);\n\t\t\tconst slot = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tblock,\n\t\t\t\tcontentIndex: output.content.length - 1,\n\t\t\t} satisfies ResponsesOutputSlot;\n\t\t\toutputSlots.set(outputIndex, slot);\n\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: slot.contentIndex, partial: output });\n\t\t\treturn slot;\n\t\t}\n\t\tif (isResponseCustomToolCallItem(item)) {\n\t\t\tconst inputProperty = options?.grammarToolInputProperties?.get(item.name) ?? \"input\";\n\t\t\tconst input = item.input || \"\";\n\t\t\tconst block: StreamingToolCall = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: `${item.call_id}|${item.id ?? \"custom\"}`,\n\t\t\t\tname: item.name,\n\t\t\t\targuments: { [inputProperty]: input },\n\t\t\t\tcustomInput: {\n\t\t\t\t\tproperty: inputProperty,\n\t\t\t\t\tjsonBuffer: { input: \"\", started: false, closed: false },\n\t\t\t\t},\n\t\t\t};\n\t\t\toutput.content.push(block);\n\t\t\tconst slot = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tblock,\n\t\t\t\tcontentIndex: output.content.length - 1,\n\t\t\t} satisfies ResponsesOutputSlot;\n\t\t\toutputSlots.set(outputIndex, slot);\n\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: slot.contentIndex, partial: output });\n\t\t\treturn slot;\n\t\t}\n\t\tconst block = { type: \"providerNative\", subtype: item.type, raw: item } satisfies ProviderNativeContent;\n\t\toutput.content.push(block);\n\t\tconst slot = {\n\t\t\ttype: \"providerNative\",\n\t\t\tblock,\n\t\t\tcontentIndex: output.content.length - 1,\n\t\t} satisfies ResponsesOutputSlot;\n\t\toutputSlots.set(outputIndex, slot);\n\t\treturn slot;\n\t};\n\tconst getOrCreateSlot = (\n\t\toutputIndex: number,\n\t\titem: ResponseOutputItem | ResponseCustomToolCallItem,\n\t): ResponsesOutputSlot | undefined => {\n\t\treturn outputSlots.get(outputIndex) ?? createSlot(outputIndex, item);\n\t};\n\t// Azure OpenAI can omit reasoning.encrypted_content from response.output_item.done\n\t// and provide it only in response.completed.response.output. Backfill the\n\t// persisted reasoning signature from the terminal response to keep store:false\n\t// multi-turn replay stateless. See https://github.com/earendil-works/pi/issues/6409.\n\tconst backfillReasoningSignatures = (responseOutput: ResponseOutputItem[]): void => {\n\t\tfor (const item of responseOutput) {\n\t\t\tif (item.type !== \"reasoning\" || !item.encrypted_content) continue;\n\t\t\tconst block = reasoningBlocksById.get(item.id);\n\t\t\tif (!block?.thinkingSignature) continue;\n\n\t\t\tconst storedItem = JSON.parse(block.thinkingSignature) as ResponseReasoningItem;\n\t\t\tif (storedItem.encrypted_content) continue;\n\t\t\tblock.thinkingSignature = JSON.stringify({\n\t\t\t\t...storedItem,\n\t\t\t\tencrypted_content: item.encrypted_content,\n\t\t\t});\n\t\t}\n\t};\n\tconst finalizeResponse = (\n\t\tresponse: Extract<ResponseStreamEvent, { type: \"response.completed\" | \"response.incomplete\" }>[\"response\"],\n\t) => {\n\t\tsawTerminalResponseEvent = true;\n\t\tbackfillReasoningSignatures(response.output ?? []);\n\t\tif (response?.id) {\n\t\t\toutput.responseId = response.id;\n\t\t}\n\t\tif (response?.usage) {\n\t\t\tconst inputDetails = response.usage.input_tokens_details as\n\t\t\t\t| { cached_tokens?: number; cache_write_tokens?: number }\n\t\t\t\t| undefined;\n\t\t\tconst cachedTokens = inputDetails?.cached_tokens || 0;\n\t\t\tconst cacheWriteTokens = inputDetails?.cache_write_tokens || 0;\n\t\t\toutput.usage = {\n\t\t\t\t// OpenAI includes cached and cache-write tokens in input_tokens, so subtract both.\n\t\t\t\tinput: Math.max(0, (response.usage.input_tokens || 0) - cachedTokens - cacheWriteTokens),\n\t\t\t\toutput: response.usage.output_tokens || 0,\n\t\t\t\tcacheRead: cachedTokens,\n\t\t\t\tcacheWrite: cacheWriteTokens,\n\t\t\t\treasoning: response.usage.output_tokens_details?.reasoning_tokens || 0,\n\t\t\t\ttotalTokens: response.usage.total_tokens || 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t};\n\t\t}\n\t\tcalculateCost(model, output.usage);\n\t\tif (options?.applyServiceTierPricing) {\n\t\t\tconst serviceTier = options.resolveServiceTier\n\t\t\t\t? options.resolveServiceTier(response?.service_tier, options.serviceTier)\n\t\t\t\t: (response?.service_tier ?? options.serviceTier);\n\t\t\toptions.applyServiceTierPricing(output.usage, serviceTier);\n\t\t}\n\t\t// Map status to stop reason\n\t\toutput.stopReason = mapStopReason(response?.status);\n\t\tif (output.content.some((b) => b.type === \"toolCall\") && output.stopReason === \"stop\") {\n\t\t\toutput.stopReason = \"toolUse\";\n\t\t}\n\t};\n\n\tfor await (const event of openaiStream) {\n\t\tif (event.type === \"response.created\") {\n\t\t\toutput.responseId = event.response.id;\n\t\t} else if (event.type === \"response.output_item.added\") {\n\t\t\tcreateSlot(event.output_index, event.item);\n\t\t} else if (event.type === \"response.reasoning_summary_text.delta\") {\n\t\t\tconst slot = getSlot(event.output_index, \"thinking\");\n\t\t\tif (!slot) continue;\n\t\t\tslot.block.thinking += event.delta;\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\tdelta: event.delta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t} else if (event.type === \"response.reasoning_summary_part.done\") {\n\t\t\tconst slot = getSlot(event.output_index, \"thinking\");\n\t\t\tif (!slot) continue;\n\t\t\tslot.block.thinking += \"\\n\\n\";\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\tdelta: \"\\n\\n\",\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t} else if (event.type === \"response.reasoning_text.delta\") {\n\t\t\tconst slot = getSlot(event.output_index, \"thinking\");\n\t\t\tif (!slot) continue;\n\t\t\tslot.block.thinking += event.delta;\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\tdelta: event.delta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t} else if (event.type === \"response.output_text.delta\") {\n\t\t\tconst slot = getSlot(event.output_index, \"text\");\n\t\t\tif (!slot) continue;\n\t\t\tslot.block.text += event.delta;\n\t\t\tstream.push({\n\t\t\t\ttype: \"text_delta\",\n\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\tdelta: event.delta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t} else if (event.type === \"response.refusal.delta\") {\n\t\t\tconst slot = getSlot(event.output_index, \"text\");\n\t\t\tif (!slot) continue;\n\t\t\tslot.block.text += event.delta;\n\t\t\tstream.push({\n\t\t\t\ttype: \"text_delta\",\n\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\tdelta: event.delta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t} else if (event.type === \"response.function_call_arguments.delta\") {\n\t\t\tconst slot = getSlot(event.output_index, \"toolCall\");\n\t\t\tif (!slot || slot.block.partialJson === undefined) continue;\n\t\t\tslot.block.partialJson += event.delta;\n\t\t\tslot.block.arguments = parseStreamingJson(slot.block.partialJson);\n\t\t\tpushToolCallDelta(slot, event.delta);\n\t\t} else if (event.type === \"response.function_call_arguments.done\") {\n\t\t\tconst slot = getSlot(event.output_index, \"toolCall\");\n\t\t\tif (!slot || slot.block.partialJson === undefined) continue;\n\t\t\tconst previousPartialJson = slot.block.partialJson;\n\t\t\tslot.block.partialJson = event.arguments;\n\t\t\tslot.block.arguments = parseStreamingJson(slot.block.partialJson);\n\n\t\t\tif (event.arguments.startsWith(previousPartialJson)) {\n\t\t\t\tconst delta = event.arguments.slice(previousPartialJson.length);\n\t\t\t\tif (delta.length > 0) pushToolCallDelta(slot, delta);\n\t\t\t}\n\t\t} else if (event.type === \"response.custom_tool_call_input.delta\") {\n\t\t\tconst slot = getSlot(event.output_index, \"toolCall\");\n\t\t\tif (!slot?.block.customInput) continue;\n\t\t\tpushToolCallDelta(\n\t\t\t\tslot,\n\t\t\t\tappendCustomToolCallInput(slot.block, getCustomToolCallInput(slot.block) + event.delta, false),\n\t\t\t);\n\t\t} else if (event.type === \"response.custom_tool_call_input.done\") {\n\t\t\tconst slot = getSlot(event.output_index, \"toolCall\");\n\t\t\tif (!slot?.block.customInput) continue;\n\t\t\tpushToolCallDelta(slot, appendCustomToolCallInput(slot.block, event.input, true));\n\t\t} else if (event.type === \"response.output_item.done\") {\n\t\t\tconst item = event.item;\n\t\t\tconst slot = getOrCreateSlot(event.output_index, item);\n\n\t\t\tif (item.type === \"reasoning\" && slot?.type === \"thinking\") {\n\t\t\t\tconst summaryText = item.summary?.map((s) => s.text).join(\"\\n\\n\") || \"\";\n\t\t\t\tconst contentText = item.content?.map((c) => c.text).join(\"\\n\\n\") || \"\";\n\t\t\t\tslot.block.thinking = summaryText || contentText || slot.block.thinking;\n\t\t\t\tslot.block.thinkingSignature = JSON.stringify(item);\n\t\t\t\treasoningBlocksById.set(item.id, slot.block);\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\t\tcontent: slot.block.thinking,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\toutputSlots.delete(event.output_index);\n\t\t\t} else if (item.type === \"message\" && slot?.type === \"text\") {\n\t\t\t\tslot.block.text = item.content?.map((c) => (c.type === \"output_text\" ? c.text : c.refusal)).join(\"\") || \"\";\n\t\t\t\tslot.block.textSignature = encodeTextSignatureV1(item.id, item.phase ?? undefined);\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\t\tcontent: slot.block.text,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\toutputSlots.delete(event.output_index);\n\t\t\t} else if (\n\t\t\t\titem.type === \"function_call\" &&\n\t\t\t\tslot?.type === \"toolCall\" &&\n\t\t\t\tslot.block.partialJson !== undefined\n\t\t\t) {\n\t\t\t\tslot.block.arguments = parseStreamingJson(item.arguments || slot.block.partialJson || \"{}\");\n\t\t\t\t// Finalize in-place and strip the scratch buffer so replay only\n\t\t\t\t// carries parsed arguments.\n\t\t\t\tdelete slot.block.partialJson;\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\t\ttoolCall: slot.block,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\toutputSlots.delete(event.output_index);\n\t\t\t} else if (item.type === \"custom_tool_call\" && slot?.type === \"toolCall\" && slot.block.customInput) {\n\t\t\t\tpushToolCallDelta(\n\t\t\t\t\tslot,\n\t\t\t\t\tappendCustomToolCallInput(slot.block, item.input ?? getCustomToolCallInput(slot.block), true),\n\t\t\t\t);\n\t\t\t\tdelete slot.block.customInput;\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\t\ttoolCall: slot.block,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\toutputSlots.delete(event.output_index);\n\t\t\t} else if (isResponseCustomToolCallItem(item) && slot?.type === \"toolCall\") {\n\t\t\t\tconst input = typeof item.input === \"string\" ? item.input : \"\";\n\t\t\t\tslot.block.arguments = { input };\n\t\t\t\tdelete (slot.block as { partialJson?: string }).partialJson;\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\t\ttoolCall: slot.block,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\toutputSlots.delete(event.output_index);\n\t\t\t} else if (slot?.type === \"providerNative\") {\n\t\t\t\tslot.block.subtype = item.type;\n\t\t\t\tslot.block.raw = item;\n\t\t\t\toutputSlots.delete(event.output_index);\n\t\t\t}\n\t\t} else if (event.type === \"response.completed\" || event.type === \"response.incomplete\") {\n\t\t\tfinalizeResponse(event.response);\n\t\t} else if (event.type === \"error\") {\n\t\t\tthrow new Error(`Error Code ${event.code}: ${event.message}` || \"Unknown error\");\n\t\t} else if (event.type === \"response.failed\") {\n\t\t\tsawTerminalResponseEvent = true;\n\t\t\tconst error = event.response?.error;\n\t\t\tconst details = event.response?.incomplete_details;\n\t\t\tconst msg = error\n\t\t\t\t? `${error.code || \"unknown\"}: ${error.message || \"no message\"}`\n\t\t\t\t: details?.reason\n\t\t\t\t\t? `incomplete: ${details.reason}`\n\t\t\t\t\t: \"Unknown error (no error details in response)\";\n\t\t\tthrow new Error(msg);\n\t\t}\n\t}\n\tconst hasFinalizedToolCall = output.content.some((block) => block.type === \"toolCall\" && !(\"partialJson\" in block));\n\tif (!sawTerminalResponseEvent && !hasFinalizedToolCall) {\n\t\tthrow new Error(\"OpenAI Responses stream ended before a terminal response event\");\n\t}\n}\n\nfunction mapStopReason(status: OpenAI.Responses.ResponseStatus | undefined): StopReason {\n\tif (!status) return \"stop\";\n\tswitch (status) {\n\t\tcase \"completed\":\n\t\t\treturn \"stop\";\n\t\tcase \"incomplete\":\n\t\t\treturn \"length\";\n\t\tcase \"failed\":\n\t\tcase \"cancelled\":\n\t\t\treturn \"error\";\n\t\t// These two are wonky ...\n\t\tcase \"in_progress\":\n\t\tcase \"queued\":\n\t\t\treturn \"stop\";\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = status;\n\t\t\tthrow new Error(`Unhandled stop reason: ${_exhaustive}`);\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"openai-responses-shared.js","sourceRoot":"","sources":["../../src/api/openai-responses-shared.ts"],"names":[],"mappings":"AAgBA,OAAO,EACN,wBAAwB,EAExB,4BAA4B,EAC5B,oBAAoB,GACpB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAiB7C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EACN,+BAA+B,EAE/B,mBAAmB,EACnB,iCAAiC,EACjC,+BAA+B,GAC/B,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAE5D,gFAAgF;AAChF,YAAY;AACZ,gFAAgF;AAEhF,SAAS,qBAAqB,CAAC,EAAU,EAAE,KAAgC;IAC1E,MAAM,OAAO,GAAoB,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,CAAC;IAC9C,IAAI,KAAK;QAAE,OAAO,CAAC,KAAK,GAAG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AO,MAAM,CAAC;QACf,KAAK,YAAY;YAChB,OAAO,QAAQ,CAAC;QACjB,KAAK,QAAQ,CAAC;QACd,KAAK,WAAW;YACf,OAAO,OAAO,CAAC;QAChB,0BAA0B;QAC1B,KAAK,aAAa,CAAC;QACnB,KAAK,QAAQ;YACZ,OAAO,MAAM,CAAC;QACf,SAAS,CAAC;YACT,MAAM,WAAW,GAAU,MAAM,CAAC;YAClC,MAAM,IAAI,KAAK,CAAC,0BAA0B,WAAW,EAAE,CAAC,CAAC;QAC1D,CAAC;IACF,CAAC;AACF,CAAC","sourcesContent":["import type OpenAI from \"openai\";\nimport type {\n\tResponseInputItem as OpenAIResponseInputItem,\n\tTool as OpenAITool,\n\tResponseCreateParamsStreaming,\n\tResponseFunctionCallOutputItemList,\n\tResponseInput,\n\tResponseInputContent,\n\tResponseInputImage,\n\tResponseInputText,\n\tResponseOutputItem,\n\tResponseOutputMessage,\n\tResponseReasoningItem,\n\tResponseStreamEvent,\n\tResponseToolSearchOutputItemParam,\n} from \"openai/resources/responses/responses.js\";\nimport {\n\tCONTEXT_PROVENANCE_FIELD,\n\ttype ContextProvenance,\n\tcontextProvenanceFingerprint,\n\tgetContextProvenance,\n} from \"../context-provenance.ts\";\nimport { calculateCost } from \"../models.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tImageContent,\n\tModel,\n\tProviderNativeContent,\n\tStopReason,\n\tTextContent,\n\tTextSignatureV1,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n\tUsage,\n} from \"../types.ts\";\nimport type { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { parseStreamingJson } from \"../utils/json-parse.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport {\n\tappendGrammarToolInputJsonDelta,\n\ttype GrammarToolInputJsonBuffer,\n\tgetGrammarToolInput,\n\tresolveGrammarConstrainedSampling,\n\tresolveJsonSchemaStrictSampling,\n} from \"./constrained-sampling.ts\";\nimport { transformMessages } from \"./transform-messages.ts\";\n\n// =============================================================================\n// Utilities\n// =============================================================================\n\nfunction encodeTextSignatureV1(id: string, phase?: TextSignatureV1[\"phase\"]): string {\n\tconst payload: TextSignatureV1 = { v: 1, id };\n\tif (phase) payload.phase = phase;\n\treturn JSON.stringify(payload);\n}\n\nfunction parseTextSignature(\n\tsignature: string | undefined,\n): { id: string; phase?: TextSignatureV1[\"phase\"] } | undefined {\n\tif (!signature) return undefined;\n\tif (signature.startsWith(\"{\")) {\n\t\ttry {\n\t\t\tconst parsed = JSON.parse(signature) as Partial<TextSignatureV1>;\n\t\t\tif (parsed.v === 1 && typeof parsed.id === \"string\") {\n\t\t\t\tif (parsed.phase === \"commentary\" || parsed.phase === \"final_answer\") {\n\t\t\t\t\treturn { id: parsed.id, phase: parsed.phase };\n\t\t\t\t}\n\t\t\t\treturn { id: parsed.id };\n\t\t\t}\n\t\t} catch {\n\t\t\t// Fall through to legacy plain-string handling.\n\t\t}\n\t}\n\treturn { id: signature };\n}\n\n/**\n * Parse a persisted reasoning-item signature, rejecting anything that is not a\n * genuine Responses reasoning item. Foreign providers store non-JSON markers\n * (Kimi's \"reasoning_content\") or opaque payloads (Anthropic signatures) in\n * the same field; an unguarded JSON.parse turns a provenance mix-up into a\n * client-side throw, and blindly pushing the parsed value leaks invalid items.\n */\nfunction parseReasoningSignature(signature: string | undefined): ResponseReasoningItem | undefined {\n\tif (!signature) return undefined;\n\ttry {\n\t\tconst parsed = JSON.parse(signature) as ResponseReasoningItem;\n\t\treturn parsed?.type === \"reasoning\" ? parsed : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\ntype ToolResultOutputContent = Array<ResponseInputText | ResponseInputImage>;\n\nfunction convertToolResultOutput<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontent: readonly (TextContent | ImageContent)[],\n): string | ToolResultOutputContent {\n\tconst textResult = content\n\t\t.filter((c): c is TextContent => c.type === \"text\")\n\t\t.map((c) => c.text)\n\t\t.join(\"\\n\");\n\tconst images = content.filter((c): c is ImageContent => c.type === \"image\");\n\tconst hasText = textResult.length > 0;\n\n\tif (images.length === 0 || !model.input.includes(\"image\")) {\n\t\treturn sanitizeSurrogates(hasText ? textResult : images.length > 0 ? \"(see attached image)\" : \"(no tool output)\");\n\t}\n\n\tconst output: ToolResultOutputContent = [];\n\tif (hasText) {\n\t\toutput.push({ type: \"input_text\", text: sanitizeSurrogates(textResult) });\n\t}\n\tfor (const image of images) {\n\t\toutput.push({\n\t\t\ttype: \"input_image\",\n\t\t\tdetail: \"auto\",\n\t\t\timage_url: `data:${image.mimeType};base64,${image.data}`,\n\t\t});\n\t}\n\treturn output;\n}\n\nexport interface OpenAIResponsesStreamOptions {\n\tserviceTier?: ResponseCreateParamsStreaming[\"service_tier\"];\n\tgrammarToolInputProperties?: ReadonlyMap<string, string>;\n\tresolveServiceTier?: (\n\t\tresponseServiceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\t\trequestServiceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\t) => ResponseCreateParamsStreaming[\"service_tier\"] | undefined;\n\tapplyServiceTierPricing?: (\n\t\tusage: Usage,\n\t\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\t) => void;\n}\n\nexport interface ConvertResponsesMessagesOptions {\n\tincludeSystemPrompt?: boolean;\n\tpreserveThinking?: boolean;\n\tpreserveTextSignatures?: boolean;\n\tgrammarToolInputProperties?: ReadonlyMap<string, string>;\n\tdeferredTools?: ReadonlyMap<string, Tool>;\n\ttoolOptions?: ConvertResponsesToolsOptions;\n\t/** Internal request-local provenance sealing pass. Never serialized to provider payloads. */\n\tsealContextProvenance?: boolean;\n}\n\nexport interface ConvertResponsesToolsOptions {\n\tstrict?: boolean | null;\n\tsupportsStrictMode?: boolean;\n\tsupportsOpenAIGrammarTools?: boolean;\n\tdeferLoading?: boolean;\n}\n\ntype ResponseCustomToolCallItem = {\n\ttype: \"custom_tool_call\";\n\tid?: string;\n\tcall_id: string;\n\tname: string;\n\tinput?: string;\n};\n\ntype ResponseCustomToolCallOutputItem = {\n\ttype: \"custom_tool_call_output\";\n\tcall_id: string;\n\tname?: string;\n\toutput: string | ResponseFunctionCallOutputItemList;\n};\n\ntype ResponseInputItem = OpenAIResponseInputItem | ResponseCustomToolCallItem | ResponseCustomToolCallOutputItem;\n\nexport const CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL = \"custom\";\n\ntype ResponseFunctionTool = Extract<OpenAITool, { type: \"function\" }>;\n\nfunction isResponseCustomToolCallItem(item: { type?: string }): item is ResponseCustomToolCallItem {\n\treturn item.type === \"custom_tool_call\";\n}\n\nfunction isFreeformTool(tool: Tool): boolean {\n\treturn tool.freeform !== undefined;\n}\n\nfunction isFreeformToolName(toolName: string, tools: Tool[] | undefined): boolean {\n\treturn tools?.some((tool) => tool.name === toolName && isFreeformTool(tool)) ?? false;\n}\n\nfunction getFreeformToolInput(argumentsValue: Record<string, unknown>): string {\n\treturn typeof argumentsValue.input === \"string\" ? argumentsValue.input : JSON.stringify(argumentsValue);\n}\n\nfunction contextProvenanceForInput(message: unknown, seal: boolean | undefined): ContextProvenance | undefined {\n\tconst provenance = getContextProvenance(message);\n\tif (!provenance) return undefined;\n\tconst fingerprint = contextProvenanceFingerprint(message);\n\tif (fingerprint === undefined) return undefined;\n\tconst stored = provenance.integrity;\n\tif (stored === undefined && seal) {\n\t\tprovenance.integrity = fingerprint;\n\t\treturn provenance;\n\t}\n\treturn stored === fingerprint ? provenance : undefined;\n}\n\nfunction withContextProvenance<T extends object>(item: T, message: unknown, seal: boolean | undefined): T {\n\tconst provenance = contextProvenanceForInput(message, seal);\n\tif (provenance) {\n\t\tObject.defineProperty(item, CONTEXT_PROVENANCE_FIELD, {\n\t\t\tvalue: provenance,\n\t\t\tenumerable: false,\n\t\t});\n\t}\n\treturn item;\n}\n// =============================================================================\n// Message conversion\n// =============================================================================\n\nexport function convertResponsesMessages<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: Context,\n\tallowedToolCallProviders: ReadonlySet<string>,\n\toptions?: ConvertResponsesMessagesOptions,\n): ResponseInput {\n\tconst messages: ResponseInputItem[] = [];\n\tconst loadedToolNames = new Set<string>();\n\n\tconst normalizeIdPart = (part: string): string => {\n\t\tconst sanitized = part.replace(/[^a-zA-Z0-9_-]/g, \"_\");\n\t\tconst normalized = sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized;\n\t\treturn normalized.replace(/_+$/, \"\");\n\t};\n\n\tconst buildForeignResponsesItemId = (itemId: string): string => {\n\t\tconst normalized = `fc_${shortHash(itemId)}`;\n\t\treturn normalized.length > 64 ? normalized.slice(0, 64) : normalized;\n\t};\n\n\tconst normalizeToolCallId = (id: string, _targetModel: Model<TApi>, source: AssistantMessage): string => {\n\t\tif (!id.includes(\"|\")) return normalizeIdPart(id);\n\t\tconst [callId, itemId] = id.split(\"|\");\n\t\tconst normalizedCallId = normalizeIdPart(callId);\n\t\tif (itemId === CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL) {\n\t\t\treturn `${normalizedCallId}|${CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL}`;\n\t\t}\n\t\tif (!allowedToolCallProviders.has(model.provider)) return normalizeIdPart(id);\n\t\tconst isForeignToolCall = source.provider !== model.provider || source.api !== model.api;\n\t\tlet normalizedItemId = isForeignToolCall ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId);\n\t\t// OpenAI Responses API requires item id to start with \"fc\"\n\t\tif (!normalizedItemId.startsWith(\"fc_\")) {\n\t\t\tnormalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);\n\t\t}\n\t\treturn `${normalizedCallId}|${normalizedItemId}`;\n\t};\n\n\tconst transformedMessages = transformMessages(context.messages, model, normalizeToolCallId, {\n\t\tpreserveThinking: options?.preserveThinking,\n\t\tpreserveTextSignatures: options?.preserveTextSignatures,\n\t});\n\n\tconst includeSystemPrompt = options?.includeSystemPrompt ?? true;\n\tif (includeSystemPrompt && context.systemPrompt) {\n\t\tconst compat = model.compat as { supportsDeveloperRole?: boolean } | undefined;\n\t\tconst role = model.reasoning && compat?.supportsDeveloperRole !== false ? \"developer\" : \"system\";\n\t\tmessages.push({\n\t\t\trole,\n\t\t\tcontent: sanitizeSurrogates(context.systemPrompt),\n\t\t});\n\t}\n\n\tlet msgIndex = 0;\n\tfor (const msg of transformedMessages) {\n\t\tif (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tmessages.push(\n\t\t\t\t\twithContextProvenance(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\t\tcontent: [{ type: \"input_text\", text: sanitizeSurrogates(msg.content) }],\n\t\t\t\t\t\t},\n\t\t\t\t\t\tmsg,\n\t\t\t\t\t\toptions?.sealContextProvenance,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst content: ResponseInputContent[] = msg.content.map((item): ResponseInputContent => {\n\t\t\t\t\tif (item.type === \"text\") {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\ttype: \"input_text\",\n\t\t\t\t\t\t\ttext: sanitizeSurrogates(item.text),\n\t\t\t\t\t\t} satisfies ResponseInputText;\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"input_image\",\n\t\t\t\t\t\tdetail: \"auto\",\n\t\t\t\t\t\timage_url: `data:${item.mimeType};base64,${item.data}`,\n\t\t\t\t\t} satisfies ResponseInputImage;\n\t\t\t\t});\n\t\t\t\tif (content.length === 0) continue;\n\t\t\t\tmessages.push(withContextProvenance({ role: \"user\", content }, msg, options?.sealContextProvenance));\n\t\t\t}\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst output: ResponseInputItem[] = [];\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isDifferentModel =\n\t\t\t\tassistantMsg.model !== model.id &&\n\t\t\t\tassistantMsg.provider === model.provider &&\n\t\t\t\tassistantMsg.api === model.api;\n\t\t\tlet textBlockIndex = 0;\n\n\t\t\tconst pushAssistantText = (text: string, textSignature?: string): void => {\n\t\t\t\tconst parsedSignature = parseTextSignature(textSignature);\n\t\t\t\tconst fallbackMessageId =\n\t\t\t\t\ttextBlockIndex === 0 ? `msg_pi_${msgIndex}` : `msg_pi_${msgIndex}_${textBlockIndex}`;\n\t\t\t\ttextBlockIndex++;\n\t\t\t\t// OpenAI requires id to be max 64 characters\n\t\t\t\tlet msgId = parsedSignature?.id;\n\t\t\t\tif (!msgId) {\n\t\t\t\t\tmsgId = fallbackMessageId;\n\t\t\t\t} else if (msgId.length > 64) {\n\t\t\t\t\tmsgId = `msg_${shortHash(msgId)}`;\n\t\t\t\t}\n\t\t\t\toutput.push({\n\t\t\t\t\ttype: \"message\",\n\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\tcontent: [{ type: \"output_text\", text: sanitizeSurrogates(text), annotations: [] }],\n\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\tid: msgId,\n\t\t\t\t\tphase: parsedSignature?.phase,\n\t\t\t\t} satisfies ResponseOutputMessage);\n\t\t\t};\n\n\t\t\tfor (const block of msg.content) {\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\tconst reasoningItem = parseReasoningSignature(block.thinkingSignature);\n\t\t\t\t\tif (reasoningItem) {\n\t\t\t\t\t\toutput.push(reasoningItem);\n\t\t\t\t\t} else if (block.thinkingSignature && block.thinking.trim() !== \"\") {\n\t\t\t\t\t\t// A signed thinking block whose signature is not a real reasoning\n\t\t\t\t\t\t// item (foreign provenance or corrupted state): demote to plain\n\t\t\t\t\t\t// text, mirroring the cross-model policy in transformMessages.\n\t\t\t\t\t\tpushAssistantText(block.thinking);\n\t\t\t\t\t}\n\t\t\t\t\t// Signed foreign blocks with no text are intentionally dropped.\n\t\t\t\t} else if (block.type === \"providerNative\") {\n\t\t\t\t} else if (block.type === \"text\") {\n\t\t\t\t\tconst textBlock = block as TextContent;\n\t\t\t\t\tpushAssistantText(textBlock.text, textBlock.textSignature);\n\t\t\t\t} else if (block.type === \"toolCall\") {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tconst [callId, itemIdRaw] = toolCall.id.split(\"|\");\n\t\t\t\t\tconst customInputProperty = options?.grammarToolInputProperties?.get(toolCall.name);\n\t\t\t\t\tconst isPersistedFreeform = itemIdRaw === CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL;\n\t\t\t\t\tconst isFreeform = isFreeformToolName(toolCall.name, context.tools) || isPersistedFreeform;\n\t\t\t\t\tlet itemId: string | undefined = isPersistedFreeform ? undefined : itemIdRaw;\n\n\t\t\t\t\t// An active grammar declaration wins over sentinel recovery below: its\n\t\t\t\t\t// named input property is richer than the persisted freeform fallback.\n\n\t\t\t\t\t// For different-model messages, set id to undefined to avoid pairing validation.\n\t\t\t\t\t// OpenAI tracks which fc_xxx IDs were paired with rs_xxx reasoning items.\n\t\t\t\t\t// By omitting the id, we avoid triggering that validation (like cross-provider does).\n\t\t\t\t\t// Function-call item ids must begin with fc_ while freeform calls can replay\n\t\t\t\t\t// without the local <call_id>|custom sentinel.\n\t\t\t\t\tif (\n\t\t\t\t\t\t(isDifferentModel && itemId?.startsWith(\"fc_\")) ||\n\t\t\t\t\t\t(!isFreeform && customInputProperty === undefined && !itemId?.startsWith(\"fc_\"))\n\t\t\t\t\t) {\n\t\t\t\t\t\titemId = undefined;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (customInputProperty !== undefined) {\n\t\t\t\t\t\toutput.push({\n\t\t\t\t\t\t\ttype: \"custom_tool_call\",\n\t\t\t\t\t\t\t...(itemId !== undefined ? { id: itemId } : {}),\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\tname: toolCall.name,\n\t\t\t\t\t\t\tinput: sanitizeSurrogates(\n\t\t\t\t\t\t\t\tgetGrammarToolInput(toolCall.name, toolCall.arguments, customInputProperty),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t} satisfies ResponseCustomToolCallItem);\n\t\t\t\t\t} else if (isFreeform) {\n\t\t\t\t\t\toutput.push({\n\t\t\t\t\t\t\ttype: \"custom_tool_call\",\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\tname: toolCall.name,\n\t\t\t\t\t\t\tinput: getFreeformToolInput(toolCall.arguments),\n\t\t\t\t\t\t} satisfies ResponseCustomToolCallItem);\n\t\t\t\t\t} else {\n\t\t\t\t\t\toutput.push({\n\t\t\t\t\t\t\ttype: \"function_call\",\n\t\t\t\t\t\t\t...(itemId?.startsWith(\"fc_\") ? { id: itemId } : {}),\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\tname: toolCall.name,\n\t\t\t\t\t\t\targuments: JSON.stringify(toolCall.arguments),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (output.length === 0) continue;\n\t\t\tmessages.push(...output.map((item) => withContextProvenance(item, msg, options?.sealContextProvenance)));\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\tconst [callId, itemIdRaw] = msg.toolCallId.split(\"|\");\n\t\t\tconst output = convertToolResultOutput(model, msg.content);\n\t\t\tconst customInputProperty = options?.grammarToolInputProperties?.get(msg.toolName);\n\t\t\tconst isPersistedFreeform = itemIdRaw === CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL;\n\n\t\t\tif (customInputProperty !== undefined) {\n\t\t\t\tmessages.push(\n\t\t\t\t\twithContextProvenance(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"custom_tool_call_output\",\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\toutput,\n\t\t\t\t\t\t} satisfies ResponseCustomToolCallOutputItem,\n\t\t\t\t\t\tmsg,\n\t\t\t\t\t\toptions?.sealContextProvenance,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else if (isFreeformToolName(msg.toolName, context.tools) || isPersistedFreeform) {\n\t\t\t\tmessages.push(\n\t\t\t\t\twithContextProvenance(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"custom_tool_call_output\",\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\tname: msg.toolName,\n\t\t\t\t\t\t\toutput,\n\t\t\t\t\t\t} satisfies ResponseCustomToolCallOutputItem,\n\t\t\t\t\t\tmsg,\n\t\t\t\t\t\toptions?.sealContextProvenance,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tmessages.push(\n\t\t\t\t\twithContextProvenance(\n\t\t\t\t\t\t{ type: \"function_call_output\", call_id: callId, output },\n\t\t\t\t\t\tmsg,\n\t\t\t\t\t\toptions?.sealContextProvenance,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst deferredTools: Tool[] = [];\n\t\t\tfor (const name of msg.addedToolNames ?? []) {\n\t\t\t\tconst tool = options?.deferredTools?.get(name);\n\t\t\t\tif (!tool || loadedToolNames.has(name)) continue;\n\t\t\t\tloadedToolNames.add(name);\n\t\t\t\tdeferredTools.push(tool);\n\t\t\t}\n\t\t\tif (deferredTools.length > 0) {\n\t\t\t\tconst names = deferredTools.map((tool) => tool.name);\n\t\t\t\tconst searchCallId = `pi_tool_load_${shortHash(`${msg.toolCallId}:${names.join(\",\")}`)}`;\n\t\t\t\tmessages.push(\n\t\t\t\t\twithContextProvenance(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"tool_search_call\",\n\t\t\t\t\t\t\tcall_id: searchCallId,\n\t\t\t\t\t\t\texecution: \"client\",\n\t\t\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\t\t\targuments: { query: names.join(\" \"), limit: names.length },\n\t\t\t\t\t\t} satisfies ResponseInputItem,\n\t\t\t\t\t\tmsg,\n\t\t\t\t\t\toptions?.sealContextProvenance,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tmessages.push(\n\t\t\t\t\twithContextProvenance(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"tool_search_output\",\n\t\t\t\t\t\t\tcall_id: searchCallId,\n\t\t\t\t\t\t\texecution: \"client\",\n\t\t\t\t\t\t\tstatus: \"completed\",\n\t\t\t\t\t\t\ttools: convertResponsesTools(deferredTools, {\n\t\t\t\t\t\t\t\t...options?.toolOptions,\n\t\t\t\t\t\t\t\tdeferLoading: true,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t} satisfies ResponseToolSearchOutputItemParam,\n\t\t\t\t\t\tmsg,\n\t\t\t\t\t\toptions?.sealContextProvenance,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tmsgIndex++;\n\t}\n\n\treturn messages as ResponseInput;\n}\n\n// =============================================================================\n// Tool conversion\n// =============================================================================\n\nexport function convertResponsesTools(tools: readonly Tool[], options?: ConvertResponsesToolsOptions): OpenAITool[] {\n\tconst defaultStrict = options?.strict === undefined ? false : options.strict;\n\tconst supportsStrictMode = options?.supportsStrictMode ?? true;\n\tconst supportsOpenAIGrammarTools = options?.supportsOpenAIGrammarTools ?? false;\n\n\treturn tools.map((tool) => {\n\t\tconst grammar = resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools);\n\t\tif (grammar) {\n\t\t\treturn {\n\t\t\t\ttype: \"custom\",\n\t\t\t\tname: tool.name,\n\t\t\t\tdescription: tool.description,\n\t\t\t\tformat: {\n\t\t\t\t\ttype: \"grammar\",\n\t\t\t\t\tsyntax: grammar.format,\n\t\t\t\t\tdefinition: grammar.definition,\n\t\t\t\t},\n\t\t\t\t...(options?.deferLoading ? { defer_loading: true } : {}),\n\t\t\t} satisfies OpenAITool;\n\t\t}\n\t\tif (tool.freeform) {\n\t\t\treturn {\n\t\t\t\ttype: \"custom\",\n\t\t\t\tname: tool.name,\n\t\t\t\tdescription: tool.description,\n\t\t\t\tformat: tool.freeform,\n\t\t\t\t...(options?.deferLoading ? { defer_loading: true } : {}),\n\t\t\t} as OpenAITool;\n\t\t}\n\n\t\tconst constrainedStrict = resolveJsonSchemaStrictSampling(tool, supportsStrictMode);\n\t\tconst functionTool: Omit<ResponseFunctionTool, \"strict\"> & {\n\t\t\tstrict?: ResponseFunctionTool[\"strict\"];\n\t\t} = {\n\t\t\ttype: \"function\",\n\t\t\tname: tool.name,\n\t\t\tdescription: tool.description,\n\t\t\tparameters: tool.parameters as ResponseFunctionTool[\"parameters\"], // TypeBox already generates JSON Schema\n\t\t\t...(options?.deferLoading ? { defer_loading: true } : {}),\n\t\t};\n\t\tif (supportsStrictMode) {\n\t\t\tfunctionTool.strict = constrainedStrict ?? defaultStrict;\n\t\t}\n\t\treturn functionTool as OpenAITool;\n\t});\n}\n\n// =============================================================================\n// Stream processing\n// =============================================================================\n\ntype StreamingToolCall = ToolCall & {\n\tpartialJson?: string;\n\tcustomInput?: {\n\t\tproperty: string;\n\t\tjsonBuffer: GrammarToolInputJsonBuffer;\n\t};\n};\n\nfunction getCustomToolCallInput(block: StreamingToolCall): string {\n\tconst property = block.customInput?.property;\n\tif (property === undefined) return \"\";\n\tconst value = block.arguments[property];\n\treturn typeof value === \"string\" ? value : \"\";\n}\n\nfunction appendCustomToolCallInput(block: StreamingToolCall, nextInput: string, close: boolean): string | undefined {\n\tconst customInput = block.customInput;\n\tif (!customInput) return undefined;\n\tconst delta = appendGrammarToolInputJsonDelta(customInput.jsonBuffer, customInput.property, nextInput, close);\n\tblock.arguments = { [customInput.property]: nextInput };\n\treturn delta;\n}\n\ntype ResponsesOutputSlot =\n\t| { type: \"thinking\"; block: ThinkingContent; contentIndex: number }\n\t| { type: \"text\"; block: TextContent; contentIndex: number }\n\t| { type: \"toolCall\"; block: StreamingToolCall; contentIndex: number }\n\t| { type: \"providerNative\"; block: ProviderNativeContent; contentIndex: number };\n\ntype ToolCallOutputSlot = Extract<ResponsesOutputSlot, { type: \"toolCall\" }>;\n\nexport async function processResponsesStream<TApi extends Api>(\n\topenaiStream: AsyncIterable<ResponseStreamEvent>,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tmodel: Model<TApi>,\n\toptions?: OpenAIResponsesStreamOptions,\n): Promise<void> {\n\tlet sawTerminalResponseEvent = false;\n\tconst outputSlots = new Map<number, ResponsesOutputSlot>();\n\tconst reasoningBlocksById = new Map<string, ThinkingContent>();\n\tconst getSlot = <TType extends ResponsesOutputSlot[\"type\"]>(\n\t\toutputIndex: number,\n\t\ttype: TType,\n\t): Extract<ResponsesOutputSlot, { type: TType }> | undefined => {\n\t\tconst slot = outputSlots.get(outputIndex);\n\t\treturn slot?.type === type ? (slot as Extract<ResponsesOutputSlot, { type: TType }>) : undefined;\n\t};\n\tconst pushToolCallDelta = (slot: ToolCallOutputSlot, delta: string | undefined): void => {\n\t\tif (delta === undefined) return;\n\t\tstream.push({\n\t\t\ttype: \"toolcall_delta\",\n\t\t\tcontentIndex: slot.contentIndex,\n\t\t\tdelta,\n\t\t\tpartial: output,\n\t\t});\n\t};\n\tconst createSlot = (\n\t\toutputIndex: number,\n\t\titem: ResponseOutputItem | ResponseCustomToolCallItem,\n\t): ResponsesOutputSlot | undefined => {\n\t\tif (item.type === \"reasoning\") {\n\t\t\tconst block: ThinkingContent = { type: \"thinking\", thinking: \"\" };\n\t\t\toutput.content.push(block);\n\t\t\tconst slot = {\n\t\t\t\ttype: \"thinking\",\n\t\t\t\tblock,\n\t\t\t\tcontentIndex: output.content.length - 1,\n\t\t\t} satisfies ResponsesOutputSlot;\n\t\t\toutputSlots.set(outputIndex, slot);\n\t\t\tstream.push({ type: \"thinking_start\", contentIndex: slot.contentIndex, partial: output });\n\t\t\treturn slot;\n\t\t}\n\t\tif (item.type === \"message\") {\n\t\t\tconst block: TextContent = { type: \"text\", text: \"\" };\n\t\t\toutput.content.push(block);\n\t\t\tconst slot = { type: \"text\", block, contentIndex: output.content.length - 1 } satisfies ResponsesOutputSlot;\n\t\t\toutputSlots.set(outputIndex, slot);\n\t\t\tstream.push({ type: \"text_start\", contentIndex: slot.contentIndex, partial: output });\n\t\t\treturn slot;\n\t\t}\n\t\tif (item.type === \"function_call\") {\n\t\t\tconst block: StreamingToolCall = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: `${item.call_id}|${item.id}`,\n\t\t\t\tname: item.name,\n\t\t\t\targuments: {},\n\t\t\t\tpartialJson: item.arguments || \"\",\n\t\t\t};\n\t\t\toutput.content.push(block);\n\t\t\tconst slot = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tblock,\n\t\t\t\tcontentIndex: output.content.length - 1,\n\t\t\t} satisfies ResponsesOutputSlot;\n\t\t\toutputSlots.set(outputIndex, slot);\n\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: slot.contentIndex, partial: output });\n\t\t\treturn slot;\n\t\t}\n\t\tif (isResponseCustomToolCallItem(item)) {\n\t\t\tconst inputProperty = options?.grammarToolInputProperties?.get(item.name) ?? \"input\";\n\t\t\tconst input = item.input || \"\";\n\t\t\tconst block: StreamingToolCall = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tid: `${item.call_id}|${item.id ?? CUSTOM_TOOL_CALL_ITEM_ID_SENTINEL}`,\n\t\t\t\tname: item.name,\n\t\t\t\targuments: { [inputProperty]: input },\n\t\t\t\tcustomInput: {\n\t\t\t\t\tproperty: inputProperty,\n\t\t\t\t\tjsonBuffer: { input: \"\", started: false, closed: false },\n\t\t\t\t},\n\t\t\t};\n\t\t\toutput.content.push(block);\n\t\t\tconst slot = {\n\t\t\t\ttype: \"toolCall\",\n\t\t\t\tblock,\n\t\t\t\tcontentIndex: output.content.length - 1,\n\t\t\t} satisfies ResponsesOutputSlot;\n\t\t\toutputSlots.set(outputIndex, slot);\n\t\t\tstream.push({ type: \"toolcall_start\", contentIndex: slot.contentIndex, partial: output });\n\t\t\treturn slot;\n\t\t}\n\t\tconst block = { type: \"providerNative\", subtype: item.type, raw: item } satisfies ProviderNativeContent;\n\t\toutput.content.push(block);\n\t\tconst slot = {\n\t\t\ttype: \"providerNative\",\n\t\t\tblock,\n\t\t\tcontentIndex: output.content.length - 1,\n\t\t} satisfies ResponsesOutputSlot;\n\t\toutputSlots.set(outputIndex, slot);\n\t\treturn slot;\n\t};\n\tconst getOrCreateSlot = (\n\t\toutputIndex: number,\n\t\titem: ResponseOutputItem | ResponseCustomToolCallItem,\n\t): ResponsesOutputSlot | undefined => {\n\t\treturn outputSlots.get(outputIndex) ?? createSlot(outputIndex, item);\n\t};\n\t// Azure OpenAI can omit reasoning.encrypted_content from response.output_item.done\n\t// and provide it only in response.completed.response.output. Backfill the\n\t// persisted reasoning signature from the terminal response to keep store:false\n\t// multi-turn replay stateless. See https://github.com/earendil-works/pi/issues/6409.\n\tconst backfillReasoningSignatures = (responseOutput: ResponseOutputItem[]): void => {\n\t\tfor (const item of responseOutput) {\n\t\t\tif (item.type !== \"reasoning\" || !item.encrypted_content) continue;\n\t\t\tconst block = reasoningBlocksById.get(item.id);\n\t\t\tif (!block?.thinkingSignature) continue;\n\n\t\t\tconst storedItem = parseReasoningSignature(block.thinkingSignature);\n\t\t\tif (!storedItem || storedItem.encrypted_content) continue;\n\t\t\tblock.thinkingSignature = JSON.stringify({\n\t\t\t\t...storedItem,\n\t\t\t\tencrypted_content: item.encrypted_content,\n\t\t\t});\n\t\t}\n\t};\n\tconst finalizeResponse = (\n\t\tresponse: Extract<ResponseStreamEvent, { type: \"response.completed\" | \"response.incomplete\" }>[\"response\"],\n\t) => {\n\t\tsawTerminalResponseEvent = true;\n\t\tbackfillReasoningSignatures(response.output ?? []);\n\t\tif (response?.id) {\n\t\t\toutput.responseId = response.id;\n\t\t}\n\t\tif (response?.usage) {\n\t\t\tconst inputDetails = response.usage.input_tokens_details as\n\t\t\t\t| { cached_tokens?: number; cache_write_tokens?: number }\n\t\t\t\t| undefined;\n\t\t\tconst cachedTokens = inputDetails?.cached_tokens || 0;\n\t\t\tconst cacheWriteTokens = inputDetails?.cache_write_tokens || 0;\n\t\t\toutput.usage = {\n\t\t\t\t// OpenAI includes cached and cache-write tokens in input_tokens, so subtract both.\n\t\t\t\tinput: Math.max(0, (response.usage.input_tokens || 0) - cachedTokens - cacheWriteTokens),\n\t\t\t\toutput: response.usage.output_tokens || 0,\n\t\t\t\tcacheRead: cachedTokens,\n\t\t\t\tcacheWrite: cacheWriteTokens,\n\t\t\t\treasoning: response.usage.output_tokens_details?.reasoning_tokens || 0,\n\t\t\t\ttotalTokens: response.usage.total_tokens || 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t};\n\t\t}\n\t\tcalculateCost(model, output.usage);\n\t\tif (options?.applyServiceTierPricing) {\n\t\t\tconst serviceTier = options.resolveServiceTier\n\t\t\t\t? options.resolveServiceTier(response?.service_tier, options.serviceTier)\n\t\t\t\t: (response?.service_tier ?? options.serviceTier);\n\t\t\toptions.applyServiceTierPricing(output.usage, serviceTier);\n\t\t}\n\t\t// Map status to stop reason\n\t\toutput.stopReason = mapStopReason(response?.status);\n\t\tif (output.content.some((b) => b.type === \"toolCall\") && output.stopReason === \"stop\") {\n\t\t\toutput.stopReason = \"toolUse\";\n\t\t}\n\t};\n\n\tfor await (const event of openaiStream) {\n\t\tif (event.type === \"response.created\") {\n\t\t\toutput.responseId = event.response.id;\n\t\t} else if (event.type === \"response.output_item.added\") {\n\t\t\tcreateSlot(event.output_index, event.item);\n\t\t} else if (event.type === \"response.reasoning_summary_text.delta\") {\n\t\t\tconst slot = getSlot(event.output_index, \"thinking\");\n\t\t\tif (!slot) continue;\n\t\t\tslot.block.thinking += event.delta;\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\tdelta: event.delta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t} else if (event.type === \"response.reasoning_summary_part.done\") {\n\t\t\tconst slot = getSlot(event.output_index, \"thinking\");\n\t\t\tif (!slot) continue;\n\t\t\tslot.block.thinking += \"\\n\\n\";\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\tdelta: \"\\n\\n\",\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t} else if (event.type === \"response.reasoning_text.delta\") {\n\t\t\tconst slot = getSlot(event.output_index, \"thinking\");\n\t\t\tif (!slot) continue;\n\t\t\tslot.block.thinking += event.delta;\n\t\t\tstream.push({\n\t\t\t\ttype: \"thinking_delta\",\n\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\tdelta: event.delta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t} else if (event.type === \"response.output_text.delta\") {\n\t\t\tconst slot = getSlot(event.output_index, \"text\");\n\t\t\tif (!slot) continue;\n\t\t\tslot.block.text += event.delta;\n\t\t\tstream.push({\n\t\t\t\ttype: \"text_delta\",\n\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\tdelta: event.delta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t} else if (event.type === \"response.refusal.delta\") {\n\t\t\tconst slot = getSlot(event.output_index, \"text\");\n\t\t\tif (!slot) continue;\n\t\t\tslot.block.text += event.delta;\n\t\t\tstream.push({\n\t\t\t\ttype: \"text_delta\",\n\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\tdelta: event.delta,\n\t\t\t\tpartial: output,\n\t\t\t});\n\t\t} else if (event.type === \"response.function_call_arguments.delta\") {\n\t\t\tconst slot = getSlot(event.output_index, \"toolCall\");\n\t\t\tif (!slot || slot.block.partialJson === undefined) continue;\n\t\t\tslot.block.partialJson += event.delta;\n\t\t\tslot.block.arguments = parseStreamingJson(slot.block.partialJson);\n\t\t\tpushToolCallDelta(slot, event.delta);\n\t\t} else if (event.type === \"response.function_call_arguments.done\") {\n\t\t\tconst slot = getSlot(event.output_index, \"toolCall\");\n\t\t\tif (!slot || slot.block.partialJson === undefined) continue;\n\t\t\tconst previousPartialJson = slot.block.partialJson;\n\t\t\tslot.block.partialJson = event.arguments;\n\t\t\tslot.block.arguments = parseStreamingJson(slot.block.partialJson);\n\n\t\t\tif (event.arguments.startsWith(previousPartialJson)) {\n\t\t\t\tconst delta = event.arguments.slice(previousPartialJson.length);\n\t\t\t\tif (delta.length > 0) pushToolCallDelta(slot, delta);\n\t\t\t}\n\t\t} else if (event.type === \"response.custom_tool_call_input.delta\") {\n\t\t\tconst slot = getSlot(event.output_index, \"toolCall\");\n\t\t\tif (!slot?.block.customInput) continue;\n\t\t\tpushToolCallDelta(\n\t\t\t\tslot,\n\t\t\t\tappendCustomToolCallInput(slot.block, getCustomToolCallInput(slot.block) + event.delta, false),\n\t\t\t);\n\t\t} else if (event.type === \"response.custom_tool_call_input.done\") {\n\t\t\tconst slot = getSlot(event.output_index, \"toolCall\");\n\t\t\tif (!slot?.block.customInput) continue;\n\t\t\tpushToolCallDelta(slot, appendCustomToolCallInput(slot.block, event.input, true));\n\t\t} else if (event.type === \"response.output_item.done\") {\n\t\t\tconst item = event.item;\n\t\t\tconst slot = getOrCreateSlot(event.output_index, item);\n\n\t\t\tif (item.type === \"reasoning\" && slot?.type === \"thinking\") {\n\t\t\t\tconst summaryText = item.summary?.map((s) => s.text).join(\"\\n\\n\") || \"\";\n\t\t\t\tconst contentText = item.content?.map((c) => c.text).join(\"\\n\\n\") || \"\";\n\t\t\t\tslot.block.thinking = summaryText || contentText || slot.block.thinking;\n\t\t\t\tslot.block.thinkingSignature = JSON.stringify(item);\n\t\t\t\treasoningBlocksById.set(item.id, slot.block);\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"thinking_end\",\n\t\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\t\tcontent: slot.block.thinking,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\toutputSlots.delete(event.output_index);\n\t\t\t} else if (item.type === \"message\" && slot?.type === \"text\") {\n\t\t\t\tslot.block.text = item.content?.map((c) => (c.type === \"output_text\" ? c.text : c.refusal)).join(\"\") || \"\";\n\t\t\t\tslot.block.textSignature = encodeTextSignatureV1(item.id, item.phase ?? undefined);\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\t\tcontent: slot.block.text,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\toutputSlots.delete(event.output_index);\n\t\t\t} else if (\n\t\t\t\titem.type === \"function_call\" &&\n\t\t\t\tslot?.type === \"toolCall\" &&\n\t\t\t\tslot.block.partialJson !== undefined\n\t\t\t) {\n\t\t\t\tslot.block.arguments = parseStreamingJson(item.arguments || slot.block.partialJson || \"{}\");\n\t\t\t\t// Finalize in-place and strip the scratch buffer so replay only\n\t\t\t\t// carries parsed arguments.\n\t\t\t\tdelete slot.block.partialJson;\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\t\ttoolCall: slot.block,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\toutputSlots.delete(event.output_index);\n\t\t\t} else if (item.type === \"custom_tool_call\" && slot?.type === \"toolCall\" && slot.block.customInput) {\n\t\t\t\tpushToolCallDelta(\n\t\t\t\t\tslot,\n\t\t\t\t\tappendCustomToolCallInput(slot.block, item.input ?? getCustomToolCallInput(slot.block), true),\n\t\t\t\t);\n\t\t\t\tdelete slot.block.customInput;\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\t\ttoolCall: slot.block,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\toutputSlots.delete(event.output_index);\n\t\t\t} else if (isResponseCustomToolCallItem(item) && slot?.type === \"toolCall\") {\n\t\t\t\tconst input = typeof item.input === \"string\" ? item.input : \"\";\n\t\t\t\tslot.block.arguments = { input };\n\t\t\t\tdelete (slot.block as { partialJson?: string }).partialJson;\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"toolcall_end\",\n\t\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\t\ttoolCall: slot.block,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\toutputSlots.delete(event.output_index);\n\t\t\t} else if (slot?.type === \"providerNative\") {\n\t\t\t\tslot.block.subtype = item.type;\n\t\t\t\tslot.block.raw = item;\n\t\t\t\toutputSlots.delete(event.output_index);\n\t\t\t}\n\t\t} else if (event.type === \"response.completed\" || event.type === \"response.incomplete\") {\n\t\t\tfinalizeResponse(event.response);\n\t\t} else if (event.type === \"error\") {\n\t\t\tthrow new Error(`Error Code ${event.code}: ${event.message}` || \"Unknown error\");\n\t\t} else if (event.type === \"response.failed\") {\n\t\t\tsawTerminalResponseEvent = true;\n\t\t\tconst error = event.response?.error;\n\t\t\tconst details = event.response?.incomplete_details;\n\t\t\tconst msg = error\n\t\t\t\t? `${error.code || \"unknown\"}: ${error.message || \"no message\"}`\n\t\t\t\t: details?.reason\n\t\t\t\t\t? `incomplete: ${details.reason}`\n\t\t\t\t\t: \"Unknown error (no error details in response)\";\n\t\t\tthrow new Error(msg);\n\t\t}\n\t}\n\tconst hasFinalizedToolCall = output.content.some((block) => block.type === \"toolCall\" && !(\"partialJson\" in block));\n\tif (!sawTerminalResponseEvent && !hasFinalizedToolCall) {\n\t\tthrow new Error(\"OpenAI Responses stream ended before a terminal response event\");\n\t}\n}\n\nfunction mapStopReason(status: OpenAI.Responses.ResponseStatus | undefined): StopReason {\n\tif (!status) return \"stop\";\n\tswitch (status) {\n\t\tcase \"completed\":\n\t\t\treturn \"stop\";\n\t\tcase \"incomplete\":\n\t\t\treturn \"length\";\n\t\tcase \"failed\":\n\t\tcase \"cancelled\":\n\t\t\treturn \"error\";\n\t\t// These two are wonky ...\n\t\tcase \"in_progress\":\n\t\tcase \"queued\":\n\t\t\treturn \"stop\";\n\t\tdefault: {\n\t\t\tconst _exhaustive: never = status;\n\t\t\tthrow new Error(`Unhandled stop reason: ${_exhaustive}`);\n\t\t}\n\t}\n}\n"]}
|
|
@@ -320,7 +320,7 @@ function buildParams(model, context, options, compat = getCompat(model, options?
|
|
|
320
320
|
if (reasoningRequested) {
|
|
321
321
|
params.reasoning = {
|
|
322
322
|
effort: reasoningEffort,
|
|
323
|
-
summary: options?.reasoningSummary || "auto",
|
|
323
|
+
...(options?.reasoningSummary === null ? {} : { summary: options?.reasoningSummary || "auto" }),
|
|
324
324
|
};
|
|
325
325
|
params.include = ["reasoning.encrypted_content"];
|
|
326
326
|
}
|