codex-copilot-dx 0.9.25 → 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.
- package/README.md +7 -7
- package/bin/cli.mjs +5 -3
- package/docs/ARCHITECTURE.md +21 -2
- package/docs/README.md +2 -0
- package/docs/REFERENCE.md +61 -4
- package/package.json +1 -1
- package/src/cli-options.mjs +1 -1
- package/src/copilot-responses-compat.mjs +30 -2
- package/src/copilot-responses-policy.mjs +10 -1
- package/src/dashboard/index.html +18 -16
- package/src/dashboard/language.js +1 -0
- package/src/dashboard/ui.css +2 -0
- package/src/dashboard/ui.js +1 -0
- package/src/launcher.mjs +50 -2
- package/src/native-prediction-profile.mjs +42 -16
- package/src/native-prediction-transport.mjs +8 -6
- package/src/native-prediction-windows.mjs +174 -0
- package/src/native-prediction.mjs +75 -25
- package/src/responses-proxy.mjs +13 -3
- package/src/responses-request.mjs +30 -0
- package/src/windows-prediction-network.cs +154 -0
- package/src/windows-prediction-network.mjs +123 -0
|
@@ -7,10 +7,18 @@ import { atomicWriteFileSync } from "./atomic-file.mjs";
|
|
|
7
7
|
import { userSettingsPath } from "./user-settings.mjs";
|
|
8
8
|
import { resolveNetworkRoute } from "./network-route.mjs";
|
|
9
9
|
import { codexPaths } from "./codex-paths.mjs";
|
|
10
|
+
import { assertWindowsCodexClosed, installedWindowsPredictionApp, windowsPredictionProfile,
|
|
11
|
+
windowsPredictionOpenSSL, windowsPrivatePredictionPath } from "./native-prediction-windows.mjs";
|
|
10
12
|
|
|
11
|
-
export function predictionPaths({ env = process.env, home = os.homedir() } = {}) {
|
|
13
|
+
export function predictionPaths({ env = process.env, home = os.homedir(), platform = process.platform, app } = {}) {
|
|
12
14
|
const directory = path.join(path.dirname(userSettingsPath({ env, home })), "native-prediction");
|
|
13
|
-
|
|
15
|
+
let { profile, certificateStore } = codexPaths({ env, home });
|
|
16
|
+
if (platform === "win32") {
|
|
17
|
+
const override = String(env.CODEX_ELECTRON_USER_DATA_PATH || "").trim();
|
|
18
|
+
profile = override ? path.resolve(override)
|
|
19
|
+
: app?.profile || path.join(env.APPDATA || path.join(home, "AppData", "Roaming"), "Codex");
|
|
20
|
+
certificateStore = path.join(profile, "Default", "ServerCertificate");
|
|
21
|
+
}
|
|
14
22
|
return { directory, settings: path.join(directory, "settings.json"), profile,
|
|
15
23
|
store: certificateStore };
|
|
16
24
|
}
|
|
@@ -35,7 +43,8 @@ export function assertPredictionProxyCompatible({ env = process.env, systemProxy
|
|
|
35
43
|
return resolveNetworkRoute({ env, systemProxy });
|
|
36
44
|
}
|
|
37
45
|
|
|
38
|
-
export function assertCodexClosed({ exec = execFileSync } = {}) {
|
|
46
|
+
export function assertCodexClosed({ exec = execFileSync, platform = process.platform, ...options } = {}) {
|
|
47
|
+
if (platform === "win32") return assertWindowsCodexClosed({ ...options, exec });
|
|
39
48
|
for (const name of ["ChatGPT", "Codex"]) {
|
|
40
49
|
try {
|
|
41
50
|
exec("/usr/bin/pgrep", ["-x", name], { stdio: "pipe", timeout: 2000 });
|
|
@@ -47,9 +56,11 @@ export function assertCodexClosed({ exec = execFileSync } = {}) {
|
|
|
47
56
|
}
|
|
48
57
|
}
|
|
49
58
|
|
|
50
|
-
export function installedPredictionApp({ exec = execFileSync } = {}) {
|
|
51
|
-
|
|
52
|
-
|
|
59
|
+
export function installedPredictionApp({ exec = execFileSync, platform = process.platform, ...options } = {}) {
|
|
60
|
+
const candidates = platform === "win32" ? [installedWindowsPredictionApp({ ...options, exec })]
|
|
61
|
+
: ["/Applications/ChatGPT.app", "/Applications/Codex.app"].map(app => ({ app, archive: path.join(app, "Contents", "Resources", "app.asar") }));
|
|
62
|
+
for (const candidate of candidates) {
|
|
63
|
+
const { app, archive } = candidate;
|
|
53
64
|
if (!fs.existsSync(archive)) continue;
|
|
54
65
|
// Check only during explicit setup; startup uses the cheap identity check.
|
|
55
66
|
const fd = fs.openSync(archive, "r");
|
|
@@ -71,8 +82,13 @@ export function installedPredictionApp({ exec = execFileSync } = {}) {
|
|
|
71
82
|
const rendererBytes = Buffer.alloc(renderer.size);
|
|
72
83
|
fs.readSync(fd, rendererBytes, 0, rendererBytes.length, 8 + prefix.readUInt32LE(4) + Number(renderer.offset));
|
|
73
84
|
if (!rendererBytes.includes(Buffer.from("4290031608"))) continue;
|
|
74
|
-
exec("/usr/bin/codesign", ["--verify", "--deep", "--strict", app], { stdio: "pipe", timeout: 15_000 });
|
|
85
|
+
if (platform !== "win32") exec("/usr/bin/codesign", ["--verify", "--deep", "--strict", app], { stdio: "pipe", timeout: 15_000 });
|
|
75
86
|
const stat = fs.statSync(archive);
|
|
87
|
+
if (platform === "win32") {
|
|
88
|
+
const executable = fs.statSync(app);
|
|
89
|
+
return { ...candidate, profile: windowsPredictionProfile({ app: candidate, env: options.env, preferredProfile: options.preferredProfile }),
|
|
90
|
+
size: stat.size, mtimeMs: stat.mtimeMs, executableSize: executable.size, executableMtimeMs: executable.mtimeMs };
|
|
91
|
+
}
|
|
76
92
|
return { app, archive, size: stat.size, mtimeMs: stat.mtimeMs };
|
|
77
93
|
} finally { fs.closeSync(fd); }
|
|
78
94
|
}
|
|
@@ -80,24 +96,33 @@ export function installedPredictionApp({ exec = execFileSync } = {}) {
|
|
|
80
96
|
}
|
|
81
97
|
|
|
82
98
|
export function predictionAppMatches(app) {
|
|
83
|
-
try {
|
|
99
|
+
try {
|
|
100
|
+
const stat = fs.statSync(app.archive);
|
|
101
|
+
if (app.executableSize !== undefined) {
|
|
102
|
+
const executable = fs.statSync(app.app);
|
|
103
|
+
if (executable.size !== app.executableSize || executable.mtimeMs !== app.executableMtimeMs) return false;
|
|
104
|
+
}
|
|
105
|
+
return stat.size === app.size && stat.mtimeMs === app.mtimeMs;
|
|
106
|
+
}
|
|
84
107
|
catch { return false; }
|
|
85
108
|
}
|
|
86
109
|
|
|
87
|
-
function privateDirectory(directory) {
|
|
110
|
+
function privateDirectory(directory, { platform = process.platform, ...options } = {}) {
|
|
88
111
|
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
89
112
|
const stat = fs.lstatSync(directory);
|
|
90
|
-
if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.mode & 0o077)) {
|
|
113
|
+
if (!stat.isDirectory() || stat.isSymbolicLink() || (platform !== "win32" && (stat.mode & 0o077))) {
|
|
91
114
|
throw new Error("Prediction key directory must be private and must not be a symlink");
|
|
92
115
|
}
|
|
116
|
+
if (platform === "win32") windowsPrivatePredictionPath(directory, { ...options, create: fs.readdirSync(directory).length === 0 });
|
|
93
117
|
}
|
|
94
118
|
|
|
95
|
-
export function readPredictionCertificate(directory, { allowExpired = false } = {}) {
|
|
119
|
+
export function readPredictionCertificate(directory, { allowExpired = false, platform = process.platform, ...options } = {}) {
|
|
96
120
|
const cert = fs.readFileSync(path.join(directory, "bridge.pem"));
|
|
97
121
|
const ca = new X509Certificate(fs.readFileSync(path.join(directory, "ca.pem")));
|
|
98
122
|
const keyFile = path.join(directory, "bridge.key");
|
|
99
123
|
const info = fs.lstatSync(keyFile);
|
|
100
|
-
if (!info.isFile() || info.isSymbolicLink() || (info.mode & 0o077)) throw new Error("Prediction key is not private");
|
|
124
|
+
if (!info.isFile() || info.isSymbolicLink() || (platform !== "win32" && (info.mode & 0o077))) throw new Error("Prediction key is not private");
|
|
125
|
+
if (platform === "win32") windowsPrivatePredictionPath(keyFile, options);
|
|
101
126
|
const key = fs.readFileSync(keyFile);
|
|
102
127
|
const x509 = new X509Certificate(cert);
|
|
103
128
|
const publicKey = createPublicKey(createPrivateKey(key)).export({ type: "spki", format: "der" });
|
|
@@ -109,8 +134,9 @@ export function readPredictionCertificate(directory, { allowExpired = false } =
|
|
|
109
134
|
return { cert, key, ca: ca.toString(), hash: createHash("sha256").update(ca.raw).digest("hex").toUpperCase(), der: ca.raw };
|
|
110
135
|
}
|
|
111
136
|
|
|
112
|
-
export function createPredictionCertificate(directory, { exec = execFileSync } = {}) {
|
|
113
|
-
privateDirectory(directory);
|
|
137
|
+
export function createPredictionCertificate(directory, { exec = execFileSync, platform = process.platform, ...options } = {}) {
|
|
138
|
+
privateDirectory(directory, { ...options, exec, platform });
|
|
139
|
+
const openssl = platform === "win32" ? windowsPredictionOpenSSL({ ...options, exec }) : "/usr/bin/openssl";
|
|
114
140
|
const temporary = fs.mkdtempSync(path.join(directory, "certificate-"));
|
|
115
141
|
try {
|
|
116
142
|
const config = `[req]\nprompt=no\ndistinguished_name=dn\nx509_extensions=ext\n[dn]\nCN=CCDX native prediction local bridge\n[ext]\nbasicConstraints=critical,CA:TRUE,pathlen:0\nkeyUsage=critical,keyCertSign,digitalSignature\nextendedKeyUsage=serverAuth\nsubjectAltName=DNS:chatgpt.com,DNS:ab.chatgpt.com\nnameConstraints=critical,permitted;DNS:chatgpt.com\n`;
|
|
@@ -118,7 +144,7 @@ export function createPredictionCertificate(directory, { exec = execFileSync } =
|
|
|
118
144
|
atomicWriteFileSync(configFile, config);
|
|
119
145
|
const certFile = path.join(temporary, "cert.pem"), keyFile = path.join(temporary, "key.pem");
|
|
120
146
|
const caFile = path.join(temporary, "ca.pem"), caKey = path.join(temporary, "ca.key");
|
|
121
|
-
const run = (args) => exec(
|
|
147
|
+
const run = (args) => exec(openssl, args, { stdio: "pipe", timeout: 15_000, windowsHide: true });
|
|
122
148
|
run(["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "90", "-config", configFile, "-out", caFile, "-keyout", caKey]);
|
|
123
149
|
const csr = path.join(temporary, "leaf.csr"), extensions = path.join(temporary, "leaf.cnf");
|
|
124
150
|
atomicWriteFileSync(extensions, "basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\nsubjectAltName=DNS:chatgpt.com,DNS:ab.chatgpt.com\n");
|
|
@@ -127,7 +153,7 @@ export function createPredictionCertificate(directory, { exec = execFileSync } =
|
|
|
127
153
|
atomicWriteFileSync(path.join(directory, "bridge.key"), fs.readFileSync(keyFile), { preserveMode: false });
|
|
128
154
|
atomicWriteFileSync(path.join(directory, "bridge.pem"), fs.readFileSync(certFile), { preserveMode: false });
|
|
129
155
|
atomicWriteFileSync(path.join(directory, "ca.pem"), fs.readFileSync(caFile), { preserveMode: false });
|
|
130
|
-
return readPredictionCertificate(directory);
|
|
156
|
+
return readPredictionCertificate(directory, { ...options, exec, platform });
|
|
131
157
|
} finally { fs.rmSync(temporary, { recursive: true, force: true }); }
|
|
132
158
|
}
|
|
133
159
|
|
|
@@ -44,10 +44,10 @@ async function decode(bytes, encoding, limit) {
|
|
|
44
44
|
return decoders[encoding](bytes, { maxOutputLength: limit });
|
|
45
45
|
}
|
|
46
46
|
|
|
47
|
-
function listen(server) {
|
|
47
|
+
function listen(server, port = 0) {
|
|
48
48
|
return new Promise((resolve, reject) => {
|
|
49
49
|
server.once("error", reject);
|
|
50
|
-
server.listen(
|
|
50
|
+
server.listen(port, "127.0.0.1", () => {
|
|
51
51
|
server.removeListener("error", reject);
|
|
52
52
|
resolve(server.address().port);
|
|
53
53
|
});
|
|
@@ -59,8 +59,8 @@ function listen(server) {
|
|
|
59
59
|
export async function startPredictionTransport({
|
|
60
60
|
key, cert, overlay, normalizeRequest = (value) => value,
|
|
61
61
|
enabled = () => true, requestImpl = https.request,
|
|
62
|
-
agent, networkRoute, onEvent = () => {},
|
|
63
|
-
timeoutMs = 30_000, maxConnections = 128,
|
|
62
|
+
agent, networkRoute, pacImpl, onEvent = () => {},
|
|
63
|
+
timeoutMs = 30_000, maxConnections = 128, listenPort = 0,
|
|
64
64
|
}) {
|
|
65
65
|
const sockets = new Set();
|
|
66
66
|
const upstreams = new Set();
|
|
@@ -222,7 +222,7 @@ export async function startPredictionTransport({
|
|
|
222
222
|
if (req.method === "GET" && req.url === "/proxy.pac" && !req.headers.origin
|
|
223
223
|
&& ["127.0.0.1", "localhost"].includes(String(req.headers.host || "").split(":")[0])) {
|
|
224
224
|
res.writeHead(200, { "Content-Type": "application/x-ns-proxy-autoconfig", "Cache-Control": "no-store" });
|
|
225
|
-
res.end(predictionPac(proxy.address().port, networkRoute)); return;
|
|
225
|
+
res.end(pacImpl ? pacImpl(proxy.address().port) : predictionPac(proxy.address().port, networkRoute)); return;
|
|
226
226
|
}
|
|
227
227
|
res.writeHead(403); res.end();
|
|
228
228
|
});
|
|
@@ -240,7 +240,9 @@ export async function startPredictionTransport({
|
|
|
240
240
|
gateway.emit("connection", socket);
|
|
241
241
|
});
|
|
242
242
|
proxy.on("clientError", (_error, socket) => socket.destroy());
|
|
243
|
-
|
|
243
|
+
let port;
|
|
244
|
+
try { port = await listen(proxy, listenPort); }
|
|
245
|
+
catch (error) { agent?.destroy();gateway.close();throw error; }
|
|
244
246
|
return {
|
|
245
247
|
port, pacUrl: `http://127.0.0.1:${port}/proxy.pac`,
|
|
246
248
|
async 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
|
+
}
|
|
@@ -7,11 +7,24 @@ import { predictionPaths, readPredictionSettings, writePredictionSettings, asser
|
|
|
7
7
|
import { retirePredictionIntegration } from "./prediction-retirement.mjs";
|
|
8
8
|
import { networkRouteSnapshot } from "./network-route.mjs";
|
|
9
9
|
import { withFileLock } from "./lock.mjs";
|
|
10
|
+
import { windowsSystemProxy, windowsProxySettings, windowsProxyText } from "./native-prediction-windows.mjs";
|
|
10
11
|
|
|
11
|
-
function systemProxy(exec = execFileSync) {
|
|
12
|
+
function systemProxy(exec = execFileSync, { platform = process.platform, env = process.env } = {}) {
|
|
13
|
+
if (platform === "win32") return windowsSystemProxy({ exec, env });
|
|
12
14
|
return exec("/usr/sbin/scutil", ["--proxy"], { encoding: "utf8", timeout: 2000, maxBuffer: 64 * 1024 });
|
|
13
15
|
}
|
|
14
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
|
+
|
|
15
28
|
function certificateDirectory(settings, paths) {
|
|
16
29
|
if (!settings.credentialsDirectory) return paths.directory;
|
|
17
30
|
const directory = path.resolve(settings.credentialsDirectory);
|
|
@@ -23,7 +36,7 @@ function certificateDirectory(settings, paths) {
|
|
|
23
36
|
|
|
24
37
|
export async function runPredictionCommand(options = {}) {
|
|
25
38
|
if (!options.action || options.action === "status") return runPredictionCommandUnlocked(options);
|
|
26
|
-
if ((options.platform || process.platform)
|
|
39
|
+
if (!["darwin", "win32"].includes(options.platform || process.platform)) return runPredictionCommandUnlocked(options);
|
|
27
40
|
const { settings } = predictionPaths(options);
|
|
28
41
|
return withFileLock(`${settings}.lock`, () => runPredictionCommandUnlocked(options), { timeoutMs: 2000 });
|
|
29
42
|
}
|
|
@@ -31,7 +44,7 @@ export async function runPredictionCommand(options = {}) {
|
|
|
31
44
|
async function runPredictionCommandUnlocked({ action = "status", env = process.env,
|
|
32
45
|
platform = process.platform, output = console.log, resolveApp = installedPredictionApp,
|
|
33
46
|
writeSettings = writePredictionSettings, runtimeSnapshot, ...options } = {}) {
|
|
34
|
-
const opts = { ...options, env };
|
|
47
|
+
const opts = { ...options, env, platform };
|
|
35
48
|
const settings = readPredictionSettings(opts);
|
|
36
49
|
if (action === "status") {
|
|
37
50
|
output(`Native prediction preference: ${settings.enabled ? "on" : "off"} (default: off)`);
|
|
@@ -50,15 +63,15 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
50
63
|
return settings;
|
|
51
64
|
}
|
|
52
65
|
if (!["on", "off"].includes(action)) throw new Error("Prediction action must be on, off, or status");
|
|
53
|
-
if (
|
|
54
|
-
|
|
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 });
|
|
55
68
|
if (action === "off") {
|
|
56
69
|
// Disable the response overlay first, even when App-owned trust is busy.
|
|
57
70
|
if (settings.enabled) writeSettings({ ...settings, enabled: false }, opts);
|
|
58
71
|
if (settings.certificateHash && settings.store) {
|
|
59
72
|
try {
|
|
60
|
-
assertCodexClosed(
|
|
61
|
-
const certificate = readPredictionCertificate(certificateDirectory(settings, paths), { allowExpired: true });
|
|
73
|
+
assertCodexClosed(opts);
|
|
74
|
+
const certificate = readPredictionCertificate(certificateDirectory(settings, paths), { ...opts, allowExpired: true });
|
|
62
75
|
if (certificate.hash !== settings.certificateHash) throw new Error("Prediction certificate changed; trust cleanup was skipped");
|
|
63
76
|
await updatePredictionTrust(settings.store, certificate, { remove: true });
|
|
64
77
|
} catch (error) {
|
|
@@ -67,32 +80,38 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
67
80
|
}
|
|
68
81
|
}
|
|
69
82
|
const { store, certificateHash, app, ...disabled } = settings;
|
|
70
|
-
|
|
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
|
+
}
|
|
71
88
|
try { retirePredictionIntegration(opts); }
|
|
72
89
|
catch (error) { output(`Legacy prediction cleanup skipped: ${error.message}`); }
|
|
73
90
|
output("Native predictions off. Restart Codex to clear cached predictions and its temporary route.");
|
|
74
91
|
return { ...settings, enabled: false };
|
|
75
92
|
}
|
|
76
|
-
assertCodexClosed(
|
|
77
|
-
|
|
78
|
-
const app = resolveApp(
|
|
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 });
|
|
79
97
|
if (settings.store && settings.store !== paths.store) throw new Error("Codex profile changed; disable the previous profile before enabling another");
|
|
80
98
|
let certificate, previous, generated = false;
|
|
81
99
|
let credentialsDirectory = certificateDirectory(settings, paths);
|
|
82
|
-
try { certificate = readPredictionCertificate(credentialsDirectory); }
|
|
100
|
+
try { certificate = readPredictionCertificate(credentialsDirectory, opts); }
|
|
83
101
|
catch (error) {
|
|
84
102
|
if (error.code !== "ENOENT" && !error.message.includes("needs renewal")) throw error;
|
|
85
103
|
if (settings.certificateHash) {
|
|
86
|
-
previous = readPredictionCertificate(credentialsDirectory, { allowExpired: true });
|
|
104
|
+
previous = readPredictionCertificate(credentialsDirectory, { ...opts, allowExpired: true });
|
|
87
105
|
if (previous.hash !== settings.certificateHash) throw new Error("Existing prediction certificate changed; it was preserved");
|
|
88
106
|
}
|
|
89
107
|
fs.mkdirSync(paths.directory, { recursive: true, mode: 0o700 });
|
|
90
108
|
credentialsDirectory = fs.mkdtempSync(path.join(paths.directory, "credentials-"));
|
|
91
109
|
generated = true;
|
|
92
|
-
try { certificate = createPredictionCertificate(credentialsDirectory,
|
|
110
|
+
try { certificate = createPredictionCertificate(credentialsDirectory, opts); }
|
|
93
111
|
catch (failure) { fs.rmSync(credentialsDirectory, { recursive: true, force: true }); throw failure; }
|
|
94
112
|
}
|
|
95
|
-
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 } : {}) };
|
|
96
115
|
let trustAdded = false;
|
|
97
116
|
try {
|
|
98
117
|
// Add the new trust before committing activation; retain the old record
|
|
@@ -120,16 +139,21 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
120
139
|
|
|
121
140
|
export async function startNativePrediction({ env = process.env, platform = process.platform,
|
|
122
141
|
warning = () => {}, state, ...options } = {}) {
|
|
123
|
-
const opts = { ...options, env };
|
|
142
|
+
const opts = { ...options, env, platform };
|
|
124
143
|
const settings = readPredictionSettings(opts);
|
|
125
144
|
state?.configure(settings.enabled);
|
|
126
145
|
if (!settings.enabled) return null;
|
|
127
|
-
if (
|
|
128
|
-
const
|
|
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
|
+
}
|
|
129
153
|
if (!predictionAppMatches(settings.app)) throw new Error("Codex App changed; run ccdx prediction on after quitting it to recheck compatibility");
|
|
130
|
-
const paths = predictionPaths(opts);
|
|
154
|
+
const paths = predictionPaths({ ...opts, app: settings.app });
|
|
131
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");
|
|
132
|
-
const certificate = readPredictionCertificate(certificateDirectory(settings, paths));
|
|
156
|
+
const certificate = readPredictionCertificate(certificateDirectory(settings, paths), opts);
|
|
133
157
|
if (certificate.hash !== settings.certificateHash) throw new Error("Prediction certificate changed; setup must be checked again");
|
|
134
158
|
const [{ startPredictionTransport }, { applyNativePredictionOverlay, normalizeStatsigRequest }, { createProxyAgent }] = await Promise.all([
|
|
135
159
|
import("./native-prediction-transport.mjs"), import("./native-prediction-overlay.mjs"),
|
|
@@ -144,9 +168,24 @@ export async function startNativePrediction({ env = process.env, platform = proc
|
|
|
144
168
|
}, 1000);
|
|
145
169
|
timer.unref();
|
|
146
170
|
let transport;
|
|
171
|
+
let windowsNetwork;
|
|
147
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
|
+
}
|
|
148
185
|
transport = await startPredictionTransport({ ...certificate, enabled: () => enabled,
|
|
149
|
-
|
|
186
|
+
listenPort: platform === "win32" ? settings.bridgePort || 0 : 0,
|
|
187
|
+
networkRoute, agent: networkRoute?.https ? createProxyAgent(networkRoute) : undefined,
|
|
188
|
+
...(windowsNetwork ? { requestImpl: windowsNetwork.requestImpl, pacImpl: windowsNetwork.pac } : {}),
|
|
150
189
|
onEvent: (event) => state?.event(event),
|
|
151
190
|
overlay: ({ host, pathname, status, body, enabled }) => {
|
|
152
191
|
const result = applyNativePredictionOverlay({ hostname: host, pathname, statusCode: status, body, enabled });
|
|
@@ -157,14 +196,25 @@ export async function startNativePrediction({ env = process.env, platform = proc
|
|
|
157
196
|
return result.changed ? JSON.parse(result.body) : parsed;
|
|
158
197
|
},
|
|
159
198
|
});
|
|
160
|
-
|
|
161
|
-
|
|
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));
|
|
162
211
|
warning("Native prediction bridge enabled; only the two configuration hosts use its App-only route.");
|
|
163
212
|
warning("If Codex is already running, quit it and run ccdx again to apply the route.");
|
|
164
213
|
return {
|
|
165
214
|
app: settings.app.app,
|
|
215
|
+
...(platform === "win32" ? { profile: paths.profile } : {}),
|
|
166
216
|
pacUrl: transport.pacUrl,
|
|
167
|
-
args: [`--proxy-pac-url=${transport.pacUrl}`],
|
|
168
|
-
async close() { clearInterval(timer); await transport.close(); state?.stopped(); },
|
|
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(); },
|
|
169
219
|
};
|
|
170
220
|
}
|
package/src/responses-proxy.mjs
CHANGED
|
@@ -352,8 +352,9 @@ async function selectStreamFailureRetry(reqContext, failure, usedRetryPolicies,
|
|
|
352
352
|
retry: retry ? { ...retry, releasePreparation: preparation?.release } : null,
|
|
353
353
|
retrySkipped: null,
|
|
354
354
|
};
|
|
355
|
-
} catch {
|
|
355
|
+
} catch (error) {
|
|
356
356
|
options.assertPrepareActive?.();
|
|
357
|
+
if (error.code === "ccdx_history_rebuild_required") throw error;
|
|
357
358
|
return { retry: null, retrySkipped: "history_unavailable" };
|
|
358
359
|
} finally {
|
|
359
360
|
if (!keepReservation) preparation?.release();
|
|
@@ -363,6 +364,7 @@ async function selectStreamFailureRetry(reqContext, failure, usedRetryPolicies,
|
|
|
363
364
|
function recordResponseFailure(options, reqContext, resp, failure, {
|
|
364
365
|
retry,
|
|
365
366
|
retrySkipped,
|
|
367
|
+
recovery,
|
|
366
368
|
} = {}) {
|
|
367
369
|
if (!failure) return;
|
|
368
370
|
const details = responseFailureDetails(failure.event, failure.eventType, {
|
|
@@ -372,6 +374,8 @@ function recordResponseFailure(options, reqContext, resp, failure, {
|
|
|
372
374
|
retryPolicy: retry?.policyId,
|
|
373
375
|
retrySkipped,
|
|
374
376
|
});
|
|
377
|
+
if (retry?.recovery) details.recovery = retry.recovery;
|
|
378
|
+
else if (recovery) details.recovery = recovery;
|
|
375
379
|
options.responseFailures?.record?.(details);
|
|
376
380
|
console.warn(status("warn", formatResponseFailureLog(details)));
|
|
377
381
|
}
|
|
@@ -465,7 +469,10 @@ async function proxyStreamingResponses(opened, res, upstream, options) {
|
|
|
465
469
|
try {
|
|
466
470
|
selected = await selectStreamFailureRetry(reqContext, streamState.failure, usedRetryPolicies, options);
|
|
467
471
|
} catch (error) {
|
|
468
|
-
recordResponseFailure(options, reqContext, resp, streamState.failure, {
|
|
472
|
+
recordResponseFailure(options, reqContext, resp, streamState.failure, {
|
|
473
|
+
retrySkipped: error.code === "ccdx_history_rebuild_required" ? error.code : "retry_preparation_failed",
|
|
474
|
+
recovery: error.jsonBody?.error?.recovery,
|
|
475
|
+
});
|
|
469
476
|
throw error;
|
|
470
477
|
}
|
|
471
478
|
retry = selected?.retry || null;
|
|
@@ -585,7 +592,10 @@ export async function proxyCopilotResponses(reqContext, req, res, upstream = cop
|
|
|
585
592
|
try {
|
|
586
593
|
selected = await selectStreamFailureRetry(reqContext, failure, usedRetryPolicies, options);
|
|
587
594
|
} catch (error) {
|
|
588
|
-
recordResponseFailure(options, reqContext, resp, failure, {
|
|
595
|
+
recordResponseFailure(options, reqContext, resp, failure, {
|
|
596
|
+
retrySkipped: error.code === "ccdx_history_rebuild_required" ? error.code : "retry_preparation_failed",
|
|
597
|
+
recovery: error.jsonBody?.error?.recovery,
|
|
598
|
+
});
|
|
589
599
|
throw error;
|
|
590
600
|
}
|
|
591
601
|
const retry = selected?.retry || null;
|
|
@@ -192,6 +192,36 @@ export function hasEncryptedResponseState(value) {
|
|
|
192
192
|
return responseValueHasOpaqueState(value);
|
|
193
193
|
}
|
|
194
194
|
|
|
195
|
+
// Ownership rejection is ambiguous: compaction may be the only surviving
|
|
196
|
+
// memory of earlier turns. Never infer that nearby plaintext replaces it.
|
|
197
|
+
export function sanitizeConnectionOwnedReasoningRequest(reqContext) {
|
|
198
|
+
const input = reqContext.body?.input;
|
|
199
|
+
if (!Array.isArray(input)) return null;
|
|
200
|
+
const compactions = input.filter(item => item?.type === "compaction" && item.encrypted_content);
|
|
201
|
+
const reasoning = input.filter(item => item?.type === "reasoning" && item.encrypted_content);
|
|
202
|
+
if (compactions.length) {
|
|
203
|
+
const message = "Saved encrypted compaction is unavailable on this connection. Restore the full plaintext conversation history before retrying; CCDX has preserved it and will not discard earlier context.";
|
|
204
|
+
throw Object.assign(new Error(message), { statusCode: 400, code: "ccdx_history_rebuild_required",
|
|
205
|
+
jsonBody: { error: { type: "invalid_request_error", code: "ccdx_history_rebuild_required", message,
|
|
206
|
+
recoverable: true, recovery: { action: "restore_plaintext_history", compaction_items: compactions.length, reasoning_items: reasoning.length } } } });
|
|
207
|
+
}
|
|
208
|
+
if (!reasoning.length) return null;
|
|
209
|
+
// Restrict this recovery to unavailable reasoning; visible messages and
|
|
210
|
+
// opaque tool results are left untouched, including call/result pairing.
|
|
211
|
+
const keep = item => !(item?.type === "reasoning" && item.encrypted_content);
|
|
212
|
+
const body = cloneJson(reqContext.body);
|
|
213
|
+
body.input = body.input.filter(keep);
|
|
214
|
+
const historicalRemoved = Number.isFinite(reqContext.currentInputStart)
|
|
215
|
+
? input.slice(0, reqContext.currentInputStart).filter(item => !keep(item)).length : 0;
|
|
216
|
+
const historyInputItems = Array.isArray(reqContext.historyInputItems)
|
|
217
|
+
? cloneJson(reqContext.historyInputItems.filter(keep))
|
|
218
|
+
: reqContext.historyInputItems;
|
|
219
|
+
return { ...reqContext, body, inputItems: body.input, historyInputItems,
|
|
220
|
+
currentInputStart: Number.isFinite(reqContext.currentInputStart) ? reqContext.currentInputStart - historicalRemoved : reqContext.currentInputStart,
|
|
221
|
+
...(historicalRemoved && reqContext.historyParentId ? { [ENCRYPTED_HISTORY_REBASE]: true } : {}),
|
|
222
|
+
[RELEASE_HISTORY_INPUT]: historyInputItems };
|
|
223
|
+
}
|
|
224
|
+
|
|
195
225
|
export function sanitizeEncryptedReasoningRequest(reqContext, { historicalOnly = false } = {}) {
|
|
196
226
|
const state = { changed: false };
|
|
197
227
|
let body = cloneJson(reqContext.body);
|