@goah/cli 0.13.0 → 0.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/dist/LICENSE +201 -0
  2. package/dist/THIRD-PARTY-NOTICES.md +2319 -0
  3. package/dist/anthropic-messages-WBFOHES5.js +7214 -0
  4. package/dist/azure-openai-responses-NZFH3PO6.js +253 -0
  5. package/dist/chunk-25XSBFX6.js +639 -0
  6. package/dist/chunk-2QBQZGXF.js +110 -0
  7. package/dist/chunk-2ZP2NBW3.js +345 -0
  8. package/dist/chunk-4KA63VNZ.js +2 -0
  9. package/dist/chunk-4M6TXTT5.js +86 -0
  10. package/dist/chunk-4US7ZHT3.js +20 -0
  11. package/dist/chunk-6M3OOCKO.js +11809 -0
  12. package/dist/chunk-7AXAFDPG.js +17 -0
  13. package/dist/chunk-7E7V6OIU.js +920 -0
  14. package/dist/chunk-BXA47DTF.js +548 -0
  15. package/dist/chunk-D2DVAH37.js +25 -0
  16. package/dist/chunk-FSBUS2BI.js +26 -0
  17. package/dist/chunk-GKDRAHLI.js +4787 -0
  18. package/dist/chunk-H462EFJP.js +89 -0
  19. package/dist/chunk-IIJQ3DW4.js +35 -0
  20. package/dist/chunk-JQD5EWJY.js +34 -0
  21. package/dist/chunk-K26BVR6O.js +61 -0
  22. package/dist/chunk-KAO7WIXG.js +31 -0
  23. package/dist/chunk-KJ4HJCTK.js +1178 -0
  24. package/dist/chunk-LBKI23CC.js +9810 -0
  25. package/dist/chunk-LKBKZEHT.js +41 -0
  26. package/dist/chunk-MD7TLTXZ.js +18 -0
  27. package/dist/chunk-MPXK7QBL.js +868 -0
  28. package/dist/chunk-NRLGWZJC.js +11 -0
  29. package/dist/chunk-QBD6EJ2Z.js +1746 -0
  30. package/dist/chunk-R6I3VKME.js +132 -0
  31. package/dist/chunk-TJON22J4.js +87 -0
  32. package/dist/chunk-ULY36ME4.js +33097 -0
  33. package/dist/chunk-XALZLRYK.js +9221 -0
  34. package/dist/chunk-XPQKM3L7.js +57 -0
  35. package/dist/chunk-YH6YJ2IB.js +1773 -0
  36. package/dist/cli.d.ts +0 -2
  37. package/dist/cli.js +13716 -580
  38. package/dist/console/assets/{index-Rtc_B7cs.js → index-B1vGMXKr.js} +11 -11
  39. package/dist/console/assets/{index-Rtc_B7cs.js.map → index-B1vGMXKr.js.map} +1 -1
  40. package/dist/console/index.html +1 -1
  41. package/dist/dist-65MDQA4Q.js +1126 -0
  42. package/dist/dist-KNR2XL6J.js +39 -0
  43. package/dist/execution.d.ts +557 -2
  44. package/dist/execution.js +37 -2
  45. package/dist/faux-runner-worker.js +128 -0
  46. package/dist/google-generative-ai-YMHXZSFE.js +422 -0
  47. package/dist/google-vertex-X6DB3ZQ6.js +471 -0
  48. package/dist/index.d.ts +853 -25
  49. package/dist/index.js +84 -385
  50. package/dist/kernel.d.ts +39 -2
  51. package/dist/kernel.js +21 -2
  52. package/dist/mistral-conversations-TY3MMD6G.js +718 -0
  53. package/dist/multipart-parser-F6M4NJZU.js +373 -0
  54. package/dist/openai-codex-responses-BRDUMLN5.js +1374 -0
  55. package/dist/openai-completions-CX634XN3.js +1139 -0
  56. package/dist/openai-responses-HMCXJIHT.js +300 -0
  57. package/dist/openrouter-images-KTWET2H2.js +148 -0
  58. package/dist/pi-messages-XL5OEC4K.js +307 -0
  59. package/dist/pi-worker.js +671 -0
  60. package/dist/runner-pi.d.ts +342 -2
  61. package/dist/runner-pi.js +46 -2
  62. package/dist/runner-registry-GD4BYCQC.js +22 -0
  63. package/dist/sqlite.d.ts +446 -2
  64. package/dist/sqlite.js +15 -2
  65. package/dist/src-F2KBSV4T.js +1398 -0
  66. package/dist/supervisor.d.ts +625 -2
  67. package/dist/supervisor.js +39 -2
  68. package/dist/testkit.d.ts +564 -2
  69. package/dist/testkit.js +127 -2
  70. package/dist/transcript.d.ts +84 -2
  71. package/dist/transcript.js +25 -2
  72. package/dist/verification-worker.js +72 -0
  73. package/package.json +2 -26
  74. package/dist/cli.d.ts.map +0 -1
  75. package/dist/cli.js.map +0 -1
  76. package/dist/control.d.ts +0 -106
  77. package/dist/control.d.ts.map +0 -1
  78. package/dist/control.js +0 -242
  79. package/dist/control.js.map +0 -1
  80. package/dist/execution.d.ts.map +0 -1
  81. package/dist/execution.js.map +0 -1
  82. package/dist/index.d.ts.map +0 -1
  83. package/dist/index.js.map +0 -1
  84. package/dist/kernel.d.ts.map +0 -1
  85. package/dist/kernel.js.map +0 -1
  86. package/dist/live-config.d.ts +0 -10
  87. package/dist/live-config.d.ts.map +0 -1
  88. package/dist/live-config.js +0 -44
  89. package/dist/live-config.js.map +0 -1
  90. package/dist/prompt-queue.d.ts +0 -13
  91. package/dist/prompt-queue.d.ts.map +0 -1
  92. package/dist/prompt-queue.js +0 -35
  93. package/dist/prompt-queue.js.map +0 -1
  94. package/dist/runner-pi.d.ts.map +0 -1
  95. package/dist/runner-pi.js.map +0 -1
  96. package/dist/runner-registry.d.ts +0 -8
  97. package/dist/runner-registry.d.ts.map +0 -1
  98. package/dist/runner-registry.js +0 -12
  99. package/dist/runner-registry.js.map +0 -1
  100. package/dist/searchable-select.d.ts +0 -24
  101. package/dist/searchable-select.d.ts.map +0 -1
  102. package/dist/searchable-select.js +0 -61
  103. package/dist/searchable-select.js.map +0 -1
  104. package/dist/secret-input.d.ts +0 -8
  105. package/dist/secret-input.d.ts.map +0 -1
  106. package/dist/secret-input.js +0 -14
  107. package/dist/secret-input.js.map +0 -1
  108. package/dist/setup-wizard.d.ts +0 -22
  109. package/dist/setup-wizard.d.ts.map +0 -1
  110. package/dist/setup-wizard.js +0 -154
  111. package/dist/setup-wizard.js.map +0 -1
  112. package/dist/sqlite.d.ts.map +0 -1
  113. package/dist/sqlite.js.map +0 -1
  114. package/dist/supervisor.d.ts.map +0 -1
  115. package/dist/supervisor.js.map +0 -1
  116. package/dist/testkit.d.ts.map +0 -1
  117. package/dist/testkit.js.map +0 -1
  118. package/dist/thread-inspect.d.ts +0 -47
  119. package/dist/thread-inspect.d.ts.map +0 -1
  120. package/dist/thread-inspect.js +0 -78
  121. package/dist/thread-inspect.js.map +0 -1
  122. package/dist/transcript.d.ts.map +0 -1
  123. package/dist/transcript.js.map +0 -1
  124. package/dist/tui-theme.d.ts +0 -17
  125. package/dist/tui-theme.d.ts.map +0 -1
  126. package/dist/tui-theme.js +0 -19
  127. package/dist/tui-theme.js.map +0 -1
  128. package/dist/tui.d.ts +0 -24
  129. package/dist/tui.d.ts.map +0 -1
  130. package/dist/tui.js +0 -784
  131. package/dist/tui.js.map +0 -1
  132. package/dist/update.d.ts +0 -16
  133. package/dist/update.d.ts.map +0 -1
  134. package/dist/update.js +0 -67
  135. package/dist/update.js.map +0 -1
  136. package/dist/web-console.d.ts +0 -33
  137. package/dist/web-console.d.ts.map +0 -1
  138. package/dist/web-console.js +0 -242
  139. package/dist/web-console.js.map +0 -1
  140. package/dist/welcome.d.ts +0 -30
  141. package/dist/welcome.d.ts.map +0 -1
  142. package/dist/welcome.js +0 -69
  143. package/dist/welcome.js.map +0 -1
  144. package/node_modules/goah-ledger-contract/dist/execution.d.ts +0 -544
  145. package/node_modules/goah-ledger-contract/dist/execution.d.ts.map +0 -1
  146. package/node_modules/goah-ledger-contract/dist/execution.js +0 -52
  147. package/node_modules/goah-ledger-contract/dist/execution.js.map +0 -1
  148. package/node_modules/goah-ledger-contract/dist/index.d.ts +0 -4
  149. package/node_modules/goah-ledger-contract/dist/index.d.ts.map +0 -1
  150. package/node_modules/goah-ledger-contract/dist/index.js +0 -4
  151. package/node_modules/goah-ledger-contract/dist/index.js.map +0 -1
  152. package/node_modules/goah-ledger-contract/dist/kernel.d.ts +0 -37
  153. package/node_modules/goah-ledger-contract/dist/kernel.d.ts.map +0 -1
  154. package/node_modules/goah-ledger-contract/dist/kernel.js +0 -8
  155. package/node_modules/goah-ledger-contract/dist/kernel.js.map +0 -1
  156. package/node_modules/goah-ledger-contract/dist/transcript.d.ts +0 -63
  157. package/node_modules/goah-ledger-contract/dist/transcript.d.ts.map +0 -1
  158. package/node_modules/goah-ledger-contract/dist/transcript.js +0 -115
  159. package/node_modules/goah-ledger-contract/dist/transcript.js.map +0 -1
  160. package/node_modules/goah-ledger-contract/package.json +0 -28
  161. package/node_modules/goah-ledger-sqlite/dist/index.d.ts +0 -86
  162. package/node_modules/goah-ledger-sqlite/dist/index.d.ts.map +0 -1
  163. package/node_modules/goah-ledger-sqlite/dist/index.js +0 -1254
  164. package/node_modules/goah-ledger-sqlite/dist/index.js.map +0 -1
  165. package/node_modules/goah-ledger-sqlite/package.json +0 -26
  166. package/node_modules/goah-runner-pi/dist/configurator.d.ts +0 -20
  167. package/node_modules/goah-runner-pi/dist/configurator.d.ts.map +0 -1
  168. package/node_modules/goah-runner-pi/dist/configurator.js +0 -423
  169. package/node_modules/goah-runner-pi/dist/configurator.js.map +0 -1
  170. package/node_modules/goah-runner-pi/dist/credential-store.d.ts +0 -14
  171. package/node_modules/goah-runner-pi/dist/credential-store.d.ts.map +0 -1
  172. package/node_modules/goah-runner-pi/dist/credential-store.js +0 -163
  173. package/node_modules/goah-runner-pi/dist/credential-store.js.map +0 -1
  174. package/node_modules/goah-runner-pi/dist/env-spec.d.ts +0 -17
  175. package/node_modules/goah-runner-pi/dist/env-spec.d.ts.map +0 -1
  176. package/node_modules/goah-runner-pi/dist/env-spec.js +0 -95
  177. package/node_modules/goah-runner-pi/dist/env-spec.js.map +0 -1
  178. package/node_modules/goah-runner-pi/dist/index.d.ts +0 -76
  179. package/node_modules/goah-runner-pi/dist/index.d.ts.map +0 -1
  180. package/node_modules/goah-runner-pi/dist/index.js +0 -326
  181. package/node_modules/goah-runner-pi/dist/index.js.map +0 -1
  182. package/node_modules/goah-runner-pi/dist/model-provider.d.ts +0 -30
  183. package/node_modules/goah-runner-pi/dist/model-provider.d.ts.map +0 -1
  184. package/node_modules/goah-runner-pi/dist/model-provider.js +0 -96
  185. package/node_modules/goah-runner-pi/dist/model-provider.js.map +0 -1
  186. package/node_modules/goah-runner-pi/dist/pi-worker.d.ts +0 -31
  187. package/node_modules/goah-runner-pi/dist/pi-worker.d.ts.map +0 -1
  188. package/node_modules/goah-runner-pi/dist/pi-worker.js +0 -579
  189. package/node_modules/goah-runner-pi/dist/pi-worker.js.map +0 -1
  190. package/node_modules/goah-runner-pi/dist/steering-no-ack.test-fixture.d.ts +0 -2
  191. package/node_modules/goah-runner-pi/dist/steering-no-ack.test-fixture.d.ts.map +0 -1
  192. package/node_modules/goah-runner-pi/dist/steering-no-ack.test-fixture.js +0 -3
  193. package/node_modules/goah-runner-pi/dist/steering-no-ack.test-fixture.js.map +0 -1
  194. package/node_modules/goah-runner-pi/dist/steering-reject.test-fixture.d.ts +0 -2
  195. package/node_modules/goah-runner-pi/dist/steering-reject.test-fixture.d.ts.map +0 -1
  196. package/node_modules/goah-runner-pi/dist/steering-reject.test-fixture.js +0 -5
  197. package/node_modules/goah-runner-pi/dist/steering-reject.test-fixture.js.map +0 -1
  198. package/node_modules/goah-runner-pi/dist/steering-worker.test-fixture.d.ts +0 -2
  199. package/node_modules/goah-runner-pi/dist/steering-worker.test-fixture.d.ts.map +0 -1
  200. package/node_modules/goah-runner-pi/dist/steering-worker.test-fixture.js +0 -5
  201. package/node_modules/goah-runner-pi/dist/steering-worker.test-fixture.js.map +0 -1
  202. package/node_modules/goah-runner-pi/dist/test-helpers.d.ts +0 -4
  203. package/node_modules/goah-runner-pi/dist/test-helpers.d.ts.map +0 -1
  204. package/node_modules/goah-runner-pi/dist/test-helpers.js +0 -13
  205. package/node_modules/goah-runner-pi/dist/test-helpers.js.map +0 -1
  206. package/node_modules/goah-runner-pi/dist/verification-worker.d.ts +0 -2
  207. package/node_modules/goah-runner-pi/dist/verification-worker.d.ts.map +0 -1
  208. package/node_modules/goah-runner-pi/dist/verification-worker.js +0 -46
  209. package/node_modules/goah-runner-pi/dist/verification-worker.js.map +0 -1
  210. package/node_modules/goah-runner-pi/package.json +0 -28
  211. package/node_modules/goah-supervisor/dist/context-view.d.ts +0 -30
  212. package/node_modules/goah-supervisor/dist/context-view.d.ts.map +0 -1
  213. package/node_modules/goah-supervisor/dist/context-view.js +0 -58
  214. package/node_modules/goah-supervisor/dist/context-view.js.map +0 -1
  215. package/node_modules/goah-supervisor/dist/index.d.ts +0 -96
  216. package/node_modules/goah-supervisor/dist/index.d.ts.map +0 -1
  217. package/node_modules/goah-supervisor/dist/index.js +0 -1075
  218. package/node_modules/goah-supervisor/dist/index.js.map +0 -1
  219. package/node_modules/goah-supervisor/dist/roles.d.ts +0 -4
  220. package/node_modules/goah-supervisor/dist/roles.d.ts.map +0 -1
  221. package/node_modules/goah-supervisor/dist/roles.js +0 -29
  222. package/node_modules/goah-supervisor/dist/roles.js.map +0 -1
  223. package/node_modules/goah-supervisor/dist/verification.d.ts +0 -61
  224. package/node_modules/goah-supervisor/dist/verification.d.ts.map +0 -1
  225. package/node_modules/goah-supervisor/dist/verification.js +0 -135
  226. package/node_modules/goah-supervisor/dist/verification.js.map +0 -1
  227. package/node_modules/goah-supervisor/package.json +0 -26
  228. package/node_modules/goah-testkit/dist/faux-runner-worker.d.ts +0 -2
  229. package/node_modules/goah-testkit/dist/faux-runner-worker.d.ts.map +0 -1
  230. package/node_modules/goah-testkit/dist/faux-runner-worker.js +0 -82
  231. package/node_modules/goah-testkit/dist/faux-runner-worker.js.map +0 -1
  232. package/node_modules/goah-testkit/dist/index.d.ts +0 -49
  233. package/node_modules/goah-testkit/dist/index.d.ts.map +0 -1
  234. package/node_modules/goah-testkit/dist/index.js +0 -96
  235. package/node_modules/goah-testkit/dist/index.js.map +0 -1
  236. package/node_modules/goah-testkit/package.json +0 -29
