codex-copilot-dx 0.9.28 → 0.9.30

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.
package/src/launcher.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { spawn } from "node:child_process";
1
+ import { spawn, execFileSync } from "node:child_process";
2
2
  import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { installedWindowsPredictionApp, windowsPredictionAppProcesses } from "./native-prediction-windows.mjs";
@@ -39,8 +39,30 @@ export function launchAttempts() {
39
39
  return [["-b", CODEX_BUNDLE_ID], ...APP_PATH_CANDIDATES.map((path) => [path])];
40
40
  }
41
41
 
42
+ export function macPredictionAppProcesses(app, { exec = execFileSync } = {}) {
43
+ if (!APP_PATH_CANDIDATES.includes(app)) throw new Error("Unknown macOS prediction App");
44
+ const options = { encoding: "utf8", timeout: 2000, maxBuffer: 1024 * 1024 };
45
+ const listing = exec("/bin/ps", ["-axo", "pid=,comm="], options);
46
+ const rows = [];
47
+ for (const line of listing.split("\n")) {
48
+ const match = line.match(/^\s*(\d+)\s+(.+?)\s*$/);
49
+ if (!match || ![`${app}/Contents/MacOS/ChatGPT`, `${app}/Contents/MacOS/Codex`].includes(match[2])) continue;
50
+ const pid = Number(match[1]);
51
+ try {
52
+ const args = exec("/bin/ps", ["-p", String(pid), "-o", "args="], options);
53
+ const route = args.match(/(?:^|\s)--proxy-pac-url=(?:"(http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac)"|(http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac)(?=\s|$))/);
54
+ const readable = args.trim() === match[2] || args.trimStart().startsWith(`${match[2]} `);
55
+ const uniqueRoute = (args.match(/(?:^|\s)--proxy-pac-url=/g) || []).length === 1;
56
+ rows.push({ pid, readable, route: readable && uniqueRoute ? route?.[1] || route?.[2] || null : null });
57
+ } catch { rows.push({ pid, readable: false, route: null }); }
58
+ if (rows.length === 2) break;
59
+ }
60
+ return rows;
61
+ }
62
+
42
63
  export async function openCodex({ env = process.env, spawnImpl = spawn, platform = process.platform, predictionPacUrl = null, predictionApp = null, predictionProfile = null,
43
- resolveWindowsApp = installedWindowsPredictionApp, windowsAppProcesses = windowsPredictionAppProcesses } = {}) {
64
+ resolveWindowsApp = installedWindowsPredictionApp, windowsAppProcesses = windowsPredictionAppProcesses,
65
+ macAppProcesses = macPredictionAppProcesses } = {}) {
44
66
  if (platform === "win32" && autoLaunchEnabled(env) && typeof predictionPacUrl === "string"
45
67
  && /^http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac$/.test(predictionPacUrl)
46
68
  && typeof predictionApp === "string" && path.win32.isAbsolute(predictionApp)) {
@@ -99,7 +121,33 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
99
121
  const extraArgs = typeof predictionPacUrl === "string" && /^http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac$/.test(predictionPacUrl)
100
122
  && APP_PATH_CANDIDATES.includes(predictionApp)
101
123
  ? ["--args", `--proxy-pac-url=${predictionPacUrl}`] : [];
102
- const attempts = extraArgs.length ? [[predictionApp]] : launchAttempts();
124
+ if (extraArgs.length) {
125
+ try {
126
+ const running = macAppProcesses(predictionApp);
127
+ if (running.length) {
128
+ if (running.length === 1 && running[0].readable && running[0].route === predictionPacUrl) {
129
+ console.log(status("ok", "Running Codex App uses the current prediction route"));return true;
130
+ }
131
+ throw new Error("Running Codex App uses an old or unverified prediction route. Fully quit the App, then run ccdx again; no process was stopped");
132
+ }
133
+ if (!await tryOpen([predictionApp, ...extraArgs], { spawnImpl })) {
134
+ console.log(status("warn", "Could not launch the verified macOS Codex App"));return false;
135
+ }
136
+ for (let attempt = 0; attempt < 10; attempt++) {
137
+ const actual = macAppProcesses(predictionApp);
138
+ if (actual.length === 1 && actual[0].readable && actual[0].route === predictionPacUrl) {
139
+ console.log(status("info", "Codex launch route verified; prediction status will show when configuration traffic is observed"));return true;
140
+ }
141
+ if (actual.length) break;
142
+ if (attempt < 9) await new Promise(resolve => setTimeout(resolve, 100));
143
+ }
144
+ console.log(status("warn", "Codex launch requested, but the active App did not retain the current prediction route. Core adapter remains available"));
145
+ return false;
146
+ } catch (error) {
147
+ console.log(status("warn", `Optional macOS prediction launch skipped: ${error.message}`));return false;
148
+ }
149
+ }
150
+ const attempts = launchAttempts();
103
151
  for (const attempt of attempts) {
104
152
  const args = [...attempt, ...extraArgs];
105
153
  if (await tryOpen(args, { spawnImpl })) {
@@ -2,6 +2,7 @@ import os from "node:os";
2
2
  import { validateGithubToken } from "./auth.mjs";
3
3
  import { AUTH_PROFILE_CODEX, readAuthProfileCredentials } from "./auth-profile.mjs";
4
4
  import { buildHeaders, FALLBACK_VSCODE_VERSION, parseApiBase } from "./copilot.mjs";
5
+ import { MAX_UPSTREAM_ERROR_BODY_BYTES, MAX_UPSTREAM_MODEL_CATALOG_BYTES, readBoundedResponseText } from "./upstream-body.mjs";
5
6
 
6
7
  const DEFAULT_MODELS_TIMEOUT_MS = 10000;
7
8
  const SUPPORTED_ENDPOINTS = [
@@ -59,14 +60,6 @@ function validationFailure(validation) {
59
60
  return `GitHub Copilot authentication failed: ${validation?.reason || "unknown error"}${httpStatus}`;
60
61
  }
61
62
 
62
- async function responseText(response) {
63
- try {
64
- return await response.text();
65
- } catch {
66
- return "";
67
- }
68
- }
69
-
70
63
  function readModelCredentials(home) {
71
64
  let credentials;
72
65
  try {
@@ -110,7 +103,11 @@ export async function fetchLiveCopilotModels({
110
103
  redirect: "error",
111
104
  signal: controller.signal,
112
105
  });
113
- const body = await responseText(response);
106
+ const body = await readBoundedResponseText(response, {
107
+ maxBytes: response.ok ? MAX_UPSTREAM_MODEL_CATALOG_BYTES : MAX_UPSTREAM_ERROR_BODY_BYTES,
108
+ label: "Copilot live model catalog",
109
+ signal: controller.signal,
110
+ });
114
111
  if (!response.ok) {
115
112
  const detail = safeText(body).slice(0, 240);
116
113
  throw new Error(`Copilot models endpoint returned HTTP ${response.status}${detail ? `: ${detail}` : ""}`);
@@ -146,9 +146,9 @@ export async function startNativePrediction({ env = process.env, platform = proc
146
146
  if (!["darwin", "win32"].includes(platform)) throw new Error("Native predictions were skipped: unsupported platform");
147
147
  const network = predictionNetworkOptions(opts);
148
148
  let networkRoute = network.networkRoute;
149
- if (platform === "win32" && settings.bridgePort !== undefined
149
+ if (settings.bridgePort !== undefined
150
150
  && (!Number.isInteger(settings.bridgePort) || settings.bridgePort < 1024 || settings.bridgePort > 65535)) {
151
- throw new Error("Saved Windows prediction bridge port is invalid; no route was replaced");
151
+ throw new Error("Saved prediction bridge port is invalid; no route was replaced");
152
152
  }
153
153
  if (!predictionAppMatches(settings.app)) throw new Error("Codex App changed; run ccdx prediction on after quitting it to recheck compatibility");
154
154
  const paths = predictionPaths({ ...opts, app: settings.app });
@@ -183,7 +183,7 @@ export async function startNativePrediction({ env = process.env, platform = proc
183
183
  }
184
184
  }
185
185
  transport = await startPredictionTransport({ ...certificate, enabled: () => enabled,
186
- listenPort: platform === "win32" ? settings.bridgePort || 0 : 0,
186
+ listenPort: settings.bridgePort || 0,
187
187
  networkRoute, agent: networkRoute?.https ? createProxyAgent(networkRoute) : undefined,
188
188
  ...(windowsNetwork ? { requestImpl: windowsNetwork.requestImpl, pacImpl: windowsNetwork.pac } : {}),
189
189
  onEvent: (event) => state?.event(event),
@@ -196,7 +196,7 @@ export async function startNativePrediction({ env = process.env, platform = proc
196
196
  return result.changed ? JSON.parse(result.body) : parsed;
197
197
  },
198
198
  });
199
- if (platform === "win32" && settings.bridgePort === undefined) {
199
+ if (settings.bridgePort === undefined) {
200
200
  await withFileLock(`${paths.settings}.lock`, () => {
201
201
  const current = readPredictionSettings(opts);
202
202
  if (!current.enabled || current.certificateHash !== settings.certificateHash || current.store !== settings.store
@@ -206,10 +206,16 @@ export async function startNativePrediction({ env = process.env, platform = proc
206
206
  writePredictionSettings({ ...current, bridgePort: transport.port }, opts);
207
207
  }, { timeoutMs: 2000 });
208
208
  }
209
- } catch (error) { clearInterval(timer);await transport?.close();windowsNetwork?.close();throw error; }
209
+ } catch (error) {
210
+ clearInterval(timer);await transport?.close();windowsNetwork?.close();
211
+ if (error.code === "EADDRINUSE" && settings.bridgePort !== undefined) {
212
+ error.message = `Saved prediction port ${settings.bridgePort} is already in use; it was not replaced. Native predictions are unavailable; the core adapter remains available`;
213
+ }
214
+ throw error;
215
+ }
210
216
  state?.running(windowsNetwork ? { source: "system", type: "auto", bypass_rules: null, proxy_credentials: false } : networkRouteSnapshot(networkRoute));
211
217
  warning("Native prediction bridge enabled; only the two configuration hosts use its App-only route.");
212
- warning("If Codex is already running, quit it and run ccdx again to apply the route.");
218
+ warning("If Codex uses a different or missing prediction route, fully quit it and run ccdx again.");
213
219
  return {
214
220
  app: settings.app.app,
215
221
  ...(platform === "win32" ? { profile: paths.profile } : {}),
@@ -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
  };
@@ -582,6 +582,7 @@ export async function proxyCopilotResponses(reqContext, req, res, upstream = cop
582
582
  markResponseTerminal("completed", { model: response.model || reqContext.body?.model, origin: "upstream_response" });
583
583
  res.writeHead(resp.status, safeUpstreamResponseHeaders(resp.headers, {
584
584
  contentType: "application/json",
585
+ allowReasoningIncluded: true,
585
586
  }));
586
587
  res.end(JSON.stringify(response));
587
588
  return { successful: true, compacted: true };
@@ -636,6 +637,7 @@ export async function proxyCopilotResponses(reqContext, req, res, upstream = cop
636
637
  }
637
638
  res.writeHead(resp.status, safeUpstreamResponseHeaders(resp.headers, {
638
639
  contentType: "application/json",
640
+ allowReasoningIncluded: response.status !== "failed",
639
641
  }));
640
642
  res.end(data);
641
643
  return { successful: response.status !== "failed" && response.status !== "incomplete", compacted: false };
@@ -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) {