@bastani/pi-ai 0.9.24 → 0.9.25-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/NOTICE.md +1 -1
- package/README.md +17 -6
- package/dist/api/cloudflare-workers-ai-system-one.js +2 -2
- package/dist/api/cloudflare-workers-ai-system-one.js.map +1 -1
- package/dist/api/openai-codex-responses.d.ts +2 -2
- package/dist/api/openai-codex-responses.d.ts.map +1 -1
- package/dist/api/openai-codex-responses.js +8 -28
- package/dist/api/openai-codex-responses.js.map +1 -1
- package/dist/api/openai-responses-shared.d.ts +25 -6
- package/dist/api/openai-responses-shared.d.ts.map +1 -1
- package/dist/api/openai-responses-shared.js +66 -19
- package/dist/api/openai-responses-shared.js.map +1 -1
- package/dist/api/openai-responses.d.ts +2 -1
- package/dist/api/openai-responses.d.ts.map +1 -1
- package/dist/api/openai-responses.js +21 -32
- package/dist/api/openai-responses.js.map +1 -1
- package/dist/api/system-one-shared.d.ts +2 -2
- package/dist/api/system-one-shared.d.ts.map +1 -1
- package/dist/api/system-one-shared.js +26 -1
- package/dist/api/system-one-shared.js.map +1 -1
- package/dist/api/typesafe-system-one.js +2 -2
- package/dist/api/typesafe-system-one.js.map +1 -1
- package/dist/auth/helpers.js +1 -1
- package/dist/auth/helpers.js.map +1 -1
- package/dist/auth/oauth/anthropic.d.ts.map +1 -1
- package/dist/auth/oauth/anthropic.js +19 -128
- package/dist/auth/oauth/anthropic.js.map +1 -1
- package/dist/auth/oauth/callback-server.d.ts +31 -0
- package/dist/auth/oauth/callback-server.d.ts.map +1 -0
- package/dist/auth/oauth/callback-server.js +138 -0
- package/dist/auth/oauth/callback-server.js.map +1 -0
- package/dist/auth/oauth/load.d.ts +2 -0
- package/dist/auth/oauth/load.d.ts.map +1 -1
- package/dist/auth/oauth/load.js +5 -0
- package/dist/auth/oauth/load.js.map +1 -1
- package/dist/auth/oauth/oauth-page.js +1 -1
- package/dist/auth/oauth/oauth-page.js.map +1 -1
- package/dist/auth/oauth/openai-chatgpt.d.ts +3 -0
- package/dist/auth/oauth/openai-chatgpt.d.ts.map +1 -0
- package/dist/auth/oauth/openai-chatgpt.js +250 -0
- package/dist/auth/oauth/openai-chatgpt.js.map +1 -0
- package/dist/auth/oauth/openai-codex.d.ts +1 -1
- package/dist/auth/oauth/openai-codex.d.ts.map +1 -1
- package/dist/auth/oauth/openai-codex.js +20 -124
- package/dist/auth/oauth/openai-codex.js.map +1 -1
- package/dist/auth/oauth/openrouter.d.ts +1 -1
- package/dist/auth/oauth/openrouter.d.ts.map +1 -1
- package/dist/auth/oauth/openrouter.js +19 -138
- package/dist/auth/oauth/openrouter.js.map +1 -1
- package/dist/auth/oauth/radius.d.ts +1 -1
- package/dist/auth/oauth/radius.d.ts.map +1 -1
- package/dist/auth/oauth/radius.js +21 -89
- package/dist/auth/oauth/radius.js.map +1 -1
- package/dist/auth/types.d.ts +6 -1
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/auth/types.js.map +1 -1
- package/dist/bun-oauth.d.ts.map +1 -1
- package/dist/bun-oauth.js +2 -0
- package/dist/bun-oauth.js.map +1 -1
- package/dist/cli.js +2 -1
- package/dist/cli.js.map +1 -1
- package/dist/models.d.ts +5 -3
- package/dist/models.d.ts.map +1 -1
- package/dist/models.js +6 -2
- package/dist/models.js.map +1 -1
- package/dist/providers/data/.manifest.json +1 -1
- package/dist/providers/data/amazon-bedrock.json +1 -1
- package/dist/providers/data/azure-openai-responses.json +1 -1
- package/dist/providers/data/baseten.json +1 -1
- package/dist/providers/data/cerebras.json +1 -1
- package/dist/providers/data/github-copilot.json +1 -1
- package/dist/providers/data/openai-codex.json +1 -1
- package/dist/providers/data/openai.json +1 -1
- package/dist/providers/data/opencode.json +1 -1
- package/dist/providers/data/openrouter.json +1 -1
- package/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/providers/openai-codex.js +1 -1
- package/dist/providers/openai-codex.js.map +1 -1
- package/dist/providers/openai.d.ts.map +1 -1
- package/dist/providers/openai.js +11 -2
- package/dist/providers/openai.js.map +1 -1
- package/dist/providers/opencode.d.ts +3 -1
- package/dist/providers/opencode.d.ts.map +1 -1
- package/dist/providers/opencode.js +4 -2
- package/dist/providers/opencode.js.map +1 -1
- package/dist/providers/vercel-ai-gateway.d.ts.map +1 -1
- package/dist/providers/vercel-ai-gateway.js +4 -2
- package/dist/providers/vercel-ai-gateway.js.map +1 -1
- package/dist/types.d.ts +40 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/oauth-page.d.ts +2 -0
- package/dist/utils/oauth-page.d.ts.map +1 -0
- package/dist/utils/oauth-page.js +2 -0
- package/dist/utils/oauth-page.js.map +1 -0
- package/dist/utils/retry.d.ts.map +1 -1
- package/dist/utils/retry.js +3 -0
- package/dist/utils/retry.js.map +1 -1
- package/package.json +6 -2
|
@@ -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,EAClB,6BAA6B,EAC7B,aAAa,EAQb,mBAAmB,EAEnB,MAAM,yCAAyC,CAAC;AAEjD,OAAO,KAAK,EACX,GAAG,EACH,gBAAgB,EAEhB,KAAK,
|
|
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,EAClB,6BAA6B,EAC7B,aAAa,EAQb,mBAAmB,EAEnB,MAAM,yCAAyC,CAAC;AAEjD,OAAO,KAAK,EACX,GAAG,EACH,gBAAgB,EAEhB,KAAK,EAGL,aAAa,EAKb,IAAI,EAEJ,iBAAiB,EACjB,KAAK,EACL,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,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AC,EAAE,+BAA+B,GACvC,aAAa,CA6Mf;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,CAkVf"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { calculateCost } from "../models.js";
|
|
1
|
+
import { calculateCost, getServiceTierCost } from "../models.js";
|
|
2
2
|
import { shortHash } from "../utils/hash.js";
|
|
3
3
|
import { parseStreamingJson } from "../utils/json-parse.js";
|
|
4
4
|
import { sanitizeSurrogates } from "../utils/sanitize-unicode.js";
|
|
@@ -57,25 +57,69 @@ function convertToolResultOutput(model, content) {
|
|
|
57
57
|
}
|
|
58
58
|
return output;
|
|
59
59
|
}
|
|
60
|
-
/**
|
|
61
|
-
* The service tier this request should carry.
|
|
62
|
-
*
|
|
63
|
-
* The **presence** of `fastRoute` is the discriminator, and its declared tier is the value. Fast
|
|
64
|
-
* versus normal is model identity, so a caller who wants a different tier selects the normal sibling
|
|
65
|
-
* rather than downgrading the fast one; letting a per-request option win would let a model selected,
|
|
66
|
-
* recorded, persisted, and billed as `-fast` route as an ordinary request — and, because the Codex
|
|
67
|
-
* routing identity keys on the final payload's tier, silently drop `originator: codex_cli_rs` too.
|
|
68
|
-
*
|
|
69
|
-
* A route that declares **no** tier means *no tier*, not "fall through to the caller". A GitHub
|
|
70
|
-
* Copilot fast variant is exactly that case: it sends its own advertised `-fast` model ID and must
|
|
71
|
-
* carry no OpenAI service-tier field at all, whatever the caller asks for.
|
|
72
|
-
*
|
|
73
|
-
* A normal model has no route, so an explicit `serviceTier` still applies there exactly as it did
|
|
74
|
-
* before fast variants existed.
|
|
75
|
-
*/
|
|
76
60
|
export function resolveRequestedServiceTier(model, optionsServiceTier) {
|
|
77
61
|
return model.fastRoute ? model.fastRoute.serviceTier : optionsServiceTier;
|
|
78
62
|
}
|
|
63
|
+
function advertisedServiceTierId(serviceTier) {
|
|
64
|
+
if (serviceTier === "priority" || serviceTier === "fast")
|
|
65
|
+
return "priority";
|
|
66
|
+
return serviceTier === "ultrafast" ? "ultrafast" : undefined;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Whether the model offers a Fast or Ultrafast tier. A model without tier metadata keeps offering Fast
|
|
70
|
+
* but never Ultrafast. Other tiers (`flex`, `default`, `auto`, `scale`) need no advertisement.
|
|
71
|
+
*/
|
|
72
|
+
export function supportsServiceTier(model, serviceTier) {
|
|
73
|
+
const advertisedId = advertisedServiceTierId(serviceTier);
|
|
74
|
+
if (advertisedId === undefined)
|
|
75
|
+
return true;
|
|
76
|
+
if (model.serviceTiers === undefined)
|
|
77
|
+
return advertisedId !== "ultrafast";
|
|
78
|
+
return getServiceTierCost(model, advertisedId) !== undefined;
|
|
79
|
+
}
|
|
80
|
+
/** OpenAI API: drop a Fast or Ultrafast tier the model does not advertise and send any other tier as asked. */
|
|
81
|
+
export function openAIServiceTierForRequest(model, serviceTier) {
|
|
82
|
+
return serviceTier !== undefined && supportsServiceTier(model, serviceTier) ? serviceTier : undefined;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Codex's `service_tier_for_request`: send `flex` or an advertised tier, and omit `default` and every
|
|
86
|
+
* tier the model does not advertise.
|
|
87
|
+
*/
|
|
88
|
+
export function codexServiceTierForRequest(model, serviceTier) {
|
|
89
|
+
if (serviceTier === "flex")
|
|
90
|
+
return serviceTier;
|
|
91
|
+
return advertisedServiceTierId(serviceTier) !== undefined && supportsServiceTier(model, serviceTier)
|
|
92
|
+
? serviceTier
|
|
93
|
+
: undefined;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Reprice usage at the tier that actually served the request, using the advertised tier's published
|
|
97
|
+
* rates. A model without tier metadata keeps the documented Fast multiplier.
|
|
98
|
+
*/
|
|
99
|
+
export function applyServiceTierPricing(usage, serviceTier, model) {
|
|
100
|
+
if (serviceTier === "flex") {
|
|
101
|
+
scaleUsageCost(usage, 0.5);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
const advertisedId = advertisedServiceTierId(serviceTier);
|
|
105
|
+
if (advertisedId === undefined)
|
|
106
|
+
return;
|
|
107
|
+
const tierCost = getServiceTierCost(model, advertisedId);
|
|
108
|
+
if (tierCost) {
|
|
109
|
+
calculateCost({ ...model, cost: tierCost }, usage);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
if (advertisedId === "priority") {
|
|
113
|
+
scaleUsageCost(usage, (model.fastRoute?.baseModelId ?? model.id) === "gpt-5.5" ? 2.5 : 2);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
function scaleUsageCost(usage, multiplier) {
|
|
117
|
+
usage.cost.input *= multiplier;
|
|
118
|
+
usage.cost.output *= multiplier;
|
|
119
|
+
usage.cost.cacheRead *= multiplier;
|
|
120
|
+
usage.cost.cacheWrite *= multiplier;
|
|
121
|
+
usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
|
|
122
|
+
}
|
|
79
123
|
export function normalizeResponseServiceTier(serviceTier) {
|
|
80
124
|
if (serviceTier === null || serviceTier === undefined)
|
|
81
125
|
return undefined;
|
|
@@ -109,8 +153,11 @@ export function assertPayloadPreservesFastRoute(model, payload) {
|
|
|
109
153
|
if (record.model !== fastRoute.upstreamModelId) {
|
|
110
154
|
conflicts.push(`model (expected "${fastRoute.upstreamModelId}", got ${JSON.stringify(record.model)})`);
|
|
111
155
|
}
|
|
112
|
-
|
|
113
|
-
|
|
156
|
+
const expectedServiceTier = fastRoute.serviceTier !== undefined && supportsServiceTier(model, fastRoute.serviceTier)
|
|
157
|
+
? fastRoute.serviceTier
|
|
158
|
+
: undefined;
|
|
159
|
+
if (record.service_tier !== expectedServiceTier) {
|
|
160
|
+
conflicts.push(`service_tier (expected ${JSON.stringify(expectedServiceTier)}, got ${JSON.stringify(record.service_tier)})`);
|
|
114
161
|
}
|
|
115
162
|
if (conflicts.length === 0)
|
|
116
163
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-responses-shared.js","sourceRoot":"","sources":["../../src/api/openai-responses-shared.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAkB7C,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,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,CAAC;IACjC,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;AAChC,CAAC;AAED,SAAS,kBAAkB,CAC1B,SAA6B;IAE7B,IAAI,CAAC,S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,IAAI,KAAK,CACd,mEAAmE,QAAQ,CAAC,IAAI,KAAK,QAAQ,CAAC,EAAE,GAAG,CACnG,CAAC;YACH,CAAC;QACF,CAAC;IACF,CAAC;AACF,CAAC;AAED,SAAS,aAAa,CACrB,MAAmD,EACnD,gBAAyB;IAEzB,IAAI,CAAC,MAAM;QAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC;IAC3C,QAAQ,MAAM,EAAE,CAAC;QAChB,KAAK,WAAW;YACf,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC;QAC/B,KAAK,YAAY;YAChB,IAAI,gBAAgB,KAAK,mBAAmB,EAAE,CAAC;gBAC9C,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC;YACjC,CAAC;YACD,OAAO;gBACN,UAAU,EAAE,OAAO;gBACnB,YAAY,EAAE,gBAAgB;oBAC7B,CAAC,CAAC,wBAAwB,gBAAgB,EAAE;oBAC5C,CAAC,CAAC,+CAA+C;aAClD,CAAC;QACH,KAAK,QAAQ,CAAC;QACd,KAAK,WAAW;YACf,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,CAAC;QAChC,0BAA0B;QAC1B,KAAK,aAAa,CAAC;QACnB,KAAK,QAAQ;YACZ,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC;QAC/B,SAAS,CAAC;YACT,MAAM,WAAW,GAAU,MAAM,CAAC;YAClC,MAAM,IAAI,KAAK,CAAC,0BAA0B,WAAW,EAAE,CAAC,CAAC;QAC1D,CAAC;IACF,CAAC;AACF,CAAC","sourcesContent":["import type OpenAI from \"openai\";\nimport type {\n\tTool as OpenAITool,\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 } from \"../models.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tImageContent,\n\tModel,\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 type { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { parseStreamingJson } from \"../utils/json-parse.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { 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.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 */\nexport function resolveRequestedServiceTier(\n\tmodel: Pick<Model<Api>, \"fastRoute\">,\n\toptionsServiceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n): ResponseCreateParamsStreaming[\"service_tier\"] | undefined {\n\treturn model.fastRoute ? model.fastRoute.serviceTier : optionsServiceTier;\n}\n\ntype ServiceTier = NonNullable<ResponseCreateParamsStreaming[\"service_tier\"]>;\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\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\">,\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\tif (record.service_tier !== fastRoute.serviceTier) {\n\t\tconflicts.push(\n\t\t\t`service_tier (expected ${JSON.stringify(fastRoute.serviceTier)}, 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?: ResponseCreateParamsStreaming[\"service_tier\"];\n\tgrammarToolInputProperties?: ReadonlyMap<string, string>;\n\tresolveServiceTier?: (\n\t\tresponseServiceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\t\trequestServiceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\t) => ResponseCreateParamsStreaming[\"service_tier\"] | undefined;\n\tapplyServiceTierPricing?: (\n\t\tusage: Usage,\n\t\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\t) => void;\n}\n\nexport interface ConvertResponsesMessagesOptions {\n\tincludeSystemPrompt?: boolean;\n\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}\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 = source.provider !== model.provider || source.api !== model.api;\n\t\tlet normalizedItemId = isForeignToolCall ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId);\n\t\t// OpenAI Responses API requires item id to start with \"fc\"\n\t\tif (!normalizedItemId.startsWith(\"fc_\")) {\n\t\t\tnormalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);\n\t\t}\n\t\treturn `${normalizedCallId}|${normalizedItemId}`;\n\t};\n\n\tconst transformedMessages = transformMessages(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 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 = assistantMsg.provider === model.provider && assistantMsg.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 fc_xxx IDs were paired with rs_xxx reasoning items.\n\t\t\t\t\t// By omitting the id, we avoid triggering that validation (like cross-provider does).\n\t\t\t\t\t// When replaying custom-tool calls as a function_call, also drop non-fc_* ids such as\n\t\t\t\t\t// ctc_* custom-tool ids because function_call item ids must be fc_*.\n\t\t\t\t\tif (\n\t\t\t\t\t\t(isDifferentModel && itemId?.startsWith(\"fc_\")) ||\n\t\t\t\t\t\t(customInputProperty === undefined && !itemId?.startsWith(\"fc_\"))\n\t\t\t\t\t) {\n\t\t\t\t\t\titemId = undefined;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (customInputProperty !== undefined) {\n\t\t\t\t\t\toutput.push({\n\t\t\t\t\t\t\ttype: \"custom_tool_call\",\n\t\t\t\t\t\t\tid: itemId,\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\tname: toolCall.name,\n\t\t\t\t\t\t\tinput: sanitizeSurrogates(\n\t\t\t\t\t\t\t\tgetGrammarToolInput(toolCall.name, toolCall.arguments, customInputProperty),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\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\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\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}\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\toutput.rawStopReason = incompleteReason ? `${status}.${incompleteReason}` : status;\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\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\tslot.block.text = item.content?.map((c) => (c.type === \"output_text\" ? c.text : c.refusal)).join(\"\") || \"\";\n\t\t\t\tslot.block.textSignature = encodeTextSignatureV1(item.id, item.phase ?? undefined);\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\t\tcontent: slot.block.text,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\toutputSlots.delete(event.output_index);\n\t\t\t} else if (\n\t\t\t\titem.type === \"function_call\" &&\n\t\t\t\tslot?.type === \"toolCall\" &&\n\t\t\t\tslot.block.partialJson !== undefined\n\t\t\t) {\n\t\t\t\tslot.block.arguments = parseStreamingJson(item.arguments || slot.block.partialJson || \"{}\");\n\t\t\t\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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;gBAC9C,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,CAAC;YACjC,CAAC;YACD,OAAO;gBACN,UAAU,EAAE,OAAO;gBACnB,YAAY,EAAE,gBAAgB;oBAC7B,CAAC,CAAC,wBAAwB,gBAAgB,EAAE;oBAC5C,CAAC,CAAC,+CAA+C;aAClD,CAAC;QACH,KAAK,QAAQ,CAAC;QACd,KAAK,WAAW;YACf,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,CAAC;QAChC,0BAA0B;QAC1B,KAAK,aAAa,CAAC;QACnB,KAAK,QAAQ;YACZ,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,CAAC;QAC/B,SAAS,CAAC;YACT,MAAM,WAAW,GAAU,MAAM,CAAC;YAClC,MAAM,IAAI,KAAK,CAAC,0BAA0B,WAAW,EAAE,CAAC,CAAC;QAC1D,CAAC;IACF,CAAC;AACF,CAAC","sourcesContent":["import type OpenAI from \"openai\";\nimport type {\n\tTool as OpenAITool,\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 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 type { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { shortHash } from \"../utils/hash.ts\";\nimport { parseStreamingJson } from \"../utils/json-parse.ts\";\nimport { sanitizeSurrogates } from \"../utils/sanitize-unicode.ts\";\nimport { 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.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\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}\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}\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 = source.provider !== model.provider || source.api !== model.api;\n\t\tlet normalizedItemId = isForeignToolCall ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId);\n\t\t// OpenAI Responses API requires item id to start with \"fc\"\n\t\tif (!normalizedItemId.startsWith(\"fc_\")) {\n\t\t\tnormalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);\n\t\t}\n\t\treturn `${normalizedCallId}|${normalizedItemId}`;\n\t};\n\n\tconst transformedMessages = transformMessages(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 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 = assistantMsg.provider === model.provider && assistantMsg.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 fc_xxx IDs were paired with rs_xxx reasoning items.\n\t\t\t\t\t// By omitting the id, we avoid triggering that validation (like cross-provider does).\n\t\t\t\t\t// When replaying custom-tool calls as a function_call, also drop non-fc_* ids such as\n\t\t\t\t\t// ctc_* custom-tool ids because function_call item ids must be fc_*.\n\t\t\t\t\tif (\n\t\t\t\t\t\t(isDifferentModel && itemId?.startsWith(\"fc_\")) ||\n\t\t\t\t\t\t(customInputProperty === undefined && !itemId?.startsWith(\"fc_\"))\n\t\t\t\t\t) {\n\t\t\t\t\t\titemId = undefined;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (customInputProperty !== undefined) {\n\t\t\t\t\t\toutput.push({\n\t\t\t\t\t\t\ttype: \"custom_tool_call\",\n\t\t\t\t\t\t\tid: itemId,\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\tname: toolCall.name,\n\t\t\t\t\t\t\tinput: sanitizeSurrogates(\n\t\t\t\t\t\t\t\tgetGrammarToolInput(toolCall.name, toolCall.arguments, customInputProperty),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\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\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\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}\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\toutput.rawStopReason = incompleteReason ? `${status}.${incompleteReason}` : status;\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\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\tslot.block.text = item.content?.map((c) => (c.type === \"output_text\" ? c.text : c.refusal)).join(\"\") || \"\";\n\t\t\t\tslot.block.textSignature = encodeTextSignatureV1(item.id, item.phase ?? undefined);\n\t\t\t\tstream.push({\n\t\t\t\t\ttype: \"text_end\",\n\t\t\t\t\tcontentIndex: slot.contentIndex,\n\t\t\t\t\tcontent: slot.block.text,\n\t\t\t\t\tpartial: output,\n\t\t\t\t});\n\t\t\t\toutputSlots.delete(event.output_index);\n\t\t\t} else if (\n\t\t\t\titem.type === \"function_call\" &&\n\t\t\t\tslot?.type === \"toolCall\" &&\n\t\t\t\tslot.block.partialJson !== undefined\n\t\t\t) {\n\t\t\t\tslot.block.arguments = parseStreamingJson(item.arguments || slot.block.partialJson || \"{}\");\n\t\t\t\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,9 +1,10 @@
|
|
|
1
1
|
import type { ResponseCreateParamsStreaming } from "openai/resources/responses/responses.js";
|
|
2
2
|
import type { SimpleStreamOptions, StreamFunction, StreamOptions } from "../types.ts";
|
|
3
|
+
import { type ResponsesServiceTier } from "./openai-responses-shared.ts";
|
|
3
4
|
export interface OpenAIResponsesOptions extends StreamOptions {
|
|
4
5
|
reasoningEffort?: "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
|
|
5
6
|
reasoningSummary?: "auto" | "detailed" | "concise" | null;
|
|
6
|
-
serviceTier?:
|
|
7
|
+
serviceTier?: ResponsesServiceTier;
|
|
7
8
|
toolChoice?: ResponseCreateParamsStreaming["tool_choice"];
|
|
8
9
|
}
|
|
9
10
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openai-responses.d.ts","sourceRoot":"","sources":["../../src/api/openai-responses.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,yCAAyC,CAAC;AAE7F,OAAO,KAAK,EAQX,mBAAmB,EACnB,cAAc,EACd,aAAa,EAGb,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"openai-responses.d.ts","sourceRoot":"","sources":["../../src/api/openai-responses.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,6BAA6B,EAAE,MAAM,yCAAyC,CAAC;AAE7F,OAAO,KAAK,EAQX,mBAAmB,EACnB,cAAc,EACd,aAAa,EAGb,MAAM,aAAa,CAAC;AAgBrB,OAAO,EAMN,KAAK,oBAAoB,EAGzB,MAAM,8BAA8B,CAAC;AAqFtC,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,CAwH7E,CAAC;AAEF,eAAO,MAAM,YAAY,EAAE,cAAc,CAAC,kBAAkB,EAAE,mBAAmB,CAkBhF,CAAC"}
|
|
@@ -11,11 +11,18 @@ 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 { assertPayloadPreservesFastRoute, convertResponsesMessages, convertResponsesTools, processResponsesStream, resolveRequestedServiceTier, } from "./openai-responses-shared.js";
|
|
14
|
+
import { applyServiceTierPricing, assertPayloadPreservesFastRoute, convertResponsesMessages, convertResponsesTools, processResponsesStream, resolveRequestedServiceTier, openAIServiceTierForRequest, } from "./openai-responses-shared.js";
|
|
15
15
|
import { buildBaseOptions } from "./simple-options.js";
|
|
16
16
|
const OPENAI_TOOL_CALL_PROVIDERS = new Set(["openai", "openai-codex", "opencode"]);
|
|
17
17
|
// OpenAI Responses rejects max_output_tokens below 16: https://github.com/earendil-works/pi/issues/6265
|
|
18
18
|
const OPENAI_RESPONSES_MIN_OUTPUT_TOKENS = 16;
|
|
19
|
+
const CHATGPT_USAGE_URL = "https://chatgpt.com/settings/usage";
|
|
20
|
+
function isChatGPTSignIn(model, apiKey) {
|
|
21
|
+
return (model.provider === "openai" &&
|
|
22
|
+
model.baseUrl === "https://api.openai.com/v1" &&
|
|
23
|
+
apiKey !== undefined &&
|
|
24
|
+
!apiKey.startsWith("sk-"));
|
|
25
|
+
}
|
|
19
26
|
function hasHeader(headers, name) {
|
|
20
27
|
if (!headers)
|
|
21
28
|
return false;
|
|
@@ -131,7 +138,7 @@ export const stream = (model, context, options) => {
|
|
|
131
138
|
stream.push({ type: "start", partial: output });
|
|
132
139
|
await processResponsesStream(withStreamDeadline(openaiStream, streamDeadline.deadlineMs, streamDeadline.abort), output, stream, model, {
|
|
133
140
|
onProviderStreamEvent: options?.onProviderStreamEvent,
|
|
134
|
-
serviceTier:
|
|
141
|
+
serviceTier: resolveOpenAIRequestServiceTier(model, options?.serviceTier),
|
|
135
142
|
grammarToolInputProperties,
|
|
136
143
|
applyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),
|
|
137
144
|
});
|
|
@@ -155,7 +162,10 @@ export const stream = (model, context, options) => {
|
|
|
155
162
|
delete block.customInput;
|
|
156
163
|
}
|
|
157
164
|
output.stopReason = options?.signal?.aborted ? "aborted" : "error";
|
|
158
|
-
|
|
165
|
+
const errorMessage = formatProviderError(normalizeProviderError(error), `${model.provider === "openai" ? "OpenAI" : model.provider} API error`);
|
|
166
|
+
output.errorMessage = errorMessage.includes("subscription_sharing_usage_limit_exceeded")
|
|
167
|
+
? `${errorMessage}\nCheck your ChatGPT usage: ${CHATGPT_USAGE_URL}`
|
|
168
|
+
: errorMessage;
|
|
159
169
|
stream.push({ type: "error", reason: output.stopReason, error: output });
|
|
160
170
|
stream.end();
|
|
161
171
|
}
|
|
@@ -226,6 +236,7 @@ function buildParams(model, context, options, compat = getCompat(model), grammar
|
|
|
226
236
|
},
|
|
227
237
|
});
|
|
228
238
|
const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);
|
|
239
|
+
const omitUnsupportedFields = isChatGPTSignIn(model, options?.apiKey);
|
|
229
240
|
const params = {
|
|
230
241
|
// A fast variant keeps its canonical `-fast` id on the model object — that is the identity the
|
|
231
242
|
// caller selected and records — while routing to the base upstream model plus a service tier.
|
|
@@ -233,18 +244,17 @@ function buildParams(model, context, options, compat = getCompat(model), grammar
|
|
|
233
244
|
input: messages,
|
|
234
245
|
stream: true,
|
|
235
246
|
prompt_cache_key: cacheRetention === "none" ? undefined : clampOpenAIPromptCacheKey(options?.sessionId),
|
|
236
|
-
prompt_cache_retention: getPromptCacheRetention(compat, cacheRetention),
|
|
237
|
-
prompt_cache_options: getPromptCacheOptions(compat, cacheRetention),
|
|
247
|
+
prompt_cache_retention: omitUnsupportedFields ? undefined : getPromptCacheRetention(compat, cacheRetention),
|
|
248
|
+
prompt_cache_options: omitUnsupportedFields ? undefined : getPromptCacheOptions(compat, cacheRetention),
|
|
238
249
|
store: false,
|
|
239
250
|
};
|
|
240
|
-
if (options?.maxTokens && compat.supportsMaxOutputTokens) {
|
|
251
|
+
if (options?.maxTokens && compat.supportsMaxOutputTokens && !omitUnsupportedFields) {
|
|
241
252
|
params.max_output_tokens = Math.max(options.maxTokens, OPENAI_RESPONSES_MIN_OUTPUT_TOKENS);
|
|
242
253
|
}
|
|
243
|
-
if (options?.temperature !== undefined) {
|
|
254
|
+
if (options?.temperature !== undefined && !omitUnsupportedFields) {
|
|
244
255
|
params.temperature = options?.temperature;
|
|
245
256
|
}
|
|
246
|
-
|
|
247
|
-
const requestedServiceTier = resolveRequestedServiceTier(model, options?.serviceTier);
|
|
257
|
+
const requestedServiceTier = resolveOpenAIRequestServiceTier(model, options?.serviceTier);
|
|
248
258
|
if (requestedServiceTier !== undefined) {
|
|
249
259
|
params.service_tier = requestedServiceTier;
|
|
250
260
|
}
|
|
@@ -280,28 +290,7 @@ function buildParams(model, context, options, compat = getCompat(model), grammar
|
|
|
280
290
|
Object.assign(params, model.samplingParams, options?.samplingParams);
|
|
281
291
|
return params;
|
|
282
292
|
}
|
|
283
|
-
function
|
|
284
|
-
|
|
285
|
-
// per-model rate (gpt-5.5) is not silently charged the generic multiplier.
|
|
286
|
-
const pricedModelId = model.fastRoute?.baseModelId ?? model.id;
|
|
287
|
-
switch (serviceTier) {
|
|
288
|
-
case "flex":
|
|
289
|
-
return 0.5;
|
|
290
|
-
case "priority":
|
|
291
|
-
case "fast":
|
|
292
|
-
return pricedModelId === "gpt-5.5" ? 2.5 : 2;
|
|
293
|
-
default:
|
|
294
|
-
return 1;
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
function applyServiceTierPricing(usage, serviceTier, model) {
|
|
298
|
-
const multiplier = getServiceTierCostMultiplier(model, serviceTier);
|
|
299
|
-
if (multiplier === 1)
|
|
300
|
-
return;
|
|
301
|
-
usage.cost.input *= multiplier;
|
|
302
|
-
usage.cost.output *= multiplier;
|
|
303
|
-
usage.cost.cacheRead *= multiplier;
|
|
304
|
-
usage.cost.cacheWrite *= multiplier;
|
|
305
|
-
usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
|
|
293
|
+
function resolveOpenAIRequestServiceTier(model, optionsServiceTier) {
|
|
294
|
+
return openAIServiceTierForRequest(model, resolveRequestedServiceTier(model, optionsServiceTier));
|
|
306
295
|
}
|
|
307
296
|
//# sourceMappingURL=openai-responses.js.map
|