codex-copilot-dx 0.9.24 → 0.9.26

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 (40) hide show
  1. package/README.md +15 -12
  2. package/bin/cli.mjs +24 -32
  3. package/docs/ARCHITECTURE.md +69 -0
  4. package/docs/README.md +6 -0
  5. package/docs/REFERENCE.md +112 -10
  6. package/package.json +3 -2
  7. package/src/adapter.mjs +1 -0
  8. package/src/cli-image.mjs +13 -10
  9. package/src/cli-options.mjs +1 -1
  10. package/src/cli-status.mjs +5 -0
  11. package/src/client-integration.mjs +41 -0
  12. package/src/codex-config-doctor.mjs +3 -3
  13. package/src/codex-paths.mjs +10 -0
  14. package/src/codex-thread-compression.mjs +11 -6
  15. package/src/config.mjs +10 -6
  16. package/src/copilot-responses-compat.mjs +30 -2
  17. package/src/copilot-responses-policy.mjs +14 -3
  18. package/src/dashboard/index.html +18 -9
  19. package/src/dashboard/language.js +14 -0
  20. package/src/dashboard/ui.css +2 -0
  21. package/src/dashboard/ui.js +10 -0
  22. package/src/launcher.mjs +50 -2
  23. package/src/lock.mjs +29 -0
  24. package/src/native-prediction-profile.mjs +46 -23
  25. package/src/native-prediction-state.mjs +29 -0
  26. package/src/native-prediction-transport.mjs +24 -9
  27. package/src/native-prediction-windows.mjs +174 -0
  28. package/src/native-prediction.mjs +102 -28
  29. package/src/network-route.mjs +102 -0
  30. package/src/observability.mjs +2 -0
  31. package/src/operation-error.mjs +37 -0
  32. package/src/package-update.mjs +2 -3
  33. package/src/prediction-retirement.mjs +13 -2
  34. package/src/proxy-tunnel.mjs +102 -0
  35. package/src/responses-proxy.mjs +13 -3
  36. package/src/responses-request.mjs +35 -2
  37. package/src/user-settings.mjs +17 -4
  38. package/src/version.mjs +23 -46
  39. package/src/windows-prediction-network.cs +154 -0
  40. package/src/windows-prediction-network.mjs +123 -0
@@ -0,0 +1,29 @@
1
+ import { redactDiagnosticText } from "./diagnostic-text.mjs";
2
+ import { operationErrorDetails } from "./operation-error.mjs";
3
+
4
+ export function createPredictionState({ now = () => new Date().toISOString() } = {}) {
5
+ let state = { configured: false, bridge: "stopped", client_route: "unknown", candidate: "unknown", reason: null,
6
+ configuration: {}, counters: { configuration_responses: 0, modified: 0, tls_errors: 0, upstream_errors: 0 }, last_event_at: null };
7
+ return {
8
+ configure(enabled) { state.configured = enabled === true; },
9
+ running(proxy) { state.bridge = "running"; state.reason = null; state.proxy = proxy; },
10
+ stopped() { state.bridge = "stopped"; },
11
+ unavailable(error) {
12
+ state.bridge = "unavailable";
13
+ state.reason = redactDiagnosticText(String(error?.message || "Prediction setup failed")).slice(0, 400);
14
+ state.error = operationErrorDetails(error);
15
+ },
16
+ event(event) {
17
+ state.last_event_at = now();
18
+ if (event.type === "configuration") {
19
+ state.client_route = "observed";
20
+ state.counters.configuration_responses++;
21
+ if (event.changed) state.counters.modified++;
22
+ state.configuration[event.route] = { status: event.status, modified: event.changed === true, official: event.official === true };
23
+ } else if (event.type === "tls_error") state.counters.tls_errors++;
24
+ else if (event.type === "upstream_error") state.counters.upstream_errors++;
25
+ if (event.error) state.last_error = { code: event.error.code, source: event.error.source, message: event.error.message, status: event.error.status };
26
+ },
27
+ snapshot() { return structuredClone(state); },
28
+ };
29
+ }
@@ -2,6 +2,8 @@ import http from "node:http";
2
2
  import https from "node:https";
3
3
  import { promisify } from "node:util";
4
4
  import { gunzip, inflate, brotliDecompress } from "node:zlib";
5
+ import { networkPredictionPac } from "./network-route.mjs";
6
+ import { operationErrorDetails } from "./operation-error.mjs";
5
7
 
6
8
  export const PREDICTION_HOSTS = Object.freeze(["chatgpt.com", "ab.chatgpt.com"]);
7
9
  const CONFIG_LIMIT = 16 * 1024 * 1024;
@@ -15,8 +17,9 @@ export function predictionRoute(host, pathname) {
15
17
  return null;
16
18
  }
17
19
 
