codex-copilot-dx 0.9.33 → 0.9.35

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
@@ -61,6 +61,7 @@ export function macPredictionAppProcesses(app, { exec = execFileSync } = {}) {
61
61
  }
62
62
 
63
63
  export async function openCodex({ env = process.env, spawnImpl = spawn, platform = process.platform, predictionPacUrl = null, predictionApp = null, predictionProfile = null,
64
+ preparePredictionRoute, persistedPredictionRoute = false, onPredictionRoute = () => {}, log = console.log,
64
65
  resolveWindowsApp = installedWindowsPredictionApp, windowsAppProcesses = windowsPredictionAppProcesses,
65
66
  macAppProcesses = macPredictionAppProcesses } = {}) {
66
67
  if (platform === "win32" && autoLaunchEnabled(env) && typeof predictionPacUrl === "string"
@@ -82,10 +83,14 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
82
83
  const running = windowsAppProcesses(current.app, { env });
83
84
  if (running.length) {
84
85
  if (running.length === 1 && running[0].readable && running[0].route === predictionPacUrl) {
85
- console.log(status("ok", "Running Codex App uses the current prediction route"));return true;
86
+ onPredictionRoute("verified");log(status("ok", "Running Codex App uses the current prediction route"));return true;
87
+ }
88
+ if (running.length === 1 && running[0].readable && !running[0].route && persistedPredictionRoute) {
89
+ onPredictionRoute("persisted");log(status("info", "App route preference is saved; waiting for configuration traffic to confirm it"));return true;
86
90
  }
87
91
  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");
88
92
  }
93
+ await preparePredictionRoute?.();
89
94
  const launched = await new Promise(resolve => {
90
95
  const child = spawnImpl(current.app, [`--user-data-dir=${predictionProfile}`, `--proxy-pac-url=${predictionPacUrl}`], {
91
96
  cwd: path.win32.dirname(current.app), env: { ...env, CODEX_ELECTRON_USER_DATA_PATH: predictionProfile },
@@ -94,27 +99,28 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
94
99
  child.once("error", () => resolve(false));
95
100
  child.once("spawn", () => { child.unref(); resolve(true); });
96
101
  });
97
- if (!launched) { console.log(status("warn", "Could not launch the registered Windows Codex App"));return false; }
102
+ if (!launched) { onPredictionRoute("unverified");log(status("warn", "Could not launch the registered Windows Codex App"));return false; }
98
103
  await new Promise(resolve => setTimeout(resolve, 300));
99
104
  const actual = windowsAppProcesses(current.app, { env });
100
105
  const routeRetained = actual.length === 1 && actual[0].readable && actual[0].route === predictionPacUrl;
101
- console.log(status(routeRetained ? "info" : "warn", routeRetained
106
+ onPredictionRoute(routeRetained ? "verified" : "unverified");
107
+ log(status(routeRetained ? "info" : "warn", routeRetained
102
108
  ? "Codex launch route verified; prediction status will show when configuration traffic is observed"
103
109
  : "Codex launch requested, but the active App did not retain the current prediction route. Core adapter remains available"));
104
110
  return routeRetained;
105
111
  } catch (error) {
106
- console.log(status("warn", `Optional Windows prediction launch skipped: ${error.message}`));
112
+ onPredictionRoute("unverified");log(status("warn", `Optional Windows prediction launch skipped: ${error.message}`));
107
113
  return false;
108
114
  }
109
115
  }
110
116
  if (platform !== "darwin") {
111
- console.log(status("warn", "Automatic launch requires macOS or an enabled Windows prediction setup"));
112
- console.log(status("info", "Open Codex App manually; it will connect to the adapter."));
117
+ log(status("warn", "Automatic launch requires macOS or an enabled Windows prediction setup"));
118
+ log(status("info", "Open Codex App manually; it will connect to the adapter."));
113
119
  return false;
114
120
  }
115
121
 
116
122
  if (!autoLaunchEnabled(env)) {
117
- console.log(status("info", "Auto-launch disabled (CCDX_AUTO_LAUNCH=0); open Codex App manually."));
123
+ log(status("info", "Auto-launch disabled (CCDX_AUTO_LAUNCH=0); open Codex App manually."));
118
124
  return false;
119
125
  }
120
126
 
@@ -126,38 +132,42 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
126
132
  const running = macAppProcesses(predictionApp);
127
133
  if (running.length) {
128
134
  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;
135
+ onPredictionRoute("verified");log(status("ok", "Running Codex App uses the current prediction route"));return true;
136
+ }
137
+ if (running.length === 1 && running[0].readable && !running[0].route && persistedPredictionRoute) {
138
+ onPredictionRoute("persisted");log(status("info", "App route preference is saved; waiting for configuration traffic to confirm it"));return true;
130
139
  }
131
140
  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
141
  }
142
+ await preparePredictionRoute?.();
133
143
  if (!await tryOpen([predictionApp, ...extraArgs], { spawnImpl })) {
134
- console.log(status("warn", "Could not launch the verified macOS Codex App"));return false;
144
+ onPredictionRoute("unverified");log(status("warn", "Could not launch the verified macOS Codex App"));return false;
135
145
  }
136
146
  for (let attempt = 0; attempt < 10; attempt++) {
137
147
  const actual = macAppProcesses(predictionApp);
138
148
  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;
149
+ onPredictionRoute("verified");log(status("info", "Codex launch route verified; prediction status will show when configuration traffic is observed"));return true;
140
150
  }
141
151
  if (actual.length) break;
142
152
  if (attempt < 9) await new Promise(resolve => setTimeout(resolve, 100));
143
153
  }
144
- console.log(status("warn", "Codex launch requested, but the active App did not retain the current prediction route. Core adapter remains available"));
154
+ onPredictionRoute("unverified");log(status("warn", "Codex launch requested, but the active App did not retain the current prediction route. Core adapter remains available"));
145
155
  return false;
146
156
  } catch (error) {
147
- console.log(status("warn", `Optional macOS prediction launch skipped: ${error.message}`));return false;
157
+ onPredictionRoute("unverified");log(status("warn", `Optional macOS prediction launch skipped: ${error.message}`));return false;
148
158
  }
149
159
  }
