codex-copilot-dx 0.9.27 → 0.9.29

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.
@@ -0,0 +1,246 @@
1
+ import fs from "node:fs/promises";
2
+ import { constants } from "node:fs";
3
+ import path from "node:path";
4
+ import { createHash } from "node:crypto";
5
+ import { createZstdDecompress } from "node:zlib";
6
+ import { codexPaths } from "./codex-paths.mjs";
7
+ import { isLoopbackAddress, isLoopbackHostHeader, isLanAllowed } from "./security.mjs";
8
+ import { decodedBodyLimitPreference } from "./user-settings.mjs";
9
+ import { isResponsesToolOutputItem, readResponsesToolOutputParts } from "./responses-content.mjs";
10
+ import { prepareResponsesRequest } from "./responses-request.mjs";
11
+
12
+ const UUID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
13
+ const CALLS = new Map([["function_call", "function_call_output"], ["custom_tool_call", "custom_tool_call_output"]]);
14
+
15
+ function unavailable(code) {
16
+ return Object.assign(new Error("Verified local plaintext history is unavailable"), { code });
17
+ }
18
+
19
+ function threadId(request, body) {
20
+ const metadata = body?.client_metadata;
21
+ const primary = [request.headers?.["thread-id"], request.headers?.["x-codex-thread-id"], metadata?.thread_id];
22
+ const values = primary.filter(value => value !== undefined);
23
+ if (!values.length) values.push(metadata?.session_id ?? request.headers?.["session-id"] ?? body?.prompt_cache_key);
24
+ if (values.some(value => typeof value !== "string" || !UUID.test(value))) throw unavailable("thread_binding_missing");
25
+ const ids = new Set(values.map(value => value.toLowerCase()));
26
+ if (ids.size !== 1) throw unavailable("thread_binding_conflict");
27
+ return [...ids][0];
28
+ }
29
+
30
+ function opaque(value) {
31
+ if (Array.isArray(value)) return value.some(opaque);
32
+ if (!value || typeof value !== "object") return false;
33
+ return Object.hasOwn(value, "encrypted_content") || value.type === "encrypted_content" || Object.values(value).some(opaque);
34
+ }
35
+
36
+ function plaintext(item) {
37
+ if (!item || typeof item !== "object" || typeof item.type !== "string") throw unavailable("unsupported_rollout_item");
38
+ if (["reasoning", "compaction"].includes(item.type)) return null;
39
+ const out = structuredClone(item);
40
+ for (const key of Object.keys(out)) if (key === "id" || key.startsWith("internal_")) delete out[key];
41
+ // This field is replay metadata, not a replacement for a visible item. Never
42
+ // omit opaque content parts or invent plaintext for an encrypted tool result.
43
+ if ((out.type === "message" && out.content?.length) || (isResponsesToolOutputItem(out) && out.output !== undefined)) {
44
+ delete out.encrypted_content;
45
+ }
46
+ if (opaque(out) || (isResponsesToolOutputItem(out) && opaque(readResponsesToolOutputParts(out)?.parts))) {
47
+ throw unavailable("plaintext_content_missing");
48
+ }
49
+ return out;
50
+ }
51
+
52
+ function fingerprint(item) {
53
+ const normalized = { ...item };
54
+ delete normalized.id;delete normalized.status;
55
+ if (item.type === "message" && Array.isArray(item.content)) normalized.content = item.content.map(part => {
56
+ if (!["input_text", "output_text"].includes(part?.type)) return part;
57
+ const text = { ...part };delete text.annotations;return text;
58
+ });
59
+ return createHash("sha256").update(JSON.stringify(normalized, (_key, value) => {
60
+ if (value && typeof value === "object" && !Array.isArray(value)) {
61
+ return Object.fromEntries(Object.keys(value).sort().map(name => [name, value[name]]));
62
+ }
63
+ return value;
64
+ })).digest("hex");
65
+ }
66
+
67
+ async function candidateFiles(directory, id, check) {
68
+ const found = [];
69
+ let entries = 0;
70
+ async function walk(parent, depth) {
71
+ check();
72
+ const stat = await fs.lstat(parent);
73
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw unavailable("unsafe_rollout_path");
74
+ const iterator = await fs.opendir(parent);
75
+ for await (const entry of iterator) {
76
+ check();
77
+ if (++entries > 4096) throw unavailable("rollout_lookup_limit");
78
+ const file = path.join(parent, entry.name);
79
+ if (entry.isDirectory() && depth < 3) await walk(file, depth + 1);
80
+ else if (entry.isFile() && /^rollout-.*\.jsonl(?:\.zst)?$/.test(entry.name) && entry.name.toLowerCase().includes(id)) {
81
+ if (found.length >= 16) throw unavailable("rollout_lookup_limit");
82
+ found.push(file);
83
+ }
84
+ }
85
+ }
86
+ for (const name of ["sessions", "archived_sessions"]) {
87
+ try { await walk(path.join(directory, name), 0); }
88
+ catch (error) { if (error.code !== "ENOENT") throw error; }
89
+ }
90
+ return found;
91
+ }
92
+
93
+ async function readPrefix(file, directory, id, ciphertext, budget, check, signal) {
94
+ const real = await fs.realpath(file);
95
+ if (!real.startsWith(directory + path.sep)) throw unavailable("unsafe_rollout_path");
96
+ const before = await fs.lstat(file);
97
+ if (!before.isFile() || before.isSymbolicLink()) throw unavailable("unsafe_rollout_path");
98
+ if (!before.size) throw unavailable("incomplete_rollout");
99
+ const handle = await fs.open(file, constants.O_RDONLY | (process.platform === "win32" ? 0 : constants.O_NOFOLLOW || 0));
100
+ let stream, raw;
101
+ try {
102
+ const stat = await handle.stat();
103
+ // Older Windows libuv reports the device number differently for lstat and
104
+ // fstat. The validated path, file ID and snapshot size remain mandatory.
105
+ if (!stat.isFile() || stat.ino !== before.ino || stat.size !== before.size
106
+ || (process.platform !== "win32" && stat.dev !== before.dev)) throw unavailable("rollout_changed");
107
+ raw = handle.createReadStream({ autoClose: false, end: stat.size - 1, highWaterMark: 64 * 1024, signal });
108
+ stream = file.endsWith(".zst") ? raw.pipe(createZstdDecompress()) : raw;
109
+ if (stream !== raw) raw.on("error", error => stream.destroy(error));
110
+ const items = [];
111
+ let metadata = false, matched = false, parts = [], length = 0, bytesRead = 0;
112
+ const record = bytes => {
113
+ check();
114
+ const line = bytes.toString("utf8").replace(/^\uFEFF/, "").trim();
115
+ if (!line) return;
116
+ let row;
117
+ try { row = JSON.parse(line); } catch { throw unavailable("invalid_rollout"); }
118
+ const value = row.payload;
119
+ if (!metadata) {
120
+ if (row.type !== "session_meta" || value?.id?.toLowerCase() !== id) throw unavailable("rollout_identity_mismatch");
121
+ if (value.history_base || value.forked_from_id || (row.ordinal !== undefined && row.ordinal !== 0)
122
+ || (value.history_mode && !["full", "paginated"].includes(value.history_mode))) throw unavailable("incomplete_rollout");
123
+ metadata = true;return;
124
+ }
125
+ if (row.type === "session_meta" || (row.type === "event_msg" && /rollback|rolled_back|rewind|history_reset|context_reset/.test(value?.type || ""))) {
126
+ throw unavailable("unsupported_history_change");
127
+ }
128
+ if (row.type === "compacted" || row.type === "response_item") {
129
+ const candidates = row.type === "compacted" ? value?.replacement_history : [value];
130
+ if (Array.isArray(candidates) && candidates.some(item => item?.type === "compaction" && item.encrypted_content === ciphertext)) {
131
+ matched = true;return;
132
+ }
133
+ }
134
+ if (row.type === "response_item") {
135
+ const item = plaintext(value);
136
+ if (item) items.push(item);
137
+ }
138
+ };
139
+ for await (const chunk of stream) {
140
+ check();budget.remaining -= chunk.length;bytesRead += chunk.length;
141
+ if (budget.remaining < 0) throw unavailable("rollout_read_limit");
142
+ let start = 0;
143
+ while (start < chunk.length) {
144
+ const end = chunk.indexOf(10, start);
145
+ const part = chunk.subarray(start, end < 0 ? chunk.length : end);
146
+ parts.push(part);length += part.length;
147
+ if (end < 0) break;
148
+ record(Buffer.concat(parts, length));parts = [];length = 0;
149
+ if (matched) return { items, bytes: bytesRead };
150
+ start = end + 1;
151
+ }
152
+ }
153
+ if (length) record(Buffer.concat(parts, length));
154
+ return matched ? { items, bytes: bytesRead } : null;
155
+ } finally {
156
+ stream?.destroy();raw?.destroy();await handle.close();
157
+ }
158
+ }
159
+
160
+ function joinHistory(source, input, compactionIndex, check) {
161
+ if (!source.length || !source.some(item => item.type === "message" && item.role === "user")) throw unavailable("incomplete_rollout");
162
+ const signatures = source.map(fingerprint);
163
+ let cursor = 0;
164
+ const instructions = [];
165
+ for (const original of input.slice(0, compactionIndex)) {
166
+ check();
167
+ const item = plaintext(original);
168
+ if (!item) continue;
169
+ const match = signatures.indexOf(fingerprint(item), cursor);
170
+ if (match >= 0) cursor = match + 1;
171
+ else if (item.type === "message" && ["system", "developer"].includes(item.role)) instructions.push(item);
172
+ else throw unavailable("retained_prefix_mismatch");
173
+ }
174
+ const suffix = input.slice(compactionIndex + 1).map(plaintext).filter(Boolean);
175
+ const items = [...source, ...instructions, ...suffix];
176
+ const calls = new Map();
177
+ for (const item of items) {
178
+ check();
179
+ if (CALLS.has(item.type)) {
180
+ if (!item.call_id || calls.has(item.call_id)) throw unavailable("invalid_tool_pairs");
181
+ calls.set(item.call_id, { type: CALLS.get(item.type), completed: false });
182
+ } else if ([...CALLS.values()].includes(item.type)) {
183
+ const call = calls.get(item.call_id);
184
+ if (!call || call.type !== item.type || call.completed) throw unavailable("invalid_tool_pairs");
185
+ call.completed = true;
186
+ }
187
+ }
188
+ if ([...calls.values()].some(call => !call.completed)) throw unavailable("invalid_tool_pairs");
189
+ return { items, currentInputStart: source.length + instructions.length };
190
+ }
191
+
192
+ // Loaded only after a confirmed provider ownership rejection, never on startup
193
+ // or healthy requests. It cannot serve remote/browser callers or mutate logs.
194
+ export async function recoverLocalCompaction(reqContext, { request, env = process.env,
195
+ signal, assertActive, reserveHistory, maxBytes, timeoutMs = 5000 } = {}) {
196
+ const started = Date.now();
197
+ const check = () => {
198
+ assertActive?.();
199
+ if (signal?.aborted) throw signal.reason || new DOMException("Aborted", "AbortError");
200
+ if (Date.now() - started > timeoutMs) throw unavailable("rollout_read_timeout");
201
+ };
202
+ check();
203
+ if (isLanAllowed(env) || !isLoopbackAddress(request?.socket?.remoteAddress)
204
+ || !isLoopbackHostHeader(request?.headers?.host) || request?.headers?.origin !== undefined) {
205
+ throw unavailable("local_request_required");
206
+ }
207
+ const id = threadId(request, reqContext.body);
208
+ const input = reqContext.body?.input;
209
+ const compactions = Array.isArray(input) ? input.filter(item => item?.type === "compaction" && item.encrypted_content) : [];
210
+ if (compactions.length !== 1) throw unavailable("multiple_compactions");
211
+ if (typeof compactions[0].encrypted_content !== "string") throw unavailable("invalid_compaction");
212
+ const limit = maxBytes ?? decodedBodyLimitPreference({ env }).bytes;
213
+ let release, transferred = false;
214
+ try {
215
+ release = await reserveHistory?.(limit, { signal });
216
+ check();
217
+ const directory = await fs.realpath(codexPaths({ env }).directory);
218
+ const files = await candidateFiles(directory, id, check);
219
+ const budget = { remaining: limit };
220
+ let source;
221
+ for (const file of files) {
222
+ check();
223
+ const candidate = await readPrefix(file, directory, id, compactions[0].encrypted_content, budget, check, signal);
224
+ if (!candidate) continue;
225
+ if (source) throw unavailable("ambiguous_rollout");
226
+ source = candidate;
227
+ }
228
+ if (!source) throw unavailable("matching_rollout_missing");
229
+ const restored = joinHistory(source.items, input, input.indexOf(compactions[0]), check);
230
+ const body = { ...reqContext.body, input: restored.items };
231
+ delete body.previous_response_id;
232
+ const bodyBytes = Buffer.byteLength(JSON.stringify(body));
233
+ if (bodyBytes > limit) throw unavailable("restored_payload_limit");
234
+ release?.resize?.(bodyBytes);
235
+ const currentItems = new Set(body.input.slice(restored.currentInputStart));
236
+ const prepared = prepareResponsesRequest(body, { mutate: true, copilotBoundary: false, assertActive: check });
237
+ const currentInputStart = prepared.body.input.findIndex(item => currentItems.has(item));
238
+ prepared.currentInputStart = currentInputStart < 0 ? prepared.body.input.length : currentInputStart;
239
+ prepared.surface = reqContext.surface;
240
+ prepared.routePlan = reqContext.routePlan;
241
+ transferred = true;
242
+ return { reqContext: prepared, releasePreparation: release, recovery: { source: "local_codex_rollout", restored_items: restored.items.length,
243
+ compaction_items_removed: 1, reasoning_items_removed: input.filter(item => item?.type === "reasoning").length,
244
+ source_bytes: source.bytes } };
245
+ } finally { if (!transferred) release?.(); }
246
+ }
@@ -3,6 +3,7 @@ import { applyCopilotResponsesRequestPolicies } from "./copilot-responses-policy
3
3
  import {
4
4
  createRequestAbort,
5
5
  logRequestFailure,
6
+ MAX_DECODED_BODY_BYTES,
6
7
  MAX_UPSTREAM_CHAT_SUCCESS_BODY_BYTES,
7
8
  MAX_UPSTREAM_ERROR_BODY_BYTES,
8
9
  readJsonBody,
@@ -189,7 +190,7 @@ export function createResponsesHandler(options) {
189
190
  }
190
191
  }
