@bastani/pi-ai 0.9.39 → 0.9.40-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +2 -0
  3. package/dist/api/azure-openai-responses.d.ts.map +1 -1
  4. package/dist/api/azure-openai-responses.js +6 -2
  5. package/dist/api/azure-openai-responses.js.map +1 -1
  6. package/dist/api/openai-codex-responses.d.ts.map +1 -1
  7. package/dist/api/openai-codex-responses.js +6 -2
  8. package/dist/api/openai-codex-responses.js.map +1 -1
  9. package/dist/api/openai-completions.d.ts.map +1 -1
  10. package/dist/api/openai-completions.js +9 -3
  11. package/dist/api/openai-completions.js.map +1 -1
  12. package/dist/api/openai-responses-shared.d.ts +16 -0
  13. package/dist/api/openai-responses-shared.d.ts.map +1 -1
  14. package/dist/api/openai-responses-shared.js +60 -8
  15. package/dist/api/openai-responses-shared.js.map +1 -1
  16. package/dist/api/openai-responses.d.ts.map +1 -1
  17. package/dist/api/openai-responses.js +2 -2
  18. package/dist/api/openai-responses.js.map +1 -1
  19. package/dist/api/system-one-shared.d.ts +10 -0
  20. package/dist/api/system-one-shared.d.ts.map +1 -1
  21. package/dist/api/system-one-shared.js +34 -4
  22. package/dist/api/system-one-shared.js.map +1 -1
  23. package/dist/api/typesafe-system-one.d.ts.map +1 -1
  24. package/dist/api/typesafe-system-one.js +3 -1
  25. package/dist/api/typesafe-system-one.js.map +1 -1
  26. package/dist/providers/data/.manifest.json +1 -1
  27. package/dist/providers/data/amazon-bedrock.json +1 -1
  28. package/dist/providers/data/azure.json +1 -1
  29. package/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  30. package/dist/providers/data/cloudflare-workers-ai.json +1 -1
  31. package/dist/providers/data/google.json +1 -1
  32. package/dist/providers/data/huggingface.json +1 -1
  33. package/dist/providers/data/minimax-cn.json +1 -1
  34. package/dist/providers/data/minimax.json +1 -1
  35. package/dist/providers/data/mistral.json +1 -1
  36. package/dist/providers/data/moonshotai-cn.json +1 -1
  37. package/dist/providers/data/openai-codex.json +1 -1
  38. package/dist/providers/data/openai.json +1 -1
  39. package/dist/providers/data/opencode-go.json +1 -1
  40. package/dist/providers/data/opencode.json +1 -1
  41. package/dist/providers/data/openrouter.json +1 -1
  42. package/dist/providers/data/qwen-token-plan-cn.json +1 -1
  43. package/dist/providers/data/qwen-token-plan.json +1 -1
  44. package/dist/providers/data/radius.json +1 -1
  45. package/dist/providers/data/together.json +1 -1
  46. package/dist/providers/data/typesafe.json +1 -1
  47. package/dist/providers/data/vercel-ai-gateway.json +1 -1
  48. package/dist/providers/data/xai.json +1 -1
  49. package/dist/utils/overflow.d.ts.map +1 -1
  50. package/dist/utils/overflow.js +5 -1
  51. package/dist/utils/overflow.js.map +1 -1
  52. package/dist/utils/transcript.d.ts +22 -8
  53. package/dist/utils/transcript.d.ts.map +1 -1
  54. package/dist/utils/transcript.js +29 -18
  55. package/dist/utils/transcript.js.map +1 -1
  56. package/package.json +1 -1
@@ -1,6 +1,7 @@
1
1
  import type { Tool as OpenAITool, ResponseCreateParamsStreaming, ResponseInput, ResponseStreamEvent } from "openai/resources/responses/responses.js";
2
2
  import type { Api, AssistantMessage, Model, StreamOptions, Tool, TranscriptContext, Usage } from "../types.ts";
3
3
  import type { AssistantMessageEventStream } from "../utils/event-stream.ts";
4
+ import { type TranscriptToolSupport } from "../utils/transcript.ts";
4
5
  /**
5
6
  * The service tier this request should carry.
6
7
  *
@@ -110,6 +111,21 @@ export interface ConvertResponsesToolsOptions {
110
111
  supportsOpenAIGrammarTools?: boolean;
111
112
  toolSearchResult?: boolean;
112
113
  }
114
+ /**
115
+ * How a Responses transport expresses tool changes.
116
+ *
117
+ * `additional_tools` items accumulate: a later item adds tools and replaces same-name
118
+ * definitions from earlier items, but it cannot replace a top-level tool and cannot remove any
119
+ * tool (verified with strict schemas on the OpenAI, Codex, and Copilot backends, October 2026).
120
+ * Like Codex, every tool is therefore declared in `additional_tools` items, starting with one
121
+ * at the head of the input, and removals are announced as text. Synthetic tool search can
122
+ * only add tools. Without mid-conversation system messages there is nothing to anchor.
123
+ */
124
+ export declare function getResponsesToolSupport(options: {
125
+ supportsMidConvoSystemMessages?: boolean;
126
+ supportsAdditionalTools?: boolean;
127
+ supportsToolSearch?: boolean;
128
+ }): TranscriptToolSupport;
113
129
  export declare function convertResponsesMessages<TApi extends Api>(model: Model<TApi>, context: TranscriptContext, allowedToolCallProviders: ReadonlySet<string>, options?: ConvertResponsesMessagesOptions): ResponseInput;
114
130
  export declare function convertResponsesTools(tools: readonly Tool[], options?: ConvertResponsesToolsOptions): OpenAITool[];
115
131
  export declare function processResponsesStream<TApi extends Api>(openaiStream: AsyncIterable<ResponseStreamEvent>, output: AssistantMessage, stream: AssistantMessageEventStream, model: Model<TApi>, options?: OpenAIResponsesStreamOptions): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"openai-responses-shared.d.ts","sourceRoot":"","sources":["../../src/api/openai-responses-shared.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,IAAI,IAAI,UAAU,EAElB,6BAA6B,EAC7B,aAAa,EAQb,mBAAmB,EAEnB,MAAM,yCAAyC,CAAC;AAGjD,OAAO,KAAK,EACX,GAAG,EACH,gBAAgB,EAEhB,KAAK,EAGL,aAAa,EAKb,IAAI,EAEJ,iBAAiB,EACjB,KAAK,EACL,MAAM,aAAa,CAAC;AAGrB,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AA6E5E;;;;;;;;;;;;;;;GAeG;AACH,kFAAkF;AAClF,MAAM,MAAM,oBAAoB,GAAG,6BAA6B,CAAC,cAAc,CAAC,GAAG,WAAW,CAAC;AAE/F,wBAAgB,2BAA2B,CAC1C,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,WAAW,CAAC,EACpC,kBAAkB,EAAE,oBAAoB,GAAG,SAAS,GAClD,oBAAoB,GAAG,SA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kBD,wBAAgB,wBAAwB,CAAC,IAAI,SAAS,GAAG,EACxD,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,OAAO,EAAE,iBAAiB,EAC1B,wBAAwB,EAAE,WAAW,CAAC,MAAM,CAAC,EAC7C,OAAO,CAAC,EAAE,+BAA+B,GACvC,aAAa,CA+Of;AAMD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,EAAE,OAAO,CAAC,EAAE,4BAA4B,GAAG,UAAU,EAAE,CAqClH;AAoCD,wBAAsB,sBAAsB,CAAC,IAAI,SAAS,GAAG,EAC5D,YAAY,EAAE,aAAa,CAAC,mBAAmB,CAAC,EAChD,MAAM,EAAE,gBAAgB,EACxB,MAAM,EAAE,2BAA2B,EACnC,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,OAAO,CAAC,EAAE,4BAA4B,GACpC,OAAO,CAAC,IAAI,CAAC,CAyVf"}