150
160
  const attempts = launchAttempts();
151
161
  for (const attempt of attempts) {
152
162
  const args = [...attempt, ...extraArgs];
153
163
  if (await tryOpen(args, { spawnImpl })) {
154
- console.log(status("ok", "Codex app launched"));
164
+ log(status("ok", "Codex app launched"));
155
165
  return true;
156
166
  }
157
167
  }
158
168
 
159
- console.log(status("warn", "Could not launch the Codex app (checked com.openai.codex, Codex.app, ChatGPT.app)"));
160
- console.log(status("info", "Open Codex App manually; it will connect to the adapter."));
161
- console.log(status("info", "Download it from https://openai.com/codex"));
169
+ log(status("warn", "Could not launch the Codex app (checked com.openai.codex, Codex.app, ChatGPT.app)"));
170
+ log(status("info", "Open Codex App manually; it will connect to the adapter."));
171
+ log(status("info", "Download it from https://openai.com/codex"));
162
172
  return false;
163
173
  }
@@ -8,9 +8,14 @@ import { isLoopbackAddress, isLoopbackHostHeader, isLanAllowed } from "./securit
8
8
  import { decodedBodyLimitPreference } from "./user-settings.mjs";
9
9
  import { isResponsesToolOutputItem, readResponsesToolOutputParts } from "./responses-content.mjs";
10
10
  import { prepareResponsesRequest } from "./responses-request.mjs";
11
+ import { createAbortAwareSingleflight } from "./bounded-result-cache.mjs";
11
12
 
12
13
  const UUID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
13
14
  const CALLS = new Map([["function_call", "function_call_output"], ["custom_tool_call", "custom_tool_call_output"]]);
15
+ const sourceFlights = createAbortAwareSingleflight();
16
+ const sourceFailures = new Map();
17
+ const REUSABLE_FAILURES = new Set(["invalid_rollout", "incomplete_rollout", "rollout_identity_mismatch",
18
+ "plaintext_content_missing", "unsupported_rollout_item", "unsupported_history_change", "matching_rollout_missing", "ambiguous_rollout"]);
14
19
 
