codex-copilot-dx 0.9.35 → 0.9.36

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 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` | Repair an enabled prediction bridge; never force-restart Codex |
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, runtimeSnapshot: () => {
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: () => nativePrediction?.pacUrl || null,
414
+ nativePredictionPac: () => clientIntegration?.pacUrl() || null,
415
+ fixPrediction: async () => (await clientIntegrations()).fix(),
411
416
  clientIntegrationSnapshot: () => clientIntegration?.snapshot() || null,
412
417
  });
413
418
 
@@ -81,6 +81,23 @@ only, preserves company/user routing, and never treats a saved preference as
81
81
  proof of a running route or visible candidate. App compatibility is rechecked only
82
82
  when its recorded identity changes, before existing trust/port checks are reused.
83
83
 
84
+ `native-prediction-protocol.mjs` owns bounded archive recognition only, independent
85
+ of certificates, networking and the CLI. It accepts multiple named hashed chunks
86
+ without assuming the first general-settings chunk is the implementation. Signature
87
+ and profile checks remain in the existing platform boundary.
88
+
89
+ Explicit `prediction fix` uses the optional integration's serialized lifecycle,
90
+ not a second adapter or detached predictor. Startup, repair and shutdown cannot
91
+ create overlapping owned listeners. Healthy/current bridges are retained; explicit
92
+ recreation preserves the saved port and existing trust and starts one new supervised
93
+ lifecycle. The supervisor delegates health/route checks to its current bridge after
94
+ recovery, not a closed initial transport. The health endpoint advertises repair
95
+ capability only when the composition root supplies that operation.
96
+ `native-prediction-fix.mjs` is the bounded local management client; the adapter
97
+ enforces loopback/Host/Origin/method/media/body boundaries before dispatch. No new
98
+ inference-path work, watcher, runtime dependency, forced App restart or unverified
99
+ hot-attachment mechanism is introduced.
100
+
84
101
  `startup-ui.mjs` is pure terminal presentation: a static A atom, aligned checks
85
102
  and the common new/reused-service footer. It depends only on terminal/status
86
103
  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
@@ -200,7 +202,7 @@ Since `0.9.34`, an enabled bridge has a lightweight 30-second listener check.
200
202
  Healthy checks do not spawn processes, call upstream, inspect transcripts or
201
203
  probe model endpoints. A failed owned listener/native company-routing worker can
202
204
  be recreated on the saved port, using the same checked profile and certificate.
203
- There are at most three recovery attempts per CCDX process, with 30/60/120-second
205
+ There are at most three automatic recovery attempts per bridge lifecycle, with 30/60/120-second
204
206
  backoff gates; checks themselves run every 30 seconds. Occupied ports are not
205
207
  stolen or rotated. Startup failures do not gain a retry loop, and configuration
206
208
  HTTP errors or missing gray text alone do not trigger transport restarts. Existing
@@ -208,6 +210,36 @@ requests can fail during an outage and are never replayed by this supervisor.
208
210
  Disabled prediction startup creates no recovery timer. The existing in-memory
209
211
  overlay switch still observes explicit on/off changes independently.
210
212
 
213
+ `ccdx prediction fix` asks the running adapter for one explicit repair, without
214
+ starting another core service or forcibly restarting Codex. Disabled predictions
215
+ remain off. Healthy/current bridges are kept; a failed bridge or changed App identity
216
+ reuses the saved port, certificate and verified profile. Compatibility, certificate,
217
+ company proxy and port-ownership checks are not bypassed. Certificates are not renewed
218
+ by fix; setup problems can still require a normal closed-App `prediction on` action.
219
+ An explicit successful recreation starts a fresh three-attempt automatic recovery
220
+ lifecycle; it is not an automatic retry loop for initialization failures.
221
+
222
+ The command checks the adapter's advertised `prediction-fix-v1` capability before
223
+ posting bounded JSON to the native-loopback-only `/_ccdx/prediction/fix` endpoint.
224
+ Browser Origin headers, remote peers and non-JSON bodies are refused. A repair does
225
+ not count as model traffic. An older running adapter needs one upgrade/service restart
226
+ to gain this endpoint; the new CLI cannot hot-upgrade an old Node process.
227
+
228
+ Repair reports bridge readiness separately from the inspected App launch route.
229
+ If a running App has no verified route, fix returns a partial result (exit 1), preserves
230
+ its process and asks for a normal full quit followed by `ccdx`. A closed App is not
231
+ launched by fix; run `ccdx` to open it. Neither HTTP 200 nor a verified route proves
232
+ that gray text appeared. Normal replies, image setup and account state are not changed.
233
+ Unavailable/ambiguous process inspection reports `route_unverified` (exit 1), not
234
+ a definite missing route or an instruction to restart an otherwise healthy App.
235
+
236
+ App compatibility inspection checks up to 16 named main candidates and 16 named
237
+ general-settings candidates, rather than assuming the first hashed chunk owns the
238
+ implementation. A forwarding chunk therefore cannot hide a later real settings
239
+ module. Reads retain a 32 MiB header limit, 32/4 MiB per-entry main/settings limits,
240
+ a combined 36 MiB source limit, archive bounds/snapshot checks and platform signature
241
+ verification. Unknown layouts remain unsupported instead of being patched blindly.
242
+
211
243
  Before enabled App launch, CCDX can persist its PAC in that verified profile's
212
244
  `Default/Preferences`, but only in a direct environment, with initialized regular
213
245
  profile files and the App closed. Existing explicit App proxies and all company
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-copilot-dx",
3
- "version": "0.9.35",
3
+ "version": "0.9.36",
4
4
  "description": "Use Codex App with GitHub Copilot",
5
5
  "author": "Dale Xiao",
6
6
  "type": "module",
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
- res.end(JSON.stringify({ ...adapterHealthPayload(), ...(predictionPac ? { native_prediction_pac: predictionPac } : {}) }));
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);
@@ -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 status");
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 and CIDR bypass rules are reported as unsupported. 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.`,
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 and CIDR bypass rules are reported as unsupported. 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 bridges are retained. 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
@@ -7,9 +7,27 @@ import { supervisePrediction } from "./native-prediction-recovery.mjs";
7
7
 
