@shuind/dsh-codex-connect 0.0.0-stage → 0.2.0

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 (42) hide show
  1. package/INSTALL.md +349 -0
  2. package/LICENSE +202 -0
  3. package/MIGRATION.md +101 -0
  4. package/NOTICE +26 -0
  5. package/README.md +71 -2
  6. package/VERSIONING.md +69 -0
  7. package/cordis.patch.yml +9 -0
  8. package/docs/README.zh.md +3 -0
  9. package/docs/assets/composer-capabilities.jpg +0 -0
  10. package/docs/assets/en/hero.jpg +0 -0
  11. package/docs/assets/en/image-generation.png +0 -0
  12. package/docs/assets/en/model-selector.jpg +0 -0
  13. package/docs/assets/en/oauth-status.jpg +0 -0
  14. package/docs/assets/en/plugin-configuration.jpg +0 -0
  15. package/docs/assets/en/plugin-entry.jpg +0 -0
  16. package/docs/assets/hero.jpg +0 -0
  17. package/docs/assets/model-selector.jpg +0 -0
  18. package/docs/assets/oauth-status.jpg +0 -0
  19. package/docs/assets/plugin-configuration.jpg +0 -0
  20. package/docs/assets/zh/hero.jpg +0 -0
  21. package/docs/assets/zh/image-generation.png +0 -0
  22. package/docs/assets/zh/model-selector.jpg +0 -0
  23. package/docs/assets/zh/oauth-status.jpg +0 -0
  24. package/docs/assets/zh/plugin-configuration.jpg +0 -0
  25. package/docs/assets/zh/plugin-entry.jpg +0 -0
  26. package/docs/design.md +61 -0
  27. package/docs/design.zh.md +39 -0
  28. package/docs/licenses/pi-ai-oauth.txt +21 -0
  29. package/docs/licenses/standalone-cli.txt +115 -0
  30. package/docs/preflight-activity.md +42 -0
  31. package/docs/preflight-activity.zh.md +42 -0
  32. package/docs/quota-tool.md +46 -0
  33. package/docs/reference.md +240 -0
  34. package/docs/reference.zh.md +240 -0
  35. package/docs/skills/codex-quota-awareness/SKILL.md +12 -0
  36. package/lib/bin.js +2442 -0
  37. package/lib/client.js +6804 -0
  38. package/lib/index.d.ts +631 -0
  39. package/lib/index.js +7091 -0
  40. package/lib/models-Brnw-PH4.js +1763 -0
  41. package/lib/openai-codex-responses-DfZMR6a9.js +3452 -0
  42. package/package.json +234 -4
