codex-copilot-dx 0.9.35 → 0.9.37
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 +8 -3
- package/docs/ARCHITECTURE.md +38 -2
- package/docs/REFERENCE.md +70 -6
- package/package.json +1 -1
- package/src/adapter.mjs +34 -2
- package/src/cli-options.mjs +3 -3
- package/src/cli-status.mjs +2 -0
- package/src/client-integration.mjs +87 -11
- package/src/codex-client-doctor.mjs +3 -0
- package/src/native-prediction-environment.mjs +59 -0
- package/src/native-prediction-fix.mjs +27 -0
- package/src/native-prediction-profile.mjs +12 -29
- package/src/native-prediction-protocol.mjs +45 -0
- package/src/native-prediction-recovery.mjs +6 -0
- package/src/native-prediction-state.mjs +18 -0
- package/src/native-prediction.mjs +50 -24
- package/src/network-bypass.mjs +79 -0
- package/src/network-route.mjs +14 -30
- package/src/running-adapter.mjs +2 -0
- package/src/startup-ui.mjs +4 -2
package/README.md
CHANGED
|
@@ -39,6 +39,7 @@ Auto refresh runs every 30 minutes while visible and can be switched off. Hidden
|
|
|
39
39
|
| `ccdx usage` | Recorded tokens and upstream prompt-cache hit rate |
|
|
40
40
|
| `ccdx auto-review-model` | Select model, then reasoning effort; `0` follows client |
|
|
41
41
|
| `ccdx animation` | Preview and select terminal animation |
|
|
42
|
+
| `ccdx prediction fix` | Recheck system routing and repair enabled predictions; report required restarts |
|
|
42
43
|
| `ccdx cache --limit 128` | Set the history-cache budget in MiB |
|
|
43
44
|
| `ccdx cache --clean` | Clear the rebuildable image-transform cache |
|
|
44
45
|
| `ccdx limits --decoded 256` | Set the decoded request-body budget; restart to apply |
|
|
@@ -89,8 +90,7 @@ Updates install the exact stable tag; dependencies still use npm's configured re
|
|
|
89
90
|
Updates warn about mismatched npm targets without changing PATH/prefix and verify the installed target version (exact tag for GitHub). Restart the adapter separately. Full `ccdx doctor` reports this target and readonly credential permissions; it never changes ACLs.
|
|
90
91
|
Recent errors separate HTTP and model failures. HTTP metadata retains status, source and IDs, not error bodies or prompts; original errors still reach Codex unchanged.
|
|
91
92
|
|
|
92
|
-
The dashboard and CLI separate prediction preference, bridge state and observed config traffic; candidate visibility stays unknown.
|
|
93
|
-
Inference, client integration, optional images and management have separate ownership. See [architecture boundaries](docs/ARCHITECTURE.md).
|
|
93
|
+
The dashboard and CLI separate prediction preference, bridge state and observed config traffic; candidate visibility stays unknown. Inference, client integration, optional images and management have separate ownership. See [architecture boundaries](docs/ARCHITECTURE.md).
|
|
94
94
|
|
|
95
95
|
See the [complete reference](https://github.com/DaleXiao/codex-copilot-dx/blob/main/docs/REFERENCE.md) for authentication, configuration, limits, logging, images and compatibility. It is also included as `docs/REFERENCE.md` in the npm package.
|
|
96
96
|
|
package/bin/cli.mjs
CHANGED
|
@@ -89,11 +89,15 @@ if (CLI.command === "suggestion") {
|
|
|
89
89
|
if (CLI.command === "prediction") {
|
|
90
90
|
try {
|
|
91
91
|
const { runPredictionCommand } = await import("../src/native-prediction.mjs");
|
|
92
|
-
await runPredictionCommand({ action: CLI.action,
|
|
92
|
+
const result = await runPredictionCommand({ action: CLI.action, repairRuntime: async () => {
|
|
93
|
+
const { requestPredictionFix } = await import("../src/native-prediction-fix.mjs");
|
|
94
|
+
const probe = parseAdapterProbeOptions(process.env);
|
|
95
|
+
return requestPredictionFix({ host: probe.adapterHost, port: probe.adapterPort });
|
|
96
|
+
}, runtimeSnapshot: () => {
|
|
93
97
|
const probe = parseAdapterProbeOptions(process.env);
|
|
94
98
|
return readAdapterStatus({ host: probe.adapterHost, port: probe.adapterPort, timeoutMs: probe.existingAdapterTimeoutMs }).then(({ data }) => data);
|
|
95
99
|
} });
|
|
96
|
-
process.exit(0);
|
|
100
|
+
process.exit(CLI.action === "fix" ? result.exitCode : 0);
|
|
97
101
|
} catch (error) {
|
|
98
102
|
console.error(status("err", error.message));
|
|
99
103
|
process.exit(1);
|
|
@@ -407,7 +411,8 @@ try {
|
|
|
407
411
|
streamHandshakeTimeoutMs: RUNTIME.streamHandshakeTimeoutMs,
|
|
408
412
|
streamIdleTimeoutMs: RUNTIME.streamIdleTimeoutMs,
|
|
409
413
|
terminalAnimationTheme,
|
|
410
|
-
nativePredictionPac: () =>
|
|
414
|
+
nativePredictionPac: () => clientIntegration?.pacUrl() || null,
|
|
415
|
+
fixPrediction: async () => (await clientIntegrations()).fix(),
|
|
411
416
|
clientIntegrationSnapshot: () => clientIntegration?.snapshot() || null,
|
|
412
417
|
});
|
|
413
418
|
|
package/docs/ARCHITECTURE.md
CHANGED
|
@@ -44,8 +44,9 @@ Native prediction has a separate loopback transport and an isolated HTTPS agent.
|
|
|
44
44
|
Only its two selected hosts use the App-specific route. Non-configuration requests
|
|
45
45
|
on those hosts are forwarded unchanged. The bridge does not replace Copilot or
|
|
46
46
|
image-provider networking, modify client program files, or install system trust.
|
|
47
|
-
Static upstream proxy routes and bypass rules are preserved.
|
|
48
|
-
|
|
47
|
+
Static upstream proxy routes and bypass rules are preserved. IPv4/IPv6 CIDRs
|
|
48
|
+
match URL IP literals, without DNS. macOS dynamic PAC/WPAD remains unsupported
|
|
49
|
+
and is reported rather than discarded.
|
|
49
50
|
The Windows adapter isolates registration, process, proxy and NTFS
|
|
50
51
|
interfaces in `native-prediction-windows.mjs`. The bridge, overlay, model selection
|
|
51
52
|
and lifecycle remain shared. Windows discovery requires verified registration
|
|
@@ -81,6 +82,41 @@ only, preserves company/user routing, and never treats a saved preference as
|
|
|
81
82
|
proof of a running route or visible candidate. App compatibility is rechecked only
|
|
82
83
|
when its recorded identity changes, before existing trust/port checks are reused.
|
|
83
84
|
|
|
85
|
+
`native-prediction-protocol.mjs` owns bounded archive recognition only, independent
|
|
86
|
+
of certificates, networking and the CLI. It accepts multiple named hashed chunks
|
|
87
|
+
without assuming the first general-settings chunk is the implementation. Signature
|
|
88
|
+
and profile checks remain in the existing platform boundary.
|
|
89
|
+
|
|
90
|
+
Explicit `prediction fix` uses the optional integration's serialized lifecycle,
|
|
91
|
+
not a second adapter or detached predictor. Startup, repair and shutdown cannot
|
|
92
|
+
create overlapping owned listeners. Healthy/current bridges are retained; explicit
|
|
93
|
+
recreation preserves the saved port and existing trust and starts one new supervised
|
|
94
|
+
lifecycle. The supervisor delegates health/route checks to its current bridge after
|
|
95
|
+
recovery, not a closed initial transport. The health endpoint advertises repair
|
|
96
|
+
capability only when the composition root supplies that operation.
|
|
97
|
+
`native-prediction-fix.mjs` is the bounded local management client; the adapter
|
|
98
|
+
enforces loopback/Host/Origin/method/media/body boundaries before dispatch. No new
|
|
99
|
+
inference-path work, watcher, runtime dependency, forced App restart or unverified
|
|
100
|
+
hot-attachment mechanism is introduced.
|
|
101
|
+
|
|
102
|
+
`network-bypass.mjs` compiles static host/IP/port/CIDR rules. The exact pure
|
|
103
|
+
address/matching functions are embedded in the PAC and called by Node, with no
|
|
104
|
+
DNS or system calls. Matching IP literals instead of resolving domains preserves
|
|
105
|
+
Chromium's manual bypass semantics and SOCKS remote DNS. Existing domain matching
|
|
106
|
+
and per-protocol source priority are retained; unused lower-priority static proxy
|
|
107
|
+
addresses do not override selected routes.
|
|
108
|
+
|
|
109
|
+
`native-prediction-environment.mjs` owns bounded, read-only discovery for the
|
|
110
|
+
optional feature. Only enabled startup, explicit fix and failed-listener recovery
|
|
111
|
+
read system policy. Private comparison hashes include effective proxy settings
|
|
112
|
+
and Node trust inputs; public snapshots contain source/type/counts and diagnostic
|
|
113
|
+
states, not addresses, credentials, file paths or hashes. Trust-file inspection is
|
|
114
|
+
diagnostic, not loading or modifying certificate trust. Changed trust inputs need
|
|
115
|
+
a service restart. A changed network snapshot reuses the port but marks a running
|
|
116
|
+
App for PAC reload until it is observed closed or with a different readable PID.
|
|
117
|
+
Failed rechecks preserve the existing bridge and return a non-success result.
|
|
118
|
+
There is no new watcher, global environment owner or inference/image dispatcher.
|
|
119
|
+
|
|
84
120
|
`startup-ui.mjs` is pure terminal presentation: a static A atom, aligned checks
|
|
85
121
|
and the common new/reused-service footer. It depends only on terminal/status
|
|
86
122
|
utilities, not on inference or platform probes. The CLI feeds existing lifecycle
|
package/docs/REFERENCE.md
CHANGED
|
@@ -112,6 +112,8 @@ ccdx prediction on
|
|
|
112
112
|
# Restart the running CCDX process, then launch Codex through ccdx.
|
|
113
113
|
ccdx
|
|
114
114
|
ccdx prediction status
|
|
115
|
+
# Repair only an already-enabled bridge in a compatible running CCDX service:
|
|
116
|
+
ccdx prediction fix
|
|
115
117
|
|
|
116
118
|
# To remove the optional setup, fully quit Codex first:
|
|
117
119
|
ccdx prediction off
|
|
@@ -138,15 +140,21 @@ remain in memory, are never included in PAC responses or diagnostics, and are
|
|
|
138
140
|
sent only to the proxy. TLS verification remains enabled for both proxy and target.
|
|
139
141
|
Other App domains keep the resolved original route; if a bridge fails, its PAC
|
|
140
142
|
fallback uses that route rather than adding an unrequested direct connection.
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
143
|
+
Bypass lists support host/domain patterns, optional ports and IPv4/IPv6 CIDRs.
|
|
144
|
+
CIDRs match only IP literals in URLs, not the resolved addresses of domain names,
|
|
145
|
+
following Chromium's manual bypass semantics. No DNS request is added to proxy
|
|
146
|
+
selection, and SOCKS remote name resolution is not replaced by local resolution.
|
|
147
|
+
IPv6 CIDRs use unbracketed notation (`2001:db8::/32`); IPv6 host/port rules use
|
|
148
|
+
brackets (`[2001:db8::1]:443`). Malformed rules fail explicitly without echoing
|
|
149
|
+
their contents. Node and the generated PAC use the same matcher. Legal unused
|
|
150
|
+
exceptions do not block a direct environment or change it into a proxied route.
|
|
144
151
|
|
|
145
152
|
macOS dynamic PAC/WPAD remains unsupported and is not overwritten. Windows
|
|
146
153
|
automatic routing is opt-in and requires the native worker; a failed worker
|
|
147
154
|
closes its optional bridge while core inference continues. Restart CCDX and Codex
|
|
148
|
-
after changing
|
|
149
|
-
watcher.
|
|
155
|
+
after changing company PAC contents at an unchanged URL; this is not a live
|
|
156
|
+
network-policy watcher. Static/system-setting changes can be rechecked by
|
|
157
|
+
`prediction fix` as described below. Native composer behavior was verified on one Windows machine. Its
|
|
150
158
|
observed upstream route was direct; arbitrary company PAC, integrated-authentication
|
|
151
159
|
and client-certificate policies are not claimed as live-tested. A non-default `CODEX_API_BASE_URL` is
|
|
152
160
|
also preserved and reported as a custom-route conflict; setting it to the normal
|
|
@@ -200,7 +208,7 @@ Since `0.9.34`, an enabled bridge has a lightweight 30-second listener check.
|
|
|
200
208
|
Healthy checks do not spawn processes, call upstream, inspect transcripts or
|
|
201
209
|
probe model endpoints. A failed owned listener/native company-routing worker can
|
|
202
210
|
be recreated on the saved port, using the same checked profile and certificate.
|
|
203
|
-
There are at most three recovery attempts per
|
|
211
|
+
There are at most three automatic recovery attempts per bridge lifecycle, with 30/60/120-second
|
|
204
212
|
backoff gates; checks themselves run every 30 seconds. Occupied ports are not
|
|
205
213
|
stolen or rotated. Startup failures do not gain a retry loop, and configuration
|
|
206
214
|
HTTP errors or missing gray text alone do not trigger transport restarts. Existing
|
|
@@ -208,6 +216,62 @@ requests can fail during an outage and are never replayed by this supervisor.
|
|
|
208
216
|
Disabled prediction startup creates no recovery timer. The existing in-memory
|
|
209
217
|
overlay switch still observes explicit on/off changes independently.
|
|
210
218
|
|
|
219
|
+
`ccdx prediction fix` asks the running adapter for one explicit repair, without
|
|
220
|
+
starting another core service or forcibly restarting Codex. Disabled predictions
|
|
221
|
+
remain off. Healthy/current bridges with unchanged environments are kept; a failed bridge or changed App identity
|
|
222
|
+
reuses the saved port, certificate and verified profile. Compatibility, certificate,
|
|
223
|
+
company proxy and port-ownership checks are not bypassed. Certificates are not renewed
|
|
224
|
+
by fix; setup problems can still require a normal closed-App `prediction on` action.
|
|
225
|
+
An explicit successful recreation starts a fresh three-attempt automatic recovery
|
|
226
|
+
lifecycle; it is not an automatic retry loop for initialization failures.
|
|
227
|
+
|
|
228
|
+
Since `0.9.37`, fix rechecks system proxy settings and compares the effective
|
|
229
|
+
network snapshot before replacing a listener. A changed valid snapshot recreates
|
|
230
|
+
only the optional bridge on its saved port, retaining certificate/profile checks.
|
|
231
|
+
A running App may cache its earlier PAC, so `needs_app_relaunch` (exit 1) remains
|
|
232
|
+
until inspection observes it closed or with a different readable main PID. No App
|
|
233
|
+
is forced closed. A failed recheck reports `environment_preserved` (exit 1) and
|
|
234
|
+
keeps the previous bridge; this is not a successful application of the new policy.
|
|
235
|
+
|
|
236
|
+
Environment variables belong to the running service's process. A new terminal's
|
|
237
|
+
variables are not copied into it by fix. Node trust inputs, including
|
|
238
|
+
`NODE_EXTRA_CA_CERTS`, are startup settings, not a hot-reload interface. Changed
|
|
239
|
+
inputs or changed readable extra-CA content report `needs_service_restart` (exit 1)
|
|
240
|
+
without recreating certificates or claiming new trust was loaded. Extra-CA files
|
|
241
|
+
are inspected read-only up to 1 MiB; `configured` means readable PEM certificates,
|
|
242
|
+
not proof that they were loaded or trusted. Missing/invalid/oversized bundles are
|
|
243
|
+
reported diagnostically; no root is imported and TLS verification remains required.
|
|
244
|
+
|
|
245
|
+
Startup, `status`, `prediction status/fix` and a running-adapter `doctor` use the
|
|
246
|
+
same sanitized environment summary: source/type, exception/CIDR counts, trust-file
|
|
247
|
+
state and adaptation/restart status. They do not print proxy credentials, internal
|
|
248
|
+
rules, CA paths or private comparison hashes. Status/doctor reuse runtime evidence
|
|
249
|
+
instead of spawning another proxy probe. Disabled predictions perform no prediction
|
|
250
|
+
environment discovery, CA-file inspection or worker/timer startup. Existing App
|
|
251
|
+
paths, user settings, npm/PATH/prefix, permissions and terminal policies remain
|
|
252
|
+
owned by their existing modules; there is no global auto-configuration framework.
|
|
253
|
+
|
|
254
|
+
The command checks the adapter's advertised `prediction-fix-v1` capability before
|
|
255
|
+
posting bounded JSON to the native-loopback-only `/_ccdx/prediction/fix` endpoint.
|
|
256
|
+
Browser Origin headers, remote peers and non-JSON bodies are refused. A repair does
|
|
257
|
+
not count as model traffic. An older running adapter needs one upgrade/service restart
|
|
258
|
+
to gain this endpoint; the new CLI cannot hot-upgrade an old Node process.
|
|
259
|
+
|
|
260
|
+
Repair reports bridge readiness separately from the inspected App launch route.
|
|
261
|
+
If a running App has no verified route, fix returns a partial result (exit 1), preserves
|
|
262
|
+
its process and asks for a normal full quit followed by `ccdx`. A closed App is not
|
|
263
|
+
launched by fix; run `ccdx` to open it. Neither HTTP 200 nor a verified route proves
|
|
264
|
+
that gray text appeared. Normal replies, image setup and account state are not changed.
|
|
265
|
+
Unavailable/ambiguous process inspection reports `route_unverified` (exit 1), not
|
|
266
|
+
a definite missing route or an instruction to restart an otherwise healthy App.
|
|
267
|
+
|
|
268
|
+
App compatibility inspection checks up to 16 named main candidates and 16 named
|
|
269
|
+
general-settings candidates, rather than assuming the first hashed chunk owns the
|
|
270
|
+
implementation. A forwarding chunk therefore cannot hide a later real settings
|
|
271
|
+
module. Reads retain a 32 MiB header limit, 32/4 MiB per-entry main/settings limits,
|
|
272
|
+
a combined 36 MiB source limit, archive bounds/snapshot checks and platform signature
|
|
273
|
+
verification. Unknown layouts remain unsupported instead of being patched blindly.
|
|
274
|
+
|
|
211
275
|
Before enabled App launch, CCDX can persist its PAC in that verified profile's
|
|
212
276
|
`Default/Preferences`, but only in a direct environment, with initialized regular
|
|
213
277
|
profile files and the App closed. Existing explicit App proxies and all company
|
package/package.json
CHANGED
package/src/adapter.mjs
CHANGED
|
@@ -12,7 +12,7 @@ import { createRequestId, runWithRequestContext } from "./request-context.mjs";
|
|
|
12
12
|
import { createStreamPerformanceMetrics } from "./stream-performance.mjs";
|
|
13
13
|
import { status } from "./status.mjs";
|
|
14
14
|
import { createTerminalActivityIndicator } from "./terminal-activity.mjs";
|
|
15
|
-
import { ADAPTER_HEALTH_PATH, adapterHealthPayload } from "./running-adapter.mjs";
|
|
15
|
+
import { ADAPTER_HEALTH_PATH, ADAPTER_PREDICTION_FIX_PATH, PREDICTION_FIX_CAPABILITY, adapterHealthPayload } from "./running-adapter.mjs";
|
|
16
16
|
import { createResponsesCompactHandler, createResponsesHandler } from "./responses-handler.mjs";
|
|
17
17
|
import { createResponsesImagePressureController } from "./responses-image-pressure.mjs";
|
|
18
18
|
import { createResponseFailureDiagnostics, buildHttpFailureDetails } from "./response-failures.mjs";
|
|
@@ -253,7 +253,38 @@ export function createAdapterHandler(options = {}) {
|
|
|
253
253
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
254
254
|
const predictionPac = isLoopbackAddress(req.socket?.remoteAddress) && isLoopbackHostHeader(req.headers?.host)
|
|
255
255
|
? options.nativePredictionPac?.() : null;
|
|
256
|
-
|
|
256
|
+
const health = adapterHealthPayload();
|
|
257
|
+
res.end(JSON.stringify({ ...health,
|
|
258
|
+
capabilities: [...health.capabilities, ...(typeof options.fixPrediction === "function" ? [PREDICTION_FIX_CAPABILITY] : [])],
|
|
259
|
+
...(predictionPac ? { native_prediction_pac: predictionPac } : {}) }));
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
if (pathname === ADAPTER_PREDICTION_FIX_PATH) {
|
|
264
|
+
if (!isLoopbackAddress(req.socket?.remoteAddress) || req.headers?.host === undefined
|
|
265
|
+
|| !isLoopbackHostHeader(req.headers.host) || Object.hasOwn(req.headers, "origin")) {
|
|
266
|
+
sendJsonError(res, httpError("Prediction repair is available only to native loopback clients", 403));return;
|
|
267
|
+
}
|
|
268
|
+
if (req.method !== "POST") {
|
|
269
|
+
res.setHeader?.("Allow", "POST");sendJsonError(res, httpError("Prediction repair requires POST", 405));return;
|
|
270
|
+
}
|
|
271
|
+
if (String(req.headers["content-type"] || "").split(";", 1)[0].trim().toLowerCase() !== "application/json") {
|
|
272
|
+
sendJsonError(res, httpError("Prediction repair requires application/json", 415));return;
|
|
273
|
+
}
|
|
274
|
+
if (typeof options.fixPrediction !== "function") {
|
|
275
|
+
sendJsonError(res, httpError("This adapter does not support prediction repair; upgrade and restart CCDX once", 503));return;
|
|
276
|
+
}
|
|
277
|
+
const abort = createRequestAbort(req, res);abort.setTimeout(2000);
|
|
278
|
+
try {
|
|
279
|
+
const body = await readJsonBody(req, { maxBodyBytes: 1024, maxDecodedBodyBytes: 1024, signal: abort.signal });
|
|
280
|
+
if (!body || Object.keys(body).length !== 1 || body.action !== "fix") throw httpError("Expected prediction repair action: fix", 400);
|
|
281
|
+
abort.clearTimeout();
|
|
282
|
+
const result = await options.fixPrediction();
|
|
283
|
+
if (!res.destroyed && !res.writableEnded) {
|
|
284
|
+
res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store" });res.end(JSON.stringify(result));
|
|
285
|
+
}
|
|
286
|
+
} catch (error) { sendJsonError(res, error, 503); }
|
|
287
|
+
finally { abort.cleanup(); }
|
|
257
288
|
return;
|
|
258
289
|
}
|
|
259
290
|
|
|
@@ -397,6 +428,7 @@ export function createAdapterHandler(options = {}) {
|
|
|
397
428
|
const trackRequest = pathname !== ADAPTER_HEALTH_PATH
|
|
398
429
|
&& pathname !== ADAPTER_STATUS_PATH
|
|
399
430
|
&& pathname !== ADAPTER_CACHE_PATH
|
|
431
|
+
&& pathname !== ADAPTER_PREDICTION_FIX_PATH
|
|
400
432
|
&& !DASHBOARD_API_PATHS.has(pathname)
|
|
401
433
|
&& !((req.method === "GET" || req.method === "HEAD") && DASHBOARD_PATHS.has(pathname));
|
|
402
434
|
const routeName = classifyAdapterRoute(req.method, pathname);
|
package/src/cli-options.mjs
CHANGED
|
@@ -255,7 +255,7 @@ export function parseCliArgs(args = []) {
|
|
|
255
255
|
}
|
|
256
256
|
if (command === "prediction") {
|
|
257
257
|
const [action = "status", ...extra] = rest;
|
|
258
|
-
if (!["on", "off", "status"].includes(action)) throw new Error("Prediction action must be on, off, or
|
|
258
|
+
if (!["on", "off", "status", "fix"].includes(action)) throw new Error("Prediction action must be on, off, status, or fix");
|
|
259
259
|
if (extra.length) unexpectedArgs(extra);
|
|
260
260
|
return baseCommand("prediction", { action });
|
|
261
261
|
}
|
|
@@ -372,7 +372,7 @@ function topicHelp(name, topic) {
|
|
|
372
372
|
"image-status": `Usage:\n ${name} image-status\n\nShows provider configuration and locally advertised generation/editing tools without generating an image or exposing its API key.`,
|
|
373
373
|
"auto-review-model": `Usage:\n ${name} auto-review-model\n\nSelect a Responses model, then an advertised reasoning effort. Enter keeps the default/current choice; q cancels both steps without saving. Effort 0 follows the client (low when omitted). Settings apply only to Auto-review on the next request; no client patch or restart is required for adapters running 0.9.13 or newer.`,
|
|
374
374
|
"suggestion": `The CCDX prediction panel has been retired. Run ${name} suggestion off to safely remove unchanged CCDX registrations. This cleanup does not change native predictions; see ${name} prediction --help for that separate opt-in feature.`,
|
|
375
|
-
prediction: `Usage:\n ${name} prediction [status|on|off]\n\nOptional native next-message predictions; off by default. macOS and Windows. Windows requires the registered official MSIX App, an initialized profile, Windows PowerShell and .NET Framework 4.7.2+; Git/OpenSSL is not required for prediction setup. Quit Codex before on/off, then restart ccdx. On adds private App-profile certificate trust and an App-only route for chatgpt.com and ab.chatgpt.com. HTTPS on those hosts is decrypted locally; only prediction configuration is changed. No client program files, OS trust, account permissions, MCP or Hooks are changed. Static HTTP/HTTPS/SOCKS5 proxies and bypass rules are preserved. Windows supports company PAC/WPAD; macOS dynamic PAC/WPAD
|
|
375
|
+
prediction: `Usage:\n ${name} prediction [status|on|off|fix]\n\nOptional native next-message predictions; off by default. macOS and Windows. Windows requires the registered official MSIX App, an initialized profile, Windows PowerShell and .NET Framework 4.7.2+; Git/OpenSSL is not required for prediction setup. Quit Codex before on/off, then restart ccdx. On adds private App-profile certificate trust and an App-only route for chatgpt.com and ab.chatgpt.com. HTTPS on those hosts is decrypted locally; only prediction configuration is changed. No client program files, OS trust, account permissions, MCP or Hooks are changed. Static HTTP/HTTPS/SOCKS5 proxies and bypass rules are preserved. Windows supports company PAC/WPAD; macOS dynamic PAC/WPAD remains unsupported. Static IPv4/IPv6 CIDRs match URL IP literals without DNS. The bridge port persists across restarts/updates; a busy saved port disables only predictions. Launch/reuse checks the App's actual route; an older random or missing route may require one full App quit. Official prediction configuration is preserved; the conversation's model is used. App updates require another compatibility check. Status distinguishes saved preference and observed config traffic from unverified candidate visibility.\n\nFix asks a compatible running CCDX adapter to repair the enabled bridge once on its saved port. It never enables predictions, renews certificates or force-restarts Codex. Healthy unchanged bridges are retained. Fix rechecks system proxy settings. Changed routes may need a normal App relaunch to reload cached PAC; failed rechecks preserve the previous bridge with a nonzero exit. Process environment variables and Node trust are not hot-reloaded; changed trust inputs need a CCDX service restart. Startup, status and doctor share sanitized environment diagnostics. Missing App routes require a normal full quit and ccdx launch; partial repair exits 1. An older adapter must first be upgraded and restarted once to gain this repair endpoint.`,
|
|
376
376
|
update: `Usage:\n ${name} update [npm|github]\n\nUpdates the global package from the configured npm registry or the latest stable GitHub release. With no source, an interactive terminal prompts for one. Windows uses system cmd.exe to run npm.cmd without changing PowerShell policy; use the .cmd entrypoint if scripts are blocked. GitHub installs require Git on PATH and dependencies may still use the configured npm registry. Restart the running adapter after installation.`,
|
|
377
377
|
version: `Usage:\n ${name} --version`,
|
|
378
378
|
};
|
|
@@ -398,7 +398,7 @@ export function cliHelp(commandName = "ccdx", topic = "") {
|
|
|
398
398
|
${name} disable-image
|
|
399
399
|
${name} image-status
|
|
400
400
|
${name} auto-review-model
|
|
401
|
-
${name} prediction [status|on|off]
|
|
401
|
+
${name} prediction [status|on|off|fix]
|
|
402
402
|
${name} update [npm|github]
|
|
403
403
|
${name} --version
|
|
404
404
|
${name} --help
|
package/src/cli-status.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ADAPTER_STATUS_PATH, adapterBaseUrl } from "./running-adapter.mjs";
|
|
2
2
|
import { status } from "./status.mjs";
|
|
3
3
|
import { terminalCell } from "./cli-table.mjs";
|
|
4
|
+
import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
|
|
4
5
|
|
|
5
6
|
function finiteNumber(value) {
|
|
6
7
|
const number = Number(value);
|
|
@@ -194,6 +195,7 @@ export function formatAdapterStatus({ baseUrl, data }, { commandName = "ccdx", c
|
|
|
194
195
|
lines.push(status("info", `Native predictions: ${prediction.configured ? "on" : "off"}; bridge ${prediction.bridge}; client route ${prediction.client_route}; visible candidate unknown`));
|
|
195
196
|
if (prediction.launch_route) lines.push(status("info", `Prediction self-check: App route ${prediction.launch_route}; persistent route ${prediction.persistence || "unknown"}; ${count(prediction.recovery?.recovered)} bridge recoveries, ${count(prediction.recovery?.attempts)}/3 attempts used`));
|
|
196
197
|
if (prediction.reason) lines.push(status("warn", terminalCell(prediction.reason).slice(0, 400)));
|
|
198
|
+
if (prediction.environment) lines.push(status("info", formatPredictionEnvironment(prediction.environment)));
|
|
197
199
|
}
|
|
198
200
|
if (data.profiles?.codex) {
|
|
199
201
|
lines.push(status("info", `Profile: ${profileSummary("Codex", data.profiles.codex)}`));
|
|
@@ -4,12 +4,47 @@ import { ensureCodexThreadCompression } from "./codex-thread-compression.mjs";
|
|
|
4
4
|
import { runInBackground } from "./startup.mjs";
|
|
5
5
|
import { createPredictionState } from "./native-prediction-state.mjs";
|
|
6
6
|
import { supervisePrediction } from "./native-prediction-recovery.mjs";
|
|
7
|
+
import { operationErrorDetails } from "./operation-error.mjs";
|
|
7
8
|
|
|
8
9
|
// The CLI composes the services; this module owns optional client integration
|
|
9
10
|
// lifecycle. It never forwards model requests or depends on dashboard rendering.
|
|
10
|
-
export function createClientIntegration({ port, host, info = () => {}, warning = () => {}, configLog
|
|
11
|
+
export function createClientIntegration({ port, host, info = () => {}, warning = () => {}, configLog,
|
|
12
|
+
startPrediction = async options => (await import("./native-prediction.mjs")).startNativePrediction(options) } = {}) {
|
|
11
13
|
const prediction = createPredictionState();
|
|
12
14
|
let native = null;
|
|
15
|
+
let operation = null, operationName = null, closed = false;
|
|
16
|
+
let pendingRoutePid = null;
|
|
17
|
+
async function startPredictionBridge(expectedPort, environment) {
|
|
18
|
+
const started = await startPrediction({ state: prediction, warning: info,
|
|
19
|
+
...(environment ? { environment } : {}), ...(expectedPort ? { expectedPort } : {}) });
|
|
20
|
+
if (!started) return null;
|
|
21
|
+
if (closed) { await started.close();return null; }
|
|
22
|
+
const port = Number(new URL(started.pacUrl).port);
|
|
23
|
+
prediction.supervising();
|
|
24
|
+
let latest = started;
|
|
25
|
+
return supervisePrediction({ native: started, state: prediction, warning,
|
|
26
|
+
restart: async () => {
|
|
27
|
+
const check = await latest.inspectEnvironment?.();
|
|
28
|
+
if (check?.requiresServiceRestart) throw Object.assign(new Error("Node trust settings changed; restart CCDX before restoring the prediction bridge"), {
|
|
29
|
+
code: "tls_restart_required", predictionEnvironment: { ...check.next.summary, status: "needs_service_restart" } });
|
|
30
|
+
const resumed = await startPrediction({ state: prediction, warning: info, expectedPort: port, ...(check ? { environment: check.next } : {}) });
|
|
31
|
+
if (resumed) latest = resumed;
|
|
32
|
+
if (check?.changed && resumed) {
|
|
33
|
+
let route;try { route = await resumed.inspectRoute?.(); } catch {}
|
|
34
|
+
const pid = resumed.routeProcessId?.();pendingRoutePid = route === "closed" ? null : Number.isInteger(pid) ? pid : "unknown";
|
|
35
|
+
prediction.environment({ ...check.next.summary, status: pendingRoutePid === null ? "adapted" : "needs_app_relaunch" }, { resetTraffic: true });
|
|
36
|
+
if (pendingRoutePid !== null) warning("Prediction network settings changed; normally relaunch Codex to reload its PAC. No App was restarted");
|
|
37
|
+
}
|
|
38
|
+
return resumed;
|
|
39
|
+
} });
|
|
40
|
+
}
|
|
41
|
+
function serialize(name, task) {
|
|
42
|
+
if (closed) return Promise.reject(new Error("Client integration is closing; repair was skipped"));
|
|
43
|
+
if (operation) return operationName === name ? operation : operation.then(() => serialize(name, task));
|
|
44
|
+
operationName = name;
|
|
45
|
+
operation = Promise.resolve().then(task).finally(() => { operation = null;operationName = null; });
|
|
46
|
+
return operation;
|
|
47
|
+
}
|
|
13
48
|
return {
|
|
14
49
|
async configure() {
|
|
15
50
|
try {
|
|
@@ -28,21 +63,62 @@ export function createClientIntegration({ port, host, info = () => {}, warning =
|
|
|
28
63
|
}
|
|
29
64
|
return { imageEnabled: enabled, imageMcpSkipped, compressionSetup: runInBackground(ensureCodexThreadCompression) };
|
|
30
65
|
},
|
|
31
|
-
async
|
|
66
|
+
start() { return serialize("start", async () => {
|
|
32
67
|
try {
|
|
33
|
-
|
|
34
|
-
native = await startNativePrediction({ state: prediction, warning: info });
|
|
35
|
-
if (native) {
|
|
36
|
-
const expectedPort = Number(new URL(native.pacUrl).port);
|
|
37
|
-
native = supervisePrediction({ native, state: prediction, warning,
|
|
38
|
-
restart: () => startNativePrediction({ state: prediction, warning: info, expectedPort }) });
|
|
39
|
-
}
|
|
68
|
+
native ||= await startPredictionBridge();
|
|
40
69
|
} catch (error) { prediction.unavailable(error); warning(`${error.message}. Core startup will continue.`); }
|
|
41
70
|
return native;
|
|
42
|
-
},
|
|
71
|
+
}); },
|
|
72
|
+
fix() { return serialize("fix", async () => {
|
|
73
|
+
let restarted = false, route = "unknown";
|
|
74
|
+
let environmentCheck;
|
|
75
|
+
if (native?.enabled?.() !== false && native?.inspectEnvironment) {
|
|
76
|
+
try {
|
|
77
|
+
environmentCheck = await native.inspectEnvironment();
|
|
78
|
+
if (environmentCheck?.requiresServiceRestart) {
|
|
79
|
+
prediction.environment({ ...prediction.snapshot().environment, tls: environmentCheck.next.summary.tls,
|
|
80
|
+
checked_at: environmentCheck.next.summary.checked_at, status: "needs_service_restart" });
|
|
81
|
+
return { status: "needs_service_restart", bridge_restarted: false, app_route: route, prediction: prediction.snapshot() };
|
|
82
|
+
}
|
|
83
|
+
} catch (error) {
|
|
84
|
+
const details = operationErrorDetails(error);
|
|
85
|
+
prediction.environment({ ...prediction.snapshot().environment, status: "preserved", error: details, checked_at: new Date().toISOString() });
|
|
86
|
+
return { status: "environment_preserved", bridge_restarted: false, app_route: route,
|
|
87
|
+
environment_error: details, prediction: prediction.snapshot() };
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
if (!native?.healthy() || native.enabled?.() === false || native.appCurrent?.() === false || environmentCheck?.changed) {
|
|
92
|
+
const expectedPort = native ? Number(new URL(native.pacUrl).port) : undefined;
|
|
93
|
+
await native?.close();native = null;
|
|
94
|
+
native = await startPredictionBridge(expectedPort, environmentCheck?.next);restarted = Boolean(native);
|
|
95
|
+
} else if (environmentCheck) {
|
|
96
|
+
prediction.environment(environmentCheck.next.summary);
|
|
97
|
+
}
|
|
98
|
+
} catch (error) { prediction.unavailable(error); }
|
|
99
|
+
let routeError = false;
|
|
100
|
+
if (native && !closed) {
|
|
101
|
+
try {
|
|
102
|
+
await native.prepareRoute?.();
|
|
103
|
+
route = await native.inspectRoute?.() || "unverified";
|
|
104
|
+
} catch { routeError = true;warning("Prediction bridge is ready, but App route inspection failed"); }
|
|
105
|
+
}
|
|
106
|
+
const pid = native?.routeProcessId?.();
|
|
107
|
+
if (pendingRoutePid !== null && (route === "closed" || (Number.isInteger(pendingRoutePid) && Number.isInteger(pid) && pid !== pendingRoutePid))) pendingRoutePid = null;
|
|
108
|
+
if (environmentCheck?.changed && native) {
|
|
109
|
+
pendingRoutePid = route === "closed" ? null : Number.isInteger(pid) ? pid : "unknown";
|
|
110
|
+
prediction.environment({ ...environmentCheck.next.summary, status: pendingRoutePid === null ? "adapted" : "needs_app_relaunch" }, { resetTraffic: true });
|
|
111
|
+
} else if (pendingRoutePid !== null && native) {
|
|
112
|
+
prediction.environment({ ...prediction.snapshot().environment, status: "needs_app_relaunch" });
|
|
113
|
+
}
|
|
114
|
+
const snapshot = prediction.snapshot();
|
|
115
|
+
const status = !snapshot.configured && snapshot.bridge !== "unavailable" ? "disabled" : snapshot.bridge !== "running" ? "failed"
|
|
116
|
+
: pendingRoutePid !== null ? "needs_app_relaunch" : route === "verified" || route === "closed" ? "ready" : route === "missing" ? "needs_app_relaunch" : "route_unverified";
|
|
117
|
+
return { status, bridge_restarted: restarted, app_route: route, ...(routeError ? { route_error: true } : {}), prediction: snapshot };
|
|
118
|
+
}); },
|
|
43
119
|
pacUrl() { return native?.pacUrl || null; },
|
|
44
120
|
launched(route) { prediction.launch(route); },
|
|
45
121
|
snapshot() { return { prediction: prediction.snapshot() }; },
|
|
46
|
-
async close() { await native?.close();
|
|
122
|
+
async close() { closed = true;try { await operation; } finally { await native?.close();native = null; } },
|
|
47
123
|
};
|
|
48
124
|
}
|
|
@@ -4,6 +4,7 @@ import path from "node:path";
|
|
|
4
4
|
import { execFile } from "node:child_process";
|
|
5
5
|
import { promisify } from "node:util";
|
|
6
6
|
import { readAdapterStatus } from "./cli-status.mjs";
|
|
7
|
+
import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
|
|
7
8
|
|
|
8
9
|
export function parseRunningCodexApps(stdout) {
|
|
9
10
|
const apps = new Map();
|
|
@@ -51,6 +52,8 @@ export async function inspectCodexClient({
|
|
|
51
52
|
const { data } = await readStatus({ host, port, fetchImpl, timeoutMs: 1500 });
|
|
52
53
|
const source = ["live", "cache", "built-in"].includes(data.models?.source) ? data.models.source : "unknown";
|
|
53
54
|
checks.push({ kind: "info", message: `Running adapter ${data.version}; upstream model directory source: ${source}` });
|
|
55
|
+
const prediction = data.client_integrations?.prediction;
|
|
56
|
+
if (prediction?.environment) checks.push({ kind: prediction.environment.status === "adapted" ? "info" : "warn", message: formatPredictionEnvironment(prediction.environment) });
|
|
54
57
|
const catalog = data.models?.client_catalog;
|
|
55
58
|
const observed = catalog?.last_request;
|
|
56
59
|
if (!catalog) {
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { createHash, X509Certificate } from "node:crypto";
|
|
3
|
+
import { readBoundedFileSync } from "./bounded-file.mjs";
|
|
4
|
+
import { resolveNetworkRoute, networkRouteSnapshot } from "./network-route.mjs";
|
|
5
|
+
import { windowsProxySettings, windowsProxyText } from "./native-prediction-windows.mjs";
|
|
6
|
+
|
|
7
|
+
const digest = value => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
8
|
+
|
|
9
|
+
function trustSnapshot(env, readFile) {
|
|
10
|
+
let extraCa = "not_set", content = null;
|
|
11
|
+
if (env.NODE_EXTRA_CA_CERTS) {
|
|
12
|
+
try {
|
|
13
|
+
const pem = readFile(env.NODE_EXTRA_CA_CERTS, { maxBytes: 1024 * 1024, encoding: "utf8" });
|
|
14
|
+
content = digest(pem);
|
|
15
|
+
const certificates = pem.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g) || [];
|
|
16
|
+
if (!certificates.length) throw new Error("invalid");
|
|
17
|
+
for (const certificate of certificates) new X509Certificate(certificate);
|
|
18
|
+
extraCa = "configured";
|
|
19
|
+
} catch { extraCa = "unreadable_or_invalid"; }
|
|
20
|
+
}
|
|
21
|
+
// Keys and paths participate only in a private comparison, never diagnostics.
|
|
22
|
+
return { key: digest([env.NODE_EXTRA_CA_CERTS, env.NODE_OPTIONS, env.NODE_USE_SYSTEM_CA,
|
|
23
|
+
env.SSL_CERT_FILE, env.SSL_CERT_DIR, content]),
|
|
24
|
+
summary: { extra_ca: extraCa, tls_verification: "required", changes_require_service_restart: true } };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Called only for enabled prediction startup or an explicit fix. No system
|
|
28
|
+
// policy, trust store, environment, PATH or account is written by discovery.
|
|
29
|
+
export function inspectPredictionEnvironment({ env = process.env, platform = process.platform,
|
|
30
|
+
exec = execFileSync, readFile = readBoundedFileSync, now = () => new Date().toISOString() } = {}) {
|
|
31
|
+
const trust = trustSnapshot(env, readFile);
|
|
32
|
+
let network;
|
|
33
|
+
try {
|
|
34
|
+
if (platform === "win32") {
|
|
35
|
+
const settings = windowsProxySettings({ exec, env });
|
|
36
|
+
if (!settings.autoDetect && !settings.pac) network = { networkRoute: resolveNetworkRoute({ env, systemProxy: windowsProxyText(settings) }) };
|
|
37
|
+
else {
|
|
38
|
+
const explicit = resolveNetworkRoute({ env });
|
|
39
|
+
if (explicit.http || explicit.https || explicit.bypass.length) {
|
|
40
|
+
throw Object.assign(new Error("Windows automatic proxy and explicit proxy environment rules require separate routing; existing routes were preserved"), { code: "proxy_route_conflict" });
|
|
41
|
+
}
|
|
42
|
+
network = { settings };
|
|
43
|
+
}
|
|
44
|
+
} else {
|
|
45
|
+
const systemProxy = exec("/usr/sbin/scutil", ["--proxy"], { encoding: "utf8", timeout: 2000, maxBuffer: 64 * 1024 });
|
|
46
|
+
network = { networkRoute: resolveNetworkRoute({ env, systemProxy }) };
|
|
47
|
+
}
|
|
48
|
+
} catch (error) {
|
|
49
|
+
error.predictionEnvironment = { status: "unavailable", checked_at: now(), tls: trust.summary };
|
|
50
|
+
throw error;
|
|
51
|
+
}
|
|
52
|
+
const plan = network.networkRoute;
|
|
53
|
+
const summary = { status: "adapted", checked_at: now(),
|
|
54
|
+
network: plan ? { ...networkRouteSnapshot(plan), cidr_rules: plan.bypass.filter(rule => rule.includes("/")).length,
|
|
55
|
+
dns: "system_or_proxy", http_source: plan.http?.source || "direct" }
|
|
56
|
+
: { source: "system", type: "auto", bypass_rules: null, cidr_rules: null, dns: "native_policy" },
|
|
57
|
+
tls: trust.summary };
|
|
58
|
+
return { network, networkKey: digest(network), trustKey: trust.key, summary };
|
|
59
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { checkRunningAdapter, ADAPTER_PREDICTION_FIX_PATH, PREDICTION_FIX_CAPABILITY } from "./running-adapter.mjs";
|
|
2
|
+
import { readBoundedResponseText } from "./upstream-body.mjs";
|
|
3
|
+
|
|
4
|
+
// Management request only. An older running adapter cannot be hot-upgraded by
|
|
5
|
+
// a new CLI, and a successful HTTP response is not proof of a visible prediction.
|
|
6
|
+
export async function requestPredictionFix({ host = "127.0.0.1", port = 2026, fetchImpl = fetch,
|
|
7
|
+
timeoutMs = 45_000, probeTimeoutMs = 5000 } = {}) {
|
|
8
|
+
const probe = await checkRunningAdapter({ host, port, fetchImpl: (url, options) => fetchImpl(url, { ...options, redirect: "error" }), timeoutMs: probeTimeoutMs,
|
|
9
|
+
requiredCapabilities: [PREDICTION_FIX_CAPABILITY] });
|
|
10
|
+
if (!probe.ok) throw new Error(probe.incompatible
|
|
11
|
+
? "The running adapter lacks compatible prediction repair. Upgrade and restart the CCDX service once; the App was not restarted."
|
|
12
|
+
: "Could not reach a running CCDX adapter. Start ccdx, then retry ccdx prediction fix.");
|
|
13
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
14
|
+
const response = await fetchImpl(probe.baseUrl + ADAPTER_PREDICTION_FIX_PATH, {
|
|
15
|
+
method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" },
|
|
16
|
+
body: JSON.stringify({ action: "fix" }), redirect: "error", signal,
|
|
17
|
+
});
|
|
18
|
+
const text = await readBoundedResponseText(response, { maxBytes: 64 * 1024, label: "Prediction repair response", signal });
|
|
19
|
+
if (!response.ok) throw new Error(`Prediction repair returned HTTP ${response.status}; no App was restarted`);
|
|
20
|
+
let value;try { value = JSON.parse(text); } catch {}
|
|
21
|
+
if (!["ready", "disabled", "failed", "needs_app_relaunch", "route_unverified", "needs_service_restart", "environment_preserved"].includes(value?.status)
|
|
22
|
+
|| !["running", "stopped", "unavailable", "recovering"].includes(value?.prediction?.bridge)
|
|
23
|
+
|| value.prediction.candidate !== "unknown"
|
|
24
|
+
|| (["ready", "needs_app_relaunch", "route_unverified"].includes(value.status) && value.prediction.bridge !== "running")
|
|
25
|
+
|| (value.status === "ready" && !["verified", "closed"].includes(value.app_route))) throw new Error("Adapter returned an invalid prediction repair result");
|
|
26
|
+
return value;
|
|
27
|
+
}
|
|
@@ -11,6 +11,7 @@ import { codexPaths } from "./codex-paths.mjs";
|
|
|
11
11
|
import { assertWindowsCodexClosed, installedWindowsPredictionApp, windowsPredictionProfile,
|
|
12
12
|
windowsPrivatePredictionPath } from "./native-prediction-windows.mjs";
|
|
13
13
|
import { windowsPredictionCertificate } from "./windows-prediction-certificate.mjs";
|
|
14
|
+
import { inspectPredictionArchive } from "./native-prediction-protocol.mjs";
|
|
14
15
|
|
|
15
16
|
export function predictionPaths({ env = process.env, home = os.homedir(), platform = process.platform, app } = {}) {
|
|
16
17
|
const directory = path.join(path.dirname(userSettingsPath({ env, home })), "native-prediction");
|
|
@@ -64,35 +65,17 @@ export function installedPredictionApp({ exec = execFileSync, platform = process
|
|
|
64
65
|
for (const candidate of candidates) {
|
|
65
66
|
const { app, archive } = candidate;
|
|
66
67
|
if (!fs.existsSync(archive)) continue;
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
const
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
fs.readSync(fd, bytes, 0, bytes.length, 8 + prefix.readUInt32LE(4) + Number(entry.offset));
|
|
79
|
-
const source = bytes.toString();
|
|
80
|
-
if (!["/wham/predictions/config", "experimentalPredictionMode"].every((value) => source.includes(value))) continue;
|
|
81
|
-
const renderer = Object.entries(JSON.parse(header).files?.webview?.files?.assets?.files || {})
|
|
82
|
-
.find(([name]) => /^general-settings-[\w-]+\.js$/.test(name))?.[1];
|
|
83
|
-
if (!renderer || renderer.unpacked || renderer.size > 4 * 1024 * 1024) continue;
|
|
84
|
-
const rendererBytes = Buffer.alloc(renderer.size);
|
|
85
|
-
fs.readSync(fd, rendererBytes, 0, rendererBytes.length, 8 + prefix.readUInt32LE(4) + Number(renderer.offset));
|
|
86
|
-
if (!rendererBytes.includes(Buffer.from("4290031608"))) continue;
|
|
87
|
-
if (platform !== "win32") exec("/usr/bin/codesign", ["--verify", "--deep", "--strict", app], { stdio: "pipe", timeout: 15_000 });
|
|
88
|
-
const stat = fs.statSync(archive);
|
|
89
|
-
if (platform === "win32") {
|
|
90
|
-
const executable = fs.statSync(app);
|
|
91
|
-
return { ...candidate, profile: windowsPredictionProfile({ app: candidate, env: options.env, preferredProfile: options.preferredProfile }),
|
|
92
|
-
size: stat.size, mtimeMs: stat.mtimeMs, executableSize: executable.size, executableMtimeMs: executable.mtimeMs };
|
|
93
|
-
}
|
|
94
|
-
return { app, archive, size: stat.size, mtimeMs: stat.mtimeMs };
|
|
95
|
-
} finally { fs.closeSync(fd); }
|
|
68
|
+
const inspected = inspectPredictionArchive(archive);
|
|
69
|
+
if (!inspected.compatible) continue;
|
|
70
|
+
if (platform !== "win32") exec("/usr/bin/codesign", ["--verify", "--deep", "--strict", app], { stdio: "pipe", timeout: 15_000 });
|
|
71
|
+
const stat = fs.statSync(archive);
|
|
72
|
+
if (stat.size !== inspected.size || stat.mtimeMs !== inspected.mtimeMs) throw new Error("Codex App changed during compatibility verification");
|
|
73
|
+
if (platform === "win32") {
|
|
74
|
+
const executable = fs.statSync(app);
|
|
75
|
+
return { ...candidate, profile: windowsPredictionProfile({ app: candidate, env: options.env, preferredProfile: options.preferredProfile }),
|
|
76
|
+
size: stat.size, mtimeMs: stat.mtimeMs, executableSize: executable.size, executableMtimeMs: executable.mtimeMs };
|
|
77
|
+
}
|
|
78
|
+
return { app, archive, size: stat.size, mtimeMs: stat.mtimeMs };
|
|
96
79
|
}
|
|
97
80
|
throw new Error("This Codex App does not expose the verified native prediction protocol; setup was skipped");
|
|
98
81
|
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
|
|
3
|
+
const MAX_HEADER_BYTES = 32 * 1024 * 1024;
|
|
4
|
+
const MAX_SOURCE_BYTES = 36 * 1024 * 1024;
|
|
5
|
+
|
|
6
|
+
// Inspect only packed, named protocol/settings candidates in the installed
|
|
7
|
+
// archive. A small forwarding chunk must not hide its real implementation.
|
|
8
|
+
export function inspectPredictionArchive(archive) {
|
|
9
|
+
const fd = fs.openSync(archive, "r");
|
|
10
|
+
try {
|
|
11
|
+
const before = fs.fstatSync(fd);
|
|
12
|
+
const read = (size, offset) => {
|
|
13
|
+
if (!before.isFile() || !Number.isSafeInteger(size) || size < 0 || !Number.isSafeInteger(offset)
|
|
14
|
+
|| offset < 0 || offset + size > before.size) throw new Error("Invalid prediction App archive bounds");
|
|
15
|
+
const bytes = Buffer.alloc(size);
|
|
16
|
+
if (fs.readSync(fd, bytes, 0, size, offset) !== size) throw new Error("Prediction App archive changed during inspection");
|
|
17
|
+
return bytes;
|
|
18
|
+
};
|
|
19
|
+
const prefix = read(16, 0), headerSize = prefix.readUInt32LE(12);
|
|
20
|
+
if (headerSize > MAX_HEADER_BYTES) throw new Error("Prediction App archive header exceeds its inspection limit");
|
|
21
|
+
const tree = JSON.parse(read(headerSize, 16)).files;
|
|
22
|
+
const base = 8 + prefix.readUInt32LE(4);
|
|
23
|
+
let sourceBytes = 0;
|
|
24
|
+
const contains = (files, pattern, markers, maxEntryBytes) => {
|
|
25
|
+
const entries = Object.entries(files || {}).filter(([name]) => pattern.test(name));
|
|
26
|
+
if (entries.length > 16) throw new Error("Prediction App protocol candidates exceed their inspection limit");
|
|
27
|
+
for (const [, entry] of entries) {
|
|
28
|
+
if (!entry || typeof entry !== "object") throw new Error("Invalid prediction App archive entry");
|
|
29
|
+
if (entry.unpacked) continue;
|
|
30
|
+
if (!Number.isSafeInteger(entry.size) || entry.size > maxEntryBytes
|
|
31
|
+
|| sourceBytes + entry.size > MAX_SOURCE_BYTES) throw new Error("Prediction App source exceeds its inspection limit");
|
|
32
|
+
sourceBytes += entry.size;
|
|
33
|
+
const bytes = read(entry.size, base + Number(entry.offset));
|
|
34
|
+
if (markers.every(marker => bytes.includes(Buffer.from(marker)))) return true;
|
|
35
|
+
}
|
|
36
|
+
return false;
|
|
37
|
+
};
|
|
38
|
+
const compatible = contains(tree?.[".vite"]?.files?.build?.files, /^main-[\w-]+\.js$/,
|
|
39
|
+
["/wham/predictions/config", "experimentalPredictionMode"], 32 * 1024 * 1024)
|
|
40
|
+
&& contains(tree?.webview?.files?.assets?.files, /^general-settings-[\w-]+\.js$/, ["4290031608"], 4 * 1024 * 1024);
|
|
41
|
+
const after = fs.fstatSync(fd);
|
|
42
|
+
if (after.size !== before.size || after.mtimeMs !== before.mtimeMs) throw new Error("Prediction App archive changed during inspection");
|
|
43
|
+
return { compatible, size: after.size, mtimeMs: after.mtimeMs };
|
|
44
|
+
} finally { fs.closeSync(fd); }
|
|
45
|
+
}
|
|
@@ -33,6 +33,12 @@ export function supervisePrediction({ native, restart, state, warning = () => {}
|
|
|
33
33
|
return {
|
|
34
34
|
...native,
|
|
35
35
|
check,
|
|
36
|
+
healthy() { return !closed && current.healthy(); },
|
|
37
|
+
enabled() { return !closed && current.enabled?.() !== false; },
|
|
38
|
+
appCurrent() { return current.appCurrent?.() !== false; },
|
|
39
|
+
inspectEnvironment() { return current.inspectEnvironment?.(); },
|
|
40
|
+
routeProcessId() { return current.routeProcessId?.(); },
|
|
41
|
+
inspectRoute() { return current.inspectRoute?.(); },
|
|
36
42
|
prepareRoute() { return current.prepareRoute?.(); },
|
|
37
43
|
async close() { closed = true;clearIntervalImpl(timer);await flight;await current?.close(); },
|
|
38
44
|
};
|
|
@@ -7,17 +7,23 @@ export function createPredictionState({ now = () => new Date().toISOString() } =
|
|
|
7
7
|
configuration: {}, counters: { configuration_responses: 0, modified: 0, tls_errors: 0, upstream_errors: 0 }, last_event_at: null };
|
|
8
8
|
return {
|
|
9
9
|
configure(enabled) { state.configured = enabled === true; },
|
|
10
|
+
environment(value, { resetTraffic = false } = {}) {
|
|
11
|
+
state.environment = structuredClone(value);
|
|
12
|
+
if (resetTraffic) { state.client_route = "unknown";state.configuration = {}; }
|
|
13
|
+
},
|
|
10
14
|
running(proxy) { state.bridge = "running"; state.reason = null; state.proxy = proxy;delete state.error; },
|
|
11
15
|
stopped() { state.bridge = "stopped"; },
|
|
12
16
|
launch(route) { state.launch_route = ["verified", "persisted"].includes(route) ? route : "unverified"; },
|
|
13
17
|
persistence(value) { state.persistence = value.status; },
|
|
14
18
|
checked() { state.recovery.last_check_at = now(); },
|
|
19
|
+
supervising() { state.recovery.attempts = 0;state.recovery.last_check_at = null; },
|
|
15
20
|
recovering(attempt) { state.bridge = "recovering";state.recovery.attempts = attempt;state.recovery.last_check_at = now(); },
|
|
16
21
|
recovered() { state.bridge = "running";state.reason = null;delete state.error;state.recovery.recovered++; },
|
|
17
22
|
unavailable(error) {
|
|
18
23
|
state.bridge = "unavailable";
|
|
19
24
|
state.reason = redactDiagnosticText(String(error?.message || "Prediction setup failed")).slice(0, 400);
|
|
20
25
|
state.error = operationErrorDetails(error);
|
|
26
|
+
if (error?.predictionEnvironment) state.environment = structuredClone(error.predictionEnvironment);
|
|
21
27
|
},
|
|
22
28
|
event(event) {
|
|
23
29
|
state.last_event_at = now();
|
|
@@ -33,3 +39,15 @@ export function createPredictionState({ now = () => new Date().toISOString() } =
|
|
|
33
39
|
snapshot() { return structuredClone(state); },
|
|
34
40
|
};
|
|
35
41
|
}
|
|
42
|
+
|
|
43
|
+
export function formatPredictionEnvironment(environment) {
|
|
44
|
+
if (!environment) return "";
|
|
45
|
+
const statuses = ["adapted", "preserved", "unavailable", "needs_service_restart", "needs_app_relaunch"];
|
|
46
|
+
const state = statuses.includes(environment.status) ? environment.status : "unknown";
|
|
47
|
+
const network = environment.network;
|
|
48
|
+
const type = ["http", "https", "socks5", "socks5h", "direct", "auto"].includes(network?.type) ? network.type : "unknown";
|
|
49
|
+
const source = ["HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy", "system HTTPS", "system SOCKS", "system", "direct"].includes(network?.source) ? network.source : "unknown";
|
|
50
|
+
const count = value => Number.isSafeInteger(value) && value >= 0 ? String(value) : "unknown";
|
|
51
|
+
const ca = ["not_set", "configured", "unreadable_or_invalid"].includes(environment.tls?.extra_ca) ? environment.tls.extra_ca : "unknown";
|
|
52
|
+
return `Prediction environment: ${state}; proxy ${source}/${type}; bypass ${count(network?.bypass_rules)} (${count(network?.cidr_rules)} CIDR); extra CA ${ca}; TLS verification required`;
|
|
53
|
+
}
|
|
@@ -1,30 +1,15 @@
|
|
|
1
1
|
import fs from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { execFileSync } from "node:child_process";
|
|
4
3
|
import { predictionPaths, readPredictionSettings, writePredictionSettings, assertPredictionProxyCompatible,
|
|
5
4
|
assertCodexClosed, installedPredictionApp, predictionAppMatches, readPredictionCertificate,
|
|
6
5
|
createPredictionCertificate, updatePredictionTrust } from "./native-prediction-profile.mjs";
|
|
7
6
|
import { retirePredictionIntegration } from "./prediction-retirement.mjs";
|
|
8
7
|
import { networkRouteSnapshot } from "./network-route.mjs";
|
|
9
8
|
import { withFileLock } from "./lock.mjs";
|
|
10
|
-
import {
|
|
9
|
+
import { windowsProxyText, windowsPredictionAppProcesses } from "./native-prediction-windows.mjs";
|
|
11
10
|
import { updatePredictionRoute } from "./native-prediction-route.mjs";
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
if (platform === "win32") return windowsSystemProxy({ exec, env });
|
|
15
|
-
return exec("/usr/sbin/scutil", ["--proxy"], { encoding: "utf8", timeout: 2000, maxBuffer: 64 * 1024 });
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
function predictionNetworkOptions(options) {
|
|
19
|
-
if (options.platform !== "win32") return { networkRoute: assertPredictionProxyCompatible({ env: options.env, systemProxy: systemProxy(options.exec, options) }) };
|
|
20
|
-
const settings = windowsProxySettings(options);
|
|
21
|
-
if (!settings.autoDetect && !settings.pac) return { networkRoute: assertPredictionProxyCompatible({ env: options.env, systemProxy: windowsProxyText(settings) }) };
|
|
22
|
-
const environment = assertPredictionProxyCompatible({ env: options.env });
|
|
23
|
-
if (environment.http || environment.https || environment.bypass.length) {
|
|
24
|
-
throw new Error("Windows automatic proxy and explicit proxy environment rules require separate routing; existing routes were preserved");
|
|
25
|
-
}
|
|
26
|
-
return { settings };
|
|
27
|
-
}
|
|
11
|
+
import { inspectPredictionEnvironment } from "./native-prediction-environment.mjs";
|
|
12
|
+
import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
|
|
28
13
|
|
|
29
14
|
function certificateDirectory(settings, paths) {
|
|
30
15
|
if (!settings.credentialsDirectory) return paths.directory;
|
|
@@ -36,7 +21,7 @@ function certificateDirectory(settings, paths) {
|
|
|
36
21
|
}
|
|
37
22
|
|
|
38
23
|
export async function runPredictionCommand(options = {}) {
|
|
39
|
-
if (!options.action || options.action
|
|
24
|
+
if (!options.action || ["status", "fix"].includes(options.action)) return runPredictionCommandUnlocked(options);
|
|
40
25
|
if (!["darwin", "win32"].includes(options.platform || process.platform)) return runPredictionCommandUnlocked(options);
|
|
41
26
|
const { settings } = predictionPaths(options);
|
|
42
27
|
return withFileLock(`${settings}.lock`, () => runPredictionCommandUnlocked(options), { timeoutMs: 2000 });
|
|
@@ -44,9 +29,30 @@ export async function runPredictionCommand(options = {}) {
|
|
|
44
29
|
|
|
45
30
|
async function runPredictionCommandUnlocked({ action = "status", env = process.env,
|
|
46
31
|
platform = process.platform, output = console.log, resolveApp = installedPredictionApp,
|
|
47
|
-
writeSettings = writePredictionSettings, runtimeSnapshot, ...options } = {}) {
|
|
32
|
+
writeSettings = writePredictionSettings, runtimeSnapshot, repairRuntime, ...options } = {}) {
|
|
48
33
|
const opts = { ...options, env, platform };
|
|
49
34
|
const settings = readPredictionSettings(opts);
|
|
35
|
+
if (action === "fix") {
|
|
36
|
+
if (!settings.enabled) {
|
|
37
|
+
output("Native predictions are off; nothing was enabled or changed. Run ccdx prediction on to opt in.");
|
|
38
|
+
return { status: "disabled", exitCode: 0 };
|
|
39
|
+
}
|
|
40
|
+
if (!repairRuntime) throw new Error("Prediction repair needs a running CCDX adapter with prediction-fix support");
|
|
41
|
+
const result = await repairRuntime();
|
|
42
|
+
const prediction = result.prediction;
|
|
43
|
+
output(`Prediction repair: ${result.status}; bridge: ${prediction.bridge}; candidate: ${prediction.candidate}`);
|
|
44
|
+
if (prediction.environment) output(formatPredictionEnvironment(prediction.environment));
|
|
45
|
+
if (result.status === "disabled") output("The running adapter has predictions off; no feature was enabled.");
|
|
46
|
+
else if (result.status === "needs_service_restart") output("Node trust settings changed. Restart the CCDX service to apply them; no certificate or App was changed.");
|
|
47
|
+
else if (result.status === "environment_preserved") output(`Network recheck failed; the existing bridge and routes were preserved. ${result.environment_error?.message || "Check ccdx prediction status."}`);
|
|
48
|
+
else if (prediction.bridge !== "running") output(prediction.reason || "Prediction bridge is unavailable; core service was not changed.");
|
|
49
|
+
else if (prediction.environment?.status === "needs_app_relaunch") output("Network settings changed. The bridge uses the new snapshot, but the App may cache its earlier PAC. Fully quit Codex, then run ccdx; no App was restarted.");
|
|
50
|
+
else if (result.app_route === "verified") output("App launch route verified. A visible suggestion still needs an App-side check.");
|
|
51
|
+
else if (result.app_route === "closed") output("Bridge is ready. Run ccdx to open Codex with its prediction route.");
|
|
52
|
+
else if (result.status === "route_unverified") output("Bridge is ready, but App route inspection was unavailable or ambiguous. Check ccdx prediction status; no App was restarted.");
|
|
53
|
+
else output("Bridge is ready, but the running App route is not verified. No App was restarted. Fully quit Codex, then run ccdx to attach the route.");
|
|
54
|
+
return { ...result, exitCode: ["ready", "disabled"].includes(result.status) ? 0 : 1 };
|
|
55
|
+
}
|
|
50
56
|
if (action === "status") {
|
|
51
57
|
output(`Native prediction preference: ${settings.enabled ? "on" : "off"} (default: off)`);
|
|
52
58
|
output("Uses the conversation's model. No prediction MCP, Hook, or panel.");
|
|
@@ -59,13 +65,14 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
59
65
|
if (runtime.launch_route) output(`App launch route: ${runtime.launch_route}; persistent route: ${runtime.persistence || "unknown"}`);
|
|
60
66
|
if (runtime.recovery) output(`Bridge recovery: ${runtime.recovery.recovered} recovered; ${runtime.recovery.attempts}/3 attempts used`);
|
|
61
67
|
if (runtime.reason) output(runtime.reason);
|
|
68
|
+
if (runtime.environment) output(formatPredictionEnvironment(runtime.environment));
|
|
62
69
|
for (const [name, event] of Object.entries(runtime.configuration || {})) output(`${name}: HTTP ${event.status}${event.modified ? " (local compatibility)" : " (upstream)"}`);
|
|
63
70
|
} else output("Runtime prediction state: unavailable; status is a saved preference, not proof of a visible suggestion.");
|
|
64
71
|
} catch { output("Runtime prediction state: unavailable; start ccdx and check again."); }
|
|
65
72
|
}
|
|
66
73
|
return settings;
|
|
67
74
|
}
|
|
68
|
-
if (!["on", "off"].includes(action)) throw new Error("Prediction action must be on, off, or
|
|
75
|
+
if (!["on", "off"].includes(action)) throw new Error("Prediction action must be on, off, status, or fix");
|
|
69
76
|
if (!["darwin", "win32"].includes(platform)) throw new Error("Native prediction setup supports macOS and Windows only; no configuration changed");
|
|
70
77
|
let paths = predictionPaths({ ...opts, app: settings.app });
|
|
71
78
|
if (action === "off") {
|
|
@@ -95,7 +102,7 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
|
|
|
95
102
|
return { ...settings, enabled: false };
|
|
96
103
|
}
|
|
97
104
|
assertCodexClosed(opts);
|
|
98
|
-
|
|
105
|
+
inspectPredictionEnvironment(opts);
|
|
99
106
|
const app = resolveApp({ ...opts, ...(platform === "win32" && settings.app?.profile ? { preferredProfile: settings.app.profile } : {}) });
|
|
100
107
|
paths = predictionPaths({ ...opts, app });
|
|
101
108
|
if (settings.store && settings.store !== paths.store) throw new Error("Codex profile changed; disable the previous profile before enabling another");
|
|
@@ -148,7 +155,9 @@ export async function startNativePrediction({ env = process.env, platform = proc
|
|
|
148
155
|
state?.configure(settings.enabled);
|
|
149
156
|
if (!settings.enabled) return null;
|
|
150
157
|
if (!["darwin", "win32"].includes(platform)) throw new Error("Native predictions were skipped: unsupported platform");
|
|
151
|
-
const
|
|
158
|
+
const environment = options.environment || inspectPredictionEnvironment(opts);
|
|
159
|
+
state?.environment(environment.summary);
|
|
160
|
+
const network = environment.network;
|
|
152
161
|
let networkRoute = network.networkRoute;
|
|
153
162
|
if (settings.bridgePort !== undefined
|
|
154
163
|
&& (!Number.isInteger(settings.bridgePort) || settings.bridgePort < 1024 || settings.bridgePort > 65535)) {
|
|
@@ -233,15 +242,32 @@ export async function startNativePrediction({ env = process.env, platform = proc
|
|
|
233
242
|
throw error;
|
|
234
243
|
}
|
|
235
244
|
state?.running(windowsNetwork ? { source: "system", type: "auto", bypass_rules: null, proxy_credentials: false } : networkRouteSnapshot(networkRoute));
|
|
245
|
+
let routeProcessId = null;
|
|
236
246
|
return {
|
|
237
247
|
app: settings.app.app,
|
|
238
248
|
...(platform === "win32" ? { profile: paths.profile } : {}),
|
|
239
249
|
pacUrl: transport.pacUrl,
|
|
240
250
|
enabled() { return enabled; },
|
|
251
|
+
appCurrent() { return predictionAppMatches(settings.app); },
|
|
252
|
+
inspectEnvironment() {
|
|
253
|
+
const next = inspectPredictionEnvironment(opts);
|
|
254
|
+
return { changed: next.networkKey !== environment.networkKey, requiresServiceRestart: next.trustKey !== environment.trustKey, next };
|
|
255
|
+
},
|
|
256
|
+
routeProcessId() { return routeProcessId; },
|
|
241
257
|
healthy() { return transport.healthy() && (!windowsNetwork || windowsNetwork.healthy()); },
|
|
258
|
+
async inspectRoute() {
|
|
259
|
+
const inspect = options.inspectAppProcesses || (platform === "win32" ? windowsPredictionAppProcesses
|
|
260
|
+
: (await import("./launcher.mjs")).macPredictionAppProcesses);
|
|
261
|
+
const rows = inspect(settings.app.app, opts);
|
|
262
|
+
routeProcessId = rows.length === 1 && rows[0].readable ? rows[0].pid : null;
|
|
263
|
+
const route = rows.length === 0 ? "closed" : rows.length !== 1 || !rows[0].readable ? "unverified"
|
|
264
|
+
: rows[0].route === transport.pacUrl ? "verified" : "missing";
|
|
265
|
+
state?.launch(route);
|
|
266
|
+
return route;
|
|
267
|
+
},
|
|
242
268
|
async prepareRoute() {
|
|
243
269
|
try {
|
|
244
|
-
const direct = !windowsNetwork && !networkRoute?.http && !networkRoute?.https
|
|
270
|
+
const direct = !windowsNetwork && !networkRoute?.http && !networkRoute?.https;
|
|
245
271
|
if (!direct) {
|
|
246
272
|
// A profile previously configured on a direct network must not pin
|
|
247
273
|
// that local PAC after the environment switches to company routing.
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Pure matching shared by Node and the generated PAC. CIDRs apply to URL IP
|
|
2
|
+
// literals, as in Chromium's manual bypass rules; they never trigger DNS.
|
|
3
|
+
export function literalAddress(value) {
|
|
4
|
+
var text = String(value).toLowerCase().replace(/^\[|\]$/g, "");
|
|
5
|
+
var ipv4 = function (s) {
|
|
6
|
+
if (!/^(0|[1-9][0-9]{0,2})(\.(0|[1-9][0-9]{0,2})){3}$/.test(s)) return null;
|
|
7
|
+
var bytes = s.split(".").map(Number);
|
|
8
|
+
return bytes.every(function (n) { return n <= 255; }) ? bytes : null;
|
|
9
|
+
};
|
|
10
|
+
if (text.indexOf(":") < 0) return ipv4(text);
|
|
11
|
+
if (text.indexOf(".") >= 0) {
|
|
12
|
+
var last = text.lastIndexOf(":"), tail = ipv4(text.slice(last + 1));
|
|
13
|
+
if (!tail) return null;
|
|
14
|
+
text = text.slice(0, last + 1) + (tail[0] * 256 + tail[1]).toString(16) + ":" + (tail[2] * 256 + tail[3]).toString(16);
|
|
15
|
+
}
|
|
16
|
+
if (!/^[0-9a-f:]+$/.test(text) || text.indexOf(":::") >= 0) return null;
|
|
17
|
+
var halves = text.split("::");
|
|
18
|
+
if (halves.length > 2) return null;
|
|
19
|
+
var left = halves[0] ? halves[0].split(":") : [], right = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
|
|
20
|
+
var missing = 8 - left.length - right.length;
|
|
21
|
+
if (halves.length === 1 ? left.length !== 8 : missing < 1) return null;
|
|
22
|
+
var groups = left.slice();
|
|
23
|
+
if (halves.length === 2) for (var i = 0; i < missing; i++) groups.push("0");
|
|
24
|
+
groups = groups.concat(right);
|
|
25
|
+
var result = [];
|
|
26
|
+
for (var j = 0; j < groups.length; j++) {
|
|
27
|
+
if (!/^[0-9a-f]{1,4}$/.test(groups[j])) return null;
|
|
28
|
+
var number = parseInt(groups[j], 16);result.push(number >>> 8, number & 255);
|
|
29
|
+
}
|
|
30
|
+
return result;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function compileBypassRules(values) {
|
|
34
|
+
return values.map(raw => {
|
|
35
|
+
if (raw.includes("/")) {
|
|
36
|
+
const parts = raw.split("/"), address = literalAddress(parts[0]);
|
|
37
|
+
if (parts.length !== 2 || !address || /[\[\]]/.test(parts[0]) || !/^\d{1,3}$/.test(parts[1]) || Number(parts[1]) > address.length * 8) {
|
|
38
|
+
throw Object.assign(new Error("Invalid proxy bypass CIDR rule; existing routes were preserved"), { code: "proxy_bypass_invalid" });
|
|
39
|
+
}
|
|
40
|
+
return { address, prefix: Number(parts[1]), port: null };
|
|
41
|
+
}
|
|
42
|
+
let host = raw, port = null;
|
|
43
|
+
const bracket = /^\[([^\]]+)\](?::(\d+))?$/.exec(raw);
|
|
44
|
+
const suffix = !literalAddress(raw) && /^(.*):(\d+)$/.exec(raw);
|
|
45
|
+
if (bracket) { host = bracket[1];port = bracket[2] ? Number(bracket[2]) : null; }
|
|
46
|
+
else if (suffix) { host = suffix[1];port = Number(suffix[2]); }
|
|
47
|
+
if ((port !== null && (port < 1 || port > 65535)) || /[\s/@?#\\\[\]]/.test(host) || !host) {
|
|
48
|
+
throw Object.assign(new Error("Invalid proxy bypass host or port; existing routes were preserved"), { code: "proxy_bypass_invalid" });
|
|
49
|
+
}
|
|
50
|
+
const address = literalAddress(host);
|
|
51
|
+
if (bracket && address?.length !== 16) throw Object.assign(new Error("Invalid proxy bypass IPv6 literal; existing routes were preserved"), { code: "proxy_bypass_invalid" });
|
|
52
|
+
if (host.includes(":") && !address) throw Object.assign(new Error("Invalid proxy bypass IP literal; existing routes were preserved"), { code: "proxy_bypass_invalid" });
|
|
53
|
+
return address ? { address, prefix: address.length * 8, port }
|
|
54
|
+
: { host, port, ...(host.includes("*") ? { expression: "^" + host.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replaceAll("*", ".*") + "$" } : {}) };
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function matchesBypass(hostname, port, rules, excludeSimple) {
|
|
59
|
+
var host = hostname.toLowerCase().replace(/^\[|\]$/g, ""), address = literalAddress(host);
|
|
60
|
+
if (host === "localhost" || host === "127.0.0.1" || (address && address.length === 16 && address.slice(0, 15).every(function (n) { return n === 0; }) && address[15] === 1)
|
|
61
|
+
|| (excludeSimple && !address && host.indexOf(".") < 0)) return true;
|
|
62
|
+
for (var i = 0; i < rules.length; i++) {
|
|
63
|
+
var rule = rules[i];
|
|
64
|
+
if (rule.port !== null && rule.port !== Number(port)) continue;
|
|
65
|
+
if (rule.address) {
|
|
66
|
+
if (!address || address.length !== rule.address.length) continue;
|
|
67
|
+
var equal = true;
|
|
68
|
+
for (var index = 0; index < Math.ceil(rule.prefix / 8); index++) {
|
|
69
|
+
var mask = (255 << Math.max(0, 8 - (rule.prefix - index * 8))) & 255;
|
|
70
|
+
if ((address[index] & mask) !== (rule.address[index] & mask)) { equal = false;break; }
|
|
71
|
+
}
|
|
72
|
+
if (equal) return true;
|
|
73
|
+
} else if (rule.expression ? new RegExp(rule.expression).test(host)
|
|
74
|
+
: host === rule.host.replace(/^\*?\./, "") || host.slice(-(rule.host.replace(/^\*?\./, "").length + 1)) === "." + rule.host.replace(/^\*?\./, "")) return true;
|
|
75
|
+
}
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function bypassPacSource() { return literalAddress.toString() + "\n" + matchesBypass.toString(); }
|
package/src/network-route.mjs
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
import net from "node:net";
|
|
2
|
+
import { compileBypassRules, matchesBypass, bypassPacSource } from "./network-bypass.mjs";
|
|
2
3
|
|
|
3
4
|
const OFFICIAL_API = "https://chatgpt.com/backend-api";
|
|
5
|
+
const routeError = (code, message) => Object.assign(new Error(message), { code });
|
|
4
6
|
|
|
5
7
|
function proxy(value, source) {
|
|
6
8
|
if (!value) return null;
|
|
7
9
|
let url;
|
|
8
|
-
try { url = new URL(value); } catch { throw
|
|
10
|
+
try { url = new URL(value); } catch { throw routeError("proxy_address_invalid", `Invalid proxy address in ${source}`); }
|
|
9
11
|
if (!["http:", "https:", "socks5:", "socks5h:"].includes(url.protocol)
|
|
10
12
|
|| !url.hostname || !["", "/"].includes(url.pathname) || url.search || url.hash) {
|
|
11
|
-
throw
|
|
13
|
+
throw routeError("proxy_address_unsupported", `Unsupported proxy address in ${source}; expected HTTP, HTTPS or SOCKS5`);
|
|
12
14
|
}
|
|
13
15
|
return { url, source };
|
|
14
16
|
}
|
|
@@ -21,50 +23,33 @@ function variable(env, lower, upper) {
|
|
|
21
23
|
export function resolveNetworkRoute({ env = process.env, systemProxy = "", checkApi = true } = {}) {
|
|
22
24
|
const api = String(env.CODEX_API_BASE_URL || "").trim().replace(/\/+$/, "");
|
|
23
25
|
if (checkApi && api && api !== OFFICIAL_API) {
|
|
24
|
-
throw
|
|
26
|
+
throw routeError("prediction_route_conflict", "Native prediction setup skipped: CODEX_API_BASE_URL selects a custom API route; it was preserved");
|
|
25
27
|
}
|
|
26
28
|
const settings = Object.fromEntries([...systemProxy.matchAll(/^\s*([A-Za-z]+)\s*:\s*(.+?)\s*$/gm)].map((m) => [m[1], m[2]]));
|
|
27
29
|
for (const key of ["ProxyAutoConfigEnable", "ProxyAutoDiscoveryEnable"]) {
|
|
28
|
-
if (settings[key] === "1") throw
|
|
30
|
+
if (settings[key] === "1") throw routeError("proxy_dynamic_unsupported", `Native prediction setup skipped: system ${key === "ProxyAutoConfigEnable" ? "PAC" : "WPAD"} (${key}) needs dynamic routing; its rules were preserved`);
|
|
29
31
|
}
|
|
30
32
|
const system = (prefix, scheme) => {
|
|
31
33
|
if (settings[`${prefix}Enable`] !== "1") return null;
|
|
32
34
|
const host = settings[`${prefix}Proxy`], port = settings[`${prefix}Port`];
|
|
33
35
|
if (!host || !/^\d+$/.test(port || "") || Number(port) < 1 || Number(port) > 65535) {
|
|
34
|
-
throw
|
|
36
|
+
throw routeError("proxy_system_invalid", `Invalid system ${prefix} proxy settings`);
|
|
35
37
|
}
|
|
36
38
|
return proxy(`${scheme}://${net.isIP(host) === 6 ? `[${host}]` : host}:${port}`, `system ${prefix}`);
|
|
37
39
|
};
|
|
38
40
|
const httpEnv = variable(env, "http_proxy", "HTTP_PROXY"), httpsEnv = variable(env, "https_proxy", "HTTPS_PROXY");
|
|
39
41
|
const allEnv = variable(env, "all_proxy", "ALL_PROXY");
|
|
40
|
-
const
|
|
41
|
-
const
|
|
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;
|
|
42
|
+
const http = proxy(httpEnv.value, httpEnv.source) || proxy(allEnv.value, allEnv.source) || system("HTTP", "http") || system("SOCKS", "socks5");
|
|
43
|
+
const https = proxy(httpsEnv.value, httpsEnv.source) || proxy(allEnv.value, allEnv.source) || system("HTTPS", "http") || system("SOCKS", "socks5");
|
|
45
44
|
const noProxy = variable(env, "no_proxy", "NO_PROXY").value;
|
|
46
45
|
const exceptions = /ExceptionsList\s*:\s*<array>\s*\{([^}]+)\}/.exec(systemProxy)?.[1] || "";
|
|
47
46
|
const bypass = [...new Set([...noProxy.split(","), ...[...exceptions.matchAll(/\d+\s*:\s*([^\n]+)/g)].map((m) => m[1])]
|
|
48
47
|
.map((s) => s.trim().toLowerCase()).filter(Boolean))];
|
|
49
|
-
|
|
50
|
-
return { http, https, bypass, excludeSimple: settings.ExcludeSimpleHostnames === "1" };
|
|
48
|
+
return { http, https, bypass, rules: compileBypassRules(bypass), excludeSimple: settings.ExcludeSimpleHostnames === "1" };
|
|
51
49
|
}
|
|
52
50
|
|
|
53
51
|
export function bypassNetworkProxy(hostname, port, plan) {
|
|
54
|
-
|
|
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
|
-
});
|
|
52
|
+
return matchesBypass(hostname, port, plan.rules || compileBypassRules(plan.bypass), plan.excludeSimple);
|
|
68
53
|
}
|
|
69
54
|
|
|
70
55
|
export function networkProxyFor(url, plan) {
|
|
@@ -88,13 +73,12 @@ function pacProxy(route) {
|
|
|
88
73
|
export function networkPredictionPac(port, plan) {
|
|
89
74
|
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error("Invalid prediction proxy port");
|
|
90
75
|
// Embed only routing rules, never proxy passwords or API credentials.
|
|
91
|
-
return
|
|
76
|
+
return `${bypassPacSource()}
|
|
77
|
+
var ccdxRoute=${JSON.stringify({ http: pacProxy(plan.http), https: pacProxy(plan.https), rules: plan.rules || compileBypassRules(plan.bypass), excludeSimple: plan.excludeSimple })};
|
|
92
78
|
function FindProxyForURL(url,host) {
|
|
93
79
|
var secure=url.indexOf('https:')===0, p=secure?443:80;
|
|
94
80
|
var authority=url.split('/')[2]||'', explicit=/:([0-9]+)$/.exec(authority);if(explicit)p=Number(explicit[1]);
|
|
95
|
-
var skip=host
|
|
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));}
|
|
81
|
+
var skip=matchesBypass(host,p,ccdxRoute.rules,ccdxRoute.excludeSimple);
|
|
98
82
|
var original=skip?'DIRECT':secure?ccdxRoute.https:ccdxRoute.http;
|
|
99
83
|
if(secure&&(host==='chatgpt.com'||host==='ab.chatgpt.com'))return 'PROXY 127.0.0.1:${port}; '+original;
|
|
100
84
|
return original;
|
package/src/running-adapter.mjs
CHANGED
|
@@ -3,6 +3,8 @@ import { localPackageVersion } from "./version.mjs";
|
|
|
3
3
|
|
|
4
4
|
export const ADAPTER_HEALTH_PATH = "/_ccdx/health";
|
|
5
5
|
export const ADAPTER_STATUS_PATH = "/_ccdx/status";
|
|
6
|
+
export const ADAPTER_PREDICTION_FIX_PATH = "/_ccdx/prediction/fix";
|
|
7
|
+
export const PREDICTION_FIX_CAPABILITY = "prediction-fix-v1";
|
|
6
8
|
export const ADAPTER_PROTOCOL_VERSION = 4;
|
|
7
9
|
export const ADAPTER_VERSION = localPackageVersion();
|
|
8
10
|
export const ADAPTER_CAPABILITIES = Object.freeze(["cache-control-v1"]);
|
package/src/startup-ui.mjs
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { status } from "./status.mjs";
|
|
2
2
|
import { terminalCell } from "./terminal-text.mjs";
|
|
3
|
+
import { formatPredictionEnvironment } from "./native-prediction-state.mjs";
|
|
3
4
|
|
|
4
5
|
// The favicon's three ellipses, rasterized as terminal half-blocks. No runtime
|
|
5
6
|
// graphics library or terminal cursor control is needed.
|
|
@@ -45,10 +46,11 @@ export function startupLogger(name, output = console.log) {
|
|
|
45
46
|
|
|
46
47
|
export function predictionStartupCheck(prediction) {
|
|
47
48
|
if (!prediction?.configured) return startupCheck("info", "Prediction", "Off");
|
|
48
|
-
|
|
49
|
+
const details = prediction.environment ? `\n${startupCheck("info", "Environment", formatPredictionEnvironment(prediction.environment))}` : "";
|
|
50
|
+
if (prediction.bridge !== "running") return startupCheck("warn", "Prediction", prediction.reason || "Bridge unavailable; core service is available") + details;
|
|
49
51
|
const route = prediction.launch_route;
|
|
50
52
|
const summary = startupCheck(route === "unverified" ? "warn" : "info", "Prediction", route === "verified"
|
|
51
53
|
? "Bridge running; App route verified; suggestion not checked"
|
|
52
54
|
: "Bridge running; App route not verified; suggestion not checked");
|
|
53
|
-
return prediction.recovery ? `${summary}\n${startupCheck("info", "Recovery", `${prediction.recovery.attempts}/3 attempts used; persistent route ${prediction.persistence || "unknown"}`)}` : summary;
|
|
55
|
+
return (prediction.recovery ? `${summary}\n${startupCheck("info", "Recovery", `${prediction.recovery.attempts}/3 attempts used; persistent route ${prediction.persistence || "unknown"}`)}` : summary) + details;
|
|
54
56
|
}
|