@dsh-ray/coding-subscription-provider 0.0.1-seed.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +98 -1
  3. package/cordis.patch.yml +8 -0
  4. package/lib/adapter.d.ts +120 -0
  5. package/lib/adapter.d.ts.map +1 -0
  6. package/lib/adapter.js +742 -0
  7. package/lib/adapter.js.map +1 -0
  8. package/lib/auth.d.ts +33 -0
  9. package/lib/auth.d.ts.map +1 -0
  10. package/lib/auth.js +101 -0
  11. package/lib/auth.js.map +1 -0
  12. package/lib/codex-catalog.d.ts +57 -0
  13. package/lib/codex-catalog.d.ts.map +1 -0
  14. package/lib/codex-catalog.js +369 -0
  15. package/lib/codex-catalog.js.map +1 -0
  16. package/lib/codex-direct-auth.d.ts +35 -0
  17. package/lib/codex-direct-auth.d.ts.map +1 -0
  18. package/lib/codex-direct-auth.js +626 -0
  19. package/lib/codex-direct-auth.js.map +1 -0
  20. package/lib/codex-direct-responses.d.ts +57 -0
  21. package/lib/codex-direct-responses.d.ts.map +1 -0
  22. package/lib/codex-direct-responses.js +1759 -0
  23. package/lib/codex-direct-responses.js.map +1 -0
  24. package/lib/config.d.ts +65 -0
  25. package/lib/config.d.ts.map +1 -0
  26. package/lib/config.js +105 -0
  27. package/lib/config.js.map +1 -0
  28. package/lib/index.d.ts +10 -0
  29. package/lib/index.d.ts.map +1 -0
  30. package/lib/index.js +70 -0
  31. package/lib/index.js.map +1 -0
  32. package/lib/process.d.ts +131 -0
  33. package/lib/process.d.ts.map +1 -0
  34. package/lib/process.js +1131 -0
  35. package/lib/process.js.map +1 -0
  36. package/lib/prompt.d.ts +15 -0
  37. package/lib/prompt.d.ts.map +1 -0
  38. package/lib/prompt.js +299 -0
  39. package/lib/prompt.js.map +1 -0
  40. package/lib/providers.d.ts +43 -0
  41. package/lib/providers.d.ts.map +1 -0
  42. package/lib/providers.js +179 -0
  43. package/lib/providers.js.map +1 -0
  44. package/lib/session-cwd.d.ts +26 -0
  45. package/lib/session-cwd.d.ts.map +1 -0
  46. package/lib/session-cwd.js +57 -0
  47. package/lib/session-cwd.js.map +1 -0
  48. package/lib/subscription-catalog.d.ts +51 -0
  49. package/lib/subscription-catalog.d.ts.map +1 -0
  50. package/lib/subscription-catalog.js +290 -0
  51. package/lib/subscription-catalog.js.map +1 -0
  52. package/lib/version.d.ts +2 -0
  53. package/lib/version.d.ts.map +1 -0
  54. package/lib/version.js +2 -0
  55. package/lib/version.js.map +1 -0
  56. package/package.json +82 -4