@@ -248,6 +248,34 @@ export function assertPayloadPreservesFastRoute(model, payload) {
248
248
  // =============================================================================
249
249
  // Message conversion
250
250
  // =============================================================================
251
+ /**
252
+ * How a Responses transport expresses tool changes.
253
+ *
254
+ * `additional_tools` items accumulate: a later item adds tools and replaces same-name
255
+ * definitions from earlier items, but it cannot replace a top-level tool and cannot remove any
256
+ * tool (verified with strict schemas on the OpenAI, Codex, and Copilot backends, October 2026).
257
+ * Like Codex, every tool is therefore declared in `additional_tools` items, starting with one
258
+ * at the head of the input, and removals are announced as text. Synthetic tool search can
259
+ * only add tools. Without mid-conversation system messages there is nothing to anchor.
260
+ */
261
+ export function getResponsesToolSupport(options) {
262
+ if (options.supportsMidConvoSystemMessages && options.supportsAdditionalTools)
263
+ return "changes";
264
+ return options.supportsToolSearch ? "additions" : "none";
265
+ }
266
+ /**
267
+ * Precedes every additional_tools item after the first. Without it, models read the latest item as
268
+ * the complete tool set once a removal was announced; Codex precedes its incremental tool batches
269
+ * with the same guidance. Restating the tools that are still unavailable keeps smaller models
270
+ * (gpt-5.6-luna, gpt-6-luna) from calling them again after later loads (verified October 2026).
271
+ */
272
+ function renderIncrementalToolsNotice(unavailable) {
273
+ const notice = "This is an incremental tools update. Previously declared tools remain available unless explicitly marked unavailable. A tool declared again here is available again, and its latest definition replaces the earlier one.";
274
+ return unavailable.size > 0 ? `${notice}\nStill unavailable: ${[...unavailable].join(", ")}.` : notice;
275
+ }
276
+ function renderToolRemovalNotice(names) {
277
+ return `The following tools are no longer available. Do not call them:\n${names.map((name) => `- ${name}`).join("\n")}`;
278
+ }
251
279
  export function convertResponsesMessages(model, context, allowedToolCallProviders, options) {
252
280
  const normalizedContext = resolveTranscript(context, options?.supportsMidConvoSystemMessages);
253
281
  const messages = [];
@@ -276,20 +304,30 @@ export function convertResponsesMessages(model, context, allowedToolCallProvider
276
304
  return `${normalizedCallId}|${normalizedItemId}`;
277
305
  };
278
306
  const transformedMessages = transformMessages(normalizedContext.messages, model, normalizeToolCallId);
279
- const transcriptTools = resolveTranscriptTools(normalizedContext.messages, (options?.supportsAdditionalTools ?? false) || (options?.supportsToolSearch ?? false));
307
+ const toolSupport = getResponsesToolSupport(options ?? {});
308
+ const transcriptTools = resolveTranscriptTools(normalizedContext.messages, toolSupport);
309
+ let declaredAdditionalTools = false;
310
+ /** Tools announced as removed and not declared again since. */
311
+ const unavailableTools = new Set();
280
312
  const appendSystemToolAdditions = (message, seed) => {
281
- const tools = transcriptTools.anchorsAdditions ? (message.toolsAdded ?? []) : [];
313
+ const tools = message.toolsAdded ?? [];
314
+ for (const tool of tools)
315
+ unavailableTools.delete(tool.name);
282
316
  if (tools.length === 0)
283
317
  return;
284
- if (options?.supportsAdditionalTools) {
318
+ if (toolSupport === "changes") {
319
+ if (declaredAdditionalTools) {
320
+ messages.push({ role: instructionRole, content: renderIncrementalToolsNotice(unavailableTools) });
321
+ }
322
+ declaredAdditionalTools = true;
285
323
  messages.push({
286
324
  type: "additional_tools",
287
325
  role: "developer",
288
- tools: convertResponsesTools(tools, options.toolOptions),
326
+ tools: convertResponsesTools(tools, options?.toolOptions),
289
327
  });
290
328
  return;
291
329
  }
292
- if (!options?.supportsToolSearch)
330
+ if (toolSupport !== "additions")
293
331
  return;
294
332
  const names = tools.map((tool) => tool.name);
295
333
  const callId = `pi_tool_load_${shortHash(`${seed}:${names.join(",")}`)}`;
@@ -305,7 +343,7 @@ export function convertResponsesMessages(model, context, allowedToolCallProvider
305
343
  call_id: callId,
306
344
  execution: "client",
307
345
  status: "completed",
308
- tools: convertResponsesTools(tools, { ...options.toolOptions, toolSearchResult: true }),
346
+ tools: convertResponsesTools(tools, { ...options?.toolOptions, toolSearchResult: true }),
309
347
  });
310
348
  };
311
349
  const includeInitialSystemMessage = options?.includeSystemPrompt ?? true;
@@ -319,13 +357,27 @@ export function convertResponsesMessages(model, context, allowedToolCallProvider
319
357
  const instructionRole = model.reasoning && compat?.supportsDeveloperRole !== false ? "developer" : "system";
320
358
  let msgIndex = 0;
321
359
  let sourceIndex = 0;
360
+ let systemIndex = 0;
322
361
  for (const msg of transformedMessages) {
323
362
  const isLeadingSystemMessage = sourceIndex++ === 0 && msg.role === "system";
324
363
  if (msg.role === "system") {
325
- if (!isLeadingSystemMessage)
364
+ // transformMessages keeps system messages in order, so their position matches the transcript.
365
+ const anchorsToolChanges = systemIndex++ >= transcriptTools.foldedSystemMessages;
366
+ if (anchorsToolChanges)
326
367
  appendSystemToolAdditions(msg, `system:${msgIndex}`);
327
368
  if (!isLeadingSystemMessage || includeInitialSystemMessage) {
328
- const text = isLeadingSystemMessage ? getSystemMessageText(msg) : renderSystemMessageUpdate(msg);
369
+ const parts = [isLeadingSystemMessage ? getSystemMessageText(msg) : renderSystemMessageUpdate(msg)];
370
+ if (anchorsToolChanges) {
371
+ // A redefinition is a removal plus an addition of the same name; only true removals are announced.
372
+ const added = new Set((msg.toolsAdded ?? []).map((tool) => tool.name));
373
+ const removed = (msg.toolsRemoved ?? []).map((tool) => tool.name).filter((name) => !added.has(name));
374
+ if (removed.length > 0)
375
+ parts.push(renderToolRemovalNotice(removed));
376
+ // Recorded after this message's additions, whose notice precedes this removal notice.
377
+ for (const name of removed)
378
+ unavailableTools.add(name);
379
+ }
380
+ const text = parts.filter((part) => part.length > 0).join("\n\n");
329
381
  if (text.length > 0) {
330
382
  messages.push({ role: instructionRole, content: sanitizeSurrogates(text) });
331
383
  }
@@ -1 +1 @@
1
- {"version":3,"file":"openai-responses-shared.js","sourceRoot":"","sources":["../../src/api/openai-responses-shared.ts"],"names":[],"mappings":"AAgBA,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAkBxD,OAAO,EAAE,gCAAgC,EAAE,MAAM,yBAAyB,CAAC;AAC3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AAEhE,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AACpF,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,oBAAoB,EAAE,yBAAyB,EAAE,MAAM,kBAAkB,CAAC;AACnF,OAAO,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AACnF,OAAO,EACN,+BAA+B,EAE/B,mBAAmB,EACnB,2BAA2B,EAC3B,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,KAAK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\tResponseCreateParamsStreaming,\n\tResponseInput,\n\tResponseInputContent,\n\tResponseInputImage,\n\tResponseInputItem,\n\tResponseInputText,\n\tResponseOutputItem,\n\tResponseOutputMessage,\n\tResponseReasoningItem,\n\tResponseStreamEvent,\n\tResponseToolSearchOutputItemParam,\n} from \"openai/resources/responses/responses.js\";\nimport { calculateCost, getServiceTierCost } from \"../models.ts\";\nimport { normalizeProviderId } from \"../provider-id.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tImageContent,\n\tModel,\n\tModelServiceTierId,\n\tStopReason,\n\tStreamOptions,\n\tSystemMessage,\n\tTextContent,\n\tTextSignatureV1,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n\tTranscriptContext,\n\tUsage,\n} from \"../types.ts\";\nimport { appendAssistantMessageDiagnostic } from \"../utils/diagnostics.ts\";\nimport { normalizeProviderError } from \"../utils/error-body.ts\";\nimport type { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { parseStreamingJson, parseToolCallArguments } from \"../utils/json-parse.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { getSystemMessageText, renderSystemMessageUpdate } from \"../utils/text.ts\";\nimport { resolveTranscript, resolveTranscriptTools } from \"../utils/transcript.ts\";\nimport {\n\tappendGrammarToolInputJsonDelta,\n\ttype GrammarToolInputJsonBuffer,\n\tgetGrammarToolInput,\n\tgetJsonSchemaToolParameters,\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.trim().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\n/**\n * The service tier this request should carry.\n *\n * The **presence** of `fastRoute` is the discriminator, and its declared tier is the value. Fast\n * versus normal is model identity, so a caller who wants a different tier selects the normal sibling\n * rather than downgrading the fast one; letting a per-request option win would let a model selected,\n * recorded, persisted, and billed as `-fast` route as an ordinary request — and, because the Codex\n * routing identity keys on the final payload's tier, silently drop `originator: codex_cli_rs` too.\n *\n * A route that declares **no** tier means *no tier*, not \"fall through to the caller\". A GitHub\n * Copilot fast variant is exactly that case: it sends its own advertised `-fast` model ID and must\n * carry no OpenAI service-tier field at all, whatever the caller asks for.\n *\n * A normal model has no route, so an explicit `serviceTier` still applies there exactly as it did\n * before fast variants existed.\n */\n/** Codex accepts an additional tier not yet represented by the OpenAI API SDK. */\nexport type ResponsesServiceTier = ResponseCreateParamsStreaming[\"service_tier\"] | \"ultrafast\";\n\nexport function resolveRequestedServiceTier(\n\tmodel: Pick<Model<Api>, \"fastRoute\">,\n\toptionsServiceTier: ResponsesServiceTier | undefined,\n): ResponsesServiceTier | undefined {\n\treturn model.fastRoute ? model.fastRoute.serviceTier : optionsServiceTier;\n}\n\nfunction advertisedServiceTierId(serviceTier: ResponsesServiceTier | undefined): ModelServiceTierId | undefined {\n\tif (serviceTier === \"priority\" || serviceTier === \"fast\") return \"priority\";\n\treturn serviceTier === \"ultrafast\" ? \"ultrafast\" : undefined;\n}\n\n/**\n * Whether the model offers a Fast or Ultrafast tier. A model without tier metadata keeps offering Fast\n * but never Ultrafast. Other tiers (`flex`, `default`, `auto`, `scale`) need no advertisement.\n */\nexport function supportsServiceTier(\n\tmodel: Pick<Model<Api>, \"serviceTiers\">,\n\tserviceTier: ResponsesServiceTier,\n): boolean {\n\tconst advertisedId = advertisedServiceTierId(serviceTier);\n\tif (advertisedId === undefined) return true;\n\tif (model.serviceTiers === undefined) return advertisedId !== \"ultrafast\";\n\treturn getServiceTierCost(model, advertisedId) !== undefined;\n}\n\n/** OpenAI API: drop a Fast or Ultrafast tier the model does not advertise and send any other tier as asked. */\nexport function openAIServiceTierForRequest(\n\tmodel: Pick<Model<Api>, \"serviceTiers\">,\n\tserviceTier: ResponsesServiceTier | undefined,\n): ResponsesServiceTier | undefined {\n\treturn serviceTier !== undefined && supportsServiceTier(model, serviceTier) ? serviceTier : undefined;\n}\n\n/**\n * Codex's `service_tier_for_request`: send `flex` or an advertised tier, and omit `default` and every\n * tier the model does not advertise.\n */\nexport function codexServiceTierForRequest(\n\tmodel: Pick<Model<Api>, \"serviceTiers\">,\n\tserviceTier: ResponsesServiceTier | undefined,\n): ResponsesServiceTier | undefined {\n\tif (serviceTier === \"flex\") return serviceTier;\n\treturn advertisedServiceTierId(serviceTier) !== undefined && supportsServiceTier(model, serviceTier)\n\t\t? serviceTier\n\t\t: undefined;\n}\n\n/**\n * Reprice usage at the tier that actually served the request, using the advertised tier's published\n * rates. A model without tier metadata keeps the documented Fast multiplier.\n */\nexport function applyServiceTierPricing(\n\tusage: Usage,\n\tserviceTier: ResponsesServiceTier | undefined,\n\tmodel: Model<Api>,\n): void {\n\tif (serviceTier === \"flex\") {\n\t\tscaleUsageCost(usage, 0.5);\n\t\treturn;\n\t}\n\tconst advertisedId = advertisedServiceTierId(serviceTier);\n\tif (advertisedId === undefined) return;\n\tconst tierCost = getServiceTierCost(model, advertisedId);\n\tif (tierCost) {\n\t\tcalculateCost({ ...model, cost: tierCost }, usage);\n\t\treturn;\n\t}\n\tif (advertisedId === \"priority\") {\n\t\tscaleUsageCost(usage, (model.fastRoute?.baseModelId ?? model.id) === \"gpt-5.5\" ? 2.5 : 2);\n\t}\n}\n\nfunction scaleUsageCost(usage: Usage, multiplier: number): void {\n\tusage.cost.input *= multiplier;\n\tusage.cost.output *= multiplier;\n\tusage.cost.cacheRead *= multiplier;\n\tusage.cost.cacheWrite *= multiplier;\n\tusage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n}\n\ntype ServiceTier = NonNullable<ResponsesServiceTier>;\n\nexport function normalizeResponseServiceTier(serviceTier: string | null | undefined): ServiceTier | undefined {\n\tif (serviceTier === null || serviceTier === undefined) return undefined;\n\treturn serviceTier === \"fast\" ? \"priority\" : (serviceTier as ServiceTier);\n}\n\nconst CHATGPT_AUTH_CLAIM = \"https://api.openai.com/auth\";\n\n/**\n * Whether a bearer token is a ChatGPT sign-in token (a JWT carrying OpenAI's auth claim) rather than an API key. Requests made with it are served by\n * the ChatGPT backend, which reports `default` as the tier of every response, whatever tier it applied.\n */\nexport function isChatGPTSubscriptionToken(token: string | undefined): boolean {\n\tconst payload = token?.split(\".\")[1];\n\tif (!payload || token?.split(\".\").length !== 3) return false;\n\ttry {\n\t\tconst claims = JSON.parse(atob(payload.replace(/-/g, \"+\").replace(/_/g, \"/\")));\n\t\treturn typeof claims?.[CHATGPT_AUTH_CLAIM] === \"object\" && claims[CHATGPT_AUTH_CLAIM] !== null;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * The tier a ChatGPT-backend response ran at. That backend reports `default` for every Flex, Fast or Ultrafast\n * request, so `default` there means the requested tier rather than a downgrade.\n */\nexport function resolveChatGPTBackendServiceTier(\n\tresponseServiceTier: ResponsesServiceTier | undefined,\n\trequestServiceTier: ResponsesServiceTier | undefined,\n): ResponsesServiceTier | undefined {\n\tif (\n\t\tresponseServiceTier === \"default\" &&\n\t\t(requestServiceTier === \"flex\" || requestServiceTier === \"priority\" || requestServiceTier === \"ultrafast\")\n\t) {\n\t\treturn requestServiceTier;\n\t}\n\treturn responseServiceTier ?? requestServiceTier;\n}\n\n/** Diagnostic type recorded when a requested Fast or Ultrafast tier did not apply to a response. */\nexport const SERVICE_TIER_UNAVAILABLE_DIAGNOSTIC = \"service_tier_unavailable\";\n\nconst SERVICE_TIER_SPEED_RANK: Readonly<Record<string, number>> = { priority: 1, ultrafast: 2 };\n\nfunction serviceTierSpeedRank(serviceTier: string): number {\n\treturn SERVICE_TIER_SPEED_RANK[serviceTier] ?? 0;\n}\n\nfunction serviceTierLabel(serviceTier: string): string {\n\treturn serviceTier === \"priority\" ? \"fast\" : serviceTier;\n}\n\n/**\n * Whether the server refused the request because of its `service_tier`: `400 Invalid service_tier argument`\n * on a plain request, or a status-less `error` event with `param: \"service_tier\"` on a streamed one.\n */\nexport function isServiceTierRejection(error: unknown): boolean {\n\tconst { status, body, message } = normalizeProviderError(error);\n\treturn (status === 400 || status === undefined) && /service_tier/i.test(`${message} ${body ?? \"\"}`);\n}\n\nfunction appendServiceTierWarning(\n\toutput: AssistantMessage,\n\tmodel: Pick<Model<Api>, \"fastRoute\" | \"id\">,\n\trequestedServiceTier: string,\n\tranAt: string,\n\treason: \"rejected\" | \"downgraded\",\n): void {\n\tconst baseModelId = model.fastRoute?.baseModelId ?? model.id;\n\tappendAssistantMessageDiagnostic(output, {\n\t\ttype: SERVICE_TIER_UNAVAILABLE_DIAGNOSTIC,\n\t\ttimestamp: Date.now(),\n\t\tdetails: {\n\t\t\tseverity: \"warning\",\n\t\t\tmessage: `${serviceTierLabel(requestedServiceTier)} isn't available for ${baseModelId} on this account; ran at ${serviceTierLabel(ranAt)}`,\n\t\t\treason,\n\t\t\trequestedServiceTier,\n\t\t\tranAtServiceTier: ranAt,\n\t\t},\n\t});\n}\n\n/** The server rejected the requested tier and the request was retried once without it. */\nexport function appendServiceTierRejectedWarning(\n\toutput: AssistantMessage,\n\tmodel: Pick<Model<Api>, \"fastRoute\" | \"id\">,\n\trequestedServiceTier: string,\n): void {\n\tappendServiceTierWarning(output, model, requestedServiceTier, \"default\", \"rejected\");\n}\n\n/**\n * Warn when the server reports a slower tier than the Fast or Ultrafast tier requested. A response\n * that reports no tier says nothing, so it never warns.\n */\nexport function appendServiceTierDowngradeWarning(\n\toutput: AssistantMessage,\n\tmodel: Pick<Model<Api>, \"fastRoute\" | \"id\">,\n\trequestedServiceTier: ResponsesServiceTier | undefined,\n\treportedServiceTier: ResponsesServiceTier | undefined,\n): void {\n\tconst requested = normalizeResponseServiceTier(requestedServiceTier);\n\tif (requested === undefined || reportedServiceTier == null) return;\n\tconst requestedRank = serviceTierSpeedRank(requested);\n\tif (requestedRank === 0 || serviceTierSpeedRank(reportedServiceTier) >= requestedRank) return;\n\tappendServiceTierWarning(output, model, requested, reportedServiceTier, \"downgraded\");\n}\n\n/**\n * Reject a payload hook that rewrote a field the model's route owns.\n *\n * A fast variant is a distinct selected, recorded, persisted, and billed identity, and the objective\n * requires it to send its route's upstream model ID and tier. A hook that changes either would send a\n * different model — or an ordinary-tier request — under the `-fast` identity Atomic recorded, and the\n * Codex routing identity would faithfully advertise whatever the hook left behind.\n *\n * Following the repository's precedent for discarded caller instructions, this rejects loudly rather\n * than silently restoring the route's values, so a misconfigured hook surfaces instead of hiding. A\n * hook may still rewrite every other field, and a model without a route keeps unrestricted freedom.\n */\nexport function assertPayloadPreservesFastRoute(\n\tmodel: Pick<Model<Api>, \"fastRoute\" | \"id\" | \"provider\" | \"serviceTiers\">,\n\tpayload: unknown,\n): void {\n\tconst fastRoute = model.fastRoute;\n\tif (!fastRoute) return;\n\tif (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n\t\tthrow new Error(\n\t\t\t`A request hook changed payload for fast model \"${model.provider}/${model.id}\" to a value that cannot carry ` +\n\t\t\t\t`the route's upstream model and service tier. A fast model variant must send its route's upstream model and ` +\n\t\t\t\t`service tier, because it is recorded, persisted, and billed under its own identity. Select the normal model ` +\n\t\t\t\t`\"${model.provider}/${fastRoute.baseModelId}\" if the request needs different routing, or return an object that ` +\n\t\t\t\t`preserves those fields.`,\n\t\t);\n\t}\n\tconst record = payload as Record<string, unknown>;\n\tconst conflicts: string[] = [];\n\tif (record.model !== fastRoute.upstreamModelId) {\n\t\tconflicts.push(`model (expected \"${fastRoute.upstreamModelId}\", got ${JSON.stringify(record.model)})`);\n\t}\n\tconst expectedServiceTier =\n\t\tfastRoute.serviceTier !== undefined && supportsServiceTier(model, fastRoute.serviceTier)\n\t\t\t? fastRoute.serviceTier\n\t\t\t: undefined;\n\tif (record.service_tier !== expectedServiceTier) {\n\t\tconflicts.push(\n\t\t\t`service_tier (expected ${JSON.stringify(expectedServiceTier)}, got ${JSON.stringify(record.service_tier)})`,\n\t\t);\n\t}\n\tif (conflicts.length === 0) return;\n\tthrow new Error(\n\t\t`A request hook changed ${conflicts.join(\" and \")} for fast model \"${model.provider}/${model.id}\". ` +\n\t\t\t`A fast model variant must send its route's upstream model and service tier, because it is ` +\n\t\t\t`recorded, persisted, and billed under its own identity. Select the normal model \"${model.provider}/${fastRoute.baseModelId}\" ` +\n\t\t\t`if the request needs different routing, or stop rewriting those fields.`,\n\t);\n}\n\nexport interface OpenAIResponsesStreamOptions {\n\tonProviderStreamEvent?: StreamOptions[\"onProviderStreamEvent\"];\n\tserviceTier?: ResponsesServiceTier;\n\tgrammarToolInputProperties?: ReadonlyMap<string, string>;\n\tresolveServiceTier?: (\n\t\tresponseServiceTier: ResponsesServiceTier | undefined,\n\t\trequestServiceTier: ResponsesServiceTier | undefined,\n\t) => ResponsesServiceTier | undefined;\n\tapplyServiceTierPricing?: (usage: Usage, serviceTier: ResponsesServiceTier | undefined) => void;\n\t/** Attach a warning when the response reports a slower tier than requested. Off where the reported tier is ambiguous. */\n\twarnOnServiceTierDowngrade?: boolean;\n}\n\nexport interface ConvertResponsesMessagesOptions {\n\tincludeSystemPrompt?: boolean;\n\tgrammarToolInputProperties?: ReadonlyMap<string, string>;\n\t/** Whether later system messages are sent in place; otherwise they are folded into the leading prompt. */\n\tsupportsMidConvoSystemMessages?: boolean;\n\tsupportsAdditionalTools?: boolean;\n\tsupportsToolSearch?: boolean;\n\ttoolOptions?: ConvertResponsesToolsOptions;\n\t/**\n\t * Effort for the reply being generated. When set, the thinking level is sent as\n\t * configuration_update items instead of a changing reasoning.effort, which would invalidate the\n\t * prompt cache. Each item sets the effort from that point on: one goes before every earlier\n\t * reply with the level recorded on it (`providerThinkingLevel`), and one with this effort goes\n\t * at the end. Earlier input therefore never changes. OpenAI documents the item before user\n\t * messages only. After tool results it was verified on gpt-6-luna (October 2026) to be accepted\n\t * and to apply to the next reply.\n\t */\n\tconfigurationUpdateEffort?: string;\n}\n\nexport interface ConvertResponsesToolsOptions {\n\tstrict?: boolean | null;\n\tsupportsStrictMode?: boolean;\n\tsupportsOpenAIGrammarTools?: boolean;\n\ttoolSearchResult?: boolean;\n}\n\n// =============================================================================\n// Message conversion\n// =============================================================================\n\nexport function convertResponsesMessages<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: TranscriptContext,\n\tallowedToolCallProviders: ReadonlySet<string>,\n\toptions?: ConvertResponsesMessagesOptions,\n): ResponseInput {\n\tconst normalizedContext = resolveTranscript(context, options?.supportsMidConvoSystemMessages);\n\tconst messages: ResponseInput = [];\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 =\n\t\t\tnormalizeProviderId(source.provider) !== normalizeProviderId(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(normalizedContext.messages, model, normalizeToolCallId);\n\tconst transcriptTools = resolveTranscriptTools(\n\t\tnormalizedContext.messages,\n\t\t(options?.supportsAdditionalTools ?? false) || (options?.supportsToolSearch ?? false),\n\t);\n\tconst appendSystemToolAdditions = (message: SystemMessage, seed: string): void => {\n\t\tconst tools = transcriptTools.anchorsAdditions ? (message.toolsAdded ?? []) : [];\n\t\tif (tools.length === 0) return;\n\t\tif (options?.supportsAdditionalTools) {\n\t\t\tmessages.push({\n\t\t\t\ttype: \"additional_tools\",\n\t\t\t\trole: \"developer\",\n\t\t\t\ttools: convertResponsesTools(tools, options.toolOptions),\n\t\t\t} satisfies ResponseInputItem);\n\t\t\treturn;\n\t\t}\n\t\tif (!options?.supportsToolSearch) return;\n\t\tconst names = tools.map((tool) => tool.name);\n\t\tconst callId = `pi_tool_load_${shortHash(`${seed}:${names.join(\",\")}`)}`;\n\t\tmessages.push({\n\t\t\ttype: \"tool_search_call\",\n\t\t\tcall_id: callId,\n\t\t\texecution: \"client\",\n\t\t\tstatus: \"completed\",\n\t\t\targuments: { query: names.join(\" \"), limit: names.length },\n\t\t} satisfies ResponseInputItem);\n\t\tmessages.push({\n\t\t\ttype: \"tool_search_output\",\n\t\t\tcall_id: callId,\n\t\t\texecution: \"client\",\n\t\t\tstatus: \"completed\",\n\t\t\ttools: convertResponsesTools(tools, { ...options.toolOptions, toolSearchResult: true }),\n\t\t} satisfies ResponseToolSearchOutputItemParam);\n\t};\n\tconst includeInitialSystemMessage = options?.includeSystemPrompt ?? true;\n\tconst pushConfigurationUpdate = (effort: string): void => {\n\t\tmessages.push({\n\t\t\ttype: \"configuration_update\",\n\t\t\treasoning: { effort: effort as NonNullable<ResponseConfigurationUpdateItemParam.Reasoning[\"effort\"]> },\n\t\t} satisfies ResponseConfigurationUpdateItemParam);\n\t};\n\tconst compat = model.compat as { supportsDeveloperRole?: boolean } | undefined;\n\tconst instructionRole = model.reasoning && compat?.supportsDeveloperRole !== false ? \"developer\" : \"system\";\n\n\tlet msgIndex = 0;\n\tlet sourceIndex = 0;\n\tfor (const msg of transformedMessages) {\n\t\tconst isLeadingSystemMessage = sourceIndex++ === 0 && msg.role === \"system\";\n\t\tif (msg.role === \"system\") {\n\t\t\tif (!isLeadingSystemMessage) appendSystemToolAdditions(msg, `system:${msgIndex}`);\n\t\t\tif (!isLeadingSystemMessage || includeInitialSystemMessage) {\n\t\t\t\tconst text = isLeadingSystemMessage ? getSystemMessageText(msg) : renderSystemMessageUpdate(msg);\n\t\t\t\tif (text.length > 0) {\n\t\t\t\t\tmessages.push({ role: instructionRole, content: sanitizeSurrogates(text) });\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: [{ type: \"input_text\", text: sanitizeSurrogates(msg.content) }],\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({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst output: ResponseInput = [];\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isSameProviderAndApi =\n\t\t\t\tnormalizeProviderId(assistantMsg.provider) === normalizeProviderId(model.provider) &&\n\t\t\t\tassistantMsg.api === model.api;\n\t\t\tconst isSameModel = isSameProviderAndApi && assistantMsg.model === model.id;\n\t\t\tconst isDifferentModel = isSameProviderAndApi && assistantMsg.model !== model.id;\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 === \"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\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 item 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// Also drop ids that do not match the replayed item type: function_call ids must be fc_*\n\t\t\t\t\t// and custom_tool_call ids must be ctc_*. Foreign tool call ids are normalized to fc_*, and\n\t\t\t\t\t// a call can switch between the two types when grammar tool support differs.\n\t\t\t\t\tconst itemIdPrefix = customInputProperty === undefined ? \"fc_\" : \"ctc_\";\n\t\t\t\t\tif (isDifferentModel || !itemId?.startsWith(itemIdPrefix)) {\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\t...(isSameModel && toolCall.namespace !== undefined ? { namespace: toolCall.namespace } : {}),\n\t\t\t\t\t\t} satisfies ResponseOutputItem);\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\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\targuments: JSON.stringify(toolCall.arguments),\n\t\t\t\t\t\t\t...(isSameModel && toolCall.namespace !== undefined ? { namespace: toolCall.namespace } : {}),\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\tif (\n\t\t\t\toptions?.configurationUpdateEffort !== undefined &&\n\t\t\t\tisSameModel &&\n\t\t\t\tmsg.providerThinkingLevel !== undefined\n\t\t\t) {\n\t\t\t\tpushConfigurationUpdate(msg.providerThinkingLevel);\n\t\t\t}\n\t\t\tmessages.push(...output);\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\n\t\t\tif (options?.grammarToolInputProperties?.has(msg.toolName)) {\n\t\t\t\tmessages.push({\n\t\t\t\t\ttype: \"custom_tool_call_output\",\n\t\t\t\t\tcall_id: callId,\n\t\t\t\t\toutput,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tmessages.push({\n\t\t\t\t\ttype: \"function_call_output\",\n\t\t\t\t\tcall_id: callId,\n\t\t\t\t\toutput,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tif (!isLeadingSystemMessage) msgIndex++;\n\t}\n\tif (options?.configurationUpdateEffort !== undefined) pushConfigurationUpdate(options.configurationUpdateEffort);\n\n\treturn messages;\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?.toolSearchResult ? { defer_loading: true } : {}),\n\t\t\t} satisfies OpenAITool;\n\t\t}\n\n\t\tconst constrainedStrict = resolveJsonSchemaStrictSampling(tool, supportsStrictMode);\n\t\tconst strict = constrainedStrict ?? defaultStrict;\n\t\tconst functionTool: Omit<Extract<OpenAITool, { type: \"function\" }>, \"strict\"> & {\n\t\t\tstrict?: Extract<OpenAITool, { type: \"function\" }>[\"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: getJsonSchemaToolParameters(tool, strict === true) as Record<string, unknown>,\n\t\t\t...(options?.toolSearchResult ? { defer_loading: true } : {}),\n\t\t};\n\t\tif (supportsStrictMode) {\n\t\t\tfunctionTool.strict = strict;\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\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 applyMessagePhaseStopReason = (item: ResponseOutputItem): void => {\n\t\tif (item.type === \"message\" && item.phase === \"final_answer\") {\n\t\t\toutput.stopReason = \"stop\";\n\t\t}\n\t};\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 = (outputIndex: number, item: ResponseOutputItem): 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\tapplyMessagePhaseStopReason(item);\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\t...(item.namespace !== undefined ? { namespace: item.namespace } : {}),\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 (item.type === \"custom_tool_call\") {\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}`,\n\t\t\t\tname: item.name,\n\t\t\t\targuments: { [inputProperty]: input },\n\t\t\t\t...(item.namespace !== undefined ? { namespace: item.namespace } : {}),\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\treturn undefined;\n\t};\n\tconst getOrCreateSlot = (outputIndex: number, item: ResponseOutputItem): 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): void => {\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 responseServiceTier = normalizeResponseServiceTier(response?.service_tier);\n\t\t\tconst serviceTier = options.resolveServiceTier\n\t\t\t\t? options.resolveServiceTier(responseServiceTier, options.serviceTier)\n\t\t\t\t: (responseServiceTier ?? options.serviceTier);\n\t\t\toptions.applyServiceTierPricing(output.usage, serviceTier);\n\t\t\tif (options.warnOnServiceTierDowngrade) {\n\t\t\t\tappendServiceTierDowngradeWarning(output, model, options.serviceTier, responseServiceTier);\n\t\t\t}\n\t\t}\n\t\t// Map status to stop reason. For incomplete responses, retain the provider's\n\t\t// specific reason so max-output truncation and content filtering stay distinct.\n\t\tconst status = response?.status;\n\t\tconst incompleteDetails = response?.incomplete_details as { reason?: unknown } | null | undefined;\n\t\tconst incompleteReason = typeof incompleteDetails?.reason === \"string\" ? incompleteDetails.reason : undefined;\n\t\tif (output.rawStopReason !== \"refusal\") {\n\t\t\toutput.rawStopReason = incompleteReason ? `${status}.${incompleteReason}` : status;\n\t\t}\n\t\tconst mappedStop = mapStopReason(status, incompleteReason);\n\t\toutput.stopReason = mappedStop.stopReason;\n\t\toutput.errorMessage = mappedStop.errorMessage;\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\tawait options?.onProviderStreamEvent?.(event, model);\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\toutput.rawStopReason = \"refusal\";\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 || !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 || !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\tapplyMessagePhaseStopReason(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\tif (item.content?.some((content) => content.type === \"refusal\")) output.rawStopReason = \"refusal\";\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\tObject.assign(slot.block, parseToolCallArguments(item.arguments || slot.block.partialJson));\n\t\t\t\tif (item.namespace !== undefined) slot.block.namespace = item.namespace;\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\tif (item.namespace !== undefined) slot.block.namespace = item.namespace;\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}\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\toutput.rawStopReason = event.response?.status;\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\tif (!sawTerminalResponseEvent) {\n\t\tthrow new Error(\"OpenAI Responses stream ended before a terminal response event\");\n\t}\n\t// The agent runs every tool call in the final message. Refuse to hand over calls whose\n\t// output_item.done never arrived: their arguments may be cut off or mixed up, e.g. when a\n\t// non-compliant server omits output_index. Finished calls have their scratch buffers removed.\n\tif (output.stopReason === \"toolUse\") {\n\t\tfor (const block of output.content) {\n\t\t\tif (block.type !== \"toolCall\") continue;\n\t\t\tconst toolCall = block as StreamingToolCall;\n\t\t\tif (toolCall.partialJson !== undefined || toolCall.customInput !== undefined) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`OpenAI Responses stream completed with an unfinished tool call: ${toolCall.name} (${toolCall.id})`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction mapStopReason(\n\tstatus: OpenAI.Responses.ResponseStatus | undefined,\n\tincompleteReason?: string,\n): { stopReason: StopReason; errorMessage?: string } {\n\tif (!status) return { stopReason: \"stop\" };\n\tswitch (status) {\n\t\tcase \"completed\":\n\t\t\treturn { stopReason: \"stop\" };\n\t\tcase \"incomplete\":\n\t\t\tif (incompleteReason === \"max_output_tokens\") {\n\t\t\t\treturn { stopReason: \"length\" };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terrorMessage: incompleteReason\n\t\t\t\t\t? `Response incomplete: ${incompleteReason}`\n\t\t\t\t\t: \"Response incomplete without a provider reason\",\n\t\t\t};\n\t\tcase \"failed\":\n\t\tcase \"cancelled\":\n\t\t\treturn { stopReason: \"error\" };\n\t\t// These two are wonky ...\n\t\tcase \"in_progress\":\n\t\tcase \"queued\":\n\t\t\treturn { stopReason: \"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,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACjE,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAkBxD,OAAO,EAAE,gCAAgC,EAAE,MAAM,yBAAyB,CAAC;AAC3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AAEhE,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AACpF,OAAO,EAAE,kBAAk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";\nimport type {\n\tTool as OpenAITool,\n\tResponseConfigurationUpdateItemParam,\n\tResponseCreateParamsStreaming,\n\tResponseInput,\n\tResponseInputContent,\n\tResponseInputImage,\n\tResponseInputItem,\n\tResponseInputText,\n\tResponseOutputItem,\n\tResponseOutputMessage,\n\tResponseReasoningItem,\n\tResponseStreamEvent,\n\tResponseToolSearchOutputItemParam,\n} from \"openai/resources/responses/responses.js\";\nimport { calculateCost, getServiceTierCost } from \"../models.ts\";\nimport { normalizeProviderId } from \"../provider-id.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tImageContent,\n\tModel,\n\tModelServiceTierId,\n\tStopReason,\n\tStreamOptions,\n\tSystemMessage,\n\tTextContent,\n\tTextSignatureV1,\n\tThinkingContent,\n\tTool,\n\tToolCall,\n\tTranscriptContext,\n\tUsage,\n} from \"../types.ts\";\nimport { appendAssistantMessageDiagnostic } from \"../utils/diagnostics.ts\";\nimport { normalizeProviderError } from \"../utils/error-body.ts\";\nimport type { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { parseStreamingJson, parseToolCallArguments } from \"../utils/json-parse.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { getSystemMessageText, renderSystemMessageUpdate } from \"../utils/text.ts\";\nimport { resolveTranscript, resolveTranscriptTools, type TranscriptToolSupport } from \"../utils/transcript.ts\";\nimport {\n\tappendGrammarToolInputJsonDelta,\n\ttype GrammarToolInputJsonBuffer,\n\tgetGrammarToolInput,\n\tgetJsonSchemaToolParameters,\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.trim().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\n/**\n * The service tier this request should carry.\n *\n * The **presence** of `fastRoute` is the discriminator, and its declared tier is the value. Fast\n * versus normal is model identity, so a caller who wants a different tier selects the normal sibling\n * rather than downgrading the fast one; letting a per-request option win would let a model selected,\n * recorded, persisted, and billed as `-fast` route as an ordinary request — and, because the Codex\n * routing identity keys on the final payload's tier, silently drop `originator: codex_cli_rs` too.\n *\n * A route that declares **no** tier means *no tier*, not \"fall through to the caller\". A GitHub\n * Copilot fast variant is exactly that case: it sends its own advertised `-fast` model ID and must\n * carry no OpenAI service-tier field at all, whatever the caller asks for.\n *\n * A normal model has no route, so an explicit `serviceTier` still applies there exactly as it did\n * before fast variants existed.\n */\n/** Codex accepts an additional tier not yet represented by the OpenAI API SDK. */\nexport type ResponsesServiceTier = ResponseCreateParamsStreaming[\"service_tier\"] | \"ultrafast\";\n\nexport function resolveRequestedServiceTier(\n\tmodel: Pick<Model<Api>, \"fastRoute\">,\n\toptionsServiceTier: ResponsesServiceTier | undefined,\n): ResponsesServiceTier | undefined {\n\treturn model.fastRoute ? model.fastRoute.serviceTier : optionsServiceTier;\n}\n\nfunction advertisedServiceTierId(serviceTier: ResponsesServiceTier | undefined): ModelServiceTierId | undefined {\n\tif (serviceTier === \"priority\" || serviceTier === \"fast\") return \"priority\";\n\treturn serviceTier === \"ultrafast\" ? \"ultrafast\" : undefined;\n}\n\n/**\n * Whether the model offers a Fast or Ultrafast tier. A model without tier metadata keeps offering Fast\n * but never Ultrafast. Other tiers (`flex`, `default`, `auto`, `scale`) need no advertisement.\n */\nexport function supportsServiceTier(\n\tmodel: Pick<Model<Api>, \"serviceTiers\">,\n\tserviceTier: ResponsesServiceTier,\n): boolean {\n\tconst advertisedId = advertisedServiceTierId(serviceTier);\n\tif (advertisedId === undefined) return true;\n\tif (model.serviceTiers === undefined) return advertisedId !== \"ultrafast\";\n\treturn getServiceTierCost(model, advertisedId) !== undefined;\n}\n\n/** OpenAI API: drop a Fast or Ultrafast tier the model does not advertise and send any other tier as asked. */\nexport function openAIServiceTierForRequest(\n\tmodel: Pick<Model<Api>, \"serviceTiers\">,\n\tserviceTier: ResponsesServiceTier | undefined,\n): ResponsesServiceTier | undefined {\n\treturn serviceTier !== undefined && supportsServiceTier(model, serviceTier) ? serviceTier : undefined;\n}\n\n/**\n * Codex's `service_tier_for_request`: send `flex` or an advertised tier, and omit `default` and every\n * tier the model does not advertise.\n */\nexport function codexServiceTierForRequest(\n\tmodel: Pick<Model<Api>, \"serviceTiers\">,\n\tserviceTier: ResponsesServiceTier | undefined,\n): ResponsesServiceTier | undefined {\n\tif (serviceTier === \"flex\") return serviceTier;\n\treturn advertisedServiceTierId(serviceTier) !== undefined && supportsServiceTier(model, serviceTier)\n\t\t? serviceTier\n\t\t: undefined;\n}\n\n/**\n * Reprice usage at the tier that actually served the request, using the advertised tier's published\n * rates. A model without tier metadata keeps the documented Fast multiplier.\n */\nexport function applyServiceTierPricing(\n\tusage: Usage,\n\tserviceTier: ResponsesServiceTier | undefined,\n\tmodel: Model<Api>,\n): void {\n\tif (serviceTier === \"flex\") {\n\t\tscaleUsageCost(usage, 0.5);\n\t\treturn;\n\t}\n\tconst advertisedId = advertisedServiceTierId(serviceTier);\n\tif (advertisedId === undefined) return;\n\tconst tierCost = getServiceTierCost(model, advertisedId);\n\tif (tierCost) {\n\t\tcalculateCost({ ...model, cost: tierCost }, usage);\n\t\treturn;\n\t}\n\tif (advertisedId === \"priority\") {\n\t\tscaleUsageCost(usage, (model.fastRoute?.baseModelId ?? model.id) === \"gpt-5.5\" ? 2.5 : 2);\n\t}\n}\n\nfunction scaleUsageCost(usage: Usage, multiplier: number): void {\n\tusage.cost.input *= multiplier;\n\tusage.cost.output *= multiplier;\n\tusage.cost.cacheRead *= multiplier;\n\tusage.cost.cacheWrite *= multiplier;\n\tusage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;\n}\n\ntype ServiceTier = NonNullable<ResponsesServiceTier>;\n\nexport function normalizeResponseServiceTier(serviceTier: string | null | undefined): ServiceTier | undefined {\n\tif (serviceTier === null || serviceTier === undefined) return undefined;\n\treturn serviceTier === \"fast\" ? \"priority\" : (serviceTier as ServiceTier);\n}\n\nconst CHATGPT_AUTH_CLAIM = \"https://api.openai.com/auth\";\n\n/**\n * Whether a bearer token is a ChatGPT sign-in token (a JWT carrying OpenAI's auth claim) rather than an API key. Requests made with it are served by\n * the ChatGPT backend, which reports `default` as the tier of every response, whatever tier it applied.\n */\nexport function isChatGPTSubscriptionToken(token: string | undefined): boolean {\n\tconst payload = token?.split(\".\")[1];\n\tif (!payload || token?.split(\".\").length !== 3) return false;\n\ttry {\n\t\tconst claims = JSON.parse(atob(payload.replace(/-/g, \"+\").replace(/_/g, \"/\")));\n\t\treturn typeof claims?.[CHATGPT_AUTH_CLAIM] === \"object\" && claims[CHATGPT_AUTH_CLAIM] !== null;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/**\n * The tier a ChatGPT-backend response ran at. That backend reports `default` for every Flex, Fast or Ultrafast\n * request, so `default` there means the requested tier rather than a downgrade.\n */\nexport function resolveChatGPTBackendServiceTier(\n\tresponseServiceTier: ResponsesServiceTier | undefined,\n\trequestServiceTier: ResponsesServiceTier | undefined,\n): ResponsesServiceTier | undefined {\n\tif (\n\t\tresponseServiceTier === \"default\" &&\n\t\t(requestServiceTier === \"flex\" || requestServiceTier === \"priority\" || requestServiceTier === \"ultrafast\")\n\t) {\n\t\treturn requestServiceTier;\n\t}\n\treturn responseServiceTier ?? requestServiceTier;\n}\n\n/** Diagnostic type recorded when a requested Fast or Ultrafast tier did not apply to a response. */\nexport const SERVICE_TIER_UNAVAILABLE_DIAGNOSTIC = \"service_tier_unavailable\";\n\nconst SERVICE_TIER_SPEED_RANK: Readonly<Record<string, number>> = { priority: 1, ultrafast: 2 };\n\nfunction serviceTierSpeedRank(serviceTier: string): number {\n\treturn SERVICE_TIER_SPEED_RANK[serviceTier] ?? 0;\n}\n\nfunction serviceTierLabel(serviceTier: string): string {\n\treturn serviceTier === \"priority\" ? \"fast\" : serviceTier;\n}\n\n/**\n * Whether the server refused the request because of its `service_tier`: `400 Invalid service_tier argument`\n * on a plain request, or a status-less `error` event with `param: \"service_tier\"` on a streamed one.\n */\nexport function isServiceTierRejection(error: unknown): boolean {\n\tconst { status, body, message } = normalizeProviderError(error);\n\treturn (status === 400 || status === undefined) && /service_tier/i.test(`${message} ${body ?? \"\"}`);\n}\n\nfunction appendServiceTierWarning(\n\toutput: AssistantMessage,\n\tmodel: Pick<Model<Api>, \"fastRoute\" | \"id\">,\n\trequestedServiceTier: string,\n\tranAt: string,\n\treason: \"rejected\" | \"downgraded\",\n): void {\n\tconst baseModelId = model.fastRoute?.baseModelId ?? model.id;\n\tappendAssistantMessageDiagnostic(output, {\n\t\ttype: SERVICE_TIER_UNAVAILABLE_DIAGNOSTIC,\n\t\ttimestamp: Date.now(),\n\t\tdetails: {\n\t\t\tseverity: \"warning\",\n\t\t\tmessage: `${serviceTierLabel(requestedServiceTier)} isn't available for ${baseModelId} on this account; ran at ${serviceTierLabel(ranAt)}`,\n\t\t\treason,\n\t\t\trequestedServiceTier,\n\t\t\tranAtServiceTier: ranAt,\n\t\t},\n\t});\n}\n\n/** The server rejected the requested tier and the request was retried once without it. */\nexport function appendServiceTierRejectedWarning(\n\toutput: AssistantMessage,\n\tmodel: Pick<Model<Api>, \"fastRoute\" | \"id\">,\n\trequestedServiceTier: string,\n): void {\n\tappendServiceTierWarning(output, model, requestedServiceTier, \"default\", \"rejected\");\n}\n\n/**\n * Warn when the server reports a slower tier than the Fast or Ultrafast tier requested. A response\n * that reports no tier says nothing, so it never warns.\n */\nexport function appendServiceTierDowngradeWarning(\n\toutput: AssistantMessage,\n\tmodel: Pick<Model<Api>, \"fastRoute\" | \"id\">,\n\trequestedServiceTier: ResponsesServiceTier | undefined,\n\treportedServiceTier: ResponsesServiceTier | undefined,\n): void {\n\tconst requested = normalizeResponseServiceTier(requestedServiceTier);\n\tif (requested === undefined || reportedServiceTier == null) return;\n\tconst requestedRank = serviceTierSpeedRank(requested);\n\tif (requestedRank === 0 || serviceTierSpeedRank(reportedServiceTier) >= requestedRank) return;\n\tappendServiceTierWarning(output, model, requested, reportedServiceTier, \"downgraded\");\n}\n\n/**\n * Reject a payload hook that rewrote a field the model's route owns.\n *\n * A fast variant is a distinct selected, recorded, persisted, and billed identity, and the objective\n * requires it to send its route's upstream model ID and tier. A hook that changes either would send a\n * different model — or an ordinary-tier request — under the `-fast` identity Atomic recorded, and the\n * Codex routing identity would faithfully advertise whatever the hook left behind.\n *\n * Following the repository's precedent for discarded caller instructions, this rejects loudly rather\n * than silently restoring the route's values, so a misconfigured hook surfaces instead of hiding. A\n * hook may still rewrite every other field, and a model without a route keeps unrestricted freedom.\n */\nexport function assertPayloadPreservesFastRoute(\n\tmodel: Pick<Model<Api>, \"fastRoute\" | \"id\" | \"provider\" | \"serviceTiers\">,\n\tpayload: unknown,\n): void {\n\tconst fastRoute = model.fastRoute;\n\tif (!fastRoute) return;\n\tif (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n\t\tthrow new Error(\n\t\t\t`A request hook changed payload for fast model \"${model.provider}/${model.id}\" to a value that cannot carry ` +\n\t\t\t\t`the route's upstream model and service tier. A fast model variant must send its route's upstream model and ` +\n\t\t\t\t`service tier, because it is recorded, persisted, and billed under its own identity. Select the normal model ` +\n\t\t\t\t`\"${model.provider}/${fastRoute.baseModelId}\" if the request needs different routing, or return an object that ` +\n\t\t\t\t`preserves those fields.`,\n\t\t);\n\t}\n\tconst record = payload as Record<string, unknown>;\n\tconst conflicts: string[] = [];\n\tif (record.model !== fastRoute.upstreamModelId) {\n\t\tconflicts.push(`model (expected \"${fastRoute.upstreamModelId}\", got ${JSON.stringify(record.model)})`);\n\t}\n\tconst expectedServiceTier =\n\t\tfastRoute.serviceTier !== undefined && supportsServiceTier(model, fastRoute.serviceTier)\n\t\t\t? fastRoute.serviceTier\n\t\t\t: undefined;\n\tif (record.service_tier !== expectedServiceTier) {\n\t\tconflicts.push(\n\t\t\t`service_tier (expected ${JSON.stringify(expectedServiceTier)}, got ${JSON.stringify(record.service_tier)})`,\n\t\t);\n\t}\n\tif (conflicts.length === 0) return;\n\tthrow new Error(\n\t\t`A request hook changed ${conflicts.join(\" and \")} for fast model \"${model.provider}/${model.id}\". ` +\n\t\t\t`A fast model variant must send its route's upstream model and service tier, because it is ` +\n\t\t\t`recorded, persisted, and billed under its own identity. Select the normal model \"${model.provider}/${fastRoute.baseModelId}\" ` +\n\t\t\t`if the request needs different routing, or stop rewriting those fields.`,\n\t);\n}\n\nexport interface OpenAIResponsesStreamOptions {\n\tonProviderStreamEvent?: StreamOptions[\"onProviderStreamEvent\"];\n\tserviceTier?: ResponsesServiceTier;\n\tgrammarToolInputProperties?: ReadonlyMap<string, string>;\n\tresolveServiceTier?: (\n\t\tresponseServiceTier: ResponsesServiceTier | undefined,\n\t\trequestServiceTier: ResponsesServiceTier | undefined,\n\t) => ResponsesServiceTier | undefined;\n\tapplyServiceTierPricing?: (usage: Usage, serviceTier: ResponsesServiceTier | undefined) => void;\n\t/** Attach a warning when the response reports a slower tier than requested. Off where the reported tier is ambiguous. */\n\twarnOnServiceTierDowngrade?: boolean;\n}\n\nexport interface ConvertResponsesMessagesOptions {\n\tincludeSystemPrompt?: boolean;\n\tgrammarToolInputProperties?: ReadonlyMap<string, string>;\n\t/** Whether later system messages are sent in place; otherwise they are folded into the leading prompt. */\n\tsupportsMidConvoSystemMessages?: boolean;\n\tsupportsAdditionalTools?: boolean;\n\tsupportsToolSearch?: boolean;\n\ttoolOptions?: ConvertResponsesToolsOptions;\n\t/**\n\t * Effort for the reply being generated. When set, the thinking level is sent as\n\t * configuration_update items instead of a changing reasoning.effort, which would invalidate the\n\t * prompt cache. Each item sets the effort from that point on: one goes before every earlier\n\t * reply with the level recorded on it (`providerThinkingLevel`), and one with this effort goes\n\t * at the end. Earlier input therefore never changes. OpenAI documents the item before user\n\t * messages only. After tool results it was verified on gpt-6-luna (October 2026) to be accepted\n\t * and to apply to the next reply.\n\t */\n\tconfigurationUpdateEffort?: string;\n}\n\nexport interface ConvertResponsesToolsOptions {\n\tstrict?: boolean | null;\n\tsupportsStrictMode?: boolean;\n\tsupportsOpenAIGrammarTools?: boolean;\n\ttoolSearchResult?: boolean;\n}\n\n// =============================================================================\n// Message conversion\n// =============================================================================\n\n/**\n * How a Responses transport expresses tool changes.\n *\n * `additional_tools` items accumulate: a later item adds tools and replaces same-name\n * definitions from earlier items, but it cannot replace a top-level tool and cannot remove any\n * tool (verified with strict schemas on the OpenAI, Codex, and Copilot backends, October 2026).\n * Like Codex, every tool is therefore declared in `additional_tools` items, starting with one\n * at the head of the input, and removals are announced as text. Synthetic tool search can\n * only add tools. Without mid-conversation system messages there is nothing to anchor.\n */\nexport function getResponsesToolSupport(options: {\n\tsupportsMidConvoSystemMessages?: boolean;\n\tsupportsAdditionalTools?: boolean;\n\tsupportsToolSearch?: boolean;\n}): TranscriptToolSupport {\n\tif (options.supportsMidConvoSystemMessages && options.supportsAdditionalTools) return \"changes\";\n\treturn options.supportsToolSearch ? \"additions\" : \"none\";\n}\n\n/**\n * Precedes every additional_tools item after the first. Without it, models read the latest item as\n * the complete tool set once a removal was announced; Codex precedes its incremental tool batches\n * with the same guidance. Restating the tools that are still unavailable keeps smaller models\n * (gpt-5.6-luna, gpt-6-luna) from calling them again after later loads (verified October 2026).\n */\nfunction renderIncrementalToolsNotice(unavailable: ReadonlySet<string>): string {\n\tconst notice =\n\t\t\"This is an incremental tools update. Previously declared tools remain available unless explicitly marked unavailable. A tool declared again here is available again, and its latest definition replaces the earlier one.\";\n\treturn unavailable.size > 0 ? `${notice}\\nStill unavailable: ${[...unavailable].join(\", \")}.` : notice;\n}\n\nfunction renderToolRemovalNotice(names: readonly string[]): string {\n\treturn `The following tools are no longer available. Do not call them:\\n${names.map((name) => `- ${name}`).join(\"\\n\")}`;\n}\n\nexport function convertResponsesMessages<TApi extends Api>(\n\tmodel: Model<TApi>,\n\tcontext: TranscriptContext,\n\tallowedToolCallProviders: ReadonlySet<string>,\n\toptions?: ConvertResponsesMessagesOptions,\n): ResponseInput {\n\tconst normalizedContext = resolveTranscript(context, options?.supportsMidConvoSystemMessages);\n\tconst messages: ResponseInput = [];\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 =\n\t\t\tnormalizeProviderId(source.provider) !== normalizeProviderId(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(normalizedContext.messages, model, normalizeToolCallId);\n\tconst toolSupport = getResponsesToolSupport(options ?? {});\n\tconst transcriptTools = resolveTranscriptTools(normalizedContext.messages, toolSupport);\n\tlet declaredAdditionalTools = false;\n\t/** Tools announced as removed and not declared again since. */\n\tconst unavailableTools = new Set<string>();\n\tconst appendSystemToolAdditions = (message: SystemMessage, seed: string): void => {\n\t\tconst tools = message.toolsAdded ?? [];\n\t\tfor (const tool of tools) unavailableTools.delete(tool.name);\n\t\tif (tools.length === 0) return;\n\t\tif (toolSupport === \"changes\") {\n\t\t\tif (declaredAdditionalTools) {\n\t\t\t\tmessages.push({ role: instructionRole, content: renderIncrementalToolsNotice(unavailableTools) });\n\t\t\t}\n\t\t\tdeclaredAdditionalTools = true;\n\t\t\tmessages.push({\n\t\t\t\ttype: \"additional_tools\",\n\t\t\t\trole: \"developer\",\n\t\t\t\ttools: convertResponsesTools(tools, options?.toolOptions),\n\t\t\t} satisfies ResponseInputItem);\n\t\t\treturn;\n\t\t}\n\t\tif (toolSupport !== \"additions\") return;\n\t\tconst names = tools.map((tool) => tool.name);\n\t\tconst callId = `pi_tool_load_${shortHash(`${seed}:${names.join(\",\")}`)}`;\n\t\tmessages.push({\n\t\t\ttype: \"tool_search_call\",\n\t\t\tcall_id: callId,\n\t\t\texecution: \"client\",\n\t\t\tstatus: \"completed\",\n\t\t\targuments: { query: names.join(\" \"), limit: names.length },\n\t\t} satisfies ResponseInputItem);\n\t\tmessages.push({\n\t\t\ttype: \"tool_search_output\",\n\t\t\tcall_id: callId,\n\t\t\texecution: \"client\",\n\t\t\tstatus: \"completed\",\n\t\t\ttools: convertResponsesTools(tools, { ...options?.toolOptions, toolSearchResult: true }),\n\t\t} satisfies ResponseToolSearchOutputItemParam);\n\t};\n\tconst includeInitialSystemMessage = options?.includeSystemPrompt ?? true;\n\tconst pushConfigurationUpdate = (effort: string): void => {\n\t\tmessages.push({\n\t\t\ttype: \"configuration_update\",\n\t\t\treasoning: { effort: effort as NonNullable<ResponseConfigurationUpdateItemParam.Reasoning[\"effort\"]> },\n\t\t} satisfies ResponseConfigurationUpdateItemParam);\n\t};\n\tconst compat = model.compat as { supportsDeveloperRole?: boolean } | undefined;\n\tconst instructionRole = model.reasoning && compat?.supportsDeveloperRole !== false ? \"developer\" : \"system\";\n\n\tlet msgIndex = 0;\n\tlet sourceIndex = 0;\n\tlet systemIndex = 0;\n\tfor (const msg of transformedMessages) {\n\t\tconst isLeadingSystemMessage = sourceIndex++ === 0 && msg.role === \"system\";\n\t\tif (msg.role === \"system\") {\n\t\t\t// transformMessages keeps system messages in order, so their position matches the transcript.\n\t\t\tconst anchorsToolChanges = systemIndex++ >= transcriptTools.foldedSystemMessages;\n\t\t\tif (anchorsToolChanges) appendSystemToolAdditions(msg, `system:${msgIndex}`);\n\t\t\tif (!isLeadingSystemMessage || includeInitialSystemMessage) {\n\t\t\t\tconst parts = [isLeadingSystemMessage ? getSystemMessageText(msg) : renderSystemMessageUpdate(msg)];\n\t\t\t\tif (anchorsToolChanges) {\n\t\t\t\t\t// A redefinition is a removal plus an addition of the same name; only true removals are announced.\n\t\t\t\t\tconst added = new Set((msg.toolsAdded ?? []).map((tool) => tool.name));\n\t\t\t\t\tconst removed = (msg.toolsRemoved ?? []).map((tool) => tool.name).filter((name) => !added.has(name));\n\t\t\t\t\tif (removed.length > 0) parts.push(renderToolRemovalNotice(removed));\n\t\t\t\t\t// Recorded after this message's additions, whose notice precedes this removal notice.\n\t\t\t\t\tfor (const name of removed) unavailableTools.add(name);\n\t\t\t\t}\n\t\t\t\tconst text = parts.filter((part) => part.length > 0).join(\"\\n\\n\");\n\t\t\t\tif (text.length > 0) {\n\t\t\t\t\tmessages.push({ role: instructionRole, content: sanitizeSurrogates(text) });\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (msg.role === \"user\") {\n\t\t\tif (typeof msg.content === \"string\") {\n\t\t\t\tmessages.push({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent: [{ type: \"input_text\", text: sanitizeSurrogates(msg.content) }],\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({\n\t\t\t\t\trole: \"user\",\n\t\t\t\t\tcontent,\n\t\t\t\t});\n\t\t\t}\n\t\t} else if (msg.role === \"assistant\") {\n\t\t\tconst output: ResponseInput = [];\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isSameProviderAndApi =\n\t\t\t\tnormalizeProviderId(assistantMsg.provider) === normalizeProviderId(model.provider) &&\n\t\t\t\tassistantMsg.api === model.api;\n\t\t\tconst isSameModel = isSameProviderAndApi && assistantMsg.model === model.id;\n\t\t\tconst isDifferentModel = isSameProviderAndApi && assistantMsg.model !== model.id;\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 === \"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\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 item 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// Also drop ids that do not match the replayed item type: function_call ids must be fc_*\n\t\t\t\t\t// and custom_tool_call ids must be ctc_*. Foreign tool call ids are normalized to fc_*, and\n\t\t\t\t\t// a call can switch between the two types when grammar tool support differs.\n\t\t\t\t\tconst itemIdPrefix = customInputProperty === undefined ? \"fc_\" : \"ctc_\";\n\t\t\t\t\tif (isDifferentModel || !itemId?.startsWith(itemIdPrefix)) {\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\t...(isSameModel && toolCall.namespace !== undefined ? { namespace: toolCall.namespace } : {}),\n\t\t\t\t\t\t} satisfies ResponseOutputItem);\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\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\targuments: JSON.stringify(toolCall.arguments),\n\t\t\t\t\t\t\t...(isSameModel && toolCall.namespace !== undefined ? { namespace: toolCall.namespace } : {}),\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\tif (\n\t\t\t\toptions?.configurationUpdateEffort !== undefined &&\n\t\t\t\tisSameModel &&\n\t\t\t\tmsg.providerThinkingLevel !== undefined\n\t\t\t) {\n\t\t\t\tpushConfigurationUpdate(msg.providerThinkingLevel);\n\t\t\t}\n\t\t\tmessages.push(...output);\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\n\t\t\tif (options?.grammarToolInputProperties?.has(msg.toolName)) {\n\t\t\t\tmessages.push({\n\t\t\t\t\ttype: \"custom_tool_call_output\",\n\t\t\t\t\tcall_id: callId,\n\t\t\t\t\toutput,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tmessages.push({\n\t\t\t\t\ttype: \"function_call_output\",\n\t\t\t\t\tcall_id: callId,\n\t\t\t\t\toutput,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tif (!isLeadingSystemMessage) msgIndex++;\n\t}\n\tif (options?.configurationUpdateEffort !== undefined) pushConfigurationUpdate(options.configurationUpdateEffort);\n\n\treturn messages;\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?.toolSearchResult ? { defer_loading: true } : {}),\n\t\t\t} satisfies OpenAITool;\n\t\t}\n\n\t\tconst constrainedStrict = resolveJsonSchemaStrictSampling(tool, supportsStrictMode);\n\t\tconst strict = constrainedStrict ?? defaultStrict;\n\t\tconst functionTool: Omit<Extract<OpenAITool, { type: \"function\" }>, \"strict\"> & {\n\t\t\tstrict?: Extract<OpenAITool, { type: \"function\" }>[\"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: getJsonSchemaToolParameters(tool, strict === true) as Record<string, unknown>,\n\t\t\t...(options?.toolSearchResult ? { defer_loading: true } : {}),\n\t\t};\n\t\tif (supportsStrictMode) {\n\t\t\tfunctionTool.strict = strict;\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\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 applyMessagePhaseStopReason = (item: ResponseOutputItem): void => {\n\t\tif (item.type === \"message\" && item.phase === \"final_answer\") {\n\t\t\toutput.stopReason = \"stop\";\n\t\t}\n\t};\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 = (outputIndex: number, item: ResponseOutputItem): 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\tapplyMessagePhaseStopReason(item);\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\t...(item.namespace !== undefined ? { namespace: item.namespace } : {}),\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 (item.type === \"custom_tool_call\") {\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}`,\n\t\t\t\tname: item.name,\n\t\t\t\targuments: { [inputProperty]: input },\n\t\t\t\t...(item.namespace !== undefined ? { namespace: item.namespace } : {}),\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\treturn undefined;\n\t};\n\tconst getOrCreateSlot = (outputIndex: number, item: ResponseOutputItem): 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): void => {\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 responseServiceTier = normalizeResponseServiceTier(response?.service_tier);\n\t\t\tconst serviceTier = options.resolveServiceTier\n\t\t\t\t? options.resolveServiceTier(responseServiceTier, options.serviceTier)\n\t\t\t\t: (responseServiceTier ?? options.serviceTier);\n\t\t\toptions.applyServiceTierPricing(output.usage, serviceTier);\n\t\t\tif (options.warnOnServiceTierDowngrade) {\n\t\t\t\tappendServiceTierDowngradeWarning(output, model, options.serviceTier, responseServiceTier);\n\t\t\t}\n\t\t}\n\t\t// Map status to stop reason. For incomplete responses, retain the provider's\n\t\t// specific reason so max-output truncation and content filtering stay distinct.\n\t\tconst status = response?.status;\n\t\tconst incompleteDetails = response?.incomplete_details as { reason?: unknown } | null | undefined;\n\t\tconst incompleteReason = typeof incompleteDetails?.reason === \"string\" ? incompleteDetails.reason : undefined;\n\t\tif (output.rawStopReason !== \"refusal\") {\n\t\t\toutput.rawStopReason = incompleteReason ? `${status}.${incompleteReason}` : status;\n\t\t}\n\t\tconst mappedStop = mapStopReason(status, incompleteReason);\n\t\toutput.stopReason = mappedStop.stopReason;\n\t\toutput.errorMessage = mappedStop.errorMessage;\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\tawait options?.onProviderStreamEvent?.(event, model);\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\toutput.rawStopReason = \"refusal\";\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 || !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 || !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\tapplyMessagePhaseStopReason(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\tif (item.content?.some((content) => content.type === \"refusal\")) output.rawStopReason = \"refusal\";\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\tObject.assign(slot.block, parseToolCallArguments(item.arguments || slot.block.partialJson));\n\t\t\t\tif (item.namespace !== undefined) slot.block.namespace = item.namespace;\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\tif (item.namespace !== undefined) slot.block.namespace = item.namespace;\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}\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\toutput.rawStopReason = event.response?.status;\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\tif (!sawTerminalResponseEvent) {\n\t\tthrow new Error(\"OpenAI Responses stream ended before a terminal response event\");\n\t}\n\t// The agent runs every tool call in the final message. Refuse to hand over calls whose\n\t// output_item.done never arrived: their arguments may be cut off or mixed up, e.g. when a\n\t// non-compliant server omits output_index. Finished calls have their scratch buffers removed.\n\tif (output.stopReason === \"toolUse\") {\n\t\tfor (const block of output.content) {\n\t\t\tif (block.type !== \"toolCall\") continue;\n\t\t\tconst toolCall = block as StreamingToolCall;\n\t\t\tif (toolCall.partialJson !== undefined || toolCall.customInput !== undefined) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`OpenAI Responses stream completed with an unfinished tool call: ${toolCall.name} (${toolCall.id})`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction mapStopReason(\n\tstatus: OpenAI.Responses.ResponseStatus | undefined,\n\tincompleteReason?: string,\n): { stopReason: StopReason; errorMessage?: string } {\n\tif (!status) return { stopReason: \"stop\" };\n\tswitch (status) {\n\t\tcase \"completed\":\n\t\t\treturn { stopReason: \"stop\" };\n\t\tcase \"incomplete\":\n\t\t\tif (incompleteReason === \"max_output_tokens\") {\n\t\t\t\treturn { stopReason: \"length\" };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstopReason: \"error\",\n\t\t\t\terrorMessage: incompleteReason\n\t\t\t\t\t? `Response incomplete: ${incompleteReason}`\n\t\t\t\t\t: \"Response incomplete without a provider reason\",\n\t\t\t};\n\t\tcase \"failed\":\n\t\tcase \"cancelled\":\n\t\t\treturn { stopReason: \"error\" };\n\t\t// These two are wonky ...\n\t\tcase \"in_progress\":\n\t\tcase \"queued\":\n\t\t\treturn { stopReason: \"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 +1 @@
1
- {"version":3,"file":"openai-responses.d.ts","sourceRoot":"","sources":["../../src/api/openai-responses.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,yCAAyC,CAAC;AAE7F,OAAO,KAAK,EAQX,mBAAmB,EACnB,cAAc,EACd,aAAa,EAEb,MAAM,aAAa,CAAC;AAiBrB,OAAO,EAUN,KAAK,oBAAoB,EAGzB,MAAM,8BAA8B,CAAC;AAkHtC,MAAM,WAAW,sBAAuB,SAAQ,aAAa;IAC5D,eAAe,CAAC,EAAE,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,GAAG,KAAK,CAAC;IAC1E,gBAAgB,CAAC,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,GAAG,IAAI,CAAC;IAC1D,WAAW,CAAC,EAAE,oBAAoB,CAAC;IACnC,UAAU,CAAC,EAAE,6BAA6B,CAAC,aAAa,CAAC,CAAC;CAC1D;AAED;;GAEG;AACH,eAAO,MAAM,MAAM,EAAE,cAAc,CAAC,kBAAkB,EAAE,sBAAsB,CAqJ7E,CAAC;AAuDF,eAAO,MAAM,YAAY,EAAE,cAAc,CAAC,kBAAkB,EAAE,mBAAmB,CAkBhF,CAAC"}
1
+ {"version":3,"file":"openai-responses.d.ts","sourceRoot":"","sources":["../../src/api/openai-responses.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,yCAAyC,CAAC;AAE7F,OAAO,KAAK,EAQX,mBAAmB,EACnB,cAAc,EACd,aAAa,EAEb,MAAM,aAAa,CAAC;AAiBrB,OAAO,EAWN,KAAK,oBAAoB,EAGzB,MAAM,8BAA8B,CAAC;AAkHtC,MAAM,WAAW,sBAAuB,SAAQ,aAAa;IAC5D,eAAe,CAAC,EAAE,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,GAAG,KAAK,CAAC;IAC1E,gBAAgB,CAAC,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS,GAAG,IAAI,CAAC;IAC1D,WAAW,CAAC,EAAE,oBAAoB,CAAC;IACnC,UAAU,CAAC,EAAE,6BAA6B,CAAC,aAAa,CAAC,CAAC;CAC1D;AAED;;GAEG;AACH,eAAO,MAAM,MAAM,EAAE,cAAc,CAAC,kBAAkB,EAAE,sBAAsB,CAqJ7E,CAAC;AAuDF,eAAO,MAAM,YAAY,EAAE,cAAc,CAAC,kBAAkB,EAAE,mBAAmB,CAkBhF,CAAC"}
@@ -11,7 +11,7 @@ import { getDeclaredTools, resolveTranscript, resolveTranscriptTools } from "../
11
11
  import { createGrammarToolInputProperties } from "./constrained-sampling.js";
12
12
  import { buildCopilotDynamicHeaders, hasCopilotVisionInput, preserveCopilotIntegrationHeader, } from "./github-copilot-headers.js";
13
13
  import { clampOpenAIPromptCacheKey } from "./openai-prompt-cache.js";
14
- import { appendServiceTierRejectedWarning, applyServiceTierPricing, assertPayloadPreservesFastRoute, convertResponsesMessages, convertResponsesTools, isChatGPTSubscriptionToken, isServiceTierRejection, openAIServiceTierForRequest, processResponsesStream, resolveChatGPTBackendServiceTier, resolveRequestedServiceTier, } from "./openai-responses-shared.js";
14
+ import { appendServiceTierRejectedWarning, applyServiceTierPricing, assertPayloadPreservesFastRoute, convertResponsesMessages, convertResponsesTools, getResponsesToolSupport, isChatGPTSubscriptionToken, isServiceTierRejection, openAIServiceTierForRequest, processResponsesStream, resolveChatGPTBackendServiceTier, resolveRequestedServiceTier, } from "./openai-responses-shared.js";
15
15
  import { RetryHintOpenAI } from "./openai-retry-hint-client.js";
16
16
  import { buildBaseOptions, resolveSamplingParams } from "./simple-options.js";
17
17
  const OPENAI_TOOL_CALL_PROVIDERS = new Set(["openai", "openai-api", "openai-codex", "opencode"]);
@@ -333,7 +333,7 @@ function createClient(model, context, apiKey, optionsHeaders, fetch, sessionId,
333
333
  });
334
334
  }
335
335
  function buildParams(model, context, options, compat, grammarToolInputProperties, configurationUpdateEffort) {
336
- const transcriptTools = resolveTranscriptTools(context.messages, compat.supportsAdditionalTools || compat.supportsToolSearch);
336
+ const transcriptTools = resolveTranscriptTools(context.messages, getResponsesToolSupport(compat));
337
337
  const messages = convertResponsesMessages(model, context, OPENAI_TOOL_CALL_PROVIDERS, {
338
338
  grammarToolInputProperties,
339
339
  supportsMidConvoSystemMessages: compat.supportsMidConvoSystemMessages,