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.
- package/README.md +15 -12
- package/bin/cli.mjs +24 -32
- package/docs/ARCHITECTURE.md +69 -0
- package/docs/README.md +6 -0
- package/docs/REFERENCE.md +112 -10
- package/package.json +3 -2
- package/src/adapter.mjs +1 -0
- package/src/cli-image.mjs +13 -10
- package/src/cli-options.mjs +1 -1
- package/src/cli-status.mjs +5 -0
- package/src/client-integration.mjs +41 -0
- package/src/codex-config-doctor.mjs +3 -3
- package/src/codex-paths.mjs +10 -0
- package/src/codex-thread-compression.mjs +11 -6
- package/src/config.mjs +10 -6
- package/src/copilot-responses-compat.mjs +30 -2
- package/src/copilot-responses-policy.mjs +14 -3
- package/src/dashboard/index.html +18 -9
- package/src/dashboard/language.js +14 -0
- package/src/dashboard/ui.css +2 -0
- package/src/dashboard/ui.js +10 -0
- package/src/launcher.mjs +50 -2
- package/src/lock.mjs +29 -0
- package/src/native-prediction-profile.mjs +46 -23
- package/src/native-prediction-state.mjs +29 -0
- package/src/native-prediction-transport.mjs +24 -9
- package/src/native-prediction-windows.mjs +174 -0
- package/src/native-prediction.mjs +102 -28
- package/src/network-route.mjs +102 -0
- package/src/observability.mjs +2 -0
- package/src/operation-error.mjs +37 -0
- package/src/package-update.mjs +2 -3
- package/src/prediction-retirement.mjs +13 -2
- package/src/proxy-tunnel.mjs +102 -0
- package/src/responses-proxy.mjs +13 -3
- package/src/responses-request.mjs +35 -2
- package/src/user-settings.mjs +17 -4
- package/src/version.mjs +23 -46
- package/src/windows-prediction-network.cs +154 -0
- package/src/windows-prediction-network.mjs +123 -0
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import net from "node:net";
|
|
2
|
+
|
|
3
|
+
const OFFICIAL_API = "https://chatgpt.com/backend-api";
|
|
4
|
+
|
|
5
|
+
function proxy(value, source) {
|
|
6
|
+
if (!value) return null;
|
|
7
|
+
let url;
|
|
8
|
+
try { url = new URL(value); } catch { throw new Error(`Invalid proxy address in ${source}`); }
|
|
9
|
+
if (!["http:", "https:", "socks5:", "socks5h:"].includes(url.protocol)
|
|
10
|
+
|| !url.hostname || !["", "/"].includes(url.pathname) || url.search || url.hash) {
|
|
11
|
+
throw new Error(`Unsupported proxy address in ${source}; expected HTTP, HTTPS or SOCKS5`);
|
|
12
|
+
}
|
|
13
|
+
return { url, source };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function variable(env, lower, upper) {
|
|
17
|
+
const key = String(env[lower] || "").trim() ? lower : upper;
|
|
18
|
+
return { value: String(env[key] || "").trim(), source: key };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function resolveNetworkRoute({ env = process.env, systemProxy = "", checkApi = true } = {}) {
|
|
22
|
+
const api = String(env.CODEX_API_BASE_URL || "").trim().replace(/\/+$/, "");
|
|
23
|
+
if (checkApi && api && api !== OFFICIAL_API) {
|
|
24
|
+
throw new Error("Native prediction setup skipped: CODEX_API_BASE_URL selects a custom API route; it was preserved");
|
|
25
|
+
}
|
|
26
|
+
const settings = Object.fromEntries([...systemProxy.matchAll(/^\s*([A-Za-z]+)\s*:\s*(.+?)\s*$/gm)].map((m) => [m[1], m[2]]));
|
|
27
|
+
for (const key of ["ProxyAutoConfigEnable", "ProxyAutoDiscoveryEnable"]) {
|
|
28
|
+
if (settings[key] === "1") throw new Error(`Native prediction setup skipped: system ${key === "ProxyAutoConfigEnable" ? "PAC" : "WPAD"} (${key}) needs dynamic routing; its rules were preserved`);
|
|
29
|
+
}
|
|
30
|
+
const system = (prefix, scheme) => {
|
|
31
|
+
if (settings[`${prefix}Enable`] !== "1") return null;
|
|
32
|
+
const host = settings[`${prefix}Proxy`], port = settings[`${prefix}Port`];
|
|
33
|
+
if (!host || !/^\d+$/.test(port || "") || Number(port) < 1 || Number(port) > 65535) {
|
|
34
|
+
throw new Error(`Invalid system ${prefix} proxy settings`);
|
|
35
|
+
}
|
|
36
|
+
return proxy(`${scheme}://${net.isIP(host) === 6 ? `[${host}]` : host}:${port}`, `system ${prefix}`);
|
|
37
|
+
};
|
|
38
|
+
const httpEnv = variable(env, "http_proxy", "HTTP_PROXY"), httpsEnv = variable(env, "https_proxy", "HTTPS_PROXY");
|
|
39
|
+
const allEnv = variable(env, "all_proxy", "ALL_PROXY");
|
|
40
|
+
const all = proxy(allEnv.value, allEnv.source);
|
|
41
|
+
const systemSocks = system("SOCKS", "socks5");
|
|
42
|
+
const systemHttp = system("HTTP", "http"), systemHttps = system("HTTPS", "http");
|
|
43
|
+
const http = proxy(httpEnv.value, httpEnv.source) || all || systemHttp || systemSocks;
|
|
44
|
+
const https = proxy(httpsEnv.value, httpsEnv.source) || all || systemHttps || systemSocks;
|
|
45
|
+
const noProxy = variable(env, "no_proxy", "NO_PROXY").value;
|
|
46
|
+
const exceptions = /ExceptionsList\s*:\s*<array>\s*\{([^}]+)\}/.exec(systemProxy)?.[1] || "";
|
|
47
|
+
const bypass = [...new Set([...noProxy.split(","), ...[...exceptions.matchAll(/\d+\s*:\s*([^\n]+)/g)].map((m) => m[1])]
|
|
48
|
+
.map((s) => s.trim().toLowerCase()).filter(Boolean))];
|
|
49
|
+
if (bypass.some((rule) => rule.includes("/"))) throw new Error("Unsupported proxy bypass CIDR rule in NO_PROXY or system exceptions; existing routes were preserved");
|
|
50
|
+
return { http, https, bypass, excludeSimple: settings.ExcludeSimpleHostnames === "1" };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function bypassNetworkProxy(hostname, port, plan) {
|
|
54
|
+
const host = hostname.replace(/^\[|\]$/g, "").toLowerCase();
|
|
55
|
+
if (["localhost", "127.0.0.1", "::1"].includes(host) || (plan.excludeSimple && !host.includes("."))) return true;
|
|
56
|
+
return plan.bypass.some((raw) => {
|
|
57
|
+
if (raw === "*") return true;
|
|
58
|
+
const match = /^(.*):(\d+)$/.exec(raw);
|
|
59
|
+
const rule = match ? match[1] : raw;
|
|
60
|
+
if (match && Number(match[2]) !== Number(port)) return false;
|
|
61
|
+
const suffix = rule.replace(/^\*?\./, "");
|
|
62
|
+
if (rule.includes("*")) {
|
|
63
|
+
const expression = rule.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replaceAll("*", ".*");
|
|
64
|
+
return new RegExp(`^${expression}$`).test(host);
|
|
65
|
+
}
|
|
66
|
+
return host === suffix || host.endsWith(`.${suffix}`);
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function networkProxyFor(url, plan) {
|
|
71
|
+
if (bypassNetworkProxy(url.hostname, url.port || (url.protocol === "https:" ? 443 : 80), plan)) return null;
|
|
72
|
+
return url.protocol === "https:" ? plan.https : plan.http;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function networkRouteSnapshot(plan) {
|
|
76
|
+
const route = plan.https;
|
|
77
|
+
return { source: route?.source || "direct", type: route?.url.protocol.replace(":", "") || "direct",
|
|
78
|
+
bypass_rules: plan.bypass.length, proxy_credentials: Boolean(route?.url.username || route?.url.password) };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function pacProxy(route) {
|
|
82
|
+
if (!route) return "DIRECT";
|
|
83
|
+
const type = route.url.protocol.startsWith("socks5") ? "SOCKS5" : route.url.protocol === "https:" ? "HTTPS" : "PROXY";
|
|
84
|
+
const port = route.url.port || (type === "HTTPS" ? 443 : type === "SOCKS5" ? 1080 : 80);
|
|
85
|
+
return `${type} ${route.url.hostname}:${port}`;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function networkPredictionPac(port, plan) {
|
|
89
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid prediction proxy port");
|
|
90
|
+
// Embed only routing rules, never proxy passwords or API credentials.
|
|
91
|
+
return `var ccdxRoute=${JSON.stringify({ http: pacProxy(plan.http), https: pacProxy(plan.https), bypass: plan.bypass, excludeSimple: plan.excludeSimple })};
|
|
92
|
+
function FindProxyForURL(url,host) {
|
|
93
|
+
var secure=url.indexOf('https:')===0, p=secure?443:80;
|
|
94
|
+
var authority=url.split('/')[2]||'', explicit=/:([0-9]+)$/.exec(authority);if(explicit)p=Number(explicit[1]);
|
|
95
|
+
var skip=host==='localhost'||host==='127.0.0.1'||host==='::1'||(ccdxRoute.excludeSimple&&host.indexOf('.')<0);
|
|
96
|
+
for(var i=0;i<ccdxRoute.bypass.length&&!skip;i++){var raw=ccdxRoute.bypass[i],m=/^(.*):([0-9]+)$/.exec(raw),r=m?m[1]:raw;if(m&&Number(m[2])!==p)continue;
|
|
97
|
+
var suffix=r.indexOf('*.')===0?r.slice(2):r[0]==='.'?r.slice(1):r;skip=r==='*'||(r.indexOf('*')>=0?shExpMatch(host,r):host===suffix||dnsDomainIs(host,'.'+suffix));}
|
|
98
|
+
var original=skip?'DIRECT':secure?ccdxRoute.https:ccdxRoute.http;
|
|
99
|
+
if(secure&&(host==='chatgpt.com'||host==='ab.chatgpt.com'))return 'PROXY 127.0.0.1:${port}; '+original;
|
|
100
|
+
return original;
|
|
101
|
+
}\n`;
|
|
102
|
+
}
|
package/src/observability.mjs
CHANGED
|
@@ -159,6 +159,7 @@ export function runtimeStatusPayload({
|
|
|
159
159
|
codexClient,
|
|
160
160
|
codexModelRegistry,
|
|
161
161
|
codexModelCatalog,
|
|
162
|
+
clientIntegrations,
|
|
162
163
|
} = {}) {
|
|
163
164
|
const memory = process.memoryUsage();
|
|
164
165
|
const codexRuntime = safeClientRuntimeStatus(codexClient);
|
|
@@ -196,6 +197,7 @@ export function runtimeStatusPayload({
|
|
|
196
197
|
response_history: history,
|
|
197
198
|
image_optimization: imageOptimizationStats(),
|
|
198
199
|
image_generation: imageGeneration || null,
|
|
200
|
+
client_integrations: clientIntegrations || null,
|
|
199
201
|
logging: { usage: usageLoggingStats(), debug: debugLoggingStats() },
|
|
200
202
|
image_history_pressure: imagePressure?.snapshot?.() || null,
|
|
201
203
|
response_failures: responseFailures?.snapshot?.() || null,
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { redactDiagnosticText } from "./diagnostic-text.mjs";
|
|
2
|
+
|
|
3
|
+
export function operationError(code, message, { status = null, retryAt = null } = {}) {
|
|
4
|
+
return Object.assign(new Error(message), { code, status, retryAt });
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function operationErrorDetails(error) {
|
|
8
|
+
const code = String(error?.code || error?.cause?.code || "unknown");
|
|
9
|
+
let source = "unknown";
|
|
10
|
+
if (/proxy/i.test(code)) source = "proxy";
|
|
11
|
+
else if (/cert|tls|ssl/i.test(code)) source = "tls";
|
|
12
|
+
else if (/timeout|abort/i.test(code) || error?.name === "AbortError" || error?.name === "TimeoutError") source = "timeout";
|
|
13
|
+
else if (/limit|429/.test(code)) source = "rate_limit";
|
|
14
|
+
else if (/config|format|route|redirect/.test(code)) source = "configuration";
|
|
15
|
+
else if (/HTTP|http/.test(code)) source = "upstream";
|
|
16
|
+
else if (/ENOTFOUND|ECONN|EAI_/.test(code)) source = "network";
|
|
17
|
+
return { code: /^[A-Za-z0-9_-]{1,80}$/.test(code) ? code : "unknown", source,
|
|
18
|
+
message: redactDiagnosticText(String(error?.message || "Operation failed")).slice(0, 400),
|
|
19
|
+
status: Number.isInteger(error?.status) ? error.status : null };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Error classifiers consume decoded string fields; responses retain their
|
|
23
|
+
// original bytes. Only escaped, bounded JSON errors need this extra work.
|
|
24
|
+
export function errorEvidenceText(value) {
|
|
25
|
+
const text = String(value || "");
|
|
26
|
+
if (!text.includes("\\u") || text.length > 16 * 1024) return text;
|
|
27
|
+
try {
|
|
28
|
+
const strings = [];
|
|
29
|
+
const visit = (node, depth) => {
|
|
30
|
+
if (depth > 4 || strings.length >= 32) return;
|
|
31
|
+
if (typeof node === "string") strings.push(node);
|
|
32
|
+
else if (node && typeof node === "object") for (const child of Object.values(node)) visit(child, depth + 1);
|
|
33
|
+
};
|
|
34
|
+
visit(JSON.parse(text), 0);
|
|
35
|
+
return `${text}\n${strings.join("\n")}`;
|
|
36
|
+
} catch { return text; }
|
|
37
|
+
}
|
package/src/package-update.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
2
|
import { createInterface } from "node:readline/promises";
|
|
3
|
-
import {
|
|
3
|
+
import { lookupLatestRelease, githubReleaseVersion } from "./version.mjs";
|
|
4
4
|
|
|
5
5
|
const PACKAGE_NAME = "codex-copilot-dx";
|
|
6
6
|
const UPDATE_SPECS = {
|
|
@@ -95,8 +95,7 @@ export async function runPackageUpdateCommand({
|
|
|
95
95
|
let release;
|
|
96
96
|
if (selectedSource === "github") {
|
|
97
97
|
output.write("Checking the latest stable GitHub release...\n");
|
|
98
|
-
release = await
|
|
99
|
-
if (!release) throw new Error("Could not read the latest stable GitHub release. No update was installed.");
|
|
98
|
+
release = await lookupLatestRelease({ fetchImpl, timeoutMs: 10000 });
|
|
100
99
|
}
|
|
101
100
|
const update = globalUpdateCommand(selectedSource, { platform, releaseTag: release?.tagName });
|
|
102
101
|
const sourceLabel = selectedSource === "npm" ? "npm registry" : `GitHub release ${release.tagName}`;
|
|
@@ -6,6 +6,8 @@ import { isDeepStrictEqual } from "node:util";
|
|
|
6
6
|
import { atomicWriteFileIfChangedSync, atomicWriteFilePairSync } from "./atomic-file.mjs";
|
|
7
7
|
import { codexTomlStatements, parseCodexToml, validateManagedConfigEdit } from "./config-toml.mjs";
|
|
8
8
|
import { userSettingsPath } from "./user-settings.mjs";
|
|
9
|
+
import { codexPaths } from "./codex-paths.mjs";
|
|
10
|
+
import { withFileLockSync } from "./lock.mjs";
|
|
9
11
|
|
|
10
12
|
const SERVER_PATH = ["mcp_servers", "ccdx_suggestion"];
|
|
11
13
|
const same = (left, right) => isDeepStrictEqual(left, right);
|
|
@@ -52,9 +54,18 @@ export function computeRetiredPredictionConfig(content, filePath) {
|
|
|
52
54
|
return { content: updated, changed: updated !== content, preserved: Boolean(existing && !owned) || (content.includes("# ccdx:suggestion-auto:start") && !hookOwned) };
|
|
53
55
|
}
|
|
54
56
|
|
|
55
|
-
export function retirePredictionIntegration(
|
|
57
|
+
export function retirePredictionIntegration(options = {}) {
|
|
58
|
+
if (options.dryRun) return retirePredictionIntegrationUnlocked(options);
|
|
59
|
+
const { config } = codexPaths(options);
|
|
60
|
+
// No registration/settings means no lock directory or other write on startup.
|
|
61
|
+
const env = options.env || process.env;
|
|
62
|
+
const settings = path.resolve(env.CCDX_SUGGESTION_CONFIG || path.join(path.dirname(userSettingsPath(options)), "suggestion.json"));
|
|
63
|
+
if (!fs.existsSync(config) && !fs.existsSync(settings)) return { changed: false, preserved: false };
|
|
64
|
+
return withFileLockSync(`${config}.ccdx.lock`, () => retirePredictionIntegrationUnlocked(options));
|
|
65
|
+
}
|
|
66
|
+
function retirePredictionIntegrationUnlocked({ env = process.env, home = os.homedir(), dryRun = false } = {}) {
|
|
56
67
|
const settings = path.resolve(env.CCDX_SUGGESTION_CONFIG || path.join(path.dirname(userSettingsPath({ env, home })), "suggestion.json"));
|
|
57
|
-
const codex =
|
|
68
|
+
const codex = codexPaths({ env, home }).config;
|
|
58
69
|
let content;
|
|
59
70
|
try { content = new TextDecoder("utf-8", { fatal: true }).decode(fs.readFileSync(codex)); }
|
|
60
71
|
catch (error) { if (error.code !== "ENOENT") throw new Error("Cannot safely read prediction configuration"); }
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import net from "node:net";
|
|
2
|
+
import tls from "node:tls";
|
|
3
|
+
import https from "node:https";
|
|
4
|
+
import { networkProxyFor } from "./network-route.mjs";
|
|
5
|
+
|
|
6
|
+
// A bounded read preserves bytes following the handshake for the TLS parser.
|
|
7
|
+
function readSocket(socket, ready, maxBytes = 16 * 1024) {
|
|
8
|
+
return new Promise((resolve, reject) => {
|
|
9
|
+
let chunks = [], size = 0;
|
|
10
|
+
const cleanup = () => { socket.off("data", data); socket.off("error", error); socket.off("close", closed); };
|
|
11
|
+
const error = (e) => { cleanup(); reject(e); };
|
|
12
|
+
const closed = () => error(new Error("Proxy closed the connection"));
|
|
13
|
+
const data = (chunk) => {
|
|
14
|
+
chunks.push(chunk); size += chunk.length;
|
|
15
|
+
if (size > maxBytes) { error(new Error("Proxy handshake exceeds its limit")); return; }
|
|
16
|
+
const bytes = Buffer.concat(chunks, size), end = ready(bytes);
|
|
17
|
+
if (end !== null) {
|
|
18
|
+
socket.pause(); cleanup();
|
|
19
|
+
if (bytes.length > end) socket.unshift(bytes.subarray(end));
|
|
20
|
+
resolve(bytes.subarray(0, end));
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
socket.on("data", data); socket.once("error", error); socket.once("close", closed); socket.resume();
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function connectProxy(target, route, timeoutMs, pending) {
|
|
28
|
+
const proxy = route.url;
|
|
29
|
+
const proxyHost = proxy.hostname.replace(/^\[|\]$/g, "");
|
|
30
|
+
const socket = proxy.protocol === "https:"
|
|
31
|
+
? tls.connect({ host: proxyHost, port: Number(proxy.port || 443), servername: net.isIP(proxyHost) ? undefined : proxyHost, rejectUnauthorized: true })
|
|
32
|
+
: net.connect({ host: proxyHost, port: Number(proxy.port || (proxy.protocol.startsWith("socks") ? 1080 : 80)) });
|
|
33
|
+
pending.add(socket);
|
|
34
|
+
const timer = setTimeout(() => socket.destroy(new Error("Proxy connection timed out")), timeoutMs);
|
|
35
|
+
socket.once("close", () => pending.delete(socket));
|
|
36
|
+
try {
|
|
37
|
+
await new Promise((resolve, reject) => {
|
|
38
|
+
const event = proxy.protocol === "https:" ? "secureConnect" : "connect";
|
|
39
|
+
const failed = (error) => { socket.off(event, connected); reject(error); };
|
|
40
|
+
const connected = () => { socket.off("error", failed); resolve(); };
|
|
41
|
+
socket.once(event, connected); socket.once("error", failed);
|
|
42
|
+
});
|
|
43
|
+
if (proxy.protocol.startsWith("socks5")) {
|
|
44
|
+
const user = Buffer.from(decodeURIComponent(proxy.username)), password = Buffer.from(decodeURIComponent(proxy.password));
|
|
45
|
+
if (user.length > 255 || password.length > 255) throw new Error("SOCKS5 proxy credentials are too long");
|
|
46
|
+
const greeting = readSocket(socket, b => b.length >= 2 ? 2 : null);
|
|
47
|
+
socket.write(user.length ? Buffer.from([5, 2, 0, 2]) : Buffer.from([5, 1, 0]));
|
|
48
|
+
const choice = await greeting;
|
|
49
|
+
if (choice[0] !== 5 || ![0, 2].includes(choice[1]) || (choice[1] === 2 && !user.length)) throw new Error("SOCKS5 proxy authentication is unsupported");
|
|
50
|
+
if (choice[1] === 2) {
|
|
51
|
+
const auth = readSocket(socket, b => b.length >= 2 ? 2 : null);
|
|
52
|
+
socket.write(Buffer.concat([Buffer.from([1, user.length]), user, Buffer.from([password.length]), password]));
|
|
53
|
+
const result = await auth; if (result[0] !== 1 || result[1] !== 0) throw new Error("SOCKS5 proxy authentication failed");
|
|
54
|
+
}
|
|
55
|
+
const host = Buffer.from(target.hostname);
|
|
56
|
+
if (host.length > 255) throw new Error("Proxy target hostname is too long");
|
|
57
|
+
const response = readSocket(socket, b => {
|
|
58
|
+
if (b.length < 5) return null;
|
|
59
|
+
const size = b[3] === 1 ? 10 : b[3] === 4 ? 22 : b[3] === 3 ? 7 + b[4] : 5;
|
|
60
|
+
return b.length >= size ? size : null;
|
|
61
|
+
});
|
|
62
|
+
socket.write(Buffer.concat([Buffer.from([5, 1, 0, 3, host.length]), host, Buffer.from([1, 187])]));
|
|
63
|
+
const result = await response;
|
|
64
|
+
if (result[0] !== 5 || result[1] !== 0 || ![1, 3, 4].includes(result[3])) throw new Error("SOCKS5 proxy rejected the connection");
|
|
65
|
+
} else {
|
|
66
|
+
const response = readSocket(socket, b => { const end = b.indexOf("\r\n\r\n"); return end < 0 ? null : end + 4; });
|
|
67
|
+
const credentials = proxy.username || proxy.password
|
|
68
|
+
? `Proxy-Authorization: Basic ${Buffer.from(`${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`).toString("base64")}\r\n` : "";
|
|
69
|
+
socket.write(`CONNECT ${target.hostname}:443 HTTP/1.1\r\nHost: ${target.hostname}:443\r\n${credentials}\r\n`);
|
|
70
|
+
const headers = (await response).toString("latin1");
|
|
71
|
+
const status = /^HTTP\/1\.[01] (\d{3})/.exec(headers)?.[1];
|
|
72
|
+
if (status !== "200") throw new Error(`HTTP proxy rejected CONNECT (${status || "invalid response"})`);
|
|
73
|
+
}
|
|
74
|
+
clearTimeout(timer); pending.delete(socket);
|
|
75
|
+
return socket;
|
|
76
|
+
} catch (error) { clearTimeout(timer); socket.destroy(); throw error; }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function createProxyAgent(plan, { timeoutMs = 30_000 } = {}) {
|
|
80
|
+
const pending = new Set();
|
|
81
|
+
let closed = false;
|
|
82
|
+
const agent = new https.Agent({ keepAlive: true, maxSockets: 32, maxFreeSockets: 4 });
|
|
83
|
+
const direct = agent.createConnection.bind(agent);
|
|
84
|
+
agent.createConnection = (options, callback) => {
|
|
85
|
+
if (closed) { queueMicrotask(() => callback(new Error("Proxy agent is closed"))); return undefined; }
|
|
86
|
+
const target = new URL(`https://${options.host}`), route = networkProxyFor(target, plan);
|
|
87
|
+
if (!route) return direct(options, callback);
|
|
88
|
+
void connectProxy(target, route, timeoutMs, pending).then(socket => {
|
|
89
|
+
if (closed) { socket.destroy(); callback(new Error("Proxy agent is closed")); return; }
|
|
90
|
+
const secure = tls.connect({ ...options, socket, rejectUnauthorized: true });
|
|
91
|
+
pending.add(secure);
|
|
92
|
+
const timer = setTimeout(() => secure.destroy(new Error("Proxy target TLS timed out")), timeoutMs);
|
|
93
|
+
const fail = (error) => { clearTimeout(timer); pending.delete(secure); secure.off("secureConnect", done); callback(error); };
|
|
94
|
+
const done = () => { clearTimeout(timer); pending.delete(secure); secure.off("error", fail); callback(null, secure); };
|
|
95
|
+
secure.once("error", fail); secure.once("secureConnect", done); secure.resume();
|
|
96
|
+
}, callback);
|
|
97
|
+
return undefined;
|
|
98
|
+
};
|
|
99
|
+
const destroy = agent.destroy.bind(agent);
|
|
100
|
+
agent.destroy = () => { closed = true; for (const socket of pending) socket.destroy(new Error("Proxy agent closed")); pending.clear(); destroy(); };
|
|
101
|
+
return agent;
|
|
102
|
+
}
|
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);
|
|
@@ -309,7 +339,8 @@ export function prepareResponsesRequest(reqBody, {
|
|
|
309
339
|
assertActive?.();
|
|
310
340
|
const body = mutate ? reqBody : cloneJson(reqBody);
|
|
311
341
|
assertActive?.();
|
|
312
|
-
|
|
342
|
+
// body is already an owned clone unless the caller explicitly allows mutation.
|
|
343
|
+
const currentInputItems = responsesInputItems(body.input, { assertActive, clone: false });
|
|
313
344
|
const currentInputRefs = new Set(
|
|
314
345
|
currentInputItems.filter((item) => item && typeof item === "object"),
|
|
315
346
|
);
|
|
@@ -359,7 +390,9 @@ export function prepareResponsesRequest(reqBody, {
|
|
|
359
390
|
// concrete Copilot RoutePlan.
|
|
360
391
|
if (copilotBoundary) applyCopilotResponsesRequestPolicies(body);
|
|
361
392
|
stripInternalResponsesInputFields(body.input, { assertActive });
|
|
362
|
-
|
|
393
|
+
// The first pass already covers shared current items. Only an independent
|
|
394
|
+
// pre-adaptation snapshot needs another pass.
|
|
395
|
+
if (historyInputItems !== currentInputItems) stripInternalResponsesInputFields(historyInputItems, { assertActive });
|
|
363
396
|
assertActive?.();
|
|
364
397
|
const retainedCurrentInputStart = body.input.findIndex((item) => currentInputRefs.has(item));
|
|
365
398
|
|
package/src/user-settings.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import fs from "node:fs";
|
|
|
2
2
|
import os from "node:os";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { atomicWriteFileIfChangedSync } from "./atomic-file.mjs";
|
|
5
|
+
import { withFileLockSync } from "./lock.mjs";
|
|
5
6
|
import { AUTO_REVIEW_REASONING_EFFORTS, DEFAULT_CODEX_AUTO_REVIEW_MODEL } from "./models.mjs";
|
|
6
7
|
import { loadRuntimeConfig, RUNTIME_DEFAULTS } from "./runtime-config.mjs";
|
|
7
8
|
import {
|
|
@@ -155,7 +156,10 @@ export function decodedBodyLimitPreference({ env = process.env, home = os.homedi
|
|
|
155
156
|
return { bytes: RUNTIME_DEFAULTS.maxDecodedBodyBytes, mib: DECODED_BODY_LIMIT_MIN_MIB, source: "default" };
|
|
156
157
|
}
|
|
157
158
|
|
|
158
|
-
export function writeDecodedBodyLimitMib(mib,
|
|
159
|
+
export function writeDecodedBodyLimitMib(mib, options = {}) {
|
|
160
|
+
return withFileLockSync(`${userSettingsPath(options)}.lock`, () => writeDecodedBodyLimitMibUnlocked(mib, options));
|
|
161
|
+
}
|
|
162
|
+
function writeDecodedBodyLimitMibUnlocked(mib, { env = process.env, home = os.homedir() } = {}) {
|
|
159
163
|
const filePath = userSettingsPath({ env, home });
|
|
160
164
|
const settings = readUserSettings({ env, home, strict: true });
|
|
161
165
|
const next = { ...settings };
|
|
@@ -177,7 +181,10 @@ export function writeDecodedBodyLimitMib(mib, { env = process.env, home = os.hom
|
|
|
177
181
|
return { changed, filePath, ...decodedBodyLimitPreference({ env, home }) };
|
|
178
182
|
}
|
|
179
183
|
|
|
180
|
-
export function writeResponseHistoryLimitMib(mib,
|
|
184
|
+
export function writeResponseHistoryLimitMib(mib, options = {}) {
|
|
185
|
+
return withFileLockSync(`${userSettingsPath(options)}.lock`, () => writeResponseHistoryLimitMibUnlocked(mib, options));
|
|
186
|
+
}
|
|
187
|
+
function writeResponseHistoryLimitMibUnlocked(mib, { env = process.env, home = os.homedir() } = {}) {
|
|
181
188
|
const filePath = userSettingsPath({ env, home });
|
|
182
189
|
const settings = readUserSettings({ env, home, strict: true });
|
|
183
190
|
const next = { ...settings };
|
|
@@ -199,7 +206,10 @@ export function writeResponseHistoryLimitMib(mib, { env = process.env, home = os
|
|
|
199
206
|
return { changed, filePath, ...responseHistoryLimitPreference({ env, home }) };
|
|
200
207
|
}
|
|
201
208
|
|
|
202
|
-
export function writeAutoReviewModel(model,
|
|
209
|
+
export function writeAutoReviewModel(model, options = {}) {
|
|
210
|
+
return withFileLockSync(`${userSettingsPath(options)}.lock`, () => writeAutoReviewModelUnlocked(model, options));
|
|
211
|
+
}
|
|
212
|
+
function writeAutoReviewModelUnlocked(model, { env = process.env, home = os.homedir(), reasoningEffort } = {}) {
|
|
203
213
|
if (reasoningEffort !== undefined && reasoningEffort !== null
|
|
204
214
|
&& !AUTO_REVIEW_REASONING_EFFORTS.includes(reasoningEffort)) {
|
|
205
215
|
throw new Error("Auto-review reasoning effort is invalid");
|
|
@@ -220,7 +230,10 @@ export function writeAutoReviewModel(model, { env = process.env, home = os.homed
|
|
|
220
230
|
return { changed, filePath, model: value || DEFAULT_CODEX_AUTO_REVIEW_MODEL };
|
|
221
231
|
}
|
|
222
232
|
|
|
223
|
-
export function writeTerminalAnimationTheme(theme,
|
|
233
|
+
export function writeTerminalAnimationTheme(theme, options = {}) {
|
|
234
|
+
return withFileLockSync(`${userSettingsPath(options)}.lock`, () => writeTerminalAnimationThemeUnlocked(theme, options));
|
|
235
|
+
}
|
|
236
|
+
function writeTerminalAnimationThemeUnlocked(theme, { env = process.env, home = os.homedir() } = {}) {
|
|
224
237
|
if (!isTerminalAnimationTheme(theme)) {
|
|
225
238
|
const choices = TERMINAL_ANIMATION_THEMES.map(({ id }) => id).join(", ");
|
|
226
239
|
throw new Error(`Terminal animation must be one of: ${choices}`);
|
package/src/version.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { operationError } from "./operation-error.mjs";
|
|
4
5
|
|
|
5
|
-
const GITHUB_LATEST_RELEASE_URL = "https://
|
|
6
|
-
const MAX_RELEASE_BYTES = 256 * 1024;
|
|
6
|
+
const GITHUB_LATEST_RELEASE_URL = "https://github.com/DaleXiao/codex-copilot-dx/releases/latest";
|
|
7
7
|
|
|
8
8
|
export function localPackageVersion() {
|
|
9
9
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
@@ -37,62 +37,39 @@ export function githubReleaseVersion(tag) {
|
|
|
37
37
|
return match.slice(1).join(".");
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
async function
|
|
41
|
-
const reader = response.body?.getReader?.();
|
|
42
|
-
if (!reader) throw new Error("GitHub release response has no readable body");
|
|
43
|
-
const cancel = () => { void reader.cancel().catch(() => {}); };
|
|
44
|
-
signal.addEventListener("abort", cancel, { once: true });
|
|
45
|
-
const chunks = [];
|
|
46
|
-
let bytes = 0;
|
|
47
|
-
let complete = false;
|
|
48
|
-
try {
|
|
49
|
-
if (Number(response.headers?.get?.("content-length")) > MAX_RELEASE_BYTES) {
|
|
50
|
-
throw new Error("GitHub release response is too large");
|
|
51
|
-
}
|
|
52
|
-
while (!signal.aborted) {
|
|
53
|
-
const { done, value } = await reader.read();
|
|
54
|
-
if (done) {
|
|
55
|
-
complete = true;
|
|
56
|
-
break;
|
|
57
|
-
}
|
|
58
|
-
bytes += value.byteLength;
|
|
59
|
-
if (bytes > MAX_RELEASE_BYTES) throw new Error("GitHub release response is too large");
|
|
60
|
-
chunks.push(Buffer.from(value));
|
|
61
|
-
}
|
|
62
|
-
if (signal.aborted) throw new Error("GitHub release request timed out");
|
|
63
|
-
return JSON.parse(Buffer.concat(chunks, bytes).toString("utf8"));
|
|
64
|
-
} finally {
|
|
65
|
-
signal.removeEventListener("abort", cancel);
|
|
66
|
-
if (!complete) cancel();
|
|
67
|
-
reader.releaseLock();
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
export async function fetchLatestRelease({ fetchImpl = fetch, timeoutMs = 2000 } = {}) {
|
|
40
|
+
export async function lookupLatestRelease({ fetchImpl = fetch, timeoutMs = 2000 } = {}) {
|
|
72
41
|
const controller = new AbortController();
|
|
73
42
|
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
74
43
|
try {
|
|
75
44
|
const resp = await fetchImpl(GITHUB_LATEST_RELEASE_URL, {
|
|
76
|
-
headers: { Accept: "
|
|
77
|
-
redirect: "
|
|
45
|
+
headers: { Accept: "text/html", "User-Agent": "codex-copilot-dx" },
|
|
46
|
+
redirect: "manual",
|
|
78
47
|
signal: controller.signal,
|
|
79
48
|
});
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
49
|
+
void resp.body?.cancel?.().catch(() => {});
|
|
50
|
+
if ([403, 429].includes(resp.status)) throw operationError("github_rate_limit", `GitHub release lookup was refused (HTTP ${resp.status}); retry later. No update was installed.`, { status: resp.status });
|
|
51
|
+
if (![301, 302, 303, 307, 308].includes(resp.status)) throw operationError("github_http_error", `GitHub release lookup returned HTTP ${resp.status}; no stable release redirect was received. No update was installed.`, { status: resp.status });
|
|
52
|
+
let url;
|
|
53
|
+
try { url = new URL(resp.headers.get("location"), GITHUB_LATEST_RELEASE_URL); } catch {}
|
|
54
|
+
const match = url?.pathname.match(/^\/DaleXiao\/codex-copilot-dx\/releases\/tag\/([^/]+)$/i);
|
|
55
|
+
const tagName = match?.[1], version = githubReleaseVersion(tagName);
|
|
56
|
+
if (!url || url.origin !== "https://github.com" || url.username || url.password || url.search || url.hash || !version) {
|
|
57
|
+
throw operationError("github_invalid_redirect", "GitHub did not return a valid stable release tag for this repository. No update was installed.");
|
|
83
58
|
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
} catch {
|
|
90
|
-
return null;
|
|
59
|
+
return { version, tagName };
|
|
60
|
+
} catch (error) {
|
|
61
|
+
if (error.code?.startsWith("github_")) throw error;
|
|
62
|
+
if (controller.signal.aborted) throw operationError("github_timeout", "GitHub release lookup timed out. No update was installed.");
|
|
63
|
+
throw operationError(error.cause?.code || "github_network_error", "Could not connect to the GitHub release page. Check your network or proxy. No update was installed.");
|
|
91
64
|
} finally {
|
|
92
65
|
clearTimeout(timer);
|
|
93
66
|
}
|
|
94
67
|
}
|
|
95
68
|
|
|
69
|
+
export async function fetchLatestRelease(options = {}) {
|
|
70
|
+
try { return await lookupLatestRelease(options); } catch { return null; }
|
|
71
|
+
}
|
|
72
|
+
|
|
96
73
|
export async function fetchLatestVersion(options) {
|
|
97
74
|
return (await fetchLatestRelease(options))?.version || null;
|
|
98
75
|
}
|