@earendil-works/pi-ai 0.80.7 → 0.80.8

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 (189) hide show
  1. package/README.md +76 -22
  2. package/dist/api/lazy.d.ts.map +1 -1
  3. package/dist/api/lazy.js +9 -10
  4. package/dist/api/lazy.js.map +1 -1
  5. package/dist/api/openai-codex-responses.d.ts.map +1 -1
  6. package/dist/api/openai-codex-responses.js +3 -2
  7. package/dist/api/openai-codex-responses.js.map +1 -1
  8. package/dist/api/openai-responses.d.ts.map +1 -1
  9. package/dist/api/openai-responses.js +2 -0
  10. package/dist/api/openai-responses.js.map +1 -1
  11. package/dist/auth/credential-store.d.ts +2 -1
  12. package/dist/auth/credential-store.d.ts.map +1 -1
  13. package/dist/auth/credential-store.js +3 -0
  14. package/dist/auth/credential-store.js.map +1 -1
  15. package/dist/auth/helpers.d.ts.map +1 -1
  16. package/dist/auth/helpers.js +3 -3
  17. package/dist/auth/helpers.js.map +1 -1
  18. package/dist/auth/oauth/anthropic.d.ts +9 -0
  19. package/dist/auth/oauth/anthropic.d.ts.map +1 -0
  20. package/dist/{utils → auth}/oauth/anthropic.js +51 -116
  21. package/dist/auth/oauth/anthropic.js.map +1 -0
  22. package/dist/auth/oauth/device-code.d.ts.map +1 -0
  23. package/dist/auth/oauth/device-code.js.map +1 -0
  24. package/dist/auth/oauth/github-copilot.d.ts +6 -0
  25. package/dist/auth/oauth/github-copilot.d.ts.map +1 -0
  26. package/dist/{utils → auth}/oauth/github-copilot.js +18 -77
  27. package/dist/auth/oauth/github-copilot.js.map +1 -0
  28. package/dist/auth/oauth/load.d.ts +23 -0
  29. package/dist/auth/oauth/load.d.ts.map +1 -0
  30. package/dist/auth/oauth/load.js +49 -0
  31. package/dist/auth/oauth/load.js.map +1 -0
  32. package/dist/auth/oauth/oauth-page.d.ts.map +1 -0
  33. package/dist/auth/oauth/oauth-page.js.map +1 -0
  34. package/dist/auth/oauth/openai-codex.d.ts +9 -0
  35. package/dist/auth/oauth/openai-codex.d.ts.map +1 -0
  36. package/dist/{utils → auth}/oauth/openai-codex.js +61 -155
  37. package/dist/auth/oauth/openai-codex.js.map +1 -0
  38. package/dist/auth/oauth/pkce.d.ts.map +1 -0
  39. package/dist/auth/oauth/pkce.js.map +1 -0
  40. package/dist/auth/oauth/radius.d.ts +16 -0
  41. package/dist/auth/oauth/radius.d.ts.map +1 -0
  42. package/dist/{utils → auth}/oauth/radius.js +31 -128
  43. package/dist/auth/oauth/radius.js.map +1 -0
  44. package/dist/auth/oauth/xai.d.ts +6 -0
  45. package/dist/auth/oauth/xai.d.ts.map +1 -0
  46. package/dist/auth/oauth/xai.js +184 -0
  47. package/dist/auth/oauth/xai.js.map +1 -0
  48. package/dist/auth/resolve.d.ts +2 -4
  49. package/dist/auth/resolve.d.ts.map +1 -1
  50. package/dist/auth/resolve.js +9 -7
  51. package/dist/auth/resolve.js.map +1 -1
  52. package/dist/auth/types.d.ts +47 -10
  53. package/dist/auth/types.d.ts.map +1 -1
  54. package/dist/auth/types.js.map +1 -1
  55. package/dist/bun-oauth.d.ts +3 -0
  56. package/dist/bun-oauth.d.ts.map +1 -0
  57. package/dist/bun-oauth.js +17 -0
  58. package/dist/bun-oauth.js.map +1 -0
  59. package/dist/cli.d.ts.map +1 -1
  60. package/dist/cli.js +58 -76
  61. package/dist/cli.js.map +1 -1
  62. package/dist/compat/extension-oauth-types.d.ts +39 -0
  63. package/dist/compat/extension-oauth-types.d.ts.map +1 -0
  64. package/dist/compat/extension-oauth-types.js +2 -0
  65. package/dist/compat/extension-oauth-types.js.map +1 -0
  66. package/dist/compat.d.ts.map +1 -1
  67. package/dist/compat.js +20 -7
  68. package/dist/compat.js.map +1 -1
  69. package/dist/env-api-keys.d.ts.map +1 -1
  70. package/dist/env-api-keys.js +1 -1
  71. package/dist/env-api-keys.js.map +1 -1
  72. package/dist/images-models.d.ts +4 -2
  73. package/dist/images-models.d.ts.map +1 -1
  74. package/dist/images-models.js +5 -4
  75. package/dist/images-models.js.map +1 -1
  76. package/dist/index.d.ts +2 -1
  77. package/dist/index.d.ts.map +1 -1
  78. package/dist/index.js +1 -0
  79. package/dist/index.js.map +1 -1
  80. package/dist/models-store.d.ts +25 -0
  81. package/dist/models-store.d.ts.map +1 -0
  82. package/dist/models-store.js +14 -0
  83. package/dist/models-store.js.map +1 -0
  84. package/dist/models.d.ts +66 -30
  85. package/dist/models.d.ts.map +1 -1
  86. package/dist/models.generated.d.ts +93 -4
  87. package/dist/models.generated.d.ts.map +1 -1
  88. package/dist/models.js +214 -29
  89. package/dist/models.js.map +1 -1
  90. package/dist/oauth.d.ts +2 -1
  91. package/dist/oauth.d.ts.map +1 -1
  92. package/dist/oauth.js +1 -1
  93. package/dist/oauth.js.map +1 -1
  94. package/dist/providers/all.d.ts +2 -1
  95. package/dist/providers/all.d.ts.map +1 -1
  96. package/dist/providers/all.js +3 -0
  97. package/dist/providers/all.js.map +1 -1
  98. package/dist/providers/amazon-bedrock.d.ts.map +1 -1
  99. package/dist/providers/amazon-bedrock.js +51 -10
  100. package/dist/providers/amazon-bedrock.js.map +1 -1
  101. package/dist/providers/anthropic.d.ts.map +1 -1
  102. package/dist/providers/anthropic.js +1 -1
  103. package/dist/providers/anthropic.js.map +1 -1
  104. package/dist/providers/cloudflare-ai-gateway.d.ts.map +1 -1
  105. package/dist/providers/cloudflare-ai-gateway.js +4 -3
  106. package/dist/providers/cloudflare-ai-gateway.js.map +1 -1
  107. package/dist/providers/cloudflare-auth.d.ts.map +1 -1
  108. package/dist/providers/cloudflare-auth.js +13 -20
  109. package/dist/providers/cloudflare-auth.js.map +1 -1
  110. package/dist/providers/cloudflare-stream.d.ts +8 -0
  111. package/dist/providers/cloudflare-stream.d.ts.map +1 -0
  112. package/dist/providers/cloudflare-stream.js +21 -0
  113. package/dist/providers/cloudflare-stream.js.map +1 -0
  114. package/dist/providers/cloudflare-workers-ai.d.ts.map +1 -1
  115. package/dist/providers/cloudflare-workers-ai.js +2 -1
  116. package/dist/providers/cloudflare-workers-ai.js.map +1 -1
  117. package/dist/providers/github-copilot.d.ts.map +1 -1
  118. package/dist/providers/github-copilot.js +11 -1
  119. package/dist/providers/github-copilot.js.map +1 -1
  120. package/dist/providers/google-vertex.d.ts.map +1 -1
  121. package/dist/providers/google-vertex.js +56 -5
  122. package/dist/providers/google-vertex.js.map +1 -1
  123. package/dist/providers/kimi-coding.models.d.ts +20 -0
  124. package/dist/providers/kimi-coding.models.d.ts.map +1 -1
  125. package/dist/providers/kimi-coding.models.js +18 -0
  126. package/dist/providers/kimi-coding.models.js.map +1 -1
  127. package/dist/providers/openai-codex.d.ts.map +1 -1
  128. package/dist/providers/openai-codex.js +1 -1
  129. package/dist/providers/openai-codex.js.map +1 -1
  130. package/dist/providers/openrouter.models.d.ts.map +1 -1
  131. package/dist/providers/openrouter.models.js +135 -135
  132. package/dist/providers/openrouter.models.js.map +1 -1
  133. package/dist/providers/radius-config.d.ts +26 -0
  134. package/dist/providers/radius-config.d.ts.map +1 -0
  135. package/dist/providers/radius-config.js +59 -0
  136. package/dist/providers/radius-config.js.map +1 -0
  137. package/dist/providers/radius.d.ts +9 -0
  138. package/dist/providers/radius.d.ts.map +1 -0
  139. package/dist/providers/radius.js +54 -0
  140. package/dist/providers/radius.js.map +1 -0
  141. package/dist/providers/vercel-ai-gateway.models.d.ts +67 -0
  142. package/dist/providers/vercel-ai-gateway.models.d.ts.map +1 -1
  143. package/dist/providers/vercel-ai-gateway.models.js +57 -2
  144. package/dist/providers/vercel-ai-gateway.models.js.map +1 -1
  145. package/dist/providers/xai.d.ts +1 -1
  146. package/dist/providers/xai.d.ts.map +1 -1
  147. package/dist/providers/xai.js +11 -3
  148. package/dist/providers/xai.js.map +1 -1
  149. package/dist/providers/xai.models.d.ts +6 -4
  150. package/dist/providers/xai.models.d.ts.map +1 -1
  151. package/dist/providers/xai.models.js +3 -2
  152. package/dist/providers/xai.models.js.map +1 -1
  153. package/package.json +6 -1
  154. package/dist/utils/oauth/anthropic.d.ts +0 -27
  155. package/dist/utils/oauth/anthropic.d.ts.map +0 -1
  156. package/dist/utils/oauth/anthropic.js.map +0 -1
  157. package/dist/utils/oauth/device-code.d.ts.map +0 -1
  158. package/dist/utils/oauth/device-code.js.map +0 -1
  159. package/dist/utils/oauth/github-copilot.d.ts +0 -32
  160. package/dist/utils/oauth/github-copilot.d.ts.map +0 -1
  161. package/dist/utils/oauth/github-copilot.js.map +0 -1
  162. package/dist/utils/oauth/index.d.ts +0 -59
  163. package/dist/utils/oauth/index.d.ts.map +0 -1
  164. package/dist/utils/oauth/index.js +0 -131
  165. package/dist/utils/oauth/index.js.map +0 -1
  166. package/dist/utils/oauth/load.d.ts +0 -5
  167. package/dist/utils/oauth/load.d.ts.map +0 -1
  168. package/dist/utils/oauth/load.js +0 -22
  169. package/dist/utils/oauth/load.js.map +0 -1
  170. package/dist/utils/oauth/oauth-page.d.ts.map +0 -1
  171. package/dist/utils/oauth/oauth-page.js.map +0 -1
  172. package/dist/utils/oauth/openai-codex.d.ts +0 -45
  173. package/dist/utils/oauth/openai-codex.d.ts.map +0 -1
  174. package/dist/utils/oauth/openai-codex.js.map +0 -1
  175. package/dist/utils/oauth/pkce.d.ts.map +0 -1
  176. package/dist/utils/oauth/pkce.js.map +0 -1
  177. package/dist/utils/oauth/radius.d.ts +0 -39
  178. package/dist/utils/oauth/radius.d.ts.map +0 -1
  179. package/dist/utils/oauth/radius.js.map +0 -1
  180. package/dist/utils/oauth/types.d.ts +0 -64
  181. package/dist/utils/oauth/types.d.ts.map +0 -1
  182. package/dist/utils/oauth/types.js +0 -2
  183. package/dist/utils/oauth/types.js.map +0 -1
  184. /package/dist/{utils → auth}/oauth/device-code.d.ts +0 -0
  185. /package/dist/{utils → auth}/oauth/device-code.js +0 -0
  186. /package/dist/{utils → auth}/oauth/oauth-page.d.ts +0 -0
  187. /package/dist/{utils → auth}/oauth/oauth-page.js +0 -0
  188. /package/dist/{utils → auth}/oauth/pkce.d.ts +0 -0
  189. /package/dist/{utils → auth}/oauth/pkce.js +0 -0