18
- export function predictionPac(port) {
20
+ export function predictionPac(port, networkRoute) {
19
21
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid prediction proxy port");
22
+ if (networkRoute) return networkPredictionPac(port, networkRoute);
20
23
  return `function FindProxyForURL(url, host) { if (url.indexOf('https:') === 0 && (host === 'chatgpt.com' || host === 'ab.chatgpt.com')) return 'PROXY 127.0.0.1:${port}; DIRECT'; return 'DIRECT'; }\n`;
21
24
  }
22
25
 
@@ -41,10 +44,10 @@ async function decode(bytes, encoding, limit) {
41
44
  return decoders[encoding](bytes, { maxOutputLength: limit });
42
45
  }
43
46
 
44
- function listen(server) {
47
+ function listen(server, port = 0) {
45
48
  return new Promise((resolve, reject) => {
46
49
  server.once("error", reject);
47
- server.listen(0, "127.0.0.1", () => {
50
+ server.listen(port, "127.0.0.1", () => {
48
51
  server.removeListener("error", reject);
49
52
  resolve(server.address().port);
50
53
  });
@@ -56,7 +59,8 @@ function listen(server) {
56
59
  export async function startPredictionTransport({
57
60
  key, cert, overlay, normalizeRequest = (value) => value,
58
61
  enabled = () => true, requestImpl = https.request,
59
- timeoutMs = 30_000, maxConnections = 128,
62
+ agent, networkRoute, pacImpl, onEvent = () => {},
63
+ timeoutMs = 30_000, maxConnections = 128, listenPort = 0,
60
64
  }) {
61
65
  const sockets = new Set();
62
66
  const upstreams = new Set();
@@ -76,7 +80,8 @@ export async function startPredictionTransport({
76
80
  // No decoding/re-encoding on pass-through paths.
77
81
  if (route && enabled()) headers["accept-encoding"] = "identity";
78
82
  let upstream;
79
- const fail = () => {
83
+ const fail = (error) => {
84
+ onEvent({ type: "upstream_error", error: operationErrorDetails(error) });
80
85
  if (!res.headersSent) { res.writeHead(502); res.end(); } else res.destroy();
81
86
  };
82
87
  const send = (body, streamRemainder = false) => {
@@ -86,6 +91,7 @@ export async function startPredictionTransport({
86
91
  servername: target.hostname, method: req.method,
87
92
  path: req.url, headers,
88
93
  rejectUnauthorized: true,
94
+ ...(agent ? { agent } : {}),
89
95
  }, (reply) => {
90
96
  const pass = () => {
91
97
  res.writeHead(reply.statusCode, cleanHeaders(reply.headers));
@@ -95,7 +101,10 @@ export async function startPredictionTransport({
95
101
  // Error and non-JSON responses are forwarded as received. The overlay
96
102
  // decides whether the narrowly allowed missing-config response applies.
97
103
  const mediaType = String(reply.headers["content-type"] || "").split(";", 1)[0].trim();
98
- if (!route || !enabled() || mediaType !== "application/json") { pass(); return; }
104
+ if (!route || !enabled() || mediaType !== "application/json") {
105
+ if (route) onEvent({ type: "configuration", route, status: reply.statusCode, changed: false });
106
+ pass(); return;
107
+ }
99
108
  let size = 0;
100
109
  const parts = [];
101
110
  let streaming = false;
@@ -124,10 +133,12 @@ export async function startPredictionTransport({
124
133
  });
125
134
  } catch { /* Preserve unexpected upstream payloads byte-for-byte. */ }
126
135
  if (next?.body !== undefined && (next.body !== original.toString("utf8") || next.status !== reply.statusCode)) {
136
+ onEvent({ type: "configuration", route, status: next.status ?? reply.statusCode, changed: true });
127
137
  const bytes = Buffer.from(next.body);
128
138
  res.writeHead(next.status ?? reply.statusCode, changedHeaders(reply.headers, bytes.length));
129
139
  res.end(bytes);
130
140
  } else {
141
+ onEvent({ type: "configuration", route, status: reply.statusCode, changed: false, official: next?.official });
131
142
  res.writeHead(reply.statusCode, cleanHeaders(reply.headers)); res.end(original);
132
143
  }
133
144
  })().catch(fail));
@@ -179,6 +190,7 @@ export async function startPredictionTransport({
179
190
  const upstream = requestImpl({
180
191
  protocol: "https:", hostname: host, port: 443, servername: host,
181
192
  method: req.method, path: req.url, rejectUnauthorized: true,
193
+ ...(agent ? { agent } : {}),
182
194
  headers: { ...cleanHeaders(req.headers), connection: "Upgrade", upgrade: req.headers.upgrade },
183
195
  });
184
196
  upstreams.add(upstream);
@@ -204,13 +216,13 @@ export async function startPredictionTransport({
204
216
  socket.once("close", () => { upstreams.delete(upstream); upstream.destroy(); });
205
217
  upstream.end();
206
218
  });
207
- gateway.on("tlsClientError", (_error, socket) => socket.destroy());
219
+ gateway.on("tlsClientError", (error, socket) => { onEvent({ type: "tls_error", error: operationErrorDetails(error) }); socket.destroy(); });
208
220
  gateway.on("clientError", (_error, socket) => socket.destroy());
209
221
  const proxy = http.createServer((req, res) => {
210
222
  if (req.method === "GET" && req.url === "/proxy.pac" && !req.headers.origin
211
223
  && ["127.0.0.1", "localhost"].includes(String(req.headers.host || "").split(":")[0])) {
212
224
  res.writeHead(200, { "Content-Type": "application/x-ns-proxy-autoconfig", "Cache-Control": "no-store" });
213
- res.end(predictionPac(proxy.address().port)); return;
225
+ res.end(pacImpl ? pacImpl(proxy.address().port) : predictionPac(proxy.address().port, networkRoute)); return;
214
226
  }
215
227
  res.writeHead(403); res.end();
216
228
  });
@@ -228,12 +240,15 @@ export async function startPredictionTransport({
228
240
  gateway.emit("connection", socket);
229
241
  });
230
242
  proxy.on("clientError", (_error, socket) => socket.destroy());
231
- const port = await listen(proxy);
243
+ let port;
244
+ try { port = await listen(proxy, listenPort); }
245
+ catch (error) { agent?.destroy();gateway.close();throw error; }
232
246
  return {
233
247
  port, pacUrl: `http://127.0.0.1:${port}/proxy.pac`,
234
248
  async close() {
235
249
  closing = true;
236
250
  for (const upstream of upstreams) upstream.destroy();
251
+ agent?.destroy();
237
252
  for (const socket of sockets) socket.destroy();
238
253
  await new Promise((resolve) => proxy.close(resolve));
239
254
  gateway.close();
@@ -0,0 +1,174 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { execFileSync } from "node:child_process";
4
+
5
+ const WINDOWS_PUBLISHER = "CN=50BDFD77-8903-4850-9FFE-6E8522F64D5B";
6
+ const WINDOWS_PACKAGE_FAMILY = "OpenAI.Codex_2p2nqsd0c76g0";
7
+
8
+ export function windowsPowerShellEnvironment(env = process.env) {
9
+ // PowerShell 7 can export a Core-only PSModulePath. Prefer the bundled
10
+ // Windows PowerShell modules for this child, retaining user module paths.
11
+ const modules = path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "Modules");
12
+ return { ...env, PSModulePath: [modules, env.PSModulePath].filter(Boolean).join(";") };
13
+ }
14
+
15
+ function powershell(script, { env = process.env, exec = execFileSync, ...options } = {}) {
16
+ const command = path.win32.join(env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
17
+ try {
18
+ return exec(command, ["-NoProfile", "-NonInteractive", "-Command",
19
+ "$ErrorActionPreference='Stop';[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new($false);" + script],
20
+ { encoding: "utf8", timeout: 10_000, maxBuffer: 64 * 1024, env: windowsPowerShellEnvironment(env), windowsHide: true, ...options }).trim();
21
+ } catch {
22
+ throw new Error("Windows prediction check failed; verify PowerShell, App registration and current-user permissions");
23
+ }
24
+ }
25
+
26
+ export function assertWindowsCodexClosed(options = {}) {
27
+ let result;
28
+ try { result = powershell("if (@(Get-Process -Name Codex,ChatGPT -ErrorAction SilentlyContinue).Count) {'running'} else {'closed'}", options); }
29
+ catch { throw new Error("Could not check whether Codex is closed; prediction setup was skipped"); }
30
+ if (result !== "closed") throw new Error("Quit Codex App before changing native prediction setup; no running App will be stopped");
31
+ }
32
+
33
+ export function windowsPredictionAppProcesses(app, { env = process.env, ...options } = {}) {
34
+ const raw = powershell(`$rows=@(Get-CimInstance Win32_Process -Filter "Name='ChatGPT.exe' OR Name='Codex.exe'" -OperationTimeoutSec 5 | Where-Object {
35
+ $_.ExecutablePath -eq $env:CCDX_PREDICTION_APP_PATH -and ($_.CommandLine -notmatch '--type(?:=|\\s)')
36
+ } | ForEach-Object {
37
+ $route=$null;
38
+ if($_.CommandLine -match '--proxy-pac-url=(?:"(http://127\\.0\\.0\\.1:\\d{1,5}/proxy\\.pac)"|(http://127\\.0\\.0\\.1:\\d{1,5}/proxy\\.pac))'){
39
+ $route=if($Matches[1]){$Matches[1]}else{$Matches[2]}
40
+ };
41
+ @{pid=[int]$_.ProcessId;route=$route;readable=![string]::IsNullOrWhiteSpace($_.CommandLine)}
42
+ });ConvertTo-Json -InputObject $rows -Compress`, { ...options, env: { ...env, CCDX_PREDICTION_APP_PATH: app } });
43
+ let rows;
44
+ try { rows = JSON.parse(raw); } catch { throw new Error("Could not verify the running Windows App route; launch was skipped"); }
45
+ if (!Array.isArray(rows) || rows.length > 8 || rows.some(row => !Number.isInteger(row?.pid) || typeof row.readable !== "boolean"
46
+ || (row.route !== null && (typeof row.route !== "string" || !/^http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac$/.test(row.route))))) {
47
+ throw new Error("Unknown running Windows App route; launch was skipped");
48
+ }
49
+ return rows;
50
+ }
51
+
52
+ export function installedWindowsPredictionApp(options = {}) {
53
+ const raw = powershell(`$p=@(Get-AppxPackage -Name OpenAI.Codex | Where-Object { [int]$_.Status -eq 0 -and [int]$_.SignatureKind -eq 3 -and $_.Publisher -eq '${WINDOWS_PUBLISHER}' -and $_.PackageFamilyName -eq '${WINDOWS_PACKAGE_FAMILY}' });
54
+ if($p.Count -ne 1){throw 'A single official OpenAI.Codex MSIX registration is required'};
55
+ $m=Get-AppxPackageManifest -Package ([string]$p[0].PackageFullName);
56
+ $a=@($m.Package.Applications.Application | Where-Object { [System.IO.Path]::GetFileName($_.Executable) -in @('Codex.exe','ChatGPT.exe') });
57
+ if($a.Count -ne 1){throw 'Unknown Windows App executable'};
58
+ @{root=$p[0].InstallLocation;executable=$a[0].Executable;family=$p[0].PackageFamilyName} | ConvertTo-Json -Compress`, options);
59
+ let metadata;
60
+ try { metadata = JSON.parse(raw); } catch { throw new Error("Could not read the registered Windows Codex App"); }
61
+ const { root, executable, family } = metadata;
62
+ if (typeof root !== "string" || !/^[a-z]:[\\/]/i.test(root) || typeof executable !== "string"
63
+ || path.win32.isAbsolute(executable) || executable.split(/[\\/]/).includes("..")
64
+ || !/^(Codex|ChatGPT)\.exe$/i.test(path.win32.basename(executable))
65
+ || family !== WINDOWS_PACKAGE_FAMILY) {
66
+ throw new Error("Unknown Windows App registration; prediction setup was skipped");
67
+ }
68
+ const app = path.win32.join(root, executable);
69
+ const archives = [path.win32.join(path.win32.dirname(app), "resources", "app.asar"), path.win32.join(root, "resources", "app.asar")];
70
+ const archive = [...new Set(archives)].find(candidate => fs.existsSync(candidate));
71
+ if (!archive) throw new Error("The registered Windows App has no readable app archive");
72
+ return { app, archive, family };
73
+ }
74
+
75
+ export function windowsPredictionProfile({ app, env = process.env, preferredProfile } = {}) {
76
+ const override = String(env.CODEX_ELECTRON_USER_DATA_PATH || "").trim();
77
+ if (override) return path.resolve(override);
78
+ if (preferredProfile !== undefined) {
79
+ if (typeof preferredProfile !== "string" || !path.win32.isAbsolute(preferredProfile)
80
+ || /[\0\r\n]/.test(preferredProfile) || !fs.existsSync(path.win32.join(preferredProfile, "Local State"))) {
81
+ throw new Error("Previously selected Windows profile is unavailable; set CODEX_ELECTRON_USER_DATA_PATH explicitly");
82
+ }
83
+ return path.win32.normalize(preferredProfile);
84
+ }
85
+ const names = path.win32.basename(app?.app || "").toLowerCase() === "chatgpt.exe" ? ["Codex", "ChatGPT"] : ["Codex"];
86
+ const roots = names.flatMap(name => [env.APPDATA && path.win32.join(env.APPDATA, name),
87
+ env.LOCALAPPDATA && app?.family && path.win32.join(env.LOCALAPPDATA, "Packages", app.family, "LocalCache", "Roaming", name)]).filter(Boolean);
88
+ const candidates = roots.flatMap(root => path.win32.basename(root) === "Codex"
89
+ ? [root, path.win32.join(root, "web", "Codex")] : [root]);
90
+ // MSIX can virtualize AppData. Select only an existing App-created profile;
91
+ // newer Windows builds nest the browser profile under web/Codex. Never guess
92
+ // which copy owns trust when more than one initialized profile is present.
93
+ const profiles = [...new Set(candidates)].filter(candidate => fs.existsSync(path.win32.join(candidate, "Local State")));
94
+ if (profiles.length !== 1) throw new Error(profiles.length
95
+ ? "Multiple Codex App profiles found; set CODEX_ELECTRON_USER_DATA_PATH to the active profile"
96
+ : "Open Codex App once, fully quit it, then run ccdx prediction on; its Windows profile was not found");
97
+ return profiles[0];
98
+ }
99
+
100
+ export function windowsPredictionOpenSSL(options = {}) {
101
+ const raw = powershell(`$found=Get-Command openssl.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1;
102
+ if($found){$found.Source}else{
103
+ $paths=@("$env:ProgramFiles\\Git\\usr\\bin\\openssl.exe", "$env:LOCALAPPDATA\\Programs\\Git\\usr\\bin\\openssl.exe");
104
+ $paths | Where-Object {Test-Path -LiteralPath $_ -PathType Leaf} | Select-Object -First 1
105
+ }`, options);
106
+ if (!path.win32.isAbsolute(raw) || !/openssl\.exe$/i.test(path.win32.basename(raw))) {
107
+ throw new Error("Native prediction needs OpenSSL on Windows; install Git for Windows (includes OpenSSL) and retry");
108
+ }
109
+ return raw;
110
+ }
111
+
112
+ export function windowsPrivatePredictionPath(filePath, { create = false, env = process.env, ...options } = {}) {
113
+ powershell(`$p=$env:CCDX_PREDICTION_PRIVATE_PATH;$sid=[System.Security.Principal.WindowsIdentity]::GetCurrent().User;
114
+ $acl=Get-Acl -LiteralPath $p;
115
+ ${create ? `$acl.SetAccessRuleProtection($true,$false);
116
+ $rule=[System.Security.AccessControl.FileSystemAccessRule]::new($sid,'FullControl','ContainerInherit,ObjectInherit','None','Allow');
117
+ $acl.AddAccessRule($rule);$acl.SetOwner($sid);Set-Acl -LiteralPath $p -AclObject $acl;$acl=Get-Acl -LiteralPath $p;` : ""}
118
+ $allowed=@($sid.Value,'S-1-5-18','S-1-5-32-544');
119
+ if($acl.GetOwner([System.Security.Principal.SecurityIdentifier]).Value -notin $allowed){throw 'Prediction key path has a different owner'};
120
+ foreach($rule in $acl.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier])){
121
+ if($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin $allowed){throw 'Prediction key path is not private'}
122
+ }`, { ...options, env: { ...env, CCDX_PREDICTION_PRIVATE_PATH: filePath } });
123
+ }
124
+
125
+ export function windowsProxySettings(options = {}) {
126
+ const raw = powershell(`Add-Type -TypeDefinition @'
127
+ using System;using System.Runtime.InteropServices;
128
+ public static class CCDXWinInetProxy {
129
+ [StructLayout(LayoutKind.Sequential)] public struct Config { [MarshalAs(UnmanagedType.Bool)] public bool AutoDetect;public IntPtr Pac;public IntPtr Proxy;public IntPtr Bypass; }
130
+ [DllImport("winhttp.dll",SetLastError=true)] public static extern bool WinHttpGetIEProxyConfigForCurrentUser(ref Config value);
131
+ [DllImport("kernel32.dll")] public static extern IntPtr GlobalFree(IntPtr value);
132
+ }
133
+ '@
134
+ $c=[CCDXWinInetProxy+Config]::new();
135
+ if(-not [CCDXWinInetProxy]::WinHttpGetIEProxyConfigForCurrentUser([ref]$c)){throw 'Could not read current-user proxy settings'};
136
+ try{@{autoDetect=$c.AutoDetect;pac=[Runtime.InteropServices.Marshal]::PtrToStringUni($c.Pac);proxy=[Runtime.InteropServices.Marshal]::PtrToStringUni($c.Proxy);bypass=[Runtime.InteropServices.Marshal]::PtrToStringUni($c.Bypass)} | ConvertTo-Json -Compress}
137
+ finally{foreach($p in @($c.Pac,$c.Proxy,$c.Bypass)){if($p -ne [IntPtr]::Zero){[void][CCDXWinInetProxy]::GlobalFree($p)}}}`, options);
138
+ let settings;
139
+ try { settings = JSON.parse(raw); } catch { throw new Error("Could not read Windows proxy settings; existing routes were preserved"); }
140
+ if (!settings || typeof settings !== "object" || Array.isArray(settings) || typeof settings.autoDetect !== "boolean"
141
+ || [settings.pac, settings.proxy, settings.bypass].some(value => value !== undefined && value !== null && typeof value !== "string")) {
142
+ throw new Error("Unknown Windows proxy settings; existing routes were preserved");
143
+ }
144
+ return settings;
145
+ }
146
+
147
+ export function windowsSystemProxy(options = {}) { return windowsProxyText(windowsProxySettings(options)); }
148
+
149
+ export function windowsProxyText({ autoDetect, pac, proxy = "", bypass = "" } = {}) {
150
+ if (autoDetect || pac) throw new Error("Native prediction setup skipped: Windows PAC/WPAD needs dynamic routing; its rules were preserved");
151
+ if (/[\r\n{}]/.test(String(proxy || "") + String(bypass || ""))) throw new Error("Unsupported Windows proxy rules; existing routes were preserved");
152
+ const protocols = new Map();
153
+ for (const item of String(proxy || "").split(";").map(value => value.trim()).filter(Boolean)) {
154
+ const match = /^(http|https|socks)=(.+)$/i.exec(item);
155
+ if (!match && item.includes("=")) throw new Error("Unsupported Windows proxy protocol; existing routes were preserved");
156
+ for (const scheme of match ? [match[1].toLowerCase()] : ["http", "https"]) {
157
+ if (protocols.has(scheme)) throw new Error("Duplicate Windows proxy route; existing routes were preserved");
158
+ let url;
159
+ try { url = new URL("http://" + (match ? match[2] : item)); } catch {}
160
+ if (!url?.hostname || (url.port && Number(url.port) < 1) || url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
161
+ throw new Error("Unsupported Windows proxy address; existing routes were preserved");
162
+ }
163
+ protocols.set(scheme, url);
164
+ }
165
+ }
166
+ const parts = [...protocols].map(([scheme, url]) => {
167
+ const name = scheme === "socks" ? "SOCKS" : scheme.toUpperCase();
168
+ return `${name}Enable : 1\n${name}Proxy : ${url.hostname.replace(/^\[|\]$/g, "")}\n${name}Port : ${url.port || 80}`;
169
+ });
170
+ const exceptions = String(bypass || "").split(";").map(value => value.trim()).filter(Boolean);
171
+ if (exceptions.includes("<local>")) parts.push("ExcludeSimpleHostnames : 1");
172
+ parts.push(`ExceptionsList : <array> {\n${exceptions.filter(value => value !== "<local>").map((value, index) => `${index} : ${value}`).join("\n")}\n}`);
173
+ return parts.join("\n");
174
+ }
@@ -5,11 +5,26 @@ import { predictionPaths, readPredictionSettings, writePredictionSettings, asser
5
5
  assertCodexClosed, installedPredictionApp, predictionAppMatches, readPredictionCertificate,
6
6
  createPredictionCertificate, updatePredictionTrust } from "./native-prediction-profile.mjs";
7
7
  import { retirePredictionIntegration } from "./prediction-retirement.mjs";
8
+ import { networkRouteSnapshot } from "./network-route.mjs";
9
+ import { withFileLock } from "./lock.mjs";
10
+ import { windowsSystemProxy, windowsProxySettings, windowsProxyText } from "./native-prediction-windows.mjs";
8
11
 
9
- function systemProxy(exec = execFileSync) {
12
+ function systemProxy(exec = execFileSync, { platform = process.platform, env = process.env } = {}) {
13
+ if (platform === "win32") return windowsSystemProxy({ exec, env });
10
14
  return exec("/usr/sbin/scutil", ["--proxy"], { encoding: "utf8", timeout: 2000, maxBuffer: 64 * 1024 });
11
15
  }
12
16
 
17
+ function predictionNetworkOptions(options) {
18
+ if (options.platform !== "win32") return { networkRoute: assertPredictionProxyCompatible({ env: options.env, systemProxy: systemProxy(options.exec, options) }) };
19
+ const settings = windowsProxySettings(options);
20
+ if (!settings.autoDetect && !settings.pac) return { networkRoute: assertPredictionProxyCompatible({ env: options.env, systemProxy: windowsProxyText(settings) }) };
21
+ const environment = assertPredictionProxyCompatible({ env: options.env });
22
+ if (environment.http || environment.https || environment.bypass.length) {
23
+ throw new Error("Windows automatic proxy and explicit proxy environment rules require separate routing; existing routes were preserved");
24
+ }
25
+ return { settings };
26
+ }
27
+
13
28
  function certificateDirectory(settings, paths) {
14
29
  if (!settings.credentialsDirectory) return paths.directory;
15
30
  const directory = path.resolve(settings.credentialsDirectory);
@@ -19,27 +34,44 @@ function certificateDirectory(settings, paths) {
19
34
  return directory;
20
35
  }
21
36
 
22
- export async function runPredictionCommand({ action = "status", env = process.env,
37
+ export async function runPredictionCommand(options = {}) {
38
+ if (!options.action || options.action === "status") return runPredictionCommandUnlocked(options);
39
+ if (!["darwin", "win32"].includes(options.platform || process.platform)) return runPredictionCommandUnlocked(options);
40
+ const { settings } = predictionPaths(options);
41
+ return withFileLock(`${settings}.lock`, () => runPredictionCommandUnlocked(options), { timeoutMs: 2000 });
42
+ }
43
+
44
+ async function runPredictionCommandUnlocked({ action = "status", env = process.env,
23
45
  platform = process.platform, output = console.log, resolveApp = installedPredictionApp,
24
- writeSettings = writePredictionSettings, ...options } = {}) {
25
- const opts = { ...options, env };
46
+ writeSettings = writePredictionSettings, runtimeSnapshot, ...options } = {}) {
47
+ const opts = { ...options, env, platform };
26
48
  const settings = readPredictionSettings(opts);
27
49
  if (action === "status") {
28
50
  output(`Native prediction preference: ${settings.enabled ? "on" : "off"} (default: off)`);
29
51
  output("Uses the conversation's model. No prediction MCP, Hook, or panel.");
30
52
  if (settings.enabled && !predictionAppMatches(settings.app)) output("Codex App changed; quit it and run ccdx prediction on to recheck compatibility.");
53
+ if (runtimeSnapshot) {
54
+ try {
55
+ const runtime = (await runtimeSnapshot())?.client_integrations?.prediction;
56
+ if (runtime) {
57
+ output(`Bridge: ${runtime.bridge}; client route: ${runtime.client_route}; visible candidate: ${runtime.candidate}`);
58
+ if (runtime.reason) output(runtime.reason);
59
+ for (const [name, event] of Object.entries(runtime.configuration || {})) output(`${name}: HTTP ${event.status}${event.modified ? " (local compatibility)" : " (upstream)"}`);
60
+ } else output("Runtime prediction state: unavailable; status is a saved preference, not proof of a visible suggestion.");
61
+ } catch { output("Runtime prediction state: unavailable; start ccdx and check again."); }
62
+ }
31
63
  return settings;
32
64
  }
33
65
  if (!["on", "off"].includes(action)) throw new Error("Prediction action must be on, off, or status");
34
- if (platform !== "darwin") throw new Error("Native prediction setup currently supports macOS only; no configuration changed");
35
- const paths = predictionPaths(opts);
66
+ if (!["darwin", "win32"].includes(platform)) throw new Error("Native prediction setup supports macOS and Windows only; no configuration changed");
67
+ let paths = predictionPaths({ ...opts, app: settings.app });
36
68
  if (action === "off") {
37
69
  // Disable the response overlay first, even when App-owned trust is busy.
38
70
  if (settings.enabled) writeSettings({ ...settings, enabled: false }, opts);
39
71
  if (settings.certificateHash && settings.store) {
40
72
  try {
41
- assertCodexClosed(options);
42
- const certificate = readPredictionCertificate(certificateDirectory(settings, paths), { allowExpired: true });
73
+ assertCodexClosed(opts);
74
+ const certificate = readPredictionCertificate(certificateDirectory(settings, paths), { ...opts, allowExpired: true });
43
75
  if (certificate.hash !== settings.certificateHash) throw new Error("Prediction certificate changed; trust cleanup was skipped");
44
76
  await updatePredictionTrust(settings.store, certificate, { remove: true });
45
77
  } catch (error) {
@@ -48,32 +80,38 @@ export async function runPredictionCommand({ action = "status", env = process.en
48
80
  }
49
81
  }
50
82
  const { store, certificateHash, app, ...disabled } = settings;
51
- if (store || certificateHash || app) writeSettings({ ...disabled, enabled: false }, opts);
83
+ // Retain the verified Windows profile binding, not its certificate trust.
84
+ // An earlier direct launch can have created a second initialized profile.
85
+ if (store || certificateHash || (app && platform !== "win32")) {
86
+ writeSettings({ ...disabled, enabled: false, ...(platform === "win32" && app ? { app } : {}) }, opts);
87
+ }
52
88
  try { retirePredictionIntegration(opts); }
53
89
  catch (error) { output(`Legacy prediction cleanup skipped: ${error.message}`); }
54
90
  output("Native predictions off. Restart Codex to clear cached predictions and its temporary route.");
55
91
  return { ...settings, enabled: false };
56
92
  }
57
- assertCodexClosed(options);
58
- assertPredictionProxyCompatible({ env, systemProxy: systemProxy(options.exec) });
59
- const app = resolveApp(options);
93
+ assertCodexClosed(opts);
94
+ predictionNetworkOptions(opts);
95
+ const app = resolveApp({ ...opts, ...(platform === "win32" && settings.app?.profile ? { preferredProfile: settings.app.profile } : {}) });
96
+ paths = predictionPaths({ ...opts, app });
60
97
  if (settings.store && settings.store !== paths.store) throw new Error("Codex profile changed; disable the previous profile before enabling another");
61
98
  let certificate, previous, generated = false;
62
99
  let credentialsDirectory = certificateDirectory(settings, paths);
63
- try { certificate = readPredictionCertificate(credentialsDirectory); }
100
+ try { certificate = readPredictionCertificate(credentialsDirectory, opts); }
64
101
  catch (error) {
65
102
  if (error.code !== "ENOENT" && !error.message.includes("needs renewal")) throw error;
66
103
  if (settings.certificateHash) {
67
- previous = readPredictionCertificate(credentialsDirectory, { allowExpired: true });
104
+ previous = readPredictionCertificate(credentialsDirectory, { ...opts, allowExpired: true });
68
105
  if (previous.hash !== settings.certificateHash) throw new Error("Existing prediction certificate changed; it was preserved");
69
106
  }
70
107
  fs.mkdirSync(paths.directory, { recursive: true, mode: 0o700 });
71
108
  credentialsDirectory = fs.mkdtempSync(path.join(paths.directory, "credentials-"));
72
109
  generated = true;
73
- try { certificate = createPredictionCertificate(credentialsDirectory, options); }
110
+ try { certificate = createPredictionCertificate(credentialsDirectory, opts); }
74
111
  catch (failure) { fs.rmSync(credentialsDirectory, { recursive: true, force: true }); throw failure; }
75
112
  }
76
- const next = { version: 1, enabled: true, app, store: paths.store, certificateHash: certificate.hash, credentialsDirectory };
113
+ const next = { version: 1, enabled: true, app, store: paths.store, certificateHash: certificate.hash, credentialsDirectory,
114
+ ...(Number.isInteger(settings.bridgePort) ? { bridgePort: settings.bridgePort } : {}) };
77
115
  let trustAdded = false;
78
116
  try {
79
117
  // Add the new trust before committing activation; retain the old record
@@ -100,47 +138,83 @@ export async function runPredictionCommand({ action = "status", env = process.en
100
138
  }
101
139
 
102
140
  export async function startNativePrediction({ env = process.env, platform = process.platform,
103
- warning = () => {}, ...options } = {}) {
104
- const opts = { ...options, env };
141
+ warning = () => {}, state, ...options } = {}) {
142
+ const opts = { ...options, env, platform };
105
143
  const settings = readPredictionSettings(opts);
144
+ state?.configure(settings.enabled);
106
145
  if (!settings.enabled) return null;
107
- if (platform !== "darwin") throw new Error("Native predictions were skipped: unsupported platform");
108
- assertPredictionProxyCompatible({ env, systemProxy: systemProxy(options.exec) });
146
+ if (!["darwin", "win32"].includes(platform)) throw new Error("Native predictions were skipped: unsupported platform");
147
+ const network = predictionNetworkOptions(opts);
148
+ let networkRoute = network.networkRoute;
149
+ if (platform === "win32" && settings.bridgePort !== undefined
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");
152
+ }
109
153
  if (!predictionAppMatches(settings.app)) throw new Error("Codex App changed; run ccdx prediction on after quitting it to recheck compatibility");
110
- const paths = predictionPaths(opts);
154
+ const paths = predictionPaths({ ...opts, app: settings.app });
111
155
  if (settings.store !== paths.store || !fs.existsSync(paths.store)) throw new Error("Prediction profile trust is unavailable; run ccdx prediction on after quitting Codex");
112
- const certificate = readPredictionCertificate(certificateDirectory(settings, paths));
156
+ const certificate = readPredictionCertificate(certificateDirectory(settings, paths), opts);
113
157
  if (certificate.hash !== settings.certificateHash) throw new Error("Prediction certificate changed; setup must be checked again");
114
- const [{ startPredictionTransport }, { applyNativePredictionOverlay, normalizeStatsigRequest }] = await Promise.all([
158
+ const [{ startPredictionTransport }, { applyNativePredictionOverlay, normalizeStatsigRequest }, { createProxyAgent }] = await Promise.all([
115
159
  import("./native-prediction-transport.mjs"), import("./native-prediction-overlay.mjs"),
160
+ import("./proxy-tunnel.mjs"),
116
161
  ]);
117
162
  // An in-memory switch is refreshed independently of request bodies and never
118
163
  // touches the model path. A failed read turns off this optional overlay.
119
164
  let enabled = true;
120
165
  const timer = setInterval(() => {
121
- try { enabled = readPredictionSettings(opts).enabled; }
166
+ try { enabled = readPredictionSettings(opts).enabled; state?.configure(enabled); }
122
167
  catch { enabled = false; }
123
168
  }, 1000);
124
169
  timer.unref();
125
170
  let transport;
171
+ let windowsNetwork;
126
172
  try {
173
+ if (network.settings) {
174
+ const { startWindowsPredictionNetwork } = await import("./windows-prediction-network.mjs");
175
+ windowsNetwork = await startWindowsPredictionNetwork({ settings: network.settings, env, onFailure(error) {
176
+ clearInterval(timer);state?.unavailable(error);void transport?.close();
177
+ } });
178
+ // Automatic detection enabled does not prove a company PAC exists.
179
+ // A native "not found" result retains the configured static/direct route.
180
+ if (windowsNetwork.script === null) {
181
+ windowsNetwork.close();windowsNetwork = null;
182
+ networkRoute = assertPredictionProxyCompatible({ env, systemProxy: windowsProxyText({ ...network.settings, autoDetect: false, pac: null }) });
183
+ }
184
+ }
127
185
  transport = await startPredictionTransport({ ...certificate, enabled: () => enabled,
186
+ listenPort: platform === "win32" ? settings.bridgePort || 0 : 0,
187
+ networkRoute, agent: networkRoute?.https ? createProxyAgent(networkRoute) : undefined,
188
+ ...(windowsNetwork ? { requestImpl: windowsNetwork.requestImpl, pacImpl: windowsNetwork.pac } : {}),
189
+ onEvent: (event) => state?.event(event),
128
190
  overlay: ({ host, pathname, status, body, enabled }) => {
129
191
  const result = applyNativePredictionOverlay({ hostname: host, pathname, statusCode: status, body, enabled });
130
- return result.changed ? { body: result.body, status: result.statusCode } : null;
192
+ return result.changed ? { body: result.body, status: result.statusCode } : { official: result.official };
131
193
  },
132
194
  normalizeRequest: (parsed) => {
133
195
  const result = normalizeStatsigRequest({ hostname: "ab.chatgpt.com", pathname: "/v1/initialize", body: JSON.stringify(parsed), enabled });
134
196
  return result.changed ? JSON.parse(result.body) : parsed;
135
197
  },
136
198
  });
137
- } catch (error) { clearInterval(timer); throw error; }
199
+ if (platform === "win32" && settings.bridgePort === undefined) {
200
+ await withFileLock(`${paths.settings}.lock`, () => {
201
+ const current = readPredictionSettings(opts);
202
+ if (!current.enabled || current.certificateHash !== settings.certificateHash || current.store !== settings.store
203
+ || (current.bridgePort !== undefined && current.bridgePort !== transport.port)) {
204
+ throw new Error("Prediction setup changed during startup; no saved route was replaced");
205
+ }
206
+ writePredictionSettings({ ...current, bridgePort: transport.port }, opts);
207
+ }, { timeoutMs: 2000 });
208
+ }
209
+ } catch (error) { clearInterval(timer);await transport?.close();windowsNetwork?.close();throw error; }
210
+ state?.running(windowsNetwork ? { source: "system", type: "auto", bypass_rules: null, proxy_credentials: false } : networkRouteSnapshot(networkRoute));
138
211
  warning("Native prediction bridge enabled; only the two configuration hosts use its App-only route.");
139
212
  warning("If Codex is already running, quit it and run ccdx again to apply the route.");
140
213
  return {
141
214
  app: settings.app.app,
215
+ ...(platform === "win32" ? { profile: paths.profile } : {}),
142
216
  pacUrl: transport.pacUrl,
143
- args: [`--proxy-pac-url=${transport.pacUrl}`],
144
- async close() { clearInterval(timer); await transport.close(); },
217
+ args: [...(platform === "win32" ? [`--user-data-dir=${paths.profile}`] : []), `--proxy-pac-url=${transport.pacUrl}`],
218
+ async close() { clearInterval(timer); await transport.close(); windowsNetwork?.close(); state?.stopped(); },
145
219
  };
146
220
  }