@@ -0,0 +1,1759 @@
1
+ import { ToolCallId, IMAGE_OFFLOAD_REQUIRED_CODE, LlmError, projectOffloadedImages, requiredImageOffload, } from '@deepseek-ai/dsh-llm';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ const DEFAULT_MAX_REQUEST_BYTES = 32 * 1024 * 1024;
4
+ const DEFAULT_MAX_REQUEST_IMAGE_BYTES = 24 * 1024 * 1024;
5
+ const DEFAULT_MAX_RESPONSE_BYTES = 64 * 1024 * 1024;
6
+ const DEFAULT_MAX_SSE_EVENT_BYTES = 1024 * 1024;
7
+ const MAX_PROVIDER_ID_BYTES = 4 * 1024;
8
+ const MAX_CALL_ID_BYTES = 4 * 1024;
9
+ const MAX_WIRE_ITEM_ID_CHARS = 64;
10
+ const MAX_TOOL_NAME_BYTES = 1024;
11
+ const MAX_JSON_DEPTH = 64;
12
+ const CONVERSATION_SCOPE_DOMAIN = 'dsh-ray/codex-direct/conversation/v1';
13
+ const PROMPT_CACHE_KEY_DOMAIN = 'dsh-ray/codex-direct/prompt-cache/v1';
14
+ const THREAD_SCOPE_DOMAIN = 'dsh-ray/codex-direct/thread/v1';
15
+ const HARMONY_TOKEN_NAMES = ['start', 'end', 'channel', 'message', 'constrain', 'return', 'call'];
16
+ const FORMAT_CHARACTER = /\p{Cf}/gu;
17
+ const HARMONY_CONTROL_TOKEN = new RegExp(`<\\p{Cf}*\\|\\p{Cf}*(?:${HARMONY_TOKEN_NAMES
18
+ .map(name => [...name].join('\\p{Cf}*'))
19
+ .join('|')})\\p{Cf}*\\|\\p{Cf}*>`, 'giu');
20
+ const FULLWIDTH_PIPE = '\uff5c';
21
+ export class CodexDirectResponsesError extends Error {
22
+ status;
23
+ constructor(message, cause, status) {
24
+ super(message, { cause });
25
+ this.name = 'CodexDirectResponsesError';
26
+ this.status = status;
27
+ }
28
+ }
29
+ /**
30
+ * Translate one DSH call to Codex's private Responses dialect and stream only
31
+ * provider-neutral chunks. It never reads credentials and never executes tools.
32
+ */
33
+ export async function* runCodexDirectResponses(options, dependencies) {
34
+ const signal = combineSignals(options.signal, dependencies.signal);
35
+ throwIfAborted(signal);
36
+ const limits = resolveLimits(dependencies);
37
+ if (options.stop !== undefined && options.stop.length > 0) {
38
+ throw protocolError('Codex private Responses does not support stop sequences');
39
+ }
40
+ if (options.temperature !== undefined) {
41
+ throw protocolError('Codex private Responses does not support temperature');
42
+ }
43
+ if (options.maxTokens !== undefined) {
44
+ throw protocolError('Codex private Responses does not support max tokens');
45
+ }
46
+ const toolNames = validateToolSchemas(options);
47
+ const built = await buildRequest(options, dependencies, limits.maxRequestImageBytes, signal);
48
+ const { request, routing } = built;
49
+ let serialized;
50
+ try {
51
+ serialized = JSON.stringify(request);
52
+ }
53
+ catch {
54
+ throw protocolError('Codex private Responses request is not serializable');
55
+ }
56
+ if (Buffer.byteLength(serialized, 'utf8') > limits.maxRequestBytes) {
57
+ throw new CodexDirectResponsesError('Codex private Responses request exceeds the configured request limit', 'prompt-limit');
58
+ }
59
+ const response = await dependencies.request(serialized, signal, routing);
60
+ if (signal.aborted) {
61
+ cancelBody(response.body);
62
+ throwIfAborted(signal);
63
+ }
64
+ if (!response.ok) {
65
+ cancelBody(response.body);
66
+ if (response.status === 401) {
67
+ throw new CodexDirectResponsesError('Codex private Responses rejected the ChatGPT subscription session', 'subscription-auth', 401);
68
+ }
69
+ throw new CodexDirectResponsesError(`Codex private Responses returned HTTP ${response.status}`, 'provider-http', response.status);
70
+ }
71
+ const contentType = response.headers.get('content-type')?.toLowerCase() ?? '';
72
+ // The ChatGPT Codex gateway currently omits Content-Type on otherwise valid
73
+ // SSE responses. Keep rejecting an explicitly different media type, while
74
+ // allowing the strict, bounded SSE parser below to authenticate a missing
75
+ // header from the event framing and terminal response shape.
76
+ if (contentType !== '' && !contentType.startsWith('text/event-stream')) {
77
+ cancelBody(response.body);
78
+ throw protocolError('Codex private Responses returned a non-SSE response');
79
+ }
80
+ const processor = new ResponseStreamProcessor(options, toolNames);
81
+ let preliminaryTerminal;
82
+ for await (const payload of parseSse(response, signal, limits.maxResponseBytes, limits.maxSseEventBytes)) {
83
+ if (payload === '[DONE]') {
84
+ if (preliminaryTerminal === undefined) {
85
+ throw protocolError('Codex private Responses ended before a terminal event');
86
+ }
87
+ for (const chunk of processor.accept(preliminaryTerminal.type, preliminaryTerminal.event))
88
+ yield chunk;
89
+ return;
90
+ }
91
+ const event = requireRecord(payload, 'SSE event');
92
+ const type = requireBoundedString(event.type, 'event type', MAX_PROVIDER_ID_BYTES);
93
+ if (type === 'response.completed') {
94
+ for (const chunk of processor.accept(type, event))
95
+ yield chunk;
96
+ return;
97
+ }
98
+ if (type === 'response.incomplete' || type === 'response.failed') {
99
+ if (preliminaryTerminal !== undefined) {
100
+ throw protocolError('Codex private Responses repeated a preliminary terminal event');
101
+ }
102
+ preliminaryTerminal = { type, event };
103
+ continue;
104
+ }
105
+ if (preliminaryTerminal !== undefined && isOfficialPrivateNoopEvent(type))
106
+ continue;
107
+ if (preliminaryTerminal !== undefined) {
108
+ throw protocolError('Codex private Responses emitted semantic data after a preliminary terminal event');
109
+ }
110
+ for (const chunk of processor.accept(type, event))
111
+ yield chunk;
112
+ }
113
+ if (preliminaryTerminal !== undefined) {
114
+ for (const chunk of processor.accept(preliminaryTerminal.type, preliminaryTerminal.event))
115
+ yield chunk;
116
+ return;
117
+ }
118
+ throw protocolError('Codex private Responses stream ended without a terminal event');
119
+ }
120
+ async function buildRequest(options, dependencies, maxRequestImageBytes, signal) {
121
+ const input = await buildInput(options, dependencies.attachments, maxRequestImageBytes, signal);
122
+ const tools = options.tools?.map(tool => ({
123
+ type: 'function',
124
+ name: tool.name,
125
+ description: neutralizeHarmonyText(tool.description),
126
+ parameters: neutralizeHarmonyStructure(tool.parameters),
127
+ strict: false,
128
+ }));
129
+ const instructions = neutralizeHarmonyText(options.system ?? '');
130
+ const routing = deriveRequestRouting(options.sessionId, instructions, tools ?? []);
131
+ const request = {
132
+ model: options.model,
133
+ instructions,
134
+ prompt_cache_key: routing.promptCacheKey,
135
+ input,
136
+ ...(tools === undefined || tools.length === 0 ? {} : { tools }),
137
+ tool_choice: 'auto',
138
+ parallel_tool_calls: true,
139
+ stream: true,
140
+ store: false,
141
+ include: ['reasoning.encrypted_content'],
142
+ reasoning: options.reasoningEffort === undefined
143
+ ? null
144
+ : {
145
+ effort: String(options.reasoningEffort) === 'ultra' ? 'max' : String(options.reasoningEffort),
146
+ summary: 'auto',
147
+ },
148
+ };
149
+ return { request, routing };
150
+ }
151
+ function deriveRequestRouting(sessionId, instructions, tools) {
152
+ // Production adapters only reach this point with an attested SessionId. A
153
+ // random seed preserves the standalone runner's low-level compatibility
154
+ // without manufacturing a stable identity when no Host session exists.
155
+ const sessionSeed = sessionId === undefined ? randomUUID() : String(sessionId);
156
+ const sessionScope = `dshc_${domainHash(CONVERSATION_SCOPE_DOMAIN, [sessionSeed]).slice(0, 32)}`;
157
+ const canonicalTools = [...tools]
158
+ .sort((left, right) => compareCodePoints(String(left.name), String(right.name)));
159
+ const promptCacheKey = `pck_${domainHash(PROMPT_CACHE_KEY_DOMAIN, [
160
+ sessionScope,
161
+ instructions,
162
+ canonicalJson(canonicalTools),
163
+ ]).slice(0, 24)}`;
164
+ const threadId = `dshth_${domainHash(THREAD_SCOPE_DOMAIN, [sessionScope]).slice(0, 32)}`;
165
+ return Object.freeze({ sessionId: sessionScope, threadId, promptCacheKey });
166
+ }
167
+ function compareCodePoints(left, right) {
168
+ return left < right ? -1 : left > right ? 1 : 0;
169
+ }
170
+ function domainHash(domain, values) {
171
+ const hash = createHash('sha256').update(domain).update('\0');
172
+ for (const value of values) {
173
+ hash.update(String(Buffer.byteLength(value, 'utf8'))).update(':').update(value).update('\0');
174
+ }
175
+ return hash.digest('hex');
176
+ }
177
+ function canonicalJson(value) {
178
+ const serialized = JSON.stringify(canonicalJsonValue(value));
179
+ if (serialized === undefined)
180
+ throw protocolError('Codex private Responses cache prefix is not serializable');
181
+ return serialized;
182
+ }
183
+ function canonicalJsonValue(value) {
184
+ if (Array.isArray(value))
185
+ return value.map(canonicalJsonValue);
186
+ if (!isRecord(value))
187
+ return value;
188
+ const canonical = {};
189
+ for (const key of Object.keys(value).sort())
190
+ canonical[key] = canonicalJsonValue(value[key]);
191
+ return canonical;
192
+ }
193
+ async function buildInput(options, attachments, maxRequestImageBytes, signal) {
194
+ const offloadImages = requiredImageOffload(options.messages, { maxBytes: maxRequestImageBytes, representation: 'raw' }, block => block.attachment.bytes);
195
+ if (offloadImages > 0)
196
+ throw LlmError.fromFailure({ message: 'Codex private Responses requires older images to be offloaded', code: IMAGE_OFFLOAD_REQUIRED_CODE, offloadImages });
197
+ const messages = projectOffloadedImages(options.messages, () => '[image omitted to keep the request within its image limit; older images are omitted first. If this image is still needed, read its file again when a path is available; otherwise ask the user to attach it again.]');
198
+ const input = [];
199
+ for (const message of messages) {
200
+ const replay = matchingReplay(message, options.provider, options.model);
201
+ if (replay !== undefined) {
202
+ input.push(...prepareReplayInput(replay.output));
203
+ continue;
204
+ }
205
+ await appendGenericMessage(input, message, attachments, signal);
206
+ }
207
+ return input;
208
+ }
209
+ function matchingReplay(message, provider, model) {
210
+ if (message.role !== 'assistant' || message.source.kind !== 'model')
211
+ return undefined;
212
+ // The durable source retains the user-facing model alias (`default`) while
213
+ // replay records the concrete model sent on the wire. The replay's own model
214
+ // identity plus exact durable-content projection is the safe comparison.
215
+ if (message.source.provider !== provider)
216
+ return undefined;
217
+ const envelope = message.source.replayState;
218
+ if (!isRecord(envelope))
219
+ return undefined;
220
+ const response = envelope.response;
221
+ if (!isRecord(response)
222
+ || response.kind !== 'codex-private-responses'
223
+ || (response.version !== 2 && response.version !== 3)
224
+ || response.provider !== provider
225
+ || response.model !== model
226
+ || !isBoundedString(response.responseId, MAX_PROVIDER_ID_BYTES)
227
+ || !Array.isArray(response.output)
228
+ || !isLosslessJson(response.output)
229
+ || !Array.isArray(response.blockOrder)
230
+ || !isLosslessJson(response.blockOrder))
231
+ return undefined;
232
+ let projected;
233
+ try {
234
+ projected = projectNativeOutput(response.output, response.blockOrder);
235
+ }
236
+ catch {
237
+ return undefined;
238
+ }
239
+ if (!contentEquals(projected.blocks, message.content))
240
+ return undefined;
241
+ return response;
242
+ }
243
+ /**
244
+ * Rebuild provider output before replaying it. With `store: false`, reasoning
245
+ * and function-call item ids are not durable server references. Keeping the
246
+ * raw items in replayState preserves lossless Host projection, while this
247
+ * outbound copy contains only fields accepted as fresh Responses input.
248
+ */
249
+ function prepareReplayInput(output) {
250
+ const prepared = [];
251
+ for (const value of output) {
252
+ const item = requireRecord(value, 'replay output item');
253
+ switch (item.type) {
254
+ case 'reasoning': {
255
+ if (typeof item.encrypted_content !== 'string' || item.encrypted_content.length === 0)
256
+ break;
257
+ const summary = Array.isArray(item.summary)
258
+ ? item.summary.map(value => {
259
+ const part = requireRecord(value, 'replay reasoning summary');
260
+ if (part.type !== 'summary_text')
261
+ throw protocolError('Replay reasoning summary type is unsupported');
262
+ return {
263
+ type: 'summary_text',
264
+ text: neutralizeHarmonyText(requireString(part.text, 'replay reasoning summary text')),
265
+ };
266
+ })
267
+ : [];
268
+ prepared.push({
269
+ type: 'reasoning',
270
+ encrypted_content: item.encrypted_content,
271
+ summary,
272
+ });
273
+ break;
274
+ }
275
+ case 'message': {
276
+ if (item.role !== 'assistant' || !Array.isArray(item.content)) {
277
+ throw protocolError('Replay message content is invalid');
278
+ }
279
+ const content = item.content.map(value => {
280
+ const part = requireRecord(value, 'replay message content');
281
+ if (part.type === 'output_text') {
282
+ return { type: 'output_text', text: neutralizeHarmonyText(requireString(part.text, 'replay output text')) };
283
+ }
284
+ if (part.type === 'refusal') {
285
+ return { type: 'output_text', text: neutralizeHarmonyText(requireString(part.refusal, 'replay refusal')) };
286
+ }
287
+ throw protocolError('Replay message content type is unsupported');
288
+ });
289
+ const message = {
290
+ type: 'message',
291
+ role: 'assistant',
292
+ status: normalizeReplayMessageStatus(item.status),
293
+ content,
294
+ };
295
+ if (typeof item.id === 'string' && [...item.id].length <= MAX_WIRE_ITEM_ID_CHARS)
296
+ message.id = item.id;
297
+ if (typeof item.phase === 'string' && item.phase.length > 0)
298
+ message.phase = item.phase;
299
+ prepared.push(message);
300
+ break;
301
+ }
302
+ case 'function_call':
303
+ prepared.push({
304
+ type: 'function_call',
305
+ call_id: wireCallId(requireBoundedString(item.call_id, 'replay function call id', MAX_CALL_ID_BYTES)),
306
+ name: requireBoundedString(item.name, 'replay function name', MAX_TOOL_NAME_BYTES),
307
+ arguments: neutralizeHarmonyText(requireString(item.arguments, 'replay function arguments')),
308
+ });
309
+ break;
310
+ default:
311
+ throw protocolError('Replay output item type is unsupported');
312
+ }
313
+ }
314
+ const finalItem = prepared.at(-1);
315
+ if (isRecord(finalItem) && finalItem.type === 'reasoning') {
316
+ prepared.push({ role: 'assistant', content: '' });
317
+ }
318
+ return prepared;
319
+ }
320
+ function normalizeReplayMessageStatus(value) {
321
+ return value === 'incomplete' ? 'incomplete' : 'completed';
322
+ }
323
+ function wireCallId(value) {
324
+ const normalized = requireBoundedString(value.trim(), 'function call id', MAX_CALL_ID_BYTES);
325
+ if ([...normalized].length <= MAX_WIRE_ITEM_ID_CHARS)
326
+ return normalized;
327
+ return `call_${createHash('sha256').update(normalized).digest('hex').slice(0, 32)}`;
328
+ }
329
+ function neutralizeHarmonyText(value) {
330
+ if (!value.includes('<') || !value.includes('|'))
331
+ return value;
332
+ return value.replace(HARMONY_CONTROL_TOKEN, match => {
333
+ const visible = match.replace(FORMAT_CHARACTER, '');
334
+ return `<${FULLWIDTH_PIPE}${visible.slice(2, -2)}${FULLWIDTH_PIPE}>`;
335
+ });
336
+ }
337
+ function neutralizeHarmonyStructure(value, depth = 0) {
338
+ if (typeof value === 'string')
339
+ return neutralizeHarmonyText(value);
340
+ if (value === null || typeof value === 'boolean' || typeof value === 'number')
341
+ return value;
342
+ if (depth >= MAX_JSON_DEPTH)
343
+ throw protocolError('Codex private Responses tool parameters exceed maximum depth');
344
+ if (Array.isArray(value))
345
+ return value.map(item => neutralizeHarmonyStructure(item, depth + 1));
346
+ if (!isRecord(value) || Object.getPrototypeOf(value) !== Object.prototype) {
347
+ throw protocolError('Codex private Responses received invalid tool parameters');
348
+ }
349
+ const normalized = {};
350
+ for (const [key, item] of Object.entries(value)) {
351
+ if (neutralizeHarmonyText(key) !== key) {
352
+ throw protocolError('Codex private Responses tool parameter keys contain a reserved token');
353
+ }
354
+ normalized[key] = neutralizeHarmonyStructure(item, depth + 1);
355
+ }
356
+ return normalized;
357
+ }
358
+ async function appendGenericMessage(input, message, attachments, signal) {
359
+ if (message.role === 'assistant') {
360
+ let content = [];
361
+ const flush = () => {
362
+ if (content.length === 0)
363
+ return;
364
+ input.push({ role: 'assistant', content });
365
+ content = [];
366
+ };
367
+ for (const block of message.content) {
368
+ switch (block.type) {
369
+ case 'text':
370
+ case 'reasoning':
371
+ content.push({ type: 'output_text', text: neutralizeHarmonyText(block.text) });
372
+ break;
373
+ case 'tool-call':
374
+ flush();
375
+ input.push({
376
+ type: 'function_call',
377
+ call_id: wireCallId(String(block.id)),
378
+ name: block.name,
379
+ arguments: neutralizeHarmonyText(block.arguments),
380
+ });
381
+ break;
382
+ case 'image':
383
+ throw protocolError(`Codex private Responses cannot serialize ${block.type} in an assistant message`);
384
+ default:
385
+ throw protocolError('Codex private Responses encountered an unknown assistant content block');
386
+ }
387
+ }
388
+ flush();
389
+ return;
390
+ }
391
+ if (message.role === 'tool') {
392
+ if (message.toolCallId !== message.source.callId)
393
+ throw protocolError('Codex private Responses received a mismatched tool result');
394
+ input.push({ type: 'function_call_output', call_id: wireCallId(String(message.toolCallId)),
395
+ output: await functionOutput(message.content, message.isError === true, attachments, signal) });
396
+ return;
397
+ }
398
+ if (message.role === 'user' && message.source?.kind === 'tool')
399
+ throw protocolError('Codex private Responses received a tool result in a user message');
400
+ const role = message.role;
401
+ let content = [];
402
+ const flush = () => {
403
+ if (content.length === 0)
404
+ return;
405
+ input.push({ role, content });
406
+ content = [];
407
+ };
408
+ for (const block of message.content) {
409
+ switch (block.type) {
410
+ case 'text':
411
+ case 'reasoning':
412
+ content.push({ type: 'input_text', text: neutralizeHarmonyText(block.text) });
413
+ break;
414
+ case 'image':
415
+ if (message.role !== 'user') {
416
+ throw protocolError(`Codex private Responses cannot serialize an image in a ${message.role} message`);
417
+ }
418
+ content.push(await inputImage(block.attachment, attachments, signal));
419
+ break;
420
+ case 'tool-call':
421
+ throw protocolError(`Codex private Responses cannot serialize ${block.type} in a ${message.role} message`);
422
+ default:
423
+ throw protocolError('Codex private Responses encountered an unknown input content block');
424
+ }
425
+ }
426
+ flush();
427
+ }
428
+ async function functionOutput(content, isError, attachments, signal) {
429
+ const parts = isError ? [{ type: 'input_text', text: '[tool_error]' }] : [];
430
+ for (const block of content) {
431
+ switch (block.type) {
432
+ case 'text':
433
+ case 'reasoning':
434
+ parts.push({ type: 'input_text', text: neutralizeHarmonyText(block.text) });
435
+ break;
436
+ case 'image':
437
+ parts.push(await inputImage(block.attachment, attachments, signal));
438
+ break;
439
+ case 'tool-call':
440
+ throw protocolError('Codex private Responses cannot nest a tool block inside a tool result');
441
+ default:
442
+ throw protocolError('Codex private Responses encountered an unknown tool-result content block');
443
+ }
444
+ }
445
+ if (parts.length === 0)
446
+ return '';
447
+ if (parts.length === 1 && isRecord(parts[0]) && parts[0].type === 'input_text')
448
+ return String(parts[0].text);
449
+ return parts;
450
+ }
451
+ async function inputImage(ref, attachments, signal) {
452
+ if (attachments === undefined)
453
+ throw protocolError('Codex private Responses requires attachment storage for image input');
454
+ throwIfAborted(signal);
455
+ const stored = await attachments.readImage(ref, signal);
456
+ throwIfAborted(signal);
457
+ if (!(stored.data instanceof Uint8Array)
458
+ || stored.data.byteLength !== ref.bytes
459
+ || stored.ref === undefined
460
+ || !sameImageRef(ref, stored.ref)) {
461
+ throw protocolError('Codex private Responses received an invalid stored image');
462
+ }
463
+ return {
464
+ type: 'input_image',
465
+ detail: 'auto',
466
+ image_url: `data:${ref.mediaType};base64,${Buffer.from(stored.data).toString('base64')}`,
467
+ };
468
+ }
469
+ function sameImageRef(left, right) {
470
+ return left.attachmentId === right.attachmentId
471
+ && left.mediaType === right.mediaType
472
+ && left.bytes === right.bytes
473
+ && left.width === right.width
474
+ && left.height === right.height;
475
+ }
476
+ class ResponseStreamProcessor {
477
+ #items = new Map();
478
+ #providerItems = new Map();
479
+ #outputIndexes = new Map();
480
+ #doneItems = new Map();
481
+ #blocks = new Map();
482
+ #callIds = new Map();
483
+ #toolNames;
484
+ #options;
485
+ #nextIndex = 0;
486
+ #hasVisibleOutput = false;
487
+ #activeItemId;
488
+ #createdSeen = false;
489
+ #createdResponseId;
490
+ constructor(options, toolNames) {
491
+ this.#options = options;
492
+ this.#toolNames = toolNames;
493
+ }
494
+ accept(type, event) {
495
+ switch (type) {
496
+ case 'response.created':
497
+ return this.#created(event);
498
+ case 'response.queued':
499
+ case 'response.in_progress':
500
+ case 'response.output_text.annotation.added':
501
+ case 'codex.response.metadata':
502
+ case 'response.metadata':
503
+ case 'responsesapi.websocket_timing':
504
+ case 'response.custom_tool_call_input.done':
505
+ return [];
506
+ case 'response.output_item.added':
507
+ return this.#outputItemAdded(event);
508
+ case 'response.output_item.done':
509
+ return this.#outputItemDone(event);
510
+ case 'response.content_part.added':
511
+ if (!hasRichPartIdentity(event))
512
+ return [];
513
+ return this.#contentPart(event, false);
514
+ case 'response.content_part.done':
515
+ if (!hasRichPartIdentity(event))
516
+ return [];
517
+ return this.#contentPart(event, true);
518
+ case 'response.output_text.delta':
519
+ return this.#textDelta(event, 'output_text');
520
+ case 'response.output_text.done':
521
+ if (!hasRichPartIdentity(event))
522
+ return [];
523
+ return this.#textDone(event, 'output_text');
524
+ case 'response.refusal.delta':
525
+ return this.#textDelta(event, 'refusal');
526
+ case 'response.refusal.done':
527
+ return this.#textDone(event, 'refusal');
528
+ case 'response.reasoning_summary_part.added':
529
+ return this.#reasoningPart(event, false);
530
+ case 'response.reasoning_summary_part.done':
531
+ if (event.item_id === undefined && event.output_index === undefined)
532
+ return [];
533
+ return this.#reasoningPart(event, true);
534
+ case 'response.reasoning_summary_text.delta':
535
+ return this.#textDelta(event, 'summary_text');
536
+ case 'response.reasoning_summary_text.done':
537
+ return this.#textDone(event, 'summary_text');
538
+ case 'response.function_call_arguments.delta':
539
+ if (event.item_id === undefined && event.output_index === undefined)
540
+ return [];
541
+ return this.#functionDelta(event);
542
+ case 'response.function_call_arguments.done':
543
+ if (event.item_id === undefined && event.output_index === undefined)
544
+ return [];
545
+ return this.#functionDone(event);
546
+ case 'response.reasoning_text.delta':
547
+ return this.#rawReasoning(event, false);
548
+ case 'response.reasoning_text.done':
549
+ return this.#rawReasoning(event, true);
550
+ case 'response.completed':
551
+ case 'response.incomplete':
552
+ case 'response.failed':
553
+ return this.#terminal(type, event);
554
+ case 'error':
555
+ throw new CodexDirectResponsesError('Codex private Responses request failed', 'provider-failure');
556
+ default:
557
+ throw protocolError('Codex private Responses emitted an unsupported event type');
558
+ }
559
+ }
560
+ #created(event) {
561
+ const response = requireRecord(event.response, 'created response');
562
+ const responseId = optionalBoundedString(response.id, 'created response id', MAX_PROVIDER_ID_BYTES);
563
+ if (this.#createdSeen) {
564
+ throw protocolError('Codex private Responses repeated its created event');
565
+ }
566
+ this.#createdSeen = true;
567
+ this.#createdResponseId = responseId;
568
+ return [];
569
+ }
570
+ #outputItemAdded(event) {
571
+ const item = requireRecord(event.item, 'output item');
572
+ if (!isLosslessJson(item))
573
+ throw protocolError('Codex private Responses output item is invalid');
574
+ const explicitIndex = optionalIndex(event.output_index, 'output index');
575
+ const itemType = requireBoundedString(item.type, 'output item type', MAX_PROVIDER_ID_BYTES);
576
+ validateOutputItem(item, 'streamed output item', true);
577
+ const active = this.#activeItemId === undefined ? undefined : this.#items.get(this.#activeItemId);
578
+ if (explicitIndex === undefined && active !== undefined && !(active.provisional && itemType === 'message')) {
579
+ throw protocolError('Codex private Responses overlapped active output items');
580
+ }
581
+ const outputIndex = explicitIndex ?? active?.outputIndex ?? this.#outputIndexes.size;
582
+ const itemState = this.#registerItem(item, outputIndex, itemType);
583
+ itemState.provisional = false;
584
+ if (this.#activeItemId === undefined)
585
+ this.#activeItemId = itemState.id;
586
+ const chunks = [];
587
+ this.#seedAddedItem(item, itemState, chunks);
588
+ return chunks;
589
+ }
590
+ #outputItemDone(event) {
591
+ const item = requireRecord(event.item, 'completed output item');
592
+ if (!isLosslessJson(item))
593
+ throw protocolError('Codex private Responses completed output item is invalid');
594
+ const explicitIndex = optionalIndex(event.output_index, 'output index');
595
+ const itemType = requireBoundedString(item.type, 'output item type', MAX_PROVIDER_ID_BYTES);
596
+ const providerId = optionalBoundedString(item.id, 'output item id', MAX_PROVIDER_ID_BYTES);
597
+ const providerKey = providerId === undefined ? undefined : this.#providerItems.get(providerId);
598
+ let outputIndex;
599
+ if (explicitIndex !== undefined) {
600
+ outputIndex = explicitIndex;
601
+ }
602
+ else if (providerKey !== undefined) {
603
+ const known = this.#items.get(providerKey);
604
+ if (known === undefined)
605
+ throw protocolError('Codex private Responses lost an output item');
606
+ outputIndex = known.outputIndex;
607
+ }
608
+ else {
609
+ const candidates = this.#unfinishedItems(itemType);
610
+ if (candidates.length > 1) {
611
+ throw protocolError('Codex private Responses emitted an ambiguous identity-less completed item');
612
+ }
613
+ outputIndex = candidates[0]?.outputIndex ?? this.#outputIndexes.size;
614
+ }
615
+ if (outputIndex !== this.#doneItems.size) {
616
+ throw protocolError('Codex private Responses completed output items out of order');
617
+ }
618
+ const chunks = [];
619
+ const state = this.#finalizeItem(item, outputIndex, chunks, 'stream-item');
620
+ if (this.#activeItemId !== undefined) {
621
+ if (state.id !== this.#activeItemId) {
622
+ throw protocolError('Codex private Responses completed a different active output item');
623
+ }
624
+ this.#activeItemId = undefined;
625
+ }
626
+ if (state.doneItem !== undefined && !jsonEquals(state.doneItem, item)) {
627
+ throw protocolError('Codex private Responses changed an already completed output item');
628
+ }
629
+ state.doneItem = item;
630
+ this.#doneItems.set(outputIndex, item);
631
+ return chunks;
632
+ }
633
+ #seedAddedItem(item, state, chunks) {
634
+ switch (state.type) {
635
+ case 'message': {
636
+ if (item.content === undefined)
637
+ return;
638
+ if (!Array.isArray(item.content))
639
+ throw protocolError('Codex private Responses message content is invalid');
640
+ item.content.forEach((value, contentIndex) => {
641
+ const part = requireRecord(value, 'message content part');
642
+ if (part.type !== 'output_text' && part.type !== 'refusal') {
643
+ throw protocolError('Codex private Responses emitted an unsupported message content part');
644
+ }
645
+ const text = requireString(part.type === 'refusal' ? part.refusal : part.text, 'message content prefix');
646
+ const block = this.#ensureText(state.id, state.outputIndex, contentIndex, part.type, chunks, true, true);
647
+ this.#appendText(block, text, chunks);
648
+ });
649
+ return;
650
+ }
651
+ case 'reasoning': {
652
+ if (item.summary === undefined)
653
+ return;
654
+ if (!Array.isArray(item.summary))
655
+ throw protocolError('Codex private Responses reasoning summary is invalid');
656
+ item.summary.forEach((value, summaryIndex) => {
657
+ const part = requireRecord(value, 'reasoning summary part');
658
+ if (part.type !== 'summary_text')
659
+ throw protocolError('Codex private Responses emitted an unsupported reasoning summary');
660
+ const block = this.#ensureText(state.id, state.outputIndex, summaryIndex, 'summary_text', chunks, true, true);
661
+ this.#appendText(block, requireString(part.text, 'reasoning summary prefix'), chunks);
662
+ });
663
+ return;
664
+ }
665
+ case 'function_call':
666
+ this.#ensureTool(item, state, chunks);
667
+ return;
668
+ default:
669
+ throw protocolError('Codex private Responses emitted an unsupported output item');
670
+ }
671
+ }
672
+ #resolveItem(event, expectedType, label, allowProvisionalMessage = false) {
673
+ const providerId = optionalBoundedString(event.item_id, `${label} item id`, MAX_PROVIDER_ID_BYTES);
674
+ const outputIndex = optionalIndex(event.output_index, `${label} output index`);
675
+ const providerKey = providerId === undefined ? undefined : this.#providerItems.get(providerId);
676
+ const indexedKey = outputIndex === undefined ? undefined : this.#outputIndexes.get(outputIndex);
677
+ if (providerKey !== undefined && indexedKey !== undefined && providerKey !== indexedKey) {
678
+ throw protocolError('Codex private Responses changed an output item identity');
679
+ }
680
+ let key = providerKey ?? indexedKey;
681
+ if (key === undefined && providerId === undefined && outputIndex === undefined) {
682
+ const candidates = this.#unfinishedItems(expectedType);
683
+ if (candidates.length > 1) {
684
+ throw protocolError('Codex private Responses emitted ambiguous identity-less item data');
685
+ }
686
+ key = candidates[0]?.id;
687
+ }
688
+ if (key === undefined && allowProvisionalMessage && expectedType === 'message'
689
+ && providerId === undefined && outputIndex === undefined && this.#activeItemId === undefined) {
690
+ const provisional = this.#registerItem({ type: 'message', role: 'assistant' }, this.#outputIndexes.size, 'message');
691
+ provisional.provisional = true;
692
+ this.#activeItemId = provisional.id;
693
+ key = provisional.id;
694
+ }
695
+ const state = key === undefined ? undefined : this.#items.get(key);
696
+ if (state === undefined || state.type !== expectedType) {
697
+ throw protocolError(`Codex private Responses emitted ${label} for an unknown or incompatible output item`);
698
+ }
699
+ if (providerId !== undefined && state.providerId !== providerId) {
700
+ throw protocolError('Codex private Responses changed an output item identity');
701
+ }
702
+ if (outputIndex !== undefined && state.outputIndex !== outputIndex) {
703
+ throw protocolError('Codex private Responses changed an output item index');
704
+ }
705
+ return state;
706
+ }
707
+ #unfinishedItems(expectedType) {
708
+ return [...this.#items.values()].filter(state => state.type === expectedType && state.doneItem === undefined);
709
+ }
710
+ #contentPart(event, done) {
711
+ const part = requireRecord(event.part, 'content part');
712
+ const nativeType = part.type;
713
+ if (nativeType !== 'output_text' && nativeType !== 'refusal') {
714
+ throw protocolError('Codex private Responses emitted an unsupported message content part');
715
+ }
716
+ const item = this.#resolveItem(event, 'message', 'message content');
717
+ const contentIndex = requireIndex(event.content_index, 'content index');
718
+ const chunks = [];
719
+ const state = this.#ensureText(item.id, item.outputIndex, contentIndex, nativeType, chunks, true, !done);
720
+ const value = requireString(nativeType === 'refusal' ? part.refusal : part.text, 'content part text');
721
+ if (done)
722
+ this.#finishText(state, value, chunks);
723
+ else
724
+ this.#appendText(state, value, chunks);
725
+ return chunks;
726
+ }
727
+ #reasoningPart(event, done) {
728
+ const part = event.part === undefined
729
+ ? { type: 'summary_text', text: '' }
730
+ : requireRecord(event.part, 'reasoning summary part');
731
+ if (part.type !== 'summary_text') {
732
+ throw protocolError('Codex private Responses emitted an unsupported reasoning summary part');
733
+ }
734
+ const item = this.#resolveItem(event, 'reasoning', 'reasoning summary');
735
+ const summaryIndex = requireIndex(event.summary_index, 'summary index');
736
+ const chunks = [];
737
+ const state = this.#ensureText(item.id, item.outputIndex, summaryIndex, 'summary_text', chunks, true, !done);
738
+ const value = requireString(part.text, 'reasoning summary part text');
739
+ if (done)
740
+ this.#finishText(state, value, chunks);
741
+ else
742
+ this.#appendText(state, value, chunks);
743
+ return chunks;
744
+ }
745
+ #textDelta(event, nativeType) {
746
+ const expectedType = nativeType === 'summary_text' ? 'reasoning' : 'message';
747
+ const item = this.#resolveItem(event, expectedType, nativeType === 'summary_text' ? 'reasoning summary' : 'text', nativeType === 'output_text');
748
+ const rawPartIndex = nativeType === 'summary_text' ? event.summary_index : event.content_index;
749
+ const partIndex = rawPartIndex === undefined && nativeType !== 'summary_text'
750
+ ? 0
751
+ : requireIndex(rawPartIndex, nativeType === 'summary_text' ? 'summary index' : 'content index');
752
+ const delta = requireString(event.delta, 'text delta');
753
+ const chunks = [];
754
+ const state = this.#ensureText(item.id, item.outputIndex, partIndex, nativeType, chunks, true);
755
+ if (state.closed)
756
+ throw protocolError('Codex private Responses emitted text after closing its content part');
757
+ state.text += delta;
758
+ if (delta.length > 0) {
759
+ chunks.push(state.kind === 'text'
760
+ ? { type: 'text-delta', index: state.index, text: delta }
761
+ : { type: 'reasoning-delta', index: state.index, text: delta });
762
+ }
763
+ return chunks;
764
+ }
765
+ #textDone(event, nativeType) {
766
+ const expectedType = nativeType === 'summary_text' ? 'reasoning' : 'message';
767
+ const item = this.#resolveItem(event, expectedType, nativeType === 'summary_text' ? 'reasoning summary' : 'text');
768
+ const rawPartIndex = nativeType === 'summary_text' ? event.summary_index : event.content_index;
769
+ const partIndex = rawPartIndex === undefined && nativeType !== 'summary_text'
770
+ ? 0
771
+ : requireIndex(rawPartIndex, nativeType === 'summary_text' ? 'summary index' : 'content index');
772
+ const value = nativeType === 'refusal' ? event.refusal : event.text;
773
+ const text = requireString(value, 'completed text');
774
+ const chunks = [];
775
+ const state = this.#ensureText(item.id, item.outputIndex, partIndex, nativeType, chunks, true);
776
+ this.#finishText(state, text, chunks);
777
+ return chunks;
778
+ }
779
+ #functionDelta(event) {
780
+ const item = this.#resolveItem(event, 'function_call', 'function arguments');
781
+ const delta = requireString(event.delta, 'function arguments delta');
782
+ const state = this.#toolForItem(item.id, item.outputIndex);
783
+ if (state.closed)
784
+ throw protocolError('Codex private Responses emitted arguments after closing a function call');
785
+ state.arguments += delta;
786
+ return delta.length === 0
787
+ ? []
788
+ : [{ type: 'tool-call-delta', index: state.index, id: ToolCallId(state.callId), argumentsDelta: delta }];
789
+ }
790
+ #functionDone(event) {
791
+ const item = this.#resolveItem(event, 'function_call', 'function arguments');
792
+ const state = this.#toolForItem(item.id, item.outputIndex);
793
+ const finalArguments = requireString(event.arguments, 'function arguments');
794
+ if (state.argumentsDone || state.closed) {
795
+ throw protocolError('Codex private Responses repeated completed function arguments');
796
+ }
797
+ const chunks = [];
798
+ this.#reconcileToolArguments(state, finalArguments, chunks);
799
+ state.argumentsDone = true;
800
+ return chunks;
801
+ }
802
+ #rawReasoning(event, done) {
803
+ this.#resolveItem(event, 'reasoning', 'raw reasoning');
804
+ requireIndex(event.content_index, 'reasoning content index');
805
+ requireString(done ? event.text : event.delta, done ? 'completed raw reasoning' : 'raw reasoning delta');
806
+ return [];
807
+ }
808
+ #terminal(type, event) {
809
+ const response = requireRecord(event.response, 'terminal response');
810
+ const expectedStatus = type.slice('response.'.length);
811
+ if (response.status !== undefined && response.status !== expectedStatus) {
812
+ throw protocolError('Codex private Responses terminal status does not match its event');
813
+ }
814
+ if (type === 'response.failed') {
815
+ const code = isRecord(response.error) && typeof response.error.code === 'string'
816
+ && Buffer.byteLength(response.error.code, 'utf8') <= MAX_PROVIDER_ID_BYTES
817
+ ? response.error.code
818
+ : undefined;
819
+ if (code === 'context_length_exceeded') {
820
+ throw new CodexDirectResponsesError('Codex private Responses exceeded the model context window', 'context-window');
821
+ }
822
+ if (code === 'insufficient_quota') {
823
+ throw new CodexDirectResponsesError('Codex private Responses subscription quota is unavailable', 'quota');
824
+ }
825
+ throw new CodexDirectResponsesError('Codex private Responses request failed', 'provider-failure');
826
+ }
827
+ const responseId = requireBoundedString(response.id, 'response id', MAX_PROVIDER_ID_BYTES);
828
+ if (this.#createdResponseId !== undefined && this.#createdResponseId !== responseId) {
829
+ throw protocolError('Codex private Responses changed its response id');
830
+ }
831
+ if (response.end_turn !== undefined
832
+ && response.end_turn !== null
833
+ && typeof response.end_turn !== 'boolean') {
834
+ throw protocolError('Codex private Responses end-turn flag is invalid');
835
+ }
836
+ if (response.end_turn === false) {
837
+ throw protocolError('Codex private Responses requested an unsupported follow-up turn');
838
+ }
839
+ let incomplete = false;
840
+ if (type === 'response.incomplete') {
841
+ const details = requireRecord(response.incomplete_details, 'incomplete response details');
842
+ if (details.reason === 'content_filter') {
843
+ throw new CodexDirectResponsesError('Codex private Responses output was filtered', 'content-filter');
844
+ }
845
+ if (details.reason !== 'max_output_tokens') {
846
+ throw protocolError('Codex private Responses ended in an unsupported incomplete state');
847
+ }
848
+ incomplete = true;
849
+ }
850
+ let terminalOutput;
851
+ if (response.output !== undefined && response.output !== null) {
852
+ if (!Array.isArray(response.output) || !isLosslessJson(response.output)) {
853
+ throw protocolError('Codex private Responses terminal output is invalid');
854
+ }
855
+ terminalOutput = response.output;
856
+ }
857
+ const chunks = [];
858
+ let output;
859
+ const observed = [...this.#doneItems.entries()]
860
+ .sort(([left], [right]) => left - right)
861
+ .map(([, item]) => item);
862
+ if (terminalOutput?.length === 0 && observed.length > 0)
863
+ terminalOutput = undefined;
864
+ const active = this.#activeItemId === undefined ? undefined : this.#items.get(this.#activeItemId);
865
+ if (terminalOutput !== undefined && observed.length === 0 && active?.provisional === true) {
866
+ if (terminalOutput.length !== 1) {
867
+ throw protocolError('Codex private Responses terminal output conflicts with provisional text');
868
+ }
869
+ const placeholder = requireRecord(terminalOutput[0], 'terminal provisional message');
870
+ if (placeholder.type !== 'message' || placeholder.role !== 'assistant'
871
+ || !Array.isArray(placeholder.content) || placeholder.content.length !== 0) {
872
+ throw protocolError('Codex private Responses terminal output conflicts with provisional text');
873
+ }
874
+ const text = this.#blocks.get(`text:${active.id}:0`);
875
+ if (active.type !== 'message' || text?.kind !== 'text' || text.nativeType !== 'output_text') {
876
+ throw protocolError('Codex private Responses completed an invalid provisional message');
877
+ }
878
+ terminalOutput = [{
879
+ ...placeholder,
880
+ content: [{ type: 'output_text', text: text.text }],
881
+ }];
882
+ }
883
+ if (terminalOutput !== undefined && observed.length > 0) {
884
+ if (terminalOutput.length !== observed.length
885
+ || terminalOutput.some((item, index) => !jsonEquals(item, observed[index]))) {
886
+ throw protocolError('Codex private Responses terminal output disagrees with completed items');
887
+ }
888
+ output = terminalOutput;
889
+ }
890
+ else if (terminalOutput !== undefined) {
891
+ output = terminalOutput;
892
+ }
893
+ else if (observed.length > 0) {
894
+ output = observed;
895
+ }
896
+ else if (this.#activeItemId !== undefined && incomplete) {
897
+ output = [];
898
+ }
899
+ else if (this.#activeItemId !== undefined) {
900
+ const active = this.#items.get(this.#activeItemId);
901
+ if (active === undefined || !active.provisional || active.type !== 'message') {
902
+ throw protocolError('Codex private Responses completed with an active output item');
903
+ }
904
+ const state = this.#blocks.get(`text:${active.id}:0`);
905
+ if (state?.kind !== 'text' || state.nativeType !== 'output_text') {
906
+ throw protocolError('Codex private Responses completed an invalid provisional message');
907
+ }
908
+ output = [{
909
+ type: 'message', role: 'assistant',
910
+ content: [{ type: 'output_text', text: state.text }],
911
+ }];
912
+ }
913
+ else {
914
+ output = [];
915
+ }
916
+ if (!isLosslessJson(output))
917
+ throw protocolError('Codex private Responses terminal output is invalid');
918
+ if (this.#activeItemId !== undefined && !incomplete) {
919
+ const active = this.#items.get(this.#activeItemId);
920
+ if (active === undefined || (!active.provisional && observed.length === 0)) {
921
+ throw protocolError('Codex private Responses completed with an active output item');
922
+ }
923
+ }
924
+ output.forEach((value, outputIndex) => {
925
+ const item = requireRecord(value, 'terminal output item');
926
+ const state = this.#finalizeItem(item, outputIndex, chunks, incomplete ? 'max-tokens-terminal' : 'completed-terminal');
927
+ if (state.doneItem !== undefined && !jsonEquals(state.doneItem, item)) {
928
+ throw protocolError('Codex private Responses terminal output disagrees with its completed item');
929
+ }
930
+ state.doneItem = item;
931
+ this.#doneItems.set(outputIndex, item);
932
+ });
933
+ if (incomplete) {
934
+ for (const state of this.#blocks.values()) {
935
+ if (state.closed)
936
+ continue;
937
+ if (state.kind === 'tool-call')
938
+ this.#finishTool(state, state.arguments, chunks);
939
+ else
940
+ this.#finishText(state, state.text, chunks);
941
+ }
942
+ }
943
+ else {
944
+ if (this.#items.size !== output.length) {
945
+ throw protocolError('Codex private Responses terminal output omitted a streamed item');
946
+ }
947
+ for (const state of this.#items.values()) {
948
+ if (state.doneItem === undefined)
949
+ throw protocolError('Codex private Responses terminal output omitted a streamed item');
950
+ }
951
+ }
952
+ this.#activeItemId = undefined;
953
+ const blockOrder = [...this.#blocks.values()]
954
+ .sort(compareBlockOrder)
955
+ .map(state => state.key);
956
+ if (!incomplete)
957
+ projectNativeOutput(output, blockOrder);
958
+ const usage = parseUsage(response.usage);
959
+ if (!incomplete && !this.#hasVisibleOutput) {
960
+ throw new CodexDirectResponsesError('Codex private Responses returned no visible output', 'empty-response');
961
+ }
962
+ if (usage !== undefined)
963
+ chunks.push({ type: 'usage', usage });
964
+ if (incomplete) {
965
+ chunks.push({ type: 'finish', reason: { kind: 'max-tokens' } });
966
+ return chunks;
967
+ }
968
+ const replay = {
969
+ kind: 'codex-private-responses',
970
+ version: 3,
971
+ provider: this.#options.provider,
972
+ model: this.#options.model,
973
+ responseId,
974
+ output,
975
+ blockOrder,
976
+ };
977
+ chunks.push({
978
+ type: 'finish',
979
+ reason: this.#callIds.size > 0 ? { kind: 'tool-calls' } : { kind: 'stop' },
980
+ replayState: { response: replay },
981
+ });
982
+ return chunks;
983
+ }
984
+ #finalizeItem(item, outputIndex, chunks, context) {
985
+ const type = requireBoundedString(item.type, 'output item type', MAX_PROVIDER_ID_BYTES);
986
+ validateOutputItem(item, 'completed output item');
987
+ if (context === 'completed-terminal' && item.status !== undefined && item.status !== 'completed') {
988
+ throw protocolError('Codex private Responses completed with an incomplete output item');
989
+ }
990
+ const itemState = this.#registerItem(item, outputIndex, type);
991
+ itemState.provisional = false;
992
+ const itemId = itemState.id;
993
+ switch (type) {
994
+ case 'message': {
995
+ if (!Array.isArray(item.content))
996
+ throw protocolError('Codex private Responses message content is invalid');
997
+ this.#validateTerminalParts(itemState, item.content, 'message');
998
+ item.content.forEach((value, contentIndex) => {
999
+ const part = requireRecord(value, 'message content part');
1000
+ if (part.type !== 'output_text' && part.type !== 'refusal') {
1001
+ throw protocolError('Codex private Responses returned an unsupported message content part');
1002
+ }
1003
+ const state = this.#ensureText(itemId, outputIndex, contentIndex, part.type, chunks, false);
1004
+ const text = requireString(part.type === 'refusal' ? part.refusal : part.text, 'message text');
1005
+ this.#finishText(state, text, chunks);
1006
+ });
1007
+ return itemState;
1008
+ }
1009
+ case 'reasoning': {
1010
+ if (item.encrypted_content !== undefined && item.encrypted_content !== null) {
1011
+ requireString(item.encrypted_content, 'encrypted reasoning');
1012
+ }
1013
+ if (item.summary === undefined) {
1014
+ if (itemState.streamedParts) {
1015
+ throw protocolError('Codex private Responses terminal reasoning omitted streamed summary parts');
1016
+ }
1017
+ return itemState;
1018
+ }
1019
+ if (!Array.isArray(item.summary))
1020
+ throw protocolError('Codex private Responses reasoning summary is invalid');
1021
+ this.#validateTerminalParts(itemState, item.summary, 'reasoning');
1022
+ item.summary.forEach((value, summaryIndex) => {
1023
+ const part = requireRecord(value, 'reasoning summary');
1024
+ if (part.type !== 'summary_text')
1025
+ throw protocolError('Codex private Responses returned an unsupported reasoning summary');
1026
+ const state = this.#ensureText(itemId, outputIndex, summaryIndex, 'summary_text', chunks, false);
1027
+ this.#finishText(state, requireString(part.text, 'reasoning summary text'), chunks);
1028
+ });
1029
+ return itemState;
1030
+ }
1031
+ case 'function_call': {
1032
+ const argumentsValue = requireString(item.arguments, 'function arguments');
1033
+ const state = this.#ensureTool(item, itemState, chunks);
1034
+ if (context === 'max-tokens-terminal') {
1035
+ this.#finishTool(state, argumentsValue, chunks);
1036
+ return itemState;
1037
+ }
1038
+ if (item.status !== undefined && item.status !== 'completed') {
1039
+ throw protocolError('Codex private Responses returned an incomplete function call');
1040
+ }
1041
+ if (context === 'stream-item') {
1042
+ this.#reconcileToolArguments(state, argumentsValue, chunks);
1043
+ state.argumentsDone = true;
1044
+ return itemState;
1045
+ }
1046
+ this.#finishTool(state, argumentsValue, chunks);
1047
+ return itemState;
1048
+ }
1049
+ default:
1050
+ throw protocolError('Codex private Responses returned an unsupported output item');
1051
+ }
1052
+ }
1053
+ #registerItem(item, outputIndex, type) {
1054
+ const providerId = optionalBoundedString(item.id, 'output item id', MAX_PROVIDER_ID_BYTES);
1055
+ const indexedKey = this.#outputIndexes.get(outputIndex);
1056
+ const providerKey = providerId === undefined ? undefined : this.#providerItems.get(providerId);
1057
+ if (indexedKey !== undefined && providerKey !== undefined && indexedKey !== providerKey) {
1058
+ throw protocolError('Codex private Responses changed an output item identity');
1059
+ }
1060
+ const existingKey = indexedKey ?? providerKey;
1061
+ const existing = existingKey === undefined ? undefined : this.#items.get(existingKey);
1062
+ if (existing !== undefined) {
1063
+ if (existing.outputIndex !== outputIndex || existing.type !== type) {
1064
+ throw protocolError('Codex private Responses changed an output item identity');
1065
+ }
1066
+ if (providerId !== undefined) {
1067
+ if (existing.providerId !== undefined && existing.providerId !== providerId) {
1068
+ throw protocolError('Codex private Responses changed an output item identity');
1069
+ }
1070
+ existing.providerId = providerId;
1071
+ this.#providerItems.set(providerId, existing.id);
1072
+ }
1073
+ return existing;
1074
+ }
1075
+ if (outputIndex !== this.#outputIndexes.size) {
1076
+ throw protocolError('Codex private Responses registered output items out of order');
1077
+ }
1078
+ const itemId = `@output:${outputIndex}`;
1079
+ if (this.#items.has(itemId))
1080
+ throw protocolError('Codex private Responses repeated an output item id');
1081
+ const state = {
1082
+ id: itemId,
1083
+ ...(providerId === undefined ? {} : { providerId }),
1084
+ outputIndex,
1085
+ type,
1086
+ parts: new Map(),
1087
+ addedParts: new Set(),
1088
+ streamedParts: false,
1089
+ provisional: false,
1090
+ };
1091
+ this.#items.set(itemId, state);
1092
+ if (providerId !== undefined)
1093
+ this.#providerItems.set(providerId, itemId);
1094
+ this.#outputIndexes.set(outputIndex, itemId);
1095
+ return state;
1096
+ }
1097
+ #ensureText(itemId, outputIndex, partIndex, nativeType, chunks, fromStream, added = false) {
1098
+ const kind = nativeType === 'summary_text' ? 'reasoning' : 'text';
1099
+ const item = this.#items.get(itemId);
1100
+ const expectedItemType = kind === 'reasoning' ? 'reasoning' : 'message';
1101
+ if (item === undefined || item.type !== expectedItemType || item.outputIndex !== outputIndex) {
1102
+ throw protocolError('Codex private Responses emitted content for an unknown or incompatible output item');
1103
+ }
1104
+ if (fromStream) {
1105
+ const registeredType = item.parts.get(partIndex);
1106
+ if (registeredType !== undefined && registeredType !== nativeType) {
1107
+ throw protocolError('Codex private Responses changed a content part type');
1108
+ }
1109
+ if (added && item.addedParts.has(partIndex)) {
1110
+ throw protocolError('Codex private Responses repeated a content part index');
1111
+ }
1112
+ if (registeredType === undefined && partIndex !== item.parts.size) {
1113
+ throw protocolError('Codex private Responses registered content parts out of order');
1114
+ }
1115
+ item.parts.set(partIndex, nativeType);
1116
+ if (added)
1117
+ item.addedParts.add(partIndex);
1118
+ item.streamedParts = true;
1119
+ }
1120
+ const key = `${kind}:${itemId}:${partIndex}`;
1121
+ const existing = this.#blocks.get(key);
1122
+ if (existing !== undefined) {
1123
+ if (existing.kind === 'tool-call' || existing.kind !== kind || existing.nativeType !== nativeType) {
1124
+ throw protocolError('Codex private Responses changed a content part type');
1125
+ }
1126
+ return existing;
1127
+ }
1128
+ if (fromStream && outputIndex !== this.#outputIndexes.size - 1) {
1129
+ throw protocolError('Codex private Responses registered visible content out of order');
1130
+ }
1131
+ if (!fromStream && [...this.#blocks.values()].some(block => block.outputIndex > outputIndex)) {
1132
+ throw protocolError('Codex private Responses synthesized visible content out of order');
1133
+ }
1134
+ const state = {
1135
+ key,
1136
+ kind,
1137
+ index: this.#nextIndex,
1138
+ itemId,
1139
+ outputIndex,
1140
+ partIndex,
1141
+ nativeType,
1142
+ text: '',
1143
+ closed: false,
1144
+ };
1145
+ this.#nextIndex += 1;
1146
+ this.#blocks.set(key, state);
1147
+ chunks.push({ type: 'block-start', index: state.index, blockType: kind });
1148
+ return state;
1149
+ }
1150
+ #validateTerminalParts(item, values, kind) {
1151
+ if (!item.streamedParts)
1152
+ return;
1153
+ if (values.length !== item.parts.size) {
1154
+ throw protocolError(`Codex private Responses terminal ${kind} parts do not cover streamed part indexes`);
1155
+ }
1156
+ values.forEach((value, partIndex) => {
1157
+ const part = requireRecord(value, `${kind} content part`);
1158
+ const nativeType = kind === 'reasoning' ? 'summary_text' : part.type;
1159
+ if (item.parts.get(partIndex) !== nativeType) {
1160
+ throw protocolError(`Codex private Responses terminal ${kind} changed a streamed part type`);
1161
+ }
1162
+ });
1163
+ }
1164
+ #finishText(state, finalText, chunks) {
1165
+ if (state.closed) {
1166
+ if (state.text !== finalText)
1167
+ throw protocolError('Codex private Responses changed completed text');
1168
+ return;
1169
+ }
1170
+ if (state.text.length === 0 && finalText.length > 0) {
1171
+ chunks.push(state.kind === 'text'
1172
+ ? { type: 'text-delta', index: state.index, text: finalText }
1173
+ : { type: 'reasoning-delta', index: state.index, text: finalText });
1174
+ state.text = finalText;
1175
+ }
1176
+ else if (state.text !== finalText) {
1177
+ throw protocolError('Codex private Responses text deltas disagree with completed text');
1178
+ }
1179
+ state.closed = true;
1180
+ if (state.text.length > 0)
1181
+ this.#hasVisibleOutput = true;
1182
+ chunks.push({
1183
+ type: 'block-end',
1184
+ index: state.index,
1185
+ block: state.kind === 'text'
1186
+ ? { type: 'text', text: state.text }
1187
+ : { type: 'reasoning', text: state.text },
1188
+ });
1189
+ }
1190
+ #appendText(state, value, chunks) {
1191
+ if (state.closed)
1192
+ throw protocolError('Codex private Responses emitted text after closing its content part');
1193
+ state.text += value;
1194
+ if (value.length === 0)
1195
+ return;
1196
+ chunks.push(state.kind === 'text'
1197
+ ? { type: 'text-delta', index: state.index, text: value }
1198
+ : { type: 'reasoning-delta', index: state.index, text: value });
1199
+ }
1200
+ #ensureTool(item, itemState, chunks) {
1201
+ const itemId = itemState.id;
1202
+ const outputIndex = itemState.outputIndex;
1203
+ const callId = requireBoundedString(item.call_id, 'function call id', MAX_CALL_ID_BYTES);
1204
+ const name = requireBoundedString(item.name, 'function name', MAX_TOOL_NAME_BYTES);
1205
+ if (!this.#toolNames.has(name))
1206
+ throw protocolError('Codex private Responses requested an unknown tool');
1207
+ const key = `tool:${itemId}`;
1208
+ const existing = this.#blocks.get(key);
1209
+ if (existing !== undefined) {
1210
+ if (existing.kind !== 'tool-call' || existing.callId !== callId || existing.name !== name) {
1211
+ throw protocolError('Codex private Responses changed a function call identity');
1212
+ }
1213
+ return existing;
1214
+ }
1215
+ const duplicate = this.#callIds.get(callId);
1216
+ if (duplicate !== undefined && duplicate !== itemId) {
1217
+ throw protocolError('Codex private Responses repeated a function call id');
1218
+ }
1219
+ const initialArguments = item.arguments === undefined ? '' : requireString(item.arguments, 'function arguments');
1220
+ const state = {
1221
+ key,
1222
+ kind: 'tool-call',
1223
+ index: this.#nextIndex,
1224
+ itemId,
1225
+ outputIndex,
1226
+ callId,
1227
+ name,
1228
+ arguments: initialArguments,
1229
+ argumentsDone: false,
1230
+ closed: false,
1231
+ };
1232
+ this.#nextIndex += 1;
1233
+ this.#hasVisibleOutput = true;
1234
+ this.#blocks.set(key, state);
1235
+ this.#callIds.set(callId, itemState.id);
1236
+ chunks.push({ type: 'block-start', index: state.index, blockType: 'tool-call' }, {
1237
+ type: 'tool-call-delta',
1238
+ index: state.index,
1239
+ id: ToolCallId(callId),
1240
+ name,
1241
+ argumentsDelta: initialArguments,
1242
+ });
1243
+ return state;
1244
+ }
1245
+ #toolForItem(itemId, outputIndex) {
1246
+ const state = this.#blocks.get(`tool:${itemId}`);
1247
+ if (state?.kind !== 'tool-call' || state.outputIndex !== outputIndex) {
1248
+ throw protocolError('Codex private Responses emitted function arguments before the function item');
1249
+ }
1250
+ return state;
1251
+ }
1252
+ #finishTool(state, finalArguments, chunks) {
1253
+ if (state.closed) {
1254
+ if (state.arguments !== finalArguments)
1255
+ throw protocolError('Codex private Responses changed completed function arguments');
1256
+ return;
1257
+ }
1258
+ this.#reconcileToolArguments(state, finalArguments, chunks);
1259
+ state.argumentsDone = true;
1260
+ state.closed = true;
1261
+ chunks.push({
1262
+ type: 'block-end',
1263
+ index: state.index,
1264
+ block: {
1265
+ type: 'tool-call',
1266
+ id: ToolCallId(state.callId),
1267
+ name: state.name,
1268
+ arguments: state.arguments,
1269
+ },
1270
+ });
1271
+ }
1272
+ #reconcileToolArguments(state, finalArguments, chunks) {
1273
+ if (state.arguments.length === 0 && finalArguments.length > 0) {
1274
+ chunks.push({
1275
+ type: 'tool-call-delta',
1276
+ index: state.index,
1277
+ id: ToolCallId(state.callId),
1278
+ argumentsDelta: finalArguments,
1279
+ });
1280
+ state.arguments = finalArguments;
1281
+ }
1282
+ else if (state.arguments !== finalArguments) {
1283
+ throw protocolError('Codex private Responses argument deltas disagree with completed arguments');
1284
+ }
1285
+ }
1286
+ }
1287
+ function compareBlockOrder(left, right) {
1288
+ return left.outputIndex - right.outputIndex || blockPartIndex(left) - blockPartIndex(right);
1289
+ }
1290
+ function blockPartIndex(state) {
1291
+ return state.kind === 'tool-call' ? 0 : state.partIndex;
1292
+ }
1293
+ function validateOutputItem(item, label, allowInProgress = false) {
1294
+ const type = requireBoundedString(item.type, `${label} type`, MAX_PROVIDER_ID_BYTES);
1295
+ if (type !== 'message' && type !== 'reasoning' && type !== 'function_call') {
1296
+ throw protocolError(`Codex private Responses ${label} type is unsupported`);
1297
+ }
1298
+ if (item.status !== undefined
1299
+ && item.status !== 'completed'
1300
+ && item.status !== 'incomplete'
1301
+ && !(allowInProgress && item.status === 'in_progress')) {
1302
+ throw protocolError(`Codex private Responses ${label} status is unsupported`);
1303
+ }
1304
+ if (type === 'message' && item.role !== 'assistant') {
1305
+ throw protocolError(`Codex private Responses ${label} role is unsupported`);
1306
+ }
1307
+ }
1308
+ function projectNativeOutput(output, blockOrder) {
1309
+ const blocksByKey = new Map();
1310
+ const legacyAliases = new Map();
1311
+ let hiddenReasoning = false;
1312
+ const callIds = new Set();
1313
+ for (const [outputIndex, value] of output.entries()) {
1314
+ const item = requireRecord(value, 'replay output item');
1315
+ validateOutputItem(item, 'replay output item');
1316
+ const providerId = optionalBoundedString(item.id, 'replay output item id', MAX_PROVIDER_ID_BYTES);
1317
+ const itemId = `@output:${outputIndex}`;
1318
+ switch (item.type) {
1319
+ case 'message': {
1320
+ if (!Array.isArray(item.content))
1321
+ throw protocolError('Replay message content is invalid');
1322
+ for (const [contentIndex, value] of item.content.entries()) {
1323
+ const part = requireRecord(value, 'replay message content');
1324
+ if (part.type === 'output_text') {
1325
+ blocksByKey.set(`text:${itemId}:${contentIndex}`, {
1326
+ type: 'text', text: requireString(part.text, 'replay output text'),
1327
+ });
1328
+ if (providerId !== undefined) {
1329
+ legacyAliases.set(`text:${providerId}:${contentIndex}`, `text:${itemId}:${contentIndex}`);
1330
+ }
1331
+ }
1332
+ else if (part.type === 'refusal') {
1333
+ blocksByKey.set(`text:${itemId}:${contentIndex}`, {
1334
+ type: 'text', text: requireString(part.refusal, 'replay refusal'),
1335
+ });
1336
+ if (providerId !== undefined) {
1337
+ legacyAliases.set(`text:${providerId}:${contentIndex}`, `text:${itemId}:${contentIndex}`);
1338
+ }
1339
+ }
1340
+ else {
1341
+ throw protocolError('Replay message content type is unsupported');
1342
+ }
1343
+ }
1344
+ break;
1345
+ }
1346
+ case 'reasoning': {
1347
+ if (item.encrypted_content !== undefined && item.encrypted_content !== null) {
1348
+ requireString(item.encrypted_content, 'replay encrypted reasoning');
1349
+ hiddenReasoning = true;
1350
+ }
1351
+ if (item.summary === undefined)
1352
+ break;
1353
+ if (!Array.isArray(item.summary))
1354
+ throw protocolError('Replay reasoning summary is invalid');
1355
+ for (const [summaryIndex, value] of item.summary.entries()) {
1356
+ const part = requireRecord(value, 'replay reasoning summary');
1357
+ if (part.type !== 'summary_text')
1358
+ throw protocolError('Replay reasoning summary type is unsupported');
1359
+ blocksByKey.set(`reasoning:${itemId}:${summaryIndex}`, {
1360
+ type: 'reasoning', text: requireString(part.text, 'replay reasoning summary text'),
1361
+ });
1362
+ if (providerId !== undefined) {
1363
+ legacyAliases.set(`reasoning:${providerId}:${summaryIndex}`, `reasoning:${itemId}:${summaryIndex}`);
1364
+ }
1365
+ }
1366
+ break;
1367
+ }
1368
+ case 'function_call': {
1369
+ const callId = requireBoundedString(item.call_id, 'replay function call id', MAX_CALL_ID_BYTES);
1370
+ if (callIds.has(callId))
1371
+ throw protocolError('Replay repeated a function call id');
1372
+ callIds.add(callId);
1373
+ blocksByKey.set(`tool:${itemId}`, {
1374
+ type: 'tool-call',
1375
+ id: ToolCallId(callId),
1376
+ name: requireBoundedString(item.name, 'replay function name', MAX_TOOL_NAME_BYTES),
1377
+ arguments: requireString(item.arguments, 'replay function arguments'),
1378
+ });
1379
+ if (providerId !== undefined)
1380
+ legacyAliases.set(`tool:${providerId}`, `tool:${itemId}`);
1381
+ break;
1382
+ }
1383
+ default:
1384
+ throw protocolError('Replay output item type is unsupported');
1385
+ }
1386
+ }
1387
+ if (blockOrder.length !== blocksByKey.size)
1388
+ throw protocolError('Replay block order is incomplete');
1389
+ const seen = new Set();
1390
+ const blocks = blockOrder.map(value => {
1391
+ const suppliedKey = requireBoundedString(value, 'replay block key', MAX_PROVIDER_ID_BYTES * 2);
1392
+ const key = legacyAliases.get(suppliedKey) ?? suppliedKey;
1393
+ if (seen.has(key))
1394
+ throw protocolError('Replay block order contains a duplicate key');
1395
+ seen.add(key);
1396
+ const block = blocksByKey.get(key);
1397
+ if (block === undefined)
1398
+ throw protocolError('Replay block order references an unknown key');
1399
+ return block;
1400
+ });
1401
+ return { blocks, hiddenReasoning };
1402
+ }
1403
+ function contentEquals(left, right) {
1404
+ if (left.length !== right.length)
1405
+ return false;
1406
+ return left.every((block, index) => {
1407
+ const candidate = right[index];
1408
+ if (candidate === undefined || candidate.type !== block.type)
1409
+ return false;
1410
+ switch (block.type) {
1411
+ case 'text':
1412
+ case 'reasoning':
1413
+ return candidate.type === block.type && candidate.text === block.text;
1414
+ case 'tool-call':
1415
+ return candidate.type === 'tool-call'
1416
+ && candidate.id === block.id
1417
+ && candidate.name === block.name
1418
+ && candidate.arguments === block.arguments;
1419
+ case 'image':
1420
+ return candidate.type === 'image' && sameImageRef(candidate.attachment, block.attachment);
1421
+ default:
1422
+ return false;
1423
+ }
1424
+ });
1425
+ }
1426
+ async function* parseSse(response, signal, maxResponseBytes, maxEventBytes) {
1427
+ const reader = response.body?.getReader();
1428
+ if (reader === undefined)
1429
+ throw protocolError('Codex private Responses returned an empty SSE body');
1430
+ const decoder = new TextDecoder('utf-8', { fatal: true });
1431
+ let buffer = '';
1432
+ let dataLines = [];
1433
+ let eventBytes = 0;
1434
+ let totalBytes = 0;
1435
+ let naturalEof = false;
1436
+ const dispatch = () => {
1437
+ if (dataLines.length === 0)
1438
+ return undefined;
1439
+ const data = dataLines.join('\n');
1440
+ dataLines = [];
1441
+ eventBytes = 0;
1442
+ if (data === '[DONE]')
1443
+ return '[DONE]';
1444
+ try {
1445
+ return JSON.parse(data);
1446
+ }
1447
+ catch {
1448
+ throw protocolError('Codex private Responses emitted invalid SSE JSON');
1449
+ }
1450
+ };
1451
+ const consumeLine = (rawLine) => {
1452
+ const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
1453
+ if (line === '')
1454
+ return dispatch();
1455
+ if (line.startsWith(':'))
1456
+ return undefined;
1457
+ const separator = line.indexOf(':');
1458
+ const field = separator === -1 ? line : line.slice(0, separator);
1459
+ let value = separator === -1 ? '' : line.slice(separator + 1);
1460
+ if (value.startsWith(' '))
1461
+ value = value.slice(1);
1462
+ if (field !== 'data')
1463
+ return undefined;
1464
+ eventBytes += Buffer.byteLength(value, 'utf8') + (dataLines.length === 0 ? 0 : 1);
1465
+ if (eventBytes > maxEventBytes)
1466
+ throw protocolError('Codex private Responses SSE event exceeded its safety limit');
1467
+ dataLines.push(value);
1468
+ return undefined;
1469
+ };
1470
+ try {
1471
+ while (true) {
1472
+ throwIfAborted(signal);
1473
+ const part = await waitForAbort(reader.read(), signal);
1474
+ if (part.done)
1475
+ break;
1476
+ totalBytes += part.value.byteLength;
1477
+ if (totalBytes > maxResponseBytes)
1478
+ throw protocolError('Codex private Responses stream exceeded its safety limit');
1479
+ try {
1480
+ buffer += decoder.decode(part.value, { stream: true });
1481
+ }
1482
+ catch {
1483
+ throw protocolError('Codex private Responses SSE was not valid UTF-8');
1484
+ }
1485
+ const payloads = [];
1486
+ let doneParsed = false;
1487
+ let newline = buffer.indexOf('\n');
1488
+ while (newline !== -1) {
1489
+ const rawLine = buffer.slice(0, newline);
1490
+ const normalizedLine = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
1491
+ if (doneParsed && normalizedLine !== '') {
1492
+ throw protocolError('Codex private Responses emitted data after DONE');
1493
+ }
1494
+ const payload = consumeLine(rawLine);
1495
+ buffer = buffer.slice(newline + 1);
1496
+ if (payload !== undefined)
1497
+ payloads.push(payload);
1498
+ if (payload === '[DONE]')
1499
+ doneParsed = true;
1500
+ newline = buffer.indexOf('\n');
1501
+ }
1502
+ const doneIndex = payloads.indexOf('[DONE]');
1503
+ if (doneIndex !== -1) {
1504
+ if (payloads.lastIndexOf('[DONE]') !== doneIndex) {
1505
+ throw protocolError('Codex private Responses emitted a duplicate DONE marker');
1506
+ }
1507
+ if (doneIndex !== payloads.length - 1) {
1508
+ throw protocolError('Codex private Responses emitted data after DONE');
1509
+ }
1510
+ if (buffer.length > 0 || dataLines.length > 0) {
1511
+ throw protocolError('Codex private Responses emitted data after DONE');
1512
+ }
1513
+ }
1514
+ const terminalIndexes = payloads.flatMap((payload, index) => {
1515
+ if (!isRecord(payload) || !isTerminalEvent(payload.type))
1516
+ return [];
1517
+ return [index];
1518
+ });
1519
+ if (terminalIndexes.length > 1) {
1520
+ throw protocolError('Codex private Responses emitted a duplicate terminal event');
1521
+ }
1522
+ const terminalIndex = terminalIndexes[0];
1523
+ if (terminalIndex !== undefined) {
1524
+ const trailing = payloads.slice(terminalIndex + 1);
1525
+ if (trailing.length > 1 || (trailing.length === 1 && trailing[0] !== '[DONE]')) {
1526
+ throw protocolError('Codex private Responses emitted data after its terminal event');
1527
+ }
1528
+ if (buffer.length > 0 || dataLines.length > 0) {
1529
+ throw protocolError('Codex private Responses emitted data after its terminal event');
1530
+ }
1531
+ }
1532
+ for (const payload of payloads)
1533
+ yield payload;
1534
+ if (Buffer.byteLength(buffer, 'utf8') + eventBytes > maxEventBytes) {
1535
+ throw protocolError('Codex private Responses SSE line exceeded its safety limit');
1536
+ }
1537
+ }
1538
+ try {
1539
+ buffer += decoder.decode();
1540
+ }
1541
+ catch {
1542
+ throw protocolError('Codex private Responses SSE ended with invalid UTF-8');
1543
+ }
1544
+ if (buffer.length > 0 || dataLines.length > 0) {
1545
+ throw protocolError('Codex private Responses SSE ended with an unterminated event');
1546
+ }
1547
+ naturalEof = true;
1548
+ }
1549
+ finally {
1550
+ if (!naturalEof)
1551
+ cancelReader(reader);
1552
+ try {
1553
+ reader.releaseLock();
1554
+ }
1555
+ catch {
1556
+ // Cancellation is best effort; prompt completion and the original failure win.
1557
+ }
1558
+ }
1559
+ }
1560
+ function parseUsage(value) {
1561
+ if (value === undefined || value === null)
1562
+ return undefined;
1563
+ const usage = requireRecord(value, 'usage');
1564
+ const inputTokens = requireTokenCount(usage.input_tokens, 'input token count');
1565
+ const outputTokens = requireTokenCount(usage.output_tokens, 'output token count');
1566
+ const inputDetails = usage.input_tokens_details === undefined || usage.input_tokens_details === null
1567
+ ? {}
1568
+ : requireRecord(usage.input_tokens_details, 'input token details');
1569
+ const outputDetails = usage.output_tokens_details === undefined || usage.output_tokens_details === null
1570
+ ? {}
1571
+ : requireRecord(usage.output_tokens_details, 'output token details');
1572
+ const cacheReadTokens = optionalTokenCount(inputDetails.cached_tokens, 'cache read token count') ?? 0;
1573
+ const cacheWriteTokens = optionalTokenCount(inputDetails.cache_write_tokens, 'cache write token count') ?? 0;
1574
+ const reasoningTokens = optionalTokenCount(outputDetails.reasoning_tokens, 'reasoning token count');
1575
+ if (cacheReadTokens + cacheWriteTokens > inputTokens) {
1576
+ throw protocolError('Codex private Responses usage cache tokens exceed input tokens');
1577
+ }
1578
+ if (reasoningTokens !== undefined && reasoningTokens > outputTokens) {
1579
+ throw protocolError('Codex private Responses reasoning tokens exceed output tokens');
1580
+ }
1581
+ if (usage.total_tokens !== undefined
1582
+ && requireTokenCount(usage.total_tokens, 'total token count') !== inputTokens + outputTokens) {
1583
+ throw protocolError('Codex private Responses total token count is inconsistent');
1584
+ }
1585
+ return {
1586
+ inputTokens: inputTokens - cacheReadTokens - cacheWriteTokens,
1587
+ outputTokens,
1588
+ ...(cacheReadTokens === 0 ? {} : { cacheReadTokens }),
1589
+ ...(cacheWriteTokens === 0 ? {} : { cacheWriteTokens }),
1590
+ ...(reasoningTokens === undefined ? {} : { reasoningTokens }),
1591
+ };
1592
+ }
1593
+ function validateToolSchemas(options) {
1594
+ const names = new Set();
1595
+ for (const tool of options.tools ?? []) {
1596
+ const name = requireBoundedString(tool.name, 'tool name', MAX_TOOL_NAME_BYTES);
1597
+ if (names.has(name))
1598
+ throw protocolError('Codex private Responses received duplicate tool schemas');
1599
+ names.add(name);
1600
+ if (!isLosslessJson(tool.parameters))
1601
+ throw protocolError('Codex private Responses received invalid tool parameters');
1602
+ }
1603
+ return names;
1604
+ }
1605
+ function resolveLimits(dependencies) {
1606
+ return {
1607
+ maxRequestBytes: positiveLimit(dependencies.maxRequestBytes, DEFAULT_MAX_REQUEST_BYTES, 'request'),
1608
+ maxRequestImageBytes: positiveLimit(dependencies.maxRequestImageBytes, DEFAULT_MAX_REQUEST_IMAGE_BYTES, 'image request'),
1609
+ maxResponseBytes: positiveLimit(dependencies.maxResponseBytes, DEFAULT_MAX_RESPONSE_BYTES, 'response'),
1610
+ maxSseEventBytes: positiveLimit(dependencies.maxSseEventBytes, DEFAULT_MAX_SSE_EVENT_BYTES, 'SSE event'),
1611
+ };
1612
+ }
1613
+ function positiveLimit(value, fallback, label) {
1614
+ const resolved = value ?? fallback;
1615
+ if (!Number.isSafeInteger(resolved) || resolved <= 0)
1616
+ throw protocolError(`Codex private Responses ${label} limit is invalid`);
1617
+ return resolved;
1618
+ }
1619
+ function requireIndex(value, label) {
1620
+ if (!Number.isSafeInteger(value) || value < 0)
1621
+ throw protocolError(`Codex private Responses ${label} is invalid`);
1622
+ return value;
1623
+ }
1624
+ function optionalIndex(value, label) {
1625
+ return value === undefined ? undefined : requireIndex(value, label);
1626
+ }
1627
+ function optionalBoundedString(value, label, maxBytes) {
1628
+ return value === undefined ? undefined : requireBoundedString(value, label, maxBytes);
1629
+ }
1630
+ function hasRichPartIdentity(event) {
1631
+ return event.item_id !== undefined || event.output_index !== undefined || event.content_index !== undefined;
1632
+ }
1633
+ function requireTokenCount(value, label) {
1634
+ if (!Number.isSafeInteger(value) || value < 0)
1635
+ throw protocolError(`Codex private Responses ${label} is invalid`);
1636
+ return value;
1637
+ }
1638
+ function optionalTokenCount(value, label) {
1639
+ return value === undefined ? undefined : requireTokenCount(value, label);
1640
+ }
1641
+ function requireString(value, label) {
1642
+ if (typeof value !== 'string')
1643
+ throw protocolError(`Codex private Responses ${label} is invalid`);
1644
+ return value;
1645
+ }
1646
+ function requireBoundedString(value, label, maxBytes) {
1647
+ if (!isBoundedString(value, maxBytes))
1648
+ throw protocolError(`Codex private Responses ${label} is invalid`);
1649
+ return value;
1650
+ }
1651
+ function isBoundedString(value, maxBytes) {
1652
+ return typeof value === 'string' && value.length > 0 && Buffer.byteLength(value, 'utf8') <= maxBytes;
1653
+ }
1654
+ function requireRecord(value, label) {
1655
+ if (!isRecord(value))
1656
+ throw protocolError(`Codex private Responses ${label} is invalid`);
1657
+ return value;
1658
+ }
1659
+ function isRecord(value) {
1660
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
1661
+ }
1662
+ function isLosslessJson(value, depth = 0, seen = new Set()) {
1663
+ if (value === null || typeof value === 'string' || typeof value === 'boolean')
1664
+ return true;
1665
+ if (typeof value === 'number')
1666
+ return Number.isFinite(value);
1667
+ if (depth >= MAX_JSON_DEPTH || typeof value !== 'object')
1668
+ return false;
1669
+ if (seen.has(value))
1670
+ return false;
1671
+ seen.add(value);
1672
+ const valid = Array.isArray(value)
1673
+ ? value.every(item => isLosslessJson(item, depth + 1, seen))
1674
+ : Object.getPrototypeOf(value) === Object.prototype
1675
+ && Object.values(value).every(item => isLosslessJson(item, depth + 1, seen));
1676
+ seen.delete(value);
1677
+ return valid;
1678
+ }
1679
+ function jsonEquals(left, right) {
1680
+ if (Object.is(left, right))
1681
+ return true;
1682
+ if (Array.isArray(left) || Array.isArray(right)) {
1683
+ return Array.isArray(left)
1684
+ && Array.isArray(right)
1685
+ && left.length === right.length
1686
+ && left.every((value, index) => jsonEquals(value, right[index]));
1687
+ }
1688
+ if (!isRecord(left) || !isRecord(right))
1689
+ return false;
1690
+ const keys = Object.keys(left);
1691
+ return keys.length === Object.keys(right).length
1692
+ && keys.every(key => Object.hasOwn(right, key) && jsonEquals(left[key], right[key]));
1693
+ }
1694
+ function isTerminalEvent(type) {
1695
+ return type === 'response.completed';
1696
+ }
1697
+ function isOfficialPrivateNoopEvent(type) {
1698
+ return type === 'response.queued'
1699
+ || type === 'codex.response.metadata'
1700
+ || type === 'response.content_part.added'
1701
+ || type === 'response.content_part.done'
1702
+ || type === 'response.custom_tool_call_input.done'
1703
+ || type === 'response.function_call_arguments.delta'
1704
+ || type === 'response.function_call_arguments.done'
1705
+ || type === 'response.in_progress'
1706
+ || type === 'response.metadata'
1707
+ || type === 'response.output_text.done'
1708
+ || type === 'response.output_text.annotation.added'
1709
+ || type === 'response.reasoning_summary_part.done'
1710
+ || type === 'responsesapi.websocket_timing';
1711
+ }
1712
+ function cancelBody(body) {
1713
+ if (body === null)
1714
+ return;
1715
+ try {
1716
+ void body.cancel().catch(() => { });
1717
+ }
1718
+ catch {
1719
+ // Cancellation is best effort; never delay or replace the classified outcome.
1720
+ }
1721
+ }
1722
+ function cancelReader(reader) {
1723
+ try {
1724
+ void reader.cancel().catch(() => { });
1725
+ }
1726
+ catch {
1727
+ // Cancellation is best effort; never delay or replace the classified outcome.
1728
+ }
1729
+ }
1730
+ function throwIfAborted(signal) {
1731
+ if (signal?.aborted !== true)
1732
+ return;
1733
+ if (signal.reason instanceof Error)
1734
+ throw signal.reason;
1735
+ throw new Error('Codex private Responses request was aborted', { cause: 'abort' });
1736
+ }
1737
+ function combineSignals(request, lifecycle) {
1738
+ if (request === undefined)
1739
+ return lifecycle ?? new AbortController().signal;
1740
+ if (lifecycle === undefined || lifecycle === request)
1741
+ return request;
1742
+ return AbortSignal.any([request, lifecycle]);
1743
+ }
1744
+ function waitForAbort(promise, signal) {
1745
+ if (signal.aborted)
1746
+ return Promise.reject(abortReason(signal));
1747
+ return new Promise((resolve, reject) => {
1748
+ const aborted = () => reject(abortReason(signal));
1749
+ signal.addEventListener('abort', aborted, { once: true });
1750
+ promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', aborted)).catch(() => { });
1751
+ });
1752
+ }
1753
+ function abortReason(signal) {
1754
+ return signal.reason ?? new Error('Codex private Responses request was aborted', { cause: 'abort' });
1755
+ }
1756
+ function protocolError(message) {
1757
+ return new CodexDirectResponsesError(message, 'protocol');
1758
+ }
1759
+ //# sourceMappingURL=codex-direct-responses.js.map