15
20
  function unavailable(code) {
16
21
  return Object.assign(new Error("Verified local plaintext history is unavailable"), { code });
@@ -189,6 +194,52 @@ function joinHistory(source, input, compactionIndex, check) {
189
194
  return { items, currentInputStart: source.length + instructions.length };
190
195
  }
191
196
 
197
+ async function sourceVersion(files) {
198
+ return JSON.stringify(await Promise.all(files.map(async file => {
199
+ const stat = await fs.lstat(file);
200
+ if (!stat.isFile() || stat.isSymbolicLink()) throw unavailable("unsafe_rollout_path");
201
+ return [file, stat.dev, stat.ino, stat.size, stat.mtimeMs, stat.ctimeMs];
202
+ })));
203
+ }
204
+
205
+ async function loadSource(directory, id, ciphertext, limit, timeoutMs, signal) {
206
+ const started = Date.now();
207
+ const check = () => {
208
+ if (signal.aborted) throw signal.reason;
209
+ if (Date.now() - started > timeoutMs) throw unavailable("rollout_read_timeout");
210
+ };
211
+ const files = await candidateFiles(directory, id, check);
212
+ const version = await sourceVersion(files);
213
+ // Cache only failure codes for exact file snapshots, never plaintext or a
214
+ // missing directory. Discovery still runs so added pages are not hidden.
215
+ const key = createHash("sha256").update(JSON.stringify([directory, id, ciphertext, limit, version])).digest("hex");
216
+ const cached = sourceFailures.get(key);
217
+ if (cached && cached.until > Date.now()) throw unavailable(cached.code);
218
+ sourceFailures.delete(key);
219
+ try {
220
+ let source;
221
+ const budget = { remaining: limit };
222
+ for (const file of files) {
223
+ check();
224
+ const candidate = await readPrefix(file, directory, id, ciphertext, budget, check, signal);
225
+ if (!candidate) continue;
226
+ if (source) throw unavailable("ambiguous_rollout");
227
+ source = candidate;
228
+ }
229
+ if (!source) throw unavailable("matching_rollout_missing");
230
+ if (await sourceVersion(files) !== version) throw unavailable("rollout_changed");
231
+ return source;
232
+ } catch (error) {
233
+ if (files.length && !signal.aborted && REUSABLE_FAILURES.has(error.code)
234
+ && await sourceVersion(files) === version) {
235
+ for (const [old, value] of sourceFailures) if (value.until <= Date.now()) sourceFailures.delete(old);
236
+ while (sourceFailures.size >= 32) sourceFailures.delete(sourceFailures.keys().next().value);
237
+ sourceFailures.set(key, { code: error.code, until: Date.now() + 2000 });
238
+ }
239
+ throw error;
240
+ }
241
+ }
242
+
192
243
  // Loaded only after a confirmed provider ownership rejection, never on startup
193
244
  // or healthy requests. It cannot serve remote/browser callers or mutate logs.
194
245
  export async function recoverLocalCompaction(reqContext, { request, env = process.env,
@@ -215,18 +266,11 @@ export async function recoverLocalCompaction(reqContext, { request, env = proces
215
266
  release = await reserveHistory?.(limit, { signal });
216
267
  check();
217
268
  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);
269
+ const ciphertext = compactions[0].encrypted_content;
270
+ const key = createHash("sha256").update(JSON.stringify([directory, id, ciphertext, limit, timeoutMs])).digest("hex");
271
+ const source = await sourceFlights.run(key, sharedSignal => loadSource(directory, id, ciphertext, limit, timeoutMs, sharedSignal), { signal });
272
+ check();
273
+ const restored = joinHistory(structuredClone(source.items), input, input.indexOf(compactions[0]), check);
230
274
  const body = { ...reqContext.body, input: restored.items };
231
275
  delete body.previous_response_id;
232
276
  const bodyBytes = Buffer.byteLength(JSON.stringify(body));
@@ -0,0 +1,39 @@
1
+ // Only the optional bridge is supervised. Model/image traffic, App processes,
2
+ // global proxy settings and certificate trust are never changed here.
3
+ export function supervisePrediction({ native, restart, state, warning = () => {},
4
+ intervalMs = 30_000, now = Date.now, setIntervalImpl = setInterval, clearIntervalImpl = clearInterval } = {}) {
5
+ let current = native, closed = false, flight = null, attempts = 0, retryAt = 0;
6
+ const delays = [30_000, 60_000, 120_000];
7
+ async function check() {
8
+ if (closed || flight || !current || current.enabled?.() === false || attempts >= delays.length || now() < retryAt) return;
9
+ if (current.healthy()) { state?.checked();return; }
10
+ const attempt = ++attempts;
11
+ retryAt = now() + delays[attempt - 1];
12
+ state?.recovering(attempt);
13
+ flight = (async () => {
14
+ try {
15
+ await current.close();
16
+ if (closed) return;
17
+ const resumed = await restart();
18
+ if (closed) { await resumed?.close();return; }
19
+ if (!resumed || resumed.pacUrl !== native.pacUrl) {
20
+ await resumed?.close();throw new Error("Prediction recovery did not retain the original route");
21
+ }
22
+ current = resumed;state?.recovered();
23
+ warning("Prediction bridge recovered on its original port; App restart was not requested");
24
+ } catch (error) {
25
+ state?.unavailable(error);
26
+ warning(`Prediction bridge recovery ${attempt}/${delays.length} failed: ${error.message}. Core service remains available`);
27
+ }
28
+ })();
29
+ try { await flight; } finally { flight = null; }
30
+ }
31
+ const timer = setIntervalImpl(() => { void check().catch(error => state?.unavailable(error)); }, intervalMs);
32
+ timer.unref?.();
33
+ return {
34
+ ...native,
35
+ check,
36
+ prepareRoute() { return current.prepareRoute?.(); },
37
+ async close() { closed = true;clearIntervalImpl(timer);await flight;await current?.close(); },
38
+ };
39
+ }
@@ -0,0 +1,94 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { isDeepStrictEqual } from "node:util";
4
+ import { readBoundedFileSync } from "./bounded-file.mjs";
5
+ import { atomicWriteFileSync } from "./atomic-file.mjs";
6
+ import { withFileLock } from "./lock.mjs";
7
+
8
+ const validPac = value => typeof value === "string" && /^http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac$/.test(value)
9
+ && Number(new URL(value).port) >= 1024 && Number(new URL(value).port) <= 65535;
10
+ const object = value => value && typeof value === "object" && !Array.isArray(value);
11
+
12
+ function regularFile(file) {
13
+ const stat = fs.lstatSync(file);
14
+ if (!stat.isFile() || stat.isSymbolicLink()) throw new Error("Prediction route file is not a regular owned file; it was preserved");
15
+ }
16
+
17
+ function preferences(profile) {
18
+ for (const directory of [profile, path.join(profile, "Default")]) {
19
+ const stat = fs.lstatSync(directory);
20
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("Prediction profile is not a regular directory; it was preserved");
21
+ }
22
+ regularFile(path.join(profile, "Local State"));
23
+ const file = path.join(profile, "Default", "Preferences");
24
+ regularFile(file);
25
+ const bytes = readBoundedFileSync(file);
26
+ const value = JSON.parse(bytes);
27
+ if (!object(value)) throw new Error("Unknown App preferences; they were preserved");
28
+ return { file, bytes, value };
29
+ }
30
+
31
+ function recordAt(file, profile) {
32
+ try {
33
+ regularFile(file);
34
+ const value = JSON.parse(readBoundedFileSync(file, { encoding: "utf8" }));
35
+ if (value?.version !== 1 || value.profile !== profile || !validPac(value.pacUrl)
36
+ || typeof value.hadProxy !== "boolean" || (value.hadProxy && !isDeepStrictEqual(value.previousProxy, { mode: "system" }))) {
37
+ throw new Error("Unknown saved prediction route ownership; no preference was changed");
38
+ }
39
+ return value;
40
+ } catch (error) { if (error.code === "ENOENT") return null; throw error; }
41
+ }
42
+
43
+ export function hasInstalledPredictionRoute({ directory, profile, pacUrl } = {}) {
44
+ try {
45
+ const record = recordAt(path.join(directory, "route.json"), profile);
46
+ return record?.pacUrl === pacUrl && isDeepStrictEqual(preferences(profile).value.proxy, { mode: "pac_script", pac_url: pacUrl });
47
+ } catch { return false; }
48
+ }
49
+
50
+ // A write is allowed only while the App is closed. The ownership intent is
51
+ // committed first, so an interrupted activation remains identifiable on off.
52
+ export async function updatePredictionRoute({ directory, profile, pacUrl, remove = false, assertClosed, direct = false,
53
+ writeFile = atomicWriteFileSync } = {}) {
54
+ if (!path.isAbsolute(profile || "") || (!remove && !validPac(pacUrl))) throw new Error("Invalid prediction route binding");
55
+ const recordFile = path.join(directory, "route.json");
56
+ if (remove && !fs.existsSync(recordFile)) return { status: "absent" };
57
+ if (!remove && !direct) return { status: "preserved", reason: "Existing system/company routing was preserved" };
58
+ return withFileLock(`${recordFile}.lock`, () => {
59
+ const record = recordAt(recordFile, profile);
60
+ if (remove && !record) return { status: "absent" };
61
+ let current;
62
+ try { current = preferences(profile); }
63
+ catch (error) {
64
+ if (error.code === "ENOENT" && !remove) return { status: "pending", reason: "App preferences are not initialized" };
65
+ throw error;
66
+ }
67
+ const owned = record && isDeepStrictEqual(current.value.proxy, { mode: "pac_script", pac_url: record.pacUrl });
68
+ if (remove && !owned) {
69
+ // The user replaced the route; retain their edit and remove only our intent.
70
+ fs.unlinkSync(recordFile);return { status: "preserved", reason: "User-edited App route was preserved" };
71
+ }
72
+ if (!remove && owned && record.pacUrl === pacUrl) return { status: "installed" };
73
+ if (!remove && !owned && Object.hasOwn(current.value, "proxy") && !isDeepStrictEqual(current.value.proxy, { mode: "system" })) {
74
+ return { status: "preserved", reason: "Existing App proxy preference was preserved" };
75
+ }
76
+ assertClosed();
77
+ if (!readBoundedFileSync(current.file).equals(current.bytes)) throw new Error("App preferences changed during route setup; retry after quitting the App");
78
+ if (remove) {
79
+ if (record.hadProxy) current.value.proxy = record.previousProxy;
80
+ else delete current.value.proxy;
81
+ } else {
82
+ const next = record || { version: 1, profile, pacUrl, hadProxy: Object.hasOwn(current.value, "proxy"),
83
+ ...(Object.hasOwn(current.value, "proxy") ? { previousProxy: current.value.proxy } : {}) };
84
+ writeFile(recordFile, JSON.stringify({ ...next, pacUrl }, null, 2) + "\n", { preserveMode: false });
85
+ current.value.proxy = { mode: "pac_script", pac_url: pacUrl };
86
+ }
87
+ // Recheck after committing the small intent file, before touching App data.
88
+ assertClosed();
89
+ if (!readBoundedFileSync(current.file).equals(current.bytes)) throw new Error("App preferences changed during route setup; the saved intent was retained");
90
+ writeFile(current.file, JSON.stringify(current.value) + "\n");
91
+ if (remove) fs.unlinkSync(recordFile);
92
+ return { status: remove ? "removed" : "installed" };
93
+ }, { timeoutMs: 100, pollMs: 10 });
94
+ }
@@ -3,11 +3,17 @@ import { operationErrorDetails } from "./operation-error.mjs";
3
3
 
4
4
  export function createPredictionState({ now = () => new Date().toISOString() } = {}) {
5
5
  let state = { configured: false, bridge: "stopped", client_route: "unknown", candidate: "unknown", reason: null,
6
+ launch_route: "unknown", persistence: "unknown", recovery: { attempts: 0, recovered: 0, last_check_at: null },
6
7
  configuration: {}, counters: { configuration_responses: 0, modified: 0, tls_errors: 0, upstream_errors: 0 }, last_event_at: null };
7
8
  return {
8
9
  configure(enabled) { state.configured = enabled === true; },
9
- running(proxy) { state.bridge = "running"; state.reason = null; state.proxy = proxy; },
10
+ running(proxy) { state.bridge = "running"; state.reason = null; state.proxy = proxy;delete state.error; },
10
11
  stopped() { state.bridge = "stopped"; },
12
+ launch(route) { state.launch_route = ["verified", "persisted"].includes(route) ? route : "unverified"; },
13
+ persistence(value) { state.persistence = value.status; },
14
+ checked() { state.recovery.last_check_at = now(); },
15
+ recovering(attempt) { state.bridge = "recovering";state.recovery.attempts = attempt;state.recovery.last_check_at = now(); },
16
+ recovered() { state.bridge = "running";state.reason = null;delete state.error;state.recovery.recovered++; },
11
17
  unavailable(error) {
12
18
  state.bridge = "unavailable";
13
19
  state.reason = redactDiagnosticText(String(error?.message || "Prediction setup failed")).slice(0, 400);
@@ -65,6 +65,7 @@ export async function startPredictionTransport({
65
65
  const sockets = new Set();
66
66
  const upstreams = new Set();
67
67
  let closing = false;
68
+ let listenerError = false;
68
69
  const gateway = https.createServer({ key, cert, minVersion: "TLSv1.2" }, (req, res) => {
69
70
  let target;
70
71
  try {
@@ -240,11 +241,16 @@ export async function startPredictionTransport({
240
241
  gateway.emit("connection", socket);
241
242
  });
242
243
  proxy.on("clientError", (_error, socket) => socket.destroy());
244
+ proxy.on("error", (error) => {
245
+ listenerError = true;
246
+ onEvent({ type: "bridge_error", error: operationErrorDetails(error) });
247
+ });
243
248
  let port;
244
249
  try { port = await listen(proxy, listenPort); }
245
250
  catch (error) { agent?.destroy();gateway.close();throw error; }
246
251
  return {
247
252
  port, pacUrl: `http://127.0.0.1:${port}/proxy.pac`,
253
+ healthy() { return !closing && !listenerError && proxy.listening; },
248
254
  async close() {
249
255
  closing = true;
250
256
  for (const upstream of upstreams) upstream.destroy();
@@ -8,6 +8,7 @@ import { retirePredictionIntegration } from "./prediction-retirement.mjs";
8
8
  import { networkRouteSnapshot } from "./network-route.mjs";
9
9
  import { withFileLock } from "./lock.mjs";
10
10
  import { windowsSystemProxy, windowsProxySettings, windowsProxyText } from "./native-prediction-windows.mjs";
11
+ import { updatePredictionRoute } from "./native-prediction-route.mjs";
11
12
 
12
13
  function systemProxy(exec = execFileSync, { platform = process.platform, env = process.env } = {}) {
13
14
  if (platform === "win32") return windowsSystemProxy({ exec, env });
@@ -49,12 +50,14 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
49
50
  if (action === "status") {
50
51
  output(`Native prediction preference: ${settings.enabled ? "on" : "off"} (default: off)`);
51
52
  output("Uses the conversation's model. No prediction MCP, Hook, or panel.");
52
- if (settings.enabled && !predictionAppMatches(settings.app)) output("Codex App changed; quit it and run ccdx prediction on to recheck compatibility.");
53
+ if (settings.enabled && !predictionAppMatches(settings.app)) output("Codex App changed; bridge startup will recheck compatibility. Unsupported changes still require explicit setup.");
53
54
  if (runtimeSnapshot) {
54
55
  try {
55
56
  const runtime = (await runtimeSnapshot())?.client_integrations?.prediction;
56
57
  if (runtime) {
57
58
  output(`Bridge: ${runtime.bridge}; client route: ${runtime.client_route}; visible candidate: ${runtime.candidate}`);
59
+ if (runtime.launch_route) output(`App launch route: ${runtime.launch_route}; persistent route: ${runtime.persistence || "unknown"}`);
60
+ if (runtime.recovery) output(`Bridge recovery: ${runtime.recovery.recovered} recovered; ${runtime.recovery.attempts}/3 attempts used`);
58
61
  if (runtime.reason) output(runtime.reason);
59
62
  for (const [name, event] of Object.entries(runtime.configuration || {})) output(`${name}: HTTP ${event.status}${event.modified ? " (local compatibility)" : " (upstream)"}`);
60
63
  } else output("Runtime prediction state: unavailable; status is a saved preference, not proof of a visible suggestion.");
@@ -71,6 +74,7 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
71
74
  if (settings.certificateHash && settings.store) {
72
75
  try {
73
76
  assertCodexClosed(opts);
77
+ await updatePredictionRoute({ ...paths, remove: true, assertClosed: () => assertCodexClosed(opts) });
74
78
  const certificate = readPredictionCertificate(certificateDirectory(settings, paths), { ...opts, allowExpired: true });
75
79
  if (certificate.hash !== settings.certificateHash) throw new Error("Prediction certificate changed; trust cleanup was skipped");
76
80
  await updatePredictionTrust(settings.store, certificate, { remove: true });
@@ -150,7 +154,22 @@ export async function startNativePrediction({ env = process.env, platform = proc
150
154
  && (!Number.isInteger(settings.bridgePort) || settings.bridgePort < 1024 || settings.bridgePort > 65535)) {
151
155
  throw new Error("Saved prediction bridge port is invalid; no route was replaced");
152
156
  }
153
- if (!predictionAppMatches(settings.app)) throw new Error("Codex App changed; run ccdx prediction on after quitting it to recheck compatibility");
157
+ if (options.expectedPort !== undefined && settings.bridgePort !== options.expectedPort) throw new Error("Prediction route changed; automatic recovery was skipped");
158
+ if (!predictionAppMatches(settings.app)) {
159
+ const current = (options.resolveApp || installedPredictionApp)({ ...opts,
160
+ ...(platform === "win32" && settings.app?.profile ? { preferredProfile: settings.app.profile } : {}) });
161
+ if (current.app !== settings.app?.app || (platform === "win32" && current.profile !== settings.app?.profile)) {
162
+ throw new Error("Codex App identity/profile changed; run ccdx prediction on after quitting it to recheck compatibility");
163
+ }
164
+ const settingsFile = predictionPaths(opts).settings;
165
+ await withFileLock(`${settingsFile}.lock`, () => {
166
+ const latest = readPredictionSettings(opts);
167
+ if (JSON.stringify(latest) !== JSON.stringify(settings)) throw new Error("Prediction setup changed during App compatibility recheck");
168
+ writePredictionSettings({ ...latest, app: current }, opts);
169
+ }, { timeoutMs: 2000 });
170
+ settings.app = current;
171
+ warning("Codex App compatibility rechecked; prediction port and trust were preserved");
172
+ }
154
173
  const paths = predictionPaths({ ...opts, app: settings.app });
155
174
  if (settings.store !== paths.store || !fs.existsSync(paths.store)) throw new Error("Prediction profile trust is unavailable; run ccdx prediction on after quitting Codex");
156
175
  const certificate = readPredictionCertificate(certificateDirectory(settings, paths), opts);
@@ -214,12 +233,31 @@ export async function startNativePrediction({ env = process.env, platform = proc
214
233
  throw error;
215
234
  }
216
235
  state?.running(windowsNetwork ? { source: "system", type: "auto", bypass_rules: null, proxy_credentials: false } : networkRouteSnapshot(networkRoute));
217
- warning("Native prediction bridge enabled; only the two configuration hosts use its App-only route.");
218
- warning("If Codex uses a different or missing prediction route, fully quit it and run ccdx again.");
219
236
  return {
220
237
  app: settings.app.app,
221
238
  ...(platform === "win32" ? { profile: paths.profile } : {}),
222
239
  pacUrl: transport.pacUrl,
240
+ enabled() { return enabled; },
241
+ healthy() { return transport.healthy() && (!windowsNetwork || windowsNetwork.healthy()); },
242
+ async prepareRoute() {
243
+ try {
244
+ const direct = !windowsNetwork && !networkRoute?.http && !networkRoute?.https && !networkRoute?.bypass?.length;
245
+ if (!direct) {
246
+ // A profile previously configured on a direct network must not pin
247
+ // that local PAC after the environment switches to company routing.
248
+ await updatePredictionRoute({ ...paths, remove: true, assertClosed: () => assertCodexClosed(opts) });
249
+ }
250
+ const result = await updatePredictionRoute({ ...paths, pacUrl: transport.pacUrl, direct,
251
+ assertClosed: () => assertCodexClosed(opts) });
252
+ state?.persistence(result);
253
+ if (result.status === "preserved") warning(`Prediction route persistence skipped: ${result.reason}`);
254
+ return result;
255
+ } catch (error) {
256
+ state?.persistence({ status: "pending" });
257
+ if (!error.message.startsWith("Quit Codex App")) warning(`Prediction route persistence deferred: ${error.message}`);
258
+ return { status: "pending" };
259
+ }
260
+ },
223
261
  args: [...(platform === "win32" ? [`--user-data-dir=${paths.profile}`] : []), `--proxy-pac-url=${transport.pacUrl}`],
224
262
  async close() { clearInterval(timer); await transport.close(); windowsNetwork?.close(); state?.stopped(); },
225
263
  };
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
5
5
  import { createInterface } from "node:readline/promises";
6
6
  import { lookupLatestRelease, githubReleaseVersion } from "./version.mjs";
7
7
  import { terminalCell } from "./terminal-text.mjs";
8
+ import { readBoundedFileSync } from "./bounded-file.mjs";
8
9
 
9
10
  const PACKAGE_NAME = "codex-copilot-dx";
10
11
  const UPDATE_SPECS = {
@@ -84,6 +85,17 @@ function waitForExit(child) {
84
85
  });
85
86
  }
86
87
 
88
+ export function verifyInstalledPackage(target, { expectedVersion } = {}) {
89
+ if (!target) return null;
90
+ let pkg;
91
+ try { pkg = JSON.parse(readBoundedFileSync(path.join(target, "package.json"), { encoding: "utf8" })); } catch {}
92
+ if (pkg?.name !== PACKAGE_NAME || !githubReleaseVersion(pkg.version)
93
+ || (expectedVersion && pkg.version !== expectedVersion)) {
94
+ throw new Error("npm finished, but the target package version could not be verified. Check ccdx doctor; installation was not retried.");
95
+ }
96
+ return pkg.version;
97
+ }
98
+
87
99
  export async function runPackageUpdateCommand({
88
100
  commandName = "ccdx",
89
101
  env = process.env,
@@ -95,6 +107,7 @@ export async function runPackageUpdateCommand({
95
107
  spawnImpl = spawn,
96
108
  fetchImpl = fetch,
97
109
  inspectEnvironmentFn = inspectPackageUpdateEnvironment,
110
+ verifyInstalledFn = verifyInstalledPackage,
98
111
  } = {}) {
99
112
  let selectedSource = normalizeUpdateSource(source);
100
113
  if (source && !selectedSource) throw new Error(`Update source must be npm or github: ${source}`);
@@ -151,6 +164,12 @@ export async function runPackageUpdateCommand({
151
164
  ...launch.options,
152
165
  });
153
166
  await waitForExit(child);
154
- output.write(`Updated ${PACKAGE_NAME} from ${sourceLabel}. Restart the running adapter to use the new version.\n`);
167
+ const installedVersion = verifyInstalledFn(environment?.target, { expectedVersion: release?.version });
168
+ if (installedVersion) {
169
+ output.write(`Updated ${PACKAGE_NAME}: installed v${terminalCell(installedVersion)} at ${terminalCell(environment.target)}.\n`);
170
+ } else {
171
+ output.write("Installer finished; the global target was unavailable, so the installed version was not verified. Run ccdx doctor.\n");
172
+ }
173
+ output.write("Restart the running adapter to use the installed version; an existing service is not replaced automatically.\n");
155
174
  return { cancelled: false, source: selectedSource };
156
175
  }
@@ -122,7 +122,7 @@ export function createProfileModelRuntime({
122
122
  }
123
123
  const gptModelIds = gptModelIdsFromCopilotModels(models);
124
124
  if (gptModelIds.length) {
125
- emit("ok", `Refreshed GPT models from GitHub Copilot: ${gptModelIds.join(", ")}`);
125
+ emit("ok", `Model catalog refreshed: ${gptModelIds.length} GPT models`);
126
126
  } else {
127
127
  emit("warn", "Copilot models response contained no GPT models");
128
128
  }
@@ -69,7 +69,7 @@ function chatCompatibilityError(kind, itemType) {
69
69
  return error;
70
70
  }
71
71
 
72
- export function responsesToChat(body) {
72
+ export function responsesToChat(body, { reasoningEfforts } = {}) {
73
73
  const messages = [];
74
74
  if (body.instructions) messages.push({ role: "system", content: body.instructions });
75
75
 
@@ -165,11 +165,16 @@ export function responsesToChat(body) {
165
165
  const maxTok = body.max_output_tokens ?? body.max_tokens ?? body.max_completion_tokens;
166
166
  if (maxTok !== undefined) chatReq.max_completion_tokens = maxTok;
167
167
 
168
+ if (body.tools !== undefined && !Array.isArray(body.tools)) throw chatCompatibilityError("tools", typeof body.tools);
168
169
  if (body.tools?.length) {
169
- const unsupportedTool = body.tools.find((tool) => tool?.type !== "function");
170
- if (unsupportedTool) throw chatCompatibilityError("tool", unsupportedTool?.type);
170
+ if (body.tools.some(tool => tool?.type !== "function")) {
171
+ throw chatCompatibilityError("tool", body.tools.find(tool => tool?.type !== "function")?.type);
172
+ }
171
173
  chatReq.tools = body.tools
172
174
  .map((tool) => {
175
+ if (typeof (tool.function?.name ?? tool.name) !== "string" || !(tool.function?.name ?? tool.name).trim()) {
176
+ throw chatCompatibilityError("function tool", "missing_name");
177
+ }
173
178
  if (tool.function?.name) return cloneJson(tool);
174
179
  const fn = {
175
180
  name: tool.name,
@@ -179,21 +184,29 @@ export function responsesToChat(body) {
179
184
  };
180
185
  for (const key of Object.keys(fn)) if (fn[key] === undefined) delete fn[key];
181
186
  return { type: "function", function: fn };
182
- })
183
- .filter(Boolean)
184
- .filter((t) => t.function?.name);
185
- if (!chatReq.tools.length) delete chatReq.tools;
187
+ });
186
188
  }
187
189
  if (body.tool_choice !== undefined) {
188
190
  if (typeof body.tool_choice === "string") {
191
+ if (!["auto", "none", "required"].includes(body.tool_choice)) throw chatCompatibilityError("tool choice", body.tool_choice);
189
192
  chatReq.tool_choice = body.tool_choice;
190
193
  } else if (body.tool_choice?.type === "function" && body.tool_choice.name) {
194
+ if (!chatReq.tools?.some(tool => tool.function.name === body.tool_choice.name)) {
195
+ throw chatCompatibilityError("tool choice", "undeclared_function");
196
+ }
191
197
  chatReq.tool_choice = { type: "function", function: { name: body.tool_choice.name } };
192
198
  } else {
193
199
  throw chatCompatibilityError("tool choice", body.tool_choice?.type);
194
200
  }
195
201
  }
196
202
  if (body.parallel_tool_calls !== undefined) chatReq.parallel_tool_calls = body.parallel_tool_calls;
203
+ if (body.reasoning?.effort !== undefined) {
204
+ if (!["none", "minimal", "low", "medium", "high", "xhigh", "max"].includes(body.reasoning.effort)
205
+ || (Array.isArray(reasoningEfforts) && !reasoningEfforts.includes(body.reasoning.effort))) {
206
+ throw chatCompatibilityError("reasoning effort", String(body.reasoning.effort));
207
+ }
208
+ chatReq.reasoning_effort = body.reasoning.effort;
209
+ }
197
210
  const textFormat = body.text?.format;
198
211
  if (textFormat?.type === "json_schema") {
199
212
  chatReq.response_format = {
@@ -207,6 +220,8 @@ export function responsesToChat(body) {
207
220
  };
208
221
  } else if (textFormat?.type === "json_object") {
209
222
  chatReq.response_format = { type: "json_object" };
223
+ } else if (textFormat !== undefined && textFormat?.type !== "text") {
224
+ throw chatCompatibilityError("text format", textFormat?.type);
210
225
  }
211
226
  return chatReq;
212
227
  }
@@ -32,8 +32,8 @@ function jsonPayload(value, assertActive) {
32
32
  });
33
33
  }
34
34
 
35
- function chatRequest(responsesBody, stream) {
36
- const chatReq = responsesToChat(responsesBody);
35
+ function chatRequest(responsesBody, stream, reasoningEfforts) {
36
+ const chatReq = responsesToChat(responsesBody, { reasoningEfforts });
37
37
  chatReq.stream = Boolean(stream);
38
38
  delete chatReq.max_tokens;
39
39
  return stream ? withChatStreamUsage(chatReq) : chatReq;
@@ -81,12 +81,13 @@ function checkedChatPayload(chatReq, payload, limit, stage, adapted, assertActiv
81
81
  export async function prepareResponsesChatPayload(reqContext, {
82
82
  assertActive,
83
83
  payloadOptions = {},
84
+ reasoningEfforts,
84
85
  signal,
85
86
  stream = false,
86
87
  } = {}) {
87
88
  assertActive?.();
88
89
  const limit = configuredBodyLimit(payloadOptions);
89
- let finalChatReq = chatRequest(reqContext.body, stream);
90
+ let finalChatReq = chatRequest(reqContext.body, stream, reasoningEfforts);
90
91
  assertActive?.();
91
92
  let finalChat = jsonPayload(finalChatReq, assertActive);
92
93
  const hasInlineImage = bodyHasInlineImage(reqContext.body, assertActive);
@@ -108,7 +109,7 @@ export async function prepareResponsesChatPayload(reqContext, {
108
109
  responsesPayload = { bodyText: prepared.bodyText, bodyBytes: prepared.bodyBytes };
109
110
  adapted = prepared.adapted;
110
111
  stage = prepared.stage;
111
- finalChatReq = chatRequest(reqContext.body, stream);
112
+ finalChatReq = chatRequest(reqContext.body, stream, reasoningEfforts);
112
113
  assertActive?.();
113
114
  finalChat = jsonPayload(finalChatReq, assertActive);
114
115
  }
@@ -132,7 +133,7 @@ export async function prepareResponsesChatPayload(reqContext, {
132
133
  initialBodyBytes: responsesPayload.bodyBytes,
133
134
  });
134
135
  if (!trimmed.adapted) break;
135
- const candidateChatReq = chatRequest(reqContext.body, stream);
136
+ const candidateChatReq = chatRequest(reqContext.body, stream, reasoningEfforts);
136
137
  assertActive?.();
137
138
  const candidateChat = jsonPayload(candidateChatReq, assertActive);
138
139
  if (candidateChat.bodyBytes >= finalChat.bodyBytes) {