191
192
  assertPrepareActive();
192
- return { historySnapshot: retrySnapshot, release };
193
+ return { historySnapshot: retrySnapshot, reserveHistory: releaseRetryRequest.reserveResponseHistory, release };
193
194
  } catch (error) {
194
195
  release();
195
196
  throw error;
@@ -308,6 +309,12 @@ export function createResponsesHandler(options) {
308
309
  if (prepared.historyParentId === null) releaseHistorySnapshot();
309
310
  applyCopilotResponsesRequestPolicies(prepared.body);
310
311
  if (routePlan.protocol === "openai-responses") {
312
+ const restorePlaintextHistory = async (context, { reserveHistory } = {}) => {
313
+ assertPrepareActive();
314
+ const { recoverLocalCompaction } = await import("./local-compaction-recovery.mjs");
315
+ return recoverLocalCompaction(context, { request: req, env: openAIModelEnv,
316
+ signal: abort.signal, assertActive: assertPrepareActive, reserveHistory, maxBytes: MAX_DECODED_BODY_BYTES });
317
+ };
311
318
  const result = await proxyCopilotResponses(prepared, req, res, responsesFn, {
312
319
  acquireRetryPreparation,
313
320
  assertPrepareActive,
@@ -317,6 +324,8 @@ export function createResponsesHandler(options) {
317
324
  onStreamStart: startStream,
318
325
  releaseRequest: releaseUpstreamPayload,
319
326
  responseFailures,
327
+ restorePlaintextHistory,
328
+ reserveHistory: releaseRequest.reserveResponseHistory,
320
329
  streamIdleTimeoutMs,
321
330
  keepaliveIntervalMs,
322
331
  });
@@ -11,7 +11,7 @@ import { httpError } from "./http-errors.mjs";
11
11
  import {
12
12
  hasCopilotResponseRetryPolicy,
13
13
  openCopilotResponse,
14
- selectCopilotResponseRetry,
14
+ selectCopilotResponseRetryWithHistory,
15
15
  } from "./copilot-responses-compat.mjs";
16
16
  import {
17
17
  dropMaterializedResponseHistory,
@@ -328,7 +328,7 @@ function storeCompletedResponse(reqContext, completed) {
328
328
 
329
329
  function streamHeaders(resp) {
330
330
  return {
331
- ...safeUpstreamResponseHeaders(resp.headers, { defaultContentType: "text/event-stream" }),
331
+ ...safeUpstreamResponseHeaders(resp.headers, { defaultContentType: "text/event-stream", allowReasoningIncluded: resp.ok }),
332
332
  "Cache-Control": "no-cache",
333
333
  Connection: "keep-alive",
334
334
  };
@@ -345,11 +345,13 @@ async function selectStreamFailureRetry(reqContext, failure, usedRetryPolicies,
345
345
  assertActive: options.assertPrepareActive,
346
346
  historySnapshot: preparation?.historySnapshot,
347
347
  });
348
- const retry = selectCopilotResponseRetry(restored, 400, errorText, usedRetryPolicies);
348
+ const retry = await selectCopilotResponseRetryWithHistory(restored, 400, errorText, usedRetryPolicies, {
349
+ ...options, reserveHistory: preparation?.reserveHistory || options.reserveHistory,
350
+ });
349
351
  options.assertPrepareActive?.();
350
352
  keepReservation = Boolean(retry);
351
353
  return {
352
- retry: retry ? { ...retry, releasePreparation: preparation?.release } : null,
354
+ retry: retry ? { ...retry, releasePreparation: () => { retry.releasePreparation?.();preparation?.release(); } } : null,
353
355
  retrySkipped: null,
354
356
  };
355
357
  } catch (error) {
@@ -580,6 +582,7 @@ export async function proxyCopilotResponses(reqContext, req, res, upstream = cop
580
582
  markResponseTerminal("completed", { model: response.model || reqContext.body?.model, origin: "upstream_response" });
581
583
  res.writeHead(resp.status, safeUpstreamResponseHeaders(resp.headers, {
582
584
  contentType: "application/json",
585
+ allowReasoningIncluded: true,
583
586
  }));
584
587
  res.end(JSON.stringify(response));
585
588
  return { successful: true, compacted: true };
@@ -634,6 +637,7 @@ export async function proxyCopilotResponses(reqContext, req, res, upstream = cop
634
637
  }
635
638
  res.writeHead(resp.status, safeUpstreamResponseHeaders(resp.headers, {
636
639
  contentType: "application/json",
640
+ allowReasoningIncluded: response.status !== "failed",
637
641
  }));
638
642
  res.end(data);
639
643
  return { successful: response.status !== "failed" && response.status !== "incomplete", compacted: false };
@@ -200,7 +200,7 @@ export function sanitizeConnectionOwnedReasoningRequest(reqContext) {
200
200
  const compactions = input.filter(item => item?.type === "compaction" && item.encrypted_content);
201
201
  const reasoning = input.filter(item => item?.type === "reasoning" && item.encrypted_content);
202
202
  if (compactions.length) {
203
- const message = "Saved encrypted compaction is unavailable on this connection. Restore the full plaintext conversation history before retrying; CCDX has preserved it and will not discard earlier context.";
203
+ const message = "The request contains encrypted compaction and upstream rejected saved state. Verified local recovery was unavailable; restore the full plaintext conversation history before retrying. CCDX has not modified the original history.";
204
204
  throw Object.assign(new Error(message), { statusCode: 400, code: "ccdx_history_rebuild_required",
205
205
  jsonBody: { error: { type: "invalid_request_error", code: "ccdx_history_rebuild_required", message,
206
206
  recoverable: true, recovery: { action: "restore_plaintext_history", compaction_items: compactions.length, reasoning_items: reasoning.length } } } });
@@ -0,0 +1,137 @@
1
+ import { httpError } from "./http-errors.mjs";
2
+
3
+ export const MAX_UPSTREAM_ERROR_BODY_BYTES = 1024 * 1024;
4
+ export const MAX_UPSTREAM_MODEL_CATALOG_BYTES = 8 * 1024 * 1024;
5
+ export const MAX_UPSTREAM_RETRY_DRAIN_BYTES = 64 * 1024;
6
+
7
+ function upstreamBodyTooLarge(label, maxBytes) {
8
+ const error = httpError(`${label} exceeds ${maxBytes} bytes`, 502);
9
+ error.code = "ccdx_upstream_response_too_large";
10
+ error.jsonBody = {
11
+ error: {
12
+ message: error.message,
13
+ type: "upstream_error",
14
+ code: error.code,
15
+ },
16
+ };
17
+ return error;
18
+ }
19
+
20
+ function unreadableUpstreamBody(label) {
21
+ const error = httpError(`${label} is not a readable web stream`, 502);
22
+ error.code = "ccdx_upstream_response_unreadable";
23
+ error.jsonBody = {
24
+ error: {
25
+ message: error.message,
26
+ type: "upstream_error",
27
+ code: error.code,
28
+ },
29
+ };
30
+ return error;
31
+ }
32
+
33
+ async function cancelResponseBody(response) {
34
+ try { await response?.body?.cancel?.(); } catch {}
35
+ }
36
+
37
+ function responseAbortError(signal) {
38
+ if (signal?.reason instanceof Error) return signal.reason;
39
+ const error = new Error("The operation was aborted");
40
+ error.name = "AbortError";
41
+ return error;
42
+ }
43
+
44
+ function readResponseChunk(reader, signal) {
45
+ if (!signal) return reader.read();
46
+ if (signal.aborted) return Promise.reject(responseAbortError(signal));
47
+ return new Promise((resolve, reject) => {
48
+ let settled = false;
49
+ const finish = (callback, value) => {
50
+ if (settled) return;
51
+ settled = true;
52
+ signal.removeEventListener("abort", onAbort);
53
+ callback(value);
54
+ };
55
+ const onAbort = () => {
56
+ const error = responseAbortError(signal);
57
+ try { Promise.resolve(reader.cancel(error)).catch(() => {}); } catch {}
58
+ finish(reject, error);
59
+ };
60
+ signal.addEventListener("abort", onAbort, { once: true });
61
+ reader.read().then(
62
+ (value) => finish(resolve, value),
63
+ (error) => finish(reject, error),
64
+ );
65
+ });
66
+ }
67
+
68
+ function responseContentLength(response) {
69
+ const raw = response?.headers?.get?.("content-length")
70
+ ?? response?.headers?.["content-length"]
71
+ ?? response?.headers?.["Content-Length"];
72
+ const parsed = Number.parseInt(raw || "", 10);
73
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : null;
74
+ }
75
+
76
+ export async function readBoundedResponseBuffer(response, {
77
+ maxBytes,
78
+ label = "Upstream response body",
79
+ signal,
80
+ } = {}) {
81
+ const limit = Number.isFinite(maxBytes) && maxBytes >= 0 ? Math.floor(maxBytes) : 0;
82
+ if (signal?.aborted) {
83
+ cancelResponseBody(response);
84
+ throw responseAbortError(signal);
85
+ }
86
+ if (responseContentLength(response) > limit) {
87
+ await cancelResponseBody(response);
88
+ throw upstreamBodyTooLarge(label, limit);
89
+ }
90
+ if (!response?.body) {
91
+ if (typeof response?.text === "function") {
92
+ const buffer = Buffer.from(await response.text());
93
+ if (buffer.length > limit) throw upstreamBodyTooLarge(label, limit);
94
+ return buffer;
95
+ }
96
+ if ((responseContentLength(response) || 0) > 0) throw unreadableUpstreamBody(label);
97
+ return Buffer.alloc(0);
98
+ }
99
+ const reader = response?.body?.getReader?.();
100
+ if (!reader) throw unreadableUpstreamBody(label);
101
+ const chunks = [];
102
+ let total = 0;
103
+ try {
104
+ while (true) {
105
+ const { done, value } = await readResponseChunk(reader, signal);
106
+ if (done) break;
107
+ const chunk = Buffer.from(value);
108
+ total += chunk.length;
109
+ if (total > limit) {
110
+ await reader.cancel().catch(() => {});
111
+ throw upstreamBodyTooLarge(label, limit);
112
+ }
113
+ chunks.push(chunk);
114
+ }
115
+ return Buffer.concat(chunks, total);
116
+ } finally {
117
+ try {
118
+ reader.releaseLock();
119
+ } catch (error) {
120
+ if (!signal?.aborted) throw error;
121
+ }
122
+ }
123
+ }
124
+
125
+ export async function readBoundedResponseText(response, options) {
126
+ return new TextDecoder().decode(await readBoundedResponseBuffer(response, options));
127
+ }
128
+
129
+ export async function discardBoundedResponseBody(response, maxBytes = MAX_UPSTREAM_RETRY_DRAIN_BYTES) {
130
+ try {
131
+ await readBoundedResponseBuffer(response, { maxBytes, label: "Upstream retry response body" });
132
+ return true;
133
+ } catch {
134
+ await cancelResponseBody(response);
135
+ return false;
136
+ }
137
+ }
@@ -41,12 +41,18 @@ function isSafeMetadataHeader(name) {
41
41
  export function safeUpstreamResponseHeaders(headers, {
42
42
  contentType,
43
43
  defaultContentType,
44
+ allowReasoningIncluded = false,
44
45
  } = {}) {
45
46
  const out = {};
46
47
  const resolvedContentType = contentType
47
48
  ?? headerValue(headers, "content-type")
48
49
  ?? defaultContentType;
49
50
  if (resolvedContentType) out["Content-Type"] = resolvedContentType;
51
+ // Codex treats presence as true, even for a literal "false" value.
52
+ // Native Responses callers opt in; never invent a declaration for other routes.
53
+ if (allowReasoningIncluded && headerValue(headers, "x-reasoning-included")?.trim().toLowerCase() === "true") {
54
+ out["X-Reasoning-Included"] = "true";
55
+ }
50
56
 
51
57
  if (headers && typeof headers[Symbol.iterator] === "function") {
52
58
  for (const [rawName, value] of headers) {