package/README.md CHANGED
@@ -17,6 +17,7 @@ Unified LLM API with provider collections, automatic auth resolution, token and
17
17
  - [Dynamic Providers](#dynamic-providers)
18
18
  - [Auth](#auth)
19
19
  - [How Auth Resolves](#how-auth-resolves)
20
+ - [Transforming Request Headers](#transforming-request-headers)
20
21
  - [Credential Store](#credential-store)
21
22
  - [Environment Variables](#environment-variables)
22
23
  - [Tools](#tools)
@@ -334,18 +335,45 @@ await models.complete(model, context);
334
335
  await models.complete(model, context, { apiKey: 'sk-explicit' });
335
336
  ```
336
337
 
337
- You can inspect resolution without making a request useful for status UIs:
338
+ You can inspect resolution without making a request. Pass a provider ID for provider-scoped auth, or a model to include its static `model.headers`:
338
339
 
339
340
  ```typescript
340
- const auth = await models.getAuth(model);
341
- if (auth) {
342
- console.log(`configured via ${auth.source}`); // e.g. "ANTHROPIC_API_KEY", "OAuth", "stored credential"
341
+ const providerAuth = await models.getAuth(model.provider);
342
+ const modelAuth = await models.getAuth(model);
343
+
344
+ if (modelAuth) {
345
+ console.log(`configured via ${modelAuth.source}`); // e.g. "ANTHROPIC_API_KEY", "OAuth", "stored credential"
346
+ console.log(modelAuth.auth.headers); // Provider auth headers + model.headers
343
347
  } else {
344
348
  console.log('not configured');
345
349
  }
346
350
  ```
347
351
 
348
- `getAuth()` resolves `undefined` for unconfigured providers and rejects with `ModelsError` when something is actually broken (`"oauth"`: token refresh failed, credential preserved for re-login; `"auth"`: key resolution or credential store failure). Request paths surface the same failures as stream errors.
352
+ Both overloads resolve credentials, refresh expired OAuth when necessary, and may return an auth-derived `apiKey`, `headers`, or `baseUrl`. `getAuth()` resolves `undefined` for unconfigured providers and rejects with `ModelsError` when something is actually broken (`"oauth"`: token refresh failed, credential preserved for re-login; `"auth"`: key resolution or credential store failure). Request paths surface the same failures as stream errors.
353
+
354
+ ### Transforming Request Headers
355
+
356
+ `Models.stream()`, `complete()`, `streamSimple()`, and `completeSimple()` accept a Models-only `transformHeaders` option. It runs once after provider auth, `model.headers`, and explicit `options.headers` have been merged, but before provider dispatch:
357
+
358
+ ```typescript
359
+ const response = await models.completeSimple(model, context, {
360
+ headers: { "X-Client": "my-app" },
361
+ transformHeaders: async (headers) => ({
362
+ ...headers,
363
+ "X-Request-ID": crypto.randomUUID(),
364
+ }),
365
+ });
366
+ ```
367
+
368
+ The ordering is:
369
+
370
+ ```text
371
+ provider auth headers -> model.headers -> explicit options.headers -> transformHeaders -> Provider.stream*()
372
+ ```
373
+
374
+ Header names are merged case-insensitively. Explicit headers override auth/model headers, and the transform has final control; returning `null` for a header suppresses lower-level defaults that support deletion.
375
+
376
+ `transformHeaders` belongs to `Models`, not `Provider`. A `Models` implementation must consume it and remove it before calling `Provider.stream*()`. Provider implementations continue receiving ordinary `ApiStreamOptions` or `SimpleStreamOptions` and never handle the transform themselves. Use this option instead of calling `getAuth(model)` before `stream*()`, which would resolve request auth twice.
349
377
 
350
378
  ### Credential Store
351
379
 
@@ -359,7 +387,7 @@ const models = createModels({ credentials: myFileBackedStore });
359
387
  // const models = builtinModels({ credentials: myFileBackedStore });
360
388
  ```
361
389
 
362
- The contract is small: `read(providerId)`, `modify(providerId, fn)` (the only write path — a serialized read-modify-write), and `delete(providerId)`. OAuth token refresh runs inside `modify`, so concurrent requests and processes cannot double-refresh a rotated token. A stored credential *owns* its provider: environment variables are only consulted when nothing is stored, and a failed refresh never silently falls back to an env key.
390
+ The contract is small: `read(providerId)`, `list()` for non-secret `{ providerId, type }` metadata, `modify(providerId, fn)` (the only write path — a serialized read-modify-write), and `delete(providerId)`. Enumeration must not resolve secrets or execute configured key commands. OAuth token refresh runs inside `modify`, so concurrent requests and processes cannot double-refresh a rotated token. A stored credential *owns* its provider: environment variables are only consulted when nothing is stored, and a failed refresh never silently falls back to an env key.
363
391
 
364
392
  API-key credentials use the same discriminator as pi's `auth.json` and can carry provider-scoped env/config values:
365
393
 
@@ -412,7 +440,7 @@ Built-in providers resolve these env vars (Node.js; in browsers pass `apiKey` ex
412
440
  | Xiaomi MiMo Token Plan (Singapore) | `XIAOMI_TOKEN_PLAN_SGP_API_KEY` |
413
441
  | GitHub Copilot | `COPILOT_GITHUB_TOKEN` |
414
442
 
415
- Amazon Bedrock resolves ambient AWS credentials (`AWS_PROFILE`, access key pairs, `AWS_BEARER_TOKEN_BEDROCK`, ECS task roles, web identity tokens). Vertex AI resolves either an explicit key or gcloud Application Default Credentials plus project/location.
443
+ Amazon Bedrock resolves ambient AWS credentials (`AWS_PROFILE`, access key pairs, `AWS_BEARER_TOKEN_BEDROCK`, ECS task roles, web identity tokens); its provider-owned login flow supports bearer tokens, AWS profiles, and the existing credential chain. Vertex AI resolves either an explicit key or gcloud Application Default Credentials plus project/location, with a provider-owned login flow for API keys, ADC, and service-account files.
416
444
 
417
445
  ## Tools
418
446
 
@@ -660,7 +688,7 @@ for (const block of result.output) {
660
688
  }
661
689
  ```
662
690
 
663
- Like the chat side, you can build the collection from parts: `createImagesModels({ credentials?, authContext? })`, the `openrouterImagesProvider()` factory from `@earendil-works/pi-ai/providers/openrouter-images`, and `createImagesProvider({ id, auth, models, refreshModels?, api })` for custom image providers (with `imagesModels.refresh(provider?)` for dynamic lists). Failures never reject — they return an `AssistantImages` with `stopReason: "error"`. The collection's `getAuth(model)` works exactly like the chat-side one.
691
+ Like the chat side, you can build the collection from parts: `createImagesModels({ credentials?, authContext? })`, the `openrouterImagesProvider()` factory from `@earendil-works/pi-ai/providers/openrouter-images`, and `createImagesProvider({ id, auth, models, refreshModels?, api })` for custom image providers (with `imagesModels.refresh(provider?)` for dynamic lists). Failures never reject — they return an `AssistantImages` with `stopReason: "error"`. The collection's provider-scoped `getAuth(providerId)` works exactly like the chat-side one.
664
692
 
665
693
  The old global API (`getImageModel()` / `getImageModels()` / `getImageProviders()` / `generateImages()`) remains available on the [compat entrypoint](#migrating-from-the-old-global-api):
666
694
 
@@ -982,22 +1010,46 @@ const gateway = createProvider({
982
1010
  });
983
1011
  ```
984
1012
 
985
- Dynamic model lists use `refreshModels`; the provider lists empty until the first `models.refresh()`:
1013
+ Provider-wide endpoint or request transformations belong in the provider's API implementation: wrap the `ProviderStreams` you pass as `api` so every request goes through the transformation before dispatch. The Cloudflare providers do this to materialize account/gateway endpoint placeholders from the resolved provider env:
986
1014
 
987
1015
  ```typescript
1016
+ function tenantStreams(streams: ProviderStreams): ProviderStreams {
1017
+ const withTenant = (model: Model<Api>) => ({ ...model, baseUrl: model.baseUrl.replace('{tenant}', tenantId) });
1018
+ return {
1019
+ stream: (model, context, options) => streams.stream(withTenant(model), context, options),
1020
+ streamSimple: (model, context, options) => streams.streamSimple(withTenant(model), context, options),
1021
+ };
1022
+ }
1023
+
1024
+ const tenantGateway = createProvider({
1025
+ id: 'tenant-gateway',
1026
+ auth: { apiKey: envApiKeyAuth('Gateway key', ['GATEWAY_API_KEY']) },
1027
+ models: [/* ... */],
1028
+ api: tenantStreams(openAICompletionsApi()),
1029
+ });
1030
+ ```
1031
+
1032
+ Dynamic model lists use `fetchModels`. `Models.refresh()` refreshes every configured dynamic provider, passing its effective API-key or refreshed OAuth credential. A `ModelsStore` persists dynamic catalogs; both stores default to in-memory implementations.
1033
+
1034
+ ```typescript
1035
+ const models = createModels({ credentials, modelsStore });
988
1036
  const llamacpp = createProvider({
989
1037
  id: 'llamacpp',
990
1038
  auth: { apiKey: { name: 'llama.cpp', resolve: async () => ({ auth: {} }) } },
991
1039
  models: [],
992
- refreshModels: async () => fetchModelsFromServer('http://localhost:8080'),
1040
+ fetchModels: async ({ signal }) => fetchModelsFromServer('http://localhost:8080', signal),
993
1041
  api: openAICompletionsApi(),
994
1042
  });
995
1043
 
996
1044
  models.setProvider(llamacpp);
997
- await models.refresh('llamacpp');
1045
+ const result = await models.refresh({ signal });
1046
+ if (result.aborted) console.log('refresh cancelled');
1047
+ for (const [provider, error] of result.errors) console.error(provider, error);
998
1048
  ```
999
1049
 
1000
- Custom models can carry `headers` (e.g. proxies behind bot detection) and `compat` flags see [OpenAI Compatibility Settings](#openai-compatibility-settings).
1050
+ Use `models.refresh({ allowNetwork: false })` to restore persisted catalogs without network access, or `models.refresh({ force: true })` to bypass provider freshness checks. Model reads stay synchronous and return the last restored or refreshed list.
1051
+
1052
+ Custom models can carry `headers` (e.g. proxies behind bot detection) and `compat` flags. `Models.getAuth(model)` includes those model headers, and stream methods merge them before explicit request headers and `transformHeaders`. See [OpenAI Compatibility Settings](#openai-compatibility-settings).
1001
1053
 
1002
1054
  Some OpenAI-compatible servers do not understand the `developer` role used for reasoning-capable models. For those providers, set `compat.supportsDeveloperRole` to `false` so the system prompt is sent as a `system` message instead. If the server also does not support `reasoning_effort`, set `compat.supportsReasoningEffort` to `false` too. This commonly applies to Ollama, vLLM, SGLang, and similar OpenAI-compatible servers.
1003
1055
 
@@ -1369,7 +1421,7 @@ Several providers support OAuth authentication instead of static API keys:
1369
1421
  - **OpenAI Codex** (ChatGPT Plus/Pro subscription, access to GPT-5.x Codex models)
1370
1422
  - **GitHub Copilot** (Copilot subscription)
1371
1423
 
1372
- Each of these providers carries an `OAuthAuth` on `provider.auth.oauth` with three operations: `login(callbacks)` runs the interactive flow and returns a credential, `refresh(credential)` exchanges the refresh token, and `toAuth(credential)` derives request auth (GitHub Copilot's per-account base URL comes from here). Refresh is automatic: `models.getAuth()` and the request paths refresh expired tokens under a credential-store lock, so concurrent requests and processes cannot double-refresh.
1424
+ Each of these providers carries an `OAuthAuth` on `provider.auth.oauth` with three operations: `login(interaction)` uses the provider-neutral `AuthInteraction.prompt()`/`notify()` protocol and returns a credential, `refresh(credential)` exchanges the refresh token, and `toAuth(credential)` derives request auth (GitHub Copilot's per-account base URL comes from here). Refresh is automatic: `models.getAuth(providerId)` and request paths refresh expired tokens under a credential-store lock, so concurrent requests and processes cannot double-refresh.
1373
1425
 
1374
1426
  ```typescript
1375
1427
  import { createModels } from '@earendil-works/pi-ai';
@@ -1378,34 +1430,36 @@ import { anthropicProvider } from '@earendil-works/pi-ai/providers/anthropic';
1378
1430
  const models = createModels({ credentials: myStore }); // persistent CredentialStore
1379
1431
  models.setProvider(anthropicProvider());
1380
1432
 
1381
- // Login: drive the flow with prompt()/notify() callbacks, persist the credential
1382
- const provider = models.getProvider('anthropic')!;
1383
- const credential = await provider.auth.oauth!.login({
1433
+ // Login: Models drives the flow and persists the credential
1434
+ await models.login('anthropic', 'oauth', {
1384
1435
  prompt: async (p) => {
1385
1436
  // p.type: 'text' | 'secret' | 'select' | 'manual_code'
1386
1437
  // manual_code prompts race a local callback server; p.signal aborts them when the server wins
1387
1438
  return await askUser(p.message);
1388
1439
  },
1389
1440
  notify: (event) => {
1390
- // event.type: 'auth_url' | 'device_code' | 'progress'
1441
+ // event.type: 'info' | 'auth_url' | 'device_code' | 'progress'
1442
+ if (event.type === 'info') {
1443
+ console.log(event.message);
1444
+ for (const link of event.links ?? []) console.log(`${link.label ?? 'More information'}: ${link.url}`);
1445
+ }
1391
1446
  if (event.type === 'auth_url') console.log(`Open: ${event.url}`);
1392
1447
  if (event.type === 'device_code') console.log(`Code: ${event.userCode} at ${event.verificationUri}`);
1393
1448
  if (event.type === 'progress') console.log(event.message);
1394
1449
  },
1395
1450
  });
1396
- await myStore.modify('anthropic', async () => credential);
1397
1451
 
1398
1452
  // From here on, requests resolve and refresh the token automatically
1399
1453
  const model = models.getModel('anthropic', 'claude-sonnet-4-5')!;
1400
1454
  await models.complete(model, context);
1401
1455
 
1402
1456
  // Logout
1403
- await myStore.delete('anthropic');
1457
+ await models.logout('anthropic');
1404
1458
  ```
1405
1459
 
1406
1460
  ### Vertex AI
1407
1461
 
1408
- Vertex AI models support either a Google Cloud API key or Application Default Credentials (ADC):
1462
+ Vertex AI models support either a Google Cloud API key or Application Default Credentials (ADC). Its provider-owned API-key login flow can configure either method:
1409
1463
 
1410
1464
  - **API key**: Set `GOOGLE_CLOUD_API_KEY` or pass `apiKey` in the call options.
1411
1465
  - **Local development (ADC)**: Run `gcloud auth application-default login`
@@ -1439,7 +1493,7 @@ Credentials are saved to `auth.json` in the current directory.
1439
1493
 
1440
1494
  ### Programmatic OAuth
1441
1495
 
1442
- The legacy flow functions remain available via the `@earendil-works/pi-ai/oauth` entry point (`loginAnthropic`, `loginOpenAICodex`, `loginGitHubCopilot`, `refreshOAuthToken`, `getOAuthApiKey`); credential storage is the caller's responsibility there. New code should prefer the provider-owned `OAuthAuth` shown above it composes with the credential store and gets locked auto-refresh for free.
1496
+ Built-in login and refresh flows are private provider implementations. Use provider-owned `OAuthAuth`, which composes with `CredentialStore` and gets locked auto-refresh through `Models`. The `@earendil-works/pi-ai/oauth` entry point retains only type declarations required by coding-agent extension OAuth compatibility.
1443
1497
 
1444
1498
  Provider notes:
1445
1499
 
@@ -1469,7 +1523,7 @@ Compat is a strict superset of the root entrypoint, so a file can switch its imp
1469
1523
  | `getModels('anthropic')` / `getProviders()` | `models.getModels('anthropic')` / `models.getProviders()` or `getBuiltin*` |
1470
1524
  | `stream(model, ctx, opts)` (env-key injection) | `models.stream(model, ctx, opts)` (provider auth resolution) |
1471
1525
  | `registerApiProvider({ api, stream, streamSimple })` | `createProvider({ id, auth, models, api })` + `models.setProvider()` |
1472
- | `getEnvApiKey('openai')` | `await models.getAuth(model)` |
1526
+ | `getEnvApiKey('openai')` | `await models.getAuth(model.provider)` |
1473
1527
  | `streamAnthropic(model, ctx, opts)` | `stream` from `@earendil-works/pi-ai/api/anthropic-messages`, or a provider in a collection |
1474
1528
  | `registerFauxProvider()` | `fauxProvider()` + `models.setProvider()` |
1475
1529
 
@@ -1 +1 @@
1
- {"version":3,"file":"lazy.d.ts","sourceRoot":"","sources":["../../src/api/lazy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAoB,qBAAqB,EAAE,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACxG,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAgCvE;;;;GAIG;AACH,wBAAgB,UAAU,CACzB,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,KAAK,EAAE,MAAM,OAAO,CAAC,aAAa,CAAC,qBAAqB,CAAC,CAAC,GACxD,2BAA2B,CAc7B;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,OAAO,CAAC,eAAe,CAAC,GAAG,eAAe,CAO7E","sourcesContent":["import type { Api, AssistantMessage, AssistantMessageEvent, Model, ProviderStreams } from \"../types.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\n\nfunction createSetupErrorMessage(model: Model<Api>, error: unknown): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction forwardStream(target: AssistantMessageEventStream, source: AsyncIterable<AssistantMessageEvent>): void {\n\t(async () => {\n\t\tfor await (const event of source) {\n\t\t\ttarget.push(event);\n\t\t}\n\t\ttarget.end();\n\t})();\n}\n\n/**\n * Returns a stream synchronously while running async setup (auth resolution,\n * lazy module loading) behind it. Setup failures terminate the stream with an\n * error event.\n */\nexport function lazyStream(\n\tmodel: Model<Api>,\n\tsetup: () => Promise<AsyncIterable<AssistantMessageEvent>>,\n): AssistantMessageEventStream {\n\tconst outer = new AssistantMessageEventStream();\n\n\tsetup()\n\t\t.then((inner) => {\n\t\t\tforwardStream(outer, inner);\n\t\t})\n\t\t.catch((error) => {\n\t\t\tconst message = createSetupErrorMessage(model, error);\n\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\touter.end(message);\n\t\t});\n\n\treturn outer;\n}\n\n/**\n * Wraps a dynamically imported API implementation module as `ProviderStreams`.\n * The module loads on first stream call; the host's import cache deduplicates\n * loads. Load failures terminate the returned stream with an error event.\n */\nexport function lazyApi(load: () => Promise<ProviderStreams>): ProviderStreams {\n\treturn {\n\t\tstream: (model, context, options) =>\n\t\t\tlazyStream(model, async () => (await load()).stream(model, context, options)),\n\t\tstreamSimple: (model, context, options) =>\n\t\t\tlazyStream(model, async () => (await load()).streamSimple(model, context, options)),\n\t};\n}\n"]}
1
+ {"version":3,"file":"lazy.d.ts","sourceRoot":"","sources":["../../src/api/lazy.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,GAAG,EAAoB,qBAAqB,EAAE,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AACxG,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAuCvE;;;;GAIG;AACH,wBAAgB,UAAU,CACzB,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,KAAK,EAAE,MAAM,OAAO,CAAC,aAAa,CAAC,qBAAqB,CAAC,CAAC,GACxD,2BAA2B,CAY7B;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,IAAI,EAAE,MAAM,OAAO,CAAC,eAAe,CAAC,GAAG,eAAe,CAO7E","sourcesContent":["import type { Api, AssistantMessage, AssistantMessageEvent, Model, ProviderStreams } from \"../types.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\n\nfunction createSetupErrorMessage(model: Model<Api>, error: unknown): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction hasResult(\n\tsource: AsyncIterable<AssistantMessageEvent>,\n): source is AsyncIterable<AssistantMessageEvent> & { result(): Promise<AssistantMessage> } {\n\treturn typeof (source as { result?: unknown }).result === \"function\";\n}\n\nasync function forwardStream(\n\ttarget: AssistantMessageEventStream,\n\tsource: AsyncIterable<AssistantMessageEvent>,\n): Promise<void> {\n\tfor await (const event of source) {\n\t\ttarget.push(event);\n\t}\n\ttarget.end(hasResult(source) ? await source.result() : undefined);\n}\n\n/**\n * Returns a stream synchronously while running async setup (auth resolution,\n * lazy module loading) behind it. Setup failures terminate the stream with an\n * error event.\n */\nexport function lazyStream(\n\tmodel: Model<Api>,\n\tsetup: () => Promise<AsyncIterable<AssistantMessageEvent>>,\n): AssistantMessageEventStream {\n\tconst outer = new AssistantMessageEventStream();\n\n\tsetup()\n\t\t.then((inner) => forwardStream(outer, inner))\n\t\t.catch((error) => {\n\t\t\tconst message = createSetupErrorMessage(model, error);\n\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\touter.end(message);\n\t\t});\n\n\treturn outer;\n}\n\n/**\n * Wraps a dynamically imported API implementation module as `ProviderStreams`.\n * The module loads on first stream call; the host's import cache deduplicates\n * loads. Load failures terminate the returned stream with an error event.\n */\nexport function lazyApi(load: () => Promise<ProviderStreams>): ProviderStreams {\n\treturn {\n\t\tstream: (model, context, options) =>\n\t\t\tlazyStream(model, async () => (await load()).stream(model, context, options)),\n\t\tstreamSimple: (model, context, options) =>\n\t\t\tlazyStream(model, async () => (await load()).streamSimple(model, context, options)),\n\t};\n}\n"]}
package/dist/api/lazy.js CHANGED
@@ -19,13 +19,14 @@ function createSetupErrorMessage(model, error) {
19
19
  timestamp: Date.now(),
20
20
  };
21
21
  }
22
- function forwardStream(target, source) {
23
- (async () => {
24
- for await (const event of source) {
25
- target.push(event);
26
- }
27
- target.end();
28
- })();
22
+ function hasResult(source) {
23
+ return typeof source.result === "function";
24
+ }
25
+ async function forwardStream(target, source) {
26
+ for await (const event of source) {
27
+ target.push(event);
28
+ }
29
+ target.end(hasResult(source) ? await source.result() : undefined);
29
30
  }
30
31
  /**
31
32
  * Returns a stream synchronously while running async setup (auth resolution,
@@ -35,9 +36,7 @@ function forwardStream(target, source) {
35
36
  export function lazyStream(model, setup) {
36
37
  const outer = new AssistantMessageEventStream();
37
38
  setup()
38
- .then((inner) => {
39
- forwardStream(outer, inner);
40
- })
39
+ .then((inner) => forwardStream(outer, inner))
41
40
  .catch((error) => {
42
41
  const message = createSetupErrorMessage(model, error);
43
42
  outer.push({ type: "error", reason: "error", error: message });
@@ -1 +1 @@
1
- {"version":3,"file":"lazy.js","sourceRoot":"","sources":["../../src/api/lazy.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAEvE,SAAS,uBAAuB,CAAC,KAAiB,EAAE,KAAc,EAAoB;IACrF,OAAO;QACN,IAAI,EAAE,WAAW;QACjB,OAAO,EAAE,EAAE;QACX,GAAG,EAAE,KAAK,CAAC,GAAG;QACd,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,KAAK,EAAE,KAAK,CAAC,EAAE;QACf,KAAK,EAAE;YACN,KAAK,EAAE,CAAC;YACR,MAAM,EAAE,CAAC;YACT,SAAS,EAAE,CAAC;YACZ,UAAU,EAAE,CAAC;YACb,WAAW,EAAE,CAAC;YACd,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE;SACpE;QACD,UAAU,EAAE,OAAO;QACnB,YAAY,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;QACpE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;KACrB,CAAC;AAAA,CACF;AAED,SAAS,aAAa,CAAC,MAAmC,EAAE,MAA4C,EAAQ;IAC/G,CAAC,KAAK,IAAI,EAAE,CAAC;QACZ,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;YAClC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACpB,CAAC;QACD,MAAM,CAAC,GAAG,EAAE,CAAC;IAAA,CACb,CAAC,EAAE,CAAC;AAAA,CACL;AAED;;;;GAIG;AACH,MAAM,UAAU,UAAU,CACzB,KAAiB,EACjB,KAA0D,EAC5B;IAC9B,MAAM,KAAK,GAAG,IAAI,2BAA2B,EAAE,CAAC;IAEhD,KAAK,EAAE;SACL,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC;QAChB,aAAa,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IAAA,CAC5B,CAAC;SACD,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC;QACjB,MAAM,OAAO,GAAG,uBAAuB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QACtD,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;QAC/D,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAAA,CACnB,CAAC,CAAC;IAEJ,OAAO,KAAK,CAAC;AAAA,CACb;AAED;;;;GAIG;AACH,MAAM,UAAU,OAAO,CAAC,IAAoC,EAAmB;IAC9E,OAAO;QACN,MAAM,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CACnC,UAAU,CAAC,KAAK,EAAE,KAAK,IAAI,EAAE,CAAC,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QAC9E,YAAY,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CACzC,UAAU,CAAC,KAAK,EAAE,KAAK,IAAI,EAAE,CAAC,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;KACpF,CAAC;AAAA,CACF","sourcesContent":["import type { Api, AssistantMessage, AssistantMessageEvent, Model, ProviderStreams } from \"../types.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\n\nfunction createSetupErrorMessage(model: Model<Api>, error: unknown): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction forwardStream(target: AssistantMessageEventStream, source: AsyncIterable<AssistantMessageEvent>): void {\n\t(async () => {\n\t\tfor await (const event of source) {\n\t\t\ttarget.push(event);\n\t\t}\n\t\ttarget.end();\n\t})();\n}\n\n/**\n * Returns a stream synchronously while running async setup (auth resolution,\n * lazy module loading) behind it. Setup failures terminate the stream with an\n * error event.\n */\nexport function lazyStream(\n\tmodel: Model<Api>,\n\tsetup: () => Promise<AsyncIterable<AssistantMessageEvent>>,\n): AssistantMessageEventStream {\n\tconst outer = new AssistantMessageEventStream();\n\n\tsetup()\n\t\t.then((inner) => {\n\t\t\tforwardStream(outer, inner);\n\t\t})\n\t\t.catch((error) => {\n\t\t\tconst message = createSetupErrorMessage(model, error);\n\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\touter.end(message);\n\t\t});\n\n\treturn outer;\n}\n\n/**\n * Wraps a dynamically imported API implementation module as `ProviderStreams`.\n * The module loads on first stream call; the host's import cache deduplicates\n * loads. Load failures terminate the returned stream with an error event.\n */\nexport function lazyApi(load: () => Promise<ProviderStreams>): ProviderStreams {\n\treturn {\n\t\tstream: (model, context, options) =>\n\t\t\tlazyStream(model, async () => (await load()).stream(model, context, options)),\n\t\tstreamSimple: (model, context, options) =>\n\t\t\tlazyStream(model, async () => (await load()).streamSimple(model, context, options)),\n\t};\n}\n"]}
1
+ {"version":3,"file":"lazy.js","sourceRoot":"","sources":["../../src/api/lazy.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAEvE,SAAS,uBAAuB,CAAC,KAAiB,EAAE,KAAc,EAAoB;IACrF,OAAO;QACN,IAAI,EAAE,WAAW;QACjB,OAAO,EAAE,EAAE;QACX,GAAG,EAAE,KAAK,CAAC,GAAG;QACd,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,KAAK,EAAE,KAAK,CAAC,EAAE;QACf,KAAK,EAAE;YACN,KAAK,EAAE,CAAC;YACR,MAAM,EAAE,CAAC;YACT,SAAS,EAAE,CAAC;YACZ,UAAU,EAAE,CAAC;YACb,WAAW,EAAE,CAAC;YACd,IAAI,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,UAAU,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE;SACpE;QACD,UAAU,EAAE,OAAO;QACnB,YAAY,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;QACpE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE;KACrB,CAAC;AAAA,CACF;AAED,SAAS,SAAS,CACjB,MAA4C,EAC+C;IAC3F,OAAO,OAAQ,MAA+B,CAAC,MAAM,KAAK,UAAU,CAAC;AAAA,CACrE;AAED,KAAK,UAAU,aAAa,CAC3B,MAAmC,EACnC,MAA4C,EAC5B;IAChB,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAClC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACpB,CAAC;IACD,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;AAAA,CAClE;AAED;;;;GAIG;AACH,MAAM,UAAU,UAAU,CACzB,KAAiB,EACjB,KAA0D,EAC5B;IAC9B,MAAM,KAAK,GAAG,IAAI,2BAA2B,EAAE,CAAC;IAEhD,KAAK,EAAE;SACL,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,aAAa,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;SAC5C,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC;QACjB,MAAM,OAAO,GAAG,uBAAuB,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QACtD,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC,CAAC;QAC/D,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;IAAA,CACnB,CAAC,CAAC;IAEJ,OAAO,KAAK,CAAC;AAAA,CACb;AAED;;;;GAIG;AACH,MAAM,UAAU,OAAO,CAAC,IAAoC,EAAmB;IAC9E,OAAO;QACN,MAAM,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CACnC,UAAU,CAAC,KAAK,EAAE,KAAK,IAAI,EAAE,CAAC,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;QAC9E,YAAY,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CACzC,UAAU,CAAC,KAAK,EAAE,KAAK,IAAI,EAAE,CAAC,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC,YAAY,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;KACpF,CAAC;AAAA,CACF","sourcesContent":["import type { Api, AssistantMessage, AssistantMessageEvent, Model, ProviderStreams } from \"../types.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\n\nfunction createSetupErrorMessage(model: Model<Api>, error: unknown): AssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: [],\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tusage: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotalTokens: 0,\n\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t},\n\t\tstopReason: \"error\",\n\t\terrorMessage: error instanceof Error ? error.message : String(error),\n\t\ttimestamp: Date.now(),\n\t};\n}\n\nfunction hasResult(\n\tsource: AsyncIterable<AssistantMessageEvent>,\n): source is AsyncIterable<AssistantMessageEvent> & { result(): Promise<AssistantMessage> } {\n\treturn typeof (source as { result?: unknown }).result === \"function\";\n}\n\nasync function forwardStream(\n\ttarget: AssistantMessageEventStream,\n\tsource: AsyncIterable<AssistantMessageEvent>,\n): Promise<void> {\n\tfor await (const event of source) {\n\t\ttarget.push(event);\n\t}\n\ttarget.end(hasResult(source) ? await source.result() : undefined);\n}\n\n/**\n * Returns a stream synchronously while running async setup (auth resolution,\n * lazy module loading) behind it. Setup failures terminate the stream with an\n * error event.\n */\nexport function lazyStream(\n\tmodel: Model<Api>,\n\tsetup: () => Promise<AsyncIterable<AssistantMessageEvent>>,\n): AssistantMessageEventStream {\n\tconst outer = new AssistantMessageEventStream();\n\n\tsetup()\n\t\t.then((inner) => forwardStream(outer, inner))\n\t\t.catch((error) => {\n\t\t\tconst message = createSetupErrorMessage(model, error);\n\t\t\touter.push({ type: \"error\", reason: \"error\", error: message });\n\t\t\touter.end(message);\n\t\t});\n\n\treturn outer;\n}\n\n/**\n * Wraps a dynamically imported API implementation module as `ProviderStreams`.\n * The module loads on first stream call; the host's import cache deduplicates\n * loads. Load failures terminate the returned stream with an error event.\n */\nexport function lazyApi(load: () => Promise<ProviderStreams>): ProviderStreams {\n\treturn {\n\t\tstream: (model, context, options) =>\n\t\t\tlazyStream(model, async () => (await load()).stream(model, context, options)),\n\t\tstreamSimple: (model, context, options) =>\n\t\t\tlazyStream(model, async () => (await load()).streamSimple(model, context, options)),\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"openai-codex-responses.d.ts","sourceRoot":"","sources":["../../src/api/openai-codex-responses.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAEX,6BAA6B,EAG7B,MAAM,yCAAyC,CAAC;AAkBjD,OAAO,KAAK,EAOX,mBAAmB,EACnB,cAAc,EACd,aAAa,EAEb,MAAM,aAAa,CAAC;AA8CrB,MAAM,WAAW,2BAA4B,SAAQ,aAAa;IACjE,eAAe,CAAC,EAAE,MAAM,GAAG,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,GAAG,KAAK,CAAC;IACnF,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,GAAG,UAAU,GAAG,KAAK,GAAG,IAAI,GAAG,IAAI,CAAC;IACzE,WAAW,CAAC,EAAE,6BAA6B,CAAC,cAAc,CAAC,CAAC;IAC5D,aAAa,CAAC,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;IAC1C,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,UAAU,CAAC;CAC1C;AAsID,eAAO,MAAM,MAAM,EAAE,cAAc,CAAC,wBAAwB,EAAE,2BAA2B,CAwOxF,CAAC;AAEF,eAAO,MAAM,YAAY,EAAE,cAAc,CAAC,wBAAwB,EAAE,mBAAmB,CAkBtF,CAAC;AAoTF,MAAM,WAAW,8BAA8B;IAC9C,QAAQ,EAAE,MAAM,CAAC;IACjB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,qBAAqB,EAAE,MAAM,CAAC;IAC9B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,mBAAmB,EAAE,MAAM,CAAC;IAC5B,aAAa,EAAE,MAAM,CAAC;IACtB,cAAc,EAAE,MAAM,CAAC;IACvB,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,iBAAiB,EAAE,MAAM,CAAC;IAC1B,YAAY,EAAE,MAAM,CAAC;IACrB,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAClC,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC5B;AA0BD,wBAAgB,iCAAiC,CAAC,SAAS,EAAE,MAAM,GAAG,8BAA8B,GAAG,SAAS,CAG/G;AAED,wBAAgB,mCAAmC,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAQ5E;AAED,wBAAgB,iCAAiC,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAe1E","sourcesContent":["import type * as NodeOs from \"node:os\";\nimport type * as NodeZlib from \"node:zlib\";\nimport type {\n\tTool as OpenAITool,\n\tResponseCreateParamsStreaming,\n\tResponseInput,\n\tResponseStreamEvent,\n} from \"openai/resources/responses/responses.js\";\n\ntype ProcessWithOsBuiltinModule = typeof process & {\n\tgetBuiltinModule?: (id: \"node:os\") => typeof NodeOs;\n};\n\nfunction loadNodeOs(): typeof NodeOs | null {\n\tif (typeof process === \"undefined\" || !(process.versions?.node || process.versions?.bun)) {\n\t\treturn null;\n\t}\n\treturn (process as ProcessWithOsBuiltinModule).getBuiltinModule?.(\"node:os\") ?? null;\n}\n\n// NEVER convert to top-level runtime imports - breaks browser/Vite builds\nconst _os: typeof NodeOs | null = loadNodeOs();\n\nimport { clampThinkingLevel } from \"../models.ts\";\nimport { registerSessionResourceCleanup } from \"../session-resources.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tModel,\n\tProviderEnv,\n\tProviderHeaders,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tUsage,\n} from \"../types.ts\";\nimport { combineAbortSignals } from \"../utils/abort-signals.ts\";\nimport { splitDeferredTools } from \"../utils/deferred-tools.ts\";\nimport {\n\tappendAssistantMessageDiagnostic,\n\tcreateAssistantMessageDiagnostic,\n\tformatThrownValue,\n} from \"../utils/diagnostics.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { headersToRecord } from \"../utils/headers.ts\";\nimport { resolveHttpProxyUrlForTarget } from \"../utils/node-http-proxy.ts\";\nimport { clampOpenAIPromptCacheKey } from \"./openai-prompt-cache.ts\";\nimport { convertResponsesMessages, convertResponsesTools, processResponsesStream } from \"./openai-responses-shared.ts\";\nimport { buildBaseOptions } from \"./simple-options.ts\";\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\nconst DEFAULT_CODEX_BASE_URL = \"https://chatgpt.com/backend-api\";\nconst JWT_CLAIM_PATH = \"https://api.openai.com/auth\" as const;\nconst DEFAULT_MAX_RETRIES = 0;\nconst BASE_DELAY_MS = 1000;\nconst DEFAULT_MAX_RETRY_DELAY_MS = 60_000;\nconst DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS = 15_000;\n// The Codex backend accepts zstd-compressed request bodies on the SSE responses\n// endpoint (the same endpoint the official Codex client compresses against).\nconst REQUEST_COMPRESSION_ZSTD_LEVEL = 3;\nconst CODEX_TOOL_CALL_PROVIDERS = new Set([\"openai\", \"openai-codex\", \"opencode\"]);\nconst WEBSOCKET_MESSAGE_TOO_BIG_CLOSE_CODE = 1009;\nconst WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE = \"websocket_connection_limit_reached\";\n\nconst CODEX_RESPONSE_STATUSES = new Set<CodexResponseStatus>([\n\t\"completed\",\n\t\"incomplete\",\n\t\"failed\",\n\t\"cancelled\",\n\t\"queued\",\n\t\"in_progress\",\n]);\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface OpenAICodexResponsesOptions extends StreamOptions {\n\treasoningEffort?: \"none\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\treasoningSummary?: \"auto\" | \"concise\" | \"detailed\" | \"off\" | \"on\" | null;\n\tserviceTier?: ResponseCreateParamsStreaming[\"service_tier\"];\n\ttextVerbosity?: \"low\" | \"medium\" | \"high\";\n\ttoolChoice?: \"auto\" | \"none\" | \"required\";\n}\n\ntype CodexResponseStatus = \"completed\" | \"incomplete\" | \"failed\" | \"cancelled\" | \"queued\" | \"in_progress\";\n\ninterface RequestBody {\n\tmodel: string;\n\tstore?: boolean;\n\tstream?: boolean;\n\tinstructions?: string;\n\tprevious_response_id?: string;\n\tinput?: ResponseInput;\n\ttools?: OpenAITool[];\n\ttool_choice?: OpenAICodexResponsesOptions[\"toolChoice\"];\n\tparallel_tool_calls?: boolean;\n\ttemperature?: number;\n\treasoning?: { effort?: string; summary?: string };\n\tservice_tier?: ResponseCreateParamsStreaming[\"service_tier\"];\n\ttext?: { verbosity?: string };\n\tinclude?: string[];\n\tprompt_cache_key?: string;\n\t[key: string]: unknown;\n}\n\n// ============================================================================\n// Retry Helpers\n// ============================================================================\n\nfunction isTerminalRateLimitError(errorText: string): boolean {\n\treturn /GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(\n\t\terrorText,\n\t);\n}\n\nfunction isRetryableError(status: number, errorText: string): boolean {\n\tif (status === 429 && isTerminalRateLimitError(errorText)) {\n\t\treturn false;\n\t}\n\tif (status === 429 || status === 500 || status === 502 || status === 503 || status === 504) {\n\t\treturn true;\n\t}\n\treturn /rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(errorText);\n}\n\nfunction getRetryAfterDelayMs(headers: Headers): number | undefined {\n\tconst retryAfterMs = headers.get(\"retry-after-ms\");\n\tif (retryAfterMs !== null) {\n\t\tconst millis = Number(retryAfterMs);\n\t\tif (Number.isFinite(millis)) {\n\t\t\treturn Math.max(0, millis);\n\t\t}\n\t}\n\n\tconst retryAfter = headers.get(\"retry-after\");\n\tif (!retryAfter) {\n\t\treturn undefined;\n\t}\n\n\tconst seconds = Number(retryAfter);\n\tif (Number.isFinite(seconds)) {\n\t\treturn Math.max(0, seconds * 1000);\n\t}\n\n\tconst date = Date.parse(retryAfter);\n\tif (!Number.isNaN(date)) {\n\t\treturn Math.max(0, date - Date.now());\n\t}\n\n\treturn undefined;\n}\n\nfunction capRetryDelayMs(delayMs: number, options?: StreamOptions): number {\n\tconst maxRetryDelayMs = options?.maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;\n\treturn maxRetryDelayMs > 0 ? Math.min(delayMs, maxRetryDelayMs) : delayMs;\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new Error(\"Request was aborted\"));\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\"abort\", () => {\n\t\t\tclearTimeout(timeout);\n\t\t\treject(new Error(\"Request was aborted\"));\n\t\t});\n\t});\n}\n\nfunction normalizeTimeoutMs(value: number | undefined): number | undefined {\n\tif (value === undefined) return undefined;\n\tif (!Number.isFinite(value) || value < 0) {\n\t\tthrow new Error(`Invalid timeoutMs: ${String(value)}`);\n\t}\n\treturn Math.floor(value);\n}\n\n// ============================================================================\n// Request Compression\n// ============================================================================\n\ntype ProcessWithBuiltinModule = typeof process & {\n\tgetBuiltinModule?: (id: \"node:zlib\") => typeof NodeZlib;\n};\n\nfunction loadNodeZlib(): typeof NodeZlib | null {\n\tif (typeof process === \"undefined\" || !(process.versions?.node || process.versions?.bun)) {\n\t\treturn null;\n\t}\n\treturn (process as ProcessWithBuiltinModule).getBuiltinModule?.(\"node:zlib\") ?? null;\n}\n\n// Returns the zstd-compressed body bytes, or null when compression is\n// unavailable (browser/Vite builds). Callers fall back to sending the\n// uncompressed JSON when this returns null.\nfunction compressRequestBodyZstd(bodyJson: string): Uint8Array | null {\n\tconst zlib = loadNodeZlib();\n\tif (!zlib || typeof zlib.zstdCompressSync !== \"function\") {\n\t\treturn null;\n\t}\n\ttry {\n\t\tconst compressed = zlib.zstdCompressSync(bodyJson, {\n\t\t\tparams: { [zlib.constants.ZSTD_c_compressionLevel]: REQUEST_COMPRESSION_ZSTD_LEVEL },\n\t\t});\n\t\treturn new Uint8Array(compressed.buffer, compressed.byteOffset, compressed.byteLength);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n// ============================================================================\n// Main Stream Function\n// ============================================================================\n\nexport const stream: StreamFunction<\"openai-codex-responses\", OpenAICodexResponsesOptions> = (\n\tmodel: Model<\"openai-codex-responses\">,\n\tcontext: Context,\n\toptions?: OpenAICodexResponsesOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: \"openai-codex-responses\" as Api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"stop\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\ttry {\n\t\t\tconst apiKey = options?.apiKey;\n\t\t\tif (!apiKey) {\n\t\t\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t\t\t}\n\n\t\t\tconst accountId = extractAccountId(apiKey);\n\t\t\tlet body = buildRequestBody(model, context, options);\n\t\t\tconst nextBody = await options?.onPayload?.(body, model);\n\t\t\tif (nextBody !== undefined) {\n\t\t\t\tbody = nextBody as RequestBody;\n\t\t\t}\n\t\t\tconst websocketRequestId = options?.sessionId || createCodexRequestId();\n\t\t\tconst sseHeaders = buildSSEHeaders(model.headers, options?.headers, accountId, apiKey, options?.sessionId);\n\t\t\tconst websocketHeaders = buildWebSocketHeaders(\n\t\t\t\tmodel.headers,\n\t\t\t\toptions?.headers,\n\t\t\t\taccountId,\n\t\t\t\tapiKey,\n\t\t\t\twebsocketRequestId,\n\t\t\t);\n\t\t\tconst bodyJson = JSON.stringify(body);\n\t\t\tconst httpTimeoutMs = normalizeTimeoutMs(options?.timeoutMs);\n\t\t\tconst websocketConnectTimeoutMs = normalizeTimeoutMs(options?.websocketConnectTimeoutMs);\n\t\t\tconst transport = options?.transport || \"auto\";\n\t\t\tconst websocketDisabledForSession = transport !== \"sse\" && isWebSocketSseFallbackActive(options?.sessionId);\n\t\t\tif (websocketDisabledForSession) {\n\t\t\t\trecordWebSocketSseFallback(options?.sessionId);\n\t\t\t}\n\n\t\t\tif (transport !== \"sse\" && !websocketDisabledForSession) {\n\t\t\t\tlet websocketStarted = false;\n\t\t\t\tlet retriedWebSocketConnectionLimit = false;\n\t\t\t\twhile (true) {\n\t\t\t\t\twebsocketStarted = false;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait processWebSocketStream(\n\t\t\t\t\t\t\tresolveCodexWebSocketUrl(model.baseUrl),\n\t\t\t\t\t\t\tbody,\n\t\t\t\t\t\t\twebsocketHeaders,\n\t\t\t\t\t\t\toutput,\n\t\t\t\t\t\t\tstream,\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\t\twebsocketStarted = true;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\thttpTimeoutMs,\n\t\t\t\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\t\t\t\toptions,\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"done\",\n\t\t\t\t\t\t\treason: output.stopReason as \"stop\" | \"length\" | \"toolUse\",\n\t\t\t\t\t\t\tmessage: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tstream.end();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst aborted = options?.signal?.aborted;\n\t\t\t\t\t\tconst connectionLimitBeforeStart = !websocketStarted && isWebSocketConnectionLimitReachedError(error);\n\t\t\t\t\t\tif (!aborted && connectionLimitBeforeStart && !retriedWebSocketConnectionLimit) {\n\t\t\t\t\t\t\tretriedWebSocketConnectionLimit = true;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (aborted || (isCodexNonTransportError(error) && !connectionLimitBeforeStart)) {\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tappendAssistantMessageDiagnostic(\n\t\t\t\t\t\t\toutput,\n\t\t\t\t\t\t\tcreateAssistantMessageDiagnostic(\"provider_transport_failure\", error, {\n\t\t\t\t\t\t\t\tconfiguredTransport: transport,\n\t\t\t\t\t\t\t\tfallbackTransport: websocketStarted ? undefined : \"sse\",\n\t\t\t\t\t\t\t\teventsEmitted: websocketStarted,\n\t\t\t\t\t\t\t\tphase: websocketStarted ? \"after_message_stream_start\" : \"before_message_stream_start\",\n\t\t\t\t\t\t\t\trequestBytes: new TextEncoder().encode(bodyJson).byteLength,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t\trecordWebSocketFailure(options?.sessionId, error);\n\t\t\t\t\t\tif (websocketStarted) {\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t\trecordWebSocketSseFallback(options?.sessionId);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Compress the request body once for the SSE path. The Codex backend\n\t\t\t// decodes Content-Encoding: zstd; the WebSocket transport above sends the\n\t\t\t// uncompressed JSON frame, matching the official Codex client.\n\t\t\tconst compressedBody = compressRequestBodyZstd(bodyJson);\n\t\t\tif (compressedBody) {\n\t\t\t\tsseHeaders.set(\"content-encoding\", \"zstd\");\n\t\t\t}\n\t\t\tconst sseBody: Uint8Array | string = compressedBody ?? bodyJson;\n\n\t\t\t// Fetch with retry logic for rate limits and transient errors\n\t\t\tlet response: Response | undefined;\n\t\t\tlet lastError: Error | undefined;\n\t\t\tconst maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES;\n\n\t\t\tfor (let attempt = 0; attempt <= maxRetries; attempt++) {\n\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tconst headerTimeoutSignal =\n\t\t\t\t\t\thttpTimeoutMs !== undefined && httpTimeoutMs > 0 ? AbortSignal.timeout(httpTimeoutMs) : undefined;\n\t\t\t\t\tconst combinedSignal = combineAbortSignals([options?.signal, headerTimeoutSignal]);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresponse = await fetch(resolveCodexUrl(model.baseUrl), {\n\t\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\t\theaders: sseHeaders,\n\t\t\t\t\t\t\tbody: sseBody,\n\t\t\t\t\t\t\tsignal: combinedSignal.signal,\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (headerTimeoutSignal?.aborted && !options?.signal?.aborted) {\n\t\t\t\t\t\t\tthrow new Error(`Codex SSE response headers timed out after ${httpTimeoutMs}ms`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tcombinedSignal.cleanup();\n\t\t\t\t\t}\n\t\t\t\t\tawait options?.onResponse?.(\n\t\t\t\t\t\t{ status: response.status, headers: headersToRecord(response.headers) },\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t);\n\n\t\t\t\t\tif (response.ok) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst errorText = await response.text();\n\t\t\t\t\tif (attempt < maxRetries && isRetryableError(response.status, errorText)) {\n\t\t\t\t\t\tconst retryAfterDelayMs = getRetryAfterDelayMs(response.headers);\n\t\t\t\t\t\tconst delayMs =\n\t\t\t\t\t\t\tretryAfterDelayMs === undefined\n\t\t\t\t\t\t\t\t? BASE_DELAY_MS * 2 ** attempt\n\t\t\t\t\t\t\t\t: response.status === 429\n\t\t\t\t\t\t\t\t\t? capRetryDelayMs(retryAfterDelayMs, options)\n\t\t\t\t\t\t\t\t\t: retryAfterDelayMs;\n\n\t\t\t\t\t\tawait sleep(delayMs, options?.signal);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Parse error for friendly message on final attempt or non-retryable error\n\t\t\t\t\tconst fakeResponse = new Response(errorText, {\n\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\tstatusText: response.statusText,\n\t\t\t\t\t});\n\t\t\t\t\tconst info = await parseErrorResponse(fakeResponse);\n\t\t\t\t\tthrow new Error(info.friendlyMessage || info.message);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\t\tif (error.name === \"AbortError\" || error.message === \"Request was aborted\") {\n\t\t\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlastError = error instanceof Error ? error : new Error(String(error));\n\t\t\t\t\t// Network errors are retryable\n\t\t\t\t\tif (attempt < maxRetries && !lastError.message.includes(\"usage limit\")) {\n\t\t\t\t\t\tconst delayMs = BASE_DELAY_MS * 2 ** attempt;\n\t\t\t\t\t\tawait sleep(delayMs, options?.signal);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthrow lastError;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!response?.ok) {\n\t\t\t\tthrow lastError ?? new Error(\"Failed after retries\");\n\t\t\t}\n\n\t\t\tif (!response.body) {\n\t\t\t\tthrow new Error(\"No response body\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\tawait processStream(response, output, stream, model, options);\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason as \"stop\" | \"length\" | \"toolUse\", message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.content) {\n\t\t\t\t// partialJson is only a streaming scratch buffer; never persist it.\n\t\t\t\tdelete (block as { partialJson?: string }).partialJson;\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = formatProviderError(normalizeProviderError(error));\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\nexport const streamSimple: StreamFunction<\"openai-codex-responses\", SimpleStreamOptions> = (\n\tmodel: Model<\"openai-codex-responses\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey;\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\n\tconst base = buildBaseOptions(model, context, options, apiKey);\n\tconst clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n\tconst reasoningEffort = clampedReasoning === \"off\" ? undefined : clampedReasoning;\n\n\treturn stream(model, context, {\n\t\t...base,\n\t\treasoningEffort,\n\t} satisfies OpenAICodexResponsesOptions);\n};\n\n// ============================================================================\n// Request Building\n// ============================================================================\n\nfunction buildRequestBody(\n\tmodel: Model<\"openai-codex-responses\">,\n\tcontext: Context,\n\toptions?: OpenAICodexResponsesOptions,\n): RequestBody {\n\tconst toolPlacement = splitDeferredTools(context, model.compat?.supportsToolSearch ?? false);\n\tconst messages = convertResponsesMessages(model, context, CODEX_TOOL_CALL_PROVIDERS, {\n\t\tincludeSystemPrompt: false,\n\t\tdeferredTools: toolPlacement.deferred,\n\t});\n\n\tconst body: RequestBody = {\n\t\tmodel: model.id,\n\t\tstore: false,\n\t\tstream: true,\n\t\tinstructions: context.systemPrompt || \"You are a helpful assistant.\",\n\t\tinput: messages,\n\t\ttext: { verbosity: options?.textVerbosity || \"low\" },\n\t\tinclude: [\"reasoning.encrypted_content\"],\n\t\tprompt_cache_key: clampOpenAIPromptCacheKey(options?.sessionId),\n\t\ttool_choice: options?.toolChoice ?? \"auto\",\n\t\tparallel_tool_calls: true,\n\t};\n\n\tif (options?.temperature !== undefined) {\n\t\tbody.temperature = options.temperature;\n\t}\n\n\tif (options?.serviceTier !== undefined) {\n\t\tbody.service_tier = options.serviceTier;\n\t}\n\n\tif (toolPlacement.immediate.length > 0) {\n\t\tbody.tools = convertResponsesTools(toolPlacement.immediate, { strict: null });\n\t}\n\n\tif (options?.reasoningEffort !== undefined) {\n\t\tconst effort =\n\t\t\toptions.reasoningEffort === \"none\"\n\t\t\t\t? (model.thinkingLevelMap?.off ?? \"none\")\n\t\t\t\t: (model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort);\n\t\tif (effort !== null) {\n\t\t\tbody.reasoning = {\n\t\t\t\teffort,\n\t\t\t\tsummary: options.reasoningSummary ?? \"auto\",\n\t\t\t};\n\t\t}\n\t}\n\n\treturn body;\n}\n\nfunction getServiceTierCostMultiplier(\n\tmodel: Pick<Model<\"openai-codex-responses\">, \"id\">,\n\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n): number {\n\tswitch (serviceTier) {\n\t\tcase \"flex\":\n\t\t\treturn 0.5;\n\t\tcase \"priority\":\n\t\t\treturn model.id === \"gpt-5.5\" ? 2.5 : 2;\n\t\tdefault:\n\t\t\treturn 1;\n\t}\n}\n\nfunction applyServiceTierPricing(\n\tusage: Usage,\n\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\tmodel: Pick<Model<\"openai-codex-responses\">, \"id\">,\n) {\n\tconst multiplier = getServiceTierCostMultiplier(model, serviceTier);\n\tif (multiplier === 1) return;\n\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\nfunction resolveCodexServiceTier(\n\tresponseServiceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\trequestServiceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n): ResponseCreateParamsStreaming[\"service_tier\"] | undefined {\n\tif (responseServiceTier === \"default\" && (requestServiceTier === \"flex\" || requestServiceTier === \"priority\")) {\n\t\treturn requestServiceTier;\n\t}\n\treturn responseServiceTier ?? requestServiceTier;\n}\n\nfunction resolveCodexUrl(baseUrl?: string): string {\n\tconst raw = baseUrl && baseUrl.trim().length > 0 ? baseUrl : DEFAULT_CODEX_BASE_URL;\n\tconst normalized = raw.replace(/\\/+$/, \"\");\n\tif (normalized.endsWith(\"/codex/responses\")) return normalized;\n\tif (normalized.endsWith(\"/codex\")) return `${normalized}/responses`;\n\treturn `${normalized}/codex/responses`;\n}\n\nfunction resolveCodexWebSocketUrl(baseUrl?: string): string {\n\tconst url = new URL(resolveCodexUrl(baseUrl));\n\tif (url.protocol === \"https:\") url.protocol = \"wss:\";\n\tif (url.protocol === \"http:\") url.protocol = \"ws:\";\n\treturn url.toString();\n}\n\n// ============================================================================\n// Response Processing\n// ============================================================================\n\nasync function processStream(\n\tresponse: Response,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tmodel: Model<\"openai-codex-responses\">,\n\toptions?: OpenAICodexResponsesOptions,\n): Promise<void> {\n\tawait processResponsesStream(mapCodexEvents(parseSSE(response, options?.signal)), output, stream, model, {\n\t\tserviceTier: options?.serviceTier,\n\t\tresolveServiceTier: resolveCodexServiceTier,\n\t\tapplyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),\n\t});\n}\n\nclass CodexApiError extends Error {\n\treadonly code?: string;\n\treadonly payload?: Record<string, unknown>;\n\n\tconstructor(message: string, options?: { code?: string; payload?: Record<string, unknown>; cause?: unknown }) {\n\t\tsuper(message);\n\t\tthis.name = \"CodexApiError\";\n\t\tthis.code = options?.code;\n\t\tthis.payload = options?.payload;\n\t\tthis.cause = options?.cause;\n\t}\n}\n\nclass CodexProtocolError extends Error {\n\treadonly payload?: unknown;\n\n\tconstructor(message: string, options?: { payload?: unknown; cause?: unknown }) {\n\t\tsuper(message);\n\t\tthis.name = \"CodexProtocolError\";\n\t\tthis.payload = options?.payload;\n\t\tthis.cause = options?.cause;\n\t}\n}\n\nfunction isCodexNonTransportError(error: unknown): boolean {\n\treturn error instanceof CodexApiError || error instanceof CodexProtocolError;\n}\n\nfunction isWebSocketConnectionLimitReachedError(error: unknown): boolean {\n\treturn error instanceof CodexApiError && error.code === WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE;\n}\n\nfunction extractCodexEventError(event: Record<string, unknown>): { code?: string; message?: string } {\n\tconst nested = event.error && typeof event.error === \"object\" ? (event.error as Record<string, unknown>) : undefined;\n\treturn {\n\t\tcode: typeof event.code === \"string\" ? event.code : typeof nested?.code === \"string\" ? nested.code : undefined,\n\t\tmessage:\n\t\t\ttypeof event.message === \"string\"\n\t\t\t\t? event.message\n\t\t\t\t: typeof nested?.message === \"string\"\n\t\t\t\t\t? nested.message\n\t\t\t\t\t: undefined,\n\t};\n}\n\nasync function* mapCodexEvents(events: AsyncIterable<Record<string, unknown>>): AsyncGenerator<ResponseStreamEvent> {\n\tfor await (const event of events) {\n\t\tconst type = typeof event.type === \"string\" ? event.type : undefined;\n\t\tif (!type) continue;\n\n\t\tif (type === \"error\") {\n\t\t\tconst { code, message } = extractCodexEventError(event);\n\t\t\tthrow new CodexApiError(`Codex error: ${message || code || JSON.stringify(event)}`, {\n\t\t\t\tcode,\n\t\t\t\tpayload: event,\n\t\t\t});\n\t\t}\n\n\t\tif (type === \"response.failed\") {\n\t\t\tconst response = (event as { response?: { error?: { code?: string; message?: string } } }).response;\n\t\t\tconst code = response?.error?.code;\n\t\t\tconst message = response?.error?.message;\n\t\t\tthrow new CodexApiError(message || \"Codex response failed\", { code, payload: event });\n\t\t}\n\n\t\tif (type === \"response.done\" || type === \"response.completed\" || type === \"response.incomplete\") {\n\t\t\tconst response = (event as { response?: { status?: unknown } }).response;\n\t\t\tconst normalizedResponse = response\n\t\t\t\t? { ...response, status: normalizeCodexStatus(response.status) }\n\t\t\t\t: response;\n\t\t\tyield { ...event, type: \"response.completed\", response: normalizedResponse } as ResponseStreamEvent;\n\t\t\treturn;\n\t\t}\n\n\t\tyield event as unknown as ResponseStreamEvent;\n\t}\n}\n\nfunction normalizeCodexStatus(status: unknown): CodexResponseStatus | undefined {\n\tif (typeof status !== \"string\") return undefined;\n\treturn CODEX_RESPONSE_STATUSES.has(status as CodexResponseStatus) ? (status as CodexResponseStatus) : undefined;\n}\n\n// ============================================================================\n// SSE Parsing\n// ============================================================================\n\nasync function* parseSSE(response: Response, signal?: AbortSignal): AsyncGenerator<Record<string, unknown>> {\n\tif (!response.body) return;\n\n\tconst reader = response.body.getReader();\n\tconst decoder = new TextDecoder();\n\tlet buffer = \"\";\n\tconst onAbort = () => {\n\t\tvoid reader.cancel().catch(() => {});\n\t};\n\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\ttry {\n\t\twhile (true) {\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\t\t\tif (done) break;\n\t\t\tbuffer += decoder.decode(value, { stream: true });\n\n\t\t\tlet idx = buffer.indexOf(\"\\n\\n\");\n\t\t\twhile (idx !== -1) {\n\t\t\t\tconst chunk = buffer.slice(0, idx);\n\t\t\t\tbuffer = buffer.slice(idx + 2);\n\n\t\t\t\tconst dataLines = chunk\n\t\t\t\t\t.split(\"\\n\")\n\t\t\t\t\t.filter((l) => l.startsWith(\"data:\"))\n\t\t\t\t\t.map((l) => l.slice(5).trim());\n\t\t\t\tif (dataLines.length > 0) {\n\t\t\t\t\tconst data = dataLines.join(\"\\n\").trim();\n\t\t\t\t\tif (data && data !== \"[DONE]\") {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tyield JSON.parse(data) as Record<string, unknown>;\n\t\t\t\t\t\t} catch (cause) {\n\t\t\t\t\t\t\tthrow new CodexProtocolError(`Invalid Codex SSE JSON: ${formatThrownValue(cause)}`, {\n\t\t\t\t\t\t\t\tcause,\n\t\t\t\t\t\t\t\tpayload: data,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tidx = buffer.indexOf(\"\\n\\n\");\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\ttry {\n\t\t\tawait reader.cancel();\n\t\t} catch {}\n\t\ttry {\n\t\t\treader.releaseLock();\n\t\t} catch {}\n\t}\n}\n\n// ============================================================================\n// WebSocket Parsing\n// ============================================================================\n\nconst OPENAI_BETA_RESPONSES_WEBSOCKETS = \"responses_websockets=2026-02-06\";\nconst SESSION_WEBSOCKET_CACHE_TTL_MS = 5 * 60 * 1000;\nconst SESSION_WEBSOCKET_MAX_AGE_MS = 55 * 60 * 1000;\n\ntype WebSocketEventType = \"open\" | \"message\" | \"error\" | \"close\";\ntype WebSocketListener = (event: unknown) => void;\n\ninterface WebSocketLike {\n\tclose(code?: number, reason?: string): void;\n\tsend(data: string): void;\n\taddEventListener(type: WebSocketEventType, listener: WebSocketListener): void;\n\tremoveEventListener(type: WebSocketEventType, listener: WebSocketListener): void;\n}\n\ninterface CachedWebSocketContinuationState {\n\tlastRequestBody: RequestBody;\n\tlastResponseId: string;\n\tlastResponseItems: ResponseInput;\n}\n\ninterface CachedWebSocketConnection {\n\tsocket: WebSocketLike;\n\tbusy: boolean;\n\tcreatedAt: number;\n\tidleTimer?: ReturnType<typeof setTimeout>;\n\tcontinuation?: CachedWebSocketContinuationState;\n}\n\nexport interface OpenAICodexWebSocketDebugStats {\n\trequests: number;\n\tconnectionsCreated: number;\n\tconnectionsReused: number;\n\tcachedContextRequests: number;\n\tstoreTrueRequests: number;\n\tfullContextRequests: number;\n\tdeltaRequests: number;\n\tlastInputItems: number;\n\tlastDeltaInputItems?: number;\n\tlastPreviousResponseId?: string;\n\twebsocketFailures: number;\n\tsseFallbacks: number;\n\twebsocketFallbackActive?: boolean;\n\tlastWebSocketError?: string;\n}\n\nconst websocketSessionCache = new Map<string, CachedWebSocketConnection>();\nconst websocketDebugStats = new Map<string, OpenAICodexWebSocketDebugStats>();\nconst websocketSseFallbackSessions = new Set<string>();\n\nfunction getOrCreateWebSocketDebugStats(sessionId: string): OpenAICodexWebSocketDebugStats {\n\tlet stats = websocketDebugStats.get(sessionId);\n\tif (!stats) {\n\t\tstats = {\n\t\t\trequests: 0,\n\t\t\tconnectionsCreated: 0,\n\t\t\tconnectionsReused: 0,\n\t\t\tcachedContextRequests: 0,\n\t\t\tstoreTrueRequests: 0,\n\t\t\tfullContextRequests: 0,\n\t\t\tdeltaRequests: 0,\n\t\t\tlastInputItems: 0,\n\t\t\twebsocketFailures: 0,\n\t\t\tsseFallbacks: 0,\n\t\t};\n\t\twebsocketDebugStats.set(sessionId, stats);\n\t}\n\treturn stats;\n}\n\nexport function getOpenAICodexWebSocketDebugStats(sessionId: string): OpenAICodexWebSocketDebugStats | undefined {\n\tconst stats = websocketDebugStats.get(sessionId);\n\treturn stats ? { ...stats } : undefined;\n}\n\nexport function resetOpenAICodexWebSocketDebugStats(sessionId?: string): void {\n\tif (sessionId) {\n\t\twebsocketDebugStats.delete(sessionId);\n\t\twebsocketSseFallbackSessions.delete(sessionId);\n\t\treturn;\n\t}\n\twebsocketDebugStats.clear();\n\twebsocketSseFallbackSessions.clear();\n}\n\nexport function closeOpenAICodexWebSocketSessions(sessionId?: string): void {\n\tconst closeEntry = (entry: CachedWebSocketConnection) => {\n\t\tif (entry.idleTimer) clearTimeout(entry.idleTimer);\n\t\tcloseWebSocketSilently(entry.socket, 1000, \"debug_close\");\n\t};\n\tif (sessionId) {\n\t\tconst entry = websocketSessionCache.get(sessionId);\n\t\tif (entry) closeEntry(entry);\n\t\twebsocketSessionCache.delete(sessionId);\n\t\treturn;\n\t}\n\tfor (const entry of websocketSessionCache.values()) {\n\t\tcloseEntry(entry);\n\t}\n\twebsocketSessionCache.clear();\n}\n\nregisterSessionResourceCleanup(closeOpenAICodexWebSocketSessions);\n\nfunction isWebSocketSseFallbackActive(sessionId: string | undefined): boolean {\n\treturn sessionId ? websocketSseFallbackSessions.has(sessionId) : false;\n}\n\nfunction recordWebSocketSseFallback(sessionId: string | undefined): void {\n\tif (!sessionId) return;\n\tconst stats = getOrCreateWebSocketDebugStats(sessionId);\n\tstats.sseFallbacks++;\n\tstats.websocketFallbackActive = isWebSocketSseFallbackActive(sessionId);\n}\n\nfunction recordWebSocketFailure(sessionId: string | undefined, error: unknown): void {\n\tif (!sessionId) return;\n\twebsocketSseFallbackSessions.add(sessionId);\n\n\tconst stats = getOrCreateWebSocketDebugStats(sessionId);\n\tstats.websocketFailures++;\n\tstats.lastWebSocketError = formatThrownValue(error);\n\tstats.websocketFallbackActive = true;\n}\n\ntype WebSocketConstructor = new (\n\turl: string,\n\tprotocols?: string | string[] | { headers?: Record<string, string> },\n) => WebSocketLike;\n\nlet _cachedWebsocket: WebSocketConstructor | null = null;\nasync function getWebSocketConstructor(env?: ProviderEnv): Promise<WebSocketConstructor | null> {\n\tif (!env && _cachedWebsocket) return _cachedWebsocket;\n\n\t// bun doesn't respect http proxy envs, ref: https://github.com/oven-sh/bun/issues/15489\n\t// TODO: remove this when bun supports proxy envs in websocket.\n\tif (typeof process !== \"undefined\" && process.versions?.bun) {\n\t\tconst WebSocketWithProxy = class extends WebSocket {\n\t\t\tconstructor(url: string | URL, options?: string | string[] | Record<string, unknown>) {\n\t\t\t\tlet _opts: Record<string, unknown> = {};\n\t\t\t\tif (Array.isArray(options) || typeof options === \"string\") {\n\t\t\t\t\t_opts = { protocols: options };\n\t\t\t\t} else {\n\t\t\t\t\t_opts = { ...options };\n\t\t\t\t}\n\n\t\t\t\tconst proxyUrl = resolveHttpProxyUrlForTarget(\n\t\t\t\t\turl.toString().replace(/^wss:/, \"https:\").replace(/^ws:/, \"http:\"),\n\t\t\t\t\tenv,\n\t\t\t\t);\n\t\t\t\tsuper(url, { ..._opts, ...(proxyUrl ? { proxy: proxyUrl.toString() } : {}) } as any);\n\t\t\t}\n\t\t};\n\t\tif (!env) {\n\t\t\t_cachedWebsocket = WebSocketWithProxy;\n\t\t}\n\t\treturn WebSocketWithProxy;\n\t}\n\n\tconst ctor = (globalThis as { WebSocket?: unknown }).WebSocket;\n\tif (typeof ctor !== \"function\") return null;\n\treturn ctor as unknown as WebSocketConstructor;\n}\n\nclass WebSocketCloseError extends Error {\n\treadonly code?: number;\n\treadonly reason?: string;\n\treadonly wasClean?: boolean;\n\n\tconstructor(message: string, options?: { code?: number; reason?: string; wasClean?: boolean }) {\n\t\tsuper(message);\n\t\tthis.name = \"WebSocketCloseError\";\n\t\tthis.code = options?.code;\n\t\tthis.reason = options?.reason;\n\t\tthis.wasClean = options?.wasClean;\n\t}\n}\n\nfunction getWebSocketReadyState(socket: WebSocketLike): number | undefined {\n\tconst readyState = (socket as { readyState?: unknown }).readyState;\n\treturn typeof readyState === \"number\" ? readyState : undefined;\n}\n\nfunction isWebSocketReusable(socket: WebSocketLike): boolean {\n\tconst readyState = getWebSocketReadyState(socket);\n\t// If readyState is unavailable, assume the runtime keeps it open/reusable.\n\treturn readyState === undefined || readyState === 1;\n}\n\nfunction isWebSocketSessionExpired(entry: CachedWebSocketConnection): boolean {\n\treturn Date.now() - entry.createdAt >= SESSION_WEBSOCKET_MAX_AGE_MS;\n}\n\nfunction closeWebSocketSilently(socket: WebSocketLike, code = 1000, reason = \"done\"): void {\n\ttry {\n\t\tsocket.close(code, reason);\n\t} catch {}\n}\n\nfunction scheduleSessionWebSocketExpiry(sessionId: string, entry: CachedWebSocketConnection): void {\n\tif (entry.idleTimer) {\n\t\tclearTimeout(entry.idleTimer);\n\t}\n\tentry.idleTimer = setTimeout(() => {\n\t\tif (entry.busy) return;\n\t\tcloseWebSocketSilently(entry.socket, 1000, \"idle_timeout\");\n\t\twebsocketSessionCache.delete(sessionId);\n\t}, SESSION_WEBSOCKET_CACHE_TTL_MS);\n}\n\nasync function connectWebSocket(\n\turl: string,\n\theaders: Headers,\n\tsignal?: AbortSignal,\n\tconnectTimeoutMs = DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS,\n\tenv?: ProviderEnv,\n): Promise<WebSocketLike> {\n\tconst WebSocketCtor = await getWebSocketConstructor(env);\n\tif (!WebSocketCtor) {\n\t\tthrow new Error(\"WebSocket transport is not available in this runtime\");\n\t}\n\n\tconst wsHeaders = headersToRecord(headers);\n\tdelete wsHeaders[\"OpenAI-Beta\"];\n\n\treturn new Promise<WebSocketLike>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\t\tlet socket: WebSocketLike;\n\n\t\ttry {\n\t\t\tsocket = new WebSocketCtor(url, { headers: wsHeaders });\n\t\t} catch (error) {\n\t\t\treject(error instanceof Error ? error : new Error(String(error)));\n\t\t\treturn;\n\t\t}\n\n\t\tconst cleanup = () => {\n\t\t\tif (timeout) {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\ttimeout = undefined;\n\t\t\t}\n\t\t\tsocket.removeEventListener(\"open\", onOpen);\n\t\t\tsocket.removeEventListener(\"error\", onError);\n\t\t\tsocket.removeEventListener(\"close\", onClose);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst fail = (error: Error, closeReason?: string) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tif (closeReason) {\n\t\t\t\tcloseWebSocketSilently(socket, 1000, closeReason);\n\t\t\t}\n\t\t\treject(error);\n\t\t};\n\t\tconst onOpen: WebSocketListener = () => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tresolve(socket);\n\t\t};\n\t\tconst onError: WebSocketListener = (event) => {\n\t\t\tfail(extractWebSocketError(event));\n\t\t};\n\t\tconst onClose: WebSocketListener = (event) => {\n\t\t\tfail(extractWebSocketCloseError(event));\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tfail(new Error(\"Request was aborted\"), \"aborted\");\n\t\t};\n\n\t\tsocket.addEventListener(\"open\", onOpen);\n\t\tsocket.addEventListener(\"error\", onError);\n\t\tsocket.addEventListener(\"close\", onClose);\n\t\tsignal?.addEventListener(\"abort\", onAbort);\n\n\t\tif (connectTimeoutMs > 0) {\n\t\t\ttimeout = setTimeout(() => {\n\t\t\t\tfail(new Error(`WebSocket connect timeout after ${connectTimeoutMs}ms`), \"connect_timeout\");\n\t\t\t}, connectTimeoutMs);\n\t\t}\n\t\tif (signal?.aborted) {\n\t\t\tonAbort();\n\t\t}\n\t});\n}\n\nasync function acquireWebSocket(\n\turl: string,\n\theaders: Headers,\n\tsessionId: string | undefined,\n\tsignal?: AbortSignal,\n\tconnectTimeoutMs?: number,\n\tenv?: ProviderEnv,\n): Promise<{\n\tsocket: WebSocketLike;\n\tentry?: CachedWebSocketConnection;\n\treused: boolean;\n\trelease: (options?: { keep?: boolean }) => void;\n}> {\n\tif (!sessionId) {\n\t\tconst socket = await connectWebSocket(url, headers, signal, connectTimeoutMs, env);\n\t\treturn {\n\t\t\tsocket,\n\t\t\treused: false,\n\t\t\trelease: () => closeWebSocketSilently(socket),\n\t\t};\n\t}\n\n\tconst cached = websocketSessionCache.get(sessionId);\n\tif (cached) {\n\t\tif (cached.idleTimer) {\n\t\t\tclearTimeout(cached.idleTimer);\n\t\t\tcached.idleTimer = undefined;\n\t\t}\n\t\tif (!cached.busy && isWebSocketSessionExpired(cached)) {\n\t\t\tcloseWebSocketSilently(cached.socket, 1000, \"connection_age_limit\");\n\t\t\twebsocketSessionCache.delete(sessionId);\n\t\t} else if (!cached.busy && isWebSocketReusable(cached.socket)) {\n\t\t\tcached.busy = true;\n\t\t\treturn {\n\t\t\t\tsocket: cached.socket,\n\t\t\t\tentry: cached,\n\t\t\t\treused: true,\n\t\t\t\trelease: ({ keep } = {}) => {\n\t\t\t\t\tif (!keep || !isWebSocketReusable(cached.socket)) {\n\t\t\t\t\t\tcloseWebSocketSilently(cached.socket);\n\t\t\t\t\t\twebsocketSessionCache.delete(sessionId);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcached.busy = false;\n\t\t\t\t\tscheduleSessionWebSocketExpiry(sessionId, cached);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (cached.busy) {\n\t\t\tconst socket = await connectWebSocket(url, headers, signal, connectTimeoutMs, env);\n\t\t\treturn {\n\t\t\t\tsocket,\n\t\t\t\treused: false,\n\t\t\t\trelease: () => {\n\t\t\t\t\tcloseWebSocketSilently(socket);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (!isWebSocketReusable(cached.socket)) {\n\t\t\tcloseWebSocketSilently(cached.socket);\n\t\t\twebsocketSessionCache.delete(sessionId);\n\t\t}\n\t}\n\n\tconst socket = await connectWebSocket(url, headers, signal, connectTimeoutMs, env);\n\tconst entry: CachedWebSocketConnection = { socket, busy: true, createdAt: Date.now() };\n\twebsocketSessionCache.set(sessionId, entry);\n\treturn {\n\t\tsocket,\n\t\tentry,\n\t\treused: false,\n\t\trelease: ({ keep } = {}) => {\n\t\t\tif (!keep || !isWebSocketReusable(entry.socket)) {\n\t\t\t\tcloseWebSocketSilently(entry.socket);\n\t\t\t\tif (entry.idleTimer) clearTimeout(entry.idleTimer);\n\t\t\t\tif (websocketSessionCache.get(sessionId) === entry) {\n\t\t\t\t\twebsocketSessionCache.delete(sessionId);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tentry.busy = false;\n\t\t\tscheduleSessionWebSocketExpiry(sessionId, entry);\n\t\t},\n\t};\n}\n\nfunction extractWebSocketError(event: unknown): Error {\n\tif (event && typeof event === \"object\") {\n\t\tconst message = \"message\" in event ? (event as { message?: unknown }).message : undefined;\n\t\tif (typeof message === \"string\" && message.length > 0) {\n\t\t\treturn new Error(message);\n\t\t}\n\n\t\tconst nestedError = \"error\" in event ? (event as { error?: unknown }).error : undefined;\n\t\tif (nestedError instanceof Error && nestedError.message.length > 0) {\n\t\t\treturn nestedError;\n\t\t}\n\t\tif (nestedError && typeof nestedError === \"object\" && \"message\" in nestedError) {\n\t\t\tconst nestedMessage = (nestedError as { message?: unknown }).message;\n\t\t\tif (typeof nestedMessage === \"string\" && nestedMessage.length > 0) {\n\t\t\t\treturn new Error(nestedMessage);\n\t\t\t}\n\t\t}\n\t}\n\treturn new Error(\"WebSocket error\");\n}\n\nfunction extractWebSocketCloseError(event: unknown): Error {\n\tif (event && typeof event === \"object\") {\n\t\tconst code = \"code\" in event ? (event as { code?: unknown }).code : undefined;\n\t\tconst reason = \"reason\" in event ? (event as { reason?: unknown }).reason : undefined;\n\t\tconst wasClean = \"wasClean\" in event ? (event as { wasClean?: unknown }).wasClean : undefined;\n\t\tconst codeText = typeof code === \"number\" ? ` ${code}` : \"\";\n\t\tlet reasonText = typeof reason === \"string\" && reason.length > 0 ? ` ${reason}` : \"\";\n\t\tif (!reasonText && code === WEBSOCKET_MESSAGE_TOO_BIG_CLOSE_CODE) {\n\t\t\treasonText = \" message too big\";\n\t\t}\n\t\treturn new WebSocketCloseError(`WebSocket closed${codeText}${reasonText}`.trim(), {\n\t\t\tcode: typeof code === \"number\" ? code : undefined,\n\t\t\treason: typeof reason === \"string\" && reason.length > 0 ? reason : undefined,\n\t\t\twasClean: typeof wasClean === \"boolean\" ? wasClean : undefined,\n\t\t});\n\t}\n\treturn new Error(\"WebSocket closed\");\n}\n\nasync function decodeWebSocketData(data: unknown): Promise<string | null> {\n\tif (typeof data === \"string\") return data;\n\tif (data instanceof ArrayBuffer) {\n\t\treturn new TextDecoder().decode(new Uint8Array(data));\n\t}\n\tif (ArrayBuffer.isView(data)) {\n\t\tconst view = data as ArrayBufferView;\n\t\treturn new TextDecoder().decode(new Uint8Array(view.buffer, view.byteOffset, view.byteLength));\n\t}\n\tif (data && typeof data === \"object\" && \"arrayBuffer\" in data) {\n\t\tconst blobLike = data as { arrayBuffer: () => Promise<ArrayBuffer> };\n\t\tconst arrayBuffer = await blobLike.arrayBuffer();\n\t\treturn new TextDecoder().decode(new Uint8Array(arrayBuffer));\n\t}\n\treturn null;\n}\n\nasync function* parseWebSocket(\n\tsocket: WebSocketLike,\n\tsignal?: AbortSignal,\n\tidleTimeoutMs?: number,\n): AsyncGenerator<Record<string, unknown>> {\n\tconst queue: Record<string, unknown>[] = [];\n\tlet pending: (() => void) | null = null;\n\tlet done = false;\n\tlet failed: Error | null = null;\n\tlet sawCompletion = false;\n\n\tconst wake = () => {\n\t\tif (!pending) return;\n\t\tconst resolve = pending;\n\t\tpending = null;\n\t\tresolve();\n\t};\n\n\tconst onMessage: WebSocketListener = (event) => {\n\t\tvoid (async () => {\n\t\t\tlet text: string | null = null;\n\t\t\ttry {\n\t\t\t\tif (!event || typeof event !== \"object\" || !(\"data\" in event)) return;\n\t\t\t\ttext = await decodeWebSocketData((event as { data?: unknown }).data);\n\t\t\t\tif (!text) return;\n\t\t\t\tconst parsed = JSON.parse(text) as Record<string, unknown>;\n\t\t\t\tconst type = typeof parsed.type === \"string\" ? parsed.type : \"\";\n\t\t\t\tif (type === \"response.completed\" || type === \"response.done\" || type === \"response.incomplete\") {\n\t\t\t\t\tsawCompletion = true;\n\t\t\t\t\tdone = true;\n\t\t\t\t}\n\t\t\t\tqueue.push(parsed);\n\t\t\t\twake();\n\t\t\t} catch (cause) {\n\t\t\t\tfailed = new CodexProtocolError(`Invalid Codex WebSocket JSON: ${formatThrownValue(cause)}`, {\n\t\t\t\t\tcause,\n\t\t\t\t\tpayload: text,\n\t\t\t\t});\n\t\t\t\tdone = true;\n\t\t\t\twake();\n\t\t\t}\n\t\t})();\n\t};\n\n\tconst onError: WebSocketListener = (event) => {\n\t\tfailed = extractWebSocketError(event);\n\t\tdone = true;\n\t\twake();\n\t};\n\n\tconst onClose: WebSocketListener = (event) => {\n\t\tif (sawCompletion) {\n\t\t\tdone = true;\n\t\t\twake();\n\t\t\treturn;\n\t\t}\n\t\tif (!failed) {\n\t\t\tfailed = extractWebSocketCloseError(event);\n\t\t}\n\t\tdone = true;\n\t\twake();\n\t};\n\n\tconst onAbort = () => {\n\t\tfailed = new Error(\"Request was aborted\");\n\t\tdone = true;\n\t\twake();\n\t};\n\n\tsocket.addEventListener(\"message\", onMessage);\n\tsocket.addEventListener(\"error\", onError);\n\tsocket.addEventListener(\"close\", onClose);\n\tsignal?.addEventListener(\"abort\", onAbort);\n\n\ttry {\n\t\twhile (true) {\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\t\t\tif (queue.length > 0) {\n\t\t\t\tyield queue.shift()!;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (done) break;\n\t\t\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\tpending = resolve;\n\t\t\t\tif (idleTimeoutMs !== undefined && idleTimeoutMs > 0) {\n\t\t\t\t\ttimeout = setTimeout(() => {\n\t\t\t\t\t\tconst error = new Error(`WebSocket idle timeout after ${idleTimeoutMs}ms`);\n\t\t\t\t\t\tfailed = error;\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t\tpending = null;\n\t\t\t\t\t\tcloseWebSocketSilently(socket, 1000, \"idle_timeout\");\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}, idleTimeoutMs);\n\t\t\t\t}\n\t\t\t}).finally(() => {\n\t\t\t\tif (timeout) {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tif (failed) {\n\t\t\tthrow failed;\n\t\t}\n\t\tif (!sawCompletion) {\n\t\t\tthrow new Error(\"WebSocket stream closed before response.completed\");\n\t\t}\n\t} finally {\n\t\tsocket.removeEventListener(\"message\", onMessage);\n\t\tsocket.removeEventListener(\"error\", onError);\n\t\tsocket.removeEventListener(\"close\", onClose);\n\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t}\n}\n\nfunction requestBodyWithoutInput(body: RequestBody): RequestBody {\n\tconst { input: _input, previous_response_id: _previousResponseId, ...rest } = body;\n\treturn rest;\n}\n\nfunction responseInputsEqual(a: ResponseInput | undefined, b: ResponseInput | undefined): boolean {\n\treturn JSON.stringify(a ?? []) === JSON.stringify(b ?? []);\n}\n\nfunction requestBodiesMatchExceptInput(a: RequestBody, b: RequestBody): boolean {\n\treturn JSON.stringify(requestBodyWithoutInput(a)) === JSON.stringify(requestBodyWithoutInput(b));\n}\n\nfunction getCachedWebSocketInputDelta(\n\tbody: RequestBody,\n\tcontinuation: CachedWebSocketContinuationState,\n): ResponseInput | undefined {\n\tif (!requestBodiesMatchExceptInput(body, continuation.lastRequestBody)) {\n\t\treturn undefined;\n\t}\n\n\tconst currentInput = body.input ?? [];\n\tconst baseline = [...(continuation.lastRequestBody.input ?? []), ...continuation.lastResponseItems];\n\tif (currentInput.length < baseline.length) {\n\t\treturn undefined;\n\t}\n\n\tconst prefix = currentInput.slice(0, baseline.length);\n\tif (!responseInputsEqual(prefix, baseline)) {\n\t\treturn undefined;\n\t}\n\n\treturn currentInput.slice(baseline.length);\n}\n\nfunction buildCachedWebSocketRequestBody(entry: CachedWebSocketConnection, body: RequestBody): RequestBody {\n\tconst continuation = entry.continuation;\n\tif (!continuation) {\n\t\treturn body;\n\t}\n\n\tconst delta = getCachedWebSocketInputDelta(body, continuation);\n\tif (!delta || !continuation.lastResponseId) {\n\t\tentry.continuation = undefined;\n\t\treturn body;\n\t}\n\n\treturn {\n\t\t...body,\n\t\tprevious_response_id: continuation.lastResponseId,\n\t\tinput: delta,\n\t};\n}\n\nasync function* startWebSocketOutputOnFirstEvent(\n\tevents: AsyncIterable<ResponseStreamEvent>,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tonStart: () => void,\n): AsyncGenerator<ResponseStreamEvent> {\n\tlet started = false;\n\tfor await (const event of events) {\n\t\tif (!started) {\n\t\t\tstarted = true;\n\t\t\tonStart();\n\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t}\n\t\tyield event;\n\t}\n}\n\nasync function processWebSocketStream(\n\turl: string,\n\tbody: RequestBody,\n\theaders: Headers,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tmodel: Model<\"openai-codex-responses\">,\n\tonStart: () => void,\n\tidleTimeoutMs: number | undefined,\n\twebsocketConnectTimeoutMs: number | undefined,\n\toptions?: OpenAICodexResponsesOptions,\n): Promise<void> {\n\tconst { socket, entry, reused, release } = await acquireWebSocket(\n\t\turl,\n\t\theaders,\n\t\toptions?.sessionId,\n\t\toptions?.signal,\n\t\twebsocketConnectTimeoutMs,\n\t\toptions?.env,\n\t);\n\tlet keepConnection = true;\n\tconst useCachedContext = options?.transport === \"websocket-cached\" || options?.transport === \"auto\";\n\t// ChatGPT Codex Responses rejects `store: true` (\"Store must be set to false\").\n\t// WebSocket continuation still works via connection-scoped previous_response_id state.\n\tconst fullBody = body;\n\tconst requestBody = useCachedContext && entry ? buildCachedWebSocketRequestBody(entry, fullBody) : fullBody;\n\tconst stats = options?.sessionId ? getOrCreateWebSocketDebugStats(options.sessionId) : undefined;\n\tif (stats) {\n\t\tstats.requests++;\n\t\tif (reused) stats.connectionsReused++;\n\t\telse stats.connectionsCreated++;\n\t\tif (useCachedContext) stats.cachedContextRequests++;\n\t\tif (requestBody.store === true) stats.storeTrueRequests++;\n\t\tstats.lastInputItems = requestBody.input?.length ?? 0;\n\t\tif (requestBody.previous_response_id) {\n\t\t\tstats.deltaRequests++;\n\t\t\tstats.lastDeltaInputItems = requestBody.input?.length ?? 0;\n\t\t\tstats.lastPreviousResponseId = requestBody.previous_response_id;\n\t\t} else {\n\t\t\tstats.fullContextRequests++;\n\t\t\tstats.lastDeltaInputItems = undefined;\n\t\t\tstats.lastPreviousResponseId = undefined;\n\t\t}\n\t}\n\ttry {\n\t\tsocket.send(JSON.stringify({ type: \"response.create\", ...requestBody }));\n\t\tawait processResponsesStream(\n\t\t\tstartWebSocketOutputOnFirstEvent(\n\t\t\t\tmapCodexEvents(parseWebSocket(socket, options?.signal, idleTimeoutMs)),\n\t\t\t\toutput,\n\t\t\t\tstream,\n\t\t\t\tonStart,\n\t\t\t),\n\t\t\toutput,\n\t\t\tstream,\n\t\t\tmodel,\n\t\t\t{\n\t\t\t\tserviceTier: options?.serviceTier,\n\t\t\t\tresolveServiceTier: resolveCodexServiceTier,\n\t\t\t\tapplyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),\n\t\t\t},\n\t\t);\n\t\tif (options?.signal?.aborted) {\n\t\t\tkeepConnection = false;\n\t\t} else if (useCachedContext && entry && output.responseId) {\n\t\t\tconst responseItems = convertResponsesMessages(model, { messages: [output] }, CODEX_TOOL_CALL_PROVIDERS, {\n\t\t\t\tincludeSystemPrompt: false,\n\t\t\t}).filter((item) => item.type !== \"function_call_output\");\n\t\t\tentry.continuation = {\n\t\t\t\tlastRequestBody: fullBody,\n\t\t\t\tlastResponseId: output.responseId,\n\t\t\t\tlastResponseItems: responseItems,\n\t\t\t};\n\t\t}\n\t} catch (error) {\n\t\tif (entry) {\n\t\t\tentry.continuation = undefined;\n\t\t}\n\t\tkeepConnection = false;\n\t\tthrow error;\n\t} finally {\n\t\trelease({ keep: keepConnection });\n\t}\n}\n\n// ============================================================================\n// Error Handling\n// ============================================================================\n\nasync function parseErrorResponse(response: Response): Promise<{ message: string; friendlyMessage?: string }> {\n\tconst raw = await response.text();\n\tlet message = raw || response.statusText || \"Request failed\";\n\tlet friendlyMessage: string | undefined;\n\n\ttry {\n\t\tconst parsed = JSON.parse(raw) as {\n\t\t\terror?: { code?: string; type?: string; message?: string; plan_type?: string; resets_at?: number };\n\t\t};\n\t\tconst err = parsed?.error;\n\t\tif (err) {\n\t\t\tconst code = err.code || err.type || \"\";\n\t\t\tif (/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(code) || response.status === 429) {\n\t\t\t\tconst plan = err.plan_type ? ` (${err.plan_type.toLowerCase()} plan)` : \"\";\n\t\t\t\tconst mins = err.resets_at\n\t\t\t\t\t? Math.max(0, Math.round((err.resets_at * 1000 - Date.now()) / 60000))\n\t\t\t\t\t: undefined;\n\t\t\t\tconst when = mins !== undefined ? ` Try again in ~${mins} min.` : \"\";\n\t\t\t\tfriendlyMessage = `You have hit your ChatGPT usage limit${plan}.${when}`.trim();\n\t\t\t}\n\t\t\tmessage = err.message || friendlyMessage || message;\n\t\t}\n\t} catch {}\n\n\treturn { message, friendlyMessage };\n}\n\n// ============================================================================\n// Auth & Headers\n// ============================================================================\n\nfunction extractAccountId(token: string): string {\n\ttry {\n\t\tconst parts = token.split(\".\");\n\t\tif (parts.length !== 3) throw new Error(\"Invalid token\");\n\t\tconst payload = JSON.parse(atob(parts[1]));\n\t\tconst accountId = payload?.[JWT_CLAIM_PATH]?.chatgpt_account_id;\n\t\tif (!accountId) throw new Error(\"No account ID in token\");\n\t\treturn accountId;\n\t} catch {\n\t\tthrow new Error(\"Failed to extract accountId from token\");\n\t}\n}\n\nfunction createCodexRequestId(): string {\n\tif (typeof globalThis.crypto?.randomUUID === \"function\") {\n\t\treturn globalThis.crypto.randomUUID();\n\t}\n\treturn `codex_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction buildBaseCodexHeaders(\n\tinitHeaders: Record<string, string> | undefined,\n\tadditionalHeaders: ProviderHeaders | undefined,\n\taccountId: string,\n\ttoken: string,\n): Headers {\n\tconst headers = new Headers(initHeaders);\n\tfor (const [key, value] of Object.entries(additionalHeaders || {})) {\n\t\tif (value === null) {\n\t\t\theaders.delete(key);\n\t\t} else {\n\t\t\theaders.set(key, value);\n\t\t}\n\t}\n\theaders.set(\"Authorization\", `Bearer ${token}`);\n\theaders.set(\"chatgpt-account-id\", accountId);\n\theaders.set(\"originator\", \"pi\");\n\tconst userAgent = _os ? `pi (${_os.platform()} ${_os.release()}; ${_os.arch()})` : \"pi (browser)\";\n\theaders.set(\"User-Agent\", userAgent);\n\treturn headers;\n}\n\nfunction buildSSEHeaders(\n\tinitHeaders: Record<string, string> | undefined,\n\tadditionalHeaders: ProviderHeaders | undefined,\n\taccountId: string,\n\ttoken: string,\n\tsessionId?: string,\n): Headers {\n\tconst headers = buildBaseCodexHeaders(initHeaders, additionalHeaders, accountId, token);\n\theaders.set(\"OpenAI-Beta\", \"responses=experimental\");\n\theaders.set(\"accept\", \"text/event-stream\");\n\theaders.set(\"content-type\", \"application/json\");\n\n\tif (sessionId) {\n\t\theaders.set(\"session-id\", sessionId);\n\t\theaders.set(\"x-client-request-id\", sessionId);\n\t}\n\n\treturn headers;\n}\n\nfunction buildWebSocketHeaders(\n\tinitHeaders: Record<string, string> | undefined,\n\tadditionalHeaders: ProviderHeaders | undefined,\n\taccountId: string,\n\ttoken: string,\n\trequestId: string,\n): Headers {\n\tconst headers = buildBaseCodexHeaders(initHeaders, additionalHeaders, accountId, token);\n\theaders.delete(\"accept\");\n\theaders.delete(\"content-type\");\n\theaders.delete(\"OpenAI-Beta\");\n\theaders.delete(\"openai-beta\");\n\theaders.set(\"OpenAI-Beta\", OPENAI_BETA_RESPONSES_WEBSOCKETS);\n\theaders.set(\"x-client-request-id\", requestId);\n\theaders.set(\"session-id\", requestId);\n\treturn headers;\n}\n"]}
1
+ {"version":3,"file":"openai-codex-responses.d.ts","sourceRoot":"","sources":["../../src/api/openai-codex-responses.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAEX,6BAA6B,EAG7B,MAAM,yCAAyC,CAAC;AAkBjD,OAAO,KAAK,EAOX,mBAAmB,EACnB,cAAc,EACd,aAAa,EAEb,MAAM,aAAa,CAAC;AA8CrB,MAAM,WAAW,2BAA4B,SAAQ,aAAa;IACjE,eAAe,CAAC,EAAE,MAAM,GAAG,SAAS,GAAG,KAAK,GAAG,QAAQ,GAAG,MAAM,GAAG,OAAO,GAAG,KAAK,CAAC;IACnF,gBAAgB,CAAC,EAAE,MAAM,GAAG,SAAS,GAAG,UAAU,GAAG,KAAK,GAAG,IAAI,GAAG,IAAI,CAAC;IACzE,WAAW,CAAC,EAAE,6BAA6B,CAAC,cAAc,CAAC,CAAC;IAC5D,aAAa,CAAC,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;IAC1C,UAAU,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,UAAU,CAAC;CAC1C;AAsID,eAAO,MAAM,MAAM,EAAE,cAAc,CAAC,wBAAwB,EAAE,2BAA2B,CAyOxF,CAAC;AAEF,eAAO,MAAM,YAAY,EAAE,cAAc,CAAC,wBAAwB,EAAE,mBAAmB,CAkBtF,CAAC;AAoTF,MAAM,WAAW,8BAA8B;IAC9C,QAAQ,EAAE,MAAM,CAAC;IACjB,kBAAkB,EAAE,MAAM,CAAC;IAC3B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,qBAAqB,EAAE,MAAM,CAAC;IAC9B,iBAAiB,EAAE,MAAM,CAAC;IAC1B,mBAAmB,EAAE,MAAM,CAAC;IAC5B,aAAa,EAAE,MAAM,CAAC;IACtB,cAAc,EAAE,MAAM,CAAC;IACvB,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,iBAAiB,EAAE,MAAM,CAAC;IAC1B,YAAY,EAAE,MAAM,CAAC;IACrB,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAClC,kBAAkB,CAAC,EAAE,MAAM,CAAC;CAC5B;AA0BD,wBAAgB,iCAAiC,CAAC,SAAS,EAAE,MAAM,GAAG,8BAA8B,GAAG,SAAS,CAG/G;AAED,wBAAgB,mCAAmC,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAQ5E;AAED,wBAAgB,iCAAiC,CAAC,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAe1E","sourcesContent":["import type * as NodeOs from \"node:os\";\nimport type * as NodeZlib from \"node:zlib\";\nimport type {\n\tTool as OpenAITool,\n\tResponseCreateParamsStreaming,\n\tResponseInput,\n\tResponseStreamEvent,\n} from \"openai/resources/responses/responses.js\";\n\ntype ProcessWithOsBuiltinModule = typeof process & {\n\tgetBuiltinModule?: (id: \"node:os\") => typeof NodeOs;\n};\n\nfunction loadNodeOs(): typeof NodeOs | null {\n\tif (typeof process === \"undefined\" || !(process.versions?.node || process.versions?.bun)) {\n\t\treturn null;\n\t}\n\treturn (process as ProcessWithOsBuiltinModule).getBuiltinModule?.(\"node:os\") ?? null;\n}\n\n// NEVER convert to top-level runtime imports - breaks browser/Vite builds\nconst _os: typeof NodeOs | null = loadNodeOs();\n\nimport { clampThinkingLevel } from \"../models.ts\";\nimport { registerSessionResourceCleanup } from \"../session-resources.ts\";\nimport type {\n\tApi,\n\tAssistantMessage,\n\tContext,\n\tModel,\n\tProviderEnv,\n\tProviderHeaders,\n\tSimpleStreamOptions,\n\tStreamFunction,\n\tStreamOptions,\n\tUsage,\n} from \"../types.ts\";\nimport { combineAbortSignals } from \"../utils/abort-signals.ts\";\nimport { splitDeferredTools } from \"../utils/deferred-tools.ts\";\nimport {\n\tappendAssistantMessageDiagnostic,\n\tcreateAssistantMessageDiagnostic,\n\tformatThrownValue,\n} from \"../utils/diagnostics.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { AssistantMessageEventStream } from \"../utils/event-stream.ts\";\nimport { headersToRecord } from \"../utils/headers.ts\";\nimport { resolveHttpProxyUrlForTarget } from \"../utils/node-http-proxy.ts\";\nimport { clampOpenAIPromptCacheKey } from \"./openai-prompt-cache.ts\";\nimport { convertResponsesMessages, convertResponsesTools, processResponsesStream } from \"./openai-responses-shared.ts\";\nimport { buildBaseOptions } from \"./simple-options.ts\";\n\n// ============================================================================\n// Configuration\n// ============================================================================\n\nconst DEFAULT_CODEX_BASE_URL = \"https://chatgpt.com/backend-api\";\nconst JWT_CLAIM_PATH = \"https://api.openai.com/auth\" as const;\nconst DEFAULT_MAX_RETRIES = 0;\nconst BASE_DELAY_MS = 1000;\nconst DEFAULT_MAX_RETRY_DELAY_MS = 60_000;\nconst DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS = 15_000;\n// The Codex backend accepts zstd-compressed request bodies on the SSE responses\n// endpoint (the same endpoint the official Codex client compresses against).\nconst REQUEST_COMPRESSION_ZSTD_LEVEL = 3;\nconst CODEX_TOOL_CALL_PROVIDERS = new Set([\"openai\", \"openai-codex\", \"opencode\"]);\nconst WEBSOCKET_MESSAGE_TOO_BIG_CLOSE_CODE = 1009;\nconst WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE = \"websocket_connection_limit_reached\";\n\nconst CODEX_RESPONSE_STATUSES = new Set<CodexResponseStatus>([\n\t\"completed\",\n\t\"incomplete\",\n\t\"failed\",\n\t\"cancelled\",\n\t\"queued\",\n\t\"in_progress\",\n]);\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface OpenAICodexResponsesOptions extends StreamOptions {\n\treasoningEffort?: \"none\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\treasoningSummary?: \"auto\" | \"concise\" | \"detailed\" | \"off\" | \"on\" | null;\n\tserviceTier?: ResponseCreateParamsStreaming[\"service_tier\"];\n\ttextVerbosity?: \"low\" | \"medium\" | \"high\";\n\ttoolChoice?: \"auto\" | \"none\" | \"required\";\n}\n\ntype CodexResponseStatus = \"completed\" | \"incomplete\" | \"failed\" | \"cancelled\" | \"queued\" | \"in_progress\";\n\ninterface RequestBody {\n\tmodel: string;\n\tstore?: boolean;\n\tstream?: boolean;\n\tinstructions?: string;\n\tprevious_response_id?: string;\n\tinput?: ResponseInput;\n\ttools?: OpenAITool[];\n\ttool_choice?: OpenAICodexResponsesOptions[\"toolChoice\"];\n\tparallel_tool_calls?: boolean;\n\ttemperature?: number;\n\treasoning?: { effort?: string; summary?: string };\n\tservice_tier?: ResponseCreateParamsStreaming[\"service_tier\"];\n\ttext?: { verbosity?: string };\n\tinclude?: string[];\n\tprompt_cache_key?: string;\n\t[key: string]: unknown;\n}\n\n// ============================================================================\n// Retry Helpers\n// ============================================================================\n\nfunction isTerminalRateLimitError(errorText: string): boolean {\n\treturn /GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(\n\t\terrorText,\n\t);\n}\n\nfunction isRetryableError(status: number, errorText: string): boolean {\n\tif (status === 429 && isTerminalRateLimitError(errorText)) {\n\t\treturn false;\n\t}\n\tif (status === 429 || status === 500 || status === 502 || status === 503 || status === 504) {\n\t\treturn true;\n\t}\n\treturn /rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(errorText);\n}\n\nfunction getRetryAfterDelayMs(headers: Headers): number | undefined {\n\tconst retryAfterMs = headers.get(\"retry-after-ms\");\n\tif (retryAfterMs !== null) {\n\t\tconst millis = Number(retryAfterMs);\n\t\tif (Number.isFinite(millis)) {\n\t\t\treturn Math.max(0, millis);\n\t\t}\n\t}\n\n\tconst retryAfter = headers.get(\"retry-after\");\n\tif (!retryAfter) {\n\t\treturn undefined;\n\t}\n\n\tconst seconds = Number(retryAfter);\n\tif (Number.isFinite(seconds)) {\n\t\treturn Math.max(0, seconds * 1000);\n\t}\n\n\tconst date = Date.parse(retryAfter);\n\tif (!Number.isNaN(date)) {\n\t\treturn Math.max(0, date - Date.now());\n\t}\n\n\treturn undefined;\n}\n\nfunction capRetryDelayMs(delayMs: number, options?: StreamOptions): number {\n\tconst maxRetryDelayMs = options?.maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;\n\treturn maxRetryDelayMs > 0 ? Math.min(delayMs, maxRetryDelayMs) : delayMs;\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new Error(\"Request was aborted\"));\n\t\t\treturn;\n\t\t}\n\t\tconst timeout = setTimeout(resolve, ms);\n\t\tsignal?.addEventListener(\"abort\", () => {\n\t\t\tclearTimeout(timeout);\n\t\t\treject(new Error(\"Request was aborted\"));\n\t\t});\n\t});\n}\n\nfunction normalizeTimeoutMs(value: number | undefined): number | undefined {\n\tif (value === undefined) return undefined;\n\tif (!Number.isFinite(value) || value < 0) {\n\t\tthrow new Error(`Invalid timeoutMs: ${String(value)}`);\n\t}\n\treturn Math.floor(value);\n}\n\n// ============================================================================\n// Request Compression\n// ============================================================================\n\ntype ProcessWithBuiltinModule = typeof process & {\n\tgetBuiltinModule?: (id: \"node:zlib\") => typeof NodeZlib;\n};\n\nfunction loadNodeZlib(): typeof NodeZlib | null {\n\tif (typeof process === \"undefined\" || !(process.versions?.node || process.versions?.bun)) {\n\t\treturn null;\n\t}\n\treturn (process as ProcessWithBuiltinModule).getBuiltinModule?.(\"node:zlib\") ?? null;\n}\n\n// Returns the zstd-compressed body bytes, or null when compression is\n// unavailable (browser/Vite builds). Callers fall back to sending the\n// uncompressed JSON when this returns null.\nfunction compressRequestBodyZstd(bodyJson: string): Uint8Array | null {\n\tconst zlib = loadNodeZlib();\n\tif (!zlib || typeof zlib.zstdCompressSync !== \"function\") {\n\t\treturn null;\n\t}\n\ttry {\n\t\tconst compressed = zlib.zstdCompressSync(bodyJson, {\n\t\t\tparams: { [zlib.constants.ZSTD_c_compressionLevel]: REQUEST_COMPRESSION_ZSTD_LEVEL },\n\t\t});\n\t\treturn new Uint8Array(compressed.buffer, compressed.byteOffset, compressed.byteLength);\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n// ============================================================================\n// Main Stream Function\n// ============================================================================\n\nexport const stream: StreamFunction<\"openai-codex-responses\", OpenAICodexResponsesOptions> = (\n\tmodel: Model<\"openai-codex-responses\">,\n\tcontext: Context,\n\toptions?: OpenAICodexResponsesOptions,\n): AssistantMessageEventStream => {\n\tconst stream = new AssistantMessageEventStream();\n\n\t(async () => {\n\t\tconst output: AssistantMessage = {\n\t\t\trole: \"assistant\",\n\t\t\tcontent: [],\n\t\t\tapi: \"openai-codex-responses\" as Api,\n\t\t\tprovider: model.provider,\n\t\t\tmodel: model.id,\n\t\t\tusage: {\n\t\t\t\tinput: 0,\n\t\t\t\toutput: 0,\n\t\t\t\tcacheRead: 0,\n\t\t\t\tcacheWrite: 0,\n\t\t\t\ttotalTokens: 0,\n\t\t\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t\t\t},\n\t\t\tstopReason: \"stop\",\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\n\t\ttry {\n\t\t\tconst apiKey = options?.apiKey;\n\t\t\tif (!apiKey) {\n\t\t\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t\t\t}\n\n\t\t\tconst accountId = extractAccountId(apiKey);\n\t\t\tlet body = buildRequestBody(model, context, options);\n\t\t\tconst nextBody = await options?.onPayload?.(body, model);\n\t\t\tif (nextBody !== undefined) {\n\t\t\t\tbody = nextBody as RequestBody;\n\t\t\t}\n\t\t\tconst codexSessionId = clampOpenAIPromptCacheKey(options?.sessionId);\n\t\t\tconst websocketRequestId = codexSessionId || createCodexRequestId();\n\t\t\tconst sseHeaders = buildSSEHeaders(model.headers, options?.headers, accountId, apiKey, codexSessionId);\n\t\t\tconst websocketHeaders = buildWebSocketHeaders(\n\t\t\t\tmodel.headers,\n\t\t\t\toptions?.headers,\n\t\t\t\taccountId,\n\t\t\t\tapiKey,\n\t\t\t\twebsocketRequestId,\n\t\t\t);\n\t\t\tconst bodyJson = JSON.stringify(body);\n\t\t\tconst httpTimeoutMs = normalizeTimeoutMs(options?.timeoutMs);\n\t\t\tconst websocketConnectTimeoutMs = normalizeTimeoutMs(options?.websocketConnectTimeoutMs);\n\t\t\tconst transport = options?.transport || \"auto\";\n\t\t\tconst websocketDisabledForSession = transport !== \"sse\" && isWebSocketSseFallbackActive(options?.sessionId);\n\t\t\tif (websocketDisabledForSession) {\n\t\t\t\trecordWebSocketSseFallback(options?.sessionId);\n\t\t\t}\n\n\t\t\tif (transport !== \"sse\" && !websocketDisabledForSession) {\n\t\t\t\tlet websocketStarted = false;\n\t\t\t\tlet retriedWebSocketConnectionLimit = false;\n\t\t\t\twhile (true) {\n\t\t\t\t\twebsocketStarted = false;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait processWebSocketStream(\n\t\t\t\t\t\t\tresolveCodexWebSocketUrl(model.baseUrl),\n\t\t\t\t\t\t\tbody,\n\t\t\t\t\t\t\twebsocketHeaders,\n\t\t\t\t\t\t\toutput,\n\t\t\t\t\t\t\tstream,\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t() => {\n\t\t\t\t\t\t\t\twebsocketStarted = true;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\thttpTimeoutMs,\n\t\t\t\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\t\t\t\toptions,\n\t\t\t\t\t\t);\n\n\t\t\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstream.push({\n\t\t\t\t\t\t\ttype: \"done\",\n\t\t\t\t\t\t\treason: output.stopReason as \"stop\" | \"length\" | \"toolUse\",\n\t\t\t\t\t\t\tmessage: output,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tstream.end();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tconst aborted = options?.signal?.aborted;\n\t\t\t\t\t\tconst connectionLimitBeforeStart = !websocketStarted && isWebSocketConnectionLimitReachedError(error);\n\t\t\t\t\t\tif (!aborted && connectionLimitBeforeStart && !retriedWebSocketConnectionLimit) {\n\t\t\t\t\t\t\tretriedWebSocketConnectionLimit = true;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (aborted || (isCodexNonTransportError(error) && !connectionLimitBeforeStart)) {\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tappendAssistantMessageDiagnostic(\n\t\t\t\t\t\t\toutput,\n\t\t\t\t\t\t\tcreateAssistantMessageDiagnostic(\"provider_transport_failure\", error, {\n\t\t\t\t\t\t\t\tconfiguredTransport: transport,\n\t\t\t\t\t\t\t\tfallbackTransport: websocketStarted ? undefined : \"sse\",\n\t\t\t\t\t\t\t\teventsEmitted: websocketStarted,\n\t\t\t\t\t\t\t\tphase: websocketStarted ? \"after_message_stream_start\" : \"before_message_stream_start\",\n\t\t\t\t\t\t\t\trequestBytes: new TextEncoder().encode(bodyJson).byteLength,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t);\n\t\t\t\t\t\trecordWebSocketFailure(options?.sessionId, error);\n\t\t\t\t\t\tif (websocketStarted) {\n\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t}\n\t\t\t\t\t\trecordWebSocketSseFallback(options?.sessionId);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Compress the request body once for the SSE path. The Codex backend\n\t\t\t// decodes Content-Encoding: zstd; the WebSocket transport above sends the\n\t\t\t// uncompressed JSON frame, matching the official Codex client.\n\t\t\tconst compressedBody = compressRequestBodyZstd(bodyJson);\n\t\t\tif (compressedBody) {\n\t\t\t\tsseHeaders.set(\"content-encoding\", \"zstd\");\n\t\t\t}\n\t\t\tconst sseBody: Uint8Array | string = compressedBody ?? bodyJson;\n\n\t\t\t// Fetch with retry logic for rate limits and transient errors\n\t\t\tlet response: Response | undefined;\n\t\t\tlet lastError: Error | undefined;\n\t\t\tconst maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES;\n\n\t\t\tfor (let attempt = 0; attempt <= maxRetries; attempt++) {\n\t\t\t\tif (options?.signal?.aborted) {\n\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tconst headerTimeoutSignal =\n\t\t\t\t\t\thttpTimeoutMs !== undefined && httpTimeoutMs > 0 ? AbortSignal.timeout(httpTimeoutMs) : undefined;\n\t\t\t\t\tconst combinedSignal = combineAbortSignals([options?.signal, headerTimeoutSignal]);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tresponse = await fetch(resolveCodexUrl(model.baseUrl), {\n\t\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\t\theaders: sseHeaders,\n\t\t\t\t\t\t\tbody: sseBody,\n\t\t\t\t\t\t\tsignal: combinedSignal.signal,\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (headerTimeoutSignal?.aborted && !options?.signal?.aborted) {\n\t\t\t\t\t\t\tthrow new Error(`Codex SSE response headers timed out after ${httpTimeoutMs}ms`);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tcombinedSignal.cleanup();\n\t\t\t\t\t}\n\t\t\t\t\tawait options?.onResponse?.(\n\t\t\t\t\t\t{ status: response.status, headers: headersToRecord(response.headers) },\n\t\t\t\t\t\tmodel,\n\t\t\t\t\t);\n\n\t\t\t\t\tif (response.ok) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\n\t\t\t\t\tconst errorText = await response.text();\n\t\t\t\t\tif (attempt < maxRetries && isRetryableError(response.status, errorText)) {\n\t\t\t\t\t\tconst retryAfterDelayMs = getRetryAfterDelayMs(response.headers);\n\t\t\t\t\t\tconst delayMs =\n\t\t\t\t\t\t\tretryAfterDelayMs === undefined\n\t\t\t\t\t\t\t\t? BASE_DELAY_MS * 2 ** attempt\n\t\t\t\t\t\t\t\t: response.status === 429\n\t\t\t\t\t\t\t\t\t? capRetryDelayMs(retryAfterDelayMs, options)\n\t\t\t\t\t\t\t\t\t: retryAfterDelayMs;\n\n\t\t\t\t\t\tawait sleep(delayMs, options?.signal);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Parse error for friendly message on final attempt or non-retryable error\n\t\t\t\t\tconst fakeResponse = new Response(errorText, {\n\t\t\t\t\t\tstatus: response.status,\n\t\t\t\t\t\tstatusText: response.statusText,\n\t\t\t\t\t});\n\t\t\t\t\tconst info = await parseErrorResponse(fakeResponse);\n\t\t\t\t\tthrow new Error(info.friendlyMessage || info.message);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (error instanceof Error) {\n\t\t\t\t\t\tif (error.name === \"AbortError\" || error.message === \"Request was aborted\") {\n\t\t\t\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tlastError = error instanceof Error ? error : new Error(String(error));\n\t\t\t\t\t// Network errors are retryable\n\t\t\t\t\tif (attempt < maxRetries && !lastError.message.includes(\"usage limit\")) {\n\t\t\t\t\t\tconst delayMs = BASE_DELAY_MS * 2 ** attempt;\n\t\t\t\t\t\tawait sleep(delayMs, options?.signal);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthrow lastError;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (!response?.ok) {\n\t\t\t\tthrow lastError ?? new Error(\"Failed after retries\");\n\t\t\t}\n\n\t\t\tif (!response.body) {\n\t\t\t\tthrow new Error(\"No response body\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t\tawait processStream(response, output, stream, model, options);\n\n\t\t\tif (options?.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\n\t\t\tstream.push({ type: \"done\", reason: output.stopReason as \"stop\" | \"length\" | \"toolUse\", message: output });\n\t\t\tstream.end();\n\t\t} catch (error) {\n\t\t\tfor (const block of output.content) {\n\t\t\t\t// partialJson is only a streaming scratch buffer; never persist it.\n\t\t\t\tdelete (block as { partialJson?: string }).partialJson;\n\t\t\t}\n\t\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\t\toutput.errorMessage = formatProviderError(normalizeProviderError(error));\n\t\t\tstream.push({ type: \"error\", reason: output.stopReason, error: output });\n\t\t\tstream.end();\n\t\t}\n\t})();\n\n\treturn stream;\n};\n\nexport const streamSimple: StreamFunction<\"openai-codex-responses\", SimpleStreamOptions> = (\n\tmodel: Model<\"openai-codex-responses\">,\n\tcontext: Context,\n\toptions?: SimpleStreamOptions,\n): AssistantMessageEventStream => {\n\tconst apiKey = options?.apiKey;\n\tif (!apiKey) {\n\t\tthrow new Error(`No API key for provider: ${model.provider}`);\n\t}\n\n\tconst base = buildBaseOptions(model, context, options, apiKey);\n\tconst clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : undefined;\n\tconst reasoningEffort = clampedReasoning === \"off\" ? undefined : clampedReasoning;\n\n\treturn stream(model, context, {\n\t\t...base,\n\t\treasoningEffort,\n\t} satisfies OpenAICodexResponsesOptions);\n};\n\n// ============================================================================\n// Request Building\n// ============================================================================\n\nfunction buildRequestBody(\n\tmodel: Model<\"openai-codex-responses\">,\n\tcontext: Context,\n\toptions?: OpenAICodexResponsesOptions,\n): RequestBody {\n\tconst toolPlacement = splitDeferredTools(context, model.compat?.supportsToolSearch ?? false);\n\tconst messages = convertResponsesMessages(model, context, CODEX_TOOL_CALL_PROVIDERS, {\n\t\tincludeSystemPrompt: false,\n\t\tdeferredTools: toolPlacement.deferred,\n\t});\n\n\tconst body: RequestBody = {\n\t\tmodel: model.id,\n\t\tstore: false,\n\t\tstream: true,\n\t\tinstructions: context.systemPrompt || \"You are a helpful assistant.\",\n\t\tinput: messages,\n\t\ttext: { verbosity: options?.textVerbosity || \"low\" },\n\t\tinclude: [\"reasoning.encrypted_content\"],\n\t\tprompt_cache_key: clampOpenAIPromptCacheKey(options?.sessionId),\n\t\ttool_choice: options?.toolChoice ?? \"auto\",\n\t\tparallel_tool_calls: true,\n\t};\n\n\tif (options?.temperature !== undefined) {\n\t\tbody.temperature = options.temperature;\n\t}\n\n\tif (options?.serviceTier !== undefined) {\n\t\tbody.service_tier = options.serviceTier;\n\t}\n\n\tif (toolPlacement.immediate.length > 0) {\n\t\tbody.tools = convertResponsesTools(toolPlacement.immediate, { strict: null });\n\t}\n\n\tif (options?.reasoningEffort !== undefined) {\n\t\tconst effort =\n\t\t\toptions.reasoningEffort === \"none\"\n\t\t\t\t? (model.thinkingLevelMap?.off ?? \"none\")\n\t\t\t\t: (model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort);\n\t\tif (effort !== null) {\n\t\t\tbody.reasoning = {\n\t\t\t\teffort,\n\t\t\t\tsummary: options.reasoningSummary ?? \"auto\",\n\t\t\t};\n\t\t}\n\t}\n\n\treturn body;\n}\n\nfunction getServiceTierCostMultiplier(\n\tmodel: Pick<Model<\"openai-codex-responses\">, \"id\">,\n\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n): number {\n\tswitch (serviceTier) {\n\t\tcase \"flex\":\n\t\t\treturn 0.5;\n\t\tcase \"priority\":\n\t\t\treturn model.id === \"gpt-5.5\" ? 2.5 : 2;\n\t\tdefault:\n\t\t\treturn 1;\n\t}\n}\n\nfunction applyServiceTierPricing(\n\tusage: Usage,\n\tserviceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\tmodel: Pick<Model<\"openai-codex-responses\">, \"id\">,\n) {\n\tconst multiplier = getServiceTierCostMultiplier(model, serviceTier);\n\tif (multiplier === 1) return;\n\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\nfunction resolveCodexServiceTier(\n\tresponseServiceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n\trequestServiceTier: ResponseCreateParamsStreaming[\"service_tier\"] | undefined,\n): ResponseCreateParamsStreaming[\"service_tier\"] | undefined {\n\tif (responseServiceTier === \"default\" && (requestServiceTier === \"flex\" || requestServiceTier === \"priority\")) {\n\t\treturn requestServiceTier;\n\t}\n\treturn responseServiceTier ?? requestServiceTier;\n}\n\nfunction resolveCodexUrl(baseUrl?: string): string {\n\tconst raw = baseUrl && baseUrl.trim().length > 0 ? baseUrl : DEFAULT_CODEX_BASE_URL;\n\tconst normalized = raw.replace(/\\/+$/, \"\");\n\tif (normalized.endsWith(\"/codex/responses\")) return normalized;\n\tif (normalized.endsWith(\"/codex\")) return `${normalized}/responses`;\n\treturn `${normalized}/codex/responses`;\n}\n\nfunction resolveCodexWebSocketUrl(baseUrl?: string): string {\n\tconst url = new URL(resolveCodexUrl(baseUrl));\n\tif (url.protocol === \"https:\") url.protocol = \"wss:\";\n\tif (url.protocol === \"http:\") url.protocol = \"ws:\";\n\treturn url.toString();\n}\n\n// ============================================================================\n// Response Processing\n// ============================================================================\n\nasync function processStream(\n\tresponse: Response,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tmodel: Model<\"openai-codex-responses\">,\n\toptions?: OpenAICodexResponsesOptions,\n): Promise<void> {\n\tawait processResponsesStream(mapCodexEvents(parseSSE(response, options?.signal)), output, stream, model, {\n\t\tserviceTier: options?.serviceTier,\n\t\tresolveServiceTier: resolveCodexServiceTier,\n\t\tapplyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),\n\t});\n}\n\nclass CodexApiError extends Error {\n\treadonly code?: string;\n\treadonly payload?: Record<string, unknown>;\n\n\tconstructor(message: string, options?: { code?: string; payload?: Record<string, unknown>; cause?: unknown }) {\n\t\tsuper(message);\n\t\tthis.name = \"CodexApiError\";\n\t\tthis.code = options?.code;\n\t\tthis.payload = options?.payload;\n\t\tthis.cause = options?.cause;\n\t}\n}\n\nclass CodexProtocolError extends Error {\n\treadonly payload?: unknown;\n\n\tconstructor(message: string, options?: { payload?: unknown; cause?: unknown }) {\n\t\tsuper(message);\n\t\tthis.name = \"CodexProtocolError\";\n\t\tthis.payload = options?.payload;\n\t\tthis.cause = options?.cause;\n\t}\n}\n\nfunction isCodexNonTransportError(error: unknown): boolean {\n\treturn error instanceof CodexApiError || error instanceof CodexProtocolError;\n}\n\nfunction isWebSocketConnectionLimitReachedError(error: unknown): boolean {\n\treturn error instanceof CodexApiError && error.code === WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE;\n}\n\nfunction extractCodexEventError(event: Record<string, unknown>): { code?: string; message?: string } {\n\tconst nested = event.error && typeof event.error === \"object\" ? (event.error as Record<string, unknown>) : undefined;\n\treturn {\n\t\tcode: typeof event.code === \"string\" ? event.code : typeof nested?.code === \"string\" ? nested.code : undefined,\n\t\tmessage:\n\t\t\ttypeof event.message === \"string\"\n\t\t\t\t? event.message\n\t\t\t\t: typeof nested?.message === \"string\"\n\t\t\t\t\t? nested.message\n\t\t\t\t\t: undefined,\n\t};\n}\n\nasync function* mapCodexEvents(events: AsyncIterable<Record<string, unknown>>): AsyncGenerator<ResponseStreamEvent> {\n\tfor await (const event of events) {\n\t\tconst type = typeof event.type === \"string\" ? event.type : undefined;\n\t\tif (!type) continue;\n\n\t\tif (type === \"error\") {\n\t\t\tconst { code, message } = extractCodexEventError(event);\n\t\t\tthrow new CodexApiError(`Codex error: ${message || code || JSON.stringify(event)}`, {\n\t\t\t\tcode,\n\t\t\t\tpayload: event,\n\t\t\t});\n\t\t}\n\n\t\tif (type === \"response.failed\") {\n\t\t\tconst response = (event as { response?: { error?: { code?: string; message?: string } } }).response;\n\t\t\tconst code = response?.error?.code;\n\t\t\tconst message = response?.error?.message;\n\t\t\tthrow new CodexApiError(message || \"Codex response failed\", { code, payload: event });\n\t\t}\n\n\t\tif (type === \"response.done\" || type === \"response.completed\" || type === \"response.incomplete\") {\n\t\t\tconst response = (event as { response?: { status?: unknown } }).response;\n\t\t\tconst normalizedResponse = response\n\t\t\t\t? { ...response, status: normalizeCodexStatus(response.status) }\n\t\t\t\t: response;\n\t\t\tyield { ...event, type: \"response.completed\", response: normalizedResponse } as ResponseStreamEvent;\n\t\t\treturn;\n\t\t}\n\n\t\tyield event as unknown as ResponseStreamEvent;\n\t}\n}\n\nfunction normalizeCodexStatus(status: unknown): CodexResponseStatus | undefined {\n\tif (typeof status !== \"string\") return undefined;\n\treturn CODEX_RESPONSE_STATUSES.has(status as CodexResponseStatus) ? (status as CodexResponseStatus) : undefined;\n}\n\n// ============================================================================\n// SSE Parsing\n// ============================================================================\n\nasync function* parseSSE(response: Response, signal?: AbortSignal): AsyncGenerator<Record<string, unknown>> {\n\tif (!response.body) return;\n\n\tconst reader = response.body.getReader();\n\tconst decoder = new TextDecoder();\n\tlet buffer = \"\";\n\tconst onAbort = () => {\n\t\tvoid reader.cancel().catch(() => {});\n\t};\n\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\ttry {\n\t\twhile (true) {\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\t\t\tif (done) break;\n\t\t\tbuffer += decoder.decode(value, { stream: true });\n\n\t\t\tlet idx = buffer.indexOf(\"\\n\\n\");\n\t\t\twhile (idx !== -1) {\n\t\t\t\tconst chunk = buffer.slice(0, idx);\n\t\t\t\tbuffer = buffer.slice(idx + 2);\n\n\t\t\t\tconst dataLines = chunk\n\t\t\t\t\t.split(\"\\n\")\n\t\t\t\t\t.filter((l) => l.startsWith(\"data:\"))\n\t\t\t\t\t.map((l) => l.slice(5).trim());\n\t\t\t\tif (dataLines.length > 0) {\n\t\t\t\t\tconst data = dataLines.join(\"\\n\").trim();\n\t\t\t\t\tif (data && data !== \"[DONE]\") {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tyield JSON.parse(data) as Record<string, unknown>;\n\t\t\t\t\t\t} catch (cause) {\n\t\t\t\t\t\t\tthrow new CodexProtocolError(`Invalid Codex SSE JSON: ${formatThrownValue(cause)}`, {\n\t\t\t\t\t\t\t\tcause,\n\t\t\t\t\t\t\t\tpayload: data,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tidx = buffer.indexOf(\"\\n\\n\");\n\t\t\t}\n\t\t}\n\t} finally {\n\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\ttry {\n\t\t\tawait reader.cancel();\n\t\t} catch {}\n\t\ttry {\n\t\t\treader.releaseLock();\n\t\t} catch {}\n\t}\n}\n\n// ============================================================================\n// WebSocket Parsing\n// ============================================================================\n\nconst OPENAI_BETA_RESPONSES_WEBSOCKETS = \"responses_websockets=2026-02-06\";\nconst SESSION_WEBSOCKET_CACHE_TTL_MS = 5 * 60 * 1000;\nconst SESSION_WEBSOCKET_MAX_AGE_MS = 55 * 60 * 1000;\n\ntype WebSocketEventType = \"open\" | \"message\" | \"error\" | \"close\";\ntype WebSocketListener = (event: unknown) => void;\n\ninterface WebSocketLike {\n\tclose(code?: number, reason?: string): void;\n\tsend(data: string): void;\n\taddEventListener(type: WebSocketEventType, listener: WebSocketListener): void;\n\tremoveEventListener(type: WebSocketEventType, listener: WebSocketListener): void;\n}\n\ninterface CachedWebSocketContinuationState {\n\tlastRequestBody: RequestBody;\n\tlastResponseId: string;\n\tlastResponseItems: ResponseInput;\n}\n\ninterface CachedWebSocketConnection {\n\tsocket: WebSocketLike;\n\tbusy: boolean;\n\tcreatedAt: number;\n\tidleTimer?: ReturnType<typeof setTimeout>;\n\tcontinuation?: CachedWebSocketContinuationState;\n}\n\nexport interface OpenAICodexWebSocketDebugStats {\n\trequests: number;\n\tconnectionsCreated: number;\n\tconnectionsReused: number;\n\tcachedContextRequests: number;\n\tstoreTrueRequests: number;\n\tfullContextRequests: number;\n\tdeltaRequests: number;\n\tlastInputItems: number;\n\tlastDeltaInputItems?: number;\n\tlastPreviousResponseId?: string;\n\twebsocketFailures: number;\n\tsseFallbacks: number;\n\twebsocketFallbackActive?: boolean;\n\tlastWebSocketError?: string;\n}\n\nconst websocketSessionCache = new Map<string, CachedWebSocketConnection>();\nconst websocketDebugStats = new Map<string, OpenAICodexWebSocketDebugStats>();\nconst websocketSseFallbackSessions = new Set<string>();\n\nfunction getOrCreateWebSocketDebugStats(sessionId: string): OpenAICodexWebSocketDebugStats {\n\tlet stats = websocketDebugStats.get(sessionId);\n\tif (!stats) {\n\t\tstats = {\n\t\t\trequests: 0,\n\t\t\tconnectionsCreated: 0,\n\t\t\tconnectionsReused: 0,\n\t\t\tcachedContextRequests: 0,\n\t\t\tstoreTrueRequests: 0,\n\t\t\tfullContextRequests: 0,\n\t\t\tdeltaRequests: 0,\n\t\t\tlastInputItems: 0,\n\t\t\twebsocketFailures: 0,\n\t\t\tsseFallbacks: 0,\n\t\t};\n\t\twebsocketDebugStats.set(sessionId, stats);\n\t}\n\treturn stats;\n}\n\nexport function getOpenAICodexWebSocketDebugStats(sessionId: string): OpenAICodexWebSocketDebugStats | undefined {\n\tconst stats = websocketDebugStats.get(sessionId);\n\treturn stats ? { ...stats } : undefined;\n}\n\nexport function resetOpenAICodexWebSocketDebugStats(sessionId?: string): void {\n\tif (sessionId) {\n\t\twebsocketDebugStats.delete(sessionId);\n\t\twebsocketSseFallbackSessions.delete(sessionId);\n\t\treturn;\n\t}\n\twebsocketDebugStats.clear();\n\twebsocketSseFallbackSessions.clear();\n}\n\nexport function closeOpenAICodexWebSocketSessions(sessionId?: string): void {\n\tconst closeEntry = (entry: CachedWebSocketConnection) => {\n\t\tif (entry.idleTimer) clearTimeout(entry.idleTimer);\n\t\tcloseWebSocketSilently(entry.socket, 1000, \"debug_close\");\n\t};\n\tif (sessionId) {\n\t\tconst entry = websocketSessionCache.get(sessionId);\n\t\tif (entry) closeEntry(entry);\n\t\twebsocketSessionCache.delete(sessionId);\n\t\treturn;\n\t}\n\tfor (const entry of websocketSessionCache.values()) {\n\t\tcloseEntry(entry);\n\t}\n\twebsocketSessionCache.clear();\n}\n\nregisterSessionResourceCleanup(closeOpenAICodexWebSocketSessions);\n\nfunction isWebSocketSseFallbackActive(sessionId: string | undefined): boolean {\n\treturn sessionId ? websocketSseFallbackSessions.has(sessionId) : false;\n}\n\nfunction recordWebSocketSseFallback(sessionId: string | undefined): void {\n\tif (!sessionId) return;\n\tconst stats = getOrCreateWebSocketDebugStats(sessionId);\n\tstats.sseFallbacks++;\n\tstats.websocketFallbackActive = isWebSocketSseFallbackActive(sessionId);\n}\n\nfunction recordWebSocketFailure(sessionId: string | undefined, error: unknown): void {\n\tif (!sessionId) return;\n\twebsocketSseFallbackSessions.add(sessionId);\n\n\tconst stats = getOrCreateWebSocketDebugStats(sessionId);\n\tstats.websocketFailures++;\n\tstats.lastWebSocketError = formatThrownValue(error);\n\tstats.websocketFallbackActive = true;\n}\n\ntype WebSocketConstructor = new (\n\turl: string,\n\tprotocols?: string | string[] | { headers?: Record<string, string> },\n) => WebSocketLike;\n\nlet _cachedWebsocket: WebSocketConstructor | null = null;\nasync function getWebSocketConstructor(env?: ProviderEnv): Promise<WebSocketConstructor | null> {\n\tif (!env && _cachedWebsocket) return _cachedWebsocket;\n\n\t// bun doesn't respect http proxy envs, ref: https://github.com/oven-sh/bun/issues/15489\n\t// TODO: remove this when bun supports proxy envs in websocket.\n\tif (typeof process !== \"undefined\" && process.versions?.bun) {\n\t\tconst WebSocketWithProxy = class extends WebSocket {\n\t\t\tconstructor(url: string | URL, options?: string | string[] | Record<string, unknown>) {\n\t\t\t\tlet _opts: Record<string, unknown> = {};\n\t\t\t\tif (Array.isArray(options) || typeof options === \"string\") {\n\t\t\t\t\t_opts = { protocols: options };\n\t\t\t\t} else {\n\t\t\t\t\t_opts = { ...options };\n\t\t\t\t}\n\n\t\t\t\tconst proxyUrl = resolveHttpProxyUrlForTarget(\n\t\t\t\t\turl.toString().replace(/^wss:/, \"https:\").replace(/^ws:/, \"http:\"),\n\t\t\t\t\tenv,\n\t\t\t\t);\n\t\t\t\tsuper(url, { ..._opts, ...(proxyUrl ? { proxy: proxyUrl.toString() } : {}) } as any);\n\t\t\t}\n\t\t};\n\t\tif (!env) {\n\t\t\t_cachedWebsocket = WebSocketWithProxy;\n\t\t}\n\t\treturn WebSocketWithProxy;\n\t}\n\n\tconst ctor = (globalThis as { WebSocket?: unknown }).WebSocket;\n\tif (typeof ctor !== \"function\") return null;\n\treturn ctor as unknown as WebSocketConstructor;\n}\n\nclass WebSocketCloseError extends Error {\n\treadonly code?: number;\n\treadonly reason?: string;\n\treadonly wasClean?: boolean;\n\n\tconstructor(message: string, options?: { code?: number; reason?: string; wasClean?: boolean }) {\n\t\tsuper(message);\n\t\tthis.name = \"WebSocketCloseError\";\n\t\tthis.code = options?.code;\n\t\tthis.reason = options?.reason;\n\t\tthis.wasClean = options?.wasClean;\n\t}\n}\n\nfunction getWebSocketReadyState(socket: WebSocketLike): number | undefined {\n\tconst readyState = (socket as { readyState?: unknown }).readyState;\n\treturn typeof readyState === \"number\" ? readyState : undefined;\n}\n\nfunction isWebSocketReusable(socket: WebSocketLike): boolean {\n\tconst readyState = getWebSocketReadyState(socket);\n\t// If readyState is unavailable, assume the runtime keeps it open/reusable.\n\treturn readyState === undefined || readyState === 1;\n}\n\nfunction isWebSocketSessionExpired(entry: CachedWebSocketConnection): boolean {\n\treturn Date.now() - entry.createdAt >= SESSION_WEBSOCKET_MAX_AGE_MS;\n}\n\nfunction closeWebSocketSilently(socket: WebSocketLike, code = 1000, reason = \"done\"): void {\n\ttry {\n\t\tsocket.close(code, reason);\n\t} catch {}\n}\n\nfunction scheduleSessionWebSocketExpiry(sessionId: string, entry: CachedWebSocketConnection): void {\n\tif (entry.idleTimer) {\n\t\tclearTimeout(entry.idleTimer);\n\t}\n\tentry.idleTimer = setTimeout(() => {\n\t\tif (entry.busy) return;\n\t\tcloseWebSocketSilently(entry.socket, 1000, \"idle_timeout\");\n\t\twebsocketSessionCache.delete(sessionId);\n\t}, SESSION_WEBSOCKET_CACHE_TTL_MS);\n}\n\nasync function connectWebSocket(\n\turl: string,\n\theaders: Headers,\n\tsignal?: AbortSignal,\n\tconnectTimeoutMs = DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS,\n\tenv?: ProviderEnv,\n): Promise<WebSocketLike> {\n\tconst WebSocketCtor = await getWebSocketConstructor(env);\n\tif (!WebSocketCtor) {\n\t\tthrow new Error(\"WebSocket transport is not available in this runtime\");\n\t}\n\n\tconst wsHeaders = headersToRecord(headers);\n\tdelete wsHeaders[\"OpenAI-Beta\"];\n\n\treturn new Promise<WebSocketLike>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\t\tlet socket: WebSocketLike;\n\n\t\ttry {\n\t\t\tsocket = new WebSocketCtor(url, { headers: wsHeaders });\n\t\t} catch (error) {\n\t\t\treject(error instanceof Error ? error : new Error(String(error)));\n\t\t\treturn;\n\t\t}\n\n\t\tconst cleanup = () => {\n\t\t\tif (timeout) {\n\t\t\t\tclearTimeout(timeout);\n\t\t\t\ttimeout = undefined;\n\t\t\t}\n\t\t\tsocket.removeEventListener(\"open\", onOpen);\n\t\t\tsocket.removeEventListener(\"error\", onError);\n\t\t\tsocket.removeEventListener(\"close\", onClose);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst fail = (error: Error, closeReason?: string) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tif (closeReason) {\n\t\t\t\tcloseWebSocketSilently(socket, 1000, closeReason);\n\t\t\t}\n\t\t\treject(error);\n\t\t};\n\t\tconst onOpen: WebSocketListener = () => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tresolve(socket);\n\t\t};\n\t\tconst onError: WebSocketListener = (event) => {\n\t\t\tfail(extractWebSocketError(event));\n\t\t};\n\t\tconst onClose: WebSocketListener = (event) => {\n\t\t\tfail(extractWebSocketCloseError(event));\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tfail(new Error(\"Request was aborted\"), \"aborted\");\n\t\t};\n\n\t\tsocket.addEventListener(\"open\", onOpen);\n\t\tsocket.addEventListener(\"error\", onError);\n\t\tsocket.addEventListener(\"close\", onClose);\n\t\tsignal?.addEventListener(\"abort\", onAbort);\n\n\t\tif (connectTimeoutMs > 0) {\n\t\t\ttimeout = setTimeout(() => {\n\t\t\t\tfail(new Error(`WebSocket connect timeout after ${connectTimeoutMs}ms`), \"connect_timeout\");\n\t\t\t}, connectTimeoutMs);\n\t\t}\n\t\tif (signal?.aborted) {\n\t\t\tonAbort();\n\t\t}\n\t});\n}\n\nasync function acquireWebSocket(\n\turl: string,\n\theaders: Headers,\n\tsessionId: string | undefined,\n\tsignal?: AbortSignal,\n\tconnectTimeoutMs?: number,\n\tenv?: ProviderEnv,\n): Promise<{\n\tsocket: WebSocketLike;\n\tentry?: CachedWebSocketConnection;\n\treused: boolean;\n\trelease: (options?: { keep?: boolean }) => void;\n}> {\n\tif (!sessionId) {\n\t\tconst socket = await connectWebSocket(url, headers, signal, connectTimeoutMs, env);\n\t\treturn {\n\t\t\tsocket,\n\t\t\treused: false,\n\t\t\trelease: () => closeWebSocketSilently(socket),\n\t\t};\n\t}\n\n\tconst cached = websocketSessionCache.get(sessionId);\n\tif (cached) {\n\t\tif (cached.idleTimer) {\n\t\t\tclearTimeout(cached.idleTimer);\n\t\t\tcached.idleTimer = undefined;\n\t\t}\n\t\tif (!cached.busy && isWebSocketSessionExpired(cached)) {\n\t\t\tcloseWebSocketSilently(cached.socket, 1000, \"connection_age_limit\");\n\t\t\twebsocketSessionCache.delete(sessionId);\n\t\t} else if (!cached.busy && isWebSocketReusable(cached.socket)) {\n\t\t\tcached.busy = true;\n\t\t\treturn {\n\t\t\t\tsocket: cached.socket,\n\t\t\t\tentry: cached,\n\t\t\t\treused: true,\n\t\t\t\trelease: ({ keep } = {}) => {\n\t\t\t\t\tif (!keep || !isWebSocketReusable(cached.socket)) {\n\t\t\t\t\t\tcloseWebSocketSilently(cached.socket);\n\t\t\t\t\t\twebsocketSessionCache.delete(sessionId);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcached.busy = false;\n\t\t\t\t\tscheduleSessionWebSocketExpiry(sessionId, cached);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (cached.busy) {\n\t\t\tconst socket = await connectWebSocket(url, headers, signal, connectTimeoutMs, env);\n\t\t\treturn {\n\t\t\t\tsocket,\n\t\t\t\treused: false,\n\t\t\t\trelease: () => {\n\t\t\t\t\tcloseWebSocketSilently(socket);\n\t\t\t\t},\n\t\t\t};\n\t\t}\n\t\tif (!isWebSocketReusable(cached.socket)) {\n\t\t\tcloseWebSocketSilently(cached.socket);\n\t\t\twebsocketSessionCache.delete(sessionId);\n\t\t}\n\t}\n\n\tconst socket = await connectWebSocket(url, headers, signal, connectTimeoutMs, env);\n\tconst entry: CachedWebSocketConnection = { socket, busy: true, createdAt: Date.now() };\n\twebsocketSessionCache.set(sessionId, entry);\n\treturn {\n\t\tsocket,\n\t\tentry,\n\t\treused: false,\n\t\trelease: ({ keep } = {}) => {\n\t\t\tif (!keep || !isWebSocketReusable(entry.socket)) {\n\t\t\t\tcloseWebSocketSilently(entry.socket);\n\t\t\t\tif (entry.idleTimer) clearTimeout(entry.idleTimer);\n\t\t\t\tif (websocketSessionCache.get(sessionId) === entry) {\n\t\t\t\t\twebsocketSessionCache.delete(sessionId);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tentry.busy = false;\n\t\t\tscheduleSessionWebSocketExpiry(sessionId, entry);\n\t\t},\n\t};\n}\n\nfunction extractWebSocketError(event: unknown): Error {\n\tif (event && typeof event === \"object\") {\n\t\tconst message = \"message\" in event ? (event as { message?: unknown }).message : undefined;\n\t\tif (typeof message === \"string\" && message.length > 0) {\n\t\t\treturn new Error(message);\n\t\t}\n\n\t\tconst nestedError = \"error\" in event ? (event as { error?: unknown }).error : undefined;\n\t\tif (nestedError instanceof Error && nestedError.message.length > 0) {\n\t\t\treturn nestedError;\n\t\t}\n\t\tif (nestedError && typeof nestedError === \"object\" && \"message\" in nestedError) {\n\t\t\tconst nestedMessage = (nestedError as { message?: unknown }).message;\n\t\t\tif (typeof nestedMessage === \"string\" && nestedMessage.length > 0) {\n\t\t\t\treturn new Error(nestedMessage);\n\t\t\t}\n\t\t}\n\t}\n\treturn new Error(\"WebSocket error\");\n}\n\nfunction extractWebSocketCloseError(event: unknown): Error {\n\tif (event && typeof event === \"object\") {\n\t\tconst code = \"code\" in event ? (event as { code?: unknown }).code : undefined;\n\t\tconst reason = \"reason\" in event ? (event as { reason?: unknown }).reason : undefined;\n\t\tconst wasClean = \"wasClean\" in event ? (event as { wasClean?: unknown }).wasClean : undefined;\n\t\tconst codeText = typeof code === \"number\" ? ` ${code}` : \"\";\n\t\tlet reasonText = typeof reason === \"string\" && reason.length > 0 ? ` ${reason}` : \"\";\n\t\tif (!reasonText && code === WEBSOCKET_MESSAGE_TOO_BIG_CLOSE_CODE) {\n\t\t\treasonText = \" message too big\";\n\t\t}\n\t\treturn new WebSocketCloseError(`WebSocket closed${codeText}${reasonText}`.trim(), {\n\t\t\tcode: typeof code === \"number\" ? code : undefined,\n\t\t\treason: typeof reason === \"string\" && reason.length > 0 ? reason : undefined,\n\t\t\twasClean: typeof wasClean === \"boolean\" ? wasClean : undefined,\n\t\t});\n\t}\n\treturn new Error(\"WebSocket closed\");\n}\n\nasync function decodeWebSocketData(data: unknown): Promise<string | null> {\n\tif (typeof data === \"string\") return data;\n\tif (data instanceof ArrayBuffer) {\n\t\treturn new TextDecoder().decode(new Uint8Array(data));\n\t}\n\tif (ArrayBuffer.isView(data)) {\n\t\tconst view = data as ArrayBufferView;\n\t\treturn new TextDecoder().decode(new Uint8Array(view.buffer, view.byteOffset, view.byteLength));\n\t}\n\tif (data && typeof data === \"object\" && \"arrayBuffer\" in data) {\n\t\tconst blobLike = data as { arrayBuffer: () => Promise<ArrayBuffer> };\n\t\tconst arrayBuffer = await blobLike.arrayBuffer();\n\t\treturn new TextDecoder().decode(new Uint8Array(arrayBuffer));\n\t}\n\treturn null;\n}\n\nasync function* parseWebSocket(\n\tsocket: WebSocketLike,\n\tsignal?: AbortSignal,\n\tidleTimeoutMs?: number,\n): AsyncGenerator<Record<string, unknown>> {\n\tconst queue: Record<string, unknown>[] = [];\n\tlet pending: (() => void) | null = null;\n\tlet done = false;\n\tlet failed: Error | null = null;\n\tlet sawCompletion = false;\n\n\tconst wake = () => {\n\t\tif (!pending) return;\n\t\tconst resolve = pending;\n\t\tpending = null;\n\t\tresolve();\n\t};\n\n\tconst onMessage: WebSocketListener = (event) => {\n\t\tvoid (async () => {\n\t\t\tlet text: string | null = null;\n\t\t\ttry {\n\t\t\t\tif (!event || typeof event !== \"object\" || !(\"data\" in event)) return;\n\t\t\t\ttext = await decodeWebSocketData((event as { data?: unknown }).data);\n\t\t\t\tif (!text) return;\n\t\t\t\tconst parsed = JSON.parse(text) as Record<string, unknown>;\n\t\t\t\tconst type = typeof parsed.type === \"string\" ? parsed.type : \"\";\n\t\t\t\tif (type === \"response.completed\" || type === \"response.done\" || type === \"response.incomplete\") {\n\t\t\t\t\tsawCompletion = true;\n\t\t\t\t\tdone = true;\n\t\t\t\t}\n\t\t\t\tqueue.push(parsed);\n\t\t\t\twake();\n\t\t\t} catch (cause) {\n\t\t\t\tfailed = new CodexProtocolError(`Invalid Codex WebSocket JSON: ${formatThrownValue(cause)}`, {\n\t\t\t\t\tcause,\n\t\t\t\t\tpayload: text,\n\t\t\t\t});\n\t\t\t\tdone = true;\n\t\t\t\twake();\n\t\t\t}\n\t\t})();\n\t};\n\n\tconst onError: WebSocketListener = (event) => {\n\t\tfailed = extractWebSocketError(event);\n\t\tdone = true;\n\t\twake();\n\t};\n\n\tconst onClose: WebSocketListener = (event) => {\n\t\tif (sawCompletion) {\n\t\t\tdone = true;\n\t\t\twake();\n\t\t\treturn;\n\t\t}\n\t\tif (!failed) {\n\t\t\tfailed = extractWebSocketCloseError(event);\n\t\t}\n\t\tdone = true;\n\t\twake();\n\t};\n\n\tconst onAbort = () => {\n\t\tfailed = new Error(\"Request was aborted\");\n\t\tdone = true;\n\t\twake();\n\t};\n\n\tsocket.addEventListener(\"message\", onMessage);\n\tsocket.addEventListener(\"error\", onError);\n\tsocket.addEventListener(\"close\", onClose);\n\tsignal?.addEventListener(\"abort\", onAbort);\n\n\ttry {\n\t\twhile (true) {\n\t\t\tif (signal?.aborted) {\n\t\t\t\tthrow new Error(\"Request was aborted\");\n\t\t\t}\n\t\t\tif (queue.length > 0) {\n\t\t\t\tyield queue.shift()!;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (done) break;\n\t\t\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\tpending = resolve;\n\t\t\t\tif (idleTimeoutMs !== undefined && idleTimeoutMs > 0) {\n\t\t\t\t\ttimeout = setTimeout(() => {\n\t\t\t\t\t\tconst error = new Error(`WebSocket idle timeout after ${idleTimeoutMs}ms`);\n\t\t\t\t\t\tfailed = error;\n\t\t\t\t\t\tdone = true;\n\t\t\t\t\t\tpending = null;\n\t\t\t\t\t\tcloseWebSocketSilently(socket, 1000, \"idle_timeout\");\n\t\t\t\t\t\treject(error);\n\t\t\t\t\t}, idleTimeoutMs);\n\t\t\t\t}\n\t\t\t}).finally(() => {\n\t\t\t\tif (timeout) {\n\t\t\t\t\tclearTimeout(timeout);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\n\t\tif (failed) {\n\t\t\tthrow failed;\n\t\t}\n\t\tif (!sawCompletion) {\n\t\t\tthrow new Error(\"WebSocket stream closed before response.completed\");\n\t\t}\n\t} finally {\n\t\tsocket.removeEventListener(\"message\", onMessage);\n\t\tsocket.removeEventListener(\"error\", onError);\n\t\tsocket.removeEventListener(\"close\", onClose);\n\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t}\n}\n\nfunction requestBodyWithoutInput(body: RequestBody): RequestBody {\n\tconst { input: _input, previous_response_id: _previousResponseId, ...rest } = body;\n\treturn rest;\n}\n\nfunction responseInputsEqual(a: ResponseInput | undefined, b: ResponseInput | undefined): boolean {\n\treturn JSON.stringify(a ?? []) === JSON.stringify(b ?? []);\n}\n\nfunction requestBodiesMatchExceptInput(a: RequestBody, b: RequestBody): boolean {\n\treturn JSON.stringify(requestBodyWithoutInput(a)) === JSON.stringify(requestBodyWithoutInput(b));\n}\n\nfunction getCachedWebSocketInputDelta(\n\tbody: RequestBody,\n\tcontinuation: CachedWebSocketContinuationState,\n): ResponseInput | undefined {\n\tif (!requestBodiesMatchExceptInput(body, continuation.lastRequestBody)) {\n\t\treturn undefined;\n\t}\n\n\tconst currentInput = body.input ?? [];\n\tconst baseline = [...(continuation.lastRequestBody.input ?? []), ...continuation.lastResponseItems];\n\tif (currentInput.length < baseline.length) {\n\t\treturn undefined;\n\t}\n\n\tconst prefix = currentInput.slice(0, baseline.length);\n\tif (!responseInputsEqual(prefix, baseline)) {\n\t\treturn undefined;\n\t}\n\n\treturn currentInput.slice(baseline.length);\n}\n\nfunction buildCachedWebSocketRequestBody(entry: CachedWebSocketConnection, body: RequestBody): RequestBody {\n\tconst continuation = entry.continuation;\n\tif (!continuation) {\n\t\treturn body;\n\t}\n\n\tconst delta = getCachedWebSocketInputDelta(body, continuation);\n\tif (!delta || !continuation.lastResponseId) {\n\t\tentry.continuation = undefined;\n\t\treturn body;\n\t}\n\n\treturn {\n\t\t...body,\n\t\tprevious_response_id: continuation.lastResponseId,\n\t\tinput: delta,\n\t};\n}\n\nasync function* startWebSocketOutputOnFirstEvent(\n\tevents: AsyncIterable<ResponseStreamEvent>,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tonStart: () => void,\n): AsyncGenerator<ResponseStreamEvent> {\n\tlet started = false;\n\tfor await (const event of events) {\n\t\tif (!started) {\n\t\t\tstarted = true;\n\t\t\tonStart();\n\t\t\tstream.push({ type: \"start\", partial: output });\n\t\t}\n\t\tyield event;\n\t}\n}\n\nasync function processWebSocketStream(\n\turl: string,\n\tbody: RequestBody,\n\theaders: Headers,\n\toutput: AssistantMessage,\n\tstream: AssistantMessageEventStream,\n\tmodel: Model<\"openai-codex-responses\">,\n\tonStart: () => void,\n\tidleTimeoutMs: number | undefined,\n\twebsocketConnectTimeoutMs: number | undefined,\n\toptions?: OpenAICodexResponsesOptions,\n): Promise<void> {\n\tconst { socket, entry, reused, release } = await acquireWebSocket(\n\t\turl,\n\t\theaders,\n\t\toptions?.sessionId,\n\t\toptions?.signal,\n\t\twebsocketConnectTimeoutMs,\n\t\toptions?.env,\n\t);\n\tlet keepConnection = true;\n\tconst useCachedContext = options?.transport === \"websocket-cached\" || options?.transport === \"auto\";\n\t// ChatGPT Codex Responses rejects `store: true` (\"Store must be set to false\").\n\t// WebSocket continuation still works via connection-scoped previous_response_id state.\n\tconst fullBody = body;\n\tconst requestBody = useCachedContext && entry ? buildCachedWebSocketRequestBody(entry, fullBody) : fullBody;\n\tconst stats = options?.sessionId ? getOrCreateWebSocketDebugStats(options.sessionId) : undefined;\n\tif (stats) {\n\t\tstats.requests++;\n\t\tif (reused) stats.connectionsReused++;\n\t\telse stats.connectionsCreated++;\n\t\tif (useCachedContext) stats.cachedContextRequests++;\n\t\tif (requestBody.store === true) stats.storeTrueRequests++;\n\t\tstats.lastInputItems = requestBody.input?.length ?? 0;\n\t\tif (requestBody.previous_response_id) {\n\t\t\tstats.deltaRequests++;\n\t\t\tstats.lastDeltaInputItems = requestBody.input?.length ?? 0;\n\t\t\tstats.lastPreviousResponseId = requestBody.previous_response_id;\n\t\t} else {\n\t\t\tstats.fullContextRequests++;\n\t\t\tstats.lastDeltaInputItems = undefined;\n\t\t\tstats.lastPreviousResponseId = undefined;\n\t\t}\n\t}\n\ttry {\n\t\tsocket.send(JSON.stringify({ type: \"response.create\", ...requestBody }));\n\t\tawait processResponsesStream(\n\t\t\tstartWebSocketOutputOnFirstEvent(\n\t\t\t\tmapCodexEvents(parseWebSocket(socket, options?.signal, idleTimeoutMs)),\n\t\t\t\toutput,\n\t\t\t\tstream,\n\t\t\t\tonStart,\n\t\t\t),\n\t\t\toutput,\n\t\t\tstream,\n\t\t\tmodel,\n\t\t\t{\n\t\t\t\tserviceTier: options?.serviceTier,\n\t\t\t\tresolveServiceTier: resolveCodexServiceTier,\n\t\t\t\tapplyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model),\n\t\t\t},\n\t\t);\n\t\tif (options?.signal?.aborted) {\n\t\t\tkeepConnection = false;\n\t\t} else if (useCachedContext && entry && output.responseId) {\n\t\t\tconst responseItems = convertResponsesMessages(model, { messages: [output] }, CODEX_TOOL_CALL_PROVIDERS, {\n\t\t\t\tincludeSystemPrompt: false,\n\t\t\t}).filter((item) => item.type !== \"function_call_output\");\n\t\t\tentry.continuation = {\n\t\t\t\tlastRequestBody: fullBody,\n\t\t\t\tlastResponseId: output.responseId,\n\t\t\t\tlastResponseItems: responseItems,\n\t\t\t};\n\t\t}\n\t} catch (error) {\n\t\tif (entry) {\n\t\t\tentry.continuation = undefined;\n\t\t}\n\t\tkeepConnection = false;\n\t\tthrow error;\n\t} finally {\n\t\trelease({ keep: keepConnection });\n\t}\n}\n\n// ============================================================================\n// Error Handling\n// ============================================================================\n\nasync function parseErrorResponse(response: Response): Promise<{ message: string; friendlyMessage?: string }> {\n\tconst raw = await response.text();\n\tlet message = raw || response.statusText || \"Request failed\";\n\tlet friendlyMessage: string | undefined;\n\n\ttry {\n\t\tconst parsed = JSON.parse(raw) as {\n\t\t\terror?: { code?: string; type?: string; message?: string; plan_type?: string; resets_at?: number };\n\t\t};\n\t\tconst err = parsed?.error;\n\t\tif (err) {\n\t\t\tconst code = err.code || err.type || \"\";\n\t\t\tif (/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(code) || response.status === 429) {\n\t\t\t\tconst plan = err.plan_type ? ` (${err.plan_type.toLowerCase()} plan)` : \"\";\n\t\t\t\tconst mins = err.resets_at\n\t\t\t\t\t? Math.max(0, Math.round((err.resets_at * 1000 - Date.now()) / 60000))\n\t\t\t\t\t: undefined;\n\t\t\t\tconst when = mins !== undefined ? ` Try again in ~${mins} min.` : \"\";\n\t\t\t\tfriendlyMessage = `You have hit your ChatGPT usage limit${plan}.${when}`.trim();\n\t\t\t}\n\t\t\tmessage = err.message || friendlyMessage || message;\n\t\t}\n\t} catch {}\n\n\treturn { message, friendlyMessage };\n}\n\n// ============================================================================\n// Auth & Headers\n// ============================================================================\n\nfunction extractAccountId(token: string): string {\n\ttry {\n\t\tconst parts = token.split(\".\");\n\t\tif (parts.length !== 3) throw new Error(\"Invalid token\");\n\t\tconst payload = JSON.parse(atob(parts[1]));\n\t\tconst accountId = payload?.[JWT_CLAIM_PATH]?.chatgpt_account_id;\n\t\tif (!accountId) throw new Error(\"No account ID in token\");\n\t\treturn accountId;\n\t} catch {\n\t\tthrow new Error(\"Failed to extract accountId from token\");\n\t}\n}\n\nfunction createCodexRequestId(): string {\n\tif (typeof globalThis.crypto?.randomUUID === \"function\") {\n\t\treturn globalThis.crypto.randomUUID();\n\t}\n\treturn `codex_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;\n}\n\nfunction buildBaseCodexHeaders(\n\tinitHeaders: Record<string, string> | undefined,\n\tadditionalHeaders: ProviderHeaders | undefined,\n\taccountId: string,\n\ttoken: string,\n): Headers {\n\tconst headers = new Headers(initHeaders);\n\tfor (const [key, value] of Object.entries(additionalHeaders || {})) {\n\t\tif (value === null) {\n\t\t\theaders.delete(key);\n\t\t} else {\n\t\t\theaders.set(key, value);\n\t\t}\n\t}\n\theaders.set(\"Authorization\", `Bearer ${token}`);\n\theaders.set(\"chatgpt-account-id\", accountId);\n\theaders.set(\"originator\", \"pi\");\n\tconst userAgent = _os ? `pi (${_os.platform()} ${_os.release()}; ${_os.arch()})` : \"pi (browser)\";\n\theaders.set(\"User-Agent\", userAgent);\n\treturn headers;\n}\n\nfunction buildSSEHeaders(\n\tinitHeaders: Record<string, string> | undefined,\n\tadditionalHeaders: ProviderHeaders | undefined,\n\taccountId: string,\n\ttoken: string,\n\tsessionId?: string,\n): Headers {\n\tconst headers = buildBaseCodexHeaders(initHeaders, additionalHeaders, accountId, token);\n\theaders.set(\"OpenAI-Beta\", \"responses=experimental\");\n\theaders.set(\"accept\", \"text/event-stream\");\n\theaders.set(\"content-type\", \"application/json\");\n\n\tif (sessionId) {\n\t\theaders.set(\"session-id\", sessionId);\n\t\theaders.set(\"x-client-request-id\", sessionId);\n\t}\n\n\treturn headers;\n}\n\nfunction buildWebSocketHeaders(\n\tinitHeaders: Record<string, string> | undefined,\n\tadditionalHeaders: ProviderHeaders | undefined,\n\taccountId: string,\n\ttoken: string,\n\trequestId: string,\n): Headers {\n\tconst headers = buildBaseCodexHeaders(initHeaders, additionalHeaders, accountId, token);\n\theaders.delete(\"accept\");\n\theaders.delete(\"content-type\");\n\theaders.delete(\"OpenAI-Beta\");\n\theaders.delete(\"openai-beta\");\n\theaders.set(\"OpenAI-Beta\", OPENAI_BETA_RESPONSES_WEBSOCKETS);\n\theaders.set(\"x-client-request-id\", requestId);\n\theaders.set(\"session-id\", requestId);\n\treturn headers;\n}\n"]}
@@ -161,8 +161,9 @@ export const stream = (model, context, options) => {
161
161
  if (nextBody !== undefined) {
162
162
  body = nextBody;
163
163
  }
164
- const websocketRequestId = options?.sessionId || createCodexRequestId();
165
- const sseHeaders = buildSSEHeaders(model.headers, options?.headers, accountId, apiKey, options?.sessionId);
164
+ const codexSessionId = clampOpenAIPromptCacheKey(options?.sessionId);
165
+ const websocketRequestId = codexSessionId || createCodexRequestId();
166
+ const sseHeaders = buildSSEHeaders(model.headers, options?.headers, accountId, apiKey, codexSessionId);
166
167
  const websocketHeaders = buildWebSocketHeaders(model.headers, options?.headers, accountId, apiKey, websocketRequestId);
167
168
  const bodyJson = JSON.stringify(body);
168
169
  const httpTimeoutMs = normalizeTimeoutMs(options?.timeoutMs);