codex-copilot-dx 0.9.39 → 0.9.40
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 +2 -2
- package/bin/cli.mjs +6 -1
- package/docs/ARCHITECTURE.md +14 -0
- package/docs/REFERENCE.md +31 -0
- package/package.json +1 -1
- package/src/auth.mjs +11 -2
- package/src/copilot-token-session.mjs +19 -3
- package/src/launcher.mjs +4 -4
- package/src/native-prediction-route.mjs +2 -2
- package/src/native-prediction-transport.mjs +4 -3
- package/src/native-prediction-windows.mjs +2 -2
- package/src/network-route.mjs +2 -1
- package/src/prediction-pac.mjs +17 -0
- package/src/windows-prediction-network.mjs +2 -1
package/README.md
CHANGED
|
@@ -66,7 +66,7 @@ Auto refresh runs every 30 minutes while visible and can be switched off. Hidden
|
|
|
66
66
|
break continuations. Generated images and Codex transcripts are not deleted.
|
|
67
67
|
- Optional image setup/maintenance never blocks the primary service. Disabled
|
|
68
68
|
users get no CCDX image skill or MCP installation.
|
|
69
|
-
- Missing-token discovery includes legacy OpenCode Copilot OAuth and GitHub CLI. Reads are bounded and account-matched; incomplete/network-failed discovery does not start another login. Other apps' credentials stay read-only.
|
|
69
|
+
- Missing-token discovery includes legacy OpenCode Copilot OAuth and GitHub CLI. Reads are bounded and account-matched; incomplete/network-failed or HTTP-403-blocked discovery does not start another login. The default saved credential is preserved; Copilot 401/403 alone is not proof that it expired. Other apps' credentials stay read-only.
|
|
70
70
|
- `doctor --fix` does not start login, enable optional features, change company policy or force-restart Apps. It backs up changed config; missing-token repair can contact GitHub. Partial repairs exit 1. See the reference for exact scope.
|
|
71
71
|
- Native predictions are a separate, opt-in compatibility feature. Quit Codex,
|
|
72
72
|
run `ccdx prediction on`, then restart CCDX. This adds App-profile certificate
|
|
@@ -75,7 +75,7 @@ Auto refresh runs every 30 minutes while visible and can be switched off. Hidden
|
|
|
75
75
|
Other domains and the CCDX model endpoint stay on their existing routes.
|
|
76
76
|
No program files or OS trust are changed. Static HTTP/HTTPS/SOCKS5 proxies and bypass rules are retained.
|
|
77
77
|
Windows supports company PAC/WPAD; macOS dynamic routing remains unsupported. Windows setup needs the official MSIX App, Windows PowerShell and .NET Framework 4.7.2+—not Git/OpenSSL. See the reference for limits.
|
|
78
|
-
Bridge checks allow three same-port recovery attempts per process,
|
|
78
|
+
Bridge checks allow three same-port recovery attempts per process. The revised PAC adds a loopback retry endpoint after the unchanged primary, preserving company fallback. Quit Codex once to load this route revision; later CCDX upgrades retain it. App prediction failures can remain cached for five minutes, so network recovery is not proof of an immediate suggestion. Only closed, initialized Apps in direct environments receive an owned persistent route; missing routes in running Apps are not hot-attached.
|
|
79
79
|
- CCDX adds experimental local history compression only when installed App
|
|
80
80
|
runtimes support it and report it off. Existing choices are preserved; an
|
|
81
81
|
already-enabled default, unavailable runtime or failed check is skipped.
|
package/bin/cli.mjs
CHANGED
|
@@ -382,6 +382,11 @@ try {
|
|
|
382
382
|
process.exit(0);
|
|
383
383
|
}
|
|
384
384
|
|
|
385
|
+
// Restore the opted-in listener alongside authentication/model initialization;
|
|
386
|
+
// a slow company-proxy setup must not delay the core listener.
|
|
387
|
+
const earlyIntegration = await clientIntegrations();
|
|
388
|
+
const predictionSetup = runInBackground(() => earlyIntegration.start());
|
|
389
|
+
|
|
385
390
|
// Ensure GitHub login, using device flow if no token exists.
|
|
386
391
|
await ensureAuth({ log: startupLogger("Auth") });
|
|
387
392
|
|
|
@@ -430,7 +435,7 @@ try {
|
|
|
430
435
|
const { compressionSetup, imageEnabled, imageMcpSkipped } = await configureCodexClient();
|
|
431
436
|
|
|
432
437
|
// Optional native prediction setup must never prevent the core adapter from running.
|
|
433
|
-
nativePrediction = await
|
|
438
|
+
nativePrediction = await predictionSetup;
|
|
434
439
|
const persistentRoute = await nativePrediction?.prepareRoute();
|
|
435
440
|
|
|
436
441
|
// Launch Codex when available. A running App is never forcibly restarted.
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -71,6 +71,10 @@ backup transactionally. Disabled optional features stay disabled. JSON reports
|
|
|
71
71
|
separate before checks from final repair evidence; HTTP 200 alone is not success.
|
|
72
72
|
|
|
73
73
|
Native prediction has a separate loopback transport and an isolated HTTPS agent.
|
|
74
|
+
The opted-in listener starts in parallel with auth/model initialization,
|
|
75
|
+
independently of Copilot credentials. A slow optional start cannot block core
|
|
76
|
+
listener setup, and fatal
|
|
77
|
+
startup cleanup closes any optional listener that was already started.
|
|
74
78
|
Only its two selected hosts use the App-specific route. Non-configuration requests
|
|
75
79
|
on those hosts are forwarded unchanged. The bridge does not replace Copilot or
|
|
76
80
|
image-provider networking, modify client program files, or install system trust.
|
|
@@ -117,6 +121,16 @@ of certificates, networking and the CLI. It accepts multiple named hashed chunks
|
|
|
117
121
|
without assuming the first general-settings chunk is the implementation. Signature
|
|
118
122
|
and profile checks remain in the existing platform boundary.
|
|
119
123
|
|
|
124
|
+
`prediction-pac.mjs` is the pure shared format boundary for direct, static and
|
|
125
|
+
Windows company-PAC composition. Its stable revision URL makes a one-time old-PAC
|
|
126
|
+
migration observable without coupling routes to package versions. The unchanged
|
|
127
|
+
primary endpoint comes first; a clock-bucketed `.localhost` secondary lets
|
|
128
|
+
Chromium retry the same restored listener despite its per-endpoint failure cache.
|
|
129
|
+
The original company/direct fallback remains afterward. This adds no Node DNS
|
|
130
|
+
lookup, timer, listener, process or inference-path work. Browser route recovery
|
|
131
|
+
and the client's independently cached prediction configuration remain distinct;
|
|
132
|
+
neither is a visibility guarantee.
|
|
133
|
+
|
|
120
134
|
Explicit `prediction fix` uses the optional integration's serialized lifecycle,
|
|
121
135
|
not a second adapter or detached predictor. Startup, repair and shutdown cannot
|
|
122
136
|
create overlapping owned listeners. Healthy/current bridges are retained; explicit
|
package/docs/REFERENCE.md
CHANGED
|
@@ -31,6 +31,27 @@ feature uses the App's existing composer UI and the conversation's
|
|
|
31
31
|
selected model through CCDX. Suggestions are not sent automatically. Native
|
|
32
32
|
eligibility rules still apply; availability is not promised for every thread type.
|
|
33
33
|
|
|
34
|
+
The `0.9.40` routing revision uses the stable local PAC URL
|
|
35
|
+
`/proxy.pac?v=2`, independent of the package version. The primary proxy remains
|
|
36
|
+
`127.0.0.1` on the saved port. A secondary, time-bucketed `.localhost` name points
|
|
37
|
+
Chromium back to that same loopback listener after a cached proxy failure. Its
|
|
38
|
+
name changes every ten seconds when the PAC is evaluated, without a Node timer,
|
|
39
|
+
new listener, dependency, port, or background App watcher. Healthy traffic keeps
|
|
40
|
+
the original primary connection path. Direct/static/company-PAC fallbacks remain
|
|
41
|
+
after the two local entries, and unrelated hosts retain their original route.
|
|
42
|
+
The optional listener starts alongside GitHub auth and model initialization;
|
|
43
|
+
slow proxy setup does not delay the core adapter listener.
|
|
44
|
+
|
|
45
|
+
An App that loaded the old PAC must normally quit once to load this revision;
|
|
46
|
+
CCDX never force-restarts it or hot-writes an open profile. Subsequent upgrades
|
|
47
|
+
keep the revision URL, saved port and trust unchanged. An occupied saved port or
|
|
48
|
+
missing App route is not repaired by this retry mechanism. The installed App may
|
|
49
|
+
cache a failed prediction configuration for five minutes, and a subsequent
|
|
50
|
+
eligible turn may be needed to request another prediction. Returning configuration
|
|
51
|
+
traffic is not proof that native gray text is visible. Cross-platform browser
|
|
52
|
+
routing is tested separately from the user's native end-to-end acceptance;
|
|
53
|
+
the investigation report records these evidence levels without equating them.
|
|
54
|
+
|
|
34
55
|
Version `0.9.26` adds Windows platform adapters. Native gray suggestions,
|
|
35
56
|
adoption/sending and switching predictions off were verified on Windows with the
|
|
36
57
|
`.4` candidate. Windows setup
|
|
@@ -926,6 +947,16 @@ Directory/profile scans have explicit caps; hitting a cap or a network failure
|
|
|
926
947
|
reports incomplete discovery rather than silently selecting an account or
|
|
927
948
|
starting another login. Set an explicit source/account to resolve ambiguity.
|
|
928
949
|
An existing saved-token startup path performs no extra discovery/network calls.
|
|
950
|
+
Package reinstallation does not clear that user-owned credential. Copilot's short-lived
|
|
951
|
+
access token is obtained again when needed; it is not the saved GitHub credential.
|
|
952
|
+
For the default credential store, Copilot HTTP 403 preserves the credential and
|
|
953
|
+
reports access/network policy rather than recommending deletion. Copilot HTTP 401
|
|
954
|
+
performs a bounded GitHub identity check only if compatible local recovery did not
|
|
955
|
+
succeed. Only an identity HTTP 401 permits reauthorization guidance; an unavailable
|
|
956
|
+
check does not establish expiry. Neither case automatically deletes the credential
|
|
957
|
+
or starts Device Flow. Denials are not hidden by a cached Copilot token. A discovery
|
|
958
|
+
HTTP 403 also stops before Device Flow, preserving external sources and account
|
|
959
|
+
selection. Isolated/custom credential clients retain their own recovery contract.
|
|
929
960
|
|
|
930
961
|
After an account is selected, automatic `401`/`403` recovery and in-process token rotation accept only that same GitHub account. Concurrent callers share token refresh work without sharing cancellation, and a still-valid Copilot token may be used briefly after a transient refresh failure. Explicit token variables remain the intentional way to select another account.
|
|
931
962
|
|
package/package.json
CHANGED
package/src/auth.mjs
CHANGED
|
@@ -55,7 +55,10 @@ export async function fetchGithubIdentity(token, {
|
|
|
55
55
|
headers: { Authorization: `token ${token.trim()}`, Accept: "application/json" },
|
|
56
56
|
signal: controller.signal,
|
|
57
57
|
}), controller.signal);
|
|
58
|
-
if (!resp.ok)
|
|
58
|
+
if (!resp.ok) {
|
|
59
|
+
cancelResponseBody(resp);
|
|
60
|
+
return { ok: false, status: resp.status, reason: "github_user_failed" };
|
|
61
|
+
}
|
|
59
62
|
const data = await awaitWithSignal(() => resp.json(), controller.signal);
|
|
60
63
|
const identity = normalizeGithubIdentity(data);
|
|
61
64
|
return identity ? { ok: true, ...identity } : { ok: false, reason: "github_identity_missing" };
|
|
@@ -120,8 +123,9 @@ async function validateGithubTokenRequest(token, { fetchImpl, signal }) {
|
|
|
120
123
|
return {
|
|
121
124
|
ok: false,
|
|
122
125
|
status: userResp.status,
|
|
126
|
+
accessDenied: userResp.status === 403,
|
|
123
127
|
transient: userResp.status === 429 || userResp.status >= 500 || userResp.headers?.get?.("x-ratelimit-remaining") === "0",
|
|
124
|
-
reason: userResp.status === 401
|
|
128
|
+
reason: userResp.status === 401 ? "github_token_invalid" : userResp.status === 403 ? "github_access_denied" : "github_user_failed",
|
|
125
129
|
};
|
|
126
130
|
}
|
|
127
131
|
|
|
@@ -145,6 +149,7 @@ async function validateGithubTokenRequest(token, { fetchImpl, signal }) {
|
|
|
145
149
|
return {
|
|
146
150
|
ok: false,
|
|
147
151
|
status: copilotResp.status,
|
|
152
|
+
accessDenied: copilotResp.status === 403,
|
|
148
153
|
transient: copilotResp.status === 429 || copilotResp.status >= 500,
|
|
149
154
|
reason: copilotResp.status === 401 || copilotResp.status === 403 ? "copilot_access_denied" : "copilot_token_failed",
|
|
150
155
|
login,
|
|
@@ -244,6 +249,9 @@ export async function discoverGithubToken({
|
|
|
244
249
|
};
|
|
245
250
|
}
|
|
246
251
|
|
|
252
|
+
if (failures.some(item => item.validation?.accessDenied)) {
|
|
253
|
+
return { ok: false, accessDenied: true, failures };
|
|
254
|
+
}
|
|
247
255
|
return { ok: false, failures };
|
|
248
256
|
}
|
|
249
257
|
|
|
@@ -287,6 +295,7 @@ export async function importDiscoveredGithubToken({
|
|
|
287
295
|
const logins = [...new Set(discovered.candidates.map((candidate) => candidate.login || candidate.id || "unknown"))];
|
|
288
296
|
throw new Error(`Multiple GitHub Copilot accounts were found (${logins.join(", ")}). Set CCDX_GITHUB_LOGIN or CCDX_GITHUB_TOKEN_PATH to select one explicitly.`);
|
|
289
297
|
}
|
|
298
|
+
if (discovered.accessDenied) throw new Error("GitHub or Copilot denied access to an existing credential. Check account access and network policy; credentials were preserved and no new login was started.");
|
|
290
299
|
if (discovered.transient) throw new Error("Local GitHub credentials could not be fully checked. Check network access and retry; no new login was started.");
|
|
291
300
|
if (!discovered.ok) return null;
|
|
292
301
|
writeToken(discovered.token, home, discovered.validation);
|
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
normalizeGithubIdentity,
|
|
16
16
|
} from "./github-identity.mjs";
|
|
17
17
|
import { status } from "./status.mjs";
|
|
18
|
+
import { cancelResponseBody } from "./auth-device-flow.mjs";
|
|
18
19
|
|
|
19
20
|
const GITHUB_API = "https://api.github.com";
|
|
20
21
|
|
|
@@ -251,6 +252,7 @@ export function createCopilotTokenSession({
|
|
|
251
252
|
throw error;
|
|
252
253
|
}
|
|
253
254
|
if (!response.ok) {
|
|
255
|
+
cancelResponseBody(response);
|
|
254
256
|
if ((response.status === 401 || response.status === 403) && allowTokenDiscovery) {
|
|
255
257
|
const imported = await importDiscoveredGithubToken({
|
|
256
258
|
home: resolvedHome,
|
|
@@ -272,9 +274,23 @@ export function createCopilotTokenSession({
|
|
|
272
274
|
}
|
|
273
275
|
if (response.status === 401 || response.status === 403) {
|
|
274
276
|
const prefix = profile === "codex" ? "Failed to get Copilot token" : `Failed to get Copilot token for ${profile} profile`;
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
277
|
+
const reason = `${prefix}: ${response.status}.`;
|
|
278
|
+
if (!usesDefaultTokenStore || typeof reauthMessage === "function") {
|
|
279
|
+
throw refreshError(formatReauth(`${reason} The saved GitHub token may be expired, revoked, or missing Copilot access.`, resolvedHome), {
|
|
280
|
+
statusCode: response.status,
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
// A Copilot denial is not proof that the underlying GitHub credential
|
|
284
|
+
// expired. Only GitHub's own 401 can justify reauthorization guidance.
|
|
285
|
+
const identity = response.status === 401
|
|
286
|
+
? await fetchGithubIdentity(credentials.token, { fetchImpl, signal, timeoutMs: 4000 }) : null;
|
|
287
|
+
if (signal?.aborted) throw abortError(signal);
|
|
288
|
+
const message = identity?.status === 401
|
|
289
|
+
? formatReauth(`${reason} GitHub also rejected the saved credential.`, resolvedHome)
|
|
290
|
+
: `${reason} The saved GitHub credential was preserved. ${response.status === 403 || identity?.ok
|
|
291
|
+
? "Check Copilot account access and network policy; this response does not establish that a new login is needed."
|
|
292
|
+
: "GitHub credential validity could not be confirmed; check network access before changing authentication."}`;
|
|
293
|
+
throw refreshError(message, { statusCode: response.status });
|
|
278
294
|
}
|
|
279
295
|
const prefix = profile === "codex" ? "Failed to get Copilot token" : `Failed to get Copilot token for ${profile} profile`;
|
|
280
296
|
throw refreshError(`${prefix}: ${response.status}`, {
|
package/src/launcher.mjs
CHANGED
|
@@ -3,6 +3,7 @@ import fs from "node:fs";
|
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { installedWindowsPredictionApp, windowsPredictionAppProcesses } from "./native-prediction-windows.mjs";
|
|
5
5
|
import { status } from "./status.mjs";
|
|
6
|
+
import { isPredictionPacUrl } from "./prediction-pac.mjs";
|
|
6
7
|
|
|
7
8
|
export { ensureAuth } from "./auth.mjs";
|
|
8
9
|
|
|
@@ -50,7 +51,7 @@ export function macPredictionAppProcesses(app, { exec = execFileSync } = {}) {
|
|
|
50
51
|
const pid = Number(match[1]);
|
|
51
52
|
try {
|
|
52
53
|
const args = exec("/bin/ps", ["-p", String(pid), "-o", "args="], options);
|
|
53
|
-
const route = args.match(/(?:^|\s)--proxy-pac-url=(?:"(http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac)"|(http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac)(?=\s|$))/);
|
|
54
|
+
const route = args.match(/(?:^|\s)--proxy-pac-url=(?:"(http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac(?:\?v=2)?)"|(http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac(?:\?v=2)?)(?=\s|$))/);
|
|
54
55
|
const readable = args.trim() === match[2] || args.trimStart().startsWith(`${match[2]} `);
|
|
55
56
|
const uniqueRoute = (args.match(/(?:^|\s)--proxy-pac-url=/g) || []).length === 1;
|
|
56
57
|
rows.push({ pid, readable, route: readable && uniqueRoute ? route?.[1] || route?.[2] || null : null });
|
|
@@ -64,8 +65,7 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
|
|
|
64
65
|
preparePredictionRoute, persistedPredictionRoute = false, onPredictionRoute = () => {}, log = console.log,
|
|
65
66
|
resolveWindowsApp = installedWindowsPredictionApp, windowsAppProcesses = windowsPredictionAppProcesses,
|
|
66
67
|
macAppProcesses = macPredictionAppProcesses } = {}) {
|
|
67
|
-
if (platform === "win32" && autoLaunchEnabled(env) &&
|
|
68
|
-
&& /^http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac$/.test(predictionPacUrl)
|
|
68
|
+
if (platform === "win32" && autoLaunchEnabled(env) && isPredictionPacUrl(predictionPacUrl)
|
|
69
69
|
&& typeof predictionApp === "string" && path.win32.isAbsolute(predictionApp)) {
|
|
70
70
|
try {
|
|
71
71
|
if (typeof predictionProfile !== "string" || !path.win32.isAbsolute(predictionProfile)
|
|
@@ -124,7 +124,7 @@ export async function openCodex({ env = process.env, spawnImpl = spawn, platform
|
|
|
124
124
|
return false;
|
|
125
125
|
}
|
|
126
126
|
|
|
127
|
-
const extraArgs =
|
|
127
|
+
const extraArgs = isPredictionPacUrl(predictionPacUrl)
|
|
128
128
|
&& APP_PATH_CANDIDATES.includes(predictionApp)
|
|
129
129
|
? ["--args", `--proxy-pac-url=${predictionPacUrl}`] : [];
|
|
130
130
|
if (extraArgs.length) {
|
|
@@ -4,9 +4,9 @@ import { isDeepStrictEqual } from "node:util";
|
|
|
4
4
|
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
5
5
|
import { atomicWriteFileSync } from "./atomic-file.mjs";
|
|
6
6
|
import { withFileLock } from "./lock.mjs";
|
|
7
|
+
import { isPredictionPacUrl } from "./prediction-pac.mjs";
|
|
7
8
|
|
|
8
|
-
const validPac =
|
|
9
|
-
&& Number(new URL(value).port) >= 1024 && Number(new URL(value).port) <= 65535;
|
|
9
|
+
const validPac = isPredictionPacUrl;
|
|
10
10
|
const object = value => value && typeof value === "object" && !Array.isArray(value);
|
|
11
11
|
|
|
12
12
|
function regularFile(file) {
|
|
@@ -4,6 +4,7 @@ import { promisify } from "node:util";
|
|
|
4
4
|
import { gunzip, inflate, brotliDecompress } from "node:zlib";
|
|
5
5
|
import { networkPredictionPac } from "./network-route.mjs";
|
|
6
6
|
import { operationErrorDetails } from "./operation-error.mjs";
|
|
7
|
+
import { PREDICTION_PAC_PATH, predictionProxyExpression } from "./prediction-pac.mjs";
|
|
7
8
|
|
|
8
9
|
export const PREDICTION_HOSTS = Object.freeze(["chatgpt.com", "ab.chatgpt.com"]);
|
|
9
10
|
const CONFIG_LIMIT = 16 * 1024 * 1024;
|
|
@@ -20,7 +21,7 @@ export function predictionRoute(host, pathname) {
|
|
|
20
21
|
export function predictionPac(port, networkRoute) {
|
|
21
22
|
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid prediction proxy port");
|
|
22
23
|
if (networkRoute) return networkPredictionPac(port, networkRoute);
|
|
23
|
-
return `function FindProxyForURL(url, host) { if (url.indexOf('https:') === 0 && (host === 'chatgpt.com' || host === 'ab.chatgpt.com')) return
|
|
24
|
+
return `function FindProxyForURL(url, host) { if (url.indexOf('https:') === 0 && (host === 'chatgpt.com' || host === 'ab.chatgpt.com')) return ${predictionProxyExpression(port)}+'; DIRECT'; return 'DIRECT'; }\n`;
|
|
24
25
|
}
|
|
25
26
|
|
|
26
27
|
function cleanHeaders(headers) {
|
|
@@ -220,7 +221,7 @@ export async function startPredictionTransport({
|
|
|
220
221
|
gateway.on("tlsClientError", (error, socket) => { onEvent({ type: "tls_error", error: operationErrorDetails(error) }); socket.destroy(); });
|
|
221
222
|
gateway.on("clientError", (_error, socket) => socket.destroy());
|
|
222
223
|
const proxy = http.createServer((req, res) => {
|
|
223
|
-
if (req.method === "GET" &&
|
|
224
|
+
if (req.method === "GET" && ["/proxy.pac", PREDICTION_PAC_PATH].includes(req.url) && !req.headers.origin
|
|
224
225
|
&& ["127.0.0.1", "localhost"].includes(String(req.headers.host || "").split(":")[0])) {
|
|
225
226
|
res.writeHead(200, { "Content-Type": "application/x-ns-proxy-autoconfig", "Cache-Control": "no-store" });
|
|
226
227
|
res.end(pacImpl ? pacImpl(proxy.address().port) : predictionPac(proxy.address().port, networkRoute)); return;
|
|
@@ -249,7 +250,7 @@ export async function startPredictionTransport({
|
|
|
249
250
|
try { port = await listen(proxy, listenPort); }
|
|
250
251
|
catch (error) { agent?.destroy();gateway.close();throw error; }
|
|
251
252
|
return {
|
|
252
|
-
port, pacUrl: `http://127.0.0.1:${port}
|
|
253
|
+
port, pacUrl: `http://127.0.0.1:${port}${PREDICTION_PAC_PATH}`,
|
|
253
254
|
healthy() { return !closing && !listenerError && proxy.listening; },
|
|
254
255
|
async close() {
|
|
255
256
|
closing = true;
|
|
@@ -35,7 +35,7 @@ export function windowsPredictionAppProcesses(app, { env = process.env, ...optio
|
|
|
35
35
|
$_.ExecutablePath -eq $env:CCDX_PREDICTION_APP_PATH -and ($_.CommandLine -notmatch '--type(?:=|\\s)')
|
|
36
36
|
} | ForEach-Object {
|
|
37
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))'){
|
|
38
|
+
if($_.CommandLine -match '--proxy-pac-url=(?:"(http://127\\.0\\.0\\.1:\\d{1,5}/proxy\\.pac(?:\\?v=2)?)"|(http://127\\.0\\.0\\.1:\\d{1,5}/proxy\\.pac(?:\\?v=2)?)(?=\\s|$))'){
|
|
39
39
|
$route=if($Matches[1]){$Matches[1]}else{$Matches[2]}
|
|
40
40
|
};
|
|
41
41
|
@{pid=[int]$_.ProcessId;route=$route;readable=![string]::IsNullOrWhiteSpace($_.CommandLine)}
|
|
@@ -43,7 +43,7 @@ export function windowsPredictionAppProcesses(app, { env = process.env, ...optio
|
|
|
43
43
|
let rows;
|
|
44
44
|
try { rows = JSON.parse(raw); } catch { throw new Error("Could not verify the running Windows App route; launch was skipped"); }
|
|
45
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
|
|
46
|
+
|| (row.route !== null && (typeof row.route !== "string" || !/^http:\/\/127\.0\.0\.1:\d{1,5}\/proxy\.pac(?:\?v=2)?$/.test(row.route))))) {
|
|
47
47
|
throw new Error("Unknown running Windows App route; launch was skipped");
|
|
48
48
|
}
|
|
49
49
|
return rows;
|
package/src/network-route.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import net from "node:net";
|
|
2
2
|
import { compileBypassRules, matchesBypass, bypassPacSource } from "./network-bypass.mjs";
|
|
3
|
+
import { predictionProxyExpression } from "./prediction-pac.mjs";
|
|
3
4
|
|
|
4
5
|
const OFFICIAL_API = "https://chatgpt.com/backend-api";
|
|
5
6
|
const routeError = (code, message) => Object.assign(new Error(message), { code });
|
|
@@ -80,7 +81,7 @@ function FindProxyForURL(url,host) {
|
|
|
80
81
|
var authority=url.split('/')[2]||'', explicit=/:([0-9]+)$/.exec(authority);if(explicit)p=Number(explicit[1]);
|
|
81
82
|
var skip=matchesBypass(host,p,ccdxRoute.rules,ccdxRoute.excludeSimple);
|
|
82
83
|
var original=skip?'DIRECT':secure?ccdxRoute.https:ccdxRoute.http;
|
|
83
|
-
if(secure&&(host==='chatgpt.com'||host==='ab.chatgpt.com'))return
|
|
84
|
+
if(secure&&(host==='chatgpt.com'||host==='ab.chatgpt.com'))return ${predictionProxyExpression(port)}+'; '+original;
|
|
84
85
|
return original;
|
|
85
86
|
}\n`;
|
|
86
87
|
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// A stable format revision, not the CCDX package version. Existing Apps must
|
|
2
|
+
// load it once; later adapter upgrades keep the same URL, port and trust.
|
|
3
|
+
export const PREDICTION_PAC_PATH = "/proxy.pac?v=2";
|
|
4
|
+
|
|
5
|
+
export function isPredictionPacUrl(value) {
|
|
6
|
+
const match = typeof value === "string" && /^http:\/\/127\.0\.0\.1:(\d{1,5})\/proxy\.pac(?:\?v=2)?$/.exec(value);
|
|
7
|
+
return Boolean(match && Number(match[1]) >= 1024 && Number(match[1]) <= 65535);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
// Chromium caches failed proxy endpoints separately from the PAC URL. A fresh
|
|
11
|
+
// loopback-only name lets its next resolution retry a restored listener without
|
|
12
|
+
// waiting for that failed endpoint's retry cache. No timer, DNS lookup in Node,
|
|
13
|
+
// new port, process, or system proxy mutation is involved.
|
|
14
|
+
export function predictionProxyExpression(port) {
|
|
15
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid prediction proxy port");
|
|
16
|
+
return `'PROXY 127.0.0.1:${port}; PROXY ccdx-'+Math.floor(Date.now()/10000)+'.localhost:${port}'`;
|
|
17
|
+
}
|
|
@@ -4,6 +4,7 @@ import { spawn } from "node:child_process";
|
|
|
4
4
|
import { PassThrough, Writable } from "node:stream";
|
|
5
5
|
import { Script } from "node:vm";
|
|
6
6
|
import { windowsPowerShellEnvironment } from "./native-prediction-windows.mjs";
|
|
7
|
+
import { predictionProxyExpression } from "./prediction-pac.mjs";
|
|
7
8
|
|
|
8
9
|
function failure(code) {
|
|
9
10
|
return Object.assign(new Error(`Windows prediction network failed (${code}); existing company routes were preserved`), { code });
|
|
@@ -12,7 +13,7 @@ function failure(code) {
|
|
|
12
13
|
export function companyPredictionPac(script, port) {
|
|
13
14
|
if (typeof script !== "string" || Buffer.byteLength(script) > 1024 * 1024 || !Number.isInteger(port) || port < 1 || port > 65535) throw failure("proxy_pac_invalid");
|
|
14
15
|
// Compile only for syntax validation; never execute a downloaded PAC in Node.
|
|
15
|
-
const combined = `var ccdxCompanyRoute=(function(){\n${script}\n;return FindProxyForURL;})();\nfunction FindProxyForURL(url,host){var original=ccdxCompanyRoute(url,host);if(url.indexOf('https:')===0&&(host==='chatgpt.com'||host==='ab.chatgpt.com'))return
|
|
16
|
+
const combined = `var ccdxCompanyRoute=(function(){\n${script}\n;return FindProxyForURL;})();\nfunction FindProxyForURL(url,host){var original=ccdxCompanyRoute(url,host);if(url.indexOf('https:')===0&&(host==='chatgpt.com'||host==='ab.chatgpt.com'))return ${predictionProxyExpression(port)}+'; '+original;return original;}\n`;
|
|
16
17
|
try { new Script(combined); } catch { throw failure("proxy_pac_invalid"); }
|
|
17
18
|
return combined;
|
|
18
19
|
}
|