@@ -0,0 +1,1374 @@
1
+ import { createRequire as __goahCreateRequire } from "node:module";
2
+ const require = __goahCreateRequire(import.meta.url);
3
+ import {
4
+ getPiUserAgent
5
+ } from "./chunk-MD7TLTXZ.js";
6
+ import {
7
+ splitDeferredTools
8
+ } from "./chunk-LKBKZEHT.js";
9
+ import {
10
+ convertResponsesMessages,
11
+ convertResponsesTools,
12
+ processResponsesStream
13
+ } from "./chunk-25XSBFX6.js";
14
+ import {
15
+ clampOpenAIPromptCacheKey
16
+ } from "./chunk-7AXAFDPG.js";
17
+ import "./chunk-4US7ZHT3.js";
18
+ import {
19
+ formatProviderError,
20
+ normalizeProviderError
21
+ } from "./chunk-H462EFJP.js";
22
+ import {
23
+ buildBaseOptions,
24
+ createGrammarToolInputProperties
25
+ } from "./chunk-BXA47DTF.js";
26
+ import "./chunk-NRLGWZJC.js";
27
+ import {
28
+ headersToRecord
29
+ } from "./chunk-FSBUS2BI.js";
30
+ import {
31
+ registerSessionResourceCleanup,
32
+ uuidv7
33
+ } from "./chunk-K26BVR6O.js";
34
+ import {
35
+ getProviderEnvValue
36
+ } from "./chunk-IIJQ3DW4.js";
37
+ import "./chunk-2ZP2NBW3.js";
38
+ import {
39
+ clampThinkingLevel
40
+ } from "./chunk-MPXK7QBL.js";
41
+ import {
42
+ AssistantMessageEventStream,
43
+ appendAssistantMessageDiagnostic,
44
+ createAssistantMessageDiagnostic,
45
+ formatThrownValue
46
+ } from "./chunk-2QBQZGXF.js";
47
+ import "./chunk-XPQKM3L7.js";
48
+
49
+ // ../../node_modules/@earendil-works/pi-ai/dist/utils/abort-signals.js
50
+ function combineAbortSignals(signals) {
51
+ const activeSignals = signals.filter((signal) => signal !== void 0);
52
+ if (activeSignals.length === 0) {
53
+ return { cleanup: () => {
54
+ } };
55
+ }
56
+ if (activeSignals.length === 1) {
57
+ return { signal: activeSignals[0], cleanup: () => {
58
+ } };
59
+ }
60
+ const controller = new AbortController();
61
+ const listeners = [];
62
+ const abort = (signal) => {
63
+ if (!controller.signal.aborted) {
64
+ controller.abort(signal.reason);
65
+ }
66
+ };
67
+ for (const signal of activeSignals) {
68
+ if (signal.aborted) {
69
+ abort(signal);
70
+ break;
71
+ }
72
+ const listener = () => abort(signal);
73
+ signal.addEventListener("abort", listener, { once: true });
74
+ listeners.push({ signal, listener });
75
+ }
76
+ return {
77
+ signal: controller.signal,
78
+ cleanup: () => {
79
+ for (const { signal, listener } of listeners) {
80
+ signal.removeEventListener("abort", listener);
81
+ }
82
+ }
83
+ };
84
+ }
85
+
86
+ // ../../node_modules/@earendil-works/pi-ai/dist/utils/node-http-proxy.js
87
+ var DEFAULT_PROXY_PORTS = {
88
+ ftp: 21,
89
+ gopher: 70,
90
+ http: 80,
91
+ https: 443,
92
+ ws: 80,
93
+ wss: 443
94
+ };
95
+ function getProxyEnv(key, env) {
96
+ const lowercaseKey = key.toLowerCase();
97
+ const uppercaseKey = key.toUpperCase();
98
+ return env?.[lowercaseKey] || env?.[uppercaseKey] || getProviderEnvValue(lowercaseKey) || getProviderEnvValue(uppercaseKey) || "";
99
+ }
100
+ function parseProxyTargetUrl(targetUrl) {
101
+ if (targetUrl instanceof URL) {
102
+ return targetUrl;
103
+ }
104
+ try {
105
+ return new URL(targetUrl);
106
+ } catch {
107
+ return void 0;
108
+ }
109
+ }
110
+ function shouldProxyHostname(hostname, port, env) {
111
+ const noProxy = getProxyEnv("no_proxy", env).toLowerCase();
112
+ if (!noProxy) {
113
+ return true;
114
+ }
115
+ if (noProxy === "*") {
116
+ return false;
117
+ }
118
+ return noProxy.split(/[,\s]/).every((proxy) => {
119
+ if (!proxy) {
120
+ return true;
121
+ }
122
+ const parsedProxy = proxy.match(/^(.+):(\d+)$/);
123
+ let proxyHostname = parsedProxy ? parsedProxy[1] : proxy;
124
+ const proxyPort = parsedProxy ? Number.parseInt(parsedProxy[2], 10) : 0;
125
+ if (proxyPort && proxyPort !== port) {
126
+ return true;
127
+ }
128
+ if (!/^[.*]/.test(proxyHostname)) {
129
+ return hostname !== proxyHostname;
130
+ }
131
+ if (proxyHostname.startsWith("*")) {
132
+ proxyHostname = proxyHostname.slice(1);
133
+ }
134
+ return !hostname.endsWith(proxyHostname);
135
+ });
136
+ }
137
+ function getProxyForUrl(targetUrl, env) {
138
+ const parsedUrl = parseProxyTargetUrl(targetUrl);
139
+ if (!parsedUrl?.protocol || !parsedUrl.host) {
140
+ return "";
141
+ }
142
+ const protocol = parsedUrl.protocol.split(":", 1)[0];
143
+ const hostname = parsedUrl.host.replace(/:\d*$/, "");
144
+ const port = Number.parseInt(parsedUrl.port, 10) || DEFAULT_PROXY_PORTS[protocol] || 0;
145
+ if (!shouldProxyHostname(hostname, port, env)) {
146
+ return "";
147
+ }
148
+ let proxy = getProxyEnv(`${protocol}_proxy`, env) || getProxyEnv("all_proxy", env);
149
+ if (proxy && !proxy.includes("://")) {
150
+ proxy = `${protocol}://${proxy}`;
151
+ }
152
+ return proxy;
153
+ }
154
+ var UNSUPPORTED_PROXY_PROTOCOL_MESSAGE = "Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";
155
+ function resolveHttpProxyUrlForTarget(targetUrl, env) {
156
+ const proxy = getProxyForUrl(targetUrl, env);
157
+ if (!proxy) {
158
+ return void 0;
159
+ }
160
+ let proxyUrl;
161
+ try {
162
+ proxyUrl = new URL(proxy);
163
+ } catch (error) {
164
+ throw new Error(`Invalid proxy URL ${JSON.stringify(proxy)}: ${error instanceof Error ? error.message : String(error)}`);
165
+ }
166
+ if (proxyUrl.protocol !== "http:" && proxyUrl.protocol !== "https:") {
167
+ throw new Error(`${UNSUPPORTED_PROXY_PROTOCOL_MESSAGE} Got ${proxyUrl.protocol}`);
168
+ }
169
+ return proxyUrl;
170
+ }
171
+
172
+ // ../../node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js
173
+ var DEFAULT_CODEX_BASE_URL = "https://chatgpt.com/backend-api";
174
+ var JWT_CLAIM_PATH = "https://api.openai.com/auth";
175
+ var DEFAULT_MAX_RETRIES = 0;
176
+ var BASE_DELAY_MS = 1e3;
177
+ var DEFAULT_MAX_RETRY_DELAY_MS = 6e4;
178
+ var DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS = 15e3;
179
+ var REQUEST_COMPRESSION_ZSTD_LEVEL = 3;
180
+ var CODEX_TOOL_CALL_PROVIDERS = /* @__PURE__ */ new Set(["openai", "openai-codex", "opencode"]);
181
+ var WEBSOCKET_MESSAGE_TOO_BIG_CLOSE_CODE = 1009;
182
+ var WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE = "websocket_connection_limit_reached";
183
+ var PREVIOUS_RESPONSE_NOT_FOUND_CODE = "previous_response_not_found";
184
+ var CODEX_RESPONSE_STATUSES = /* @__PURE__ */ new Set([
185
+ "completed",
186
+ "incomplete",
187
+ "failed",
188
+ "cancelled",
189
+ "queued",
190
+ "in_progress"
191
+ ]);
192
+ function assertSuccessfulOutput(output) {
193
+ if (output.stopReason === "pending") {
194
+ throw new Error("Codex stream ended without a stop reason");
195
+ }
196
+ if (output.stopReason === "error" || output.stopReason === "aborted") {
197
+ throw new Error(output.errorMessage || "An unknown error occurred");
198
+ }
199
+ }
200
+ function isTerminalRateLimitError(errorText) {
201
+ return /GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(errorText);
202
+ }
203
+ function isRetryableError(status, errorText) {
204
+ if (status === 429 && isTerminalRateLimitError(errorText)) {
205
+ return false;
206
+ }
207
+ if (status === 429 || status === 500 || status === 502 || status === 503 || status === 504) {
208
+ return true;
209
+ }
210
+ return /rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(errorText);
211
+ }
212
+ function getRetryAfterDelayMs(headers) {
213
+ const retryAfterMs = headers.get("retry-after-ms");
214
+ if (retryAfterMs !== null) {
215
+ const millis = Number(retryAfterMs);
216
+ if (Number.isFinite(millis)) {
217
+ return Math.max(0, millis);
218
+ }
219
+ }
220
+ const retryAfter = headers.get("retry-after");
221
+ if (!retryAfter) {
222
+ return void 0;
223
+ }
224
+ const seconds = Number(retryAfter);
225
+ if (Number.isFinite(seconds)) {
226
+ return Math.max(0, seconds * 1e3);
227
+ }
228
+ const date = Date.parse(retryAfter);
229
+ if (!Number.isNaN(date)) {
230
+ return Math.max(0, date - Date.now());
231
+ }
232
+ return void 0;
233
+ }
234
+ var RetryDelayExceededError = class extends Error {
235
+ };
236
+ function validateRetryDelayMs(delayMs, options) {
237
+ const maxRetryDelayMs = options?.maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;
238
+ if (maxRetryDelayMs > 0 && delayMs > maxRetryDelayMs) {
239
+ throw new RetryDelayExceededError(`Server requested ${Math.ceil(delayMs / 1e3)}s retry delay (max: ${Math.ceil(maxRetryDelayMs / 1e3)}s)`);
240
+ }
241
+ return delayMs;
242
+ }
243
+ function sleep(ms, signal) {
244
+ return new Promise((resolve, reject) => {
245
+ if (signal?.aborted) {
246
+ reject(new Error("Request was aborted"));
247
+ return;
248
+ }
249
+ const timeout = setTimeout(resolve, ms);
250
+ signal?.addEventListener("abort", () => {
251
+ clearTimeout(timeout);
252
+ reject(new Error("Request was aborted"));
253
+ });
254
+ });
255
+ }
256
+ function normalizeTimeoutMs(value) {
257
+ if (value === void 0)
258
+ return void 0;
259
+ if (!Number.isFinite(value) || value < 0) {
260
+ throw new Error(`Invalid timeoutMs: ${String(value)}`);
261
+ }
262
+ return Math.floor(value);
263
+ }
264
+ function loadNodeZlib() {
265
+ if (typeof process === "undefined" || !(process.versions?.node || process.versions?.bun)) {
266
+ return null;
267
+ }
268
+ return process.getBuiltinModule?.("node:zlib") ?? null;
269
+ }
270
+ function compressRequestBodyZstd(bodyJson) {
271
+ const zlib = loadNodeZlib();
272
+ if (!zlib || typeof zlib.zstdCompressSync !== "function") {
273
+ return null;
274
+ }
275
+ try {
276
+ const compressed = zlib.zstdCompressSync(bodyJson, {
277
+ params: { [zlib.constants.ZSTD_c_compressionLevel]: REQUEST_COMPRESSION_ZSTD_LEVEL }
278
+ });
279
+ return new Uint8Array(compressed.buffer, compressed.byteOffset, compressed.byteLength);
280
+ } catch {
281
+ return null;
282
+ }
283
+ }
284
+ var stream = (model, context, options) => {
285
+ const stream2 = new AssistantMessageEventStream();
286
+ (async () => {
287
+ const output = {
288
+ role: "assistant",
289
+ content: [],
290
+ api: "openai-codex-responses",
291
+ provider: model.provider,
292
+ model: model.id,
293
+ usage: {
294
+ input: 0,
295
+ output: 0,
296
+ cacheRead: 0,
297
+ cacheWrite: 0,
298
+ totalTokens: 0,
299
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }
300
+ },
301
+ stopReason: "pending",
302
+ timestamp: Date.now()
303
+ };
304
+ try {
305
+ const apiKey = options?.apiKey;
306
+ if (!apiKey) {
307
+ throw new Error(`No API key for provider: ${model.provider}`);
308
+ }
309
+ const accountId = extractAccountId(apiKey);
310
+ const grammarToolInputProperties = createGrammarToolInputProperties(context.tools, model.compat?.supportsOpenAIGrammarTools ?? false);
311
+ const cacheSessionId = options?.cacheRetention === "none" ? void 0 : options?.sessionId;
312
+ const codexSessionId = clampOpenAIPromptCacheKey(cacheSessionId);
313
+ let body = buildRequestBody(model, context, options, codexSessionId, grammarToolInputProperties);
314
+ const nextBody = await options?.onPayload?.(body, model);
315
+ if (nextBody !== void 0) {
316
+ body = nextBody;
317
+ }
318
+ const websocketRequestId = codexSessionId || uuidv7();
319
+ const sseHeaders = buildSSEHeaders(model.headers, options?.headers, accountId, apiKey, codexSessionId);
320
+ const websocketHeaders = buildWebSocketHeaders(model.headers, options?.headers, accountId, apiKey, websocketRequestId);
321
+ const bodyJson = JSON.stringify(body);
322
+ const httpTimeoutMs = normalizeTimeoutMs(options?.timeoutMs);
323
+ const websocketConnectTimeoutMs = normalizeTimeoutMs(options?.websocketConnectTimeoutMs);
324
+ const transport = options?.transport || "auto";
325
+ let startEmitted = false;
326
+ const websocketDisabledForSession = transport !== "sse" && isWebSocketSseFallbackActive(cacheSessionId);
327
+ if (websocketDisabledForSession) {
328
+ recordWebSocketSseFallback(cacheSessionId);
329
+ }
330
+ if (transport !== "sse" && !websocketDisabledForSession) {
331
+ let websocketStarted = false;
332
+ let retriedWebSocketConnectionLimit = false;
333
+ let retriedMissingWebSocketContinuation = false;
334
+ while (true) {
335
+ websocketStarted = false;
336
+ try {
337
+ await processWebSocketStream(resolveCodexWebSocketUrl(model.baseUrl), body, websocketHeaders, output, stream2, model, () => {
338
+ websocketStarted = true;
339
+ if (!startEmitted) {
340
+ startEmitted = true;
341
+ stream2.push({ type: "start", partial: output });
342
+ }
343
+ }, httpTimeoutMs, websocketConnectTimeoutMs, cacheSessionId, accountId, grammarToolInputProperties, options);
344
+ if (options?.signal?.aborted) {
345
+ throw new Error("Request was aborted");
346
+ }
347
+ assertSuccessfulOutput(output);
348
+ stream2.push({
349
+ type: "done",
350
+ reason: output.stopReason,
351
+ message: output
352
+ });
353
+ stream2.end();
354
+ return;
355
+ } catch (error) {
356
+ const aborted = options?.signal?.aborted;
357
+ const connectionLimitBeforeStart = !websocketStarted && isWebSocketConnectionLimitReachedError(error);
358
+ const previousResponseNotFound = isPreviousResponseNotFoundError(error);
359
+ if (!aborted && previousResponseNotFound && !retriedMissingWebSocketContinuation) {
360
+ retriedMissingWebSocketContinuation = true;
361
+ continue;
362
+ }
363
+ if (!aborted && connectionLimitBeforeStart && !retriedWebSocketConnectionLimit) {
364
+ retriedWebSocketConnectionLimit = true;
365
+ continue;
366
+ }
367
+ if (aborted || isCodexNonTransportError(error) && !connectionLimitBeforeStart) {
368
+ throw error;
369
+ }
370
+ appendAssistantMessageDiagnostic(output, createAssistantMessageDiagnostic("provider_transport_failure", error, {
371
+ configuredTransport: transport,
372
+ fallbackTransport: websocketStarted ? void 0 : "sse",
373
+ eventsEmitted: websocketStarted,
374
+ phase: websocketStarted ? "after_message_stream_start" : "before_message_stream_start",
375
+ requestBytes: new TextEncoder().encode(bodyJson).byteLength
376
+ }));
377
+ recordWebSocketFailure(cacheSessionId, error);
378
+ if (websocketStarted) {
379
+ throw error;
380
+ }
381
+ recordWebSocketSseFallback(cacheSessionId);
382
+ break;
383
+ }
384
+ }
385
+ }
386
+ const compressedBody = compressRequestBodyZstd(bodyJson);
387
+ if (compressedBody) {
388
+ sseHeaders.set("content-encoding", "zstd");
389
+ }
390
+ const sseBody = compressedBody ?? bodyJson;
391
+ let response;
392
+ let lastError;
393
+ const maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES;
394
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
395
+ if (options?.signal?.aborted) {
396
+ throw new Error("Request was aborted");
397
+ }
398
+ try {
399
+ const headerTimeoutSignal = httpTimeoutMs !== void 0 && httpTimeoutMs > 0 ? AbortSignal.timeout(httpTimeoutMs) : void 0;
400
+ const combinedSignal = combineAbortSignals([options?.signal, headerTimeoutSignal]);
401
+ try {
402
+ response = await (options?.fetch ?? globalThis.fetch)(resolveCodexUrl(model.baseUrl), {
403
+ method: "POST",
404
+ headers: sseHeaders,
405
+ body: sseBody,
406
+ signal: combinedSignal.signal
407
+ });
408
+ } catch (error) {
409
+ if (headerTimeoutSignal?.aborted && !options?.signal?.aborted) {
410
+ throw new Error(`Codex SSE response headers timed out after ${httpTimeoutMs}ms`);
411
+ }
412
+ throw error;
413
+ } finally {
414
+ combinedSignal.cleanup();
415
+ }
416
+ await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);
417
+ if (response.ok) {
418
+ break;
419
+ }
420
+ const errorText = await response.text();
421
+ if (attempt < maxRetries && isRetryableError(response.status, errorText)) {
422
+ const retryAfterDelayMs = getRetryAfterDelayMs(response.headers);
423
+ const delayMs = retryAfterDelayMs === void 0 ? BASE_DELAY_MS * 2 ** attempt : validateRetryDelayMs(retryAfterDelayMs, options);
424
+ await sleep(delayMs, options?.signal);
425
+ continue;
426
+ }
427
+ const fakeResponse = new Response(errorText, {
428
+ status: response.status,
429
+ statusText: response.statusText
430
+ });
431
+ const info = await parseErrorResponse(fakeResponse);
432
+ throw new Error(info.friendlyMessage || info.message);
433
+ } catch (error) {
434
+ if (error instanceof Error) {
435
+ if (error.name === "AbortError" || error.message === "Request was aborted") {
436
+ throw new Error("Request was aborted");
437
+ }
438
+ }
439
+ lastError = error instanceof Error ? error : new Error(String(error));
440
+ if (attempt < maxRetries && !(lastError instanceof RetryDelayExceededError) && !lastError.message.includes("usage limit")) {
441
+ const delayMs = BASE_DELAY_MS * 2 ** attempt;
442
+ await sleep(delayMs, options?.signal);
443
+ continue;
444
+ }
445
+ throw lastError;
446
+ }
447
+ }
448
+ if (!response?.ok) {
449
+ throw lastError ?? new Error("Failed after retries");
450
+ }
451
+ if (!response.body) {
452
+ throw new Error("No response body");
453
+ }
454
+ if (!startEmitted) {
455
+ startEmitted = true;
456
+ stream2.push({ type: "start", partial: output });
457
+ }
458
+ await processStream(response, output, stream2, model, grammarToolInputProperties, options);
459
+ if (options?.signal?.aborted) {
460
+ throw new Error("Request was aborted");
461
+ }
462
+ assertSuccessfulOutput(output);
463
+ stream2.push({ type: "done", reason: output.stopReason, message: output });
464
+ stream2.end();
465
+ } catch (error) {
466
+ for (const block of output.content) {
467
+ delete block.partialJson;
468
+ delete block.customInput;
469
+ }
470
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
471
+ output.errorMessage = formatProviderError(normalizeProviderError(error));
472
+ stream2.push({ type: "error", reason: output.stopReason, error: output });
473
+ stream2.end();
474
+ }
475
+ })();
476
+ return stream2;
477
+ };
478
+ var streamSimple = (model, context, options) => {
479
+ const apiKey = options?.apiKey;
480
+ if (!apiKey) {
481
+ throw new Error(`No API key for provider: ${model.provider}`);
482
+ }
483
+ const base = buildBaseOptions(model, context, options, apiKey);
484
+ const clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : void 0;
485
+ const reasoningEffort = clampedReasoning === "off" ? void 0 : clampedReasoning;
486
+ return stream(model, context, {
487
+ ...base,
488
+ reasoningEffort
489
+ });
490
+ };
491
+ function buildRequestBody(model, context, options, cacheSessionId, grammarToolInputProperties = createGrammarToolInputProperties(context.tools, model.compat?.supportsOpenAIGrammarTools ?? false)) {
492
+ const supportsStrictMode = model.compat?.supportsStrictMode ?? true;
493
+ const supportsOpenAIGrammarTools = model.compat?.supportsOpenAIGrammarTools ?? false;
494
+ const deferredToolsMode = model.compat?.supportsAdditionalTools ? "additional-tools" : model.compat?.supportsToolSearch ? "tool-search" : void 0;
495
+ const toolPlacement = splitDeferredTools(context, deferredToolsMode !== void 0);
496
+ const messages = convertResponsesMessages(model, context, CODEX_TOOL_CALL_PROVIDERS, {
497
+ includeSystemPrompt: false,
498
+ grammarToolInputProperties,
499
+ deferredTools: toolPlacement.deferred,
500
+ deferredToolsMode,
501
+ toolOptions: {
502
+ strict: null,
503
+ supportsStrictMode,
504
+ supportsOpenAIGrammarTools
505
+ }
506
+ });
507
+ const body = {
508
+ model: model.id,
509
+ store: false,
510
+ stream: true,
511
+ instructions: context.systemPrompt || "You are a helpful assistant.",
512
+ input: messages,
513
+ text: { verbosity: options?.textVerbosity || "low" },
514
+ include: ["reasoning.encrypted_content"],
515
+ prompt_cache_key: cacheSessionId,
516
+ tool_choice: options?.toolChoice ?? "auto",
517
+ parallel_tool_calls: true
518
+ };
519
+ if (options?.temperature !== void 0) {
520
+ body.temperature = options.temperature;
521
+ }
522
+ if (options?.serviceTier !== void 0) {
523
+ body.service_tier = options.serviceTier;
524
+ }
525
+ if (toolPlacement.immediate.length > 0) {
526
+ body.tools = convertResponsesTools(toolPlacement.immediate, {
527
+ strict: null,
528
+ supportsStrictMode,
529
+ supportsOpenAIGrammarTools
530
+ });
531
+ }
532
+ if (options?.reasoningEffort !== void 0) {
533
+ const effort = options.reasoningEffort === "none" ? model.thinkingLevelMap?.off ?? "none" : model.thinkingLevelMap?.[options.reasoningEffort] ?? options.reasoningEffort;
534
+ if (effort !== null) {
535
+ body.reasoning = {
536
+ effort,
537
+ summary: options.reasoningSummary ?? "auto"
538
+ };
539
+ }
540
+ }
541
+ return body;
542
+ }
543
+ function getServiceTierCostMultiplier(model, serviceTier) {
544
+ switch (serviceTier) {
545
+ case "flex":
546
+ return 0.5;
547
+ case "priority":
548
+ return model.id === "gpt-5.5" ? 2.5 : 2;
549
+ default:
550
+ return 1;
551
+ }
552
+ }
553
+ function applyServiceTierPricing(usage, serviceTier, model) {
554
+ const multiplier = getServiceTierCostMultiplier(model, serviceTier);
555
+ if (multiplier === 1)
556
+ return;
557
+ usage.cost.input *= multiplier;
558
+ usage.cost.output *= multiplier;
559
+ usage.cost.cacheRead *= multiplier;
560
+ usage.cost.cacheWrite *= multiplier;
561
+ usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
562
+ }
563
+ function resolveCodexServiceTier(responseServiceTier, requestServiceTier) {
564
+ if (responseServiceTier === "default" && (requestServiceTier === "flex" || requestServiceTier === "priority")) {
565
+ return requestServiceTier;
566
+ }
567
+ return responseServiceTier ?? requestServiceTier;
568
+ }
569
+ function resolveCodexUrl(baseUrl) {
570
+ const raw = baseUrl && baseUrl.trim().length > 0 ? baseUrl : DEFAULT_CODEX_BASE_URL;
571
+ const normalized = raw.replace(/\/+$/, "");
572
+ if (normalized.endsWith("/codex/responses"))
573
+ return normalized;
574
+ if (normalized.endsWith("/codex"))
575
+ return `${normalized}/responses`;
576
+ return `${normalized}/codex/responses`;
577
+ }
578
+ function resolveCodexWebSocketUrl(baseUrl) {
579
+ const url = new URL(resolveCodexUrl(baseUrl));
580
+ if (url.protocol === "https:")
581
+ url.protocol = "wss:";
582
+ if (url.protocol === "http:")
583
+ url.protocol = "ws:";
584
+ return url.toString();
585
+ }
586
+ async function processStream(response, output, stream2, model, grammarToolInputProperties, options) {
587
+ await processResponsesStream(mapCodexEvents(parseSSE(response, options?.signal), output), output, stream2, model, {
588
+ serviceTier: options?.serviceTier,
589
+ grammarToolInputProperties,
590
+ resolveServiceTier: resolveCodexServiceTier,
591
+ applyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model)
592
+ });
593
+ }
594
+ var CodexApiError = class extends Error {
595
+ code;
596
+ payload;
597
+ constructor(message, options) {
598
+ super(message);
599
+ this.name = "CodexApiError";
600
+ this.code = options?.code;
601
+ this.payload = options?.payload;
602
+ this.cause = options?.cause;
603
+ }
604
+ };
605
+ var CodexProtocolError = class extends Error {
606
+ payload;
607
+ constructor(message, options) {
608
+ super(message);
609
+ this.name = "CodexProtocolError";
610
+ this.payload = options?.payload;
611
+ this.cause = options?.cause;
612
+ }
613
+ };
614
+ function isCodexNonTransportError(error) {
615
+ return error instanceof CodexApiError || error instanceof CodexProtocolError;
616
+ }
617
+ function isWebSocketConnectionLimitReachedError(error) {
618
+ return error instanceof CodexApiError && error.code === WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE;
619
+ }
620
+ function isPreviousResponseNotFoundError(error) {
621
+ return error instanceof CodexApiError && error.code === PREVIOUS_RESPONSE_NOT_FOUND_CODE;
622
+ }
623
+ function extractCodexEventError(event) {
624
+ const nested = event.error && typeof event.error === "object" ? event.error : void 0;
625
+ return {
626
+ code: typeof event.code === "string" ? event.code : typeof nested?.code === "string" ? nested.code : void 0,
627
+ message: typeof event.message === "string" ? event.message : typeof nested?.message === "string" ? nested.message : void 0
628
+ };
629
+ }
630
+ async function* mapCodexEvents(events, output) {
631
+ for await (const event of events) {
632
+ const type = typeof event.type === "string" ? event.type : void 0;
633
+ if (!type)
634
+ continue;
635
+ if (type === "error") {
636
+ const { code, message } = extractCodexEventError(event);
637
+ throw new CodexApiError(`Codex error: ${message || code || JSON.stringify(event)}`, {
638
+ code,
639
+ payload: event
640
+ });
641
+ }
642
+ if (type === "response.failed") {
643
+ const response = event.response;
644
+ const code = response?.error?.code;
645
+ const message = response?.error?.message;
646
+ throw new CodexApiError(message || "Codex response failed", { code, payload: event });
647
+ }
648
+ if (type === "response.done" || type === "response.completed" || type === "response.incomplete") {
649
+ const response = event.response;
650
+ if (typeof response?.end_turn === "boolean") {
651
+ output.endTurn = response.end_turn;
652
+ }
653
+ const normalizedResponse = response ? { ...response, status: normalizeCodexStatus(response.status) } : response;
654
+ yield { ...event, type: "response.completed", response: normalizedResponse };
655
+ return;
656
+ }
657
+ yield event;
658
+ }
659
+ }
660
+ function normalizeCodexStatus(status) {
661
+ if (typeof status !== "string")
662
+ return void 0;
663
+ return CODEX_RESPONSE_STATUSES.has(status) ? status : void 0;
664
+ }
665
+ async function* parseSSE(response, signal) {
666
+ if (!response.body)
667
+ return;
668
+ const reader = response.body.getReader();
669
+ const decoder = new TextDecoder();
670
+ let buffer = "";
671
+ const onAbort = () => {
672
+ void reader.cancel().catch(() => {
673
+ });
674
+ };
675
+ signal?.addEventListener("abort", onAbort, { once: true });
676
+ try {
677
+ while (true) {
678
+ if (signal?.aborted) {
679
+ throw new Error("Request was aborted");
680
+ }
681
+ const { done, value } = await reader.read();
682
+ if (signal?.aborted) {
683
+ throw new Error("Request was aborted");
684
+ }
685
+ if (done)
686
+ break;
687
+ buffer += decoder.decode(value, { stream: true });
688
+ let idx = buffer.indexOf("\n\n");
689
+ while (idx !== -1) {
690
+ const chunk = buffer.slice(0, idx);
691
+ buffer = buffer.slice(idx + 2);
692
+ const dataLines = chunk.split("\n").filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trim());
693
+ if (dataLines.length > 0) {
694
+ const data = dataLines.join("\n").trim();
695
+ if (data && data !== "[DONE]") {
696
+ try {
697
+ yield JSON.parse(data);
698
+ } catch (cause) {
699
+ throw new CodexProtocolError(`Invalid Codex SSE JSON: ${formatThrownValue(cause)}`, {
700
+ cause,
701
+ payload: data
702
+ });
703
+ }
704
+ }
705
+ }
706
+ idx = buffer.indexOf("\n\n");
707
+ }
708
+ }
709
+ } finally {
710
+ signal?.removeEventListener("abort", onAbort);
711
+ try {
712
+ await reader.cancel();
713
+ } catch {
714
+ }
715
+ try {
716
+ reader.releaseLock();
717
+ } catch {
718
+ }
719
+ }
720
+ }
721
+ var OPENAI_BETA_RESPONSES_WEBSOCKETS = "responses_websockets=2026-02-06";
722
+ var SESSION_WEBSOCKET_CACHE_TTL_MS = 5 * 60 * 1e3;
723
+ var SESSION_WEBSOCKET_MAX_AGE_MS = 55 * 60 * 1e3;
724
+ var websocketSessionCache = /* @__PURE__ */ new Map();
725
+ var websocketDebugStats = /* @__PURE__ */ new Map();
726
+ var websocketSseFallbackSessions = /* @__PURE__ */ new Set();
727
+ function getOrCreateWebSocketDebugStats(sessionId) {
728
+ let stats = websocketDebugStats.get(sessionId);
729
+ if (!stats) {
730
+ stats = {
731
+ requests: 0,
732
+ connectionsCreated: 0,
733
+ connectionsReused: 0,
734
+ cachedContextRequests: 0,
735
+ storeTrueRequests: 0,
736
+ fullContextRequests: 0,
737
+ deltaRequests: 0,
738
+ lastInputItems: 0,
739
+ websocketFailures: 0,
740
+ sseFallbacks: 0
741
+ };
742
+ websocketDebugStats.set(sessionId, stats);
743
+ }
744
+ return stats;
745
+ }
746
+ function getOpenAICodexWebSocketDebugStats(sessionId) {
747
+ const stats = websocketDebugStats.get(sessionId);
748
+ return stats ? { ...stats } : void 0;
749
+ }
750
+ function resetOpenAICodexWebSocketDebugStats(sessionId) {
751
+ if (sessionId) {
752
+ websocketDebugStats.delete(sessionId);
753
+ websocketSseFallbackSessions.delete(sessionId);
754
+ return;
755
+ }
756
+ websocketDebugStats.clear();
757
+ websocketSseFallbackSessions.clear();
758
+ }
759
+ function closeOpenAICodexWebSocketSessions(sessionId) {
760
+ const closeEntry = (entry) => {
761
+ if (entry.idleTimer)
762
+ clearTimeout(entry.idleTimer);
763
+ closeWebSocketSilently(entry.socket, 1e3, "debug_close");
764
+ };
765
+ if (sessionId) {
766
+ for (const entry of websocketSessionCache.get(sessionId)?.values() ?? [])
767
+ closeEntry(entry);
768
+ websocketSessionCache.delete(sessionId);
769
+ return;
770
+ }
771
+ for (const accountEntries of websocketSessionCache.values()) {
772
+ for (const entry of accountEntries.values())
773
+ closeEntry(entry);
774
+ }
775
+ websocketSessionCache.clear();
776
+ }
777
+ registerSessionResourceCleanup(closeOpenAICodexWebSocketSessions);
778
+ function isWebSocketSseFallbackActive(sessionId) {
779
+ return sessionId ? websocketSseFallbackSessions.has(sessionId) : false;
780
+ }
781
+ function recordWebSocketSseFallback(sessionId) {
782
+ if (!sessionId)
783
+ return;
784
+ const stats = getOrCreateWebSocketDebugStats(sessionId);
785
+ stats.sseFallbacks++;
786
+ stats.websocketFallbackActive = isWebSocketSseFallbackActive(sessionId);
787
+ }
788
+ function recordWebSocketFailure(sessionId, error) {
789
+ if (!sessionId)
790
+ return;
791
+ websocketSseFallbackSessions.add(sessionId);
792
+ const stats = getOrCreateWebSocketDebugStats(sessionId);
793
+ stats.websocketFailures++;
794
+ stats.lastWebSocketError = formatThrownValue(error);
795
+ stats.websocketFallbackActive = true;
796
+ }
797
+ var _cachedWebsocket = null;
798
+ async function getWebSocketConstructor(env) {
799
+ if (!env && _cachedWebsocket)
800
+ return _cachedWebsocket;
801
+ if (typeof process !== "undefined" && process.versions?.bun) {
802
+ const WebSocketWithProxy = class extends WebSocket {
803
+ constructor(url, options) {
804
+ let _opts = {};
805
+ if (Array.isArray(options) || typeof options === "string") {
806
+ _opts = { protocols: options };
807
+ } else {
808
+ _opts = { ...options };
809
+ }
810
+ const proxyUrl = resolveHttpProxyUrlForTarget(url.toString().replace(/^wss:/, "https:").replace(/^ws:/, "http:"), env);
811
+ super(url, { ..._opts, ...proxyUrl ? { proxy: proxyUrl.toString() } : {} });
812
+ }
813
+ };
814
+ if (!env) {
815
+ _cachedWebsocket = WebSocketWithProxy;
816
+ }
817
+ return WebSocketWithProxy;
818
+ }
819
+ const ctor = globalThis.WebSocket;
820
+ if (typeof ctor !== "function")
821
+ return null;
822
+ return ctor;
823
+ }
824
+ var WebSocketCloseError = class extends Error {
825
+ code;
826
+ reason;
827
+ wasClean;
828
+ constructor(message, options) {
829
+ super(message);
830
+ this.name = "WebSocketCloseError";
831
+ this.code = options?.code;
832
+ this.reason = options?.reason;
833
+ this.wasClean = options?.wasClean;
834
+ }
835
+ };
836
+ function getWebSocketReadyState(socket) {
837
+ const readyState = socket.readyState;
838
+ return typeof readyState === "number" ? readyState : void 0;
839
+ }
840
+ function isWebSocketReusable(socket) {
841
+ const readyState = getWebSocketReadyState(socket);
842
+ return readyState === void 0 || readyState === 1;
843
+ }
844
+ function isWebSocketSessionExpired(entry) {
845
+ return Date.now() - entry.createdAt >= SESSION_WEBSOCKET_MAX_AGE_MS;
846
+ }
847
+ function closeWebSocketSilently(socket, code = 1e3, reason = "done") {
848
+ try {
849
+ socket.close(code, reason);
850
+ } catch {
851
+ }
852
+ }
853
+ function scheduleSessionWebSocketExpiry(sessionId, accountId, entry) {
854
+ if (entry.idleTimer) {
855
+ clearTimeout(entry.idleTimer);
856
+ }
857
+ entry.idleTimer = setTimeout(() => {
858
+ if (entry.busy)
859
+ return;
860
+ closeWebSocketSilently(entry.socket, 1e3, "idle_timeout");
861
+ const accountEntries = websocketSessionCache.get(sessionId);
862
+ if (accountEntries?.get(accountId) === entry)
863
+ accountEntries.delete(accountId);
864
+ if (accountEntries?.size === 0)
865
+ websocketSessionCache.delete(sessionId);
866
+ }, SESSION_WEBSOCKET_CACHE_TTL_MS);
867
+ }
868
+ async function connectWebSocket(url, headers, signal, connectTimeoutMs = DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS, env) {
869
+ const WebSocketCtor = await getWebSocketConstructor(env);
870
+ if (!WebSocketCtor) {
871
+ throw new Error("WebSocket transport is not available in this runtime");
872
+ }
873
+ const wsHeaders = headersToRecord(headers);
874
+ delete wsHeaders["OpenAI-Beta"];
875
+ return new Promise((resolve, reject) => {
876
+ let settled = false;
877
+ let timeout;
878
+ let socket;
879
+ try {
880
+ socket = new WebSocketCtor(url, { headers: wsHeaders });
881
+ } catch (error) {
882
+ reject(error instanceof Error ? error : new Error(String(error)));
883
+ return;
884
+ }
885
+ const cleanup = () => {
886
+ if (timeout) {
887
+ clearTimeout(timeout);
888
+ timeout = void 0;
889
+ }
890
+ socket.removeEventListener("open", onOpen);
891
+ socket.removeEventListener("error", onError);
892
+ socket.removeEventListener("close", onClose);
893
+ signal?.removeEventListener("abort", onAbort);
894
+ };
895
+ const fail = (error, closeReason) => {
896
+ if (settled)
897
+ return;
898
+ settled = true;
899
+ cleanup();
900
+ if (closeReason) {
901
+ closeWebSocketSilently(socket, 1e3, closeReason);
902
+ }
903
+ reject(error);
904
+ };
905
+ const onOpen = () => {
906
+ if (settled)
907
+ return;
908
+ settled = true;
909
+ cleanup();
910
+ resolve(socket);
911
+ };
912
+ const onError = (event) => {
913
+ fail(extractWebSocketError(event));
914
+ };
915
+ const onClose = (event) => {
916
+ fail(extractWebSocketCloseError(event));
917
+ };
918
+ const onAbort = () => {
919
+ fail(new Error("Request was aborted"), "aborted");
920
+ };
921
+ socket.addEventListener("open", onOpen);
922
+ socket.addEventListener("error", onError);
923
+ socket.addEventListener("close", onClose);
924
+ signal?.addEventListener("abort", onAbort);
925
+ if (connectTimeoutMs > 0) {
926
+ timeout = setTimeout(() => {
927
+ fail(new Error(`WebSocket connect timeout after ${connectTimeoutMs}ms`), "connect_timeout");
928
+ }, connectTimeoutMs);
929
+ }
930
+ if (signal?.aborted) {
931
+ onAbort();
932
+ }
933
+ });
934
+ }
935
+ async function acquireWebSocket(url, headers, sessionId, accountId, signal, connectTimeoutMs, env) {
936
+ if (!sessionId) {
937
+ const socket2 = await connectWebSocket(url, headers, signal, connectTimeoutMs, env);
938
+ return {
939
+ socket: socket2,
940
+ reused: false,
941
+ release: () => closeWebSocketSilently(socket2)
942
+ };
943
+ }
944
+ let accountEntries = websocketSessionCache.get(sessionId);
945
+ const cached = accountEntries?.get(accountId);
946
+ if (cached) {
947
+ if (cached.idleTimer) {
948
+ clearTimeout(cached.idleTimer);
949
+ cached.idleTimer = void 0;
950
+ }
951
+ if (!cached.busy && isWebSocketSessionExpired(cached)) {
952
+ closeWebSocketSilently(cached.socket, 1e3, "connection_age_limit");
953
+ accountEntries?.delete(accountId);
954
+ if (accountEntries?.size === 0)
955
+ websocketSessionCache.delete(sessionId);
956
+ } else if (!cached.busy && isWebSocketReusable(cached.socket)) {
957
+ cached.busy = true;
958
+ return {
959
+ socket: cached.socket,
960
+ entry: cached,
961
+ reused: true,
962
+ release: ({ keep } = {}) => {
963
+ if (!keep || !isWebSocketReusable(cached.socket)) {
964
+ closeWebSocketSilently(cached.socket);
965
+ const currentEntries = websocketSessionCache.get(sessionId);
966
+ if (currentEntries?.get(accountId) === cached)
967
+ currentEntries.delete(accountId);
968
+ if (currentEntries?.size === 0)
969
+ websocketSessionCache.delete(sessionId);
970
+ return;
971
+ }
972
+ cached.busy = false;
973
+ scheduleSessionWebSocketExpiry(sessionId, accountId, cached);
974
+ }
975
+ };
976
+ }
977
+ if (cached.busy) {
978
+ const socket2 = await connectWebSocket(url, headers, signal, connectTimeoutMs, env);
979
+ return {
980
+ socket: socket2,
981
+ reused: false,
982
+ release: () => {
983
+ closeWebSocketSilently(socket2);
984
+ }
985
+ };
986
+ }
987
+ if (!isWebSocketReusable(cached.socket)) {
988
+ closeWebSocketSilently(cached.socket);
989
+ accountEntries?.delete(accountId);
990
+ if (accountEntries?.size === 0)
991
+ websocketSessionCache.delete(sessionId);
992
+ }
993
+ }
994
+ const socket = await connectWebSocket(url, headers, signal, connectTimeoutMs, env);
995
+ const entry = { socket, busy: true, createdAt: Date.now() };
996
+ accountEntries = websocketSessionCache.get(sessionId);
997
+ if (!accountEntries) {
998
+ accountEntries = /* @__PURE__ */ new Map();
999
+ websocketSessionCache.set(sessionId, accountEntries);
1000
+ }
1001
+ accountEntries.set(accountId, entry);
1002
+ return {
1003
+ socket,
1004
+ entry,
1005
+ reused: false,
1006
+ release: ({ keep } = {}) => {
1007
+ if (!keep || !isWebSocketReusable(entry.socket)) {
1008
+ closeWebSocketSilently(entry.socket);
1009
+ if (entry.idleTimer)
1010
+ clearTimeout(entry.idleTimer);
1011
+ const currentEntries = websocketSessionCache.get(sessionId);
1012
+ if (currentEntries?.get(accountId) === entry)
1013
+ currentEntries.delete(accountId);
1014
+ if (currentEntries?.size === 0)
1015
+ websocketSessionCache.delete(sessionId);
1016
+ return;
1017
+ }
1018
+ entry.busy = false;
1019
+ scheduleSessionWebSocketExpiry(sessionId, accountId, entry);
1020
+ }
1021
+ };
1022
+ }
1023
+ function extractWebSocketError(event) {
1024
+ if (event && typeof event === "object") {
1025
+ const message = "message" in event ? event.message : void 0;
1026
+ if (typeof message === "string" && message.length > 0) {
1027
+ return new Error(message);
1028
+ }
1029
+ const nestedError = "error" in event ? event.error : void 0;
1030
+ if (nestedError instanceof Error && nestedError.message.length > 0) {
1031
+ return nestedError;
1032
+ }
1033
+ if (nestedError && typeof nestedError === "object" && "message" in nestedError) {
1034
+ const nestedMessage = nestedError.message;
1035
+ if (typeof nestedMessage === "string" && nestedMessage.length > 0) {
1036
+ return new Error(nestedMessage);
1037
+ }
1038
+ }
1039
+ }
1040
+ return new Error("WebSocket error");
1041
+ }
1042
+ function extractWebSocketCloseError(event) {
1043
+ if (event && typeof event === "object") {
1044
+ const code = "code" in event ? event.code : void 0;
1045
+ const reason = "reason" in event ? event.reason : void 0;
1046
+ const wasClean = "wasClean" in event ? event.wasClean : void 0;
1047
+ const codeText = typeof code === "number" ? ` ${code}` : "";
1048
+ let reasonText = typeof reason === "string" && reason.length > 0 ? ` ${reason}` : "";
1049
+ if (!reasonText && code === WEBSOCKET_MESSAGE_TOO_BIG_CLOSE_CODE) {
1050
+ reasonText = " message too big";
1051
+ }
1052
+ return new WebSocketCloseError(`WebSocket closed${codeText}${reasonText}`.trim(), {
1053
+ code: typeof code === "number" ? code : void 0,
1054
+ reason: typeof reason === "string" && reason.length > 0 ? reason : void 0,
1055
+ wasClean: typeof wasClean === "boolean" ? wasClean : void 0
1056
+ });
1057
+ }
1058
+ return new Error("WebSocket closed");
1059
+ }
1060
+ async function decodeWebSocketData(data) {
1061
+ if (typeof data === "string")
1062
+ return data;
1063
+ if (data instanceof ArrayBuffer) {
1064
+ return new TextDecoder().decode(new Uint8Array(data));
1065
+ }
1066
+ if (ArrayBuffer.isView(data)) {
1067
+ const view = data;
1068
+ return new TextDecoder().decode(new Uint8Array(view.buffer, view.byteOffset, view.byteLength));
1069
+ }
1070
+ if (data && typeof data === "object" && "arrayBuffer" in data) {
1071
+ const blobLike = data;
1072
+ const arrayBuffer = await blobLike.arrayBuffer();
1073
+ return new TextDecoder().decode(new Uint8Array(arrayBuffer));
1074
+ }
1075
+ return null;
1076
+ }
1077
+ async function* parseWebSocket(socket, signal, idleTimeoutMs) {
1078
+ const queue = [];
1079
+ let pending = null;
1080
+ let done = false;
1081
+ let failed = null;
1082
+ let sawCompletion = false;
1083
+ const wake = () => {
1084
+ if (!pending)
1085
+ return;
1086
+ const resolve = pending;
1087
+ pending = null;
1088
+ resolve();
1089
+ };
1090
+ const onMessage = (event) => {
1091
+ void (async () => {
1092
+ let text = null;
1093
+ try {
1094
+ if (!event || typeof event !== "object" || !("data" in event))
1095
+ return;
1096
+ text = await decodeWebSocketData(event.data);
1097
+ if (!text)
1098
+ return;
1099
+ const parsed = JSON.parse(text);
1100
+ const type = typeof parsed.type === "string" ? parsed.type : "";
1101
+ if (type === "response.completed" || type === "response.done" || type === "response.incomplete") {
1102
+ sawCompletion = true;
1103
+ done = true;
1104
+ }
1105
+ queue.push(parsed);
1106
+ wake();
1107
+ } catch (cause) {
1108
+ failed = new CodexProtocolError(`Invalid Codex WebSocket JSON: ${formatThrownValue(cause)}`, {
1109
+ cause,
1110
+ payload: text
1111
+ });
1112
+ done = true;
1113
+ wake();
1114
+ }
1115
+ })();
1116
+ };
1117
+ const onError = (event) => {
1118
+ failed = extractWebSocketError(event);
1119
+ done = true;
1120
+ wake();
1121
+ };
1122
+ const onClose = (event) => {
1123
+ if (sawCompletion) {
1124
+ done = true;
1125
+ wake();
1126
+ return;
1127
+ }
1128
+ if (!failed) {
1129
+ failed = extractWebSocketCloseError(event);
1130
+ }
1131
+ done = true;
1132
+ wake();
1133
+ };
1134
+ const onAbort = () => {
1135
+ failed = new Error("Request was aborted");
1136
+ done = true;
1137
+ wake();
1138
+ };
1139
+ socket.addEventListener("message", onMessage);
1140
+ socket.addEventListener("error", onError);
1141
+ socket.addEventListener("close", onClose);
1142
+ signal?.addEventListener("abort", onAbort);
1143
+ try {
1144
+ while (true) {
1145
+ if (signal?.aborted) {
1146
+ throw new Error("Request was aborted");
1147
+ }
1148
+ if (queue.length > 0) {
1149
+ yield queue.shift();
1150
+ continue;
1151
+ }
1152
+ if (done)
1153
+ break;
1154
+ let timeout;
1155
+ await new Promise((resolve, reject) => {
1156
+ pending = resolve;
1157
+ if (idleTimeoutMs !== void 0 && idleTimeoutMs > 0) {
1158
+ timeout = setTimeout(() => {
1159
+ const error = new Error(`WebSocket idle timeout after ${idleTimeoutMs}ms`);
1160
+ failed = error;
1161
+ done = true;
1162
+ pending = null;
1163
+ closeWebSocketSilently(socket, 1e3, "idle_timeout");
1164
+ reject(error);
1165
+ }, idleTimeoutMs);
1166
+ }
1167
+ }).finally(() => {
1168
+ if (timeout) {
1169
+ clearTimeout(timeout);
1170
+ }
1171
+ });
1172
+ }
1173
+ if (failed) {
1174
+ throw failed;
1175
+ }
1176
+ if (!sawCompletion) {
1177
+ throw new Error("WebSocket stream closed before response.completed");
1178
+ }
1179
+ } finally {
1180
+ socket.removeEventListener("message", onMessage);
1181
+ socket.removeEventListener("error", onError);
1182
+ socket.removeEventListener("close", onClose);
1183
+ signal?.removeEventListener("abort", onAbort);
1184
+ }
1185
+ }
1186
+ function requestBodyWithoutInput(body) {
1187
+ const { input: _input, previous_response_id: _previousResponseId, ...rest } = body;
1188
+ return rest;
1189
+ }
1190
+ function responseInputsEqual(a, b) {
1191
+ return JSON.stringify(a ?? []) === JSON.stringify(b ?? []);
1192
+ }
1193
+ function requestBodiesMatchExceptInput(a, b) {
1194
+ return JSON.stringify(requestBodyWithoutInput(a)) === JSON.stringify(requestBodyWithoutInput(b));
1195
+ }
1196
+ function getCachedWebSocketInputDelta(body, continuation) {
1197
+ if (!requestBodiesMatchExceptInput(body, continuation.lastRequestBody)) {
1198
+ return void 0;
1199
+ }
1200
+ const currentInput = body.input ?? [];
1201
+ const baseline = [...continuation.lastRequestBody.input ?? [], ...continuation.lastResponseItems];
1202
+ if (currentInput.length < baseline.length) {
1203
+ return void 0;
1204
+ }
1205
+ const prefix = currentInput.slice(0, baseline.length);
1206
+ if (!responseInputsEqual(prefix, baseline)) {
1207
+ return void 0;
1208
+ }
1209
+ return currentInput.slice(baseline.length);
1210
+ }
1211
+ function buildCachedWebSocketRequestBody(entry, body) {
1212
+ const continuation = entry.continuation;
1213
+ if (!continuation) {
1214
+ return body;
1215
+ }
1216
+ const delta = getCachedWebSocketInputDelta(body, continuation);
1217
+ if (!delta || !continuation.lastResponseId) {
1218
+ entry.continuation = void 0;
1219
+ return body;
1220
+ }
1221
+ return {
1222
+ ...body,
1223
+ previous_response_id: continuation.lastResponseId,
1224
+ input: delta
1225
+ };
1226
+ }
1227
+ async function* startWebSocketOutputOnFirstEvent(events, onStart) {
1228
+ let started = false;
1229
+ for await (const event of events) {
1230
+ if (!started) {
1231
+ started = true;
1232
+ onStart();
1233
+ }
1234
+ yield event;
1235
+ }
1236
+ }
1237
+ async function processWebSocketStream(url, body, headers, output, stream2, model, onStart, idleTimeoutMs, websocketConnectTimeoutMs, cacheSessionId, accountId, grammarToolInputProperties, options) {
1238
+ const { socket, entry, reused, release } = await acquireWebSocket(url, headers, cacheSessionId, accountId, options?.signal, websocketConnectTimeoutMs, options?.env);
1239
+ let keepConnection = true;
1240
+ const useCachedContext = options?.transport === "websocket-cached" || options?.transport === "auto";
1241
+ const fullBody = body;
1242
+ const requestBody = useCachedContext && entry ? buildCachedWebSocketRequestBody(entry, fullBody) : fullBody;
1243
+ const stats = cacheSessionId ? getOrCreateWebSocketDebugStats(cacheSessionId) : void 0;
1244
+ if (stats) {
1245
+ stats.requests++;
1246
+ if (reused)
1247
+ stats.connectionsReused++;
1248
+ else
1249
+ stats.connectionsCreated++;
1250
+ if (useCachedContext)
1251
+ stats.cachedContextRequests++;
1252
+ if (requestBody.store === true)
1253
+ stats.storeTrueRequests++;
1254
+ stats.lastInputItems = requestBody.input?.length ?? 0;
1255
+ if (requestBody.previous_response_id) {
1256
+ stats.deltaRequests++;
1257
+ stats.lastDeltaInputItems = requestBody.input?.length ?? 0;
1258
+ stats.lastPreviousResponseId = requestBody.previous_response_id;
1259
+ } else {
1260
+ stats.fullContextRequests++;
1261
+ stats.lastDeltaInputItems = void 0;
1262
+ stats.lastPreviousResponseId = void 0;
1263
+ }
1264
+ }
1265
+ try {
1266
+ socket.send(JSON.stringify({ type: "response.create", ...requestBody }));
1267
+ await processResponsesStream(startWebSocketOutputOnFirstEvent(mapCodexEvents(parseWebSocket(socket, options?.signal, idleTimeoutMs), output), onStart), output, stream2, model, {
1268
+ serviceTier: options?.serviceTier,
1269
+ grammarToolInputProperties,
1270
+ resolveServiceTier: resolveCodexServiceTier,
1271
+ applyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model)
1272
+ });
1273
+ if (options?.signal?.aborted) {
1274
+ keepConnection = false;
1275
+ } else if (useCachedContext && entry && output.responseId) {
1276
+ const responseItems = convertResponsesMessages(model, { messages: [output] }, CODEX_TOOL_CALL_PROVIDERS, {
1277
+ includeSystemPrompt: false,
1278
+ grammarToolInputProperties
1279
+ }).filter((item) => item.type !== "function_call_output" && item.type !== "custom_tool_call_output");
1280
+ entry.continuation = {
1281
+ lastRequestBody: fullBody,
1282
+ lastResponseId: output.responseId,
1283
+ lastResponseItems: responseItems
1284
+ };
1285
+ }
1286
+ } catch (error) {
1287
+ if (entry) {
1288
+ entry.continuation = void 0;
1289
+ }
1290
+ keepConnection = false;
1291
+ throw error;
1292
+ } finally {
1293
+ release({ keep: keepConnection });
1294
+ }
1295
+ }
1296
+ async function parseErrorResponse(response) {
1297
+ const raw = await response.text();
1298
+ let message = raw || response.statusText || "Request failed";
1299
+ let friendlyMessage;
1300
+ try {
1301
+ const parsed = JSON.parse(raw);
1302
+ const err = parsed?.error;
1303
+ if (err) {
1304
+ const code = err.code || err.type || "";
1305
+ if (/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(code) || response.status === 429) {
1306
+ const plan = err.plan_type ? ` (${err.plan_type.toLowerCase()} plan)` : "";
1307
+ const mins = err.resets_at ? Math.max(0, Math.round((err.resets_at * 1e3 - Date.now()) / 6e4)) : void 0;
1308
+ const when = mins !== void 0 ? ` Try again in ~${mins} min.` : "";
1309
+ friendlyMessage = `You have hit your ChatGPT usage limit${plan}.${when}`.trim();
1310
+ }
1311
+ message = err.message || friendlyMessage || message;
1312
+ }
1313
+ } catch {
1314
+ }
1315
+ return { message, friendlyMessage };
1316
+ }
1317
+ function extractAccountId(token) {
1318
+ try {
1319
+ const parts = token.split(".");
1320
+ if (parts.length !== 3)
1321
+ throw new Error("Invalid token");
1322
+ const payload = JSON.parse(atob(parts[1]));
1323
+ const accountId = payload?.[JWT_CLAIM_PATH]?.chatgpt_account_id;
1324
+ if (!accountId)
1325
+ throw new Error("No account ID in token");
1326
+ return accountId;
1327
+ } catch {
1328
+ throw new Error("Failed to extract accountId from token");
1329
+ }
1330
+ }
1331
+ function buildBaseCodexHeaders(initHeaders, additionalHeaders, accountId, token) {
1332
+ const headers = new Headers(initHeaders);
1333
+ for (const [key, value] of Object.entries(additionalHeaders || {})) {
1334
+ if (value === null) {
1335
+ headers.delete(key);
1336
+ } else {
1337
+ headers.set(key, value);
1338
+ }
1339
+ }
1340
+ headers.set("Authorization", `Bearer ${token}`);
1341
+ headers.set("chatgpt-account-id", accountId);
1342
+ headers.set("originator", "pi");
1343
+ headers.set("User-Agent", getPiUserAgent());
1344
+ return headers;
1345
+ }
1346
+ function buildSSEHeaders(initHeaders, additionalHeaders, accountId, token, sessionId) {
1347
+ const headers = buildBaseCodexHeaders(initHeaders, additionalHeaders, accountId, token);
1348
+ headers.set("OpenAI-Beta", "responses=experimental");
1349
+ headers.set("accept", "text/event-stream");
1350
+ headers.set("content-type", "application/json");
1351
+ if (sessionId) {
1352
+ headers.set("session-id", sessionId);
1353
+ headers.set("x-client-request-id", sessionId);
1354
+ }
1355
+ return headers;
1356
+ }
1357
+ function buildWebSocketHeaders(initHeaders, additionalHeaders, accountId, token, requestId) {
1358
+ const headers = buildBaseCodexHeaders(initHeaders, additionalHeaders, accountId, token);
1359
+ headers.delete("accept");
1360
+ headers.delete("content-type");
1361
+ headers.delete("OpenAI-Beta");
1362
+ headers.delete("openai-beta");
1363
+ headers.set("OpenAI-Beta", OPENAI_BETA_RESPONSES_WEBSOCKETS);
1364
+ headers.set("x-client-request-id", requestId);
1365
+ headers.set("session-id", requestId);
1366
+ return headers;
1367
+ }
1368
+ export {
1369
+ closeOpenAICodexWebSocketSessions,
1370
+ getOpenAICodexWebSocketDebugStats,
1371
+ resetOpenAICodexWebSocketDebugStats,
1372
+ stream,
1373
+ streamSimple
1374
+ };