@bastani/pi-ai 0.9.25 → 0.9.26-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/NOTICE.md +1 -1
  3. package/dist/api/openai-responses-shared.d.ts.map +1 -1
  4. package/dist/api/openai-responses-shared.js +6 -5
  5. package/dist/api/openai-responses-shared.js.map +1 -1
  6. package/dist/auth/helpers.d.ts +1 -0
  7. package/dist/auth/helpers.d.ts.map +1 -1
  8. package/dist/auth/helpers.js +1 -0
  9. package/dist/auth/helpers.js.map +1 -1
  10. package/dist/auth/oauth/anthropic.d.ts.map +1 -1
  11. package/dist/auth/oauth/anthropic.js +1 -0
  12. package/dist/auth/oauth/anthropic.js.map +1 -1
  13. package/dist/auth/oauth/oauth-page.js +1 -1
  14. package/dist/auth/oauth/oauth-page.js.map +1 -1
  15. package/dist/auth/oauth/openai-chatgpt.d.ts.map +1 -1
  16. package/dist/auth/oauth/openai-chatgpt.js +1 -0
  17. package/dist/auth/oauth/openai-chatgpt.js.map +1 -1
  18. package/dist/auth/oauth/openai-codex.d.ts.map +1 -1
  19. package/dist/auth/oauth/openai-codex.js +1 -0
  20. package/dist/auth/oauth/openai-codex.js.map +1 -1
  21. package/dist/auth/oauth/openrouter.d.ts.map +1 -1
  22. package/dist/auth/oauth/openrouter.js +1 -0
  23. package/dist/auth/oauth/openrouter.js.map +1 -1
  24. package/dist/auth/types.d.ts +1 -0
  25. package/dist/auth/types.d.ts.map +1 -1
  26. package/dist/auth/types.js.map +1 -1
  27. package/dist/providers/anthropic.d.ts.map +1 -1
  28. package/dist/providers/anthropic.js +1 -0
  29. package/dist/providers/anthropic.js.map +1 -1
  30. package/dist/providers/data/.manifest.json +1 -1
  31. package/dist/providers/data/fireworks.json +1 -1
  32. package/dist/providers/data/nvidia.json +1 -1
  33. package/dist/providers/data/opencode.json +1 -1
  34. package/dist/providers/data/openrouter.json +1 -1
  35. package/dist/providers/data/together.json +1 -1
  36. package/dist/providers/data/vercel-ai-gateway.json +1 -1
  37. package/dist/providers/openai-codex.d.ts.map +1 -1
  38. package/dist/providers/openai-codex.js +1 -0
  39. package/dist/providers/openai-codex.js.map +1 -1
  40. package/dist/providers/openai.d.ts.map +1 -1
  41. package/dist/providers/openai.js +1 -0
  42. package/dist/providers/openai.js.map +1 -1
  43. package/dist/providers/openrouter.d.ts.map +1 -1
  44. package/dist/providers/openrouter.js +1 -0
  45. package/dist/providers/openrouter.js.map +1 -1
  46. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -4,6 +4,23 @@ This package is a Bastani fork of `@earendil-works/pi-ai`. Upstream history at t
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.9.26-alpha.2] - 2026-10-02
8
+
9
+ ### Added
10
+
11
+ - Added `OAuthAuth.usesCallbackServer` so native providers can declare callback-server login flows with a manual-paste fallback. Built-in Anthropic, OpenAI, OpenAI Codex, and OpenRouter OAuth definitions carry this metadata through lazy loading ([#3400](https://github.com/bastani-inc/atomic/issues/3400)).
12
+
13
+ ## [0.9.26-alpha.1] - 2026-10-01
14
+
15
+ ### Changed
16
+
17
+ - OAuth browser pages now show the Atomic logo in color instead of white.
18
+
19
+ ### Fixed
20
+
21
+ - Fixed OpenAI Responses requests failing with `Expected an ID that begins with 'ctc'` when replaying grammar tool calls, such as `codemode`, from another provider or a gateway.
22
+ - Fixed Together's `deepseek-ai/DeepSeek-V4-Pro-0813` (the renamed DeepSeek V4 Pro) losing its `high` reasoning control after the model catalog refreshed.
23
+
7
24
  ## [0.9.25] - 2026-10-01
8
25
 
9
26
  ### Added
package/NOTICE.md CHANGED
@@ -6,7 +6,7 @@ monorepo at `packages/ai` and publishes at the same version as `@bastani/atomic`
6
6
 
7
7
  - Upstream package: [`@earendil-works/pi-ai`](https://www.npmjs.com/package/@earendil-works/pi-ai)
8
8
  - Original fork point: `v0.84.2` (`914cf1472e715297caa30db4b9535d534a9eb718`)
9
- - Applicable Pi AI fixes synced through audited upstream `main`: `earendil-works/pi@7a11fe1c723b942fa093edb8b00f051ddb9b6627`, with remaining registry Pi packages at `0.99.2`. Atomic retains its adaptations and does not enable upstream virtual models.
9
+ - Applicable Pi AI fixes synced through audited upstream `main`: `earendil-works/pi@86dfceec402ad77e563bf4feab5f26c42d5f5db6`, with remaining registry Pi packages at `1.0.0`. Atomic retains its adaptations and does not enable upstream virtual models.
10
10
  - Catalog JSON under `src/providers/data/` is generated at build time from models.dev, matching upstream. It is not committed.
11
11
 
12
12
  Original work is Copyright (c) 2025 Mario Zechner and is licensed under the MIT License.
@@ -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,EAGL,aAAa,EAKb,IAAI,EAEJ,iBAAiB,EACjB,KAAK,EACL,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AA6E5E;;;;;;;;;;;;;;;GAeG;AACH,kFAAkF;AAClF,MAAM,MAAM,oBAAoB,GAAG,6BAA6B,CAAC,cAAc,CAAC,GAAG,WAAW,CAAC;AAE/F,wBAAgB,2BAA2B,CAC1C,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,WAAW,CAAC,EACpC,kBAAkB,EAAE,oBAAoB,GAAG,SAAS,GAClD,oBAAoB,GAAG,SAAS,CAElC;AAOD;;;GAGG;AACH,wBAAgB,mBAAmB,CAClC,KAAK,EAAE,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,cAAc,CAAC,EACvC,WAAW,EAAE,oBAAoB,GAC/B,OAAO,CA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5C,MAAM,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;IACxB,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,0BAA0B,CAAC,EAAE,OAAO,CAAC;IACrC,gBAAgB,CAAC,EAAE,OAAO,CAAC;CAC3B;AAMD,wBAAgB,wBAAwB,CAAC,IAAI,SAAS,GAAG,EACxD,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,OAAO,EAAE,iBAAiB,EAC1B,wBAAwB,EAAE,WAAW,CAAC,MAAM,CAAC,EAC7C,OAAO,CAAC,EAAE,+BAA+B,GACvC,aAAa,CA4Mf;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"}
@@ -317,12 +317,13 @@ export function convertResponsesMessages(model, context, allowedToolCallProvider
317
317
  const customInputProperty = options?.grammarToolInputProperties?.get(toolCall.name);
318
318
  let itemId = itemIdRaw;
319
319
  // For different-model messages, set id to undefined to avoid pairing validation.
320
- // OpenAI tracks which fc_xxx IDs were paired with rs_xxx reasoning items.
320
+ // OpenAI tracks which item IDs were paired with rs_xxx reasoning items.
321
321
  // By omitting the id, we avoid triggering that validation (like cross-provider does).
322
- // When replaying custom-tool calls as a function_call, also drop non-fc_* ids such as
323
- // ctc_* custom-tool ids because function_call item ids must be fc_*.
324
- if ((isDifferentModel && itemId?.startsWith("fc_")) ||
325
- (customInputProperty === undefined && !itemId?.startsWith("fc_"))) {
322
+ // Also drop ids that do not match the replayed item type: function_call ids must be fc_*
323
+ // and custom_tool_call ids must be ctc_*. Foreign tool call ids are normalized to fc_*, and
324
+ // a call can switch between the two types when grammar tool support differs.
325
+ const itemIdPrefix = customInputProperty === undefined ? "fc_" : "ctc_";
326
+ if (isDifferentModel || !itemId?.startsWith(itemIdPrefix)) {
326
327
  itemId = undefined;
327
328
  }
328
329
  if (customInputProperty !== undefined) {
@@ -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,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAmBjE,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,SAAS;QAAE,OAAO,SAAS,CAA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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, 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
+ {"version":3,"file":"openai-responses-shared.js","sourceRoot":"","sources":["../../src/api/openai-responses-shared.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAmBjE,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,GA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AK,SAAS,IAAI,QAAQ,CAAC,WAAW,KAAK,SAAS,EAAE,CAAC;gBAC9E,MAAM,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, 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 item IDs were paired with rs_xxx reasoning items.\n\t\t\t\t\t// By omitting the id, we avoid triggering that validation (like cross-provider does).\n\t\t\t\t\t// Also drop ids that do not match the replayed item type: function_call ids must be fc_*\n\t\t\t\t\t// and custom_tool_call ids must be ctc_*. Foreign tool call ids are normalized to fc_*, and\n\t\t\t\t\t// a call can switch between the two types when grammar tool support differs.\n\t\t\t\t\tconst itemIdPrefix = customInputProperty === undefined ? \"fc_\" : \"ctc_\";\n\t\t\t\t\tif (isDifferentModel || !itemId?.startsWith(itemIdPrefix)) {\n\t\t\t\t\t\titemId = undefined;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (customInputProperty !== undefined) {\n\t\t\t\t\t\toutput.push({\n\t\t\t\t\t\t\ttype: \"custom_tool_call\",\n\t\t\t\t\t\t\tid: itemId,\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\tname: toolCall.name,\n\t\t\t\t\t\t\tinput: sanitizeSurrogates(\n\t\t\t\t\t\t\t\tgetGrammarToolInput(toolCall.name, toolCall.arguments, customInputProperty),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t...(isSameModel && toolCall.namespace !== undefined ? { namespace: toolCall.namespace } : {}),\n\t\t\t\t\t\t} satisfies ResponseOutputItem);\n\t\t\t\t\t} else {\n\t\t\t\t\t\toutput.push({\n\t\t\t\t\t\t\ttype: \"function_call\",\n\t\t\t\t\t\t\tid: itemId,\n\t\t\t\t\t\t\tcall_id: callId,\n\t\t\t\t\t\t\tname: toolCall.name,\n\t\t\t\t\t\t\targuments: JSON.stringify(toolCall.arguments),\n\t\t\t\t\t\t\t...(isSameModel && toolCall.namespace !== undefined ? { namespace: toolCall.namespace } : {}),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (output.length === 0) continue;\n\t\t\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"]}
@@ -17,6 +17,7 @@ export declare function lazyOAuth(input: {
17
17
  name: string;
18
18
  isSubscription?: boolean;
19
19
  loginLabel?: string;
20
+ usesCallbackServer?: boolean;
20
21
  load: () => Promise<OAuthAuth>;
21
22
  }): OAuthAuth;
22
23
  //# sourceMappingURL=helpers.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../src/auth/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAExD;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,UAAU,CAsBlF;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,OAAO,CAAC,SAAS,CAAC,CAAC;CAC/B,GAAG,SAAS,CAcZ"}
1
+ {"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../src/auth/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAExD;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,UAAU,CAsBlF;AAED;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,IAAI,EAAE,MAAM,OAAO,CAAC,SAAS,CAAC,CAAC;CAC/B,GAAG,SAAS,CAeZ"}
@@ -45,6 +45,7 @@ export function lazyOAuth(input) {
45
45
  name: input.name,
46
46
  isSubscription: input.isSubscription,
47
47
  loginLabel: input.loginLabel,
48
+ usesCallbackServer: input.usesCallbackServer,
48
49
  login: async (interaction, options) => (await loaded()).login(interaction, options),
49
50
  refresh: async (credential, signal) => (await loaded()).refresh(credential, signal),
50
51
  toAuth: async (credential) => (await loaded()).toAuth(credential),
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../src/auth/helpers.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,OAA0B;IACrE,OAAO;QACN,IAAI;QACJ,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,EAAE;YAC5B,WAAW,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC;YACpC,MAAM,GAAG,GAAG,MAAM,WAAW,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,O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MAAM,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE,OAAO,CAAC;QACnF,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,EAAE,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,CAAC;QACnF,MAAM,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC;KACjE,CAAC;AACH,CAAC","sourcesContent":["import type { ApiKeyAuth, OAuthAuth } from \"./types.ts\";\n\n/**\n * Standard api-key auth: a stored credential key wins, otherwise the first\n * set env var resolves. Includes a `login` that prompts for the key.\n * Providers with non-standard resolution (provider env, ambient files, IAM)\n * write their own `ApiKeyAuth`.\n */\nexport function envApiKeyAuth(name: string, envVars: readonly string[]): ApiKeyAuth {\n\treturn {\n\t\tname,\n\t\tlogin: async (interaction) => {\n\t\t\tinteraction.signal.throwIfAborted();\n\t\t\tconst key = await interaction.prompt({ type: \"secret\", message: `Enter ${name}` });\n\t\t\tinteraction.signal.throwIfAborted();\n\t\t\treturn { type: \"api_key\", key };\n\t\t},\n\t\tresolve: async ({ ctx, credential, signal }) => {\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (credential?.key) {\n\t\t\t\treturn { auth: { apiKey: credential.key }, env: credential.env, source: \"stored credential\" };\n\t\t\t}\n\t\t\tfor (const envVar of envVars) {\n\t\t\t\tconst value = await ctx.env(envVar);\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tif (value) return { auth: { apiKey: value }, source: envVar };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t};\n}\n\n/**\n * Wraps a dynamically imported `OAuthAuth` so provider definitions can\n * advertise OAuth without importing the implementation. The flow loads on\n * first `login`/`refresh`/`toAuth` call; callers keep Node-only flow code out\n * of bundles by loading through a bundler-opaque dynamic import (variable\n * specifier, see the bedrock lazy wrapper).\n */\nexport function lazyOAuth(input: {\n\tname: string;\n\tisSubscription?: boolean;\n\tloginLabel?: string;\n\tload: () => Promise<OAuthAuth>;\n}): OAuthAuth {\n\tlet promise: Promise<OAuthAuth> | undefined;\n\tconst loaded = () => {\n\t\tpromise ??= input.load();\n\t\treturn promise;\n\t};\n\treturn {\n\t\tname: input.name,\n\t\tisSubscription: input.isSubscription,\n\t\tloginLabel: input.loginLabel,\n\t\tlogin: async (interaction, options) => (await loaded()).login(interaction, options),\n\t\trefresh: async (credential, signal) => (await loaded()).refresh(credential, signal),\n\t\ttoAuth: async (credential) => (await loaded()).toAuth(credential),\n\t};\n}\n"]}
1
+ {"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../src/auth/helpers.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,OAA0B;IACrE,OAAO;QACN,IAAI;QACJ,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,EAAE;YAC5B,WAAW,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC;YACpC,MAAM,GAAG,GAAG,MAAM,WAAW,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,SAAS,IAAI,EAAE,EAAE,CAAC,CAAC;YACnF,WAAW,CAAC,MAAM,CAAC,cAAc,EAAE,CAAC;YACpC,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,GAAG,EAAE,CAAC;QACjC,CAAC;QACD,OAAO,EAAE,KAAK,EAAE,EAAE,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE;YAC9C,MAAM,CAAC,cAAc,EAAE,CAAC;YACxB,IAAI,UAAU,EAAE,GAAG,EAAE,CAAC;gBACrB,OAAO,EAAE,IAAI,EAAE,EAAE,MAAM,EAAE,UAAU,CAAC,GAAG,EAAE,EAAE,GAAG,EAAE,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,mBAAmB,EAAE,CAAC;YAC/F,CAAC;YACD,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;gBAC9B,MAAM,KAAK,GAAG,MAAM,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;gBACpC,MAAM,CAAC,cAAc,EAAE,CAAC;gBACxB,IAAI,KAAK;oBAAE,OAAO,EAAE,IAAI,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC;YAC/D,CAAC;YACD,OAAO,SAAS,CAAC;QAClB,CAAC;KACD,CAAC;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,KAMzB;IACA,IAAI,OAAuC,CAAC;IAC5C,MAAM,MAAM,GAAG,GAAG,EAAE;QACnB,OAAO,KAAK,KAAK,CAAC,IAAI,EAAE,CAAC;QACzB,OAAO,OAAO,CAAC;IAChB,CAAC,CAAC;IACF,OAAO;QACN,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,KAAK,EAAE,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE,OAAO,CAAC;QACnF,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,EAAE,CAAC,CAAC,OAAO,CAAC,UAAU,EAAE,MAAM,CAAC;QACnF,MAAM,EAAE,KAAK,EAAE,UAAU,EAAE,EAAE,CAAC,CAAC,MAAM,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,UAAU,CAAC;KACjE,CAAC;AACH,CAAC","sourcesContent":["import type { ApiKeyAuth, OAuthAuth } from \"./types.ts\";\n\n/**\n * Standard api-key auth: a stored credential key wins, otherwise the first\n * set env var resolves. Includes a `login` that prompts for the key.\n * Providers with non-standard resolution (provider env, ambient files, IAM)\n * write their own `ApiKeyAuth`.\n */\nexport function envApiKeyAuth(name: string, envVars: readonly string[]): ApiKeyAuth {\n\treturn {\n\t\tname,\n\t\tlogin: async (interaction) => {\n\t\t\tinteraction.signal.throwIfAborted();\n\t\t\tconst key = await interaction.prompt({ type: \"secret\", message: `Enter ${name}` });\n\t\t\tinteraction.signal.throwIfAborted();\n\t\t\treturn { type: \"api_key\", key };\n\t\t},\n\t\tresolve: async ({ ctx, credential, signal }) => {\n\t\t\tsignal.throwIfAborted();\n\t\t\tif (credential?.key) {\n\t\t\t\treturn { auth: { apiKey: credential.key }, env: credential.env, source: \"stored credential\" };\n\t\t\t}\n\t\t\tfor (const envVar of envVars) {\n\t\t\t\tconst value = await ctx.env(envVar);\n\t\t\t\tsignal.throwIfAborted();\n\t\t\t\tif (value) return { auth: { apiKey: value }, source: envVar };\n\t\t\t}\n\t\t\treturn undefined;\n\t\t},\n\t};\n}\n\n/**\n * Wraps a dynamically imported `OAuthAuth` so provider definitions can\n * advertise OAuth without importing the implementation. The flow loads on\n * first `login`/`refresh`/`toAuth` call; callers keep Node-only flow code out\n * of bundles by loading through a bundler-opaque dynamic import (variable\n * specifier, see the bedrock lazy wrapper).\n */\nexport function lazyOAuth(input: {\n\tname: string;\n\tisSubscription?: boolean;\n\tloginLabel?: string;\n\tusesCallbackServer?: boolean;\n\tload: () => Promise<OAuthAuth>;\n}): OAuthAuth {\n\tlet promise: Promise<OAuthAuth> | undefined;\n\tconst loaded = () => {\n\t\tpromise ??= input.load();\n\t\treturn promise;\n\t};\n\treturn {\n\t\tname: input.name,\n\t\tisSubscription: input.isSubscription,\n\t\tloginLabel: input.loginLabel,\n\t\tusesCallbackServer: input.usesCallbackServer,\n\t\tlogin: async (interaction, options) => (await loaded()).login(interaction, options),\n\t\trefresh: async (credential, signal) => (await loaded()).refresh(credential, signal),\n\t\ttoAuth: async (credential) => (await loaded()).toAuth(credential),\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"anthropic.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,SAAS,EAA4C,MAAM,aAAa,CAAC;AAoQvF,eAAO,MAAM,cAAc,EAAE,SA6B5B,CAAC"}
1
+ {"version":3,"file":"anthropic.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,SAAS,EAA4C,MAAM,aAAa,CAAC;AAoQvF,eAAO,MAAM,cAAc,EAAE,SA8B5B,CAAC"}
@@ -223,6 +223,7 @@ async function refreshAnthropicToken(refreshToken, signal) {
223
223
  }
224
224
  export const anthropicOAuth = {
225
225
  name: "Anthropic (Claude Pro/Max)",
226
+ usesCallbackServer: true,
226
227
  isSubscription: true,
227
228
  async login(interaction) {
228
229
  const method = await interaction.prompt({
@@ -1 +1 @@
1
- {"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../../src/auth/oauth/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAElE,OAAO,EAAE,wBAAwB,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,MAAM,MAAM,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,SAAS,GAAG,MAAM,CAAC,kDAAkD,CAAC,CAAC;AAC7E,MAAM,aAAa,GAAG,mCAAmC,CAAC;AAC1D,MAAM,SAAS,GAAG,4CAA4C,CAAC;AAC/D,MAAM,aAAa,GAAG,mBAAmB,CAAC,wBAAwB,CAAC,IAAI,WAAW,CAAC;AACnF,MAAM,aAAa,GAAG,KAAK,CAAC;AAC5B,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AAC,UAAU;QACtB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;CACD,CAAC","sourcesContent":["/**\n * Anthropic OAuth flow (Claude Pro/Max)\n *\n * NOTE: This module uses Node.js http.createServer for the OAuth callback server.\n * It is only intended for CLI use, not browser environments.\n */\n\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { startOAuthCallbackServer, waitForCallbackOrManualInput } from \"./callback-server.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\nconst decode = (s: string) => atob(s);\nconst CLIENT_ID = decode(\"OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl\");\nconst AUTHORIZE_URL = \"https://claude.ai/oauth/authorize\";\nconst TOKEN_URL = \"https://platform.claude.com/v1/oauth/token\";\nconst CALLBACK_HOST = getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\nconst CALLBACK_PORT = 53692;\nconst CALLBACK_PATH = \"/callback\";\nconst REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;\nconst COPY_CODE_REDIRECT_URI = \"https://platform.claude.com/oauth/code/callback\";\nconst ANTHROPIC_BROWSER_LOGIN_METHOD = \"browser\";\nconst ANTHROPIC_COPY_CODE_LOGIN_METHOD = \"copy_code\";\nconst SCOPES =\n\t\"org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload\";\n\nfunction parseAuthorizationInput(input: string): { code?: string; state?: string } {\n\tconst value = input.trim();\n\tif (!value) return {};\n\n\ttry {\n\t\tconst url = new URL(value);\n\t\treturn {\n\t\t\tcode: url.searchParams.get(\"code\") ?? undefined,\n\t\t\tstate: url.searchParams.get(\"state\") ?? undefined,\n\t\t};\n\t} catch {\n\t\t// not a URL\n\t}\n\n\tif (value.includes(\"#\")) {\n\t\tconst [code, state] = value.split(\"#\", 2);\n\t\treturn { code, state };\n\t}\n\n\tif (value.includes(\"code=\")) {\n\t\tconst params = new URLSearchParams(value);\n\t\treturn {\n\t\t\tcode: params.get(\"code\") ?? undefined,\n\t\t\tstate: params.get(\"state\") ?? undefined,\n\t\t};\n\t}\n\n\treturn { code: value };\n}\n\nfunction formatErrorDetails(error: unknown): string {\n\tif (error instanceof Error) {\n\t\tconst details: string[] = [`${error.name}: ${error.message}`];\n\t\tconst errorWithCode = error as Error & { code?: string; errno?: number | string; cause?: unknown };\n\t\tif (errorWithCode.code) details.push(`code=${errorWithCode.code}`);\n\t\tif (typeof errorWithCode.errno !== \"undefined\") details.push(`errno=${String(errorWithCode.errno)}`);\n\t\tif (typeof error.cause !== \"undefined\") {\n\t\t\tdetails.push(`cause=${formatErrorDetails(error.cause)}`);\n\t\t}\n\t\tif (error.stack) {\n\t\t\tdetails.push(`stack=${error.stack}`);\n\t\t}\n\t\treturn details.join(\"; \");\n\t}\n\treturn String(error);\n}\n\nasync function postJson(url: string, body: Record<string, string | number>, signal: AbortSignal): Promise<string> {\n\tconst response = await fetch(url, {\n\t\tmethod: \"POST\",\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\tAccept: \"application/json\",\n\t\t},\n\t\tbody: JSON.stringify(body),\n\t\tsignal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]),\n\t});\n\n\tconst responseBody = await response.text();\n\n\tif (!response.ok) {\n\t\tthrow new Error(`HTTP request failed. status=${response.status}; url=${url}; body=${responseBody}`);\n\t}\n\n\treturn responseBody;\n}\n\nasync function exchangeAuthorizationCode(\n\tcode: string,\n\tstate: string,\n\tverifier: string,\n\tredirectUri: string,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\tlet responseBody: string;\n\ttry {\n\t\tresponseBody = await postJson(\n\t\t\tTOKEN_URL,\n\t\t\t{\n\t\t\t\tgrant_type: \"authorization_code\",\n\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\tcode,\n\t\t\t\tstate,\n\t\t\t\tredirect_uri: redirectUri,\n\t\t\t\tcode_verifier: verifier,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Token exchange request failed. url=${TOKEN_URL}; redirect_uri=${redirectUri}; response_type=authorization_code; details=${formatErrorDetails(error)}`,\n\t\t);\n\t}\n\n\tlet tokenData: { access_token: string; refresh_token: string; expires_in: number };\n\ttry {\n\t\ttokenData = JSON.parse(responseBody) as { access_token: string; refresh_token: string; expires_in: number };\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Token exchange returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`,\n\t\t);\n\t}\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\trefresh: tokenData.refresh_token,\n\t\taccess: tokenData.access_token,\n\t\texpires: Date.now() + tokenData.expires_in * 1000 - 5 * 60 * 1000,\n\t};\n}\n\nasync function loginAnthropic(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst callback = await startOAuthCallbackServer({\n\t\tproviderName: \"Anthropic\",\n\t\thost: CALLBACK_HOST,\n\t\tport: CALLBACK_PORT,\n\t\tpath: CALLBACK_PATH,\n\t\tstate: verifier,\n\t\tcomplete: async (code) => code,\n\t\tsignal: interaction.signal,\n\t}).catch(() => undefined);\n\n\ttry {\n\t\tconst authParams = new URLSearchParams({\n\t\t\tcode: \"true\",\n\t\t\tclient_id: CLIENT_ID,\n\t\t\tresponse_type: \"code\",\n\t\t\tredirect_uri: REDIRECT_URI,\n\t\t\tscope: SCOPES,\n\t\t\tcode_challenge: challenge,\n\t\t\tcode_challenge_method: \"S256\",\n\t\t\tstate: verifier,\n\t\t});\n\t\tinteraction.notify({\n\t\t\ttype: \"auth_url\",\n\t\t\turl: `${AUTHORIZE_URL}?${authParams.toString()}`,\n\t\t\tinstructions:\n\t\t\t\t\"Complete login in your browser. If the browser is on another machine, paste the final redirect URL here.\",\n\t\t});\n\n\t\tconst result = await waitForCallbackOrManualInput(interaction, callback, {\n\t\t\tmessage: \"Complete login in your browser, or paste the authorization code / redirect URL here:\",\n\t\t\tplaceholder: REDIRECT_URI,\n\t\t});\n\t\tlet code: string | undefined;\n\t\tlet state = verifier;\n\t\tif (result.type === \"callback\") {\n\t\t\tcode = result.value;\n\t\t} else {\n\t\t\tconst parsed = parseAuthorizationInput(result.input);\n\t\t\tif (parsed.state && parsed.state !== verifier) throw new Error(\"OAuth state mismatch\");\n\t\t\tcode = parsed.code;\n\t\t\tstate = parsed.state ?? verifier;\n\t\t}\n\n\t\tif (!code) throw new Error(\"Missing authorization code\");\n\t\tinteraction.notify({ type: \"progress\", message: \"Exchanging authorization code for tokens...\" });\n\t\treturn await exchangeAuthorizationCode(code, state, verifier, REDIRECT_URI, interaction.signal);\n\t} finally {\n\t\tcallback?.close();\n\t}\n}\n\nasync function loginAnthropicCopyCode(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst authParams = new URLSearchParams({\n\t\tcode: \"true\",\n\t\tclient_id: CLIENT_ID,\n\t\tresponse_type: \"code\",\n\t\tredirect_uri: COPY_CODE_REDIRECT_URI,\n\t\tscope: SCOPES,\n\t\tcode_challenge: challenge,\n\t\tcode_challenge_method: \"S256\",\n\t\tstate: verifier,\n\t});\n\tinteraction.notify({\n\t\ttype: \"auth_url\",\n\t\turl: `${AUTHORIZE_URL}?${authParams.toString()}`,\n\t\tinstructions: \"Complete login in your browser, then copy the code Anthropic shows and paste it here.\",\n\t});\n\n\tconst input = await interaction.prompt({\n\t\ttype: \"manual_code\",\n\t\tmessage: \"Paste the code Anthropic shows after you sign in:\",\n\t\tplaceholder: \"code#state\",\n\t\tsignal: interaction.signal,\n\t});\n\tconst parsed = parseAuthorizationInput(input);\n\tif (parsed.state && parsed.state !== verifier) throw new Error(\"OAuth state mismatch\");\n\tif (!parsed.code) throw new Error(\"Missing authorization code\");\n\tinteraction.notify({ type: \"progress\", message: \"Exchanging authorization code for tokens...\" });\n\treturn await exchangeAuthorizationCode(\n\t\tparsed.code,\n\t\tparsed.state ?? verifier,\n\t\tverifier,\n\t\tCOPY_CODE_REDIRECT_URI,\n\t\tinteraction.signal,\n\t);\n}\n\n/**\n * Refresh Anthropic OAuth token\n */\nasync function refreshAnthropicToken(refreshToken: string, signal: AbortSignal): Promise<OAuthCredential> {\n\tlet responseBody: string;\n\ttry {\n\t\tresponseBody = await postJson(\n\t\t\tTOKEN_URL,\n\t\t\t{\n\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\trefresh_token: refreshToken,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t} catch (error) {\n\t\tthrow new Error(`Anthropic token refresh request failed. url=${TOKEN_URL}; details=${formatErrorDetails(error)}`);\n\t}\n\n\tlet data: { access_token: string; refresh_token: string; expires_in: number; scope?: string };\n\ttry {\n\t\tdata = JSON.parse(responseBody) as {\n\t\t\taccess_token: string;\n\t\t\trefresh_token: string;\n\t\t\texpires_in: number;\n\t\t\tscope?: string;\n\t\t};\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Anthropic token refresh returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`,\n\t\t);\n\t}\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\trefresh: data.refresh_token,\n\t\taccess: data.access_token,\n\t\texpires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000,\n\t};\n}\n\nexport const anthropicOAuth: OAuthAuth = {\n\tname: \"Anthropic (Claude Pro/Max)\",\n\tisSubscription: true,\n\n\tasync login(interaction) {\n\t\tconst method = await interaction.prompt({\n\t\t\ttype: \"select\",\n\t\t\tmessage: \"Select Anthropic login method:\",\n\t\t\toptions: [\n\t\t\t\t{ id: ANTHROPIC_BROWSER_LOGIN_METHOD, label: \"Browser login (default)\" },\n\t\t\t\t{ id: ANTHROPIC_COPY_CODE_LOGIN_METHOD, label: \"Copy code login (headless)\" },\n\t\t\t],\n\t\t});\n\n\t\tif (method === ANTHROPIC_COPY_CODE_LOGIN_METHOD) {\n\t\t\treturn loginAnthropicCopyCode(interaction);\n\t\t}\n\t\tif (method !== ANTHROPIC_BROWSER_LOGIN_METHOD) {\n\t\t\tthrow new Error(`Unknown Anthropic login method: ${method}`);\n\t\t}\n\n\t\treturn loginAnthropic(interaction);\n\t},\n\n\trefresh: (credential, signal) => refreshAnthropicToken(credential.refresh, signal),\n\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
1
+ {"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../../src/auth/oauth/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAElE,OAAO,EAAE,wBAAwB,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,MAAM,MAAM,GAAG,CAAC,CAAS,EAAE,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACtC,MAAM,SAAS,GAAG,MAAM,CAAC,kDAAkD,CAAC,CAAC;AAC7E,MAAM,aAAa,GAAG,mCAAmC,CAAC;AAC1D,MAAM,SAAS,GAAG,4CAA4C,CAAC;AAC/D,MAAM,aAAa,GAAG,mBAAmB,CAAC,wBAAwB,CAAC,IAAI,WAAW,CAAC;AACnF,MAAM,aAAa,GAAG,KAAK,CAAC;AAC5B,MAAM,aAAa,GAAG,WAAW,CAAC;AAClC,MAAM,YAAY,GAAG,oBAAoB,aAAa,GAAG,aAAa,EAAE,CAAC;AACzE,MAAM,sBAAsB,GAAG,iDAAiD,CAAC;AACjF,MAAM,8BAA8B,GAAG,SAAS,CAAC;AACjD,MAAM,gCAAgC,GAAG,WAAW,CAAC;AACrD,MAA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,EAAE,IAAI,CAAC,aAAa;QAC3B,MAAM,EAAE,IAAI,CAAC,YAAY;QACzB,OAAO,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,UAAU,GAAG,IAAI,GAAG,CAAC,GAAG,EAAE,GAAG,IAAI;KAC5D,CAAC;AACH,CAAC;AAED,MAAM,CAAC,MAAM,cAAc,GAAc;IACxC,IAAI,EAAE,4BAA4B;IAClC,kBAAkB,EAAE,IAAI;IACxB,cAAc,EAAE,IAAI;IAEpB,KAAK,CAAC,KAAK,CAAC,WAAW;QACtB,MAAM,MAAM,GAAG,MAAM,WAAW,CAAC,MAAM,CAAC;YACvC,IAAI,EAAE,QAAQ;YACd,OAAO,EAAE,gCAAgC;YACzC,OAAO,EAAE;gBACR,EAAE,EAAE,EAAE,8BAA8B,EAAE,KAAK,EAAE,yBAAyB,EAAE;gBACxE,EAAE,EAAE,EAAE,gCAAgC,EAAE,KAAK,EAAE,4BAA4B,EAAE;aAC7E;SACD,CAAC,CAAC;QAEH,IAAI,MAAM,KAAK,gCAAgC,EAAE,CAAC;YACjD,OAAO,sBAAsB,CAAC,WAAW,CAAC,CAAC;QAC5C,CAAC;QACD,IAAI,MAAM,KAAK,8BAA8B,EAAE,CAAC;YAC/C,MAAM,IAAI,KAAK,CAAC,mCAAmC,MAAM,EAAE,CAAC,CAAC;QAC9D,CAAC;QAED,OAAO,cAAc,CAAC,WAAW,CAAC,CAAC;IACpC,CAAC;IAED,OAAO,EAAE,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,CAAC,qBAAqB,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC;IAElF,KAAK,CAAC,MAAM,CAAC,UAAU;QACtB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;CACD,CAAC","sourcesContent":["/**\n * Anthropic OAuth flow (Claude Pro/Max)\n *\n * NOTE: This module uses Node.js http.createServer for the OAuth callback server.\n * It is only intended for CLI use, not browser environments.\n */\n\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { startOAuthCallbackServer, waitForCallbackOrManualInput } from \"./callback-server.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\nconst decode = (s: string) => atob(s);\nconst CLIENT_ID = decode(\"OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl\");\nconst AUTHORIZE_URL = \"https://claude.ai/oauth/authorize\";\nconst TOKEN_URL = \"https://platform.claude.com/v1/oauth/token\";\nconst CALLBACK_HOST = getProviderEnvValue(\"PI_OAUTH_CALLBACK_HOST\") || \"127.0.0.1\";\nconst CALLBACK_PORT = 53692;\nconst CALLBACK_PATH = \"/callback\";\nconst REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;\nconst COPY_CODE_REDIRECT_URI = \"https://platform.claude.com/oauth/code/callback\";\nconst ANTHROPIC_BROWSER_LOGIN_METHOD = \"browser\";\nconst ANTHROPIC_COPY_CODE_LOGIN_METHOD = \"copy_code\";\nconst SCOPES =\n\t\"org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload\";\n\nfunction parseAuthorizationInput(input: string): { code?: string; state?: string } {\n\tconst value = input.trim();\n\tif (!value) return {};\n\n\ttry {\n\t\tconst url = new URL(value);\n\t\treturn {\n\t\t\tcode: url.searchParams.get(\"code\") ?? undefined,\n\t\t\tstate: url.searchParams.get(\"state\") ?? undefined,\n\t\t};\n\t} catch {\n\t\t// not a URL\n\t}\n\n\tif (value.includes(\"#\")) {\n\t\tconst [code, state] = value.split(\"#\", 2);\n\t\treturn { code, state };\n\t}\n\n\tif (value.includes(\"code=\")) {\n\t\tconst params = new URLSearchParams(value);\n\t\treturn {\n\t\t\tcode: params.get(\"code\") ?? undefined,\n\t\t\tstate: params.get(\"state\") ?? undefined,\n\t\t};\n\t}\n\n\treturn { code: value };\n}\n\nfunction formatErrorDetails(error: unknown): string {\n\tif (error instanceof Error) {\n\t\tconst details: string[] = [`${error.name}: ${error.message}`];\n\t\tconst errorWithCode = error as Error & { code?: string; errno?: number | string; cause?: unknown };\n\t\tif (errorWithCode.code) details.push(`code=${errorWithCode.code}`);\n\t\tif (typeof errorWithCode.errno !== \"undefined\") details.push(`errno=${String(errorWithCode.errno)}`);\n\t\tif (typeof error.cause !== \"undefined\") {\n\t\t\tdetails.push(`cause=${formatErrorDetails(error.cause)}`);\n\t\t}\n\t\tif (error.stack) {\n\t\t\tdetails.push(`stack=${error.stack}`);\n\t\t}\n\t\treturn details.join(\"; \");\n\t}\n\treturn String(error);\n}\n\nasync function postJson(url: string, body: Record<string, string | number>, signal: AbortSignal): Promise<string> {\n\tconst response = await fetch(url, {\n\t\tmethod: \"POST\",\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\tAccept: \"application/json\",\n\t\t},\n\t\tbody: JSON.stringify(body),\n\t\tsignal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]),\n\t});\n\n\tconst responseBody = await response.text();\n\n\tif (!response.ok) {\n\t\tthrow new Error(`HTTP request failed. status=${response.status}; url=${url}; body=${responseBody}`);\n\t}\n\n\treturn responseBody;\n}\n\nasync function exchangeAuthorizationCode(\n\tcode: string,\n\tstate: string,\n\tverifier: string,\n\tredirectUri: string,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\tlet responseBody: string;\n\ttry {\n\t\tresponseBody = await postJson(\n\t\t\tTOKEN_URL,\n\t\t\t{\n\t\t\t\tgrant_type: \"authorization_code\",\n\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\tcode,\n\t\t\t\tstate,\n\t\t\t\tredirect_uri: redirectUri,\n\t\t\t\tcode_verifier: verifier,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Token exchange request failed. url=${TOKEN_URL}; redirect_uri=${redirectUri}; response_type=authorization_code; details=${formatErrorDetails(error)}`,\n\t\t);\n\t}\n\n\tlet tokenData: { access_token: string; refresh_token: string; expires_in: number };\n\ttry {\n\t\ttokenData = JSON.parse(responseBody) as { access_token: string; refresh_token: string; expires_in: number };\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Token exchange returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`,\n\t\t);\n\t}\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\trefresh: tokenData.refresh_token,\n\t\taccess: tokenData.access_token,\n\t\texpires: Date.now() + tokenData.expires_in * 1000 - 5 * 60 * 1000,\n\t};\n}\n\nasync function loginAnthropic(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst callback = await startOAuthCallbackServer({\n\t\tproviderName: \"Anthropic\",\n\t\thost: CALLBACK_HOST,\n\t\tport: CALLBACK_PORT,\n\t\tpath: CALLBACK_PATH,\n\t\tstate: verifier,\n\t\tcomplete: async (code) => code,\n\t\tsignal: interaction.signal,\n\t}).catch(() => undefined);\n\n\ttry {\n\t\tconst authParams = new URLSearchParams({\n\t\t\tcode: \"true\",\n\t\t\tclient_id: CLIENT_ID,\n\t\t\tresponse_type: \"code\",\n\t\t\tredirect_uri: REDIRECT_URI,\n\t\t\tscope: SCOPES,\n\t\t\tcode_challenge: challenge,\n\t\t\tcode_challenge_method: \"S256\",\n\t\t\tstate: verifier,\n\t\t});\n\t\tinteraction.notify({\n\t\t\ttype: \"auth_url\",\n\t\t\turl: `${AUTHORIZE_URL}?${authParams.toString()}`,\n\t\t\tinstructions:\n\t\t\t\t\"Complete login in your browser. If the browser is on another machine, paste the final redirect URL here.\",\n\t\t});\n\n\t\tconst result = await waitForCallbackOrManualInput(interaction, callback, {\n\t\t\tmessage: \"Complete login in your browser, or paste the authorization code / redirect URL here:\",\n\t\t\tplaceholder: REDIRECT_URI,\n\t\t});\n\t\tlet code: string | undefined;\n\t\tlet state = verifier;\n\t\tif (result.type === \"callback\") {\n\t\t\tcode = result.value;\n\t\t} else {\n\t\t\tconst parsed = parseAuthorizationInput(result.input);\n\t\t\tif (parsed.state && parsed.state !== verifier) throw new Error(\"OAuth state mismatch\");\n\t\t\tcode = parsed.code;\n\t\t\tstate = parsed.state ?? verifier;\n\t\t}\n\n\t\tif (!code) throw new Error(\"Missing authorization code\");\n\t\tinteraction.notify({ type: \"progress\", message: \"Exchanging authorization code for tokens...\" });\n\t\treturn await exchangeAuthorizationCode(code, state, verifier, REDIRECT_URI, interaction.signal);\n\t} finally {\n\t\tcallback?.close();\n\t}\n}\n\nasync function loginAnthropicCopyCode(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst authParams = new URLSearchParams({\n\t\tcode: \"true\",\n\t\tclient_id: CLIENT_ID,\n\t\tresponse_type: \"code\",\n\t\tredirect_uri: COPY_CODE_REDIRECT_URI,\n\t\tscope: SCOPES,\n\t\tcode_challenge: challenge,\n\t\tcode_challenge_method: \"S256\",\n\t\tstate: verifier,\n\t});\n\tinteraction.notify({\n\t\ttype: \"auth_url\",\n\t\turl: `${AUTHORIZE_URL}?${authParams.toString()}`,\n\t\tinstructions: \"Complete login in your browser, then copy the code Anthropic shows and paste it here.\",\n\t});\n\n\tconst input = await interaction.prompt({\n\t\ttype: \"manual_code\",\n\t\tmessage: \"Paste the code Anthropic shows after you sign in:\",\n\t\tplaceholder: \"code#state\",\n\t\tsignal: interaction.signal,\n\t});\n\tconst parsed = parseAuthorizationInput(input);\n\tif (parsed.state && parsed.state !== verifier) throw new Error(\"OAuth state mismatch\");\n\tif (!parsed.code) throw new Error(\"Missing authorization code\");\n\tinteraction.notify({ type: \"progress\", message: \"Exchanging authorization code for tokens...\" });\n\treturn await exchangeAuthorizationCode(\n\t\tparsed.code,\n\t\tparsed.state ?? verifier,\n\t\tverifier,\n\t\tCOPY_CODE_REDIRECT_URI,\n\t\tinteraction.signal,\n\t);\n}\n\n/**\n * Refresh Anthropic OAuth token\n */\nasync function refreshAnthropicToken(refreshToken: string, signal: AbortSignal): Promise<OAuthCredential> {\n\tlet responseBody: string;\n\ttry {\n\t\tresponseBody = await postJson(\n\t\t\tTOKEN_URL,\n\t\t\t{\n\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\trefresh_token: refreshToken,\n\t\t\t},\n\t\t\tsignal,\n\t\t);\n\t} catch (error) {\n\t\tthrow new Error(`Anthropic token refresh request failed. url=${TOKEN_URL}; details=${formatErrorDetails(error)}`);\n\t}\n\n\tlet data: { access_token: string; refresh_token: string; expires_in: number; scope?: string };\n\ttry {\n\t\tdata = JSON.parse(responseBody) as {\n\t\t\taccess_token: string;\n\t\t\trefresh_token: string;\n\t\t\texpires_in: number;\n\t\t\tscope?: string;\n\t\t};\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Anthropic token refresh returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`,\n\t\t);\n\t}\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\trefresh: data.refresh_token,\n\t\taccess: data.access_token,\n\t\texpires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000,\n\t};\n}\n\nexport const anthropicOAuth: OAuthAuth = {\n\tname: \"Anthropic (Claude Pro/Max)\",\n\tusesCallbackServer: true,\n\tisSubscription: true,\n\n\tasync login(interaction) {\n\t\tconst method = await interaction.prompt({\n\t\t\ttype: \"select\",\n\t\t\tmessage: \"Select Anthropic login method:\",\n\t\t\toptions: [\n\t\t\t\t{ id: ANTHROPIC_BROWSER_LOGIN_METHOD, label: \"Browser login (default)\" },\n\t\t\t\t{ id: ANTHROPIC_COPY_CODE_LOGIN_METHOD, label: \"Copy code login (headless)\" },\n\t\t\t],\n\t\t});\n\n\t\tif (method === ANTHROPIC_COPY_CODE_LOGIN_METHOD) {\n\t\t\treturn loginAnthropicCopyCode(interaction);\n\t\t}\n\t\tif (method !== ANTHROPIC_BROWSER_LOGIN_METHOD) {\n\t\t\tthrow new Error(`Unknown Anthropic login method: ${method}`);\n\t\t}\n\n\t\treturn loginAnthropic(interaction);\n\t},\n\n\trefresh: (credential, signal) => refreshAnthropicToken(credential.refresh, signal),\n\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
@@ -1,4 +1,4 @@
1
- const LOGO_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 80" aria-hidden="true"><text x="40" y="62" text-anchor="middle" font-family="monospace" font-size="72" fill="#fff">∀</text></svg>`;
1
+ const LOGO_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 80" aria-hidden="true"><text x="40" y="62" text-anchor="middle" font-family="monospace" font-size="72" fill="#89b4fa">∀</text></svg>`;
2
2
  function escapeHtml(value) {
3
3
  return value
4
4
  .replaceAll("&", "&amp;")