@@ -0,0 +1,3452 @@
1
+ import { _ as AssistantMessageEventStream, a as getDeclaredTools, c as resolveTranscriptTools, d as ownedSlice, f as renderSystemMessageUpdate, h as formatThrownValue, l as getIdentityHeaders, m as createAssistantMessageDiagnostic, n as clampThinkingLevel, o as normalizeContext, p as appendAssistantMessageDiagnostic, s as resolveTranscript, t as calculateCost, u as getSystemMessageText, v as __commonJSMin, y as __require } from "./models-Brnw-PH4.js";
2
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/utils/provider-env.js
3
+ let procEnvCache = null;
4
+ /**
5
+ * Fallback for https://github.com/oven-sh/bun/issues/27802.
6
+ * Bun compiled binaries can expose an empty process.env inside Linux sandboxes
7
+ * even though /proc/self/environ contains the environment.
8
+ *
9
+ * This intentionally duplicates restoreSandboxEnv() in
10
+ * packages/coding-agent/src/bun/restore-sandbox-env.ts. The ai package can be
11
+ * used directly, without going through that entrypoint, so provider env lookup
12
+ * must not depend on process.env having been patched.
13
+ */
14
+ function getBunSandboxEnvValue(name) {
15
+ if (typeof process === "undefined" || !process.versions?.bun || Object.keys(process.env).length > 0) return;
16
+ if (procEnvCache === null) {
17
+ procEnvCache = /* @__PURE__ */ new Map();
18
+ try {
19
+ const { readFileSync } = __require("node:fs");
20
+ const data = readFileSync("/proc/self/environ", "utf-8");
21
+ for (const entry of data.split("\0")) {
22
+ const idx = entry.indexOf("=");
23
+ if (idx > 0) procEnvCache.set(entry.slice(0, idx), entry.slice(idx + 1));
24
+ }
25
+ } catch {}
26
+ }
27
+ return procEnvCache.get(name);
28
+ }
29
+ /**
30
+ * Resolve a provider env value from scoped overrides, normal process.env, then
31
+ * the duplicated Bun sandbox fallback for direct pi-ai consumers.
32
+ */
33
+ function getProviderEnvValue(name, env) {
34
+ return env?.[name] || (typeof process !== "undefined" ? process.env[name] : void 0) || getBunSandboxEnvValue(name) || void 0;
35
+ }
36
+ // node_modules/.pnpm/partial-json@0.1.7/node_modules/partial-json/dist/options.js
37
+ var require_options = /* @__PURE__ */ __commonJSMin(((exports) => {
38
+ /**
39
+ * Sometimes you don't allow every type to be partially parsed.
40
+ * For example, you may not want a partial number because it may increase its size gradually before it's complete.
41
+ * In this case, you can use the `Allow` object to control what types you allow to be partially parsed.
42
+ * @module
43
+ */
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.Allow = exports.ALL = exports.COLLECTION = exports.ATOM = exports.SPECIAL = exports.INF = exports._INFINITY = exports.INFINITY = exports.NAN = exports.BOOL = exports.NULL = exports.OBJ = exports.ARR = exports.NUM = exports.STR = void 0;
46
+ /**
47
+ * allow partial strings like `"hello \u12` to be parsed as `"hello "`
48
+ */
49
+ exports.STR = 1;
50
+ /**
51
+ * allow partial numbers like `123.` to be parsed as `123`
52
+ */
53
+ exports.NUM = 2;
54
+ /**
55
+ * allow partial arrays like `[1, 2,` to be parsed as `[1, 2]`
56
+ */
57
+ exports.ARR = 4;
58
+ /**
59
+ * allow partial objects like `{"a": 1, "b":` to be parsed as `{"a": 1}`
60
+ */
61
+ exports.OBJ = 8;
62
+ /**
63
+ * allow `nu` to be parsed as `null`
64
+ */
65
+ exports.NULL = 16;
66
+ /**
67
+ * allow `tr` to be parsed as `true`, and `fa` to be parsed as `false`
68
+ */
69
+ exports.BOOL = 32;
70
+ /**
71
+ * allow `Na` to be parsed as `NaN`
72
+ */
73
+ exports.NAN = 64;
74
+ /**
75
+ * allow `Inf` to be parsed as `Infinity`
76
+ */
77
+ exports.INFINITY = 128;
78
+ /**
79
+ * allow `-Inf` to be parsed as `-Infinity`
80
+ */
81
+ exports._INFINITY = 256;
82
+ exports.INF = exports.INFINITY | exports._INFINITY;
83
+ exports.SPECIAL = exports.NULL | exports.BOOL | exports.INF | exports.NAN;
84
+ exports.ATOM = exports.STR | exports.NUM | exports.SPECIAL;
85
+ exports.COLLECTION = exports.ARR | exports.OBJ;
86
+ exports.ALL = exports.ATOM | exports.COLLECTION;
87
+ /**
88
+ * Control what types you allow to be partially parsed.
89
+ * The default is to allow all types to be partially parsed, which in most casees is the best option.
90
+ * @example
91
+ * If you don't want to allow partial objects, you can use the following code:
92
+ * ```ts
93
+ * import { Allow, parse } from "partial-json";
94
+ * parse(`[{"a": 1, "b": 2}, {"a": 3,`, Allow.ARR); // [ { a: 1, b: 2 } ]
95
+ * ```
96
+ * Or you can use `~` to disallow a type:
97
+ * ```ts
98
+ * parse(`[{"a": 1, "b": 2}, {"a": 3,`, ~Allow.OBJ); // [ { a: 1, b: 2 } ]
99
+ * ```
100
+ * @example
101
+ * If you don't want to allow partial strings, you can use the following code:
102
+ * ```ts
103
+ * import { Allow, parse } from "partial-json";
104
+ * parse(`["complete string", "incompl`, ~Allow.STR); // [ 'complete string' ]
105
+ * ```
106
+ */
107
+ exports.Allow = {
108
+ STR: exports.STR,
109
+ NUM: exports.NUM,
110
+ ARR: exports.ARR,
111
+ OBJ: exports.OBJ,
112
+ NULL: exports.NULL,
113
+ BOOL: exports.BOOL,
114
+ NAN: exports.NAN,
115
+ INFINITY: exports.INFINITY,
116
+ _INFINITY: exports._INFINITY,
117
+ INF: exports.INF,
118
+ SPECIAL: exports.SPECIAL,
119
+ ATOM: exports.ATOM,
120
+ COLLECTION: exports.COLLECTION,
121
+ ALL: exports.ALL
122
+ };
123
+ exports.default = exports.Allow;
124
+ }));
125
+ (/* @__PURE__ */ __commonJSMin(((exports, module, this$1) => {
126
+ var __createBinding = this$1 && this$1.__createBinding || (Object.create ? (function(o, m, k, k2) {
127
+ if (k2 === void 0) k2 = k;
128
+ var desc = Object.getOwnPropertyDescriptor(m, k);
129
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
130
+ enumerable: true,
131
+ get: function() {
132
+ return m[k];
133
+ }
134
+ };
135
+ Object.defineProperty(o, k2, desc);
136
+ }) : (function(o, m, k, k2) {
137
+ if (k2 === void 0) k2 = k;
138
+ o[k2] = m[k];
139
+ }));
140
+ var __exportStar = this$1 && this$1.__exportStar || function(m, exports) {
141
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
142
+ };
143
+ Object.defineProperty(exports, "__esModule", { value: true });
144
+ exports.Allow = exports.MalformedJSON = exports.PartialJSON = exports.parseJSON = exports.parse = void 0;
145
+ const options_1 = require_options();
146
+ Object.defineProperty(exports, "Allow", {
147
+ enumerable: true,
148
+ get: function() {
149
+ return options_1.Allow;
150
+ }
151
+ });
152
+ __exportStar(require_options(), exports);
153
+ var PartialJSON = class extends Error {};
154
+ exports.PartialJSON = PartialJSON;
155
+ var MalformedJSON = class extends Error {};
156
+ exports.MalformedJSON = MalformedJSON;
157
+ /**
158
+ * Parse incomplete JSON
159
+ * @param {string} jsonString Partial JSON to be parsed
160
+ * @param {number} allowPartial Specify what types are allowed to be partial, see {@link Allow} for details
161
+ * @returns The parsed JSON
162
+ * @throws {PartialJSON} If the JSON is incomplete (related to the `allow` parameter)
163
+ * @throws {MalformedJSON} If the JSON is malformed
164
+ */
165
+ function parseJSON(jsonString, allowPartial = options_1.Allow.ALL) {
166
+ if (typeof jsonString !== "string") throw new TypeError(`expecting str, got ${typeof jsonString}`);
167
+ if (!jsonString.trim()) throw new Error(`${jsonString} is empty`);
168
+ return _parseJSON(jsonString.trim(), allowPartial);
169
+ }
170
+ exports.parseJSON = parseJSON;
171
+ const _parseJSON = (jsonString, allow) => {
172
+ const length = jsonString.length;
173
+ let index = 0;
174
+ const markPartialJSON = (msg) => {
175
+ throw new PartialJSON(`${msg} at position ${index}`);
176
+ };
177
+ const throwMalformedError = (msg) => {
178
+ throw new MalformedJSON(`${msg} at position ${index}`);
179
+ };
180
+ const parseAny = () => {
181
+ skipBlank();
182
+ if (index >= length) markPartialJSON("Unexpected end of input");
183
+ if (jsonString[index] === "\"") return parseStr();
184
+ if (jsonString[index] === "{") return parseObj();
185
+ if (jsonString[index] === "[") return parseArr();
186
+ if (jsonString.substring(index, index + 4) === "null" || options_1.Allow.NULL & allow && length - index < 4 && "null".startsWith(jsonString.substring(index))) {
187
+ index += 4;
188
+ return null;
189
+ }
190
+ if (jsonString.substring(index, index + 4) === "true" || options_1.Allow.BOOL & allow && length - index < 4 && "true".startsWith(jsonString.substring(index))) {
191
+ index += 4;
192
+ return true;
193
+ }
194
+ if (jsonString.substring(index, index + 5) === "false" || options_1.Allow.BOOL & allow && length - index < 5 && "false".startsWith(jsonString.substring(index))) {
195
+ index += 5;
196
+ return false;
197
+ }
198
+ if (jsonString.substring(index, index + 8) === "Infinity" || options_1.Allow.INFINITY & allow && length - index < 8 && "Infinity".startsWith(jsonString.substring(index))) {
199
+ index += 8;
200
+ return Infinity;
201
+ }
202
+ if (jsonString.substring(index, index + 9) === "-Infinity" || options_1.Allow._INFINITY & allow && 1 < length - index && length - index < 9 && "-Infinity".startsWith(jsonString.substring(index))) {
203
+ index += 9;
204
+ return -Infinity;
205
+ }
206
+ if (jsonString.substring(index, index + 3) === "NaN" || options_1.Allow.NAN & allow && length - index < 3 && "NaN".startsWith(jsonString.substring(index))) {
207
+ index += 3;
208
+ return NaN;
209
+ }
210
+ return parseNum();
211
+ };
212
+ const parseStr = () => {
213
+ const start = index;
214
+ let escape = false;
215
+ index++;
216
+ while (index < length && (jsonString[index] !== "\"" || escape && jsonString[index - 1] === "\\")) {
217
+ escape = jsonString[index] === "\\" ? !escape : false;
218
+ index++;
219
+ }
220
+ if (jsonString.charAt(index) == "\"") try {
221
+ return JSON.parse(jsonString.substring(start, ++index - Number(escape)));
222
+ } catch (e) {
223
+ throwMalformedError(String(e));
224
+ }
225
+ else if (options_1.Allow.STR & allow) try {
226
+ return JSON.parse(jsonString.substring(start, index - Number(escape)) + "\"");
227
+ } catch (e) {
228
+ return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("\\")) + "\"");
229
+ }
230
+ markPartialJSON("Unterminated string literal");
231
+ };
232
+ const parseObj = () => {
233
+ index++;
234
+ skipBlank();
235
+ const obj = {};
236
+ try {
237
+ while (jsonString[index] !== "}") {
238
+ skipBlank();
239
+ if (index >= length && options_1.Allow.OBJ & allow) return obj;
240
+ const key = parseStr();
241
+ skipBlank();
242
+ index++;
243
+ try {
244
+ obj[key] = parseAny();
245
+ } catch (e) {
246
+ if (options_1.Allow.OBJ & allow) return obj;
247
+ else throw e;
248
+ }
249
+ skipBlank();
250
+ if (jsonString[index] === ",") index++;
251
+ }
252
+ } catch (e) {
253
+ if (options_1.Allow.OBJ & allow) return obj;
254
+ else markPartialJSON("Expected '}' at end of object");
255
+ }
256
+ index++;
257
+ return obj;
258
+ };
259
+ const parseArr = () => {
260
+ index++;
261
+ const arr = [];
262
+ try {
263
+ while (jsonString[index] !== "]") {
264
+ arr.push(parseAny());
265
+ skipBlank();
266
+ if (jsonString[index] === ",") index++;
267
+ }
268
+ } catch (e) {
269
+ if (options_1.Allow.ARR & allow) return arr;
270
+ markPartialJSON("Expected ']' at end of array");
271
+ }
272
+ index++;
273
+ return arr;
274
+ };
275
+ const parseNum = () => {
276
+ if (index === 0) {
277
+ if (jsonString === "-") throwMalformedError("Not sure what '-' is");
278
+ try {
279
+ return JSON.parse(jsonString);
280
+ } catch (e) {
281
+ if (options_1.Allow.NUM & allow) try {
282
+ return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf("e")));
283
+ } catch (e) {}
284
+ throwMalformedError(String(e));
285
+ }
286
+ }
287
+ const start = index;
288
+ if (jsonString[index] === "-") index++;
289
+ while (jsonString[index] && ",]}".indexOf(jsonString[index]) === -1) index++;
290
+ if (index == length && !(options_1.Allow.NUM & allow)) markPartialJSON("Unterminated number literal");
291
+ try {
292
+ return JSON.parse(jsonString.substring(start, index));
293
+ } catch (e) {
294
+ if (jsonString.substring(start, index) === "-") markPartialJSON("Not sure what '-' is");
295
+ try {
296
+ return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("e")));
297
+ } catch (e) {
298
+ throwMalformedError(String(e));
299
+ }
300
+ }
301
+ };
302
+ const skipBlank = () => {
303
+ while (index < length && " \n\r ".includes(jsonString[index])) index++;
304
+ };
305
+ return parseAny();
306
+ };
307
+ exports.parse = parseJSON;
308
+ })))();
309
+ const VALID_JSON_ESCAPES = /* @__PURE__ */ new Set([
310
+ "\"",
311
+ "\\",
312
+ "/",
313
+ "b",
314
+ "f",
315
+ "n",
316
+ "r",
317
+ "t"
318
+ ]);
319
+ function isControlCharacter(char) {
320
+ const codePoint = char.codePointAt(0);
321
+ return codePoint !== void 0 && codePoint >= 0 && codePoint <= 31;
322
+ }
323
+ function escapeControlCharacter(char) {
324
+ switch (char) {
325
+ case "\b": return "\\b";
326
+ case "\f": return "\\f";
327
+ case "\n": return "\\n";
328
+ case "\r": return "\\r";
329
+ case " ": return "\\t";
330
+ default: return `\\u${char.codePointAt(0)?.toString(16).padStart(4, "0") ?? "0000"}`;
331
+ }
332
+ }
333
+ /**
334
+ * Repairs malformed JSON string literals by:
335
+ * - escaping raw control characters inside strings
336
+ * - doubling backslashes before invalid escape characters
337
+ */
338
+ function repairJson(json) {
339
+ let repaired = "";
340
+ let inString = false;
341
+ for (let index = 0; index < json.length; index++) {
342
+ const char = json[index];
343
+ if (!inString) {
344
+ repaired += char;
345
+ if (char === "\"") inString = true;
346
+ continue;
347
+ }
348
+ if (char === "\"") {
349
+ repaired += char;
350
+ inString = false;
351
+ continue;
352
+ }
353
+ if (char === "\\") {
354
+ const nextChar = json[index + 1];
355
+ if (nextChar === void 0) {
356
+ repaired += "\\\\";
357
+ continue;
358
+ }
359
+ if (nextChar === "u") {
360
+ const unicodeDigits = json.slice(index + 2, index + 6);
361
+ if (/^[0-9a-fA-F]{4}$/.test(unicodeDigits)) {
362
+ repaired += `\\u${unicodeDigits}`;
363
+ index += 5;
364
+ continue;
365
+ }
366
+ }
367
+ if (VALID_JSON_ESCAPES.has(nextChar)) {
368
+ repaired += `\\${nextChar}`;
369
+ index += 1;
370
+ continue;
371
+ }
372
+ repaired += "\\\\";
373
+ continue;
374
+ }
375
+ repaired += isControlCharacter(char) ? escapeControlCharacter(char) : char;
376
+ }
377
+ return repaired;
378
+ }
379
+ function parseJsonWithRepair(json) {
380
+ try {
381
+ return JSON.parse(json);
382
+ } catch (error) {
383
+ const repairedJson = repairJson(json);
384
+ if (repairedJson !== json) return JSON.parse(repairedJson);
385
+ throw error;
386
+ }
387
+ }
388
+ /**
389
+ * Parses the model's complete arguments text of a finished tool call.
390
+ *
391
+ * Unlike {@link parseStreamingJson}, this never keeps a partially parsed prefix: once the call is
392
+ * finished, text that is not a valid JSON object means the model sent malformed arguments. In that
393
+ * case `arguments` is `{}` and `argumentsError` describes the problem, including the text the
394
+ * model sent, so tool validation can report it back to the model.
395
+ */
396
+ function parseToolCallArguments(json) {
397
+ if (!json?.trim()) return { arguments: {} };
398
+ try {
399
+ const parsed = parseJsonWithRepair(json);
400
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("Tool arguments must be a JSON object");
401
+ return { arguments: parsed };
402
+ } catch (error) {
403
+ return {
404
+ arguments: {},
405
+ argumentsError: `${error instanceof Error ? error.message : String(error)}\n\nReceived arguments:\n${json}`
406
+ };
407
+ }
408
+ }
409
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/utils/streaming-json.js
410
+ /**
411
+ * Incremental, tolerant parsing of JSON text that arrives in pieces, such as streamed tool-call arguments.
412
+ *
413
+ * `StreamingJsonParser.append()` reads each piece once, so a stream costs time and memory linear in its length, and
414
+ * `snapshot()` returns the value of the text read so far. Snapshots are plain JSON values and never change once
415
+ * returned: the parser copies the containers that are still open (the "open path") into every new snapshot and shares
416
+ * completed containers and strings. The rules for incomplete text follow `parseStreamingJson()`:
417
+ *
418
+ * - An unterminated string shows the characters read so far; an unterminated escape is held back until complete.
419
+ * - An unterminated container shows the members and elements read so far.
420
+ * - A member whose key or value has not started is omitted.
421
+ * - An unterminated literal shows its value once it is a prefix of `true`, `false` or `null`; an unterminated number
422
+ * shows its value when the digits read so far form a number (an exponent without digits is ignored).
423
+ *
424
+ * Malformed text is read leniently, the way `repairJson()` and `parseStreamingJson()` treat it: raw control characters
425
+ * in strings are kept, an invalid escape such as `\d` stays literal text, missing commas and colons are tolerated,
426
+ * values in invalid positions and unknown words are dropped, and text after the root value is ignored. The parser never
427
+ * throws. Callers that need the exact value of the finished text parse it once, e.g. with `parseToolCallArguments()`.
428
+ *
429
+ * Differences from `parseStreamingJson()` on incomplete text: trailing whitespace inside an unterminated string is
430
+ * kept (it was trimmed), a string that contains a raw control character or an invalid escape stays visible while it
431
+ * streams (it was dropped until the document was complete), and `NaN` and `Infinity` words are dropped.
432
+ *
433
+ * `append()` also returns the changes the piece made, for a writer that keeps its own copy of the value and applies
434
+ * them instead of re-assigning snapshots: `set` when a key, an array item or a finished value appears (a new string is
435
+ * set once with its first text, a container empty), `append` when the piece extended an open string. Unterminated
436
+ * numbers and literals are not reported until they end. A container nested more than 32 levels deep is reported as one
437
+ * `set` of its whole value when it closes, so paths stay short.
438
+ *
439
+ * Cost: copying the open path costs its member and element count. Each `append()` earns copy credit proportional to its
440
+ * length plus a constant; `snapshot()` spends it and returns the previous snapshot while the open path costs more than
441
+ * the credit. So a document that keeps a very large container open (thousands of elements) shows a preview that lags
442
+ * a little behind the text, and no input makes the total work grow faster than the text.
443
+ */
444
+ const MAX_REPORTED_DEPTH = 32;
445
+ const ROOT_SLOT = { kind: "root" };
446
+ const CREDIT_PER_APPEND = 256;
447
+ const CREDIT_PER_CHARACTER = 8;
448
+ const MAX_PENDING_SCALAR_LENGTH = 64;
449
+ const NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/;
450
+ const NUMBER_WITHOUT_EXPONENT_DIGITS = /^(-?(?:0|[1-9]\d*)(?:\.\d+)?)[eE][+-]?$/;
451
+ const LITERALS = [
452
+ ["true", true],
453
+ ["false", false],
454
+ ["null", null]
455
+ ];
456
+ const QUOTE = 34;
457
+ const BACKSLASH = 92;
458
+ /** Incremental, tolerant JSON parser; see the module comment for its rules and costs. */
459
+ var StreamingJsonParser = class {
460
+ #root = void 0;
461
+ #done = false;
462
+ #stack = [];
463
+ #string = void 0;
464
+ #scalar = "";
465
+ #scalarSlot = void 0;
466
+ /** Sum of `size + 1` over the open path: what a fresh snapshot copies. */
467
+ #pathCost = 0;
468
+ #credit = 0;
469
+ #dirty = false;
470
+ #snapshot = void 0;
471
+ /** Changes of the piece being read. */
472
+ #changes = [];
473
+ /**
474
+ * Read the next piece of text; returns the changes it made, in order. Costs time linear in `text.length`.
475
+ */
476
+ append(text) {
477
+ this.#credit += CREDIT_PER_APPEND + CREDIT_PER_CHARACTER * text.length;
478
+ this.#changes = [];
479
+ if (this.#string !== void 0) this.#string.change = void 0;
480
+ let index = 0;
481
+ while (index < text.length && !this.#done) {
482
+ const open = this.#string;
483
+ if (open !== void 0) index = this.#readString(open, text, index);
484
+ else if (this.#scalar !== "") index = this.#readScalar(text, index);
485
+ else this.#structural(text[index++]);
486
+ }
487
+ return this.#changes;
488
+ }
489
+ /**
490
+ * The value of the text read so far: `undefined` before a value starts, otherwise a plain JSON value that never
491
+ * changes afterwards. Returns the previous snapshot while the text read since did not change the value, or while a
492
+ * fresh copy of the open path is not yet paid for (see the module comment).
493
+ */
494
+ snapshot() {
495
+ if (!this.#dirty) return this.#snapshot;
496
+ const pending = this.#pendingScalar();
497
+ const cost = this.#pathCost + (pending === void 0 ? 0 : 1);
498
+ if (cost > this.#credit) return this.#snapshot;
499
+ this.#credit -= cost;
500
+ this.#dirty = false;
501
+ this.#snapshot = this.#copyOpenPath(pending);
502
+ return this.#snapshot;
503
+ }
504
+ /** Read string characters from `start` until the string ends or the text does; returns the next index. */
505
+ #readString(open, text, start) {
506
+ let runStart = start;
507
+ for (let index = start; index < text.length; index++) {
508
+ const code = text.charCodeAt(index);
509
+ if (open.escape !== "") {
510
+ if (this.#continueEscape(open, text[index])) {
511
+ runStart = index + 1;
512
+ continue;
513
+ }
514
+ runStart = index;
515
+ }
516
+ if (code === QUOTE) {
517
+ if (index > runStart) this.#appendString(open, text.slice(runStart, index));
518
+ this.#endString(open);
519
+ return index + 1;
520
+ }
521
+ if (code === BACKSLASH) {
522
+ if (index > runStart) this.#appendString(open, text.slice(runStart, index));
523
+ open.escape = "\\";
524
+ runStart = index + 1;
525
+ }
526
+ }
527
+ if (text.length > runStart) this.#appendString(open, text.slice(runStart));
528
+ return text.length;
529
+ }
530
+ /** Read number or literal characters from `start` up to the next delimiter; returns the delimiter's index. */
531
+ #readScalar(text, start) {
532
+ let end = start;
533
+ while (end < text.length && !isDelimiter(text[end])) end++;
534
+ if (end > start) {
535
+ this.#scalar += text.slice(start, end);
536
+ if (this.#scalarSlot !== void 0) this.#dirty = true;
537
+ }
538
+ if (end < text.length) this.#endScalar();
539
+ return end;
540
+ }
541
+ /** Handle one character outside strings. */
542
+ #structural(char) {
543
+ switch (char) {
544
+ case " ":
545
+ case " ":
546
+ case "\n":
547
+ case "\r": return;
548
+ case "\"":
549
+ this.#startString();
550
+ return;
551
+ case "{":
552
+ case "[":
553
+ this.#openContainer(char === "{" ? {} : []);
554
+ return;
555
+ case "}":
556
+ case "]":
557
+ this.#closeContainer();
558
+ return;
559
+ case ":": {
560
+ const frame = this.#stack.at(-1);
561
+ if (frame !== void 0 && !Array.isArray(frame.container) && frame.phase === "colon") frame.phase = "value";
562
+ return;
563
+ }
564
+ case ",": {
565
+ const frame = this.#stack.at(-1);
566
+ if (frame !== void 0) frame.phase = Array.isArray(frame.container) ? "value" : "key";
567
+ return;
568
+ }
569
+ default:
570
+ this.#scalar = char;
571
+ this.#scalarSlot = this.#valueSlot();
572
+ if (this.#scalarSlot !== void 0) this.#dirty = true;
573
+ }
574
+ }
575
+ /** Where a value starting now goes, or `undefined` when this position takes no value. */
576
+ #valueSlot() {
577
+ const frame = this.#stack.at(-1);
578
+ if (frame === void 0) return this.#root === void 0 ? ROOT_SLOT : void 0;
579
+ if (Array.isArray(frame.container)) return {
580
+ kind: "element",
581
+ index: frame.container.length
582
+ };
583
+ if ((frame.phase === "value" || frame.phase === "colon") && frame.key !== void 0) return {
584
+ kind: "member",
585
+ key: frame.key
586
+ };
587
+ }
588
+ #startString() {
589
+ const frame = this.#stack.at(-1);
590
+ if (frame !== void 0 && !Array.isArray(frame.container) && (frame.phase === "key" || frame.phase === "comma")) {
591
+ this.#string = {
592
+ target: "key",
593
+ slot: void 0,
594
+ text: "",
595
+ escape: "",
596
+ path: void 0,
597
+ change: void 0
598
+ };
599
+ return;
600
+ }
601
+ const slot = this.#valueSlot();
602
+ const path = this.#reportedPath(slot);
603
+ this.#string = {
604
+ target: "value",
605
+ slot,
606
+ text: "",
607
+ escape: "",
608
+ path,
609
+ change: void 0
610
+ };
611
+ this.#place(slot, "");
612
+ if (path !== void 0) this.#string.change = this.#report({
613
+ kind: "set",
614
+ path,
615
+ value: ""
616
+ });
617
+ }
618
+ /** The path of a value at `slot` in the innermost open container, when its changes are reported. */
619
+ #reportedPath(slot) {
620
+ if (slot === void 0) return void 0;
621
+ if (slot.kind === "root") return [];
622
+ const frame = this.#stack.at(-1);
623
+ if (!frame.reportsInside) return void 0;
624
+ return [...frame.path, slot.kind === "member" ? slot.key : slot.index];
625
+ }
626
+ #report(change) {
627
+ this.#changes.push(change);
628
+ return change;
629
+ }
630
+ /** Continue an escape with `char`; returns false when `char` is not part of it and must be read normally. */
631
+ #continueEscape(open, char) {
632
+ if (open.escape === "\\") {
633
+ const decoded = SIMPLE_ESCAPES[char];
634
+ if (decoded !== void 0) {
635
+ open.escape = "";
636
+ this.#appendString(open, decoded);
637
+ return true;
638
+ }
639
+ if (char === "u") {
640
+ open.escape = "\\u";
641
+ return true;
642
+ }
643
+ open.escape = "";
644
+ this.#appendString(open, "\\");
645
+ return false;
646
+ }
647
+ if (isHexDigit(char)) {
648
+ open.escape += char;
649
+ if (open.escape.length < 6) return true;
650
+ const decoded = String.fromCharCode(Number.parseInt(open.escape.slice(2), 16));
651
+ open.escape = "";
652
+ this.#appendString(open, decoded);
653
+ return true;
654
+ }
655
+ const literal = open.escape;
656
+ open.escape = "";
657
+ this.#appendString(open, literal);
658
+ return false;
659
+ }
660
+ #appendString(open, text) {
661
+ open.text += text;
662
+ if (open.target !== "value") return;
663
+ this.#place(open.slot, open.text);
664
+ if (open.path === void 0) return;
665
+ const change = open.change;
666
+ if (change !== void 0 && this.#changes.at(-1) === change) {
667
+ if (change.kind === "set") change.value = change.value + text;
668
+ else change.text += text;
669
+ return;
670
+ }
671
+ open.change = this.#report({
672
+ kind: "append",
673
+ path: open.path,
674
+ text
675
+ });
676
+ }
677
+ #endString(open) {
678
+ this.#string = void 0;
679
+ const frame = this.#stack.at(-1);
680
+ if (open.target === "key") {
681
+ if (frame === void 0) return;
682
+ frame.key = open.text;
683
+ frame.phase = "colon";
684
+ return;
685
+ }
686
+ this.#valueEnded(frame);
687
+ }
688
+ #endScalar() {
689
+ const token = this.#scalar;
690
+ const slot = this.#scalarSlot;
691
+ this.#scalar = "";
692
+ this.#scalarSlot = void 0;
693
+ const value = scalarValue(token);
694
+ if (value !== void 0) {
695
+ this.#place(slot, value);
696
+ const path = this.#reportedPath(slot);
697
+ if (path !== void 0) this.#report({
698
+ kind: "set",
699
+ path,
700
+ value
701
+ });
702
+ }
703
+ this.#valueEnded(this.#stack.at(-1));
704
+ }
705
+ /** The value of the unterminated scalar at the end of the text, if it shows. */
706
+ #pendingScalar() {
707
+ const slot = this.#scalarSlot;
708
+ const token = this.#scalar;
709
+ if (slot === void 0 || token === "" || token.length > MAX_PENDING_SCALAR_LENGTH) return void 0;
710
+ const value = pendingScalarValue(token);
711
+ return value === void 0 ? void 0 : {
712
+ slot,
713
+ value
714
+ };
715
+ }
716
+ #openContainer(container) {
717
+ const slot = this.#valueSlot();
718
+ const path = this.#reportedPath(slot);
719
+ this.#place(slot, container);
720
+ this.#stack.push({
721
+ container,
722
+ slot,
723
+ path,
724
+ reportsInside: path !== void 0 && path.length < MAX_REPORTED_DEPTH,
725
+ size: 0,
726
+ key: void 0,
727
+ phase: Array.isArray(container) ? "value" : "key"
728
+ });
729
+ this.#pathCost += 1;
730
+ this.#dirty = true;
731
+ if (path !== void 0) this.#report({
732
+ kind: "set",
733
+ path,
734
+ value: Array.isArray(container) ? [] : {}
735
+ });
736
+ }
737
+ #closeContainer() {
738
+ const frame = this.#stack.pop();
739
+ if (frame === void 0) return;
740
+ this.#pathCost -= frame.size + 1;
741
+ this.#dirty = true;
742
+ if (frame.path !== void 0 && !frame.reportsInside) this.#report({
743
+ kind: "set",
744
+ path: frame.path,
745
+ value: frame.container
746
+ });
747
+ this.#valueEnded(this.#stack.at(-1));
748
+ }
749
+ /** A value in `frame`, or the root value when there is no frame, has ended. */
750
+ #valueEnded(frame) {
751
+ if (frame === void 0) {
752
+ if (this.#root !== void 0) this.#done = true;
753
+ return;
754
+ }
755
+ frame.phase = "comma";
756
+ }
757
+ /** Set the value at `slot` in the open path; nothing for a value in an invalid position. */
758
+ #place(slot, value) {
759
+ if (slot === void 0) return;
760
+ this.#dirty = true;
761
+ if (slot.kind === "root") {
762
+ this.#root = value;
763
+ return;
764
+ }
765
+ const frame = this.#stack.at(-1);
766
+ if (slot.kind === "element") {
767
+ const elements = frame.container;
768
+ if (slot.index === elements.length) {
769
+ frame.size++;
770
+ this.#pathCost++;
771
+ }
772
+ elements[slot.index] = value;
773
+ return;
774
+ }
775
+ const members = frame.container;
776
+ if (!Object.hasOwn(members, slot.key)) {
777
+ frame.size++;
778
+ this.#pathCost++;
779
+ }
780
+ setMember(members, slot.key, value);
781
+ }
782
+ /** A fresh snapshot: copies of the open containers, innermost first, each holding the copy of its open child. */
783
+ #copyOpenPath(pending) {
784
+ if (this.#stack.length === 0) return pending?.slot.kind === "root" ? pending.value : this.#root;
785
+ let child;
786
+ let childSlot;
787
+ for (let depth = this.#stack.length - 1; depth >= 0; depth--) {
788
+ const frame = this.#stack[depth];
789
+ const copy = Array.isArray(frame.container) ? frame.container.slice() : { ...frame.container };
790
+ if (depth === this.#stack.length - 1 && pending !== void 0) setSlot(copy, pending.slot, pending.value);
791
+ if (child !== void 0 && childSlot !== void 0) setSlot(copy, childSlot, child);
792
+ child = copy;
793
+ childSlot = frame.slot;
794
+ }
795
+ return childSlot?.kind === "root" ? child : this.#root;
796
+ }
797
+ };
798
+ /**
799
+ * The arguments of one streaming tool call: the raw text, for the one full parse when the call ends, and a
800
+ * `StreamingJsonParser` for the partial arguments in between. Providers keep one per call in their own stream state,
801
+ * never on the content block, so the raw text never reaches partial messages or transcripts.
802
+ */
803
+ var ToolCallArgumentsStream = class {
804
+ #text = "";
805
+ #parser = new StreamingJsonParser();
806
+ #snapshot = void 0;
807
+ #arguments = {};
808
+ /** The raw argument text received so far. */
809
+ get text() {
810
+ return this.#text;
811
+ }
812
+ /** Append a piece of argument text; returns the partial arguments, a new object whenever they changed. */
813
+ append(delta) {
814
+ this.#text += delta;
815
+ this.#parser.append(delta);
816
+ return this.#partial();
817
+ }
818
+ /**
819
+ * Take the provider's complete argument text. When it continues the text so far, returns the missing piece as
820
+ * `delta`; otherwise starts over with `text`. Either way returns the partial arguments of `text`.
821
+ */
822
+ replace(text) {
823
+ if (text.startsWith(this.#text)) {
824
+ const delta = text.slice(this.#text.length);
825
+ return {
826
+ delta,
827
+ arguments: delta === "" ? this.#partial() : this.append(delta)
828
+ };
829
+ }
830
+ this.#text = "";
831
+ this.#parser = new StreamingJsonParser();
832
+ return {
833
+ delta: void 0,
834
+ arguments: this.append(text)
835
+ };
836
+ }
837
+ /** The final arguments: one full parse of the complete text, which reports malformed arguments. */
838
+ finish() {
839
+ return parseToolCallArguments(this.#text);
840
+ }
841
+ #partial() {
842
+ const snapshot = this.#parser.snapshot();
843
+ if (snapshot === this.#snapshot) return this.#arguments;
844
+ this.#snapshot = snapshot;
845
+ this.#arguments = typeof snapshot === "object" && snapshot !== null && !Array.isArray(snapshot) ? snapshot : {};
846
+ return this.#arguments;
847
+ }
848
+ };
849
+ const SIMPLE_ESCAPES = {
850
+ "\"": "\"",
851
+ "\\": "\\",
852
+ "/": "/",
853
+ b: "\b",
854
+ f: "\f",
855
+ n: "\n",
856
+ r: "\r",
857
+ t: " "
858
+ };
859
+ function isDelimiter(char) {
860
+ return char === " " || char === " " || char === "\n" || char === "\r" || char === "," || char === ":" || char === "{" || char === "}" || char === "[" || char === "]" || char === "\"";
861
+ }
862
+ function isHexDigit(char) {
863
+ return char >= "0" && char <= "9" || char >= "a" && char <= "f" || char >= "A" && char <= "F";
864
+ }
865
+ /** The value of a complete number or literal token; `undefined` for anything else, which is dropped. */
866
+ function scalarValue(token) {
867
+ for (const [literal, value] of LITERALS) if (token === literal) return value;
868
+ return NUMBER.test(token) ? Number(token) : void 0;
869
+ }
870
+ /** The value an unterminated number or literal token shows. */
871
+ function pendingScalarValue(token) {
872
+ for (const [literal, value] of LITERALS) if (literal.startsWith(token)) return value;
873
+ if (NUMBER.test(token)) return Number(token);
874
+ const mantissa = NUMBER_WITHOUT_EXPONENT_DIGITS.exec(token);
875
+ return mantissa === null ? void 0 : Number(mantissa[1]);
876
+ }
877
+ function setSlot(container, slot, value) {
878
+ if (slot.kind === "element") container[slot.index] = value;
879
+ else if (slot.kind === "member") setMember(container, slot.key, value);
880
+ }
881
+ function setMember(members, key, value) {
882
+ if (key === "__proto__") Object.defineProperty(members, key, {
883
+ value,
884
+ writable: true,
885
+ enumerable: true,
886
+ configurable: true
887
+ });
888
+ else members[key] = value;
889
+ }
890
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/session-resources.js
891
+ const sessionResourceCleanups = /* @__PURE__ */ new Set();
892
+ function registerSessionResourceCleanup(cleanup) {
893
+ sessionResourceCleanups.add(cleanup);
894
+ return () => {
895
+ sessionResourceCleanups.delete(cleanup);
896
+ };
897
+ }
898
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/utils/uuid.js
899
+ const MAX_UUID_V7_TIMESTAMP = 0xffffffffffff;
900
+ const MAX_SEQUENCE = (1n << 41n) - 1n;
901
+ let lastOrdinaryTimestamp = -1;
902
+ let sequence;
903
+ /** Generate a time-ordered UUIDv7. A supplied timestamp is preserved for follower ids. */
904
+ function uuidv7(timestampMs) {
905
+ const requestedTimestamp = timestampMs ?? Date.now();
906
+ if (!Number.isInteger(requestedTimestamp) || requestedTimestamp < 0 || requestedTimestamp > MAX_UUID_V7_TIMESTAMP) throw new RangeError(`UUIDv7 timestamp must be an integer between 0 and ${MAX_UUID_V7_TIMESTAMP}`);
907
+ const effectiveTimestamp = timestampMs === void 0 ? Math.max(requestedTimestamp, lastOrdinaryTimestamp) : timestampMs;
908
+ if (timestampMs === void 0) lastOrdinaryTimestamp = effectiveTimestamp;
909
+ const bytes = /* @__PURE__ */ new Uint8Array(16);
910
+ globalThis.crypto.getRandomValues(bytes);
911
+ if (sequence === void 0) sequence = BigInt(bytes[1]) << 32n | BigInt(bytes[2]) << 24n | BigInt(bytes[3]) << 16n | BigInt(bytes[4]) << 8n | BigInt(bytes[5]);
912
+ else {
913
+ if (sequence === MAX_SEQUENCE) throw new RangeError("UUIDv7 generator sequence exhausted");
914
+ sequence++;
915
+ }
916
+ const timestamp = BigInt(effectiveTimestamp);
917
+ for (let index = 5; index >= 0; index--) bytes[index] = Number(timestamp >> BigInt((5 - index) * 8)) & 255;
918
+ bytes[6] = 112 | Number(sequence >> 37n & 15n);
919
+ bytes[7] = Number(sequence >> 29n & 255n);
920
+ bytes[8] = 128 | Number(sequence >> 23n & 63n);
921
+ bytes[9] = Number(sequence >> 15n & 255n);
922
+ bytes[10] = Number(sequence >> 7n & 255n);
923
+ bytes[11] = Number((sequence & 127n) << 1n) | bytes[11] & 1;
924
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));
925
+ return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
926
+ }
927
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/utils/abort-signals.js
928
+ function combineAbortSignals(signals) {
929
+ const activeSignals = signals.filter((signal) => signal !== void 0);
930
+ if (activeSignals.length === 0) return { cleanup: () => {} };
931
+ if (activeSignals.length === 1) return {
932
+ signal: activeSignals[0],
933
+ cleanup: () => {}
934
+ };
935
+ const controller = new AbortController();
936
+ const listeners = [];
937
+ const abort = (signal) => {
938
+ if (!controller.signal.aborted) controller.abort(signal.reason);
939
+ };
940
+ for (const signal of activeSignals) {
941
+ if (signal.aborted) {
942
+ abort(signal);
943
+ break;
944
+ }
945
+ const listener = () => abort(signal);
946
+ signal.addEventListener("abort", listener, { once: true });
947
+ listeners.push({
948
+ signal,
949
+ listener
950
+ });
951
+ }
952
+ return {
953
+ signal: controller.signal,
954
+ cleanup: () => {
955
+ for (const { signal, listener } of listeners) signal.removeEventListener("abort", listener);
956
+ }
957
+ };
958
+ }
959
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/utils/error-body.js
960
+ const MAX_PROVIDER_ERROR_BODY_CHARS = 4e3;
961
+ function normalizeProviderError(error) {
962
+ if (!(error instanceof Error)) return {
963
+ message: safeJsonStringify$1(error),
964
+ messageCarriesBody: false
965
+ };
966
+ const sdkError = error;
967
+ const status = extractStatus(sdkError);
968
+ const body = extractBody(sdkError);
969
+ const messageCarriesBody = body === void 0 || error.message.includes(body);
970
+ return {
971
+ status,
972
+ body,
973
+ message: status === void 0 && body === void 0 ? withCauseDetail(error) : error.message,
974
+ messageCarriesBody
975
+ };
976
+ }
977
+ const MAX_CAUSE_DEPTH = 5;
978
+ /**
979
+ * Connection-level failures carry no status or body, and SDKs replace the
980
+ * reason with a generic message (`openai`: `"Connection error."`). The real
981
+ * reason sits in the `cause` chain, often two levels deep (undici's
982
+ * `"fetch failed"` wraps `connect ECONNREFUSED ...`). Append the deepest
983
+ * cause so callers that surface only the message keep the reason.
984
+ */
985
+ function withCauseDetail(error) {
986
+ let deepest;
987
+ let current = error.cause;
988
+ for (let depth = 0; depth < MAX_CAUSE_DEPTH && current instanceof Error; depth++) {
989
+ deepest = current;
990
+ current = current.cause;
991
+ }
992
+ if (!deepest) return error.message;
993
+ let detail = (deepest.message || deepest.name).trim();
994
+ const code = deepest.code;
995
+ if ((typeof code === "string" || typeof code === "number") && !detail.includes(String(code))) detail = detail ? `${detail} (${code})` : String(code);
996
+ if (!detail || error.message.includes(detail)) return error.message;
997
+ return error.message ? `${error.message}: ${detail}` : detail;
998
+ }
999
+ /**
1000
+ * Probe the HTTP status, first numeric hit wins, in SDK-field order:
1001
+ * `statusCode` (Mistral) → `status` (`openai`, `@google/genai`) →
1002
+ * `$metadata.httpStatusCode` (Bedrock) → `$response.statusCode` (Bedrock).
1003
+ */
1004
+ function extractStatus(error) {
1005
+ if (typeof error.statusCode === "number") return error.statusCode;
1006
+ if (typeof error.status === "number") return error.status;
1007
+ if (typeof error.$metadata?.httpStatusCode === "number") return error.$metadata.httpStatusCode;
1008
+ if (typeof error.$response?.statusCode === "number") return error.$response.statusCode;
1009
+ }
1010
+ /**
1011
+ * Probe the raw body reason, first usable hit wins, in SDK-field order:
1012
+ * `body` string (Mistral) → `error` parsed JSON body object (`openai` SDK's
1013
+ * `this.error`) → `$response.body` (Bedrock). Empty objects and unread response
1014
+ * streams are treated as no body so they do not surface as `"{}"` or serialized
1015
+ * stream internals. The chosen body is truncated to the cap.
1016
+ */
1017
+ function extractBody(error) {
1018
+ const bodyText = pickBodyText(error);
1019
+ if (bodyText === void 0) return void 0;
1020
+ const trimmed = bodyText.trim();
1021
+ if (trimmed.length === 0) return void 0;
1022
+ return truncateErrorText(trimmed, MAX_PROVIDER_ERROR_BODY_CHARS);
1023
+ }
1024
+ function pickBodyText(error) {
1025
+ if (typeof error.body === "string") return error.body;
1026
+ if (isPlainNonEmptyObject(error.error)) return safeJsonStringify$1(error.error);
1027
+ const responseBody = error.$response?.body;
1028
+ if (typeof responseBody === "string") return responseBody;
1029
+ if (isReadableStreamLike(responseBody)) return void 0;
1030
+ if (isPlainNonEmptyObject(responseBody)) return safeJsonStringify$1(responseBody);
1031
+ }
1032
+ function isReadableStreamLike(value) {
1033
+ return typeof value === "object" && value !== null && "pipe" in value && typeof value.pipe === "function";
1034
+ }
1035
+ /**
1036
+ * Only a PLAIN object counts as an HTTP body. SDK error fields can hold class
1037
+ * instances instead of parsed bodies — AWS SDK v3's `$response.body` is an
1038
+ * HTTP stream/response wrapper object, and stringifying one produced garbage
1039
+ * like `{"_events":...}` as the "body", which then REPLACED `error.message`
1040
+ * in the composed display string. `error.message` is where the SDK puts the
1041
+ * real deserialized exception text ("Input is too long...", schema validation
1042
+ * details, ...), so the one useful string was discarded for noise. A class
1043
+ * instance yields no body, `messageCarriesBody` stays true, and the real
1044
+ * message survives. Complements the `pipe` sniffing above: web
1045
+ * ReadableStreams (pipeTo/pipeThrough, no `pipe`) and non-stream SDK wrapper
1046
+ * classes fail the prototype check, while parsed JSON bodies (plain objects
1047
+ * by construction) still pass.
1048
+ */
1049
+ function isPlainNonEmptyObject(value) {
1050
+ if (typeof value !== "object" || value === null) return false;
1051
+ const proto = Object.getPrototypeOf(value);
1052
+ if (proto !== Object.prototype && proto !== null) return false;
1053
+ return Object.keys(value).length > 0;
1054
+ }
1055
+ /**
1056
+ * Compose a display string from a normalized error. When the message already
1057
+ * carries the body (Anthropic / `@google/genai` happy path) or no body/status
1058
+ * was extracted, the message is returned unchanged. Otherwise the status and
1059
+ * body are surfaced, with an optional provider prefix.
1060
+ *
1061
+ * - no prefix: `"<status>: <body>"`
1062
+ * - prefix: `"<prefix> (<status>): <body>"`
1063
+ */
1064
+ function formatProviderError(norm, prefix) {
1065
+ if (norm.messageCarriesBody || norm.status === void 0 || norm.body === void 0) return prefix !== void 0 && norm.status !== void 0 ? `${prefix} (${norm.status}): ${norm.message}` : norm.message;
1066
+ return prefix !== void 0 ? `${prefix} (${norm.status}): ${norm.body}` : `${norm.status}: ${norm.body}`;
1067
+ }
1068
+ function truncateErrorText(text, maxChars) {
1069
+ if (text.length <= maxChars) return text;
1070
+ return `${ownedSlice(text, 0, maxChars)}... [truncated ${text.length - maxChars} chars]`;
1071
+ }
1072
+ function safeJsonStringify$1(value) {
1073
+ try {
1074
+ const serialized = JSON.stringify(value);
1075
+ return serialized === void 0 ? String(value) : serialized;
1076
+ } catch {
1077
+ return String(value);
1078
+ }
1079
+ }
1080
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/utils/headers.js
1081
+ function headersToRecord(headers) {
1082
+ const result = {};
1083
+ for (const [key, value] of headers.entries()) result[key] = value;
1084
+ return result;
1085
+ }
1086
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/utils/node-http-proxy.js
1087
+ const DEFAULT_PROXY_PORTS = {
1088
+ ftp: 21,
1089
+ gopher: 70,
1090
+ http: 80,
1091
+ https: 443,
1092
+ ws: 80,
1093
+ wss: 443
1094
+ };
1095
+ function getProxyEnv(key, env) {
1096
+ const lowercaseKey = key.toLowerCase();
1097
+ const uppercaseKey = key.toUpperCase();
1098
+ return env?.[lowercaseKey] || env?.[uppercaseKey] || getProviderEnvValue(lowercaseKey) || getProviderEnvValue(uppercaseKey) || "";
1099
+ }
1100
+ function parseProxyTargetUrl(targetUrl) {
1101
+ if (targetUrl instanceof URL) return targetUrl;
1102
+ try {
1103
+ return new URL(targetUrl);
1104
+ } catch {
1105
+ return;
1106
+ }
1107
+ }
1108
+ function stripBrackets(host) {
1109
+ return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
1110
+ }
1111
+ function parseNoProxyEntry(entry) {
1112
+ const trimmed = entry.trim().toLowerCase();
1113
+ if (!trimmed) return void 0;
1114
+ if (trimmed.startsWith("[")) {
1115
+ const closingBracket = trimmed.indexOf("]");
1116
+ if (closingBracket !== -1) {
1117
+ const host = trimmed.slice(1, closingBracket);
1118
+ const rest = trimmed.slice(closingBracket + 1);
1119
+ if (rest.startsWith(":")) {
1120
+ const port = Number.parseInt(rest.slice(1), 10);
1121
+ return {
1122
+ host,
1123
+ port: Number.isNaN(port) ? 0 : port
1124
+ };
1125
+ }
1126
+ return {
1127
+ host,
1128
+ port: 0
1129
+ };
1130
+ }
1131
+ }
1132
+ if (trimmed.includes(":") && trimmed.split(":").length > 2) return {
1133
+ host: trimmed,
1134
+ port: 0
1135
+ };
1136
+ const colonIndex = trimmed.lastIndexOf(":");
1137
+ if (colonIndex !== -1 && colonIndex === trimmed.indexOf(":")) {
1138
+ const host = trimmed.slice(0, colonIndex);
1139
+ const port = Number.parseInt(trimmed.slice(colonIndex + 1), 10);
1140
+ if (!Number.isNaN(port)) return {
1141
+ host,
1142
+ port
1143
+ };
1144
+ }
1145
+ return {
1146
+ host: trimmed,
1147
+ port: 0
1148
+ };
1149
+ }
1150
+ function shouldProxyHostname(hostname, port, env) {
1151
+ const noProxy = getProxyEnv("no_proxy", env).toLowerCase();
1152
+ if (!noProxy) return true;
1153
+ if (noProxy === "*") return false;
1154
+ const normalizedTargetHost = stripBrackets(hostname.toLowerCase());
1155
+ return noProxy.split(/[,\s]/).every((entry) => {
1156
+ const parsed = parseNoProxyEntry(entry);
1157
+ if (!parsed) return true;
1158
+ if (parsed.port && parsed.port !== port) return true;
1159
+ let domain = stripBrackets(parsed.host);
1160
+ if (domain.startsWith("*.")) domain = domain.slice(2);
1161
+ else if (domain.startsWith(".") || domain.startsWith("*")) domain = domain.slice(1);
1162
+ if (!domain) return true;
1163
+ if (normalizedTargetHost === domain) return false;
1164
+ if (normalizedTargetHost.endsWith(`.${domain}`)) return false;
1165
+ return true;
1166
+ });
1167
+ }
1168
+ function getProxyForUrl(targetUrl, env) {
1169
+ const parsedUrl = parseProxyTargetUrl(targetUrl);
1170
+ if (!parsedUrl?.protocol || !parsedUrl.host) return "";
1171
+ const protocol = parsedUrl.protocol.split(":", 1)[0];
1172
+ if (!shouldProxyHostname(stripBrackets(parsedUrl.hostname || parsedUrl.host.replace(/:\d*$/, "")), Number.parseInt(parsedUrl.port, 10) || DEFAULT_PROXY_PORTS[protocol] || 0, env)) return "";
1173
+ let proxy = getProxyEnv(`${protocol}_proxy`, env) || getProxyEnv("all_proxy", env);
1174
+ if (proxy && !proxy.includes("://")) proxy = `${protocol}://${proxy}`;
1175
+ return proxy;
1176
+ }
1177
+ const UNSUPPORTED_PROXY_PROTOCOL_MESSAGE = "Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.";
1178
+ function resolveHttpProxyUrlForTarget(targetUrl, env) {
1179
+ const proxy = getProxyForUrl(targetUrl, env);
1180
+ if (!proxy) return;
1181
+ let proxyUrl;
1182
+ try {
1183
+ proxyUrl = new URL(proxy);
1184
+ } catch (error) {
1185
+ throw new Error(`Invalid proxy URL ${JSON.stringify(proxy)}: ${error instanceof Error ? error.message : String(error)}`);
1186
+ }
1187
+ if (proxyUrl.protocol !== "http:" && proxyUrl.protocol !== "https:") throw new Error(`${UNSUPPORTED_PROXY_PROTOCOL_MESSAGE} Got ${proxyUrl.protocol}`);
1188
+ return proxyUrl;
1189
+ }
1190
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/api/constrained-sampling.js
1191
+ var UnsupportedStrictJsonSchemaError = class extends Error {};
1192
+ const UNSUPPORTED_STRICT_SCHEMA_KEYS = [
1193
+ "$ref",
1194
+ "$defs",
1195
+ "definitions",
1196
+ "allOf",
1197
+ "oneOf",
1198
+ "patternProperties",
1199
+ "dependentSchemas",
1200
+ "dependencies",
1201
+ "unevaluatedProperties",
1202
+ "propertyNames",
1203
+ "contains",
1204
+ "prefixItems",
1205
+ "not",
1206
+ "if",
1207
+ "then",
1208
+ "else"
1209
+ ];
1210
+ function isJsonSchemaObject(value) {
1211
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1212
+ }
1213
+ function isStructuredSchema(schema) {
1214
+ if (!isJsonSchemaObject(schema)) return false;
1215
+ const types = typeof schema.type === "string" ? [schema.type] : Array.isArray(schema.type) ? schema.type : [];
1216
+ return types.includes("object") || types.includes("array") || schema.properties !== void 0 || schema.items !== void 0;
1217
+ }
1218
+ function schemaAllowsNull(schema) {
1219
+ if (!isJsonSchemaObject(schema)) return false;
1220
+ if (schema.type === "null" || Array.isArray(schema.type) && schema.type.includes("null")) return true;
1221
+ if (schema.const === null || Array.isArray(schema.enum) && schema.enum.includes(null)) return true;
1222
+ return Array.isArray(schema.anyOf) && schema.anyOf.some((variant) => schemaAllowsNull(variant));
1223
+ }
1224
+ function makeJsonSchemaNodeStrict(schema, isUnsupportedKeyword) {
1225
+ if (!isJsonSchemaObject(schema)) throw new UnsupportedStrictJsonSchemaError("boolean schemas are unsupported");
1226
+ for (const key of UNSUPPORTED_STRICT_SCHEMA_KEYS) if (schema[key] !== void 0) throw new UnsupportedStrictJsonSchemaError(`${key} schemas are unsupported`);
1227
+ if (isUnsupportedKeyword) {
1228
+ for (const [key, value] of Object.entries(schema)) if (isUnsupportedKeyword(key, value)) throw new UnsupportedStrictJsonSchemaError(`${key}: ${JSON.stringify(value)} is unsupported`);
1229
+ }
1230
+ if (schema.type === void 0 && schema.anyOf === void 0 && schema.enum === void 0) throw new UnsupportedStrictJsonSchemaError("schemas without a type are unsupported");
1231
+ if (schema.anyOf !== void 0) {
1232
+ if (!Array.isArray(schema.anyOf) || schema.anyOf.length === 0) throw new UnsupportedStrictJsonSchemaError("anyOf must contain at least one schema");
1233
+ for (const variant of schema.anyOf) {
1234
+ if (isStructuredSchema(variant)) throw new UnsupportedStrictJsonSchemaError("object and array unions are unsupported");
1235
+ makeJsonSchemaNodeStrict(variant, isUnsupportedKeyword);
1236
+ }
1237
+ }
1238
+ if (schema.items !== void 0) {
1239
+ if (Array.isArray(schema.items)) throw new UnsupportedStrictJsonSchemaError("tuple schemas are unsupported");
1240
+ makeJsonSchemaNodeStrict(schema.items, isUnsupportedKeyword);
1241
+ }
1242
+ const isObjectSchema = schema.type === "object";
1243
+ if (schema.properties !== void 0 && !isObjectSchema) throw new UnsupportedStrictJsonSchemaError("properties require type object");
1244
+ if (!isObjectSchema) return;
1245
+ if (schema.additionalProperties !== void 0 && schema.additionalProperties !== false) throw new UnsupportedStrictJsonSchemaError("schema-valued or true additionalProperties is unsupported");
1246
+ if (schema.properties !== void 0 && !isJsonSchemaObject(schema.properties)) throw new UnsupportedStrictJsonSchemaError("object properties must be a schema map");
1247
+ if (schema.required !== void 0 && (!Array.isArray(schema.required) || schema.required.some((key) => typeof key !== "string"))) throw new UnsupportedStrictJsonSchemaError("object required must be a string array");
1248
+ const properties = schema.properties ?? {};
1249
+ const propertyNames = Object.keys(properties);
1250
+ const required = new Set(Array.isArray(schema.required) ? schema.required : []);
1251
+ if ([...required].some((key) => !propertyNames.includes(key))) throw new UnsupportedStrictJsonSchemaError("required contains an unknown property");
1252
+ for (const [key, property] of Object.entries(properties)) {
1253
+ makeJsonSchemaNodeStrict(property, isUnsupportedKeyword);
1254
+ if (!required.has(key) && !schemaAllowsNull(property)) properties[key] = { anyOf: [property, { type: "null" }] };
1255
+ }
1256
+ schema.required = propertyNames;
1257
+ schema.additionalProperties = false;
1258
+ }
1259
+ /** Convert a tool schema to the strict subset expected by provider constrained sampling. */
1260
+ function makeStrictJsonSchema(schema, isUnsupportedKeyword) {
1261
+ const cloned = structuredClone(schema);
1262
+ if (!isJsonSchemaObject(cloned)) throw new UnsupportedStrictJsonSchemaError("root schema must have type object");
1263
+ makeJsonSchemaNodeStrict(cloned, isUnsupportedKeyword);
1264
+ if (cloned.type !== "object") throw new UnsupportedStrictJsonSchemaError("root schema must have type object");
1265
+ return cloned;
1266
+ }
1267
+ function getJsonSchemaToolParameters(tool, strict) {
1268
+ return strict === true ? makeStrictJsonSchema(tool.parameters) : tool.parameters;
1269
+ }
1270
+ function getGrammarToolInput(toolName, arguments_, inputProperty) {
1271
+ const input = arguments_[inputProperty];
1272
+ if (typeof input !== "string") throw new Error(`Grammar tool call "${toolName}" requires argument "${inputProperty}" to be a string.`);
1273
+ return input;
1274
+ }
1275
+ /**
1276
+ * Append `inputDelta` to a streaming grammar tool input and return the matching piece of its JSON arguments text, or
1277
+ * `undefined` for an empty delta. Costs time linear in the delta, never in the input so far.
1278
+ */
1279
+ function appendGrammarToolInputJsonDelta(buffer, inputProperty, inputDelta) {
1280
+ if (buffer.closed) throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`);
1281
+ if (inputDelta.length === 0) return void 0;
1282
+ buffer.input += inputDelta;
1283
+ return grammarToolInputJsonStart(buffer, inputProperty) + JSON.stringify(inputDelta).slice(1, -1);
1284
+ }
1285
+ /**
1286
+ * Close a streaming grammar tool input and return the rest of its JSON arguments text. `finalInput` is the complete
1287
+ * input when the provider sends one; it must continue the input streamed so far. Closing again with the same input
1288
+ * returns `undefined`.
1289
+ */
1290
+ function closeGrammarToolInputJson(buffer, inputProperty, finalInput) {
1291
+ if (buffer.closed) {
1292
+ if (finalInput === void 0 || finalInput === buffer.input) return void 0;
1293
+ throw new Error(`grammar tool input for property "${inputProperty}" changed after it was closed`);
1294
+ }
1295
+ if (finalInput !== void 0 && !finalInput.startsWith(buffer.input)) throw new Error(`grammar tool input for property "${inputProperty}" changed non-monotonically`);
1296
+ const rest = finalInput === void 0 ? "" : finalInput.slice(buffer.input.length);
1297
+ if (finalInput !== void 0) buffer.input = finalInput;
1298
+ buffer.closed = true;
1299
+ return `${grammarToolInputJsonStart(buffer, inputProperty)}${JSON.stringify(rest).slice(1, -1)}"}`;
1300
+ }
1301
+ /** The opening of the JSON arguments text, once. */
1302
+ function grammarToolInputJsonStart(buffer, inputProperty) {
1303
+ if (buffer.started) return "";
1304
+ buffer.started = true;
1305
+ return `{${JSON.stringify(inputProperty)}:"`;
1306
+ }
1307
+ function inferGrammarInputProperty(tool) {
1308
+ const schema = tool.parameters;
1309
+ if (schema.type !== "object") throw new Error("grammar constrained sampling requires an object parameter schema");
1310
+ if (!Array.isArray(schema.required) || schema.required.length !== 1 || typeof schema.required[0] !== "string") throw new Error("grammar constrained sampling requires exactly one required string property");
1311
+ const inputProperty = schema.required[0];
1312
+ if (!schema.properties?.[inputProperty]) throw new Error(`grammar constrained sampling requires a properties entry for ${inputProperty}`);
1313
+ if (schema.properties[inputProperty]?.type !== "string") throw new Error(`grammar constrained sampling property ${inputProperty} must have type string`);
1314
+ return inputProperty;
1315
+ }
1316
+ /**
1317
+ * Decide whether a JSON-schema tool is sent in strict mode. `isUnsupportedKeyword` lets a provider
1318
+ * reject extra keywords its strict mode does not accept, so "prefer" tools fall back to non-strict.
1319
+ */
1320
+ function resolveJsonSchemaStrictSampling(tool, supportsStrictMode, isUnsupportedKeyword) {
1321
+ const config = tool.constrainedSampling;
1322
+ if (!config || config.type !== "json_schema") return void 0;
1323
+ if (supportsStrictMode) try {
1324
+ makeStrictJsonSchema(tool.parameters, isUnsupportedKeyword);
1325
+ return true;
1326
+ } catch (error) {
1327
+ if (!(error instanceof UnsupportedStrictJsonSchemaError)) throw error;
1328
+ if (config.strict !== "require") return void 0;
1329
+ throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but ${error.message}.`);
1330
+ }
1331
+ if (config.strict === "require") throw new Error(`Tool "${tool.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`);
1332
+ }
1333
+ function resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools) {
1334
+ const config = tool.constrainedSampling;
1335
+ if (!config || config.type !== "grammar") return;
1336
+ if (!supportsOpenAIGrammarTools) return;
1337
+ const larkDefinition = config.variants.openai_lark;
1338
+ const regexDefinition = config.variants.openai_regex;
1339
+ const hasLarkDefinition = typeof larkDefinition === "string" && larkDefinition.trim().length > 0;
1340
+ const hasRegexDefinition = typeof regexDefinition === "string" && regexDefinition.trim().length > 0;
1341
+ if (!hasLarkDefinition && !hasRegexDefinition) throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);
1342
+ try {
1343
+ return {
1344
+ format: hasLarkDefinition ? "lark" : "regex",
1345
+ definition: hasLarkDefinition ? larkDefinition : regexDefinition,
1346
+ inputProperty: inferGrammarInputProperty(tool)
1347
+ };
1348
+ } catch (error) {
1349
+ const message = error instanceof Error ? error.message : String(error);
1350
+ throw new Error(`Tool "${tool.name}" cannot use grammar constrained sampling: ${message}.`);
1351
+ }
1352
+ }
1353
+ function createGrammarToolInputProperties(tools, supportsOpenAIGrammarTools) {
1354
+ const properties = /* @__PURE__ */ new Map();
1355
+ for (const tool of tools ?? []) {
1356
+ const grammar = resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools);
1357
+ if (grammar) properties.set(tool.name, grammar.inputProperty);
1358
+ }
1359
+ return properties;
1360
+ }
1361
+ function clampOpenAIPromptCacheKey(key) {
1362
+ if (key === void 0) return void 0;
1363
+ const chars = Array.from(key);
1364
+ if (chars.length <= 64) return key;
1365
+ return chars.slice(0, 64).join("");
1366
+ }
1367
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/utils/hash.js
1368
+ /** Fast deterministic hash to shorten long strings */
1369
+ function shortHash(str) {
1370
+ let h1 = 3735928559;
1371
+ let h2 = 1103547991;
1372
+ for (let i = 0; i < str.length; i++) {
1373
+ const ch = str.charCodeAt(i);
1374
+ h1 = Math.imul(h1 ^ ch, 2654435761);
1375
+ h2 = Math.imul(h2 ^ ch, 1597334677);
1376
+ }
1377
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
1378
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
1379
+ return (h2 >>> 0).toString(36) + (h1 >>> 0).toString(36);
1380
+ }
1381
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/utils/sanitize-unicode.js
1382
+ /**
1383
+ * Removes unpaired Unicode surrogate characters from a string.
1384
+ *
1385
+ * Unpaired surrogates (high surrogates 0xD800-0xDBFF without matching low surrogates 0xDC00-0xDFFF,
1386
+ * or vice versa) cause JSON serialization errors in many API providers.
1387
+ *
1388
+ * Valid emoji and other characters outside the Basic Multilingual Plane use properly paired
1389
+ * surrogates and will NOT be affected by this function.
1390
+ *
1391
+ * @param text - The text to sanitize
1392
+ * @returns The sanitized text with unpaired surrogates removed
1393
+ *
1394
+ * @example
1395
+ * // Valid emoji (properly paired surrogates) are preserved
1396
+ * sanitizeSurrogates("Hello 🙈 World") // => "Hello 🙈 World"
1397
+ *
1398
+ * // Unpaired high surrogate is removed
1399
+ * const unpaired = String.fromCharCode(0xD83D); // high surrogate without low
1400
+ * sanitizeSurrogates(`Text ${unpaired} here`) // => "Text here"
1401
+ */
1402
+ function sanitizeSurrogates(text) {
1403
+ return text.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "");
1404
+ }
1405
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/api/transform-messages.js
1406
+ const NON_VISION_USER_IMAGE_PLACEHOLDER = "(image omitted: model does not support images)";
1407
+ const NON_VISION_TOOL_IMAGE_PLACEHOLDER = "(tool image omitted: model does not support images)";
1408
+ function replaceImagesWithPlaceholder(content, placeholder) {
1409
+ const result = [];
1410
+ let previousWasPlaceholder = false;
1411
+ for (const block of content) {
1412
+ if (block.type === "image") {
1413
+ if (!previousWasPlaceholder) result.push({
1414
+ type: "text",
1415
+ text: placeholder
1416
+ });
1417
+ previousWasPlaceholder = true;
1418
+ continue;
1419
+ }
1420
+ result.push(block);
1421
+ previousWasPlaceholder = block.text === placeholder;
1422
+ }
1423
+ return result;
1424
+ }
1425
+ function downgradeUnsupportedImages(messages, model) {
1426
+ if (model.input.includes("image")) return messages;
1427
+ return messages.map((msg) => {
1428
+ if (msg.role === "user" && Array.isArray(msg.content)) return {
1429
+ ...msg,
1430
+ content: replaceImagesWithPlaceholder(msg.content, NON_VISION_USER_IMAGE_PLACEHOLDER)
1431
+ };
1432
+ if (msg.role === "toolResult") return {
1433
+ ...msg,
1434
+ content: replaceImagesWithPlaceholder(msg.content, NON_VISION_TOOL_IMAGE_PLACEHOLDER)
1435
+ };
1436
+ return msg;
1437
+ });
1438
+ }
1439
+ /**
1440
+ * Normalize tool call ID for cross-provider compatibility.
1441
+ * OpenAI Responses API generates IDs that are 450+ chars with special characters like `|`.
1442
+ * Anthropic APIs require IDs matching ^[a-zA-Z0-9_-]+$ (max 64 chars).
1443
+ */
1444
+ function transformMessages(messages, model, normalizeToolCallId) {
1445
+ const toolCallIdMap = /* @__PURE__ */ new Map();
1446
+ const transformed = downgradeUnsupportedImages(messages.map((msg) => msg.content == null ? {
1447
+ ...msg,
1448
+ content: []
1449
+ } : msg), model).map((msg) => {
1450
+ if (msg.role === "system" || msg.role === "user") return msg;
1451
+ if (msg.role === "toolResult") {
1452
+ const normalizedId = toolCallIdMap.get(msg.toolCallId);
1453
+ if (normalizedId && normalizedId !== msg.toolCallId) return {
1454
+ ...msg,
1455
+ toolCallId: normalizedId
1456
+ };
1457
+ return msg;
1458
+ }
1459
+ if (msg.role === "assistant") {
1460
+ const assistantMsg = msg;
1461
+ const isSameModel = assistantMsg.provider === model.provider && assistantMsg.api === model.api && assistantMsg.model === model.id;
1462
+ const transformedContent = assistantMsg.content.flatMap((block) => {
1463
+ if (block.type === "thinking") {
1464
+ if (!isSameModel) return [];
1465
+ if (block.redacted || block.thinkingSignature) return block;
1466
+ if (!block.thinking || block.thinking.trim() === "") return [];
1467
+ return block;
1468
+ }
1469
+ if (block.type === "text") {
1470
+ if (isSameModel) return block;
1471
+ return {
1472
+ type: "text",
1473
+ text: block.text
1474
+ };
1475
+ }
1476
+ if (block.type === "toolCall") {
1477
+ const toolCall = block;
1478
+ let normalizedToolCall = toolCall;
1479
+ if (!isSameModel && toolCall.thoughtSignature) {
1480
+ normalizedToolCall = { ...toolCall };
1481
+ delete normalizedToolCall.thoughtSignature;
1482
+ }
1483
+ if (!isSameModel && normalizeToolCallId) {
1484
+ const normalizedId = normalizeToolCallId(toolCall.id, model, assistantMsg);
1485
+ if (normalizedId !== toolCall.id) {
1486
+ toolCallIdMap.set(toolCall.id, normalizedId);
1487
+ normalizedToolCall = {
1488
+ ...normalizedToolCall,
1489
+ id: normalizedId
1490
+ };
1491
+ }
1492
+ }
1493
+ return normalizedToolCall;
1494
+ }
1495
+ return block;
1496
+ });
1497
+ return {
1498
+ ...assistantMsg,
1499
+ content: transformedContent
1500
+ };
1501
+ }
1502
+ return msg;
1503
+ });
1504
+ const result = [];
1505
+ let pendingToolCalls = [];
1506
+ let existingToolResultIds = /* @__PURE__ */ new Set();
1507
+ const heldSystemMessages = [];
1508
+ const closePendingToolCalls = () => {
1509
+ if (pendingToolCalls.length > 0) {
1510
+ for (const tc of pendingToolCalls) if (!existingToolResultIds.has(tc.id)) result.push({
1511
+ role: "toolResult",
1512
+ toolCallId: tc.id,
1513
+ toolName: tc.name,
1514
+ content: [{
1515
+ type: "text",
1516
+ text: "No result provided"
1517
+ }],
1518
+ isError: true,
1519
+ timestamp: Date.now()
1520
+ });
1521
+ pendingToolCalls = [];
1522
+ existingToolResultIds = /* @__PURE__ */ new Set();
1523
+ }
1524
+ result.push(...heldSystemMessages);
1525
+ heldSystemMessages.length = 0;
1526
+ };
1527
+ for (let i = 0; i < transformed.length; i++) {
1528
+ const msg = transformed[i];
1529
+ if (msg.role === "assistant") {
1530
+ closePendingToolCalls();
1531
+ const assistantMsg = msg;
1532
+ if (assistantMsg.stopReason === "error" || assistantMsg.stopReason === "aborted") continue;
1533
+ const toolCalls = assistantMsg.content.filter((b) => b.type === "toolCall");
1534
+ if (toolCalls.length > 0) {
1535
+ pendingToolCalls = toolCalls;
1536
+ existingToolResultIds = /* @__PURE__ */ new Set();
1537
+ }
1538
+ result.push(msg);
1539
+ } else if (msg.role === "toolResult") {
1540
+ existingToolResultIds.add(msg.toolCallId);
1541
+ result.push(msg);
1542
+ } else if (msg.role === "system") {
1543
+ if (pendingToolCalls.length > 0) heldSystemMessages.push(msg);
1544
+ else result.push(msg);
1545
+ } else if (msg.role === "user") {
1546
+ closePendingToolCalls();
1547
+ result.push(msg);
1548
+ } else result.push(msg);
1549
+ }
1550
+ closePendingToolCalls();
1551
+ return result;
1552
+ }
1553
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/api/openai-responses-shared.js
1554
+ function encodeTextSignatureV1(id, phase) {
1555
+ const payload = {
1556
+ v: 1,
1557
+ id
1558
+ };
1559
+ if (phase) payload.phase = phase;
1560
+ return JSON.stringify(payload);
1561
+ }
1562
+ function parseTextSignature(signature) {
1563
+ if (!signature) return void 0;
1564
+ if (signature.startsWith("{")) try {
1565
+ const parsed = JSON.parse(signature);
1566
+ if (parsed.v === 1 && typeof parsed.id === "string") {
1567
+ if (parsed.phase === "commentary" || parsed.phase === "final_answer") return {
1568
+ id: parsed.id,
1569
+ phase: parsed.phase
1570
+ };
1571
+ return { id: parsed.id };
1572
+ }
1573
+ } catch {}
1574
+ return { id: signature };
1575
+ }
1576
+ function convertToolResultOutput(model, content) {
1577
+ const textResult = content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
1578
+ const images = content.filter((c) => c.type === "image");
1579
+ const hasText = textResult.trim().length > 0;
1580
+ if (images.length === 0 || !model.input.includes("image")) return sanitizeSurrogates(hasText ? textResult : images.length > 0 ? "(see attached image)" : "(no tool output)");
1581
+ const output = [];
1582
+ if (hasText) output.push({
1583
+ type: "input_text",
1584
+ text: sanitizeSurrogates(textResult)
1585
+ });
1586
+ for (const image of images) output.push({
1587
+ type: "input_image",
1588
+ detail: "auto",
1589
+ image_url: `data:${image.mimeType};base64,${image.data}`
1590
+ });
1591
+ return output;
1592
+ }
1593
+ /**
1594
+ * How a Responses transport expresses tool changes.
1595
+ *
1596
+ * `additional_tools` items accumulate: a later item adds tools and replaces same-name
1597
+ * definitions from earlier items, but it cannot replace a top-level tool and cannot remove any
1598
+ * tool (verified with strict schemas on the OpenAI, Codex, and Copilot backends, October 2026).
1599
+ * Like Codex, every tool is therefore declared in `additional_tools` items, starting with one
1600
+ * at the head of the input, and removals are announced as text. Synthetic tool search can
1601
+ * only add tools. Without mid-conversation system messages there is nothing to anchor.
1602
+ */
1603
+ function getResponsesToolSupport(options) {
1604
+ if (options.supportsMidConvoSystemMessages && options.supportsAdditionalTools) return "changes";
1605
+ return options.supportsToolSearch ? "additions" : "none";
1606
+ }
1607
+ /**
1608
+ * Precedes every additional_tools item after the first. Without it, models read the latest item as
1609
+ * the complete tool set once a removal was announced; Codex precedes its incremental tool batches
1610
+ * with the same guidance. Restating the tools that are still unavailable keeps smaller models
1611
+ * (gpt-5.6-luna, gpt-6-luna) from calling them again after later loads (verified October 2026).
1612
+ */
1613
+ function renderIncrementalToolsNotice(unavailable) {
1614
+ const notice = "This is an incremental tools update. Previously declared tools remain available unless explicitly marked unavailable. A tool declared again here is available again, and its latest definition replaces the earlier one.";
1615
+ return unavailable.size > 0 ? `${notice}\nStill unavailable: ${[...unavailable].join(", ")}.` : notice;
1616
+ }
1617
+ function renderToolRemovalNotice(names) {
1618
+ return `The following tools are no longer available. Do not call them:\n${names.map((name) => `- ${name}`).join("\n")}`;
1619
+ }
1620
+ function convertResponsesMessages(model, context, allowedToolCallProviders, options) {
1621
+ const normalizedContext = resolveTranscript(context, options?.supportsMidConvoSystemMessages);
1622
+ const messages = [];
1623
+ const normalizeIdPart = (part) => {
1624
+ const sanitized = part.replace(/[^a-zA-Z0-9_-]/g, "_");
1625
+ return (sanitized.length > 64 ? sanitized.slice(0, 64) : sanitized).replace(/_+$/, "");
1626
+ };
1627
+ const buildForeignResponsesItemId = (itemId) => {
1628
+ const normalized = `fc_${shortHash(itemId)}`;
1629
+ return normalized.length > 64 ? normalized.slice(0, 64) : normalized;
1630
+ };
1631
+ const normalizeToolCallId = (id, _targetModel, source) => {
1632
+ if (!allowedToolCallProviders.has(model.provider)) return normalizeIdPart(id);
1633
+ if (!id.includes("|")) return normalizeIdPart(id);
1634
+ const [callId, itemId] = id.split("|");
1635
+ const normalizedCallId = normalizeIdPart(callId);
1636
+ let normalizedItemId = source.provider !== model.provider || source.api !== model.api ? buildForeignResponsesItemId(itemId) : normalizeIdPart(itemId);
1637
+ if (!normalizedItemId.startsWith("fc_")) normalizedItemId = normalizeIdPart(`fc_${normalizedItemId}`);
1638
+ return `${normalizedCallId}|${normalizedItemId}`;
1639
+ };
1640
+ const transformedMessages = transformMessages(normalizedContext.messages, model, normalizeToolCallId);
1641
+ const toolSupport = getResponsesToolSupport(options ?? {});
1642
+ const transcriptTools = resolveTranscriptTools(normalizedContext.messages, toolSupport);
1643
+ let declaredAdditionalTools = false;
1644
+ /** Tools announced as removed and not declared again since. */
1645
+ const unavailableTools = /* @__PURE__ */ new Set();
1646
+ const appendSystemToolAdditions = (message, seed) => {
1647
+ const tools = message.toolsAdded ?? [];
1648
+ for (const tool of tools) unavailableTools.delete(tool.name);
1649
+ if (tools.length === 0) return;
1650
+ if (toolSupport === "changes") {
1651
+ if (declaredAdditionalTools) messages.push({
1652
+ role: instructionRole,
1653
+ content: renderIncrementalToolsNotice(unavailableTools)
1654
+ });
1655
+ declaredAdditionalTools = true;
1656
+ messages.push({
1657
+ type: "additional_tools",
1658
+ role: "developer",
1659
+ tools: convertResponsesTools(tools, options?.toolOptions)
1660
+ });
1661
+ return;
1662
+ }
1663
+ if (toolSupport !== "additions") return;
1664
+ const names = tools.map((tool) => tool.name);
1665
+ const callId = `pi_tool_load_${shortHash(`${seed}:${names.join(",")}`)}`;
1666
+ messages.push({
1667
+ type: "tool_search_call",
1668
+ call_id: callId,
1669
+ execution: "client",
1670
+ status: "completed",
1671
+ arguments: {
1672
+ query: names.join(" "),
1673
+ limit: names.length
1674
+ }
1675
+ });
1676
+ messages.push({
1677
+ type: "tool_search_output",
1678
+ call_id: callId,
1679
+ execution: "client",
1680
+ status: "completed",
1681
+ tools: convertResponsesTools(tools, {
1682
+ ...options?.toolOptions,
1683
+ toolSearchResult: true
1684
+ })
1685
+ });
1686
+ };
1687
+ const pushConfigurationUpdate = (effort) => {
1688
+ messages.push({
1689
+ type: "configuration_update",
1690
+ reasoning: { effort }
1691
+ });
1692
+ };
1693
+ const compat = model.compat;
1694
+ const instructionRole = model.reasoning && compat?.supportsDeveloperRole !== false ? "developer" : "system";
1695
+ let msgIndex = 0;
1696
+ let sourceIndex = 0;
1697
+ let systemIndex = 0;
1698
+ for (const msg of transformedMessages) {
1699
+ const isLeadingSystemMessage = sourceIndex++ === 0 && msg.role === "system";
1700
+ if (msg.role === "system") {
1701
+ const anchorsToolChanges = systemIndex++ >= transcriptTools.foldedSystemMessages;
1702
+ if (anchorsToolChanges) appendSystemToolAdditions(msg, `system:${msgIndex}`);
1703
+ const parts = [isLeadingSystemMessage ? getSystemMessageText(msg) : renderSystemMessageUpdate(msg)];
1704
+ if (anchorsToolChanges) {
1705
+ const added = new Set((msg.toolsAdded ?? []).map((tool) => tool.name));
1706
+ const removed = (msg.toolsRemoved ?? []).map((tool) => tool.name).filter((name) => !added.has(name));
1707
+ if (removed.length > 0) parts.push(renderToolRemovalNotice(removed));
1708
+ for (const name of removed) unavailableTools.add(name);
1709
+ }
1710
+ const text = parts.filter((part) => part.length > 0).join("\n\n");
1711
+ if (text.length > 0) messages.push({
1712
+ role: instructionRole,
1713
+ content: sanitizeSurrogates(text)
1714
+ });
1715
+ } else if (msg.role === "user") {
1716
+ if (typeof msg.content === "string") messages.push({
1717
+ role: "user",
1718
+ content: [{
1719
+ type: "input_text",
1720
+ text: sanitizeSurrogates(msg.content)
1721
+ }]
1722
+ });
1723
+ else {
1724
+ const content = msg.content.map((item) => {
1725
+ if (item.type === "text") return {
1726
+ type: "input_text",
1727
+ text: sanitizeSurrogates(item.text)
1728
+ };
1729
+ return {
1730
+ type: "input_image",
1731
+ detail: "auto",
1732
+ image_url: `data:${item.mimeType};base64,${item.data}`
1733
+ };
1734
+ });
1735
+ if (content.length === 0) continue;
1736
+ messages.push({
1737
+ role: "user",
1738
+ content
1739
+ });
1740
+ }
1741
+ } else if (msg.role === "assistant") {
1742
+ const output = [];
1743
+ const assistantMsg = msg;
1744
+ const isSameProviderAndApi = assistantMsg.provider === model.provider && assistantMsg.api === model.api;
1745
+ const isSameModel = isSameProviderAndApi && assistantMsg.model === model.id;
1746
+ const isDifferentModel = isSameProviderAndApi && assistantMsg.model !== model.id;
1747
+ let textBlockIndex = 0;
1748
+ for (const block of msg.content) if (block.type === "thinking") {
1749
+ if (block.thinkingSignature) {
1750
+ const reasoningItem = JSON.parse(block.thinkingSignature);
1751
+ output.push(reasoningItem);
1752
+ }
1753
+ } else if (block.type === "text") {
1754
+ const textBlock = block;
1755
+ const parsedSignature = parseTextSignature(textBlock.textSignature);
1756
+ const fallbackMessageId = textBlockIndex === 0 ? `msg_pi_${msgIndex}` : `msg_pi_${msgIndex}_${textBlockIndex}`;
1757
+ textBlockIndex++;
1758
+ let msgId = parsedSignature?.id;
1759
+ if (!msgId) msgId = fallbackMessageId;
1760
+ else if (msgId.length > 64) msgId = `msg_${shortHash(msgId)}`;
1761
+ output.push({
1762
+ type: "message",
1763
+ role: "assistant",
1764
+ content: [{
1765
+ type: "output_text",
1766
+ text: sanitizeSurrogates(textBlock.text),
1767
+ annotations: []
1768
+ }],
1769
+ status: "completed",
1770
+ id: msgId,
1771
+ phase: parsedSignature?.phase
1772
+ });
1773
+ } else if (block.type === "toolCall") {
1774
+ const toolCall = block;
1775
+ const [callId, itemIdRaw] = toolCall.id.split("|");
1776
+ const customInputProperty = options?.grammarToolInputProperties?.get(toolCall.name);
1777
+ let itemId = itemIdRaw;
1778
+ const itemIdPrefix = customInputProperty === void 0 ? "fc_" : "ctc_";
1779
+ if (isDifferentModel || !itemId?.startsWith(itemIdPrefix)) itemId = void 0;
1780
+ if (customInputProperty !== void 0) output.push({
1781
+ type: "custom_tool_call",
1782
+ id: itemId,
1783
+ call_id: callId,
1784
+ name: toolCall.name,
1785
+ input: sanitizeSurrogates(getGrammarToolInput(toolCall.name, toolCall.arguments, customInputProperty)),
1786
+ ...isSameModel && toolCall.namespace !== void 0 ? { namespace: toolCall.namespace } : {}
1787
+ });
1788
+ else output.push({
1789
+ type: "function_call",
1790
+ id: itemId,
1791
+ call_id: callId,
1792
+ name: toolCall.name,
1793
+ arguments: JSON.stringify(toolCall.arguments),
1794
+ ...isSameModel && toolCall.namespace !== void 0 ? { namespace: toolCall.namespace } : {}
1795
+ });
1796
+ }
1797
+ if (output.length === 0) continue;
1798
+ if (options?.configurationUpdateEffort !== void 0 && isSameModel && msg.providerThinkingLevel !== void 0) pushConfigurationUpdate(msg.providerThinkingLevel);
1799
+ messages.push(...output);
1800
+ } else if (msg.role === "toolResult") {
1801
+ const [callId] = msg.toolCallId.split("|");
1802
+ const output = convertToolResultOutput(model, msg.content);
1803
+ if (options?.grammarToolInputProperties?.has(msg.toolName)) messages.push({
1804
+ type: "custom_tool_call_output",
1805
+ call_id: callId,
1806
+ output
1807
+ });
1808
+ else messages.push({
1809
+ type: "function_call_output",
1810
+ call_id: callId,
1811
+ output
1812
+ });
1813
+ }
1814
+ if (!isLeadingSystemMessage) msgIndex++;
1815
+ }
1816
+ if (options?.configurationUpdateEffort !== void 0) pushConfigurationUpdate(options.configurationUpdateEffort);
1817
+ return messages;
1818
+ }
1819
+ function convertResponsesTools(tools, options) {
1820
+ const defaultStrict = options?.strict === void 0 ? false : options.strict;
1821
+ const supportsStrictMode = options?.supportsStrictMode ?? true;
1822
+ const supportsOpenAIGrammarTools = options?.supportsOpenAIGrammarTools ?? false;
1823
+ return tools.map((tool) => {
1824
+ const grammar = resolveGrammarConstrainedSampling(tool, supportsOpenAIGrammarTools);
1825
+ if (grammar) return {
1826
+ type: "custom",
1827
+ name: tool.name,
1828
+ description: tool.description,
1829
+ format: {
1830
+ type: "grammar",
1831
+ syntax: grammar.format,
1832
+ definition: grammar.definition
1833
+ },
1834
+ ...options?.toolSearchResult ? { defer_loading: true } : {}
1835
+ };
1836
+ const strict = resolveJsonSchemaStrictSampling(tool, supportsStrictMode) ?? defaultStrict;
1837
+ const functionTool = {
1838
+ type: "function",
1839
+ name: tool.name,
1840
+ description: tool.description,
1841
+ parameters: getJsonSchemaToolParameters(tool, strict === true),
1842
+ ...options?.toolSearchResult ? { defer_loading: true } : {}
1843
+ };
1844
+ if (supportsStrictMode) functionTool.strict = strict;
1845
+ return functionTool;
1846
+ });
1847
+ }
1848
+ async function processResponsesStream(openaiStream, output, stream, model, options) {
1849
+ let sawTerminalResponseEvent = false;
1850
+ const outputSlots = /* @__PURE__ */ new Map();
1851
+ const unfinishedToolCalls = /* @__PURE__ */ new Set();
1852
+ const reasoningBlocksById = /* @__PURE__ */ new Map();
1853
+ const applyMessagePhaseStopReason = (item) => {
1854
+ if (item.type === "message" && item.phase === "final_answer") output.stopReason = "stop";
1855
+ };
1856
+ const getSlot = (outputIndex, type) => {
1857
+ const slot = outputSlots.get(outputIndex);
1858
+ return slot?.type === type ? slot : void 0;
1859
+ };
1860
+ const pushToolCallDelta = (slot, delta) => {
1861
+ if (delta === void 0) return;
1862
+ stream.push({
1863
+ type: "toolcall_delta",
1864
+ contentIndex: slot.contentIndex,
1865
+ delta,
1866
+ partial: output
1867
+ });
1868
+ };
1869
+ const createSlot = (outputIndex, item) => {
1870
+ if (item.type === "reasoning") {
1871
+ const block = {
1872
+ type: "thinking",
1873
+ thinking: ""
1874
+ };
1875
+ output.content.push(block);
1876
+ const slot = {
1877
+ type: "thinking",
1878
+ block,
1879
+ contentIndex: output.content.length - 1
1880
+ };
1881
+ outputSlots.set(outputIndex, slot);
1882
+ stream.push({
1883
+ type: "thinking_start",
1884
+ contentIndex: slot.contentIndex,
1885
+ partial: output
1886
+ });
1887
+ return slot;
1888
+ }
1889
+ if (item.type === "message") {
1890
+ applyMessagePhaseStopReason(item);
1891
+ const block = {
1892
+ type: "text",
1893
+ text: ""
1894
+ };
1895
+ output.content.push(block);
1896
+ const slot = {
1897
+ type: "text",
1898
+ block,
1899
+ contentIndex: output.content.length - 1
1900
+ };
1901
+ outputSlots.set(outputIndex, slot);
1902
+ stream.push({
1903
+ type: "text_start",
1904
+ contentIndex: slot.contentIndex,
1905
+ partial: output
1906
+ });
1907
+ return slot;
1908
+ }
1909
+ if (item.type === "function_call") {
1910
+ const args = new ToolCallArgumentsStream();
1911
+ const block = {
1912
+ type: "toolCall",
1913
+ id: `${item.call_id}|${item.id}`,
1914
+ name: item.name,
1915
+ arguments: item.arguments ? args.append(item.arguments) : {},
1916
+ ...item.namespace !== void 0 ? { namespace: item.namespace } : {}
1917
+ };
1918
+ output.content.push(block);
1919
+ unfinishedToolCalls.add(block);
1920
+ const slot = {
1921
+ type: "toolCall",
1922
+ block,
1923
+ contentIndex: output.content.length - 1,
1924
+ input: {
1925
+ kind: "json",
1926
+ arguments: args
1927
+ }
1928
+ };
1929
+ outputSlots.set(outputIndex, slot);
1930
+ stream.push({
1931
+ type: "toolcall_start",
1932
+ contentIndex: slot.contentIndex,
1933
+ partial: output
1934
+ });
1935
+ return slot;
1936
+ }
1937
+ if (item.type === "custom_tool_call") {
1938
+ const inputProperty = options?.grammarToolInputProperties?.get(item.name) ?? "input";
1939
+ const input = item.input || "";
1940
+ const block = {
1941
+ type: "toolCall",
1942
+ id: `${item.call_id}|${item.id}`,
1943
+ name: item.name,
1944
+ arguments: { [inputProperty]: input },
1945
+ ...item.namespace !== void 0 ? { namespace: item.namespace } : {}
1946
+ };
1947
+ output.content.push(block);
1948
+ unfinishedToolCalls.add(block);
1949
+ const slot = {
1950
+ type: "toolCall",
1951
+ block,
1952
+ contentIndex: output.content.length - 1,
1953
+ input: customInput(inputProperty, input)
1954
+ };
1955
+ outputSlots.set(outputIndex, slot);
1956
+ stream.push({
1957
+ type: "toolcall_start",
1958
+ contentIndex: slot.contentIndex,
1959
+ partial: output
1960
+ });
1961
+ return slot;
1962
+ }
1963
+ };
1964
+ const getOrCreateSlot = (outputIndex, item) => {
1965
+ return outputSlots.get(outputIndex) ?? createSlot(outputIndex, item);
1966
+ };
1967
+ const backfillReasoningSignatures = (responseOutput) => {
1968
+ for (const item of responseOutput) {
1969
+ if (item.type !== "reasoning" || !item.encrypted_content) continue;
1970
+ const block = reasoningBlocksById.get(item.id);
1971
+ if (!block?.thinkingSignature) continue;
1972
+ const storedItem = JSON.parse(block.thinkingSignature);
1973
+ if (storedItem.encrypted_content) continue;
1974
+ block.thinkingSignature = JSON.stringify({
1975
+ ...storedItem,
1976
+ encrypted_content: item.encrypted_content
1977
+ });
1978
+ }
1979
+ };
1980
+ const finalizeResponse = (response) => {
1981
+ sawTerminalResponseEvent = true;
1982
+ backfillReasoningSignatures(response.output ?? []);
1983
+ appendReasoningRemovals(output, response.input_transformations);
1984
+ if (response?.id) output.responseId = response.id;
1985
+ if (response?.usage) {
1986
+ const inputDetails = response.usage.input_tokens_details;
1987
+ const cachedTokens = inputDetails?.cached_tokens || 0;
1988
+ const cacheWriteTokens = inputDetails?.cache_write_tokens || 0;
1989
+ output.usage = {
1990
+ input: Math.max(0, (response.usage.input_tokens || 0) - cachedTokens - cacheWriteTokens),
1991
+ output: response.usage.output_tokens || 0,
1992
+ cacheRead: cachedTokens,
1993
+ cacheWrite: cacheWriteTokens,
1994
+ reasoning: response.usage.output_tokens_details?.reasoning_tokens || 0,
1995
+ totalTokens: response.usage.total_tokens || 0,
1996
+ cost: {
1997
+ input: 0,
1998
+ output: 0,
1999
+ cacheRead: 0,
2000
+ cacheWrite: 0,
2001
+ total: 0
2002
+ }
2003
+ };
2004
+ }
2005
+ calculateCost(model, output.usage);
2006
+ if (options?.applyServiceTierPricing) {
2007
+ const serviceTier = options.resolveServiceTier ? options.resolveServiceTier(response?.service_tier, options.serviceTier) : response?.service_tier ?? options.serviceTier;
2008
+ options.applyServiceTierPricing(output.usage, serviceTier);
2009
+ }
2010
+ const status = response?.status;
2011
+ const incompleteDetails = response?.incomplete_details;
2012
+ const incompleteReason = typeof incompleteDetails?.reason === "string" ? incompleteDetails.reason : void 0;
2013
+ output.rawStopReason = incompleteReason ? `${status}.${incompleteReason}` : status;
2014
+ const mappedStop = mapStopReason(status, incompleteReason);
2015
+ output.stopReason = mappedStop.stopReason;
2016
+ if (mappedStop.errorMessage === void 0) delete output.errorMessage;
2017
+ else output.errorMessage = mappedStop.errorMessage;
2018
+ if (output.content.some((b) => b.type === "toolCall") && output.stopReason === "stop") output.stopReason = "toolUse";
2019
+ };
2020
+ for await (const event of openaiStream) {
2021
+ await options?.onProviderStreamEvent?.(event, model);
2022
+ if (event.type === "response.created") output.responseId = event.response.id;
2023
+ else if (event.type === "response.output_item.added") createSlot(event.output_index, event.item);
2024
+ else if (event.type === "response.reasoning_summary_text.delta") {
2025
+ const slot = getSlot(event.output_index, "thinking");
2026
+ if (!slot) continue;
2027
+ slot.block.thinking += event.delta;
2028
+ stream.push({
2029
+ type: "thinking_delta",
2030
+ contentIndex: slot.contentIndex,
2031
+ delta: event.delta,
2032
+ partial: output
2033
+ });
2034
+ } else if (event.type === "response.reasoning_summary_part.done") {
2035
+ const slot = getSlot(event.output_index, "thinking");
2036
+ if (!slot) continue;
2037
+ slot.block.thinking += "\n\n";
2038
+ stream.push({
2039
+ type: "thinking_delta",
2040
+ contentIndex: slot.contentIndex,
2041
+ delta: "\n\n",
2042
+ partial: output
2043
+ });
2044
+ } else if (event.type === "response.reasoning_text.delta") {
2045
+ const slot = getSlot(event.output_index, "thinking");
2046
+ if (!slot) continue;
2047
+ slot.block.thinking += event.delta;
2048
+ stream.push({
2049
+ type: "thinking_delta",
2050
+ contentIndex: slot.contentIndex,
2051
+ delta: event.delta,
2052
+ partial: output
2053
+ });
2054
+ } else if (event.type === "response.output_text.delta") {
2055
+ const slot = getSlot(event.output_index, "text");
2056
+ if (!slot) continue;
2057
+ slot.block.text += event.delta;
2058
+ stream.push({
2059
+ type: "text_delta",
2060
+ contentIndex: slot.contentIndex,
2061
+ delta: event.delta,
2062
+ partial: output
2063
+ });
2064
+ } else if (event.type === "response.refusal.delta") {
2065
+ const slot = getSlot(event.output_index, "text");
2066
+ if (!slot) continue;
2067
+ slot.block.text += event.delta;
2068
+ stream.push({
2069
+ type: "text_delta",
2070
+ contentIndex: slot.contentIndex,
2071
+ delta: event.delta,
2072
+ partial: output
2073
+ });
2074
+ } else if (event.type === "response.function_call_arguments.delta") {
2075
+ const slot = getSlot(event.output_index, "toolCall");
2076
+ if (slot?.input.kind !== "json") continue;
2077
+ slot.block.arguments = slot.input.arguments.append(event.delta);
2078
+ pushToolCallDelta(slot, event.delta);
2079
+ } else if (event.type === "response.function_call_arguments.done") {
2080
+ const slot = getSlot(event.output_index, "toolCall");
2081
+ if (slot?.input.kind !== "json") continue;
2082
+ const replaced = slot.input.arguments.replace(event.arguments);
2083
+ slot.block.arguments = replaced.arguments;
2084
+ if (replaced.delta) pushToolCallDelta(slot, replaced.delta);
2085
+ } else if (event.type === "response.custom_tool_call_input.delta") {
2086
+ const slot = getSlot(event.output_index, "toolCall");
2087
+ if (slot?.input.kind !== "custom") continue;
2088
+ pushToolCallDelta(slot, appendCustomInput(slot.block, slot.input, event.delta));
2089
+ } else if (event.type === "response.custom_tool_call_input.done") {
2090
+ const slot = getSlot(event.output_index, "toolCall");
2091
+ if (slot?.input.kind !== "custom") continue;
2092
+ pushToolCallDelta(slot, closeCustomInput(slot.block, slot.input, event.input));
2093
+ } else if (event.type === "response.output_item.done") {
2094
+ const item = event.item;
2095
+ applyMessagePhaseStopReason(item);
2096
+ const slot = getOrCreateSlot(event.output_index, item);
2097
+ if (item.type === "reasoning" && slot?.type === "thinking") {
2098
+ const summaryText = item.summary?.map((s) => s.text).join("\n\n") || "";
2099
+ const contentText = item.content?.map((c) => c.text).join("\n\n") || "";
2100
+ slot.block.thinking = summaryText || contentText || slot.block.thinking;
2101
+ slot.block.thinkingSignature = JSON.stringify(item);
2102
+ reasoningBlocksById.set(item.id, slot.block);
2103
+ stream.push({
2104
+ type: "thinking_end",
2105
+ contentIndex: slot.contentIndex,
2106
+ content: slot.block.thinking,
2107
+ partial: output
2108
+ });
2109
+ outputSlots.delete(event.output_index);
2110
+ } else if (item.type === "message" && slot?.type === "text") {
2111
+ slot.block.text = item.content?.map((c) => c.type === "output_text" ? c.text : c.refusal).join("") || "";
2112
+ slot.block.textSignature = encodeTextSignatureV1(item.id, item.phase ?? void 0);
2113
+ stream.push({
2114
+ type: "text_end",
2115
+ contentIndex: slot.contentIndex,
2116
+ content: slot.block.text,
2117
+ partial: output
2118
+ });
2119
+ outputSlots.delete(event.output_index);
2120
+ } else if (item.type === "function_call" && slot?.type === "toolCall" && slot.input.kind === "json") {
2121
+ if (item.arguments) slot.input.arguments.replace(item.arguments);
2122
+ Object.assign(slot.block, slot.input.arguments.finish());
2123
+ if (item.namespace !== void 0) slot.block.namespace = item.namespace;
2124
+ unfinishedToolCalls.delete(slot.block);
2125
+ stream.push({
2126
+ type: "toolcall_end",
2127
+ contentIndex: slot.contentIndex,
2128
+ toolCall: slot.block,
2129
+ partial: output
2130
+ });
2131
+ outputSlots.delete(event.output_index);
2132
+ } else if (item.type === "custom_tool_call" && slot?.type === "toolCall" && slot.input.kind === "custom") {
2133
+ pushToolCallDelta(slot, closeCustomInput(slot.block, slot.input, item.input));
2134
+ if (item.namespace !== void 0) slot.block.namespace = item.namespace;
2135
+ unfinishedToolCalls.delete(slot.block);
2136
+ stream.push({
2137
+ type: "toolcall_end",
2138
+ contentIndex: slot.contentIndex,
2139
+ toolCall: slot.block,
2140
+ partial: output
2141
+ });
2142
+ outputSlots.delete(event.output_index);
2143
+ }
2144
+ } else if (event.type === "response.completed" || event.type === "response.incomplete") finalizeResponse(event.response);
2145
+ else if (event.type === "error") throw new Error(`Error Code ${event.code}: ${event.message}` || "Unknown error");
2146
+ else if (event.type === "response.failed") {
2147
+ sawTerminalResponseEvent = true;
2148
+ output.rawStopReason = event.response?.status;
2149
+ const error = event.response?.error;
2150
+ const details = event.response?.incomplete_details;
2151
+ const msg = error ? `${error.code || "unknown"}: ${error.message || "no message"}` : details?.reason ? `incomplete: ${details.reason}` : "Unknown error (no error details in response)";
2152
+ throw new Error(msg);
2153
+ }
2154
+ }
2155
+ if (!sawTerminalResponseEvent) throw new Error("OpenAI Responses stream ended before a terminal response event");
2156
+ if (output.stopReason === "toolUse") for (const toolCall of unfinishedToolCalls) throw new Error(`OpenAI Responses stream completed with an unfinished tool call: ${toolCall.name} (${toolCall.id})`);
2157
+ }
2158
+ /**
2159
+ * Record the replayed reasoning items the API withheld from the model, with the reason for each.
2160
+ * From GPT-6.2 on, OpenAI removes reasoning that follows an edit of earlier input (`prefix_mismatch`)
2161
+ * and reasoning created under another organization, end user, or model. A removal is reported again
2162
+ * on every later request that replays the item.
2163
+ *
2164
+ * `turn_boundary` removals are left out: models that use only current-turn reasoning (all models
2165
+ * before GPT-5.6) report every earlier turn's reasoning item on every request. That is their normal
2166
+ * behavior, and storing it would grow the session quadratically with the conversation.
2167
+ */
2168
+ function appendReasoningRemovals(output, transformations) {
2169
+ if (!Array.isArray(transformations)) return;
2170
+ const removals = transformations.filter((transformation) => transformation?.type === "reasoning" && transformation.action === "removed" && transformation.reason !== "turn_boundary");
2171
+ if (removals.length === 0) return;
2172
+ appendAssistantMessageDiagnostic(output, {
2173
+ type: "openai_input_transformations",
2174
+ timestamp: Date.now(),
2175
+ details: { transformations: removals.map(({ type, id, action, reason }) => ({
2176
+ type,
2177
+ id,
2178
+ action,
2179
+ reason
2180
+ })) }
2181
+ });
2182
+ }
2183
+ /** Stream state of a custom tool call that starts with `initialInput`. */
2184
+ function customInput(property, initialInput) {
2185
+ const buffer = {
2186
+ input: "",
2187
+ started: false,
2188
+ closed: false
2189
+ };
2190
+ return {
2191
+ kind: "custom",
2192
+ property,
2193
+ buffer,
2194
+ unsent: appendGrammarToolInputJsonDelta(buffer, property, initialInput) ?? ""
2195
+ };
2196
+ }
2197
+ /** Append to a streaming custom tool input; returns the matching piece of its JSON arguments text. */
2198
+ function appendCustomInput(block, input, delta) {
2199
+ return sendCustomInput(block, input, appendGrammarToolInputJsonDelta(input.buffer, input.property, delta));
2200
+ }
2201
+ /** Close a custom tool input with the provider's complete input, if it sent one. */
2202
+ function closeCustomInput(block, input, finalInput) {
2203
+ return sendCustomInput(block, input, closeGrammarToolInputJson(input.buffer, input.property, finalInput));
2204
+ }
2205
+ function sendCustomInput(block, input, jsonDelta) {
2206
+ block.arguments = { [input.property]: input.buffer.input };
2207
+ if (input.unsent === "") return jsonDelta;
2208
+ const sent = input.unsent + (jsonDelta ?? "");
2209
+ input.unsent = "";
2210
+ return sent;
2211
+ }
2212
+ function mapStopReason(status, incompleteReason) {
2213
+ if (!status) return { stopReason: "stop" };
2214
+ switch (status) {
2215
+ case "completed": return { stopReason: "stop" };
2216
+ case "incomplete":
2217
+ if (incompleteReason === "max_output_tokens") return { stopReason: "length" };
2218
+ return {
2219
+ stopReason: "error",
2220
+ errorMessage: incompleteReason ? `Response incomplete: ${incompleteReason}` : "Response incomplete without a provider reason"
2221
+ };
2222
+ case "failed":
2223
+ case "cancelled": return { stopReason: "error" };
2224
+ case "in_progress":
2225
+ case "queued": return { stopReason: "stop" };
2226
+ default: throw new Error(`Unhandled stop reason: ${status}`);
2227
+ }
2228
+ }
2229
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/utils/estimate.js
2230
+ const CHARS_PER_TOKEN = 3.5;
2231
+ const ESTIMATED_IMAGE_CHARS = 4800;
2232
+ function calculateContextTokens(usage) {
2233
+ return usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
2234
+ }
2235
+ function safeJsonStringify(value) {
2236
+ try {
2237
+ return JSON.stringify(value) ?? "undefined";
2238
+ } catch {
2239
+ return "[unserializable]";
2240
+ }
2241
+ }
2242
+ function estimateTextAndImageContentChars(content) {
2243
+ if (typeof content === "string") return content.length;
2244
+ let chars = 0;
2245
+ for (const block of content) chars += block.type === "text" ? block.text.length : ESTIMATED_IMAGE_CHARS;
2246
+ return chars;
2247
+ }
2248
+ function estimateTextTokens(text) {
2249
+ return Math.ceil(text.length / CHARS_PER_TOKEN);
2250
+ }
2251
+ function estimateTextAndImageContentTokens(content) {
2252
+ return Math.ceil(estimateTextAndImageContentChars(content) / CHARS_PER_TOKEN);
2253
+ }
2254
+ function estimateMessageTokens(message) {
2255
+ let chars = 0;
2256
+ if (message.role === "system") return estimateTextTokens(getSystemMessageText(message)) + estimateToolsTokens(message.toolsAdded) + estimateToolsTokens(message.toolsRemoved);
2257
+ if (message.role === "user") return estimateTextAndImageContentTokens(message.content);
2258
+ if (message.role === "toolResult") return estimateTextAndImageContentTokens(message.content);
2259
+ for (const block of message.content) if (block.type === "text") chars += block.text.length;
2260
+ else if (block.type === "thinking") chars += block.thinking.length;
2261
+ else chars += block.name.length + safeJsonStringify(block.arguments).length;
2262
+ return Math.ceil(chars / CHARS_PER_TOKEN);
2263
+ }
2264
+ function getLastAssistantUsageInfo(messages) {
2265
+ let latestPrefixTimestamp = Number.NEGATIVE_INFINITY;
2266
+ let usageInfo;
2267
+ for (let i = 0; i < messages.length; i++) {
2268
+ const message = messages[i];
2269
+ if (message.role === "assistant") {
2270
+ const assistant = message;
2271
+ if (assistant.timestamp >= latestPrefixTimestamp && assistant.stopReason !== "aborted" && assistant.stopReason !== "error" && calculateContextTokens(assistant.usage) > 0) usageInfo = {
2272
+ usage: assistant.usage,
2273
+ index: i
2274
+ };
2275
+ }
2276
+ latestPrefixTimestamp = Math.max(latestPrefixTimestamp, message.timestamp);
2277
+ }
2278
+ return usageInfo;
2279
+ }
2280
+ function estimateContextTokens(context) {
2281
+ const messages = "messages" in context ? context.messages : context;
2282
+ const usageInfo = getLastAssistantUsageInfo(messages);
2283
+ if (usageInfo) {
2284
+ const usageTokens = calculateContextTokens(usageInfo.usage);
2285
+ let trailingTokens = 0;
2286
+ for (let i = usageInfo.index + 1; i < messages.length; i++) trailingTokens += estimateMessageTokens(messages[i]);
2287
+ return {
2288
+ tokens: usageTokens + trailingTokens,
2289
+ usageTokens,
2290
+ trailingTokens,
2291
+ lastUsageIndex: usageInfo.index
2292
+ };
2293
+ }
2294
+ let tokens = 0;
2295
+ for (const message of messages) tokens += estimateMessageTokens(message);
2296
+ return {
2297
+ tokens,
2298
+ usageTokens: 0,
2299
+ trailingTokens: tokens,
2300
+ lastUsageIndex: null
2301
+ };
2302
+ }
2303
+ function estimateToolsTokens(tools) {
2304
+ if (!tools || tools.length === 0) return 0;
2305
+ return estimateTextTokens(safeJsonStringify(tools));
2306
+ }
2307
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/api/simple-options.js
2308
+ const CONTEXT_SAFETY_TOKENS = 4096;
2309
+ const CONTEXT_SAFETY_RATIO = .15;
2310
+ const MIN_OUTPUT_WITH_RATIO_MARGIN = 32768;
2311
+ const MIN_MAX_TOKENS = 1;
2312
+ /** Fit maxTokens into the context window, leaving room for the input being counted higher than estimated. */
2313
+ function clampMaxTokensToContext(model, context, maxTokens) {
2314
+ if (model.contextWindow <= 0) return Math.max(MIN_MAX_TOKENS, maxTokens);
2315
+ const input = estimateContextTokens(context).tokens;
2316
+ const margin = Math.max(CONTEXT_SAFETY_TOKENS, Math.ceil(input * CONTEXT_SAFETY_RATIO));
2317
+ let room = model.contextWindow - input - margin;
2318
+ if (room < MIN_OUTPUT_WITH_RATIO_MARGIN) room = Math.min(MIN_OUTPUT_WITH_RATIO_MARGIN, model.contextWindow - input - CONTEXT_SAFETY_TOKENS);
2319
+ return Math.min(maxTokens, Math.max(MIN_MAX_TOKENS, room));
2320
+ }
2321
+ function resolveSamplingParams(model, thinkingLevel, requestParams) {
2322
+ const effectiveThinkingLevel = clampThinkingLevel(model, thinkingLevel);
2323
+ const thinkingLevelParams = model.samplingParamsByThinkingLevel?.[effectiveThinkingLevel];
2324
+ return model.samplingParams || thinkingLevelParams || requestParams ? {
2325
+ ...model.samplingParams,
2326
+ ...thinkingLevelParams,
2327
+ ...requestParams
2328
+ } : void 0;
2329
+ }
2330
+ function buildBaseOptions(model, context, options, apiKey) {
2331
+ const samplingParams = resolveSamplingParams(model, options?.reasoning ?? "off", options?.samplingParams);
2332
+ return {
2333
+ temperature: options?.temperature,
2334
+ samplingParams,
2335
+ maxTokens: clampMaxTokensToContext(model, context, options?.maxTokens ?? model.maxTokens),
2336
+ signal: options?.signal,
2337
+ telemetry: options?.telemetry,
2338
+ apiKey: apiKey || options?.apiKey,
2339
+ fetch: options?.fetch,
2340
+ transport: options?.transport,
2341
+ cacheRetention: options?.cacheRetention,
2342
+ sessionId: options?.sessionId,
2343
+ disableContinuation: options?.disableContinuation,
2344
+ headers: options?.headers,
2345
+ identity: options?.identity,
2346
+ onPayload: options?.onPayload,
2347
+ onResponse: options?.onResponse,
2348
+ onProviderStreamEvent: options?.onProviderStreamEvent,
2349
+ timeoutMs: options?.timeoutMs,
2350
+ websocketConnectTimeoutMs: options?.websocketConnectTimeoutMs,
2351
+ maxRetries: options?.maxRetries,
2352
+ maxRetryDelayMs: options?.maxRetryDelayMs,
2353
+ metadata: options?.metadata,
2354
+ env: options?.env
2355
+ };
2356
+ }
2357
+ // node_modules/.pnpm/@earendil-works+pi-ai@1.6.0_3204f39f3ad26528ec3165fb3f7546e0/node_modules/@earendil-works/pi-ai/dist/api/openai-codex-responses.js
2358
+ const DEFAULT_CODEX_BASE_URL = "https://chatgpt.com/backend-api";
2359
+ const JWT_CLAIM_PATH = "https://api.openai.com/auth";
2360
+ const DEFAULT_MAX_RETRIES = 0;
2361
+ const BASE_DELAY_MS = 1e3;
2362
+ const DEFAULT_MAX_RETRY_DELAY_MS = 6e4;
2363
+ const DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS = 15e3;
2364
+ const REQUEST_COMPRESSION_ZSTD_LEVEL = 3;
2365
+ const CODEX_TOOL_CALL_PROVIDERS = /* @__PURE__ */ new Set([
2366
+ "openai",
2367
+ "openai-codex",
2368
+ "opencode"
2369
+ ]);
2370
+ const WEBSOCKET_MESSAGE_TOO_BIG_CLOSE_CODE = 1009;
2371
+ const WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE = "websocket_connection_limit_reached";
2372
+ const PREVIOUS_RESPONSE_NOT_FOUND_CODE = "previous_response_not_found";
2373
+ const MIN_OUTPUT_TOKENS = 16;
2374
+ const CONFIGURATION_UPDATE_REQUEST_EFFORT = "medium";
2375
+ const CODEX_RESPONSE_STATUSES = /* @__PURE__ */ new Set([
2376
+ "completed",
2377
+ "incomplete",
2378
+ "failed",
2379
+ "cancelled",
2380
+ "queued",
2381
+ "in_progress"
2382
+ ]);
2383
+ function assertSuccessfulOutput(output) {
2384
+ if (output.stopReason === "pending") throw new Error("Codex stream ended without a stop reason");
2385
+ if (output.stopReason === "error" || output.stopReason === "aborted") throw new Error(output.errorMessage || "An unknown error occurred");
2386
+ }
2387
+ function isTerminalRateLimitError(errorText) {
2388
+ return /GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(errorText);
2389
+ }
2390
+ function isRetryableError(status, errorText) {
2391
+ if (status === 429 && isTerminalRateLimitError(errorText)) return false;
2392
+ if (status === 429 || status === 500 || status === 502 || status === 503 || status === 504) return true;
2393
+ return /rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(errorText);
2394
+ }
2395
+ function getRetryAfterDelayMs(headers) {
2396
+ const retryAfterMs = headers.get("retry-after-ms");
2397
+ if (retryAfterMs !== null) {
2398
+ const millis = Number(retryAfterMs);
2399
+ if (Number.isFinite(millis)) return Math.max(0, millis);
2400
+ }
2401
+ const retryAfter = headers.get("retry-after");
2402
+ if (!retryAfter) return;
2403
+ const seconds = Number(retryAfter);
2404
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
2405
+ const date = Date.parse(retryAfter);
2406
+ if (!Number.isNaN(date)) return Math.max(0, date - Date.now());
2407
+ }
2408
+ var RetryDelayExceededError = class extends Error {};
2409
+ function validateRetryDelayMs(delayMs, options) {
2410
+ const maxRetryDelayMs = options?.maxRetryDelayMs ?? DEFAULT_MAX_RETRY_DELAY_MS;
2411
+ if (maxRetryDelayMs > 0 && delayMs > maxRetryDelayMs) throw new RetryDelayExceededError(`Server requested ${Math.ceil(delayMs / 1e3)}s retry delay (max: ${Math.ceil(maxRetryDelayMs / 1e3)}s)`);
2412
+ return delayMs;
2413
+ }
2414
+ function sleep(ms, signal) {
2415
+ return new Promise((resolve, reject) => {
2416
+ if (signal?.aborted) {
2417
+ reject(/* @__PURE__ */ new Error("Request was aborted"));
2418
+ return;
2419
+ }
2420
+ const onAbort = () => {
2421
+ clearTimeout(timeout);
2422
+ reject(/* @__PURE__ */ new Error("Request was aborted"));
2423
+ };
2424
+ const timeout = setTimeout(() => {
2425
+ signal?.removeEventListener("abort", onAbort);
2426
+ resolve();
2427
+ }, ms);
2428
+ signal?.addEventListener("abort", onAbort, { once: true });
2429
+ });
2430
+ }
2431
+ function normalizeTimeoutMs(value) {
2432
+ if (value === void 0) return void 0;
2433
+ if (!Number.isFinite(value) || value < 0) throw new Error(`Invalid timeoutMs: ${String(value)}`);
2434
+ return Math.floor(value);
2435
+ }
2436
+ function loadNodeZlib() {
2437
+ if (typeof process === "undefined" || !(process.versions?.node || process.versions?.bun)) return null;
2438
+ return process.getBuiltinModule?.("node:zlib") ?? null;
2439
+ }
2440
+ function compressRequestBodyZstd(bodyJson) {
2441
+ const zlib = loadNodeZlib();
2442
+ if (!zlib || typeof zlib.zstdCompressSync !== "function") return null;
2443
+ try {
2444
+ const compressed = zlib.zstdCompressSync(bodyJson, { params: { [zlib.constants.ZSTD_c_compressionLevel]: REQUEST_COMPRESSION_ZSTD_LEVEL } });
2445
+ return new Uint8Array(compressed);
2446
+ } catch {
2447
+ return null;
2448
+ }
2449
+ }
2450
+ const stream = (model, context, options) => {
2451
+ const stream = new AssistantMessageEventStream();
2452
+ const normalizedContext = resolveTranscript(context, model.compat?.supportsMidConvoSystemMessages);
2453
+ (async () => {
2454
+ const configurationUpdateEffort = getConfigurationUpdateEffort(model, options);
2455
+ const output = {
2456
+ role: "assistant",
2457
+ content: [],
2458
+ api: "openai-codex-responses",
2459
+ provider: model.provider,
2460
+ model: model.id,
2461
+ ...configurationUpdateEffort === void 0 ? {} : { providerThinkingLevel: configurationUpdateEffort },
2462
+ usage: {
2463
+ input: 0,
2464
+ output: 0,
2465
+ cacheRead: 0,
2466
+ cacheWrite: 0,
2467
+ totalTokens: 0,
2468
+ cost: {
2469
+ input: 0,
2470
+ output: 0,
2471
+ cacheRead: 0,
2472
+ cacheWrite: 0,
2473
+ total: 0
2474
+ }
2475
+ },
2476
+ stopReason: "pending",
2477
+ timestamp: Date.now()
2478
+ };
2479
+ try {
2480
+ const apiKey = options?.apiKey;
2481
+ if (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);
2482
+ const accountId = extractAccountId(apiKey);
2483
+ const grammarToolInputProperties = createGrammarToolInputProperties(getDeclaredTools(normalizedContext.messages), model.compat?.supportsOpenAIGrammarTools ?? false);
2484
+ const cacheSessionId = options?.cacheRetention === "none" ? void 0 : options?.sessionId;
2485
+ const codexSessionId = clampOpenAIPromptCacheKey(cacheSessionId);
2486
+ let body = buildRequestBody(model, normalizedContext, options, codexSessionId, grammarToolInputProperties, configurationUpdateEffort);
2487
+ const nextBody = await options?.onPayload?.(body, model);
2488
+ if (nextBody !== void 0) body = nextBody;
2489
+ const websocketRequestId = codexSessionId || uuidv7();
2490
+ const identityHeaders = {
2491
+ originator: "pi",
2492
+ ...getIdentityHeaders(model, options?.identity)
2493
+ };
2494
+ const sseHeaders = buildSSEHeaders(identityHeaders, model.headers, options?.headers, accountId, apiKey, codexSessionId);
2495
+ const websocketHeaders = buildWebSocketHeaders(identityHeaders, model.headers, options?.headers, accountId, apiKey, websocketRequestId);
2496
+ const bodyJson = JSON.stringify(body);
2497
+ const httpTimeoutMs = normalizeTimeoutMs(options?.timeoutMs);
2498
+ const websocketConnectTimeoutMs = normalizeTimeoutMs(options?.websocketConnectTimeoutMs);
2499
+ const transport = options?.transport || "auto";
2500
+ let startEmitted = false;
2501
+ const websocketDisabledForSession = transport !== "sse" && isWebSocketSseFallbackActive(cacheSessionId);
2502
+ if (websocketDisabledForSession) recordWebSocketSseFallback(cacheSessionId);
2503
+ if (transport !== "sse" && !websocketDisabledForSession) {
2504
+ let websocketStarted = false;
2505
+ let retriedWebSocketConnectionLimit = false;
2506
+ let retriedMissingWebSocketContinuation = false;
2507
+ while (true) {
2508
+ websocketStarted = false;
2509
+ try {
2510
+ await processWebSocketStream(resolveCodexWebSocketUrl(model.baseUrl), body, websocketHeaders, output, stream, model, () => {
2511
+ websocketStarted = true;
2512
+ if (!startEmitted) {
2513
+ startEmitted = true;
2514
+ stream.push({
2515
+ type: "start",
2516
+ partial: output
2517
+ });
2518
+ }
2519
+ }, httpTimeoutMs, websocketConnectTimeoutMs, cacheSessionId, accountId, grammarToolInputProperties, options);
2520
+ if (options?.signal?.aborted) throw new Error("Request was aborted");
2521
+ assertSuccessfulOutput(output);
2522
+ stream.push({
2523
+ type: "done",
2524
+ reason: output.stopReason,
2525
+ message: output
2526
+ });
2527
+ stream.end();
2528
+ return;
2529
+ } catch (error) {
2530
+ const aborted = options?.signal?.aborted;
2531
+ const connectionLimitBeforeStart = !websocketStarted && isWebSocketConnectionLimitReachedError(error);
2532
+ const previousResponseNotFound = isPreviousResponseNotFoundError(error);
2533
+ if (!aborted && previousResponseNotFound && !retriedMissingWebSocketContinuation) {
2534
+ retriedMissingWebSocketContinuation = true;
2535
+ continue;
2536
+ }
2537
+ if (!aborted && connectionLimitBeforeStart && !retriedWebSocketConnectionLimit) {
2538
+ retriedWebSocketConnectionLimit = true;
2539
+ continue;
2540
+ }
2541
+ if (aborted || isCodexNonTransportError(error) && !connectionLimitBeforeStart) throw error;
2542
+ appendAssistantMessageDiagnostic(output, createAssistantMessageDiagnostic("provider_transport_failure", error, {
2543
+ configuredTransport: transport,
2544
+ ...websocketStarted ? {} : { fallbackTransport: "sse" },
2545
+ eventsEmitted: websocketStarted,
2546
+ phase: websocketStarted ? "after_message_stream_start" : "before_message_stream_start",
2547
+ requestBytes: new TextEncoder().encode(bodyJson).byteLength
2548
+ }));
2549
+ recordWebSocketFailure(cacheSessionId, error);
2550
+ if (websocketStarted) throw error;
2551
+ recordWebSocketSseFallback(cacheSessionId);
2552
+ break;
2553
+ }
2554
+ }
2555
+ }
2556
+ const compressedBody = compressRequestBodyZstd(bodyJson);
2557
+ if (compressedBody) sseHeaders.set("content-encoding", "zstd");
2558
+ const sseBody = compressedBody ?? bodyJson;
2559
+ let response;
2560
+ let lastError;
2561
+ const maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES;
2562
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
2563
+ if (options?.signal?.aborted) throw new Error("Request was aborted");
2564
+ try {
2565
+ const headerTimeoutSignal = httpTimeoutMs !== void 0 && httpTimeoutMs > 0 ? AbortSignal.timeout(httpTimeoutMs) : void 0;
2566
+ const combinedSignal = combineAbortSignals([options?.signal, headerTimeoutSignal]);
2567
+ try {
2568
+ response = await (options?.fetch ?? globalThis.fetch)(resolveCodexUrl(model.baseUrl), {
2569
+ method: "POST",
2570
+ headers: sseHeaders,
2571
+ body: sseBody,
2572
+ signal: combinedSignal.signal
2573
+ });
2574
+ } catch (error) {
2575
+ if (headerTimeoutSignal?.aborted && !options?.signal?.aborted) throw new Error(`Codex SSE response headers timed out after ${httpTimeoutMs}ms`);
2576
+ throw error;
2577
+ } finally {
2578
+ combinedSignal.cleanup();
2579
+ }
2580
+ await options?.onResponse?.({
2581
+ status: response.status,
2582
+ headers: headersToRecord(response.headers)
2583
+ }, model);
2584
+ if (response.ok) break;
2585
+ const errorText = await response.text();
2586
+ if (attempt < maxRetries && isRetryableError(response.status, errorText)) {
2587
+ const retryAfterDelayMs = getRetryAfterDelayMs(response.headers);
2588
+ await sleep(retryAfterDelayMs === void 0 ? BASE_DELAY_MS * 2 ** attempt : validateRetryDelayMs(retryAfterDelayMs, options), options?.signal);
2589
+ continue;
2590
+ }
2591
+ const info = await parseErrorResponse(new Response(errorText, {
2592
+ status: response.status,
2593
+ statusText: response.statusText
2594
+ }));
2595
+ throw new Error(info.friendlyMessage || info.message);
2596
+ } catch (error) {
2597
+ if (error instanceof Error) {
2598
+ if (error.name === "AbortError" || error.message === "Request was aborted") throw new Error("Request was aborted");
2599
+ }
2600
+ lastError = error instanceof Error ? error : new Error(String(error));
2601
+ if (attempt < maxRetries && !(lastError instanceof RetryDelayExceededError) && !lastError.message.includes("usage limit")) {
2602
+ await sleep(BASE_DELAY_MS * 2 ** attempt, options?.signal);
2603
+ continue;
2604
+ }
2605
+ throw lastError;
2606
+ }
2607
+ }
2608
+ if (!response?.ok) throw lastError ?? /* @__PURE__ */ new Error("Failed after retries");
2609
+ if (!response.body) throw new Error("No response body");
2610
+ if (!startEmitted) {
2611
+ startEmitted = true;
2612
+ stream.push({
2613
+ type: "start",
2614
+ partial: output
2615
+ });
2616
+ }
2617
+ await processStream(response, output, stream, model, grammarToolInputProperties, options);
2618
+ if (options?.signal?.aborted) throw new Error("Request was aborted");
2619
+ assertSuccessfulOutput(output);
2620
+ stream.push({
2621
+ type: "done",
2622
+ reason: output.stopReason,
2623
+ message: output
2624
+ });
2625
+ stream.end();
2626
+ } catch (error) {
2627
+ output.stopReason = options?.signal?.aborted ? "aborted" : "error";
2628
+ output.errorMessage = formatProviderError(normalizeProviderError(error));
2629
+ stream.push({
2630
+ type: "error",
2631
+ reason: output.stopReason,
2632
+ error: output
2633
+ });
2634
+ stream.end();
2635
+ }
2636
+ })();
2637
+ return stream;
2638
+ };
2639
+ const streamSimple = (model, context, options) => {
2640
+ const apiKey = options?.apiKey;
2641
+ if (!apiKey) throw new Error(`No API key for provider: ${model.provider}`);
2642
+ const base = {
2643
+ ...buildBaseOptions(model, context, options, apiKey),
2644
+ toolChoice: options?.toolChoice
2645
+ };
2646
+ const clampedReasoning = options?.reasoning ? clampThinkingLevel(model, options.reasoning) : "off";
2647
+ const reasoningEffort = clampedReasoning !== "off" ? clampedReasoning : model.reasoning ? "none" : void 0;
2648
+ return stream(model, context, {
2649
+ ...base,
2650
+ reasoningEffort
2651
+ });
2652
+ };
2653
+ /** Effort to send in configuration_update items, or undefined to send it as reasoning.effort. */
2654
+ function getConfigurationUpdateEffort(model, options) {
2655
+ if (!model.compat?.supportsMidConvoEffort || options?.reasoningEffort === void 0) return void 0;
2656
+ return resolveReasoningEffort(model, options.reasoningEffort) ?? void 0;
2657
+ }
2658
+ /** Provider-native effort for a requested level; null when the model takes no reasoning field for it. */
2659
+ function resolveReasoningEffort(model, reasoningEffort) {
2660
+ if (reasoningEffort === "none") return model.thinkingLevelMap?.off === void 0 ? "none" : model.thinkingLevelMap.off;
2661
+ return model.thinkingLevelMap?.[reasoningEffort] ?? reasoningEffort;
2662
+ }
2663
+ function buildRequestBody(model, context, options, cacheSessionId, grammarToolInputProperties, configurationUpdateEffort) {
2664
+ const supportsStrictMode = model.compat?.supportsStrictMode ?? true;
2665
+ const supportsOpenAIGrammarTools = model.compat?.supportsOpenAIGrammarTools ?? false;
2666
+ const supportsAdditionalTools = model.compat?.supportsAdditionalTools ?? false;
2667
+ const supportsToolSearch = model.compat?.supportsToolSearch ?? false;
2668
+ const transcriptTools = resolveTranscriptTools(context.messages, getResponsesToolSupport({
2669
+ supportsMidConvoSystemMessages: model.compat?.supportsMidConvoSystemMessages ?? false,
2670
+ supportsAdditionalTools,
2671
+ supportsToolSearch
2672
+ }));
2673
+ const messages = convertResponsesMessages(model, context, CODEX_TOOL_CALL_PROVIDERS, {
2674
+ grammarToolInputProperties,
2675
+ supportsMidConvoSystemMessages: model.compat?.supportsMidConvoSystemMessages ?? false,
2676
+ supportsAdditionalTools,
2677
+ supportsToolSearch,
2678
+ toolOptions: {
2679
+ strict: null,
2680
+ supportsStrictMode,
2681
+ supportsOpenAIGrammarTools
2682
+ },
2683
+ configurationUpdateEffort
2684
+ });
2685
+ const body = {
2686
+ model: model.id,
2687
+ store: false,
2688
+ stream: true,
2689
+ input: messages,
2690
+ text: { verbosity: options?.textVerbosity || "low" },
2691
+ include: ["reasoning.encrypted_content"],
2692
+ prompt_cache_key: cacheSessionId,
2693
+ tool_choice: options?.toolChoice ?? "auto",
2694
+ parallel_tool_calls: true
2695
+ };
2696
+ if (options?.maxTokens && (model.compat?.supportsMaxOutputTokens ?? true)) body.max_output_tokens = Math.max(options.maxTokens, MIN_OUTPUT_TOKENS);
2697
+ if (options?.temperature !== void 0) body.temperature = options.temperature;
2698
+ if (options?.serviceTier !== void 0) body.service_tier = options.serviceTier;
2699
+ if (transcriptTools.requestTools.length > 0) body.tools = convertResponsesTools(transcriptTools.requestTools, {
2700
+ strict: null,
2701
+ supportsStrictMode,
2702
+ supportsOpenAIGrammarTools
2703
+ });
2704
+ if (options?.reasoningEffort !== void 0) {
2705
+ const effort = configurationUpdateEffort === void 0 ? resolveReasoningEffort(model, options.reasoningEffort) : CONFIGURATION_UPDATE_REQUEST_EFFORT;
2706
+ if (effort !== null) body.reasoning = {
2707
+ effort,
2708
+ summary: options.reasoningSummary ?? "auto"
2709
+ };
2710
+ } else if (model.reasoning && model.thinkingLevelMap?.off !== null) body.reasoning = { effort: model.thinkingLevelMap?.off ?? "none" };
2711
+ return body;
2712
+ }
2713
+ function getServiceTierCostMultiplier(model, serviceTier) {
2714
+ switch (serviceTier) {
2715
+ case "flex": return .5;
2716
+ case "priority": return model.id === "gpt-5.5" ? 2.5 : 2;
2717
+ default: return 1;
2718
+ }
2719
+ }
2720
+ function applyServiceTierPricing(usage, serviceTier, model) {
2721
+ const multiplier = getServiceTierCostMultiplier(model, serviceTier);
2722
+ if (multiplier === 1) return;
2723
+ usage.cost.input *= multiplier;
2724
+ usage.cost.output *= multiplier;
2725
+ usage.cost.cacheRead *= multiplier;
2726
+ usage.cost.cacheWrite *= multiplier;
2727
+ usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite;
2728
+ }
2729
+ function resolveCodexServiceTier(responseServiceTier, requestServiceTier) {
2730
+ if (responseServiceTier === "default" && (requestServiceTier === "flex" || requestServiceTier === "priority")) return requestServiceTier;
2731
+ return responseServiceTier ?? requestServiceTier;
2732
+ }
2733
+ function resolveCodexUrl(baseUrl) {
2734
+ const normalized = (baseUrl && baseUrl.trim().length > 0 ? baseUrl : DEFAULT_CODEX_BASE_URL).replace(/\/+$/, "");
2735
+ if (normalized.endsWith("/codex/responses")) return normalized;
2736
+ if (normalized.endsWith("/codex")) return `${normalized}/responses`;
2737
+ return `${normalized}/codex/responses`;
2738
+ }
2739
+ function resolveCodexWebSocketUrl(baseUrl) {
2740
+ const url = new URL(resolveCodexUrl(baseUrl));
2741
+ if (url.protocol === "https:") url.protocol = "wss:";
2742
+ if (url.protocol === "http:") url.protocol = "ws:";
2743
+ return url.toString();
2744
+ }
2745
+ async function processStream(response, output, stream, model, grammarToolInputProperties, options) {
2746
+ await processResponsesStream(mapCodexEvents(parseSSE(response, options?.signal), output, model, options?.onProviderStreamEvent), output, stream, model, {
2747
+ serviceTier: options?.serviceTier,
2748
+ grammarToolInputProperties,
2749
+ resolveServiceTier: resolveCodexServiceTier,
2750
+ applyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model)
2751
+ });
2752
+ }
2753
+ var CodexApiError = class extends Error {
2754
+ code;
2755
+ payload;
2756
+ constructor(message, options) {
2757
+ super(message);
2758
+ this.name = "CodexApiError";
2759
+ this.code = options?.code;
2760
+ this.payload = options?.payload;
2761
+ this.cause = options?.cause;
2762
+ }
2763
+ };
2764
+ var CodexProtocolError = class extends Error {
2765
+ payload;
2766
+ constructor(message, options) {
2767
+ super(message);
2768
+ this.name = "CodexProtocolError";
2769
+ this.payload = options?.payload;
2770
+ this.cause = options?.cause;
2771
+ }
2772
+ };
2773
+ var ProviderStreamEventCallbackError = class extends Error {
2774
+ constructor(cause) {
2775
+ super(formatThrownValue(cause));
2776
+ this.name = "ProviderStreamEventCallbackError";
2777
+ this.cause = cause;
2778
+ }
2779
+ };
2780
+ function isCodexNonTransportError(error) {
2781
+ return error instanceof CodexApiError || error instanceof CodexProtocolError || error instanceof ProviderStreamEventCallbackError;
2782
+ }
2783
+ function isWebSocketConnectionLimitReachedError(error) {
2784
+ return error instanceof CodexApiError && error.code === WEBSOCKET_CONNECTION_LIMIT_REACHED_CODE;
2785
+ }
2786
+ function isPreviousResponseNotFoundError(error) {
2787
+ return error instanceof CodexApiError && error.code === PREVIOUS_RESPONSE_NOT_FOUND_CODE;
2788
+ }
2789
+ function extractCodexEventError(event) {
2790
+ const nested = event.error && typeof event.error === "object" ? event.error : void 0;
2791
+ return {
2792
+ code: typeof event.code === "string" ? event.code : typeof nested?.code === "string" ? nested.code : void 0,
2793
+ message: typeof event.message === "string" ? event.message : typeof nested?.message === "string" ? nested.message : void 0
2794
+ };
2795
+ }
2796
+ async function* mapCodexEvents(events, output, model, onProviderStreamEvent) {
2797
+ for await (const event of events) {
2798
+ try {
2799
+ await onProviderStreamEvent?.(event, model);
2800
+ } catch (error) {
2801
+ throw new ProviderStreamEventCallbackError(error);
2802
+ }
2803
+ const type = typeof event.type === "string" ? event.type : void 0;
2804
+ if (!type) continue;
2805
+ if (type === "error") {
2806
+ const { code, message } = extractCodexEventError(event);
2807
+ throw new CodexApiError(`Codex error: ${message || code || JSON.stringify(event)}`, {
2808
+ code,
2809
+ payload: event
2810
+ });
2811
+ }
2812
+ if (type === "response.failed") {
2813
+ const response = event.response;
2814
+ const code = response?.error?.code;
2815
+ const message = response?.error?.message;
2816
+ throw new CodexApiError(message || "Codex response failed", {
2817
+ code,
2818
+ payload: event
2819
+ });
2820
+ }
2821
+ if (type === "response.done" || type === "response.completed" || type === "response.incomplete") {
2822
+ const response = event.response;
2823
+ if (typeof response?.end_turn === "boolean") output.endTurn = response.end_turn;
2824
+ const normalizedResponse = response ? {
2825
+ ...response,
2826
+ status: normalizeCodexStatus(response.status)
2827
+ } : response;
2828
+ yield {
2829
+ ...event,
2830
+ type: "response.completed",
2831
+ response: normalizedResponse
2832
+ };
2833
+ return;
2834
+ }
2835
+ yield event;
2836
+ }
2837
+ }
2838
+ function normalizeCodexStatus(status) {
2839
+ if (typeof status !== "string") return void 0;
2840
+ return CODEX_RESPONSE_STATUSES.has(status) ? status : void 0;
2841
+ }
2842
+ async function* parseSSE(response, signal) {
2843
+ if (!response.body) return;
2844
+ const reader = response.body.getReader();
2845
+ const decoder = new TextDecoder();
2846
+ let buffer = "";
2847
+ const onAbort = () => {
2848
+ reader.cancel().catch(() => {});
2849
+ };
2850
+ signal?.addEventListener("abort", onAbort, { once: true });
2851
+ try {
2852
+ while (true) {
2853
+ if (signal?.aborted) throw new Error("Request was aborted");
2854
+ const { done, value } = await reader.read();
2855
+ if (signal?.aborted) throw new Error("Request was aborted");
2856
+ buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
2857
+ if (done && buffer.trim()) buffer += "\n\n";
2858
+ let idx = buffer.indexOf("\n\n");
2859
+ while (idx !== -1) {
2860
+ const chunk = buffer.slice(0, idx);
2861
+ buffer = buffer.slice(idx + 2);
2862
+ const dataLines = chunk.split("\n").filter((l) => l.startsWith("data:")).map((l) => l.slice(5).trim());
2863
+ if (dataLines.length > 0) {
2864
+ const data = dataLines.join("\n").trim();
2865
+ if (data && data !== "[DONE]") try {
2866
+ yield JSON.parse(data);
2867
+ } catch (cause) {
2868
+ throw new CodexProtocolError(`Invalid Codex SSE JSON: ${formatThrownValue(cause)}`, {
2869
+ cause,
2870
+ payload: data
2871
+ });
2872
+ }
2873
+ }
2874
+ idx = buffer.indexOf("\n\n");
2875
+ }
2876
+ if (done) break;
2877
+ }
2878
+ } finally {
2879
+ signal?.removeEventListener("abort", onAbort);
2880
+ try {
2881
+ await reader.cancel();
2882
+ } catch {}
2883
+ try {
2884
+ reader.releaseLock();
2885
+ } catch {}
2886
+ }
2887
+ }
2888
+ const OPENAI_BETA_RESPONSES_WEBSOCKETS = "responses_websockets=2026-02-06";
2889
+ const SESSION_WEBSOCKET_CACHE_TTL_MS = 3e5;
2890
+ const SESSION_WEBSOCKET_MAX_AGE_MS = 27e5;
2891
+ const websocketSessionCache = /* @__PURE__ */ new Map();
2892
+ const websocketDebugStats = /* @__PURE__ */ new Map();
2893
+ const websocketSseFallbackSessions = /* @__PURE__ */ new Set();
2894
+ function getOrCreateWebSocketDebugStats(sessionId) {
2895
+ let stats = websocketDebugStats.get(sessionId);
2896
+ if (!stats) {
2897
+ stats = {
2898
+ requests: 0,
2899
+ connectionsCreated: 0,
2900
+ connectionsReused: 0,
2901
+ cachedContextRequests: 0,
2902
+ storeTrueRequests: 0,
2903
+ fullContextRequests: 0,
2904
+ deltaRequests: 0,
2905
+ lastInputItems: 0,
2906
+ websocketFailures: 0,
2907
+ sseFallbacks: 0
2908
+ };
2909
+ websocketDebugStats.set(sessionId, stats);
2910
+ }
2911
+ return stats;
2912
+ }
2913
+ function getOpenAICodexWebSocketDebugStats(sessionId) {
2914
+ const stats = websocketDebugStats.get(sessionId);
2915
+ return stats ? { ...stats } : void 0;
2916
+ }
2917
+ function resetOpenAICodexWebSocketDebugStats(sessionId) {
2918
+ if (sessionId) {
2919
+ websocketDebugStats.delete(sessionId);
2920
+ websocketSseFallbackSessions.delete(sessionId);
2921
+ return;
2922
+ }
2923
+ websocketDebugStats.clear();
2924
+ websocketSseFallbackSessions.clear();
2925
+ }
2926
+ function closeOpenAICodexWebSocketSessions(sessionId) {
2927
+ const closeEntry = (entry) => {
2928
+ if (entry.idleTimer) clearTimeout(entry.idleTimer);
2929
+ closeWebSocketSilently(entry.socket, 1e3, "debug_close");
2930
+ };
2931
+ if (sessionId) {
2932
+ for (const entry of websocketSessionCache.get(sessionId)?.values() ?? []) closeEntry(entry);
2933
+ websocketSessionCache.delete(sessionId);
2934
+ return;
2935
+ }
2936
+ for (const accountEntries of websocketSessionCache.values()) for (const entry of accountEntries.values()) closeEntry(entry);
2937
+ websocketSessionCache.clear();
2938
+ }
2939
+ registerSessionResourceCleanup(closeOpenAICodexWebSocketSessions);
2940
+ function isWebSocketSseFallbackActive(sessionId) {
2941
+ return sessionId ? websocketSseFallbackSessions.has(sessionId) : false;
2942
+ }
2943
+ function recordWebSocketSseFallback(sessionId) {
2944
+ if (!sessionId) return;
2945
+ const stats = getOrCreateWebSocketDebugStats(sessionId);
2946
+ stats.sseFallbacks++;
2947
+ stats.websocketFallbackActive = isWebSocketSseFallbackActive(sessionId);
2948
+ }
2949
+ function recordWebSocketFailure(sessionId, error) {
2950
+ if (!sessionId) return;
2951
+ websocketSseFallbackSessions.add(sessionId);
2952
+ const stats = getOrCreateWebSocketDebugStats(sessionId);
2953
+ stats.websocketFailures++;
2954
+ stats.lastWebSocketError = formatThrownValue(error);
2955
+ stats.websocketFallbackActive = true;
2956
+ }
2957
+ let _cachedWebsocket = null;
2958
+ async function getWebSocketConstructor(env) {
2959
+ if (!env && _cachedWebsocket) return _cachedWebsocket;
2960
+ if (typeof process !== "undefined" && process.versions?.bun) {
2961
+ const WebSocketWithProxy = class extends WebSocket {
2962
+ constructor(url, options) {
2963
+ let _opts = {};
2964
+ if (Array.isArray(options) || typeof options === "string") _opts = { protocols: options };
2965
+ else _opts = { ...options };
2966
+ const proxyUrl = resolveHttpProxyUrlForTarget(url.toString().replace(/^wss:/, "https:").replace(/^ws:/, "http:"), env);
2967
+ super(url, {
2968
+ ..._opts,
2969
+ ...proxyUrl ? { proxy: proxyUrl.toString() } : {}
2970
+ });
2971
+ }
2972
+ };
2973
+ if (!env) _cachedWebsocket = WebSocketWithProxy;
2974
+ return WebSocketWithProxy;
2975
+ }
2976
+ const ctor = globalThis.WebSocket;
2977
+ if (typeof ctor !== "function") return null;
2978
+ return ctor;
2979
+ }
2980
+ var WebSocketCloseError = class extends Error {
2981
+ code;
2982
+ reason;
2983
+ wasClean;
2984
+ constructor(message, options) {
2985
+ super(message);
2986
+ this.name = "WebSocketCloseError";
2987
+ this.code = options?.code;
2988
+ this.reason = options?.reason;
2989
+ this.wasClean = options?.wasClean;
2990
+ }
2991
+ };
2992
+ function getWebSocketReadyState(socket) {
2993
+ const readyState = socket.readyState;
2994
+ return typeof readyState === "number" ? readyState : void 0;
2995
+ }
2996
+ function isWebSocketReusable(socket) {
2997
+ const readyState = getWebSocketReadyState(socket);
2998
+ return readyState === void 0 || readyState === 1;
2999
+ }
3000
+ function isWebSocketSessionExpired(entry) {
3001
+ return Date.now() - entry.createdAt >= SESSION_WEBSOCKET_MAX_AGE_MS;
3002
+ }
3003
+ function closeWebSocketSilently(socket, code = 1e3, reason = "done") {
3004
+ try {
3005
+ socket.close(code, reason);
3006
+ } catch {}
3007
+ }
3008
+ function scheduleSessionWebSocketExpiry(sessionId, accountId, entry) {
3009
+ if (entry.idleTimer) clearTimeout(entry.idleTimer);
3010
+ entry.idleTimer = setTimeout(() => {
3011
+ if (entry.busy) return;
3012
+ closeWebSocketSilently(entry.socket, 1e3, "idle_timeout");
3013
+ const accountEntries = websocketSessionCache.get(sessionId);
3014
+ if (accountEntries?.get(accountId) === entry) accountEntries.delete(accountId);
3015
+ if (accountEntries?.size === 0) websocketSessionCache.delete(sessionId);
3016
+ }, SESSION_WEBSOCKET_CACHE_TTL_MS);
3017
+ }
3018
+ async function connectWebSocket(url, headers, signal, connectTimeoutMs = DEFAULT_WEBSOCKET_CONNECT_TIMEOUT_MS, env) {
3019
+ const WebSocketCtor = await getWebSocketConstructor(env);
3020
+ if (!WebSocketCtor) throw new Error("WebSocket transport is not available in this runtime");
3021
+ const wsHeaders = headersToRecord(headers);
3022
+ delete wsHeaders["OpenAI-Beta"];
3023
+ return new Promise((resolve, reject) => {
3024
+ let settled = false;
3025
+ let timeout;
3026
+ let socket;
3027
+ try {
3028
+ socket = new WebSocketCtor(url, { headers: wsHeaders });
3029
+ } catch (error) {
3030
+ reject(error instanceof Error ? error : new Error(String(error)));
3031
+ return;
3032
+ }
3033
+ const cleanup = () => {
3034
+ if (timeout) {
3035
+ clearTimeout(timeout);
3036
+ timeout = void 0;
3037
+ }
3038
+ socket.removeEventListener("open", onOpen);
3039
+ socket.removeEventListener("error", onError);
3040
+ socket.removeEventListener("close", onClose);
3041
+ signal?.removeEventListener("abort", onAbort);
3042
+ };
3043
+ const fail = (error, closeReason) => {
3044
+ if (settled) return;
3045
+ settled = true;
3046
+ cleanup();
3047
+ if (closeReason) closeWebSocketSilently(socket, 1e3, closeReason);
3048
+ reject(error);
3049
+ };
3050
+ const onOpen = () => {
3051
+ if (settled) return;
3052
+ settled = true;
3053
+ cleanup();
3054
+ resolve(socket);
3055
+ };
3056
+ const onError = (event) => {
3057
+ fail(extractWebSocketError(event));
3058
+ };
3059
+ const onClose = (event) => {
3060
+ fail(extractWebSocketCloseError(event));
3061
+ };
3062
+ const onAbort = () => {
3063
+ fail(/* @__PURE__ */ new Error("Request was aborted"), "aborted");
3064
+ };
3065
+ socket.addEventListener("open", onOpen);
3066
+ socket.addEventListener("error", onError);
3067
+ socket.addEventListener("close", onClose);
3068
+ signal?.addEventListener("abort", onAbort);
3069
+ if (connectTimeoutMs > 0) timeout = setTimeout(() => {
3070
+ fail(/* @__PURE__ */ new Error(`WebSocket connect timeout after ${connectTimeoutMs}ms`), "connect_timeout");
3071
+ }, connectTimeoutMs);
3072
+ if (signal?.aborted) onAbort();
3073
+ });
3074
+ }
3075
+ async function acquireWebSocket(url, headers, sessionId, accountId, signal, connectTimeoutMs, env) {
3076
+ if (!sessionId) {
3077
+ const socket = await connectWebSocket(url, headers, signal, connectTimeoutMs, env);
3078
+ return {
3079
+ socket,
3080
+ reused: false,
3081
+ release: () => closeWebSocketSilently(socket)
3082
+ };
3083
+ }
3084
+ let accountEntries = websocketSessionCache.get(sessionId);
3085
+ const cached = accountEntries?.get(accountId);
3086
+ if (cached) {
3087
+ if (cached.idleTimer) {
3088
+ clearTimeout(cached.idleTimer);
3089
+ cached.idleTimer = void 0;
3090
+ }
3091
+ if (!cached.busy && isWebSocketSessionExpired(cached)) {
3092
+ closeWebSocketSilently(cached.socket, 1e3, "connection_age_limit");
3093
+ accountEntries?.delete(accountId);
3094
+ if (accountEntries?.size === 0) websocketSessionCache.delete(sessionId);
3095
+ } else if (!cached.busy && isWebSocketReusable(cached.socket)) {
3096
+ cached.busy = true;
3097
+ return {
3098
+ socket: cached.socket,
3099
+ entry: cached,
3100
+ reused: true,
3101
+ release: ({ keep } = {}) => {
3102
+ if (!keep || !isWebSocketReusable(cached.socket)) {
3103
+ closeWebSocketSilently(cached.socket);
3104
+ const currentEntries = websocketSessionCache.get(sessionId);
3105
+ if (currentEntries?.get(accountId) === cached) currentEntries.delete(accountId);
3106
+ if (currentEntries?.size === 0) websocketSessionCache.delete(sessionId);
3107
+ return;
3108
+ }
3109
+ cached.busy = false;
3110
+ scheduleSessionWebSocketExpiry(sessionId, accountId, cached);
3111
+ }
3112
+ };
3113
+ }
3114
+ if (cached.busy) {
3115
+ const socket = await connectWebSocket(url, headers, signal, connectTimeoutMs, env);
3116
+ return {
3117
+ socket,
3118
+ reused: false,
3119
+ release: () => {
3120
+ closeWebSocketSilently(socket);
3121
+ }
3122
+ };
3123
+ }
3124
+ if (!isWebSocketReusable(cached.socket)) {
3125
+ closeWebSocketSilently(cached.socket);
3126
+ accountEntries?.delete(accountId);
3127
+ if (accountEntries?.size === 0) websocketSessionCache.delete(sessionId);
3128
+ }
3129
+ }
3130
+ const socket = await connectWebSocket(url, headers, signal, connectTimeoutMs, env);
3131
+ const entry = {
3132
+ socket,
3133
+ busy: true,
3134
+ createdAt: Date.now()
3135
+ };
3136
+ accountEntries = websocketSessionCache.get(sessionId);
3137
+ if (!accountEntries) {
3138
+ accountEntries = /* @__PURE__ */ new Map();
3139
+ websocketSessionCache.set(sessionId, accountEntries);
3140
+ }
3141
+ accountEntries.set(accountId, entry);
3142
+ return {
3143
+ socket,
3144
+ entry,
3145
+ reused: false,
3146
+ release: ({ keep } = {}) => {
3147
+ if (!keep || !isWebSocketReusable(entry.socket)) {
3148
+ closeWebSocketSilently(entry.socket);
3149
+ if (entry.idleTimer) clearTimeout(entry.idleTimer);
3150
+ const currentEntries = websocketSessionCache.get(sessionId);
3151
+ if (currentEntries?.get(accountId) === entry) currentEntries.delete(accountId);
3152
+ if (currentEntries?.size === 0) websocketSessionCache.delete(sessionId);
3153
+ return;
3154
+ }
3155
+ entry.busy = false;
3156
+ scheduleSessionWebSocketExpiry(sessionId, accountId, entry);
3157
+ }
3158
+ };
3159
+ }
3160
+ function extractWebSocketError(event) {
3161
+ if (event && typeof event === "object") {
3162
+ const message = "message" in event ? event.message : void 0;
3163
+ if (typeof message === "string" && message.length > 0) return new Error(message);
3164
+ const nestedError = "error" in event ? event.error : void 0;
3165
+ if (nestedError instanceof Error && nestedError.message.length > 0) return nestedError;
3166
+ if (nestedError && typeof nestedError === "object" && "message" in nestedError) {
3167
+ const nestedMessage = nestedError.message;
3168
+ if (typeof nestedMessage === "string" && nestedMessage.length > 0) return new Error(nestedMessage);
3169
+ }
3170
+ }
3171
+ return /* @__PURE__ */ new Error("WebSocket error");
3172
+ }
3173
+ function extractWebSocketCloseError(event) {
3174
+ if (event && typeof event === "object") {
3175
+ const code = "code" in event ? event.code : void 0;
3176
+ const reason = "reason" in event ? event.reason : void 0;
3177
+ const wasClean = "wasClean" in event ? event.wasClean : void 0;
3178
+ const codeText = typeof code === "number" ? ` ${code}` : "";
3179
+ let reasonText = typeof reason === "string" && reason.length > 0 ? ` ${reason}` : "";
3180
+ if (!reasonText && code === WEBSOCKET_MESSAGE_TOO_BIG_CLOSE_CODE) reasonText = " message too big";
3181
+ return new WebSocketCloseError(`WebSocket closed${codeText}${reasonText}`.trim(), {
3182
+ code: typeof code === "number" ? code : void 0,
3183
+ reason: typeof reason === "string" && reason.length > 0 ? reason : void 0,
3184
+ wasClean: typeof wasClean === "boolean" ? wasClean : void 0
3185
+ });
3186
+ }
3187
+ return /* @__PURE__ */ new Error("WebSocket closed");
3188
+ }
3189
+ async function decodeWebSocketData(data) {
3190
+ if (typeof data === "string") return data;
3191
+ if (data instanceof ArrayBuffer) return new TextDecoder().decode(new Uint8Array(data));
3192
+ if (ArrayBuffer.isView(data)) {
3193
+ const view = data;
3194
+ return new TextDecoder().decode(new Uint8Array(view.buffer, view.byteOffset, view.byteLength));
3195
+ }
3196
+ if (data && typeof data === "object" && "arrayBuffer" in data) {
3197
+ const arrayBuffer = await data.arrayBuffer();
3198
+ return new TextDecoder().decode(new Uint8Array(arrayBuffer));
3199
+ }
3200
+ return null;
3201
+ }
3202
+ async function* parseWebSocket(socket, signal, idleTimeoutMs) {
3203
+ const queue = [];
3204
+ let pending = null;
3205
+ let done = false;
3206
+ let failed = null;
3207
+ let sawCompletion = false;
3208
+ const wake = () => {
3209
+ if (!pending) return;
3210
+ const resolve = pending;
3211
+ pending = null;
3212
+ resolve();
3213
+ };
3214
+ const onMessage = (event) => {
3215
+ (async () => {
3216
+ let text = null;
3217
+ try {
3218
+ if (!event || typeof event !== "object" || !("data" in event)) return;
3219
+ text = await decodeWebSocketData(event.data);
3220
+ if (!text) return;
3221
+ const parsed = JSON.parse(text);
3222
+ const type = typeof parsed.type === "string" ? parsed.type : "";
3223
+ if (type === "response.completed" || type === "response.done" || type === "response.incomplete") {
3224
+ sawCompletion = true;
3225
+ done = true;
3226
+ }
3227
+ queue.push(parsed);
3228
+ wake();
3229
+ } catch (cause) {
3230
+ failed = new CodexProtocolError(`Invalid Codex WebSocket JSON: ${formatThrownValue(cause)}`, {
3231
+ cause,
3232
+ payload: text
3233
+ });
3234
+ done = true;
3235
+ wake();
3236
+ }
3237
+ })();
3238
+ };
3239
+ const onError = (event) => {
3240
+ failed = extractWebSocketError(event);
3241
+ done = true;
3242
+ wake();
3243
+ };
3244
+ const onClose = (event) => {
3245
+ if (sawCompletion) {
3246
+ done = true;
3247
+ wake();
3248
+ return;
3249
+ }
3250
+ if (!failed) failed = extractWebSocketCloseError(event);
3251
+ done = true;
3252
+ wake();
3253
+ };
3254
+ const onAbort = () => {
3255
+ failed = /* @__PURE__ */ new Error("Request was aborted");
3256
+ done = true;
3257
+ wake();
3258
+ };
3259
+ socket.addEventListener("message", onMessage);
3260
+ socket.addEventListener("error", onError);
3261
+ socket.addEventListener("close", onClose);
3262
+ signal?.addEventListener("abort", onAbort);
3263
+ try {
3264
+ while (true) {
3265
+ if (signal?.aborted) throw new Error("Request was aborted");
3266
+ if (queue.length > 0) {
3267
+ yield queue.shift();
3268
+ continue;
3269
+ }
3270
+ if (done) break;
3271
+ let timeout;
3272
+ await new Promise((resolve, reject) => {
3273
+ pending = resolve;
3274
+ if (idleTimeoutMs !== void 0 && idleTimeoutMs > 0) timeout = setTimeout(() => {
3275
+ const error = /* @__PURE__ */ new Error(`WebSocket idle timeout after ${idleTimeoutMs}ms`);
3276
+ failed = error;
3277
+ done = true;
3278
+ pending = null;
3279
+ closeWebSocketSilently(socket, 1e3, "idle_timeout");
3280
+ reject(error);
3281
+ }, idleTimeoutMs);
3282
+ }).finally(() => {
3283
+ if (timeout) clearTimeout(timeout);
3284
+ });
3285
+ }
3286
+ if (failed) throw failed;
3287
+ if (!sawCompletion) throw new Error("WebSocket stream closed before response.completed");
3288
+ } finally {
3289
+ socket.removeEventListener("message", onMessage);
3290
+ socket.removeEventListener("error", onError);
3291
+ socket.removeEventListener("close", onClose);
3292
+ signal?.removeEventListener("abort", onAbort);
3293
+ }
3294
+ }
3295
+ function requestBodyWithoutInput(body) {
3296
+ const { input: _input, previous_response_id: _previousResponseId, ...rest } = body;
3297
+ return rest;
3298
+ }
3299
+ function responseInputsEqual(a, b) {
3300
+ return JSON.stringify(a ?? []) === JSON.stringify(b ?? []);
3301
+ }
3302
+ function requestBodiesMatchExceptInput(a, b) {
3303
+ return JSON.stringify(requestBodyWithoutInput(a)) === JSON.stringify(requestBodyWithoutInput(b));
3304
+ }
3305
+ function getCachedWebSocketInputDelta(body, continuation) {
3306
+ if (!requestBodiesMatchExceptInput(body, continuation.lastRequestBody)) return;
3307
+ const currentInput = body.input ?? [];
3308
+ const baseline = [...continuation.lastRequestBody.input ?? [], ...continuation.lastResponseItems];
3309
+ if (currentInput.length < baseline.length) return;
3310
+ if (!responseInputsEqual(currentInput.slice(0, baseline.length), baseline)) return;
3311
+ return currentInput.slice(baseline.length);
3312
+ }
3313
+ function buildCachedWebSocketRequestBody(entry, body) {
3314
+ const continuation = entry.continuation;
3315
+ if (!continuation) return body;
3316
+ const delta = getCachedWebSocketInputDelta(body, continuation);
3317
+ if (!delta || !continuation.lastResponseId) {
3318
+ entry.continuation = void 0;
3319
+ return body;
3320
+ }
3321
+ return {
3322
+ ...body,
3323
+ previous_response_id: continuation.lastResponseId,
3324
+ input: delta
3325
+ };
3326
+ }
3327
+ async function* startWebSocketOutputOnFirstEvent(events, onStart) {
3328
+ let started = false;
3329
+ for await (const event of events) {
3330
+ if (!started) {
3331
+ started = true;
3332
+ onStart();
3333
+ }
3334
+ yield event;
3335
+ }
3336
+ }
3337
+ async function processWebSocketStream(url, body, headers, output, stream, model, onStart, idleTimeoutMs, websocketConnectTimeoutMs, cacheSessionId, accountId, grammarToolInputProperties, options) {
3338
+ const { socket, entry, reused, release } = await acquireWebSocket(url, headers, cacheSessionId, accountId, options?.signal, websocketConnectTimeoutMs, options?.env);
3339
+ let keepConnection = true;
3340
+ const useCachedContext = options?.transport === "websocket-cached" || options?.transport === "auto";
3341
+ const fullBody = body;
3342
+ const requestBody = useCachedContext && entry ? buildCachedWebSocketRequestBody(entry, fullBody) : fullBody;
3343
+ const stats = cacheSessionId ? getOrCreateWebSocketDebugStats(cacheSessionId) : void 0;
3344
+ if (stats) {
3345
+ stats.requests++;
3346
+ if (reused) stats.connectionsReused++;
3347
+ else stats.connectionsCreated++;
3348
+ if (useCachedContext) stats.cachedContextRequests++;
3349
+ if (requestBody.store === true) stats.storeTrueRequests++;
3350
+ stats.lastInputItems = requestBody.input?.length ?? 0;
3351
+ if (requestBody.previous_response_id) {
3352
+ stats.deltaRequests++;
3353
+ stats.lastDeltaInputItems = requestBody.input?.length ?? 0;
3354
+ stats.lastPreviousResponseId = requestBody.previous_response_id;
3355
+ } else {
3356
+ stats.fullContextRequests++;
3357
+ stats.lastDeltaInputItems = void 0;
3358
+ stats.lastPreviousResponseId = void 0;
3359
+ }
3360
+ }
3361
+ try {
3362
+ socket.send(JSON.stringify({
3363
+ type: "response.create",
3364
+ ...requestBody
3365
+ }));
3366
+ await processResponsesStream(startWebSocketOutputOnFirstEvent(mapCodexEvents(parseWebSocket(socket, options?.signal, idleTimeoutMs), output, model, options?.onProviderStreamEvent), onStart), output, stream, model, {
3367
+ serviceTier: options?.serviceTier,
3368
+ grammarToolInputProperties,
3369
+ resolveServiceTier: resolveCodexServiceTier,
3370
+ applyServiceTierPricing: (usage, serviceTier) => applyServiceTierPricing(usage, serviceTier, model)
3371
+ });
3372
+ if (options?.signal?.aborted) keepConnection = false;
3373
+ else if (useCachedContext && entry && output.responseId) {
3374
+ const responseItems = convertResponsesMessages(model, normalizeContext({ messages: [output] }), CODEX_TOOL_CALL_PROVIDERS, { grammarToolInputProperties }).filter((item) => item.type !== "function_call_output" && item.type !== "custom_tool_call_output");
3375
+ entry.continuation = {
3376
+ lastRequestBody: fullBody,
3377
+ lastResponseId: output.responseId,
3378
+ lastResponseItems: responseItems
3379
+ };
3380
+ }
3381
+ } catch (error) {
3382
+ if (entry) entry.continuation = void 0;
3383
+ keepConnection = false;
3384
+ throw error;
3385
+ } finally {
3386
+ release({ keep: keepConnection });
3387
+ }
3388
+ }
3389
+ async function parseErrorResponse(response) {
3390
+ const raw = await response.text();
3391
+ let message = raw || response.statusText || "Request failed";
3392
+ let friendlyMessage;
3393
+ try {
3394
+ const err = JSON.parse(raw)?.error;
3395
+ if (err) {
3396
+ const code = err.code || err.type || "";
3397
+ if (/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(code) || response.status === 429) {
3398
+ const plan = err.plan_type ? ` (${err.plan_type.toLowerCase()} plan)` : "";
3399
+ const mins = err.resets_at ? Math.max(0, Math.round((err.resets_at * 1e3 - Date.now()) / 6e4)) : void 0;
3400
+ friendlyMessage = `You have hit your ChatGPT usage limit${plan}.${mins !== void 0 ? ` Try again in ~${mins} min.` : ""}`.trim();
3401
+ }
3402
+ message = err.message || friendlyMessage || message;
3403
+ }
3404
+ } catch {}
3405
+ return {
3406
+ message,
3407
+ friendlyMessage
3408
+ };
3409
+ }
3410
+ function extractAccountId(token) {
3411
+ try {
3412
+ const parts = token.split(".");
3413
+ if (parts.length !== 3) throw new Error("Invalid token");
3414
+ const accountId = JSON.parse(atob(parts[1]))?.[JWT_CLAIM_PATH]?.chatgpt_account_id;
3415
+ if (!accountId) throw new Error("No account ID in token");
3416
+ return accountId;
3417
+ } catch {
3418
+ throw new Error("Failed to extract accountId from token");
3419
+ }
3420
+ }
3421
+ function buildBaseCodexHeaders(defaultHeaders, initHeaders, additionalHeaders, accountId, token) {
3422
+ const headers = new Headers(defaultHeaders);
3423
+ for (const [key, value] of Object.entries(initHeaders || {})) headers.set(key, value);
3424
+ for (const [key, value] of Object.entries(additionalHeaders || {})) if (value === null) headers.delete(key);
3425
+ else headers.set(key, value);
3426
+ headers.set("Authorization", `Bearer ${token}`);
3427
+ headers.set("chatgpt-account-id", accountId);
3428
+ return headers;
3429
+ }
3430
+ function buildSSEHeaders(defaultHeaders, initHeaders, additionalHeaders, accountId, token, sessionId) {
3431
+ const headers = buildBaseCodexHeaders(defaultHeaders, initHeaders, additionalHeaders, accountId, token);
3432
+ headers.set("OpenAI-Beta", "responses=experimental");
3433
+ headers.set("accept", "text/event-stream");
3434
+ headers.set("content-type", "application/json");
3435
+ if (sessionId) {
3436
+ headers.set("session-id", sessionId);
3437
+ headers.set("x-client-request-id", sessionId);
3438
+ }
3439
+ return headers;
3440
+ }
3441
+ function buildWebSocketHeaders(defaultHeaders, initHeaders, additionalHeaders, accountId, token, requestId) {
3442
+ const headers = buildBaseCodexHeaders(defaultHeaders, initHeaders, additionalHeaders, accountId, token);
3443
+ headers.delete("accept");
3444
+ headers.delete("content-type");
3445
+ headers.delete("OpenAI-Beta");
3446
+ headers.delete("openai-beta");
3447
+ headers.set("OpenAI-Beta", OPENAI_BETA_RESPONSES_WEBSOCKETS);
3448
+ headers.set("x-client-request-id", requestId);
3449
+ headers.set("session-id", requestId);
3450
+ return headers;
3451
+ }
3452
+ export { closeOpenAICodexWebSocketSessions, getOpenAICodexWebSocketDebugStats, resetOpenAICodexWebSocketDebugStats, stream, streamSimple };