8
8
  // The CLI composes the services; this module owns optional client integration
9
9
  // lifecycle. It never forwards model requests or depends on dashboard rendering.
10
- export function createClientIntegration({ port, host, info = () => {}, warning = () => {}, configLog } = {}) {
10
+ export function createClientIntegration({ port, host, info = () => {}, warning = () => {}, configLog,
11
+ startPrediction = async options => (await import("./native-prediction.mjs")).startNativePrediction(options) } = {}) {
11
12
  const prediction = createPredictionState();
12
13
  let native = null;
14
+ let operation = null, operationName = null, closed = false;
15
+ async function startPredictionBridge(expectedPort) {
16
+ const started = await startPrediction({ state: prediction, warning: info, ...(expectedPort ? { expectedPort } : {}) });
17
+ if (!started) return null;
18
+ if (closed) { await started.close();return null; }
19
+ const port = Number(new URL(started.pacUrl).port);
20
+ prediction.supervising();
21
+ return supervisePrediction({ native: started, state: prediction, warning,
22
+ restart: () => startPrediction({ state: prediction, warning: info, expectedPort: port }) });
23
+ }
24
+ function serialize(name, task) {
25
+ if (closed) return Promise.reject(new Error("Client integration is closing; repair was skipped"));
26
+ if (operation) return operationName === name ? operation : operation.then(() => serialize(name, task));
27
+ operationName = name;
28
+ operation = Promise.resolve().then(task).finally(() => { operation = null;operationName = null; });
29
+ return operation;
30
+ }
13
31
  return {
14
32
  async configure() {
15
33
  try {
@@ -28,21 +46,36 @@ export function createClientIntegration({ port, host, info = () => {}, warning =
28
46
  }
29
47
  return { imageEnabled: enabled, imageMcpSkipped, compressionSetup: runInBackground(ensureCodexThreadCompression) };
30
48
  },
31
- async start() {
49
+ start() { return serialize("start", async () => {
32
50
  try {
33
- const { startNativePrediction } = await import("./native-prediction.mjs");
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
- }
51
+ native ||= await startPredictionBridge();
40
52
  } catch (error) { prediction.unavailable(error); warning(`${error.message}. Core startup will continue.`); }
41
53
  return native;
42
- },
54
+ }); },
55
+ fix() { return serialize("fix", async () => {
56
+ let restarted = false, route = "unknown";
57
+ try {
58
+ if (!native?.healthy() || native.enabled?.() === false || native.appCurrent?.() === false) {
59
+ const expectedPort = native ? Number(new URL(native.pacUrl).port) : undefined;
60
+ await native?.close();native = null;
61
+ native = await startPredictionBridge(expectedPort);restarted = Boolean(native);
62
+ }
63
+ } catch (error) { prediction.unavailable(error); }
64
+ let routeError = false;
65
+ if (native && !closed) {
66
+ try {
67
+ await native.prepareRoute?.();
68
+ route = await native.inspectRoute?.() || "unverified";
69
+ } catch { routeError = true;warning("Prediction bridge is ready, but App route inspection failed"); }
70
+ }
71
+ const snapshot = prediction.snapshot();
72
+ const status = !snapshot.configured && snapshot.bridge !== "unavailable" ? "disabled" : snapshot.bridge !== "running" ? "failed"
73
+ : route === "verified" || route === "closed" ? "ready" : route === "missing" ? "needs_app_relaunch" : "route_unverified";
74
+ return { status, bridge_restarted: restarted, app_route: route, ...(routeError ? { route_error: true } : {}), prediction: snapshot };
75
+ }); },
43
76
  pacUrl() { return native?.pacUrl || null; },
44
77
  launched(route) { prediction.launch(route); },
45
78
  snapshot() { return { prediction: prediction.snapshot() }; },
46
- async close() { await native?.close(); native = null; },
79
+ async close() { closed = true;try { await operation; } finally { await native?.close();native = null; } },
47
80
  };
48
81
  }
@@ -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"].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
- // Check only during explicit setup; startup uses the cheap identity check.
68
- const fd = fs.openSync(archive, "r");
69
- try {
70
- const prefix = Buffer.alloc(16); fs.readSync(fd, prefix, 0, 16, 0);
71
- const headerSize = prefix.readUInt32LE(12);
72
- if (headerSize > 32 * 1024 * 1024) continue;
73
- const header = Buffer.alloc(headerSize); fs.readSync(fd, header, 0, header.length, 16);
74
- const files = JSON.parse(header).files?.[".vite"]?.files?.build?.files;
75
- const entry = Object.entries(files || {}).find(([name]) => /^main-[\w-]+\.js$/.test(name))?.[1];
76
- if (!entry || entry.size > 32 * 1024 * 1024 || entry.unpacked) continue;
77
- const bytes = Buffer.alloc(entry.size);
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,10 @@ 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
+ inspectRoute() { return current.inspectRoute?.(); },
36
40
  prepareRoute() { return current.prepareRoute?.(); },
37
41
  async close() { closed = true;clearIntervalImpl(timer);await flight;await current?.close(); },
38
42
  };
@@ -12,6 +12,7 @@ export function createPredictionState({ now = () => new Date().toISOString() } =
12
12
  launch(route) { state.launch_route = ["verified", "persisted"].includes(route) ? route : "unverified"; },
13
13
  persistence(value) { state.persistence = value.status; },
14
14
  checked() { state.recovery.last_check_at = now(); },
15
+ supervising() { state.recovery.attempts = 0;state.recovery.last_check_at = null; },
15
16
  recovering(attempt) { state.bridge = "recovering";state.recovery.attempts = attempt;state.recovery.last_check_at = now(); },
16
17
  recovered() { state.bridge = "running";state.reason = null;delete state.error;state.recovery.recovered++; },
17
18
  unavailable(error) {
@@ -7,7 +7,7 @@ import { predictionPaths, readPredictionSettings, writePredictionSettings, asser
7
7
  import { retirePredictionIntegration } from "./prediction-retirement.mjs";
8
8
  import { networkRouteSnapshot } from "./network-route.mjs";
9
9
  import { withFileLock } from "./lock.mjs";
10
- import { windowsSystemProxy, windowsProxySettings, windowsProxyText } from "./native-prediction-windows.mjs";
10
+ import { windowsSystemProxy, windowsProxySettings, windowsProxyText, windowsPredictionAppProcesses } from "./native-prediction-windows.mjs";
11
11
  import { updatePredictionRoute } from "./native-prediction-route.mjs";
12
12
 
13
13
  function systemProxy(exec = execFileSync, { platform = process.platform, env = process.env } = {}) {
@@ -36,7 +36,7 @@ function certificateDirectory(settings, paths) {
36
36
  }
37
37
 
38
38
  export async function runPredictionCommand(options = {}) {
39
- if (!options.action || options.action === "status") return runPredictionCommandUnlocked(options);
39
+ if (!options.action || ["status", "fix"].includes(options.action)) return runPredictionCommandUnlocked(options);
40
40
  if (!["darwin", "win32"].includes(options.platform || process.platform)) return runPredictionCommandUnlocked(options);
41
41
  const { settings } = predictionPaths(options);
42
42
  return withFileLock(`${settings}.lock`, () => runPredictionCommandUnlocked(options), { timeoutMs: 2000 });
@@ -44,9 +44,26 @@ export async function runPredictionCommand(options = {}) {
44
44
 
45
45
  async function runPredictionCommandUnlocked({ action = "status", env = process.env,
46
46
  platform = process.platform, output = console.log, resolveApp = installedPredictionApp,
47
- writeSettings = writePredictionSettings, runtimeSnapshot, ...options } = {}) {
47
+ writeSettings = writePredictionSettings, runtimeSnapshot, repairRuntime, ...options } = {}) {
48
48
  const opts = { ...options, env, platform };
49
49
  const settings = readPredictionSettings(opts);
50
+ if (action === "fix") {
51
+ if (!settings.enabled) {
52
+ output("Native predictions are off; nothing was enabled or changed. Run ccdx prediction on to opt in.");
53
+ return { status: "disabled", exitCode: 0 };
54
+ }
55
+ if (!repairRuntime) throw new Error("Prediction repair needs a running CCDX adapter with prediction-fix support");
56
+ const result = await repairRuntime();
57
+ const prediction = result.prediction;
58
+ output(`Prediction repair: ${result.status}; bridge: ${prediction.bridge}; candidate: ${prediction.candidate}`);
59
+ if (result.status === "disabled") output("The running adapter has predictions off; no feature was enabled.");
60
+ else if (prediction.bridge !== "running") output(prediction.reason || "Prediction bridge is unavailable; core service was not changed.");
61
+ else if (result.app_route === "verified") output("App launch route verified. A visible suggestion still needs an App-side check.");
62
+ else if (result.app_route === "closed") output("Bridge is ready. Run ccdx to open Codex with its prediction route.");
63
+ 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.");
64
+ 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.");
65
+ return { ...result, exitCode: ["ready", "disabled"].includes(result.status) ? 0 : 1 };
66
+ }
50
67
  if (action === "status") {
51
68
  output(`Native prediction preference: ${settings.enabled ? "on" : "off"} (default: off)`);
52
69
  output("Uses the conversation's model. No prediction MCP, Hook, or panel.");
@@ -65,7 +82,7 @@ async function runPredictionCommandUnlocked({ action = "status", env = process.e
65
82
  }
66
83
  return settings;
67
84
  }
68
- if (!["on", "off"].includes(action)) throw new Error("Prediction action must be on, off, or status");
85
+ if (!["on", "off"].includes(action)) throw new Error("Prediction action must be on, off, status, or fix");
69
86
  if (!["darwin", "win32"].includes(platform)) throw new Error("Native prediction setup supports macOS and Windows only; no configuration changed");
70
87
  let paths = predictionPaths({ ...opts, app: settings.app });
71
88
  if (action === "off") {
@@ -238,7 +255,17 @@ export async function startNativePrediction({ env = process.env, platform = proc
238
255
  ...(platform === "win32" ? { profile: paths.profile } : {}),
239
256
  pacUrl: transport.pacUrl,
240
257
  enabled() { return enabled; },
258
+ appCurrent() { return predictionAppMatches(settings.app); },
241
259
  healthy() { return transport.healthy() && (!windowsNetwork || windowsNetwork.healthy()); },
260
+ async inspectRoute() {
261
+ const inspect = options.inspectAppProcesses || (platform === "win32" ? windowsPredictionAppProcesses
262
+ : (await import("./launcher.mjs")).macPredictionAppProcesses);
263
+ const rows = inspect(settings.app.app, opts);
264
+ const route = rows.length === 0 ? "closed" : rows.length !== 1 || !rows[0].readable ? "unverified"
265
+ : rows[0].route === transport.pacUrl ? "verified" : "missing";
266
+ state?.launch(route);
267
+ return route;
268
+ },
242
269
  async prepareRoute() {
243
270
  try {
244
271
  const direct = !windowsNetwork && !networkRoute?.http && !networkRoute?.https && !networkRoute?.bypass?.length;
@@ -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"]);